Skip to content

LLM ⇄ Workspace: object tools and Env removal - #13635

Merged
vito merged 31 commits into
mainfrom
llm-workspace-llm-binding
Aug 5, 2026
Merged

vito merged 31 commits into
mainfrom
llm-workspace-llm-binding

Conversation

@vito

@vito vito commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

The headline of the stack: the LLM becomes a workspace-bound agent, and Env/Binding are deleted entirely — taking with them the engine's last dynamically-extended core schema surface. hack/designs/workspace-agents.md documents the as-built design.

The LLM binds to a Workspace

The LLM binds to the same Workspace a CLI user sees, and its tools are generated from the objects bound via LLM.withTools:

  • Binding is always explicit. llm() starts unbound; a workspace arrives only via LLM.withWorkspace, recorded as a selector on the ID, so an LLM's ID never lies about what it is bound to. dagger prompt mode chains withWorkspace(currentWorkspace) at session start, dagger mcp binds it on the served LLM, and a module function returning an LLM threads a Workspace it was handed. An unbound LLM stays valid — MCP.Server falls back to the current client's served deps.
  • Every eligible method of a bound object becomes a tool, and the schema the model sees derives from the bound workspace — the same modules the CLI would serve.
  • Returns route by type: a method returning the object's own type rebinds it as the new state, a Changeset applies to the workspace overlay, a Workspace rebinds the LLM's workspace, and any other object syncs and returns its logs. Several Changeset-returning tools may run in one turn; their changesets apply to the overlay in call order rather than last-writer-wins.
  • Workspace!-typed args auto-inject from the binding and never appear in tool schemas. A module function's contextual (+defaultPath) arguments resolve against the bound workspace too, anchored at its root.
  • Host writes are unreachable from the model — only an explicit Workspace.export touches disk.
  • The new Query.currentNode lets a module's agent entrypoint bind its live receiver (withTools(currentNode)), since a self reconstructed from serialized state has no engine-side identity.
  • dagger mcp is migrated onto the same path: with nothing else bound, MCP binds each served workspace module's main object through the canonical server, so a served module exposes its methods again after the removal of ListMethods/SelectMethods/CallMethod.

Lazy reference args

Restoring a persisted session must not re-run the calls that built the objects bound as tools — they may have side effects, or may no longer be reproducible (a workspace carrying conflict markers, say, would break any tool that builds or starts something).

withTools was already lazy on the live path: its resolver takes an ID, and boundTool keeps that ID plus the object's GraphQL type, loading the object only on first dispatch. But that laziness is downstream of the problem. Loading an ID from its recipe evaluates every argument eagerly — the loader walks each argument literal, gathers the IDs it depends on, and resolves the whole transitive DAG before the field's resolver runs. It has no way to know the resolver only wants a type name.

So dagql grows LazyRef: an argument marked with it is skipped when gathering recipe inputs, carried into the frame in pure recipe form, and decoded for the selector straight from the recipe ID's literals, so it arrives at the resolver as an unevaluated ID. The marking is resolved from the schema by receiver type and field without evaluating anything, and is best-effort — an argument on a type that is not currently installed is treated as normal.

Env and Binding are gone

With the workspace supplying mutable state and scope, and object tools supplying tool generation, Env loses its last responsibility. Env, Binding, their schemas, the prompt I/O machinery (inputs/outputs, Save, DeclareOutput, $VAR expansion), the nested-client EnvContext plumbing, docs, and SDK surface are all deleted.

That removal also eliminates a source of dynamic core schema behavior: Env and Binding were the two core types whose fields were generated per installed type (Env.with<Type>Input/Output, Binding.as<Type>), meaning the core schema changed shape depending on which modules were loaded. Codegen's ExtendableTypes is now just Query.

Workspace propagation: seeding, not inheritance

The LLM's in-session overlay makes the bound workspace diverge from the frozen per-client one, which exposed every place the engine assumed those were the same. The rule this branch settles on — matching the direction main took in #13229 — is that a workspace is seeded into a call chain and otherwise passed explicitly; it is never carried implicitly across a module boundary.

  • Seeding. MCP tool dispatch threads the bound workspace into the tool call's context, and currentWorkspace prefers a context-bound workspace over the session's frozen one. Group runs (checks/generators/agents/services) already re-seeded the workspace they were rolled up from (Workspace & Directory APIs: patch conflicts, overlay search, path removal #13777), but loadWorkspaceArg consulted its callerInModuleFunction guard before the bound workspace — and a group leaf's auto-injected Workspace! resolves while running inside the module runtime, so the seeded workspace was rejected and the leaf read stale, frozen source. The visible symptom: an agent edits a file, runs its generate tool, and the edit has no effect. Checking the bound workspace first fixes it (TestGeneratorSeesOverlayEdits).
  • No cross-module carry. A module function calling another module must pass a Workspace explicitly; an omitted auto-injected Workspace! errors rather than silently falling back to the caller's workspace. An earlier revision of this branch did carry the binding across nested module clients (a WorkspaceContext alongside the receiver object, plus a server-side CurrentWorkspaceContext fallback); that leaked into dependencies, which then resolved their own module context against the caller's tree, and it has been removed along with the now-redundant isModuleRuntimeClient inheritance guard. The explicit-pass gate in loadWorkspaceArg is the single place this is enforced.
  • Frozen per-client workspace inheritance into nested clients stays as an engine-internal discovery mechanism, and module source stays session-served, so ordinary module usage is unchanged.

Also in here

  • Context-token reporting and cache accounting fixes across the providers, and Anthropic thinking blocks are surfaced.
  • Tool-call span fidelity on replay: arguments kept as span attributes, thinking re-emitted, the server set on the replayed LLM, and the duplicate per-call span collapsed. LLM spans stop using telemetry.Reveal() now that the TUI surfaces the conversation itself. Setting Server for that fidelity made CallBatch mistake object tools for MCP server tools; batching now routes on membership in mcpServers instead.
  • The TUI surfaces Generate spans structurally rather than via reveal: dagui gains a SurfacedGenerators tree keyed on the generator marker (same boundary/severed-chain containment as checks), and the final report grows a GENERATORS section alongside CHECKS/TESTS, with failed leaf generators rendering their own rolled-up logs and error.
  • LLM replay recordings are derived from the engine's own messages export instead of hand-edited golden files, so an API change no longer means editing recordings by hand.
  • The new LLM/workspace API surface (withWorkspace, workspace, contextTokens, Query.currentNode) is gated to v1 clients; the Java SDK marshals interface-typed args by ID, which the object-tools call path depends on; tests, fixtures, and docs are reworked from the Env era to the workspace/object-tools world.

Note on session resources

An earlier revision of this branch gated client-owned workspace results behind a per-client session-resource handle, so a cached result embedding a workspace could only be served to the session that created it. That handle has been dropped, along with its dagql value-scoping support in #13776.

It was a point fix for one instance of a broader class — state pinned to a client session that has since gone away — and resume was observed to break through other members of that class even while the workspace survived. Dropping it is safe here because module calls taking Workspace! args are session-unique by construction: the injected currentWorkspace ID carries a per-call nonce, so those calls are never shared across sessions, and cross-session sharing rides only on returned-module-object content digests, which carry no client binding. TestWorkspaceBoundLLMAcrossSessions covers this and passes without the handle. The generic SessionResourceHandle used by secrets and sockets is untouched.

@vito
vito changed the base branch from llm-workspace-llm-foundation to main July 13, 2026 21:21
@vito
vito force-pushed the llm-workspace-llm-binding branch from 31c8b75 to 4183bac Compare July 13, 2026 21:27
@vito
vito changed the base branch from main to llm-workspace-llm-foundation July 13, 2026 21:35
@vito
vito force-pushed the llm-workspace-llm-binding branch from 4183bac to 1fd56dc Compare July 13, 2026 21:57
@vito vito modified the milestones: 1.0.0-beta.1, v1.0.0 Jul 14, 2026
@vito
vito force-pushed the llm-workspace-llm-binding branch 2 times, most recently from 6ed219d to e197067 Compare July 14, 2026 20:01
@vito
vito force-pushed the llm-workspace-llm-binding branch 3 times, most recently from 566ba9b to a3b7c2f Compare July 15, 2026 01:01
@vito
vito force-pushed the llm-workspace-llm-binding branch from 4773b57 to 15bde10 Compare July 15, 2026 19:54
@vito
vito force-pushed the llm-workspace-llm-binding branch from cb8d48d to 6c303ed Compare July 15, 2026 23:26
vito added 28 commits August 4, 2026 19:55
The LLM acts through the methods of the objects it's bound to via
LLM.withTools: each eligible method becomes a tool, a method that returns
the bound object's own type rebinds it as the new state, and a Changeset
return applies to the bound workspace. Host-writing fields are blocked
from the model, module entrypoints are surfaced as the way in, and the
schema the model sees derives from the workspace it's bound to.

This replaces the per-field MCP tool surface, and with the workspace
binding in place the Env type loses its last responsibility: Env, its
schema, and its prompt I/O machinery are deleted.

(cherry picked from commit 6b74120)
Signed-off-by: Alex Suraci <[email protected]>
Add Query.currentNode, returning the object that received the current
module function call as the universal Node interface. It reads the
receiver threaded onto the active FunctionCall (ModuleFunction.Call now
records it on FunctionCall.parentTyped), which rides the existing
per-session fnCall channel into the module's nested client, so a module
can reference itself without reconstructing a fresh instance.

To let a statically typed caller pass that Node where an object is
wanted, LLM.withTools's object argument now carries
@expectedType(name: "Node"): every object implements Node, so Dang
accepts any object and conveys it as its id. A new dagql Argument.Directive
builder attaches the directive. Together these let a module bind its own
methods as the LLM's tools via base.withTools(currentNode, ...),
unblocking doug2.

Verified for the in-process Dang runtime, where the receiver crosses by
reference. The containerized runtime rides the same fnCall channel but,
along with the interface-typed return, needs a from-source engine to
confirm. SDKs and docs are regenerated.

(cherry picked from commit f690e8a)
Signed-off-by: Alex Suraci <[email protected]>
Two token-accounting fixes. Add LLM.contextTokens, the estimated tokens
currently occupying the context window -- the last provider-reported usage
plus an estimate of any messages appended since -- as distinct from the
cumulative LLM.tokenUsage. And stop double-counting cached prompt tokens:
OpenAI and Codex report prompt_tokens inclusive of cached reads, so
subtract the cached portion from InputTokens, record the cache-read metric
they were dropping, and include cache tokens in TotalTokens across the
providers.

(cherry picked from commit 83cf980)
Signed-off-by: Alex Suraci <[email protected]>
The LLM's in-session overlay makes the workspace it is bound to diverge from
the frozen per-client one, which exposed every place the engine assumed those
were the same. Close them: currentWorkspace prefers the bound workspace, group
runs (checks, generators, agents, services) re-seed the workspace they were
called on into each leaf, the binding is carried across nested module clients
on the same channel that carries the receiver object, and a tool returning a
Workspace rebinds the LLM to it.

Module source stays session-served, so ordinary module usage is unchanged.

REBASE NOTE: this replaced WorkspaceOverride which emerged independently
and landed first

Signed-off-by: Alex Suraci <[email protected]>
Consolidate the architecture of the workspace-bound LLM: the Workspace
binding that replaced Env, object tools as the agent interface, installable
@agent plugins, and the workspace propagation semantics (seed vs propagate,
the A-calls-B invariant). Supersedes the retired working docs for the
individual pieces.

(cherry picked from commit 1690122)
Signed-off-by: Alex Suraci <[email protected]>
Old module views were seeing the new API surface: the Agent and
AgentGroup types (plus their generated ID/load fields), the @agent
plumbing (Function.withAgent, Workspace.agents), Query.currentNode,
and the LLM workspace binding (withWorkspace, workspace,
contextTokens). Gate them all to v1.0.0-0, following the same pattern
the LLM foundation PR used for the content-block model.

Update base_schema.json to reflect the intended base view: identical
to main's plus the Env/Binding removal (a deliberate breaking change
of this PR) and the @agent directive, which has no view gating
mechanism. The golden had been recorded before the foundation PR
gated its own surface, so it also wrongly allowlisted content-block
types, Workspace.glob/search, and the loop(maxAPICalls) move.

(cherry picked from commit 1fcf9a2)
Signed-off-by: Alex Suraci <[email protected]>
Env and Binding were the two core types whose fields were generated per
installed type, so the core schema changed shape depending on which modules
were loaded. With them gone, codegen's ExtendableTypes is just Query.

Regenerate the Go client and the other SDKs without Env, drop the
hand-written documentation references, and rework the Env-era test fixtures
for the workspace world — including the go-programmer fixture, which is
rewritten against object tools and loses its checked-in generated client.
The Java SDK also learns to marshal interface-typed args by ID, which the
object-tools call path now depends on.

Signed-off-by: Alex Suraci <[email protected]>
The LLM replay recordings were checked in as golden files keyed by a bespoke
format, so every API change meant hand-editing them. Derive them from the
engine's own messages export instead, keyed the same way, and update the
remaining Env-era API usage in the tests that consume them.

Signed-off-by: Alex Suraci <[email protected]>
Refresh the base schema gold now that the agent-era surface is gated, and
regenerate the SDK clients and reference docs to match. Also drops a codegen
file left orphaned by the go-programmer fixture rewrite.

Signed-off-by: Alex Suraci <[email protected]>
The object-tools rewrite removed the ListMethods/SelectMethods/CallMethod
surface but dagger mcp was never migrated, so a served module exposed no
module methods at all: a bare LLM binds no tool objects. MCP now binds
each served workspace module's main object through the canonical server
(entrypoint constructors are not in the sugared schema), skipping
constructors with required non-Workspace args, when nothing else is
bound. Rewrite the MCP tests to the object-tools surface; the privileged
variants are renamed since --env-privileged no longer has a core-API tool
surface post-Env and now only gates module-less serving.

(cherry picked from commit 8ebfaf3)
Signed-off-by: Alex Suraci <[email protected]>
Workspace inheritance leaked into dependencies: a module's deps picked up the
caller's workspace, so a dep resolved its own module context against the wrong
tree. Stop inheriting into deps while keeping the frozen per-client workspace
inherited where it is still correct, and rewrite the propagation section of
the design doc to describe the resulting rule.

Signed-off-by: Alex Suraci <[email protected]>
Surface the Anthropic thinking blocks the provider already returns, and let
several Changeset-returning tools run in one turn: each changeset is applied
to the workspace overlay in call order instead of the last one winning.

Signed-off-by: Alex Suraci <[email protected]>
LLM spans were emitted with telemetry.Reveal() so they would surface at the
top level. The TUI now surfaces the conversation itself, so revealing every
individual span double-counts them and fights the transcript rendering. Drop
Reveal() from the LLM, display, and mod-tree spans.

Signed-off-by: Alex Suraci <[email protected]>
Loading an ID from its recipe evaluates every argument eagerly: the
loader walks each argument literal, gathers the IDs it depends on, and
resolves them all before the field's resolver ever runs. That is
necessary in general — reconstructing a receiver's state usually needs
real argument values — but it is wrong for an argument whose value the
resolver never dereferences.

Add lazy reference args for those. An argument marked LazyRef is skipped
when gathering recipe inputs, carried into the frame in pure recipe
form, and decoded for the selector straight from the recipe ID's
literals, so it reaches the resolver as an unevaluated ID rather than a
result that was intentionally never produced. The resolver loads the
referenced object itself, only if and when it needs the value.

This lets a session be resumed even when it carries stale data or
content that would fail to evaluate — conflict markers, for instance,
which would otherwise break any tool that builds or starts something.

The marking is resolved from the schema by receiver type and field
without evaluating anything, and is best-effort: if the type is not
currently installed, the argument is treated as normal.

Signed-off-by: Alex Suraci <[email protected]>
LLM.withTools binds an object only to expose its type's methods as
tools; the value itself is never dereferenced when the conversation is
reconstructed. Mark the object argument LazyRef so restoring a persisted
session does not re-run the call that produced it — which may have side
effects, or may no longer be reproducible.

boundTool holds the binding as an unevaluated ID plus the object's
GraphQL type, so the toolset can be built without loading anything. The
object is loaded on first dispatch, when a tool is actually invoked on
it.

Signed-off-by: Alex Suraci <[email protected]>
Replaying a conversation lost most of what the TUI needs to render it: tool
arguments were dropped, thinking blocks were not re-emitted, the server was
not set on the replayed LLM, and each tool call produced a redundant extra
span. Keep the arguments as span attributes, re-emit thinking, set the server,
collapse the duplicate span, and set the LLM call digest so the TUI can group
a call with its result. Tool output previews are also trimmed to the last 8
lines instead of 100.

Signed-off-by: Alex Suraci <[email protected]>
loadWorkspaceArg had two identical callerInModuleFunction guards — a
rebase artifact — with one placed before the bound-workspace check. A
generator/check leaf's auto-injected Workspace! is resolved while running
inside the module runtime, so callerInModuleFunction is true at that
point. The misplaced first guard short-circuited with the "workspace
arguments are not inherited by module runtime calls" error before the
seeded bound workspace was ever consulted, so the leaf fell back to stale
(frozen) source.

The visible symptom: an agent edits files, runs its `generate` tool
(which rolls up and runs Workspace.generators), and the edit has no
effect — e.g. removing an API from core/schema/ left docs:references
unchanged, because the overlay never reached the generator.

Fix: check the bound workspace (WorkspaceFromContext) first, then apply
the single callerInModuleFunction guard as the fallback. This matches the
design in hack/designs/workspace-agents.md §4 and the surviving comment.
It does not weaken cross-module isolation: the overlay is explicit (the
group threaded it via WorkspaceToContext), not silent inheritance.

Add TestGeneratorSeesOverlayEdits to TestLLM, with a gen-agent fixture: a
workspace whose module exposes write + generate tools and a @generate
generator. The canned conversation edits input.txt, runs generate, and
asserts the generator observed the overlay ("generated from: B-OVERLAY")
rather than the frozen base. Verified the test fails when the bug is
reintroduced.

(cherry picked from commit 7fb7cd3)
Signed-off-by: Alex Suraci <[email protected]>
NewLLM captured the calling context's currentWorkspace imperatively,
invisible to the LLM's recipe. That ambient inheritance is how a module
function returning a bare llm() picked up the caller's live workspace
(the doug2 dead-client bug), and it made LLM IDs lie about what they
were bound to.

Start the LLM with no workspace instead. Binding one is now always the
caller's explicit choice via LLM.withWorkspace, recorded as a selector
on the ID. An unbound LLM remains valid: MCP.Server already falls back
to the current client's served deps.

Signed-off-by: Alex Suraci <[email protected]>
dagger mcp served llm().__mcp and relied on the ambient workspace
capture to expose the workspace's schema over MCP. Resolve the current
workspace and bind it explicitly on the served LLM instead.

Signed-off-by: Alex Suraci <[email protected]>
The cross-session gating fixture returned a bare llm, relying on the
ambient workspace capture that no longer exists. Take the auto-injected
Workspace! arg and bind it explicitly — the calling session's live
workspace still ends up embedded in the cached LLM, so the test guards
the same dead-client regression through the explicit path.

Signed-off-by: Alex Suraci <[email protected]>
go-programmer and gen-agent constructed a bare llm and relied on the
ambient workspace for their Workspace!-typed tools. Take ws as an
explicit arg on run/drive (auto-injected at the CLI boundary, passed
explicitly module-internally) and bind it with withWorkspace. The replay
recordings are unaffected: they diff message text only, and the prompts
are unchanged.

Signed-off-by: Alex Suraci <[email protected]>
llm() no longer inherits the ambient workspace, so the CLI states its
intent on the ID: a fresh prompt-mode LLM chains
withWorkspace(currentWorkspace).

Resume needs no change in principle: a saved recipe's
withWorkspace(currentWorkspace) node replays through the cache lookup
and re-resolves against the resuming session's live workspace.

Signed-off-by: Alex Suraci <[email protected]>
The parallel-changeset shell pipeline relied on the ambient binding
llm() no longer performs; give it an explicit
with-workspace $(current-workspace) stage.

The unbound-LLM error message stops claiming a default binding exists.

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Setting Server to the bound type name for replay span fidelity (2717ed8)
made CallBatch treat object tools as MCP server tools, since it used a
non-empty Server as the discriminator. Parallel Changeset-returning calls
then skipped callBatchChangesets, fell through callBatchMCPServer's
unknown-server fallback into plain parallel execution, and each call applied
its changeset directly to the workspace — last writer wins, dropping the
other tool's changes. It also lost the sequential guarantee for destructive
object tools. Route on membership in mcpServers instead, so Server stays
display metadata for tools that aren't backed by a registered MCP server.

Signed-off-by: Alex Suraci <[email protected]>
Generator spans stopped setting `reveal` along with the rest of the mod-tree
spans, which broke the generate-fail golden: the failed generator row and its
rolled-up exec stderr vanished from the report. Instead of restoring reveal,
detect Generate spans structurally, the way checks, tests, and conversations
already surface.

dagui gains SurfacedGenerators -- a reveal-independent tree keyed on the
GeneratorName marker with the same boundary/severed-chain containment as
checks, deduped by name, failed-first -- plus HasGenerators and
PromoteGeneratorsTo for the live tree. The final report renders a GENERATORS
section in lockstep with CHECKS/TESTS; a failed leaf generator renders its own
rolled-up logs and error (the changeset is forced inside the generator span,
so its log buffer is the exec failure), deferring to explicit ErrorOrigins
links when present rather than hunting descendants, which repeated the
generator's row and surfaced runc internals. Live, promoteGeneratorsLocked
wires the surfaced tree into the host's RevealedSpans and marks it
Passthrough, keeping skipped-module rows visible alongside. The FinalRender
persistence gate, report-only log prefetch, SurfacedFailedCheckSpans, and the
root-cause suppression guard all learn about generators, and the generate-fail
golden is regenerated to the new sectioned shape with the same failure
content.

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Rebasing onto main picked up Query.volume (#13719), whose additions to the
schema and every client collided with this stack's own generated output.
The conflicts were resolved by regenerating rather than merging by hand,
so this is codegen output only - no hand edits.

Signed-off-by: Alex Suraci <[email protected]>

@grouville grouville left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving eagerly, everything LGTM apart the LLM edge case I found and documented on the comment

Comment thread internal/cmd/dagger/llm.go Outdated

changed = true
syncedLLMQ = syncedLLMQ.
Select("withObject").

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like syncing an object-typed shell variable into the LLM still uses withObject, which no longer exists.

I was able to reproduce it against the dev engine:

./hack/with-dev ./bin/dagger shell
obj=$(container)
● ✔ obj=$(container) 0.0s

# press > to switch to prompt mode, then submit a prompt
gpt-5.6 ❯ hello

Error: returned error 422: Cannot query field "withObject" on type "LLM".

After assigning the object, switching to prompt mode, and typing hello, GraphQL validation fails before the prompt can run. I think this should use withTools(object: ...) instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, yeah makes sense - that code all gets ripped out in #13780 so I didn't catch it. I'll remove it from this PR so we can merge it independently.

Remove syncVarsToLLM/syncVarsFromLLM instead of porting the object-var
loop to withTools. Binding every object-typed shell var as a toolset was
a holdover from the tagged-value Env model and no longer makes sense now
that objects reach the LLM as tools bound to the workspace. The two
useful side effects buried in syncVarsToLLM survive inline in
WithPrompt: picking up a reassigned $agent var as the LLM to prompt, and
initializing the beforeFS baseline for the "Changes" preview. Also drop
the now-unused skipEnv/syncedVars session state, the lastValueVar const,
and the DAGUI_DEBUG dbg logger whose only caller was the sync loop.

Signed-off-by: Alex Suraci <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants