Skip to content

LLM foundation: providers, config, session CLI, and TUI - #13634

Merged
vito merged 63 commits into
mainfrom
llm-workspace-llm-foundation
Jul 17, 2026
Merged

vito merged 63 commits into
mainfrom
llm-workspace-llm-foundation

Conversation

@vito

@vito vito commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Warning

(From a human:) this PR implements a conscious breaking API change. Previously the LLM type was opaque and mutable - when you called e.g. LLM.lastReply that would detect whether the LLM evaluated and, if not, lazily evaluate (i.e. do the agent request/response/tool calls loop until the model ends its turn).

This PR instead 1. exposes an immutable LLM constructed with the message history as it grows, and 2. requires you to explicitly call .loop or .step so it's clear when content is done being appended and it's time to evaluate. The explicit .step and .loop calls are important, because they're how you hold a reference to the single lazily-evaluated LLM result, so you can chain .lastReply or other fields against it. Previously the LLM type had to be mutable to support calling multiple leaf fields without evaluating on each field call.

Considering the LLM APIs were always experimental, and the change is so foundational (it changes how you call it, not what you call), I opted to just break since a major bump to 1.0 is right around the corner anyway.

LLM-written below:


Note

Stack 3/5 — each PR is based on the one below it, so the diff shows only this PR's own changes. Merge bottom-up; when a PR below merges and its branch is deleted, GitHub retargets this one automatically and the rest of the stack gets rebased.

  1. Engine & TUI fixes: clientdb writes, dagql fan-out, high-verbosity traces #13632 — Engine & TUI fixes
  2. Workspace file APIs: glob and search #13633 — Workspace file APIs: glob and search
  3. LLM foundation: providers, config, session CLI, and TUI #13634 — LLM foundation: providers, config, session CLI, and TUI 👈 this PR
  4. LLM ⇄ Workspace: object tools and Env removal #13635 — LLM ⇄ Workspace: object tools, Env removal, and @agent plugins
  5. llm-workspace dev tooling: skills, tui-qa agent, sparse-read design doc #13636 — llm-workspace dev tooling

Client-side and engine plumbing for the LLM API the rest of the stack builds on. The new API surface is gated to v1.

Config, CLI, and Anthropic OAuth — the llmconfig package (provider/model config, persistence, model suggestions), the dagger llm command group, and Claude Code subscription OAuth.

Content-block message model — LLMMessage/LLMContentBlock and the message-history API (messages, serializeHistory, replay, withResponse, withToolCall, …), regenerated across the SDKs and docs.

Providers — OpenAI Codex over the Responses API against the ChatGPT backend, and self-hosted OpenAI/Anthropic-compatible servers (Ollama, LM Studio, vLLM) under a local slot, tunneled through the client session so the engine can reach a server only the client can.

Reasoning effort — the model catalog and reasoning config come from catwalk (bumped for Opus 4.8 / Fable 5), not curated locally; reasoning is a single per-provider effort level mapped to each provider's native parameter (Anthropic output_config.effort, OpenAI/Codex reasoning.effort, Gemini thinking_level), with no separate token budget.

Extended thinking — thinking and redacted-thinking blocks are captured and replayed across turns (Anthropic, Google) so multi-turn tool use keeps its reasoning context.

Sessions — save, .resume, and mid-turn interject for dagger llm, plus branch summaries.

TUI — unified-diff and tool-argument rendering, interject queue with recall, a token/cost/context status line, and branching a conversation from a span.

Tracing — a per-HTTP-call OTel span that tees request/response bodies, and live per-turn display spans (thinking, response, tool calls) matching the replay layout.

🤖 Generated with Claude Code

@vito
vito changed the base branch from llm-workspace-file-apis to main July 13, 2026 21:21
@vito
vito force-pushed the llm-workspace-llm-foundation branch from 35d33c5 to 50c3bf6 Compare July 13, 2026 21:27
@vito
vito changed the base branch from main to llm-workspace-file-apis July 13, 2026 21:35
@vito
vito force-pushed the llm-workspace-llm-foundation branch from 50c3bf6 to 9d603cb Compare July 13, 2026 21:57
@vito
vito force-pushed the llm-workspace-file-apis branch from 3f3ac71 to 2bdc629 Compare July 14, 2026 01:05
@vito
vito force-pushed the llm-workspace-llm-foundation branch 3 times, most recently from e3cfbb3 to d1f80aa Compare July 14, 2026 14:07
@vito
vito force-pushed the llm-workspace-file-apis branch from aad0a00 to c767c6f Compare July 14, 2026 14:55
@vito
vito force-pushed the llm-workspace-llm-foundation branch from 7b3c8b4 to 3761bb2 Compare July 14, 2026 15:49
@vito vito modified the milestones: 1.0.0-beta.1, v1.0.0 Jul 14, 2026
vito added a commit to vito/dagger that referenced this pull request Jul 14, 2026
C (dagger#13634) is fully green: compat commits dropped in favor of fixture
and golden updates, the MCP object-tag aliasing fix landed, regens are
committed, and the branch was rebased onto B's rewritten history. Record
the state of the stack, the fix's invariants for D's Env rework, and the
session's operational lessons (host-side golden recording, replay
matching blind spots, prompt-confirmation persistence, credential-free
replay testing). Next up: rebase D onto C, then the tip.

Signed-off-by: Alex Suraci <[email protected]>
@grouville
grouville force-pushed the llm-workspace-file-apis branch from c767c6f to 03f6e49 Compare July 14, 2026 17:47
@vito
vito force-pushed the llm-workspace-file-apis branch from 03f6e49 to c767c6f Compare July 14, 2026 18:02
Base automatically changed from llm-workspace-file-apis to main July 14, 2026 18:51
@vito
vito force-pushed the llm-workspace-llm-foundation branch from b245612 to 6bd1564 Compare July 14, 2026 23:15
@tiborvass

tiborvass commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor
  1. [P1] WithToolCall mutates ancestor/sibling LLM states. Clone only copies the message pointer slice, then WithToolCall modifies the shared LLMMessage.Content. Branching from a response can therefore change the original branch and invalidate persisted DAG identity. Copy the target message and its content slice before appending.

  2. [P1] Saving LLM config destroys unrelated TOML sections. Load unmarshals into an LLM-only struct and Save marshals that struct back, despite the comment promising that other sections are preserved. llm reset also deletes the entire shared config file rather than only [llm].

  3. [P1] OpenAI and OpenRouter configuration is nondeterministic. applyLLMConfigEnv ranges over a map while both providers populate the same OPENAI_* variables. Since setIfEmpty makes the first value win, users can get the wrong provider or an OpenAI key paired with the OpenRouter base URL. Resolve the selected default provider first and export one coherent slot.

  4. [P1] Switching providers can retain and misroute through the old model. set-default <provider> leaves DefaultModel unchanged when its optional model argument is omitted. For example, switching from OpenAI/gpt-4.1 to Anthropic exports gpt-4.1 as the Anthropic model, after which prefix routing selects OpenAI again. Pick the provider default model or clear the stale value.

  5. [P1] HTTPS local/custom endpoints do not survive the tunnel rewrite. Replacing u.Host with the engine loopback listener makes TLS verification/SNI and the HTTP Host header use 127.0.0.1, breaking certificates and virtual-hosted endpoints. Preserve the original TLS server name and Host header while dialing through the tunnel.

  6. [P2] Local tunnels are never stopped. The tunnel deliberately strips request cancellation and says its owner must call Stop, but there are no callers. Changing models or ending a client session leaves listeners and goroutines alive for the engine lifetime.

  7. [P2] Auto-saved conversations are world-readable by default. The session directory is created as 0755 and files as 0644. Each file contains the initial prompt and a history-bearing LLM ID. These should be 0700/0600, including correcting permissions on existing paths.

Reviewed by Codex (GPT-5)

@vito
vito force-pushed the llm-workspace-llm-foundation branch from 5468088 to 57b2471 Compare July 15, 2026 02:21
@vito
vito marked this pull request as ready for review July 15, 2026 19:20
@vito
vito requested review from a team as code owners July 15, 2026 19:20
vito and others added 24 commits July 16, 2026 18:58
The Anthropic request builder always replayed stored thinking and
redacted-thinking blocks, but Anthropic rejects a request that carries
thinking blocks when thinking is not enabled for it. A conversation whose
earlier turn produced thinking then failed once reasoning was turned off
(effort cleared, or a model that does not support output_config.effort).

Gate thinking-block replay on the same condition that enables
output_config.effort, dropping the stored blocks when reasoning is off.

Signed-off-by: Alex Suraci <[email protected]>
handlePromptForm's OnQuit invoked the result callback before removing the
form. The branch-from-span "custom prompt" path chains a second form from
that callback, which reassigns fe.formWrap/formModel/formSpacer, so the
subsequent removeForm hit its "not the active form" guard and left the
first form and its spacer stranded on screen with broken height budgeting.

Remove the form before invoking the callback, capturing the form model
first since removeForm nils it.

Signed-off-by: Alex Suraci <[email protected]>
renderUnifiedLine hard-coded a 12-column gutter, so once a line number
reached five digits the gutter and marker overflowed the target width and
the line wrapped. addFileContext also miscounted the covered line range
when the edited text ended in a newline, starting the after-context one
line too far down and skipping a line.

Compute the gutter width from the widest line number in the diff and
truncate content against it, and account for a trailing newline when
deriving the covered range.

Signed-off-by: Alex Suraci <[email protected]>
The status line right-aligned the model name using a byte count of the
left segment, but the up and down token arrows are multi-byte glyphs that
occupy one display cell each, so the padding was overcounted and the name
drifted left of the right edge.

Measure the left segment in display cells with ansi.StringWidth, which
also strips escape codes.

Signed-off-by: Alex Suraci <[email protected]>
The Anthropic API requires max_tokens, and the client hardcoded 8192,
silently truncating replies on models that support 64k-128k output.
Look up per-model metadata (default max tokens, context window) from
catwalk's embedded catalog at routing time, keyed by a normalized model
ID so dated, aliased, and prefixed variants all resolve. The Anthropic
client now defaults to the model's own cap, keeping 8192 only as a
fallback for unknown models such as Anthropic-compatible local
endpoints, and clamps the value to the context window's remaining
space, since the API rejects requests whose input plus max_tokens
exceed it. An explicit cap is respected as-is rather than silently
raised when reasoning is enabled.

Signed-off-by: Alex Suraci <[email protected]>
Replace the withMaxTokens LLM field with an optional maxTokens argument
on loop and step, capping the model's output tokens per API call made
during that invocation. An output cap is a call-site contract - "this
generation must fit in this box", e.g. a summary injected back into
context - not durable conversation configuration: middleware such as
agent modules has no reason to set one, and sticky state would silently
truncate later, unrelated calls. This mirrors pi, which passes maxTokens
per request at specific call sites and keeps durable caps in per-model
config (our catalog defaults). Providers honor an explicit cap where
safe: OpenAI via max_completion_tokens (or classic max_tokens for
OpenAI-compatible endpoints, which often lack the modern field), Gemini
via maxOutputTokens, while Codex sends nothing since its backend only
officially serves the Codex CLI, which never sends a cap.

Signed-off-by: Alex Suraci <[email protected]>
Regenerate client libraries and API reference for the LLM maxTokens
change: withMaxTokens is removed and loop/step gain an optional
maxTokens argument.

Signed-off-by: Alex Suraci <[email protected]>
Branch summaries lost their 2048-token output cap when withMaxTokens
was replaced, since the loop argument did not exist in the generated
SDK until the regen. Pass it via the loop opts again: the summary is
injected into future context, so it must stay small, and maxAPICalls
alone does not bound the reply size. The cap matches pi's branch
summarization.

Signed-off-by: Alex Suraci <[email protected]>
Branch summaries serialized the entire conversation into a single
prompt, so a near-window-sized history left the summarization request
little or no room to respond, or failed outright once the input alone
exceeded the model's context window. Trim the serialized conversation
to a conservative input budget before prompting, dropping the oldest
messages at serialization boundaries and marking the omission, with a
tail-keeping fallback for a single oversized message. This mirrors pi's
branch summarization, which budgets input to the context window minus
tokens reserved for the prompt scaffolding and the reply.

Signed-off-by: Alex Suraci <[email protected]>
Add a contextWindow field returning the model's total context size from
the catalog metadata on the endpoint, or zero when the model is unknown
(e.g. local endpoints). Clients that build prompts from serialized
history - such as the CLI's branch summarization - need it to budget
their input against the actual model instead of guessing a conservative
constant.

Signed-off-by: Alex Suraci <[email protected]>
Regenerate client libraries and API reference for the new LLM
contextWindow field.

Signed-off-by: Alex Suraci <[email protected]>
Branch summary trimming assumed a fixed 128k-token context window.
Query the new contextWindow field so the input budget matches the
model actually summarizing, keeping the fixed value only as a fallback
for unknown models, and floor the budget so tiny windows still see some
conversation.

Signed-off-by: Alex Suraci <[email protected]>
The maxTokens branches pushed SendQuery past the gocyclo threshold.
Move the content-block-to-OpenAI message conversion into its own
function, mirroring the Google client's prepareGenaiHistory, which
leaves SendQuery well under the limit instead of at the cliff edge.

Signed-off-by: Alex Suraci <[email protected]>
v1 allows breaking changes, so revise the LLM type for coherence and
correctness. loop(maxAPICalls) becomes loop(maxSteps), defined in terms
of the step primitive, and step returns LLM lazily like every other
field, leaving sync as the one forcing mechanism. hasPrompt becomes
hasPending (it reports queued tool results too), attempt(number)
becomes fork(label), globalID becomes portableID, serializeHistory
becomes transcript, and withToolResponse becomes withToolResult with
callId/toolName arguments matching LLMContentBlockInput. history and
historyJSON demote to pre-v1 views, superseded by messages and
transcript; attempt also stays pre-v1 for the evaluator module.
contextWindow returns null rather than 0 when unknown. LLMContentBlock
exposes signature so exported conversations reconstruct losslessly via
withResponse. llm() and withModel() accept an optional provider to
route explicitly instead of pattern-matching the model name. Every
LLM-family type and field gains a real description.

Signed-off-by: Alex Suraci <[email protected]>
Regenerate client libraries and the API reference for the reworked LLM
conversation API. Note that this commit does not build on its own: the
CLI still references the old SDK names until the following commit
adopts the new ones.

Signed-off-by: Alex Suraci <[email protected]>
Update the CLI and integration tests to the regenerated SDK: drive
turns with step().Sync() and hasPending, persist sessions via
portableID, print and summarize conversations via transcript, and cap
branch summaries with LLMLoopOpts.MaxSteps. TestAPILimit becomes
TestStepLimit; since the v1 view no longer serves historyJSON, its
golden-update path records conversations by exporting structured
messages over raw GraphQL and re-encoding them in the replay decoder's
format (the existing golden replays unchanged). Also fix two stale
core comments that referenced withToolResponse and historyJSON.

Signed-off-by: Alex Suraci <[email protected]>
Expose per-message token usage as LLMMessage.tokenUsage, making a
messages{...} export a lossless record of a conversation. The messages
resolver serves zeroed usage for messages that never had any (prompts,
tool results) since the field is non-null.

The replay/ model decoder now consumes exactly that export shape
(lowerCamel keys, usage included) instead of core.LLMMessage's private
snake_case encoding, so recordings can be produced by any client with
a single query and no re-encoding.

Drop the pre-v1 history and historyJSON fields and their backing
methods. They existed only for the record/replay test machinery, which
now records via the messages export; in-repo modules still calling
history (modules/evaluator, modules/evals) are unused and slated for
deletion.

Signed-off-by: Alex Suraci <[email protected]>
Pick up the new LLMMessage.tokenUsage field across the SDK clients and
the docs schema reference. The removed history/historyJSON fields were
only visible to pre-v1 module views, so nothing else changes in the
rendered v1 schema.

Signed-off-by: Alex Suraci <[email protected]>
Replay recordings are now plain messages{...} query exports, recorded
uniformly by -update: TestCase and TestAllowLLM query the module's
conversation (agent returns the LLM itself), and TestStepLimit drives
the same pipeline as its shell command over raw GraphQL through a
shared recordMessages helper. All three goldens are re-recorded in the
new shape, and no test needs bespoke re-encoding anymore since the
export already is the replay wire format.

go-programmer is rewritten in Dang against the v1 API, replacing the
historyJSON-dumping save hack. TestAllowLLM now drives new Dang
modules at a new path in dagger-test-modules (the old Go modules
remain for older branches), with the refs pinned to a commit so
changes to that repo can no longer silently affect every branch's CI.
Cache busting moved from a UUID env input inside the module to a fork
label passed by the harness, keeping the message history
deterministic.

Signed-off-by: Alex Suraci <[email protected]>
connect() used to discard the Dagger client's log output entirely,
with a FIXME noting it kept TUI spans readable. Only silence it when
the tests themselves run nested inside Dagger (detected by
DAGGER_SESSION_PORT, the same check the engine client uses): there a
TUI already renders progress. On the host there is no such frontend,
so stream the logs into the test output for debuggability.

Signed-off-by: Alex Suraci <[email protected]>
withToolCall has had no caller since it was introduced: the engine
materializes tool calls inside withResponse's content blocks, and
reconstruction from another source uses the same path (that's why
content blocks carry signature). Its semantics were also a trap: it
retroactively edited the last assistant message, silently did nothing
when no assistant message existed, and inserting a call into an old
turn mid-conversation produces sequences providers reject. Tool
results keep their own field because step() records them engine-side,
after the response.

Signed-off-by: Alex Suraci <[email protected]>
Drop the removed LLM.withToolCall field from the SDK clients and the
docs schema reference.

Signed-off-by: Alex Suraci <[email protected]>
The dagger-test-modules refs move from dang/llm-dir-module-depender
(organized by SDK, named after its mechanics) to llm/direct and
llm/indirect: organized by purpose, and named for exactly what the
allow-llm policy test distinguishes - direct versus transitive LLM
access. The modules are now siblings, with llm/indirect depending on
../direct. Pin bumped to the reorganized commit; consts and subtest
labels renamed to match.

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the llm-workspace-llm-foundation branch from 3309499 to 46aec6f Compare July 16, 2026 23:00
@vito
vito merged commit dc12c3a into main Jul 17, 2026
86 of 87 checks passed
@vito
vito deleted the llm-workspace-llm-foundation branch July 17, 2026 00:13
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