Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat: switch the model inside a Session — compact on the current model, continue on the new one (#748)

Yaowei Zheng76355dcf6928
diff --git a/.agents/skills/penguin-harness-dev/SKILL.md b/.agents/skills/penguin-harness-dev/SKILL.md
index acaf3ba2..c7cf73d9 100644
--- a/.agents/skills/penguin-harness-dev/SKILL.md
+++ b/.agents/skills/penguin-harness-dev/SKILL.md
@@ -180,3 +180,11 @@ Whatever is decided, compatibility code is a standing cost: name **how long it s
it, and what has to be true first**, at the code site and in a dedicated
`changelog/unreleased/YYYY-MM-DD-backward-compatibility.md`. Other entries in that batch reference
that file instead of re-telling it. A batch with no compatibility handling has no such file.
+
+## The message protocol is closed by default
+
+- **OmniMessage is closed by default.** No new field, type or enum value unless the fact is
+ unrepresentable by existing records and underivable by readers; prefer recording earlier or
+ streaming an existing record over a new field. Say so in the PR. The architecture spec's
+ message-format section states the rule, and `packages/core/src/omnimessage/types.ts` repeats it
+ at its head.
diff --git a/changelog/unreleased/2026-09-16-in-session-model-switch.md b/changelog/unreleased/2026-09-16-in-session-model-switch.md
new file mode 100644
index 00000000..50de229d
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-in-session-model-switch.md
@@ -0,0 +1,35 @@
+# Switching the model inside a Session
+
+- **Date:** 2026-09-16
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `cli`, `docs`
+- **PR:** [#748](https://github.com/Prism-Shadow/penguin-harness/pull/748)
+
+[中文版](2026-09-16-in-session-model-switch.zh.md)
+
+A Session could run on only one model: the model reference was fixed when the Session was created, and changing it meant `/model`, which opens a new conversation. A Session can now switch models in place. The switch compacts the context on the current model first, and only when that compaction completes does the next model context open on the target model, carrying the summary. One Session can therefore run several models over its life. Changing the thinking level still leaves compacting first to the user; a model switch always compacts.
+
+## Core
+
+- `Session.switchModel({ provider, modelId, signal })` streams the switch and returns its terminal status. The target is checked against the Project config on disk and its client is constructed before any event, so a missing model or credential is refused without touching the Trace. Switching to the current model does nothing.
+- The model reference moved from the Session to the model context. Context assembly resolves the entry each context opens on, and `Session.provider` / `Session.modelId` read the running context's `session_meta`. Subagents spawned after a switch inherit the new model; the image fold and `read_file`'s vision describer follow the current entry; explicit SDK credentials apply only to the model the Session was created with.
+- A switch always summarizes, whatever `compaction.mode` says. Its compaction request is an ordinary one on the current model — the same system prompt, toolset and parameters, one appended user turn — so it extends the prefix the provider has cached. A context with no completed turn has nothing to summarize and switches without a request or a compaction pair: right after a compaction the held summary is carried over; an open context whose first request never completed is left as it is, its pending text carried over in memory and the summary it opened with, if any, written again at the head of the new file; a Session that never ran is re-assembled on the target without writing anything. A switch carries text only: pending images are not carried to the new context.
+- A switch's compaction is an ordinary `manual` compaction; the next context's Trace file opens as soon as the switch completes, headed by its `session_meta`, and that record is also streamed — no OmniMessage field or enum value was added. `resumeSession` therefore lands on the new model from the Trace alone, with the summary pending — and still written on to the next file by another switch made before the first turn completes. A switch interrupted before its new file exists resumes on the model the Session was on, the summary still pending.
+- A failed or aborted switch leaves the Session on its model.
+- The switch's known refusals are thrown as `ModelSwitchRefusedError` with a `reason` (`model_not_configured`, `model_unavailable`, `compaction_not_configured`), so a host maps them without reading messages; any other error is a failure.
+
+## Server
+
+- `POST /api/sessions/:sessionId/switch-model` with `{ provider, modelId }`. It answers 202 and streams like `/compact` (status `compacting`), or 200 with the updated Session when the Session had never run. Refusals are 409 `task_in_progress`, `compacting`, `same_model`, `model_not_configured`, `model_unavailable` and `compaction_not_configured`; any other error core throws before its first event answers 500.
+- The Session row's `provider` / `model_id` became the current model: they move as the new context's `session_meta` passes through the stream and are reconciled from the loaded Session. The switch's compaction request is billed to the old model and later requests to the new one. A fork takes its model from the shard it cuts.
+- The switch is the Session's run from its first step: it can be stopped, and a deletion waits for it, before anything has streamed.
+
+## Web
+
+- The model badge of an open conversation became a model picker. Picking another model asks for confirmation (compact and switch, or cancel); an empty conversation switches directly, and right after a compaction or another switch the dialog says nothing is compacted again and only offers "Switch". The picker is disabled while the conversation runs or compacts. The conversation shows the switch as an ordinary compaction row (when there was something to compact) followed by a "Model switched · A → B" marker, derived from two consecutive `session_meta` records, and the page picks up the new model when the switch completes.
+- A Task's cost estimate is priced on the model the Task ran on, so the rows above a switch keep their figures.
+- `/model` keeps opening a new conversation on another model; its description, picker, chip and banner now say so.
+
+## CLI
+
+- `penguin chat` gained `/switch-model <provider> <model_id>`; bare `/switch-model` prints the current model. The REPL renders the switch's compaction like any other and prints `model: A → B` when it completes. `--resume` still rejects model flags and points to `/switch-model`.
diff --git a/changelog/unreleased/2026-09-16-in-session-model-switch.zh.md b/changelog/unreleased/2026-09-16-in-session-model-switch.zh.md
new file mode 100644
index 00000000..ee1eee93
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-in-session-model-switch.zh.md
@@ -0,0 +1,35 @@
+# 会话内切换模型
+
+- **Date:** 2026-09-16
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `cli`, `docs`
+- **PR:** [#748](https://github.com/Prism-Shadow/penguin-harness/pull/748)
+
+[English](2026-09-16-in-session-model-switch.md)
+
+此前一个 Session 只能使用一个模型:模型引用在创建 Session 时固定,要换模型只能用 `/model` 新开一个会话。现在 Session 可以就地切换模型:先用当前模型压缩上下文,压缩完成后才在目标模型上开启下一个模型上下文,并带上摘要,于是同一个 Session 可以先后使用多个模型。调节思考等级时是否先压缩仍由用户决定;切换模型则必定先压缩。
+
+## Core
+
+- `Session.switchModel({ provider, modelId, signal })` 流式产出切换过程,返回其终态。目标先按磁盘上的 Project 配置校验并构造其客户端,之后才产出事件,因此模型或凭据缺失时直接拒绝、不触碰 Trace;切换到当前模型不做任何事。
+- 模型引用从 Session 移到模型上下文:上下文装配时解析该上下文所用的模型条目,`Session.provider` / `Session.modelId` 读取运行中上下文的 `session_meta`。切换后派生的子会话继承新模型;图片折叠与 `read_file` 的视觉描述跟随当前条目;SDK 显式传入的凭据只作用于创建时的模型。
+- 切换一律 summarize,无视 `compaction.mode`。这次压缩请求就是当前模型上的一次普通请求——系统提示词、工具集和参数都不变,只追加一条用户消息——因此延续服务商已缓存的前缀。没有完成任何一轮的上下文没有可总结的内容,切换时不发请求、也不产生压缩事件对:刚压缩过时带上已持有的摘要;首个请求未完成的上下文保持原样,其尚未送达的文本在内存中带过去,该上下文开启时所带的摘要(如有)则再写一次到新文件开头;从未运行过的 Session 直接在目标模型上重新装配,不写任何记录。切换只携带文本:尚未送达的图片不会带进新上下文。
+- 切换所做的压缩就是一次普通的 `manual` 压缩;切换完成时即开启下一个上下文的 Trace 文件,以其 `session_meta` 开头,这条记录同时推入输出流——OmniMessage 未新增任何字段或枚举值。因此 `resumeSession` 仅凭 Trace 即运行在新模型上,并带着待发的摘要——在完成第一轮之前再次切换,这条摘要仍会写到下一个文件的开头。切换在新文件建立之前中断时,Session 恢复在原模型上,摘要仍然待发。
+- 切换失败或被中断时 Session 保持原模型。
+- 切换的已知拒绝以带 `reason` 的 `ModelSwitchRefusedError` 抛出(`model_not_configured`、`model_unavailable`、`compaction_not_configured`),宿主据此映射、不必解析错误信息;其余异常一律视为失败。
+
+## Server
+
+- 新增 `POST /api/sessions/:sessionId/switch-model`(`{ provider, modelId }`):答 202 并像 `/compact` 一样流式推送(状态 `compacting`);Session 从未运行过时答 200 并带回更新后的 Session。拒绝一律 409:`task_in_progress`、`compacting`、`same_model`、`model_not_configured`、`model_unavailable`、`compaction_not_configured`;core 在首个事件前抛出的其他异常答 500。
+- Session 行的 `provider` / `model_id` 改为当前模型:新上下文的 `session_meta` 经过输出流时更新,并在加载 Session 时按其实际模型校正。切换所用的压缩请求计入旧模型,此后的请求计入新模型。fork 取所截分片的模型。
+- 切换自第一步起即是该 Session 的一次运行:尚未推送任何内容时就可以中断,删除 Session 也会等它结束。
+
+## Web
+
+- 进行中对话的模型标识改为模型选择器:选择其他模型时弹出确认(压缩并切换 / 取消),空对话则直接切换,刚压缩或刚切换过的对话则说明不会再次压缩、只提供「切换」;对话运行或压缩中选择器不可用。切换在对话中显示为一条普通的压缩行(有内容可压缩时),其后是由前后两条 `session_meta` 推导出的「模型已切换 · A → B」标记,切换完成后页面随之改用新模型。
+- Task 的费用估算按该 Task 实际运行的模型计价,切换之前各行的数字保持不变。
+- `/model` 仍是换模型开新会话;其描述、选择器、标签与横幅都写明这一点。
+
+## CLI
+
+- `penguin chat` 新增 `/switch-model <provider> <model_id>`;不带参数时打印当前模型。REPL 像渲染其他压缩一样渲染切换的压缩,完成后打印 `模型:A → B`。`--resume` 仍不接受模型参数,并提示改用 `/switch-model`。
diff --git a/packages/cli/src/client.ts b/packages/cli/src/client.ts
index f3652c5b..4371231e 100644
--- a/packages/cli/src/client.ts
+++ b/packages/cli/src/client.ts
@@ -195,6 +195,13 @@ export class ApiError extends Error {
) {
super(message);
}
+
+ /** The server's own message, unwrapped (empty when the body carried none) — for a caller that localizes the code and still needs the specifics. */
+ get detail(): string {
+ const message = (this.body as { error?: { message?: unknown } } | null | undefined)?.error
+ ?.message;
+ return typeof message === "string" ? message : "";
+ }
}
export class ServerClient {
diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.ts
index 1fe30f3a..bd2637ea 100644
--- a/packages/cli/src/commands/chat.ts
+++ b/packages/cli/src/commands/chat.ts
@@ -10,12 +10,15 @@
* Session's SSE stream (subscribe first, POST second) through the shared watcher.
* `/goal[:<budget>] <objective>` runs goal mode; `/compact` POSTs a compaction and
* renders its progress; `/clear` creates a fresh server Session in place; `/thinking`
- * shows or re-pins the Session's thinking level; `/verbose` toggles tool-output
+ * shows or re-pins the Session's thinking level; `/switch-model <provider> <model_id>`
+ * switches the Session's model in place (compacting on the current model first) and
+ * bare `/switch-model` shows the current one; `/verbose` toggles tool-output
* collapsing (display only); `/exit` or `/quit` exits. Typing while a turn runs POSTs
* a steering message (delivered between turns); Ctrl-C during a run POSTs /abort.
*
* `--resume` reuses an existing Session (full id or unique fragment; omitted = the
- * agent's most recent Session) and first renders its history from GET /messages.
+ * agent's most recent Session) and first renders its history from GET /messages; it
+ * takes no model flags — `/switch-model` changes the model inside the chat.
* Ctrl-C behavior (state-dependent): buffer has content -> clear it; awaiting approval
* -> deny; running -> abort the current turn; empty buffer -> y/N exit confirmation.
* Docs: /docs/cli § "penguin chat".
@@ -28,6 +31,12 @@ import type { SessionInfo } from "@prismshadow/penguin-server/api";
import { StreamRenderer, dim, renderHistory } from "../render.js";
import { parseGoalCommand } from "../goal-command.js";
import { parseThinkingCommand, resolveThinkingLevel } from "../thinking-command.js";
+import {
+ formatModelLabel,
+ parseSwitchModelCommand,
+ switchModelRefusal,
+ type ModelTarget,
+} from "../switch-model-command.js";
import { parseApprovalAnswer, resolveApprovalMode } from "../approval.js";
import { LineComposer, PasteFilter } from "../input.js";
import {
@@ -93,8 +102,9 @@ export function registerChatCommand(program: Command, t: Messages): void {
process.exitCode = 1;
return;
}
- // --resume excludes --workspace and the model pair (neither can change once the
- // Session exists); checked before any connection is made.
+ // --resume excludes --workspace and the model pair (the resumed Session keeps its
+ // own; /switch-model changes the model inside the chat); checked before any
+ // connection is made.
if (opts.resume !== undefined && (opts.workspace || opts.modelId || opts.provider)) {
process.stdout.write(`${t.error(t.resumeNoOverride())}\n`);
process.exitCode = 1;
@@ -111,9 +121,9 @@ export function registerChatCommand(program: Command, t: Messages): void {
const projectId = resolveProjectId(opts.projectId);
const agentId = resolveAgentId(opts.agentId);
- // --resume reuses an existing Session (workspace/model fixed at creation); a new
- // chat creates one on this cwd. `session` is reassigned by /clear after the
- // closures below capture it, so it stays a let.
+ // --resume reuses an existing Session (its own workspace and model); a new chat
+ // creates one on this cwd. `session` is reassigned by /clear and /switch-model
+ // after the closures below capture it, so it stays a let.
let session: SessionInfo;
let resumedMessages: OmniMessage[] | null = null;
if (opts.resume !== undefined) {
@@ -411,12 +421,14 @@ export function registerChatCommand(program: Command, t: Messages): void {
/**
* One server-driven turn: subscribe, POST via `post`, watch to idle. Returns once
* the turn (or compaction/goal) has fully settled. Wires this turn's Ctrl-C to
- * POST /abort exactly once.
+ * POST /abort exactly once. `inline` recognizes a response that already settled
+ * the request inside the POST (nothing streams for it, so there is nothing to watch);
+ * the result says whether the stream was watched.
*/
const runTurn = async (
post: () => Promise<unknown>,
- watch: { goal?: boolean } = {},
- ): Promise<void> => {
+ watch: { goal?: boolean; inline?: (response: unknown) => boolean } = {},
+ ): Promise<boolean> => {
const stream = new SessionStream(client, session.sessionId, t);
let aborted = false;
abortTurn = () => {
@@ -428,7 +440,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
};
try {
await stream.waitReady();
- await post();
+ const response = await post();
+ if (watch.inline?.(response)) return false;
await watchTask(stream, {
client,
sessionId: session.sessionId,
@@ -437,6 +450,7 @@ export function registerChatCommand(program: Command, t: Messages): void {
approvalPrompt: interactivePrompt,
...(watch.goal ? { goal: { out } } : {}),
});
+ return true;
} finally {
abortTurn = null;
stream.close();
@@ -446,6 +460,55 @@ export function registerChatCommand(program: Command, t: Messages): void {
// Whether this Session already has (or gained) history worth a resume hint.
let resumable = opts.resume !== undefined;
+ /**
+ * `/switch-model <provider> <model_id>`: POST /switch-model through runTurn. A 202
+ * streams like /compact — an ordinary compaction, rendered as any compaction is (none
+ * for a context just compacted) — and the Session is re-read once it ends. A 200 carries
+ * the Session back: it never ran, so it switched inside the request (under a new id when
+ * the server had to rebuild one that left no Trace, which the chat follows). The model
+ * line prints only when the model actually changed, since a failed compaction already
+ * said why it did not. A 409 prints one localized line per refusal code.
+ */
+ const switchModel = async (target: ModelTarget): Promise<void> => {
+ const previous = session;
+ const startedAt = Date.now();
+ let streamed: boolean;
+ let switched: SessionInfo | undefined;
+ try {
+ streamed = await runTurn(
+ () => client.request("POST", `/api/sessions/${session.sessionId}/switch-model`, target),
+ // 200 SessionResponse vs 202 TaskCreateResponse: only the former has `session`.
+ {
+ inline: (response) => {
+ switched = (response as { session?: SessionInfo } | null)?.session;
+ return switched !== undefined;
+ },
+ },
+ );
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 409) {
+ const line = switchModelRefusal(err, target, session.projectId, t);
+ if (line !== null) {
+ out.write(`${line}\n`);
+ return;
+ }
+ }
+ throw err;
+ } finally {
+ renderer.endCompact(Date.now() - startedAt);
+ }
+ if (streamed) resumable = true;
+ session = switched ?? (await getSessionInfo(client, previous.sessionId));
+ if (session.provider !== previous.provider || session.modelId !== previous.modelId) {
+ out.write(
+ `${t.switchModelDone(
+ formatModelLabel(previous.provider, previous.modelId),
+ formatModelLabel(session.provider, session.modelId),
+ )}\n`,
+ );
+ }
+ };
+
// The copy-pastable resume command for one Session: includes this run's Project /
// Agent options so it works as-is.
const resumeCommand = (sessionId: string): string =>
@@ -480,6 +543,21 @@ export function registerChatCommand(program: Command, t: Messages): void {
}
continue;
}
+ let switchTarget: ModelTarget | null = null;
+ if (text === "/switch-model" || text.startsWith("/switch-model ")) {
+ const parsed = parseSwitchModelCommand(text);
+ if (!parsed.ok) {
+ out.write(`${t.error(t.switchModelUsage())}\n`);
+ continue;
+ }
+ if (parsed.target === null) {
+ out.write(
+ `${t.switchModelCurrent(formatModelLabel(session.provider, session.modelId))}\n`,
+ );
+ continue;
+ }
+ switchTarget = parsed.target;
+ }
if (text === "/verbose") {
verbose = !verbose;
renderer.setCollapseToolOutput(!verbose);
@@ -508,6 +586,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
} finally {
renderer.endCompact(Date.now() - startedAt);
}
+ } else if (switchTarget !== null) {
+ await switchModel(switchTarget);
} else if (text === "/clear") {
// Start over with a brand-new blank Session on the same Workspace and model.
// The old Session stays on the server (resumable), so its resume command is
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 90123ef2..e4f0e753 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -904,6 +904,22 @@ export interface Messages {
thinkingSet(level: string): string;
/** Invalid `--thinking` / `/thinking` value (lists the selectable levels). */
thinkingInvalid(value: string): string;
+ /** Bare `/switch-model`: the Session's current model (a formatted label) plus the usage; a switch compacts first. */
+ switchModelCurrent(model: string): string;
+ /** `/switch-model` with anything but exactly `<provider> <model_id>`. */
+ switchModelUsage(): string;
+ /** After `/switch-model` completed: the model the Session was on and the one it is on now (formatted labels). */
+ switchModelDone(previous: string, next: string): string;
+ /** 409 `task_in_progress` / `compacting`: the Session is busy (possibly driven from another surface). */
+ switchModelBusy(): string;
+ /** 409 `same_model`: the Session already runs on the target. */
+ switchModelSame(model: string): string;
+ /** 409 `model_not_configured`: the target is not in the Project config; names the `penguin config model` commands to list and add models. */
+ switchModelNotConfigured(model: string, listCommand: string, addCommand: string): string;
+ /** 409 `model_unavailable`: the target is configured but cannot be constructed (e.g. no credential); `detail` is the server's message, verbatim (may be empty). */
+ switchModelUnavailable(model: string, detail: string): string;
+ /** 409 `compaction_not_configured`: a switch always compacts first, and this Session has no compaction. */
+ switchModelNoCompaction(): string;
/** `/verbose` toggled on: tool output renders in full from here on. */
verboseOn(): string;
/** `/verbose` toggled off: long tool output is collapsed again from here on. */
@@ -916,7 +932,7 @@ export interface Messages {
approvalDecision(decision: "allow" | "deny" | "forbidden"): string;
/** run/chat given only one of --model-id / --provider: a model reference is always an explicit pair, never a lookup. */
modelRefIncomplete(): string;
- /** --resume is mutually exclusive with --workspace/--model-id (neither can change once the Session is created). */
+ /** --resume is mutually exclusive with --workspace/--model-id/--provider (the resumed Session keeps its own); points at `/switch-model` for changing the model inside the chat. */
resumeNoOverride(): string;
/** --resume given without a session id, and the current Agent has no Session at all. */
resumeNoSession(): string;
@@ -1075,7 +1091,7 @@ const en: Messages = {
"Mark the new session as created by a Benchmark evaluation (`benchmark`); the Web App files it under the Evaluations folder",
background: "Post the task and exit immediately, printing the session id",
sessionNoOverride: () =>
- "--session reuses an existing Session: --workspace, --model-id, --provider and --source cannot be combined with it (none can change after creation).",
+ "--session reuses an existing Session: --workspace, --model-id, --provider and --source cannot be combined with it (the Session keeps its own; /switch-model inside penguin chat --resume changes its model, compacting first).",
sourceInvalid: (value) =>
`Invalid --source value "${value}". The only accepted value is benchmark.`,
timeoutWithBackground: () =>
@@ -1084,7 +1100,7 @@ const en: Messages = {
chat: {
desc: "Open the interactive REPL",
resume:
- "Resume an existing Session (defaults to the agent's most recent one); workspace and model follow the original Session",
+ "Resume an existing Session (defaults to the agent's most recent one); workspace and model follow the original Session (/switch-model changes the model inside the chat, compacting first)",
verbose:
"Show full tool output (by default long tool outputs are collapsed to their first and last lines; /verbose toggles it mid-chat)",
},
@@ -1774,7 +1790,7 @@ const en: Messages = {
header: headerEn,
chatHints: () =>
- "Type a message to start a conversation; end a line with \\; typing while a task runs steers the agent; /goal runs a goal to completion; /compact to compact the context; /clear to start a fresh session; /thinking changes the thinking level; /verbose toggles full tool output; /exit to quit; and Ctrl-C interrupts the current conversation.",
+ "Type a message to start a conversation; end a line with \\; typing while a task runs steers the agent; /goal runs a goal to completion; /compact to compact the context; /clear to start a fresh session; /thinking changes the thinking level; /switch-model <provider> <model_id> switches the model (compacting the context first); /verbose toggles full tool output; /exit to quit; and Ctrl-C interrupts the current conversation.",
confirmExit: () => "Exit penguin? [y/N] ",
taskInterrupted: () => "[current conversation interrupted]",
steerQueued: (text) => `» steering queued (delivered with the next turn): ${text}`,
@@ -1863,6 +1879,20 @@ const en: Messages = {
`[thinking] level pinned to ${level} for this Session, effective from the next request — changing it invalidates the model's cached context, so /compact first is recommended (the Agent config is unchanged)`,
thinkingInvalid: (value) =>
`Invalid thinking level "${value}". Use low, medium, high, xhigh, or max.`,
+ switchModelCurrent: (model) =>
+ `[model switch] current model: ${model} — switch with /switch-model <provider> <model_id> (the context is compacted on the current model first)`,
+ switchModelUsage: () =>
+ "Usage: /switch-model <provider> <model_id> (e.g. /switch-model deepseek deepseek-v4-pro; penguin config model list shows the configured models)",
+ switchModelDone: (previous, next) => `[model switch] model: ${previous} → ${next}`,
+ switchModelBusy: () =>
+ "[model switch] the Session is busy (a task or a compaction is running); switch once it finishes",
+ switchModelSame: (model) => `[model switch] already on ${model}; nothing to switch`,
+ switchModelNotConfigured: (model, listCommand, addCommand) =>
+ `[model switch] ${model} is not in the Project config: ${listCommand} lists the configured models, ${addCommand} adds it`,
+ switchModelUnavailable: (model, detail) =>
+ `[model switch] ${model} is configured but cannot be used${detail ? `: ${detail}` : ""}`,
+ switchModelNoCompaction: () =>
+ "[model switch] context compaction is not configured for this Session, and a model switch always compacts first",
verboseOn: () => "[verbose] on — tool output from here on shows in full",
verboseOff: () =>
"[verbose] off — long tool output from here on is collapsed (/verbose to toggle)",
@@ -1878,7 +1908,7 @@ const en: Messages = {
modelRefIncomplete: () =>
"--model-id and --provider must be given together: a model reference is always an explicit (provider, model_id) pair. Omit both to use the Project default model.",
resumeNoOverride: () =>
- "--resume does not accept --workspace, --model-id or --provider: they follow the original Session and cannot change.",
+ "--resume does not accept --workspace, --model-id or --provider: the resumed Session keeps its own. To change its model, run /switch-model <provider> <model_id> inside the chat (it compacts the context first).",
resumeNoSession: () => "No session to resume: this agent has no recorded sessions yet.",
resumedBanner: (sessionId, messageCount) =>
`[resumed] ${sessionId} · ${messageCount} message${messageCount === 1 ? "" : "s"} in the current context`,
@@ -2013,14 +2043,14 @@ const zh: Messages = {
source: "把新建会话标记为 Benchmark 评估创建(`benchmark`);Web App 将其归入「评估任务」子夹",
background: "提交任务后立即退出,打印 session id",
sessionNoOverride: () =>
- "--session 复用既有 Session:不能与 --workspace、--model-id、--provider、--source 同时使用(Workspace、模型与来源创建后不可更换)。",
+ "--session 复用既有 Session:不能与 --workspace、--model-id、--provider、--source 同时使用(均沿用该 Session;如需换模型,在 penguin chat --resume 内用 /switch-model,会先压缩上下文)。",
sourceInvalid: (value) => `无效的 --source 取值 "${value}"。唯一可用取值为 benchmark。`,
timeoutWithBackground: () => "--timeout 限定等待,而 --background 不等待:二者去其一。",
},
chat: {
desc: "打开交互式 REPL",
resume:
- "恢复既有 Session 继续对话(缺省恢复当前 Agent 最近一次);Workspace 与模型沿用原 Session",
+ "恢复既有 Session 继续对话(缺省恢复当前 Agent 最近一次);Workspace 与模型沿用原 Session(会话内可用 /switch-model 切换模型,会先压缩上下文)",
verbose: "显示完整工具输出(缺省折叠过长的工具输出、只保留首尾数行;/verbose 可随时切换)",
},
ls: {
@@ -2663,7 +2693,7 @@ const zh: Messages = {
header: headerZh,
chatHints: () =>
- "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/thinking 调整思考等级;/verbose 切换完整工具输出;/exit 退出;Ctrl-C 中断对话。",
+ "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/thinking 调整思考等级;/switch-model <provider> <model_id> 切换模型(先压缩上下文);/verbose 切换完整工具输出;/exit 退出;Ctrl-C 中断对话。",
confirmExit: () => "确认退出 penguin?[y/N] ",
taskInterrupted: () => "[已中断当前对话]",
steerQueued: (text) => `» 插话已排队(随下一轮送达):${text}`,
@@ -2717,7 +2747,8 @@ const zh: Messages = {
: status === "aborted"
? "[压缩] 已中断,保留当前上下文"
: `[压缩] 失败${errorMessage !== undefined ? `(${errorMessage})` : ""},保留当前上下文${
- // retryable = 本次放弃、下次触发自动重试;fatal = 需先修复模型配置或凭据。旧 Trace 两者都拼作 "failed"。
+ // retryable = abandoned this time, retried at the next trigger; fatal = a config
+ // or credential change has to come first. Legacy Traces spell both "failed".
status === "retryable"
? ",下次触发时重试"
: status === "fatal"
@@ -2747,6 +2778,19 @@ const zh: Messages = {
thinkingSet: (level) =>
`[思考] 本 Session 的等级已钉为 ${level},下一轮请求起生效——更换思考等级会使模型缓存失效,建议先 /compact 压缩上下文(不改动 Agent 配置)`,
thinkingInvalid: (value) => `无效的思考等级 "${value}"。请使用 low、medium、high、xhigh 或 max。`,
+ switchModelCurrent: (model) =>
+ `[切换模型] 当前模型:${model}——用 /switch-model <provider> <model_id> 切换(会先用当前模型压缩上下文)`,
+ switchModelUsage: () =>
+ "用法:/switch-model <provider> <model_id>(例如 /switch-model deepseek deepseek-v4-pro;penguin config model list 列出已配置的模型)",
+ switchModelDone: (previous, next) => `[切换模型] 模型:${previous} → ${next}`,
+ switchModelBusy: () => "[切换模型] 会话正忙(任务或压缩进行中),请待其结束后再切换",
+ switchModelSame: (model) => `[切换模型] 已在使用 ${model},无需切换`,
+ switchModelNotConfigured: (model, listCommand, addCommand) =>
+ `[切换模型] Project 配置中没有 ${model}:${listCommand} 列出已配置的模型,${addCommand} 可添加它`,
+ switchModelUnavailable: (model, detail) =>
+ `[切换模型] ${model} 已配置但无法使用${detail ? `:${detail}` : ""}`,
+ switchModelNoCompaction: () =>
+ "[切换模型] 本 Session 未配置上下文压缩,而切换模型必须先压缩,因此无法切换",
verboseOn: () => "[详细输出] 已开启——后续工具输出完整显示(/verbose 切换)",
verboseOff: () => "[详细输出] 已关闭——后续过长的工具输出将折叠(/verbose 切换)",
toolOutputElided: (hidden) => `……(另有 ${hidden} 行,/verbose 显示完整输出)`,
@@ -2757,7 +2801,7 @@ const zh: Messages = {
modelRefIncomplete: () =>
"--model-id 与 --provider 必须成对给出:模型引用始终是显式的 (provider, model_id) 组合。两者都不给则使用 Project 默认模型。",
resumeNoOverride: () =>
- "--resume 不接受 --workspace、--model-id 与 --provider:均沿用原 Session,创建后不可更换。",
+ "--resume 不接受 --workspace、--model-id 与 --provider:均沿用原 Session。如需换模型,请在会话内使用 /switch-model <provider> <model_id>(会先压缩上下文)。",
resumeNoSession: () => "没有可恢复的 Session:当前 Agent 还没有任何会话记录。",
resumedBanner: (sessionId, messageCount) =>
`[已恢复] ${sessionId} · 当前上下文共 ${messageCount} 条消息`,
diff --git a/packages/cli/src/switch-model-command.ts b/packages/cli/src/switch-model-command.ts
new file mode 100644
index 00000000..ca2fdc24
--- /dev/null
+++ b/packages/cli/src/switch-model-command.ts
@@ -0,0 +1,76 @@
+/**
+ * `/switch-model` — the chat REPL's in-session model switch (pure logic, unit-tested).
+ *
+ * Syntax: `/switch-model <provider> <model_id>`. The target is the explicit
+ * `(provider, model_id)` pair, never inferred — the same rule `--provider` / `--model-id`
+ * follow. Both tokens are taken verbatim (case preserved) and split on whitespace: an
+ * upstream model id may carry slashes or colons (`anthropic/claude-opus-5` under
+ * `openrouter`, `accounts/fireworks/models/…` under `fireworks`) but never whitespace, so a
+ * third token is a usage error rather than part of the id. Bare `/switch-model` shows the
+ * current model.
+ *
+ * The switch itself is `POST /api/sessions/:id/switch-model`: the server compacts on the
+ * current model first (always summarizing), then opens the next context on the target; a
+ * Session that never ran switches inline.
+ */
+import { DEFAULT_PROJECT_ID } from "@prismshadow/penguin-core";
+import type { Messages } from "./i18n.js";
+
+/** A model reference as the server API spells it. */
+export interface ModelTarget {
+ provider: string;
+ modelId: string;
+}
+
+export type SwitchModelCommandResult =
+ /** `target` null = bare `/switch-model`: show the current model. */
+ { ok: true; target: ModelTarget | null } | { ok: false };
+
+/** Parses a full `/switch-model…` chat line (the caller has already matched the prefix). */
+export function parseSwitchModelCommand(line: string): SwitchModelCommandResult {
+ const rest = line.trim().slice("/switch-model".length).trim();
+ if (rest === "") return { ok: true, target: null };
+ const tokens = rest.split(/\s+/);
+ if (tokens.length !== 2) return { ok: false };
+ return { ok: true, target: { provider: tokens[0]!, modelId: tokens[1]! } };
+}
+
+/** How the REPL names a model in its lines: the upstream id, then its provider group. */
+export function formatModelLabel(provider: string, modelId: string): string {
+ return `${modelId} (${provider})`;
+}
+
+/**
+ * The one line a 409 refusal of the switch prints, localized by its code; null for a code
+ * this client does not know (the caller prints the server's own message instead).
+ * `projectId` is the Session's Project: the `penguin config model` commands named for an
+ * unconfigured target carry `--project-id` when it is not the default one.
+ */
+export function switchModelRefusal(
+ err: { code: string; detail: string },
+ target: ModelTarget,
+ projectId: string,
+ t: Messages,
+): string | null {
+ const label = formatModelLabel(target.provider, target.modelId);
+ const projectFlag = projectId === DEFAULT_PROJECT_ID ? "" : ` --project-id ${projectId}`;
+ switch (err.code) {
+ case "task_in_progress":
+ case "compacting":
+ return t.switchModelBusy();
+ case "same_model":
+ return t.switchModelSame(label);
+ case "model_not_configured":
+ return t.switchModelNotConfigured(
+ label,
+ `penguin config model list${projectFlag}`,
+ `penguin config model add --provider ${target.provider} --model-id ${target.modelId}${projectFlag}`,
+ );
+ case "model_unavailable":
+ return t.switchModelUnavailable(label, err.detail);
+ case "compaction_not_configured":
+ return t.switchModelNoCompaction();
+ default:
+ return null;
+ }
+}
diff --git a/packages/cli/test/chat-switch-model.test.ts b/packages/cli/test/chat-switch-model.test.ts
new file mode 100644
index 00000000..71f07254
--- /dev/null
+++ b/packages/cli/test/chat-switch-model.test.ts
@@ -0,0 +1,258 @@
+/**
+ * chat `/switch-model`: switches the Session's model in place over the server API. Drives
+ * the real REPL over a fake stdin against the in-process fake server (same harness as
+ * chat-clear.test.ts and chat-thinking.test.ts). The fake answers the contract's three
+ * shapes — 202 streaming an ordinary manual compaction pair and then the new context's
+ * `session_meta`, 200 carrying the Session back for one that never ran, and 409 with a code
+ * per refusal. The REPL renders the compaction like any other and learns the new model from
+ * the Session it re-reads.
+ */
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { compactionBegin, compactionEnd, sessionMeta } from "@prismshadow/penguin-core";
+import { registerChatCommand } from "../src/commands/chat.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+import type { FakeSessionState } from "./fake-server.js";
+
+const t = getMessages("en");
+
+let server: FakeServer;
+let uninstall: () => void;
+
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+});
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+});
+
+function stripAnsi(s: string): string {
+ // eslint-disable-next-line no-control-regex
+ return s.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
+}
+
+/** Runs `penguin chat <argv>` end to end over a PassThrough stdin, feeding each line at the prompt (same driver as chat-clear.test.ts); returns stdout without colors. */
+async function driveChat(lines: string[], argv: string[] = []): Promise<string> {
+ const stdin = new PassThrough();
+ const realStdin = process.stdin;
+ Object.defineProperty(process, "stdin", { value: stdin, configurable: true });
+ const chunks: string[] = [];
+ let promptCount = 0;
+ const waiters: Array<() => void> = [];
+ const outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ const text = String(chunk);
+ chunks.push(text);
+ if (text === "> ") promptCount++;
+ for (const wake of waiters.splice(0)) wake();
+ return true;
+ });
+ const waitForPrompt = (n: number): Promise<void> =>
+ new Promise((resolve) => {
+ const check = (): void => {
+ if (promptCount >= n) resolve();
+ else waiters.push(check);
+ };
+ check();
+ });
+ try {
+ const program = new Command();
+ program.exitOverride();
+ registerChatCommand(program, t);
+ const done = program.parseAsync(["node", "penguin", "chat", ...argv]);
+ for (let i = 0; i < lines.length; i++) {
+ await Promise.race([waitForPrompt(i + 1), done]);
+ stdin.write(`${lines[i]}\n`);
+ }
+ await done;
+ return stripAnsi(chunks.join(""));
+ } finally {
+ outSpy.mockRestore();
+ Object.defineProperty(process, "stdin", { value: realStdin, configurable: true });
+ }
+}
+
+const CURRENT = "model-default (prov-default)";
+const TARGET = "anthropic/claude-opus-5 (openrouter)";
+const SWITCH_LINE = "/switch-model openrouter anthropic/claude-opus-5";
+
+/** The requests one session received, as `METHOD /path` strings, in order. */
+function requestLog(sessionId: string): string[] {
+ return server.requests
+ .filter((r) => r.path.startsWith(`/api/sessions/${sessionId}`))
+ .map((r) => `${r.method} ${r.path.slice(`/api/sessions/${sessionId}`.length) || "/"}`);
+}
+
+/**
+ * A 202 switch whose compaction ends with `status`: a plain manual pair, then — on completed
+ * only — the new context's main-session `session_meta` naming the target, as core streams it.
+ * The fake moves the Session's model only on completed.
+ */
+function streamedSwitch(status: "completed" | "fatal" | "aborted", errorMessage?: string) {
+ return (session: FakeSessionState, target: { provider: string; modelId: string }) => {
+ const completed = status === "completed";
+ return {
+ completed,
+ messages: [
+ compactionBegin({ reason: "manual", mode: "summarize", context: 5000, turns: 2 }),
+ compactionEnd({
+ reason: "manual",
+ mode: "summarize",
+ status,
+ ...(errorMessage !== undefined ? { errorMessage } : {}),
+ }),
+ ...(completed
+ ? [
+ sessionMeta({
+ session_id: session.sessionId,
+ provider: target.provider,
+ model_id: target.modelId,
+ model_context_window: "unknown",
+ system_prompt: "",
+ agent_state: "/tmp/agents/default_agent/agent_state",
+ workspace: session.workspace,
+ }),
+ ]
+ : []),
+ ],
+ };
+ };
+}
+
+describe("chat /switch-model: parsing and display (no request)", () => {
+ it("bare /switch-model shows the current model and usage; bad arity prints the usage error", async () => {
+ const out = await driveChat(["/switch-model", "/switch-model openrouter", "/exit"]);
+ expect(out).toContain(t.switchModelCurrent(CURRENT));
+ expect(out).toContain(t.error(t.switchModelUsage()));
+ expect(server.requests.some((r) => r.path.endsWith("/switch-model"))).toBe(false);
+ });
+
+ it("the hints line teaches /switch-model", async () => {
+ const out = await driveChat(["/exit"]);
+ expect(out).toContain("/switch-model <provider> <model_id>");
+ });
+});
+
+describe("chat /switch-model: 202 streams the switch", () => {
+ it("completed: renders the switch, refreshes the Session and runs later turns on the new model", async () => {
+ server.switchModel = streamedSwitch("completed");
+ const out = await driveChat(["hello", SWITCH_LINE, "/switch-model", "/clear", "/exit"]);
+
+ const [first, replacement] = [...server.sessions.values()];
+ // The POST carried the pair as the API spells it.
+ const post = server.requests.find((r) => r.path.endsWith("/switch-model"));
+ expect(post?.method).toBe("POST");
+ expect(post?.body).toEqual({ provider: "openrouter", modelId: "anthropic/claude-opus-5" });
+ // The compaction renders as any manual compaction does, then the model line — from the
+ // Session re-read after the stream, not from anything the stream says.
+ const start = out.indexOf(t.compactionStart("summarize", "manual"));
+ const stop = out.indexOf(t.compactionStop("summarize", "completed"));
+ const done = out.indexOf(t.switchModelDone(CURRENT, TARGET));
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(stop).toBeGreaterThan(start);
+ expect(done).toBeGreaterThan(stop);
+ // The Session was re-read after the switch, and the local copy follows it: bare
+ // /switch-model shows the new model and /clear carries it to the replacement Session.
+ const log = requestLog(first!.sessionId);
+ expect(log.slice(log.indexOf("POST /switch-model"))).toContain("GET /");
+ expect(out).toContain(t.switchModelCurrent(TARGET));
+ expect(replacement!.provider).toBe("openrouter");
+ expect(replacement!.modelId).toBe("anthropic/claude-opus-5");
+ });
+
+ it("a failed switch prints the plain failed compaction line and no model line; the Session stays on its model", async () => {
+ server.switchModel = streamedSwitch("fatal", "the summary does not fit");
+ const out = await driveChat(["hello", SWITCH_LINE, "/switch-model", "/exit"]);
+ expect(out).toContain(
+ t.compactionStop("summarize", "fatal", undefined, "the summary does not fit"),
+ );
+ expect(out).not.toContain(t.switchModelDone(CURRENT, TARGET));
+ expect(out).toContain(t.switchModelCurrent(CURRENT));
+ });
+});
+
+describe("chat /switch-model: 200 switches a Session that never ran inline", () => {
+ it("prints the model line without watching a stream; the Session is the one the response carries", async () => {
+ server.switchModel = "inline";
+ const out = await driveChat([SWITCH_LINE, "/switch-model", "/exit"]);
+ expect(out).toContain(t.switchModelDone(CURRENT, TARGET));
+ expect(out).not.toContain("[compaction]");
+ expect(out).toContain(t.switchModelCurrent(TARGET));
+ const session = [...server.sessions.values()][0]!;
+ const log = requestLog(session.sessionId);
+ // The response is the refresh: nothing is read again.
+ expect(log.slice(log.indexOf("POST /switch-model"))).not.toContain("GET /");
+ // Nothing ran, so there is nothing to resume.
+ expect(out).not.toContain("--resume");
+ });
+
+ it("follows the id the response carries: a Session the server rebuilt answers to a new one from here on", async () => {
+ server.switchModel = "inline-rebuilt";
+ const out = await driveChat([SWITCH_LINE, "hello", "/exit"]);
+ expect(out).toContain(t.switchModelDone(CURRENT, TARGET));
+ const [rebuilt] = [...server.sessions.values()];
+ // The next turn went to the id that answers now, on the model switched to.
+ expect(requestLog(rebuilt!.sessionId)).toContain("POST /tasks");
+ expect(rebuilt!.modelId).toBe("anthropic/claude-opus-5");
+ });
+});
+
+describe("chat /switch-model: 409 refusals print one localized line each", () => {
+ const cases: Array<[string, string]> = [
+ ["task_in_progress", t.switchModelBusy()],
+ ["compacting", t.switchModelBusy()],
+ ["same_model", t.switchModelSame(TARGET)],
+ [
+ "model_not_configured",
+ t.switchModelNotConfigured(
+ TARGET,
+ "penguin config model list",
+ "penguin config model add --provider openrouter --model-id anthropic/claude-opus-5",
+ ),
+ ],
+ ["model_unavailable", t.switchModelUnavailable(TARGET, "Refused: model_unavailable.")],
+ ["compaction_not_configured", t.switchModelNoCompaction()],
+ ];
+ for (const [code, line] of cases) {
+ it(code, async () => {
+ server.switchModel = { refuse: code };
+ const out = await driveChat([SWITCH_LINE, "/switch-model", "/exit"]);
+ expect(out).toContain(`${line}\n`);
+ expect(out).not.toContain(t.switchModelDone(CURRENT, TARGET));
+ // Still on the original model; no refresh was needed.
+ expect(out).toContain(t.switchModelCurrent(CURRENT));
+ const session = [...server.sessions.values()][0]!;
+ expect(requestLog(session.sessionId)).not.toContain("GET /");
+ });
+ }
+
+ it("an unknown 409 code prints the server's error", async () => {
+ server.switchModel = { refuse: "something_new" };
+ const out = await driveChat([SWITCH_LINE, "/exit"]);
+ expect(out).toContain(
+ t.error(t.client.httpError(409, "something_new", "Refused: something_new.")),
+ );
+ });
+});
+
+describe("chat --resume with model flags", () => {
+ it("is still rejected, pointing at /switch-model inside the chat", async () => {
+ const existing = server.addSession();
+ const prevExitCode = process.exitCode;
+ try {
+ const out = await driveChat(
+ [],
+ ["--resume", existing.sessionId, "--provider", "openrouter", "--model-id", "x"],
+ );
+ expect(out).toContain(t.error(t.resumeNoOverride()));
+ expect(t.resumeNoOverride()).toContain("/switch-model");
+ expect(process.exitCode).toBe(1);
+ expect(server.requests).toHaveLength(0);
+ } finally {
+ process.exitCode = prevExitCode;
+ }
+ });
+});
diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.ts
index e6be1a63..03ed3f55 100644
--- a/packages/cli/test/fake-server.ts
+++ b/packages/cli/test/fake-server.ts
@@ -1,9 +1,9 @@
/**
* In-process fake PenguinHarness server for CLI tests: stubs `globalThis.fetch` with a
* handler covering exactly the endpoints the server-backed commands touch (the current
- * user, session create/get/patch, tasks/steer/compact/abort, SSE stream, messages, agents,
- * projects, usage, schedules, organizations and their channels, and — through the
- * `builtinBrowser` handler a test sets — the built-in browser). Connection resolution is pinned via PENGUIN_API_URL
+ * user, session create/get/patch, tasks/steer/compact/switch-model/abort, SSE stream,
+ * messages, agents, projects, usage, schedules, organizations and their channels, and — through
+ * the `builtinBrowser` handler a test sets — the built-in browser). Connection resolution is pinned via PENGUIN_API_URL
* (a loopback URL, so no token gate) and PENGUIN_HOME points at a scratch directory so
* nothing of the developer's real data root is read.
*
@@ -194,6 +194,22 @@ export class FakeServer {
history: unknown[] = [];
/** POST /compact behavior: "reject" -> 409 nothing_to_compact; a function emits its messages like a task. */
compact: "reject" | ((session: FakeSessionState) => unknown[]) = "reject";
+ /**
+ * POST /switch-model behavior. "inline" (default): the Session never ran, so it switches
+ * inside the request and answers 200 with the updated SessionResponse; "inline-rebuilt" does
+ * the same for a Session the server had to rebuild first, which comes back under a new id.
+ * `{ refuse }`: 409 with that code. A function streams like /compact (202): its `messages`
+ * are emitted between running and idle, and the Session's model changes only when
+ * `completed`.
+ */
+ switchModel:
+ | "inline"
+ | "inline-rebuilt"
+ | { refuse: string }
+ | ((
+ session: FakeSessionState,
+ target: { provider: string; modelId: string },
+ ) => { messages: unknown[]; completed: boolean }) = "inline";
/** POST /steer behavior: accept (202) or reject (409 not_running). */
steerMode: "accept" | "reject" = "accept";
/** When true, a task POST emits `running` + the script's messages but never `idle` — the turn hangs (soft-yield timeout tests). */
@@ -1806,6 +1822,29 @@ export class FakeServer {
this.runTurn(session, this.compact(session));
return this.json({ sessionId: session.sessionId }, 202);
}
+ if (rest === "/switch-model" && method === "POST") {
+ const target = { provider: String(body?.provider), modelId: String(body?.modelId) };
+ if (typeof this.switchModel === "object") {
+ return this.error(409, this.switchModel.refuse, `Refused: ${this.switchModel.refuse}.`);
+ }
+ if (this.switchModel === "inline" || this.switchModel === "inline-rebuilt") {
+ if (this.switchModel === "inline-rebuilt") {
+ this.sessions.delete(session.sessionId);
+ session.sessionId = this.mintSessionId();
+ this.sessions.set(session.sessionId, session);
+ }
+ session.provider = target.provider;
+ session.modelId = target.modelId;
+ return this.json({ session: this.sessionInfo(session) });
+ }
+ const { messages, completed } = this.switchModel(session, target);
+ if (completed) {
+ session.provider = target.provider;
+ session.modelId = target.modelId;
+ }
+ this.runTurn(session, messages);
+ return this.json({ sessionId: session.sessionId }, 202);
+ }
if (rest === "/abort" && method === "POST") {
session.aborts += 1;
return new Response(null, { status: 202 });
diff --git a/packages/cli/test/i18n.test.ts b/packages/cli/test/i18n.test.ts
index cdd4cc18..d5e08554 100644
--- a/packages/cli/test/i18n.test.ts
+++ b/packages/cli/test/i18n.test.ts
@@ -65,6 +65,34 @@ describe("getMessages", () => {
expect(getMessages("zh").chatHints()).toContain("/verbose");
});
+ it("the in-session model switch reads the same in both languages", () => {
+ const en = getMessages("en");
+ const zh = getMessages("zh");
+ for (const m of [en, zh]) {
+ // Every surface that teaches the command names it with its argument pair and says a
+ // switch compacts first.
+ for (const text of [m.chatHints(), m.switchModelCurrent("a (p)"), m.resumeNoOverride()]) {
+ expect(text).toContain("/switch-model <provider> <model_id>");
+ }
+ expect(m.chat.resume).toContain("/switch-model");
+ expect(m.switchModelUsage()).toContain("/switch-model <provider> <model_id>");
+ // Interpolations carry their arguments.
+ const done = m.switchModelDone("a (p)", "b (q)");
+ expect(done).toContain("a (p) → b (q)");
+ expect(m.switchModelSame("b (q)")).toContain("b (q)");
+ const notConfigured = m.switchModelNotConfigured("b (q)", "LIST-CMD", "ADD-CMD");
+ for (const part of ["b (q)", "LIST-CMD", "ADD-CMD"]) expect(notConfigured).toContain(part);
+ expect(m.switchModelUnavailable("b (q)", "no key")).toContain("no key");
+ expect(m.switchModelUnavailable("b (q)", "")).not.toMatch(/[::]$/);
+ expect(m.switchModelBusy().length).toBeGreaterThan(0);
+ expect(m.switchModelNoCompaction().length).toBeGreaterThan(0);
+ }
+ // Two languages, not one copied twice.
+ expect(zh.switchModelDone("a", "b")).not.toBe(en.switchModelDone("a", "b"));
+ expect(zh.switchModelBusy()).not.toBe(en.switchModelBusy());
+ expect(zh.switchModelNoCompaction()).not.toBe(en.switchModelNoCompaction());
+ });
+
it("server-backed command families exist in both languages (spot checks)", () => {
for (const lang of ["en", "zh"] as const) {
const m = getMessages(lang);
diff --git a/packages/cli/test/switch-model-command.test.ts b/packages/cli/test/switch-model-command.test.ts
new file mode 100644
index 00000000..e2f4aeb7
--- /dev/null
+++ b/packages/cli/test/switch-model-command.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatModelLabel,
+ parseSwitchModelCommand,
+ switchModelRefusal,
+} from "../src/switch-model-command.js";
+import { getMessages } from "../src/i18n.js";
+
+describe("parseSwitchModelCommand", () => {
+ it("bare /switch-model asks to show the current model", () => {
+ expect(parseSwitchModelCommand("/switch-model")).toEqual({ ok: true, target: null });
+ expect(parseSwitchModelCommand(" /switch-model ")).toEqual({ ok: true, target: null });
+ });
+
+ it("/switch-model <provider> <model_id> names the target pair, verbatim", () => {
+ expect(parseSwitchModelCommand("/switch-model deepseek deepseek-v4-pro")).toEqual({
+ ok: true,
+ target: { provider: "deepseek", modelId: "deepseek-v4-pro" },
+ });
+ // Case is kept: a model id is an upstream identifier, not a keyword.
+ expect(parseSwitchModelCommand("/switch-model custom Qwen3-Coder ")).toEqual({
+ ok: true,
+ target: { provider: "custom", modelId: "Qwen3-Coder" },
+ });
+ });
+
+ it("a model id may carry slashes and colons (gateway and local ids)", () => {
+ expect(parseSwitchModelCommand("/switch-model openrouter anthropic/claude-opus-5")).toEqual({
+ ok: true,
+ target: { provider: "openrouter", modelId: "anthropic/claude-opus-5" },
+ });
+ expect(
+ parseSwitchModelCommand("/switch-model fireworks accounts/fireworks/models/deepseek-v4-pro"),
+ ).toEqual({
+ ok: true,
+ target: { provider: "fireworks", modelId: "accounts/fireworks/models/deepseek-v4-pro" },
+ });
+ expect(parseSwitchModelCommand("/switch-model vllm qwen3:8b")).toEqual({
+ ok: true,
+ target: { provider: "vllm", modelId: "qwen3:8b" },
+ });
+ });
+
+ it("anything but exactly two tokens is a usage error (a model id never contains whitespace)", () => {
+ expect(parseSwitchModelCommand("/switch-model deepseek-v4-pro")).toEqual({ ok: false });
+ expect(parseSwitchModelCommand("/switch-model openrouter claude opus 5")).toEqual({
+ ok: false,
+ });
+ });
+});
+
+describe("formatModelLabel", () => {
+ it("names the upstream id, then its provider group", () => {
+ expect(formatModelLabel("openrouter", "anthropic/claude-opus-5")).toBe(
+ "anthropic/claude-opus-5 (openrouter)",
+ );
+ });
+});
+
+describe("switchModelRefusal (409 codes -> one localized line)", () => {
+ const t = getMessages("en");
+ const target = { provider: "openrouter", modelId: "anthropic/claude-opus-5" };
+ const label = "anthropic/claude-opus-5 (openrouter)";
+ const refuse = (code: string, detail = "", projectId = "default_project"): string | null =>
+ switchModelRefusal({ code, detail }, target, projectId, t);
+
+ it("both busy codes read as busy", () => {
+ expect(refuse("task_in_progress")).toBe(t.switchModelBusy());
+ expect(refuse("compacting")).toBe(t.switchModelBusy());
+ });
+
+ it("same_model and compaction_not_configured", () => {
+ expect(refuse("same_model")).toBe(t.switchModelSame(label));
+ expect(refuse("compaction_not_configured")).toBe(t.switchModelNoCompaction());
+ });
+
+ it("model_not_configured names the config commands, with --project-id only off the default Project", () => {
+ expect(refuse("model_not_configured")).toBe(
+ t.switchModelNotConfigured(
+ label,
+ "penguin config model list",
+ "penguin config model add --provider openrouter --model-id anthropic/claude-opus-5",
+ ),
+ );
+ expect(refuse("model_not_configured", "", "proj_x")).toBe(
+ t.switchModelNotConfigured(
+ label,
+ "penguin config model list --project-id proj_x",
+ "penguin config model add --provider openrouter --model-id anthropic/claude-opus-5 --project-id proj_x",
+ ),
+ );
+ });
+
+ it("model_unavailable carries the server's detail", () => {
+ const line = refuse("model_unavailable", "OPENROUTER_API_KEY is not set");
+ expect(line).toBe(t.switchModelUnavailable(label, "OPENROUTER_API_KEY is not set"));
+ expect(line).toContain("OPENROUTER_API_KEY is not set");
+ });
+
+ it("an unknown code is left to the caller", () => {
+ expect(refuse("not_found")).toBeNull();
+ });
+});
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index e539ff57..d5aac024 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -9,8 +9,11 @@
* A Session runs on **model contexts**, each assembled from the Agent State as it is on disk
* the moment the context opens — Session creation, the context a completed compaction opens,
* a resume that finds its context closed — and fixed until the context closes (see
- * `assembleContext`). The Agent object's own `state` is the load-time snapshot, used for
- * identity and initialization; no Session runs on it.
+ * `assembleContext`). The model is a fact of the context too: every rotation keeps the
+ * closing context's model except the one a user's in-session switch drives, which opens the
+ * next context on the model they picked (see `Session.switchModel`). The Agent object's own
+ * `state` is the load-time snapshot, used for identity and initialization; no Session runs on
+ * it.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -33,6 +36,7 @@ import {
resolveSessionMemory,
resolveModelCredential,
resolveModelRef,
+ sameModelRef,
sessionScratchpadDir,
systemConfigPath,
tracesDir,
@@ -58,12 +62,17 @@ import {
readTraceTolerant,
resumeTrace,
} from "./trace/index.js";
-import { Session } from "./session.js";
+import { ModelSwitchRefusedError, Session } from "./session.js";
import { scriptPreToolUseHook, scriptStopHook, scriptUserPromptHook } from "./hooks/script-hook.js";
import type { ScriptHookOptions } from "./hooks/script-hook.js";
import type { HookSubagentRequest, SessionHooks } from "./hooks/stop-hook.js";
import { predatesEveryPromptHooks, userPromptTrigger } from "./plugins/index.js";
-import type { SessionConfig, SessionOpenedContext } from "./session.js";
+import type {
+ ModelSwitchSupport,
+ SessionConfig,
+ SessionOpenContextOptions,
+ SessionOpenedContext,
+} from "./session.js";
import {
createTempWorkspace,
formatSessionId,
@@ -253,16 +262,22 @@ export interface ResumeSessionOptions {
/**
* The facts fixed for a Session's lifetime — every model context of the Session is opened
- * against them. Everything else a context runs with comes from the Agent State as it is on
- * disk when the context opens (see `Agent.assembleContext`).
+ * against them. Everything else a context runs with — the model included — comes from the
+ * Agent State and the Project config as they are on disk when the context opens (see
+ * `Agent.assembleContext`).
*/
interface SessionSpec {
sessionId: string;
workspaceDir: string;
- /** The Session's model entry as resolved from the Project config at creation (or recorded at resume): reference, credentials, window and per-model annotations. */
- modelEntry: ModelEntry;
- apiKey: string | undefined;
- baseUrl: string | undefined;
+ /** The model the Session was created on (or resumed on). The model a context runs on is the context's own fact (see AssembledContext.modelEntry); this one only says which entry the credentials below were given for. */
+ creationRef: ModelRef;
+ /**
+ * Explicit credentials the SDK caller gave (CreateSessionOptions / ResumeSessionOptions
+ * `apiKey` / `baseUrl`). They were given for `creationRef` and apply to that entry alone: a
+ * context an in-session switch opens on another model runs on that entry's own configured
+ * credentials (a key handed in for one vendor must never be sent to another).
+ */
+ credentialOverride: { apiKey: string | undefined; baseUrl: string | undefined };
/**
* The Session's thinking-level pin, the tri-state of {@link CreateSessionOptions.thinkingLevel}:
* a value pins every context opened from now on; `null` runs them without a level;
@@ -297,9 +312,13 @@ interface SessionRuntime {
* with it, then the same opening procedure as `bootstrap` — and the session_meta recording
* the context alongside its engine settings, with the hooks the context runs with.
*/
- openNextContext: (opts: OpenContextOptions) => Promise<SessionOpenedContext>;
+ openNextContext: (opts: SessionOpenContextOptions) => Promise<SessionOpenedContext>;
/** The running context's command policy — follows the rotation (see SessionConfig.commandPolicy). */
commandPolicy: () => CommandPolicyConfig | undefined;
+ /** The running context's model window — follows the rotation, so the live compaction reader caps the threshold against the model that is running (see `compactionReader`). */
+ contextWindow: () => number | undefined;
+ /** The composition layer's half of an in-session model switch (see SessionConfig.modelSwitch). */
+ modelSwitch: ModelSwitchSupport;
createBareLLM: () => GenerativeModel;
/** The child-session runner the run_subagent tool uses; sessionHooks' subagent spawner shares it. */
@@ -311,6 +330,8 @@ interface SessionRuntime {
* moment the context opened; immutable for the context's lifetime.
*/
interface AssembledContext {
+ /** The model this context runs on: its entry as resolved from the Project config when the context opened — reference, credentials, window and per-model annotations. */
+ modelEntry: ModelEntry;
systemPrompt: string;
/** The vault's values, for the Environment's command subprocesses; only the key names enter the prompt. */
vault: Record<string, string>;
@@ -332,7 +353,7 @@ interface AssembledContext {
* anyway.
*/
hookPackages: InstalledHook[];
- /** The session_meta describing this context: the prompt it runs with, and the Session-fixed facts. */
+ /** The session_meta describing this context: the prompt and the model it runs with, and the Session-fixed facts. */
meta: SessionMetaPayload;
}
@@ -384,6 +405,11 @@ function entryCredential(
});
}
+/** The message for a model reference that names no entry in the Project config. */
+function modelNotConfigured(ref: ModelRef): string {
+ return `Model is not in the Project config: ${formatModelRef(ref)}. Use \`penguin config model list\` to see the configured models, or \`penguin config model add\` to add one.`;
+}
+
/**
* Output cap for meta requests (title generation / vision describing): these carry their own
* small hardcoded budget, tightened further by the entry's per-model `max_tokens` when that is
@@ -424,7 +450,8 @@ export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent>
export class Agent {
constructor(
readonly state: AgentState,
- readonly projectConfig: ProjectConfig,
+ /** The Project config as this Agent last read it from disk (see `projectConfig`). */
+ private config: ProjectConfig,
/** See {@link CreateAgentOptions.proxyEnv}; forwarded into every Session's Environment. */
private readonly proxyEnv?: () => ProxyEnvPolicy | null,
/** See {@link CreateAgentOptions.controlEnv}; evaluated per Session with that Session's coordinates. */
@@ -437,6 +464,15 @@ export class Agent {
private readonly assembly?: AgentAssembly,
) {}
+ /**
+ * The Project config as this Agent last read it from disk: when it was created, and again
+ * whenever a model switch resolved its target (see `modelEntryOnDisk`). Session creation
+ * and resumption resolve their model against it.
+ */
+ get projectConfig(): ProjectConfig {
+ return this.config;
+ }
+
/**
* A Session's default thinking level when no explicit per-session level is given — the
* resolution chain (the single rule, keep both sites on it): the Agent's explicit
@@ -471,8 +507,10 @@ export class Agent {
* opens (buildRuntime's openNextContext) and a resume that finds its context closed — so an
* edit made during one context, by the user or by the model working on its own
* configuration, lands in the next context and never in the one that is running. What
- * stays fixed is the Session itself (`spec`): id, Workspace, model entry, origin, depth and
- * the thinking-level pin.
+ * stays fixed is the Session itself (`spec`): id, Workspace, origin, depth and the
+ * thinking-level pin. The model is the caller's to name: `modelEntry` is the entry the
+ * context runs on — the closing context's for an ordinary rotation, the one the user picked
+ * for a switch (see `modelEntryOnDisk`).
*
* The vault's values go to the Environment's command subprocesses and only its **key
* names** enter the prompt (so the model knows which API keys are available); Skills only
@@ -486,6 +524,7 @@ export class Agent {
*/
private async assembleContext(
spec: SessionSpec,
+ modelEntry: ModelEntry,
opts: { systemPrompt?: string } = {},
): Promise<AssembledContext> {
const { root, projectId, agentId } = this.state;
@@ -524,8 +563,8 @@ export class Agent {
sessionEnvironment(spec.workspaceDir, spec.sessionId, {
agentId,
projectDir: projectDir(root, projectId),
- provider: spec.modelEntry.provider,
- modelId: spec.modelEntry.model_id,
+ provider: modelEntry.provider,
+ modelId: modelEntry.model_id,
}),
Object.keys(vault),
installedSkills,
@@ -539,12 +578,12 @@ export class Agent {
// Tool exposure is capped by depth: a (leaf) child Agent that has reached the max spawn
// depth no longer gets run_subagent or input_subagent (the latter depends on the
// subagent_id produced by the former, so exposing it alone is meaningless). Tool entries
- // are also selected by the session model's type through their forModel annotation
+ // are also selected by the context model's type through their forModel annotation
// (entries without it are unaffected — the built-in set carries none; read_file decides
// per model at runtime through the injected vision describer).
const canSpawn = spec.subagentDepth < MAX_SUBAGENT_DEPTH;
const baseToolConfig = buildToolConfig(state);
- const modelVision = spec.modelEntry.vision !== false;
+ const modelVision = modelEntry.vision !== false;
let customTools = selectBuiltinToolsForModel(baseToolConfig.customTools, modelVision);
if (!canSpawn) {
customTools = customTools.filter(
@@ -571,10 +610,7 @@ export class Agent {
// Compaction config: this context's baseline. It is no longer the last word — the engine
// re-reads the section at every compaction checkpoint through `compactionReader` — but a
// context still opens on the configuration that was on disk when it opened.
- const compaction = resolveCompaction(
- state.systemConfig.compaction,
- spec.modelEntry.context_window,
- );
+ const compaction = resolveCompaction(state.systemConfig.compaction, modelEntry.context_window);
// session_meta: this context's runtime configuration — the assembled prompt goes both to
// the LLM and in here, so the Trace can audit the actual effective value and a resume
@@ -582,9 +618,9 @@ export class Agent {
// is only known once the context's MCP Servers connected).
const meta: SessionMetaPayload = {
session_id: spec.sessionId,
- provider: spec.modelEntry.provider,
- model_id: spec.modelEntry.model_id,
- model_context_window: spec.modelEntry.context_window ?? "unknown",
+ provider: modelEntry.provider,
+ model_id: modelEntry.model_id,
+ model_context_window: modelEntry.context_window ?? "unknown",
system_prompt: systemPrompt,
agent_state: state.stateDir,
workspace: spec.workspaceDir,
@@ -592,6 +628,7 @@ export class Agent {
};
return {
+ modelEntry,
systemPrompt,
vault,
toolConfig,
@@ -603,7 +640,7 @@ export class Agent {
// entry's context window can still fit (see llm/context-limits.ts, issue #218), so the
// seeded per-Agent default (32000) no longer needs a manual per-model override to work
// against e.g. a 32768-token window — setting the entry's `context_window` is enough.
- maxTokens: spec.modelEntry.max_tokens ?? state.systemConfig.model?.max_tokens,
+ maxTokens: modelEntry.max_tokens ?? state.systemConfig.model?.max_tokens,
requestTimeoutMs: state.systemConfig.model?.timeoutMs,
// Max turns is an Agent runtime parameter (system_config), not a Session option.
maxTurns: state.systemConfig.max_turns,
@@ -613,6 +650,18 @@ export class Agent {
};
}
+ /**
+ * The entry `ref` names in the Project config **as it is on disk**, or undefined: the user
+ * picks a switch target from the models configured now, and a long-lived Agent must not
+ * answer from the ones configured when it loaded. The Agent's own copy follows the read, so
+ * what is resolved against it afterwards — a subagent spawned on the model just switched to,
+ * the vision model a text-only target describes images with — sees the same config.
+ */
+ private async modelEntryOnDisk(ref: ModelRef): Promise<ModelEntry | undefined> {
+ this.config = await loadProjectConfig(this.state.root, this.state.projectId);
+ return getModel(this.config, ref);
+ }
+
/**
* Create a Session in the specified (or a temporary) Workspace.
* Docs: /docs/sessions-and-traces § "Run model".
@@ -642,16 +691,14 @@ export class Agent {
);
}
const modelEntry = getModel(this.projectConfig, ref);
- if (!modelEntry) {
- throw new Error(
- `Model is not in the Project config: ${formatModelRef(ref)}. Use \`penguin config model list\` to see the configured models, or \`penguin config model add\` to add one.`,
- );
- }
+ if (!modelEntry) throw new Error(modelNotConfigured(ref));
// Credentials are inlined on the model entry (single config file); an explicit
// argument takes priority. With neither, the entry may lean on the environment only
// where the rule in resolveModelCredential allows (the vendor's own endpoint): a keyless
- // row pointed elsewhere is refused here, before any client exists.
- const { apiKey, baseUrl } = entryCredential(modelEntry, opts);
+ // row pointed elsewhere is refused here, before any client exists. Called for that
+ // refusal alone: each context's clients resolve the credential of the entry the context
+ // runs on (see buildRuntime's `credentialsFor`).
+ entryCredential(modelEntry, opts);
// An explicit Workspace must already exist as a directory: if it
// doesn't, throw rather than auto-create (to avoid a typo silently working in
@@ -681,9 +728,8 @@ export class Agent {
const spec: SessionSpec = {
sessionId,
workspaceDir,
- modelEntry,
- apiKey,
- baseUrl,
+ creationRef: ref,
+ credentialOverride: { apiKey: opts.apiKey, baseUrl: opts.baseUrl },
thinkingLevel: opts.thinkingLevel,
subagentDepth: opts.subagentDepth ?? 0,
...(opts.source !== undefined ? { source: opts.source } : {}),
@@ -691,7 +737,7 @@ export class Agent {
// The first context: assembled from the Agent State on disk now (never from this Agent
// object's load-time snapshot — a long-lived Agent, a self-spawned subagent's for
// instance, would otherwise start Sessions on stale configuration).
- const context = await this.assembleContext(spec);
+ const context = await this.assembleContext(spec, modelEntry);
const rt = this.buildRuntime(spec, context);
const trace = new Writer({
@@ -706,10 +752,13 @@ export class Agent {
* Resume an existing Session and continue the conversation.
*
* The resume source is the Session's **latest-index** Trace file: the Session-fixed facts
- * are read from its `session_meta` (Model and Workspace carry over from the original
- * Session and cannot be changed), and the context is assembled from the current Agent
- * State — keeping the recorded system prompt when the file's context is still open (see
- * below). The replayed, already-committed history is injected once via AgentHub's
+ * are read from its `session_meta` (the Workspace carries over from the original Session and
+ * cannot be changed), the model is the one that file's `session_meta` records — a model switch
+ * opens its new context's file at once, so the latest file always names the model the Session
+ * runs on — and the context is assembled from the current Agent State, keeping the recorded
+ * system prompt when the file's context is still open (see below). A resume never changes the
+ * model on its own; switching goes through `Session.switchModel`. The replayed,
+ * already-committed history is injected once via AgentHub's
* setHistory (used only on resume); any leftover input is rebuilt as carry-over (paired
* fallback placeholders are synthesized in memory only, never written to the Trace).
* Messages after resume continue in the original Trace file (the file follows the
@@ -754,7 +803,8 @@ export class Agent {
);
}
- // The Model carries over from the original Session (paired reference) and must still be present in the Project config.
+ // The Model carries over from the Trace (the latest file's paired reference) and must still
+ // be present in the Project config.
const ref: ModelRef = { provider: meta.provider, model_id: meta.model_id };
const modelEntry = getModel(this.projectConfig, ref);
if (!modelEntry) {
@@ -764,7 +814,7 @@ export class Agent {
}
// Same credential rule as createSession (see entryCredential): a key deleted since the
// Session was created surfaces here, at resume.
- const { apiKey, baseUrl } = entryCredential(modelEntry, opts);
+ entryCredential(modelEntry, opts);
// No level at resume: the host re-applies its stored value (Session.thinkingLevel) when it holds one,
// and contexts opened without a pin read the Agent config's chain (the same chain
@@ -775,9 +825,8 @@ export class Agent {
const spec: SessionSpec = {
sessionId,
workspaceDir,
- modelEntry,
- apiKey,
- baseUrl,
+ creationRef: ref,
+ credentialOverride: { apiKey: opts.apiKey, baseUrl: opts.baseUrl },
thinkingLevel: undefined,
subagentDepth: 0,
...(meta.source === "subagent" || meta.source === "schedule" || meta.source === "benchmark"
@@ -796,6 +845,7 @@ export class Agent {
// recorded prefix: it resolves from the pin and the config like on any other open.
const context = await this.assembleContext(
spec,
+ modelEntry,
resumed.contextClosed ? {} : { systemPrompt: meta.system_prompt },
);
const rt = this.buildRuntime(spec, context);
@@ -857,14 +907,18 @@ export class Agent {
initialEngineState: {
carryOver: resumed.carryOver,
...(resumed.pendingSummary ? { pendingSummary: resumed.pendingSummary } : {}),
+ ...(resumed.openingSummary ? { openingSummary: resumed.openingSummary } : {}),
sessionTurns: resumed.sessionTurns,
sessionTokens: resumed.sessionTokens,
lastRequestTotal: resumed.lastRequestTotal,
pendingTraceRotation: resumed.contextClosed,
// A closed context is one a completed compaction opened: the same fact drives the
// deferred Trace rotation above and the "just compacted" compaction reason, but they
- // are separate meanings and stay separate fields.
- fromCompaction: resumed.contextClosed,
+ // are separate meanings and stay separate fields. A file past the first was opened by
+ // a compaction too, so one with no completed turn yet — a model switch's eagerly opened
+ // file, or any new context the process died in before its first answer — is just as
+ // freshly compacted (read structurally, from the index, never from its records).
+ fromCompaction: resumed.contextClosed || (located.index > 1 && resumed.sessionTurns === 0),
},
resumedHistory: resumed.renderMessages,
});
@@ -888,26 +942,29 @@ export class Agent {
* tier and belongs to the context that was assembled from it; reading the file is not
* licence to apply the rest of it mid-context.
*
- * The model's context window comes from the Session's own entry, which is fixed at creation
- * (a mid-conversation model change opens a new Session), so one reader serves every context
- * the Session opens. A parse that fails throws: the engine keeps the settings in force and
- * warns once, which is the right answer for a file being rewritten badly.
+ * The model's context window comes from the running context's entry (`contextWindow`, a
+ * getter because an in-session model switch moves it), so one reader serves every context
+ * the Session opens and caps the threshold against the model that is running. A parse that
+ * fails throws: the engine keeps the settings in force and warns once, which is the right
+ * answer for a file being rewritten badly.
*/
- private compactionReader(spec: SessionSpec): () => Promise<CompactionSettings> {
+ private compactionReader(
+ contextWindow: () => number | undefined,
+ ): () => Promise<CompactionSettings> {
const { root, projectId, agentId } = this.state;
const configPath = systemConfigPath(root, projectId, agentId);
- const contextWindow = spec.modelEntry.context_window;
let cachedKey: string | null = null;
let cached: CompactionSettings | null = null;
return async (): Promise<CompactionSettings> => {
const stat = await fs.stat(configPath, { bigint: true });
- const key = `${stat.mtimeNs}:${stat.size}:${stat.ino}`;
+ const window = contextWindow();
+ const key = `${stat.mtimeNs}:${stat.size}:${stat.ino}:${window ?? "unknown"}`;
if (cached !== null && key === cachedKey) return cached;
const parsed = parseYaml(await fs.readFile(configPath, "utf8")) as unknown;
if (parsed === null || typeof parsed !== "object") {
throw new Error(`Invalid Agent State config: ${configPath} is empty or corrupted.`);
}
- cached = resolveCompaction((parsed as SystemConfig).compaction, contextWindow);
+ cached = resolveCompaction((parsed as SystemConfig).compaction, window);
cachedKey = key;
return cached;
};
@@ -941,10 +998,11 @@ export class Agent {
compaction: context.compaction,
// Live tier: the baseline above is what this context opened on, and this is how every
// checkpoint after it asks the disk again.
- readCompaction: this.compactionReader(spec),
+ readCompaction: this.compactionReader(rt.contextWindow),
// Where an input image lands when it becomes a path line (see SessionConfig.imagesDir).
imagesDir: sessionScratchpadDir(root, projectId, agentId, spec.sessionId),
- modelHasVision: spec.modelEntry.vision !== false,
+ modelHasVision: context.modelEntry.vision !== false,
+ modelSwitch: rt.modelSwitch,
...(context.maxTurns !== undefined ? { maxTurns: context.maxTurns } : {}),
// Sandbox command policy, strict-tier like the rest of the context (though
// Project-owned, never Agent State): read from disk when each context opens, so an
@@ -968,10 +1026,39 @@ export class Agent {
* around the context it starts in — see {@link SessionRuntime} for what each part does.
*/
private buildRuntime(spec: SessionSpec, initial: AssembledContext): SessionRuntime {
- const { sessionId, workspaceDir, modelEntry, apiKey, baseUrl, subagentDepth } = spec;
+ const { sessionId, workspaceDir, subagentDepth } = spec;
// The context the Session is running: the initial one, then whatever `openNextContext` last
- // assembled.
+ // opened (or a never-run Session's model switch re-assembled, see `modelSwitch` below). Its
+ // model entry is the model the Session is on.
let current = initial;
+ // The host's per-request credential resolver for one entry (see
+ // AgentAssembly.resolveModelApiKey), when the host supplies one.
+ const apiKeyResolverFor = (entry: ModelEntry): Pick<GenerativeModelConfig, "resolveApiKey"> =>
+ this.assembly?.resolveModelApiKey
+ ? {
+ resolveApiKey: () =>
+ this.assembly!.resolveModelApiKey!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ provider: entry.provider,
+ modelId: entry.model_id,
+ }),
+ }
+ : {};
+ // The credentials a context's LLM objects run on: the caller's explicit override for the
+ // entry it was given for (the creation model), every other entry's own configured pair —
+ // under the one credential rule (see entryCredential), so a keyless entry pointed away
+ // from its vendor is refused here too — plus the host's resolver for that entry.
+ const credentialsFor = (
+ entry: ModelEntry,
+ ): Pick<GenerativeModelConfig, "apiKey" | "baseUrl" | "resolveApiKey"> => ({
+ ...entryCredential(
+ entry,
+ sameModelRef(entry, spec.creationRef) ? spec.credentialOverride : {},
+ ),
+ ...apiKeyResolverFor(entry),
+ });
// Child-Agent runner: injected into the run_subagent tool so it doesn't need to
// depend on Agent/Session (breaking a circular dependency). The model can
// optionally choose agentId (omitted = call the current Agent), the child
@@ -1023,13 +1110,14 @@ export class Agent {
})
: parentAgent;
// The child Session follows the PARENT Session, never the Project default: with the
- // model pair fully omitted it reuses the parent's resolved (provider, model_id) —
- // the same Project-config entry, so max_tokens / context_window / vision follow
+ // model pair fully omitted it reuses the parent's CURRENT (provider, model_id) — the
+ // model the parent's running context is on, after any in-session switch — the same
+ // Project-config entry, so max_tokens / context_window / vision follow
// automatically. An explicit pair still wins, and half a pair is forwarded as-is so
// createSession rejects it (never silently completed from the parent's here).
const childModel =
modelId === undefined && provider === undefined
- ? { modelId: modelEntry.model_id, provider: modelEntry.provider }
+ ? { modelId: current.modelEntry.model_id, provider: current.modelEntry.provider }
: {
...(modelId !== undefined ? { modelId } : {}),
...(provider !== undefined ? { provider } : {}),
@@ -1152,60 +1240,48 @@ export class Agent {
};
}
- // When the session model doesn't support images (vision=false): inject a vision
- // model service for read_file's image branch — images are described by the Project
- // config's vision_model (a paired reference), and the tool returns text instead of
- // image content. Even when unconfigured or invalid, it is still injected (modelId=null):
- // its presence is what tells read_file the session model cannot view images; the tool
- // then finishes with a failed explanation, and images are never allowed into that
- // session's history.
- let visionDescriber: VisionDescriberService | undefined;
- if (modelEntry.vision === false) {
+ // When a context's model doesn't support images (vision=false): inject a vision model
+ // service for read_file's image branch — images are described by the Project config's
+ // vision_model (a paired reference), and the tool returns text instead of image content.
+ // Even when unconfigured or invalid, it is still injected (modelId=null): its presence is
+ // what tells read_file the session model cannot view images; the tool then finishes with a
+ // failed explanation, and images are never allowed into that session's history. Decided
+ // per context (a model switch can move to or from a text-only model): the Environment is
+ // handed the answer for each context it is equipped for.
+ const visionDescriberFor = (entry: ModelEntry): VisionDescriberService | undefined => {
+ if (entry.vision !== false) return undefined;
const visionRef = this.projectConfig.vision_model;
const visionEntry = visionRef ? getModel(this.projectConfig, visionRef) : undefined;
- if (visionEntry && visionEntry.vision !== false) {
- visionDescriber = {
- // The model attribution in the tool output matches the request's source: both are the entry's upstream model_id.
- modelId: visionEntry.model_id,
- // Resolved on each call rather than once here: the same credential rule as the
- // session model (a keyless entry pointed away from its vendor is refused), and a
- // refusal is a failed read_file, not a failed Session.
- createLLM: () =>
- new GenerativeModel({
- modelId: visionEntry.model_id,
- ...entryCredential(visionEntry, {}),
- ...(this.assembly?.resolveModelApiKey
- ? {
- resolveApiKey: () =>
- this.assembly!.resolveModelApiKey!({
- projectId: this.state.projectId,
- agentId: this.state.agentId,
- sessionId,
- provider: visionEntry.provider,
- modelId: visionEntry.model_id,
- }),
- }
- : {}),
- ...(visionEntry.client_type !== undefined
- ? { clientType: visionEntry.client_type }
- : {}),
- tools: [],
- thinkingLevel: "none",
- // The describing budget, tightened by the vision entry's own pinned cap when smaller.
- maxTokens: metaMaxTokens(2048, visionEntry.max_tokens),
- // Same window derivation as ordinary requests (a formality here: the meta
- // budget is far below any real window, so the clamp never binds).
- ...(visionEntry.context_window !== undefined
- ? { contextWindow: visionEntry.context_window }
- : {}),
- sessionId,
- requestTimeoutMs: 60_000,
- }),
- };
- } else {
- visionDescriber = { modelId: null };
- }
- }
+ if (!visionEntry || visionEntry.vision === false) return { modelId: null };
+ return {
+ // The model attribution in the tool output matches the request's source: both are the entry's upstream model_id.
+ modelId: visionEntry.model_id,
+ // Resolved on each call rather than once here: the same credential rule as the
+ // session model (a keyless entry pointed away from its vendor is refused), and a
+ // refusal is a failed read_file, not a failed Session.
+ createLLM: () =>
+ new GenerativeModel({
+ modelId: visionEntry.model_id,
+ ...entryCredential(visionEntry, {}),
+ ...apiKeyResolverFor(visionEntry),
+ ...(visionEntry.client_type !== undefined
+ ? { clientType: visionEntry.client_type }
+ : {}),
+ tools: [],
+ thinkingLevel: "none",
+ // The describing budget, tightened by the vision entry's own pinned cap when smaller.
+ maxTokens: metaMaxTokens(2048, visionEntry.max_tokens),
+ // Same window derivation as ordinary requests (a formality here: the meta
+ // budget is far below any real window, so the clamp never binds).
+ ...(visionEntry.context_window !== undefined
+ ? { contextWindow: visionEntry.context_window }
+ : {}),
+ sessionId,
+ requestTimeoutMs: 60_000,
+ }),
+ };
+ };
+ const visionDescriber = visionDescriberFor(initial.modelEntry);
// Environment binds the Workspace for the Session's lifetime and is equipped with the
// initial context's tool config and vault (a later context re-equips it, see
@@ -1261,48 +1337,35 @@ export class Agent {
// uniqueness scope is the Session's whole render span, so same-named tool calls after
// compaction don't collide with earlier cards' ids.
const toolCallIds = new ToolCallIdAllocator();
- // The LLM object of one context: the Session-fixed model entry and credentials, plus the
+ // The LLM object of one context: the context's model entry and its credentials, plus the
// context's prompt, toolset and model defaults. The model id sent to AgentHub is always
// the entry's upstream `model_id` (client_type inference/passing follows it);
// session_meta, Trace, usage, pricing, and catalog matching all use the (provider,
// model_id) pair as the primary key.
- const buildLLM = (context: AssembledContext, tools: ToolDefinition[]): GenerativeModel =>
- new GenerativeModel({
- modelId: modelEntry.model_id,
+ const buildLLM = (context: AssembledContext, tools: ToolDefinition[]): GenerativeModel => {
+ const entry = context.modelEntry;
+ return new GenerativeModel({
+ modelId: entry.model_id,
toolCallIds,
- ...(apiKey !== undefined ? { apiKey } : {}),
- ...(this.assembly?.resolveModelApiKey
- ? {
- resolveApiKey: () =>
- this.assembly!.resolveModelApiKey!({
- projectId: this.state.projectId,
- agentId: this.state.agentId,
- sessionId,
- provider: modelEntry.provider,
- modelId: modelEntry.model_id,
- }),
- }
- : {}),
- ...(baseUrl !== undefined ? { baseUrl } : {}),
- ...(modelEntry.client_type !== undefined ? { clientType: modelEntry.client_type } : {}),
+ ...credentialsFor(entry),
+ ...(entry.client_type !== undefined ? { clientType: entry.client_type } : {}),
tools,
systemPrompt: context.systemPrompt,
- ...(modelEntry.context_window !== undefined
- ? { contextWindow: modelEntry.context_window }
- : {}),
+ ...(entry.context_window !== undefined ? { contextWindow: entry.context_window } : {}),
...(context.maxTokens !== undefined ? { maxTokens: context.maxTokens } : {}),
// Fast mode is a session-request annotation: it rides every context's LLM object,
// while the bare/meta LLM below and the vision describer deliberately skip it — their
// background requests gain nothing user-facing from a premium tier, and skipping
// keeps them working (titles included) even while the annotation is enabled on a
// model that rejects it.
- ...(modelEntry.fast_mode === true ? { fastMode: true } : {}),
+ ...(entry.fast_mode === true ? { fastMode: true } : {}),
...(context.thinkingLevel !== undefined ? { thinkingLevel: context.thinkingLevel } : {}),
sessionId,
...(context.requestTimeoutMs !== undefined
? { requestTimeoutMs: context.requestTimeoutMs }
: {}),
});
+ };
// THE opening procedure — behind the first run's bootstrap and every post-compaction
// openNextContext alike, so initialization and rotation cannot drift apart: connects
@@ -1329,58 +1392,77 @@ export class Agent {
const bootstrap = async (opts: OpenContextOptions): Promise<{ llm: GenerativeModel }> =>
openAssembled(current, opts.emit);
+ // Equips the Environment for a context: its toolset (selected for its model's type), its
+ // vault, and the vision answer read_file needs.
+ const equip = (context: AssembledContext): void =>
+ environment.reconfigure({
+ toolConfig: context.toolConfig,
+ vault: context.vault,
+ visionDescriber: visionDescriberFor(context.modelEntry) ?? null,
+ });
+ // What an assembled context tells the Session and its engine beyond its LLM (see
+ // SessionOpenedContext): its meta and engine settings, its vision answer, and the hooks
+ // it runs with.
+ const contextFacts = (context: AssembledContext): Omit<SessionOpenedContext, "llm"> => ({
+ sessionMeta: sessionMeta(context.meta),
+ maxTurns: context.maxTurns ?? -1,
+ compaction: context.compaction,
+ modelHasVision: context.modelEntry.vision !== false,
+ hooks: this.sessionHooks(subagentRunner, context.hookPackages, spec),
+ });
+ // A switch target's entry once the switch is under way (the opener, or the never-run
+ // re-assembly): validated a moment ago, so one that is gone by now is a failure, not the
+ // refusal `modelSwitch.validate` answers with.
+ const switchTargetEntry = async (ref: ModelRef): Promise<ModelEntry> => {
+ const entry = await this.modelEntryOnDisk(ref);
+ if (!entry) throw new Error(modelNotConfigured(ref));
+ return entry;
+ };
+
// The context that follows a completed compaction: assembled anew from the Agent State
// as it is now — an edit the model (or the user) made during the old context to
- // AGENTS.md, system_config.yaml, the vault, the Skills or the MCP Servers lands here.
- // The Environment is re-equipped with the new toolset and vault, then the context is
- // opened by the same procedure as the first one — the engine yields the published
- // records live and writes them at the head of the rotated Trace file. An Agent State
- // that cannot be assembled (a config that no longer parses) throws: the run fails with
- // that error and the engine keeps the old context.
- const openNextContext = async ({ emit }: OpenContextOptions): Promise<SessionOpenedContext> => {
- const next = await this.assembleContext(spec);
+ // AGENTS.md, system_config.yaml, the vault, the Skills or the MCP Servers lands here —
+ // on the model the closing context ran on, or on the one a model switch names
+ // (`modelRef`, resolved against the Project config on disk). The Environment is
+ // re-equipped with the new toolset and vault, then the context is opened by the same
+ // procedure as the first one — the engine yields the published records live and writes
+ // them at the head of the rotated Trace file. An Agent State that cannot be assembled (a
+ // config that no longer parses) throws: the run fails with that error and the engine
+ // keeps the old context. So does this layer when the open itself fails: `current` moves
+ // only once the context is open, and the Environment goes back to the running one.
+ const openNextContext = async ({
+ emit,
+ modelRef,
+ }: SessionOpenContextOptions): Promise<SessionOpenedContext> => {
+ const entry = modelRef ? await switchTargetEntry(modelRef) : current.modelEntry;
+ const next = await this.assembleContext(spec, entry);
+ equip(next);
+ let llm: GenerativeModel;
+ try {
+ ({ llm } = await openAssembled(next, emit));
+ } catch (err) {
+ equip(current);
+ throw err;
+ }
current = next;
- environment.reconfigure({ toolConfig: next.toolConfig, vault: next.vault });
- const { llm } = await openAssembled(next, emit);
- return {
- llm,
- sessionMeta: sessionMeta(next.meta),
- maxTurns: next.maxTurns ?? -1,
- compaction: next.compaction,
- hooks: this.sessionHooks(subagentRunner, next.hookPackages, spec),
- };
+ return { llm, ...contextFacts(next) };
};
- // Bare LLM for one-off out-of-band requests (meta requests like generateTitle):
- // same Model/credentials, no tools, no system prompt, thinking disabled, a small
- // output cap, and an independent timeout.
- const createBareLLM = (): GenerativeModel =>
+ // Bare LLM for one-off out-of-band requests (meta requests like generateTitle): the
+ // running context's Model/credentials (or the given entry's), no tools, no system prompt,
+ // thinking disabled, a small output cap, and an independent timeout.
+ const createBareLLM = (entry: ModelEntry = current.modelEntry): GenerativeModel =>
new GenerativeModel({
- modelId: modelEntry.model_id,
- ...(apiKey !== undefined ? { apiKey } : {}),
- ...(this.assembly?.resolveModelApiKey
- ? {
- resolveApiKey: () =>
- this.assembly!.resolveModelApiKey!({
- projectId: this.state.projectId,
- agentId: this.state.agentId,
- sessionId,
- provider: modelEntry.provider,
- modelId: modelEntry.model_id,
- }),
- }
- : {}),
- ...(baseUrl !== undefined ? { baseUrl } : {}),
- ...(modelEntry.client_type !== undefined ? { clientType: modelEntry.client_type } : {}),
+ modelId: entry.model_id,
+ ...credentialsFor(entry),
+ ...(entry.client_type !== undefined ? { clientType: entry.client_type } : {}),
tools: [],
thinkingLevel: "none",
// The meta budget, tightened by the entry's pinned per-model cap when smaller.
- maxTokens: metaMaxTokens(300, modelEntry.max_tokens),
+ maxTokens: metaMaxTokens(300, entry.max_tokens),
// Same window derivation as ordinary requests (a formality here: the meta budget
// is far below any real window, so the clamp never binds).
- ...(modelEntry.context_window !== undefined
- ? { contextWindow: modelEntry.context_window }
- : {}),
+ ...(entry.context_window !== undefined ? { contextWindow: entry.context_window } : {}),
sessionId,
requestTimeoutMs: 30_000,
});
@@ -1393,11 +1475,42 @@ export class Agent {
// that throw here; the instance is discarded.
createBareLLM();
+ // The composition layer's half of an in-session model switch (see Session.switchModel):
+ // the target is validated exactly as a creation model is — configured on disk, credential
+ // present at client construction — before anything is sent or recorded; a Session that
+ // never ran has its first context assembled again on the target, which the bootstrap then
+ // opens like any first context.
+ const modelSwitch: ModelSwitchSupport = {
+ validate: async (ref) => {
+ const entry = await this.modelEntryOnDisk(ref);
+ if (!entry)
+ throw new ModelSwitchRefusedError("model_not_configured", modelNotConfigured(ref));
+ try {
+ createBareLLM(entry);
+ } catch (err) {
+ // A configured target whose client cannot be built — a missing credential foremost:
+ // a refusal with the loader's own wording, not a failure of the switch.
+ throw new ModelSwitchRefusedError(
+ "model_unavailable",
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ },
+ reassembleInitialContext: async (ref) => {
+ const next = await this.assembleContext(spec, await switchTargetEntry(ref));
+ equip(next);
+ current = next;
+ return contextFacts(next);
+ },
+ };
+
return {
environment,
bootstrap,
openNextContext,
commandPolicy: () => current.commandPolicy,
+ contextWindow: () => current.modelEntry.context_window,
+ modelSwitch,
createBareLLM,
subagentRunner,
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 85980636..0ba6f9ec 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -189,6 +189,8 @@ export interface EngineInitialState {
carryOver?: OmniMessage[];
/** Summary recovered from a completed summarize compaction: used as the prefix of the next `run` input (merged with the user Prompt). */
pendingSummary?: OmniMessage;
+ /** The summary the resumed context opened with, when it is already on the context's own file and no turn has completed since (see ResumeResult.openingSummary). */
+ openingSummary?: OmniMessage;
/** Carried-over Session cumulative turn count. */
sessionTurns?: number;
/**
@@ -300,19 +302,25 @@ export interface ContextEngineDeps {
* inside the new turn in the Trace, after the user's message (their timestamps precede
* the write; the file stays chronologically consistent because the input message was
* created before the connect began). Streaming already yielded them live before the
- * engine existed. Present (possibly empty) marks "first-run records still owed".
+ * engine existed. Present (possibly empty) marks "first-run records still owed". Owed
+ * only while the first context runs: when that context is replaced before any run wrote
+ * them (a compaction or a model switch on a Session just resumed, whose engine was built
+ * outside a run), they are dropped with it — and the first-run write of `toolList` with
+ * them — rather than landing behind the next run's input, in the next context's file.
*/
bootstrapRecords?: OmniMessage[];
/**
* Input adapter for a session whose model has no vision: folds image messages into text
* lines appended to the input's user text. Absent = the model takes images directly. `run`'s
* Prompt is folded by the caller before it reaches the engine; this hook exists for the one
- * input the engine assembles itself — steering (see `steeringMessages`).
+ * input the engine assembles itself — steering (see `steeringMessages`). A `null` answer
+ * leaves the input as it is too: the caller's model can change between contexts (a model
+ * switch), and only the caller knows whether the one running now takes images.
*
* Expected to settle rather than reject: it runs mid-Task, and Session's binding already
* degrades a failure into text saying the images were dropped.
*/
- foldInputImages?: (messages: OmniMessage[]) => Promise<OmniMessage[]>;
+ foldInputImages?: (messages: OmniMessage[]) => Promise<OmniMessage[] | null>;
/**
* Background-task completion notices (harness user messages the Session queues when a
* `run_in_background` task settles — see Session's notice queue). Pull seam: the engine
@@ -497,12 +505,19 @@ export class ContextEngine {
private lastSessionTokens: TokenCounts = emptyTokenCounts();
/** Summary produced by a Task-boundary compaction: used as the prefix of the next `run` input (merged with the next user Prompt). */
private pendingSummary: OmniMessage | null = null;
+ /**
+ * The summary the running context opened with, until a turn completes on it. It is the only
+ * record of the conversation before the compaction, so a model switch away from such a
+ * context writes it at the head of the next context's file (see `switchContext`).
+ */
+ private openingSummary: OmniMessage | null = null;
/** Bootstrap records still owed to the Trace (written after the first run's input); see ContextEngineDeps.bootstrapRecords. */
private pendingBootstrapRecords: OmniMessage[] | null = null;
/**
* Set to true once compaction completes: Trace rotation is deferred until the next
* message that needs writing (see `write`) — so that if no further messages follow the
- * compaction, we don't create an empty file containing only session_meta.
+ * compaction, we don't create an empty file containing only session_meta. A model switch is
+ * the one exception: it performs the rotation at once (see `switchContext`).
*/
private pendingTraceRotation = false;
/**
@@ -563,6 +578,9 @@ export class ContextEngine {
if (init) {
this.pendingCarryOver = init.carryOver ?? [];
this.pendingSummary = init.pendingSummary ?? null;
+ // A resumed context that has not completed a turn still opens with its summary: the one
+ // already on its own file, or the one a closed file left pending.
+ this.openingSummary = init.openingSummary ?? this.pendingSummary;
this.sessionTurns = init.sessionTurns ?? 0;
this.fromCompaction = init.fromCompaction ?? false;
this.lastSessionTokens = init.sessionTokens ?? emptyTokenCounts();
@@ -671,8 +689,8 @@ export class ContextEngine {
*/
private async steeringMessages(input: OmniMessage[]): Promise<OmniMessage[]> {
// No images, no fold: an image-free steering message is the same message either way.
- const fold = input.some(isImageMessage) ? this.deps.foldInputImages : undefined;
- const messages = fold ? await fold(input) : input;
+ const folded = input.some(isImageMessage) ? await this.deps.foldInputImages?.(input) : null;
+ const messages = folded ?? input;
const texts: string[] = [];
// The delivered [user_steering] message keeps the queued input's sender: a parent agent
// steering its child (input_subagent) records as "parent_agent" in the child's Trace,
@@ -691,7 +709,7 @@ export class ContextEngine {
// model known to refuse it, and no text at all means the images were dropped rather than
// written down as paths. Name the contract instead of delivering a steering message that
// lost what it was sent to carry.
- if (fold && (rest.some(isImageMessage) || texts.length === 0)) {
+ if (folded && (rest.some(isImageMessage) || texts.length === 0)) {
throw new Error("foldInputImages must return the input's images folded into a user text.");
}
return [userText(userSteeringText(texts.join("\n\n")), sender), ...rest];
@@ -1050,7 +1068,11 @@ export class ContextEngine {
});
}
- async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {
+ async *compact(opts?: {
+ signal?: AbortSignal | undefined;
+ /** Compacts in this mode whatever the settings say (a model switch always summarizes). */
+ mode?: CompactionMode;
+ }): AsyncGenerator<OmniMessage, StopReason | undefined> {
// The manual entry into a compaction, and the second place the live settings decide
// something: the `mode` below, and the prompt summarizeContext reads from them.
await this.refreshCompaction();
@@ -1061,12 +1083,12 @@ export class ContextEngine {
// pendingSummary with an "empty summary," permanently losing the only record of the prior
// conversation.
if (this.sessionTurns === 0) return;
- if (this.compaction.mode === "discard") {
+ if ((opts?.mode ?? this.compaction.mode) === "discard") {
this.pendingCarryOver = this.pendingCarryOver.filter(
(m) => (m.payload as { type?: string }).type !== "tool_call_output",
);
yield* this.discardContext("manual");
- return;
+ return "completed";
}
// The carry seam is a clean binary on whether the compaction committed anything to
// AgentHub (PR #87 review):
@@ -1086,6 +1108,51 @@ export class ContextEngine {
this.pendingCarryOver = folded;
}
// committed but not completed: the carry-over is deliberately not restored.
+ return result.status;
+ }
+
+ /**
+ * A model switch's rotation: closes the running context and opens the next one at once.
+ * Which model the next context runs on is the opener's business (`openNextContext`, which
+ * the Session owns); the engine only closes and opens. Callable at a Task boundary, with
+ * compaction configured, like `compact()`.
+ *
+ * - A context with completed turns is closed by `compact()`, always in **summarize** mode:
+ * the summary is what the next model continues from. It is an ordinary compaction request
+ * on the running LLM object — the same model, prompt, toolset and parameters, one appended
+ * user turn — so it extends the prefix the provider has cached. Short of `completed`, the
+ * context stays as it was.
+ * - A context with none has nothing to summarize and is simply replaced: no request and no
+ * event pair. Its pending text rides on in memory. Nothing is written until the next
+ * context is open, so an opener that throws leaves the Trace as it was.
+ *
+ * The next context's Trace file is then opened at once rather than at its first message:
+ * its `session_meta` is the durable record of the switch — a resume reads the model from
+ * the latest file — and the summary the context opens with follows it. That meta is yielded
+ * last. Returns the terminal status.
+ */
+ async *switchContext(signal?: AbortSignal): AsyncGenerator<OmniMessage, StopReason> {
+ if (this.sessionTurns > 0) {
+ const status = yield* this.compact({ signal, mode: "summarize" });
+ if (status !== "completed") return status ?? "fatal";
+ } else {
+ yield* this.startNewContext();
+ // A switch carries text alone: tool outputs pair with tool calls only the context left
+ // behind holds, and images stay behind with them.
+ this.pendingCarryOver = this.pendingCarryOver.filter(
+ (m) => (m.payload as { type?: string }).type === "text",
+ );
+ }
+ // The eager open: session_meta and the opener's records head the new file, then the summary.
+ await this.rotateIfPending();
+ if (this.openingSummary) await this.write(this.openingSummary);
+ if (this.pendingSummary) {
+ // On the file now: from here it is pending input, which a run sends without writing.
+ this.pendingCarryOver = [this.pendingSummary, ...this.pendingCarryOver];
+ this.pendingSummary = null;
+ }
+ if (this.contextMeta) yield this.contextMeta;
+ return "completed";
}
/**
@@ -1260,7 +1327,11 @@ export class ContextEngine {
// written, so the stream and the Trace carry the Session series rather than the
// LLM's per-request stand-in — and increment the Session turn count (counted per
// LLM Request, across Tasks; used for compaction threshold checks).
- if (this.observeTokenUsage(msg)) this.sessionTurns += 1;
+ if (this.observeTokenUsage(msg)) {
+ this.sessionTurns += 1;
+ // A turn completed: the summary the context opened with is history now.
+ this.openingSummary = null;
+ }
queue.push(msg);
await this.write(msg);
// Collect complete thinking/text segments (including partial segments finalized on
@@ -1682,6 +1753,7 @@ export class ContextEngine {
const summary = userText(buildContextSummaryText(summaryText));
yield* this.emitCompactionEnd(reason, "summarize", "completed", { attempt: attempts });
yield* this.startNewContext();
+ this.openingSummary = summary;
return { status: "completed", summary, committed };
}
// Not a summary — one more failed attempt, sharing the reconnect budget below. Tool
@@ -1956,7 +2028,8 @@ export class ContextEngine {
* tool_list_ready) are yielded live as they come, so a slow connect is never a silent gap.
* Trace **does not** split files immediately — that's deferred until the next message that
* needs writing, when it rotates and opens with the context's session_meta and records (see
- * `write`), avoiding an empty file if no further messages follow the compaction.
+ * `write`), avoiding an empty file if no further messages follow the compaction; a model
+ * switch opens the file right after this returns instead (see `switchContext`).
*/
private async *startNewContext(): AsyncGenerator<OmniMessage> {
// The opener publishes records through a callback; a merge queue turns them into this
@@ -1984,6 +2057,9 @@ export class ContextEngine {
if (opened.compaction) this.compaction = opened.compaction;
this.sessionTurns = 0;
this.lastRequestTotal = 0;
+ // First-run records no run has written yet describe the context this one replaces: they
+ // are dropped with it rather than written into this context's file.
+ this.pendingBootstrapRecords = null;
// Lets compactability() distinguish "just compacted" from "hasn't chatted yet" — both have
// sessionTurns === 0, but they mean two completely different things to the user (being told
// "no completed conversation turns yet" right after compacting is as good as saying nothing).
@@ -2148,25 +2224,34 @@ export class ContextEngine {
return [...input, userText(buildTurnRetriedBlock(lines))];
}
+ /**
+ * Performs the deferred Trace rotation when one is pending: splits the file and opens it with
+ * the current context's session_meta and records (its MCP connect pair, if any, and its
+ * toolset). Best-effort like every Trace write. Reached through `write` by the first message
+ * after a compaction, and directly by `switchContext`, which opens the file at once.
+ */
+ private async rotateIfPending(): Promise<void> {
+ const trace = this.deps.trace;
+ if (!trace || !this.pendingTraceRotation) return;
+ this.pendingTraceRotation = false;
+ try {
+ if (trace.rotate) await trace.rotate();
+ if (this.contextMeta) await trace.write(this.contextMeta);
+ for (const record of this.contextRecords) await trace.write(record);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ process.stderr.write(`[trace] rotate failed: ${message}\n`);
+ }
+ }
+
/**
* Trace writes are **best-effort**: observability should never interrupt the ReAct
* loop, so write failures only warn rather than throw. The first write after compaction first
- * performs the deferred Trace rotation: splitting the file and opening it with the current
- * context's session_meta and records (its MCP connect pair, if any, and its toolset).
+ * performs the deferred Trace rotation (see `rotateIfPending`).
*/
private async write(msg: OmniMessage): Promise<void> {
+ await this.rotateIfPending();
if (!this.deps.trace) return;
- if (this.pendingTraceRotation) {
- this.pendingTraceRotation = false;
- try {
- if (this.deps.trace.rotate) await this.deps.trace.rotate();
- if (this.contextMeta) await this.deps.trace.write(this.contextMeta);
- for (const record of this.contextRecords) await this.deps.trace.write(record);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- process.stderr.write(`[trace] rotate failed: ${message}\n`);
- }
- }
try {
await this.deps.trace.write(msg);
} catch (err) {
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index 3656a3fe..b57b738c 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -48,6 +48,7 @@ import type {
ToolDetachResult,
ToolExecutionRequest,
ToolPermission,
+ VisionDescriberService,
} from "../interfaces/index.js";
import type { BuiltinTool, ToolResult } from "./tools/types.js";
import { BUILTIN_TOOL_FACTORIES } from "./tools/registry.js";
@@ -291,8 +292,18 @@ export class Environment implements EnvironmentInterface {
* started with. The Session-lifetime parts — background command processes, subagent child
* sessions, the listeners, the Workspace and the scratchpad — are untouched. Concrete-class
* surface, not part of EnvironmentInterface.
+ *
+ * `visionDescriber` is the new context's answer to "does the session model view images"
+ * (see EnvironmentServices.visionDescriber): a service when that context's model has no
+ * vision, `null` when it views images itself — a model switch can move either way — and
+ * absent leaves the running answer in place. Applied before the toolset is re-equipped, so
+ * the new context's read_file is built on it.
*/
- reconfigure(config: { toolConfig: ToolConfig; vault: Record<string, string> }): void {
+ reconfigure(config: {
+ toolConfig: ToolConfig;
+ vault: Record<string, string>;
+ visionDescriber?: VisionDescriberService | null;
+ }): void {
const servers = config.toolConfig.mcpServers;
if (this.mcp && servers.length > 0) {
this.mcp.reconfigure(servers);
@@ -300,6 +311,10 @@ export class Environment implements EnvironmentInterface {
this.mcp?.closeQuietly();
this.mcp = this.newMcpProvider(servers);
}
+ if (config.visionDescriber !== undefined) {
+ if (config.visionDescriber === null) delete this.services.visionDescriber;
+ else this.services.visionDescriber = config.visionDescriber;
+ }
this.equip(config.toolConfig);
this.commandSessions.setVault(config.vault);
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 620d9292..6e69ff7b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -48,8 +48,15 @@ export type {
RunOptions,
TraceSink,
} from "./engine/context-engine.js";
-export { Session } from "./session.js";
-export type { SessionConfig, SessionOpenedContext } from "./session.js";
+export { ModelSwitchRefusedError, Session } from "./session.js";
+export type {
+ ModelSwitchOptions,
+ ModelSwitchRefusal,
+ ModelSwitchSupport,
+ SessionConfig,
+ SessionOpenContextOptions,
+ SessionOpenedContext,
+} from "./session.js";
export type { AgentAssembly, ModelRequestContext, PromptSection } from "./agent.js";
// Session-title generation lives in internal/ (an assembly detail of Session.generateTitle);
// only its narrow public surface is re-exported: the result type (part of
diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.ts
index 3734582e..df298cb8 100644
--- a/packages/core/src/interfaces/environment.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -227,7 +227,7 @@ export interface VisionDescriberService {
*/
export interface EnvironmentServices {
subagentRunner?: SubagentRunner;
- /** Injected when (and only when) the session model doesn't support images: read_file then describes an image through it instead of returning image content. */
+ /** Injected when (and only when) the running context's model doesn't support images: read_file then describes an image through it instead of returning image content. Follows the model across an in-session switch (`Environment.reconfigure` re-injects or removes it as each context opens). */
visionDescriber?: VisionDescriberService;
/** Registry of long-running command sessions (shared by `exec_command` / `input_command`); constructed and injected internally by Environment. */
commandSessions?: CommandSessionManager;
diff --git a/packages/core/src/omnimessage/markers/index.ts b/packages/core/src/omnimessage/markers/index.ts
index bb35834f..7f5a452a 100644
--- a/packages/core/src/omnimessage/markers/index.ts
+++ b/packages/core/src/omnimessage/markers/index.ts
@@ -29,7 +29,10 @@
* structured facts only — payload fields such as `sender`, and the explicit queue/state that
* delivered the message — so core BUILDS markers but never branches on them. Transforming a
* protocol block core itself authored (the compaction `[summary]` extraction) is not source
- * discrimination and stays legitimate.
+ * discrimination and stays legitimate. Trace replay also recognizes the `[context_summary]` a
+ * context opened with (no field marks that record): the answer only decides whether that
+ * pending text is carried on to the next Trace file, so a user text that happens to start
+ * with the tag is kept where it would have stayed behind — never the reverse.
*
* Everything here is pure string work: no OmniMessage envelopes, no I/O — the callers wrap
* the result in `userText(...)` (or match against a payload's text) themselves.
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index 5dbe4a1a..d11084c6 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -12,6 +12,13 @@
* the Human interface communicates using: complete `model_msg`, streaming `partial_*`, and all
* `event_msg`.
*
+ * OmniMessage is a closed vocabulary. A new payload field or enum value is a protocol change
+ * every reader — Trace replay, the server, the Web App, the CLI, third-party consumers — has to
+ * learn, forever. Before adding one, show that no existing record carries the fact (the model
+ * lives in `session_meta`; a context's boundaries in the compaction pair and the file split)
+ * and that readers cannot derive it. The PR description says why the existing records could
+ * not carry it. The rule itself is stated in the architecture spec's message-format section.
+ *
* Docs: packages/docs/content/omni-message.{zh,en}.md (site path /docs/omni-message) documents
* this protocol payload-for-payload — keep the page in sync when changing types here.
*/
@@ -102,20 +109,23 @@ export interface ToolDefinition {
/**
* Session metadata: the runtime configuration of one **model context**. One `session_meta`
* opens every Trace file — the Session's first, and each file a compaction's rotation starts.
- * The model reference, the paths and the origin are fixed for the Session's lifetime; the
- * assembled system prompt is fixed per context — a context is assembled from the Agent State
- * as it is when it opens (the template, `AGENTS.md` and the other placeholders re-read), so
- * each file's meta carries the prompt its context actually ran with; the context's toolset
- * follows as the `tool_list_ready` record. Everything that shapes the request prefix — model,
- * prompt, toolset — holds from a context's open to its close; the thinking level is not part
- * of it (a per-request parameter, deliberately not recorded — see the note in the body).
+ * The paths and the origin are fixed for the Session's lifetime; the model reference and the
+ * assembled system prompt are fixed per context — a context is assembled from the Agent State
+ * as it is when it opens (the template, `AGENTS.md` and the other placeholders re-read), on the
+ * model the Session is running at that point (an in-session model switch opens its new
+ * context on another one — see `Session.switchModel`), so each file's meta carries the prompt
+ * and the model its context actually ran with; the context's toolset follows as the
+ * `tool_list_ready` record. Everything that shapes the request prefix — model, prompt,
+ * toolset — holds from a context's open to its close; the thinking level is not part of it (a
+ * per-request parameter, deliberately not recorded — see the note in the body).
*/
export interface SessionMetaPayload {
session_id: string;
- /** The session model's provider group (paired with `model_id` to form a model reference). */
+ /** This context's model: the provider group (paired with `model_id` to form a model reference). */
provider: string;
- /** The session model's upstream model_id (the request id sent to AgentHub; paired with `provider`). */
+ /** This context's model: the upstream model_id (the request id sent to AgentHub; paired with `provider`). */
model_id: string;
+ /** The context window of this context's model, or `"unknown"` when its entry configures none. */
model_context_window: number | string;
/** The system prompt this context runs with (the assembled result, placeholders already substituted). */
system_prompt: string;
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index cc147ddc..860d32a0 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -24,8 +24,15 @@ import {
sessionMeta,
userText,
} from "./omnimessage/index.js";
-import type { OmniMessage, SessionMetaPayload } from "./omnimessage/index.js";
+import type {
+ OmniMessage,
+ SessionMetaMessage,
+ SessionMetaPayload,
+ StopReason,
+} from "./omnimessage/index.js";
import { stripLeadingMarkerBlocks } from "./omnimessage/markers/index.js";
+import type { ModelRef } from "./state/project-config.js";
+import { sameModelRef } from "./state/project-config.js";
import { imagesToScratchpadPaths } from "./internal/session-support.js";
import { runStopHooks } from "./hooks/stop-hook.js";
import type { HookSubagentSpawner, SessionHooks, StopHook } from "./hooks/stop-hook.js";
@@ -67,15 +74,28 @@ import type {
* A context as the composition layer opens it for a Session: the engine's
* {@link OpenedContext}, plus the hooks that context runs with. Hook packages are read when
* a model context opens, like the rest of the Agent State, so a rotation brings its own
- * set; the engine never sees them.
+ * set; the engine never sees them. Nor does it see whether the context's model has vision:
+ * the image fold is the Session's own.
*/
export interface SessionOpenedContext extends OpenedContext {
/** The opened context's hooks, replacing the Session's whole set. Absent = the Session keeps the ones it has (an embedder that registered in-process hooks and rotates without re-reading any). */
hooks?: SessionHooks;
+ /** Whether the opened context's model accepts image input (see SessionConfig.modelHasVision). Absent = as before. */
+ modelHasVision?: boolean;
+}
+
+/**
+ * What `SessionConfig.openNextContext` is called with: the engine's options, plus the model a
+ * switch in flight opens the context on (see {@link Session.switchModel}) — absent for every
+ * other rotation, which keeps the model the closing context ran on. The opener resolves the
+ * reference against the Project config as it is on disk.
+ */
+export interface SessionOpenContextOptions extends OpenContextOptions {
+ modelRef?: ModelRef;
}
export interface SessionConfig {
- /** Session metadata: the first context's runtime configuration (session_id / provider / model_id / model_context_window / system_prompt / agent_state / workspace / source) — a context a compaction opens brings its own through `openNextContext`; the toolset travels separately as the first run's tool_list_ready event. */
+ /** Session metadata: the first context's runtime configuration (session_id / provider / model_id / model_context_window / system_prompt / agent_state / workspace / source) — a context a compaction or a model switch opens brings its own through `openNextContext`; the toolset travels separately as the first run's tool_list_ready event. */
meta: SessionMetaPayload;
/**
* Opens the Session's FIRST context, lazily at the start of the first run: resolves the
@@ -108,7 +128,7 @@ export interface SessionConfig {
* {@link SessionOpenedContext}).
*/
openNextContext?: (
- opts: OpenContextOptions,
+ opts: SessionOpenContextOptions,
) => SessionOpenedContext | Promise<SessionOpenedContext>;
/**
@@ -135,10 +155,16 @@ export interface SessionConfig {
*/
imagesDir: string;
/**
- * Whether the session's model accepts image input (from ModelEntry.vision). Prompts and
- * steering messages fold their images only when this is false.
+ * Whether the first context's model accepts image input (from ModelEntry.vision). Prompts and
+ * steering messages fold their images only while the running context's model has none — a
+ * context `openNextContext` opens brings its own answer (SessionOpenedContext.modelHasVision).
*/
modelHasVision: boolean;
+ /**
+ * The composition layer's half of an in-session model switch (see {@link Session.switchModel});
+ * absent = the Session's model cannot be switched.
+ */
+ modelSwitch?: ModelSwitchSupport;
/**
* The first context's hooks — one list per hook point, and the spawner that honors a stop
* hook's `subagent` answer (see hooks/stop-hook.ts). Absent = none. A context
@@ -161,6 +187,59 @@ export interface SessionConfig {
/** `Session.run` options: the engine's per-call options. */
export type SessionRunOptions = RunOptions;
+/** Why a model switch was refused before its first event (see {@link ModelSwitchRefusedError}). */
+export type ModelSwitchRefusal =
+ /** The target pair names no entry in the Project config on disk. */
+ | "model_not_configured"
+ /** The target is configured but its client cannot be constructed (a missing credential foremost), or this Session has no switch support. */
+ | "model_unavailable"
+ /** The Session has a context to close but no compaction configured to close it with. */
+ | "compaction_not_configured";
+
+/**
+ * A model switch refused before anything was sent or recorded: no event was produced and the
+ * Session is exactly where it was. `Session.switchModel` throws it for the refusals `reason`
+ * enumerates, so a host maps each to its own code (the server's 409s) and treats anything
+ * else a switch throws as a failure.
+ */
+export class ModelSwitchRefusedError extends Error {
+ constructor(
+ readonly reason: ModelSwitchRefusal,
+ message: string,
+ ) {
+ super(message);
+ this.name = "ModelSwitchRefusedError";
+ }
+}
+
+/**
+ * What the composition layer provides for {@link Session.switchModel}: the Session owns the
+ * policy, the Agent owns the Project config, the credentials and the assembly.
+ */
+export interface ModelSwitchSupport {
+ /**
+ * Validates a switch target before anything is sent or recorded: resolves it against the
+ * Project config as it is on disk and constructs its client, so a pair that is not
+ * configured, or has no credential, is refused here (a {@link ModelSwitchRefusedError})
+ * exactly where Session creation would have failed.
+ */
+ validate(ref: ModelRef): Promise<void>;
+ /**
+ * Re-assembles the Session's not-yet-opened first context on `ref` — the switch of a Session
+ * that never ran, which has no context to close. The Environment is re-equipped for it, and
+ * what comes back is what a rotation's opener returns minus the LLM, which the first run's
+ * bootstrap builds as usual.
+ */
+ reassembleInitialContext(ref: ModelRef): Promise<Omit<SessionOpenedContext, "llm">>;
+}
+
+/** `Session.switchModel` options: the target's paired reference, and the abort signal for the compaction request. */
+export interface ModelSwitchOptions {
+ provider: string;
+ modelId: string;
+ signal?: AbortSignal;
+}
+
/**
* Awaits `work` unless `signal` aborts first — the abort side never cancels `work`
* (deliberate: see the bootstrap single-flight). Settles immediately when the signal is
@@ -252,10 +331,6 @@ function appendTitleText(
export class Session {
readonly sessionId: string;
- /** The session model's provider group (paired with `modelId` to form the model reference). */
- readonly provider: string;
- /** The session model's upstream model_id (the request id sent to AgentHub). */
- readonly modelId: string;
readonly workspaceDir: string;
/** Session resume: the full historical messages of the current context (for rendering); undefined for a non-resumed Session. */
readonly resumedHistory?: OmniMessage[];
@@ -279,20 +354,28 @@ export class Session {
private abortedBootstrapRecords: OmniMessage[] = [];
private readonly bootstrap: SessionConfig["bootstrap"];
private readonly cancelBootstrap: (() => void) | undefined;
- /** Engine dependencies minus the LLM (which the bootstrap provides); kept whole so ensureReady can construct the engine late. */
+ /**
+ * Engine dependencies, kept so ensureReady can construct the engine late — minus what only
+ * that moment knows: the LLM and its records (the bootstrap provides them), and the first
+ * context's session_meta (the Session's own `meta` as it stands then).
+ */
private readonly engineDeps: Omit<
ConstructorParameters<typeof ContextEngine>[0],
- "llm" | "toolList" | "bootstrapRecords"
+ "llm" | "toolList" | "bootstrapRecords" | "sessionMeta"
>;
private readonly environment: EnvironmentInterface;
private readonly trace?: TraceSink;
- /** session_meta of the context that is running: the first context's at construction, re-stamped by each context `openNextContext` opens (see `metaMessage`). */
- private meta: OmniMessage;
+ /** session_meta of the context that is running: the first context's at construction, re-stamped by each context `openNextContext` opens (see `metaMessage`); `provider` / `modelId` read from it. */
+ private meta: SessionMetaMessage;
private readonly createBareLLM?: () => LLMInterface;
/** The Session's thinking level — buffered here until the engine exists, engine state afterwards (see the `thinkingLevel` accessors). */
private level?: ThinkingLevelName;
private readonly imagesDir: string;
- private readonly modelHasVision: boolean;
+ /** Whether the running context's model views images itself (see SessionConfig.modelHasVision); follows each context `openNextContext` opens. */
+ private modelHasVision: boolean;
+ private readonly modelSwitch: ModelSwitchSupport | undefined;
+ /** The model a switch in flight opens the next context on: what the opener is told (see `switchModel`). */
+ private switchTarget: ModelRef | undefined;
/**
* The hooks of the context that is running, and the spawner for a stop hook's subagent
* answer: the first context's at construction, replaced whole by each context
@@ -337,8 +420,6 @@ export class Session {
constructor(config: SessionConfig) {
this.sessionId = config.meta.session_id;
- this.provider = config.meta.provider;
- this.modelId = config.meta.model_id;
this.workspaceDir = config.meta.workspace;
this.environment = config.environment;
this.trace = config.trace;
@@ -349,6 +430,7 @@ export class Session {
this.imagesDir = config.imagesDir;
this.modelHasVision = config.modelHasVision;
+ this.modelSwitch = config.modelSwitch;
if (config.hooks) this.adoptHooks(config.hooks);
if (config.commandPolicy) this.commandPolicy = config.commandPolicy;
this.bootstrap = config.bootstrap;
@@ -361,14 +443,16 @@ export class Session {
...(config.maxTurns !== undefined ? { maxTurns: config.maxTurns } : {}),
// Context compaction: the new-context factory + resolved settings; the engine writes the
// context's session_meta (and tool_list_ready) at the start of the new Trace file after
- // splitting. The factory is wrapped so the Session's own meta follows the opened context:
- // `metaMessage` must describe the context that is running, not the one that was.
+ // splitting. The factory is wrapped so the opener is told the model a switch in flight is
+ // moving to, and the Session follows the opened context (see `adoptContext`).
...(config.openNextContext
? {
openNextContext: async (opts: OpenContextOptions): Promise<OpenedContext> => {
- const { hooks, ...opened } = await config.openNextContext!(opts);
- if (opened.sessionMeta) this.meta = opened.sessionMeta;
- if (hooks) this.adoptHooks(hooks);
+ const { hooks, modelHasVision, ...opened } = await config.openNextContext!({
+ ...opts,
+ ...(this.switchTarget ? { modelRef: this.switchTarget } : {}),
+ });
+ this.adoptContext(opened.sessionMeta, modelHasVision, hooks);
return opened;
},
}
@@ -380,10 +464,10 @@ export class Session {
// it through the same converter `runTask` uses, failures included: a scratchpad that
// can't be written to ends the run rather than dropping the attachment and carrying on.
// The picture usually arrives BECAUSE the run is going the wrong way, so continuing
- // without it spends the rest of the Task heading further that way. A vision model simply
- // isn't given the function, which is all the engine needs to know about the subject.
- ...(config.modelHasVision ? {} : { foldInputImages: this.foldImages }),
- sessionMeta: this.meta,
+ // without it spends the rest of the Task heading further that way. A model that takes
+ // images is answered `null` — the model can change with the context, so the question is
+ // asked each time.
+ foldInputImages: async (messages) => (this.modelHasVision ? null : this.foldImages(messages)),
// Background completion notices: the engine pulls from the Session's queue at every
// input-assembly boundary (see pendingNotices for the exactly-once contract). This is
// the steering delivery path — the notice joins a Task that already exists — so the
@@ -763,6 +847,7 @@ export class Session {
...this.engineDeps,
...(trace !== undefined ? { trace } : {}),
llm,
+ sessionMeta: this.meta,
...(toolsMsg !== undefined ? { toolList: toolsMsg } : {}),
bootstrapRecords: connectRecords,
});
@@ -812,6 +897,99 @@ export class Session {
return this.engine?.skipReconnectWait() ?? false;
}
+ /** The running context's model: its provider group (paired with `modelId` to form the model reference). The first context's at construction; a model switch moves it. */
+ get provider(): string {
+ return this.meta.payload.provider;
+ }
+
+ /** The running context's model: its upstream model_id (the request id sent to AgentHub). */
+ get modelId(): string {
+ return this.meta.payload.model_id;
+ }
+
+ /**
+ * Follows a context the composition layer opened (or re-assembled): `metaMessage`,
+ * `provider` and `modelId` answer from its session_meta, the Prompt fold from its vision
+ * answer, and its hooks replace the Session's. What it did not bring stays as it was.
+ */
+ private adoptContext(
+ meta: OmniMessage | undefined,
+ modelHasVision: boolean | undefined,
+ hooks: SessionHooks | undefined,
+ ): void {
+ if (meta) this.meta = meta as SessionMetaMessage;
+ if (modelHasVision !== undefined) this.modelHasVision = modelHasVision;
+ if (hooks) this.adoptHooks(hooks);
+ }
+
+ /**
+ * Switches the model this Session runs on, in place: the running context is closed on the
+ * model it ran on, and the next one opens on the target. A context with completed turns is
+ * closed by a compaction — always **summarize**, whatever the Agent's `compaction.mode`
+ * says, because the summary is what the new model continues from. That compaction is an
+ * ordinary `manual` one: an ordinary request on the old model, extending the prefix the
+ * provider has cached. The model is recorded by the new context's `session_meta` alone; its
+ * Trace file opens at once, headed by that record — what a resume reads the model from —
+ * and the record is yielded last, so the stream names the model too. Only callable at a Task
+ * boundary, like `compact()`. Not the `/model` handoff, which opens a NEW Session.
+ *
+ * Before any event: the model the Session is already on is a no-op, and a target that
+ * cannot be switched to is refused with a {@link ModelSwitchRefusedError} naming why
+ * (anything else thrown is a failure). A Session that never ran has no context to close:
+ * its first context is re-assembled on the target, silently, and the first run opens it.
+ * One resumed after a restart builds its engine first, as `compact()` does. How the context
+ * is then closed and the next one opened is `ContextEngine.switchContext`; on which model,
+ * the opener is told here.
+ *
+ * Returns the terminal status: `completed` — the Session is on the target, and children
+ * spawned from here inherit it; anything else — the switch was stopped or its compaction
+ * failed (the events say how) and the Session stays on the model it was on.
+ */
+ async *switchModel(opts: ModelSwitchOptions): AsyncGenerator<OmniMessage, StopReason> {
+ const target: ModelRef = { provider: opts.provider, model_id: opts.modelId };
+ if (sameModelRef(target, { provider: this.provider, model_id: this.modelId })) {
+ return "completed";
+ }
+ if (!this.modelSwitch) {
+ throw new ModelSwitchRefusedError(
+ "model_unavailable",
+ "Switching the model is not available for this Session.",
+ );
+ }
+ await this.modelSwitch.validate(target);
+ if (!this.engine && !this.metaWritten) {
+ // Never ran: no context to close and nothing recorded — the first context is simply
+ // assembled again, on the target, and the first run writes that context's meta.
+ const { hooks, modelHasVision, ...first } =
+ await this.modelSwitch.reassembleInitialContext(target);
+ this.adoptContext(first.sessionMeta, modelHasVision, hooks);
+ if (first.compaction) this.engineDeps.compaction = first.compaction;
+ if (first.maxTurns !== undefined) this.engineDeps.maxTurns = first.maxTurns;
+ return "completed";
+ }
+ if (this.compactability() === "unsupported") {
+ throw new ModelSwitchRefusedError(
+ "compaction_not_configured",
+ "Context compaction is not configured for this Session, so its model cannot be switched.",
+ );
+ }
+ if (!(yield* this.ensureEngine(opts.signal))) return "aborted";
+ this.switchTarget = target;
+ try {
+ const status = yield* this.engine!.switchContext(opts.signal);
+ // Input an aborted bootstrap left with the Session rides on like the engine's pending
+ // input: its text alone, in memory (the original stays where the abort wrote it).
+ if (status === "completed") {
+ this.carryOverInput = this.carryOverInput.filter(
+ (m) => (m.payload as { type?: string }).type === "text",
+ );
+ }
+ return status;
+ } finally {
+ this.switchTarget = undefined;
+ }
+ }
+
/**
* User-initiated request to compact context (e.g. a CLI command): reuses the automatic
* compaction flow but skips the threshold check (reason=manual). Only callable at Task
@@ -821,30 +999,35 @@ export class Session {
* Docs: /docs/agent-loop § "Compaction".
*/
async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {
- if (!this.engine) {
- // Nothing compactable and no engine: stay a strict no-op, without bootstrapping — a
- // session that never ran must not leave trace records (meta / tool_list_ready) behind,
- // or an untouched session would look resumable.
- if (this.compactability() !== "ok") return;
- // A Session resumed after a restart is the opposite case: its history is real and
- // already on disk, and the engine simply has not been built yet (that happens on the
- // first run). Build it here — the bootstrap injects the replayed history into the LLM,
- // so the compaction request folds the actual conversation — rather than silently doing
- // nothing and leaving the user waiting for a banner that never arrives.
- const ready = yield* this.ensureReady(opts?.signal);
- if (!ready) {
- // Aborted mid-bootstrap: no engine exists to write the records, so the Session writes
- // them itself (as runTask does), keeping the interruption visible in the Trace.
- for (const m of this.abortedBootstrapRecords) {
- await this.writeTrace(m, "aborted bootstrap record");
- }
- this.abortedBootstrapRecords = [];
- return;
- }
- }
+ // Nothing compactable and no engine: stay a strict no-op, without bootstrapping — a
+ // session that never ran must not leave trace records (meta / tool_list_ready) behind,
+ // or an untouched session would look resumable.
+ if (!this.engine && this.compactability() !== "ok") return;
+ if (!(yield* this.ensureEngine(opts?.signal))) return;
yield* this.engine!.compact(opts);
}
+ /**
+ * Builds the engine outside a run, for a compaction or a model switch. A Session resumed
+ * after a restart is the case: its history is real and already on disk, and the engine
+ * simply has not been built yet (that happens on the first run). The bootstrap injects the
+ * replayed history into the LLM, so the compaction request folds the actual conversation —
+ * rather than the call silently doing nothing and leaving the user waiting for a banner that
+ * never arrives. A no-op returning true once the engine exists.
+ *
+ * Returns false when `signal` aborted the bootstrap: no engine exists to write the attempt's
+ * records, so the Session writes them itself (as runTask does), keeping the interruption
+ * visible in the Trace.
+ */
+ private async *ensureEngine(signal?: AbortSignal): AsyncGenerator<OmniMessage, boolean> {
+ if (yield* this.ensureReady(signal)) return true;
+ for (const m of this.abortedBootstrapRecords) {
+ await this.writeTrace(m, "aborted bootstrap record");
+ }
+ this.abortedBootstrapRecords = [];
+ return false;
+ }
+
/**
* Whether compaction is possible, and why not if not (see ContextEngine.compactability).
* When the result isn't `ok`, `compact()` is a no-op and yields no messages — callers should
diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.ts
index 5bd5a956..bd749cf3 100644
--- a/packages/core/src/state/project-config.ts
+++ b/packages/core/src/state/project-config.ts
@@ -776,13 +776,13 @@ export async function removeModel(
ref: ModelRef,
): Promise<ProjectConfig> {
const cfg = await loadProjectConfig(root, projectId);
- const idx = cfg.models.findIndex((m) => sameRef(m, ref));
+ const idx = cfg.models.findIndex((m) => sameModelRef(m, ref));
if (idx < 0) return cfg;
cfg.models.splice(idx, 1);
- if (cfg.default_model && sameRef(cfg.default_model, ref)) {
+ if (cfg.default_model && sameModelRef(cfg.default_model, ref)) {
delete cfg.default_model;
}
- if (cfg.vision_model && sameRef(cfg.vision_model, ref)) {
+ if (cfg.vision_model && sameModelRef(cfg.vision_model, ref)) {
delete cfg.vision_model;
}
await saveProjectConfig(root, projectId, cfg);
@@ -790,7 +790,7 @@ export async function removeModel(
}
/** Whether two paired references name the same entry. Both halves must match — the pair is the config's unique key. */
-function sameRef(a: ModelRef, b: ModelRef): boolean {
+export function sameModelRef(a: ModelRef, b: ModelRef): boolean {
return a.provider === b.provider && a.model_id === b.model_id;
}
diff --git a/packages/core/src/trace/resume.ts b/packages/core/src/trace/resume.ts
index 7cf4fd2e..d5d4294c 100644
--- a/packages/core/src/trace/resume.ts
+++ b/packages/core/src/trace/resume.ts
@@ -49,7 +49,12 @@ import type {
TokenUsagePayload,
ToolCallPayload,
} from "../omnimessage/index.js";
-import { buildContextSummaryText, extractSummary } from "../omnimessage/markers/index.js";
+import {
+ buildContextSummaryText,
+ extractSummary,
+ MARKER_TAGS,
+ startsWithMarker,
+} from "../omnimessage/markers/index.js";
/** Replay result: all the state needed to resume a Session. */
export interface ResumeResult {
@@ -65,6 +70,12 @@ export interface ResumeResult {
contextClosed: boolean;
/** Compaction closure in summarize mode: the reconstructed `[context_summary]` summary, prepended to the next run's input. */
pendingSummary?: OmniMessage;
+ /**
+ * The `[context_summary]` this file's context opened with, while no turn has completed on
+ * it: its first pending input (so it is in `carryOver` too). A model switch away from such
+ * a context writes it at the head of the next file (see ContextEngine's `openingSummary`).
+ */
+ openingSummary?: OmniMessage;
/** Session-level cumulative Token carry-over (the session value from the last token_usage). */
sessionTokens: TokenCounts;
/** The request.total from the last token_usage (context usage figure). */
@@ -259,6 +270,20 @@ function isCompactionEnd(msg: OmniMessage): msg is OmniMessage<CompactionEndPayl
return isEventMessage(msg) && (msg.payload as { type?: string }).type === "compaction_end";
}
+/**
+ * Whether the message is a `[context_summary]` user text: the first input of a context a
+ * summarize compaction opened. Read off the text because no field marks the record (see the
+ * markers module's consumption boundary for why that is safe here).
+ */
+function isContextSummary(msg: OmniMessage): boolean {
+ const p = msg.payload as { type?: string; role?: string; text?: string };
+ return (
+ p.type === "text" &&
+ p.role === "user" &&
+ startsWithMarker(p.text ?? "", MARKER_TAGS.contextSummary)
+ );
+}
+
function toolCallOutputId(msg: OmniMessage): string | null {
const p = msg.payload as { type?: string; tool_call_id?: string };
return p.type === "tool_call_output" ? (p.tool_call_id ?? null) : null;
@@ -466,10 +491,13 @@ export function resumeTrace(messages: OmniMessage[]): ResumeResult {
pairingBackfill.push(placeholderFor(id));
}
+ const opening = sessionTurns === 0 ? pending[0] : undefined;
+
return {
history,
carryOver: [...pending, ...pairingBackfill],
contextClosed: false,
+ ...(opening !== undefined && isContextSummary(opening) ? { openingSummary: opening } : {}),
sessionTokens,
lastRequestTotal,
sessionTurns,
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index 2e57d13a..5e3ae2b3 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -16,13 +16,14 @@ import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import type { OmniMessage } from "../src/omnimessage/index.js";
-import type { OpenContextOptions, OpenedContext, SystemConfig } from "../src/index.js";
+import type { ModelRef, OpenContextOptions, OpenedContext, SystemConfig } from "../src/index.js";
import {
agentsMdPath,
hooksDir,
projectConfigPath,
skillsDir,
systemConfigPath,
+ tracesDir,
} from "../src/state/paths.js";
import {
MODEL_CATALOG,
@@ -30,13 +31,16 @@ import {
createAgent,
DEFAULT_AGENT_ID,
DEFAULT_PROJECT_ID,
+ imageUrlMessage,
installSkill,
loadProjectConfig,
+ ModelSwitchRefusedError,
saveProjectConfig,
setVaultEntry,
userText,
} from "../src/index.js";
import { metaMaxTokens } from "../src/agent.js";
+import { findLatestTraceFile, readTrace } from "../src/trace/index.js";
import { mapThinkingLevel } from "../src/llm/index.js";
import { stubProviderKeys } from "./provider-keys.js";
import type {
@@ -602,6 +606,28 @@ describe("run_subagent spawning follows the PARENT session (never the Project de
}
});
+ it("inherits the parent's CURRENT model: a child spawned after an in-session switch runs on the switched-to model", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-inherit-switched");
+ await fs.mkdir(ws, { recursive: true });
+ const parent = await agent.createSession({ workspaceDir: ws });
+ const runner = lastSpawnedRunner();
+ try {
+ expect(parent.provider).toBe("deepseek");
+ for await (const _ of parent.switchModel({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ })) {
+ // a never-run Session switches silently
+ }
+ const child = await spawnedChildMeta(runner, {});
+ expect(child.provider).toBe("anthropic");
+ expect(child.model_id).toBe("claude-sonnet-4-6");
+ } finally {
+ parent.dispose();
+ }
+ });
+
it("forwards the run input as an origin-tagged user message, after session_meta and before any model output", async () => {
const agent = await createAgent();
const ws = path.join(tmpRoot, "ws-input-forward");
@@ -1234,6 +1260,265 @@ describe("Agent model contexts are assembled from the Agent State on disk, at ev
});
});
+describe("Session.switchModel on a real Agent (the composition layer's half)", () => {
+ const TARGET = { provider: "anthropic", modelId: "claude-sonnet-4-6" };
+ /** Runs a switch to its end, keeping what it streamed. */
+ async function drain(gen: AsyncGenerator<OmniMessage, unknown>): Promise<OmniMessage[]> {
+ const all: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) return all;
+ all.push(res.value);
+ }
+ }
+ const lastBuilt = () =>
+ capturedLLMConfigs.list.at(-1) as
+ { modelId?: string; apiKey?: string; baseUrl?: string; systemPrompt?: string } | undefined;
+ const modelIdOf = (session: { metaMessage: OmniMessage }): string =>
+ (session.metaMessage.payload as { model_id: string }).model_id;
+ /**
+ * The opener the Session's engine calls for its next context, and the Session's way of
+ * telling it which model a switch is moving to: `open()` is a plain rotation, `open(target)`
+ * a switch's — what `Session.switchModel` sets around the engine's rotation.
+ */
+ function openerOf(session: unknown): (target?: ModelRef) => Promise<OpenedContext> {
+ const internals = session as {
+ switchTarget: ModelRef | undefined;
+ engine: { deps: { openNextContext: (opts: OpenContextOptions) => Promise<OpenedContext> } };
+ };
+ return (target) => {
+ internals.switchTarget = target;
+ return internals.engine.deps
+ .openNextContext({ emit: () => {} })
+ .finally(() => (internals.switchTarget = undefined));
+ };
+ }
+
+ it("a Session that never ran is re-assembled on the target: nothing recorded, and its first run opens on it", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-switch-fresh");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ expect(session.provider).toBe("deepseek");
+ expect(session.modelId).toBe("deepseek-flash");
+
+ const events = await drain(session.switchModel(TARGET));
+
+ expect(events).toEqual([]);
+ expect(session.provider).toBe("anthropic");
+ expect(session.modelId).toBe("claude-sonnet-4-6");
+ // The re-assembled first context's meta names the target, and its prompt was assembled
+ // for it (the Environment section names the model the context runs on).
+ expect(modelIdOf(session)).toBe("claude-sonnet-4-6");
+ expect((session.metaMessage.payload as { system_prompt: string }).system_prompt).toContain(
+ "claude-sonnet-4-6",
+ );
+ // Nothing was recorded: an untouched Session must not look resumable.
+ expect(await agent.latestSessionId()).toBeNull();
+
+ // The first run builds the target's LLM and opens the Trace with the target's meta.
+ await bootstrapped(session);
+ expect(lastBuilt()!.modelId).toBe("claude-sonnet-4-6");
+ const located = await findLatestTraceFile(
+ tracesDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID),
+ session.sessionId,
+ );
+ const head = (await readTrace(located!.path))[0]!;
+ expect(head.type).toBe("session_meta");
+ expect((head.payload as { model_id: string }).model_id).toBe("claude-sonnet-4-6");
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("refuses a target the Project config does not have, before anything happens", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-switch-unknown");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ // A typed refusal, so a host maps it to its own code without reading the message.
+ const refusal = await drain(
+ session.switchModel({ provider: "custom", modelId: "nobody-configured-this" }),
+ ).catch((e: unknown) => e);
+ expect(refusal).toBeInstanceOf(ModelSwitchRefusedError);
+ expect(refusal).toMatchObject({
+ reason: "model_not_configured",
+ message: expect.stringMatching(/is not in the Project config/) as unknown,
+ });
+ expect(session.modelId).toBe("deepseek-flash");
+ expect(await agent.latestSessionId()).toBeNull();
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("resolves the target against the Project config on disk, not the Agent's load-time snapshot", async () => {
+ const agent = await createAgent();
+ // Configured after the Agent loaded: the snapshot does not know it, the disk does.
+ await addModel(tmpRoot, DEFAULT_PROJECT_ID, {
+ provider: "myproxy",
+ model_id: "claude-sonnet-4-6",
+ base_url: "https://proxy.invalid/v1",
+ api_key: "proxy-key",
+ });
+ expect(agent.projectConfig.models.some((m) => m.provider === "myproxy")).toBe(false);
+ const ws = path.join(tmpRoot, "ws-switch-disk");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ await drain(session.switchModel({ provider: "myproxy", modelId: "claude-sonnet-4-6" }));
+ expect(session.provider).toBe("myproxy");
+ // The validation constructed the target's bare LLM on the target entry's own credentials.
+ expect(lastBuilt()).toMatchObject({
+ modelId: "claude-sonnet-4-6",
+ apiKey: "proxy-key",
+ baseUrl: "https://proxy.invalid/v1",
+ });
+ // The Agent's own copy of the config followed the read, so a child spawned from here —
+ // which inherits the model just switched to — finds it configured.
+ expect(agent.projectConfig.models.some((m) => m.provider === "myproxy")).toBe(true);
+ const runner = (capturedEnvServices.list.at(-1) as EnvironmentServices).subagentRunner!;
+ const child = await runner.spawn({});
+ try {
+ const gen = child.run({ messages: [userText("noop")] });
+ const first = await gen.next();
+ await gen.return(null);
+ expect((first.value as OmniMessage).payload).toMatchObject({
+ provider: "myproxy",
+ model_id: "claude-sonnet-4-6",
+ });
+ } finally {
+ child.dispose();
+ }
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("explicit creation credentials stay with the creation model: a context on another model runs on that entry's own", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-switch-creds");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({
+ workspaceDir: ws,
+ apiKey: "creation-key",
+ baseUrl: "https://creation.invalid/v1",
+ });
+ try {
+ // The creation model's bare LLM (the credential check) carries the override.
+ expect(lastBuilt()).toMatchObject({
+ modelId: "deepseek-flash",
+ apiKey: "creation-key",
+ baseUrl: "https://creation.invalid/v1",
+ });
+ await drain(session.switchModel(TARGET));
+ // The target's validation LLM, and the session LLM the first run builds, do not: the
+ // key was handed in for one vendor and must never be sent to another.
+ expect(lastBuilt()!.modelId).toBe("claude-sonnet-4-6");
+ expect(lastBuilt()!.apiKey).toBeUndefined();
+ expect(lastBuilt()!.baseUrl).toBeUndefined();
+ await bootstrapped(session);
+ expect(lastBuilt()!.modelId).toBe("claude-sonnet-4-6");
+ expect(lastBuilt()!.apiKey).toBeUndefined();
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("a rotation keeps the running model unless the opener is told the switch target", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-switch-rotation");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ await bootstrapped(session);
+ const open = openerOf(session);
+ // The fold the engine asks for a steering message's images: `null` means the running
+ // context's model takes them as they are.
+ const { foldInputImages } = (
+ session as unknown as {
+ engine: {
+ deps: { foldInputImages: (messages: OmniMessage[]) => Promise<OmniMessage[] | null> };
+ };
+ }
+ ).engine.deps;
+ const picture = [imageUrlMessage("https://images.invalid/pic.png")];
+
+ // A plain rotation: the same model, re-assembled, with the vision answer its entry gives.
+ const kept = await open();
+ expect((kept.sessionMeta!.payload as { model_id: string }).model_id).toBe("deepseek-flash");
+ const deepseek = agent.projectConfig.models.find((m) => m.model_id === "deepseek-flash")!;
+ expect((await foldInputImages(picture)) === null).toBe(deepseek.vision !== false);
+ expect(lastBuilt()!.modelId).toBe("deepseek-flash");
+ expect(session.modelId).toBe("deepseek-flash");
+
+ // A switch's rotation: the target, with its own vision answer and window-derived settings.
+ const switched = await open({ provider: "anthropic", model_id: "claude-sonnet-4-6" });
+ expect((switched.sessionMeta!.payload as { model_id: string }).model_id).toBe(
+ "claude-sonnet-4-6",
+ );
+ expect(await foldInputImages(picture)).toBeNull();
+ expect(lastBuilt()!.modelId).toBe("claude-sonnet-4-6");
+ expect(lastBuilt()!.systemPrompt).toContain("claude-sonnet-4-6");
+ // The Session's own answer follows the opened context.
+ expect(session.provider).toBe("anthropic");
+ expect(session.modelId).toBe("claude-sonnet-4-6");
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("an open that fails leaves the running context in place: the Environment is equipped for it again and the next rotation keeps its model", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-switch-open-fails");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ await bootstrapped(session);
+ const { environment } = session as unknown as {
+ environment: {
+ listTools(): Promise<unknown>;
+ reconfigure(update: { toolConfig: unknown }): void;
+ };
+ };
+ const open = openerOf(session);
+ const reconfigure = vi.spyOn(environment, "reconfigure");
+ const target = { provider: "anthropic", model_id: "claude-sonnet-4-6" };
+
+ // A plain rotation first, so the running context is one this opener equipped.
+ await open();
+ const running = reconfigure.mock.calls[0]![0].toolConfig;
+
+ // The target assembles, the Environment is equipped for it, and then its toolset cannot
+ // be resolved: the open fails.
+ vi.spyOn(environment, "listTools").mockRejectedValueOnce(new Error("toolset unavailable"));
+ await expect(open(target)).rejects.toThrow("toolset unavailable");
+ expect(reconfigure).toHaveBeenCalledTimes(3);
+ expect(reconfigure.mock.calls[1]![0].toolConfig).not.toBe(running);
+ expect(reconfigure.mock.calls[2]![0].toolConfig).toBe(running);
+ expect(session.modelId).toBe("deepseek-flash");
+
+ // The running context is still the one a rotation re-assembles.
+ const kept = await open();
+ expect((kept.sessionMeta!.payload as { model_id: string }).model_id).toBe("deepseek-flash");
+ expect(lastBuilt()!.modelId).toBe("deepseek-flash");
+
+ // A target gone from the config by the time the context opens is a failure of the
+ // switch, not its typed refusal: the refusal is the validation's answer, before any event.
+ const gone = await open({ provider: "custom", model_id: "nobody-configured-this" }).catch(
+ (e: unknown) => e,
+ );
+ expect(gone).toBeInstanceOf(Error);
+ expect(gone).not.toBeInstanceOf(ModelSwitchRefusedError);
+ expect((gone as Error).message).toMatch(/is not in the Project config/);
+ } finally {
+ session.dispose();
+ }
+ });
+});
+
describe("Agent.createSession credential rule (a keyless gateway row never borrows a vendor key)", () => {
it("refuses a keyless gateway preset before any client exists, even with OPENAI_API_KEY set", async () => {
// stubProviderKeys has set OPENAI_API_KEY and friends: the pre-rule behaviour was to hand
diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.ts
index baf7c26c..3f0f1ee3 100644
--- a/packages/core/test/compaction.test.ts
+++ b/packages/core/test/compaction.test.ts
@@ -1982,11 +1982,15 @@ describe("context compaction", () => {
// must build it and fold the conversation: the caller has already been told compaction is
// available, so a silent no-op leaves it waiting for a banner that never arrives.
const resumedLLM = new ScriptedLLM([{ messages: [assistantText("[summary]s[/summary]")] }]);
- const newContextLLM = new ScriptedLLM([]);
+ const newContextLLM = new ScriptedLLM([{ messages: [assistantText("on it")] }]);
const written: OmniMessage[] = [];
const session = new Session({
meta: metaMessage.payload,
- bootstrap: async () => ({ llm: resumedLLM }),
+ // Like the real opener, the bootstrap publishes the context's toolset record.
+ bootstrap: async ({ emit }) => {
+ emit(toolListReady([]));
+ return { llm: resumedLLM };
+ },
environment: fakeEnvironment,
trace: {
write: async (msg) => {
@@ -2012,6 +2016,15 @@ describe("context compaction", () => {
// Compaction reset the context, and the reason stays specific rather than falling back to
// "nothing said yet".
expect(session.compactability()).toBe("just_compacted");
+ // The engine was built for this call rather than by a run, so the context's first-run
+ // records were still owed to the Trace. They describe the context the compaction closed,
+ // and are dropped with it: the one toolset record is the one the rotation writes at the
+ // head of the next context's file, and the next run writes no second one behind its input.
+ await collect(session.run([userText("next")], { approve: allowAll }));
+ const types = payloadTypes(written);
+ const input = written.findIndex((m) => (m.payload as { text?: string }).text === "next");
+ expect(types.filter((t) => t === "tool_list_ready")).toHaveLength(1);
+ expect(types.indexOf("tool_list_ready")).toBeLessThan(input);
session.dispose();
});
diff --git a/packages/core/test/model-switch.test.ts b/packages/core/test/model-switch.test.ts
new file mode 100644
index 00000000..8b8ede69
--- /dev/null
+++ b/packages/core/test/model-switch.test.ts
@@ -0,0 +1,1466 @@
+/**
+ * In-session model switch (`Session.switchModel` over `ContextEngine.switchContext`).
+ *
+ * A switch is a compaction whose new context opens on the model the user picked: the running
+ * context is summarized on the model it is on — always summarize, whatever the configured mode —
+ * and the next context opens on the target. The compaction is an ordinary `manual` one: no
+ * OmniMessage field or reason names the switch. The model lives only in the new context's
+ * `session_meta`, and the switch opens that context's Trace file at once — its head is the
+ * durable record — and streams the meta last, so a Session rebuilt from the latest file alone
+ * runs on the new model, carrying the summary. The engine knows nothing of models: the Session
+ * tells its opener which one the next context opens on.
+ *
+ * Covered here with fake collaborators: the two engine shapes (completed turns: a summarize
+ * compaction; none — a context a compaction just closed, or an open one that has not answered
+ * yet: simply replaced, with no event pair), switching twice before typing, the never-run
+ * Session, the same-model and refused-target no-ops, the failure paths that keep the old
+ * model, and — for every switch path — the file the switch opened and what `resumeTrace`
+ * recovers from it. The real Agent's composition (Project config, credentials, spawn
+ * inheritance) is in agent.test.ts; `agent.resumeSession` on a switched Session's Trace is in
+ * resume.test.ts.
+ */
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ assistantText,
+ imageUrlMessage,
+ mcpConnectBegin,
+ sessionMeta,
+ tokenUsage,
+ toolCall,
+ toolListReady,
+ userText,
+} from "../src/omnimessage/index.js";
+import type {
+ CompactionBeginPayload,
+ CompactionEndPayload,
+ OmniMessage,
+ SessionMetaPayload,
+ TextPayload,
+} from "../src/omnimessage/index.js";
+import type {
+ ApproveFn,
+ EnvironmentInterface,
+ GenerativeModelParameters,
+ LLMInterface,
+ LLMOutcome,
+} from "../src/interfaces/index.js";
+import type { CompactionSettings } from "../src/engine/context-engine.js";
+import { ModelSwitchRefusedError, Session } from "../src/session.js";
+import type {
+ ModelSwitchSupport,
+ SessionConfig,
+ SessionOpenContextOptions,
+} from "../src/session.js";
+import type { ModelRef } from "../src/state/project-config.js";
+import { Writer, readTrace, resumeTrace } from "../src/trace/index.js";
+
+// ---------------------------------------------------------------------------
+// Test fixtures
+// ---------------------------------------------------------------------------
+
+interface ScriptedResponse {
+ messages: OmniMessage[];
+ outcome?: LLMOutcome;
+}
+
+/** Fake LLM that responds according to a script, recording each input it receives. */
+class ScriptedLLM implements LLMInterface {
+ calls: OmniMessage[][] = [];
+ constructor(
+ private readonly responses: ScriptedResponse[],
+ readonly label = "llm",
+ ) {}
+
+ async *streamGenerate(
+ params: GenerativeModelParameters,
+ ): AsyncGenerator<OmniMessage, LLMOutcome> {
+ this.calls.push(params.newMessages);
+ const next = this.responses.shift();
+ if (!next) {
+ return { status: "retryable", errorMessage: `${this.label}: no scripted response` };
+ }
+ for (const msg of next.messages) yield msg;
+ return next.outcome ?? { status: "completed" };
+ }
+}
+
+/** Fake Environment that never runs real commands. */
+const fakeEnvironment: EnvironmentInterface = {
+ async listTools() {
+ return [];
+ },
+ async *executeTool() {
+ throw new Error("no tool runs in these scenarios");
+ },
+ toolPermission() {
+ return "rw";
+ },
+};
+
+const allowAll: ApproveFn = async () => "allow";
+
+const usage = (requestTotal: number, sessionTotal: number): OmniMessage =>
+ tokenUsage(
+ { cache_read: 0, cache_write: 0, output: 0, total: sessionTotal },
+ { cache_read: 0, cache_write: 0, output: 0, total: requestTotal },
+ );
+
+const settings = (over: Partial<CompactionSettings> = {}): CompactionSettings => ({
+ // High enough that no scenario compacts on its own unless it says so.
+ maxContextLength: 1000,
+ maxSessionTurns: -1,
+ mode: "summarize",
+ prompt: "COMPACT NOW",
+ ...over,
+});
+
+const MODEL_A: ModelRef = { provider: "custom", model_id: "model-a" };
+const MODEL_B: ModelRef = { provider: "custom", model_id: "model-b" };
+const MODEL_C: ModelRef = { provider: "custom", model_id: "model-c" };
+const SESSION_ID = "sess_switch";
+
+const metaFor = (model: ModelRef): SessionMetaPayload => ({
+ session_id: SESSION_ID,
+ provider: model.provider,
+ model_id: model.model_id,
+ model_context_window: 200000,
+ system_prompt: "sp",
+ agent_state: "/tmp/state",
+ workspace: "/tmp/ws",
+});
+
+const SUMMARY_REPLY = "[summary]the distilled summary[/summary]";
+const SUMMARY_TEXT = "[context_summary]\nthe distilled summary\n[/context_summary]";
+
+async function collect<R>(gen: AsyncGenerator<OmniMessage, R>): Promise<OmniMessage[]> {
+ const all: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) return all;
+ all.push(res.value);
+ }
+}
+
+/** Like collect, but also captures the generator's return value. */
+async function collectWithReturn<R>(
+ gen: AsyncGenerator<OmniMessage, R>,
+): Promise<{ all: OmniMessage[]; result: R }> {
+ const all: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) return { all, result: res.value };
+ all.push(res.value);
+ }
+}
+
+type CompactionEventPayload = CompactionBeginPayload | CompactionEndPayload;
+
+const compactionEvents = (msgs: OmniMessage[]): CompactionEventPayload[] =>
+ msgs
+ .filter((m) => {
+ const t = (m.payload as { type?: string }).type ?? "";
+ return t === "compaction_begin" || t === "compaction_end";
+ })
+ .map((m) => m.payload as CompactionEventPayload);
+
+/** Each record's kind: the payload type, or `session_meta` for the file head (whose payload carries no type). */
+const payloadTypes = (msgs: OmniMessage[]): (string | undefined)[] =>
+ msgs.map((m) =>
+ m.type === "session_meta" ? "session_meta" : (m.payload as { type?: string }).type,
+ );
+
+const textOf = (m: OmniMessage): string => (m.payload as TextPayload).text;
+
+/** The user-side texts of `msgs`, in order — what a replayed history sends as the user's side. */
+const userTexts = (msgs: OmniMessage[]): string[] =>
+ msgs
+ .filter((m) => {
+ const p = m.payload as { type?: string; role?: string };
+ return p.type === "text" && p.role === "user";
+ })
+ .map(textOf);
+
+/** Each message's payload type (`image_url` is what a text-only model must never receive). */
+const payloadTypeList = (msgs: OmniMessage[]): string[] =>
+ msgs.map((m) => (m.payload as { type: string }).type);
+
+/** The model a `session_meta` record names, as a reference. */
+const modelOf = (m: OmniMessage): ModelRef => {
+ const p = m.payload as SessionMetaPayload;
+ return { provider: p.provider, model_id: p.model_id };
+};
+
+/** The switch stream's last record is the new context's session_meta, naming `model`. */
+const expectEndsWithMetaOn = (all: OmniMessage[], model: ModelRef): void => {
+ const last = all.at(-1)!;
+ expect(last.type).toBe("session_meta");
+ expect(modelOf(last)).toEqual(model);
+};
+
+const hasMeta = (msgs: OmniMessage[]): boolean => msgs.some((m) => m.type === "session_meta");
+
+/**
+ * The composition layer's half, as fakes that record what they were asked: which model each
+ * opened context was asked for, which targets were validated, and which ref a never-run
+ * Session's first context was re-assembled on. `llms` maps a model id to the LLM the next
+ * context on that model gets (a plain compaction keeps the model, so it takes the current one's
+ * next object); `vision` maps a model id to its vision answer (default: views images). Like the
+ * real opener, each opened context publishes its toolset record.
+ */
+interface Harness {
+ opens: (ModelRef | undefined)[];
+ validated: ModelRef[];
+ reassembled: ModelRef[];
+ written: OmniMessage[];
+ trace: Writer;
+ session: Session;
+ /** The Session's Trace files, in index order. */
+ files: () => Promise<string[]>;
+}
+
+function harness(
+ traces: string,
+ args: {
+ llmA: LLMInterface;
+ /** LLM objects for contexts opened on each model id, taken in order. */
+ llms: Record<string, LLMInterface[]>;
+ compaction?: CompactionSettings;
+ vision?: Record<string, boolean>;
+ modelHasVision?: boolean;
+ /** Runs the Session without a Trace sink (an embedder that records nothing). */
+ sinkless?: boolean;
+ extras?: Partial<SessionConfig>;
+ },
+): Harness {
+ const opens: (ModelRef | undefined)[] = [];
+ const validated: ModelRef[] = [];
+ const reassembled: ModelRef[] = [];
+ const written: OmniMessage[] = [];
+ let current = MODEL_A;
+ const trace = new Writer({ tracesDir: traces, sessionId: SESSION_ID });
+ const sink = {
+ write: async (msg: OmniMessage) => {
+ written.push(msg);
+ await trace.write(msg);
+ },
+ rotate: () => trace.rotate(),
+ currentPath: () => trace.currentPath(),
+ };
+ const modelSwitch: ModelSwitchSupport = {
+ async validate(ref) {
+ validated.push(ref);
+ if (ref.model_id === "unknown") {
+ throw new Error(`Model is not in the Project config: ${ref.model_id}`);
+ }
+ },
+ async reassembleInitialContext(ref) {
+ reassembled.push(ref);
+ current = ref;
+ return {
+ sessionMeta: sessionMeta(metaFor(ref)),
+ ...(args.vision?.[ref.model_id] !== undefined
+ ? { modelHasVision: args.vision[ref.model_id]! }
+ : {}),
+ };
+ },
+ };
+ const session = new Session({
+ meta: metaFor(MODEL_A),
+ bootstrap: async () => ({ llm: args.llmA }),
+ environment: fakeEnvironment,
+ ...(args.sinkless ? {} : { trace: sink }),
+ compaction: args.compaction ?? settings(),
+ openNextContext: ({ modelRef, emit }: SessionOpenContextOptions) => {
+ opens.push(modelRef);
+ const model = modelRef ?? current;
+ const llm = args.llms[model.model_id]?.shift();
+ if (!llm) throw new Error(`no LLM prepared for a context on ${model.model_id}`);
+ // Like the real opener, the running model moves only once the context is open.
+ current = model;
+ emit(toolListReady([]));
+ return {
+ llm,
+ sessionMeta: sessionMeta(metaFor(model)),
+ ...(args.vision?.[model.model_id] !== undefined
+ ? { modelHasVision: args.vision[model.model_id]! }
+ : {}),
+ };
+ },
+ modelSwitch,
+ imagesDir: join(traces, "scratch"),
+ modelHasVision: args.modelHasVision ?? true,
+ ...args.extras,
+ });
+ const files = async (): Promise<string[]> =>
+ (await readdir(dirname(trace.currentPath()))).filter((f) => f.endsWith(".jsonl")).sort();
+ return { opens, validated, reassembled, written, trace, session, files };
+}
+
+const switchTo = (session: Session, model: ModelRef, signal?: AbortSignal) =>
+ session.switchModel({
+ provider: model.provider,
+ modelId: model.model_id,
+ ...(signal ? { signal } : {}),
+ });
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe("in-session model switch", () => {
+ let traces: string;
+ const sessions: Session[] = [];
+
+ beforeEach(async () => {
+ traces = await mkdtemp(join(tmpdir(), "penguin-model-switch-"));
+ });
+
+ afterEach(async () => {
+ for (const s of sessions.splice(0)) s.dispose();
+ await rm(traces, { recursive: true, force: true });
+ });
+
+ it("after completed turns: a plain manual summarize on the old model whatever the configured mode, then the target's file opens at once, headed by the session_meta the stream carries last", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmB = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 130)] }],
+ "B",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [llmB] },
+ // The user's rule: a switch summarizes even when the Agent compacts by discarding.
+ compaction: settings({ mode: "discard" }),
+ });
+ sessions.push(h.session);
+ const oldPath = h.trace.currentPath();
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ expect(h.session.compactability()).toBe("ok");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ // The target was validated before anything else happened.
+ expect(h.validated).toEqual([MODEL_B]);
+ // An ordinary manual summarize pair: nothing on it names a model.
+ expect(compactionEvents(all)).toEqual([
+ { type: "compaction_begin", reason: "manual", mode: "summarize", context: 50, turns: 1 },
+ {
+ type: "compaction_end",
+ reason: "manual",
+ mode: "summarize",
+ status: "completed",
+ attempt: 1,
+ },
+ ]);
+ // The compaction request went to the OLD model; the opener was told the target.
+ expect(llmA.calls).toHaveLength(2);
+ expect(llmA.calls[1]!.map(textOf)).toEqual(["COMPACT NOW"]);
+ expect(h.opens).toEqual([MODEL_B]);
+ // The stream: the pair, the opener's toolset record, and last the new context's meta.
+ expect(payloadTypes(all).slice(-3)).toEqual([
+ "compaction_end",
+ "tool_list_ready",
+ "session_meta",
+ ]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ // The Session answers with the new model from here.
+ expect(h.session.provider).toBe(MODEL_B.provider);
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+ expect(modelOf(h.session.metaMessage)).toEqual(MODEL_B);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ // Durability: the closed file ends with the plain pair, and the new file already exists —
+ // the target's meta, its toolset, the summary as the context's first input.
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`, `${SESSION_ID}_002.jsonl`]);
+ expect((await readTrace(oldPath)).at(-1)!.payload).toMatchObject({
+ type: "compaction_end",
+ reason: "manual",
+ status: "completed",
+ });
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ // A Session rebuilt from that file alone: no history, the summary pending, on B.
+ const resumed = resumeTrace(opened);
+ expect(resumed.contextClosed).toBe(false);
+ expect(resumed.history).toEqual([]);
+ expect(resumed.sessionTurns).toBe(0);
+ expect(resumed.carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+ expect(modelOf(resumed.meta!)).toEqual(MODEL_B);
+
+ // The summary leads the new model's first input, and is not written a second time.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls).toHaveLength(1);
+ expect(llmB.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const fresh = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(fresh).slice(0, 4)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ ]);
+ expect(textOf(fresh[3]!)).toBe("task two");
+ expect(fresh.filter((m) => m.type === "model_msg" && textOf(m) === SUMMARY_TEXT)).toHaveLength(
+ 1,
+ );
+ });
+
+ it("right after a compaction: no request and no pair; the rotation is performed on the target and the held summary heads the new file", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ // Over the threshold at the task's wrap-up round: the Agent's own compaction fires.
+ { messages: [assistantText("answer one"), usage(150, 150)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(160, 310)] },
+ ],
+ "A",
+ );
+ // The context the compaction opens stays on A; the switch then moves off it unused.
+ const llmA2 = new ScriptedLLM([], "A2");
+ const llmB = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 330)] }],
+ "B",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_A.model_id]: [llmA2], [MODEL_B.model_id]: [llmB] },
+ compaction: settings({ maxContextLength: 100 }),
+ });
+ sessions.push(h.session);
+ const oldPath = h.trace.currentPath();
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ expect(h.opens).toEqual([undefined]);
+ expect(h.session.compactability()).toBe("just_compacted");
+ const closedBefore = await readTrace(oldPath);
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ // No model was asked anything, and nothing was compacted: the summary is already held and
+ // the closing pair is already on the closed file.
+ expect(llmA.calls).toHaveLength(2);
+ expect(llmA2.calls).toHaveLength(0);
+ expect(compactionEvents(all)).toEqual([]);
+ expect(payloadTypes(all)).toEqual(["tool_list_ready", "session_meta"]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ expect(h.opens).toEqual([undefined, MODEL_B]);
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ // Durability: the closed file is untouched; the context the compaction had opened on A was
+ // never written and never exists on disk; the new file is B's, headed by its meta, with the
+ // summary as its first input.
+ expect(await readTrace(oldPath)).toEqual(closedBefore);
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`, `${SESSION_ID}_002.jsonl`]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ const resumed = resumeTrace(opened);
+ expect(resumed.contextClosed).toBe(false);
+ expect(resumed.carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const fresh = await readTrace(h.trace.currentPath());
+ expect(fresh.filter((m) => m.type === "model_msg" && textOf(m) === SUMMARY_TEXT)).toHaveLength(
+ 1,
+ );
+ });
+
+ it("right after a discard compaction: no pair; the new file holds meta and tools only", async () => {
+ const llmA = new ScriptedLLM(
+ [{ messages: [assistantText("answer one"), usage(150, 150)] }],
+ "A",
+ );
+ const llmA2 = new ScriptedLLM([], "A2");
+ const llmB = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 170)] }],
+ "B",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_A.model_id]: [llmA2], [MODEL_B.model_id]: [llmB] },
+ compaction: settings({ maxContextLength: 100, mode: "discard" }),
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ expect(h.session.compactability()).toBe("just_compacted");
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`, `${SESSION_ID}_002.jsonl`]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ const resumed = resumeTrace(opened);
+ expect(resumed.contextClosed).toBe(false);
+ expect(resumed.carryOver).toEqual([]);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls[0]!.map(textOf)).toEqual(["task two"]);
+ });
+
+ it("an open context whose first request never completed is simply replaced: no pair, its file left as it was, and its text carry-over follows to the new model in memory", async () => {
+ const llmA = new ScriptedLLM([], "A");
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 20)] }], "B");
+ const h = harness(traces, { llmA, llms: { [MODEL_B.model_id]: [llmB] } });
+ sessions.push(h.session);
+ const oldPath = h.trace.currentPath();
+
+ // Aborted before the request went out: the input is written and held as carry-over.
+ const controller = new AbortController();
+ controller.abort();
+ await collect(h.session.run([userText("task one")], { signal: controller.signal }));
+ expect(llmA.calls).toHaveLength(0);
+ expect(h.session.compactability()).toBe("empty");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ // Nothing to summarize: no request and no event pair — the target's records, then its meta.
+ expect(compactionEvents(all)).toEqual([]);
+ expect(payloadTypes(all)).toEqual(["tool_list_ready", "session_meta"]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ expect(llmA.calls).toHaveLength(0);
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+
+ // Durability: the file being left stays as it was; the new file opens at once on B. The
+ // carry-over is not written to it — carry-over may hold synthetic messages, which are never
+ // persisted — so a resume of that file has nothing pending (the documented gap: the user
+ // re-sends the message).
+ expect(payloadTypes(await readTrace(oldPath))).toEqual(["session_meta", "text", "abort"]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(resumeTrace(opened).carryOver).toEqual([]);
+
+ // In-process the carry-over rides.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls[0]!.map(textOf)).toEqual(["task one", "task two"]);
+ });
+
+ it("a just-compacted context the user already wrote on is replaced the same way: the summary written there heads the new file too, the aborted prompt rides in memory only", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(150, 150)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(160, 310)] },
+ ],
+ "A",
+ );
+ const llmA2 = new ScriptedLLM([], "A2");
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 330)] }], "B");
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_A.model_id]: [llmA2], [MODEL_B.model_id]: [llmB] },
+ compaction: settings({ maxContextLength: 100 }),
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ // The next run rotates the Trace (summary + prompt land in the new file) and then never
+ // issues its request: the context on A2 is open, with the summary as carry-over.
+ const controller = new AbortController();
+ controller.abort();
+ await collect(h.session.run([userText("task two")], { signal: controller.signal }));
+ const openPath = h.trace.currentPath();
+ expect(payloadTypes(await readTrace(openPath))).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ "abort",
+ ]);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ expect(llmA2.calls).toHaveLength(0);
+
+ // The file being left is as the stopped run left it. The new file holds meta, tools — and
+ // the summary again: it is the one record of the conversation before the compaction, and a
+ // resume of this file must not replay a history without it. The aborted prompt is not
+ // written (carry-over may hold synthetic messages; the user re-sends it).
+ const left = await readTrace(openPath);
+ expect(payloadTypes(left)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ "abort",
+ ]);
+ expect(textOf(left[2]!)).toBe(SUMMARY_TEXT);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(h.trace.currentPath()).not.toBe(openPath);
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ expect(resumeTrace(opened).carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+
+ await collect(h.session.run([userText("task three")], { approve: allowAll }));
+ // In-process the aborted input is carried as-is (it never reached a request), the summary
+ // once — the file's copy is not re-sent.
+ expect(llmB.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two", "task three"]);
+ expect(userTexts(resumeTrace(await readTrace(h.trace.currentPath())).history)).toEqual([
+ SUMMARY_TEXT,
+ "task three",
+ ]);
+ });
+
+ it("switching twice before typing: the second switch replaces the untouched context without a pair, and the summary heads the third file", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmB = new ScriptedLLM([], "B");
+ const llmC = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 130)] }],
+ "C",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [llmB], [MODEL_C.model_id]: [llmC] },
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+ const bPath = h.trace.currentPath();
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_C));
+
+ expect(result).toBe("completed");
+ // B's context holds the summary as an input but no completed turn: nothing to summarize,
+ // so no request and no pair — the stream is the target's records and its meta.
+ expect(compactionEvents(all)).toEqual([]);
+ expect(payloadTypes(all)).toEqual(["tool_list_ready", "session_meta"]);
+ expectEndsWithMetaOn(all, MODEL_C);
+ expect(llmB.calls).toHaveLength(0);
+ expect(h.opens).toEqual([MODEL_B, MODEL_C]);
+ expect(h.session.modelId).toBe(MODEL_C.model_id);
+
+ expect(await h.files()).toEqual([
+ `${SESSION_ID}_001.jsonl`,
+ `${SESSION_ID}_002.jsonl`,
+ `${SESSION_ID}_003.jsonl`,
+ ]);
+ expect(payloadTypes(await readTrace(bPath))).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ ]);
+ // C's file opens with the summary B's context had opened with — the only record of the
+ // conversation on A — so a resume of it lands on C with the summary pending, as a resume
+ // of B's file would have.
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_C);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ expect(resumeTrace(opened).carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ // Live, the summary is sent once; on disk it is written once — the run does not re-write it.
+ expect(llmC.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const latest = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(latest).slice(0, 4)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ ]);
+ // Any later restart replays C's history from this file, the summary at its head.
+ expect(userTexts(resumeTrace(latest).history)).toEqual([SUMMARY_TEXT, "task two"]);
+ });
+
+ it("without a Trace sink a second switch before typing reads the same, and the summary is still sent once", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmC = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 130)] }],
+ "C",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [new ScriptedLLM([], "B")], [MODEL_C.model_id]: [llmC] },
+ sinkless: true,
+ });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_C));
+
+ expect(result).toBe("completed");
+ expect(payloadTypes(all)).toEqual(["tool_list_ready", "session_meta"]);
+ expectEndsWithMetaOn(all, MODEL_C);
+ expect(h.written).toEqual([]);
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmC.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ });
+
+ it("a failed first request on the new model, then another switch: the summary the failed context opened with heads the next file, while the model gets the [turn_aborted] flatten", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmB = new ScriptedLLM(
+ [{ messages: [], outcome: { status: "fatal", errorMessage: "B rejected the request" } }],
+ "B",
+ );
+ const llmC = new ScriptedLLM(
+ [{ messages: [assistantText("answer three"), usage(20, 130)] }],
+ "C",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [llmB], [MODEL_C.model_id]: [llmC] },
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+ // B's first request fails outright: no completed turn, the summary and the prompt become a
+ // `[turn_aborted]` flatten in the carry-over, where nothing marks the summary any more.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_C));
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ expectEndsWithMetaOn(all, MODEL_C);
+
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_C);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+
+ await collect(h.session.run([userText("task three")], { approve: allowAll }));
+ // The live request carries the flatten (the summary inside it) — request assembly after a
+ // failed request is unchanged — and the file carries the summary as a plain record.
+ const live = llmC.calls[0]!.map(textOf);
+ expect(live).toHaveLength(2);
+ expect(live[0]).toMatch(/^\[turn_aborted\]/);
+ expect(live[0]).toContain(SUMMARY_TEXT);
+ expect(live[1]).toBe("task three");
+ expect(userTexts(resumeTrace(await readTrace(h.trace.currentPath())).history)).toEqual([
+ SUMMARY_TEXT,
+ "task three",
+ ]);
+ });
+
+ it("compact, a failed request on the new context, then a switch: the summary heads the target's file the same way", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ // The context the compaction opened, still on A: its first request fails.
+ const llmA2 = new ScriptedLLM(
+ [{ messages: [], outcome: { status: "fatal", errorMessage: "A rejected the request" } }],
+ "A2",
+ );
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 130)] }], "B");
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_A.model_id]: [llmA2], [MODEL_B.model_id]: [llmB] },
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(h.session.compact());
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmA2.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const failedPath = h.trace.currentPath();
+ const failed = await readTrace(failedPath);
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ expectEndsWithMetaOn(all, MODEL_B);
+ // The switch adds nothing to the file it leaves.
+ expect(await readTrace(failedPath)).toEqual(failed);
+
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ expect(resumeTrace(opened).carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+
+ await collect(h.session.run([userText("task three")], { approve: allowAll }));
+ expect(userTexts(resumeTrace(await readTrace(h.trace.currentPath())).history)).toEqual([
+ SUMMARY_TEXT,
+ "task three",
+ ]);
+ });
+
+ it("a summary written mid-Task is kept the same way: the Task's next request fails, a switch follows, and the summary heads the target's file", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ // A tool turn over the threshold: the compaction runs mid-Task, the tool output folded
+ // into its request.
+ { messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "c1" }), usage(150, 150)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(160, 310)] },
+ ],
+ "A",
+ );
+ // The context the compaction opened, still on A: the Task's continuation request fails.
+ const llmA2 = new ScriptedLLM(
+ [{ messages: [], outcome: { status: "fatal", errorMessage: "A rejected the request" } }],
+ "A2",
+ );
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 330)] }], "B");
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_A.model_id]: [llmA2], [MODEL_B.model_id]: [llmB] },
+ compaction: settings({ maxContextLength: 100 }),
+ });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ // The Task itself sent the summary, as the new context's first input.
+ expect(llmA2.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT]);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ expectEndsWithMetaOn(all, MODEL_B);
+
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ expect(resumeTrace(opened).carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+ });
+
+ it("a switch carries text alone: a Prompt stopped before its bootstrap rides on without its image", async () => {
+ const llmA = new ScriptedLLM([], "A");
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 20)] }], "B");
+ // Both models take images: what is left behind is left behind by the switch, not by a fold.
+ const h = harness(traces, { llmA, llms: { [MODEL_B.model_id]: [llmB] } });
+ sessions.push(h.session);
+
+ // Stopped during the first connect: the Session itself holds the input, as sent.
+ const controller = new AbortController();
+ controller.abort();
+ await collect(
+ h.session.run([userText("look"), imageUrlMessage("https://images.invalid/pic.png")], {
+ signal: controller.signal,
+ }),
+ );
+ await collect(switchTo(h.session, MODEL_B));
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmB.calls[0]!.map((m) => [payloadTypeList([m])[0], textOf(m)])).toEqual([
+ ["text", "look"],
+ ["text", "task two"],
+ ]);
+ });
+
+ it("a switch carries text alone: input the engine held as-is (stopped before its request) rides on without its image", async () => {
+ // A's first request fails, so the context is open with no completed turn and the engine
+ // exists; the next run is stopped before its request goes out and its input — image
+ // included — is held unchanged as the engine's carry-over.
+ const llmA = new ScriptedLLM(
+ [{ messages: [], outcome: { status: "fatal", errorMessage: "A is down" } }],
+ "A",
+ );
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 20)] }], "B");
+ const h = harness(traces, { llmA, llms: { [MODEL_B.model_id]: [llmB] } });
+ sessions.push(h.session);
+
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ expect(llmA.calls).toHaveLength(1);
+ const controller = new AbortController();
+ controller.abort();
+ await collect(
+ h.session.run([userText("look"), imageUrlMessage("https://images.invalid/pic.png")], {
+ signal: controller.signal,
+ }),
+ );
+ expect(llmA.calls).toHaveLength(1);
+
+ const { all } = await collectWithReturn(switchTo(h.session, MODEL_B));
+ expect(compactionEvents(all)).toEqual([]);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ const first = llmB.calls[0]!;
+ // The pending text reached the target — the failed task's and the stopped one's — and
+ // nothing but text did.
+ expect(new Set(payloadTypeList(first))).toEqual(new Set(["text"]));
+ const texts = first.map(textOf);
+ expect(texts.some((t) => t.includes("task one"))).toBe(true);
+ expect(texts).toContain("look");
+ expect(texts.at(-1)).toBe("task two");
+ });
+
+ it("a Session that never ran is re-assembled on the target: no events, nothing written, and its first run opens on it", async () => {
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 20)] }], "B");
+ const h = harness(traces, { llmA: llmB, llms: {}, vision: { [MODEL_B.model_id]: false } });
+ sessions.push(h.session);
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ expect(all).toEqual([]);
+ expect(h.written).toEqual([]);
+ expect(h.validated).toEqual([MODEL_B]);
+ expect(h.reassembled).toEqual([MODEL_B]);
+ expect(h.opens).toEqual([]);
+ expect(h.session.provider).toBe(MODEL_B.provider);
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+ expect(h.session.compactability()).toBe("empty");
+
+ // The first run writes the re-assembled context's meta at the file's head, and the
+ // re-assembled model's vision answer governs the Prompt fold from the start.
+ await collect(
+ h.session.run([userText("look"), imageUrlMessage("https://images.invalid/pic.png")], {
+ approve: allowAll,
+ }),
+ );
+ const file = await readTrace(h.trace.currentPath());
+ expect(file[0]!.type).toBe("session_meta");
+ expect(modelOf(file[0]!)).toEqual(MODEL_B);
+ expect(llmB.calls[0]!.map((m) => (m.payload as { type: string }).type)).toEqual(["text"]);
+ expect(textOf(llmB.calls[0]![0]!)).toContain(
+ "[attached image: https://images.invalid/pic.png]",
+ );
+ });
+
+ it("the same model completes with no events", async () => {
+ const llmA = new ScriptedLLM([{ messages: [assistantText("answer one"), usage(50, 50)] }], "A");
+ const h = harness(traces, { llmA, llms: {} });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_A));
+
+ expect(result).toBe("completed");
+ expect(all).toEqual([]);
+ expect(llmA.calls).toHaveLength(1);
+ expect(h.session.compactability()).toBe("ok");
+ });
+
+ it("a target that fails validation is refused before anything is produced", async () => {
+ const llmA = new ScriptedLLM([{ messages: [assistantText("answer one"), usage(50, 50)] }], "A");
+ const h = harness(traces, { llmA, llms: {} });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ const writtenBefore = h.written.length;
+
+ await expect(
+ collect(switchTo(h.session, { provider: "custom", model_id: "unknown" })),
+ ).rejects.toThrow(/is not in the Project config/);
+
+ expect(llmA.calls).toHaveLength(1);
+ expect(h.written).toHaveLength(writtenBefore);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ });
+
+ it("a compaction that fails keeps the old model: the end is a plain manual end, no session_meta follows, nothing rotates, and the next run stays put", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [], outcome: { status: "fatal", errorCode: "auth", errorMessage: "nope" } },
+ { messages: [assistantText("answer two"), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmB = new ScriptedLLM([], "B");
+ const h = harness(traces, { llmA, llms: { [MODEL_B.model_id]: [llmB] } });
+ sessions.push(h.session);
+ const oldPath = h.trace.currentPath();
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("fatal");
+ expect(compactionEvents(all)[1]).toEqual({
+ type: "compaction_end",
+ reason: "manual",
+ mode: "summarize",
+ status: "fatal",
+ attempt: 1,
+ error_code: "auth",
+ error_message: "nope",
+ });
+ expect(hasMeta(all)).toBe(false);
+ expect(h.opens).toEqual([]);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ expect(h.session.compactability()).toBe("ok");
+ // A resume of the file reads an open context on A: the failed end closes nothing.
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`]);
+ const resumed = resumeTrace(await readTrace(oldPath));
+ expect(resumed.contextClosed).toBe(false);
+ expect(modelOf(resumed.meta!)).toEqual(MODEL_A);
+
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmA.calls).toHaveLength(3);
+ expect(llmB.calls).toHaveLength(0);
+ expect(h.trace.currentPath()).toBe(oldPath);
+ });
+
+ it("an aborted compaction request keeps the old model too, and the compaction after it opens on that model", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [], outcome: { status: "aborted" } },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: {
+ [MODEL_A.model_id]: [new ScriptedLLM([], "A2")],
+ [MODEL_B.model_id]: [new ScriptedLLM([], "B")],
+ },
+ });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("aborted");
+ expect(compactionEvents(all)[1]).toMatchObject({ reason: "manual", status: "aborted" });
+ expect(hasMeta(all)).toBe(false);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ expect(h.opens).toEqual([]);
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`]);
+
+ // The target was the stopped switch's alone: an ordinary compaction names no model to its
+ // opener, and the next context opens on the model the Session is on.
+ await collect(h.session.compact());
+ expect(h.opens).toEqual([undefined]);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ });
+
+ it("a target whose context cannot be opened after the compaction completed fails the switch: the Session stays on its model, and so does the next compaction", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(70, 180)] },
+ ],
+ "A",
+ );
+ // Nothing is prepared for a context on B: the opener throws.
+ const h = harness(traces, { llmA, llms: { [MODEL_A.model_id]: [new ScriptedLLM([], "A2")] } });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+
+ await expect(collect(switchTo(h.session, MODEL_B))).rejects.toThrow(
+ /no LLM prepared for a context on model-b/,
+ );
+ expect(h.opens).toEqual([MODEL_B]);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ expect(await h.files()).toEqual([`${SESSION_ID}_001.jsonl`]);
+
+ // The failed switch's target is not held: the next rotation keeps the running model.
+ await collect(h.session.compact());
+ expect(h.opens).toEqual([MODEL_B, undefined]);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ });
+
+ it("a target whose context cannot be opened leaves a just-compacted context as it was: the summary still pending, nothing written", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmA2 = new ScriptedLLM([{ messages: [assistantText("answer two"), usage(20, 130)] }]);
+ const h = harness(traces, { llmA, llms: { [MODEL_A.model_id]: [llmA2] } });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(h.session.compact());
+ const writtenBefore = h.written.length;
+
+ await expect(collect(switchTo(h.session, MODEL_B))).rejects.toThrow(
+ /no LLM prepared for a context on model-b/,
+ );
+ expect(h.written).toHaveLength(writtenBefore);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ // The context the compaction opened is still the one that runs next, opening with the summary.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmA2.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened).slice(0, 4)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ ]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_A);
+ });
+
+ it("a target whose context cannot be opened leaves an unanswered context as it was: nothing written, a restart finds its summary pending, and a retry carries it on", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmC = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 130)] }], "C");
+ const llms: Record<string, LLMInterface[]> = { [MODEL_B.model_id]: [new ScriptedLLM([], "B")] };
+ const h = harness(traces, { llmA, llms });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+ const bPath = h.trace.currentPath();
+ const before = await readTrace(bPath);
+
+ // B's context holds the summary and no completed turn, in a file of its own. Nothing is
+ // written before C's context is open, and the open fails.
+ await expect(collect(switchTo(h.session, MODEL_C))).rejects.toThrow(
+ /no LLM prepared for a context on model-c/,
+ );
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+ expect(h.trace.currentPath()).toBe(bPath);
+ const left = await readTrace(bPath);
+ expect(left).toEqual(before);
+ expect(payloadTypes(left)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ // A restart now reads the same open context on B, the summary it opened with pending: the
+ // switch is lost, the conversation before it is not.
+ const resumed = resumeTrace(left);
+ expect(resumed.contextClosed).toBe(false);
+ expect(modelOf(resumed.meta!)).toEqual(MODEL_B);
+ expect(resumed.carryOver.map(textOf)).toEqual([SUMMARY_TEXT]);
+ expect(resumed.openingSummary).toBe(resumed.carryOver[0]);
+
+ // In-process nothing was lost either: the retry carries the summary to C's file.
+ llms[MODEL_C.model_id] = [llmC];
+ const { result } = await collectWithReturn(switchTo(h.session, MODEL_C));
+ expect(result).toBe("completed");
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_C);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmC.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ });
+
+ it("the vision answer follows the model: a switch to a model without vision folds the next Prompt's images", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ const llmB = new ScriptedLLM(
+ [{ messages: [assistantText("answer two"), usage(20, 130)] }],
+ "B",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [llmB] },
+ vision: { [MODEL_B.model_id]: false },
+ });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+
+ await collect(
+ h.session.run([userText("look"), imageUrlMessage("https://images.invalid/pic.png")], {
+ approve: allowAll,
+ }),
+ );
+
+ const types = llmB.calls[0]!.map((m) => (m.payload as { type: string }).type);
+ expect(types).toEqual(["text", "text"]);
+ expect(textOf(llmB.calls[0]![1]!)).toContain(
+ "[attached image: https://images.invalid/pic.png]",
+ );
+ });
+
+ it("the engine's own fold follows the model too: a steering message's image reaches a model without vision as a path line", async () => {
+ const llmA = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(50, 50)] },
+ { messages: [assistantText(SUMMARY_REPLY), usage(60, 110)] },
+ ],
+ "A",
+ );
+ // B is steered while it answers: the message is delivered between its two requests.
+ let steer = (): void => {};
+ const llmB = new (class extends ScriptedLLM {
+ override async *streamGenerate(
+ params: GenerativeModelParameters,
+ ): AsyncGenerator<OmniMessage, LLMOutcome> {
+ steer();
+ steer = () => {};
+ return yield* super.streamGenerate(params);
+ }
+ })(
+ [
+ { messages: [assistantText("working"), usage(20, 130)] },
+ { messages: [assistantText("seen"), usage(30, 160)] },
+ ],
+ "B",
+ );
+ const h = harness(traces, {
+ llmA,
+ llms: { [MODEL_B.model_id]: [llmB] },
+ vision: { [MODEL_B.model_id]: false },
+ });
+ sessions.push(h.session);
+ await collect(h.session.run([userText("task one")], { approve: allowAll }));
+ await collect(switchTo(h.session, MODEL_B));
+
+ steer = () => {
+ h.session.steer([
+ userText("look at this"),
+ imageUrlMessage("https://images.invalid/pic.png"),
+ ]);
+ };
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+
+ expect(llmB.calls).toHaveLength(2);
+ const delivered = llmB.calls[1]!;
+ expect(payloadTypeList(delivered)).toEqual(["text"]);
+ expect(textOf(delivered[0]!)).toContain("look at this");
+ expect(textOf(delivered[0]!)).toContain("[attached image: https://images.invalid/pic.png]");
+ });
+
+ it("a Session resumed after a restart builds its engine first, so the switch compacts the real conversation — and the first-run records of the context it leaves never reach the target's file", async () => {
+ // What agent.resumeSession derives from a Trace: real history, no engine yet.
+ const resumedLLM = new ScriptedLLM(
+ [{ messages: [assistantText(SUMMARY_REPLY), usage(90, 90)] }],
+ "A",
+ );
+ const llmB = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 110)] }], "B");
+ const h = harness(traces, {
+ llmA: resumedLLM,
+ llms: { [MODEL_B.model_id]: [llmB] },
+ extras: {
+ // Like the real opener, the bootstrap publishes the context's toolset record.
+ bootstrap: async ({ emit }) => {
+ emit(toolListReady([]));
+ return { llm: resumedLLM };
+ },
+ metaAlreadyWritten: true,
+ initialEngineState: { sessionTurns: 3, lastRequestTotal: 80 },
+ },
+ });
+ sessions.push(h.session);
+ expect(h.session.compactability()).toBe("ok");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+
+ expect(result).toBe("completed");
+ expect(resumedLLM.calls).toHaveLength(1);
+ expect(compactionEvents(all)[0]).toMatchObject({ reason: "manual", turns: 3 });
+ // The bootstrap streams as it does for a run: the stream opens on its toolset record.
+ expect(payloadTypes(all)[0]).toBe("tool_list_ready");
+ expectEndsWithMetaOn(all, MODEL_B);
+ expect(h.session.modelId).toBe(MODEL_B.model_id);
+
+ // The engine was built for the switch, not by a run, so that record was still owed to the
+ // Trace: it is dropped with the context it describes. The target's file holds the target's
+ // own and no other.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened).slice(0, 5)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ "text",
+ "request_begin",
+ ]);
+ expect(payloadTypes(opened).filter((t) => t === "tool_list_ready")).toHaveLength(1);
+ });
+
+ it("a Session resumed just compacted switches without a pair: its bootstrap streams, then the target's records and meta, and the held summary heads the new file", async () => {
+ const held = userText(SUMMARY_TEXT);
+ const h = harness(traces, {
+ llmA: new ScriptedLLM([], "A"),
+ llms: { [MODEL_B.model_id]: [new ScriptedLLM([], "B")] },
+ extras: {
+ bootstrap: async ({ emit }) => {
+ emit(toolListReady([]));
+ return { llm: new ScriptedLLM([], "A") };
+ },
+ metaAlreadyWritten: true,
+ // What a resume of a file closed by a completed compaction hands the engine.
+ initialEngineState: {
+ pendingSummary: held,
+ pendingTraceRotation: true,
+ fromCompaction: true,
+ sessionTurns: 0,
+ },
+ },
+ });
+ sessions.push(h.session);
+ expect(h.session.compactability()).toBe("just_compacted");
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_B));
+ expect(result).toBe("completed");
+ // The closing pair is on the closed file: none here. The bootstrap's toolset record, the
+ // target's own, then its meta.
+ expect(payloadTypes(all)).toEqual(["tool_list_ready", "tool_list_ready", "session_meta"]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(modelOf(opened[0]!)).toEqual(MODEL_B);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+ });
+
+ it("a switch stopped while a resumed Session is still opening the context it leaves ends aborted, with the stopped bootstrap on the stream", async () => {
+ const controller = new AbortController();
+ let connecting!: () => void;
+ const started = new Promise<void>((resolve) => (connecting = resolve));
+ const h = harness(traces, {
+ llmA: new ScriptedLLM([], "A"),
+ llms: { [MODEL_B.model_id]: [new ScriptedLLM([], "B")] },
+ extras: {
+ // A connect that never finishes: only the stop ends it.
+ bootstrap: ({ emit }) => {
+ emit(mcpConnectBegin(["slow"]));
+ connecting();
+ return new Promise(() => {});
+ },
+ metaAlreadyWritten: true,
+ initialEngineState: {
+ pendingSummary: userText(SUMMARY_TEXT),
+ pendingTraceRotation: true,
+ fromCompaction: true,
+ sessionTurns: 0,
+ },
+ },
+ });
+ sessions.push(h.session);
+
+ const switching = collectWithReturn(switchTo(h.session, MODEL_B, controller.signal));
+ await started;
+ // Let the Session take the connect's first record before the stop lands.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ controller.abort();
+ const { all, result } = await switching;
+
+ expect(result).toBe("aborted");
+ expect(payloadTypes(all)).toEqual(["mcp_connect_begin", "mcp_connect_end", "abort"]);
+ expect(h.session.modelId).toBe(MODEL_A.model_id);
+ expect(h.opens).toEqual([]);
+ });
+
+ it("a Session resumed from a file a switch opened carries the summary on through another switch", async () => {
+ // What a resume of the file a switch opened hands the engine: the summary as pending
+ // input, named as the one the context opened with.
+ const resumed = resumeTrace([
+ sessionMeta(metaFor(MODEL_A)),
+ toolListReady([]),
+ userText(SUMMARY_TEXT),
+ ]);
+ expect(resumed.openingSummary).toBe(resumed.carryOver[0]);
+ const llmC = new ScriptedLLM([{ messages: [assistantText("answer"), usage(20, 20)] }], "C");
+ const h = harness(traces, {
+ llmA: new ScriptedLLM([], "A"),
+ llms: { [MODEL_C.model_id]: [llmC] },
+ extras: {
+ metaAlreadyWritten: true,
+ initialEngineState: {
+ carryOver: resumed.carryOver,
+ openingSummary: resumed.openingSummary!,
+ fromCompaction: true,
+ sessionTurns: resumed.sessionTurns,
+ },
+ },
+ });
+ sessions.push(h.session);
+
+ const { all, result } = await collectWithReturn(switchTo(h.session, MODEL_C));
+ expect(result).toBe("completed");
+ expect(compactionEvents(all)).toEqual([]);
+ const opened = await readTrace(h.trace.currentPath());
+ expect(payloadTypes(opened)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect(textOf(opened[2]!)).toBe(SUMMARY_TEXT);
+
+ // Sent once, and never written a second time.
+ await collect(h.session.run([userText("task two")], { approve: allowAll }));
+ expect(llmC.calls[0]!.map(textOf)).toEqual([SUMMARY_TEXT, "task two"]);
+ const latest = await readTrace(h.trace.currentPath());
+ expect(latest.filter((m) => m.type === "model_msg" && textOf(m) === SUMMARY_TEXT)).toHaveLength(
+ 1,
+ );
+ });
+
+ it("switching is refused when compaction is not configured and there is a context to close", async () => {
+ const llmA = new ScriptedLLM([{ messages: [assistantText("answer one"), usage(50, 50)] }], "A");
+ const written: OmniMessage[] = [];
+ const session = new Session({
+ meta: metaFor(MODEL_A),
+ bootstrap: async () => ({ llm: llmA }),
+ environment: fakeEnvironment,
+ trace: { write: async (m) => void written.push(m) },
+ modelSwitch: {
+ validate: async () => {},
+ reassembleInitialContext: async () => ({}),
+ },
+ imagesDir: join(traces, "scratch"),
+ modelHasVision: true,
+ });
+ sessions.push(session);
+ await collect(session.run([userText("task one")], { approve: allowAll }));
+
+ const refusal = await collect(switchTo(session, MODEL_B)).catch((e: unknown) => e);
+ expect(refusal).toBeInstanceOf(ModelSwitchRefusedError);
+ expect(refusal).toMatchObject({
+ reason: "compaction_not_configured",
+ message: expect.stringMatching(/Context compaction is not configured/) as unknown,
+ });
+ expect(session.modelId).toBe(MODEL_A.model_id);
+ });
+
+ it("switching is unavailable without the composition layer's support", async () => {
+ const session = new Session({
+ meta: metaFor(MODEL_A),
+ bootstrap: async () => ({ llm: new ScriptedLLM([], "A") }),
+ environment: fakeEnvironment,
+ imagesDir: join(traces, "scratch"),
+ modelHasVision: true,
+ });
+ sessions.push(session);
+ const refusal = await collect(switchTo(session, MODEL_B)).catch((e: unknown) => e);
+ expect(refusal).toBeInstanceOf(ModelSwitchRefusedError);
+ expect(refusal).toMatchObject({
+ reason: "model_unavailable",
+ message: expect.stringMatching(/Switching the model is not available/) as unknown,
+ });
+ });
+});
diff --git a/packages/core/test/prompt-cache-invariants.test.ts b/packages/core/test/prompt-cache-invariants.test.ts
index 99b72e0e..d2e7744d 100644
--- a/packages/core/test/prompt-cache-invariants.test.ts
+++ b/packages/core/test/prompt-cache-invariants.test.ts
@@ -278,4 +278,105 @@ describe("prompt-cache invariants of request assembly", () => {
expect(appended.content[1]!.text).toBe(COMPACTION_PROMPT);
expect(configFingerprint(first.requests[1]!)).toBe(configFingerprint(first.requests[0]!));
});
+
+ it("a model switch's compaction request extends the turn it follows on the old model; the new model's first request is a new line carrying its id", async () => {
+ const target = "claude-opus-4-7";
+ const first = recordingModel(modelConfig(), [
+ { text: "First answer.", promptTokens: 20 },
+ { text: "[summary]the distilled summary[/summary]", promptTokens: 30 },
+ ]);
+ const second = recordingModel(modelConfig({ modelId: target }), [
+ { text: "Carried on from the summary." },
+ ]);
+ // The opener decides which model the next context runs on; the engine only closes the
+ // running context and opens the next.
+ const engine = new ContextEngine({
+ llm: first.model,
+ environment: fakeEnvironment,
+ compaction: compactionSettings(),
+ openNextContext: () => ({ llm: second.model }),
+ });
+
+ await collect(engine.run([userText("task one")], { approve: allowAll }));
+ await collect(engine.switchContext());
+ await collect(engine.run([userText("task two")], { approve: allowAll }));
+
+ // The switch's compaction request is an ordinary compaction request to the OLD model: same
+ // model id, tools, system prompt and parameters, one appended user turn (the prompt alone —
+ // a Task-boundary switch has nothing pending to fold in).
+ expect(first.requests).toHaveLength(2);
+ const reasons = diagnoseSeries(first.requests);
+ expect(reasons, formatDiagnostics(first.requests, reasons)).toEqual([{ type: "none" }]);
+ expect(configFingerprint(first.requests[1]!)).toBe(configFingerprint(first.requests[0]!));
+ expect(first.requests[1]!.wireConfig.model).toBe("claude-sonnet-4-6");
+ const appended = wireMessage(first.requests[1]!, -1);
+ expect(appended.role).toBe("user");
+ expect(blockTypes(appended)).toEqual(["text"]);
+ expect(appended.content[0]!.text).toBe(COMPACTION_PROMPT);
+ // The new model's first request is a new cache line by definition — a prompt cache is
+ // scoped to one model — and it opens with the summary the old model wrote.
+ expect(second.requests).toHaveLength(1);
+ expect(second.requests[0]!.wireConfig.model).toBe(target);
+ const opening = wireMessage(second.requests[0]!, 0);
+ expect(opening.role).toBe("user");
+ expect(blockTypes(opening)).toEqual(["text", "text"]);
+ expect(opening.content[0]!.text).toContain("[context_summary]");
+ expect(opening.content[1]!.text).toBe("task two");
+ });
+
+ it("a model switch that does not complete leaves the old model's line intact: every later request still extends the one before it", async () => {
+ const first = recordingModel(modelConfig(), [
+ { text: "First answer.", promptTokens: 20 },
+ // The first switch's compaction request is cut by the user: nothing is committed.
+ { text: "[summary]half a summ", promptTokens: 30, outcome: "abort-after-text" },
+ // The second switch's summary is complete, and the target's context cannot be opened.
+ { text: "[summary]the distilled summary[/summary]", promptTokens: 30 },
+ { text: "Second answer.", promptTokens: 40 },
+ ]);
+ const engine = new ContextEngine({
+ llm: first.model,
+ environment: fakeEnvironment,
+ compaction: compactionSettings(),
+ openNextContext: () => {
+ throw new Error("the target's context could not be assembled");
+ },
+ });
+
+ await collect(engine.run([userText("task one")], { approve: allowAll }));
+ const controller = new AbortController();
+ const switching = engine.switchContext(controller.signal);
+ let aborted: string | undefined;
+ for (;;) {
+ const res = await switching.next();
+ if (res.done) {
+ aborted = res.value;
+ break;
+ }
+ const payload = res.value.payload as { type?: string; event_type?: string };
+ if (payload.type === "partial_text" && payload.event_type === "delta") controller.abort();
+ }
+ await expect(collect(engine.switchContext())).rejects.toThrow(
+ "the target's context could not be assembled",
+ );
+ await collect(engine.run([userText("task two")], { approve: allowAll }));
+
+ expect(aborted).toBe("aborted");
+ // Four requests, all to the OLD model with one config: the aborted compaction request, the
+ // same request again (nothing was committed, so nothing moved), and the next turn on top of
+ // the committed compaction exchange. Nothing about either target reached the wire.
+ expect(first.requests).toHaveLength(4);
+ const reasons = diagnoseSeries(first.requests);
+ expect(reasons, formatDiagnostics(first.requests, reasons)).toEqual([
+ { type: "none" },
+ { type: "none" },
+ { type: "none" },
+ ]);
+ expect(new Set(first.requests.map(configFingerprint)).size).toBe(1);
+ expect(first.requests.map((r) => r.wireConfig.model)).toEqual(
+ Array(4).fill("claude-sonnet-4-6"),
+ );
+ const last = wireMessage(first.requests[3]!, -1);
+ expect(last.role).toBe("user");
+ expect(last.content.at(-1)!.text).toBe("task two");
+ });
});
diff --git a/packages/core/test/prompt-cache-lifecycle.test.ts b/packages/core/test/prompt-cache-lifecycle.test.ts
index 16c61fcf..42d905ba 100644
--- a/packages/core/test/prompt-cache-lifecycle.test.ts
+++ b/packages/core/test/prompt-cache-lifecycle.test.ts
@@ -23,7 +23,7 @@ import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Environment } from "../src/environment/index.js";
import { Session } from "../src/index.js";
-import { buildScheduledMessage, userText } from "../src/omnimessage/index.js";
+import { buildScheduledMessage, sessionMeta, userText } from "../src/omnimessage/index.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
import { Writer, readTrace, resumeTrace } from "../src/trace/index.js";
import type { CompactionSettings, TraceSink } from "../src/engine/context-engine.js";
@@ -77,6 +77,7 @@ interface SessionSpec {
openNextContext?: ConstructorParameters<typeof Session>[0]["openNextContext"];
initialEngineState?: ConstructorParameters<typeof Session>[0]["initialEngineState"];
metaAlreadyWritten?: boolean;
+ modelSwitch?: ConstructorParameters<typeof Session>[0]["modelSwitch"];
}
function makeSession(spec: SessionSpec): Session {
@@ -91,6 +92,7 @@ function makeSession(spec: SessionSpec): Session {
...(spec.openNextContext ? { openNextContext: spec.openNextContext } : {}),
...(spec.initialEngineState ? { initialEngineState: spec.initialEngineState } : {}),
...(spec.metaAlreadyWritten ? { metaAlreadyWritten: true } : {}),
+ ...(spec.modelSwitch ? { modelSwitch: spec.modelSwitch } : {}),
});
cleanups.push(() => session.dispose());
return session;
@@ -485,6 +487,33 @@ describe("the prompt cache across a Session's lifecycle", () => {
// And the new context hits from its second request onwards.
expect(usages[4]!.cache_read_input_tokens, report).toBe(prefixTokens(order[3]!));
});
+
+ it("a model switch reads 0 on the new model — a new cache line — then hits from there", async () => {
+ const { order, onRequest } = ordering();
+ await driveModelSwitch(onRequest);
+
+ expect(order.map((request) => request.label)).toEqual([
+ "model A",
+ "model A",
+ "model A",
+ "model B",
+ "model B",
+ ]);
+ const usages = replay(order);
+ const reason =
+ "the context reopened on another model: a prompt cache is scoped to one model, so " +
+ "nothing the new model's first request sends is addressable";
+ expectHits(order, usages, new Map([[3, reason]]));
+ const report = formatCacheReport(order, usages);
+ // The switch's compaction request runs on the old model with the old config: it reads the
+ // turn it follows in full, exactly as a threshold compaction's does.
+ expect(usages[2]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));
+ // What the switch costs: the new model's first request, read in full and written anew.
+ expect(usages[3]!.cache_read_input_tokens, report).toBe(0);
+ expect(usages[3]!.cache_creation_input_tokens, report).toBe(prefixTokens(order[3]!));
+ // And the new model hits from its second request onwards.
+ expect(usages[4]!.cache_read_input_tokens, report).toBe(prefixTokens(order[3]!));
+ });
});
// ---------------------------------------------------------------------------
@@ -534,6 +563,47 @@ async function driveCompaction(onRequest: (request: RecordedRequest) => void): P
await collect(session.run([userText("task four")], { approve: allowAll }));
}
+/** The model the switch scenario moves to. */
+const SWITCH_TARGET = { provider: "anthropic", model_id: "claude-opus-4-7" };
+
+/** One Session, two tasks on one model, an in-session switch, two tasks on the other. */
+async function driveModelSwitch(onRequest: (request: RecordedRequest) => void): Promise<void> {
+ const first = recordingModel(
+ modelConfig(),
+ [
+ { text: "First answer." },
+ { text: "Second answer." },
+ { text: "[summary]the distilled summary[/summary]" },
+ ],
+ { label: "model A", onRequest },
+ );
+ const second = recordingModel(
+ modelConfig({ modelId: SWITCH_TARGET.model_id }),
+ [{ text: "Carried on from the summary." }, { text: "And on from there." }],
+ { label: "model B", onRequest },
+ );
+ const session = makeSession({
+ llm: first.model,
+ environment: fakeEnvironment,
+ compaction: compactionSettings(),
+ openNextContext: () => ({
+ llm: second.model,
+ sessionMeta: sessionMeta({ ...META, ...SWITCH_TARGET }),
+ }),
+ modelSwitch: {
+ validate: async () => {},
+ reassembleInitialContext: async () => ({}),
+ },
+ });
+ await collect(session.run([userText("task one")], { approve: allowAll }));
+ await collect(session.run([userText("task two")], { approve: allowAll }));
+ await collect(
+ session.switchModel({ provider: SWITCH_TARGET.provider, modelId: SWITCH_TARGET.model_id }),
+ );
+ await collect(session.run([userText("task three")], { approve: allowAll }));
+ await collect(session.run([userText("task four")], { approve: allowAll }));
+}
+
/**
* A runner whose every spawn hands back the one prepared child Session, origin-tagged as the
* contract requires. Enough of the composition layer to put a real child Session's requests on
diff --git a/packages/core/test/replay.test.ts b/packages/core/test/replay.test.ts
index 7e2bb657..5181ce5b 100644
--- a/packages/core/test/replay.test.ts
+++ b/packages/core/test/replay.test.ts
@@ -297,6 +297,32 @@ describe("resumeTrace", () => {
expect(result.pendingSummary).toBeUndefined();
});
+ it("an open context names the summary it opened with until a turn completes on it", () => {
+ const summary = "[context_summary]\nthe gist\n[/context_summary]";
+ const unanswered = resumeTrace([
+ meta(),
+ userText(summary),
+ userText("and now?"),
+ requestBegin(),
+ requestEnd("aborted"),
+ ]);
+ expect(textsOf(unanswered.carryOver)).toEqual([summary, "and now?"]);
+ expect(unanswered.openingSummary).toBe(unanswered.carryOver[0]);
+
+ const answered = resumeTrace([
+ meta(),
+ userText(summary),
+ userText("and now?"),
+ requestBegin(),
+ assistantText("this"),
+ requestEnd("completed"),
+ tokenUsage(usage(10), usage(10)),
+ ]);
+ expect(answered.openingSummary).toBeUndefined();
+ // A first input that is no summary is not one the context opened with.
+ expect(resumeTrace([meta(), userText("hello")]).openingSummary).toBeUndefined();
+ });
+
it("drops failed compaction rounds via the generic rule (prompt not in history)", () => {
const result = resumeTrace([
meta(),
diff --git a/packages/core/test/resume.test.ts b/packages/core/test/resume.test.ts
index 1ba96c35..eb93e76c 100644
--- a/packages/core/test/resume.test.ts
+++ b/packages/core/test/resume.test.ts
@@ -23,11 +23,12 @@ import {
sessionMeta,
tokenUsage,
toolCall,
+ toolListReady,
userText,
} from "../src/omnimessage/index.js";
import type { OmniMessage, TokenCounts } from "../src/omnimessage/index.js";
import { GenerativeModel, groupHistoryToUniMessages } from "../src/llm/index.js";
-import { readTrace } from "../src/trace/index.js";
+import { findLatestTraceFile, readTrace } from "../src/trace/index.js";
import { agentsMdPath, tracesDir } from "../src/state/paths.js";
import { stubProviderKeys } from "./provider-keys.js";
@@ -538,3 +539,152 @@ describe("agent.resumeSession system prompt per context", () => {
}
});
});
+
+describe("agent.resumeSession after an in-session model switch", () => {
+ const SID = "session-2026-07-06-11-00-00-abcdef02";
+ // The default Project config ships both: the Session starts on ORIGINAL and switches to MODEL.
+ const ORIGINAL = { provider: "deepseek", model_id: "deepseek-flash" };
+ const SUMMARY = "[context_summary]\nthe story so far\n[/context_summary]";
+ const engineStateOf = (session: unknown) =>
+ (
+ session as {
+ engineDeps: {
+ initialState?: {
+ pendingSummary?: OmniMessage;
+ openingSummary?: OmniMessage;
+ carryOver?: OmniMessage[];
+ sessionTurns?: number;
+ pendingTraceRotation?: boolean;
+ };
+ };
+ }
+ ).engineDeps.initialState;
+ /** File 1: a context on `model` with one completed turn, closed by a completed summarize pair of `reason`. */
+ const closedFile = (
+ model: { provider: string; model_id: string },
+ reason: "manual" | "context",
+ ) => [
+ metaFor(SID, workspace, model),
+ userText("q1"),
+ requestBegin(),
+ assistantText("a1"),
+ requestEnd("completed"),
+ tokenUsage(usage(150), usage(150)),
+ compactionBegin({ reason, mode: "summarize", context: 150, turns: 1 }),
+ userText("COMPACT NOW"),
+ requestBegin(),
+ assistantText("[summary]the story so far[/summary]"),
+ requestEnd("completed"),
+ compactionEnd({ reason, mode: "summarize", status: "completed" }),
+ ];
+
+ it("resumes on the model of the eagerly opened file: history empty, the summary is the carry-over, on the switched-to model", async () => {
+ const agent = await createAgent({});
+ // The switch closed the original model's context with a plain manual pair, and opened the
+ // target's file at once: its session_meta, its toolset, the summary as its first input.
+ await writeTraceFile(tmpRoot, SID, closedFile(ORIGINAL, "manual"));
+ await writeTraceFile(
+ tmpRoot,
+ SID,
+ [metaFor(SID, workspace, MODEL), toolListReady([]), userText(SUMMARY)],
+ { index: "002" },
+ );
+
+ const session = await agent.resumeSession({ sessionId: SID });
+ try {
+ expect(session.provider).toBe(MODEL.provider);
+ expect(session.modelId).toBe(MODEL.model_id);
+ expect((session.metaMessage.payload as { model_id: string }).model_id).toBe(MODEL.model_id);
+ const state = engineStateOf(session);
+ expect(state?.pendingSummary).toBeUndefined();
+ expect(state?.pendingTraceRotation).toBe(false);
+ expect(state?.sessionTurns).toBe(0);
+ expect((state?.carryOver ?? []).map((m) => (m.payload as { text: string }).text)).toEqual([
+ SUMMARY,
+ ]);
+ // Already on the file, so pending input rather than a pending summary — and still named
+ // as the summary this context opened with.
+ expect(state?.openingSummary).toBe(state?.carryOver?.[0]);
+ expect(session.compactability()).toBe("just_compacted");
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("a switch made right after the restart carries the summary on: the next file opens with it", async () => {
+ const agent = await createAgent({});
+ await writeTraceFile(tmpRoot, SID, closedFile(ORIGINAL, "manual"));
+ const leaving = await writeTraceFile(
+ tmpRoot,
+ SID,
+ [metaFor(SID, workspace, MODEL), toolListReady([]), userText(SUMMARY)],
+ { index: "002" },
+ );
+ const kind = (m: OmniMessage): string | undefined =>
+ m.type === "session_meta" ? "session_meta" : (m.payload as { type?: string }).type;
+
+ const session = await agent.resumeSession({ sessionId: SID });
+ try {
+ // Nothing ran since the restart: the engine is built by the switch itself.
+ const streamed: OmniMessage[] = [];
+ for await (const msg of session.switchModel({
+ provider: ORIGINAL.provider,
+ modelId: ORIGINAL.model_id,
+ })) {
+ streamed.push(msg);
+ }
+ // The engine is built first, so the bootstrap of the context being left streams. That
+ // context holds the summary and no completed turn: nothing to summarize and no pair —
+ // the target's own records and its meta follow.
+ expect(streamed.map(kind)).toEqual(["tool_list_ready", "tool_list_ready", "session_meta"]);
+ expect(session.provider).toBe(ORIGINAL.provider);
+ expect(session.modelId).toBe(ORIGINAL.model_id);
+
+ const located = await findLatestTraceFile(
+ tracesDir(tmpRoot, "default_project", "default_agent"),
+ SID,
+ );
+ expect(located!.index).toBe(3);
+ const opened = await readTrace(located!.path);
+ expect(opened.map(kind)).toEqual(["session_meta", "tool_list_ready", "text"]);
+ expect((opened[0]!.payload as { model_id: string }).model_id).toBe(ORIGINAL.model_id);
+ expect((opened[2]!.payload as { text: string }).text).toBe(SUMMARY);
+ // Nothing was added to the file being left.
+ expect((await readTrace(leaving)).map(kind)).toEqual([
+ "session_meta",
+ "tool_list_ready",
+ "text",
+ ]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("a file a compaction opened, with no completed turn yet, answers just_compacted after a restart", async () => {
+ const agent = await createAgent({});
+ // An ordinary compaction, then the process died before the new context's first answer: the
+ // file past the first holds the summary and a prompt whose request never completed.
+ await writeTraceFile(tmpRoot, SID, closedFile(MODEL, "context"));
+ await writeTraceFile(
+ tmpRoot,
+ SID,
+ [
+ metaFor(SID, workspace),
+ toolListReady([]),
+ userText(SUMMARY),
+ userText("q2"),
+ requestBegin(),
+ abortEvent(),
+ ],
+ { index: "002" },
+ );
+
+ const session = await agent.resumeSession({ sessionId: SID });
+ try {
+ expect(engineStateOf(session)?.sessionTurns).toBe(0);
+ expect(session.compactability()).toBe("just_compacted");
+ } finally {
+ session.dispose();
+ }
+ });
+});
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index a14398f2..7839dde2 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -346,7 +346,7 @@ Three triggers exist, recorded as `compaction_begin.reason`:
| --- | --- |
| `context` | the last turn's `token_usage.request.total` ≥ the effective context threshold |
| `turns` | Session turn count ≥ `maxSessionTurns` (default -1 = unlimited) |
-| `manual` | the user runs `/compact` or calls `session.compact()` |
+| `manual` | the user runs `/compact` or calls `session.compact()`, or switches the model inside the Session (the switch compacts on the current model first) |
The effective context threshold for the `context` trigger is the smaller of `maxContextLength` (default 256000) and the model's `context_window` − 2048. A 32k local vLLM therefore compacts at ~30.7k instead of overflowing the window first, while a 1M-window model fires at the configured 256000. An entry without a usable `context_window` — unset, or below 4096 — derives from an assumed 128000 window, i.e. ~126k.
@@ -407,7 +407,7 @@ The Environment is re-equipped at a rotation:
The rotated Trace file opens with the `session_meta` recording the prompt this context runs with, then the connect pair (if any) and the toolset record.
-What stays fixed for the Session's lifetime is the Session itself: its id, Workspace, model entry (credentials, window and per-model annotations included) and origin.
+What stays fixed for the Session's lifetime is the Session itself: its id, Workspace and origin. The model entry (credentials, window and per-model annotations included) is per context: an ordinary rotation keeps the current entry, and an in-session model switch resolves the target entry from the Project config on disk (see [Sessions & Traces](/sessions-and-traces#in-session-model-switch)).
An Agent State that cannot be assembled — a config that no longer parses — fails the run with that error, and the engine stays on the old context. This is the same error a new Session would hit. The same rule opens a context that resume finds closed by a completed compaction (see [Sessions & Traces](/sessions-and-traces)).
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index 81ce2da5..aa84e1e0 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -346,7 +346,7 @@ interface CompactionSettings {
| --- | --- |
| `context` | 上一轮的 `token_usage.request.total` ≥ 生效的上下文阈值 |
| `turns` | Session 轮数 ≥ `maxSessionTurns`(默认 -1,即不限) |
-| `manual` | 用户运行 `/compact` 或调用 `session.compact()` |
+| `manual` | 用户运行 `/compact` 或调用 `session.compact()`,或在会话内切换模型(切换先用当前模型压缩) |
`context` 触发的生效阈值取 `maxContextLength`(默认 256000)与模型 `context_window` − 2048 中的较小者:32k 的本地 vLLM 因此在约 30.7k 处压缩,而不是先撞上窗口上限;1M 窗口的模型则在配置的 256000 处触发。条目没有可用的 `context_window`(未配置或小于 4096)时,按 128000 的假定窗口推导,即约 126k。
@@ -407,7 +407,7 @@ interface CompactionSettings {
轮转出的新 Trace 文件以记录本上下文所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。
-整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。
+整个 Session 生命周期内固定的只有 Session 自身:id、Workspace 与来源。模型条目(含凭据、窗口与逐模型标注)按上下文固定:普通轮换沿用当前条目,会话内切换模型时按磁盘上的 Project 配置解析目标条目(见 [Session 与 Trace](/sessions-and-traces#会话内切换模型))。
Agent State 无法装配(例如配置文件已无法解析)时,本次运行以该错误结束,引擎保持旧上下文,与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启新上下文(见 [Session 与 Trace](/sessions-and-traces))。
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index f699684a..15453ef2 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -20,7 +20,7 @@ A new conversation starts as a draft. The Session is created when you send the f
2. Above the composer, pick the **Agent**, the **Workspace** (a directory on the server, chosen in a directory browser; to use none, select **Start in a temporary workspace** at its bottom left), the **Approval mode**, the **Model** and the **Thinking level**.
3. Type your message and press Enter.
-Once the Session exists, its model and Workspace are locked. To move to another model later, see [Switch the model](#switch-the-model).
+Once the Session exists, its Workspace is locked; its model can still change, see [Switch the model](#switch-the-model).
Good to know:
@@ -91,7 +91,7 @@ Type `/` to open the slash menu. Press Enter or Tab to run the highlighted entry
| --- | --- |
| `/compact` | Compacts the context |
| `/agent` | Hands the conversation to another agent; see [Hand off to another agent](#hand-off-to-another-agent) |
-| `/model` | Continues the conversation on another model; see [Switch the model](#switch-the-model) |
+| `/model` | Opens a new conversation on another model; see [Switch the model](#switch-the-model) |
| `/goal` | Turns on goal mode; see [Set a goal](#set-a-goal) |
| A Skill's name | Selects or clears an installed Skill; selected Skills are sent with the message |
@@ -165,15 +165,30 @@ A compaction can only start on an idle conversation, so while a Task runs the fi
## Switch the model
-A Session's model is locked; selecting the model name says "Type /model to switch models". Switching continues the conversation in a new Session.
+There are two ways to change the model, and they do different things.
+
+### In this conversation
+
+Select the model name in the composer's toolbar and pick another model. The picker is disabled while a Task runs or a compaction is under way, and picking the current model does nothing. A dialog asks first, because the switch compacts the context on the current model before moving on:
+
+- **Compact and switch**: the context is compacted on the current model (always a summary, even when the agent is configured to discard), and the conversation then continues on the new model. If the compaction fails or is aborted, the conversation stays on the current model.
+- **Cancel**: keeps the current model.
+
+Right after a compaction or another switch there is nothing to compact, so the dialog says nothing is compacted again and the button reads **Switch**; a conversation with no messages yet switches at once.
+
+The switch shows in the conversation as a compaction row followed by a "Model switched · A → B" marker (the marker alone when there was nothing to compact: right after a compaction or another switch, or when the last request never completed). A failed compaction shows as a failed compaction row with no marker. Once switched, the model badge, the context window and the cost estimate follow the new model.
+
+### In a new conversation
+
+`/model` opens a new Session that continues the conversation on another model and leaves this one as it is.
1. In the composer, type `/model` and pick a model. It appears as a chip above the text, and nothing is sent yet.
2. Type a message if you want. With an empty composer, "Continue this conversation on the new model" is sent.
3. Press Enter.
-The new Session keeps the agent, the Workspace and the approval mode. It opens with a "Switched model (was …) — continued from the earlier conversation" banner that links back, and the model reads the earlier conversation's Trace file when it needs the history.
+The new Session keeps the agent, the Workspace and the approval mode. It opens with a "New conversation on another model (was …) — continues the original" banner that links back, and the model reads the earlier conversation's Trace file when it needs the history.
-- The switch waits until the Session is idle, because it continues from the Session's Trace, which a running turn or a compaction is still writing. A line above the composer says so while it waits.
+- The handoff waits until the Session is idle, because it continues from the Session's Trace, which a running turn or a compaction is still writing. A line above the composer says so while it waits.
- To cancel, select × on the chip, or press Backspace at the start of the text.
- The chip is saved with the draft, so it survives a reload or a visit to another conversation.
@@ -383,7 +398,7 @@ On a Mac, ⌘ takes the place of Ctrl in Ctrl+S and in the Ctrl+Alt rows other t
Some of what you do in the chat travels as structured text in the conversation, which you may notice in the Trace:
-- A model switch starts the new Session with a `[model_switch_from]` block naming the source Session, its title, its Trace file, its Workspace and the previous provider and model, followed by your message. The new conversation shows the block as the "Switched model" banner.
+- `/model` starts the new Session with a `[model_switch_from]` block naming the source Session, its title, its Trace file, its Workspace and the previous provider and model, followed by your message. The new conversation shows the block as the "New conversation on another model" banner. A switch inside a conversation writes no block: it is recorded as an ordinary compaction, and the new context's `session_meta` names the new model.
- A steering message is sent as a `[user_steering]` user message with the agent's next turn.
- Selected Skills travel with the message in a `[use_skills]` block.
- Each attached file adds an `[attached file: <path>]` line to the message.
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index 1cc5c4f2..be36aa64 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -20,7 +20,7 @@ description: 与 Agent 开始对话,实时跟进它的工作,并在 Task 运
2. 在输入框上方选择 **Agent**、**Workspace**(服务器上的一个目录,在目录浏览器中选取;不选目录时点击其左下角的**从临时工作区开始**)、**审批模式**、**Model** 和**思考等级**。
3. 输入消息,按 Enter 发送。
-Session 创建后,模型和 Workspace 就锁定了。之后想换模型,见[切换模型](#切换模型)。
+Session 创建后,Workspace 就锁定了;模型仍然可以换,见[切换模型](#切换模型)。
几点说明:
@@ -91,7 +91,7 @@ Session 创建后,模型和 Workspace 就锁定了。之后想换模型,见[
| --- | --- |
| `/compact` | 压缩上下文 |
| `/agent` | 把对话交接给另一个 Agent,见[交接给其他 Agent](#交接给其他-agent) |
-| `/model` | 换一个模型继续对话,见[切换模型](#切换模型) |
+| `/model` | 用另一个模型开一个新对话,见[切换模型](#切换模型) |
| `/goal` | 开启目标模式,见[设定目标](#设定目标) |
| Skill 名称 | 选中或取消一个已安装的 Skill;选中的 Skill 随消息一起发送 |
@@ -165,15 +165,30 @@ Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的
## 切换模型
-Session 的模型是锁定的,点击模型名称会提示「输入 /model 切换模型」。切换模型会在一个新的 Session 中继续对话。
+换模型有两种方式,作用不同。
+
+### 在本对话内
+
+点击输入框工具栏上的模型名称,选另一个模型。Task 运行期间和压缩期间选择器不可用,选当前模型没有反应。会先弹出确认框,因为切换要先用当前模型压缩上下文:
+
+- **压缩并切换**:先用当前模型压缩上下文(总是生成摘要,即使 Agent 配置为清空),然后本对话在新模型上继续。压缩失败或被中断时,对话保持在当前模型上。
+- **取消**:保持当前模型。
+
+刚压缩完或刚切换完时没有可压缩的内容,确认框会说明不会再次压缩,按钮只写**切换**;还没有消息的对话直接切换。
+
+切换在对话中显示为一条压缩行,后面跟一行「模型已切换 · A → B」标记(没有内容可压缩时只有标记:刚压缩完或刚切换完,或最后一个请求没有完成)。压缩失败只显示失败的压缩行,没有标记。切换完成后,模型徽标、上下文窗口和费用估算都跟随新模型。
+
+### 开新会话
+
+`/model` 新开一个 Session 在另一个模型上延续对话,本对话保持不变。
1. 在输入框输入 `/model`,选择一个模型。它以小卡片的形式出现在正文上方,此时还不会发送。
2. 可以接着输入要说的话。输入框为空时,会发送「换用新模型继续这段对话」。
3. 按 Enter。
-新 Session 沿用原来的 Agent、Workspace 和审批模式,开头有一条「已切换模型(原为 …),延续原会话」横幅,可以点回原对话;模型需要早先的历史时,会自己读取原对话的 Trace 文件。
+新 Session 沿用原来的 Agent、Workspace 和审批模式,开头有一条「换模型新开的会话(原模型 …),延续原会话」横幅,可以点回原对话;模型需要早先的历史时,会自己读取原对话的 Trace 文件。
-- 切换要等 Session 空闲,因为新 Session 要从原 Session 的 Trace 接续,而运行中的一轮或压缩还在写这个文件。等待期间,输入框上方有一行说明。
+- 交接要等 Session 空闲,因为新 Session 要从原 Session 的 Trace 接续,而运行中的一轮或压缩还在写这个文件。等待期间,输入框上方有一行说明。
- 要取消,点小卡片上的 ×,或在正文开头按 Backspace。
- 小卡片随草稿一起保存,刷新页面或去别的对话再回来都还在。
@@ -383,7 +398,7 @@ Session 的模型是锁定的,点击模型名称会提示「输入 /model 切
你在对话中的一些操作会以结构化文本的形式写进对话,查看 Trace 时可能会注意到:
-- 切换模型时,新 Session 的第一条消息以 `[model_switch_from]` 块开头,写明原 Session、它的标题、Trace 文件、Workspace,以及原来的供应商和模型,后面跟着你的消息。新对话把这个块显示为「已切换模型」横幅。
+- `/model` 开的新 Session,第一条消息以 `[model_switch_from]` 块开头,写明原 Session、它的标题、Trace 文件、Workspace,以及原来的供应商和模型,后面跟着你的消息。新对话把这个块显示为「换模型新开的会话」横幅。在本对话内切换模型不写这个块:它记录为一次普通压缩,新上下文的 `session_meta` 记录新模型。
- 插话以 `[user_steering]` 用户消息的形式,随 Agent 的下一轮送达。
- 选中的 Skill 放在 `[use_skills]` 块里随消息发送。
- 每个附件会在消息里加一行 `[attached file: <path>]`。
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 36fba6ff..4b8d6978 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -88,7 +88,7 @@ penguin chat [options]
| `--verbose` | Shows full tool output instead of collapsing long outputs; see [Tool output collapsing](#tool-output-collapsing). | Long outputs collapsed |
| `--server <url>` | Target server; see [Server connection](#server-connection). | — |
-With `--resume`, the original Session fixes the Workspace and model, so `--workspace`, `--model-id` and `--provider` cannot override them. `--thinking` is still accepted: it re-pins the existing Session from its next LLM request. Changing the level mid-context costs the provider's cached context, so compact first. On exit, if the Session has any history, the REPL prints a copy-pastable `penguin chat --resume <sessionId>` command.
+With `--resume`, the original Session fixes the Workspace and model, so `--workspace`, `--model-id` and `--provider` cannot override them; to change the model, use `/switch-model` inside the resumed chat. `--thinking` is still accepted: it re-pins the existing Session from its next LLM request. Changing the level mid-context costs the provider's cached context, so compact first. On exit, if the Session has any history, the REPL prints a copy-pastable `penguin chat --resume <sessionId>` command.
### In-REPL commands
@@ -100,6 +100,8 @@ With `--resume`, the original Session fixes the Workspace and model, so `--works
| `/clear` | Starts a fresh blank Session in place, on the same Workspace and model. The old Session stays on the server and can be resumed with `--resume`. |
| `/thinking` | Shows this Session's thinking level: the level pinned by `--thinking` or `/thinking`, else the agent's configured level. |
| `/thinking <level>` | Pins the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`). The level is never written back to the agent config. |
+| `/switch-model` | Shows this Session's current model. |
+| `/switch-model <provider> <model_id>` | Switches this Session's model in place. The context is summarized on the current model first, even when the agent's compaction mode is `discard`, and the conversation continues on the new model; a compaction that fails or is interrupted keeps the current model. A Session that has not run yet switches without compacting. The target must be in the Project's model config (`penguin config model list`); the two arguments are whitespace-separated, and a model id may contain `/`. |
| `/verbose` | Switches between collapsed and full tool output. |
| `/exit`, `/quit` | Quits. |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index b8eba5df..16cfede1 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -88,7 +88,7 @@ penguin chat [options]
| `--verbose` | 显示完整工具输出,而不是折叠长输出;见[工具输出折叠](#工具输出折叠)。 | 长输出折叠 |
| `--server <url>` | 目标服务器;见[服务器连接](#服务器连接)。 | — |
-使用 `--resume` 时,原 Session 已固定 Workspace 和模型,`--workspace`、`--model-id` 和 `--provider` 无法覆盖它们。`--thinking` 仍然有效:它重新固定现有 Session,从下一次 LLM 请求起生效。在上下文中途更改等级会使供应商的上下文缓存失效,所以请先压缩。退出时,如果 Session 已有历史,REPL 会打印一条可直接复制运行的 `penguin chat --resume <sessionId>` 命令。
+使用 `--resume` 时,原 Session 已固定 Workspace 和模型,`--workspace`、`--model-id` 和 `--provider` 无法覆盖它们;要换模型,在恢复后的对话里使用 `/switch-model`。`--thinking` 仍然有效:它重新固定现有 Session,从下一次 LLM 请求起生效。在上下文中途更改等级会使供应商的上下文缓存失效,所以请先压缩。退出时,如果 Session 已有历史,REPL 会打印一条可直接复制运行的 `penguin chat --resume <sessionId>` 命令。
### REPL 内命令
@@ -100,6 +100,8 @@ penguin chat [options]
| `/clear` | 原地开启一个全新的空白 Session,仍用同一个 Workspace 和模型。旧 Session 保留在服务器上,之后可用 `--resume` 恢复。 |
| `/thinking` | 显示这个 Session 的思考等级:`--thinking` 或 `/thinking` 固定的等级,否则是 Agent 配置的等级。 |
| `/thinking <level>` | 固定 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`)。等级不会写回 Agent 配置。 |
+| `/switch-model` | 显示这个 Session 当前的模型。 |
+| `/switch-model <provider> <model_id>` | 在这个 Session 内切换模型。先用当前模型总结压缩上下文(Agent 的压缩方式为 `discard` 时也不例外),然后用新模型继续对话;压缩失败或被中断则保持当前模型。还没运行过的 Session 不压缩,直接切换。目标必须已在 Project 的模型配置中(`penguin config model list`);两个参数以空白分隔,model_id 可以包含 `/`。 |
| `/verbose` | 在折叠和完整工具输出之间切换。 |
| `/exit`、`/quit` | 退出。 |
diff --git a/packages/docs/content/message-flow.en.md b/packages/docs/content/message-flow.en.md
index 10fbcbbc..276c349d 100644
--- a/packages/docs/content/message-flow.en.md
+++ b/packages/docs/content/message-flow.en.md
@@ -129,7 +129,7 @@ The cases below change the observable order on the stream:
| Compaction | `compaction_begin` → the compaction request runs against the old context (its raw messages are written to Trace only, except each attempt's `token_usage` and the thinking and summary being generated, which are forwarded as ordinary `partial_thinking`/`partial_text` or `thinking`/`text` inside the span) → `compaction_end(status)` |
| max_turns reached | a length notice (`[reached max turns (N); stopping]`) → the run ends; unsubmitted input is kept as carry-over |
| The Prompt itself | written to Trace, not echoed back onto the stream (the caller already has it) |
-| `session_meta` | never emitted on the main Session's stream (it lives in the Trace and the history API); a Subagent child stream's first message is the child's `session_meta` |
+| `session_meta` | emitted on the main Session's stream only by an in-session model switch, as its last message: the new context's meta, naming the model the Session now runs on. Otherwise it lives in the Trace and the history API. A Subagent child stream's first message is the child's `session_meta` |
## Across Sessions: the origin chain
diff --git a/packages/docs/content/message-flow.zh.md b/packages/docs/content/message-flow.zh.md
index 0441fcf4..41bc82b6 100644
--- a/packages/docs/content/message-flow.zh.md
+++ b/packages/docs/content/message-flow.zh.md
@@ -129,7 +129,7 @@ Human ──run(newMessages)──► engine
| 上下文压缩 | `compaction_begin` → 压缩请求在旧上下文中执行(压缩请求的原始消息只写 Trace,例外是每次尝试的 `token_usage`,以及正在生成的思考与摘要,它们以普通的 `partial_thinking`/`partial_text` 或 `thinking`/`text` 在区间内转发)→ `compaction_end(status)` |
| 达到 max_turns | 长度提示(`[reached max turns (N); stopping]`)→ 运行结束;未提交的输入按补发保留 |
| Prompt 本身 | 写入 Trace,但不回流(调用方已经有了) |
-| `session_meta` | 主 Session 的输出流不产出它(它在 Trace 与历史接口中);子 Agent 子流的第一条消息是子 Session 的 `session_meta` |
+| `session_meta` | 主 Session 的输出流只在会话内切换模型时产出它,作为切换的最后一条:新上下文的 meta,记录 Session 此后所用的模型。其余时候它在 Trace 与历史接口中。子 Agent 子流的第一条消息是子 Session 的 `session_meta` |
## 跨 Session:origin 链
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 4ecc306e..f2e5e2d2 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -607,9 +607,9 @@ Where a model reference is optional (`penguin run` / `chat`, Session creation, s
### Models and agents
-An agent never binds a model. The model is chosen when a Session is created and stays fixed for that Session, so the same agent can run different Sessions on different models.
+An agent never binds a model. The model is chosen when a Session is created, so the same agent can run different Sessions on different models, and a Session can switch models later: the model picker in the conversation's toolbar compacts the context on the current model and continues the conversation on the new one (see [Sessions & Traces](/sessions-and-traces#in-session-model-switch)).
-The in-session `/model` command switches models by handoff:
+The `/model` command instead opens a new conversation on another model, by handoff:
1. It opens a new Session for the same agent on the new model, in the current Workspace.
2. The new Session's first message carries a `[model_switch_from]` block with the source Session's id and its Trace file path.
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 2206f2ad..8e8ff25b 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -606,9 +606,9 @@ api_key = "sk-..."
### 模型与 Agent
-Agent 从不绑定模型。模型在创建 Session 时确定,之后在整个 Session 期间保持不变,所以同一个 Agent 可以用不同模型运行不同的 Session。
+Agent 从不绑定模型。模型在创建 Session 时确定,所以同一个 Agent 可以用不同模型运行不同的 Session;Session 之后还能换模型:对话工具栏的模型选择器先用当前模型压缩上下文,再在新模型上继续本对话(见 [Session 与 Trace](/sessions-and-traces#会话内切换模型))。
-Session 内的 `/model` 命令通过交接来切换模型:
+`/model` 命令则是通过交接在另一个模型上开新会话:
1. 为同一个 Agent 在新模型上新建一个 Session,仍在当前 Workspace 里。
2. 新 Session 的第一条消息会带一个 `[model_switch_from]` 块,包含源 Session 的 id 和它的 Trace 文件路径。
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index 8d9f2854..09a7910a 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -47,7 +47,7 @@ interface SessionMetaPayload {
}
```
-The model and the Workspace are fixed for the Session's lifetime. The system prompt is fixed per context.
+The Workspace is fixed for the Session's lifetime. The model and the system prompt are fixed per context: an in-session model switch opens its new context on another model, and this record is the only place that says so.
Every Trace file opens with a `session_meta`. When a compaction opens a new context, the new file's `session_meta` carries the system prompt assembled for that context from the Agent State as it stands at that moment (see [Compaction](/agent-loop#compaction)). On resume, the engine takes the latest file's `session_meta` as the runtime configuration. See [Sessions & Traces](/sessions-and-traces).
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index 260381c6..a8a5e027 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -47,7 +47,7 @@ interface SessionMetaPayload {
}
```
-模型与 Workspace 在整个 Session 生命周期内不变,系统提示词则按上下文固定。
+Workspace 在整个 Session 生命周期内不变,模型与系统提示词则按上下文固定:会话内切换模型时,新上下文开在另一个模型上,所用模型只记在这条记录里。
每个 Trace 文件都以一条 `session_meta` 开头。压缩开启新上下文时,新文件的 `session_meta` 记录的系统提示词,按当时的 Agent State 为这个上下文重新装配(见[上下文压缩](/agent-loop#上下文压缩))。恢复 Session 时,引擎以最新文件里的 `session_meta` 作为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index dd4ab1dd..0b89e4bf 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -735,6 +735,7 @@ A fork clones the retained Trace files and snapshots the source scratchpad under
| POST | `/abort` | Interrupts the current Task: 202 when triggered, 204 when idle |
| POST | `/retry-now` | Skips the reconnect countdown: → 200 `{skipped}` |
| POST | `/compact` | Starts context compaction: 202 |
+| POST | `/switch-model` | Switches this Session's model in place: 202, or 200 with the updated Session when the Session never ran |
- `POST /tasks` answers `{sessionId, queued?}`. With `queueIfBusy`, a busy Session holds the input as a follow-up (`queued: true`) and starts it as an ordinary next Task once the Session is idle; `task_state` events report the number queued. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see [Request bodies](#request-bodies)).
- `POST /tasks` with `goal: {budget?}` starts a goal loop instead. It returns 409 `goal_plugin_not_installed` unless the `goal` plugin is installed on the agent. The objective is the input's text, with any leading marker blocks removed, so the input must carry non-empty text (400 otherwise): an image alone states no objective. Images are sent in round 1 as ordinary input, and later rounds re-inject only the objective text. `file` parts are refused with 400, because nothing carries them into the objective that every round re-injects. See [Goal mode](/goal-mode).
@@ -746,6 +747,7 @@ A fork clones the retained Trace files and snapshots the source scratchpad under
- `POST /subagents/:childSessionId/abort` stops only the child's current run; the child Session stays available for steering and follow-ups. It returns 202 when a run was stopped, and 204 when the child is already idle or unknown.
- `POST /retry-now` backs the **Retry now** button on the reconnect countdown. It skips the backoff wait in progress and fires the next retry immediately, without changing the attempt counter. `skipped: false` means no wait was in progress; it is not an error.
- `POST /compact` returns 409 when there is nothing to compact, with the reason in the code: `compaction_not_configured` (the agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet) or `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart works this out from its Trace, so an existing conversation can be compacted without running a Task first.
+- `POST /switch-model` takes `{provider, modelId}`, the complete pair (one half alone is 400). It compacts the context on the current model, always in summarize mode, then opens the next context on the target. It answers 202 and streams like `/compact`, with the Session status `compacting`: an ordinary manual `compaction_begin` / `compaction_end` pair when the context had completed turns to summarize (none otherwise: just compacted, or its first request never finished), then the new context's opener records and its `session_meta`, whose `provider` / `model_id` name the model the Session now runs on; `GET /` returns the new pair from that record on. A compaction that ends other than `completed` means no switch: no `session_meta` follows and the Session keeps its model. A Session that never ran has nothing to compact, so the switch completes inside the request, which answers 200 with the updated `{session}` and streams nothing. Refusals are 409 with a code per reason: `task_in_progress` / `compacting` (busy), `same_model`, `model_not_configured` (the target is not in the Project's model table), `model_unavailable` (the target cannot be constructed, e.g. no credential) and `compaction_not_configured`. The switch's compaction request is metered against the previous model, the Tasks after it against the new one.
### Request bodies
@@ -775,11 +777,11 @@ interface ApprovalDecisionRequest {
}
```
-The Web App's `/model` switch has no dedicated endpoint. Like the `/agent` handoff, it combines ordinary routes:
+There are two ways to change model. The in-session switch is `POST /switch-model` above: the same Session compacts and continues on another model, keeping its id and its history. The Web App's `/model` handoff instead opens a new conversation on another model and has no dedicated endpoint. Like the `/agent` handoff, it combines ordinary routes:
1. Session creation opens a new Session for the same agent, with the chosen model and the source Workspace carried over.
2. `POST /tasks` sends a first message that opens with a `[model_switch_from]` source block, naming the source session id, its `tracePath`, the Workspace and the previous model pair.
-3. The model reads that Trace file itself when it needs the earlier history.
+3. The model reads that Trace file itself when it needs the earlier history. The source Session is left as it was.
### Background processes
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 0ed7f822..9fceb579 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -735,6 +735,7 @@ interface MessagesResponse {
| POST | `/abort` | 中断当前 Task:触发时返回 202,空闲时返回 204 |
| POST | `/retry-now` | 跳过重连倒计时:→ 200 `{skipped}` |
| POST | `/compact` | 开始上下文压缩:202 |
+| POST | `/switch-model` | 在本 Session 内切换模型:202;从未运行过的 Session 返回 200 与更新后的 Session |
- `POST /tasks` 响应 `{sessionId, queued?}`。带 `queueIfBusy` 时,忙碌的 Session 会把输入存为后续 Task(`queued: true`),等 Session 空闲后作为普通的下一个 Task 启动;`task_state` 事件报告排队的数量。`file` 输入部分写入 Session 暂存区,并以 `[attached file: <path>]` 行的形式交给模型(见[请求体](#请求体))。
- `POST /tasks` 带 `goal: {budget?}` 时改为启动目标循环。Agent 没有安装 `goal` 插件时返回 409 `goal_plugin_not_installed`。目标就是输入里的文本(去掉开头的标记块),所以输入必须带非空文本(否则返回 400):只有图片说明不了目标。图片作为普通输入随第 1 轮发送,之后各轮只重新注入目标文本。`file` 部分一律以 400 拒绝,因为没有办法把文件带进每一轮都重新注入的目标。见[目标模式](/goal-mode)。
@@ -746,6 +747,7 @@ interface MessagesResponse {
- `POST /subagents/:childSessionId/abort` 只停止子 Agent 当前的运行;子 Session 仍可用于插话和后续 Task。成功停止一次运行时返回 202;子 Agent 已空闲或未知时返回 204。
- `POST /retry-now` 对应重连倒计时上的**立即重试**按钮。它跳过当前的退避等待,立即发起下一次重试,不改动尝试计数。`skipped: false` 表示当时没有等待在进行,这不是错误。
- `POST /compact` 在没有可压缩内容时返回 409,原因写在错误码里:`compaction_not_configured`(Agent 没有配置压缩)、`nothing_to_compact`(上下文还没有完整的对话轮次)或 `already_compacted`(上次压缩之后没有新内容)。服务器重启后恢复的 Session 会从自己的 Trace 推导出这些状态,所以已有对话无需先跑一个 Task 也能压缩。
+- `POST /switch-model` 接收 `{provider, modelId}`,必须是完整的一对(只给一半返回 400)。它先用当前模型压缩上下文(总是 summarize 模式),再在目标模型上开启下一个上下文。返回 202 并像 `/compact` 一样流式进行,Session 状态为 `compacting`:上下文有完成的轮可总结时,流上先是一对普通的 manual `compaction_begin` / `compaction_end`(否则没有:刚压缩过,或首个请求没有完成),随后是新上下文的开档记录和它的 `session_meta`,其 `provider` / `model_id` 就是 Session 此后所用的模型;从这条记录起 `GET /` 返回新的模型组合。压缩以非 `completed` 结束即没有切换:不会跟随 `session_meta`,Session 保持原模型。从未运行过的 Session 没有可压缩的上下文,切换在请求内完成,返回 200 与更新后的 `{session}`,不产生任何事件。拒绝返回 409,原因写在错误码里:`task_in_progress` / `compacting`(忙)、`same_model`、`model_not_configured`(目标不在 Project 的模型表中)、`model_unavailable`(目标无法构造,例如缺少凭据)和 `compaction_not_configured`。切换的压缩请求计入原模型的用量,之后的 Task 计入新模型。
### 请求体
@@ -775,11 +777,11 @@ interface ApprovalDecisionRequest {
}
```
-Web App 的 `/model` 切换没有专用端点。和 `/agent` 交接一样,它把几条普通路由组合起来:
+换模型有两条路。会话内切换走上面的 `POST /switch-model`:同一个 Session 先压缩,再在另一个模型上继续,会话 id 与历史不变。Web App 的 `/model` 交接则是用另一个模型开一个新会话,没有专用端点。和 `/agent` 交接一样,它把几条普通路由组合起来:
1. 创建 Session:为同一个 Agent 打开新 Session,沿用所选模型和源 Workspace。
2. `POST /tasks` 发送第一条消息,开头是 `[model_switch_from]` 来源块,写明源 session id、它的 `tracePath`、Workspace 以及之前的模型组合。
-3. 需要更早的历史时,模型自己去读那个 Trace 文件。
+3. 需要更早的历史时,模型自己去读那个 Trace 文件。源 Session 保持原样。
### 后台进程
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index 89468358..9a5dca97 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -14,7 +14,7 @@ The run model has six levels: Project → Agent → Workspace → Session → Ta
| Project | Top-level unit that organizes agents; owns the model and credential configuration; in a multi-user Web deployment, users and Projects are many-to-many |
| Agent | The executing subject; has exactly one Agent State (a persistent directory); one agent can serve many Workspaces |
| Workspace | The working directory of one run — the only file scope the model sees; an explicit `workspaceDir` must already exist; when none is given, a temporary Workspace `workspaces/tmp-<8hex>` is created |
-| Session | A continuous conversation under one (Agent, Workspace); model and Workspace are locked at Session creation; ids look like `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
+| Session | A continuous conversation under one (Agent, Workspace); the Workspace is locked at Session creation, and the model chosen then can be switched inside the Session (see [In-session model switch](#in-session-model-switch)); ids look like `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
| Task | One execution goal started by one Prompt; consists of one or more consecutive Requests |
| Request | One LLM API call: context and tool definitions in, streamed output out |
@@ -97,7 +97,7 @@ The Trace is the single source of truth for recovery. There is no separate sessi
1. Locate the highest-index Trace file of the Session.
2. Read the runtime configuration from its `session_meta`:
- - the model and the Workspace, which are immutable for the lifetime of the Session;
+ - the Workspace, which is immutable for the lifetime of the Session, and the model that context runs on (a model switch opens a new file, so the latest file always names the current model);
- the system prompt that the context opened with.
3. Replay the committed history into a fresh LLM context.
4. Reconstruct the carry-over (undelivered tool outputs, interruption markers) and the turn and Token counters.
@@ -132,9 +132,24 @@ The empty context is opened like any context a compaction opens. It is assembled
An open context behaves differently: it keeps the prompt its file recorded. Its tools, Environment and vault can only come from the current Agent State, because the Trace records no executable configuration.
-## Model switch (/model)
+## In-session model switch
-In the Web App, the `/model` command changes models the way the `/agent` handoff does:
+The model picker in an active conversation's toolbar switches the model inside the same Session. A switch is a context rotation:
+
+1. The context is compacted on the current model, always in summarize mode, even when the agent's `compaction.mode` is `discard`: the summary is what reaches the new model. The request is an ordinary compaction request — the current model, system prompt, toolset and parameters, plus one user turn — so it extends the prefix the provider has cached, and nothing about the target model reaches it.
+2. The next context opens on the target model in a new Trace file, whose `session_meta` records that context's model. The file opens as soon as the switch completes, headed by the `session_meta` and then the summary, and that `session_meta` is also streamed.
+
+The compaction is an ordinary `manual` one: nothing on the `compaction_begin` / `compaction_end` pair names a model. A context with no completed turn has nothing to summarize, so the switch sends no request and records no pair. One that was just compacted hands its held summary to the new file. One whose first request failed or was stopped is left as it is: the summary it opened with, if any, is written again at the head of the new file, and of its other pending input only the text rides on, in memory. A switch carries no image to the new context.
+
+The Session keeps its model when the compaction fails or is aborted. The target must be in the Project configuration and constructible (credentials in place), or the switch is refused before any request. A Session that never ran has no context to compact: it switches directly and writes nothing.
+
+Resume reads the model from the latest file, so a Session restarted right after a switch runs on the new model with the summary pending. The summary is still known as the one that file opened with: another switch before the first turn completes writes it on to the next file, restart or not. A switch that dies before its new file exists is lost, the summary is not: the Session resumes on the model it was on, with the summary pending.
+
+For how to use the picker, see [Switch the model](/chat#switch-the-model).
+
+## New conversation on another model (/model)
+
+In the Web App, the `/model` command opens a new Session that continues the conversation on another model and leaves this one as it is. It works the way the `/agent` handoff does:
1. Picking a model stages it in the composer.
2. Sending creates a new Session under the same agent through the ordinary session-creation API. The new Session uses the chosen model and the source session's Workspace, so files stay reachable.
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index 8e215f24..8b004c9c 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -14,7 +14,7 @@ PenguinHarness 的全部运行时数据都存放在本地文件系统上。配
| Project | 组织 Agent 的顶层单位;持有模型和凭证配置;在多用户 Web 部署中,用户与 Project 多对多 |
| Agent | 执行主体;有且仅有一个 Agent State(一个持久化目录);一个 Agent 可以服务多个 Workspace |
| Workspace | 一次运行的工作目录,也是模型唯一能看到的文件范围;显式指定的 `workspaceDir` 必须已经存在,未指定时会创建临时 Workspace `workspaces/tmp-<8hex>` |
-| Session | 同一(Agent、Workspace)下的一段连续对话;模型和 Workspace 在 Session 创建时锁定;id 形如 `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
+| Session | 同一(Agent、Workspace)下的一段连续对话;Workspace 在 Session 创建时锁定,模型在创建时选定、之后可在会话内切换(见[会话内切换模型](#会话内切换模型));id 形如 `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
| Task | 由一个 Prompt 启动的一个执行目标;由一个或多个连续 Request 组成 |
| Request | 一次 LLM API 调用:输入上下文和工具定义,输出流式结果 |
@@ -97,7 +97,7 @@ Trace 是恢复的唯一事实来源,不存在需要保持同步的独立 Sess
1. 找到这个 Session 索引最大的 Trace 文件。
2. 从文件里的 `session_meta` 读取运行时配置:
- - 模型和 Workspace,二者在 Session 的整个生命周期内不可变;
+ - Workspace(在 Session 的整个生命周期内不可变),以及这个上下文所用的模型(切换模型会开新文件,所以最新文件总是记录当前模型);
- 该上下文开启时使用的系统提示词。
3. 把已提交的历史重放进一个全新的 LLM 上下文。
4. 重建补发内容(未送达的工具输出、中断标记),以及轮次和 Token 计数器。
@@ -132,9 +132,24 @@ summarize 模式下,恢复后会重建 `[context_summary]`,并把它加在
尚未关闭的上下文则不同:它沿用所在文件记录的提示词。工具、Environment 和 vault 只能来自当前 Agent State,因为 Trace 不记录任何可执行配置。
-## 模型切换(/model)
+## 会话内切换模型
-在 Web App 中,`/model` 命令用与 `/agent` 交接相同的方式切换模型:
+活跃对话工具栏里的模型选择器在同一个 Session 内切换模型。切换是一次上下文轮换:
+
+1. 先用当前模型压缩上下文,并且总是 summarize 模式,即使 Agent 的 `compaction.mode` 是 `discard`:摘要是带到新模型上的唯一记录。这个请求就是一次普通的压缩请求——当前模型、系统提示词、工具集和参数都不变,只追加一条用户消息——因此延续服务商已缓存的前缀,目标模型的任何信息都不会进入这个请求。
+2. 下一个上下文在目标模型上开启,写进新的 Trace 文件,文件里的 `session_meta` 记录这个上下文的模型。文件在切换完成时立即开启,开头是 `session_meta`,然后是摘要;这条 `session_meta` 也会推入输出流。
+
+这次压缩是普通的 `manual` 压缩:`compaction_begin` / `compaction_end` 事件对上没有任何字段记录模型。没有完成任何一轮的上下文没有内容可总结,切换既不发请求,也不记录事件对。刚压缩过的上下文把手中的摘要直接写在新文件开头。首个请求失败或被停止的上下文保持原样:它开启时所带的摘要(如有)会再写一次到新文件开头,其余待发的输入只带文本,且只在内存中带过去。切换不会把图片带进新上下文。
+
+压缩失败或被中断时,Session 保持原模型。目标必须在 Project 配置中且能构造出来(凭据齐全),否则切换在发出任何请求之前就被拒绝。从未运行过的 Session 没有上下文可压缩:直接切换,不写入任何内容。
+
+恢复从最新文件读取模型,所以切换后立刻重启的 Session 仍运行在新模型上,摘要待发。这条摘要仍被认作该文件开头的摘要:在完成第一轮之前再次切换,无论其间是否重启,它都会写到下一个文件的开头。切换在新文件建立之前中断时,丢失的只是这次切换,摘要不丢:Session 恢复在原模型上,摘要待发。
+
+选择器的用法见[切换模型](/chat#切换模型)。
+
+## 换模型开新会话(/model)
+
+在 Web App 中,`/model` 命令新开一个 Session 在另一个模型上延续对话,本对话保持不变。它用与 `/agent` 交接相同的方式进行:
1. 选择模型后,先暂存在输入框中。
2. 发送时,通过普通的 Session 创建 API 在同一个 Agent 下创建新 Session。新 Session 使用所选模型和来源 Session 的 Workspace,因此文件仍然可以访问。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index ac83219a..4a0ccb30 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1483,9 +1483,12 @@ export interface SessionInfo {
sessionId: string;
projectId: string;
agentId: string;
- /** Provider group of the session's model (paired with `modelId` to form a model reference). */
+ /**
+ * Provider group of the session's **current** model (paired with `modelId` to form a model
+ * reference). It moves with each in-session switch (`POST /api/sessions/:id/switch-model`).
+ */
provider: string;
- /** Upstream model_id of the session's model (the request id sent to AgentHub). */
+ /** Upstream model_id of the session's current model (the request id sent to AgentHub). */
modelId: string;
workspace: string;
approvalMode: ApprovalMode;
@@ -1896,6 +1899,33 @@ export interface GoalResponse {
goal: GoalStateView | null;
}
+/**
+ * `POST /api/sessions/:sessionId/switch-model`: switch this Session to another model in place.
+ * The running context is closed on the model it ran on, then the next one opens on the target.
+ *
+ * - **202** {@link TaskCreateResponse} — the switch streams, the Session status `compacting`.
+ * A context with a completed turn is closed by an ordinary `manual` compaction pair (always
+ * summarize); one without — just compacted, or its first request never finished — has
+ * nothing to summarize and streams no pair. Then come the new context's opener records
+ * and, last, its `session_meta`: its `provider` / `model_id` name the model the Session now
+ * runs on, the Session reads report that pair from this record on, and `task_state` turns
+ * idle after it.
+ * A compaction that ends other than `completed` means no switch — no `session_meta` follows
+ * and the Session keeps its model.
+ * - **200** {@link SessionResponse} — a Session that never ran has no context to close: it
+ * switched inside the request, and nothing is streamed.
+ * - **409**, one code per refusal, before any event: `task_in_progress` / `compacting` (busy),
+ * `same_model`, `model_not_configured` (the target is not in the Project config),
+ * `model_unavailable` (its client cannot be constructed, e.g. no credential), and
+ * `compaction_not_configured`.
+ */
+export interface SessionSwitchModelRequest {
+ /** Provider group of the target model. */
+ provider: string;
+ /** Upstream model_id of the target model. */
+ modelId: string;
+}
+
export interface TaskCreateResponse {
/** Current actual session_id: a Trace-less invalid Session self-heals and returns a new id; the frontend updates its route accordingly. */
sessionId: string;
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index a9534b9b..0f0bb524 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -13,9 +13,13 @@ export interface SessionRow {
sessionId: string;
projectId: string;
agentId: string;
- /** Provider group of the session's model (pairs with `modelId` to form the model reference). */
+ /**
+ * Provider group of the session's **current** model (pairs with `modelId` to form the model
+ * reference). Moves with each in-session switch (`updateModel`); the Trace's latest
+ * `session_meta` is the durable truth, and the runtime reconciles a row it disagrees with.
+ */
provider: string;
- /** Upstream model_id of the session's model (sent as-is to AgentHub; never concatenated). */
+ /** Upstream model_id of the session's current model (sent as-is to AgentHub; never concatenated). */
modelId: string;
workspace: string;
approvalMode: ApprovalMode;
@@ -277,6 +281,13 @@ export class SessionsRepo implements SessionIndex {
this.db.prepare("UPDATE sessions SET title = ? WHERE session_id = ?").run(title, sessionId);
}
+ /** The session's current model after an in-session switch (or a reconcile against its Trace). */
+ updateModel(sessionId: string, provider: string, modelId: string): void {
+ this.db
+ .prepare("UPDATE sessions SET provider = ?, model_id = ? WHERE session_id = ?")
+ .run(provider, modelId, sessionId);
+ }
+
/**
* Writes only if the title is still NULL. Subagent-session registration and Trace
* directory discovery backfill can race on the same row, and both are insert-only:
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 23b65c60..77a23bb3 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -80,8 +80,8 @@ CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
- provider TEXT NOT NULL, -- provider group of the session model (paired with model_id as a model reference)
- model_id TEXT NOT NULL, -- upstream model id (sent to AgentHub as-is; never concatenate <provider>/<id>)
+ provider TEXT NOT NULL, -- provider group of the session's CURRENT model (paired with model_id as a model reference; moves with each in-session switch)
+ model_id TEXT NOT NULL, -- upstream model id of the current model (sent to AgentHub as-is; never concatenate <provider>/<id>)
workspace TEXT NOT NULL,
approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask
thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config
@@ -202,7 +202,7 @@ CREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at
source TEXT, -- session_meta origin: 'subagent' | 'schedule' | 'benchmark' | NULL = user-created (or head not yet readable)
workspace TEXT NOT NULL DEFAULT '',
title TEXT, -- first-prompt fallback title (sessions.title always wins when present)
- provider TEXT, -- model reference from session_meta (CLI adoption reads it from here; NULL = meta unreadable / legacy without provider)
+ provider TEXT, -- model reference from session_meta: the model the Session was created on (CLI adoption reads it from here, and the runtime's own answer corrects the row at load; NULL = meta unreadable / legacy without provider)
model_id TEXT,
first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)
meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index a2be9e06..3151874f 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -766,8 +766,10 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
sessionId: fork.sessionId,
projectId: row.projectId,
agentId: row.agentId,
- provider: row.provider,
- modelId: row.modelId,
+ // The model of the shard the fork was cut in (its session_meta) — the source row's pair
+ // is only the model the source runs on NOW, which a switch may have moved since.
+ provider: fork.provider,
+ modelId: fork.modelId,
workspace: row.workspace,
approvalMode: row.approvalMode,
// A fork carries the source's policy on, as it carries its approval mode.
@@ -1361,6 +1363,38 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
return c.json({ sessionId } satisfies TaskCreateResponse, 202);
});
+ // In-session model switch (see SessionSwitchModelRequest): the complete (provider, modelId)
+ // pair, nothing inferred — one half alone is a 400 like everywhere else a model is named.
+ // 202 when the switch streams as a compaction; 200 with the fresh DTO when a Session that
+ // never ran switched inside the call (the manager tells the two apart).
+ app.post("/:sessionId/switch-model", async (c) => {
+ const row = resolveSession(c);
+ const body = await readJson(c);
+ const ref = {
+ provider: requireString(body, "provider", { minLen: 1 }),
+ modelId: requireString(body, "modelId", { minLen: 1 }),
+ };
+ const outcome = await deps.manager.startSwitch(row.sessionId, ref);
+ if (!outcome.switched) {
+ return c.json({ sessionId: outcome.sessionId } satisfies TaskCreateResponse, 202);
+ }
+ // Re-read after the switch: the manager moved the row to the new pair inside the call. A
+ // row gone meanwhile (deleted during the request) is a 404, not the pre-switch row — that
+ // one names a model the runtime no longer runs on.
+ const fresh = deps.sessionsRepo.findById(outcome.sessionId);
+ if (!fresh) {
+ throw new HttpError(
+ 404,
+ "session_not_found",
+ "Session does not exist or you do not have access.",
+ );
+ }
+ const hasTrace = await deps.sessionService.hasTrace(fresh);
+ return c.json({
+ session: await deps.sessionService.toInfo(fresh, hasTrace),
+ } satisfies SessionResponse);
+ });
+
// —— Workspace file browsing (Files tab) ——
// The operations a directory-addressed panel shares (http/routes/workspace-files.ts), here on
// the Session's own Workspace; the preview redirect and the batch existence check below are
diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.ts
index 83c7b746..75c36142 100644
--- a/packages/server/src/mechanisms/sessions.ts
+++ b/packages/server/src/mechanisms/sessions.ts
@@ -29,6 +29,7 @@ export abstract class SessionIndex {
abstract updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void;
abstract updateTitle(sessionId: string, title: string): void;
abstract updateTitleIfNull(sessionId: string, title: string): void;
+ abstract updateModel(sessionId: string, provider: string, modelId: string): void;
abstract setArchived(sessionId: string, archivedAt: string | null): void;
abstract replaceId(oldSessionId: string, newSessionId: string): void;
abstract deleteByAgent(projectId: string, agentId: string): void;
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 260d5819..e7f58a01 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -14,12 +14,15 @@
* new api_key / base_url. Agent State changes (vault, AGENTS.md, tools, …) take no
* such shortcut: core assembles them into the next model context — at the Session's
* next compaction — exactly as the CLI does, so a running context never changes;
- * - Per-Session mutual exclusion: only one Task/compaction may be in progress at a
- * time;
- * - run/compact drive: consumes the output stream in the background, publishing each
- * message to the SSE channel and handing it to usage-recorder for persistence;
+ * - Per-Session mutual exclusion: only one Task/compaction/model switch may be in
+ * progress at a time;
+ * - run/compact/switch drive: consumes the output stream in the background, publishing
+ * each message to the SSE channel and handing it to usage-recorder for persistence;
* on completion (including errors) resets to idle and pushes a `task_state` server
- * event;
+ * event. A model switch (startSwitch) is a compaction whose next context opens on
+ * another model: the entry's (provider, modelId) — the pair usage is attributed to —
+ * and the index row follow the runtime, moving as the new context's session_meta passes
+ * through the drive;
* - Approval registration and interrupt convergence: each approval decision re-reads
* approval_mode from the DB (takes effect immediately); an interrupt first
* converges pending approvals to deny, then aborts. An organization's sessions have
@@ -39,6 +42,7 @@ import {
isHookContinue,
isHookInput,
isSessionMeta,
+ ModelSwitchRefusedError,
parseUserSteeringText,
tracesDir,
userText,
@@ -55,6 +59,7 @@ import type {
SpawnConfiner,
SessionMetaPayload,
SessionTitleResult,
+ StopReason,
SubagentMessageOptions,
SubagentMessageOutcome,
TextPayload,
@@ -62,6 +67,7 @@ import type {
ToolDetachResult,
} from "@prismshadow/penguin-core";
import type {
+ ModelRefDto,
PendingFollowUpInfo,
PendingSteeringInfo,
ServerEvent,
@@ -134,6 +140,37 @@ function compactUnavailable(why: Exclude<CompactAvailability, "ok">): HttpError
return new HttpError(409, code, message);
}
+/**
+ * Core's refusal of a model switch — a typed `ModelSwitchRefusedError`, thrown before its
+ * first event (see `Session.switchModel`) — as the 409 the HTTP contract names for it: each
+ * reason is its own code (see `SessionSwitchModelRequest`). A missing credential reads as the
+ * remedy the Web App can act on rather than the loader's own wording. Anything else core
+ * throws is not a refusal but a failure — an Agent State that no longer parses, a bootstrap
+ * that broke — and is rethrown, so it reaches the 500 path and its logging instead of being
+ * dressed up as a target problem.
+ */
+function switchRefusal(err: unknown, ref: ModelRefDto): HttpError {
+ if (!(err instanceof ModelSwitchRefusedError)) throw err;
+ const message =
+ err.reason === "model_unavailable" && isMissingCredential(err)
+ ? `Model ${ref.modelId} has no API key yet. Configure it on the Models page first.`
+ : err.message;
+ return new HttpError(409, err.reason, message);
+}
+
+/** A stream whose head was already pulled, whole again: `head`, then the rest of `rest`. */
+async function* resumeFrom<T>(head: T, rest: AsyncGenerator<T, unknown>): AsyncGenerator<T> {
+ yield head;
+ yield* rest;
+}
+
+/** The model a runtime Session reports itself on, or null for one that reports none (test fakes). */
+function runtimeModelOf(session: RuntimeSession): ModelRefDto | null {
+ const { provider, modelId } = session;
+ if (provider === undefined || modelId === undefined) return null;
+ return { provider, modelId };
+}
+
/** Minimal interface for a runtime Session (satisfied by core Session; tests may inject a fake implementation). */
export interface RuntimeSession {
readonly sessionId: string;
@@ -145,6 +182,27 @@ export interface RuntimeSession {
},
): AsyncGenerator<OmniMessage>;
compact(opts: { signal: AbortSignal }): AsyncGenerator<OmniMessage>;
+ /**
+ * The running context's model (core `Session.provider` / `Session.modelId`, getters over
+ * the context's session_meta): the row's pair at creation, moved by each in-session switch
+ * — and, after a restart, whatever the Trace resumed on. Optional: test fakes may omit them,
+ * in which case the entry keeps the row's pair.
+ */
+ readonly provider?: string;
+ readonly modelId?: string;
+ /**
+ * Switches the Session's model in place (core `Session.switchModel`): closes the running
+ * context on the model it ran on, then opens the next one on the target. A completed switch
+ * streams the new context's main-session `session_meta` last, and the getters above answer
+ * the target by then; a refusal is thrown before the first event; a Session that never ran
+ * switches without streaming anything. Optional: test fakes may omit it, reading as
+ * "switching is not available".
+ */
+ switchModel?(opts: {
+ provider: string;
+ modelId: string;
+ signal: AbortSignal;
+ }): AsyncGenerator<OmniMessage, StopReason>;
/**
* The Session's thinking level (core `Session.thinkingLevel`, plain state): soft-limited —
* an assignment applies from the Session's very next LLM request. Optional: test fakes may
@@ -436,7 +494,11 @@ interface RuntimeEntry {
sessionId: string;
projectId: string;
agentId: string;
- /** Vendor grouping for the Session's model (paired with modelId to form a model reference). */
+ /**
+ * The Session's current model (provider group paired with modelId): what the next drive
+ * attributes usage to. The row's pair, kept in step with the runtime's own answer (see
+ * `syncEntryModel`) — at load, and whenever a model switch moves it.
+ */
provider: string;
modelId: string;
session: RuntimeSession;
@@ -1308,6 +1370,113 @@ export class SessionManager {
});
}
+ /**
+ * Switches the Session's model in place (`POST /switch-model`) — core `Session.switchModel`,
+ * gated like a compaction (open, not deleting, idle). Core decides everything before its
+ * first event, so the head of its stream is pulled here, under the lock, and tells the three
+ * outcomes apart:
+ *
+ * - it throws — a refusal, answered 409 with the code of its reason (see `switchRefusal`);
+ * - it is already done — a Session that never ran has no context to close: core re-assembled
+ * its first context on the target, nothing streams, and the row carries the new pair by
+ * the time this returns (`switched: true`; the route answers with the fresh DTO);
+ * - it yields — a driven run like a compaction (`switched: false`): status `compacting`,
+ * idle when it ends. The head is a compaction's begin, the first record of a bootstrap (a
+ * Session loaded from its Trace opens its context first), or — for a context with no
+ * completed turn, which streams no pair — the opener's first record.
+ *
+ * The switch is the entry's run from that pull on — it can be stopped, and a deletion or a
+ * shutdown waits for it — while the entry only reads `compacting` once there is something
+ * to stream, so a refusal never flickers a state.
+ *
+ * The entry and the row follow the runtime as the new context's `session_meta` passes
+ * through the drive (see `drive`); a switch that does not complete streams no meta and
+ * leaves them where they were. Usage: a drive bills to the model it started on, so the
+ * switch's compaction request goes to the model that served it and the next run to the new
+ * one.
+ */
+ async startSwitch(
+ sessionId: string,
+ ref: ModelRefDto,
+ ): Promise<{ sessionId: string; switched: boolean }> {
+ return this.withLock(sessionId, async () => {
+ this.assertOpen();
+ this.assertAgentNotDeleting(sessionId);
+ this.assertSessionNotDeleting(sessionId);
+ const entry = await this.ensureEntry(sessionId);
+ this.assertIdle(entry);
+ if (entry.provider === ref.provider && entry.modelId === ref.modelId) {
+ throw new HttpError(
+ 409,
+ "same_model",
+ `This Session already runs on ${ref.provider} / ${ref.modelId}.`,
+ );
+ }
+ if (!entry.session.switchModel) {
+ throw new HttpError(
+ 409,
+ "model_unavailable",
+ "Switching the model is not available for this Session.",
+ );
+ }
+ const ac = new AbortController();
+ const gen = entry.session.switchModel({ ...ref, signal: ac.signal });
+ const head = gen.next();
+ const settled = (): void => {
+ entry.abort = null;
+ entry.running = null;
+ };
+ // One promise for the whole switch — the pull, then the drive behind it — so whoever
+ // waits for this entry's run to end waits for both.
+ entry.abort = ac;
+ entry.running = head.then((first) => {
+ if (first.done) return settled();
+ entry.status = "compacting";
+ this.publishState(entry, "compacting");
+ return this.drive(entry, resumeFrom(first.value, gen));
+ }, settled);
+ let first: IteratorResult<OmniMessage, StopReason>;
+ try {
+ first = await head;
+ } catch (err) {
+ throw switchRefusal(err, ref);
+ }
+ entry.lastActivityMs = Date.now();
+ if (!first.done) return { sessionId: entry.sessionId, switched: false };
+ this.syncEntryModel(entry);
+ return { sessionId: entry.sessionId, switched: true };
+ });
+ }
+
+ /**
+ * Moves the entry — and the row it caches into — to the model the runtime reports itself on,
+ * when that differs: the pair the next drive attributes usage to, and the one
+ * `GET /sessions/:id` describes. A runtime that reports none (test fakes) leaves the entry
+ * alone. The row write is guarded like the other bookkeeping writes (see `touchRow`): a
+ * switch must not be stranded mid-drive by a closed DB handle, and the entry is right either
+ * way.
+ */
+ private syncEntryModel(entry: RuntimeEntry): void {
+ const model = runtimeModelOf(entry.session);
+ if (!model) return;
+ if (entry.provider === model.provider && entry.modelId === model.modelId) return;
+ entry.provider = model.provider;
+ entry.modelId = model.modelId;
+ try {
+ this.deps.sessions.updateModel(entry.sessionId, model.provider, model.modelId);
+ } catch (err) {
+ this.log(
+ `[session] model bookkeeping failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ this.deps.errors?.record({
+ source: "session",
+ err,
+ ctx: { projectId: entry.projectId, agentId: entry.agentId, sessionId: entry.sessionId },
+ code: "session_model_update_failed",
+ });
+ }
+ }
+
/** Submit an approval decision; returns false if the pending approval doesn't exist (already decided/unknown). */
decideApproval(sessionId: string, toolCallId: string, decision: "allow" | "deny"): boolean {
const entry = this.entries.get(sessionId);
@@ -1804,6 +1973,10 @@ export class SessionManager {
// discard path produces today.
backgroundTasks: discardedBackgroundTasks ?? backgroundTaskCounts(session),
};
+ // The runtime's model is the truth the row caches: a Session that switched models and
+ // crashed between the Trace write and the row update resumes (from the Trace) on the new
+ // model, and the row is brought back in step here.
+ this.syncEntryModel(entry);
this.entries.set(currentId, entry);
this.registerNoticeListener(currentId, session);
if (discardedBackgroundTasks !== undefined) this.publishBackgroundTasks(currentId);
@@ -1935,6 +2108,15 @@ export class SessionManager {
entry.pendingSteering.shift();
this.publishState(entry, entry.status);
}
+ // The main session's own session_meta is streamed when a model switch opens its new
+ // context, and the runtime is on that context's model by then: the entry and the row
+ // follow it here, ahead of the publish below, so a client that re-reads the Session
+ // on this record already finds the new model. The new context's file is open too, its
+ // records on it, and what the context it replaced still held pending went with it.
+ if (isSessionMeta(msg)) {
+ this.syncEntryModel(entry);
+ entry.pendingBootstrap = [];
+ }
} else if (isSessionMeta(msg)) {
// Subagent registration is only a "side effect" — it must never interrupt the
// main run flow on error: wrap the whole thing in a defensive try/catch.
@@ -2291,6 +2473,7 @@ export abstract class Sessions extends Interface<
| "startTask"
| "startGoal"
| "startCompact"
+ | "startSwitch"
| "decideApproval"
| "steer"
| "recallSteering"
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 0bbf81c0..59e44fad 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -183,6 +183,13 @@ export interface MessagesPageResult {
export interface ForkTraceResult {
sessionId: string;
createdAt: string;
+ /**
+ * The model the fork resumes on: the `session_meta` of the shard the cut falls in. Each shard
+ * records its own context's model, so a source that switched models mid-way forks onto the
+ * model that was serving the selected reply, not the one the source runs on today.
+ */
+ provider: string;
+ modelId: string;
}
/**
@@ -701,6 +708,10 @@ export class TraceService implements Traces {
const firstMeta = shards.flat().find(isSessionMeta);
if (!firstMeta) throw invalid("The source Trace has no session metadata.");
+ // The fork's model is the target shard's: one shard is one model context, and a model
+ // switch opens the next context in a new shard headed by its own session_meta.
+ const targetMeta = targetShard.find(isSessionMeta) ?? firstMeta;
+ const model = { provider: targetMeta.payload.provider, modelId: targetMeta.payload.model_id };
const created = new Date();
const createdAt = created.toISOString();
@@ -789,7 +800,7 @@ export class TraceService implements Traces {
records,
});
}
- return { sessionId: newSessionId, createdAt };
+ return { sessionId: newSessionId, createdAt, ...model };
} catch (err) {
await Promise.all(written.map((file) => fs.rm(file, { force: true }).catch(() => undefined)));
await fs.rm(forkScratchpad, { recursive: true, force: true }).catch(() => undefined);
diff --git a/packages/server/test/session-fork.test.ts b/packages/server/test/session-fork.test.ts
index 65de1381..abfed01f 100644
--- a/packages/server/test/session-fork.test.ts
+++ b/packages/server/test/session-fork.test.ts
@@ -511,6 +511,65 @@ describe("session fork", () => {
).toBe(false);
});
+ it("a fork's model is the one of the shard it is cut in, not the model the source runs on now", async () => {
+ const { scratch } = await seedSource();
+ // The source switched models: shard 1 closes with the switch's plain manual pair, shard 2
+ // opens headed by the new model's session_meta, and the source's row already carries it.
+ const nextModel = { provider: "custom", model_id: "fork-model-b" };
+ const closing = [
+ at(
+ "2026-08-14T10:01:05.000Z",
+ compactionBegin({ reason: "manual", mode: "summarize", context: 500, turns: 2 }),
+ ),
+ at("2026-08-14T10:01:05.100Z", requestBegin()),
+ at("2026-08-14T10:01:05.200Z", assistantText("[summary]summary[/summary]")),
+ at("2026-08-14T10:01:05.300Z", requestEnd("completed")),
+ at(
+ "2026-08-14T10:01:05.400Z",
+ compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }),
+ ),
+ ];
+ await fs.appendFile(
+ path.join(tracesDir(t.root, projectId, "default_agent"), "2026-08-14", `${SID}_001.jsonl`),
+ closing.map((message) => JSON.stringify(message)).join("\n") + "\n",
+ "utf8",
+ );
+ const metaB: SessionMetaPayload = {
+ session_id: SID,
+ provider: nextModel.provider,
+ model_id: nextModel.model_id,
+ model_context_window: 20_000,
+ system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,
+ agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),
+ workspace,
+ };
+ await writeTraceFile(t.root, projectId, "default_agent", "2026-08-14", SID, 2, [
+ at("2026-08-14T10:01:05.000Z", sessionMeta(metaB)),
+ at("2026-08-14T10:01:06.000Z", userText("[context_summary]\nsummary\n[/context_summary]")),
+ at("2026-08-14T10:01:07.000Z", userText("on the new model")),
+ at("2026-08-14T10:01:08.000Z", requestBegin()),
+ at("2026-08-14T10:01:09.000Z", assistantText("answered on b")),
+ at("2026-08-14T10:01:10.000Z", requestEnd("completed")),
+ at("2026-08-14T10:01:10.100Z", tokenUsage(counts(300), counts(100))),
+ ]);
+ t.deps.sessionsRepo.updateModel(SID, nextModel.provider, nextModel.model_id);
+
+ // Cut in shard 2: the fork resumes on the model that answered there.
+ const onB = (await (
+ await api.post(`/api/sessions/${SID}/fork`, { position: { fileIndex: 2, ordinal: 4 } })
+ ).json()) as SessionForkResponse;
+ expect(onB.session).toMatchObject({ provider: "custom", modelId: "fork-model-b" });
+ // Cut in shard 1: the fork resumes on shard 1's model, although the source has moved on.
+ const onA = (await (
+ await api.post(`/api/sessions/${SID}/fork`, { position: { fileIndex: 1, ordinal: 4 } })
+ ).json()) as SessionForkResponse;
+ expect(onA.session).toMatchObject({ provider: "custom", modelId: "fork-model" });
+ expect(t.deps.sessionsRepo.findById(onA.session.sessionId)).toMatchObject({
+ provider: "custom",
+ modelId: "fork-model",
+ });
+ });
+
it("gives concurrent forks unique Sessions without overwriting the source", async () => {
await seedSource();
const responses = await Promise.all(
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index efd36a29..4bdfb450 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -1094,6 +1094,39 @@ describe("session-manager", () => {
expect(recordedCtx[0]!.sessionId).toBe("session-2-healed");
});
+ it("load reconciles the row's model with the runtime's: a Session that switched and crashed before the row update resumes on the new model, and the row follows", async () => {
+ // The Trace is the durable record of a switch (the file it opens is headed by the new
+ // context's session_meta); the row is a cache of it that a crash in between leaves stale.
+ // The loader resumes on the Trace's model, so what it reports wins — for the entry (usage
+ // attribution) and for the row (what GET /sessions/:id shows).
+ sessions.updateApprovalMode("session-1", "allow-all");
+ const resumed: RuntimeSession = {
+ ...approvalFakeSession("session-1"),
+ provider: "other",
+ modelId: "m-switched",
+ };
+ const manager = makeManager(loaderOf(resumed));
+ await manager.startTask("session-1", [userText("go")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle" && recorded.length >= 3);
+ expect(sessions.findById("session-1")).toMatchObject({
+ provider: "other",
+ modelId: "m-switched",
+ });
+ expect(recordedCtx[0]).toMatchObject({ provider: "other", modelId: "m-switched" });
+
+ // A runtime that reports no model (test fakes) keeps the row's pair.
+ db.close();
+ db = openDatabase(":memory:");
+ sessions = wire(SessionsRepo, { db });
+ sessions.insert({ ...ROW, approvalMode: "allow-all" });
+ recordedCtx = [];
+ const plain = makeManager(loaderOf(approvalFakeSession("session-1")));
+ await plain.startTask("session-1", [userText("go")]);
+ await waitFor(() => plain.statusOf("session-1") === "idle" && recordedCtx.length >= 1);
+ expect(sessions.findById("session-1")).toMatchObject({ provider: "custom", modelId: "m1" });
+ expect(recordedCtx[0]).toMatchObject({ provider: "custom", modelId: "m1" });
+ });
+
it("after the channel is swept and rebuilt, drive still sends to the current channel (re-get before every publish)", async () => {
const manager = makeManager(loaderOf(approvalFakeSession("session-1")));
await manager.startTask("session-1", [userText("go")]);
diff --git a/packages/server/test/session-switch-model.test.ts b/packages/server/test/session-switch-model.test.ts
new file mode 100644
index 00000000..ebee97cc
--- /dev/null
+++ b/packages/server/test/session-switch-model.test.ts
@@ -0,0 +1,584 @@
+/**
+ * POST /api/sessions/:id/switch-model — the server half of an in-session model switch (core does
+ * the compaction and the rotation; a fake Session stands in for it here, shaped like the real
+ * one: an ordinary manual compaction pair, the getters moving once the new context is open, then
+ * that context's main-session `session_meta` as the stream's last record).
+ *
+ * What this file pins is the HTTP contract on `SessionSwitchModelRequest` — the 400 for half a
+ * pair, each 409 code, 202 for a streamed switch and 200 for a Session that never ran — and the
+ * bookkeeping the contract implies: the index row and the runtime entry move to the new model
+ * (so `GET /` and the compaction threshold follow it, and a client re-reading the Session on the
+ * new context's `session_meta` already finds it), stay put when the compaction fails or is aborted,
+ * and usage is attributed to the model that served each request — the switch's own compaction
+ * request to the previous model, the next Task to the new one.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ abortEvent,
+ assistantText,
+ compactionBegin,
+ compactionEnd,
+ ModelSwitchRefusedError,
+ requestBegin,
+ requestEnd,
+ sessionMeta,
+ tokenUsage,
+ toolListReady,
+} from "@prismshadow/penguin-core";
+import type { OmniMessage, StopReason, TokenCounts } from "@prismshadow/penguin-core";
+import type {
+ ModelRefDto,
+ ServerEvent,
+ SessionContextResponse,
+ SessionResponse,
+ TaskCreateResponse,
+} from "../src/api/types.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { compactionThresholdFor } from "../src/services/context-breakdown.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SID = "session-2026-09-16-10-00-00-aabb0007";
+const PROJECT = "switcher-default_project";
+const A: ModelRefDto = { provider: "custom", modelId: "m-alpha" };
+const B: ModelRefDto = { provider: "custom", modelId: "m-beta" };
+/** Not in the Project config: core refuses it, and the manager answers with the refusal's code. */
+const UNKNOWN: ModelRefDto = { provider: "custom", modelId: "m-nowhere" };
+const WINDOW_A = 1_000_000;
+const WINDOW_B = 200_000;
+
+function counts(total: number): TokenCounts {
+ return { cache_read: 0, cache_write: 0, output: 0, total };
+}
+
+/** How the fake's `switchModel` behaves once core would have validated the target. */
+type SwitchBehaviour =
+ /** Core threw before its first event: a typed refusal, or — a failure — anything else. */
+ | { kind: "throw"; error: Error }
+ /** A Session that never ran: re-assembled on the target, nothing streamed. */
+ | { kind: "inline" }
+ /**
+ * A loaded Session with nothing to compact, still settling the bootstrap of the context it
+ * leaves: no event until the signal fires, then the stopped bootstrap is shown.
+ */
+ | { kind: "held" }
+ /** The compaction pair streams; `status` is how it ends. `gate` parks the compaction until it settles (or the signal fires). */
+ | { kind: "stream"; status: StopReason; gate?: Promise<void> };
+
+interface SwitchFake extends RuntimeSession {
+ provider: string;
+ modelId: string;
+ /** The signals `switchModel` was handed, so a test can see the abort reach it. */
+ signals: AbortSignal[];
+ /** Whether a `switchModel` call has run to its end. */
+ ended: boolean;
+}
+
+/** Settles when `signal` fires. */
+const aborted = (signal: AbortSignal): Promise<void> =>
+ new Promise<void>((resolve) => {
+ if (signal.aborted) resolve();
+ else signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+
+/**
+ * A fake Session shaped like core's for a switch: the compaction request's token_usage rides
+ * between a plain manual pair, and the getters move only once the new context is open — after
+ * the completed `compaction_end` and before the new context's `session_meta` is yielded, exactly
+ * as core adopts the opened context before it yields that context's meta — so the manager
+ * follows the runtime in the real order.
+ */
+function switchFake(model: ModelRefDto, behaviour: SwitchBehaviour): SwitchFake {
+ const fake: SwitchFake = {
+ sessionId: SID,
+ provider: model.provider,
+ modelId: model.modelId,
+ signals: [],
+ ended: false,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run(): AsyncGenerator<OmniMessage> {
+ yield requestBegin();
+ yield assistantText("answered");
+ yield requestEnd("completed");
+ yield tokenUsage(counts(50), counts(50));
+ },
+ async *compact(): AsyncGenerator<OmniMessage> {},
+ async *switchModel(opts): AsyncGenerator<OmniMessage, StopReason> {
+ fake.signals.push(opts.signal);
+ if (behaviour.kind === "throw") throw behaviour.error;
+ if (behaviour.kind === "inline") {
+ fake.provider = opts.provider;
+ fake.modelId = opts.modelId;
+ return "completed";
+ }
+ if (behaviour.kind === "held") {
+ await aborted(opts.signal);
+ yield abortEvent("user_abort");
+ fake.ended = true;
+ return "aborted";
+ }
+ yield compactionBegin({ reason: "manual", mode: "summarize", context: 4000, turns: 3 });
+ // The compaction request itself, on the model being left.
+ yield tokenUsage(counts(4000), counts(4000));
+ if (behaviour.gate) await Promise.race([behaviour.gate, aborted(opts.signal)]);
+ const status: StopReason = opts.signal.aborted ? "aborted" : behaviour.status;
+ yield compactionEnd({ reason: "manual", mode: "summarize", status });
+ if (status === "completed") {
+ // The new context opens on the target: the getters follow it from here. Its opener's
+ // toolset record comes first, and its session_meta — main-session, no origin — is the
+ // last record on the stream.
+ fake.provider = opts.provider;
+ fake.modelId = opts.modelId;
+ yield toolListReady([]);
+ yield sessionMeta({
+ session_id: SID,
+ provider: opts.provider,
+ model_id: opts.modelId,
+ model_context_window: WINDOW_B,
+ system_prompt: "sp",
+ agent_state: "/tmp/agents/default_agent/agent_state",
+ workspace: "/tmp/w",
+ });
+ }
+ return status;
+ },
+ };
+ return fake;
+}
+
+describe("POST /switch-model", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+
+ const row = (): SessionRow => t.deps.sessionsRepo.findById(SID)!;
+ const url = `/api/sessions/${SID}/switch-model`;
+
+ /** Inserts the Session's row on model A and adopts `fake` as its runtime. */
+ const adopt = (fake: RuntimeSession): void => {
+ const inserted: SessionRow = {
+ sessionId: SID,
+ projectId: PROJECT,
+ agentId: "default_agent",
+ provider: A.provider,
+ modelId: A.modelId,
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: "2026-09-16T10:00:00.000Z",
+ lastActiveAt: "2026-09-16T10:00:00.000Z",
+ };
+ t.deps.sessionsRepo.insert(inserted);
+ t.deps.manager.adopt(inserted, fake);
+ };
+
+ /** The Session channel's traffic, split into messages and server events, as an SSE client sees it. */
+ const listen = () => {
+ const messages: OmniMessage[] = [];
+ const events: ServerEvent[] = [];
+ /** The row's model as it stood when each compaction_end was published. */
+ const rowAtEnd: ModelRefDto[] = [];
+ /** The row's model as it stood when each session_meta was published. */
+ const rowAtMeta: ModelRefDto[] = [];
+ /** How many bootstrap records the manager held for GET /messages as each message was published. */
+ const heldAt: Array<[string | undefined, number]> = [];
+ t.deps.channels.get(SID).subscribe((evt) => {
+ if (evt.event === "server_event") {
+ events.push(JSON.parse(evt.data) as ServerEvent);
+ return;
+ }
+ const msg = JSON.parse(evt.data) as OmniMessage;
+ messages.push(msg);
+ heldAt.push([
+ msg.type === "session_meta" ? "session_meta" : (msg.payload as { type?: string }).type,
+ t.deps.manager.pendingBootstrap(SID).length,
+ ]);
+ const r = row();
+ if (msg.type === "session_meta") rowAtMeta.push({ provider: r.provider, modelId: r.modelId });
+ if ((msg.payload as { type?: string }).type === "compaction_end") {
+ rowAtEnd.push({ provider: r.provider, modelId: r.modelId });
+ }
+ });
+ return {
+ messages,
+ events,
+ rowAtEnd,
+ rowAtMeta,
+ heldAt,
+ /** Each message's kind: its payload type, or `session_meta`. */
+ kinds: () =>
+ messages.map((m) =>
+ m.type === "session_meta" ? "session_meta" : (m.payload as { type?: string }).type,
+ ),
+ states: () => events.flatMap((e) => (e.type === "task_state" ? [e.state] : [])),
+ };
+ };
+
+ const usageModels = (): string[] =>
+ (
+ t.deps.db.prepare("SELECT model_id FROM usage_records ORDER BY id").all() as {
+ model_id: string;
+ }[]
+ ).map((r) => r.model_id);
+
+ const errorCode = async (res: Response): Promise<string> =>
+ ((await res.json()) as { error: { code: string } }).error.code;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "switcher");
+ api = apiClient(t.app, cookie);
+ // Two configured models with different windows (the compaction threshold must follow the
+ // switch); the third one a test names is deliberately absent.
+ const put = await api.put(`/api/projects/${PROJECT}/models`, {
+ defaultModel: A,
+ models: [
+ {
+ ...A,
+ apiKey: "sk-alpha",
+ baseUrl: "https://alpha.example/v1",
+ clientType: "openai",
+ contextWindow: WINDOW_A,
+ },
+ {
+ ...B,
+ apiKey: "sk-beta",
+ baseUrl: "https://beta.example/v1",
+ clientType: "openai",
+ contextWindow: WINDOW_B,
+ },
+ ],
+ });
+ expect(put.status).toBe(200);
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("400 for half a pair or a non-string half — nothing is inferred", async () => {
+ adopt(switchFake(A, { kind: "inline" }));
+ for (const body of [
+ { provider: "custom" },
+ { modelId: "m-beta" },
+ { provider: 1, modelId: "m-beta" },
+ { provider: "", modelId: "m-beta" },
+ ]) {
+ const res = await api.post(url, body);
+ expect(res.status).toBe(400);
+ expect(await errorCode(res)).toBe("bad_request");
+ }
+ expect(row().modelId).toBe(A.modelId);
+ });
+
+ it("409 same_model: the target is the model the Session already runs on", async () => {
+ const fake = switchFake(A, { kind: "inline" });
+ adopt(fake);
+ const res = await api.post(url, A);
+ expect(res.status).toBe(409);
+ expect(await errorCode(res)).toBe("same_model");
+ expect(fake.signals).toHaveLength(0); // core was never asked
+ });
+
+ it("409 model_not_configured: core finds no such entry in the Project config on disk", async () => {
+ adopt(
+ switchFake(A, {
+ kind: "throw",
+ error: new ModelSwitchRefusedError(
+ "model_not_configured",
+ "Model is not in the Project config: custom/m-nowhere.",
+ ),
+ }),
+ );
+ const res = await api.post(url, UNKNOWN);
+ expect(res.status).toBe(409);
+ expect(await errorCode(res)).toBe("model_not_configured");
+ expect(t.deps.manager.statusOf(SID)).toBe("idle");
+ expect(row().modelId).toBe(A.modelId);
+ });
+
+ it("409 model_unavailable: core cannot construct the target (no credential), or the runtime has no switch at all", async () => {
+ adopt(
+ switchFake(A, {
+ kind: "throw",
+ error: new ModelSwitchRefusedError(
+ "model_unavailable",
+ "Missing credentials for provider custom (api_key).",
+ ),
+ }),
+ );
+ const res = await api.post(url, B);
+ expect(res.status).toBe(409);
+ const body = (await res.json()) as { error: { code: string; message: string } };
+ expect(body.error.code).toBe("model_unavailable");
+ // The loader's wording is replaced by the remedy the Web App can act on.
+ expect(body.error.message).toContain("no API key");
+ expect(t.deps.manager.statusOf(SID)).toBe("idle");
+ expect(row().modelId).toBe(A.modelId);
+
+ // A runtime with no `switchModel` at all (core's "not available for this Session") reads
+ // the same way: the target exists, it just cannot be switched to here.
+ const noSwitch = switchFake(A, { kind: "inline" });
+ delete (noSwitch as Partial<SwitchFake>).switchModel;
+ t.deps.manager.adopt(row(), noSwitch);
+ const bare = await api.post(url, B);
+ expect(bare.status).toBe(409);
+ expect(await errorCode(bare)).toBe("model_unavailable");
+ expect(row().modelId).toBe(A.modelId);
+ });
+
+ it("409 compaction_not_configured: the Session has a context to close but no compaction to close it with", async () => {
+ adopt(
+ switchFake(A, {
+ kind: "throw",
+ error: new ModelSwitchRefusedError("compaction_not_configured", "no compaction here"),
+ }),
+ );
+ const res = await api.post(url, B);
+ expect(res.status).toBe(409);
+ expect(await errorCode(res)).toBe("compaction_not_configured");
+ expect(row().modelId).toBe(A.modelId);
+ });
+
+ it("anything else core throws before its first event is a failure, not a refusal: 500, and the row stays", async () => {
+ // An Agent State that no longer parses, a bootstrap that broke — mapped to a 409 they would
+ // tell the user to configure the model, which is not what happened.
+ const errors: string[] = [];
+ const original = console.error;
+ console.error = (line: string) => void errors.push(String(line));
+ try {
+ adopt(
+ switchFake(A, {
+ kind: "throw",
+ error: new Error("system_config.yaml: unexpected token at line 3"),
+ }),
+ );
+ const res = await api.post(url, B);
+ expect(res.status).toBe(500);
+ expect(await errorCode(res)).toBe("internal");
+ } finally {
+ console.error = original;
+ }
+ expect(errors.some((l) => l.includes("system_config.yaml: unexpected token"))).toBe(true);
+ expect(t.deps.manager.statusOf(SID)).toBe("idle");
+ expect(row().modelId).toBe(A.modelId);
+ });
+
+ it("the idle gate: 409 task_in_progress while a Task runs, 409 compacting while a switch is in flight, and a Task is refused during the switch", async () => {
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const fake = switchFake(A, { kind: "stream", status: "completed", gate });
+ // A run that parks too, on the same gate.
+ fake.run = async function* (): AsyncGenerator<OmniMessage> {
+ await gate;
+ yield assistantText("done");
+ };
+ adopt(fake);
+
+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "busy" }] });
+ await waitFor(() => t.deps.manager.statusOf(SID) === "running");
+ const whileRunning = await api.post(url, B);
+ expect(whileRunning.status).toBe(409);
+ expect(await errorCode(whileRunning)).toBe("task_in_progress");
+ release();
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+
+ let releaseSwitch = () => {};
+ const switchGate = new Promise<void>((resolve) => {
+ releaseSwitch = resolve;
+ });
+ const switching = switchFake(A, { kind: "stream", status: "completed", gate: switchGate });
+ t.deps.manager.adopt(row(), switching);
+ expect((await api.post(url, B)).status).toBe(202);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "compacting");
+ const whileSwitching = await api.post(url, B);
+ expect(whileSwitching.status).toBe(409);
+ expect(await errorCode(whileSwitching)).toBe("compacting");
+ const task = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "text", text: "wait" }],
+ });
+ expect(task.status).toBe(409);
+ expect(await errorCode(task)).toBe("compacting");
+ releaseSwitch();
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ expect(row().modelId).toBe(B.modelId);
+ });
+
+ it("202: streams a plain manual compaction and then the new context's session_meta; the row and the entry move to the target as that meta is published, and GET / plus the compaction threshold follow", async () => {
+ const fake = switchFake(A, { kind: "stream", status: "completed" });
+ adopt(fake);
+ const agentMax = (await t.deps.agentConfigService.getConfig(PROJECT, "default_agent")).config
+ .compaction?.maxContextLength;
+ const thresholdBefore = (
+ (await (await api.get(`/api/sessions/${SID}/context`)).json()) as SessionContextResponse
+ ).compactionThreshold;
+ expect(thresholdBefore).toBe(compactionThresholdFor(agentMax, WINDOW_A));
+ const feed = listen();
+
+ const res = await api.post(url, B);
+ expect(res.status).toBe(202);
+ expect((await res.json()) as TaskCreateResponse).toEqual({ sessionId: SID });
+ await waitFor(() => feed.states().includes("idle"));
+
+ expect(feed.states()).toEqual(["compacting", "idle"]);
+ expect(feed.kinds()).toEqual([
+ "compaction_begin",
+ "token_usage",
+ "compaction_end",
+ "tool_list_ready",
+ "session_meta",
+ ]);
+ // The opener's record is held for history reads until it is on the Trace; the meta says
+ // the new context's file is open, and nothing is pending any more.
+ expect(feed.heldAt.slice(-2)).toEqual([
+ ["tool_list_ready", 1],
+ ["session_meta", 0],
+ ]);
+ // Nothing on the pair names a model.
+ expect(feed.messages[2]!.payload).toEqual({
+ type: "compaction_end",
+ reason: "manual",
+ mode: "summarize",
+ status: "completed",
+ });
+ // The new model is on the new context's meta, a main-session record (no origin).
+ const meta = feed.messages[4]!;
+ expect(meta.origin).toBeUndefined();
+ expect(meta.payload).toMatchObject({ provider: B.provider, model_id: B.modelId });
+ // A client refetching the Session on that very record reads the new model: the row had
+ // already moved when the meta was published (and not yet when the end was).
+ expect(feed.rowAtEnd).toEqual([A]);
+ expect(feed.rowAtMeta).toEqual([B]);
+ expect(row()).toMatchObject(B);
+ const info = ((await (await api.get(`/api/sessions/${SID}`)).json()) as SessionResponse)
+ .session;
+ expect(info).toMatchObject(B);
+ const thresholdAfter = (
+ (await (await api.get(`/api/sessions/${SID}/context`)).json()) as SessionContextResponse
+ ).compactionThreshold;
+ expect(thresholdAfter).toBe(compactionThresholdFor(agentMax, WINDOW_B));
+ expect(thresholdAfter).not.toBe(thresholdBefore);
+ });
+
+ it("usage: the switch's compaction request bills to the previous model, the next Task to the new one", async () => {
+ adopt(switchFake(A, { kind: "stream", status: "completed" }));
+ expect((await api.post(url, B)).status).toBe(202);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ expect(usageModels()).toEqual([A.modelId]);
+
+ const task = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "text", text: "on the new model" }],
+ });
+ expect(task.status).toBe(202);
+ await waitFor(() => usageModels().length === 2);
+ expect(usageModels()).toEqual([A.modelId, B.modelId]);
+ });
+
+ it("a failed compaction leaves the row, the entry and the attribution on the previous model", async () => {
+ adopt(switchFake(A, { kind: "stream", status: "fatal" }));
+ const feed = listen();
+ expect((await api.post(url, B)).status).toBe(202);
+ await waitFor(() => feed.states().includes("idle"));
+ expect((feed.messages[2]!.payload as { status: string }).status).toBe("fatal");
+ // No switch, so no new context and no session_meta.
+ expect(feed.kinds()).toEqual(["compaction_begin", "token_usage", "compaction_end"]);
+ expect(feed.rowAtEnd).toEqual([A]);
+ expect(row()).toMatchObject(A);
+
+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "still A" }] });
+ await waitFor(() => usageModels().length === 2);
+ expect(usageModels()).toEqual([A.modelId, A.modelId]);
+ });
+
+ it("an aborted switch (POST /abort mid-compaction) ends `aborted` and leaves the row on the previous model", async () => {
+ const fake = switchFake(A, {
+ kind: "stream",
+ status: "completed",
+ gate: new Promise(() => {}),
+ });
+ adopt(fake);
+ const feed = listen();
+ expect((await api.post(url, B)).status).toBe(202);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "compacting" && fake.signals.length === 1);
+
+ expect((await api.post(`/api/sessions/${SID}/abort`, {})).status).toBe(202);
+ await waitFor(() => feed.states().includes("idle"));
+ expect(fake.signals[0]!.aborted).toBe(true);
+ const last = feed.messages[feed.messages.length - 1]!;
+ expect((last.payload as { status: string }).status).toBe("aborted");
+ expect(feed.rowAtMeta).toEqual([]);
+ expect(row()).toMatchObject(A);
+ expect(fake.modelId).toBe(A.modelId);
+ });
+
+ it("before its first event the switch is already the Session's run: POST /abort stops it, and nothing was announced until there was something to stream", async () => {
+ const fake = switchFake(A, { kind: "held" });
+ adopt(fake);
+ const feed = listen();
+ const pending = api.post(url, B);
+ await waitFor(() => fake.signals.length === 1);
+ // Core has not answered yet: the request is open, and no state has flipped.
+ expect(t.deps.manager.statusOf(SID)).toBe("idle");
+ expect(feed.events).toEqual([]);
+
+ expect((await api.post(`/api/sessions/${SID}/abort`, {})).status).toBe(202);
+ expect((await pending).status).toBe(202);
+ await waitFor(() => feed.states().includes("idle"));
+ expect(feed.states()).toEqual(["compacting", "idle"]);
+ expect(feed.kinds()).toEqual(["abort"]);
+ expect(row()).toMatchObject(A);
+ });
+
+ it("a deletion that lands before the switch's first event stops it and waits for it to end", async () => {
+ const fake = switchFake(A, { kind: "held" });
+ adopt(fake);
+ const pending = api.post(url, B);
+ await waitFor(() => fake.signals.length === 1);
+
+ const deleted = await api.delete(`/api/sessions/${SID}`);
+ expect(deleted.status).toBe(204);
+ // The run was over before the Session's files went: nothing of it can write afterwards.
+ expect(fake.signals[0]!.aborted).toBe(true);
+ expect(fake.ended).toBe(true);
+ await pending;
+ expect(t.deps.sessionsRepo.findById(SID)).toBeNull();
+ });
+
+ it("a main-session session_meta on the stream registers no child and records no error", async () => {
+ adopt(switchFake(A, { kind: "stream", status: "completed" }));
+ const feed = listen();
+ expect((await api.post(url, B)).status).toBe(202);
+ await waitFor(() => feed.states().includes("idle"));
+
+ // The meta reached subscribers as the switch's last record, without an origin…
+ const meta = feed.messages.at(-1)!;
+ expect(meta.type).toBe("session_meta");
+ expect(meta.origin).toBeUndefined();
+ // …and the drive read it as the main session's own record: no child row, no
+ // session_created event, no registration failure on record.
+ expect(t.deps.sessionsRepo.listByProject(PROJECT).map((r) => r.sessionId)).toEqual([SID]);
+ expect(feed.events.filter((e) => e.type === "session_created")).toEqual([]);
+ expect(t.deps.errorsRepo.recent(PROJECT).map((r) => r.code)).toEqual([]);
+ });
+
+ it("200: a Session that never ran switches inside the request — no events, the fresh DTO carries the new model, the row too", async () => {
+ adopt(switchFake(A, { kind: "inline" }));
+ const feed = listen();
+ const res = await api.post(url, B);
+ expect(res.status).toBe(200);
+ const { session } = (await res.json()) as SessionResponse;
+ expect(session).toMatchObject({ sessionId: SID, ...B });
+ expect(row()).toMatchObject(B);
+ expect(t.deps.manager.statusOf(SID)).toBe("idle");
+ // Nothing streamed: no compaction pair, no status flip.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(feed.messages).toEqual([]);
+ expect(feed.events).toEqual([]);
+ expect(usageModels()).toEqual([]);
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index e8f3ffcb..ca47f95a 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -976,6 +976,18 @@ router
if (!store.session(sessionId)) notFound("Session");
return json({ sessionId } satisfies TaskCreateResponse, 202);
})
+ // In-session model switch. The demo answers the way the server does for a Session that
+ // never ran: the row moves inside the request (200 with the Session), so the picker works
+ // without a compaction to stream.
+ .post("/api/sessions/:sessionId/switch-model", ({ store, params, body }): SessionResponse => {
+ const to = record(body);
+ const session = store.patchSession(params.sessionId!, {
+ ...(typeof to.provider === "string" ? { provider: to.provider } : {}),
+ ...(typeof to.modelId === "string" ? { modelId: to.modelId } : {}),
+ });
+ if (!session) notFound("Session");
+ return { session };
+ })
.get("/api/sessions/:sessionId/context", ({ store }): SessionContextResponse => store.f.context);
// ---------------------------------------------------------------------------------------------
diff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjs
index aeeaccf6..60517fc8 100644
--- a/packages/web/e2e/draft.spec.mjs
+++ b/packages/web/e2e/draft.spec.mjs
@@ -344,7 +344,8 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
await ta.fill("/model");
await ta.press("Enter");
- await expect(page.getByText("切换模型", { exact: true })).toBeVisible(); // picker title bar
+ // The model-picker dialog, named for what /model does (it has no visible title bar).
+ await expect(page.getByRole("dialog", { name: "换模型开新会话" })).toBeVisible();
await expect(ta).toHaveValue(""); // the command consumed its own token
await page.getByPlaceholder(/搜索模型/).fill("claude-4-8");
// Both models match the query (one id is the other's prefix); pick the non-mini one, i.e. not
@@ -357,7 +358,7 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
// Nothing was sent: we are still in the same Session, with the pick pinned as a chip — which
// is why the body can be typed AFTER the pick and still ride along.
await expect(page).toHaveURL(new RegExp(`/chat/${secondSessionId}$`));
- await expect(page.getByLabel("移除切换模型")).toBeVisible();
+ await expect(page.getByLabel("移除换模型目标")).toBeVisible();
await ta.fill("Fork body typed after the pick");
// The chip is draft content, cached in the SAME entry as the text (poll on the text: it is
@@ -370,7 +371,7 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
expect(await page.evaluate((k) => localStorage.getItem(k), sessionKey)).toContain("claude-4-8");
await page.reload();
await expect(ta).toHaveValue("Fork body typed after the pick");
- await expect(page.getByLabel("移除切换模型")).toBeVisible();
+ await expect(page.getByLabel("移除换模型目标")).toBeVisible();
// Enter performs the fork: a NEW Session on the picked model, same Agent, carrying the body.
await ta.press("Enter");
@@ -381,8 +382,9 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
const third = await (await page.request.get(`${BASE}/api/sessions/${thirdSessionId}`)).json();
expect(third.session.modelId).toBe("claude-4-8");
expect(third.session.agentId).toBe("agent_helper");
- // The source block collapses into the "switched model" banner, and the typed body follows it.
- await expect(page.getByText(/已切换模型(原为 claude-4-8-mini)/)).toBeVisible();
+ // The source block collapses into the "new conversation on another model" banner, and the
+ // typed body follows it.
+ await expect(page.getByText(/换模型新开的会话(原模型 claude-4-8-mini)/)).toBeVisible();
await expect(page.getByText("Fork body typed after the pick")).toBeVisible();
// —— /agent stages the handoff; Enter is what performs it ——
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 1e4bc30d..1fb24cee 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -172,6 +172,7 @@ import type {
PluginConfigUpdateRequest,
PluginReadmeResponse,
SessionsResponse,
+ SessionSwitchModelRequest,
SessionTracesResponse,
SkillArchiveInstallRequest,
SteerRequest,
@@ -1070,6 +1071,19 @@ export const postCompact = (sessionId: string) =>
body: {},
});
+/**
+ * Switch this Session to another model in place. Two success shapes: **202** with a
+ * {@link TaskCreateResponse} — the switch compacts on the current model first and streams like
+ * `/compact`; the new context's `session_meta` follows a completed compaction, and it is what
+ * says the Session switched — or **200** with a {@link SessionResponse} when the Session never
+ * ran and switched inside the request. Only the latter carries `session`.
+ */
+export const switchSessionModel = (sessionId: string, body: SessionSwitchModelRequest) =>
+ apiFetch<TaskCreateResponse | SessionResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/switch-model`,
+ { method: "POST", body },
+ );
+
/**
* Composition of the Session's current model context (the chat page's context-ring detail panel).
* A snapshot read from the newest Trace shard on each call, not a live counter: the figures are
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index aefccc73..f5dfe50a 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -7,9 +7,10 @@
* indicator) + Model + send (up arrow);
* In draft state (Session not yet created), when models/onChangeModel are supplied, the model
* selector sits to the left of the send button (provider logo + name; it opens the model-picker
- * dialog — search, provider-group rail, configured-key-first listing — see ModelCatalogSelect)
- * — once the Session is created the model is locked, and the same spot switches to a read-only
- * logo + name display;
+ * dialog — search, provider-group rail, configured-key-first listing — see ModelCatalogSelect). Once
+ * the Session exists the same selector switches the conversation's model in place (the parent
+ * confirms and compacts on the current model first); the subagent composer shows a read-only
+ * logo + name there instead;
* Draft state also renders a thinking-level picker left of the model selector (backed by the
* Agent settings: picking a level writes through to the Agent config and applies to the session
* created on first send); in session state the level is fixed (llmConfig is assembled once per
@@ -25,11 +26,12 @@
* and opens a picker (agents / models), and the pick becomes a highlighted chip above the text
* body instead of switching on the spot. The user
* keeps typing; **Enter/Send** performs the switch — an agent chip hands the conversation off to
- * a new chat for that agent (the current Session is not sent to), a model chip forks this
- * conversation onto the picked model. A model fork additionally waits for this Session to be
- * idle (it branches off a Trace that a run or a compaction is still appending to) and says so
- * above the composer rather than just disabling Send. With an empty text body the default
- * auto-message is filled in. Only one chip at a time (picking either clears the other, picking
+ * a new chat for that agent (the current Session is not sent to), a model chip opens a new
+ * conversation on the picked model that continues this one, which itself stays as it is (the
+ * toolbar's model picker is the in-place switch). A model fork additionally waits for this
+ * Session to be idle (it branches off a Trace that a run or a compaction is still appending
+ * to) and says so above the composer rather than just disabling Send. With an empty text body
+ * the default auto-message is filled in. Only one chip at a time (picking either clears the other, picking
* the model already in use clears the staging, and both are exclusive with goal mode); a chip is
* removed via backspace at the start of the text or its x button, and both are cached with the
* draft so they survive a session switch or reload along with the text they belong to;
@@ -132,6 +134,7 @@ import { sameModelRef } from "../models/model-grouping";
import { filterAgents, stagedSendRoute } from "./agent-handoff";
import { ModelCatalogSelect, modelLabel } from "./model-select";
import { ModelPickerModal } from "./model-picker-modal";
+import { sessionModelPickerDisabled } from "./model-switch";
import { matchSlash, removeSlashToken } from "./slash-token";
import { SELECTABLE_THINKING_LEVELS, thinkingLevelLabel } from "./thinking-level";
import { BOOK_ICON, buildSkillsMessage, localizedShortText, skillSlashItems } from "./skill-use";
@@ -602,6 +605,7 @@ export function ChatInput({
models,
onChangeModel,
onSwitchModel,
+ onPickSessionModel,
defaultModel,
thinkingLevel,
onChangeThinkingLevel,
@@ -716,20 +720,28 @@ export function ChatInput({
modelRef: ModelRefDto | null;
/**
* Candidate model list: when supplied together with onChangeModel, renders the model selector
- * to the left of the send button (draft state); when only models is supplied (session state),
- * it's used to look up the locked model's display name (read-only display).
+ * to the left of the send button (draft state); with onPickSessionModel instead (session
+ * state), the same selector switches this conversation's model; with neither (the subagent
+ * composer), it only looks up the model's display name for the read-only badge.
*/
models?: ModelInfo[];
- /** Changes the selected model in draft state; no longer passed once the Session is created and the model is locked. */
+ /** Changes the selected model in draft state; not passed once the Session exists. */
onChangeModel?: (ref: ModelRefDto) => void;
/**
- * Session state: model switch via the `/model` command — forks the session onto the picked
- * model (a NEW session carrying this conversation) and navigates there; the draft written
- * after the pick is posted as the new session's first task. Returns whether it succeeded
+ * Session state: the `/model` handoff — opens a NEW session on the picked model carrying this
+ * conversation and navigates there; the draft written after the pick is posted as the new
+ * session's first task, and this conversation stays as it is. Returns whether it succeeded
* (draft kept on failure). Only passed for an active session (the command is additionally
* gated on not running/compacting); picking the current model is a no-op.
*/
onSwitchModel?: (ref: ModelRefDto, input: TaskInputPart[]) => Promise<boolean>;
+ /**
+ * Session state: a pick in the toolbar's model picker, which switches THIS conversation onto
+ * the picked model (compacting on the current one first). The parent owns the decision and
+ * the confirm dialog; the picker only reports the pick, and is disabled while a Task runs or
+ * a compaction is under way. Not passed to the subagent composer, whose badge stays display-only.
+ */
+ onPickSessionModel?: (ref: ModelRefDto) => void;
/** Project default model (marked "default" on the selector's candidate item). */
defaultModel?: ModelRefDto;
/**
@@ -853,7 +865,7 @@ export function ChatInput({
* — minus what a child has no semantics for (goal mode, image/file attachments and the "+"
* menu carrying them, paste/drop file intake; /compact and the follow-up queue are already
* gated by their absent callbacks). The model badge is inert here: a child cannot switch
- * model or agent, so there is no locked-model hint to click for.
+ * model or agent.
*/
variant?: "session" | "subagent";
/**
@@ -1091,8 +1103,8 @@ export function ChatInput({
const canMidRunSend = steerAction || queueAction;
const midRunSendLabel = midRun === "queue" ? S.chat.followUpSend : S.chat.steerSend;
const stopAction = isStopAction(status, midRun);
- // Locked-model badge text (session and subagent variants): the catalog's display name when
- // the model is known, the raw id otherwise.
+ // Display-only model badge text (see the badge below): the catalog's display name when the
+ // model is known, the raw id otherwise.
const lockedModelLabel = (() => {
const m = models?.find((x) => sameModelRef(x, modelRef));
return m ? modelLabel(m) : (modelRef?.modelId ?? "…");
@@ -2119,12 +2131,12 @@ export function ChatInput({
/>
)}
- {/* /model switch picker (session state): the same model-picker dialog the draft's model
+ {/* /model handoff picker (session state): the same model-picker dialog the draft's model
selector opens, on the session's model; picking it is a no-op. The /model token was
already consumed when the command ran, so cancelling (Escape / overlay click) keeps
the remaining draft and cannot re-open the slash menu, and the dialog hands focus back
- to the textarea it was opened from. A pick only stages the chip below — the switch
- happens on send. */}
+ to the textarea it was opened from. A pick only stages the chip below — the new
+ conversation opens on send. */}
{models && (
<ModelPickerModal
open={modelSwitchOpen}
@@ -2520,7 +2532,10 @@ export function ChatInput({
note={S.chat.thinkingLevelChangeNote}
/>
)}
- {/* Left of the send button: model selector in draft state; once the Session is created the model is locked, shown read-only (still with the provider logo). */}
+ {/* Left of the send button: the model selector. In draft state it picks the model the
+ Session will be created on; in session state it switches this conversation's
+ model (the parent confirms, then compacts on the current model first), so it is
+ disabled whenever a compaction could not start. */}
{models && onChangeModel ? (
<ModelCatalogSelect
models={models}
@@ -2529,9 +2544,19 @@ export function ChatInput({
onChange={onChangeModel}
disabled={busy}
/>
- ) : variant === "subagent" ? (
- /* Subagent composer: the child runs whatever model it was spawned with, and no
- /model command exists here — so the badge is pure display, nothing to click. */
+ ) : models && onPickSessionModel && variant === "session" ? (
+ <ModelCatalogSelect
+ models={models}
+ value={modelRef}
+ {...(defaultModel !== undefined ? { defaultModel } : {})}
+ onChange={onPickSessionModel}
+ disabled={busy || sessionModelPickerDisabled(status)}
+ />
+ ) : (
+ /* Display-only badge: the subagent composer (a child runs whatever model it was
+ spawned with and has no switch surface), and a session composer until its
+ model list has loaded. Both the logo and the name come from the DTO's paired
+ fields (no prefix parsing). */
<span
data-tooltip={modelRef?.modelId ?? ""}
className="flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 rounded-md px-1 text-gray-400 dark:text-gray-500"
@@ -2542,27 +2567,6 @@ export function ChatInput({
/>
<span className="hidden min-w-0 truncate @md:block">{lockedModelLabel}</span>
</span>
- ) : (
- /* Read-only display in session state: both the logo and the name come from the
- Session DTO's paired fields (no prefix parsing). A button rather than a plain
- span: the model is locked here, and clicking it explains the one way to switch
- (the /model command) instead of doing nothing. */
- <button
- type="button"
- data-tooltip={modelRef?.modelId ?? ""}
- // Short accessible name (the toast carries the full hint): the long copy
- // contains the literal "发送"/"Send", which would collide with the send
- // button's accessible name for assistive tech and name-based test queries.
- aria-label={`${S.chat.model} ${modelRef?.modelId ?? ""}`}
- onClick={() => toastInfo(S.chat.modelLockedHint)}
- className="flex h-8 min-w-0 max-w-44 shrink cursor-pointer items-center gap-1.5 rounded-md px-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
- >
- <ProviderLogo
- provider={modelRef?.provider ?? "custom"}
- className="h-4 w-4 shrink-0"
- />
- <span className="hidden min-w-0 truncate @md:block">{lockedModelLabel}</span>
- </button>
)}
{/* One action button, never two: while running an empty composer means "Stop"
(abort), and typing turns the very same button into "Send" — which, mid-run,
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 6c49673f..c4a7f523 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -129,6 +129,9 @@ import { buildInputHistory } from "./input-history";
import { buildOutline } from "./outline-model";
import { GoalStatusBanner } from "./goal-banner";
import { handoffMessage, modelSwitchMessage } from "./agent-handoff";
+import { modelLabel } from "./model-select";
+import { sessionModelPickerDisabled, sessionRowStale, switchContextShape } from "./model-switch";
+import type { SwitchContextShape } from "./model-switch";
import { hasConfiguredKey, promotedPricing, sameModelRef } from "../models/model-grouping";
import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import { WorkspaceBrowser } from "./workspace-browser";
@@ -357,6 +360,17 @@ export function ChatPage() {
// the pick is held until the compaction completes. Logic in thinking-level.ts
// (needsThinkingSwitchConfirm / thinkingSwitchAfterCompaction).
const [thinkingSwitch, setThinkingSwitch] = useState<StagedThinkingSwitch | null>(null);
+ // A pick in the session toolbar's model picker, waiting on its confirm dialog (null = no
+ // dialog). `shape` is what the switch will do to the context — compact it first, switch an
+ // empty conversation at once, or continue from a summary already held — so the dialog and
+ // the toast promise only that. See onPickSessionModel / confirmModelSwitch.
+ const [modelSwitchAsk, setModelSwitchAsk] = useState<{
+ to: ModelRefDto;
+ shape: SwitchContextShape;
+ } | null>(null);
+ // The dialog stays open (its buttons busy) until the switch request answers, so a double
+ // click cannot post the switch twice.
+ const [modelSwitchPosting, setModelSwitchPosting] = useState(false);
const routeSessionId = params.sessionId ?? null;
// The docks' arrangement lives in the dock store (features/dock) — tabs, active tab,
@@ -973,6 +987,7 @@ export function ChatPage() {
// Session switch: resets the usage-fetch marker, the file-card existence cache, any
// thinking-level switch staged behind its dialog (per-session UI state — a compaction
// that self-heals to a new session id routes through here too and drops the held pick),
+ // a model switch waiting behind its own dialog (it was asked of the conversation left),
// and the popover's per-session data (process list / token buckets),
// avoiding stale data from the previous Session (the panel jump commands reset in their
// own effect above, and the cost hold re-keys itself inside advanceCostStat). The thinking level itself needs no reset — it is read off the
@@ -980,6 +995,7 @@ export function ChatPage() {
useEffect(() => {
usageAppliedRef.current = null;
setThinkingSwitch(null);
+ setModelSwitchAsk(null);
statCacheRef.current = new Map();
setProcesses([]);
setUsageBuckets(null);
@@ -1486,6 +1502,19 @@ export function ChatPage() {
composerRef.current?.addReference(reference);
}, []);
+ // A fresh Session row from the server, applied wherever the page reads the row from: the
+ // paged list, and the direct lookup's copy for a row the list does not hold (see
+ // resolveRoutedSession).
+ const applySessionRow = useCallback(
+ (session: SessionInfo) => {
+ replace(session);
+ setFetchedSession((cur) =>
+ cur !== null && cur.sessionId === session.sessionId ? session : cur,
+ );
+ },
+ [replace],
+ );
+
// Pins a picked level on the Session so it outlives this tab: PATCH, then swap the
// returned row into the session store (the picker reads it back from there); it applies
// from the next LLM request (the picker's menu advises compacting first). Modeled on
@@ -1709,6 +1738,96 @@ export function ChatPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [stream.version, stream.model, thinkingSwitch, applyTurnThinkingLevel]);
+ /** A model's display label for the switch dialog and its toasts: the configured name, else the id. */
+ const modelDisplay = useCallback(
+ (ref: ModelRefDto): string => {
+ const m = models?.models.find((x) => sameModelRef(x, ref));
+ return m ? modelLabel(m) : ref.modelId;
+ },
+ [models],
+ );
+
+ // Session toolbar model picker: switches THIS conversation's model (the `/model` handoff opens
+ // a new conversation instead). Re-picking the current model does nothing, and neither does a
+ // pick that raced a Task starting (the picker is disabled then, and the server would refuse
+ // it anyway); any other pick asks first, worded for what the switch will do: compact the
+ // context on the current model before moving on, or — right after a compaction or a switch,
+ // when there is nothing to compact — continue on the picked model from what is already held.
+ const onPickSessionModel = useCallback(
+ (ref: ModelRefDto) => {
+ if (!selected || sameModelRef(ref, selected)) return;
+ if (sessionModelPickerDisabled(stream.taskState)) return;
+ // Read at pick time: the model's items mutate in place. The live tail decides, behind
+ // whatever window was backfilled above it.
+ const shape = switchContextShape([...stream.prefixItems, ...stream.model.items]);
+ setModelSwitchAsk({ to: ref, shape });
+ },
+ [selected, stream.taskState, stream.prefixItems, stream.model],
+ );
+
+ // The dialog's confirm. 202 = the switch is streaming: the compaction row (or, right after a
+ // compaction, the model-change marker alone) carries it from here, and the effect below moves
+ // the Session row once the new context's session_meta names the new model. 200 = the Session
+ // never ran and switched inside the request: the row comes back with the response — under a
+ // new id when the server had to rebuild a Session that left no Trace, which the page follows.
+ // A refusal (409 busy / same model / not configured / unavailable / compaction not configured)
+ // is a toast.
+ const confirmModelSwitch = useCallback(async () => {
+ const ask = modelSwitchAsk;
+ if (!selected || ask === null || modelSwitchPosting) return;
+ setModelSwitchPosting(true);
+ const from = modelDisplay({ provider: selected.provider, modelId: selected.modelId });
+ const to = modelDisplay(ask.to);
+ try {
+ const res = await api.switchSessionModel(selected.sessionId, {
+ provider: ask.to.provider,
+ modelId: ask.to.modelId,
+ });
+ if ("session" in res) {
+ applySessionRow(res.session);
+ toastSuccess(S.chat.modelSwitchInSessionApplied(to));
+ await syncHealedSessionId(selected.sessionId, res.session.sessionId);
+ return;
+ }
+ // Only a switch that compacts may say so; one that continues from a held summary runs
+ // no compaction and must not promise one.
+ toastInfo(
+ ask.shape === "compact"
+ ? S.chat.modelSwitchInSessionStarted(from, to)
+ : S.chat.modelSwitchInSessionSwitching(to),
+ );
+ } catch (e) {
+ // The codes that take a model name are about the model the Session is on (its loader's
+ // missing credential); a refusal of the target names it in its own message.
+ toastError(apiErrorText(e, { modelId: selected.modelId }));
+ } finally {
+ setModelSwitchPosting(false);
+ setModelSwitchAsk(null);
+ }
+ }, [
+ modelSwitchAsk,
+ modelSwitchPosting,
+ selected,
+ modelDisplay,
+ applySessionRow,
+ syncHealedSessionId,
+ ]);
+
+ // The Session row (model badge, context window, window notice, header price) follows the
+ // model the conversation is on: when the running context's session_meta names another model
+ // than the row on hand — a switch completed, on this tab or another one watching the
+ // Session, or the row was held from before a switch — the row moves to it in place, the way
+ // a title does. The server moved its own row before it published that record. Runs per
+ // stream version because the model mutates in place.
+ useEffect(() => {
+ const running = stream.model.contextModel;
+ if (!selected || running === null || stream.loading) return;
+ if (!sessionRowStale(running, selected)) return;
+ applySessionRow({ ...selected, provider: running.provider, modelId: running.modelId });
+ // `version` is the model's change signal.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [stream.version, stream.model, stream.loading, selected, applySessionRow]);
+
// "New Chat" = enter draft state: no Session is created until the first message is sent.
// Typed-but-unsent text in the ACTIVE new-chat draft first becomes a parked draft
// conversation (a sidebar row, sendable anytime) instead of lingering invisibly in the
@@ -1759,12 +1878,16 @@ export function ChatPage() {
[selected, addSession, navigate],
);
- // Real-time cost for this turn: converts the Task's bucketed usage using the session Model's
- // (paired reference) current pricing; null if no pricing is configured. That pricing is the
- // list price, so a promotion the models response reports for the Model comes off it here, as
- // it does on the recorded cost.
- const activeModel = models?.models.find((m) => sameModelRef(m, activeModelRef));
- const modelPricing = promotedPricing(activeModel?.pricing, activeModel?.discount);
+ // Real-time cost for a turn: converts the Task's bucketed usage using a Model's (paired
+ // reference) current pricing; null if no pricing is configured. That pricing is the list
+ // price, so a promotion the models response reports for the Model comes off it here, as it
+ // does on the recorded cost. A Task is priced on the model it ran on when its row names one
+ // (a Session can switch models between Tasks), else on the Session's own.
+ const pricingOf = (ref: ModelRefDto | null) => {
+ const m = models?.models.find((x) => sameModelRef(x, ref));
+ return promotedPricing(m?.pricing, m?.discount);
+ };
+ const modelPricing = pricingOf(activeModelRef);
const ctx: StreamRenderContext = {
pendingApprovals: stream.pendingApprovals,
onApprove,
@@ -1774,7 +1897,8 @@ export function ChatPage() {
// happen mid-turn, and if only running were checked, the trailing group would flash
// "finished running" during compaction before flipping back to "running".
taskRunning: stream.taskState !== "idle",
- taskCost: (stats) => bucketCostUsd(stats.tokensByBucket, modelPricing),
+ taskCost: (stats, model) =>
+ bucketCostUsd(stats.tokensByBucket, model ? pricingOf(model) : modelPricing),
// Reconnect countdown controls (live waiting state only): retry-now skips the
// remaining backoff server-side (benign no-op on timing races), give-up is the
// ordinary session abort — the engine's abort-during-backoff path ends the turn.
@@ -2003,10 +2127,10 @@ export function ChatPage() {
const emptyChat =
selected !== null && !stream.loading && !stream.error && stream.model.items.length === 0;
- // Input area in session state: Agent / Workspace / Model are already locked by the Session
- // (the model selector isn't rendered; models feeds the locked model's read-only display and
- // the /model switch picker) — approval mode and the per-turn thinking level stay editable;
- // /model forks the conversation onto another model.
+ // Input area in session state: Agent and Workspace are fixed by the Session. The toolbar's
+ // model picker switches this conversation's model in place (confirmed, compacting first);
+ // approval mode and the thinking level stay editable; /model opens a NEW conversation on
+ // another model and leaves this one as it is.
const input = selected && (
<ChatInput
controlRef={composerRef}
@@ -2029,6 +2153,7 @@ export function ChatPage() {
{...(models !== null ? { models: models.models } : {})}
{...(models?.defaultModel !== undefined ? { defaultModel: models.defaultModel } : {})}
onSwitchModel={onSwitchModel}
+ onPickSessionModel={onPickSessionModel}
// Display value: the level pinned on this Session, else the Agent config's level
// (auto-follow while unpinned; the send path uses the raw pin — see onSend).
turnThinkingLevel={sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel)}
@@ -2639,6 +2764,50 @@ export function ChatPage() {
</p>
)}
</ConfirmModal>
+
+ {/* In-conversation model switch confirmation (the session toolbar's model picker), two
+ choices only: compact and switch, or cancel. There is no "switch anyway" — a switch
+ always compacts on the current model first, and a failed compaction keeps it. The two
+ shapes with nothing to compact read "switch" instead: an empty transcript (the switch
+ is immediate) and a transcript ending in a completed compaction or a model switch (no
+ compaction runs; the conversation continues from what is already held). The session
+ can start running while the dialog is up (a queued follow-up, a schedule): the confirm
+ is then disabled and the body says why, exactly like the thinking dialog. */}
+ <ConfirmModal
+ open={modelSwitchAsk !== null}
+ title={S.chat.modelSwitchInSessionTitle}
+ tone="primary"
+ confirmLabel={
+ modelSwitchAsk?.shape === "compact"
+ ? S.chat.modelSwitchInSessionConfirm
+ : S.chat.modelSwitchInSessionDirectConfirm
+ }
+ cancelLabel={S.common.cancel}
+ confirmDisabled={stream.taskState !== "idle"}
+ busy={modelSwitchPosting}
+ onConfirm={() => void confirmModelSwitch()}
+ onClose={() => {
+ if (!modelSwitchPosting) setModelSwitchAsk(null);
+ }}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {modelSwitchAsk === null || selected === null
+ ? null
+ : modelSwitchAsk.shape === "empty"
+ ? S.chat.modelSwitchInSessionDirectBody(modelDisplay(modelSwitchAsk.to))
+ : modelSwitchAsk.shape === "compacted"
+ ? S.chat.modelSwitchInSessionCompactedBody(modelDisplay(modelSwitchAsk.to))
+ : S.chat.modelSwitchInSessionBody(
+ modelDisplay({ provider: selected.provider, modelId: selected.modelId }),
+ modelDisplay(modelSwitchAsk.to),
+ )}
+ </p>
+ {stream.taskState !== "idle" && (
+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ {S.chat.thinkingSwitchBusyHint}
+ </p>
+ )}
+ </ConfirmModal>
</div>
);
}
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index c57e9669..9397e448 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -346,6 +346,23 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
return <ReconnectLine item={item} ctx={ctx} />;
case "compaction":
return <CompactionBanner item={item} />;
+ case "model_change": {
+ // A slim divider between two contexts on different models (an in-session model switch),
+ // named by model id: it renders from the Trace alone, so a model removed from the
+ // configuration since still reads. One id under two providers is told apart by the pair.
+ const sameId = item.from.modelId === item.to.modelId;
+ const name = (m: { provider: string; modelId: string }): string =>
+ sameId ? `${m.provider} / ${m.modelId}` : m.modelId;
+ return (
+ <div className="anim-msg my-3 flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
+ <span aria-hidden className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />
+ <span className="min-w-0 break-words text-center">
+ {S.chat.modelChanged(name(item.from), name(item.to))}
+ </span>
+ <span aria-hidden className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />
+ </div>
+ );
+ }
case "mcp_connect":
return <McpConnectBanner item={item} />;
case "task_stats":
@@ -377,7 +394,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
<TaskStatsLine
stats={item.stats}
assistantText={item.assistantText}
- cost={item.stats ? (ctx.taskCost?.(item.stats) ?? null) : null}
+ cost={item.stats ? (ctx.taskCost?.(item.stats, item.model) ?? null) : null}
{...(item.atMs !== undefined ? { atMs: item.atMs } : {})}
{...(ctx.origin.length === 0 && item.forkable && ctx.onFork
? { onFork: ctx.onFork }
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index c77fa1b3..55ad1874 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -44,8 +44,8 @@ export interface StreamRenderContext {
* long as the model might still call another tool, the trailing group always shows "Running".
*/
taskRunning: boolean;
- /** Converts this turn's stats into cost (USD) using the current Model pricing; returns null when no price is configured (cost is hidden). */
- taskCost?: (stats: TaskStats) => number | null;
+ /** Converts this turn's stats into cost (USD) at the current pricing of `model`, the model the turn ran on (the Session's own when the turn names none); returns null when no price is configured (cost is hidden). */
+ taskCost?: (stats: TaskStats, model?: { provider: string; modelId: string }) => number | null;
/**
* "Retry now" on the live reconnect countdown: skips the remaining backoff wait
* server-side (POST /retry-now); the line flips to "retrying" when the request_begin
diff --git a/packages/web/src/features/chat/model-switch.ts b/packages/web/src/features/chat/model-switch.ts
new file mode 100644
index 00000000..41217820
--- /dev/null
+++ b/packages/web/src/features/chat/model-switch.ts
@@ -0,0 +1,65 @@
+/**
+ * In-conversation model switch (the active Session's toolbar model picker): the decisions the
+ * chat page makes, kept pure so they are testable without a DOM.
+ *
+ * The switch is not the `/model` handoff. `/model` opens a NEW conversation on another model
+ * and leaves this one as it is; this picker keeps the conversation and moves it onto the
+ * picked model. That compacts on the current model first (`POST …/switch-model` answers 202 and
+ * streams an ordinary compaction row, then the new context's `session_meta`), except for a
+ * Session that never ran, which has no context to compact and switches inside the request (200
+ * with the updated Session). Only that `session_meta` says the Session moved: the stream model
+ * turns it into a model-change marker, and the page moves its Session row to the model it
+ * names (see sessionRowStale). A compaction that fails streams no meta, and the Session stays
+ * on the model it was on.
+ */
+import type { ModelRefDto, SessionInfo, SessionStatus } from "@prismshadow/penguin-server/api";
+import { sameModelRef } from "../models/model-grouping";
+import { trailingCompaction } from "./thinking-level";
+import type { ThinkingSwitchItem } from "./thinking-level";
+
+/**
+ * Whether the picker is disabled: a switch compacts, and the server neither starts nor queues a
+ * compaction while a Task runs or another compaction is under way.
+ */
+export function sessionModelPickerDisabled(status: SessionStatus): boolean {
+ return status === "running" || status === "compacting";
+}
+
+/**
+ * What the switch will do to the context, read off the loaded transcript — the dialog and the
+ * toast promise exactly that and no more:
+ * - `"compact"` — there is conversation since the last compaction: the switch compacts it on
+ * the current model first, and the stream carries that compaction;
+ * - `"empty"` — nothing at all yet: the switch is immediate (the server answers 200);
+ * - `"compacted"` — the transcript ends in a completed compaction or a model switch with
+ * nothing said since: the server runs no compaction and streams no pair, and the
+ * conversation continues on the target from what that context opened with.
+ */
+export type SwitchContextShape = "compact" | "empty" | "compacted";
+
+/** Reads the shape off the transcript's end, the way the thinking switch's guard does (see `trailingCompaction`). */
+export function switchContextShape(items: ReadonlyArray<ThinkingSwitchItem>): SwitchContextShape {
+ if (items.length === 0) return "empty";
+ return trailingCompaction(items).compacted ? "compacted" : "compact";
+}
+
+/**
+ * Whether the Session row on hand names another model than the conversation is on: the running
+ * context's `session_meta` (the stream model's `contextModel`) is of this Session and says so —
+ * a switch completed, on this tab or another one watching the Session, or the row was held from
+ * before a switch. The page then moves the row to that model; the server moved its own before
+ * it published the record. False while no meta of this Session has been seen: a history window
+ * that starts after the context's meta derives nothing, and the stream of a conversation the
+ * page has just left says nothing about the row it now holds.
+ */
+export function sessionRowStale(
+ contextModel: (ModelRefDto & { sessionId: string }) | null,
+ row: Pick<SessionInfo, "sessionId" | "provider" | "modelId"> | null,
+): boolean {
+ return (
+ contextModel !== null &&
+ row !== null &&
+ contextModel.sessionId === row.sessionId &&
+ !sameModelRef(contextModel, row)
+ );
+}
diff --git a/packages/web/src/features/chat/thinking-level.ts b/packages/web/src/features/chat/thinking-level.ts
index a7291ca1..31096fbe 100644
--- a/packages/web/src/features/chat/thinking-level.ts
+++ b/packages/web/src/features/chat/thinking-level.ts
@@ -145,6 +145,30 @@ export interface ThinkingSwitchItem {
status?: string;
}
+/**
+ * Reads the end of a transcript: the trailing run of housekeeping rows — compaction banners,
+ * the model-change marker of a model switch, and the MCP connect row of a context whose
+ * servers had to be connected again. `compacted` says the context in effect is a new one with
+ * nothing said on it yet: a compaction in that run completed (a failed retry after it changed
+ * nothing), or a model switch opened it — a switch away from a context that had not answered
+ * runs no compaction and leaves the marker alone. A compaction that failed or is still running
+ * leaves the old context in effect. `before` counts the items ahead of the run.
+ */
+export function trailingCompaction(items: ReadonlyArray<ThinkingSwitchItem>): {
+ compacted: boolean;
+ before: number;
+} {
+ let last = items.length - 1;
+ let compacted = false;
+ while (last >= 0 && ["compaction", "model_change", "mcp_connect"].includes(items[last]!.kind)) {
+ const c = items[last]!;
+ if (c.kind === "model_change") compacted = true;
+ if (c.kind === "compaction" && !c.running && c.status === "completed") compacted = true;
+ last--;
+ }
+ return { compacted, before: last + 1 };
+}
+
/**
* Whether the loaded transcript indicates provider-side history whose prefix cache a
* thinking-level change would invalidate (issue #310): some providers implement the
@@ -157,22 +181,14 @@ export interface ThinkingSwitchItem {
* has a non-empty tail, and the trailing-compaction check below only looks at the tail.
* - A transcript that ENDS in a settled successful compaction is also free to switch: the
* provider context was just rewritten to a short summary, so the user who followed the
- * "compact first, then switch" advice is not warned a second time. Failed or still
- * running trailing compactions don't count (the old context is still in effect), but a
- * successful one anywhere in the trailing compaction run does (a failed retry after a
- * success changed nothing).
+ * "compact first, then switch" advice is not warned a second time. So is one that ends in a
+ * model switch: the context that switch opened has not been sent yet (see
+ * `trailingCompaction` for what counts).
*/
export function prefixCacheAtRisk(items: ReadonlyArray<ThinkingSwitchItem>): boolean {
- let last = items.length - 1;
- let compacted = false;
- while (last >= 0 && items[last]!.kind === "compaction") {
- const c = items[last]!;
- if (!c.running && c.status === "completed") compacted = true;
- last--;
- }
- // Nothing but (at most) compaction rows: no billable history to protect.
- if (last < 0) return false;
- return !compacted;
+ const { compacted, before } = trailingCompaction(items);
+ // Nothing but (at most) housekeeping rows: no billable history to protect.
+ return before > 0 && !compacted;
}
/**
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 9dc3d99e..c40ab566 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -364,6 +364,22 @@ export interface CompactionItem {
summaryDurationMs?: number;
}
+/**
+ * The Session moved to another model between two contexts: derived from two consecutive
+ * main-session `session_meta` records naming different (provider, model_id) pairs — an
+ * in-session model switch opens its new context on the model the user picked, and nothing else
+ * on the stream says so. Model ids rather than display names: the marker renders from the Trace
+ * alone, and a model removed from the configuration since must still read.
+ */
+export interface ModelChangeItem {
+ kind: "model_change";
+ id: number;
+ from: { provider: string; modelId: string };
+ to: { provider: string; modelId: string };
+ /** The timestamp of the `session_meta` that named the new model (ms). */
+ tsMs?: number;
+}
+
/** One MCP tool for the connect row's expandable list (from tool_list_ready, `mcp__` entries only). */
export interface McpToolSummary {
name: string;
@@ -431,6 +447,12 @@ export interface TaskStatsItem {
forkable?: boolean;
/** Memory topic files this Task changed through the structured file tools (merged, one row per file); absent when there were none. */
memoryChanges?: MemoryChangeRow[];
+ /**
+ * The model this Task ran on — the one its context's `session_meta` names (see
+ * `StreamModel.contextModel`). Absent when the window held no meta before the Task began;
+ * the cost shown beside the row is then priced on the Session's current model.
+ */
+ model?: { provider: string; modelId: string };
}
export type ChatItem =
@@ -446,6 +468,7 @@ export type ChatItem =
| LlmErrorItem
| ReconnectItem
| CompactionItem
+ | ModelChangeItem
| McpConnectItem
| TaskStatsItem;
@@ -475,6 +498,16 @@ export interface StreamModel {
meta: NestedSessionMeta | null;
/** Absolute `agent_state` path from session_meta (null until it arrives); the Memory root `<agent_state>/memory/` for the Task summary's memory-change rows. */
agentState: string | null;
+ /**
+ * The model the running context was opened on, and the Session its `session_meta` names (null
+ * until one arrives). A Session's model can change between contexts — each context's meta
+ * records its own — so this follows rotations, and a main-session meta naming another model
+ * than the one held pushes a model-change marker. The chat page moves its Session row to this
+ * model when the two disagree (see `sessionRowStale`).
+ */
+ contextModel: { sessionId: string; provider: string; modelId: string } | null;
+ /** `contextModel` as the open Task began: a switch only happens between Tasks, so this is the model the whole Task runs on (see `TaskStatsItem.model`). */
+ taskModel: { provider: string; modelId: string } | null;
/**
* Elapsed-time stamps for the subagents panel's topology nodes (nested models only — the main
* session's timing is covered by task stats). Stamped in routeNested: the `firstSeen` pair when
@@ -611,6 +644,8 @@ function newModel(nested: boolean, localDecisions: Set<string>): StreamModel {
nested,
meta: null,
agentState: null,
+ contextModel: null,
+ taskModel: null,
stats: createTaskStatsTracker(),
openText: null,
openThinking: null,
@@ -732,15 +767,36 @@ export function pushMessage(
advanceLastTs(model, msg.timestamp);
return;
}
- // session_meta: never rendered as an item, but read at BOTH levels. Both keep the
+ // session_meta: never rendered as an item itself, but read at BOTH levels. Both keep the
// agent_state path — the main session's Task summary classifies file-tool writes against
// `<agent_state>/memory/` for its memory-change rows, so a model built from a window that
// never carries a session_meta derives none. A NESTED child session additionally has no DTO
// loaded here, so it captures the identity the subagents panel needs (which agent runs this
// child, on which model); the main session takes the rest of its identity/config from the
- // Session DTO. A rewritten session_meta (file rotation) overwrites with the same values.
+ // Session DTO. A rewritten session_meta (file rotation) overwrites with the same values. On
+ // the main session a meta naming another model than the one held means the Session switched
+ // models: a marker says so — never for the window's first meta, a same-model rewrite, or a
+ // nested child's meta.
if (msg.type === "session_meta") {
- model.agentState = (msg.payload as SessionMetaPayload).agent_state;
+ const p = msg.payload as SessionMetaPayload;
+ model.agentState = p.agent_state;
+ const next = { provider: p.provider, modelId: p.model_id };
+ const held = model.contextModel;
+ if (
+ !model.nested &&
+ held !== null &&
+ (held.provider !== next.provider || held.modelId !== next.modelId)
+ ) {
+ const tsMs = tsOf(msg.timestamp);
+ model.items.push({
+ kind: "model_change",
+ id: nextId(model),
+ from: { provider: held.provider, modelId: held.modelId },
+ to: next,
+ ...(tsMs !== undefined ? { tsMs } : {}),
+ });
+ }
+ model.contextModel = { sessionId: p.session_id, ...next };
}
if (msg.type === "session_meta" && model.nested) {
const p = msg.payload as SessionMetaPayload;
@@ -924,6 +980,10 @@ function startTask(model: StreamModel, timestamp: string, nowMs: number): void {
model.turnToolOutputs = false;
model.reopenTaskAtSteering = false;
model.taskOpen = true;
+ model.taskModel = model.contextModel && {
+ provider: model.contextModel.provider,
+ modelId: model.contextModel.modelId,
+ };
model.taskStartLocalMs = nowMs;
const ts = Date.parse(timestamp);
model.taskFirstTsMs = Number.isFinite(ts) ? ts : nowMs;
@@ -977,17 +1037,19 @@ function finalizeOpenTask(model: StreamModel): void {
...(reply.atMs !== undefined ? { atMs: reply.atMs } : {}),
...(reply.tracePosition !== undefined ? { forkPosition: reply.tracePosition } : {}),
...(memoryChanges.length > 0 ? { memoryChanges } : {}),
+ ...(model.taskModel ? { model: model.taskModel } : {}),
};
- // The stats row is inserted **before any trailing run of compaction banners**: compaction
- // is its own round, housekeeping outside this one, so it belongs after this round's ledger
- // — a banner sandwiched between the reply and the row (assistant_text → compaction →
- // task_stats) reads as if the row were the compaction's own stats.
+ // The stats row is inserted **before any trailing run of compaction banners** (and the
+ // model-change markers a switch's compaction leaves behind them): compaction is its own
+ // round, housekeeping outside this one, so it belongs after this round's ledger — a banner
+ // sandwiched between the reply and the row (assistant_text → compaction → task_stats) reads
+ // as if the row were the compaction's own stats.
// A wrap-up compaction normally settles the round on arrival, before its banner exists
// (see isWrapUpCompaction), so this loop is what still places the row correctly in the
// cases that test declines to judge — a mid-stream join, or a round whose reply never
// landed as an item.
let at = model.items.length;
- while (at > 0 && model.items[at - 1]!.kind === "compaction") at--;
+ while (at > 0 && ["compaction", "model_change"].includes(model.items[at - 1]!.kind)) at--;
model.items.splice(at, 0, statsItem);
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 33a35f26..2581af1c 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2318,6 +2318,20 @@ export const en: Strings = {
`Context compacted; thinking level switched to "${to}".`,
thinkingSwitchCompactFailed:
"The compaction did not finish; the thinking level was switched anyway.",
+ modelSwitchInSessionTitle: "Switch model",
+ modelSwitchInSessionConfirm: "Compact and switch",
+ /** Confirm label when the transcript is empty: nothing to compact, so it only switches. */
+ modelSwitchInSessionDirectConfirm: "Switch",
+ modelSwitchInSessionBody: (from: string, to: string): string =>
+ `The context is compacted on the current model "${from}" first, and this conversation then continues on "${to}". If the compaction fails, it stays on "${from}".`,
+ modelSwitchInSessionDirectBody: (to: string): string =>
+ `This conversation has no context yet, so it switches to "${to}" right away.`,
+ modelSwitchInSessionCompactedBody: (to: string): string =>
+ `The context was compacted or switched a moment ago and nothing has been said since, so nothing is compacted again: this conversation continues on "${to}" from there.`,
+ modelSwitchInSessionStarted: (from: string, to: string): string =>
+ `Compacting the context on "${from}" — the conversation moves to "${to}" when it finishes.`,
+ modelSwitchInSessionSwitching: (to: string): string => `Switching to "${to}".`,
+ modelSwitchInSessionApplied: (to: string): string => `Switched to "${to}".`,
workspaceHere: "here",
/** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
workspaceMachineWhy: {
@@ -2928,19 +2942,19 @@ Scenarios:
handoffFrom: (agent: string) => `Handed off from ${agent}'s conversation`,
handoffBack: (title?: string) =>
title ? `Back to the original conversation: ${title}` : "Back to the original conversation",
- switchModel: "Switch model — on send, continues this conversation in a new session",
- switchModelTitle: "Switch model",
- modelSwitchTargetTitle: (model: string) => `Sending continues this conversation on ${model}`,
- modelSwitchRemove: "Remove model switch",
+ switchModel:
+ "New conversation on another model — sending opens a new session that continues this one; this conversation stays as it is",
+ switchModelTitle: "New conversation on another model",
+ modelSwitchTargetTitle: (model: string) =>
+ `Sending opens a new conversation on ${model} that continues this one; this conversation stays as it is`,
+ modelSwitchRemove: "Remove the model for the new conversation",
modelSwitchBusyHint:
- "The model switch waits for this turn to finish: the new session continues from this session's record",
+ "The new conversation waits for this turn to finish: it continues from this session's record",
modelSwitchFrom: (prevModel?: string) =>
prevModel
- ? `Switched model (was ${prevModel}) — continued from the earlier conversation`
- : "Switched model — continued from the earlier conversation",
+ ? `New conversation on another model (was ${prevModel}) — continues the original`
+ : "New conversation on another model — continues the original",
modelSwitchAutoMessage: "Continue this conversation on the new model",
- /** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
- modelLockedHint: "Type /model to switch models",
scheduledFrom: (name: string) => `Triggered by scheduled task "${name}"`,
/** `[org_trigger]` banner: what the organization scheduler sent this desk or ticket session, folded into one line. */
orgTriggerFrom: (org: string): string => `Triggered by organization "${org}"`,
@@ -2979,6 +2993,7 @@ Scenarios:
compactionRunning: (mode: string): string => (mode === "discard" ? "Clearing" : "Compacting"),
compactionDone: (mode: string): string => (mode === "discard" ? "Cleared" : "Compacted"),
compactionResult: "Result",
+ modelChanged: (from: string, to: string): string => `Model switched · ${from} → ${to}`,
compactionFailed: (status: string, errorMessage?: string): string => {
if (status === "aborted") return "aborted, keeping current context";
const detail = errorMessage !== undefined ? ` (${errorMessage})` : "";
@@ -4856,6 +4871,10 @@ Scenarios:
// own explanation here — collapsing them into one sentence would tell a user who just
// compacted that they have never spoken.
compaction_not_configured: "This agent does not have context compaction configured.",
+ same_model: "This conversation is already on that model.",
+ model_not_configured: "That model is not in this Project's model configuration.",
+ model_unavailable:
+ "That model cannot be used yet (it may have no API key) — configure it on the Models page first.",
nothing_to_compact:
"There is nothing to compact in the current context yet (no completed conversation turn).",
already_compacted:
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 26b4b2e9..4926237a 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2353,6 +2353,26 @@ export const zh = {
thinkingSwitchApplied: (to: string): string => `上下文已压缩,思考等级已切换为「${to}」。`,
/** Compaction ended without completing — the switch still applies, so say both. */
thinkingSwitchCompactFailed: "压缩未成功完成,思考等级已照常切换。",
+ /** In-conversation model switch (the session toolbar's model picker). Title is the confirm dialog's accessible name only. Unlike the thinking level there is no "switch anyway": a switch always compacts on the current model first, and a failed compaction keeps it. */
+ modelSwitchInSessionTitle: "切换模型",
+ modelSwitchInSessionConfirm: "压缩并切换",
+ /** Confirm label when the transcript is empty: nothing to compact, so it only switches. */
+ modelSwitchInSessionDirectConfirm: "切换",
+ modelSwitchInSessionBody: (from: string, to: string): string =>
+ `将先用当前模型「${from}」压缩上下文,成功后以「${to}」继续本对话;压缩失败则保持「${from}」。`,
+ /** Body when the transcript is empty: there is no context to compact, so the switch is immediate. */
+ modelSwitchInSessionDirectBody: (to: string): string =>
+ `当前上下文没有内容,将直接切换到「${to}」。`,
+ /** Body when the transcript ends in a completed compaction or a model switch with nothing since: the switch runs no compaction and continues from what that context opened with (a summary, or nothing). */
+ modelSwitchInSessionCompactedBody: (to: string): string =>
+ `上下文刚压缩或切换过、此后没有新的对话,不会再次压缩:本对话将直接以「${to}」继续。`,
+ /** Toast once the server accepted a compacting switch: the row in the conversation carries it from here. */
+ modelSwitchInSessionStarted: (from: string, to: string): string =>
+ `正在用「${from}」压缩上下文,完成后切换到「${to}」。`,
+ /** Toast once the server accepted a switch that compacts nothing (the context was just compacted or switched): the model-change marker in the conversation carries it from here. */
+ modelSwitchInSessionSwitching: (to: string): string => `正在切换到「${to}」。`,
+ /** Toast when the switch completed inside the request (the Session had never run). */
+ modelSwitchInSessionApplied: (to: string): string => `已切换到「${to}」。`,
workspaceHere: "本机",
/** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
workspaceMachineWhy: {
@@ -2976,19 +2996,20 @@ Benchmark:
skillsAutoMessage: (names: string[]): string => `使用 ${names.join("、")} 技能`,
handoffFrom: (agent: string) => `由 ${agent} 的对话交接而来`,
handoffBack: (title?: string) => (title ? `回到原对话:${title}` : "回到原对话"),
- /** `/model` switch: command description, picker title, the staged target's description and remove button, the switch-origin banner, and the empty-body auto message. */
- switchModel: "切换模型,发送时开启新会话延续本对话",
- switchModelTitle: "切换模型",
- modelSwitchTargetTitle: (model: string) => `发送后换用 ${model} 延续本对话`,
- modelSwitchRemove: "移除切换模型",
+ /** `/model` handoff: command description, picker title, the staged target's description and remove button, the origin banner, and the empty-body auto message. Every surface says that it opens a NEW conversation and leaves this one as it is — switching inside this conversation is the toolbar's model picker (`modelSwitchInSession*`). */
+ switchModel: "换模型开新会话:发送时用所选模型新开一个会话延续本对话,本会话保持不变",
+ switchModelTitle: "换模型开新会话",
+ modelSwitchTargetTitle: (model: string) =>
+ `发送后用 ${model} 新开一个会话延续本对话,本会话保持不变`,
+ modelSwitchRemove: "移除换模型目标",
/** Why Send is disabled with a model switch staged: the fork branches off a Trace this Session is still writing. */
- modelSwitchBusyHint: "本轮结束后才能切换模型:新会话要从当前会话的记录接续",
+ modelSwitchBusyHint: "本轮结束后才能换模型开新会话:新会话要从当前会话的记录接续",
modelSwitchFrom: (prevModel?: string) =>
- prevModel ? `已切换模型(原为 ${prevModel}),延续原会话` : "已切换模型,延续原会话",
+ prevModel
+ ? `换模型新开的会话(原模型 ${prevModel}),延续原会话`
+ : "换模型新开的会话,延续原会话",
/** First message body auto-sent when `/model` is staged and the composer is empty (same convention as skillsAutoMessage). */
modelSwitchAutoMessage: "换用新模型继续这段对话",
- /** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
- modelLockedHint: "输入 /model 切换模型",
scheduledFrom: (name: string) => `由定时任务「${name}」触发`,
/** `[org_trigger]` banner: what the organization scheduler sent this desk or ticket session, folded into one line. */
orgTriggerFrom: (org: string): string => `由组织「${org}」触发`,
@@ -3031,6 +3052,8 @@ Benchmark:
compactionDone: (mode: string): string => (mode === "discard" ? "清空完毕" : "压缩完毕"),
/** The summarize row's second body section (the first reuses `thinking`): the summary the compaction request wrote. */
compactionResult: "压缩结果",
+ /** The marker between two contexts on different models (an in-session model switch), naming both by model id. */
+ modelChanged: (from: string, to: string): string => `模型已切换 · ${from} → ${to}`,
compactionFailed: (status: string, errorMessage?: string): string => {
if (status === "aborted") return "已中断,保留当前上下文";
const detail = errorMessage !== undefined ? `(${errorMessage})` : "";
@@ -4868,6 +4891,9 @@ Benchmark:
// own explanation here — collapsing them into one sentence would tell a user who just
// compacted that they have never spoken.
compaction_not_configured: "该 Agent 没有配置上下文压缩。",
+ same_model: "本会话已在使用该模型。",
+ model_not_configured: "所选模型不在本 Project 的模型配置中。",
+ model_unavailable: "所选模型暂不可用(例如还没有 API key),请先在「模型」页配置。",
nothing_to_compact: "当前上下文还没有可压缩的内容(尚未完成一轮对话)。",
already_compacted: "刚刚压缩过,之后还没有新的对话,无需重复压缩。",
version_conflict: "快照版本不高于当前版本。",
diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.ts
index c27abbbc..b38774cb 100644
--- a/packages/web/test/api-error-text.test.ts
+++ b/packages/web/test/api-error-text.test.ts
@@ -39,6 +39,23 @@ describe("apiErrorText", () => {
}
});
+ it("localizes each model-switch refusal separately in both locales", () => {
+ const codes = [
+ "same_model",
+ "model_not_configured",
+ "model_unavailable",
+ "compaction_not_configured",
+ "task_in_progress",
+ "compacting",
+ ];
+ for (const dict of [ZH, EN]) {
+ setActiveStrings(dict);
+ const texts = codes.map((c) => apiErrorText(serverError(c)));
+ for (const t of texts) expect(t).not.toBe("RAW ENGLISH SERVER MESSAGE");
+ expect(new Set(texts).size).toBe(codes.length);
+ }
+ });
+
it("gives the Chinese UI Chinese text for the errors it can surface", () => {
setActiveStrings(ZH);
// A representative slice of the codes an ordinary session can produce: compaction refusals,
diff --git a/packages/web/test/model-switch.test.ts b/packages/web/test/model-switch.test.ts
new file mode 100644
index 00000000..58cbb373
--- /dev/null
+++ b/packages/web/test/model-switch.test.ts
@@ -0,0 +1,136 @@
+/**
+ * In-conversation model switch (model-switch.ts): the picker's gate, what the switch will do to
+ * the context, the stale-row predicate that makes the Session row follow the running context's
+ * `session_meta`, and the copy of the `/model` handoff, the confirm dialog and the model-change
+ * marker in both locales. (The Web suite runs in a node environment and renders no React, so
+ * the pure helpers are what get exercised.)
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+import {
+ sessionModelPickerDisabled,
+ sessionRowStale,
+ switchContextShape,
+} from "../src/features/chat/model-switch";
+
+// S is a live binding shared across the suite: always hand it back the default.
+afterEach(() => setActiveStrings(zh));
+
+const A = { provider: "anthropic", modelId: "a-1" };
+const B = { provider: "openai", modelId: "b-2" };
+
+describe("sessionModelPickerDisabled", () => {
+ it("disables the picker exactly while a compaction could not start", () => {
+ expect(sessionModelPickerDisabled("running")).toBe(true);
+ expect(sessionModelPickerDisabled("compacting")).toBe(true);
+ expect(sessionModelPickerDisabled("idle")).toBe(false);
+ });
+});
+
+describe("switchContextShape", () => {
+ const user = { kind: "user" };
+ const done = { kind: "compaction", running: false, status: "completed" };
+ const failed = { kind: "compaction", running: false, status: "fatal" };
+ const running = { kind: "compaction", running: true };
+ const marker = { kind: "model_change" };
+ /** The connect row of a context whose opener had a server to connect again; its own `status` is not a compaction's. */
+ const connect = { kind: "mcp_connect", running: false, status: "completed" };
+
+ it("is empty for no items, and compacts when there is conversation since the last compaction", () => {
+ expect(switchContextShape([])).toBe("empty");
+ expect(switchContextShape([user])).toBe("compact");
+ expect(switchContextShape([done, user])).toBe("compact");
+ });
+
+ it("continues from what the context opened with when the transcript ends in a completed compaction or a model switch — a failed retry after it changes nothing", () => {
+ expect(switchContextShape([user, done])).toBe("compacted");
+ expect(switchContextShape([user, done, failed])).toBe("compacted");
+ expect(switchContextShape([user, done, marker])).toBe("compacted");
+ expect(switchContextShape([done, marker])).toBe("compacted");
+ // A switch away from a context that had not answered ran no compaction: the marker alone.
+ expect(switchContextShape([user, marker])).toBe("compacted");
+ expect(switchContextShape([user, marker, connect])).toBe("compacted");
+ // Conversation since the switch is there to compact again.
+ expect(switchContextShape([user, marker, user])).toBe("compact");
+ // Neither does what the opened context connected behind the compaction…
+ expect(switchContextShape([user, done, connect])).toBe("compacted");
+ expect(switchContextShape([user, done, connect, marker])).toBe("compacted");
+ // …which is no compaction of its own.
+ expect(switchContextShape([user, connect])).toBe("compact");
+ });
+
+ it("still compacts when the trailing compaction did not complete: the old context is in effect", () => {
+ expect(switchContextShape([user, failed])).toBe("compact");
+ expect(switchContextShape([user, running])).toBe("compact");
+ });
+});
+
+describe("sessionRowStale", () => {
+ /** A Session row, or a running context's model as its session_meta names it: both are a model under a Session id. */
+ const on = (model: { provider: string; modelId: string }, sessionId = "session-1") => ({
+ sessionId,
+ ...model,
+ });
+
+ it("is never stale before a session_meta was seen, or without a row", () => {
+ expect(sessionRowStale(null, on(A))).toBe(false);
+ expect(sessionRowStale(null, null)).toBe(false);
+ expect(sessionRowStale(on(B), null)).toBe(false);
+ });
+
+ it("is not stale while the row names the running context's model", () => {
+ expect(sessionRowStale(on(A), on(A))).toBe(false);
+ });
+
+ it("is stale when the running context's model differs from the row's, by either half", () => {
+ expect(sessionRowStale(on(B), on(A))).toBe(true);
+ expect(sessionRowStale(on({ provider: A.provider, modelId: "a-2" }), on(A))).toBe(true);
+ expect(sessionRowStale(on({ provider: "other", modelId: A.modelId }), on(A))).toBe(true);
+ });
+
+ it("says nothing about another Session's row: the stream of the conversation the page just left", () => {
+ expect(sessionRowStale(on(B, "session-1"), on(A, "session-2"))).toBe(false);
+ });
+});
+
+describe("/model copy", () => {
+ it("says in both locales that /model opens a new conversation", () => {
+ expect(zh.chat.switchModel).toContain("新会话");
+ expect(zh.chat.switchModel).toContain("本会话保持不变");
+ expect(zh.chat.switchModelTitle).toContain("新会话");
+ expect(zh.chat.modelSwitchTargetTitle("b-2")).toContain("新开");
+ expect(en.chat.switchModel).toMatch(/new session/);
+ expect(en.chat.switchModelTitle).toMatch(/New conversation/);
+ expect(en.chat.modelSwitchTargetTitle("b-2")).toMatch(/new conversation on b-2/);
+ });
+
+ it("the confirm dialog uses the design's zh body and a two-choice label", () => {
+ expect(zh.chat.modelSwitchInSessionBody("A", "B")).toBe(
+ "将先用当前模型「A」压缩上下文,成功后以「B」继续本对话;压缩失败则保持「A」。",
+ );
+ expect(zh.chat.modelSwitchInSessionConfirm).toBe("压缩并切换");
+ expect(zh.chat.modelSwitchInSessionDirectBody("B")).toContain("直接切换到「B」");
+ expect(en.chat.modelSwitchInSessionBody("A", "B")).toContain('"B"');
+ });
+
+ it("right after a compaction, neither the dialog nor the toast promises a compaction", () => {
+ // The server runs no compaction for a just-compacted Session (design: no second pair), so
+ // the copy for that shape must not say "compact".
+ expect(zh.chat.modelSwitchInSessionCompactedBody("B")).toContain("不会再次压缩");
+ expect(zh.chat.modelSwitchInSessionCompactedBody("B")).toContain("「B」");
+ expect(en.chat.modelSwitchInSessionCompactedBody("B")).toMatch(/nothing is compacted again/);
+ expect(en.chat.modelSwitchInSessionCompactedBody("B")).toContain('"B"');
+ expect(zh.chat.modelSwitchInSessionSwitching("B")).toBe("正在切换到「B」。");
+ expect(en.chat.modelSwitchInSessionSwitching("B")).not.toMatch(/compact/i);
+ expect(zh.chat.modelSwitchInSessionDirectConfirm).toBe("切换");
+ expect(en.chat.modelSwitchInSessionDirectConfirm).toBe("Switch");
+ // The compacting toast is the one that may say so.
+ expect(en.chat.modelSwitchInSessionStarted("A", "B")).toMatch(/Compacting/);
+ });
+
+ it("the model-change marker names both model ids in both locales", () => {
+ expect(zh.chat.modelChanged("a-1", "b-2")).toBe("模型已切换 · a-1 → b-2");
+ expect(en.chat.modelChanged("a-1", "b-2")).toBe("Model switched · a-1 → b-2");
+ });
+});
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index 661dc2fe..361fb361 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -476,6 +476,104 @@ describe("approvals and events", () => {
expect(banner.errorMessage).toBe("the response contained no usable summary");
});
+ it("a main-session session_meta on another model pushes a model_change item after the compaction row; the window's first meta, a same-pair rewrite and a nested child's meta push none", () => {
+ const onModel = (provider: string, modelId: string, sessionId = "s1") =>
+ sessionMeta({ ...meta(sessionId).payload, provider, model_id: modelId });
+ const markers = (model: StreamModel) => model.items.filter((i) => i.kind === "model_change");
+ const m = createStreamModel();
+ // The window's first meta only sets the context model.
+ pushMessage(m, onModel("anthropic", "a-1"));
+ expect(items(m)).toEqual([]);
+ expect(m.contextModel).toEqual({ sessionId: "s1", provider: "anthropic", modelId: "a-1" });
+
+ // A switch streams an ordinary manual pair, then the new context's meta on another model.
+ pushMessage(
+ m,
+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 }),
+ );
+ pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }));
+ pushMessage(m, at(onModel("openai", "b-2"), "2026-09-17T08:00:00.000Z"));
+ expect(items(m).map((i) => i.kind)).toEqual(["compaction", "model_change"]);
+ expect(items(m)[1]).toEqual({
+ kind: "model_change",
+ id: expect.any(Number),
+ from: { provider: "anthropic", modelId: "a-1" },
+ to: { provider: "openai", modelId: "b-2" },
+ tsMs: Date.parse("2026-09-17T08:00:00.000Z"),
+ });
+ expect(m.contextModel).toEqual({ sessionId: "s1", provider: "openai", modelId: "b-2" });
+
+ // A same-pair rewrite — an ordinary rotation's meta, or the same record served twice by
+ // history and the live tail — pushes nothing.
+ pushMessage(m, onModel("openai", "b-2"));
+ expect(markers(m)).toHaveLength(1);
+
+ // A nested child's metas are that child's identity, never a switch of this Session, even
+ // when two of them name different models.
+ pushMessage(m, withOrigin(onModel("zhipu", "glm-5", "child1"), "child1"));
+ pushMessage(m, withOrigin(onModel("deepseek", "ds-1", "child1"), "child1"));
+ const child = items(m).find((i) => i.kind === "subagent") as SubagentItem;
+ expect(child.model.meta).toMatchObject({ provider: "deepseek", modelId: "ds-1" });
+ expect(markers(child.model)).toEqual([]);
+ expect(markers(m)).toHaveLength(1);
+ expect(m.contextModel).toEqual({ sessionId: "s1", provider: "openai", modelId: "b-2" });
+ });
+
+ it("a round settled behind a switch's compaction row and marker places its stats row above both", () => {
+ const m = createStreamModel();
+ pushMessage(
+ m,
+ at(sessionMeta({ ...meta("s1").payload, model_id: "a-1" }), "2026-09-17T08:00:00.000Z"),
+ );
+ pushMessage(m, at(userText("task"), "2026-09-17T08:00:01.000Z"));
+ pushMessage(m, at(requestBegin(), "2026-09-17T08:00:02.000Z"));
+ pushMessage(m, at(assistantText("half a reply"), "2026-09-17T08:00:03.000Z"));
+ pushMessage(m, at(tokenUsage(counts(100), counts(100)), "2026-09-17T08:00:04.000Z"));
+ // Interrupted: the round's last item is the abort, so the compaction below does not settle
+ // it on arrival — the history rebuild settles it at its end.
+ pushMessage(m, at(abortEvent(), "2026-09-17T08:00:05.000Z"));
+ pushMessage(
+ m,
+ compactionBegin({ reason: "manual", mode: "summarize", context: 100, turns: 1 }),
+ );
+ pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }));
+ pushMessage(m, sessionMeta({ ...meta("s1").payload, model_id: "b-2" }));
+ finalizeHistory(m);
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "assistant_text",
+ "abort",
+ "task_stats",
+ "compaction",
+ "model_change",
+ ]);
+ // The round is priced on the model it ran on, though it was settled after the new context's
+ // meta had arrived.
+ const stats = items(m).find((i) => i.kind === "task_stats") as TaskStatsItem;
+ expect(stats.model).toEqual({ provider: meta("s1").payload.provider, modelId: "a-1" });
+ });
+
+ it("a Task's stats row names the model its context ran on; one that began before any meta names none", () => {
+ const round = (m: StreamModel, n: number): void => {
+ const t = (s: number) => `2026-09-17T08:0${n}:0${s}.000Z`;
+ pushMessage(m, at(userText(`task ${n}`), t(1)));
+ pushMessage(m, at(requestBegin(), t(2)));
+ pushMessage(m, at(assistantText(`reply ${n}`), t(3)));
+ pushMessage(m, at(tokenUsage(counts(100 * n), counts(100)), t(4)));
+ };
+ const models = (m: StreamModel) =>
+ items(m).flatMap((i) => (i.kind === "task_stats" ? [i.model?.modelId] : []));
+ const m = createStreamModel();
+ // A window that starts partway into a context: no meta ahead of its first Task.
+ round(m, 1);
+ pushMessage(m, sessionMeta({ ...meta("s1").payload, model_id: "a-1" }));
+ round(m, 2);
+ pushMessage(m, sessionMeta({ ...meta("s1").payload, model_id: "b-2" }));
+ round(m, 3);
+ finalizeHistory(m);
+ expect(models(m)).toEqual([undefined, "a-1", "b-2"]);
+ });
+
it("compaction wall time is derived from the begin/end message timestamps", () => {
const m = createStreamModel();
pushMessage(
diff --git a/packages/web/test/thinking-level.test.ts b/packages/web/test/thinking-level.test.ts
index d2ee2b75..ac5873a9 100644
--- a/packages/web/test/thinking-level.test.ts
+++ b/packages/web/test/thinking-level.test.ts
@@ -189,6 +189,26 @@ describe("prefixCacheAtRisk (issue #310 — provider prefix cache over the exist
it("new turns after a compaction re-arm the guard (only a TRAILING compaction is safe)", () => {
expect(prefixCacheAtRisk([user, reply, compactionDone, user, reply])).toBe(true);
});
+
+ it("a transcript that ends in a model switch is safe: the context it opened has not been sent yet", () => {
+ const modelChange: ThinkingSwitchItem = { kind: "model_change" };
+ expect(prefixCacheAtRisk([user, reply, stats, compactionDone, modelChange])).toBe(false);
+ // A switch away from a context that had not answered runs no compaction: the marker
+ // stands alone, and the context behind it is just as new.
+ expect(prefixCacheAtRisk([user, modelChange])).toBe(false);
+ // Conversation since re-arms the guard.
+ expect(prefixCacheAtRisk([user, modelChange, user, reply])).toBe(true);
+ });
+
+ it("the connect row a compacted context opened with changes nothing either", () => {
+ const connect: ThinkingSwitchItem = {
+ kind: "mcp_connect",
+ running: false,
+ status: "completed",
+ };
+ expect(prefixCacheAtRisk([user, reply, stats, compactionDone, connect])).toBe(false);
+ expect(prefixCacheAtRisk([user, reply, connect])).toBe(true);
+ });
});
describe("needsThinkingSwitchConfirm (mid-chat switch guard for the session picker)", () => {