A local-first multi-agent app development platform, built on PenguinHarness
feat(core): per-rotation context assembly under a three-tier rule — strict request prefix, soft thinking level, live permissions and policy (#539)
Yaowei Zheng9d219c7d49d9
diff --git a/changelog/unreleased/2026-08-28-context-assembled-per-rotation.md b/changelog/unreleased/2026-08-28-context-assembled-per-rotation.mdnew file mode 100644index 00000000..dcf590f1--- /dev/null+++ b/changelog/unreleased/2026-08-28-context-assembled-per-rotation.md@@ -0,0 +1,115 @@+# Every model context is assembled whole from the Agent State as it is when it opens++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `cli`, `docs`+- **PR:** [#539](https://github.com/Prism-Shadow/penguin-harness/pull/539)+- **Breaking:** yes — SDK: `SessionConfig.createLLM` / `ContextEngineDeps.createLLM` became `openNextContext`, `RunOptions.thinkingLevel` and the per-round thinking level of the subagent seams are gone, `SessionConfig.commandPolicy` is a per-context source; HTTP API: `POST /tasks` and the subagent message no longer take `thinkingLevel`, and a follow-up recall no longer returns one++[中文版](2026-08-28-context-assembled-per-rotation.zh.md)++A compaction now opens its new model context exactly as a new Session opens its first: everything+under the Agent State is read from disk at that moment — `system_config.yaml` in full (the prompt+template with its section prompts and toggles, the builtin tool entries and MCP Servers, the+compaction settings, `max_turns`, the model defaults), `AGENTS.md`, the vault, the installed+Skills' metadata, the Memory indexes and the schedule roster. An edit made during the old+context — by the model working on its own configuration, or by hand in the Agent settings —+takes effect at the next compaction rather than the next Session. Runtime parameters now fall+into three explicit tiers: **strict** (system prompt, toolset incl. MCP, compaction settings,+model reference — the request prefix, byte-fixed across a whole Trace file so the provider's+prompt cache holds; the vault, per-tool `r`/`rw` permissions and the command policy never+reach the model but are read once per context, on the same rotation schedule), **soft** (the+thinking level: changeable mid-context, effective from the next request, at the cost of the+provider's cached context — the pickers advise compacting first), and **unrestricted** (the+approval mode: re-read from the DB per decision, effective immediately).++## Details++- Three openers assemble a context the same way: Session creation, a completed compaction+ (summarize and discard alike), and a resume that finds its latest Trace file closed by a+ completed compaction. A resume of an open context keeps the prompt its file recorded — the+ replayed history was produced under that prefix — and takes tools,+ Environment, vault and run settings from the current Agent State, as before (the Trace records+ no executable configuration).+- The thinking level is the soft-limited tier — a purely per-request parameter: every LLM+ request takes the Session's pinned level — the Web App's in-chat picker, the CLI's+ `--thinking` / `/thinking`, the SDK's `Session.thinkingLevel` state — or, unset, the+ Agent config's `model.thinking_level` as read when the context opened. A re-pin applies+ from the very next LLM request, mid-context included, and nothing is recorded in the Trace;+ because a change invalidates the provider's cached context, the change points remind the+ user first (the web picker's menu note, the CLI `/thinking` reply) that compacting is+ recommended. Compaction requests keep the context's opening base — their prefix must stay+ byte-identical. Nothing rides a run or a task.+- Per-tool `r`/`rw` permissions and the command policy are strict-tier as well:+ `Session.toolPermission` answers from the running context's toolset (rebuilt at every+ rotation, MCP `permission` overrides included), and the command policy is read from+ `.project_config.toml` once per context open — no approval decision reads a file. The+ unrestricted tier is the approval mode alone, re-read from the DB on every decision.+- Fixed for the Session's lifetime: its id, Workspace, model entry (credentials, window and+ per-model annotations included), origin, and the Environment's process host — background+ commands, subagent child sessions and their listeners survive the rotation.+- The Environment is re-equipped for the new context (`Environment.reconfigure`): the vault's+ values go straight into the command environment of every command spawned from then on+ (processes already running keep the environment they started with). MCP connections are cached+ by config: a server whose entry is unchanged keeps its live connection and discovered tools —+ a Session that compacts every turn does not respawn its servers — a removed or changed one is+ closed, and only new, changed or previously failed servers connect, bracketed by the same+ `mcp_connect_begin` / `mcp_connect_end` pair the first run streams (naming just those servers),+ followed by the new `tool_list_ready`; the engine yields them live.+- Each Trace file a compaction's rotation opens starts with the `session_meta` recording the+ prompt its context runs with, then the connect pair (if any) and the toolset record;+ `Session.metaMessage` follows the running context.+- An Agent State that cannot be assembled when a context opens (a `system_config.yaml` that no+ longer parses) fails the run with that error and the engine stays on the old context — the same+ error a new Session would hit; there is no silent fallback.+- Agent State loading is one function: `loadAgentState` — with `init` it is the+ create-or-load entry (`createAgent`, provisioning; `loadOrInitAgentState` is gone), without+ it a missing Agent throws, which is what a model context opening mid-session must see. So+ `createSession` and `resumeSession` read the disk too, and an Agent object held across+ edits — a self-spawned subagent's, for instance — no longer starts Sessions on its+ load-time snapshot.+- Opening a context is one procedure as well: the first run's bootstrap and the+ post-compaction `openNextContext` share the same implementation (connect what is pending,+ publish the connect pair and the toolset record through `emit`, build the LLM), delivered+ live by the same merge-queue pump on both paths.+- The server no longer rebuilds an Agent's cached Session runtimes when its vault is updated: the+ new values reach a running Session at its next compaction, the same timing the CLI's+ in-process Session has. The Agent settings pages (prompt, runtime, tools and MCP, memory,+ schedules, vault, skills), the CLI's `config vault set/remove` and the in-chat thinking picker+ say so where the change is made: new conversations pick a change up right away, running ones+ after their next compaction.++## Compatibility++- SDK: `SessionConfig.createLLM` and `ContextEngineDeps.createLLM` are replaced by+ `openNextContext({ emit }) => OpenedContext | Promise<OpenedContext>`, with+ `OpenedContext` being `{ llm, sessionMeta?, maxTurns?, compaction? }`; records passed to+ `emit` are yielded on the run stream and written at the head of the rotated Trace file, and+ the engine is the sole author of `token_usage.session` — the LLM reports per-request usage+ only, and `GenerativeModel` no longer carries a `sessionTokens` field. Code+ that constructs `Session` or `ContextEngine` directly returns `{ llm }` where it returned the+ LLM before; the `Agent.createSession` / `resumeSession` path needs no change. `Environment`+ gains `reconfigure({ toolConfig, vault })` and `pendingMcpServerNames()`.+- SDK: `loadOrInitAgentState` is folded into `loadAgentState` — pass `init: {}` (or+ `init: { preset }`) for the create-or-load behavior; without `init` a missing Agent throws.+ `SessionConfig.bootstrap` now takes `{ emit }` and returns `{ llm }` (no `tools` or `mcp`+ field), publishing its connect pair and toolset record through `emit`; the+ `SessionConfig.mcpServers` field is gone — the bootstrap knows what it is connecting.+- SDK: `RunOptions.thinkingLevel`, `SubagentHandle.run`'s `thinkingLevel` and+ `SubagentMessageOptions.thinkingLevel` are removed; a host that changed the level per run+ assigns `Session.thinkingLevel = level` instead — plain state, forwarded into the engine+ (`ContextEngine.setThinkingLevel`) and applied from the next LLM request.+- SDK: `SessionConfig.commandPolicy` takes a source function instead of a static config — the+ composition layer's source answers with the running context's policy, read from+ `.project_config.toml` once per context open. `Session.toolPermission` keeps its synchronous+ signature and answers from the running context's toolset.+- HTTP API: `TaskCreateRequest.thinkingLevel` and the subagent message's `thinkingLevel` are+ no longer read (a client still sending them is ignored), and `RecalledMessageResponse` no+ longer carries one. `PATCH /sessions/:id { thinkingLevel }` is the way to set a level; it+ applies from the Session's very next LLM request.+- Traces: no format change and nothing to migrate. A Trace file's+ `session_meta.system_prompt` has always been the prompt that file's context ran with; it now+ differs between the files of one Session when the Agent State changed in between, and a+ rotated file's head carries the context's connect pair before its `tool_list_ready`. A reader+ that took the first file's prompt or toolset as the Session's only one should read the file+ it is rendering.diff --git a/changelog/unreleased/2026-08-28-context-assembled-per-rotation.zh.md b/changelog/unreleased/2026-08-28-context-assembled-per-rotation.zh.mdnew file mode 100644index 00000000..d3a9c4a9--- /dev/null+++ b/changelog/unreleased/2026-08-28-context-assembled-per-rotation.zh.md@@ -0,0 +1,80 @@+# 每个模型上下文都按开启时的 Agent State 整体装配++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `cli`, `docs`+- **PR:** [#539](https://github.com/Prism-Shadow/penguin-harness/pull/539)+- **Breaking:** yes — SDK:`SessionConfig.createLLM` / `ContextEngineDeps.createLLM` 改为 `openNextContext`,移除 `RunOptions.thinkingLevel` 与子会话接缝上的逐轮思考等级,`SessionConfig.commandPolicy` 改为按上下文取值的来源函数;HTTP API:`POST /tasks` 与子会话消息不再接受 `thinkingLevel`,撤回跟进消息不再返回它++[English](2026-08-28-context-assembled-per-rotation.md)++压缩开启的新模型上下文,改为与新建 Session 的首个上下文完全相同地装配:Agent State 下的一切在此刻从磁盘+读取——整份 `system_config.yaml`(提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、+`max_turns`、模型默认参数)、`AGENTS.md`、vault、已装 Skill 的元数据、Memory 索引与定时任务名单。旧上下文+期间的修改——模型改自己的配置,或用户在 Agent 设置里手改——在下一次压缩即生效,不必等下一个 Session。运行参数+明确分为三层:**严格层**(系统提示词、工具集含 MCP、压缩配置、模型引用——请求前缀,一个 Trace 文件内逐字节+固定,提供商提示词缓存始终有效;vault、工具 `r`/`rw` 权限与命令策略不进模型请求,但同样每上下文读取一次、+随同一轮换节奏更换)、**软限制层**(思考等级:允许中途更换、自下一次请求生效,代价是提供商缓存失效——调节+入口提醒建议先压缩)与**不限制层**(审批模式:逐次决策从 DB 重读、即刻生效)。++## 细节++- 三处开启以同一流程装配上下文:Session 创建、完成的压缩(summarize 与 discard 皆然)、以及恢复时发现最新+ Trace 文件已被完成的压缩收尾。恢复未关闭的上下文时沿用该文件记录的提示词——注入的历史正是在该前缀下产生+ 的——工具、Environment、vault 与运行参数一如既往取自当前 Agent State(Trace 不记录可执行配置)。+- 思考等级属软限制层——纯粹的每请求参数:每次 LLM 请求取 Session 钉住的等级——Web 对话内选择器、CLI 的+ `--thinking` / `/thinking`、SDK 的 `Session.thinkingLevel` 状态——未设置则取上下文开启时读到的 Agent 配置+ `model.thinking_level`。重新钉住自下一次 LLM 请求即生效、允许中途更换,且不在 Trace 中留任何记录;因为更换+ 会使提供商的缓存失效,调节入口在调节之前提醒建议先压缩(Web 选择器菜单脚注、CLI `/thinking` 回执)。压缩+ 请求保持上下文开启时的基准等级——其前缀必须逐字节不变。运行与 Task 请求都不携带等级。+- 工具的 `r`/`rw` 权限与命令策略同属严格层:`Session.toolPermission` 取运行中上下文的工具集(随轮换重建,+ MCP 条目的 `permission` 覆盖一并烤入),命令策略在每个上下文开启时从 `.project_config.toml` 读取一次——+ 审批决策不再读任何文件。不限制层只余审批模式,逐次决策从 DB 重读、修改即刻生效。+- 随 Session 固定的只有:Session id、Workspace、模型条目(含凭据、窗口与逐模型标注)、来源,以及 Environment+ 的进程宿主——后台命令、子会话及其监听器跨轮换存续。+- Environment 为新上下文重新装备(`Environment.reconfigure`):vault 的值直接进入此后每条命令的子进程环境+ (已在运行的进程保留启动时的环境)。MCP 连接按配置缓存:条目未变的 Server 保持连接与已发现的工具——每轮压缩+ 的 Session 不会每轮重启 Server——被删除或改动的关闭,只有新增、改动或上次失败的 Server 才连接,等待期间流式+ 发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对(只列这些 Server),随后是新的+ `tool_list_ready`,由引擎实时推出。+- 压缩轮转出的每个 Trace 文件都以记录该上下文实际所用提示词的 `session_meta` 开头,随后是连接事件对(如有)+ 与工具集记录;`Session.metaMessage` 随运行中的上下文更新。+- 上下文开启时 Agent State 装配失败(例如 `system_config.yaml` 已无法解析)则本次运行以该错误结束、引擎保持+ 旧上下文——与新建 Session 遇到的是同一个错误;不做静默回退。+- Agent State 装载收敛为一个函数:`loadAgentState`——带 `init` 即创建或装载入口(`createAgent` 与内置 Agent+ 预置;`loadOrInitAgentState` 移除),不带 `init` 时 Agent 缺失即报错——上下文在会话中途开启时必须看到这个+ 错误,而不是把已删除的 Agent 悄悄重建出来。`createSession` 与 `resumeSession` 因此同样从磁盘装载,跨修改被+ 长期持有的 Agent 对象(例如自派生的子 Agent)不再用装载时的快照开启 Session。+- 上下文开启同样收敛为一个流程:首次运行的 bootstrap 与压缩后的 `openNextContext` 共用同一段实现(连接待连的+ Server、经 `emit` 发布连接事件对与工具集记录、构建 LLM),两条路径由同一个合并队列泵实时送出。+- 服务端不再因 vault 更新而重建该 Agent 已缓存的 Session 运行时:新值在运行中 Session 的下一次压缩后生效,与+ CLI 进程内 Session 的时机一致。智能体设置各页(提示词、运行参数、工具与 MCP、记忆、定时任务、vault、技能)、+ CLI 的 `config vault set/remove` 与对话内思考等级选择器都在修改处说明:新对话立即生效,进行中的对话在下一次+ 压缩后生效。++## 兼容性++- SDK:`SessionConfig.createLLM` 与 `ContextEngineDeps.createLLM` 被+ `openNextContext({ emit }) => OpenedContext | Promise<OpenedContext>` 取代,`OpenedContext` 即+ `{ llm, sessionMeta?, maxTurns?, compaction? }`;传给 `emit` 的记录在运行流上推出并写入轮转出的 Trace+ 文件头部;`token_usage.session` 由引擎统一累计并盖章——LLM 只报逐请求用量,`GenerativeModel` 不再持有+ `sessionTokens` 字段。直接构造 `Session` 或 `ContextEngine` 的代码,原先返回 LLM 的地方改为返回 `{ llm }`;走+ `Agent.createSession` / `resumeSession` 的代码无需改动。`Environment` 新增 `reconfigure({ toolConfig, vault })`+ 与 `pendingMcpServerNames()`。+- SDK:`loadOrInitAgentState` 并入 `loadAgentState`——创建或装载行为改传 `init: {}`(或 `init: { preset }`);+ 不带 `init` 时 Agent 缺失即抛错。`SessionConfig.bootstrap` 改为接受 `{ emit }`、返回 `{ llm }`(不再有+ `tools` 与 `mcp` 字段),连接事件对与工具集记录经 `emit` 发布;`SessionConfig.mcpServers` 字段随之删除——要连什么由+ bootstrap 自己知道。+- SDK:移除 `RunOptions.thinkingLevel`、`SubagentHandle.run` 的 `thinkingLevel` 与+ `SubagentMessageOptions.thinkingLevel`;原先逐次运行改等级的宿主改为给 `Session.thinkingLevel` 赋值——纯状态,+ 转发为引擎自有状态(`ContextEngine.setThinkingLevel`),自下一次 LLM 请求起生效。+- SDK:`SessionConfig.commandPolicy` 改为来源函数、不再是静态配置——组合层的来源返回运行中上下文的策略,+ 每个上下文开启时从 `.project_config.toml` 读取一次。`Session.toolPermission` 签名不变(同步),取值为运行中+ 上下文的工具集。+- HTTP API:`TaskCreateRequest.thinkingLevel` 与子会话消息的 `thinkingLevel` 不再读取(仍发送的客户端被忽略),+ `RecalledMessageResponse` 不再携带它。设置等级的方式是 `PATCH /sessions/:id { thinkingLevel }`,自该 Session+ 的下一次 LLM 请求生效。+- Trace:格式不变,无需迁移。Trace 文件的 `session_meta.system_prompt` 一直是该文件所属上下文实际所用的提示词;现在当 Agent State 在两次+ 上下文之间发生变化时,同一 Session 的各文件会记录不同的值,且轮转出的文件头部在 `tool_list_ready` 之前多出+ 该上下文的连接事件对。把首个文件的提示词或工具集当作整个 Session 唯一一份的读取方,应改为读取正在渲染的那个+ 文件。diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.tsindex e9eac0ab..1fe30f3a 100644--- a/packages/cli/src/commands/chat.ts+++ b/packages/cli/src/commands/chat.ts@@ -10,7 +10,7 @@* 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 overrides the per-turn thinking level; `/verbose` toggles tool-output+ * shows or re-pins the Session's thinking level; `/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.*@@ -44,6 +44,7 @@ import {getSessionInfo,getSessionMessages,listAgentSessions,+ pinThinkingLevel,resolveWorkspace,} from "../server-session.js";import { SessionStream, watchTask } from "../server-task.js";@@ -155,25 +156,27 @@ export function registerChatCommand(program: Command, t: Messages): void {? { approvalMode: caller.approvalMode }: {}),});- // `--thinking` on a new chat pins the Session default (sticky server-side, so- // spawned subagent sessions follow it — the same effect creation-time pinning- // had); with no flag, the caller's level pins the same way.+ // `--thinking` on a new chat pins the Session (sticky server-side: it rides every+ // later request of this Session; a subagent it spawns inherits the level its+ // parent's context opened with, not the pin — run_subagent's own argument sets a+ // child's level); with no flag, the caller's level pins the same way.const pin = flagThinking ?? caller?.thinkingLevel;if (pin) {- await client.request("PATCH", `/api/sessions/${session.sessionId}`, {- thinkingLevel: pin,- });+ await pinThinkingLevel(client, session.sessionId, pin);session = { ...session, thinkingLevel: pin };}}- // Thinking level shown/changed by `/thinking` (a per-turn run parameter):- // - a new chat's `--thinking` pinned the Session default above; under `--resume`- // the Session already exists and the flag becomes the initial per-turn override.- // - `/thinking <level>` sets the override; unset turns omit the parameter so the- // Session's pinned level (else the Agent config) applies.- let thinkingOverride = opts.resume !== undefined ? flagThinking : undefined;- const sessionThinkingDefault = (): string =>+ // The thinking level is pinned on the Session (PATCH) and core applies it from the+ // next LLM request — the soft-limited parameter: a mid-context change is allowed,+ // and the /thinking reply advises compacting first since it costs the provider's+ // cached context. `--thinking` under `--resume` pins the existing Session the same+ // way; `/thinking <level>` re-pins.+ if (opts.resume !== undefined && flagThinking) {+ await pinThinkingLevel(client, session.sessionId, flagThinking);+ session = { ...session, thinkingLevel: flagThinking };+ }+ const sessionThinkingLevel = (): string =>session.thinkingLevel ?? t.chatThinkingConfigured();let renderer = new StreamRenderer(out, t, { collapseToolOutput: !verbose });@@ -465,17 +468,15 @@ export function registerChatCommand(program: Command, t: Messages): void {if (!parsed.ok) {out.write(`${t.error(t.thinkingInvalid(parsed.value))}\n`);} else if (parsed.level === null) {- const sessionDefault = sessionThinkingDefault();- out.write(- `${- thinkingOverride- ? t.thinkingCurrentOverride(thinkingOverride, sessionDefault)- : t.thinkingCurrentDefault(sessionDefault)- }\n`,- );+ out.write(`${t.thinkingCurrent(sessionThinkingLevel())}\n`);} else {- thinkingOverride = parsed.level;- out.write(`${t.thinkingSet(parsed.level)}\n`);+ try {+ await pinThinkingLevel(client, session.sessionId, parsed.level);+ session = { ...session, thinkingLevel: parsed.level };+ out.write(`${t.thinkingSet(parsed.level)}\n`);+ } catch (err) {+ out.write(`${t.error(err instanceof Error ? err.message : String(err))}\n`);+ }}continue;}@@ -523,11 +524,7 @@ export function registerChatCommand(program: Command, t: Messages): void {// Carry the current session's pinned thinking level over (whether it came// from --thinking or from the calling session's context).const pin = session.thinkingLevel;- if (pin) {- await client.request("PATCH", `/api/sessions/${next.sessionId}`, {- thinkingLevel: pin,- });- }+ if (pin) await pinThinkingLevel(client, next.sessionId, pin);if (resumable) out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);session = pin ? { ...next, thinkingLevel: pin } : next;renderer = new StreamRenderer(out, t, { collapseToolOutput: !verbose });@@ -547,7 +544,6 @@ export function registerChatCommand(program: Command, t: Messages): void {() =>client.request("POST", `/api/sessions/${session.sessionId}/tasks`, {input: [{ type: "text", text: parsed.objective }],- ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),goal: { budget: parsed.budget },}),{ goal: true },@@ -558,7 +554,6 @@ export function registerChatCommand(program: Command, t: Messages): void {await runTurn(() =>client.request("POST", `/api/sessions/${session.sessionId}/tasks`, {input: [{ type: "text", text }],- ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),}),);}diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.tsindex 283e84f3..520ce5f4 100644--- a/packages/cli/src/commands/run.ts+++ b/packages/cli/src/commands/run.ts@@ -44,6 +44,7 @@ import {callerSessionContext,createServerSession,getSessionInfo,+ pinThinkingLevel,resolveWorkspace,} from "../server-session.js";import { SessionStream, watchTask } from "../server-task.js";@@ -161,10 +162,12 @@ export function registerRunCommand(program: Command, t: Messages): void {}}+ // The level is pinned on the Session, never sent with the task: core applies it from+ // the Session's next LLM request (and every context opened from then on).const effectiveThinking = thinking ?? callerThinking;+ if (effectiveThinking) await pinThinkingLevel(client, session.sessionId, effectiveThinking);const taskBody = {input: [{ type: "text", text: String(opts.message) }],- ...(effectiveThinking ? { thinkingLevel: effectiveThinking } : {}),...(goalBudget !== null ? { goal: { budget: goalBudget } } : {}),};diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex 442f36fa..fcfde838 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -447,7 +447,7 @@ export interface Messages {tokens?: { total: string; delta: string },errorMessage?: string,): string;- /** mcp_connect_begin event: the first run is connecting the configured MCP servers. */+ /** mcp_connect_begin event: the configured MCP servers are being connected (the first run, or a new context after compaction). */mcpConnectStart(servers: string[]): string;/** mcp_connect_end event, one line: total wall time; `failures` carries "server (reason)" per failed connect (empty = all ok); `aborted` = the user interrupted mid-connect. */mcpConnectStop(@@ -473,18 +473,9 @@ export interface Messages {goalBudgetInvalid(value: string): string;/** run's --goal given an empty/whitespace -m (the objective must be non-empty text). */goalObjectiveEmpty(): string;- /**- * `/thinking` with no argument and no override in effect: the level the next turn will run- * at is the Session's own default (pinned by `--thinking` at creation, else the config chain).- */- thinkingCurrentDefault(level: string): string;- /**- * `/thinking` with no argument while a per-turn override is in effect: the level the next- * turn will run at, plus the Session default it overrides — the two are a real distinction- * (only the Session default reaches spawned subagent sessions).- */- thinkingCurrentOverride(level: string, sessionDefault: string): string;- /** `/thinking <level>` accepted: subsequent turns carry the override (never written to the config). */+ /** `/thinking` with no argument: the level this Session is pinned to (by `--thinking` or `/thinking`), else the Agent's configured level. */+ thinkingCurrent(level: string): string;+ /** `/thinking <level>` accepted: the Session is pinned to it, effective from the next request; the reply advises compacting first — a mid-context change invalidates the provider's cached context (never written to the Agent config). */thinkingSet(level: string): string;/** Invalid `--thinking` / `/thinking` value (lists the selectable levels). */thinkingInvalid(value: string): string;@@ -1018,12 +1009,10 @@ const en: Messages = {goalBudgetInvalid: (value) =>`Invalid token budget "${value}". Use a positive number with an optional k/m suffix (500k, 2m).`,goalObjectiveEmpty: () => "Goal mode requires a non-empty objective: pass it via -m.",- thinkingCurrentDefault: (level) =>- `[thinking] level: ${level} (this Session's default) — change with /thinking <low|medium|high|xhigh|max>`,- thinkingCurrentOverride: (level, sessionDefault) =>- `[thinking] level: ${level} (override for this chat's turns; this Session's default is ${sessionDefault}) — change with /thinking <low|medium|high|xhigh|max>`,+ thinkingCurrent: (level) =>+ `[thinking] level: ${level} (this Session's) — change with /thinking <low|medium|high|xhigh|max>`,thinkingSet: (level) =>- `[thinking] level set to ${level} for this chat's subsequent turns (the Agent config is unchanged)`,+ `[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.`,verboseOn: () => "[verbose] on — tool output from here on shows in full",@@ -1063,8 +1052,10 @@ const en: Messages = {visionModelCleared: () => "It was also the vision model; that setting is now unset.",modelListTitle: () => "Configured models:",modelListEmpty: () => "No models configured yet. Add one with `penguin config model add`.",- vaultSet: (key) => `Saved vault entry ${key}.`,- vaultRemoved: (key) => `Removed vault entry ${key}.`,+ vaultSet: (key) =>+ `Saved vault entry ${key}. New conversations pick it up right away; running ones after their next compaction.`,+ vaultRemoved: (key) =>+ `Removed vault entry ${key}. New conversations pick it up right away; running ones after their next compaction.`,vaultKeyMissing: (key) => `Vault entry ${key} does not exist.`,vaultListTitle: () => "Vault environment variables (values masked):",vaultListEmpty: () => "The vault is empty. Add one with `penguin config vault set`.",@@ -1511,11 +1502,10 @@ const zh: Messages = {goalBudgetInvalid: (value) =>`无效的 token 预算 "${value}":应为正数,可带 k/m 后缀(500k、2m)。`,goalObjectiveEmpty: () => "目标模式需要非空的目标文本:请通过 -m 传入。",- thinkingCurrentDefault: (level) =>- `[思考] 当前等级:${level}(本 Session 的缺省值)——用 /thinking <low|medium|high|xhigh|max> 修改`,- thinkingCurrentOverride: (level, sessionDefault) =>- `[思考] 当前等级:${level}(本次对话后续轮次的覆盖值;本 Session 缺省为 ${sessionDefault})——用 /thinking <low|medium|high|xhigh|max> 修改`,- thinkingSet: (level) => `[思考] 等级已设为 ${level},本次对话后续轮次生效(不改动 Agent 配置)`,+ thinkingCurrent: (level) =>+ `[思考] 当前等级:${level}(本 Session)——用 /thinking <low|medium|high|xhigh|max> 修改`,+ thinkingSet: (level) =>+ `[思考] 本 Session 的等级已钉为 ${level},下一轮请求起生效——更换思考等级会使模型缓存失效,建议先 /compact 压缩上下文(不改动 Agent 配置)`,thinkingInvalid: (value) => `无效的思考等级 "${value}"。请使用 low、medium、high、xhigh 或 max。`,verboseOn: () => "[详细输出] 已开启——后续工具输出完整显示(/verbose 切换)",verboseOff: () => "[详细输出] 已关闭——后续过长的工具输出将折叠(/verbose 切换)",@@ -1549,8 +1539,9 @@ const zh: Messages = {visionModelCleared: () => "它同时是视觉模型,该设置已一并清空。",modelListTitle: () => "已配置的模型:",modelListEmpty: () => "尚未配置任何模型。用 `penguin config model add` 添加。",- vaultSet: (key) => `已保存 vault 条目 ${key}。`,- vaultRemoved: (key) => `已删除 vault 条目 ${key}。`,+ vaultSet: (key) => `已保存 vault 条目 ${key}。新对话立即生效;进行中的对话在下一次压缩后生效。`,+ vaultRemoved: (key) =>+ `已删除 vault 条目 ${key}。新对话立即生效;进行中的对话在下一次压缩后生效。`,vaultKeyMissing: (key) => `vault 条目 ${key} 不存在。`,vaultListTitle: () => "vault 环境变量(值已掩码):",vaultListEmpty: () => "vault 为空。用 `penguin config vault set` 添加。",diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.tsindex a2fb0cc0..d2a76998 100644--- a/packages/cli/src/render.ts+++ b/packages/cli/src/render.ts@@ -901,10 +901,11 @@ export class StreamRenderer {);this.lastLineKey = null;} else if (payload.type === "mcp_connect_begin") {- // Paired MCP connect events (first run only): begin shows which servers are being- // contacted so the pre-first-request wait is never a silent hang. The begin- // timestamp is kept so the end line can report the wall time (messages carry- // their own timestamps; the payload holds no duplicate duration).+ // Paired MCP connect events (the first run, and every context a compaction opens):+ // begin shows which servers are being contacted so the wait before the next+ // request is never a silent hang. The begin timestamp is kept so the end line can+ // report the wall time (messages carry their own timestamps; the payload holds no+ // duplicate duration).const p = payload as McpConnectBeginPayload;this.mcpConnectStartMs = Date.parse(msg.timestamp);this.finishLine();diff --git a/packages/cli/src/server-session.ts b/packages/cli/src/server-session.tsindex 7872c4d3..aa854414 100644--- a/packages/cli/src/server-session.ts+++ b/packages/cli/src/server-session.ts@@ -76,6 +76,15 @@ export async function createServerSession(return res.session;}+/** PATCHes the Session's thinking level: the pin core applies from the Session's next LLM request. */+export async function pinThinkingLevel(+ client: ServerClient,+ sessionId: string,+ level: string,+): Promise<void> {+ await client.request("PATCH", `/api/sessions/${enc(sessionId)}`, { thinkingLevel: level });+}+export async function getSessionInfo(client: ServerClient,sessionId: string,diff --git a/packages/cli/src/thinking-command.ts b/packages/cli/src/thinking-command.tsindex ac166f87..951c984e 100644--- a/packages/cli/src/thinking-command.ts+++ b/packages/cli/src/thinking-command.ts@@ -6,17 +6,15 @@* mirroring the web pickers: "none" stays a valid stored config value but is never offered* for selection (many models cannot disable thinking).*- * Semantics (aligned with the web active-session picker and core's tri-state option):- * - `--thinking <level>` pins the Session's default level at creation- * (`createSession.thinkingLevel`, so spawned subagent sessions follow it too). Under- * chat `--resume` the Session already exists — the flag becomes the initial per-turn- * override instead (the thinking level is a per-turn run parameter, so this is allowed- * where `--workspace` / `--model-id` are not).- * - `/thinking <level>` sets a per-turn override carried on every subsequent run- * (`RunOptions.thinkingLevel`); it never writes back to the Agent config.- * - `/thinking` bare shows the level the next turn will run at, and names its source: the- * Session's own default, or the per-turn override (plus the default it replaces). The two- * differ in reach — only the Session's level is inherited by spawned subagent sessions.+ * Semantics (aligned with the web active-session picker; the thinking level is the+ * SOFT-limited runtime parameter):+ * - `--thinking <level>` pins the Session (a PATCH on it, so spawned subagent sessions+ * follow it too). Core applies the pin from the Session's next LLM request, and every+ * context opened from then on defaults to it.+ * - `/thinking <level>` re-pins the Session the same way; the reply advises `/compact`+ * first, because a mid-context change invalidates the provider's cached context. It+ * never writes back to the Agent config.+ * - `/thinking` bare shows the Session's pinned level, else the Agent's configured level.*/import { DEFAULT_CHAT_THINKING_LEVELS } from "@prismshadow/penguin-core";import type { DefaultChatThinkingLevel, ThinkingLevelName } from "@prismshadow/penguin-core";diff --git a/packages/cli/test/chat-thinking.test.ts b/packages/cli/test/chat-thinking.test.tsindex 8cc1acdf..a8c5545a 100644--- a/packages/cli/test/chat-thinking.test.ts+++ b/packages/cli/test/chat-thinking.test.ts@@ -1,9 +1,9 @@/**- * chat `/thinking` + `--thinking` (per-turn thinking level) and `/verbose` (tool-output- * collapsing), over the server transport: drives the real REPL over a fake stdin against- * the in-process fake server (same harness as chat-clear.test.ts). Task bodies record- * what the server would receive (`thinkingLevel` on POST /tasks; a sticky pin is a PATCH- * on the Session); the verbose test streams a long fake tool output through the real+ * chat `/thinking` + `--thinking` (the Session's pinned thinking level) and `/verbose`+ * (tool-output collapsing), over the server transport: drives the real REPL over a fake+ * stdin against the in-process fake server (same harness as chat-clear.test.ts). The fake+ * records what the server would receive (a pin is a PATCH on the Session; task bodies+ * carry no level); the verbose test streams a long fake tool output through the real* renderer to prove the collapsed/full switch.*/import { PassThrough } from "node:stream";@@ -72,19 +72,27 @@ async function driveChat(lines: string[], argv: string[] = []): Promise<string>}}-/** Task bodies' thinkingLevel in POST order for one session. */-function taskLevels(sessionOrdinal: number): Array<string | undefined> {+/** The thinking levels PATCHed onto one session, in order. */+function pinnedLevels(sessionOrdinal: number): string[] {const sessions = [...server.sessions.values()];- return sessions[sessionOrdinal]!.tasks.map((b) => b.thinkingLevel as string | undefined);+ return sessions[sessionOrdinal]!.patches.map(+ (p) => (p as { thinkingLevel?: unknown }).thinkingLevel,+ ).filter((l): l is string => typeof l === "string");}-describe("chat /thinking (per-turn thinking level, server-backed)", () => {- it("bare /thinking shows the Session default (unpinned = the Agent's configured level applies server-side)", async () => {+/** Whether any task body of one session carried a thinking level (none may). */+function anyTaskCarriesLevel(sessionOrdinal: number): boolean {+ const sessions = [...server.sessions.values()];+ return sessions[sessionOrdinal]!.tasks.some((b) => "thinkingLevel" in (b as object));+}++describe("chat /thinking (the Session's pinned thinking level, applied per model context)", () => {+ it("bare /thinking shows the Session's level (unpinned = the Agent's configured level applies server-side)", async () => {const out = await driveChat(["/thinking", "/exit"]);- expect(out).toContain(t.thinkingCurrentDefault(t.chatThinkingConfigured()));+ expect(out).toContain(t.thinkingCurrent(t.chatThinkingConfigured()));});- it("/thinking <level> overrides subsequent turns; invalid values change nothing", async () => {+ it("/thinking <level> pins the Session (a PATCH) and tasks carry no level; invalid values change nothing", async () => {const out = await driveChat(["/thinking","first",@@ -96,9 +104,9 @@ describe("chat /thinking (per-turn thinking level, server-backed)", () => {"/exit",]);expect(out).toContain(t.thinkingSet("high"));- // Once overridden, the display says so and still names the Session default it overrides.- expect(out).toContain(t.thinkingCurrentOverride("high", t.chatThinkingConfigured()));- // "none" is not selectable (mirrors the web picker): error + the override stays "high".+ // Once pinned, the display shows the Session's level.+ expect(out).toContain(t.thinkingCurrent("high"));+ // "none" is not selectable (mirrors the web picker): error + the pin stays "high".expect(out).toContain(t.error(t.thinkingInvalid("none")));const session = [...server.sessions.values()][0]!;expect(session.tasks.map((b) => (b.input as Array<{ text: string }>)[0]!.text)).toEqual([@@ -106,45 +114,48 @@ describe("chat /thinking (per-turn thinking level, server-backed)", () => {"second","third",]);- expect(taskLevels(0)).toEqual([undefined, "high", "high"]);+ expect(pinnedLevels(0)).toEqual(["high"]);+ expect(session.thinkingLevel).toBe("high");+ expect(anyTaskCarriesLevel(0)).toBe(false);});- it("--thinking pins the Session default (a PATCH — sticky, so subagents follow) and runs carry no per-turn override", async () => {+ it("--thinking pins the Session (a PATCH — sticky across tasks); tasks carry no level", async () => {const out = await driveChat(["/thinking", "go", "/exit"], ["--thinking", "xhigh"]);const session = [...server.sessions.values()][0]!;expect(session.patches).toContainEqual({ thinkingLevel: "xhigh" });expect(session.thinkingLevel).toBe("xhigh");- expect(out).toContain(t.thinkingCurrentDefault("xhigh"));- expect(taskLevels(0)).toEqual([undefined]);+ expect(out).toContain(t.thinkingCurrent("xhigh"));+ expect(anyTaskCarriesLevel(0)).toBe(false);});- it("--resume turns --thinking into the initial per-turn override (the Session already exists)", async () => {+ it("--resume with --thinking re-pins the existing Session (its context in flight keeps its level until the next compaction)", async () => {const existing = server.addSession({ thinkingLevel: "low" });const out = await driveChat(["/thinking", "go", "/exit"],["--resume", existing.sessionId, "--thinking", "high"],);- // No pin is written on resume; the flag rides each task instead.- expect(existing.patches).toEqual([]);- expect(out).toContain(t.thinkingCurrentOverride("high", "low"));- expect(existing.tasks.map((b) => b.thinkingLevel)).toEqual(["high"]);+ expect(existing.patches).toContainEqual({ thinkingLevel: "high" });+ expect(existing.thinkingLevel).toBe("high");+ expect(out).toContain(t.thinkingCurrent("high"));+ expect(existing.tasks.some((b) => "thinkingLevel" in (b as object))).toBe(false);});- it("--resume without --thinking runs on the resumed Session's own pinned level (no override)", async () => {+ it("--resume without --thinking runs on the resumed Session's own pinned level (no PATCH)", async () => {const existing = server.addSession({ thinkingLevel: "xhigh" });const out = await driveChat(["/thinking", "go", "/exit"], ["--resume", existing.sessionId]);- expect(out).toContain(t.thinkingCurrentDefault("xhigh"));- expect(existing.tasks.map((b) => b.thinkingLevel)).toEqual([undefined]);+ expect(out).toContain(t.thinkingCurrent("xhigh"));+ expect(existing.patches.some((p) => "thinkingLevel" in (p as object))).toBe(false);});- it("/clear keeps the --thinking session default and the /thinking override", async () => {+ it("/clear carries the Session's latest pin to the replacement Session", async () => {await driveChat(["/thinking high", "/clear", "after", "/exit"], ["--thinking", "low"]);const sessions = [...server.sessions.values()];expect(sessions).toHaveLength(2);- // The replacement Session gets the same sticky pin…- expect(sessions[1]!.patches).toContainEqual({ thinkingLevel: "low" });- // …and the per-turn override still rides the next task.- expect(sessions[1]!.tasks.map((b) => b.thinkingLevel)).toEqual(["high"]);+ // Pinned low at creation, re-pinned high by /thinking; the replacement inherits the+ // latest pin and its tasks carry none.+ expect(pinnedLevels(0)).toEqual(["low", "high"]);+ expect(sessions[1]!.patches).toContainEqual({ thinkingLevel: "high" });+ expect(anyTaskCarriesLevel(1)).toBe(false);});});@@ -206,8 +217,8 @@ describe("chat caller-context defaults (PENGUIN_SESSION_ID inheritance)", () =>expect(created.provider).toBe("caller-prov");expect(created.approvalMode).toBe("read-only");// The caller's level pins the new Session (sticky, so subagents follow), and the- // display names it as the Session default — not an override.+ // display shows it as the Session's level.expect(created.patches).toContainEqual({ thinkingLevel: "xhigh" });- expect(out).toContain(t.thinkingCurrentDefault("xhigh"));+ expect(out).toContain(t.thinkingCurrent("xhigh"));});});diff --git a/packages/cli/test/i18n.test.ts b/packages/cli/test/i18n.test.tsindex e3c605ae..7776db18 100644--- a/packages/cli/test/i18n.test.ts+++ b/packages/cli/test/i18n.test.ts@@ -47,17 +47,13 @@ describe("getMessages", () => {expect(getMessages("en").langSet("zh", "/x/.zshrc")).toContain("/x/.zshrc");expect(getMessages("zh").langInvalid("fr")).toContain("fr");// Thinking-level control and tool-output collapsing (issue #305).- expect(getMessages("en").thinkingCurrentDefault("medium")).toContain("medium");- expect(getMessages("zh").thinkingCurrentDefault("medium")).toContain("medium");- // The override form names both levels, so the distinction is readable in either locale.- for (const lang of ["en", "zh"] as const) {- const shown = getMessages(lang).thinkingCurrentOverride("high", "low");- expect(shown).toContain("high");- expect(shown).toContain("low");- expect(shown).not.toBe(getMessages(lang).thinkingCurrentDefault("high"));- }+ expect(getMessages("en").thinkingCurrent("medium")).toContain("medium");+ expect(getMessages("zh").thinkingCurrent("medium")).toContain("medium");expect(getMessages("en").thinkingSet("high")).toContain("high");expect(getMessages("zh").thinkingSet("high")).toContain("high");+ // The soft limit's reminder: both locales advise compacting first when re-pinning.+ expect(getMessages("en").thinkingSet("high")).toContain("/compact");+ expect(getMessages("zh").thinkingSet("high")).toContain("/compact");expect(getMessages("en").thinkingInvalid("none")).toContain('"none"');expect(getMessages("zh").thinkingInvalid("none")).toContain('"none"');expect(getMessages("en").toolOutputElided(42)).toContain("42");diff --git a/packages/cli/test/server-commands.test.ts b/packages/cli/test/server-commands.test.tsindex 62b43280..58b4fc49 100644--- a/packages/cli/test/server-commands.test.ts+++ b/packages/cli/test/server-commands.test.ts@@ -105,10 +105,11 @@ describe("penguin run", () => {expect(session.tasks[0]!.goal).toEqual({ budget: 500_000 });});- it("--thinking rides the task body", async () => {+ it("--thinking pins the Session before the task (a PATCH); the task body carries no level", async () => {await cli(["run", "-m", "q", "--thinking", "high"]);const session = [...server.sessions.values()][0]!;- expect(session.tasks[0]!.thinkingLevel).toBe("high");+ expect(session.patches).toContainEqual({ thinkingLevel: "high" });+ expect("thinkingLevel" in (session.tasks[0] as object)).toBe(false);});});@@ -294,7 +295,7 @@ describe("penguin schedule ls", () => {});describe("caller-context defaults (PENGUIN_SESSION_ID inheritance)", () => {- it("run inherits workspace/model/approve from the calling session and thinking rides the task", async () => {+ it("run inherits workspace/model/approve from the calling session and pins its thinking level on the new session", async () => {const caller = server.addSession({sessionId: "session-2026-08-25-10-00-00-ca11e001",workspace: "/callers/workdir",@@ -315,7 +316,7 @@ describe("caller-context defaults (PENGUIN_SESSION_ID inheritance)", () => {client: "cli",});const created = [...server.sessions.values()].find((x) => x.sessionId !== caller.sessionId)!;- expect(created.tasks[0]!.thinkingLevel).toBe("high");+ expect(created.patches).toContainEqual({ thinkingLevel: "high" });});it("an explicit flag overrides its own field only (the rest still inherit)", async () => {@@ -340,7 +341,7 @@ describe("caller-context defaults (PENGUIN_SESSION_ID inheritance)", () => {approvalMode: "always-ask",});const created = [...server.sessions.values()].find((x) => x.sessionId !== caller.sessionId)!;- expect(created.tasks[0]!.thinkingLevel).toBe("low"); // flag wins+ expect(created.patches).toContainEqual({ thinkingLevel: "low" }); // flag wins});it("a failed caller lookup warns (dim, stderr) and falls back to the plain defaults", async () => {diff --git a/packages/cli/test/thinking-command.test.ts b/packages/cli/test/thinking-command.test.tsindex 48b52fd7..37af3b59 100644--- a/packages/cli/test/thinking-command.test.ts+++ b/packages/cli/test/thinking-command.test.ts@@ -33,8 +33,7 @@ describe("the advertised tier set matches the accepted one", () => {for (const messages of [getMessages("en"), getMessages("zh")]) {const printed = [messages.common.thinking,- messages.thinkingCurrentDefault("low"),- messages.thinkingCurrentOverride("low", "medium"),+ messages.thinkingCurrent("low"),messages.thinkingInvalid("bogus"),].join(" ");for (const level of DEFAULT_CHAT_THINKING_LEVELS) {diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 59e2ee44..93f84708 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -5,6 +5,12 @@* if the directory is empty, otherwise loads by agentId.* An Agent has exactly one Agent State and can run multiple times; the* Workspace is determined when a Session is created.+ *+ * 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.*/import fs from "node:fs/promises";import path from "node:path";@@ -19,8 +25,8 @@ import {getModel,listInstalledSkills,listScheduleNames,+ loadAgentState,loadAgentVault,- loadOrInitAgentState,loadProjectConfig,projectDir,goalFilePath,@@ -43,28 +49,42 @@ import {resumeTrace,} from "./trace/index.js";import { Session } from "./session.js";+import type { SessionConfig } from "./session.js";import {createTempWorkspace,formatSessionId,+ mcpConnectOutcome,sessionEnvironment,} from "./internal/session-support.js";-import { compactionEnd, userText, withOrigin } from "./omnimessage/index.js";+import {+ compactionEnd,+ mcpConnectBegin,+ mcpConnectEnd,+ sessionMeta,+ toolListReady,+ userText,+ withOrigin,+} from "./omnimessage/index.js";import type {- McpServerConnectResult,MessageOrigin,OmniMessage,- TokenCounts,+ SessionMetaPayload,ToolCallPayload,} from "./omnimessage/index.js";import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";import { INPUT_SUBAGENT_NAME } from "./environment/tools/input-subagent.js";-import type { CompactionSettings } from "./engine/context-engine.js";import type {- GenerativeModelConfig,+ CompactionSettings,+ OpenContextOptions,+ OpenedContext,+} from "./engine/context-engine.js";+import type {+ CommandPolicyConfig,ProxyEnvPolicy,SubagentHandle,SubagentRunner,ThinkingLevelName,+ ToolConfig,ToolDefinition,VisionDescriberService,} from "./interfaces/index.js";@@ -129,9 +149,10 @@ export interface CreateSessionOptions {* - a `ThinkingLevelName` pins the level;* - `undefined` (omitted) falls back to the config chain: the Agent's explicit* `model.thinking_level` > the Project's `default_chat.thinking_level` > the built-in- * `"medium"` (see `configuredThinkingLevel`);+ * `"medium"` (see `configuredThinkingLevel`), read again for every model context the+ * Session opens;* - `null` means "no thinking level": the config fallback is suppressed entirely- * (nothing goes into the LLM config; session_meta echoes `"default"`).+ * (nothing goes into the LLM config).* Subagent spawning passes the parent Session's effective level (its level, or `null`* when the parent has none) unless the spawn requests an explicit level (`run_subagent`'s* `thinking_level`) — either way a child Session never falls back to the child Agent's@@ -155,6 +176,81 @@ export interface ResumeSessionOptions {baseUrl?: string;}+/**+ * 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`).+ */+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 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;+ * `undefined` reads the Agent config's default when each context opens. Fixed at+ * creation: a mid-session change (`Session.thinkingLevel`) is engine state — it rides+ * requests but reshapes no context and never lands here.+ */+ thinkingLevel: ThinkingLevelName | null | undefined;+ subagentDepth: number;+ source?: "subagent" | "schedule";+}++/**+ * A Session's runtime components, assembled once by `buildRuntime` (shared by createSession+ * and resumeSession) around the context the Session starts in.+ */+interface SessionRuntime {+ /** Session-lifetime Environment, equipped with the initial context's toolset and vault (a later context re-equips it — see openNextContext). */+ environment: Environment;+ /**+ * Opens the Session's FIRST context, lazily at the start of the first run: resolves the+ * toolset (the Environment's first listTools connects any configured MCP Servers,+ * published through `opts.emit` as the connect pair, then the toolset record) and builds+ * that context's LLM object. Kept out of createSession on purpose — Session creation+ * stays instant and the records stream on the run. The same opening procedure as+ * `openNextContext`: only what is being opened differs.+ */+ bootstrap: (opts: OpenContextOptions) => Promise<{ llm: GenerativeModel }>;+ /**+ * Opens the context that follows a completed compaction (see ContextEngineDeps.openNextContext):+ * the whole configuration assembled anew from the Agent State, the Environment re-equipped+ * with it, then the same opening procedure as `bootstrap` — and the session_meta recording+ * the context alongside its engine settings.+ */+ openNextContext: (opts: OpenContextOptions) => Promise<OpenedContext>;+ /** The running context's command policy — follows the rotation (see SessionConfig.commandPolicy). */+ commandPolicy: () => CommandPolicyConfig | undefined;++ createBareLLM: () => GenerativeModel;+}++/**+ * What one model context runs with, assembled from the Agent State as it was on disk at the+ * moment the context opened; immutable for the context's lifetime.+ */+interface AssembledContext {+ systemPrompt: string;+ /** The vault's values, for the Environment's command subprocesses; only the key names enter the prompt. */+ vault: Record<string, string>;+ toolConfig: ToolConfig;+ /** The Project's command policy as read when this context opened (`[command_policy]` of `.project_config.toml`) — Project-owned rather than Agent State, rotated on the same strict-tier schedule. */+ commandPolicy: CommandPolicyConfig | undefined;+ /** The context's effective thinking level: the Session's pin, or the config default read now. */+ thinkingLevel: ThinkingLevelName | undefined;+ maxTokens: number | undefined;+ requestTimeoutMs: number | undefined;+ /** `system_config.max_turns`; the engine treats absent as unlimited (-1). */+ maxTurns: number | undefined;+ compaction: CompactionSettings;+ /** The session_meta describing this context: the prompt it runs with, and the Session-fixed facts. */+ meta: SessionMetaPayload;+}+// Compaction-threshold derivation (`effectiveMaxContextLength`) lives with the rest of the// window arithmetic in llm/context-limits.ts; re-exported by llm/index.js.@@ -169,9 +265,14 @@ export function metaMaxTokens(budget: number, modelCap: number | undefined): numreturn modelCap !== undefined && modelCap > 0 ? Math.min(budget, modelCap) : budget;}-/** Create or load an Agent. */+/** Create or load an Agent (the one init-enabled use of `loadAgentState`). */export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent> {- const state = await loadOrInitAgentState(opts);+ const state = await loadAgentState({+ ...(opts.agentId !== undefined ? { agentId: opts.agentId } : {}),+ ...(opts.projectId !== undefined ? { projectId: opts.projectId } : {}),+ ...(opts.root !== undefined ? { root: opts.root } : {}),+ init: {},+ });const projectConfig = await loadProjectConfig(state.root, state.projectId);return new Agent(state, projectConfig, opts.proxyEnv, opts.controlEnv);}@@ -190,19 +291,171 @@ export class Agent {* 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* `model.thinking_level` > the Project's `default_chat.thinking_level` > the built-in- * `"medium"` (the documented Agent default). Mirrored by the web draft picker's DISPLAY- * (web features/chat/thinking-level.ts `effectiveThinkingLevel`): the picker shows this- * effective value, and a pick writes through to the AGENT config — the project default- * is only ever a fallback, never overwritten from there.+ * `"medium"` (the documented Agent default). Read against the Agent State and the Project+ * config a context is assembled from, so the default follows both files into each new+ * context. Mirrored by+ * the web draft picker's DISPLAY (web features/chat/thinking-level.ts+ * `effectiveThinkingLevel`): the picker shows this effective value, and a pick writes+ * through to the AGENT config — the project default is only ever a fallback, never+ * overwritten from there.*/- private configuredThinkingLevel(): ThinkingLevelName {+ private configuredThinkingLevel(+ state: AgentState,+ projectConfig: ProjectConfig,+ ): ThinkingLevelName {return (- this.state.systemConfig.model?.thinking_level ??- this.projectConfig.default_chat?.thinking_level ??+ state.systemConfig.model?.thinking_level ??+ projectConfig.default_chat?.thinking_level ??"medium");}+ /**+ * Assembles what a model context runs with, from the Agent State as it is on disk **now**:+ * `system_config.yaml` in full — the prompt template with its section prompts and toggles,+ * the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the+ * model defaults — plus `AGENTS.md`, the vault, the installed Skills' metadata, the Memory+ * indexes, the schedule roster and the Environment values (the date included). Every+ * context opener goes through here — createSession, the context a completed compaction+ * 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.+ *+ * 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+ * inject metadata (name and description) and the model reads the body on demand via shell;+ * Memory likewise injects only its index; Schedules inject only task names.+ *+ * `systemPrompt`, when given, is used instead of assembling it: a+ * resume of an open context keeps the prompt its Trace recorded, since the history+ * replayed into it was produced under that request prefix.+ * Docs: /docs/agent-loop § "Compaction".+ */+ private async assembleContext(+ spec: SessionSpec,+ opts: { systemPrompt?: string } = {},+ ): Promise<AssembledContext> {+ const { root, projectId, agentId } = this.state;+ const state = await loadAgentState({ root, projectId, agentId });+ const vault = await loadAgentVault(root, projectId, agentId);+ // Strict-tier alongside the Agent State even though it is Project-owned: the command+ // policy this context runs under (and the Project half of the thinking-level chain) is+ // the one on disk at its open.+ const projectConfig = await loadProjectConfig(root, projectId);+ const commandPolicy = projectConfig.command_policy;+ let systemPrompt = opts.systemPrompt;+ if (systemPrompt === undefined) {+ const installedSkills = await listInstalledSkills(root, projectId, agentId);+ // Schedule task names for the {{SCHEDULES}} roster (names only; the files' contents are+ // the server-side scheduler's concern).+ const scheduleNames = await listScheduleNames(root, projectId, agentId);+ // Memory for this Session: null when the Agent has Memory off; a temporary Workspace+ // gets the user scope only (nothing written against it could ever be read back).+ const memory = await resolveSessionMemory({+ root,+ projectId,+ agentId,+ workspaceDir: spec.workspaceDir,+ enabled: state.systemConfig.memory?.enabled !== false,+ });+ systemPrompt = assembleSystemPrompt(+ state,+ sessionEnvironment(spec.workspaceDir, spec.sessionId, {+ agentId,+ projectDir: projectDir(root, projectId),+ provider: spec.modelEntry.provider,+ modelId: spec.modelEntry.model_id,+ }),+ Object.keys(vault),+ installedSkills,+ memory,+ scheduleNames,+ );+ }++ // 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 (marked via forModel: vision models use+ // read_image, text-only models use describe_image; entries without this marker are+ // unaffected).+ const canSpawn = spec.subagentDepth < MAX_SUBAGENT_DEPTH;+ const baseToolConfig = buildToolConfig(state);+ const modelVision = spec.modelEntry.vision !== false;+ let customTools = selectBuiltinToolsForModel(baseToolConfig.customTools, modelVision);+ if (!canSpawn) {+ customTools = customTools.filter(+ (d) =>+ d.name !== SUBAGENT_NAME &&+ d.name !== INPUT_SUBAGENT_NAME &&+ // Legacy entry still present in stale stored configs; the registry no longer+ // assembles it, this just keeps the leaf filter symmetrical.+ d.name !== "kill_subagent",+ );+ }+ const toolConfig: ToolConfig = { ...baseToolConfig, customTools };++ // The context's base thinking level — the Session's tri-state pin: a value wins over+ // every config; `null` — how subagent spawning says "the parent has none" — suppresses+ // the config fallback entirely; only `undefined` (no pin) reads the config chain,+ // against this context's State (Agent explicit > Project default_chat > built-in+ // "medium", see configuredThinkingLevel). A per-request parameter, not part of the+ // prefix: this is only the base the Session's live pin overrides, and nothing records it.+ const pin = spec.thinkingLevel;+ const thinkingLevel =+ pin === null ? undefined : (pin ?? this.configuredThinkingLevel(state, projectConfig));++ // Compaction config: defaults are filled in here; an unknown mode falls back to+ // summarize (the default).+ const compactionConfig = state.systemConfig.compaction;+ const compaction: CompactionSettings = {+ maxContextLength: effectiveMaxContextLength(+ compactionConfig?.max_context_length ?? DEFAULT_MAX_CONTEXT_LENGTH,+ spec.modelEntry.context_window,+ ),+ maxSessionTurns: compactionConfig?.max_session_turns ?? -1,+ mode: compactionConfig?.mode === "discard" ? "discard" : "summarize",+ prompt: compactionConfig?.prompt ?? DEFAULT_COMPACTION_PROMPT,+ };++ // 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+ // rebuilds the same request prefix; the toolset travels as the tool_list_ready event (it+ // 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",+ system_prompt: systemPrompt,+ agent_state: state.stateDir,+ workspace: spec.workspaceDir,+ ...(spec.source !== undefined ? { source: spec.source } : {}),+ };++ return {+ systemPrompt,+ vault,+ toolConfig,+ commandPolicy,+ thinkingLevel,+ // Configured output cap: the entry's per-model annotation wins over the Agent's+ // system_config value; unset inherits the Agent value. This is a ceiling, not the+ // literal wire value: GenerativeModel clamps each request's effective cap to what the+ // 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,+ requestTimeoutMs: state.systemConfig.model?.timeoutMs,+ // Max turns is an Agent runtime parameter (system_config), not a Session option.+ maxTurns: state.systemConfig.max_turns,+ compaction,+ meta,+ };+ }+/*** Create a Session in the specified (or a temporary) Workspace.* Docs: /docs/sessions-and-traces § "Run model".@@ -268,142 +521,43 @@ export class Agent {);}const sessionId = formatSessionId();- const subagentDepth = opts.subagentDepth ?? 0;- // Effective thinking level (tri-state option): a value wins over every config; `null` —- // how subagent spawning says "the parent has none" — suppresses the config fallback- // entirely; only `undefined` (no option) reads the config chain (Agent explicit >- // Project default_chat > built-in "medium", see configuredThinkingLevel).- const thinkingLevel =- opts.thinkingLevel === null- ? undefined- : (opts.thinkingLevel ?? this.configuredThinkingLevel());-- // Agent-level vault (agent_state/.vault.toml) and installed Skills: read the current values each time a Session is created.- const vault = await loadAgentVault(this.state.root, this.state.projectId, this.state.agentId);- const installedSkills = await listInstalledSkills(- this.state.root,- this.state.projectId,- this.state.agentId,- );- // Schedule task names for the {{SCHEDULES}} roster: read fresh like the vault and Skills- // above (names only; the files' contents are the server-side scheduler's concern).- const scheduleNames = await listScheduleNames(- this.state.root,- this.state.projectId,- this.state.agentId,- );- // Memory for this Session: null when the Agent has Memory off; a temporary Workspace gets- // the user scope only (nothing written against it could ever be read back). Reads the- // current indexes every time, like the vault and Skills above.- const memory = await resolveSessionMemory({- root: this.state.root,- projectId: this.state.projectId,- agentId: this.state.agentId,- workspaceDir,- enabled: this.state.systemConfig.memory?.enabled !== false,- });-- // The assembled system prompt goes both to the LLM and into session_meta (so the- // Trace can audit the actual effective value). The vault only injects **key names**- // into the prompt (so the model knows which API keys are available); values only- // go into the subprocess environment. Skills only inject metadata (name and- // description); the model reads the body on demand via shell. Memory likewise injects- // only its index; topic bodies are read on demand. Schedules inject only task names.- const systemPrompt = assembleSystemPrompt(- this.state,- sessionEnvironment(workspaceDir, sessionId, {- agentId: this.state.agentId,- projectDir: projectDir(this.state.root, this.state.projectId),- provider: modelEntry.provider,- modelId: modelEntry.model_id,- }),- Object.keys(vault),- installedSkills,- memory,- scheduleNames,- );-- const rt = await this.buildRuntime({+ const spec: SessionSpec = {sessionId,workspaceDir,modelEntry,apiKey,baseUrl,- systemPrompt,- thinkingLevel,- subagentDepth,- vault,- });+ thinkingLevel: opts.thinkingLevel,+ subagentDepth: opts.subagentDepth ?? 0,+ ...(opts.source !== undefined ? { source: opts.source } : {}),+ };+ // 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 rt = this.buildRuntime(spec, context);const trace = new Writer({tracesDir: tracesDir(this.state.root, this.state.projectId, this.state.agentId),sessionId,});- return new Session({- // session_meta holds per-session invariants only: the thinking level is a per-turn- // run parameter (RunOptions.thinkingLevel) and is deliberately not recorded here;- // the toolset travels as the first run's tool_list_ready event (it is only known- // after the MCP connect the bootstrap performs).- meta: {- session_id: sessionId,- provider: modelEntry.provider,- model_id: modelEntry.model_id,- model_context_window: modelEntry.context_window ?? "unknown",- system_prompt: systemPrompt,- agent_state: this.state.stateDir,- workspace: workspaceDir,- ...(opts.source !== undefined ? { source: opts.source } : {}),- },- bootstrap: rt.bootstrap,- cancelBootstrap: () => rt.environment.cancelMcpConnect(),- mcpServers: rt.environment.mcpServerNames(),- environment: rt.environment,- trace,- createLLM: rt.createLLM,- createBareLLM: rt.createBareLLM,- compaction: rt.compaction,- // Where an input image lands when it becomes a path line (see SessionConfig.imagesDir).- imagesDir: sessionScratchpadDir(- this.state.root,- this.state.projectId,- this.state.agentId,- sessionId,- ),- modelHasVision: modelEntry.vision !== false,- // Goal mode's control file lives in the session scratchpad; the path is fixed per- // Session, so it is wired here rather than passed per-run.- goalFilePath: goalFilePath(- this.state.root,- this.state.projectId,- this.state.agentId,- sessionId,- ),- // Max turns comes from the Agent's system_config (runtime parameters belong to the Agent config).- ...(this.state.systemConfig.max_turns !== undefined- ? { maxTurns: this.state.systemConfig.max_turns }- : {}),- // Sandbox command policy snapshot: Project-owned (never Agent State), read once per- // Session so the running Session's copy cannot be edited from inside it. Absent- // config means the factory rule set, on.- ...(this.projectConfig.command_policy !== undefined- ? { commandPolicy: this.projectConfig.command_policy }- : {}),- });+ return this.newSession(spec, context, rt, trace);}/*** Resume an existing Session and continue the conversation.*- * The resume source is the Session's **latest-index** Trace file: runtime config is- * read from its `session_meta` (Model, the original system prompt text, and the- * Workspace all carry over from the original Session and cannot be changed), while- * tools and Environment are reassembled from the current Agent State. 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 context, not the date),- * and Token / turn-count stats carry over from their original values.+ * 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+ * 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+ * context, not the date), and Token / turn-count stats carry over from their original+ * values.* Docs: /docs/sessions-and-traces § "Session recovery".*/async resumeSession(opts: ResumeSessionOptions): Promise<Session> {@@ -454,31 +608,37 @@ export class Agent {const apiKey = opts.apiKey ?? modelEntry.api_key;const baseUrl = opts.baseUrl ?? modelEntry.base_url;- // Tools and Environment are reassembled from the current Agent State (tool- // definitions are passed with every Request and aren't part of the history); the- // system prompt uses the original text recorded in the Trace (identical to the- // original history); the vault uses current values (it's injected into the- // subprocess environment, not the history, so a resumed Session should get the- // latest keys too).- // The default thinking level comes from the current config chain only (Agent explicit >- // Project default_chat > built-in "medium", the same configuredThinkingLevel chain- // createSession uses): session_meta no longer records one (it became a per-turn run- // parameter), and a `thinking_level` still present in a legacy Trace's meta JSON is- // deliberately ignored — a resumed legacy subagent session falls back to this Agent's- // configured level instead of keeping the level it inherited at spawn time.- const thinkingLevel = this.configuredThinkingLevel();-- const rt = await this.buildRuntime({+ // 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+ // createSession uses). The origin carries over from the original session_meta (a+ // resumed scheduled/subagent Session stays marked); the on-disk value is untrusted: only+ // the exact known origins pass, junk written by a third party is dropped rather than+ // cast through.+ const spec: SessionSpec = {sessionId,workspaceDir,modelEntry,apiKey,baseUrl,- systemPrompt: meta.system_prompt,- thinkingLevel,+ thinkingLevel: undefined,subagentDepth: 0,- vault: await loadAgentVault(this.state.root, this.state.projectId, this.state.agentId),- });+ ...(meta.source === "subagent" || meta.source === "schedule" ? { source: meta.source } : {}),+ };+ // The context follows the Trace. A context a completed compaction closed is opened here+ // for the first time — nothing was produced under any configuration yet — so it is+ // assembled from the current Agent State exactly as the compaction would have opened it,+ // and the rotation deferred to the first write records its meta at the new file's head.+ // An open context keeps the system prompt its file recorded — the history replayed into+ // it was produced under that request prefix — while its tools, Environment, vault and+ // run parameters can only come from the current Agent State: the Trace records no+ // executable configuration (tool definitions travel with every Request and are not part+ // of the history). The thinking level is a per-request parameter, not part of the+ // recorded prefix: it resolves from the pin and the config like on any other open.+ const context = await this.assembleContext(+ spec,+ resumed.contextClosed ? {} : { systemPrompt: meta.system_prompt },+ );+ const rt = this.buildRuntime(spec, context);// History is injected once into the freshly built context object as part of the lazy// bootstrap (setHistory is only used on resume); Session cumulative Token counts carry@@ -488,8 +648,8 @@ export class Agent {// history corruption rather than a regular runtime error. With the bootstrap being// lazy, that corruption now surfaces on the first run instead of at resume time —// the price of a resume that no longer blocks on MCP connects.- const bootstrap: typeof rt.bootstrap = async () => {- const r = await rt.bootstrap();+ const bootstrap: typeof rt.bootstrap = async (opts) => {+ const r = await rt.bootstrap(opts);if (resumed.history.length > 0) {try {r.llm.setHistory(resumed.history);@@ -500,7 +660,6 @@ export class Agent {);}}- r.llm.sessionTokens = resumed.sessionTokens;return r;};@@ -531,55 +690,8 @@ export class Agent {}}- return new Session({- // Invariants only — meta writes never contain a thinking level.- meta: {- session_id: sessionId,- provider: modelEntry.provider,- model_id: modelEntry.model_id,- model_context_window: modelEntry.context_window ?? "unknown",- system_prompt: meta.system_prompt,- agent_state: this.state.stateDir,- workspace: workspaceDir,- // The origin carries over from the original session_meta (a resumed scheduled/subagent- // Session stays marked). The on-disk value is untrusted: only the exact known origins- // pass; junk written by a third party is dropped rather than cast through.- ...(meta.source === "subagent" || meta.source === "schedule"- ? { source: meta.source }- : {}),- },+ return this.newSession(spec, context, rt, trace, {bootstrap,- cancelBootstrap: () => rt.environment.cancelMcpConnect(),- mcpServers: rt.environment.mcpServerNames(),- environment: rt.environment,- trace,- createLLM: rt.createLLM,- createBareLLM: rt.createBareLLM,- compaction: rt.compaction,- // Where an input image lands when it becomes a path line (see SessionConfig.imagesDir).- imagesDir: sessionScratchpadDir(- this.state.root,- this.state.projectId,- this.state.agentId,- sessionId,- ),- modelHasVision: modelEntry.vision !== false,- // Goal mode's control file lives in the session scratchpad; the path is fixed per- // Session, so it is wired here rather than passed per-run.- goalFilePath: goalFilePath(- this.state.root,- this.state.projectId,- this.state.agentId,- sessionId,- ),- ...(this.state.systemConfig.max_turns !== undefined- ? { maxTurns: this.state.systemConfig.max_turns }- : {}),- // Same policy snapshot as createSession: a resumed Session re-reads the current- // Project config, so a policy edit takes effect from the next load.- ...(this.projectConfig.command_policy !== undefined- ? { commandPolicy: this.projectConfig.command_policy }- : {}),// session_meta is already in the original Trace file, so it isn't rewritten; on the first write after a compaction-triggered rotation, the file is split first.metaAlreadyWritten: true,initialEngineState: {@@ -598,6 +710,47 @@ export class Agent {});}+ /**+ * Constructs the Session for `spec` running on `context` — the one assembly behind+ * createSession and resumeSession, so initialization and resumption cannot drift apart.+ * `extras` carries the resume-only fields (its history-injecting bootstrap wrapper, the+ * replay-derived engine state); spread last, so an override there wins.+ */+ private newSession(+ spec: SessionSpec,+ context: AssembledContext,+ rt: SessionRuntime,+ trace: Writer,+ extras: Partial<SessionConfig> = {},+ ): Session {+ const { root, projectId, agentId } = this.state;+ return new Session({+ meta: context.meta,+ bootstrap: rt.bootstrap,+ cancelBootstrap: () => rt.environment.cancelMcpConnect(),+ environment: rt.environment,+ trace,+ openNextContext: rt.openNextContext,++ createBareLLM: rt.createBareLLM,+ compaction: context.compaction,+ // 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,+ // Goal mode's control file lives in the session scratchpad; the path is fixed per+ // Session, so it is wired here rather than passed per-run.+ goalFilePath: goalFilePath(root, projectId, agentId, spec.sessionId),+ ...(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+ // edit applies at the Session's next rotation. Absent config means the factory rule+ // set, on. Tool permissions need no seam of their own: Session.toolPermission+ // answers from the Environment's toolset, which each rotation re-equips.+ commandPolicy: rt.commandPolicy,+ ...extras,+ });+ }+/** Id of the most recent Session under the current Agent (determined by the timestamp in session_id); returns null if there is no Session. */async latestSessionId(): Promise<string | null> {return latestTraceSessionId(@@ -606,51 +759,14 @@ export class Agent {}/**- * Assemble a Session's runtime components (shared by createSession and- * resumeSession): the child-Agent runner, Environment and tools, the LLM object- * and its post-compaction rebuild factory, and the compaction config.+ * Assembles a Session's runtime components (shared by createSession and resumeSession)+ * around the context it starts in — see {@link SessionRuntime} for what each part does.*/- private async buildRuntime(args: {- sessionId: string;- workspaceDir: string;- /** This Session's Model entry: the caller (createSession / resumeSession) has already validated it exists in the config. */- modelEntry: ModelEntry;- apiKey: string | undefined;- baseUrl: string | undefined;- systemPrompt: string;- /** The Session's effective thinking level: the caller resolves the explicit option against the Agent config. */- thinkingLevel: ThinkingLevelName | undefined;- subagentDepth: number;- vault: Record<string, string>;- }): Promise<{- environment: Environment;- /**- * Lazy session bootstrap, run by Session at the start of the first run: resolves the- * toolset (the Environment's first listTools connects any configured MCP Servers)- * and builds the session LLM from it; `mcp` carries the per-server connect outcomes- * for the mcp_connect_end event. Kept out of createSession on purpose — Session- * creation stays instant and the run streams connect status while this happens.- */- bootstrap: () => Promise<{- tools: ToolDefinition[];- llm: GenerativeModel;- mcp: McpServerConnectResult[];- }>;- createLLM: (sessionTokens: TokenCounts) => GenerativeModel;- createBareLLM: () => GenerativeModel;- compaction: CompactionSettings;- }> {- const {- sessionId,- workspaceDir,- modelEntry,- apiKey,- baseUrl,- systemPrompt,- thinkingLevel,- subagentDepth,- vault,- } = args;+ private buildRuntime(spec: SessionSpec, initial: AssembledContext): SessionRuntime {+ const { sessionId, workspaceDir, modelEntry, apiKey, baseUrl, subagentDepth } = spec;+ // The context the Session is running: the initial one, then whatever `openNextContext` last+ // assembled.+ let current = initial;// 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@@ -711,14 +827,17 @@ export class Agent {...(provider !== undefined ? { provider } : {}),};// An explicit spawn-time level (run_subagent's `thinking_level`) pins the child;- // otherwise the parent Session's effective thinking level (`thinkingLevel` in scope)- // is passed down, as a tri-state: `null` when the parent has none, so the child never- // falls back to its own Agent config (which would otherwise apply on a cross-agent- // spawn).+ // otherwise the parent Session's creation-time level, else the base its running+ // context opened with, is passed down as a tri-state: `null` when the parent has+ // none, so the child never falls back to its own Agent config (which would apply on+ // a cross-agent spawn). A mid-session `Session.thinkingLevel` assignment is engine+ // state and is not inherited — the spawn argument exists for explicit control.+ const parentLevel =+ spec.thinkingLevel === undefined ? current.thinkingLevel : spec.thinkingLevel;const childSession = await childAgent.createSession({workspaceDir,...childModel,- thinkingLevel: spawnThinkingLevel ?? thinkingLevel ?? null,+ thinkingLevel: spawnThinkingLevel ?? parentLevel ?? null,subagentDepth: subagentDepth + 1,source: "subagent",});@@ -767,7 +886,7 @@ export class Agent {metaSent = true;return withOrigin(childSession.metaMessage, hop);},- async *run({ messages, signal, approve, thinkingLevel: turnThinkingLevel }) {+ async *run({ messages, signal, approve }) {if (!metaSent) {metaSent = true;yield withOrigin(childSession.metaMessage, hop);@@ -798,7 +917,6 @@ export class Agent {const it = childSession.run(messages, {...(signal ? { signal } : {}),...(childApprove ? { approve: childApprove } : {}),- ...(turnThinkingLevel !== undefined ? { thinkingLevel: turnThinkingLevel } : {}),});for (;;) {const res = await it.next();@@ -814,41 +932,21 @@ export class Agent {steer(messages) {return childSession.steer(messages);},+ setThinkingLevel(level) {+ childSession.thinkingLevel = level;+ },dispose() {childSession.dispose();},};}- // 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).- const canSpawn = subagentDepth < MAX_SUBAGENT_DEPTH;- const baseToolConfig = buildToolConfig(this.state);- // Select tool entries by the session model's type (marked via forModel: vision- // models use read_image, text-only models use describe_image; entries without- // this marker are unaffected).- const modelVision = modelEntry.vision !== false;- let customTools = selectBuiltinToolsForModel(baseToolConfig.customTools, modelVision);- if (!canSpawn) {- customTools = customTools.filter(- (d) =>- d.name !== SUBAGENT_NAME &&- d.name !== INPUT_SUBAGENT_NAME &&- // Legacy entry still present in stale stored configs; the registry no longer- // assembles it, this just keeps the leaf filter symmetrical.- d.name !== "kill_subagent",- );- }- const toolConfig = { ...baseToolConfig, customTools };-// When the session model doesn't support images (vision=false): inject a vision- // model service for describe_image (forModel: "text-only", selected by the filter- // above) — images are described by the Project config's vision_model (a paired- // reference), and the tool returns text. Even when unconfigured or invalid, it is- // still injected (modelId=null); the tool then finishes with a failed explanation,- // and images are never allowed into that session's history.+ // model service for describe_image (forModel: "text-only", selected by the tool+ // filter in assembleContext) — images are described by the Project config's+ // vision_model (a paired reference), and the tool returns text. Even when unconfigured+ // or invalid, it is still injected (modelId=null); 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) {const visionRef = this.projectConfig.vision_model;@@ -882,16 +980,17 @@ export class Agent {}}- // Environment binds the Workspace and tool config; the toolset is resolved lazily by- // the bootstrap below (Session's first run), not here — its first listTools connects- // any configured MCP Servers, and that wait belongs on the run stream (bracketed by- // mcp_connect events), not inside createSession. Vault environment variables are- // injected into command subprocesses (shared by createSession and resumeSession; the- // caller reads the current agent_state/.vault.toml); a child Agent loads **its- // own** vault via createAgent rather than inheriting the parent's.+ // 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+ // openNextContext). The toolset is resolved lazily by the bootstrap below (Session's first+ // run), not here — its first listTools connects any configured MCP Servers, and that+ // wait belongs on the run stream (bracketed by mcp_connect events), not inside+ // createSession. Vault environment variables are injected into command subprocesses; a+ // child Agent loads **its own** vault via createAgent rather than inheriting the+ // parent's.const environment = new Environment({workspaceDir,- toolConfig,+ toolConfig: initial.toolConfig,// The Session's generic scratchpad root; Environment derives its truncated-tool-output// recovery directory from it.sessionScratchpadDir: sessionScratchpadDir(@@ -901,7 +1000,7 @@ export class Agent {sessionId,),services: { subagentRunner, ...(visionDescriber ? { visionDescriber } : {}) },- ...(Object.keys(vault).length > 0 ? { vault } : {}),+ ...(Object.keys(initial.vault).length > 0 ? { vault: initial.vault } : {}),...(this.proxyEnv ? { proxyEnv: this.proxyEnv } : {}),// The control-env policy is bound to THIS Session's coordinates here (sessionId is// final by now); the getter shape keeps it re-evaluated at every command spawn, so@@ -918,68 +1017,86 @@ export class Agent {: {}),});- // Configured output cap: the entry's per-model annotation wins over the Agent's- // system_config value; unset inherits the Agent value. This is a ceiling, not the- // literal wire value: GenerativeModel clamps each request's effective cap to what the- // 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.- const maxTokens = modelEntry.max_tokens ?? this.state.systemConfig.model?.max_tokens;-- // LLM constructor args are extracted into a shared object so they can be reused as-is- // when rebuilding a new LLM object after compaction (with a fresh model context) — the- // system prompt and tool definitions aren't part of the compacted history, so the new- // object keeps them unchanged. 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. The tool_call_id uniqueness registry is shared with the new LLM rebuilt- // from llmConfig after compaction: its uniqueness scope is the Session's whole render- // span, so same-named tool calls after compaction don't collide with earlier cards' ids.- //- // The config is completed by `bootstrap` once the toolset is known (listTools may- // connect MCP Servers); `createLLM` only ever runs after the first run's bootstrap- // (compaction happens mid-run), so the assertion cannot fire in a legal sequence.- let llmConfig: GenerativeModelConfig | null = null;- const bootstrap = async (): Promise<{- tools: ToolDefinition[];- llm: GenerativeModel;- mcp: McpServerConnectResult[];- }> => {- const tools = await environment.listTools();- llmConfig = {+ // The tool_call_id uniqueness registry is shared by every context's LLM object: its+ // 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+ // 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,- toolCallIds: new ToolCallIdAllocator(),+ toolCallIds,...(apiKey !== undefined ? { apiKey } : {}),...(baseUrl !== undefined ? { baseUrl } : {}),...(modelEntry.client_type !== undefined ? { clientType: modelEntry.client_type } : {}),tools,- systemPrompt,+ systemPrompt: context.systemPrompt,...(modelEntry.context_window !== undefined? { contextWindow: modelEntry.context_window }: {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- // Fast mode is a session-request annotation: it rides llmConfig (and therefore the- // post-compaction rebuild), 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.+ ...(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 } : {}),- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),- ...(this.state.systemConfig.model?.timeoutMs !== undefined- ? { requestTimeoutMs: this.state.systemConfig.model.timeoutMs }+ ...(context.thinkingLevel !== undefined ? { thinkingLevel: context.thinkingLevel } : {}),+ ...(context.requestTimeoutMs !== undefined+ ? { requestTimeoutMs: context.requestTimeoutMs }: {}),- };- return { tools, llm: new GenerativeModel(llmConfig), mcp: environment.mcpConnectResults() };- };- const createLLM = (sessionTokens: TokenCounts): GenerativeModel => {- if (llmConfig === null) {- throw new Error("createLLM called before the session bootstrap resolved the toolset");+ });++ // THE opening procedure — behind the first run's bootstrap and every post-compaction+ // openNextContext alike, so initialization and rotation cannot drift apart: connects+ // whatever MCP Servers are still pending on the Environment (publishing the connect+ // pair around the wait when there are any — at the first open that is every configured+ // server), resolves the toolset, publishes the toolset record, and builds the context's+ // LLM object. The caller's `emit` decides where the records go live (the Session's+ // first-run pump, or the engine's rotation pump).+ const openAssembled = async (+ context: AssembledContext,+ emit: OpenContextOptions["emit"],+ ): Promise<{ llm: GenerativeModel }> => {+ const pending = environment.pendingMcpServerNames();+ if (pending.length > 0) emit(mcpConnectBegin(pending));+ const tools = await environment.listTools();+ if (pending.length > 0) {+ emit(mcpConnectEnd(mcpConnectOutcome(environment.mcpConnectResults())));}- const next = new GenerativeModel(llmConfig);- // Carries over the Session's cumulative Token counts, so token_usage.session stays continuous across compaction.- next.sessionTokens = sessionTokens;- return next;+ emit(toolListReady(tools));+ return { llm: buildLLM(context, tools) };+ };++ // The first context's opener (see SessionRuntime.bootstrap).+ const bootstrap = async (opts: OpenContextOptions): Promise<{ llm: GenerativeModel }> =>+ openAssembled(current, opts.emit);++ // 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<OpenedContext> => {+ const next = await this.assembleContext(spec);+ 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,+ };};+// 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.@@ -1009,18 +1126,13 @@ export class Agent {// that throw here; the instance is discarded.createBareLLM();- // Compaction config: defaults are filled in here; an unknown mode falls back to summarize (the default).- const compactionConfig = this.state.systemConfig.compaction;- const compaction: CompactionSettings = {- maxContextLength: effectiveMaxContextLength(- compactionConfig?.max_context_length ?? DEFAULT_MAX_CONTEXT_LENGTH,- modelEntry.context_window,- ),- maxSessionTurns: compactionConfig?.max_session_turns ?? -1,- mode: compactionConfig?.mode === "discard" ? "discard" : "summarize",- prompt: compactionConfig?.prompt ?? DEFAULT_COMPACTION_PROMPT,- };+ return {+ environment,+ bootstrap,+ openNextContext,+ commandPolicy: () => current.commandPolicy,- return { environment, bootstrap, createLLM, createBareLLM, compaction };+ createBareLLM,+ };}}diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex 3077c215..87fa938d 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -35,6 +35,7 @@ import {assistantText,compactionBegin,compactionEnd,+ addTokenCounts,emptyTokenCounts,isCompleteModelMessage,isSessionMeta,@@ -82,6 +83,7 @@ import type {LLMOutcome,ThinkingLevelName,} from "../interfaces/index.js";+import { MergeQueue, pumpOpener } from "../internal/merge-queue.js";/** Trace sink: `write` a complete/event/meta message; `rotate` starts a new file (compaction splits files). */export interface TraceSink {@@ -104,6 +106,35 @@ export interface CompactionSettings {prompt: string;}+/**+ * A model context opened by {@link ContextEngineDeps.openNextContext} after a completed compaction:+ * the fresh LLM object, plus what the opener re-read for it — the `session_meta` the rotated+ * Trace file opens with (so that file's head describes the context it records) and the+ * per-context engine settings. Every optional field absent means "the previous context's+ * stays": an opener that could not re-read the Agent State returns the LLM alone.+ */+export interface OpenedContext {+ llm: LLMInterface;+ sessionMeta?: OmniMessage;+ /** Maximum LLM turns per Task in this context; -1 removes the cap. */+ maxTurns?: number;+ /** Compaction settings of this context (thresholds, mode, Prompt). */+ compaction?: CompactionSettings;+}++/** What {@link ContextEngineDeps.openNextContext} is called with. */+export interface OpenContextOptions {+ /**+ * Publishes a record the opener produces while opening — the `mcp_connect_begin` /+ * `mcp_connect_end` pair bracketing its MCP connect, and the `tool_list_ready` carrying the+ * context's toolset. The engine yields each one live, in call order, and writes them at the+ * head of the rotated Trace file right after the context's `session_meta`, so the new file+ * is self-contained; an opener that emits nothing leaves the previous context's toolset+ * record in place there.+ */+ emit: (msg: OmniMessage) => void;+}+/** Result of one compaction run: a StopReason terminal state (completed / aborted / retryable — abandoned, made up at the next trigger / fatal — needs a config change first); carries the summary message when summarize succeeds. */interface CompactionResult {status: StopReason;@@ -136,12 +167,6 @@ export interface RunOptions {signal?: AbortSignal;/** Per-tool approval callback; defaults to denying everything (conservative, to avoid accidental approval when unattended). */approve?: ApproveFn;- /**- * Thinking level for this run's LLM requests (a per-turn parameter): forwarded to every- * `streamGenerate` of this run — reconnect retries included; compaction requests keep the- * construction-time default (no override). Omitted = the LLM object's default.- */- thinkingLevel?: ThinkingLevelName;}/**@@ -163,7 +188,7 @@ export interface EngineInitialState {* after a restart — both have zero turns and are not the same message to a user.*/fromCompaction?: boolean;- /** Carried-over Session cumulative token counts (handed to the new object when compaction swaps it in). */+ /** Carried-over Session cumulative token counts (the engine resumes its own accumulator from them). */sessionTokens?: TokenCounts;/** Most recent token_usage's request.total (the context usage figure, keeps compaction threshold checks continuous). */lastRequestTotal?: number;@@ -178,7 +203,7 @@ export interface ContextEngineDeps {trace?: TraceSink;/** Engine initial state (derived by replaying Trace on Session resumption). */initialState?: EngineInitialState;- /** Maximum LLM turns for a single Task; -1 removes the cap. Omitted means -1 too — the agent-config default and the SDK fallback agree (unlimited). */+ /** Maximum LLM turns for a single Task in the first context; -1 removes the cap. Omitted means -1 too — the agent-config default and the SDK fallback agree (unlimited). A context `openNextContext` opens may bring its own. */maxTurns?: number;/*** Maximum automatic retries for LLM timeout/reconnect within a single run. Defaults@@ -215,22 +240,31 @@ export interface ContextEngineDeps {*/compactionMaxReconnects?: number;/**- * Creates a new LLM object after compaction (a fresh model context); the argument is the- * current Session cumulative token counts, for the new object to carry forward- * (token_usage.session stays continuous across compaction). Context compaction is- * unavailable if this is not provided.+ * Opens a fresh model context after compaction: the new LLM object, plus whatever the+ * opener re-read for the new context — its session_meta and its engine settings (see+ * {@link OpenedContext}) — and, through `opts.emit`, the records it produced while opening+ * (see {@link OpenContextOptions}). May rebuild the toolset and connect MCP servers, hence+ * possibly async and possibly slow; the engine yields the emitted records live meanwhile.+ * Session token continuity is the engine's own bookkeeping — it seeds the returned LLM's+ * `sessionTokens` itself. Context compaction is unavailable if this is not provided.*/- createLLM?: (sessionTokens: TokenCounts) => LLMInterface;- /** Context compaction settings; only takes effect if provided together with `createLLM`. */+ openNextContext?: (opts: OpenContextOptions) => OpenedContext | Promise<OpenedContext>;+ /** The first context's compaction settings; only takes effect if provided together with `openNextContext`. A context `openNextContext` opens may bring its own. */compaction?: CompactionSettings;- /** This Session's session_meta message; written at the start of the new Trace file after compaction splits it. */+ /**+ * The first context's session_meta message: written at the start of each Trace file a+ * compaction's rotation opens, until an `openNextContext` result brings the meta of the context+ * it opened — from then on that one is written, so every file's head describes its own+ * context.+ */sessionMeta?: OmniMessage;/**- * This Session's tool_list_ready event (the resolved toolset). Written once right after- * the first run's input (following `bootstrapRecords`), and rewritten right after- * sessionMeta on each post-compaction Trace file — every file's tool record stays- * self-contained. Held here alone; deliberately NOT part of `bootstrapRecords`, so the- * one message isn't carried twice.+ * The first context's tool_list_ready event (the resolved toolset). Written once right+ * after the first run's input (following `bootstrapRecords`), and again right after+ * sessionMeta on each Trace file a compaction's rotation opens — until an `openNextContext`+ * emits the records of the context it opened, which take its place there — so every+ * file's tool record stays self-contained. Held here alone; deliberately NOT part of+ * `bootstrapRecords`, so the one message isn't carried twice.*/toolList?: OmniMessage;/**@@ -353,54 +387,6 @@ interface TurnRetryState {consecutive: number;}-/**- * Merge queue: lets multiple concurrent producers (the LLM stream consumer + several tool- * executions) push OmniMessage entries; a single consumer (run's generator) pulls and- * yields them in push order. Finishes once all producers are done and the queue is drained.- * Docs: /docs/message-flow § "The merge point: MergeQueue".- */-class MergeQueue {- private items: OmniMessage[] = [];- private producers = 0;- private wake: (() => void) | null = null;-- /** Registers a producer. */- addProducer(): void {- this.producers += 1;- }-- /** Deregisters a producer (its stream has finished). */- removeProducer(): void {- this.producers -= 1;- this.signal();- }-- /** Pushes a message and wakes the consumer. */- push(msg: OmniMessage): void {- this.items.push(msg);- this.signal();- }-- private signal(): void {- if (this.wake) {- const w = this.wake;- this.wake = null;- w();- }- }-- /** Takes the next message; waits if empty but producers remain; returns null if empty and no producers remain. */- async next(): Promise<OmniMessage | null> {- for (;;) {- if (this.items.length > 0) return this.items.shift()!;- if (this.producers === 0) return null;- await new Promise<void>((resolve) => {- this.wake = resolve;- });- }- }-}-/*** Rewrites a dead goal's round input before carry-over re-sends it.*@@ -476,7 +462,9 @@ export function reconnectDelayMs(base: number, max: number, attempt: number): nu}export class ContextEngine {- private readonly maxTurns: number;+ /** Per-context settings: the first context's from the deps, then whatever each opened context brings (see `startNewContext`). */+ private maxTurns: number;+ private compaction: CompactionSettings | undefined;private readonly maxReconnects: number;private readonly maxTurnAttempts: number;private readonly reconnectBackoffMs: number;@@ -484,15 +472,37 @@ export class ContextEngine {private readonly compactionMaxReconnects: number;/** Interruption cleanup: content to resend generated when the previous run was aborted, held on the engine across runs. */private pendingCarryOver: OmniMessage[] = [];- /** Current LLM object; swapped for a new one created by `createLLM` after a successful compaction (a fresh model context). */+ /** Current LLM object; swapped for the one `openNextContext` returns after a successful compaction (a fresh model context). */private llm: LLMInterface;+ /**+ * session_meta of the current context, written at the head of the Trace file the deferred+ * rotation opens (see `write`): the first context's at construction, then whatever meta each+ * `openNextContext` result brings — a context that brought none keeps the previous one.+ */+ private contextMeta: OmniMessage | undefined;+ /**+ * The records written right after `contextMeta` at that rotation — the context's toolset+ * record and, when it connected MCP servers, the connect pair before it: the first context's+ * `toolList` at construction, then what each `openNextContext` emitted — a context that emitted+ * nothing keeps the previous records.+ */+ private contextRecords: OmniMessage[];/** Session cumulative turn count: counted per LLM Request that produces token_usage, across Tasks; reset to zero after compaction completes. */private sessionTurns = 0;/** Whether the current context was produced by a compaction (`startNewContext`); this flag becomes meaningless once a new completed turn occurs. */private fromCompaction = false;+ /**+ * The Session's current thinking level — the soft-limited runtime parameter as+ * engine-owned state: `setThinkingLevel` (fed by the `Session.thinkingLevel` setter) moves it+ * mid-context, and every subsequent turn request carries it as the per-request override.+ * Undefined = no pin: the LLM object's construction default (the context's opening base)+ * applies. Compaction requests ignore it and keep the context's base — their prefix must+ * stay byte-identical at the moment the context is largest.+ */+ private thinkingLevel?: ThinkingLevelName;/** Most recent token_usage's request.total, i.e. the current context usage figure. */private lastRequestTotal = 0;- /** Most recent token_usage's session cumulative counts, handed to the new LLM object when compaction swaps it in. */+ /** The Session-cumulative token series — engine-owned: accumulated from each token_usage's request counts and stamped onto the message before it is yielded or written (the LLM's lifetime is one context; the engine's is the Session). */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;@@ -553,7 +563,10 @@ export class ContextEngine {this.reconnectBackoffMs = deps.reconnectBackoffMs ?? 2000;this.reconnectBackoffMaxMs = deps.reconnectBackoffMaxMs ?? 30_000;this.compactionMaxReconnects = deps.compactionMaxReconnects ?? this.maxReconnects;+ this.compaction = deps.compaction;this.llm = deps.llm;+ this.contextMeta = deps.sessionMeta;+ this.contextRecords = deps.toolList ? [deps.toolList] : [];// Session resumption: apply the initial state derived from replay.const init = deps.initialState;if (init) {@@ -567,6 +580,11 @@ export class ContextEngine {}}+ /** Moves the Session's thinking level mid-context (see the `thinkingLevel` field); applies from the next turn request. */+ setThinkingLevel(level: ThinkingLevelName): void {+ this.thinkingLevel = level;+ }+/*** Runs a Task to completion, streaming out OmniMessage. `newMessages` is this call's* Prompt (only the newly added input, not the full history — history is maintained by the@@ -696,9 +714,6 @@ export class ContextEngine {const signal = opts?.signal;// Default approval policy: deny (conservative). CLI/Web will inject a real callback (interactive or permission-mode based).const approve: ApproveFn = opts?.approve ?? (async () => "deny");- // Per-turn thinking level: applies to each of this run's LLM requests (reconnects included);- // compaction requests are out of scope and keep the LLM default.- const thinkingLevel = opts?.thinkingLevel;// Merge the Task-boundary compaction summary (the new context's first input, merged with// this Prompt), the carry-over left over from the last interruption, and this call's new@@ -791,10 +806,7 @@ export class ContextEngine {// it decides retry/resend purely from `outcome`. The retry count so far is threaded// in so the turn's request_end can announce the planned backoff (retry_in_ms) —// the counter lives in this loop while the event is built inside the turn.- turn = yield* this.runTurn(attemptInput, approve, signal, thinkingLevel, {- attempts,- consecutive,- });+ turn = yield* this.runTurn(attemptInput, approve, signal, { attempts, consecutive });attempts += 1;// User interruption (the LLM stream was aborted, outcome=aborted, or `signal` fired@@ -872,7 +884,7 @@ export class ContextEngine {const midTask = turn.toolOutputs.length > 0;const compactionReason = this.compactionTrigger();if (compactionReason) {- const mode = this.deps.compaction!.mode;+ const mode = this.compaction!.mode;if (mode === "discard") {// Once discarded, the current Task can't continue: defer until the Task really// ends (mid-Task, or steering/notices still queued that must continue the loop).@@ -1008,21 +1020,21 @@ export class ContextEngine {*/compactability(): CompactAvailability {return compactAvailability({- configured: Boolean(this.deps.compaction && this.deps.createLLM),+ configured: Boolean(this.compaction && this.deps.openNextContext),sessionTurns: this.sessionTurns,fromCompaction: this.fromCompaction,});}async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {- if (!this.deps.compaction || !this.deps.createLLM) return;+ if (!this.compaction || !this.deps.openNextContext) return;// The current context has no completed LLM turns: nothing to compact, return immediately.// This also guards against two /compact calls in a row — the new context is empty right// after the previous compaction, so running again would overwrite the not-yet-consumed// pendingSummary with an "empty summary," permanently losing the only record of the prior// conversation.if (this.sessionTurns === 0) return;- if (this.deps.compaction.mode === "discard") {+ if (this.compaction.mode === "discard") {this.pendingCarryOver = this.pendingCarryOver.filter((m) => (m.payload as { type?: string }).type !== "tool_call_output",);@@ -1141,7 +1153,6 @@ export class ContextEngine {input: OmniMessage[],approve: ApproveFn,signal?: AbortSignal,- thinkingLevel?: ThinkingLevelName,/** This turn's retry bookkeeping from the caller's reconnect loop: lets request_end announce the NEXT attempt's planned backoff (and announce none once a budget is spent). */retry: TurnRetryState = { attempts: 0, consecutive: 0 },): AsyncGenerator<OmniMessage, TurnResult> {@@ -1173,10 +1184,11 @@ export class ContextEngine {await this.write(startEvt);// Iterate manually to capture the generator's **return value** (LLMOutcome); LLM// guarantees it never throws.+ const level = this.thinkingLevel;const gen = this.llm.streamGenerate({newMessages: input,...(signal ? { signal } : {}),- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),+ ...(level !== undefined ? { thinkingLevel: level } : {}),});for (;;) {const res = await gen.next();@@ -1218,12 +1230,14 @@ export class ContextEngine {}const msg = res.value;receivedContent = true;- queue.push(msg);- await this.write(msg);// token_usage means "this Request completed normally": record the context usage /- // Session cumulative counts, and increment the Session turn count (counted per LLM- // Request, across Tasks; used for compaction threshold checks).+ // Session cumulative counts — stamped onto the message BEFORE it is yielded or+ // 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;+ queue.push(msg);+ await this.write(msg);// Collect complete thinking/text segments (including partial segments finalized on// interruption), for carry-over flatten.if (@@ -1428,8 +1442,8 @@ export class ContextEngine {* Docs: /docs/agent-loop § "Compaction".*/private compactionTrigger(): CompactionReason | null {- const settings = this.deps.compaction;- if (!settings || !this.deps.createLLM) return null;+ const settings = this.compaction;+ if (!settings || !this.deps.openNextContext) return null;if (settings.maxContextLength > 0 && this.lastRequestTotal >= settings.maxContextLength) {return "context";}@@ -1439,13 +1453,23 @@ export class ContextEngine {return null;}- /** Records context usage and Session cumulative counts from a token_usage event; returns whether the message is a token_usage. */+ /**+ * Records context usage from a token_usage event and stamps the engine-authored session+ * series onto it; returns whether the message is a token_usage. The engine is the single+ * author of `token_usage.session`: the LLM reports per-request usage only (its lifetime is+ * one model context), and this method — on the turn path and the compaction path alike —+ * accumulates the request counts and overwrites the payload's `session` before the+ * message is yielded or written.+ */private observeTokenUsage(msg: OmniMessage): boolean {if (msg.type !== "event_msg") return false;const payload = msg.payload as Partial<TokenUsagePayload>;if (payload.type !== "token_usage") return false;- if (payload.request) this.lastRequestTotal = payload.request.total;- if (payload.session) this.lastSessionTokens = payload.session;+ if (payload.request) {+ this.lastRequestTotal = payload.request.total;+ this.lastSessionTokens = addTokenCounts(this.lastSessionTokens, payload.request);+ (payload as TokenUsagePayload).session = this.lastSessionTokens;+ }return true;}@@ -1458,7 +1482,7 @@ export class ContextEngine {private async *discardContext(reason: CompactionReason): AsyncGenerator<OmniMessage> {yield* this.emitCompactionBegin(reason, "discard");yield* this.emitCompactionEnd(reason, "discard", "completed");- await this.startNewContext();+ yield* this.startNewContext();}/**@@ -1494,7 +1518,7 @@ export class ContextEngine {pendingToolOutputs: OmniMessage[],signal?: AbortSignal,): AsyncGenerator<OmniMessage, CompactionResult> {- const settings = this.deps.compaction!;+ const settings = this.compaction!;yield* this.emitCompactionBegin(reason, "summarize");// Compaction request input: this turn's tool results (mid-Task) or leftover interruption@@ -1573,7 +1597,7 @@ export class ContextEngine {if (summaryText !== "" && attempt.toolCalls.length === 0) {const summary = userText(buildContextSummaryText(summaryText));yield* this.emitCompactionEnd(reason, "summarize", "completed", { attempt: attempts });- await this.startNewContext();+ yield* this.startNewContext();return { status: "completed", summary, committed };}// Not a summary — one more failed attempt, sharing the reconnect budget below. Tool@@ -1705,7 +1729,7 @@ export class ContextEngine {* dispatched — summarizeContext rejects such a response as not-a-summary and answers each* call with a synthesized failed output).* Token usage is counted into the Session- * cumulative totals (recorded via observeTokenUsage, for the new object to carry forward).+ * cumulative totals (accumulated and stamped onto every token_usage via observeTokenUsage).*/private async *runCompactionRequest(input: OmniMessage[],@@ -1779,8 +1803,9 @@ export class ContextEngine {};}const msg = res.value;- await this.write(msg);+ // Stamped with the Session series before the write, exactly like a turn's (runTurn).if (this.observeTokenUsage(msg)) usage = msg;+ await this.write(msg);// Streamed compaction progress (issue #290): the summary's own text rides the output// stream between the paired compaction events — partial_text fragments verbatim (all// three phases, so the server's live tail opens and closes its fragment and a join@@ -1815,15 +1840,37 @@ export class ContextEngine {}/**- * Opens a new model context after successful compaction: swaps in a new LLM object (carrying- * forward the Session cumulative token counts), resets the Session turn count and context- * usage counter. Trace **does not** split files immediately — that's deferred until the next- * message that needs writing, when it rotates and opens with a session_meta (see `write`),- * avoiding an empty file if no further messages follow the compaction.+ * Opens a new model context after successful compaction: swaps in the LLM object+ * `openNextContext` returns (seeding it with the Session cumulative token counts), adopts+ * whatever the opened context brings — its session_meta and toolset records for the rotated+ * Trace file's head, its engine settings — and resets the Session turn count and context+ * usage counter. The records the opener emits while opening (its MCP connect pair, its+ * 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.*/- private async startNewContext(): Promise<void> {+ private async *startNewContext(): AsyncGenerator<OmniMessage> {+ // The opener publishes records through a callback; a merge queue turns them into this+ // generator's live yields while the opener is still running.+ const { queue, result: opening } = pumpOpener((emit) => this.deps.openNextContext!({ emit }));+ const records: OmniMessage[] = [];+ for (;;) {+ const msg = await queue.next();+ if (msg === null) break;+ records.push(msg);+ yield msg;+ }+ // An opener that throws (the Agent State could not be assembled) propagates out of the+ // run with the engine untouched: the old context stays current and no rotation is+ // pending, so the next trigger compacts again from a consistent state.+ const opened = await opening;this.pendingTraceRotation = true;- this.llm = this.deps.createLLM!(this.lastSessionTokens);+ this.llm = opened.llm;+ if (opened.sessionMeta) this.contextMeta = opened.sessionMeta;+ if (records.length > 0) this.contextRecords = records;+ if (opened.maxTurns !== undefined) this.maxTurns = opened.maxTurns;+ if (opened.compaction) this.compaction = opened.compaction;this.sessionTurns = 0;this.lastRequestTotal = 0;// Lets compactability() distinguish "just compacted" from "hasn't chatted yet" — both have@@ -1993,7 +2040,8 @@ export class ContextEngine {/*** 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 session_meta.+ * 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).*/private async write(msg: OmniMessage): Promise<void> {if (!this.deps.trace) return;@@ -2001,8 +2049,8 @@ export class ContextEngine {this.pendingTraceRotation = false;try {if (this.deps.trace.rotate) await this.deps.trace.rotate();- if (this.deps.sessionMeta) await this.deps.trace.write(this.deps.sessionMeta);- if (this.deps.toolList) await this.deps.trace.write(this.deps.toolList);+ 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`);diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex c6e5f3c6..66aea3e7 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -37,9 +37,11 @@ import type {BackgroundTaskDoneEvent,EnvironmentConfig,EnvironmentInterface,+ EnvironmentServices,SubagentMessageOptions,SubagentMessageOutcome,SubagentRunner,+ ThinkingLevelName,ToolConfig,ToolDefinition,ToolExecutionRequest,@@ -137,32 +139,33 @@ function boundVisible(export class Environment implements EnvironmentInterface {private readonly workspaceDir: string;- private readonly toolConfig: ToolConfig;+ /** The running model context's tool configuration; replaced as a whole by `reconfigure`. */+ private toolConfig!: ToolConfig;/*** Truncated-output recovery, derived from the generic `sessionScratchpadDir` config; null for* standalone embedders without a Session directory (legacy truncation-only behavior).*/private readonly truncatedToolOutputArchive: TruncatedToolOutputArchive | null;- /** Assembled built-in tools: tool name -> BuiltinTool. Only tools supported by the registry and present in config. */- private readonly tools: Map<string, BuiltinTool>;- /** MCP Server bridge (null when config lists no servers): lazily connects and exposes `mcp__<server>__<tool>` entries. */- private readonly mcp: McpToolProvider | null;+ /** Assembled built-in tools of the running context: tool name -> BuiltinTool. Only tools supported by the registry and present in config. */+ private tools!: Map<string, BuiltinTool>;+ /** MCP Server bridge of the running context (null when its config lists no servers): lazily connects and exposes `mcp__<server>__<tool>` entries. */+ private mcp!: McpToolProvider | null;/** Long-running command session registry: constructed within this Environment and shared between exec_command / input_command. */private readonly commandSessions: CommandSessionManager;/** Background subagent session registry: constructed within this Environment and shared between run_subagent / input_subagent. */private readonly subagentSessions: SubagentSessionManager;/** The injected child-agent runner (null for embedders without one): the host resume fallback needs it outside any tool call. */private readonly subagentRunner: SubagentRunner | null;+ /** The runtime services every tool factory receives — Session-lifetime registries and sinks, so each context's toolset is assembled onto the same ones. */+ private readonly services: EnvironmentServices;constructor(config: EnvironmentConfig) {this.workspaceDir = config.workspaceDir;- this.toolConfig = config.toolConfig;this.truncatedToolOutputArchive = config.sessionScratchpadDir? new TruncatedToolOutputArchive({rootDir: path.join(config.sessionScratchpadDir, "truncated-tool-output"),}): null;- this.tools = new Map();// The background session registry is created alongside Environment (one per Session) and// injected into whichever tools need it; all sessions are finalized together on dispose.// The vault environment variables are injected into child processes by the command session@@ -174,7 +177,7 @@ export class Environment implements EnvironmentInterface {});this.subagentSessions = new SubagentSessionManager();this.subagentRunner = config.services?.subagentRunner ?? null;- const services = {+ this.services = {...config.services,commandSessions: this.commandSessions,subagentSessions: this.subagentSessions,@@ -184,22 +187,65 @@ export class Environment implements EnvironmentInterface {// Live-forwarded background-subagent messages, same single-consumer pattern.backgroundForward: (msg: OmniMessage) => this.emitBackgroundForward(msg),};- // Assemble the tools supported by config into BuiltinTool instances; unrecognized tool- // names are skipped (neither exposed to the LLM nor executable).- for (const def of config.toolConfig.customTools) {+ this.equip(config.toolConfig);+ this.mcp = this.newMcpProvider(config.toolConfig.mcpServers);+ }++ /**+ * Assembles the builtin half of a model context's toolset from its configuration: the+ * tools supported by the registry become BuiltinTool instances (unrecognized tool names+ * are skipped — neither exposed to the LLM nor executable). The MCP half is the provider:+ * `newMcpProvider` at construction, `reconfigure`'s reconciliation of the live one later.+ */+ private equip(toolConfig: ToolConfig): void {+ this.toolConfig = toolConfig;+ this.tools = new Map();+ for (const def of toolConfig.customTools) {const factory = BUILTIN_TOOL_FACTORIES[def.name];- if (factory) this.tools.set(def.name, factory(def, services));+ if (factory) this.tools.set(def.name, factory(def, this.services));}- // MCP Servers bridge in lazily: construction only records the config; connecting and- // tool discovery happen on the first listTools()/executeTool() (see McpToolProvider).- // The vault is deliberately not handed over: MCP server processes see only the SDK's- // safe env defaults plus the entry's own env.- this.mcp =- config.toolConfig.mcpServers.length > 0- ? new McpToolProvider(config.toolConfig.mcpServers, {- workspaceDir: config.workspaceDir,- })- : null;+ }++ /**+ * The MCP bridge for a server list (null without servers). MCP Servers bridge in lazily —+ * construction only records the config; connecting and tool discovery happen on the first+ * listTools()/executeTool() (see McpToolProvider). The vault is deliberately not handed to+ * it: server processes see only the SDK's safe env defaults plus the entry's own env.+ */+ private newMcpProvider(servers: ToolConfig["mcpServers"]): McpToolProvider | null {+ return servers.length > 0+ ? new McpToolProvider(servers, { workspaceDir: this.workspaceDir })+ : null;+ }++ /**+ * Re-equips the Environment for a new model context (the composition layer calls it when a+ * compaction opens one): the toolset — builtin entries and MCP Servers — and the vault are+ * replaced as a whole with what the Agent State says now. MCP connections are cached by+ * config: a server whose entry is unchanged keeps its live connection and discovered tools+ * (a Session that compacts every turn must not respawn its servers every turn), a removed+ * or changed one is closed, and a new or changed one connects lazily on the next+ * listTools() — `pendingMcpServerNames()` names those. The vault reaches every command+ * spawned from now on, while processes already running keep the environment they were+ * 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.+ */+ reconfigure(config: { toolConfig: ToolConfig; vault: Record<string, string> }): void {+ const servers = config.toolConfig.mcpServers;+ if (this.mcp && servers.length > 0) {+ this.mcp.reconfigure(servers);+ } else {+ this.mcp?.closeQuietly();+ this.mcp = this.newMcpProvider(servers);+ }+ this.equip(config.toolConfig);+ this.commandSessions.setVault(config.vault);+ }++ /** Configured MCP servers the next listTools() will contact — those without a live connection (never connected, failed, or changed by `reconfigure`); empty once every configured server is connected. Concrete-class surface for the composition layer's connect events. */+ pendingMcpServerNames(): string[] {+ return this.mcp?.pendingServerNames() ?? [];}/** Releases runtime resources held by Environment: finalizes all managed background sessions (command and subagent) and closes MCP clients (stdio server processes included). Idempotent. */@@ -290,8 +336,8 @@ export class Environment implements EnvironmentInterface {* on the same managed-session channel input_subagent uses, taking the same OmniMessage list;* the caller's messages carry no sender (human origin), unlike the model path's* "parent_agent" — and they reach both branches unchanged, so a steered round and a started- * round record the same author. `opts.thinkingLevel` pins only a round this call starts —- * steering cannot change the round already in flight.+ * round record the same author. The child runs every round at its own context's thinking+ * level (pinned on the child Session, or inherited at spawn) — a message never changes it.*/async sendToBackgroundSubagent(childSessionId: string,@@ -306,10 +352,7 @@ export class Environment implements EnvironmentInterface {try {// A host round is the user's own conversation with the child, not work the model// dispatched: it must not fire a background completion notice at the parent.- session.startRun(messages, {- ...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),- suppressDoneReport: true,- });+ session.startRun(messages, { suppressDoneReport: true });} catch {return "gone";}@@ -348,10 +391,7 @@ export class Environment implements EnvironmentInterface {this.attachHostTap(session);try {// Host-initiated like the started path: no completion notice at the parent.- session.startRun(messages, {- ...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),- suppressDoneReport: true,- });+ session.startRun(messages, { suppressDoneReport: true });} catch {return "gone";}@@ -366,6 +406,11 @@ export class Environment implements EnvironmentInterface {return session.abortRun();}+ /** Host-initiated pin of one live child session's thinking level (see EnvironmentInterface.setBackgroundSubagentThinkingLevel). */+ setBackgroundSubagentThinkingLevel(childSessionId: string, level: ThinkingLevelName): boolean {+ return this.subagentSessions.bySessionId(childSessionId)?.setThinkingLevel(level) ?? false;+ }+/** Attaches the single subagent run-state listener (see EnvironmentInterface.setSubagentStateListener). */setSubagentStateListener(listener: () => void): void {this.subagentSessions.setStateListener(() => {@@ -424,11 +469,6 @@ export class Environment implements EnvironmentInterface {return [...builtin, ...(await this.mcp.listTools())];}- /** Names of the validly configured MCP servers (config order; empty without MCP). Concrete-class surface for the composition layer's connect events — not part of EnvironmentInterface. */- mcpServerNames(): string[] {- return this.mcp?.serverNames() ?? [];- }-/** Per-server MCP connect outcomes, populated by the first listTools(); empty before it or without MCP. Feeds the mcp_connect_end event. */mcpConnectResults(): McpServerConnectResult[] {return this.mcp?.connectResults() ?? [];diff --git a/packages/core/src/environment/mcp/provider.ts b/packages/core/src/environment/mcp/provider.tsindex d970246e..0d445298 100644--- a/packages/core/src/environment/mcp/provider.ts+++ b/packages/core/src/environment/mcp/provider.ts@@ -6,13 +6,15 @@* flat tool namespace collision-free (builtin names never carry the prefix, and the server* name — validated to a safe alphabet — separates servers from each other).*- * Lifecycle: connection and tool discovery are lazy and happen exactly once per Environment- * (single-flight) — `Environment.listTools()` at Session assembly triggers it; all servers- * connect in parallel, each bounded by its `connectTimeoutMs`. A server that fails to- * connect (or an invalid config entry) is reported as a stderr warning and skipped — MCP- * problems never break Session creation, matching Environment's stance on unrecognized- * builtin tool names. Discovery is a session-lifetime snapshot: `tools/list_changed`- * notifications are ignored.+ * Lifecycle: connection and tool discovery are lazy and single-flight — `Environment.listTools()`+ * triggers a connect phase for every configured server that has no live connection; the+ * pending servers connect in parallel, each bounded by its `connectTimeoutMs`. A server that+ * fails to connect (or an invalid config entry) is reported as a stderr warning and skipped —+ * MCP problems never break Session creation, matching Environment's stance on unrecognized+ * builtin tool names. Discovery is a snapshot per connection: `tools/list_changed`+ * notifications are ignored. When a compaction opens the next model context, `reconfigure`+ * keeps every connection whose entry is unchanged (no respawn, no re-discovery), closes the+ * removed or changed ones, and leaves the new or changed ones pending for the next phase.** Execution: a call is bridged to `client.callTool` with the Environment-merged abort* signal passed through. The SDK's own per-request timeout is pushed out of the way@@ -85,11 +87,11 @@ export interface McpToolProviderOptions {warn?: (message: string) => void;}-/** One connected server: its client plus the tools discovered on it. */+/** One connected server: its client and the executable wrappers built from the usable tools discovered on it (registered into the toolset in config order, see `rebuildRegistry`). */interface McpConnection {server: ResolvedMCPServer;client: Client;- tools: Tool[];+ wrappers: BuiltinTool[];}function describeError(err: unknown): string {@@ -157,22 +159,23 @@ export function renderCallToolResult(result: CallToolResult): { text: string; im}export class McpToolProvider {- private readonly servers: ResolvedMCPServer[];- private readonly configWarnings: string[];+ /** The configured servers of the current model context (config order); replaced by `reconfigure`. */+ private servers: ResolvedMCPServer[];+ private configWarnings: string[];private readonly workspaceDir: string | undefined;private readonly warn: (message: string) => void;- /** Single-flight connect+discovery; resolved results live in the fields below. */+ /** Single-flight connect+discovery of the servers still pending; resolved results live in the fields below. */private ensurePromise: Promise<void> | null = null;/** Attempt token + abort handle of the in-flight connect; cancelConnect() invalidates the token so a cancelled attempt registers nothing. */private attempt = 0;private connectAbort: AbortController | null = null;- /** Successfully connected servers, kept for close(). */- private readonly connections: McpConnection[] = [];+ /** Live connections, kept across `reconfigure` while their entry is unchanged, and closed by close(). */+ private connections: McpConnection[] = [];/** Full tool name (`mcp__server__tool`) → executable wrapper. */private readonly byName = new Map<string, BuiltinTool>();/** LLM-facing definitions in stable server-config order. */private defs: ToolDefinition[] = [];- /** Per-server connect outcomes (config order), populated by the single-flight connect; feeds the mcp_connect_end event. */+ /** Per-server outcomes of the latest connect phase (config order) — every server on the first phase, only the pending ones after a `reconfigure`; feeds the mcp_connect_end event. */private results: McpServerConnectResult[] = [];private closed = false;@@ -184,22 +187,54 @@ export class McpToolProvider {this.warn = options?.warn ?? ((message) => process.stderr.write(`[penguin] ${message}\n`));}- /** Connects (once) and returns the LLM-facing definitions of every discovered MCP tool. */+ /** Connects the pending servers (once per phase) and returns the LLM-facing definitions of every discovered MCP tool. */async listTools(): Promise<ToolDefinition[]> {await this.ensure();return this.defs;}- /** Names of the (validly configured) servers this provider will contact, in config order. */- serverNames(): string[] {- return this.servers.map((s) => s.name);+ /**+ * Configured servers without a live connection — never connected yet, failed on their+ * last phase, or changed by `reconfigure`: the ones the next listTools() will contact.+ * Empty once every configured server is connected.+ */+ pendingServerNames(): string[] {+ const connected = new Set(this.connections.map((c) => c.server.name));+ return this.servers.filter((s) => !connected.has(s.name)).map((s) => s.name);}- /** Per-server connect outcomes; empty before the first listTools()/resolveTool() completed. */+ /** Per-server outcomes of the latest connect phase; empty before it completed, and after a phase that had nothing to connect. */connectResults(): McpServerConnectResult[] {return this.results;}+ /**+ * Replaces the server list for a new model context, keeping what it can: a server whose+ * resolved config is unchanged keeps its live connection and discovered tools — no+ * respawn, no re-discovery — a removed or changed server is closed, and a new or changed+ * one connects lazily on the next listTools(), exactly like a first connect, bounded by+ * its own connectTimeoutMs. A server that failed last time is pending again, so a rotation+ * retries it. Not for use while a connect is in flight (the composition layer calls it+ * between turns, after the first run's connect completed).+ */+ reconfigure(entries: MCPServerConfig[]): void {+ const resolved = resolveMCPServers(entries);+ this.servers = resolved.servers;+ this.configWarnings = resolved.warnings;+ // The resolved server is plain data produced by one resolver, so its JSON is a stable+ // identity for "the same entry".+ const wanted = new Map(this.servers.map((s) => [s.name, JSON.stringify(s)]));+ const kept: McpConnection[] = [];+ for (const conn of this.connections) {+ if (wanted.get(conn.server.name) === JSON.stringify(conn.server)) kept.push(conn);+ else void conn.client.close().catch(() => {});+ }+ this.connections = kept;+ this.ensurePromise = null;+ this.results = [];+ this.rebuildRegistry();+ }+/*** Resolves an executable wrapper by full tool name; connects first if discovery has not* run yet (executeTool can arrive without a prior listTools on embedder-driven runs).@@ -248,22 +283,23 @@ export class McpToolProvider {this.connectAbort = null;this.ensurePromise = null;this.results = [];- this.byName.clear();- this.defs = [];- const open = this.connections.splice(0);- for (const conn of open) void conn.client.close().catch(() => {});+ // Connections the cancelled attempt established are closed by connectAll itself once it+ // settles (it sees the stale attempt token); the ones kept from an earlier phase stay.+ this.rebuildRegistry();}private async connectAll(): Promise<void> {for (const warning of this.configWarnings) this.warn(warning);+ const connected = new Set(this.connections.map((c) => c.server.name));+ const pending = this.servers.filter((s) => !connected.has(s.name));const attempt = ++this.attempt;const ac = new AbortController();this.connectAbort = ac;- // Connect in parallel, then register in config order so tool listing order is stable.- // Each server's outcome (status + wall time, feeding the mcp_connect_end event) is- // recorded either way; a failure also keeps the existing warning behavior.+ // Connect the pending servers in parallel, then register in config order so tool listing+ // order is stable. Each server's outcome (status + wall time, feeding the mcp_connect_end+ // event) is recorded either way; a failure also keeps the existing warning behavior.const settled = await Promise.all(- this.servers.map(+ pending.map(async (server): Promise<{ conn: McpConnection | null; result: McpServerConnectResult }> => {const startedAt = performance.now();const durationMs = (): number => Math.round(performance.now() - startedAt);@@ -276,7 +312,9 @@ export class McpToolProvider {transport: server.transport.kind,status: "completed",duration_ms: durationMs(),- tools: conn.tools.length,+ // What actually joined the toolset (duplicates and LLM-unusable names are+ // skipped), keeping the count consistent with tool_list_ready.+ tools: conn.wrappers.length,},};} catch (err) {@@ -317,13 +355,28 @@ export class McpToolProvider {continue;}this.connections.push(conn);- let registered = 0;- for (const tool of conn.tools) {- if (this.register(conn, tool)) registered += 1;+ }+ this.rebuildRegistry();+ }++ /** Rebuilds the name → wrapper map and the definition list from the live connections, in config order (kept connections keep their place; a closed server's tools drop out). */+ private rebuildRegistry(): void {+ this.byName.clear();+ this.defs = [];+ const byServer = new Map(this.connections.map((c) => [c.server.name, c]));+ for (const server of this.servers) {+ const conn = byServer.get(server.name);+ if (!conn) continue;+ for (const wrapper of conn.wrappers) {+ this.byName.set(wrapper.name, wrapper);+ this.defs.push({+ name: wrapper.name,+ description: wrapper.definition.description,+ ...(wrapper.definition.parameters !== undefined+ ? { parameters: wrapper.definition.parameters }+ : {}),+ });}- // The reported count is what actually joined the toolset (duplicates and- // LLM-unusable names are skipped), keeping it consistent with tool_list_ready.- result.tools = registered;}}@@ -384,7 +437,15 @@ export class McpToolProvider {timeout: remainingMs,...(signal ? { signal } : {}),});- return { server, client, tools: listed.tools };+ // Wrappers are built once, here — the usable-name check and its warning fire at+ // connect time, not at every registry rebuild a later context triggers.+ const wrappers: BuiltinTool[] = [];+ const seen = new Set<string>();+ for (const tool of listed.tools) {+ const wrapper = this.wrap(server, client, tool, seen);+ if (wrapper) wrappers.push(wrapper);+ }+ return { server, client, wrappers };} catch (err) {await client.close().catch(() => {});await transport.close().catch(() => {});@@ -393,42 +454,46 @@ export class McpToolProvider {}}- /** Returns whether the tool joined the toolset (skips are warned, never thrown). */- private register(conn: McpConnection, tool: Tool): boolean {- const name = mcpToolName(conn.server.name, tool.name);+ /** Builds the executable wrapper of one discovered tool; null when it cannot join the toolset (skips are warned, never thrown). `seen` holds the names already taken on this server. */+ private wrap(+ server: ResolvedMCPServer,+ client: Client,+ tool: Tool,+ seen: Set<string>,+ ): BuiltinTool | null {+ const name = mcpToolName(server.name, tool.name);if (!LLM_TOOL_NAME_PATTERN.test(name)) {this.warn(- `MCP server "${conn.server.name}" tool "${tool.name}" skipped: the prefixed name ` ++ `MCP server "${server.name}" tool "${tool.name}" skipped: the prefixed name ` +`is not usable as an LLM tool name (allowed: letters, digits, _ and -, ≤128 chars total).`,);- return false;+ return null;}- if (this.byName.has(name)) {- this.warn(- `MCP server "${conn.server.name}" listed tool "${tool.name}" twice; keeping the first.`,- );- return false;+ if (seen.has(name)) {+ this.warn(`MCP server "${server.name}" listed tool "${tool.name}" twice; keeping the first.`);+ return null;}+ seen.add(name);const description =- tool.description ?? tool.title ?? `MCP tool "${tool.name}" on server "${conn.server.name}".`;+ tool.description ?? tool.title ?? `MCP tool "${tool.name}" on server "${server.name}".`;// The entry's own permission wins over the annotation for every tool of the server;// without one, readOnlyHint is an untrusted hint and only an explicit true relaxes to "r".const permission: ToolPermission =- conn.server.permission ?? (tool.annotations?.readOnlyHint === true ? "r" : "rw");- const wrapper: BuiltinTool = {+ server.permission ?? (tool.annotations?.readOnlyHint === true ? "r" : "rw");+ return {name,definition: {name,description,parameters: tool.inputSchema as Record<string, unknown>,permission,- ...(conn.server.timeoutMs !== undefined ? { timeoutMs: conn.server.timeoutMs } : {}),- ...(conn.server.maxOutputLength !== undefined- ? { maxOutputLength: conn.server.maxOutputLength }+ ...(server.timeoutMs !== undefined ? { timeoutMs: server.timeoutMs } : {}),+ ...(server.maxOutputLength !== undefined+ ? { maxOutputLength: server.maxOutputLength }: {}),},execute: async function* (args, ctx): AsyncGenerator<OmniMessage, ToolResult> {- const result = await conn.client.callTool(+ const result = await client.callTool({ name: tool.name, arguments: args },{timeout: MAX_SDK_TIMEOUT_MS,@@ -454,14 +519,5 @@ export class McpToolProvider {};},};- this.byName.set(name, wrapper);- this.defs.push({- name,- description,- ...(wrapper.definition.parameters !== undefined- ? { parameters: wrapper.definition.parameters }- : {}),- });- return true;}}diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.tsindex 3404cc3f..c5fe805f 100644--- a/packages/core/src/environment/tools/command/session-manager.ts+++ b/packages/core/src/environment/tools/command/session-manager.ts@@ -193,8 +193,8 @@ export class CommandSessionManager {maxTasks: MAX_SESSIONS,});- /** Agent vault environment variables: injected into the child process on every spawn (values never enter the model context, only the environment). */- private readonly vault: Record<string, string>;+ /** Agent vault environment variables: injected into the child process on every spawn (values never enter the model context, only the environment). Replaced per model context, see `setVault`. */+ private vault: Record<string, string>;/*** Proxy policy for the child environment (see {@link ProxyEnvPolicy}: strip the proxy* variables, inject an explicit proxy over the inherited ones, or null = pass@@ -221,6 +221,16 @@ export class CommandSessionManager {this.controlEnv = opts?.controlEnv;}+ /**+ * Replaces the vault injected into commands spawned from now on — a new model context+ * re-reads the Agent's vault (see Environment.reconfigure). Sessions already running keep+ * the environment they were spawned with: a process environment cannot be changed after+ * the fact.+ */+ setVault(vault: Record<string, string>): void {+ this.vault = vault;+ }+/** Starts a command, returning an **unregistered** session (no process_id yet). */spawn(opts: { cmd: string; cwd: string }): ManagedSession {if (this.registry.isDisposed) {diff --git a/packages/core/src/environment/tools/subagent/session.ts b/packages/core/src/environment/tools/subagent/session.tsindex 78d5dd0d..192e545a 100644--- a/packages/core/src/environment/tools/subagent/session.ts+++ b/packages/core/src/environment/tools/subagent/session.ts@@ -156,16 +156,12 @@ export class ManagedSubagentSession {* Starts a new round of the task on the child Session (async pump, doesn't block the caller).* `messages` is the round's input in the same OmniMessage shape `steer` takes — the caller* owns their `sender`, so a model dispatch and a human's panel message stay distinguishable- * in the child's Trace. `opts.thinkingLevel` pins this round only (a host follow-up's per-turn picker);- * `opts.suppressDoneReport` keeps the settle watcher quiet for this round — a HOST-initiated+ * in the child's Trace. `opts.suppressDoneReport` keeps the settle watcher quiet for this round — a HOST-initiated* round is the user's own conversation with the child, not work the model dispatched, so the* parent must not receive a completion notice for it. Throws if already disposed or still* running (converted to an explanatory output by the caller).*/- startRun(- messages: OmniMessage[],- opts?: { thinkingLevel?: ThinkingLevelName; suppressDoneReport?: boolean },- ): void {+ startRun(messages: OmniMessage[], opts?: { suppressDoneReport?: boolean }): void {if (this.killed) throw new Error("subagent session disposed");if (this.isRunning) throw new Error("subagent is still running");this.isRunning = true;@@ -173,7 +169,7 @@ export class ManagedSubagentSession {this.reportCurrentRun = opts?.suppressDoneReport !== true;this.runCtrl = new AbortController();this.notifyState();- void this.pump(messages, this.runCtrl, opts?.thinkingLevel);+ void this.pump(messages, this.runCtrl);}/**@@ -202,6 +198,13 @@ export class ManagedSubagentSession {return true;}+ /** Pins the child's thinking level (see SubagentHandle.setThinkingLevel); false when the session is dead or the handle predates the pin. */+ setThinkingLevel(level: ThinkingLevelName): boolean {+ if (this.killed || !this.handle.setThinkingLevel) return false;+ this.handle.setThinkingLevel(level);+ return true;+ }+// Run-state observer (host liveness): fired on every isRunning flip — startRun and the// pump's settle. The event carries no payload; observers re-read `running`.private stateListener: (() => void) | null = null;@@ -349,11 +352,7 @@ export class ManagedSubagentSession {// -------------------------------------------------------------------------/** Drives one round of `handle.run`: buffers messages and text, settling the terminal state when it ends. */- private async pump(- messages: OmniMessage[],- runCtrl: AbortController,- thinkingLevel?: ThinkingLevelName,- ): Promise<void> {+ private async pump(messages: OmniMessage[], runCtrl: AbortController): Promise<void> {let wroteAny = false;// Whether the round was cut off early (a user abort, a terminal LLM failure, a// mid-task compaction failure): read from the run generator's return value — the@@ -367,7 +366,6 @@ export class ManagedSubagentSession {messages,signal: AbortSignal.any([this.abortCtrl.signal, runCtrl.signal]),approve: this.childApprove,- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),});for (;;) {const res = await it.next();diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 99e73863..5bb1f302 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -41,6 +41,8 @@ export type {CompactionSettings,ContextEngineDeps,EngineInitialState,+ OpenContextOptions,+ OpenedContext,RunOptions,TraceSink,} from "./engine/context-engine.js";diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex 91d9f04a..bb37863b 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -121,8 +121,6 @@ export interface SubagentHandle {signal?: AbortSignal;/** The parent Agent's approval callback; forwarded to the child Session to inherit the parent's approval mode. */approve?: ApproveFn;- /** Per-turn thinking level for THIS round only (a host follow-up's picker); omitted keeps the child Session's own level. */- thinkingLevel?: ThinkingLevelName;}): AsyncGenerator<OmniMessage, RunCutoff | null>;/*** Queues a steering message for the child Session's running Task (the same mechanism as a@@ -132,10 +130,22 @@ export interface SubagentHandle {* handle without it simply reports "not steerable".*/steer?(messages: OmniMessage[]): boolean;+ /** Pins the child Session's thinking level (`Session.thinkingLevel`: applied from its next LLM request) — a host panel's pick on a live child. Optional, like `steer`. */+ setThinkingLevel?(level: ThinkingLevelName): void;/** Releases runtime resources held by the child Session (e.g. its managed command sessions). Idempotent. */dispose(): void;}+/** Every thinking level name, the `ThinkingLevelName` vocabulary as a runtime list (validating a wire value — the server's PATCH and Agent-config routes). */+export const THINKING_LEVEL_NAMES: readonly ThinkingLevelName[] = [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+];+/*** Thinking levels the model may request for a spawned child Session (`run_subagent`'s* `thinking_level` argument): the selectable tiers only — never `"none"`, mirroring the@@ -380,8 +390,6 @@ export type SubagentMessageOutcome = "steered" | "started" | "resumed" | "busy"/** Options of a host-initiated subagent message (see EnvironmentInterface.sendToBackgroundSubagent). */export interface SubagentMessageOptions {- /** Per-turn thinking level for a follow-up/resumed round; steering an already-running round cannot change that round's level. */- thinkingLevel?: ThinkingLevelName;/*** Enables the resume fallback when no live child bears the session id: the child Session* is revived (its own history, model and Workspace — `resumeSession` semantics) and@@ -440,6 +448,13 @@ export interface EnvironmentInterface {* never destroyed. False when the child is unknown or idle. Optional.*/abortBackgroundSubagentRun?(childSessionId: string): boolean;+ /**+ * Host-initiated pin of one live child session's thinking level (the child-session+ * equivalent of assigning `Session.thinkingLevel`: applied from the child's next LLM+ * request). False when the child is not live — a released child is revived through the+ * host's loader, which restores the pin it stores. Optional.+ */+ setBackgroundSubagentThinkingLevel?(childSessionId: string, level: ThinkingLevelName): boolean;/*** Attaches the single listener for subagent run-state changes (a round starting or* settling on any live child). The host re-reads `listBackgroundSubagents` on each ping —diff --git a/packages/core/src/internal/command-policy.ts b/packages/core/src/internal/command-policy.tsindex 848b5c38..ca30cbaa 100644--- a/packages/core/src/internal/command-policy.ts+++ b/packages/core/src/internal/command-policy.ts@@ -16,8 +16,11 @@** The config lives in `.project_config.toml` (`[command_policy]`) — Project-owned on purpose:* security policy belongs to the Project, not to Agent State the Agent itself can rewrite.- * The Session receives a parsed snapshot at creation, so the running Session's policy cannot- * be edited from inside the Session.+ * The Session receives a policy SOURCE — a getter answering with the policy of the model+ * context it is running, read from disk once when each context opens: command policy is+ * strict-tier, so an edit applies when the next context opens (rotation), never mid-file.+ * The getter is still consulted per decision, which is what hands the tool calls after a+ * mid-run rotation the new context's policy without any reload machinery.** The rules are **data, not code**: every rule (name / pattern / description / enabled) is* project-editable, and the factory set (state/command-policy-defaults.ts) is *seeded* into@@ -147,16 +150,27 @@ export function vetoForToolCall(return evaluateCommandPolicy(text, policy);}+/** Where the policy comes from at decision time: a getter answering with the running context's policy (see SessionConfig.commandPolicy) — consulted per approval, so a mid-run rotation swaps what later calls see. */+export type CommandPolicySource = () => CommandPolicyConfig | undefined;+/*** Wraps an approval callback with the policy: a vetoed call answers `"forbidden"` here and* `approve` is never reached, so no approval mode — and no Human implementation — can let* it through. `"forbidden"` is the decision's own third value: the engine renders it as* the fixed aborted line "Tool call denied by policy." (a person's denial reads "by* user."), and the `approval_decision` event carries it — the model's text and the Trace- * both name the decider.+ * both name the decider. The `source` getter is consulted at every decision (no source, or+ * a source yielding nothing, applies the factory rule set); a source that cannot be read+ * fails toward the factory rules rather than waving the call through.*/-export function withCommandPolicy(approve: ApproveFn, policy?: CommandPolicyConfig): ApproveFn {+export function withCommandPolicy(approve: ApproveFn, source?: CommandPolicySource): ApproveFn {return async (toolCall) => {+ let policy: CommandPolicyConfig | undefined;+ try {+ policy = source?.();+ } catch {+ policy = undefined;+ }const veto = vetoForToolCall(toolCall.payload.name, toolCall.payload.arguments, policy);if (veto) return "forbidden";return approve(toolCall);diff --git a/packages/core/src/internal/merge-queue.ts b/packages/core/src/internal/merge-queue.tsnew file mode 100644index 00000000..20cd29c5--- /dev/null+++ b/packages/core/src/internal/merge-queue.ts@@ -0,0 +1,78 @@+import type { OmniMessage } from "../omnimessage/index.js";++/**+ * Merge queue: lets multiple concurrent producers push OmniMessage entries; a single+ * consumer pulls and yields them in push order. Finishes once all producers are done and+ * the queue is drained. It is the engine's merge point for a turn's concurrent streams+ * (the LLM consumer plus N tool executions — see /docs/message-flow § "The merge point:+ * MergeQueue"), and the same pump turns a context opener's published records into live+ * yields (see `pumpOpener`): the engine's post-compaction `openNextContext` and the Session's+ * first-run bootstrap deliver through one mechanism.+ */+export class MergeQueue {+ private items: OmniMessage[] = [];+ private producers = 0;+ private wake: (() => void) | null = null;++ /** Registers a producer. */+ addProducer(): void {+ this.producers += 1;+ }++ /** Deregisters a producer (its stream has finished). */+ removeProducer(): void {+ this.producers -= 1;+ this.signal();+ }++ /** Pushes a message and wakes the consumer. */+ push(msg: OmniMessage): void {+ this.items.push(msg);+ this.signal();+ }++ private signal(): void {+ if (this.wake) {+ const w = this.wake;+ this.wake = null;+ w();+ }+ }++ /** Takes the next message; waits if empty but producers remain; returns null if empty and no producers remain. */+ async next(): Promise<OmniMessage | null> {+ for (;;) {+ if (this.items.length > 0) return this.items.shift()!;+ if (this.producers === 0) return null;+ await new Promise<void>((resolve) => {+ this.wake = resolve;+ });+ }+ }+}++/**+ * Runs a context opener — a procedure that publishes records through an `emit` callback while+ * it works — behind a MergeQueue the caller drains: each record becomes a queue item the+ * moment it is published, the queue closes when the opener settles, and the opener's outcome+ * is `result`. A rejection is deferred to that promise (never reported as unhandled while the+ * queue is still being drained), so the caller pumps the queue to its end, then awaits+ * `result`. The engine's post-compaction open and the Session's first-run bootstrap are the+ * two pumps.+ */+export function pumpOpener<T>(open: (emit: (msg: OmniMessage) => void) => T | Promise<T>): {+ queue: MergeQueue;+ result: Promise<T>;+} {+ const queue = new MergeQueue();+ queue.addProducer();+ const result = (async () => {+ try {+ return await open((msg) => queue.push(msg));+ } finally {+ queue.removeProducer();+ }+ })();+ void result.catch(() => {});+ return { queue, result };+}diff --git a/packages/core/src/internal/session-support.ts b/packages/core/src/internal/session-support.tsindex 1716e4a5..cf7b0835 100644--- a/packages/core/src/internal/session-support.ts+++ b/packages/core/src/internal/session-support.ts@@ -14,11 +14,33 @@ import type { SessionEnvironmentValues } from "../state/agent-state.js";import { modelVisiblePath } from "./model-visible-path.js";import { workspacesDir } from "../state/index.js";import { attachedImageLine, isWholeOriginBlock, userText } from "../omnimessage/index.js";-import type { OmniMessage } from "../omnimessage/index.js";+import type { McpServerConnectResult, OmniMessage } from "../omnimessage/index.js";/** Session runtime environment fields: the placeholder substitution values for `assembleSystemPrompt`; producer and consumer share the same type. */export type SessionEnvironment = SessionEnvironmentValues;+/**+ * The `mcp_connect_end` arguments for a finished connect phase, from the per-server outcomes:+ * one failed server makes the phase `fatal`, with the unavailable names in the message. Shared+ * by the two places a connect phase is bracketed — the Session's first-run bootstrap and the+ * context a compaction opens — so both ends read the same.+ */+export function mcpConnectOutcome(results: McpServerConnectResult[]): {+ status: "completed" | "fatal";+ results: McpServerConnectResult[];+ errorCode?: "connect_failed";+ errorMessage?: string;+} {+ const failed = results.filter((r) => r.status !== "completed").map((r) => r.server);+ return {+ status: failed.length > 0 ? "fatal" : "completed",+ results,+ ...(failed.length > 0+ ? { errorCode: "connect_failed" as const, errorMessage: `unavailable: ${failed.join(", ")}` }+ : {}),+ };+}+/** Generate a Session id of the form `session-YYYY-MM-DD-HH-mm-ss-<8-hex>` (local timezone, zero-padded: 4-digit year, 2 digits for the rest; hex from randomUUID). */export function formatSessionId(date: Date = new Date()): string {const pad = (n: number) => n.toString().padStart(2, "0");diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.tsindex 881380fd..de1df1a8 100644--- a/packages/core/src/llm/generative-model.ts+++ b/packages/core/src/llm/generative-model.ts@@ -973,9 +973,6 @@ export class GenerativeModel implements LLMInterface {/** Last hard-clamped cap already warned about on stderr (dedupe: retries reuse the same estimate and would repeat the identical line). */private lastWarnedCap: number | undefined;- /** Cumulative session tokens. */- sessionTokens: TokenCounts = emptyTokenCounts();-constructor(config: GenerativeModelConfig) {// Omit apiKey / baseUrl when undefined, letting AgentHub read them from environment// variables. clientType determines which protocol to speak (`openai-chat` means OpenAI@@ -1301,8 +1298,10 @@ export class GenerativeModel implements LLMInterface {// (see effectiveMaxTokens). Only a completed request updates it: an interrupted or// failed attempt was never committed, so the context did not grow.this.lastRequestTotal = requestTokens.total;- this.sessionTokens = addTokenCounts(this.sessionTokens, requestTokens);- yield tokenUsage(this.sessionTokens, requestTokens);+ // The session series is not this object's business (its lifetime is one model context):+ // the engine accumulates and stamps token_usage.session on every message it forwards.+ // The request counts stand in for consumers running a GenerativeModel without an engine.+ yield tokenUsage(requestTokens, requestTokens);return { status: "completed" };}diff --git a/packages/core/src/omnimessage/builders.ts b/packages/core/src/omnimessage/builders.tsindex 8729ae21..ef136d49 100644--- a/packages/core/src/omnimessage/builders.ts+++ b/packages/core/src/omnimessage/builders.ts@@ -377,7 +377,7 @@ export function toolListReady(tools: ToolDefinition[]): OmniMessage<ToolListReadreturn event({ type: "tool_list_ready", tools });}-/** mcp_connect begin event: brackets open on the first run's MCP connect + discovery phase (emitted only when servers are configured). */+/** mcp_connect begin event: brackets open on an MCP connect + discovery phase — the first run's, or a new context's after compaction (emitted only when servers are configured). */export function mcpConnectBegin(servers: string[]): OmniMessage<McpConnectBeginPayload> {return event({ type: "mcp_connect_begin", servers });}diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.tsindex 09bc7cb6..48392cb9 100644--- a/packages/core/src/omnimessage/types.ts+++ b/packages/core/src/omnimessage/types.ts@@ -100,10 +100,15 @@ export interface ToolDefinition {}/**- * Session metadata. Holds **per-session invariants only** — values fixed for the Session's- * lifetime (model reference, assembled system prompt, tool schemas, paths, origin). Per-turn- * parameters (e.g. the thinking level, passed with each run) never belong here; a- * `thinking_level` field still present in a legacy Trace's meta is ignored on resume.+ * 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).*/export interface SessionMetaPayload {session_id: string;@@ -112,8 +117,11 @@ export interface SessionMetaPayload {/** The session model's upstream model_id (the request id sent to AgentHub; paired with `provider`). */model_id: string;model_context_window: number | string;- /** The system prompt actually used by this Session (the assembled result with environment placeholders already substituted). */+ /** The system prompt this context runs with (the assembled result, placeholders already substituted). */system_prompt: string;+ // The thinking level is deliberately NOT here: it is a per-request parameter (the Session+ // pin, else the Agent config default read at context open), not part of the recorded+ // prefix. Legacy Traces may carry a `thinking_level` field; it is displayed, never read.// The tool definitions were embedded here (`tools`) before the tool_list_ready split (see// ToolListReadyPayload): the toolset is only known after MCP servers connect, and meta// must not wait for that. Pre-split Traces still carry the field on disk; it isdiff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex ee9f25a1..c0257871 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -20,20 +20,13 @@import {abortEvent,buildBackgroundTaskDoneMessage,- mcpConnectBegin,mcpConnectEnd,sessionMeta,- toolListReady,userText,} from "./omnimessage/index.js";-import type {- McpServerConnectResult,- OmniMessage,- SessionMetaPayload,- TokenCounts,- ToolDefinition,-} from "./omnimessage/index.js";+import type { OmniMessage, SessionMetaPayload } from "./omnimessage/index.js";import { imagesToScratchpadPaths } from "./internal/session-support.js";+import { pumpOpener } from "./internal/merge-queue.js";import { runGoalLoop } from "./goal/goal-loop.js";import { goalFinishedOf } from "./goal/goal-stream.js";import type {@@ -44,12 +37,13 @@ import type {SubagentMessageOptions,SubagentMessageOutcome,BackgroundTaskDoneEvent,- CommandPolicyConfig,EnvironmentInterface,LLMInterface,+ ThinkingLevelName,ToolPermission,} from "./interfaces/index.js";import { withCommandPolicy } from "./internal/command-policy.js";+import type { CommandPolicySource } from "./internal/command-policy.js";import { generateTitleWithLLM } from "./internal/session-title.js";import type { SessionTitleResult } from "./internal/session-title.js";import { compactAvailability, ContextEngine } from "./engine/context-engine.js";@@ -57,44 +51,53 @@ import type {CompactAvailability,CompactionSettings,EngineInitialState,+ OpenContextOptions,+ OpenedContext,RunOptions,TraceSink,} from "./engine/context-engine.js";export interface SessionConfig {- /** Session metadata — per-session invariants only (session_id / provider / model_id / model_context_window / system_prompt / agent_state / workspace / source); 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 opens brings its own through `openNextContext`; the toolset travels separately as the first run's tool_list_ready event. */meta: SessionMetaPayload;/**- * Lazy session bootstrap, run at the start of the first run: resolves the toolset —- * the Environment's first listTools connects any configured MCP Servers — and builds- * the session LLM from it; `mcp` carries the per-server connect outcomes for the- * mcp_connect_end event. Kept out of Session construction so creating a Session is- * instant and the connect wait streams as visible events instead. An aborted attempt- * is cancelled via `cancelBootstrap` — the next run calls this again and reconnects- * from scratch.+ * Opens the Session's FIRST context, lazily at the start of the first run: resolves the+ * toolset — the Environment's first listTools connects any configured MCP Servers — and+ * builds that context's LLM. The records it produces on the way — the+ * `mcp_connect_begin` / `mcp_connect_end` pair around a connect, then the+ * `tool_list_ready` carrying the toolset — are published through `opts.emit` and stream+ * live from `run`: the same shape as `openNextContext`, because opening the first context+ * and opening a later one are one procedure in the composition layer. Kept out of+ * Session construction so creating a Session is instant and the connect wait streams as+ * visible events instead. An aborted attempt is cancelled via `cancelBootstrap` — the+ * next run calls this again and reconnects from scratch.*/- bootstrap: () => Promise<{- tools: ToolDefinition[];- llm: LLMInterface;- mcp: McpServerConnectResult[];- }>;+ bootstrap: (opts: OpenContextOptions) => Promise<{ llm: LLMInterface }>;/** Cancels an in-flight bootstrap on user abort (the composition layer wires Environment.cancelMcpConnect). */cancelBootstrap?: () => void;- /** Names of the configured MCP Servers (config order): non-empty brackets the bootstrap in mcp_connect_begin/end events; empty emits none. */- mcpServers: string[];environment: EnvironmentInterface;trace?: TraceSink;- /** Maximum LLM turns per Task; -1 removes the cap. Omitted means -1 too — the agent-config default and the SDK fallback agree (unlimited). */+ /** Maximum LLM turns per Task in the first context; -1 removes the cap. Omitted means -1 too — the agent-config default and the SDK fallback agree (unlimited). A context `openNextContext` opens brings its own. */maxTurns?: number;- /** Creates a new LLM object after compaction (carries over the Session's accumulated Token count); context compaction is unavailable if not provided. */- createLLM?: (sessionTokens: TokenCounts) => LLMInterface;+ /**+ * Opens a fresh model context after compaction (see ContextEngineDeps.openNextContext): the new+ * LLM object, with the session_meta and engine settings of the context it opened — the+ * composition layer assembles them from the Agent State as it is then — and the records it+ * produced while opening (its MCP connect pair and tool_list_ready, through `opts.emit`).+ * The Session adopts the meta as its current one (`metaMessage`); the engine yields the+ * records live, writes meta and records at the head of the rotated Trace file, and seeds+ * the new LLM's cumulative session counts itself. Context compaction is unavailable if not+ * provided.+ */+ openNextContext?: (opts: OpenContextOptions) => OpenedContext | Promise<OpenedContext>;+/*** Factory for the bare LLM used by out-of-band, one-off requests (same Model/credential as* the session; no tools, no system prompt, thinking off): used for meta-requests such as* `generateTitle`; if not provided, `generateTitle` returns null.*/createBareLLM?: () => LLMInterface;- /** Context compaction settings (defaults are filled in by the composition layer); only takes effect when provided together with `createLLM`. */+ /** The first context's compaction settings (defaults are filled in by the composition layer); only takes effect when provided together with `openNextContext`, and a context that one opens brings its own. */compaction?: CompactionSettings;/** Session resume: `session_meta` is already in the original Trace file, so it isn't written again on the first run (avoids duplication). */metaAlreadyWritten?: boolean;@@ -122,14 +125,16 @@ export interface SessionConfig {*/goalFilePath?: string;/**- * Project sandbox command policy (`[command_policy]` of `.project_config.toml`): a- * snapshot taken when the Agent built this Session, so the Agent's own file tools cannot- * reach the effective copy. `run` wraps the injected approval callback with it — the- * refusal happens at the approval boundary, above every approval mode and below no- * Human implementation. Absent = the factory rule set applies; `{ enabled: false }` opts- * out. Docs: /docs/configuration § "Command policy".+ * Project sandbox command policy (`[command_policy]` of `.project_config.toml`), as a+ * SOURCE answering with the running context's policy: command policy is strict-tier —+ * the composition layer reads it from disk once per context open, so an edit applies at+ * the next rotation. `run` wraps the injected approval callback with it — the refusal+ * happens at the approval boundary, above every approval mode and below no Human+ * implementation.+ * Absent, or a source yielding nothing = the factory rule set applies;+ * `{ enabled: false }` opts out. Docs: /docs/configuration § "Command policy".*/- commandPolicy?: CommandPolicyConfig;+ commandPolicy?: CommandPolicySource;}/** Options of a goal-mode `run` (`opts.goal`): present = the input starts a goal loop. */@@ -261,7 +266,6 @@ export class Session {private abortedBootstrapRecords: OmniMessage[] = [];private readonly bootstrap: SessionConfig["bootstrap"];private readonly cancelBootstrap: (() => void) | undefined;- private readonly mcpServers: string[];/** Engine dependencies minus the LLM (which the bootstrap provides); kept whole so ensureReady can construct the engine late. */private readonly engineDeps: Omit<ConstructorParameters<typeof ContextEngine>[0],@@ -269,12 +273,15 @@ export class Session {>;private readonly environment: EnvironmentInterface;private readonly trace?: TraceSink;- private readonly 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`). */+ private meta: OmniMessage;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;private readonly goalFile?: string;- private readonly commandPolicy?: CommandPolicyConfig;+ private readonly commandPolicy?: CommandPolicySource;private metaWritten = false;/*** The image fold, bound to this Session's scratchpad — Session is the layer that knows both@@ -316,22 +323,32 @@ export class Session {this.metaWritten = config.metaAlreadyWritten ?? false;if (config.resumedHistory) this.resumedHistory = config.resumedHistory;if (config.createBareLLM) this.createBareLLM = config.createBareLLM;+this.imagesDir = config.imagesDir;this.modelHasVision = config.modelHasVision;if (config.goalFilePath) this.goalFile = config.goalFilePath;if (config.commandPolicy) this.commandPolicy = config.commandPolicy;this.bootstrap = config.bootstrap;this.cancelBootstrap = config.cancelBootstrap;- this.mcpServers = config.mcpServers;// The engine itself is built by ensureReady() on the first run, once the bootstrap has// produced the LLM: everything else it needs is captured here.this.engineDeps = {environment: config.environment,...(config.trace ? { trace: config.trace } : {}),...(config.maxTurns !== undefined ? { maxTurns: config.maxTurns } : {}),- // Context compaction: new LLM factory + resolved settings + writes session_meta (and- // tool_list_ready) at the start of the new Trace file after splitting.- ...(config.createLLM ? { createLLM: config.createLLM } : {}),+ // 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.+ ...(config.openNextContext+ ? {+ openNextContext: async (opts: OpenContextOptions): Promise<OpenedContext> => {+ const opened = await config.openNextContext!(opts);+ if (opened.sessionMeta) this.meta = opened.sessionMeta;+ return opened;+ },+ }+ : {}),...(config.compaction ? { compaction: config.compaction } : {}),...(config.initialEngineState ? { initialState: config.initialEngineState } : {}),// The engine assembles one input of its own — a steering message with images — and folds@@ -483,77 +500,72 @@ export class Session {}/**- * First-run bootstrap: writes `session_meta`, resolves the toolset and builds the- * engine — streaming the phase as it happens. With MCP Servers configured, the connect- * + discovery wait is bracketed by one `mcp_connect_begin` / `mcp_connect_end` pair- * (overall status + per-server outcomes; the wall time is the pair's timestamp- * difference). The resolved toolset then flows as one `tool_list_ready` event — split- * out of session_meta precisely so the meta never has to wait for this phase.+ * First-run bootstrap: writes `session_meta`, opens the first context and builds the+ * engine — streaming the phase as it happens. The bootstrap publishes its records+ * through `emit` — with MCP Servers configured, the `mcp_connect_begin` /+ * `mcp_connect_end` pair around the connect + discovery wait (overall status ++ * per-server outcomes; the wall time is the pair's timestamp difference), then the+ * `tool_list_ready` carrying the resolved toolset (split out of session_meta precisely+ * so the meta never has to wait for this phase) — and a merge queue turns them into+ * live yields here while it runs: the same pump the engine's post-compaction opener+ * uses, because opening the first context and opening a later one are one procedure.*- * The three messages are yielded live here, but their Trace writes are DEFERRED to the- * engine (ContextEngineDeps.bootstrapRecords): the engine writes them right after this- * run's input, so the connect phase belongs to the new turn in the Trace — after the- * user's message — instead of dangling before it (their earlier timestamps keep the+ * The records are yielded live, but their Trace writes are DEFERRED to the engine+ * (ContextEngineDeps.bootstrapRecords / toolList): the engine writes them right after+ * this run's input, so the connect phase belongs to the new turn in the Trace — after+ * the user's message — instead of dangling before it (their earlier timestamps keep the* file chronological, since the input message was created before the connect began).** Returns false when `signal` aborts mid-bootstrap: the attempt is CANCELLED* (`cancelBootstrap` → the provider aborts pending connects and resets — the next run- * reconnects from scratch), the pair closes with `status: "aborted"`, and a standard- * abort event follows. The aborted records are stashed (abortedBootstrapRecords) for- * the caller, which writes the turn to the Trace itself — input first, then the pair- * and the abort — since no engine exists to do it; the input is also carried- * (carryOverInput) so the next run delivers it to the model without re-writing it.- * No-op returning true once the engine exists; a rejected- * bootstrap (unreadable resume history, LLM construction) throws to the caller, and a- * later run retries with a fresh attempt.+ * reconnects from scratch), a connect the abort cut short is closed with a+ * `status: "aborted"` end, and a standard abort event follows. The records are stashed+ * (abortedBootstrapRecords) for the caller, which writes the turn to the Trace itself —+ * input first, then the records — since no engine exists to do it; the input is also+ * carried (carryOverInput) so the next run delivers it to the model without re-writing+ * it. No-op returning true once the engine exists; a rejected bootstrap (unreadable+ * resume history, LLM construction) throws to the caller, and a later run retries with+ * a fresh attempt.*/private async *ensureReady(signal?: AbortSignal): AsyncGenerator<OmniMessage, boolean> {await this.ensureMetaWritten();if (this.engine) return true;const records: OmniMessage[] = [];- if (this.mcpServers.length > 0) {- const begin = mcpConnectBegin(this.mcpServers);- yield begin;- records.push(begin);- }- const work = this.bootstrap();- const outcome = await raceAbort(work, signal);- if (outcome === "aborted") {- this.cancelBootstrap?.();- // The cancelled attempt settles on its own (rejection expected); keep it from- // surfacing as an unhandled rejection.- work.catch(() => {});- // Stashed (not written here) so the caller can put the run's INPUT first — the- // Trace stays chronological: input, pair, abort.- this.abortedBootstrapRecords = records.length > 0 ? [...records] : [];- if (this.mcpServers.length > 0) {- const end = mcpConnectEnd({ status: "aborted", results: [] });- yield end;- this.abortedBootstrapRecords.push(end);+ const { queue, result: work } = pumpOpener((emit) => this.bootstrap({ emit }));+ for (;;) {+ const res = await raceAbort(queue.next(), signal);+ if (res === "aborted") {+ this.cancelBootstrap?.();+ // The cancelled attempt settles on its own (rejection expected); anything it+ // publishes after this point is dropped, exactly as its return value is.+ work.catch(() => {});+ // Stashed (not written here) so the caller can put the run's INPUT first — the+ // Trace stays chronological: input, records, abort.+ this.abortedBootstrapRecords = [...records];+ // A connect the abort cut short never published its end: close the pair.+ const hasType = (t: string): boolean =>+ records.some((m) => (m.payload as { type?: string }).type === t);+ if (hasType("mcp_connect_begin") && !hasType("mcp_connect_end")) {+ const end = mcpConnectEnd({ status: "aborted", results: [] });+ yield end;+ this.abortedBootstrapRecords.push(end);+ }+ const aborted = abortEvent("user_abort");+ yield aborted;+ this.abortedBootstrapRecords.push(aborted);+ return false;}- const aborted = abortEvent("user_abort");- yield aborted;- this.abortedBootstrapRecords.push(aborted);- return false;- }- const { tools, llm, mcp } = outcome.value;- if (this.mcpServers.length > 0) {- const failed = mcp.filter((r) => r.status !== "completed").map((r) => r.server);- const end = mcpConnectEnd({- status: failed.length > 0 ? "fatal" : "completed",- results: mcp,- ...(failed.length > 0- ? {- errorCode: "connect_failed" as const,- errorMessage: `unavailable: ${failed.join(", ")}`,- }- : {}),- });- yield end;- records.push(end);+ if (res.value === null) break;+ records.push(res.value);+ yield res.value;}- const toolsMsg = toolListReady(tools);- yield toolsMsg;+ const { llm } = await work;+ // The opener's toolset record rides as the engine's `toolList` (first-run write ++ // rotation rewrite); the connect pair — everything else — as bootstrapRecords.+ const toolsMsg = records.findLast(+ (m) => (m.payload as { type?: string }).type === "tool_list_ready",+ );+ const connectRecords = records.filter((m) => m !== toolsMsg);// One-shot skip list: inputs carried from an aborted bootstrap were already written// to the Trace by the abort path — the engine re-delivers them (model context) but// must not re-write them. Exact-envelope match, each consumed once.@@ -574,22 +586,23 @@ export class Session {...(baseTrace.rotate ? { rotate: () => baseTrace.rotate!() } : {}),}: baseTrace;- // toolsMsg rides as `toolList` alone (first-run write + rotation rewrite); the- // records array carries only the connect pair — one message, one carrier.this.engine = new ContextEngine({...this.engineDeps,...(trace !== undefined ? { trace } : {}),llm,- toolList: toolsMsg,- bootstrapRecords: records,+ ...(toolsMsg !== undefined ? { toolList: toolsMsg } : {}),+ bootstrapRecords: connectRecords,});+ // A level assigned before the first run was buffered on the Session: hand it to the+ // engine now that it exists, ahead of the first turn request.+ if (this.level !== undefined) this.engine.setThinkingLevel(this.level);return true;}/*** The goal-mode branch of `run`: validates the input, folds any attached images into the* objective, then drives the goal loop, running each round through the single-Task path with- * the same per-call options (approval, signal, thinking level). The loop's terminal+ * the same per-call options (approval, signal). The loop's terminal* `goal_finished` event is additionally written to the Trace (best-effort, like session_meta)* so the goal's end survives with its conversation.*@@ -741,7 +754,7 @@ export class Session {// nothing to compact (the server renders this reason as a 409 `nothing_to_compact`).const init = this.engineDeps.initialState;return compactAvailability({- configured: Boolean(this.engineDeps.compaction && this.engineDeps.createLLM),+ configured: Boolean(this.engineDeps.compaction && this.engineDeps.openNextContext),sessionTurns: init?.sessionTurns ?? 0,fromCompaction: init?.fromCompaction ?? false,});@@ -795,12 +808,37 @@ export class Session {});}- /** Queries a tool's permission level (for the frontend to determine permission mode); returns undefined for unknown tools. */+ /**+ * The Session's thinking level — the SOFT-limited runtime parameter as plain state: an+ * assignment rides the very next LLM request (mid-context, even mid-Task), unlike the+ * prompt, toolset and model, which never change between a context's open and its close —+ * and nothing records it in the Trace. The live value is engine state+ * (`ContextEngine.setThinkingLevel`), buffered on the Session until the engine exists;+ * contexts keep their opening base (the creation option, else the Agent config) for+ * compaction requests and as the fallback while nothing was ever assigned. The cost of+ * the softness is the provider's cached context — changing the level invalidates the+ * cached messages — so a host lets the user know at the picker that compacting first is+ * recommended (the Web menu note, the CLI `/thinking` reply).+ * Callers: the Web App's in-chat picker (PATCH), the CLI's `--thinking` / `/thinking`.+ */+ get thinkingLevel(): ThinkingLevelName | undefined {+ return this.level;+ }+ set thinkingLevel(level: ThinkingLevelName) {+ this.level = level;+ this.engine?.setThinkingLevel(level);+ }++ /**+ * A tool's permission level (what the read-only approval mode auto-approves by);+ * undefined for unknown tools. Strict-tier: answers from the running context's toolset —+ * rebuilt at every rotation — so a permission edit applies when the next context opens.+ */toolPermission(name: string): ToolPermission | undefined {return this.environment.toolPermission(name);}- /** This Session's session_meta message (used e.g. by host tools to forward nested-session metadata to a parent session). */+ /** The running context's session_meta message — the first context's until a compaction opens another (used e.g. by host tools to forward nested-session metadata to a parent session). */get metaMessage(): OmniMessage {return this.meta;}@@ -855,6 +893,11 @@ export class Session {return this.environment.abortBackgroundSubagentRun?.(childSessionId) ?? false;}+ /** Host-initiated pin of one live child session's thinking level — the child's own `thinkingLevel`, applied from its next LLM request (see EnvironmentInterface.setBackgroundSubagentThinkingLevel); false when the child is not live. */+ setBackgroundSubagentThinkingLevel(childSessionId: string, level: ThinkingLevelName): boolean {+ return this.environment.setBackgroundSubagentThinkingLevel?.(childSessionId, level) ?? false;+ }+/** Attaches the host's session-lifetime fallback approval sink for child sessions (see EnvironmentInterface.setSubagentApprovalFallback). */setSubagentApprovalFallback(approve: ApproveFn): void {this.environment.setSubagentApprovalFallback?.(approve);diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.tsindex 84610a61..028bd53d 100644--- a/packages/core/src/state/agent-state.ts+++ b/packages/core/src/state/agent-state.ts@@ -101,6 +101,7 @@ export interface AgentState {agentId: string;stateDir: string;systemConfig: SystemConfig;+ /** `AGENTS.md` as read when the State was loaded. A Session never runs on a State object it did not load itself: every model context is assembled from a fresh `loadAgentState` (see Agent.createSession). */agentsMd: string;}@@ -122,20 +123,36 @@ export interface SessionEnvironmentValues {date: string;}+/** Reads the Agent's `AGENTS.md` as it is on disk right now; a missing file reads as the default content (see `loadAgentState`). */+export async function readAgentsMd(+ root: string,+ projectId: string,+ agentId: string,+): Promise<string> {+ const mdPath = agentsMdPath(root, projectId, agentId);+ return (await fileExists(mdPath)) ? await fs.readFile(mdPath, "utf8") : defaultAgentsMd();+}+/**- * Loads or initializes Agent State.+ * THE Agent State loader — the one function behind initialization and rotation alike.*- * When root/project/agent are omitted, `resolveRoot()` and the default constants are used. If- * `system_config.yaml` doesn't exist, the directory is treated as empty and initialized;- * otherwise the existing content is loaded. `preset` only takes effect on the initialization- * path (name/description/AGENTS.md overrides and extra Skills) and is ignored when loading an- * existing Agent — existing config is never overwritten.+ * Loads the State as it is on disk right now (`system_config.yaml` and `AGENTS.md`). With+ * `init` given and no `system_config.yaml` present, the directory is treated as a new Agent+ * and initialized first (structure, default config, preinstalled Skills; `init.preset`+ * applies there only) — the create-or-load entry `createAgent` and project provisioning use.+ * Without `init`, a missing Agent throws: the other caller is a model context opening —+ * Session creation, the context a completed compaction opens, a resume that finds its+ * context closed — which must never re-create a deleted Agent as a side effect. Either way+ * an edit to the Agent State lands in the next context and never in the one that is+ * running; the snapshot a long-lived Agent object holds is not what a Session runs on.+ * Docs: /docs/agent-loop § "Compaction".*/-export async function loadOrInitAgentState(opts?: {+export async function loadAgentState(opts?: {agentId?: string;projectId?: string;root?: string;- preset?: AgentPreset;+ /** Initialize a not-yet-initialized Agent instead of throwing (`preset` applies on that path only; an existing Agent is never overwritten). */+ init?: { preset?: AgentPreset };}): Promise<AgentState> {const root = opts?.root ?? resolveRoot();const projectId = opts?.projectId ?? DEFAULT_PROJECT_ID;@@ -147,15 +164,10 @@ export async function loadOrInitAgentState(opts?: {const stateDir = agentStateDir(root, projectId, agentId);const configPath = systemConfigPath(root, projectId, agentId);- const mdPath = agentsMdPath(root, projectId, agentId);-- let systemConfig: SystemConfig;- let agentsMd: string;if (await fileExists(configPath)) {- // Load path: read the existing system_config.yaml and AGENTS.md.- const rawConfig = await fs.readFile(configPath, "utf8");- const parsed = parseYaml(rawConfig) as unknown;+ // Load path: the State as it is on disk.+ const parsed = parseYaml(await fs.readFile(configPath, "utf8")) as unknown;// Defensive check: if the file is empty/corrupted, parseYaml may return null/a non-object,// or system_prompt may be missing — otherwise "undefined" would get spliced into the system// Prompt. Throw a clear error when validation fails.@@ -168,62 +180,71 @@ export async function loadOrInitAgentState(opts?: {`Invalid Agent State config: ${configPath} is empty, corrupted, or missing the system_prompt field.`,);}- systemConfig = parsed as SystemConfig;- agentsMd = (await fileExists(mdPath)) ? await fs.readFile(mdPath, "utf8") : defaultAgentsMd();- } else {- // Init path: create the directory structure and write default config (preset only takes effect here).- await Promise.all([- fs.mkdir(stateDir, { recursive: true }),- fs.mkdir(toolsDir(root, projectId, agentId), { recursive: true }),- // Creates memory/user/ (and memory/ above it) with an empty MEMORY.md, so the User scope- // exists from the Agent's first day; Workspace scopes appear at Session creation.- ensureUserMemoryDir(root, projectId, agentId),- fs.mkdir(skillsDir(root, projectId, agentId), { recursive: true }),- fs.mkdir(scratchpadDir(root, projectId, agentId), { recursive: true }),- ]);- const preset = opts?.preset;- systemConfig = {- ...defaultSystemConfig(),- ...(preset?.name !== undefined ? { name: preset.name } : {}),- ...(preset?.description !== undefined ? { description: preset.description } : {}),+ return {+ root,+ projectId,+ agentId,+ stateDir,+ systemConfig: parsed as SystemConfig,+ agentsMd: await readAgentsMd(root, projectId, agentId),};- agentsMd = preset?.agentsMd ?? defaultAgentsMd();- // Only installs the Skills specified by preset (a plain newly created Agent gets none- // pre-installed). A default_agent with no preset (e.g. created on first CLI run) still gets- // the library's preinstalled set (Skills marked `preinstall: false` stay manual-install) —- // the install policy follows Agent identity, not whether creation came from the server or- // was done directly via SDK/CLI.- // Skills have no dedicated tool: metadata is injected via {{SKILL_METADATA}}, and the model- // reads SKILL.md with shell and follows it.- const skills =- opts?.preset === undefined && agentId === DEFAULT_AGENT_ID- ? loadPreinstalledSkills()- : (opts?.preset?.skills ?? []);- await Promise.all([- atomicWriteFile(mdPath, agentsMd, { followSymlinks: true }),- ...skills.map((skill) => installSkill(root, projectId, agentId, skill)),- // The example Benchmark is only provisioned alongside default_agent (so the evaluation- // center has data out of the box): idempotently skipped if benchmarks/ already exists,- // and not created for plain Agents.- ...(agentId === DEFAULT_AGENT_ID- ? [provisionExampleBenchmark(root, projectId, agentId)]- : []),- ]);- // system_config.yaml is written last: its existence is the "initialization complete" marker- // (the load/init decision point). If this fails partway (disk full / crash), the next run- // still takes the init path and self-heals, so no half-initialized state with missing Skills is left behind.- await atomicWriteFile(configPath, stringifyYaml(systemConfig), { followSymlinks: true });}+ if (!opts?.init) {+ throw new Error(`Agent State is not initialized: ${configPath} does not exist.`);+ }++ // Init path: create the directory structure and write default config (preset only takes effect here).+ await Promise.all([+ fs.mkdir(stateDir, { recursive: true }),+ fs.mkdir(toolsDir(root, projectId, agentId), { recursive: true }),+ // Creates memory/user/ (and memory/ above it) with an empty MEMORY.md, so the User scope+ // exists from the Agent's first day; Workspace scopes appear at Session creation.+ ensureUserMemoryDir(root, projectId, agentId),+ fs.mkdir(skillsDir(root, projectId, agentId), { recursive: true }),+ fs.mkdir(scratchpadDir(root, projectId, agentId), { recursive: true }),+ ]);+ const preset = opts.init.preset;+ const systemConfig: SystemConfig = {+ ...defaultSystemConfig(),+ ...(preset?.name !== undefined ? { name: preset.name } : {}),+ ...(preset?.description !== undefined ? { description: preset.description } : {}),+ };+ const agentsMd = preset?.agentsMd ?? defaultAgentsMd();+ // Only installs the Skills specified by preset (a plain newly created Agent gets none+ // pre-installed). A default_agent with no preset (e.g. created on first CLI run) still gets+ // the library's preinstalled set (Skills marked `preinstall: false` stay manual-install) —+ // the install policy follows Agent identity, not whether creation came from the server or+ // was done directly via SDK/CLI.+ // Skills have no dedicated tool: metadata is injected via {{SKILL_METADATA}}, and the model+ // reads SKILL.md with shell and follows it.+ const skills =+ preset === undefined && agentId === DEFAULT_AGENT_ID+ ? loadPreinstalledSkills()+ : (preset?.skills ?? []);+ await Promise.all([+ atomicWriteFile(agentsMdPath(root, projectId, agentId), agentsMd, { followSymlinks: true }),+ ...skills.map((skill) => installSkill(root, projectId, agentId, skill)),+ // The example Benchmark is only provisioned alongside default_agent (so the evaluation+ // center has data out of the box): idempotently skipped if benchmarks/ already exists,+ // and not created for plain Agents.+ ...(agentId === DEFAULT_AGENT_ID ? [provisionExampleBenchmark(root, projectId, agentId)] : []),+ ]);+ // system_config.yaml is written last: its existence is the "initialization complete" marker+ // (the load/init decision point). If this fails partway (disk full / crash), the next run+ // still takes the init path and self-heals, so no half-initialized state with missing Skills is left behind.+ await atomicWriteFile(configPath, stringifyYaml(systemConfig), { followSymlinks: true });+return { root, projectId, agentId, stateDir, systemConfig, agentsMd };}/*** Initializes a Project's built-in Agent (the only built-in Agent: default_agent).*- * Calls loadOrInitAgentState for each one: an Agent whose directory already exists (including a- * default_agent created earlier by the CLI) is only loaded, never overwritten (preset only- * takes effect on initialization). Returns the list of built-in Agent ids.+ * Calls the init-enabled `loadAgentState` for each one: an Agent whose directory already+ * exists (including a default_agent created earlier by the CLI) is only loaded, never+ * overwritten (preset only takes effect on initialization). Returns the list of built-in+ * Agent ids.*/export async function provisionProjectAgents(opts?: {root?: string;@@ -231,11 +252,11 @@ export async function provisionProjectAgents(opts?: {}): Promise<string[]> {const agentIds: string[] = [];for (const { agentId, preset } of builtinProjectAgentPresets()) {- await loadOrInitAgentState({+ await loadAgentState({...(opts?.root !== undefined ? { root: opts.root } : {}),...(opts?.projectId !== undefined ? { projectId: opts.projectId } : {}),agentId,- preset,+ init: { preset },});agentIds.push(agentId);}@@ -255,7 +276,7 @@ export async function provisionProjectAgents(opts?: {* preserved (the file is rewritten from the default object). Other Agent State files* (AGENTS.md, skills/, vault, memory/ …) are untouched. Returns the config written.*- * Requires an existing Agent: unlike `loadOrInitAgentState` this never initializes a new+ * Requires an existing Agent: unlike an init-enabled `loadAgentState` this never initializes a new* one — it throws when `system_config.yaml` is missing.*/export async function resetSystemConfigToDefaults(diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.tsindex 5d81f0d4..cf765680 100644--- a/packages/core/test/agent.test.ts+++ b/packages/core/test/agent.test.ts@@ -14,7 +14,10 @@ import fs from "node:fs/promises";import os from "node:os";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 { agentsMdPath, projectConfigPath, systemConfigPath } from "../src/state/paths.js";import {addModel,createAgent,@@ -88,6 +91,18 @@ afterEach(async () => {// effectiveMaxContextLength moved to llm/context-limits.ts; its derivation (window-derived// compaction threshold, issue #218) is covered in test/context-limits.test.ts.+/**+ * Edits the default Agent's on-disk `system_config.yaml`: a Session runs on the Agent State as+ * it is on disk when each of its model contexts opens, never on the Agent object's load-time+ * snapshot — so a test that wants a config to take effect writes it here.+ */+async function patchSystemConfig(patch: (cfg: SystemConfig) => void): Promise<void> {+ const file = systemConfigPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);+ const cfg = parseYaml(await fs.readFile(file, "utf8")) as SystemConfig;+ patch(cfg);+ await fs.writeFile(file, stringifyYaml(cfg), "utf8");+}+/** Drains the session's lazy first-run bootstrap so the engine (and its LLM) exists for inspection. */async function bootstrapped(session: unknown): Promise<void> {const gen = (session as { ensureReady(): AsyncGenerator<unknown> }).ensureReady();@@ -153,10 +168,9 @@ describe("Agent.createSession workspace handling", () => {it("passes model timeout from system_config to GenerativeModel", async () => {const agent = await createAgent();- agent.state.systemConfig.model = {- ...(agent.state.systemConfig.model ?? {}),- timeoutMs: 3456,- };+ await patchSystemConfig((cfg) => {+ cfg.model = { ...(cfg.model ?? {}), timeoutMs: 3456 };+ });const ws = path.join(tmpRoot, "ws-timeout");await fs.mkdir(ws, { recursive: true });@@ -272,15 +286,15 @@ describe("Agent.createSession session source (session_meta origin marker)", () =});describe("Agent.createSession thinking level (explicit option wins over the Agent config)", () => {- // The session's default level lives on the LLM object (per-request overrides fall back to- // it); session_meta holds per-session invariants only and never records a thinking level.+ // A context's level is the LLM object's construction default (the Session's live pin+ // overrides it per request); nothing is recorded — the level is a per-request parameter.const defaultLevelOf = async (session: unknown): Promise<unknown> => {await bootstrapped(session);return (session as { engine: { deps: { llm: { defaultThinkingLevel?: unknown } } } }).engine.deps.llm.defaultThinkingLevel;};- it("falls back to the Agent config for the llm default; session_meta records no level", async () => {+ it("falls back to the Agent config for the llm default", async () => {const agent = await createAgent();// The seeded Agent config pins thinking_level "medium" — the only source when no option is given.expect(agent.state.systemConfig.model?.thinking_level).toBe("medium");@@ -288,10 +302,6 @@ describe("Agent.createSession thinking level (explicit option wins over the Agenawait fs.mkdir(ws, { recursive: true });const session = await agent.createSession({ workspaceDir: ws });try {- // session_meta contains ONLY per-session invariants: the thinking level is per-turn.- expect(- "thinking_level" in (session.metaMessage.payload as unknown as Record<string, unknown>),- ).toBe(false);expect(await defaultLevelOf(session)).toBe("medium");expect(mapThinkingLevel("medium")).toBeDefined(); // the name maps onto the wire enum} finally {@@ -320,7 +330,9 @@ describe("Agent.createSession thinking level (explicit option wins over the Agenawait saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, cfg);const agent = await createAgent();// A hand-edited config without a level (the seeded default pins "medium").- delete agent.state.systemConfig.model?.thinking_level;+ await patchSystemConfig((cfg) => {+ delete cfg.model?.thinking_level;+ });const ws = path.join(tmpRoot, "ws-thinking-project");await fs.mkdir(ws, { recursive: true });const session = await agent.createSession({ workspaceDir: ws });@@ -345,11 +357,16 @@ describe("Agent.createSession thinking level (explicit option wins over the Agen} finally {explicit.dispose();}- // No explicit level and no project default -> the built-in "medium".- const bare = await createAgent();- delete bare.projectConfig.default_chat;- delete bare.state.systemConfig.model?.thinking_level;- const builtin = await bare.createSession({ workspaceDir: ws });+ // No explicit level and no project default -> the built-in "medium". Both halves of+ // the chain are read from disk when a context opens, so the SAME Agent object sees the+ // Project config edited underneath it.+ const noDefault = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ delete noDefault.default_chat;+ await saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, noDefault);+ await patchSystemConfig((cfg) => {+ delete cfg.model?.thinking_level;+ });+ const builtin = await agent.createSession({ workspaceDir: ws });try {expect(await defaultLevelOf(builtin)).toBe("medium");} finally {@@ -420,10 +437,9 @@ describe("run_subagent spawning follows the PARENT session (never the Project deit("inherits the parent's model pair, thinking level, and workspace when the args omit them", async () => {const agent = await createAgent();- agent.state.systemConfig.model = {- ...(agent.state.systemConfig.model ?? {}),- thinking_level: "high",- };+ await patchSystemConfig((cfg) => {+ cfg.model = { ...(cfg.model ?? {}), thinking_level: "high" };+ });const ws = path.join(tmpRoot, "ws-inherit");await fs.mkdir(ws, { recursive: true });// The parent runs a NON-default model: the Project default (deepseek pair) must not leak in.@@ -500,10 +516,9 @@ describe("run_subagent spawning follows the PARENT session (never the Project deit("pins an explicit spawn-time thinking level over inheritance (run_subagent's thinking_level)", async () => {const agent = await createAgent();- agent.state.systemConfig.model = {- ...(agent.state.systemConfig.model ?? {}),- thinking_level: "high",- };+ await patchSystemConfig((cfg) => {+ cfg.model = { ...(cfg.model ?? {}), thinking_level: "high" };+ });const ws = path.join(tmpRoot, "ws-thinking-override");await fs.mkdir(ws, { recursive: true });const parent = await agent.createSession({ workspaceDir: ws });@@ -558,10 +573,9 @@ describe("run_subagent spawning follows the PARENT session (never the Project de// config (thinking "medium") and the Project default model must both lose to the parent.await createAgent({ agentId: "helper_agent" });const agent = await createAgent();- agent.state.systemConfig.model = {- ...(agent.state.systemConfig.model ?? {}),- thinking_level: "xhigh",- };+ await patchSystemConfig((cfg) => {+ cfg.model = { ...(cfg.model ?? {}), thinking_level: "xhigh" };+ });const ws = path.join(tmpRoot, "ws-inherit-cross");await fs.mkdir(ws, { recursive: true });const parent = await agent.createSession({@@ -848,3 +862,276 @@ describe("Agent.createSession skill metadata injection", () => {}});});++describe("Agent model contexts are assembled from the Agent State on disk, at every context open", () => {+ const promptOf = (session: { metaMessage: OmniMessage }): string =>+ (session.metaMessage.payload as { system_prompt: string }).system_prompt;+ const mdFile = () => agentsMdPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);+ const typeOf = (msg: OmniMessage | undefined): string | undefined =>+ (msg?.payload as { type?: string } | undefined)?.type;+ /** The engine-facing context opener (the Session's wrapper around the Agent's factory), reachable once the first-run bootstrap has resolved the toolset. */+ const openerOf = (session: unknown) =>+ (+ session as {+ engine: {+ deps: {+ openNextContext: (opts: OpenContextOptions) => Promise<OpenedContext>;+ };+ };+ }+ ).engine.deps.openNextContext;+ /** Opens the Session's next context through its opener, collecting the records the opener publishes. */+ async function openNext(+ session: unknown,+ ): Promise<{ opened: OpenedContext; records: OmniMessage[] }> {+ const records: OmniMessage[] = [];+ const opened = await openerOf(session)({ emit: (msg) => records.push(msg) });+ return { opened, records };+ }+ /** The config the most recently constructed GenerativeModel was given. */+ const lastBuilt = () =>+ capturedLLMConfigs.list.at(-1) as+ { systemPrompt?: string; tools?: { name: string }[]; thinkingLevel?: string } | undefined;+ const toolNames = (tools: { name: string }[] | undefined): string[] =>+ (tools ?? []).map((t) => t.name);+ /** The vault the Environment's command session registry injects at every spawn. */+ const environmentVaultOf = (session: unknown): Record<string, string> =>+ (session as { environment: { commandSessions: { vault: Record<string, string> } } }).environment+ .commandSessions.vault;++ it("createSession assembles from disk, not from the Agent's load-time snapshot", async () => {+ const agent = await createAgent();+ await fs.writeFile(mdFile(), "EDITED AFTER LOAD", "utf8");+ await patchSystemConfig((cfg) => {+ cfg.max_turns = 7;+ });+ const ws = path.join(tmpRoot, "ws-md-disk");+ await fs.mkdir(ws, { recursive: true });++ const session = await agent.createSession({ workspaceDir: ws });+ try {+ expect(promptOf(session)).toContain("EDITED AFTER LOAD");+ expect(+ (session as unknown as { engineDeps: { maxTurns?: number } }).engineDeps.maxTurns,+ ).toBe(7);+ // The Agent object's copies are the load-time snapshot; no Session runs on them.+ expect(agent.state.agentsMd).not.toContain("EDITED AFTER LOAD");+ expect(agent.state.systemConfig.max_turns).not.toBe(7);+ } finally {+ session.dispose();+ }+ });++ it("the context opened after compaction is rebuilt whole — prompt, toolset, vault, run settings — and its records describe it", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-rebuild");+ await fs.mkdir(ws, { recursive: true });+ const session = await agent.createSession({ workspaceDir: ws });+ try {+ await bootstrapped(session);+ expect(toolNames(lastBuilt()!.tools)).toContain("write_file");+ expect(environmentVaultOf(session)).toEqual({});+ expect(promptOf(session)).not.toContain("EDITED DURING THE OLD CONTEXT");++ // Everything edited during the old context — by the model working on its own+ // configuration, or by hand in the Agent settings.+ await fs.writeFile(mdFile(), "EDITED DURING THE OLD CONTEXT", "utf8");+ await setVaultEntry(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID, "NEW_API_KEY", "shh");+ await patchSystemConfig((cfg) => {+ cfg.tools = {+ ...(cfg.tools ?? {}),+ builtin: (cfg.tools?.builtin ?? []).filter((t) => t.name !== "write_file"),+ };+ cfg.compaction = { ...(cfg.compaction ?? {}), mode: "discard" };+ cfg.max_turns = 3;+ cfg.model = { ...(cfg.model ?? {}), thinking_level: "high" };+ });++ const { opened, records } = await openNext(session);++ // The new LLM object carries the re-assembled prompt, the re-read toolset and the+ // config's model defaults…+ const after = lastBuilt()!;+ expect(after.systemPrompt).toContain("EDITED DURING THE OLD CONTEXT");+ expect(after.systemPrompt).toContain("NEW_API_KEY");+ expect(toolNames(after.tools)).not.toContain("write_file");+ expect(toolNames(after.tools)).toContain("read_file");+ expect(after.thinkingLevel).toBe("high");+ // …the vault's values went straight into the Environment's command environment…+ expect(environmentVaultOf(session)).toEqual({ NEW_API_KEY: "shh" });+ // …the engine settings follow the re-read config…+ expect(opened.maxTurns).toBe(3);+ expect(opened.compaction?.mode).toBe("discard");+ // …the meta the rotated Trace file opens with records exactly that prompt (the Session's+ // own meta follows the running context), and the toolset record is published for the+ // file head and the live stream.+ const recorded = (opened.sessionMeta!.payload as { system_prompt: string }).system_prompt;+ expect(recorded).toBe(after.systemPrompt);+ expect(promptOf(session)).toBe(recorded);+ expect(records.map(typeOf)).toEqual(["tool_list_ready"]);+ expect(toolNames((records[0]!.payload as { tools: { name: string }[] }).tools)).toEqual(+ toolNames(after.tools),+ );+ } finally {+ session.dispose();+ }+ });++ it("session_meta records no level; the config default and a null pin shape only the LLM base", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-thinking-meta");+ await fs.mkdir(ws, { recursive: true });+ const levelOf = (session: { metaMessage: OmniMessage }) =>+ (session.metaMessage.payload as { thinking_level?: string }).thinking_level;++ // The seeded config pins "medium"; a `null` pin (a subagent whose parent has none) runs+ // without a level. Neither is recorded: the level is a per-request parameter.+ const configured = await agent.createSession({ workspaceDir: ws });+ const unlevelled = await agent.createSession({ workspaceDir: ws, thinkingLevel: null });+ try {+ await bootstrapped(configured);+ expect(lastBuilt()!.thinkingLevel).toBe("medium");+ expect(levelOf(configured)).toBeUndefined();+ await bootstrapped(unlevelled);+ expect(lastBuilt()!.thinkingLevel).toBeUndefined();+ expect(levelOf(unlevelled)).toBeUndefined();+ } finally {+ configured.dispose();+ unlevelled.dispose();+ }+ });++ it("toolPermission and the command policy are strict-tier: an edit lands at the next context open, not mid-context", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-strict-permission");+ await fs.mkdir(ws, { recursive: true });+ const session = await agent.createSession({ workspaceDir: ws });+ const policyOf = () =>+ (+ session as unknown as { commandPolicy?: () => { enabled?: boolean } | undefined }+ ).commandPolicy?.();+ try {+ await bootstrapped(session);+ expect(session.toolPermission("read_file")).toBe("r");+ const openedWith = policyOf();+ await patchSystemConfig((cfg) => {+ cfg.tools = {+ ...(cfg.tools ?? {}),+ builtin: (cfg.tools?.builtin ?? []).map((t) =>+ t.name === "read_file" ? { ...t, permission: "rw" as const } : t,+ ),+ };+ });+ await fs.writeFile(+ projectConfigPath(tmpRoot, DEFAULT_PROJECT_ID),+ "[command_policy]\nenabled = false\n",+ "utf8",+ );+ // The running context's toolset and policy stand until rotation…+ expect(session.toolPermission("read_file")).toBe("r");+ expect(policyOf()).toBe(openedWith);+ // …and the next context opens with both edits.+ await openNext(session);+ expect(session.toolPermission("read_file")).toBe("rw");+ expect(policyOf()).toEqual({ enabled: false });+ } finally {+ session.dispose();+ }+ });++ it("thinkingLevel is plain engine state: an assignment rides requests while contexts keep their config base", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-thinking-pin");+ await fs.mkdir(ws, { recursive: true });+ const levelOf = (session: { metaMessage: OmniMessage }) =>+ (session.metaMessage.payload as { thinking_level?: string }).thinking_level;+ const engineLevelOf = (session: unknown) =>+ (session as { engine: { thinkingLevel?: string } }).engine.thinkingLevel;++ const session = await agent.createSession({ workspaceDir: ws });+ try {+ // Assigned before the first run: buffered on the Session, handed to the engine when+ // it is built. The context's own base stays the config default ("medium").+ session.thinkingLevel = "high";+ expect(session.thinkingLevel).toBe("high");+ expect(levelOf(session)).toBeUndefined();+ await bootstrapped(session);+ expect(lastBuilt()!.thinkingLevel).toBe("medium");+ expect(engineLevelOf(session)).toBe("high");++ // Reassigned mid-session: engine state for every subsequent request; the context a+ // compaction opens still bases on the creation option and the config, and the meta+ // records nothing.+ session.thinkingLevel = "xhigh";+ expect(engineLevelOf(session)).toBe("xhigh");+ const { opened } = await openNext(session);+ expect(+ (opened.sessionMeta!.payload as { thinking_level?: string }).thinking_level,+ ).toBeUndefined();+ expect(lastBuilt()!.thinkingLevel).toBe("medium");+ expect(session.thinkingLevel).toBe("xhigh");+ } finally {+ session.dispose();+ }+ });++ it("reconnects the new context's MCP Servers, bracketing the connect with the same event pair the first run uses", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-mcp-rotate");+ await fs.mkdir(ws, { recursive: true });+ const session = await agent.createSession({ workspaceDir: ws });+ // The provider warns on stderr about the unreachable server; keep the test output clean.+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ await bootstrapped(session);+ // A server added during the old context. Its command cannot be spawned, so the connect+ // fails fast — and the outcome is recorded rather than hidden.+ await patchSystemConfig((cfg) => {+ cfg.tools = {+ ...(cfg.tools ?? {}),+ mcpServers: [{ name: "ghost", config: { command: "penguin-no-such-mcp-server" } }],+ };+ });++ const { records } = await openNext(session);++ expect(records.map(typeOf)).toEqual([+ "mcp_connect_begin",+ "mcp_connect_end",+ "tool_list_ready",+ ]);+ expect((records[0]!.payload as { servers: string[] }).servers).toEqual(["ghost"]);+ const end = records[1]!.payload as {+ status: string;+ results: { server: string; status: string }[];+ };+ expect(end.status).toBe("fatal");+ expect(end.results).toEqual([expect.objectContaining({ server: "ghost", status: "fatal" })]);+ expect(stderr).toHaveBeenCalledWith(+ expect.stringContaining('MCP server "ghost" unavailable'),+ );+ } finally {+ stderr.mockRestore();+ session.dispose();+ }+ });++ it("an Agent State that cannot be assembled fails the context open outright — no silent fallback", async () => {+ const agent = await createAgent();+ const ws = path.join(tmpRoot, "ws-unreadable");+ await fs.mkdir(ws, { recursive: true });+ const session = await agent.createSession({ workspaceDir: ws });+ try {+ await bootstrapped(session);+ const before = promptOf(session);+ // system_config.yaml no longer parses — an edit gone wrong mid-context.+ await fs.writeFile(systemConfigPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID), "");++ await expect(openNext(session)).rejects.toThrow("Invalid Agent State config");+ // Nothing was adopted: the Session still describes the context that is running.+ expect(promptOf(session)).toBe(before);+ } finally {+ session.dispose();+ }+ });+});diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.tsindex 7fe93fbf..f6fddbc1 100644--- a/packages/core/test/background-execution.test.ts+++ b/packages/core/test/background-execution.test.ts@@ -758,8 +758,7 @@ describe("Session background notices", () => {const session = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm: new ReplyLLM(), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: new ReplyLLM() }),environment,});let signaled = 0;@@ -792,8 +791,7 @@ describe("Session background notices", () => {const session = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm: new ReplyLLM(), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: new ReplyLLM() }),environment,});fire({ ...DONE_EVENT, status: "stopped", detail: "stopped by SIGTERM" });@@ -811,8 +809,7 @@ describe("Session background notices", () => {const session = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment,});fire(DONE_EVENT); // no listener registered: stays queueddiff --git a/packages/core/test/builtin-agents.test.ts b/packages/core/test/builtin-agents.test.tsindex 4f7ef1e4..d09faf4b 100644--- a/packages/core/test/builtin-agents.test.ts+++ b/packages/core/test/builtin-agents.test.ts@@ -17,7 +17,7 @@ import {DEFAULT_AGENT_ID,DEFAULT_PROJECT_ID,listInstalledSkills,- loadOrInitAgentState,+ loadAgentState,provisionProjectAgents,skillsDir,} from "../src/state/index.js";@@ -45,7 +45,7 @@ const skillMdPath = (agentId: string, skillName: string): string =>describe("Skill installation policy", () => {it("a plain new Agent preinstalls no Skills and AGENTS.md is an empty file (guidance lives in the template's Suggested workflows)", async () => {- const state = await loadOrInitAgentState({ agentId: "some_agent" });+ const state = await loadAgentState({ init: {}, agentId: "some_agent" });expect(await listInstalledSkills(tmpRoot, DEFAULT_PROJECT_ID, "some_agent")).toEqual([]);// The default AGENTS.md is empty: it carries no preset guidance (delegation and task@@ -60,7 +60,7 @@ describe("Skill installation policy", () => {});it("a default_agent created directly without a preset (e.g. first CLI run) likewise gets the library's preinstalled set", async () => {- await loadOrInitAgentState({ agentId: DEFAULT_AGENT_ID });+ await loadAgentState({ init: {}, agentId: DEFAULT_AGENT_ID });const names = (await listInstalledSkills(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID)).map((s) => s.name,);@@ -80,7 +80,7 @@ describe("provisionProjectAgents", () => {expect(BUILTIN_AGENT_IDS).toEqual([DEFAULT_AGENT_ID]);// name/description are written into system_config; AGENTS.md is an empty file.- const state = await loadOrInitAgentState({ agentId: DEFAULT_AGENT_ID });+ const state = await loadAgentState({ init: {}, agentId: DEFAULT_AGENT_ID });expect(state.systemConfig.name).toBe("General Agent");expect(state.systemConfig.description).toBeTruthy();expect(state.agentsMd).toBe("");@@ -111,7 +111,7 @@ describe("provisionProjectAgents", () => {it("an existing Agent is not overwritten (the preset only applies at initialization)", async () => {const custom = "# AGENTS.md\n\nContent the user edited themselves\n";- await loadOrInitAgentState({ agentId: DEFAULT_AGENT_ID });+ await loadAgentState({ init: {}, agentId: DEFAULT_AGENT_ID });await fs.writeFile(agentsMdPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID), custom, "utf8");await provisionProjectAgents();@@ -126,7 +126,7 @@ describe("provisionProjectAgents", () => {describe("App Data Dir / Agent ID placeholders", () => {it("assembleSystemPrompt injects App Data Dir and Agent ID (Skill lookup uses app-data-dir-relative paths, no .penguin dependency)", async () => {- const state = await loadOrInitAgentState({ agentId: "env_agent" });+ const state = await loadAgentState({ init: {}, agentId: "env_agent" });// Skill data provided (an empty list) so the {{SKILLS}} section — home of the skill// lookup path convention this test pins — renders.const prompt = assembleSystemPrompt(diff --git a/packages/core/test/command-policy.test.ts b/packages/core/test/command-policy.test.tsindex 2702483b..f30acb0c 100644--- a/packages/core/test/command-policy.test.ts+++ b/packages/core/test/command-policy.test.ts@@ -343,9 +343,33 @@ describe("withCommandPolicy (the approval-boundary wrapper)", () => {});it("a disabled policy delegates every call, vetoed or not", async () => {- const guarded = withCommandPolicy(async () => "allow", { enabled: false });+ const guarded = withCommandPolicy(+ async () => "allow",+ () => ({ enabled: false }),+ );expect(await guarded(call("rm -rf /") as never)).toBe("allow");});++ it("consults the policy source at every decision, so a mid-run rotation swaps what later calls see", async () => {+ // The source answers with the running context's policy from memory; consulting it per+ // call is what hands the tool calls after a mid-run rotation the new context's policy.+ let policy: { enabled: boolean } = { enabled: false };+ const guarded = withCommandPolicy(+ async () => "allow",+ () => policy,+ );+ expect(await guarded(call("rm -rf /") as never)).toBe("allow");+ policy = { enabled: true };+ expect(await guarded(call("rm -rf /") as never)).toBe("forbidden");+ // A source that cannot be read fails toward the factory rules, never toward allow.+ const failing = withCommandPolicy(+ async () => "allow",+ () => {+ throw new Error("unreadable");+ },+ );+ expect(await failing(call("rm -rf /") as never)).toBe("forbidden");+ });});describe("Session applies the policy at the approval boundary", () => {@@ -404,8 +428,7 @@ describe("Session applies the policy at the approval boundary", () => {// No commandPolicy in the config: the factory rule set applies, on.const session = new Session({meta: meta(),- bootstrap: async () => ({ tools: [], llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment,imagesDir: path.join(tmp, "images"),modelHasVision: true,@@ -466,12 +489,11 @@ describe("Session applies the policy at the approval boundary", () => {};const session = new Session({meta: meta(),- bootstrap: async () => ({ tools: [], llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment,imagesDir: path.join(tmp, "images"),modelHasVision: true,- commandPolicy: { enabled: false },+ commandPolicy: () => ({ enabled: false }),});for await (const _ of session.run([userText("clean up")], {diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.tsindex ee2a24f5..0d902ec5 100644--- a/packages/core/test/compaction.test.ts+++ b/packages/core/test/compaction.test.ts@@ -29,6 +29,8 @@ import {assistantText,compactionBegin,compactionEnd,+ mcpConnectBegin,+ mcpConnectEnd,partialText,requestBegin,requestEnd,@@ -37,14 +39,15 @@ import {tokenUsage,toolCall,toolCallOutput,+ toolListReady,userText,} from "../src/omnimessage/index.js";import type {CompactionBeginPayload,CompactionEndPayload,OmniMessage,+ SessionMetaPayload,TextPayload,- TokenCounts,TokenUsagePayload,} from "../src/omnimessage/index.js";import type {@@ -198,7 +201,6 @@ describe("context compaction", () => {[{ messages: [assistantText("answer two"), usage(20, 330)] }],"llm2",);- let factoryTokens: TokenCounts | null = null;const trace = new Writer({ tracesDir: traces, sessionId: "sess_compact" });const engine = new ContextEngine({llm: llm1,@@ -206,10 +208,7 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: (tokens) => {- factoryTokens = tokens;- return llm2;- },+ openNextContext: () => ({ llm: llm2 }),});const oldPath = trace.currentPath();@@ -248,11 +247,12 @@ describe("context compaction", () => {.map(textOf);expect(textBetween).toEqual(["[summary]the distilled summary[/summary]"]);- // The new LLM instance carries over the session's cumulative tokens (including compaction request usage).- expect(factoryTokens).toMatchObject({ total: 310 });-// The summary is merged with the next user prompt as the new LLM instance's first input.- await collect(engine.run([userText("task two")], { approve: allowAll }));+ const out2 = await collect(engine.run([userText("task two")], { approve: allowAll }));+ // The engine authors the session series itself: the new context's token_usage continues+ // from 310 (compaction request usage included) — nothing is seeded on the LLM object.+ const usage2 = out2.find((m) => (m.payload as { type?: string }).type === "token_usage")!;+ expect((usage2.payload as TokenUsagePayload).session.total).toBe(330);expect(llm1.calls).toHaveLength(2);expect(llm2.calls).toHaveLength(1);const firstInput = llm2.calls[0]!.map(textOf);@@ -269,6 +269,8 @@ describe("context compaction", () => {const newTrace = await readTrace(trace.currentPath());expect(trace.currentPath()).not.toBe(oldPath);expect(newTrace[0]!.type).toBe("session_meta");+ // The opened context brought no meta of its own, so the new file repeats the first one's.+ expect(newTrace[0]!.payload).toEqual(metaMessage.payload);expect(newTrace.some((m) =>((m.payload as { text?: string }).text ?? "").startsWith("[context_summary]"),@@ -276,6 +278,254 @@ describe("context compaction", () => {).toBe(true);});+ it("the rotated Trace file opens with the meta the new context was opened with, and a later context without one keeps it", async () => {+ // The composition layer re-assembles the system prompt for each context and hands the+ // engine the session_meta recording it: that meta — not the Session's first — is what the+ // rotated file must start with, so every file's head describes the context it records.+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ { messages: [assistantText("[summary]one[/summary]"), usage(160, 310)] },+ ],+ "llm1",+ );+ const llm2 = new ScriptedLLM(+ [+ { messages: [assistantText("answer two"), usage(150, 460)] },+ { messages: [assistantText("[summary]two[/summary]"), usage(160, 620)] },+ ],+ "llm2",+ );+ const llm3 = new ScriptedLLM(+ [{ messages: [assistantText("answer three"), usage(20, 640)] }],+ "llm3",+ );+ const refreshed = sessionMeta({+ ...(metaMessage.payload as SessionMetaPayload),+ system_prompt: "sp re-assembled for context two",+ });+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_meta_rotation" });+ let opened = 0;+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ compaction: settings(),+ // Context two brings its meta; context three brings none (an opener that could not+ // re-assemble) and must inherit context two's, not fall back to the Session's first.+ openNextContext: async () => {+ opened += 1;+ return opened === 1 ? { llm: llm2, sessionMeta: refreshed } : { llm: llm3 };+ },+ });+ const firstPath = trace.currentPath();++ await collect(engine.run([userText("task one")], { approve: allowAll }));+ await collect(engine.run([userText("task two")], { approve: allowAll }));+ const secondPath = trace.currentPath();+ expect(secondPath).not.toBe(firstPath);+ const second = await readTrace(secondPath);+ expect(second[0]!.type).toBe("session_meta");+ expect((second[0]!.payload as SessionMetaPayload).system_prompt).toBe(+ "sp re-assembled for context two",+ );++ await collect(engine.run([userText("task three")], { approve: allowAll }));+ const thirdPath = trace.currentPath();+ expect(thirdPath).not.toBe(secondPath);+ const third = await readTrace(thirdPath);+ expect(third[0]!.type).toBe("session_meta");+ expect((third[0]!.payload as SessionMetaPayload).system_prompt).toBe(+ "sp re-assembled for context two",+ );+ expect(opened).toBe(2);+ });++ it("records the opener publishes are yielded live and written at the rotated file's head after the meta; a context that publishes none keeps the previous records", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ { messages: [assistantText("[summary]one[/summary]"), usage(160, 310)] },+ ],+ "llm1",+ );+ const llm2 = new ScriptedLLM(+ [+ { messages: [assistantText("answer two"), usage(150, 460)] },+ { messages: [assistantText("[summary]two[/summary]"), usage(160, 620)] },+ ],+ "llm2",+ );+ const llm3 = new ScriptedLLM(+ [{ messages: [assistantText("answer three"), usage(20, 640)] }],+ "llm3",+ );+ const firstToolList = toolListReady([{ name: "old_tool", description: "context one's" }]);+ const connectBegin = mcpConnectBegin(["fx"]);+ const connectEnd = mcpConnectEnd({ status: "completed", results: [] });+ const newToolList = toolListReady([{ name: "new_tool", description: "context two's" }]);+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_records" });+ let opened = 0;+ let beginSeen = false;+ let beginSeenBeforeEnd: boolean | null = null;+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ toolList: firstToolList,+ // What the Session hands a first run: the (here empty) connect pair, so the first+ // context's toolset record takes the bootstrap path — after the input, not at a head.+ bootstrapRecords: [],+ compaction: settings(),+ openNextContext: async ({ emit }) => {+ opened += 1;+ if (opened === 2) return { llm: llm3 };+ emit(connectBegin);+ // The connect takes a while: the consumer must have received the begin by the time+ // the end exists, or a slow MCP server would be a silent gap on the stream.+ await new Promise((resolve) => setTimeout(resolve, 20));+ beginSeenBeforeEnd = beginSeen;+ emit(connectEnd);+ emit(newToolList);+ return { llm: llm2 };+ },+ });+ const firstPath = trace.currentPath();++ const out1: OmniMessage[] = [];+ for await (const msg of engine.run([userText("task one")], { approve: allowAll })) {+ out1.push(msg);+ if (msg === connectBegin) beginSeen = true;+ }+ // Live: the records follow the compaction_end on the stream, in publication order, and+ // the begin was delivered while the opener was still connecting.+ const types = payloadTypes(out1);+ expect(types.slice(types.lastIndexOf("compaction_end") + 1)).toEqual([+ "mcp_connect_begin",+ "mcp_connect_end",+ "tool_list_ready",+ ]);+ expect(beginSeenBeforeEnd).toBe(true);++ // Trace: the rotated file opens with the meta, then exactly those records, then the+ // context's first input (the summary).+ await collect(engine.run([userText("task two")], { approve: allowAll }));+ const secondPath = trace.currentPath();+ expect(secondPath).not.toBe(firstPath);+ const second = await readTrace(secondPath);+ expect(second[0]!.type).toBe("session_meta");+ expect(payloadTypes(second.slice(1, 4))).toEqual([+ "mcp_connect_begin",+ "mcp_connect_end",+ "tool_list_ready",+ ]);+ expect((second[3]!.payload as { tools: { name: string }[] }).tools[0]!.name).toBe("new_tool");+ expect(textOf(second[4]!)).toContain("[context_summary]");+ // The first file's toolset record rode the first run's bootstrap path (after the input),+ // and it is the first context's — the new one never leaks backwards.+ const first = await readTrace(firstPath);+ expect(payloadTypes(first.slice(0, 2))).toEqual(["text", "tool_list_ready"]);+ expect((first[1]!.payload as { tools: { name: string }[] }).tools[0]!.name).toBe("old_tool");+ expect(payloadTypes(first).filter((t) => t === "tool_list_ready")).toHaveLength(1);++ // Context three's opener published nothing (it could not re-read the Agent State): the+ // third file repeats context two's records, never falls back to the first context's.+ await collect(engine.run([userText("task three")], { approve: allowAll }));+ const thirdPath = trace.currentPath();+ expect(thirdPath).not.toBe(secondPath);+ const third = await readTrace(thirdPath);+ expect(third[0]!.type).toBe("session_meta");+ expect(payloadTypes(third.slice(1, 4))).toEqual([+ "mcp_connect_begin",+ "mcp_connect_end",+ "tool_list_ready",+ ]);+ expect((third[3]!.payload as { tools: { name: string }[] }).tools[0]!.name).toBe("new_tool");+ expect(opened).toBe(2);+ });++ it("an opener that throws fails the run and leaves the engine on the old context, with no rotation pending", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ { messages: [assistantText("[summary]one[/summary]"), usage(160, 310)] },+ { messages: [assistantText("still the old context"), usage(20, 330)] },+ ],+ "llm1",+ );+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_opener_throws" });+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ compaction: settings(),+ openNextContext: () => {+ throw new Error("Invalid Agent State config");+ },+ });+ const firstPath = trace.currentPath();++ await expect(+ collect(engine.run([userText("task one")], { approve: allowAll })),+ ).rejects.toThrow("Invalid Agent State config");++ // The old LLM object is still current and nothing rotates: the next run appends to the+ // same file and goes to the same object.+ const out = await collect(engine.run([userText("task two")], { approve: allowAll }));+ expect(out.map((m) => (m.payload as { text?: string }).text)).toContain(+ "still the old context",+ );+ expect(trace.currentPath()).toBe(firstPath);+ expect(llm1.calls).toHaveLength(3);+ });++ it("an opened context's maxTurns and compaction settings replace the engine's from then on", async () => {+ // Context one compacts at 100. The opened context raises the threshold to 1000 and caps a+ // Task at one turn: task two's 150-token turn must not compact again, and its tool call+ // must end the Task at the cap instead of being followed up.+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ { messages: [assistantText("[summary]one[/summary]"), usage(160, 310)] },+ ],+ "llm1",+ );+ const llm2 = new ScriptedLLM(+ [+ {+ messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "c1" }), usage(150, 460)],+ },+ { messages: [assistantText("never requested"), usage(10, 470)] },+ ],+ "llm2",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ compaction: settings(),+ openNextContext: () => ({+ llm: llm2,+ maxTurns: 1,+ compaction: settings({ maxContextLength: 1000 }),+ }),+ });++ await collect(engine.run([userText("task one")], { approve: allowAll }));+ const out = await collect(engine.run([userText("task two")], { approve: allowAll }));+ expect(compactionEvents(out)).toEqual([]);+ expect(+ out.some(+ (m) =>+ (m.payload as { type?: string }).type === "text" &&+ textOf(m).includes("reached max turns (1)"),+ ),+ ).toBe(true);+ expect(llm2.calls).toHaveLength(1);+ });+it("summarize mid-task: tool outputs pair into the compaction request, summary alone feeds the new LLM", async () => {const llm1 = new ScriptedLLM([@@ -297,7 +547,7 @@ describe("context compaction", () => {environment: fakeEnvironment,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const out = await collect(engine.run([userText("do task")], { approve: allowAll }));@@ -351,9 +601,9 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => {+ openNextContext: () => {created += 1;- return llm2;+ return { llm: llm2 };},});const oldPath = trace.currentPath();@@ -413,7 +663,7 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const oldPath = trace.currentPath();@@ -446,7 +696,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm1,+ openNextContext: () => ({ llm: llm1 }),compactionMaxReconnects: 1,reconnectBackoffMs: 1,});@@ -488,7 +738,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),maxReconnects: 4,reconnectBackoffMs: 1,});@@ -520,7 +770,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),compactionMaxReconnects: 2,reconnectBackoffMs: 1,});@@ -557,7 +807,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm1,+ openNextContext: () => ({ llm: llm1 }),maxReconnects: 8,compactionMaxReconnects: 2,reconnectBackoffMs: 1,@@ -620,9 +870,9 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => {+ openNextContext: () => {created += 1;- return new ScriptedLLM([], "llm2");+ return { llm: new ScriptedLLM([], "llm2") };},compactionMaxReconnects: 4,reconnectBackoffMs: 1,@@ -710,9 +960,9 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => {+ openNextContext: () => {created += 1;- return new ScriptedLLM([], "llm2");+ return { llm: new ScriptedLLM([], "llm2") };},compactionMaxReconnects: 4,reconnectBackoffMs: 1,@@ -798,15 +1048,11 @@ describe("context compaction", () => {"llm1",);const llm2 = new ScriptedLLM([{ messages: [assistantText("fresh"), usage(20, 500)] }], "llm2");- let factoryTokens: TokenCounts | null = null;const engine = new ContextEngine({llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: (tokens) => {- factoryTokens = tokens;- return llm2;- },+ openNextContext: () => ({ llm: llm2 }),compactionMaxReconnects: 4,reconnectBackoffMs: 1,});@@ -830,11 +1076,11 @@ describe("context compaction", () => {expect(usageBetween.map((m) => (m.payload as TokenUsagePayload).request.total)).toEqual([160, 170,]);- // Session cumulative tokens carried into the new instance include the rejected attempts' usage.- expect(factoryTokens).toMatchObject({ total: 480 });-- // The new context opens with the 5th attempt's summary.- await collect(engine.run([userText("task two")], { approve: allowAll }));+ // The new context opens with the 5th attempt's summary; the engine-authored session+ // series continues from 480 (the rejected attempts' usage included).+ const out2 = await collect(engine.run([userText("task two")], { approve: allowAll }));+ const usage2 = out2.find((m) => (m.payload as { type?: string }).type === "token_usage")!;+ expect((usage2.payload as TokenUsagePayload).session.total).toBe(500);expect(llm1.calls).toHaveLength(6);expect(llm2.calls[0]!.map(textOf)).toEqual(["[context_summary]\nfifth attempt wins\n[/context_summary]",@@ -871,7 +1117,7 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),reconnectBackoffMs: 1,});const oldPath = trace.currentPath();@@ -942,7 +1188,7 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const oldPath = trace.currentPath();@@ -1000,9 +1246,9 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => {+ openNextContext: () => {created += 1;- return new ScriptedLLM([], "llm2");+ return { llm: new ScriptedLLM([], "llm2") };},compactionMaxReconnects: 4,reconnectBackoffMs: 1,@@ -1066,7 +1312,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),compactionMaxReconnects: 4,reconnectBackoffMs: 1,});@@ -1113,7 +1359,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),compactionMaxReconnects: 1,reconnectBackoffMs: 1,});@@ -1152,7 +1398,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),reconnectBackoffMs: 1,});@@ -1223,7 +1469,7 @@ describe("context compaction", () => {llm: model,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),});const out = await collect(engine.run([userText("go")], { approve: allowAll }));@@ -1258,7 +1504,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings({ maxContextLength: -1, maxSessionTurns: 2 }),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});// Triggers right at task 1's wrap-up (compacts as soon as the threshold is reached, without waiting for the next task); the summary request goes to the old instance.@@ -1292,7 +1538,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const out = await collect(engine.run([userText("go")], { approve: allowAll }));@@ -1325,7 +1571,7 @@ describe("context compaction", () => {trace,sessionMeta: metaMessage,compaction: settings({ mode: "discard" }),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const oldPath = trace.currentPath();@@ -1362,7 +1608,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});await collect(engine.run([userText("go")], { approve: allowAll }));@@ -1393,7 +1639,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),reconnectBackoffMs: 1,});@@ -1427,7 +1673,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});await collect(engine.run([userText("hi")], { approve: allowAll }));@@ -1463,7 +1709,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),compactionMaxReconnects: 1,reconnectBackoffMs: 1,});@@ -1512,7 +1758,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),compactionMaxReconnects: 4,reconnectBackoffMs: 1,});@@ -1542,7 +1788,7 @@ describe("context compaction", () => {expect(textOf(run3[1]!)).toBe("run3");});- it("no compaction capability (createLLM missing) means thresholds never fire and compact() is a no-op", async () => {+ it("no compaction capability (openNextContext missing) means thresholds never fire and compact() is a no-op", async () => {const llm1 = new ScriptedLLM([{ messages: [assistantText("big"), usage(999999, 999999)] }],"llm1",@@ -1568,7 +1814,7 @@ describe("context compaction", () => {// have sessionTurns == 0, but they're two completely different messages to the user: telling// someone who just finished compacting that there's "no completed conversation turn yet" is// effectively saying nothing useful.- // The compaction request goes to the **current** LLM (the script's second entry); createLLM+ // The compaction request goes to the **current** LLM (the script's second entry); openNextContext// supplies the LLM used for the new context after compaction.const llm1 = new ScriptedLLM([@@ -1580,7 +1826,7 @@ describe("context compaction", () => {);const llm2 = new ScriptedLLM([{ messages: [assistantText("after"), usage(5, 20)] }], "llm2");- // (1) No compaction capability configured (no compaction / createLLM).+ // (1) No compaction capability configured (no compaction / openNextContext).const noCap = new ContextEngine({ llm: llm1, environment: fakeEnvironment });expect(noCap.compactability()).toBe("unsupported");@@ -1589,7 +1835,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});expect(engine.compactability()).toBe("empty");expect(await collect(engine.compact())).toHaveLength(0);@@ -1617,7 +1863,7 @@ describe("context compaction", () => {llm: new ScriptedLLM([]),environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([]),+ openNextContext: () => ({ llm: new ScriptedLLM([]) }),initialState: { sessionTurns: 4 },});expect(withTurns.compactability()).toBe("ok");@@ -1627,7 +1873,7 @@ describe("context compaction", () => {llm: new ScriptedLLM([]),environment: fakeEnvironment,compaction: settings(),- createLLM: () => new ScriptedLLM([]),+ openNextContext: () => ({ llm: new ScriptedLLM([]) }),initialState: { sessionTurns: 0, fromCompaction: true },});expect(justCompacted.compactability()).toBe("just_compacted");@@ -1643,15 +1889,14 @@ describe("context compaction", () => {const written: OmniMessage[] = [];const session = new Session({meta: metaMessage.payload,- bootstrap: async () => ({ tools: [], llm: resumedLLM, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: resumedLLM }),environment: fakeEnvironment,trace: {write: async (msg) => {written.push(msg);},},- createLLM: () => newContextLLM,+ openNextContext: () => ({ llm: newContextLLM }),compaction: settings(),// What agent.resumeSession derives from the Trace: three completed turns of history.metaAlreadyWritten: true,@@ -1683,16 +1928,15 @@ describe("context compaction", () => {meta: metaMessage.payload,bootstrap: async () => {bootstrapped = true;- return { tools: [], llm: new ScriptedLLM([]), mcp: [] };+ return { llm: new ScriptedLLM([]) };},- mcpServers: [],environment: fakeEnvironment,trace: {write: async (msg) => {written.push(msg);},},- createLLM: () => new ScriptedLLM([]),+ openNextContext: () => ({ llm: new ScriptedLLM([]) }),compaction: settings(),imagesDir: "/tmp/penguin-test-scratch",modelHasVision: true,@@ -1720,7 +1964,7 @@ describe("context compaction", () => {llm: llm1,environment: fakeEnvironment,compaction: settings(),- createLLM: () => llm1,+ openNextContext: () => ({ llm: llm1 }),});// The abort signal is already pending before the compaction request: the fake LLM finishes straight to aborted.const approveThenAbort: ApproveFn = async () => "allow";@@ -1787,7 +2031,7 @@ describe("compaction summary streaming (issue #290)", () => {trace,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),});const oldPath = trace.currentPath();@@ -1832,7 +2076,7 @@ describe("compaction summary streaming (issue #290)", () => {environment: fakeEnvironment,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),});const out = await collect(engine.run([userText("task one")], { approve: allowAll }));@@ -1955,7 +2199,7 @@ describe("mid-task compaction runs the tools first (issue #288)", () => {environment: fakeEnvironment,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => llm2,+ openNextContext: () => ({ llm: llm2 }),});const out = await collect(engine.run([userText("go")], { approve: allowAll }));@@ -2004,7 +2248,9 @@ describe("mid-task compaction runs the tools first (issue #288)", () => {environment: env,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => new ScriptedLLM([{ messages: [assistantText("done"), usage(1, 1)] }], "l2"),+ openNextContext: () => ({+ llm: new ScriptedLLM([{ messages: [assistantText("done"), usage(1, 1)] }], "l2"),+ }),});const gen = engine.run([userText("go")], { approve: allowAll });@@ -2064,7 +2310,9 @@ describe("mid-task compaction runs the tools first (issue #288)", () => {environment: failingEnv,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ openNextContext: () => ({+ llm: new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ }),});await collect(engine.run([userText("go")], { approve: allowAll }));@@ -2088,7 +2336,9 @@ describe("mid-task compaction runs the tools first (issue #288)", () => {environment: fakeEnvironment,sessionMeta: metaMessage,compaction: settings(),- createLLM: () => new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ openNextContext: () => ({+ llm: new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ }),});await collect(engine.run([userText("go")], { approve: async () => "deny" }));@@ -2111,7 +2361,7 @@ describe("mid-task compaction runs the tools first (issue #288)", () => {environment: fakeEnvironment,sessionMeta: metaMessage,compaction: settings({ maxContextLength: 100000 }),- createLLM: () => new ScriptedLLM([], "llm2"),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),});await collect(engine.run([userText("hi")], { approve: allowAll }));await collect(engine.compact());diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.tsindex 6dbc43c7..cb699685 100644--- a/packages/core/test/engine.test.ts+++ b/packages/core/test/engine.test.ts@@ -33,7 +33,12 @@ import type {LLMInterface,LLMOutcome,} from "../src/interfaces/index.js";-import type { OmniMessage, TextPayload, ToolCallPayload } from "../src/omnimessage/index.js";+import type {+ OmniMessage,+ TextPayload,+ TokenUsagePayload,+ ToolCallPayload,+} from "../src/omnimessage/index.js";import { Environment } from "../src/environment/index.js";import { Writer, readTrace } from "../src/trace/index.js";import { ContextEngine, reconnectDelayMs } from "../src/engine/context-engine.js";@@ -536,6 +541,31 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {expect(fedBack).toBeDefined();});+ it("stamps the Session token series onto token_usage before it is yielded or written", async () => {+ // The LLM reports per-request counts only (12 then 20 here; its session slot is a+ // stand-in) and the engine authors the cumulative series. Consumers serialize at yield+ // time (an SSE wire) and the Trace serializes inside the write, so the stamp must land+ // before either — an in-memory reference fixed up later would hide the difference.+ const llm = new FakeLLM();+ const environment = new Environment({+ workspaceDir: workspace,+ toolConfig: execCommandToolConfig(),+ });+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_series" });+ const engine = new ContextEngine({ llm, environment, trace });+ const yielded: number[] = [];+ for await (const msg of engine.run([userText("go")], { approve: allowAll })) {+ const p = msg.payload as { type?: string };+ if (p.type !== "token_usage") continue;+ yielded.push((JSON.parse(JSON.stringify(p)) as TokenUsagePayload).session.total);+ }+ expect(yielded).toEqual([12, 32]);+ const written = (await readTrace(trace.currentPath()))+ .filter((m) => (m.payload as { type?: string }).type === "token_usage")+ .map((m) => (m.payload as TokenUsagePayload).session.total);+ expect(written).toEqual([12, 32]);+ });+it("engine maxTurns fallback is -1 (unlimited) when the option is omitted (direct SDK construction)", () => {const engine = new ContextEngine({llm: new FakeLLM(),@@ -1029,8 +1059,10 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {).toBe(false);expect(recorded.filter((m) => (m.payload as { text?: string }).text === "go")).toHaveLength(1);});+});- it("forwards RunOptions.thinkingLevel to every LLM request of the run (reconnects included); compaction keeps the default", async () => {+describe("ContextEngine live thinking level (the soft-limited runtime parameter)", () => {+ it("applies setThinkingLevel to every turn request — reconnects included — while compaction requests keep the context default", async () => {const levels: (string | undefined)[] = [];let calls = 0;const llm: LLMInterface = {@@ -1038,14 +1070,14 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {calls += 1;levels.push(params.thinkingLevel);if (calls === 1) {- // First attempt drops: the reconnect retry must carry the same per-turn level.+ // First attempt drops: the reconnect retry re-reads the live level.yield assistantText("half", "retryable");return { status: "retryable" };}if (calls === 2) {// Retry completes with usage above the compaction threshold → a Task-boundary- // summarize compaction issues one more request (the engine's, not this run's turn):- // it must NOT carry the per-turn override.+ // summarize compaction issues one more request (the engine's, not a turn): it+ // must NOT carry the live override — its prefix stays the context's own.yield assistantText("recovered");yield tokenUsage(emptyTokenCounts(), {cache_read: 0,@@ -1065,29 +1097,44 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {return { status: "completed" };},};- const environment = new Environment({- workspaceDir: workspace,- toolConfig: execCommandToolConfig(),- });+ const environment: EnvironmentInterface = {+ async listTools() {+ return [];+ },+ async *executeTool() {+ // No tool ever runs in this test.+ },+ toolPermission() {+ return "rw";+ },+ };const engine = new ContextEngine({llm,environment,maxReconnects: 1,reconnectBackoffMs: 1,- createLLM: () => llm,+ openNextContext: () => ({ llm: llm }),compaction: { maxContextLength: 10, maxSessionTurns: -1, mode: "summarize", prompt: "SUM" },});- const all: OmniMessage[] = [];- for await (const msg of engine.run([userText("go")], {- approve: allowAll,- thinkingLevel: "high",- })) {- all.push(msg);- }+ engine.setThinkingLevel("high");+ await collectRun(engine, [userText("go")], allowAll);expect(calls).toBe(3);- // Turn attempt + reconnect retry carry the run's level; the compaction request does not.+ // Turn attempt + reconnect retry carry the live level; the compaction request does not.expect(levels).toEqual(["high", "high", undefined]);++ // A re-pin between runs is picked up by the next request without any rotation.+ engine.setThinkingLevel("low");+ const llm2Levels: (string | undefined)[] = [];+ (llm as { streamGenerate: unknown }).streamGenerate = async function* (params: {+ thinkingLevel?: string;+ }) {+ llm2Levels.push(params.thinkingLevel);+ yield assistantText("again");+ return { status: "completed" };+ };+ await collectRun(engine, [userText("next")], allowAll);+ expect(llm2Levels).toEqual(["low"]);});});@@ -3050,7 +3097,7 @@ describe("ContextEngine mid-run steering ([user_steering])", () => {const engine = new ContextEngine({llm: oldLLM,environment: steeringEnvironment(),- createLLM: () => newLLM,+ openNextContext: () => ({ llm: newLLM }),compaction: {maxContextLength: 1000,maxSessionTurns: -1,diff --git a/packages/core/test/environment.test.ts b/packages/core/test/environment.test.tsindex e916eea0..9485cee5 100644--- a/packages/core/test/environment.test.ts+++ b/packages/core/test/environment.test.ts@@ -208,6 +208,72 @@ describe("Environment.executeTool — vault env injection", () => {env.dispose();});+ it("reconfigure replaces the toolset and the vault as a whole; commands spawned afterwards see the new vault", async () => {+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: makeToolConfig(),+ vault: { PENGUIN_VAULT_TEST_KEY: "old-value" },+ });+ try {+ expect((await env.listTools()).map((t) => t.name)).toEqual(["exec_command"]);++ // A context without exec_command: the tool is neither listed nor executable.+ env.reconfigure({ toolConfig: { customTools: [], mcpServers: [] }, vault: {} });+ expect(await env.listTools()).toEqual([]);+ expect(env.toolPermission("exec_command")).toBeUndefined();+ const gone = await collect(+ env.executeTool({+ toolCall: toolCall({+ name: "exec_command",+ arguments: JSON.stringify({ cmd: "echo nope" }),+ toolCallId: "call_gone",+ }),+ }),+ );+ expect((gone[gone.length - 1]!.payload as { output?: string }).output).toContain(+ "Unknown tool: exec_command",+ );++ // Re-equipped with the tool and a new vault: a command spawned now carries the new+ // values (and only those — the replaced entry is gone, not merged).+ env.reconfigure({+ toolConfig: makeToolConfig(),+ vault: { PENGUIN_VAULT_TEST_KEY: "new-value", PENGUIN_VAULT_ADDED: "added" },+ });+ expect(env.toolPermission("exec_command")).toBe("rw");+ const messages = await collect(+ env.executeTool({+ toolCall: toolCall({+ name: "exec_command",+ arguments: JSON.stringify({+ cmd: 'echo "k=$PENGUIN_VAULT_TEST_KEY added=$PENGUIN_VAULT_ADDED"',+ }),+ toolCallId: "call_revault",+ }),+ }),+ );+ const last = messages[messages.length - 1]!.payload as { output?: string };+ expect(last.output).toContain("k=new-value added=added");++ // An empty vault clears it (the vault is replaced as a whole, never merged).+ env.reconfigure({ toolConfig: makeToolConfig(), vault: {} });+ const cleared = await collect(+ env.executeTool({+ toolCall: toolCall({+ name: "exec_command",+ arguments: JSON.stringify({ cmd: 'echo "k=[$PENGUIN_VAULT_TEST_KEY]"' }),+ toolCallId: "call_cleared",+ }),+ }),+ );+ expect((cleared[cleared.length - 1]!.payload as { output?: string }).output).toContain(+ "k=[]",+ );+ } finally {+ env.dispose();+ }+ });+it("leaves the command env untouched when no vault is configured", async () => {const env = new Environment({workspaceDir: tmp,diff --git a/packages/core/test/example-benchmark.test.ts b/packages/core/test/example-benchmark.test.tsindex 9ec8802d..b5d3e825 100644--- a/packages/core/test/example-benchmark.test.ts+++ b/packages/core/test/example-benchmark.test.ts@@ -16,7 +16,7 @@ import {EXAMPLE_BENCHMARK_ID,benchmarksDir,buildExampleScoreboard,- loadOrInitAgentState,+ loadAgentState,provisionProjectAgents,} from "../src/state/index.js";@@ -67,7 +67,7 @@ interface Evaluation extends Omit<CaseScore, "case" | "runs"> {describe("example benchmark provisioning", () => {it("default_agent init creates a parseable example benchmark (config + scoreboard + cases)", async () => {- await loadOrInitAgentState();+ await loadAgentState({ init: {} });const dir = path.join(benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID),EXAMPLE_BENCHMARK_ID,@@ -165,14 +165,14 @@ describe("example benchmark provisioning", () => {});it("does not create benchmarks for a non-default agent", async () => {- await loadOrInitAgentState({ agentId: "worker" });+ await loadAgentState({ init: {}, agentId: "worker" });expect(await exists(benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, "worker"))).toBe(false);});it("skips provisioning when benchmarks/ already exists (idempotent, no clobber)", async () => {const dir = benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);await fs.mkdir(dir, { recursive: true });- await loadOrInitAgentState();+ await loadAgentState({ init: {} });expect(await fs.readdir(dir)).toEqual([]);});});diff --git a/packages/core/test/goal.test.ts b/packages/core/test/goal.test.tsindex 83ebf10c..af4973e1 100644--- a/packages/core/test/goal.test.ts+++ b/packages/core/test/goal.test.ts@@ -541,8 +541,7 @@ describe("Session.runGoal input", () => {};return new Session({meta,- bootstrap: async () => ({ tools: [], llm: fakeLLM(completeOn), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: fakeLLM(completeOn) }),environment: fakeEnvironment,imagesDir: path.join(dir, "scratchpad", "session-1"),modelHasVision: true,diff --git a/packages/core/test/input-images.test.ts b/packages/core/test/input-images.test.tsindex bf74ffc8..d04df3f9 100644--- a/packages/core/test/input-images.test.ts+++ b/packages/core/test/input-images.test.ts@@ -226,8 +226,7 @@ describe("Session input-image wiring", () => {});session = new Session({meta: meta(),- bootstrap: async () => ({ tools: [], llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment: fakeEnvironment,imagesDir: await unwritableDir(),modelHasVision: false,@@ -258,8 +257,7 @@ describe("Session input-image wiring", () => {};session = new Session({meta: meta(),- bootstrap: async () => ({ tools: [], llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment: fakeEnvironment,imagesDir: await unwritableDir(),modelHasVision: true,diff --git a/packages/core/test/kernel-version.test.ts b/packages/core/test/kernel-version.test.tsindex 052d9b26..95173843 100644--- a/packages/core/test/kernel-version.test.ts+++ b/packages/core/test/kernel-version.test.ts@@ -29,7 +29,7 @@ import {defaultSystemConfig,isKernelOutdated,kernelTabHash,- loadOrInitAgentState,+ loadAgentState,resetSystemConfigToDefaults,systemConfigPath,type KernelSupersededTabHashes,@@ -172,7 +172,7 @@ describe("applyKernelUpdate", () => {/** Creates the default agent, then rewrites its config file with the given object. */async function seedConfig(config: Record<string, unknown>): Promise<void> {- await loadOrInitAgentState({ root });+ await loadAgentState({ init: {}, root });await fs.writeFile(configPath(), stringifyYaml(config), "utf8");}@@ -189,7 +189,7 @@ describe("applyKernelUpdate", () => {});it("is a stamped no-op on a freshly created config", async () => {- await loadOrInitAgentState({ root });+ await loadAgentState({ init: {}, root });const before = await readConfig();const result = await update();expect(result).toEqual({ advanced: [], kept: [], kernelVersion: KERNEL_VERSION });@@ -324,7 +324,7 @@ describe("applyKernelUpdate", () => {});it("tolerates dangling/invalid section keys (a hand-edited `tools:` with no value parses as null)", async () => {- await loadOrInitAgentState({ root });+ await loadAgentState({ init: {}, root });await fs.writeFile(configPath(),// `tools` is a dangling key: the whole tab reads absent and must be materialized instead@@ -346,7 +346,7 @@ describe("applyKernelUpdate", () => {});it("preserves YAML comments on untouched content", async () => {- await loadOrInitAgentState({ root });+ await loadAgentState({ init: {}, root });const raw = await fs.readFile(configPath(), "utf8");await fs.writeFile(configPath(),@@ -374,12 +374,12 @@ describe("kernel stamping on the materialization paths", () => {});it("a newly created agent is stamped with the current kernel version", async () => {- const state = await loadOrInitAgentState({ root });+ const state = await loadAgentState({ init: {}, root });expect(state.systemConfig.kernel_version).toBe(KERNEL_VERSION);});it("restore-defaults re-stamps a config that predates the mechanism", async () => {- await loadOrInitAgentState({ root });+ await loadAgentState({ init: {}, root });const configPath = systemConfigPath(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);await fs.writeFile(configPath, "system_prompt: old\nversion: 3\n", "utf8");const written = await resetSystemConfigToDefaults(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);diff --git a/packages/core/test/llm.e2e.test.ts b/packages/core/test/llm.e2e.test.tsindex f894477e..d56e15ee 100644--- a/packages/core/test/llm.e2e.test.ts+++ b/packages/core/test/llm.e2e.test.ts@@ -58,9 +58,6 @@ describe(`GenerativeModel live e2e (${provider?.modelId ?? "skipped"})`, () => {expect(payloadType(last)).toBe("token_usage");const usage = last.payload as { request: { total: number } };expect(usage.request.total).toBeGreaterThan(0);-- // Session-cumulative tokens are also recorded on the instance.- expect(model.sessionTokens.total).toBeGreaterThan(0);},// Live calls have inherent network/server jitter: allow a generous timeout and retries so// one slow API call doesn't fail CI (assertions stay strict; only transient timeouts are tolerated).diff --git a/packages/core/test/mcp-tools.test.ts b/packages/core/test/mcp-tools.test.tsindex a1286ec2..4159cea9 100644--- a/packages/core/test/mcp-tools.test.ts+++ b/packages/core/test/mcp-tools.test.ts@@ -12,7 +12,15 @@ import { z } from "zod";import { Environment } from "../src/environment/index.js";import { McpToolProvider, renderCallToolResult } from "../src/environment/mcp/provider.js";import { Session } from "../src/session.js";-import { assistantText, toolCall, userText } from "../src/omnimessage/index.js";+import {+ assistantText,+ mcpConnectBegin,+ mcpConnectEnd,+ toolCall,+ toolListReady,+ userText,+} from "../src/omnimessage/index.js";+import { mcpConnectOutcome } from "../src/internal/session-support.js";import type { OmniMessage, SessionMetaPayload } from "../src/omnimessage/index.js";import type { LLMInterface, LLMOutcome, MCPServerConfig } from "../src/interfaces/index.js";@@ -112,6 +120,82 @@ describe("renderCallToolResult", () => {});});+describe("Environment.reconfigure with MCP Servers (a new model context's server list)", () => {+ let dir: string;+ let env: Environment;++ beforeAll(async () => {+ dir = await realpath(await mkdtemp(path.join(tmpdir(), "penguin-mcp-reconf-")));+ env = new Environment({+ workspaceDir: dir,+ toolConfig: { customTools: [], mcpServers: [fixtureEntry()] },+ });+ });++ afterAll(async () => {+ env.dispose();+ await rmEventually(dir);+ }, 30_000);++ it("closes the previous context's servers and connects the new list on the next listTools", async () => {+ expect((await env.listTools()).map((t) => t.name)).toContain("mcp__fx__echo");+ expect(env.pendingMcpServerNames()).toEqual([]);++ // A context without servers: nothing listed, the old tool names no longer resolve.+ env.reconfigure({ toolConfig: { customTools: [], mcpServers: [] }, vault: {} });+ expect(env.pendingMcpServerNames()).toEqual([]);+ expect(env.mcpConnectResults()).toEqual([]);+ expect(await env.listTools()).toEqual([]);+ const gone = finalPayload(await runTool(env, "mcp__fx__echo", { text: "x" }));+ expect(gone.stop_reason).toBe("fatal");+ expect(gone.output).toContain("Unknown tool: mcp__fx__echo");++ // A context with the server under a new name: connected afresh, lazily, on listTools —+ // the tools come back under the new prefix and execute.+ env.reconfigure({+ toolConfig: { customTools: [], mcpServers: [{ ...fixtureEntry(), name: "fx2" }] },+ vault: {},+ });+ expect(env.pendingMcpServerNames()).toEqual(["fx2"]);+ expect(env.mcpConnectResults()).toEqual([]);+ expect((await env.listTools()).map((t) => t.name)).toContain("mcp__fx2__echo");+ expect(env.mcpConnectResults()).toEqual([+ expect.objectContaining({ server: "fx2", status: "completed" }),+ ]);+ const echoed = finalPayload(await runTool(env, "mcp__fx2__echo", { text: "hi" }));+ expect(echoed.stop_reason).toBe("completed");+ expect(echoed.output).toBe("echo: hi");++ // The same entry again — a Session compacting every turn must not respawn its servers:+ // nothing is pending, the next listTools runs no connect phase (no outcome to report),+ // and the connection keeps serving.+ env.reconfigure({+ toolConfig: { customTools: [], mcpServers: [{ ...fixtureEntry(), name: "fx2" }] },+ vault: {},+ });+ expect(env.pendingMcpServerNames()).toEqual([]);+ expect((await env.listTools()).map((t) => t.name)).toContain("mcp__fx2__echo");+ expect(env.mcpConnectResults()).toEqual([]);+ const again = finalPayload(await runTool(env, "mcp__fx2__echo", { text: "kept" }));+ expect(again.output).toBe("echo: kept");++ // A changed entry (a new env var for the server) is a different server: reconnected.+ env.reconfigure({+ toolConfig: {+ customTools: [],+ mcpServers: [{ ...fixtureEntry({ env: { FIXTURE_SECRET: "v2" } }), name: "fx2" }],+ },+ vault: {},+ });+ expect(env.pendingMcpServerNames()).toEqual(["fx2"]);+ await env.listTools();+ expect(env.mcpConnectResults()).toEqual([+ expect.objectContaining({ server: "fx2", status: "completed" }),+ ]);+ expect(finalPayload(await runTool(env, "mcp__fx2__probe", {})).output).toMatch(/^v2\|/);+ }, 30_000);+});+describe("MCP over stdio through Environment", () => {let tmp: string;let env: Environment;@@ -363,7 +447,7 @@ describe("MCP over stdio — per-server permission override", () => {const provider = new McpToolProvider([fixtureEntry({ permission: "readonly" })], { warn });try {expect(await provider.listTools()).toEqual([]);- expect(provider.serverNames()).toEqual([]);+ expect(provider.pendingServerNames()).toEqual([]);expect(warn).toHaveBeenCalledWith(expect.stringMatching(/MCP server "fx" skipped: "permission" must be "auto", "r" or "rw"/),);@@ -403,12 +487,16 @@ describe("Session first-run bootstrap events", () => {};return new Session({meta,- bootstrap: async () => ({- tools: await env.listTools(),- llm: fakeLLM,- mcp: env.mcpConnectResults(),- }),- mcpServers: env.mcpServerNames(),+ // The real composition layer's opening procedure, spelled out: connect pair around+ // the pending connect, then the toolset record, all through emit.+ bootstrap: async ({ emit }) => {+ const pending = env.pendingMcpServerNames();+ if (pending.length > 0) emit(mcpConnectBegin(pending));+ const tools = await env.listTools();+ if (pending.length > 0) emit(mcpConnectEnd(mcpConnectOutcome(env.mcpConnectResults())));+ emit(toolListReady(tools));+ return { tools, llm: fakeLLM };+ },environment: env,trace: {write: async (msg) => {@@ -519,12 +607,15 @@ describe("Session first-run bootstrap events", () => {agent_state: tmp,workspace: tmp,},- bootstrap: async () => {+ bootstrap: async ({ emit }) => {calls += 1;+ emit(mcpConnectBegin(["fx"]));await gate;- return { tools: [{ name: "t", description: "d" }], llm: capturingLLM, mcp: [] };+ emit(mcpConnectEnd({ status: "completed", results: [] }));+ const tools = [{ name: "t", description: "d" }];+ emit(toolListReady(tools));+ return { tools, llm: capturingLLM };},- mcpServers: ["fx"],environment: env,trace: {write: async (msg) => {diff --git a/packages/core/test/memory.test.ts b/packages/core/test/memory.test.tsindex 94c4af76..3f962db5 100644--- a/packages/core/test/memory.test.ts+++ b/packages/core/test/memory.test.ts@@ -7,6 +7,9 @@ import fs from "node:fs/promises";import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";+import type { SystemConfig } from "../src/index.js";+import { systemConfigPath } from "../src/state/paths.js";import {DEFAULT_AGENT_ID,DEFAULT_PROJECT_ID,@@ -19,7 +22,7 @@ import {ensureUserMemoryDir,ensureWorkspaceMemoryDir,isTemporaryWorkspace,- loadOrInitAgentState,+ loadAgentState,memoryDir,memoryScopeDir,parseMemoryFrontmatter,@@ -52,7 +55,7 @@ afterEach(async () => {/** Loads a default Agent State under the temp root (creates it on first call). */async function agentState(): Promise<AgentState> {- return loadOrInitAgentState({ root });+ return loadAgentState({ init: {}, root });}/** The effective system prompt a created Session recorded in its session_meta. */@@ -470,7 +473,12 @@ describe("{{MEMORY}} rendering", () => {it("is left out of the Session prompt when the Agent config disables Memory", async () => {const agent = await createAgent({ root });- agent.state.systemConfig.memory = { ...agent.state.systemConfig.memory, enabled: false };+ // On disk: a Session's context is assembled from the Agent State as it is on disk, never+ // from the Agent object's load-time snapshot.+ const configFile = systemConfigPath(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);+ const cfg = parseYaml(await fs.readFile(configFile, "utf8")) as SystemConfig;+ cfg.memory = { ...cfg.memory, enabled: false };+ await fs.writeFile(configFile, stringifyYaml(cfg), "utf8");const session = await agent.createSession({ workspaceDir: workspace });expect(sessionPrompt(session)).not.toContain(USER_LINE);expect(sessionPrompt(session)).not.toContain(WORKSPACE_LINE);diff --git a/packages/core/test/prompt-sections.test.ts b/packages/core/test/prompt-sections.test.tsindex abba24ca..69cfeb63 100644--- a/packages/core/test/prompt-sections.test.ts+++ b/packages/core/test/prompt-sections.test.ts@@ -9,6 +9,8 @@ import fs from "node:fs/promises";import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";+import { systemConfigPath } from "../src/state/paths.js";import {DEFAULT_AGENT_ID,DEFAULT_PROJECT_ID,@@ -29,7 +31,7 @@ import {insertSkillsPlaceholder,insertVaultPlaceholder,listScheduleNames,- loadOrInitAgentState,+ loadAgentState,scheduleDir,type AgentState,type SystemConfig,@@ -51,7 +53,7 @@ afterEach(async () => {/** Loads a default Agent State under the temp root (creates it on first call). */async function agentState(): Promise<AgentState> {- return loadOrInitAgentState({ root });+ return loadAgentState({ init: {}, root });}/** A copy of `state` with the given systemConfig fields overridden (in memory only). */@@ -402,7 +404,12 @@ describe("Session prompt integration", () => {it("is left out of the Session prompt when the Agent config disables the section", async () => {const agent = await createAgent({ root });- agent.state.systemConfig.schedules = { enabled: false };+ // On disk: a Session's context is assembled from the Agent State as it is on disk, never+ // from the Agent object's load-time snapshot.+ const configFile = systemConfigPath(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);+ const cfg = parseYaml(await fs.readFile(configFile, "utf8")) as SystemConfig;+ cfg.schedules = { enabled: false };+ await fs.writeFile(configFile, stringifyYaml(cfg), "utf8");const session = await agent.createSession();try {const meta = session.metaMessage.payload as { system_prompt: string };diff --git a/packages/core/test/resume.test.ts b/packages/core/test/resume.test.tsindex 863b188a..1ba96c35 100644--- a/packages/core/test/resume.test.ts+++ b/packages/core/test/resume.test.ts@@ -28,7 +28,7 @@ import {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 { tracesDir } from "../src/state/paths.js";+import { agentsMdPath, tracesDir } from "../src/state/paths.js";import { stubProviderKeys } from "./provider-keys.js";// The default project config ships with this model ((provider, model_id) pair reference; model_id is the upstream id).@@ -219,49 +219,6 @@ describe("agent.resumeSession", () => {expect((await readTrace(file)).length).toBe(closed.length);});- it("ignores a legacy trace's recorded thinking_level; the Agent config always wins", async () => {- // session_meta no longer carries a thinking level (it became a per-turn run parameter);- // a `thinking_level` still present in an OLD trace's meta JSON is deliberately ignored —- // resume always reads this Agent's current config, so a resumed legacy subagent session- // falls back to the config level instead of keeping the level it inherited at spawn- // time. The seeded Agent config here pins "medium".- const agent = await createAgent({});- expect(agent.state.systemConfig.model?.thinking_level).toBe("medium");- const levelOf = async (session: unknown): Promise<unknown> => {- // The LLM only exists after the lazy first-run bootstrap — drive it before reading.- const gen = (session as { ensureReady(): AsyncGenerator<unknown> }).ensureReady();- for await (const _ of gen) {- // drain- }- return (session as { engine: { deps: { llm: { defaultThinkingLevel?: unknown } } } }).engine- .deps.llm.defaultThinkingLevel;- };-- const recorded = metaFor(SID, workspace);- // A legacy trace: inject the retired field loosely into the on-disk meta JSON.- (recorded.payload as unknown as Record<string, unknown>).thinking_level = "xhigh";- await writeTraceFile(tmpRoot, SID, [recorded, userText("hello")]);- const ignored = await agent.resumeSession({ sessionId: SID });- expect(await levelOf(ignored)).toBe("medium");- // The rebuilt meta holds invariants only: the legacy field is never re-recorded either.- expect(- "thinking_level" in (ignored.metaMessage.payload as unknown as Record<string, unknown>),- ).toBe(false);-- // A current trace (no field) — and the legacy literal "default" — read the Agent config too.- const SID2 = "session-2026-07-06-11-00-00-abcdef02";- await writeTraceFile(tmpRoot, SID2, [metaFor(SID2, workspace), userText("hi")]);- const fallback = await agent.resumeSession({ sessionId: SID2 });- expect(await levelOf(fallback)).toBe("medium");-- const SID3 = "session-2026-07-06-12-00-00-abcdef03";- const legacyDefault = metaFor(SID3, workspace);- (legacyDefault.payload as unknown as Record<string, unknown>).thinking_level = "default";- await writeTraceFile(tmpRoot, SID3, [legacyDefault, userText("hi")]);- const viaDefault = await agent.resumeSession({ sessionId: SID3 });- expect(await levelOf(viaDefault)).toBe("medium");- });-it("does not write pairing placeholders to the trace file (resume is side-effect free)", async () => {const agent = await createAgent({});const file = await writeTraceFile(tmpRoot, SID, [@@ -489,3 +446,95 @@ describe("setHistory injection", () => {expect(client.getHistory()).toHaveLength(2);});});++describe("agent.resumeSession system prompt per context", () => {+ const SID = "session-2026-07-06-13-00-00-abcdef11";+ const promptOf = (session: { metaMessage: OmniMessage }): string =>+ (session.metaMessage.payload as { system_prompt: string }).system_prompt;++ it("opens a context closed by a completed compaction with the current AGENTS.md, not the closed file's recorded prompt", async () => {+ const agent = await createAgent({});+ await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ tokenUsage(usage(150), usage(150)),+ requestEnd("completed"),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ assistantText("[summary]carry on[/summary]"),+ requestEnd("completed"),+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),+ ]);+ await fs.writeFile(+ agentsMdPath(tmpRoot, "default_project", "default_agent"),+ "EDITED BEFORE RESUME",+ "utf8",+ );++ const session = await agent.resumeSession({ sessionId: SID });+ try {+ // The closed context is opened here for the first time — nothing was produced under any+ // prompt yet — so it gets the prompt assembled now, as the compaction would have opened it.+ expect(promptOf(session)).toContain("EDITED BEFORE RESUME");+ expect(promptOf(session)).not.toBe("ORIGINAL SYSTEM PROMPT");+ } finally {+ session.dispose();+ }+ });++ it("ignores a legacy recorded thinking level on resume: the level is a per-request parameter", async () => {+ const withLevel = (level: string): OmniMessage => {+ const meta = metaFor(SID, workspace);+ return {+ ...meta,+ payload: { ...meta.payload, thinking_level: level },+ } as unknown as OmniMessage;+ };+ const traceRecords = (meta: OmniMessage): OmniMessage[] => [+ meta,+ userText("hello"),+ requestBegin(),+ assistantText("hi there"),+ requestEnd("completed"),+ ];+ const agent = await createAgent({});+ // A legacy file recording "xhigh" does not shape the resumed context: the meta assembled+ // for it records no level at all — the level resolves per request from the pin and the+ // Agent config, exactly as on any other open.+ await writeTraceFile(tmpRoot, SID, traceRecords(withLevel("xhigh")));+ const session = await agent.resumeSession({ sessionId: SID });+ try {+ expect(+ (session.metaMessage.payload as { thinking_level?: string }).thinking_level,+ ).toBeUndefined();+ } finally {+ session.dispose();+ }+ });++ it("keeps the recorded prompt for an open context: its replayed history was produced under it", async () => {+ const agent = await createAgent({});+ await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("hello"),+ requestBegin(),+ assistantText("hi there"),+ requestEnd("completed"),+ ]);+ await fs.writeFile(+ agentsMdPath(tmpRoot, "default_project", "default_agent"),+ "EDITED BEFORE RESUME",+ "utf8",+ );++ const session = await agent.resumeSession({ sessionId: SID });+ try {+ expect(promptOf(session)).toBe("ORIGINAL SYSTEM PROMPT");+ } finally {+ session.dispose();+ }+ });+});diff --git a/packages/core/test/session-title.test.ts b/packages/core/test/session-title.test.tsindex 296f9e02..fe9724b2 100644--- a/packages/core/test/session-title.test.ts+++ b/packages/core/test/session-title.test.ts@@ -266,8 +266,7 @@ describe("session-title", () => {const withFactory = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm: fakeLLM([]), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: fakeLLM([]) }),environment: fakeEnvironment,createBareLLM: () => fakeLLM([assistantText("Title A")]),});@@ -281,8 +280,7 @@ describe("session-title", () => {const withoutFactory = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm: fakeLLM([]), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: fakeLLM([]) }),environment: fakeEnvironment,});expect(await withoutFactory.generateTitle()).toEqual({@@ -299,9 +297,7 @@ describe("session-title", () => {bootstrap: async () => ({tools: [],llm: fakeLLM([thinkingMessage("thinking"), assistantText("answer body")]),- mcp: [],}),- mcpServers: [],environment: fakeEnvironment,createBareLLM: () => fakeLLM([assistantText("Title B")], { status: "completed" }, seen),});@@ -322,8 +318,7 @@ describe("session-title", () => {const idle = new Session({meta: META,...IMAGES,- bootstrap: async () => ({ tools: [], llm: fakeLLM([]), mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm: fakeLLM([]) }),environment: fakeEnvironment,createBareLLM: () => fakeLLM([assistantText("must not be produced")]),});diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.tsindex 58ddc484..a6240e26 100644--- a/packages/core/test/state.test.ts+++ b/packages/core/test/state.test.ts@@ -41,7 +41,7 @@ import {resetSystemConfigToDefaults,getModel,isValidVaultKey,- loadOrInitAgentState,+ loadAgentState,loadProjectConfig,memoryDir,scratchpadDir,@@ -100,7 +100,7 @@ describe("paths / resolveRoot", () => {});});-describe("loadOrInitAgentState", () => {+describe("loadAgentState", () => {// Timeout: initialization writes the full layout — 15 library skills plus the example// benchmark, dozens of small files — and this first init test also pays the cold-I/O cost// (first-touch reads of the skills package, Defender scans) on Windows runners, where a@@ -110,7 +110,7 @@ describe("loadOrInitAgentState", () => {"initializes an empty agent directory with the full state layout",{ timeout: 20_000 },async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });expect(state.root).toBe(tmpRoot);expect(state.projectId).toBe(DEFAULT_PROJECT_ID);expect(state.agentId).toBe(DEFAULT_AGENT_ID);@@ -225,8 +225,8 @@ describe("loadOrInitAgentState", () => {);it("loads an existing agent directory and returns the same system prompt", async () => {- const first = await loadOrInitAgentState();- const second = await loadOrInitAgentState();+ const first = await loadAgentState({ init: {} });+ const second = await loadAgentState({ init: {} });expect(second.systemConfig.system_prompt).toBe(first.systemConfig.system_prompt);expect(second.systemConfig.system_prompt).toContain("PenguinHarness");expect(second.agentsMd).toBe(first.agentsMd);@@ -235,7 +235,7 @@ describe("loadOrInitAgentState", () => {});it("respects custom agentId / projectId", async () => {- const state = await loadOrInitAgentState({ agentId: "agent_x", projectId: "proj_y" });+ const state = await loadAgentState({ init: {}, agentId: "agent_x", projectId: "proj_y" });expect(state.agentId).toBe("agent_x");expect(state.projectId).toBe("proj_y");expect(await exists(systemConfigPath(tmpRoot, "proj_y", "agent_x"))).toBe(true);@@ -244,7 +244,7 @@ describe("loadOrInitAgentState", () => {describe("buildToolConfig", () => {it("exposes command, file, subagent (rw) and image (r) tools", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const cfg = buildToolConfig(state);expect(cfg.mcpServers).toEqual([]);expect(cfg.customTools.map((t) => t.name)).toEqual([@@ -330,7 +330,7 @@ describe("buildToolConfig", () => {});it("selectBuiltinToolsForModel picks the matching image tool per model kind", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const all = buildToolConfig(state).customTools;// Vision model: read_image is kept, describe_image is filtered out; unannotated tools are unaffected.const forVision = selectBuiltinToolsForModel(all, true);@@ -404,7 +404,7 @@ describe("buildToolConfig — per-tool call_description filter", () => {(t.parameters as { required?: string[] }).required;it("keeps the config-declared description property when call_description is missing or true (defaults)", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const cfg = buildToolConfig(state);for (const name of ["exec_command", "input_command", "run_subagent", "input_subagent"]) {const tool = cfg.customTools.find((t) => t.name === name)!;@@ -490,7 +490,7 @@ describe("buildToolConfig — per-tool call_description filter", () => {describe("assembleSystemPrompt", () => {it("renders default system prompt placeholders", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const prompt = assembleSystemPrompt(state,sessionEnvironment("/tmp/penguin-ws", "session-test-1", {@@ -523,7 +523,7 @@ describe("assembleSystemPrompt", () => {});it("default prompt carries the port and API-key guardrails", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const prompt = assembleSystemPrompt(state);// The wording of these rules is tuned freely; what must not drift is what they never say.// Ports: the service numbers are deliberately not listed, so a model cannot read one out@@ -679,7 +679,7 @@ describe("assembleSystemPrompt", () => {});it("does not auto-inject other Agent State files", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });await fs.writeFile(path.join(memoryDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID), "note.md"),"MEMORY_SHOULD_NOT_BE_IN_PROMPT",@@ -691,7 +691,7 @@ describe("assembleSystemPrompt", () => {"utf8",);- const reloaded = await loadOrInitAgentState();+ const reloaded = await loadAgentState({ init: {} });const prompt = assembleSystemPrompt(reloaded);expect(prompt).not.toContain("MEMORY_SHOULD_NOT_BE_IN_PROMPT");@@ -699,7 +699,7 @@ describe("assembleSystemPrompt", () => {});it("replaces generated Session environment field placeholders when provided", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });const env = sessionEnvironment("/tmp/penguin-ws","session-test-1",@@ -873,7 +873,7 @@ describe("assembleSystemPrompt", () => {describe("resetSystemConfigToDefaults", () => {it("replaces everything with the current defaults, keeping only name/description/version", async () => {- await loadOrInitAgentState();+ await loadAgentState({ init: {} });const configPath = systemConfigPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);// An old on-disk config: custom prompt/runtime/tools plus a key outside the schema.await fs.writeFile(@@ -915,14 +915,14 @@ describe("resetSystemConfigToDefaults", () => {expect(written.tools).toEqual(defaults.tools);// The file on disk round-trips to the same object; out-of-schema keys are gone.- const reloaded = await loadOrInitAgentState();+ const reloaded = await loadAgentState({ init: {} });expect(reloaded.systemConfig).toEqual(written);expect("custom_extra_key" in reloaded.systemConfig).toBe(false);expect(reloaded.systemConfig.system_prompt).toContain("App Data Dir: {{PROJECT_DIR}}");});it("normalizes an invalid version to 1 and keeps a missing name/description absent", async () => {- await loadOrInitAgentState();+ await loadAgentState({ init: {} });const configPath = systemConfigPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);await fs.writeFile(configPath, "system_prompt: old\nversion: nonsense\n", "utf8");const written = await resetSystemConfigToDefaults(@@ -1794,12 +1794,12 @@ describe("defensive config parsing", () => {it("throws a clear error when system_config.yaml is empty or corrupt", async () => {// First initialize normally, then empty out system_config.yaml; reloading should throw a// clear error rather than producing an undefined-laden message.- await loadOrInitAgentState();+ await loadAgentState({ init: {} });const cfgPath = systemConfigPath(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);await fs.writeFile(cfgPath, "", "utf8");- await expect(loadOrInitAgentState()).rejects.toThrow(/system_prompt|Invalid|corrupted/);+ await expect(loadAgentState({ init: {} })).rejects.toThrow(/system_prompt|Invalid|corrupted/);await fs.writeFile(cfgPath, "just a string, not a mapping", "utf8");- await expect(loadOrInitAgentState()).rejects.toThrow(/system_prompt|Invalid|corrupted/);+ await expect(loadAgentState({ init: {} })).rejects.toThrow(/system_prompt|Invalid|corrupted/);});});diff --git a/packages/core/test/subagent.test.ts b/packages/core/test/subagent.test.tsindex e4a36483..eea0116e 100644--- a/packages/core/test/subagent.test.ts+++ b/packages/core/test/subagent.test.ts@@ -666,11 +666,14 @@ describe("subagent steering and per-run abort", () => {/** Each round's raw input messages (the contract's own shape — sender included). */inputs: OmniMessage[][];steers: OmniMessage[][];+ /** Levels pinned on the child through the handle, in order. */+ pins: string[];release: () => void;} {const prompts: string[] = [];const inputs: OmniMessage[][] = [];const steers: OmniMessage[][] = [];+ const pins: string[] = [];let release!: () => void;const gate = new Promise<void>((r) => (release = r));const runner: SubagentRunner = {@@ -700,12 +703,15 @@ describe("subagent steering and per-run abort", () => {steers.push(messages);return true;},+ setThinkingLevel(level) {+ pins.push(level);+ },dispose() {},};return handle;},};- return { runner, prompts, inputs, steers, release: () => release() };+ return { runner, prompts, inputs, steers, pins, release: () => release() };}it("queues a mid-run prompt as a steering message with the parent_agent sender", async () => {@@ -842,6 +848,10 @@ describe("subagent steering and per-run abort", () => {expect(payload.text).toBe("from the panel");expect(payload.sender).toBeUndefined();+ // A host pin (the subagent panel's picker) reaches the live child through its handle.+ expect(env.setBackgroundSubagentThinkingLevel(HOP, "high")).toBe(true);+ expect(child.pins).toEqual(["high"]);+// Host abort ends the round; the settle pings the state listener and the listing flips.expect(env.abortBackgroundSubagentRun(HOP)).toBe(true);await until(() => env.listBackgroundSubagents()[0]?.running === false);@@ -867,6 +877,7 @@ describe("subagent steering and per-run abort", () => {expect(await env.sendToBackgroundSubagent("session-unknown", [userText("x")])).toBe("gone");expect(env.abortBackgroundSubagentRun("session-unknown")).toBe(false);+ expect(env.setBackgroundSubagentThinkingLevel("session-unknown", "low")).toBe(false);} finally {env.dispose();}@@ -920,14 +931,9 @@ describe("subagent steering and per-run abort", () => {it("revives a released child through the runner's resume and starts its next round", async () => {const prompts: string[] = [];- const levels: (string | undefined)[] = [];const resumes: { agentId?: string; sessionId: string }[] = [];- const run = async function* ({- prompt,- thinkingLevel,- }: RunInput & { thinkingLevel?: string }): AsyncGenerator<OmniMessage> {+ const run = async function* ({ prompt }: RunInput): AsyncGenerator<OmniMessage> {prompts.push(prompt);- levels.push(thinkingLevel);yield withOrigin(partialText("delta", `ran:${prompt}`), HOP);};const runner: SubagentRunner = {@@ -965,7 +971,6 @@ describe("subagent steering and per-run abort", () => {expect(await env.sendToBackgroundSubagent(HOP, [userText("wake up")])).toBe("gone");expect(await env.sendToBackgroundSubagent(HOP, [userText("wake up")], {- thinkingLevel: "high",resume: { agentId: "owner_agent" },}),).toBe("resumed");@@ -973,8 +978,6 @@ describe("subagent steering and per-run abort", () => {await until(() => env.listBackgroundSubagents()[0]?.running === false);expect(env.listBackgroundSubagents()[0]!.subagentId).toBe(`subagent-${HOP.slice(-8)}`);expect(prompts).toEqual(["task", "wake up"]);- // The per-turn thinking level rides only the round the message starts.- expect(levels).toEqual([undefined, "high"]);} finally {env.dispose();}diff --git a/packages/core/test/validate-id.test.ts b/packages/core/test/validate-id.test.tsindex a308c085..676e9a90 100644--- a/packages/core/test/validate-id.test.ts+++ b/packages/core/test/validate-id.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs/promises";import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { assertValidId, isValidId, loadOrInitAgentState } from "../src/state/index.js";+import { assertValidId, isValidId, loadAgentState } from "../src/state/index.js";describe("isValidId / assertValidId", () => {const valid = ["default_project", "default_agent", "my-agent", "agent-1", "ABC_123"];@@ -45,7 +45,7 @@ describe("isValidId / assertValidId", () => {});});-describe("loadOrInitAgentState id validation", () => {+describe("loadAgentState id validation", () => {let tmpRoot: string;let prevHome: string | undefined;@@ -65,19 +65,19 @@ describe("loadOrInitAgentState id validation", () => {});it("throws when agentId contains a path separator", async () => {- await expect(loadOrInitAgentState({ agentId: "a/b" })).rejects.toThrow(/agent_id/);+ await expect(loadAgentState({ init: {}, agentId: "a/b" })).rejects.toThrow(/agent_id/);});it("throws when projectId is ..", async () => {- await expect(loadOrInitAgentState({ projectId: ".." })).rejects.toThrow(/project_id/);+ await expect(loadAgentState({ init: {}, projectId: ".." })).rejects.toThrow(/project_id/);});it("throws on the Windows trailing-space variant '.. ' as agentId (blocks a path-traversal bypass)", async () => {- await expect(loadOrInitAgentState({ agentId: ".. " })).rejects.toThrow(/agent_id/);+ await expect(loadAgentState({ init: {}, agentId: ".. " })).rejects.toThrow(/agent_id/);});it("the default ids are valid and initialization succeeds", async () => {- const state = await loadOrInitAgentState();+ const state = await loadAgentState({ init: {} });expect(state.projectId).toBe("default_project");expect(state.agentId).toBe("default_agent");});diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex 5b71001a..2578eb91 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -59,7 +59,6 @@ for await (const output of session.run([userText("Clean up the CSV files under dinterface RunOptions {signal?: AbortSignal; // interrupt (e.g. Ctrl-C)approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)- thinkingLevel?: ThinkingLevelName; // this run's thinking level (per-turn, carried through reconnect retries; compaction requests keep the default)}```@@ -107,6 +106,8 @@ Every LLM-side failure except `auth` triggers an in-run reconnect — `timeout`## Compaction+Compaction does more than shorten the history: **every compaction rotates in a brand-new model context**. Once it completes, the Agent's entire runtime configuration is reassembled from the Agent State as it is at that moment — exactly like a new Session's first context — and the Trace starts a new file (one Trace file always equals one model context). An edit you (or the model itself) make to the Agent's configuration mid-conversation therefore takes effect after the next compaction.+Compaction settings are filled in from `system_config.yaml` by the composition layer:```ts@@ -128,6 +129,8 @@ Three triggers (`compaction_begin.reason`):Two modes: `summarize` (default) appends the compaction Prompt to the old context, extracts the `[summary]`, wraps it as a `[context_summary]` user text and continues in a **fresh model context**; `discard` simply drops the old context. System markers are written as `[tag]…[/tag]`; the earlier angle-bracket form (`<summary>`, `<context_summary>`, …) is still recognized when reading old Traces and old persisted compaction prompts. Summary extraction applies a tolerance ladder: the first non-empty `[summary]` tag pair wins; when every pair is empty, the text left after stripping the tags is used instead (rescuing models that write the body after the closing tag); with no tags at all, the whole output is used verbatim. Compaction rotates the [Trace file](/sessions-and-traces) (`_002`, `_003`, …) — one Trace file always equals one complete model context. `compactability()` probes feasibility before `session.compact()` (`ok | unsupported | empty | just_compacted`).+The new context is **assembled from the Agent State as it is at that moment**, exactly as a new Session's first context is: `system_config.yaml` in full (the prompt template with its section prompts and toggles, the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the model defaults), `AGENTS.md`, the vault, the installed Skills' metadata, the Memory indexes, the schedule roster and the Environment's date. So an edit made during the old context — by the model working on its own configuration, or by hand in the Agent settings — takes effect at the next compaction rather than the next Session. Runtime parameters fall into three tiers. **Strict** — the system prompt, the toolset (MCP included), the compaction settings and the model reference never change inside a running context: they shape the request prefix, and a context's prefix is fixed from open to close, so the provider's prompt cache stays valid across the whole Trace file (the vault, a tool's `r`/`rw` permission and the Project's command policy never reach the model, but are read once per context on the same rotation schedule). **Soft** — the thinking level: a purely per-request parameter — every LLM request takes the Session's pinned level (the Web App's in-chat picker, the CLI's `--thinking` / `/thinking`) or, unpinned, the Agent config default read when the context opened; changeable mid-context and never recorded in the Trace, at the cost of the provider's cached messages, which is why the pickers advise compacting first. **Unrestricted** — the approval mode: re-read from the database per decision, never touching the request, so an edit applies immediately. The Environment is re-equipped: the vault's values go straight into the command environment of every command spawned from then on (processes already running keep the environment they were started with); MCP Servers are cached by config — an entry that did not change keeps its live connection and discovered tools, a removed or changed one is closed, and only new, changed or previously failed ones connect, the wait streaming as the same `mcp_connect_begin` / `mcp_connect_end` pair the first run brackets it with — followed by the new `tool_list_ready`. 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. 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 — 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)).+The compaction request keeps the session's toolset **unchanged** — the request prefix (tool list included) stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest. Compaction still succeeds only with a valid summary: a response that calls a tool or whose extracted summary is empty counts as one more failed attempt — any tool calls are answered with synthesized failed outputs (keeping `tool_use`/`tool_result` pairing intact), and the resent request carries a corrective note ahead of the compaction Prompt (committed history can only be appended to; rewriting it would invalidate the prompt cache). Every failure — unusable summaries and the `failed`/`timeout`/`malformed` transport statuses alike — draws on the one reconnect budget and backoff ladder described under "Automatic reconnect" above; only `auth` stops the compaction at once. Once the budget is exhausted the compaction ends `failed`, keeping the original context and Trace file until the next trigger; `compaction_end` reuses the unified retry detail block — `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_message` detail (shown on the chat banner and the CLI line) — and a failed compaction also lands in the cost center as a `compaction_failed` error record. The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request (mid-Task tool results, or the carry-over a manual `/compact` folds in) into the old context's history: retries resend only the repairs and the Prompt, and nothing resends the absorbed input afterwards.An abandoned compaction is **made up later**, never patched over. Mid-Task the run ends the way any interruption does: the turn's still-pending state is held as carry-over under the same committed/not-committed rule, an `abort` event closes the run, and the next message resends that carry-over merged with the user's input — where the still-standing threshold triggers the compaction again. At a Task boundary the run simply ends with the original context kept. Either way nothing synthetic is invented to keep the loop running on a context that was supposed to shrink.diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex b89f423b..3677323f 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -56,7 +56,6 @@ for await (const output of session.run([userText("整理 data/ 下的 CSV 文件interface RunOptions {signal?: AbortSignal; // 中断信号(如 Ctrl-C)approve?: ApproveFn; // 逐工具审批;未注入时默认全部拒绝(保守策略)- thinkingLevel?: ThinkingLevelName; // 本次 run 的思考等级(逐轮参数,覆盖到重连重试;压缩请求用默认值)}```@@ -104,6 +103,8 @@ Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消## 上下文压缩(Compaction)+压缩不只是缩短历史:**每次压缩都会轮换出一个全新的模型上下文**。压缩完成后,Agent 的全部运行配置按此刻的 Agent State 重新装配——与新建 Session 的首个上下文完全相同——Trace 随之开启新文件(一个 Trace 文件恒等于一个模型上下文)。因此你(或模型自己)在对话进行中对 Agent 配置的修改,会在下一次压缩后生效。+压缩配置由组装层从 `system_config.yaml` 填充默认值:```ts@@ -125,6 +126,8 @@ interface CompactionSettings {两种模式:`summarize`(默认)向旧上下文追加压缩 Prompt,提取 `[summary]` 后包装为 `[context_summary]` 用户文本,在**全新的模型上下文**中继续;`discard` 直接丢弃旧上下文。系统标记统一写作 `[tag]…[/tag]`;读取旧 Trace 与旧压缩 Prompt 时仍识别早期的尖括号形式(`<summary>`、`<context_summary>` 等)。摘要提取自带容忍阶梯:优先取第一个非空的 `[summary]` 标签对;标签对全为空时,改取剥离标签后剩余的全部文本(兼容把正文写在闭合标签之后的模型);完全没有标签则整段输出照用。压缩时 [Trace 文件随之轮转](/sessions-and-traces)(`_002`、`_003`……),一个 Trace 文件恒等于一个完整模型上下文。`session.compact()` 前可用 `compactability()` 探询可行性(`ok | unsupported | empty | just_compacted`)。+新上下文**按此刻的 Agent State 整体装配**,与新建 Session 的首个上下文完全相同:整份 `system_config.yaml`(提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、`max_turns`、模型默认参数)、`AGENTS.md`、vault、已装 Skill 的元数据、Memory 索引、定时任务名单与环境字段中的日期。因此旧上下文期间的修改——模型改自己的配置,或用户在 Agent 设置里手改——在下一次压缩即生效,不必等下一个 Session。运行参数分三层。**严格层**:系统提示词、工具集(含 MCP)、压缩配置与模型引用在运行中的上下文内绝不改变——它们构成请求前缀,上下文的前缀自开启固定到关闭,整个 Trace 文件内提供商的提示词缓存始终有效(vault、工具的 `r`/`rw` 权限与 Project 的命令策略虽不进模型请求,也随同一轮换节奏在上下文开启时读取一次)。**软限制层**:思考等级——纯粹的每请求参数:每次 LLM 请求取 Session 钉住的等级(Web 对话内选择器、CLI 的 `--thinking` / `/thinking`),未钉住则取上下文开启时读到的 Agent 配置缺省;允许中途更换、不落 Trace,代价是提供商的消息缓存失效,因此选择器会提醒建议先压缩。**不限制层**:审批模式——逐次决策从数据库重读、从不进入请求,修改即刻生效。Environment 随之重新装备:vault 的值直接进入此后每条命令的子进程环境(已在运行的进程保留启动时的环境);MCP Server 按配置缓存——条目未变的保持连接与已发现的工具,被删除或改动的关闭,只有新增、改动或上次失败的才连接,等待期间流式发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对——随后是新的 `tool_list_ready`。轮转出的新 Trace 文件以记录本上下文实际所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。Agent State 装配失败(例如配置文件已无法解析)时本次运行以该错误结束、引擎保持旧上下文——与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启(见 [Session 与 Trace](/sessions-and-traces))。+压缩请求**保持会话工具集不变**——请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻提供商的提示词缓存依然有效。只有得到有效摘要,压缩才算成功:若响应中出现工具调用、或提取出的摘要为空,视同一次普通的失败尝试——工具调用先以合成的失败输出逐一应答(保持 `tool_use`/`tool_result` 配对完整),重发的请求在压缩 Prompt 前附加一条纠正说明(已提交的历史只能追加、不能改写,改写会使提示词缓存失效)。所有失败——无效摘要与 `failed`/`timeout`/`malformed` 传输失败——共用上文「自动重连」一节的同一重连预算与退避阶梯;只有 `auth` 会让压缩当场停止。预算耗尽后压缩以 `failed` 结束,保留原上下文与 Trace 文件,等待下次触发;`compaction_end` 复用统一的重试详情块——`attempt`(最终尝试序号,失败尝试也计入)与失败时的 `error_message` 详情(聊天横幅与 CLI 直接展示),压缩失败还会作为一条 `compaction_failed` 错误记录进入成本中心。首个**已提交**的尝试(无论被采纳还是被判无效)同时会把折叠进压缩请求的本轮输入(任务中途的工具结果、手动 `/compact` 折叠的补发内容)吸收进旧上下文:重试只重发修复输出与压缩 Prompt,此后也不再重发已吸收的输入。被放弃的压缩**留待补做**,而不是就地兜底。任务中途按打断的同一套流程收场:本轮尚未了结的状态按同一条「是否已提交」规则转入 carry-over,以 `abort` 事件结束本次运行,下一条消息把 carry-over 与用户输入合并重发——阈值依然超标,压缩在那里再次触发。Task 边界上则直接结束本次运行、保留原上下文。两种情形都不合成任何东西去让循环在本该缩小的上下文上硬跑下去。diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 162f014d..c1b6922a 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -49,7 +49,7 @@ penguin run -m "long job" --background # returns the session id i| `--model-id <id>` | Upstream id of the model to use; requires `--provider`. Omit both to use the Project's default model || `--provider <group>` | Provider group of the model; required whenever `--model-id` is given || `--approve <mode>` | Approval mode, see below (default `allow-all`). With `--session` it PATCHes the session's sticky mode |-| `--thinking <level>` | Thinking level for this task: `low` / `medium` / `high` / `xhigh` / `max`; rides the task request. Omitted, the session's pinned level (else the Agent config) applies |+| `--thinking <level>` | Pins the session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`) before the task; it applies from the session's next LLM request. Omitted, the session's pinned level (else the Agent config) applies || `--session <sessionId>` | Reuse an existing session (full id or unique fragment) instead of creating one; excludes `--workspace` and the model pair || `--background` | POST the task and exit immediately, printing the session id (`{"sessionId"}` under `--json`); the task keeps running on the server — follow it with `penguin logs -f` || `--timeout <duration>` | Soft-yield wait budget (see Global conventions): at expiry, print what has rendered plus a dim still-running line with the session id (`{sessionId, status: "running", text}` under `--json`) and exit 0 — the task is not aborted. `--timeout 0` returns right after the POST (`{sessionId, status: "running"}` under `--json`, no `text`). Excludes `--background` |@@ -67,7 +67,7 @@ Interactive REPL; each input line starts a Task. Takes the same options as `run`| `--verbose` | Show full tool output; by default long tool outputs are collapsed (see below) || `--server <url>` | Target server (see Server connection) |-With `--resume`, the Workspace and model are locked by the original Session and cannot be overridden via `--workspace` / `--model-id` / `--provider`. The thinking level is a per-turn parameter, so `--thinking` is still accepted: it becomes the initial `/thinking` override instead of a creation-time default. On exit, a copy-pastable `penguin chat --resume <sessionId>` command is printed.+With `--resume`, the Workspace and model are locked by the original Session and cannot be overridden via `--workspace` / `--model-id` / `--provider`. `--thinking` is still accepted: it re-pins the existing Session, effective from its next LLM request (mid-context changes cost the provider's cached context — compacting first is recommended). On exit, a copy-pastable `penguin chat --resume <sessionId>` command is printed.In-REPL commands:@@ -76,8 +76,8 @@ In-REPL commands:| any text while a Task runs | Mid-run steering: queued and delivered to the model between turns as a `[user_steering]` user message (a `»` acknowledgment echoes the text); rendering is held while you type so streamed output doesn't scribble over the line. If the Task finishes first, the line is sent as the next normal prompt || `/compact` | Proactively compact the current context || `/clear` | Start a fresh blank Session in place; the old Session stays on disk and can be resumed with `--resume` |-| `/thinking` | Show the thinking level the next turn will run at, and whether it is this Session's default or an active per-turn override (which also names the default it overrides) |-| `/thinking <level>` | Override the thinking level (`low` / `medium` / `high` / `xhigh` / `max`) for subsequent turns of this chat; never written back to the Agent config. The override applies to this Session's own turns only — subagent sessions are spawned with the level the Session was created with |+| `/thinking` | Show this Session's thinking level: the level it is pinned to (by `--thinking` or `/thinking`), else the Agent's configured level |+| `/thinking <level>` | Pin the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`); never written back to the Agent config. Soft-limited: it applies from the next request, mid-context included — the reply advises `/compact` first, since the change invalidates the provider's cached context; subagent sessions spawned from then on inherit the pinned level || `/verbose` | Toggle between collapsed and full tool output || `/exit`, `/quit` | Quit |diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex 7e93c72d..59fe4dba 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -49,7 +49,7 @@ penguin run -m "长任务" --background # 立即返回 session id| `--model-id <id>` | 指定模型的上游 id,须与 `--provider` 同时给出;两者都不给时使用 Project 默认模型 || `--provider <group>` | 模型所属 Provider 分组,给出 `--model-id` 时必填 || `--approve <mode>` | 审批模式,见下文(缺省 `allow-all`)。与 `--session` 同用时 PATCH 该会话的粘性模式 |-| `--thinking <level>` | 本次 Task 的思考等级:`low` / `medium` / `high` / `xhigh` / `max`,随任务请求下发。省略时按会话钉定值(否则 Agent 配置)生效 |+| `--thinking <level>` | 发起任务前把会话的思考等级钉为 `low` / `medium` / `high` / `xhigh` / `max`,自会话的下一次 LLM 请求起生效。省略时按会话钉定值(否则 Agent 配置)生效 || `--session <sessionId>` | 复用既有 Session(完整 id 或唯一片段),不再新建;不能与 `--workspace` 及模型对同用 || `--background` | 提交任务后立即退出并打印 session id(`--json` 下为 `{"sessionId"}`);任务在服务端继续运行,可用 `penguin logs -f` 跟随 || `--timeout <duration>` | 软让出等待预算(见「全局约定」):到时打印已渲染内容与一行暗色「仍在运行」提示(含 session id;`--json` 下为 `{sessionId, status: "running", text}`)并以 0 退出——任务不被中止。`--timeout 0` 在 POST 后立即返回(`--json` 下为 `{sessionId, status: "running"}`,无 `text`)。不能与 `--background` 同用 |@@ -67,7 +67,7 @@ penguin run -m "长任务" --background # 立即返回 session id| `--verbose` | 显示完整工具输出;缺省折叠过长的工具输出(见下文) || `--server <url>` | 目标服务器(见「服务器连接」) |-使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。思考等级是逐轮参数,`--resume` 下仍接受 `--thinking`:它作为初始的 `/thinking` 覆盖生效,而不是创建时的缺省值。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。+使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。`--resume` 下仍接受 `--thinking`:它重新钉住该 Session,自下一次 LLM 请求起生效(中途更换会使提供商缓存失效,建议先压缩)。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。REPL 内命令:@@ -76,8 +76,8 @@ REPL 内命令:| 运行中输入任意文字 | 运行中插话:排队后以 `[user_steering]` 用户消息随下一轮送达模型(`»` 确认行会回显文字);输入期间渲染暂挂,流式输出不会打断正在输入的行。若 Task 恰好已结束,该行作为下一条普通消息发送 || `/compact` | 主动压缩当前上下文 || `/clear` | 原地开启全新空白 Session;原会话保留在磁盘上,仍可用 `--resume` 恢复 |-| `/thinking` | 显示下一轮将使用的思考等级,并区分它是本 Session 的缺省值还是生效中的逐轮覆盖值(后者同时给出被覆盖的缺省值) |-| `/thinking <level>` | 覆盖本次对话后续轮次的思考等级(`low` / `medium` / `high` / `xhigh` / `max`);不会写回 Agent 配置。该覆盖只作用于本 Session 自己的轮次——派生的子会话仍按 Session 创建时的等级启动 |+| `/thinking` | 显示本 Session 的思考等级:被 `--thinking` 或 `/thinking` 钉住的等级,否则为 Agent 配置的等级 |+| `/thinking <level>` | 钉住本 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`);不会写回 Agent 配置。软限制:自下一次请求起生效、允许中途更换——回执会建议先 `/compact` 压缩,因为更换会使提供商的提示词缓存失效;此后派生的子会话继承钉住的等级 || `/verbose` | 在折叠与完整工具输出之间切换 || `/exit`、`/quit` | 退出 |diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 2869fa50..880cc55d 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -95,7 +95,7 @@ Edit this file via the CLI (`penguin config model …`) or the Web Models page### Command policy-The `[command_policy]` block is the Project's sandbox guardrail for shell commands: a deny-rule list applied at the approval boundary itself to both tools that reach a shell — `exec_command`'s `cmd` (the launch) and `input_command`'s `chars` (what gets typed into an already-running one) — `Session.run` wraps the injected approval callback with it, so a hit is rejected before the host is asked, under every approval mode, allow-all included. The model receives the fixed line `Tool call denied by policy.` — distinct from a person's cancellation — and changes course. The policy lives in the Project config rather than in Agent State: an Agent editing its own configuration cannot reach it, and each Session snapshots it at creation, so a mid-Session edit takes effect only from the next load. It is not a filesystem permission — a tool that writes arbitrary paths can still rewrite the config file itself.+The `[command_policy]` block is the Project's sandbox guardrail for shell commands: a deny-rule list applied at the approval boundary itself to both tools that reach a shell — `exec_command`'s `cmd` (the launch) and `input_command`'s `chars` (what gets typed into an already-running one) — `Session.run` wraps the injected approval callback with it, so a hit is rejected before the host is asked, under every approval mode, allow-all included. The model receives the fixed line `Tool call denied by policy.` — distinct from a person's cancellation — and changes course. The policy lives in the Project config rather than in Agent State: an Agent editing its own configuration through its settings surface cannot reach it. It sits in the strict tier of runtime parameters: read once per model context, when the context opens — an edit reaches a running Session at its next rotation (compaction), and new conversations at once. It is not a filesystem permission — a tool that writes arbitrary paths can still rewrite the config file itself, and the rewrite takes effect at the next rotation: an accident guardrail, not a security boundary.The rules are **plain data with no special tiers**: the factory set is seeded into each new project exactly like the model presets — copied in at creation, never rewritten afterward — and every rule can then be edited, disabled, deleted, or joined by new ones. A project from before the seeding (no `rules` list stored) behaves as the factory set until its first saved edit materializes the list; the settings page's "Restore defaults" loads the factory set back into the editor, and Save writes it.@@ -146,7 +146,7 @@ Manage it from the Security policy tab of Project Settings in the Web App (owner| `system_prompt` | built-in template | Required; the only template with placeholder substitution || `max_turns` | `-1` | Maximum LLM turns per Task (`-1` = unlimited; a positive integer caps the Task) || `model.max_tokens` | `32000` | Output Token ceiling per Request (-1 = no cap, provider default); each request clamps the effective value to the model's `context_window` minus the estimated input, so a small-window model never gets asked for more than fits |-| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`; the session default, overridable per-Task |+| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`; the level each model context opens at unless the Session pins one — fixed for the context, so a change lands at the next compaction || `model.timeoutMs` | `300000` | **Idle** budget for a Request (milliseconds): the longest wait for the next upstream event, reset by every event — not a cap on the request's total duration. It bounds the connect + first-event wait and the gaps between events; a model that keeps its reasoning off the wire spends its whole thinking phase inside that first gap, which is what the default leaves room for || `compaction.max_context_length` | `256000` | Context Token threshold that triggers compaction; the effective threshold is the smaller of this and the model's `context_window` − 2048, so a small-window model compacts inside its window while a window above 258048 fires at this number (an entry with no `context_window` assumes a 128000 window) || `compaction.max_session_turns` | `-1` | Cumulative Session turn threshold (`-1` = unlimited) |@@ -233,7 +233,7 @@ For developers: `kernel_version` advances manually, and only on a substantive chOn Windows, `{{PROJECT_DIR}}` and `{{CWD}}` are injected with forward slashes — like every other path core composes for the model (attachment lines, the goal-file line, truncated-output recovery paths). The model re-emits these spellings into JSON tool arguments and shell commands; forward slashes are accepted by Node's fs APIs and the package's (Git) Bash tool shell, and avoid JSON backslash-escaping mistakes.-`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)).+`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)). Like the rest of the Agent State — `system_config.yaml` included — it is read whenever a model context opens: at Session creation and again when a compaction opens the next context. An edit therefore takes effect at the next compaction of a running Session, not only in new Sessions, and never inside the context that is running (see [Compaction](/agent-loop)).The Vault / Skills / Memory / Schedules sections all follow the same placeholder + toggle + editable prompt pattern: the template holds only the `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` placeholders, the section text lives in the corresponding `*.prompt` config (edited on its settings tab), and turning `*.enabled` off empties the whole block. The four section placeholders are expanded **last, in a single pass** at assembly time: expansion products are never rescanned, so placeholder-looking text inside a memory index or a section prompt stays literal instead of triggering a second substitution.diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex a16ffd42..83d7ca80 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -95,7 +95,7 @@ output = 0.857143### 沙箱安全策略-`[command_policy]` 块是 Project 级的 shell 命令沙箱护栏:一组拒绝规则,在审批边界本身对两个能碰到 shell 的工具生效——`exec_command` 的 `cmd`(启动命令)与 `input_command` 的 `chars`(敲进已运行命令的内容)——`Session.run` 用它包装注入进来的审批回调,命中即在宿主被问到之前拒绝,任何审批模式(包括全部放行)都不能放过它,模型收到固定文案 `Tool call denied by policy.`——与人工取消可区分——从而换路。策略放在 Project 配置而不是 Agent State:Agent 改自己的配置改不到它,且每个 Session 在创建时读取快照,运行中改动要到下次加载才生效。它不是文件系统权限——能写任意路径的工具照样能改写配置文件本身。+`[command_policy]` 块是 Project 级的 shell 命令沙箱护栏:一组拒绝规则,在审批边界本身对两个能碰到 shell 的工具生效——`exec_command` 的 `cmd`(启动命令)与 `input_command` 的 `chars`(敲进已运行命令的内容)——`Session.run` 用它包装注入进来的审批回调,命中即在宿主被问到之前拒绝,任何审批模式(包括全部放行)都不能放过它,模型收到固定文案 `Tool call denied by policy.`——与人工取消可区分——从而换路。策略放在 Project 配置而不是 Agent State:Agent 经自己的配置面改不到它。它属于运行参数的严格层:随模型上下文在开启时读取一次,修改在各运行中 Session 的下一次轮换(压缩)生效,新对话立即生效。它不是文件系统权限——能写任意路径的工具照样能改写配置文件本身,改动同样在下一次轮换生效。规则是**纯数据,没有特殊层级**:出厂规则集像模型预设一样播种进每个新项目——创建时拷入、之后绝不自动改写——此后每条规则都可编辑、停用、删除,也可新增。播种之前的存量项目(未存 `rules` 列表)在首次保存编辑前按出厂集生效,首次保存即把列表物化进文件;设置页的「恢复默认」把出厂集读回编辑区,由 Save 落盘。@@ -146,7 +146,7 @@ enabled = false| `system_prompt` | 内置模板 | 必填;唯一进行占位符替换的模板 || `max_turns` | `-1` | 单个 Task 的最大 LLM 轮数(`-1` 不限制,正整数为上限) || `model.max_tokens` | `32000` | 单次输出 Token 天花板(-1 不设上限,用服务商默认);每次请求会把实际值收敛到模型 `context_window` 减估算输入以内,小窗口模型不会被索要放不下的输出 |-| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`;作为会话默认档位,可被逐轮 Task 参数覆盖 |+| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`;每个模型上下文开启时采用的档位(Session 钉住的档位优先),上下文内固定,修改在下一次压缩后生效 || `model.timeoutMs` | `300000` | 单次 Request 的**空闲**超时(毫秒):等待上游下一个事件的上限,收到任一事件即归零重计,不是整次请求的总时长上限。它约束的是连接建立与首个事件的等待、以及流式过程中的事件间隔——思考不外露的模型整段推理都落在「首个事件」这一段里,缺省值为此留足余量 || `compaction.max_context_length` | `256000` | 触发压缩的上下文 Token 阈值;生效阈值取它与模型 `context_window` − 2048 中的较小者,故小窗口模型在自己的窗口内压缩,窗口大于 258048 时则在该数值处触发(条目未配置 `context_window` 时按 128000 的假定窗口计) || `compaction.max_session_turns` | `-1` | Session 累计轮数阈值(`-1` 不限制) |@@ -233,7 +233,7 @@ compaction:Windows 上注入的 `{{PROJECT_DIR}}` 与 `{{CWD}}` 统一使用正斜杠——与 core 产出的其他模型可见路径(附件行、Goal file 行、截断输出 recovery 路径)同一拼写。模型会把这些拼写原样带入 JSON 工具参数和 Shell 命令;正斜杠被 Node 的 fs API 与包内 (Git) Bash 工具 Shell 接受,也避免 JSON 反斜杠转义出错。-`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。+`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。与 Agent State 的其余部分(含 `system_config.yaml`)一样,它在每次模型上下文开启时重新读取——Session 创建时一次,压缩开启下一个上下文时再一次——因此修改在运行中 Session 的下一次压缩即生效,不只作用于新 Session,也绝不会作用于正在运行的上下文(见[上下文压缩](/agent-loop))。Vault / 技能 / 记忆 / 定时任务四个小节均采用「段落占位符 + 开关 + 可编辑提示词」模式:模板只保留 `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` 占位符,小节文本存于各自的 `*.prompt` 配置、在对应设置标签页编辑,`*.enabled` 关闭即整段为空。四个段落占位符在装配时**最后单趟展开**:展开产物不再被扫描,因此记忆索引或提示词正文里出现的占位符字样只会保持字面原样,不会引发二次替换。diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.mdindex 8213d64e..7620ba84 100644--- a/packages/docs/content/interfaces.en.md+++ b/packages/docs/content/interfaces.en.md@@ -37,7 +37,7 @@ What travels *alongside* it is the **control plane**, deliberately not message-s| Control-plane item | Where | Why it is not a message || --- | --- | --- || `signal: AbortSignal` | `RunOptions`, `GenerativeModelParameters`, `ToolExecutionRequest` | An interruption that had to wait its turn in a message queue would not be an interruption. |-| `thinkingLevel` | `RunOptions` → `GenerativeModelParameters` | A per-request parameter, like a timeout — it says how to run the request, not what to say. |+| `thinkingLevel` | `GenerativeModelParameters` | A per-request parameter, like a timeout — it says how to run the request, not what to say. The engine holds the live value as its own state (`ContextEngine.setThinkingLevel`, fed by the `Session.thinkingLevel` setter — the soft-limited knob); unset, the LLM object's construction default — the context's opening level — applies (`RunOptions` carries no level). || `approve` and its `ApprovalDecision` | `RunOptions`, `ToolExecutionRequest` | The callback takes an OmniMessage tool call; the answer is a three-value enum the engine turns into an `approval_decision` message the moment it has it. || `LLMOutcome` | `streamGenerate`'s generator return value | The request's terminal state, which the engine's retry and reconnect policy branches on. A generator's return value is statically guaranteed to exist; "the last message yielded must be a `request_end`" would only ever be a runtime convention. The engine writes that `request_end` from it. |@@ -232,7 +232,6 @@ session.run(interface RunOptions {signal?: AbortSignal; // interrupt (e.g. Ctrl-C)approve?: ApproveFn; // per-tool approval; denies everything when omitted- thinkingLevel?: ThinkingLevelName; // this run's thinking level (per-turn; compaction requests unaffected)}```diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.mdindex 11ca3851..7e574b79 100644--- a/packages/docs/content/interfaces.zh.md+++ b/packages/docs/content/interfaces.zh.md@@ -37,7 +37,7 @@ context_engine 依赖三个接口:Human、LLM、Environment。协议转换全| 控制面项 | 位置 | 为什么不是消息 || --- | --- | --- || `signal: AbortSignal` | `RunOptions`、`GenerativeModelParameters`、`ToolExecutionRequest` | 要在消息队列里排队才生效的打断,就不叫打断了。 |-| `thinkingLevel` | `RunOptions` → `GenerativeModelParameters` | 逐次请求参数,与超时同类——它说的是这次请求怎么跑,而不是说了什么。 |+| `thinkingLevel` | `GenerativeModelParameters` | 逐次请求参数,与超时同类——它说的是这次请求怎么跑,而不是说了什么。实时值是引擎自有状态(`ContextEngine.setThinkingLevel`,由 `Session.thinkingLevel` 赋值转发,软限制旋钮);未设置时用 LLM 对象的构造默认值——即上下文开启时的等级(`RunOptions` 不带等级)。 || `approve` 及其 `ApprovalDecision` | `RunOptions`、`ToolExecutionRequest` | 回调的入参是 OmniMessage 工具调用;答案是三值枚举,引擎拿到后立刻转写为 `approval_decision` 消息。 || `LLMOutcome` | `streamGenerate` generator 的返回值 | 本次 Request 的结束态,引擎的重试与重连策略全部据此分支。generator 的返回值由类型强制存在;「最后产出的消息必须是 `request_end`」只能是运行期约定。引擎正是据它写出那条 `request_end`。 |@@ -230,7 +230,6 @@ session.run(interface RunOptions {signal?: AbortSignal; // 中断信号(如 Ctrl-C)approve?: ApproveFn; // 逐工具审批;未注入时默认全部拒绝- thinkingLevel?: ThinkingLevelName; // 本次 run 的思考等级(逐轮参数;压缩请求不受影响)}```diff --git a/packages/docs/content/message-flow.en.md b/packages/docs/content/message-flow.en.mdindex 134ab550..e4cb4f8a 100644--- a/packages/docs/content/message-flow.en.md+++ b/packages/docs/content/message-flow.en.md@@ -31,7 +31,7 @@ Key point: **every message is written to the Trace at the same moment it enters## The merge point: MergeQueue-A turn has several concurrent producers: the driver task consuming the LLM stream, plus N concurrently executing tools. All of them push into one merge queue, and a **single consumer** (the `run` generator) yields messages one at a time in **arrival order**; the turn ends only when every producer has finished and the queue is drained.+A turn has several concurrent producers: the driver task consuming the LLM stream, plus N concurrently executing tools. All of them push into one merge queue, and a **single consumer** (the `run` generator) yields messages one at a time in **arrival order**; the turn ends only when every producer has finished and the queue is drained. The same pump delivers a context opener's records — the first run's bootstrap and a compaction's `openNextContext` publish their connect pair and toolset record through it, so those stream live too.This one mechanism fixes three basic properties of message delivery:diff --git a/packages/docs/content/message-flow.zh.md b/packages/docs/content/message-flow.zh.mdindex c394b8f5..dbbc25d5 100644--- a/packages/docs/content/message-flow.zh.md+++ b/packages/docs/content/message-flow.zh.md@@ -30,7 +30,7 @@ Human ──run(newMessages)──► engine## 单一汇流点:MergeQueue-一轮内存在多个并发生产者:消费 LLM 流的驱动任务,加上 N 个并发执行的工具。它们全部 push 进同一个合并队列,由**单一消费者**(`run` 生成器)按**到达顺序**逐条 yield;生产者全部完成且队列排空,这一轮才结束。+一轮内存在多个并发生产者:消费 LLM 流的驱动任务,加上 N 个并发执行的工具。它们全部 push 进同一个合并队列,由**单一消费者**(`run` 生成器)按**到达顺序**逐条 yield;生产者全部完成且队列排空,这一轮才结束。上下文开启的记录走同一个泵:首次运行的 bootstrap 与压缩后的 `openNextContext` 都经它发布连接事件对与工具集记录,因此同样实时流出。这一机制决定了消息传递的三条基本性质:diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.mdindex 91152561..cdaff487 100644--- a/packages/docs/content/omni-message.en.md+++ b/packages/docs/content/omni-message.en.md@@ -43,9 +43,9 @@ interface SessionMetaPayload {}```-session_meta holds **per-session invariants only** — the model, system prompt and Workspace are immutable for the Session's lifetime; on resume, the engine takes this Trace line as the runtime config. See [Sessions & Traces](/sessions-and-traces). The thinking level is a per-turn parameter (sent with each Task) and is not recorded here; a `thinking_level` field still present in a legacy Trace's meta is ignored on resume — the resumed Session reads the Agent's current config instead.+session_meta describes **one model context**: the model and the Workspace are immutable for the Session's lifetime, while the system prompt is fixed per context — the file a compaction's rotation opens starts with a `session_meta` carrying the prompt assembled for the new context from the Agent State as it is then (see [Compaction](/agent-loop)); on resume, the engine takes the latest file's line as the runtime config. See [Sessions & Traces](/sessions-and-traces). The thinking level is not here: it is a per-request parameter — the Session pin (soft-limited, applying from the next request, mid-context), else the Agent config default read at context open — and nothing records it; a `thinking_level` field found in older Traces is displayed but never read back.-The tool schema is **not in the meta**: the toolset is only known after MCP Servers connect, and the meta must not wait for that — the full tool definitions arrive as a standalone `tool_list_ready` event at the first run (see event_msg). Pre-split Traces embedded a `tools` field here; that field is explicitly no longer read (their tool record is not displayed).+The tool schema is **not in the meta**: the toolset is only known after MCP Servers connect, and the meta must not wait for that — the full tool definitions arrive as a standalone `tool_list_ready` event at the first run and, for every context a compaction opens, right after that context's `session_meta` at the head of its Trace file (see event_msg). Pre-split Traces embedded a `tools` field here; that field is explicitly no longer read (their tool record is not displayed).## model_msg: complete payloads@@ -255,7 +255,7 @@ interface ApprovalDecisionPayload {interface TokenUsagePayload {type: "token_usage";- session: TokenCounts; // Session cumulative+ session: TokenCounts; // Session cumulative — authored by the engine (the LLM reports `request` only)request: TokenCounts; // this Request}diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.mdindex c8e2b7ff..c24e5188 100644--- a/packages/docs/content/omni-message.zh.md+++ b/packages/docs/content/omni-message.zh.md@@ -43,9 +43,9 @@ interface SessionMetaPayload {}```-session_meta 只承载**会话级不变量**——模型、系统提示词、Workspace 在 Session 生命周期内不可变;恢复 Session 时引擎直接以 Trace 中的这条消息为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。思考等级是逐轮参数(随每次 Task 下发),不记录在此;旧版 Trace 的 meta 里可能仍带 `thinking_level` 字段,恢复时会被忽略——恢复后的 Session 直接读取 Agent 当前配置。+session_meta 描述**一个模型上下文**:模型与 Workspace 在 Session 生命周期内不可变,系统提示词则按上下文固定——压缩轮转出的新文件以携带新上下文提示词的 `session_meta` 开头——该提示词按当时的 Agent State 装配(见[上下文压缩](/agent-loop));恢复 Session 时引擎直接以最新文件中的这条消息为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。思考等级不在此列:它是每请求参数——Session 钉住值(软限制,自下一次请求生效、允许中途更换),未钉住取上下文开启时读到的 Agent 配置缺省——不作任何记录;旧 Trace 中出现的 `thinking_level` 字段仅作展示,不再读取。-工具 schema **不在 meta 里**:工具集要等 MCP Server 连接完成才可知,而 meta 不应等待——完整工具定义在首次 run 时以独立的 `tool_list_ready` 事件下发(见 event_msg)。拆分前的旧版 Trace 在 meta 里内嵌 `tools` 字段,该字段已明确不再读取(旧 Trace 的工具记录不再展示)。+工具 schema **不在 meta 里**:工具集要等 MCP Server 连接完成才可知,而 meta 不应等待——完整工具定义在首次 run 时以独立的 `tool_list_ready` 事件下发,压缩开启的每个上下文则在其 Trace 文件头部、紧随该上下文的 `session_meta` 之后再发一次(见 event_msg)。拆分前的旧版 Trace 在 meta 里内嵌 `tools` 字段,该字段已明确不再读取(旧 Trace 的工具记录不再展示)。## model_msg:完整消息@@ -245,7 +245,7 @@ interface ApprovalDecisionPayload {interface TokenUsagePayload {type: "token_usage";- session: TokenCounts; // Session 累计+ session: TokenCounts; // Session 累计——由引擎统一累计盖章(LLM 只报 `request`)request: TokenCounts; // 本次 Request}diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex eef12fdb..9a876579 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -245,15 +245,15 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| Method | Path | Description || --- | --- | --- || GET | / | Session info (the single-session GET additionally carries `tracePath`, the absolute path of the latest Trace file; list rows omit it) |-| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable): every later run that carries no level of its own uses it instead of the Agent config's, and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned) |+| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable) and applies from its very next LLM request — the thinking level is soft-limited: changeable mid-context, at the cost of the provider's cached context, which is why the picker advises compacting first — and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned: the Agent config applies) || DELETE | / | Delete the Session (along with its Traces and scratch files) || GET | /messages | Full OmniMessage history; while a Task runs the response also carries `live` (the in-progress stream tail, see below) || POST | /fork | Fork an idle Session through a completed assistant reply: `{position:{fileIndex,ordinal}}` → `{session}` || GET | /stream | SSE event stream (next section) |-| POST | /tasks | Start a Task: `{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202. With `queueIfBusy`, a busy session holds the input as a follow-up (`queued: true`) and auto-starts it as an ordinary next task once idle; `task_state` events report the queued count. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see the request body below). With `goal: {budget?}` the input starts a goal loop instead: it must carry non-empty text (an image alone states no objective), any images it carries fold into the objective as scratchpad path lines whatever the model's vision, and `file` parts are refused — nothing folds them into a re-injected objective — see [Goal mode](/goal-mode) |+| POST | /tasks | Start a Task: `{input: TaskInputPart[], queueIfBusy?}` → 202. With `queueIfBusy`, a busy session holds the input as a follow-up (`queued: true`) and auto-starts it as an ordinary next task once idle; `task_state` events report the queued count. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see the request body below). With `goal: {budget?}` the input starts a goal loop instead: it must carry non-empty text (an image alone states no objective), any images it carries fold into the objective as scratchpad path lines whatever the model's vision, and `file` parts are refused — nothing folds them into a re-injected objective — see [Goal mode](/goal-mode) || POST | /steer | Mid-run steering: `{text, images?}` queues a message for the running Task (delivered between turns as a standalone `[user_steering]` user message, with its images right behind it) → 202; either field can carry the message on its own, but a request with neither is a 400; 409 `not_running` when no Task is in progress || DELETE | /steer/:steerId | Recall an undelivered steering message (ids ride `task_state`'s `pendingSteering`): withdraws it from the queue → 200 with its original content `{text, images, files}` (files read back from the scratchpad as data URLs, their disk copies deleted) so the composer can restore it for editing; 409 `not_pending` once it was delivered to the model |-| DELETE | /follow-ups/:followUpId | Recall a queued follow-up task (ids ride `task_state`'s `pendingFollowUps`): removes it before it auto-starts → 200 with its original content `{text, images, files, thinkingLevel?}` — every queued follow-up carries that content, however it was queued; 409 `follow_up_started` once it already started |+| DELETE | /follow-ups/:followUpId | Recall a queued follow-up task (ids ride `task_state`'s `pendingFollowUps`): removes it before it auto-starts → 200 with its original content `{text, images, files}` — every queued follow-up carries that content, however it was queued; 409 `follow_up_started` once it already started || POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 || POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle || POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error |@@ -378,9 +378,8 @@ Key request bodies (explicit keys):// POST /api/sessions/:sessionId/tasks — start a Taskinterface TaskCreateRequest {input: TaskInputPart[];- // Thinking level for this Task (a per-turn parameter, one of the six names; 400 otherwise);- // omitted = falls back to the Session's pinned level, then to the Agent config- thinkingLevel?: "none" | "low" | "medium" | "high" | "xhigh" | "max";+ // The thinking level is not a task parameter: it belongs to the model context — pin it on+ // the Session with PATCH, and each context the Session opens runs at the pinned level}type TaskInputPart =| { type: "text"; text: string }diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex d186d3e2..889e21ba 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -245,15 +245,15 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| 方法 | 路径 | 说明 || --- | --- | --- || GET | / | Session 信息(单会话 GET 额外携带 `tracePath`:最新 Trace 文件的绝对路径;列表行不含) |-| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级固定在该 Session 上并持久化:此后凡是自身未携带等级的运行都改用它,而不再回落到 Agent 配置;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未固定) |+| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级钉在该 Session 上并持久化,自下一次 LLM 请求起生效——思考等级是软限制参数:允许中途更换,代价是提供商的缓存失效,因此选择器会建议先压缩;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未钉住:按 Agent 配置生效) || DELETE | / | 删除 Session(连同 Trace 与暂存文件) || GET | /messages | 完整 OmniMessage 历史;Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) || POST | /fork | 从一条已完成的模型回复分叉空闲 Session:`{position:{fileIndex,ordinal}}` → `{session}` || GET | /stream | SSE 事件流(见下节) |-| POST | /tasks | 发起 Task:`{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) |+| POST | /tasks | 发起 Task:`{input: TaskInputPart[], queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) || POST | /steer | 运行中插话:`{text, images?}` 为运行中的 Task 排队一条消息(作为独立的 `[user_steering]` 用户消息随下一轮送达,图片紧随其后)→ 202;两个字段任一非空即可成消息,都为空则 400;无 Task 运行返回 409 `not_running` || DELETE | /steer/:steerId | 撤回一条尚未送达的插话(id 随 `task_state` 的 `pendingSteering` 下发):从队列中撤出 → 200,返回其原始内容 `{text, images, files}`(文件从 scratchpad 读回为 data URL,磁盘副本随之删除),供输入框恢复编辑;已送达模型则 409 `not_pending` |-| DELETE | /follow-ups/:followUpId | 撤回一条排队中的跟进消息(id 随 `task_state` 的 `pendingFollowUps` 下发):在自动发出前移除 → 200,返回其原始内容 `{text, images, files, thinkingLevel?}`——排队中的跟进消息一律带有该内容,与其入队路径无关;已自动发出则 409 `follow_up_started` |+| DELETE | /follow-ups/:followUpId | 撤回一条排队中的跟进消息(id 随 `task_state` 的 `pendingFollowUps` 下发):在自动发出前移除 → 200,返回其原始内容 `{text, images, files}`——排队中的跟进消息一律带有该内容,与其入队路径无关;已自动发出则 409 `follow_up_started` || POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 || POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 || POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) |@@ -377,8 +377,7 @@ GET /preview/<token>/<相对路径> (不鉴权,令牌即凭证// POST /api/sessions/:sessionId/tasks —— 发起一个 Taskinterface TaskCreateRequest {input: TaskInputPart[];- // 本次 Task 的思考等级(逐轮参数,六档之一;非法值 400);缺省 = 先回退到该 Session 固定的档位,再回退到 Agent 配置- thinkingLevel?: "none" | "low" | "medium" | "high" | "xhigh" | "max";+ // 思考等级不是 Task 参数:它属于模型上下文——用 PATCH 钉在 Session 上,此后开启的每个上下文都以钉住的等级运行}type TaskInputPart =| { type: "text"; text: string }diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.mdindex 9ae6e8f0..607dcf25 100644--- a/packages/docs/content/sessions-and-traces.en.md+++ b/packages/docs/content/sessions-and-traces.en.md@@ -81,14 +81,14 @@ When tool output exceeds `maxOutputLength`, Trace records the same bounded head,The Trace is the single source of truth for recovery — there is no separate session database to keep in sync. `resumeSession` works as follows:1. Locate the highest-index Trace file of the Session;-2. Read the runtime configuration from its `session_meta` — model, system prompt, Workspace — all immutable for the lifetime of the Session;+2. Read the runtime configuration from its `session_meta` — the model and the Workspace, immutable for the lifetime of the Session, and the system prompt and thinking level that context opened with;3. Replay the committed history into a fresh LLM context;4. Reconstruct the carry-over (undelivered tool outputs, interruption markers) plus turn and Token counters;5. Continue appending to the same Trace file.Recovery requires that the Workspace and the model still exist. What recovery guarantees is structural legality: only committed turns are replayed, with `tool_call` / `tool_call_output` pairing intact; incomplete model output (thinking, text) is allowed to be lost. A truncated last line left by an abnormal process exit is tolerated and ignored; a malformed line in the middle of a file (e.g. in a file damaged before writer appends were serialized) is skipped with a diagnostic on stderr, and every parseable record is kept. See `packages/core/src/trace/resume.ts`.-Special case: if the latest Trace file ends with a completed compaction, that context is closed as a whole — resume starts from an empty context; in summarize mode the `[context_summary]` is reconstructed and prepended to the first input after resume (old Traces using the earlier angle-bracket `<summary>` form are still understood).+Special case: if the latest Trace file ends with a completed compaction, that context is closed as a whole — resume starts from an empty context; in summarize mode the `[context_summary]` is reconstructed and prepended to the first input after resume (old Traces using the earlier angle-bracket `<summary>` form are still understood). That empty context is opened like any context a compaction opens: assembled whole from the current Agent State — prompt, toolset, vault and run settings — rather than from the closed file's recorded prompt (see [Compaction](/agent-loop)). An open context, by contrast, keeps the prompt its file recorded; its tools, Environment and vault can only come from the current Agent State, since the Trace records no executable configuration.## Model switch (/model)diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.mdindex 5364c117..84e356da 100644--- a/packages/docs/content/sessions-and-traces.zh.md+++ b/packages/docs/content/sessions-and-traces.zh.md@@ -79,14 +79,14 @@ Trace 是 append-only 的 JSON Lines 文件,每行一个 OmniMessage 信封(Trace 是恢复的唯一事实来源,没有独立的会话数据库需要与之对齐。`resumeSession` 的流程:1. 定位该 Session 索引最大的 Trace 文件;-2. 从文件内的 `session_meta` 读取运行配置——模型、系统提示词、Workspace,三者在 Session 生命周期内不可变;+2. 从文件内的 `session_meta` 读取运行配置——模型与 Workspace(二者在 Session 生命周期内不可变)以及该上下文开启时的系统提示词与思考等级;3. 将已提交的历史回放进一份全新的 LLM 上下文;4. 重建 carry-over(未送达的工具输出、中断标记)与轮数、Token 计数器;5. 继续追加写入同一个 Trace 文件。恢复的前提是 Workspace 与模型仍然存在。恢复保证的是结构合法性:只回放已提交的轮次,`tool_call` 与 `tool_call_output` 配对完整;未完成的模型输出(thinking、文本)允许丢失。异常退出留下的截断末行会被容忍并忽略;文件中间的损坏行(如写入器追加串行化之前受损的存量文件)会被跳过并在 stderr 给出诊断,其余可解析的记录全部保留。实现见 `packages/core/src/trace/resume.ts`。-特殊情形:若最新 Trace 文件以一次完成的压缩收尾,则该上下文已整体关闭——恢复从空上下文开始;summarize 模式下会重建 `[context_summary]` 摘要,前置到恢复后第一轮输入中(旧 Trace 中早期的尖括号 `<summary>` 形式仍可识别)。+特殊情形:若最新 Trace 文件以一次完成的压缩收尾,则该上下文已整体关闭——恢复从空上下文开始;summarize 模式下会重建 `[context_summary]` 摘要,前置到恢复后第一轮输入中(旧 Trace 中早期的尖括号 `<summary>` 形式仍可识别)。这个空上下文与压缩开启的上下文一样开启:按当前 Agent State 整体装配——提示词、工具集、vault 与运行参数——而不是沿用已关闭文件里记录的提示词(见[上下文压缩](/agent-loop))。未关闭的上下文则相反:提示词沿用该文件记录的原文,工具、Environment 与 vault 只能取自当前 Agent State——Trace 不记录可执行配置。## 模型切换(/model)diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.mdindex 35602eb0..df14e792 100644--- a/packages/docs/content/tools.en.md+++ b/packages/docs/content/tools.en.md@@ -170,7 +170,7 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the`run_subagent` hands a subtask you can fully specify in one prompt to a child Agent, with the same two-phase shape: after the foreground window (default 300000ms) it moves to the background with a `subagent_id`, driven by `input_subagent`; the child's pending approvals surface while the poll waits. `input_subagent` covers four gestures: an empty `prompt` polls; a `prompt` sent while the child **runs** is injected mid-run as a steering message (the same mechanism as a user interjecting into the main session — delivered as a `[user_steering]` message at the child's next step, recorded in the child's Trace with sender `parent_agent`); a `prompt` sent while it is idle continues the same session with a follow-up round; and `abort: true` stops the child's **current run only** — the session survives for steering and follow-ups, and combined with a `prompt` it interrupts and redirects. The model-facing output of every `input_subagent` access is the child's **most recent complete reply** — an idempotent “what it last said” snapshot rather than an incremental drain. With `run_in_background: true` the launch returns the `subagent_id` immediately and every model-initiated round's completion arrives as an automatic user message (panel-started and explicitly aborted rounds stay silent; see [Background completion reports](#background-completion-reports)). There is **no kill for subagents**: like the main agent, a subagent session is never destroyed — releasing an idle one only frees its slot, and a released `subagent_id` **revives automatically** when messaged again (the model's access and the panel's share the same resume path).-The Web App's subagents panel drives a selected child with the **same composer as the main conversation** (its subagent variant): the text body, skills and slash skill commands, a per-turn thinking level (applies to the round the message starts), the context ring (the child's own usage), the locked-model badge, and the approval-mode selector — which edits the parent session's mode, the one child approvals are actually judged by. A message is simply a user input on the child, whatever its state: steering while it runs, a follow-up round while it is idle, and a **revival** when the session was already released — the server resumes the child session (its own history, model and Workspace) and re-manages it, so the conversation just continues. The action button's stop face aborts only the child's current run. Everything converges on the same core channel as `input_subagent`, and the panel's running marks follow the server's live child states rather than the transcript.+The Web App's subagents panel drives a selected child with the **same composer as the main conversation** (its subagent variant): the text body, skills and slash skill commands, a thinking-level picker (pins the child Session, effective from its next model context), the context ring (the child's own usage), the locked-model badge, and the approval-mode selector — which edits the parent session's mode, the one child approvals are actually judged by. A message is simply a user input on the child, whatever its state: steering while it runs, a follow-up round while it is idle, and a **revival** when the session was already released — the server resumes the child session (its own history, model and Workspace) and re-manages it, so the conversation just continues. The action button's stop face aborts only the child's current run. Everything converges on the same core channel as `input_subagent`, and the panel's running marks follow the server's live child states rather than the transcript.```ts// run_subagent@@ -248,7 +248,7 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDec| --- | --- || SDK | Pass `approve` per `session.run`; with none injected the engine denies by default (conservative — nothing gets approved unattended) || CLI | `--approve` takes four modes: allow-all (default) / deny-all / read-only / always-ask; read-only auto-approves `permission: "r"` tools and defers the rest to a human |-| Web / Server | The same four modes, set per Session; the mode is re-read from the DB on every decision, so changes take effect immediately; manual decisions arrive via the API |+| Web / Server | The same four modes, set per Session; the mode is re-read from the DB on every decision (edits apply at once), while a tool's `r`/`rw` comes from the running context's toolset — permission edits apply at the next rotation (compaction); manual decisions arrive via the API |A deny produces a synthetic `aborted` `tool_call_output` for the model to react to — `Tool call denied by user.`, or `Tool call denied by policy.` when the [command policy](/configuration#command-policy) denied it, so a policy hit never reads as a person cancelling. See [ApproveFn](/interfaces#approvefn). Every decision is written to the Trace as an `approval_decision` event — a policy veto recorded as `forbidden` — forming a complete audit record. Approval happens in the tool-execution phase of the [Agent Loop](/agent-loop).@@ -303,7 +303,7 @@ tools:Behavior:-- Connecting is **lazy**: Session creation returns instantly, and the first `run()` connects all Servers in parallel and discovers tools once — the wait streams as one `mcp_connect_begin` / `mcp_connect_end` pair (frontends show a connecting status; the end carries the overall status plus per-Server results), and the full tool definitions follow as a `tool_list_ready` event (see [OmniMessage](/omni-message)); in the Trace all three land after the run's input, inside the new turn. Aborting mid-connect **cancels** the attempt — the next `run()` reconnects. The result is a Session-lifetime snapshot and `tools/list_changed` notifications are ignored. An unreachable Server or invalid entry only produces a stderr warning and is skipped — **the session is never blocked**.+- Connecting is **lazy**: Session creation returns instantly, and the first `run()` connects all Servers in parallel and discovers tools once — the wait streams as one `mcp_connect_begin` / `mcp_connect_end` pair (frontends show a connecting status; the end carries the overall status plus per-Server results), and the full tool definitions follow as a `tool_list_ready` event (see [OmniMessage](/omni-message)); in the Trace all three land after the run's input, inside the new turn. Aborting mid-connect **cancels** the attempt — the next `run()` reconnects. The result is a snapshot for the model context: `tools/list_changed` notifications are ignored, and when a compaction opens the next context the Servers reconnect from the then-current config, bracketed by the same event pair (see [Compaction](/agent-loop)). An unreachable Server or invalid entry only produces a stderr warning and is skipped — **the session is never blocked**.- Discovered tools join the flat tool namespace as `mcp__<server>__<tool>` and go through the same [execution contract](#execution-contract) (timeout, truncation, interruption) and [approval](#approval) flow as builtin tools.- Permission mapping: under the default `permission: auto`, a tool the Server annotates `readOnlyHint: true` is `r` (auto-approved by the read-only approval mode); everything else is `rw` — annotations are untrusted hints, so the default takes the restrictive direction. Setting the entry's `permission` to `r` or `rw` overrides the annotation for **every** tool of that Server, which is the way in for the many Servers that never set `readOnlyHint` and so land on `rw` wholesale.- What `permission` is: it fixes the level each of that Server's tools reports, and exactly one approval mode reads that level. Under `read-only` an `r` tool is auto-approved and an `rw` tool needs manual confirmation; `allow-all`, `deny-all` and `always-ask` never consult it, so marking an entry `rw` adds no prompt there. Beyond that the key does nothing: it does not sandbox the Server, does not restrict what its tools do when they run, is never sent to or verified against the Server, and the Server keeps whatever capabilities its transport gives it. Marking a Server `r` that can in fact write removes the confirmation `read-only` would have asked for.diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.mdindex 1d306286..7e766f54 100644--- a/packages/docs/content/tools.zh.md+++ b/packages/docs/content/tools.zh.md@@ -168,7 +168,7 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window`run_subagent` 把一段能一次说清的子任务交给子 Agent 执行,同样是两段式:前台窗口(默认 300000ms)过后转入后台并返回 `subagent_id`,由 `input_subagent` 驱动;子 Agent 的待审批项会在轮询等待期间浮出。`input_subagent` 覆盖四种手势:`prompt` 为空仅轮询;子会话**运行中**发 `prompt` 即中途插话(与用户对主会话的运行中 steering 同一机制——在子会话下一步以 `[user_steering]` 消息送达,写入子 Trace、sender 记为 `parent_agent`);空闲时发 `prompt` 即在同一会话上续跑一轮;`abort: true` 只停止子会话**当前这一轮**——会话保留、可继续插话或续跑,与 `prompt` 同给即打断并改道。`input_subagent` 每次访问的模型面输出是子会话**最近一条完整回复**——「它最后说了什么」的幂等快照,而非增量排空。传 `run_in_background: true` 则启动即返回 `subagent_id`,模型发起的每轮完成都以自动 user message 送达(面板发起的轮与被显式 abort 的轮不回报;见[后台完成回报](#后台完成回报))。**Subagent 没有 kill**:与主 Agent 一样,子会话永不销毁——释放空闲会话只是腾出并发额度,已释放的 `subagent_id` 在再次收到消息时**自动复活**(模型访问与面板走同一条 resume 路径)。-Web App 的智能体面板用**与主对话相同的 composer**(子会话变体)驱动选中的子会话:正文、技能与 slash 技能命令、per-turn 思考等级(作用于这条消息开启的一轮)、上下文圆环(子会话自身用量)、锁定模型徽标,以及审批模式选择——它读写的是父会话的模式,子会话审批本就按其判定。发消息就是对子会话的一次用户输入,无论其状态如何:运行中即插话,空闲即续跑一轮,会话已被释放则**复活**——服务端按 resume 口径恢复该子 Session(沿用其历史、模型与 Workspace)并重新纳管,对话直接继续。操作按钮的停止面只中止子会话当前这一轮。这一切与 `input_subagent` 收敛到 core 的同一通道;面板的运行标识以服务端实况为准,不再从对话文本推断。+Web App 的智能体面板用**与主对话相同的 composer**(子会话变体)驱动选中的子会话:正文、技能与 slash 技能命令、思考等级选择器(钉在子会话上,从其下一个模型上下文生效)、上下文圆环(子会话自身用量)、锁定模型徽标,以及审批模式选择——它读写的是父会话的模式,子会话审批本就按其判定。发消息就是对子会话的一次用户输入,无论其状态如何:运行中即插话,空闲即续跑一轮,会话已被释放则**复活**——服务端按 resume 口径恢复该子 Session(沿用其历史、模型与 Workspace)并重新纳管,对话直接继续。操作按钮的停止面只中止子会话当前这一轮。这一切与 `input_subagent` 收敛到 core 的同一通道;面板的运行标识以服务端实况为准,不再从对话文本推断。```ts// run_subagent@@ -246,7 +246,7 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDec| --- | --- || SDK | 每次 `session.run` 传入 `approve` 回调;未注入时引擎默认全部拒绝(保守策略,避免无人值守下误放行) || CLI | `--approve` 四种模式:allow-all(默认)/ deny-all / read-only / always-ask;read-only 自动放行 `permission: "r"` 的工具,其余转人工 |-| Web / Server | 同样四种模式,按 Session 设置;每次决策前从数据库重读,改模式立即生效;人工决策经 API 送达 |+| Web / Server | 同样四种模式,按 Session 设置;每次决策前从数据库重读审批模式(修改即刻生效);工具的 `r`/`rw` 取自运行中上下文的工具集——权限修改在下一次轮换(压缩)生效;人工决策经 API 送达 |deny 会合成一条 `aborted` 的 `tool_call_output` 供模型据此调整策略——`Tool call denied by user.`,被[命令策略](/configuration#沙箱安全策略)拒绝时为 `Tool call denied by policy.`,策略命中因此不会被读成「有人取消了」。见 [ApproveFn](/interfaces#approvefn)。每次决策都以 `approval_decision` 事件写入 Trace(策略拦截即记 `forbidden`),构成完整的审计记录。审批发生在 [Agent 运行循环](/agent-loop) 的工具执行阶段。@@ -300,7 +300,7 @@ tools:行为口径:-- 连接是**懒加载**的:Session 创建即时返回,首个 `run()` 开始时才并行连接全部 Server 并做一次工具发现——连接期间流式发出一对 `mcp_connect_begin` / `mcp_connect_end` 事件(前端显示连接状态;end 带总体 status 与逐 Server 结果),完成后以 `tool_list_ready` 事件下发完整工具定义(见 [OmniMessage](/omni-message));这三条消息在 Trace 中写在本轮输入之后,归属新轮次。运行中打断即**取消**本次连接,下次 `run()` 重新连接。发现结果是 Session 生命周期内的快照,`tools/list_changed` 通知被忽略。连接失败或条目非法只产生 stderr 警告并跳过该 Server,**不阻塞会话**。+- 连接是**懒加载**的:Session 创建即时返回,首个 `run()` 开始时才并行连接全部 Server 并做一次工具发现——连接期间流式发出一对 `mcp_connect_begin` / `mcp_connect_end` 事件(前端显示连接状态;end 带总体 status 与逐 Server 结果),完成后以 `tool_list_ready` 事件下发完整工具定义(见 [OmniMessage](/omni-message));这三条消息在 Trace 中写在本轮输入之后,归属新轮次。运行中打断即**取消**本次连接,下次 `run()` 重新连接。发现结果是当前模型上下文内的快照:`tools/list_changed` 通知被忽略;压缩开启下一个上下文时,Server 按当时的配置重新连接,同样以这对事件框定(见[上下文压缩](/agent-loop))。连接失败或条目非法只产生 stderr 警告并跳过该 Server,**不阻塞会话**。- 发现的工具以 `mcp__<server>__<tool>` 进入统一工具命名空间,与内置工具走同一条[执行契约](#执行契约)(超时、截断、打断)与[审批](#审批)流程。- 权限映射:缺省的 `permission: auto` 下,Server 注解 `readOnlyHint: true` 的工具为 `r`(read-only 审批模式自动放行),其余一律 `rw`——注解是未受信 hint,缺省取限制方向。把条目的 `permission` 设为 `r` 或 `rw`,则该 Server 的**全部**工具一律按此取值,覆盖注解——大量 Server 从不设置 `readOnlyHint`、因而整体落到 `rw`,这个字段就是为它们准备的。- `permission` 的边界:它固定该 Server 每个工具对外报出的等级,而读这个等级的审批模式只有一个。`read-only` 下 `r` 工具自动放行、`rw` 工具需人工确认;`allow-all` / `deny-all` / `always-ask` 根本不查询它,标成 `rw` 的条目在这些模式下也不会多出一次审批。除此之外该字段什么都不做:不为 Server 提供沙箱,不限制其工具运行时的行为,不会发给 Server、也不向 Server 核验,Server 依旧拥有其 transport 赋予的全部能力。把一个实际能写的 Server 标为 `r`,撤掉的就是 `read-only` 本会索要的那次确认。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 8c1d23f4..98fd2269 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1182,10 +1182,12 @@ export interface SessionInfo {approvalMode: ApprovalMode;/*** Thinking level pinned for this Session (set via PATCH; the Web App's in-chat picker).- * Unset = never pinned: runs that carry no level of their own fall back to the Agent- * config's `model.thinking_level`, so config edits keep taking effect. Once pinned it- * survives reloads and applies to every later run of this Session, and an Agent-config- * change no longer moves it.+ * Unset = never pinned: each model context the Session opens reads the Agent config's+ * `model.thinking_level`, so config edits keep taking effect. Once pinned it survives+ * reloads and applies from the Session's very next LLM request — the thinking level is+ * the soft-limited runtime parameter, changeable mid-context at the cost of the+ * provider's cached context (the picker advises compacting first) — and every later+ * context opens at it; an Agent-config change no longer moves it.*/thinkingLevel?: ThinkingLevelName;/** Short title auto-generated by the model after the first turn; unset until generated (frontend shows "New Chat"). */@@ -1334,9 +1336,10 @@ export interface SessionPatchRequest {approvalMode?: ApprovalMode;/*** Pin this Session's thinking level (`none | low | medium | high | xhigh | max`, anything else- * is a 400). It applies to every later run of the Session that doesn't carry its own- * level, and replaces the Agent-config fallback for this Session. There is no unpin:- * the picker only offers concrete levels.+ * is a 400). It replaces the Agent-config fallback for this Session and applies from the+ * very next LLM request — soft-limited: a mid-context change is allowed, at the cost of+ * the provider's cached context, which is why the picker advises compacting first. There+ * is no unpin: the picker only offers concrete levels.*/thinkingLevel?: ThinkingLevelName;/** Archive / unarchive (default list hides archived). */@@ -1457,14 +1460,6 @@ export type TaskInputPart =export interface TaskCreateRequest {input: TaskInputPart[];- /**- * Thinking level for this Task's LLM requests (a per-turn parameter; one of- * `none | low | medium | high | xhigh | max`, anything else is a 400). Omitted = falls back to- * the Session's pinned level (`SessionInfo.thinkingLevel`) and, when that is unset too,- * to the Agent config's `model.thinking_level`. A queued follow-up (`queueIfBusy`) keeps- * its level and applies it when it auto-starts.- */- thinkingLevel?: ThinkingLevelName;/*** Queue instead of 409 when a Task/compaction is already in progress: the input is held* server-side and auto-starts as an ordinary next task once the session returns to idle@@ -1606,8 +1601,6 @@ export interface RecalledMessageResponse {images: string[];/** The file attachments, re-encoded as base64 data URLs (the shape the composer submits them in). */files: { fileName: string; dataUrl: string }[];- /** Follow-up recall only: the per-turn thinking level the entry was queued with, when one was. */- thinkingLevel?: ThinkingLevelName;}export interface ApprovalDecisionRequest {diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 4728e1f8..ea3ebc45 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -10,8 +10,13 @@ import fs from "node:fs/promises";import path from "node:path";import { Hono } from "hono";import type { Context } from "hono";-import { imageUrlMessage, scratchpadDir, userText } from "@prismshadow/penguin-core";-import type { OmniMessage, ThinkingLevelName } from "@prismshadow/penguin-core";+import {+ THINKING_LEVEL_NAMES,+ imageUrlMessage,+ scratchpadDir,+ userText,+} from "@prismshadow/penguin-core";+import type { OmniMessage } from "@prismshadow/penguin-core";import type {ApprovalMode,FilesStatResponse,@@ -86,16 +91,6 @@ export const APPROVAL_MODES: readonly ApprovalMode[] = ["always-ask",];-/** The valid per-turn thinking level names (TaskCreateRequest.thinkingLevel). */-const THINKING_LEVELS: readonly ThinkingLevelName[] = [- "none",- "low",- "medium",- "high",- "xhigh",- "max",-];-/** Unit-count bounds for windowed history reads (`tailLimit` / `limit`), and the `before` page's default. */const MESSAGES_PAGE_LIMIT_MAX = 1000;const MESSAGES_PAGE_LIMIT_DEFAULT = 200;@@ -355,18 +350,10 @@ function recallStore(* delete their scratchpad copies (nothing references them anymore — leaving them would strand* a second copy when the user resends), and hand the composer-shaped content back.*/-async function recalledResponse(- recall: RecallStore,- thinkingLevel?: ThinkingLevelName,-): Promise<RecalledMessageResponse> {+async function recalledResponse(recall: RecallStore): Promise<RecalledMessageResponse> {const files = await readRecalledFiles(recall.files);await removeAttachments(recall.files.map((f) => f.path));- return {- text: recall.text,- images: recall.images,- files,- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),- };+ return { text: recall.text, images: recall.images, files };}/**@@ -557,7 +544,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const row = resolveSession(c);const body = await readJson(c);const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);- const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVELS);+ const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVEL_NAMES);const archivedRaw = (body as Record<string, unknown>).archived;const archived = typeof archivedRaw === "boolean" ? archivedRaw : undefined;const titleRaw = (body as Record<string, unknown>).title;@@ -599,9 +586,11 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {updated = { ...updated, approvalMode };}if (thinkingLevel !== undefined) {- // Takes effect from the next run on: launchTask/startGoal read the pinned level for- // any run that carries none of its own (a run already in flight keeps its level).+ // The row is what the loader applies at load; a runtime already loaded is assigned+ // here. Soft-limited: core applies it from the Session's very next LLM request (the+ // picker advises compacting first — a change invalidates the provider's cached context).deps.sessionsRepo.updateThinkingLevel(row.sessionId, thinkingLevel);+ deps.manager.setThinkingLevel(row.sessionId, thinkingLevel);updated = { ...updated, thinkingLevel };}if (archived !== undefined) {@@ -887,10 +876,6 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const row = resolveSession(c);const body = await readJson(c);const goal = parseGoalField(body);- // Per-turn thinking level (optional): validated against the level names; omitted follows- // the session's default. In goal mode it rides every round of the goal; a queued- // follow-up keeps its level for its auto-start.- const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVELS);// Resolved per request from the admin settings, so a limit change applies to the very next// upload rather than at the next restart.const limits = toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb());@@ -916,7 +901,6 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const { sessionId } = await deps.manager.startGoal(row.sessionId, {input: messages,budget: goal.budget,- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),});return c.json({ sessionId } satisfies TaskCreateResponse, 202);}@@ -944,7 +928,6 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {try {// 202: the Task executes on the server, decoupled from the SSE connection; sessionId is the current actual id (the new id after self-heal).const { sessionId, queued } = await deps.manager.startTask(row.sessionId, input, {- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),queueIfBusy,// Original content, kept while the input waits in the follow-up queue so a recall// (DELETE /follow-ups/:id) can hand it back; unused when the task starts directly.@@ -1013,7 +996,8 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// Panel message to one subagent child of this session (#272): a user input on the child,// whatever its state — steering while it runs, a follow-up run while it is idle, a revival// (resume-session semantics) when it was released — the same core channel input_subagent- // uses. The optional thinkingLevel pins only a round this message starts. The parent+ // uses. The child runs at its own context's thinking level (pin it through PATCH on the+ // child Session, like any Session). The parent// runtime loads on demand (the same get-or-resume path a task uses). 404 subagent_gone// when the child's record does not exist or cannot be revived; 409 subagent_busy when the// child cannot take the message right now.@@ -1022,7 +1006,6 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const body = await readJson(c);const text = typeof body.text === "string" ? body.text.trim() : "";if (!text) throw badRequest("text must carry the message.");- const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVELS);const outcome = await deps.manager.sendToSubagent(row.sessionId,pathParam(c, "childSessionId"),@@ -1030,7 +1013,6 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// a human typed this (the model's own dispatch through input_subagent stamps// "parent_agent" on its side).[userText(text)],- thinkingLevel,);if (outcome === "gone") {throw new HttpError(@@ -1067,13 +1049,8 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// user and keeps its own code.app.delete("/:sessionId/follow-ups/:followUpId", async (c) => {const row = resolveSession(c);- const { recall, thinkingLevel } = deps.manager.recallFollowUp(- row.sessionId,- pathParam(c, "followUpId"),- );- return c.json(- (await recalledResponse(recall, thinkingLevel)) satisfies RecalledMessageResponse,- );+ const { recall } = deps.manager.recallFollowUp(row.sessionId, pathParam(c, "followUpId"));+ return c.json((await recalledResponse(recall)) satisfies RecalledMessageResponse);});// The Session's most recent goal run (for restoring the chat page's goal banner on load).diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.tsindex 37dd4dd9..02cece25 100644--- a/packages/server/src/http/routes/vault.ts+++ b/packages/server/src/http/routes/vault.ts@@ -50,10 +50,9 @@ export function vaultRoutes(deps: AppDeps): Hono<AppEnv> {deps.projectService.requireProjectOwner(c.var.user.userId, projectId);const req = parseVaultUpdate(await readJson(c));const res = await deps.agentConfigService.updateVault(projectId, agentId, req);- // Effective-value semantics: no hot swap into a Task already in flight, but every- // runtime built before this update is invalidated — the next Task on any Session- // of this Agent re-resumes and picks up the new vault values.- deps.manager.invalidateAgentRuntimes(projectId, agentId);+ // No runtime invalidation: like every Agent State change, the new values reach a+ // running Session at its next compaction (core reads the vault into each model+ // context), and a new Session immediately — the same timing the CLI has.return c.json(res);});diff --git a/packages/server/src/runtime/approvals.ts b/packages/server/src/runtime/approvals.tsindex cdb8abb0..49ca5a2f 100644--- a/packages/server/src/runtime/approvals.ts+++ b/packages/server/src/runtime/approvals.ts@@ -97,6 +97,7 @@ export class ApprovalRegistry {*/export function makeApprove(args: {getMode: () => ApprovalMode;+ /** A tool's permission level, from the running context's toolset (core Session.toolPermission): strict-tier — a permission edit applies when the next context opens. */toolPermission: (name: string) => "r" | "rw" | undefined;registry: ApprovalRegistry;publishRequest: (pending: PendingApproval) => void;diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 52f4729d..db651334 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -8,9 +8,12 @@* createSession using the index row's workspace/modelId, yielding a new session_id* and updating the index's primary key; the Task response body always returns the* current actual id;- * - Vault effectiveness: a vault update bumps the Agent's config generation- * (invalidateAgentRuntimes); runtimes built earlier are discarded on their next- * idle access and re-resumed, so the next Task always runs with current values;+ * - Credential effectiveness: a Project's models/credentials change bumps every affected+ * Agent's config generation (invalidateProjectRuntimes); runtimes built earlier are+ * discarded on their next idle access and re-resumed, so the next Task runs with the+ * 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@@ -114,12 +117,17 @@ export interface RuntimeSession {opts: {approve: ApproveFn;signal: AbortSignal;- thinkingLevel?: ThinkingLevelName;/** Present = goal mode: core loops rounds inside this one run (see core SessionRunOptions). */goal?: { budget?: number };},): AsyncGenerator<OmniMessage>;compact(opts: { signal: AbortSignal }): AsyncGenerator<OmniMessage>;+ /**+ * 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+ * omit it.+ */+ thinkingLevel?: ThinkingLevelName;/** Whether compaction is possible and why; when not ok, compact() yields no messages (see core ContextEngine.compactability). */compactability(): CompactAvailability;/** Queues a mid-run steering input (core `Session.steer`); false when no Task is running. */@@ -133,6 +141,7 @@ export interface RuntimeSession {unsteer?(input: OmniMessage[]): boolean;/** Skips the in-progress reconnect backoff, firing the next retry immediately (core `Session.skipReconnectWait`); false when no wait is in progress. */skipReconnectWait(): boolean;+ /** A tool's permission level from the running context's toolset (core `Session.toolPermission`; strict-tier — rebuilt at rotation). */toolPermission(name: string): "r" | "rw" | undefined;/*** Out-of-band one-shot request for title generation (core `Session.generateTitle`,@@ -177,6 +186,8 @@ export interface RuntimeSession {setSubagentApprovalFallback?(approve: ApproveFn): void;/** Aborts one child session's current run, keeping the session (core `Session.abortBackgroundSubagentRun`); false when unknown or idle. Optional. */abortBackgroundSubagentRun?(childSessionId: string): boolean;+ /** Pins one live child session's thinking level (core `Session.setBackgroundSubagentThinkingLevel`); false when the child is not live. Optional. */+ setBackgroundSubagentThinkingLevel?(childSessionId: string, level: ThinkingLevelName): boolean;/** Subscribes subagent run-state changes (core `Session.onSubagentState`): the manager republishes `task_state` with the fresh live listing. Optional. */onSubagentState?(listener: () => void): void;/** Releases environment resources — kills the remaining background processes (core `Session.dispose`). Optional, idempotent. */@@ -232,7 +243,11 @@ export function createCoreSessionLoader(// config / Trace missing session_meta, etc.) are converged to 409, preserving// the original message rather than bubbling up as 500.try {- return await agent.resumeSession({ sessionId: row.sessionId });+ const session = await agent.resumeSession({ sessionId: row.sessionId });+ // The row's stored level — the knob position the user last chose — restored onto+ // the runtime as a plain assignment: it rides the resumed Session's requests.+ if (row.thinkingLevel) session.thinkingLevel = row.thinkingLevel;+ return session;} catch (err) {// The credential key was deleted after the Session was created: only caught// here at recovery time; give the same actionable message.@@ -258,8 +273,10 @@ export function createCoreSessionLoader(workspaceDir: row.workspace,modelId: row.modelId,provider: row.provider,- // The rebuilt Session re-records a known origin in its fresh session_meta.+ // The rebuilt Session re-records a known origin in its fresh session_meta, and+ // starts its first context at the row's pinned level....(knownSource != null ? { source: knownSource } : {}),+ ...(row.thinkingLevel ? { thinkingLevel: row.thinkingLevel } : {}),});} catch (err) {if (isMissingCredential(err)) throw modelCredentialMissing(row.modelId);@@ -325,12 +342,11 @@ export interface RecallStore {files: RecallableFile[];}-/** One queued follow-up task (`queueIfBusy`): the task input plus the per-turn thinking level it was posted with. */+/** One queued follow-up task (`queueIfBusy`): the task input, held until the session is idle. */interface QueuedFollowUp {/** Recall handle (PendingFollowUpInfo.id), assigned at queue time. */id: string;input: OmniMessage[];- thinkingLevel?: ThinkingLevelName;/*** Original content for recall, and the content `task_state` shows on the queued line.* Always present: a caller that knows more than the input carries (the HTTP route, which@@ -371,8 +387,7 @@ interface RuntimeEntry {/*** Queued follow-up tasks (`queueIfBusy`): task inputs accepted while a Task/compaction was* in progress, auto-started one at a time (in order) once the session returns to idle —- * ordinary tasks with normal semantics, unlike the mid-run steering queue. Each entry- * keeps the per-turn thinkingLevel it was posted with (applied at auto-start).+ * ordinary tasks with normal semantics, unlike the mid-run steering queue.* Deliberately NOT discarded on abort: they are future tasks the user explicitly queued.*/followUps: QueuedFollowUp[];@@ -529,7 +544,7 @@ export class SessionManager {private readonly deletingAgents = new Set<string>();/** Sessions currently being deleted (guards against the entry/Trace file being rebuilt and reviving it inside the deletion race window). */private readonly deletingSessions = new Set<string>();- /** Per-Agent config generation (key = agentKey), bumped by invalidateAgentRuntimes on vault updates. */+ /** Per-Agent config generation (key = agentKey), bumped by invalidateAgentRuntimes when a Project's credentials change. */private readonly agentGenerations = new Map<string, number>();/** Open streaming fragments of running sessions (fed by drive, served to GET /messages; see live-tail.ts). */private readonly liveTail = new LiveTailTracker();@@ -591,7 +606,6 @@ export class SessionManager {sessionId: string,childSessionId: string,messages: OmniMessage[],- thinkingLevel?: ThinkingLevelName,): Promise<SubagentMessageOutcome> {const entry = await this.ensureEntry(sessionId);entry.lastActivityMs = Date.now();@@ -602,12 +616,31 @@ export class SessionManager {: undefined;return ((await entry.session.sendToBackgroundSubagent?.(childSessionId, messages, {- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),...(resume ? { resume } : {}),})) ?? "gone");}+ /**+ * Sets a Session's thinking level on its loaded runtime (core `Session.thinkingLevel`,+ * plain state): the row's value is what the loader applies at load, so this only needs to+ * reach a runtime that is already in the active table — or a live child session, which+ * has an index row and a panel picker of its own but runs inside its parent's runtime.+ * The level is soft-limited: it applies from the Session's very next LLM request+ * (mid-context — the UI advises compacting first, since the change invalidates the+ * provider's cached context). No-op when nothing is loaded.+ */+ setThinkingLevel(sessionId: string, level: ThinkingLevelName): void {+ const session = this.entries.get(sessionId)?.session;+ if (session) {+ session.thinkingLevel = level;+ return;+ }+ for (const entry of this.entries.values()) {+ if (entry.session.setBackgroundSubagentThinkingLevel?.(sessionId, level)) return;+ }+ }+/** Host abort of one child session's current run (core `Session.abortBackgroundSubagentRun`); false when the parent runtime is not loaded, the child is unknown, or it is idle. */abortSubagentRun(sessionId: string, childSessionId: string): boolean {const entry = this.entries.get(sessionId);@@ -750,13 +783,13 @@ export class SessionManager {}/**- * After an Agent's vault is updated: bump the Agent's config generation so every- * runtime built before the update is discarded on its next idle access and- * re-resumed via the loader — resume re-reads agent_state/.vault.toml, so the next- * Task on any of this Agent's Sessions runs with the new values (history is- * preserved through the Trace). A Task already in flight is neither aborted nor- * hot-swapped: it keeps the values it started with, and its entry is rebuilt on- * the first access after it returns to idle (see ensureEntry).+ * Bumps one Agent's config generation so every runtime built before it is discarded on+ * its next idle access and re-resumed via the loader (history is preserved through the+ * Trace). What warrants it is a Session-fixed fact changing under the runtime — the+ * Project's credentials (see invalidateProjectRuntimes). Agent State changes never do:+ * core reads them into the next model context itself. A Task already in flight is neither+ * aborted nor hot-swapped: it keeps the values it started with, and its entry is rebuilt+ * on the first access after it returns to idle (see ensureEntry).*/invalidateAgentRuntimes(projectId: string, agentId: string): void {const key = agentKey(projectId, agentId);@@ -820,12 +853,10 @@ export class SessionManager {* Start a Task: get-or-load → 409* mutual-exclusion check → publish the input messages first → drive run in the* background. Returns the current actual session_id (the new id after self-heal).- * `opts.thinkingLevel` (optional, validated by the route) rides into this run's- * `session.run` options — a per-turn parameter, applied to this Task only.* With `queueIfBusy`, a busy session (running/compacting) enqueues the input as a* follow-up instead of 409: it auto-starts as an ordinary next task once the session- * returns to idle (`queued: true` in the result; see startQueuedFollowUp), keeping its- * thinkingLevel for that auto-start. `opts.recall` is that queued message's original+ * returns to idle (`queued: true` in the result; see startQueuedFollowUp).+ * `opts.recall` is that queued message's original* content — optional, because only the HTTP route knows the parts of it the input does* not carry (the pre-attachment text and where each file landed on disk); every other* caller's store is read off the input, so a queued follow-up is recallable and shows@@ -834,7 +865,7 @@ export class SessionManager {async startTask(sessionId: string,input: OmniMessage[],- opts?: { thinkingLevel?: ThinkingLevelName; queueIfBusy?: boolean; recall?: RecallStore },+ opts?: { queueIfBusy?: boolean; recall?: RecallStore },): Promise<{ sessionId: string; queued: boolean }> {return this.withLock(sessionId, async () => {this.assertOpen();@@ -845,7 +876,6 @@ export class SessionManager {entry.followUps.push({id: randomUUID(),input,- ...(opts.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),// The original content rides the queue so a recall can hand it back, and so the// queued line shows what is waiting (see recallFollowUp). Callers that know more// than the input carries pass their own; the rest get it read off the input.@@ -858,7 +888,7 @@ export class SessionManager {return { sessionId: entry.sessionId, queued: true };}this.assertIdle(entry);- this.launchTask(entry, input, opts?.thinkingLevel);+ this.launchTask(entry, input);return { sessionId: entry.sessionId, queued: false };});}@@ -878,8 +908,6 @@ export class SessionManager {/** Round-1 input (route-validated to carry text; images may ride along); its marker-stripped text is the objective. */input: OmniMessage[];budget: number;- /** Optional per-goal thinking level: rides every round's Task (route-validated). */- thinkingLevel?: ThinkingLevelName;},): Promise<{ sessionId: string }> {return this.withLock(sessionId, async () => {@@ -924,12 +952,9 @@ export class SessionManager {objective,budget: args.budget,});- // Same fallback chain as a task: the goal's own level, else the Session's pinned one.- const thinkingLevel = this.runThinkingLevel(entry.sessionId, args.thinkingLevel);const gen = this.goalStream(entry, {input: args.input,budget: args.budget,- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),approve,signal: ac.signal,...(goalId !== undefined ? { goalId } : {}),@@ -952,7 +977,6 @@ export class SessionManager {args: {input: OmniMessage[];budget: number;- thinkingLevel?: ThinkingLevelName;approve: ApproveFn;signal: AbortSignal;goalId?: number;@@ -961,7 +985,6 @@ export class SessionManager {const gen = entry.session.run(args.input, {approve: args.approve,signal: args.signal,- ...(args.thinkingLevel !== undefined ? { thinkingLevel: args.thinkingLevel } : {}),goal: { budget: args.budget },});let round = 0;@@ -1035,27 +1058,8 @@ export class SessionManager {});}- /** Shared task launch (fresh tasks and auto-started follow-ups): flips to running, publishes the input, and drives the run with the per-turn thinking level (if any). Caller holds the session lock and has verified idle. */- /**- * Thinking level for one run: the level the request carried wins, else the level pinned- * on the Session row (PATCH /api/sessions/:id — the Web App's in-chat picker), else- * undefined so core keeps falling back to the Agent config. Resolved at LAUNCH time, so- * a queued follow-up that carried no level of its own picks up the pin as it stands when- * it finally starts, and a pin set mid-run applies from the next run.- */- private runThinkingLevel(- sessionId: string,- requested?: ThinkingLevelName,- ): ThinkingLevelName | undefined {- return requested ?? this.deps.sessions.findById(sessionId)?.thinkingLevel ?? undefined;- }-- private launchTask(- entry: RuntimeEntry,- input: OmniMessage[],- requestedThinkingLevel?: ThinkingLevelName,- ): void {- const thinkingLevel = this.runThinkingLevel(entry.sessionId, requestedThinkingLevel);+ /** Shared task launch (fresh tasks and auto-started follow-ups): flips to running, publishes the input, and drives the run. Caller holds the session lock and has verified idle. */+ private launchTask(entry: RuntimeEntry, input: OmniMessage[]): void {const channel = this.deps.channels.get(entry.sessionId);const ac = new AbortController();entry.status = "running";@@ -1078,7 +1082,6 @@ export class SessionManager {const gen = entry.session.run(input, {approve,signal: ac.signal,- ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),});// This call's input user text is the whole title source: drive persists its first// words as the immediate fallback and hands it to the LLM as the generation material@@ -1107,7 +1110,7 @@ export class SessionManager {const entry = this.entries.get(sessionId);if (!entry || entry.status !== "idle" || entry.followUps.length === 0) return;const next = entry.followUps.shift()!;- this.launchTask(entry, next.input, next.thinkingLevel);+ this.launchTask(entry, next.input);});} catch (err) {this.log(`[followup] auto-start failed: ${err instanceof Error ? err.message : String(err)}`);@@ -1222,10 +1225,7 @@ export class SessionManager {* `not_pending`, because the two mean different things to the user — a follow-up became a* task of its own, a steering message reached the model mid-run.*/- recallFollowUp(- sessionId: string,- followUpId: string,- ): { recall: RecallStore; thinkingLevel?: ThinkingLevelName } {+ recallFollowUp(sessionId: string, followUpId: string): { recall: RecallStore } {const entry = this.entries.get(sessionId);const i = entry?.followUps.findIndex((f) => f.id === followUpId) ?? -1;const queued = i >= 0 ? entry!.followUps[i]! : undefined;@@ -1239,10 +1239,7 @@ export class SessionManager {entry.followUps.splice(i, 1);entry.lastActivityMs = Date.now();this.publishState(entry, entry.status);- return {- recall: queued.recall,- ...(queued.thinkingLevel !== undefined ? { thinkingLevel: queued.thinkingLevel } : {}),- };+ return { recall: queued.recall };}/**@@ -1533,8 +1530,8 @@ export class SessionManager {if (existing.generation === this.generationOf(existing.projectId, existing.agentId)) {return existing;}- // Built before the last vault update: discard once idle and fall through to a- // fresh load (resume re-reads the vault). A busy entry is returned as-is — the+ // Built before the last credential change: discard once idle and fall through to a+ // fresh load (resume re-reads the Project config). A busy entry is returned as-is — the// in-flight run keeps its values and assertIdle rejects the new Task anyway;// it is rebuilt on the first access after it finishes.if (@@ -1554,7 +1551,7 @@ export class SessionManager {"Session does not exist or you do not have access.",);}- // Captured before the (awaited) load: a vault update racing with the load leaves+ // Captured before the (awaited) load: an invalidation racing with the load leaves// this entry stale, so the access after next rebuilds it with the new values.const generation = this.generationOf(row.projectId, row.agentId);const session = await this.deps.loader.load(row);@@ -1562,6 +1559,10 @@ export class SessionManager {// don't rebuild the entry (avoids reviving an orphaned Trace).this.assertSessionNotDeleting(row.sessionId);this.assertAgentNotDeleting(row.sessionId);+ // A thinking-level PATCH that landed during the (awaited) load updated the row but found+ // no entry to assign, and the loader applied the snapshot's level: re-read the pin.+ const pin = this.deps.sessions.findById(row.sessionId)?.thinkingLevel;+ if (pin && pin !== row.thinkingLevel) session.thinkingLevel = pin;let currentId = row.sessionId;if (session.sessionId !== row.sessionId) {// Self-heal produced a new session_id: update the index's primary key; the SSEdiff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.tsindex 982b8c19..d75934d4 100644--- a/packages/server/src/services/agent-config-service.ts+++ b/packages/server/src/services/agent-config-service.ts@@ -37,6 +37,7 @@ import {resolveMCPServer,saveAgentVault,systemConfigPath,+ THINKING_LEVEL_NAMES,} from "@prismshadow/penguin-core";import type {MCPServerConfig,@@ -67,14 +68,6 @@ import {} from "../http/validate.js";import { maskApiKey } from "./project-config-service.js";-const THINKING_LEVELS: readonly ThinkingLevelName[] = [- "none",- "low",- "medium",- "high",- "xhigh",- "max",-];const COMPACTION_MODES = ["summarize", "discard"] as const;function asRecord(v: unknown): Record<string, unknown> {@@ -332,7 +325,7 @@ export class AgentConfigService {);setIfProvided(["model", "thinking_level"],- optionalEnum(model, "thinkingLevel", THINKING_LEVELS),+ optionalEnum(model, "thinkingLevel", THINKING_LEVEL_NAMES),);setIfProvided(["model", "timeoutMs"],diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.tsindex e3b85d1e..d887039f 100644--- a/packages/server/test/followup.test.ts+++ b/packages/server/test/followup.test.ts@@ -101,7 +101,7 @@ describe("follow-up queue route", () => {await waitFor(() => t.deps.manager.statusOf(SID) === "idle");});- it("recall (#287): DELETE withdraws a queued follow-up with its content and thinking level; the rest auto-start", async () => {+ it("recall (#287): DELETE withdraws a queued follow-up with its content; the rest auto-start", async () => {await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "task 1" }] });await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);@@ -112,7 +112,6 @@ describe("follow-up queue route", () => {{ type: "image_url", imageUrl: png },],queueIfBusy: true,- thinkingLevel: "high",});await api.post(`/api/sessions/${SID}/tasks`, {input: [{ type: "text", text: "follow-up 2" }],@@ -124,15 +123,10 @@ describe("follow-up queue route", () => {{ id: expect.any(String), text: "follow-up 2", images: 0, files: 0 },]);- // The recall returns the original content plus the per-turn level it was queued with.+ // The recall returns the original content.const res = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);expect(res.status).toBe(200);- expect(await res.json()).toEqual({- text: "follow-up 1",- images: [png],- files: [],- thinkingLevel: "high",- });+ expect(await res.json()).toEqual({ text: "follow-up 1", images: [png], files: [] });expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(1);// Recalled means never started: only the remaining follow-up auto-starts.diff --git a/packages/server/test/goals.test.ts b/packages/server/test/goals.test.tsindex b9bd535c..4e2b3708 100644--- a/packages/server/test/goals.test.ts+++ b/packages/server/test/goals.test.ts@@ -147,7 +147,7 @@ describe("SessionManager.startGoal", () => {db.close();});- type RunOpts = { thinkingLevel?: string; goal?: { budget?: number } };+ type RunOpts = { goal?: { budget?: number } };/*** Fake session: `run` asserts it was called in goal mode and emits the whole goal stream@@ -170,10 +170,7 @@ describe("SessionManager.startGoal", () => {skipReconnectWait: () => false,async *run(input: OmniMessage[], opts) {runs.push(input);- runOpts.push({- ...(opts.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),- ...(opts.goal !== undefined ? { goal: opts.goal } : {}),- });+ runOpts.push({ ...(opts.goal !== undefined ? { goal: opts.goal } : {}) });yield* stream(input);},async *compact() {},@@ -207,16 +204,12 @@ describe("SessionManager.startGoal", () => {const events: ChannelEvent[] = [];channels.get(ROW.sessionId).subscribe((e) => events.push(e));- await manager.startGoal(ROW.sessionId, {- input: [userText(text)],- budget: -1,- thinkingLevel: "high",- });+ await manager.startGoal(ROW.sessionId, { input: [userText(text)], budget: -1 });await waitFor(() => manager.statusOf(ROW.sessionId) === "idle");- // One run call carries the whole goal: the input verbatim, the per-goal thinking- // level, and the goal option (core loops the rounds internally).- expect(session.runOpts).toEqual([{ thinkingLevel: "high", goal: { budget: -1 } }]);+ // One run call carries the whole goal: the input verbatim and the goal option (core+ // loops the rounds internally).+ expect(session.runOpts).toEqual([{ goal: { budget: -1 } }]);const server = events.filter((e) => e.event === "server_event")diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.tsindex 36747ef2..fbac3d02 100644--- a/packages/server/test/session-index.test.ts+++ b/packages/server/test/session-index.test.ts@@ -768,17 +768,6 @@ describe("session-index", () => {expect(list.sessions.find((s) => s.sessionId === session.sessionId)?.tracePath).toBeUndefined();});- it("rejects an invalid per-task thinkingLevel with 400 (five names only)", async () => {- await configureModels();- const res = await api.post(base(), {});- const { session } = (await res.json()) as SessionCreateResponse;- const bad = await api.post(`/api/sessions/${session.sessionId}/tasks`, {- input: [{ type: "text", text: "hi" }],- thinkingLevel: "ultra",- });- expect(bad.status).toBe(400);- });-it("rejects a malformed goal.budget with 400", async () => {await configureModels();const res = await api.post(base(), {});diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.tsindex b0631c2b..c3bc2e20 100644--- a/packages/server/test/session-manager.test.ts+++ b/packages/server/test/session-manager.test.ts@@ -275,30 +275,79 @@ describe("session-manager", () => {expect(recordedErrors.map((e) => e.code)).toContain("session_touch_failed");});- it("startTask forwards thinkingLevel into session.run options (per-turn, this Task only)", async () => {+ it("startTask carries no thinking level: the manager assigns runtime state instead", async () => {sessions.updateApprovalMode("session-1", "allow-all");- const seen: (string | undefined)[] = [];+ const runOpts: Record<string, unknown>[] = [];const fake: RuntimeSession = {sessionId: "session-1",toolPermission: () => "rw",+ thinkingLevel: undefined,generateTitle: async () => ({ title: null, usage: null }),compactability: () => "ok" as const,steer: () => false,skipReconnectWait: () => false,- async *run(_input: OmniMessage[], opts: { thinkingLevel?: string }) {- seen.push(opts.thinkingLevel);+ async *run(_input: OmniMessage[], opts: Record<string, unknown>) {+ runOpts.push(opts);yield assistantText("ok");},async *compact(): AsyncGenerator<OmniMessage> {},};const manager = makeManager(loaderOf(fake));- await manager.startTask("session-1", [userText("a")], { thinkingLevel: "high" });- await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 1);- // Omitted on the next Task, with nothing pinned on the Session row either: nothing is- // forwarded and core falls back to the Agent config.- await manager.startTask("session-1", [userText("b")]);- await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 2);- expect(seen).toEqual(["high", undefined]);+ await manager.startTask("session-1", [userText("a")]);+ await waitFor(() => manager.statusOf("session-1") === "idle" && runOpts.length === 1);+ expect("thinkingLevel" in runOpts[0]!).toBe(false);+ // What the Web App's in-chat picker writes reaches the loaded runtime as a plain+ // assignment (core applies it from the next request); a Session that is not loaded is a+ // no-op — the loader assigns the row's level when it loads.+ manager.setThinkingLevel("session-1", "xhigh");+ manager.setThinkingLevel("session-nowhere", "low");+ expect(fake.thinkingLevel).toBe("xhigh");+ });++ it("setThinkingLevel reaches a live child session through its parent's runtime", async () => {+ sessions.updateApprovalMode("session-1", "allow-all");+ const childPins: [string, string][] = [];+ const fake: RuntimeSession = {+ ...approvalFakeSession("session-1"),+ setBackgroundSubagentThinkingLevel: (childSessionId, level) => {+ if (childSessionId !== "child-1") return false;+ childPins.push([childSessionId, level]);+ return true;+ },+ };+ const manager = makeManager(loaderOf(fake));+ await manager.startTask("session-1", [userText("a")]);+ await waitFor(() => manager.statusOf("session-1") === "idle");+ // A child has an index row and a panel picker of its own but no entry: the PATCH lands+ // on the child Session inside the parent runtime. An unknown id stays a no-op.+ manager.setThinkingLevel("child-1", "high");+ manager.setThinkingLevel("child-nowhere", "low");+ expect(childPins).toEqual([["child-1", "high"]]);+ });++ it("a thinking-level PATCH racing the runtime load reaches the loaded runtime", async () => {+ sessions.updateApprovalMode("session-1", "allow-all");+ const fake: RuntimeSession = { ...approvalFakeSession("session-1"), thinkingLevel: undefined };+ let release!: () => void;+ const gate = new Promise<void>((r) => (release = r));+ // The loader applies the row it was handed — a snapshot taken before the await.+ const loader: SessionLoader = {+ load: async (row) => {+ await gate;+ if (row.thinkingLevel) fake.thinkingLevel = row.thinkingLevel;+ return fake;+ },+ };+ const manager = makeManager(loader);+ const started = manager.startTask("session-1", [userText("a")]);+ // The PATCH route's two writes land while the load is in flight: the row updates, the+ // runtime assignment finds no entry yet.+ sessions.updateThinkingLevel("session-1", "xhigh");+ manager.setThinkingLevel("session-1", "xhigh");+ release();+ await started;+ await waitFor(() => manager.statusOf("session-1") === "idle");+ expect(fake.thinkingLevel).toBe("xhigh");});it("a background notice arriving while idle auto-starts a task carrying the taken notices", async () => {@@ -465,8 +514,7 @@ describe("session-manager", () => {agent_state: dir,workspace: dir,},- bootstrap: async () => ({ tools: await environment.listTools(), llm, mcp: [] }),- mcpServers: [],+ bootstrap: async () => ({ llm }),environment,imagesDir: path.join(dir, "images"),modelHasVision: true,@@ -502,36 +550,6 @@ describe("session-manager", () => {}});- it("a level pinned on the Session applies to later Tasks that carry none (a request's own level still wins)", async () => {- sessions.updateApprovalMode("session-1", "allow-all");- const seen: (string | undefined)[] = [];- const fake: RuntimeSession = {- sessionId: "session-1",- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,- async *run(_input: OmniMessage[], opts: { thinkingLevel?: string }) {- seen.push(opts.thinkingLevel);- yield assistantText("ok");- },- async *compact(): AsyncGenerator<OmniMessage> {},- };- const manager = makeManager(loaderOf(fake));- // What the Web App's in-chat picker writes (PATCH /api/sessions/:id).- sessions.updateThinkingLevel("session-1", "xhigh");- await manager.startTask("session-1", [userText("a")]);- await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 1);- await manager.startTask("session-1", [userText("b")], { thinkingLevel: "low" });- await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 2);- // Re-pinning applies from the next Task on.- sessions.updateThinkingLevel("session-1", "medium");- await manager.startTask("session-1", [userText("c")]);- await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 3);- expect(seen).toEqual(["xhigh", "low", "medium"]);- });-it("LLM / tool failures in the message stream are persisted via drive (source=llm / environment, with the current Session context)", async () => {sessions.updateApprovalMode("session-1", "allow-all");const captured: ErrorRecordArgs[] = [];diff --git a/packages/server/test/session-subagents.test.ts b/packages/server/test/session-subagents.test.tsindex 601a45fc..bb6f10a0 100644--- a/packages/server/test/session-subagents.test.ts+++ b/packages/server/test/session-subagents.test.ts@@ -2,8 +2,7 @@* Integration tests for the panel's subagent endpoints and the child-liveness broadcast:* - POST /api/sessions/:id/subagents/:childSessionId/message — a user input on the child,* whatever its state: {outcome:"steered"} while it runs, {outcome:"started"} while idle,- * {outcome:"resumed"} when the released child was revived; the optional thinkingLevel- * rides through to the round the message starts, and the resume option carries the+ * {outcome:"resumed"} when the released child was revived; the resume option carries the* child's owning agent from its session row; 404 subagent_gone when nothing can be* revived, 409 subagent_busy when the child cannot take the message, 400 without text;* - POST /api/sessions/:id/subagents/:childSessionId/abort — 202 when a run was aborted,@@ -149,7 +148,6 @@ describe("session subagent routes and liveness", () => {const idle = await api.post(`/api/sessions/${SID}/subagents/${CHILD_IDLE}/message`, {text: "one more round",- thinkingLevel: "high",});expect(idle.status).toBe(200);expect((await idle.json()) as SubagentMessageResponse).toEqual({ outcome: "started" });@@ -157,8 +155,7 @@ describe("session subagent routes and liveness", () => {expect(sent).toHaveLength(2);expect(sent[0]!.childSessionId).toBe(CHILD_RUNNING);expect(sent[0]!.text).toBe("focus on the tests");- // The per-turn thinking level rides through to core.- expect(sent[1]!.opts?.thinkingLevel).toBe("high");+ expect(sent[1]!.text).toBe("one more round");});it("message: a released child with a session row revives (outcome resumed, owning agent resolved)", async () => {diff --git a/packages/server/test/vault.test.ts b/packages/server/test/vault.test.tsindex 7e83130e..8b6eb46e 100644--- a/packages/server/test/vault.test.ts+++ b/packages/server/test/vault.test.ts@@ -4,8 +4,8 @@* is never sent), PUT is owner-only, whole-table replace semantics (omitting* value keeps the original, an absent key is deleted, a new key must supply a* value), 400 on key/shape validation, 404 for a nonexistent Agent, vaults of- * different Agents are independent of each other, and PUT invalidates the Agent's- * cached Session runtimes (the next Task re-resumes and sees the new values).+ * different Agents are independent of each other, and PUT leaves the Agent's cached+ * Session runtimes alone (core reads the vault into each Session's next model context).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { userText } from "@prismshadow/penguin-core";@@ -139,7 +139,7 @@ describe("vault api", () => {expect(modelsBody.models[0]!.credential).toBeTruthy();});- it("PUT invalidates the Agent's cached Session runtimes: the next Task re-resumes and picks up the new vault", async () => {+ it("PUT leaves the Agent's cached Session runtimes alone: the vault reaches a running Session at its next compaction, not by a rebuild", async () => {t.deps.sessionsRepo.insert({sessionId: "vault-sess-1",projectId,@@ -161,19 +161,19 @@ describe("vault api", () => {await waitFor(idle);expect(loads).toBe(1);- // Vault update via the API: the cached runtime is stale, so the next Task re-resumes- // (the loader re-reads .vault.toml — the new value reaches the next Task's environment).+ // Vault update via the API: the cached runtime stays — no re-resume. The Session's+ // running model context keeps the environment it opened with (a context's+ // configuration never changes mid-life), and core assembles the new vault into the+ // next context it opens, exactly as the CLI's in-process Session does.const put = await owner.put(vaultPath, { entries: [{ key: "NEW_KEY", value: "v-secret-1" }] });expect(put.status).toBe(200);await t.deps.manager.startTask("vault-sess-1", [userText("c")]);await waitFor(idle);- expect(loads).toBe(2);-- // Reads don't invalidate: the rebuilt runtime is reused.+ expect(loads).toBe(1);expect((await owner.get(vaultPath)).status).toBe(200);await t.deps.manager.startTask("vault-sess-1", [userText("d")]);await waitFor(idle);- expect(loads).toBe(2);+ expect(loads).toBe(1);});it("Agent-level isolation: different Agents' vaults are independent; a nonexistent Agent 404", async () => {diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex b5ccc985..d6c027ac 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -760,16 +760,11 @@ export const postSteer = (sessionId: string, body: SteerRequest) =>body,});-/** Panel message to one subagent child (#272) — a user input on the child, whatever its state: steered mid-run, started on an idle child, resumed when the released session was revived; the optional thinkingLevel pins only a round this message starts. 404 subagent_gone when nothing can be revived, 409 subagent_busy when the child cannot take it right now. */-export const messageSubagent = (- sessionId: string,- childSessionId: string,- text: string,- thinkingLevel?: string,-) =>+/** Panel message to one subagent child (#272) — a user input on the child, whatever its state: steered mid-run, started on an idle child, resumed when the released session was revived (the child runs at its own Session's thinking level; pin it with patchSession). 404 subagent_gone when nothing can be revived, 409 subagent_busy when the child cannot take it right now. */+export const messageSubagent = (sessionId: string, childSessionId: string, text: string) =>apiFetch<SubagentMessageResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/subagents/${encodeURIComponent(childSessionId)}/message`,- { method: "POST", body: { text, ...(thinkingLevel ? { thinkingLevel } : {}) } },+ { method: "POST", body: { text } },);/** Panel stop for one subagent child (#272): aborts only its CURRENT run — the session survives for follow-ups (202 aborted; 204 when already idle/unknown). */diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsxindex c95845f6..7992f597 100644--- a/packages/web/src/features/agents/agent-settings-page.tsx+++ b/packages/web/src/features/agents/agent-settings-page.tsx@@ -200,7 +200,7 @@ export function AgentSettingsPage() {try {const res = await api.putAgentConfig(projectId, agentId, update);setData(res);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);// Name/description changes affect the breadcrumb and list display; a builtin-tools// change moves the card's tool count.if (diff --git a/packages/web/src/features/agents/mcp-servers-section.tsx b/packages/web/src/features/agents/mcp-servers-section.tsxindex 0fa740d6..4d7d3462 100644--- a/packages/web/src/features/agents/mcp-servers-section.tsx+++ b/packages/web/src/features/agents/mcp-servers-section.tsx@@ -171,7 +171,7 @@ export function McpServersSection({config: { mcpServers: next },});setServers(res.config.mcpServers);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);return null;} catch (e) {return apiErrorText(e);diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex a2ec7380..807656db 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -263,7 +263,7 @@ export function MemoryTab({config: { memory: { enabled: next } },});setEnabled(res.config.memory.enabled);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);onConfigChanged?.();} catch (e) {toastError(apiErrorText(e));@@ -320,7 +320,7 @@ export function MemoryTab({.then((res) => {setMemoryPrompt(res.config.memory.prompt);setWorkspacePrompt(res.config.memory.workspacePrompt);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);onConfigChanged?.();}).catch((e: unknown) => toastError(apiErrorText(e)));diff --git a/packages/web/src/features/agents/prompt-injection-controls.tsx b/packages/web/src/features/agents/prompt-injection-controls.tsxindex e42897df..e531a71f 100644--- a/packages/web/src/features/agents/prompt-injection-controls.tsx+++ b/packages/web/src/features/agents/prompt-injection-controls.tsx@@ -137,7 +137,7 @@ export function usePromptInjection({try {const res = await api.putAgentConfig(projectId, agentId, featurePatch({ enabled: next }));applyConfig(res.config);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);onConfigChanged?.();} catch (e) {toastError(apiErrorText(e));@@ -159,7 +159,7 @@ export function usePromptInjection({const dto = await insert(projectId, agentId);setState(dto);setPrompt(dto.prompt);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);onConfigChanged?.();} catch (e) {toastError(apiErrorText(e));@@ -174,7 +174,7 @@ export function usePromptInjection({.putAgentConfig(projectId, agentId, featurePatch({ prompt })).then((res) => {applyConfig(res.config);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);onConfigChanged?.();}).catch((e: unknown) => toastError(apiErrorText(e)));diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsxindex 51877933..2aee12d6 100644--- a/packages/web/src/features/agents/schedules-tab.tsx+++ b/packages/web/src/features/agents/schedules-tab.tsx@@ -351,7 +351,7 @@ export function SchedulesTab({if (form.editing !== null) await api.updateSchedule(projectId, agentId, form.editing, body);else await api.createSchedule(projectId, agentId, { name, ...body });setForm(null);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);await load();// A created schedule moves the agent card's count; refresh the list provider too.void reloadAgents();@@ -380,7 +380,7 @@ export function SchedulesTab({// Model reference is resent as a whole pair or not at all — never half of one....(model ? { modelId: model.modelId, provider: model.provider } : {}),});- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);await load();} catch (e) {toastError(apiErrorText(e));diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsxindex ad798b2d..9ad6987e 100644--- a/packages/web/src/features/agents/skills-tab.tsx+++ b/packages/web/src/features/agents/skills-tab.tsx@@ -174,7 +174,7 @@ export function SkillsTab({setBusy(true);try {await api.removeAgentSkill(projectId, agentId, removing);- toastSuccess(S.skills.uninstalledToast(removing, agentName));+ toastSuccess(`${S.skills.uninstalledToast(removing, agentName)}${S.agent.takesEffectSuffix}`);await load();// The agent card's skill count changed; refresh the list provider too.void reloadAgents();@@ -247,7 +247,7 @@ export function SkillsTab({});setOverwriting(null);setImportOpen(false);- toastSuccess(S.skills.importDoneToast);+ toastSuccess(`${S.skills.importDoneToast}${S.agent.takesEffectSuffix}`);await load();// The agent card's skill count changed; refresh the list provider too.void reloadAgents();diff --git a/packages/web/src/features/agents/vault-tab.tsx b/packages/web/src/features/agents/vault-tab.tsxindex d5d4eeb7..90ebbbe4 100644--- a/packages/web/src/features/agents/vault-tab.tsx+++ b/packages/web/src/features/agents/vault-tab.tsx@@ -96,7 +96,7 @@ export function VaultTab({try {const res = await api.putVault(projectId, agentId, body);setEntries(res.entries);- toastSuccess(S.common.saved);+ toastSuccess(S.agent.savedTakesEffect);// Add / delete moves the agent card's vault-key count; refresh the list provider too.void reloadAgents();return null;diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex e5dc3beb..5c5c5c31 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -338,6 +338,7 @@ function ThinkingLevelSelect({onChange,disabled,direction = "down",+ note,}: {/** Level to display and mark selected ("" = none to show yet); null = the Agent config is still loading (draft). */value: string | null;@@ -345,6 +346,8 @@ function ThinkingLevelSelect({disabled: boolean;/** Popup direction: down for the draft card (room below), up for the bottom-docked session composer. */direction?: "down" | "up";+ /** Footnote under the rows — the session variant's pre-pick reminder: a change applies right away but invalidates the model's cached context, so compacting first is recommended. */+ note?: string;}) {const [open, setOpen] = useState(false);const label =@@ -398,6 +401,11 @@ function ThinkingLevelSelect({<span className="w-3 shrink-0 text-center">{level === value ? "✓" : ""}</span></button>))}+ {note && (+ <div className="max-w-56 border-t border-gray-100 px-3 pb-1 pt-1.5 text-[11px] leading-snug text-gray-400 dark:border-gray-800 dark:text-gray-500">+ {note}+ </div>+ )}</Dropdown>);}@@ -901,16 +909,15 @@ export function ChatInput({*/onChangeThinkingLevel?: (level: string) => void;/**- * Session state: the per-turn thinking level to DISPLAY — the parent resolves it as "the+ * Session state: the Session's thinking level to DISPLAY — the parent resolves it as "the* user's pick for this session, else the Agent config's level" ("" = neither known yet),- * so the picker auto-follows the config until touched. The send path is the parent's own- * state: while untouched nothing is sent with tasks (the server/core fallback applies and- * mid-session Agent-config edits keep taking effect); an explicit pick sticks and is sent- * with every subsequent task, never writing through to the Agent config (that behavior- * stays draft-only).+ * so the picker auto-follows the config until touched. A pick is the parent's own state:+ * it pins the level on the Session (PATCH), and core applies it from the next LLM request+ * (soft-limited; the menu note advises compacting first); nothing rides a task. Never+ * written through to the Agent config (that behavior stays draft-only).*/turnThinkingLevel?: string;- /** Session state: pins the per-turn thinking level for this session; also enables the editable picker. */+ /** Session state: pins the thinking level on this session (effective from its next LLM request); also enables the editable picker. */onChangeTurnThinkingLevel?: (level: string) => void;/** Model's context window (from models config; when not configured, the ring's cap falls back to 128000 via resolveContextWindow). */contextWindow?: number;@@ -2565,16 +2572,19 @@ export function ChatInput({disabled={busy}/>)}- {/* Session state: per-turn thinking level (editable) — displays the user's pick,- else the Agent config's level (auto-follow; the parent resolves it). While- untouched nothing rides on tasks; a pick sticks for the session and is sent- with every subsequent send, never writing through to the Agent config. */}+ {/* Session state: the Session's pinned thinking level (editable) — displays the+ user's pick, else the Agent config's level (auto-follow; the parent resolves+ it). A pick is pinned on the Session (PATCH) and applies from the next LLM+ request (soft-limited): the menu's footnote reminds, before the pick, that the+ change costs the model's cached context and compacting first is recommended —+ never writing through to the Agent config. */}{!onChangeModel && onChangeTurnThinkingLevel && (<ThinkingLevelSelectvalue={turnThinkingLevel ?? ""}onChange={onChangeTurnThinkingLevel}disabled={busy}direction="up"+ 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). */}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 182f74db..dda44981 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -27,7 +27,6 @@ import type {SessionProcessInfo,SessionStatus,SkillMetadataItem,- TaskCreateRequest,TaskInputPart,} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";@@ -507,10 +506,11 @@ export function ChatPage() {// The thinking level pinned on THIS Session, read straight off the Session row// (SessionInfo.thinkingLevel, written by the picker through PATCH — see// applyTurnThinkingLevel): "" = never pinned, and the picker then displays the Agent- // config's level while sends omit thinkingLevel (auto-follow — the server/core fallback- // applies, so Agent-config edits keep taking effect). A pin is DURABLE: it survives a- // reload, shows up in a second tab, and the server applies it to every later run of this- // Session. It is still never written through to the Agent config (that stays draft-only).+ // config's level (auto-follow — each model context reads the config, so Agent-config edits+ // keep taking effect). A pin is DURABLE: it survives a reload, shows up in a second tab,+ // and core applies it from the Session's next LLM request on (soft-limited — the picker's+ // menu advises compacting first, since the change invalidates the model's cached+ // context). It is still never written through to the Agent config (that stays draft-only).const turnThinkingLevel = selected?.thinkingLevel ?? "";useEffect(() => {if (selectedSessionId && selectedAgentId) setCurrentAgentId(selectedAgentId);@@ -981,15 +981,11 @@ export function ChatPage() {async (input: TaskInputPart[], goal: { budget: number } | null): Promise<boolean> => {if (!selected) return false;try {- // An explicitly picked per-turn thinking level rides on each task; "" (untouched)- // sends nothing — the server/core falls back to the Agent config, so config edits- // keep taking effect mid-session until the user pins a level.+ // No thinking level rides a task: the level belongs to the model context (pinned on+ // the Session through PATCH, see applyTurnThinkingLevel).const res = await api.postTask(selected.sessionId, {input,...(goal ? { goal } : {}),- ...(turnThinkingLevel- ? { thinkingLevel: turnThinkingLevel as TaskCreateRequest["thinkingLevel"] }- : {}),});discardSessionDraft();await syncHealedSessionId(selected.sessionId, res.sessionId);@@ -1117,13 +1113,7 @@ export function ChatPage() {async (input: TaskInputPart[]): Promise<boolean> => {if (!selected) return false;try {- const res = await api.postTask(selected.sessionId, {- input,- queueIfBusy: true,- ...(turnThinkingLevel- ? { thinkingLevel: turnThinkingLevel as TaskCreateRequest["thinkingLevel"] }- : {}),- });+ const res = await api.postTask(selected.sessionId, { input, queueIfBusy: true });discardSessionDraft();await syncHealedSessionId(selected.sessionId, res.sessionId);return true;@@ -1169,11 +1159,10 @@ export function ChatPage() {);// 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). Modeled on+ // 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// onChangeApprovalMode — a failed write surfaces as a toast and leaves the level as it- // was, rather than showing a level the server does not have. Declared above the recall- // callbacks because one of them lists it as a dependency, which is evaluated during- // render rather than when the callback runs.+ // was, rather than showing a level the server does not have.const applyTurnThinkingLevel = useCallback((level: string) => {if (!selected) return;@@ -1211,18 +1200,16 @@ export function ChatPage() {async (followUpId: string) => {if (!selected) return null;try {- const res = await api.recallFollowUp(selected.sessionId, followUpId);- // The follow-up was queued with a per-turn thinking level: restore it with the draft,- // so an unedited resend goes out exactly as it was queued. The level now lives on the- // Session (#310), so restoring it pins it there rather than in local state.- if (res.thinkingLevel) applyTurnThinkingLevel(res.thinkingLevel);- return res;+ // A queued follow-up carries no thinking level of its own: the level lives on the+ // Session and applies per model context, so a resend goes out at whatever the Session+ // is pinned to.+ return await api.recallFollowUp(selected.sessionId, followUpId);} catch (e) {toastError(apiErrorText(e));return null;}},- [selected, applyTurnThinkingLevel],+ [selected],);const onApprove = useCallback(diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsxindex 589743eb..e2b08e85 100644--- a/packages/web/src/features/chat/subagents-view.tsx+++ b/packages/web/src/features/chat/subagents-view.tsx@@ -26,13 +26,15 @@ import type {ApprovalMode,ModelInfo,SessionInfo,+ SessionPatchRequest,SkillMetadataItem,SubagentRuntimeInfo,TaskInputPart,} from "@prismshadow/penguin-server/api";import { ApiError } from "../../api/client";-import { abortSubagent, getAgentSkills, messageSubagent } from "../../api/endpoints";+import { abortSubagent, getAgentSkills, messageSubagent, patchSession } from "../../api/endpoints";import { toastError } from "../../components/ui/toast";+import { apiErrorText } from "../../lib/api-error";import { S } from "../../lib/strings";import type { NestedSessionMeta, StreamModel } from "../../lib/omni/stream-model";import { ChatInput } from "./chat-input";@@ -361,9 +363,16 @@ function SubagentComposer({};}, [projectId, meta?.agentId]);- // Per-turn thinking level for the child's NEXT round ("" = untouched, follow the child's- // own config): mirrors the main composer's per-session pick, scoped to this child.+ // The level pinned on the child Session from this panel ("" = untouched, the child runs at+ // its own level): mirrors the main composer's per-session pick, scoped to this child —+ // written through PATCH on the child; core applies it from the child's next LLM request.const [turnLevel, setTurnLevel] = useState("");+ const pinChildLevel = (level: string): void => {+ setTurnLevel(level);+ void patchSession(childSessionId, {+ thinkingLevel: level as SessionPatchRequest["thinkingLevel"],+ }).catch((err: unknown) => toastError(apiErrorText(err)));+ };const modelRef = meta ? { provider: meta.provider, modelId: meta.modelId } : null;const contextWindow = modelRef@@ -371,8 +380,7 @@ function SubagentComposer({?.contextWindow: undefined;- const send = (text: string) =>- messageSubagent(sessionId, childSessionId, text, turnLevel || undefined);+ const send = (text: string) => messageSubagent(sessionId, childSessionId, text);const sendFailure = (err: unknown): void => {toastError(err instanceof ApiError && err.code === "subagent_gone"@@ -422,10 +430,10 @@ function SubagentComposer({modelRef={modelRef}models={models}// Display: the user's pick for this child, else what the child actually runs at- // (spawn-pinned level, else the parent's effective level it inherited). Only an- // explicit pick rides the send (see messageSubagent's thinkingLevel).+ // (spawn-pinned level, else the parent's effective level it inherited). A pick is+ // PATCHed onto the child Session and applies from its next LLM request.turnThinkingLevel={turnLevel || fallbackThinkingLevel}- onChangeTurnThinkingLevel={setTurnLevel}+ onChangeTurnThinkingLevel={pinChildLevel}{...(contextWindow !== undefined ? { contextWindow } : {})}contextNow={contextNow}vision={false}diff --git a/packages/web/src/features/skills/skills-page.tsx b/packages/web/src/features/skills/skills-page.tsxindex 9823faf7..d9544d46 100644--- a/packages/web/src/features/skills/skills-page.tsx+++ b/packages/web/src/features/skills/skills-page.tsx@@ -236,10 +236,10 @@ export function SkillsPage() {if (on) {const res = await api.installAgentSkills(projectId, agentId, [name]);calibrateAgent(agentId, res.skills);- toastSuccess(S.skills.installedToast(name, agentName));+ toastSuccess(`${S.skills.installedToast(name, agentName)}${S.agent.takesEffectSuffix}`);} else {await api.removeAgentSkill(projectId, agentId, name);- toastSuccess(S.skills.uninstalledToast(name, agentName));+ toastSuccess(`${S.skills.uninstalledToast(name, agentName)}${S.agent.takesEffectSuffix}`);}} catch (e) {// A 404 on uninstall means "was already not installed": the targetdiff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsxindex 528d3bf2..a2d633d0 100644--- a/packages/web/src/features/traces/trace-event-row.tsx+++ b/packages/web/src/features/traces/trace-event-row.tsx@@ -189,9 +189,9 @@ function SessionMetaBody({ p }: { p: Record<string, unknown> }) {["source", String(p.source ?? "")],["model_id", String(p.model_id ?? "")],["context_window", String(p.model_context_window ?? "")],- // Legacy metas only: current traces no longer record a thinking level (it became a- // per-turn Task parameter), but old traces still carry the field — keep showing it- // for them (loose read) instead of losing the display.+ // Legacy metas only: current traces no longer record a thinking level (it is a+ // per-request Session parameter), but old traces still carry the field — keep showing+ // it for them (loose read) instead of losing the display....(typeof p.thinking_level === "string" && p.thinking_level? ([["thinking_level", p.thinking_level]] as Array<[string, string]>): []),diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 94fc6e7a..aa23788e 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -455,6 +455,10 @@ export const en: Strings = {},agent: {+ savedTakesEffect:+ "Saved. New conversations pick it up right away; running ones after their next compaction.",+ takesEffectSuffix:+ " — new conversations pick it up right away, running ones after their next compaction",listTitle: "Agents",create: "Create agent",createTitle: "Create agent",@@ -1228,6 +1232,8 @@ export const en: Strings = {},chat: {+ thinkingLevelChangeNote:+ "Applies right away. Changing it invalidates the model's cached context — compacting first is recommended.",newSessionMenu: "New chat",chooseAgent: "Choose agent",chooseModel: "Choose model",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 39d232a4..0f1a239a 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -448,6 +448,14 @@ export const zh = {},agent: {+ /**+ * Toast after a save on this page: when the change reaches a Session. Core assembles the+ * Agent State into each model context, so a running conversation sees it only after its+ * next compaction; a new conversation starts with it.+ */+ savedTakesEffect: "已保存。新对话立即生效;进行中的对话在下一次压缩后生效。",+ /** Appended to an action's own toast (skill install / uninstall) — same timing statement. */+ takesEffectSuffix: ";新对话立即生效,进行中的对话在下一次压缩后生效",listTitle: "Agents",create: "创建 Agent",createTitle: "创建 Agent",@@ -1192,6 +1200,8 @@ export const zh = {},chat: {+ /** Footnote of the session picker's menu — the pre-pick reminder: a change applies right away but costs the model's cached context, so compacting first is recommended. */+ thinkingLevelChangeNote: "立即生效。更换思考等级会使模型缓存失效,建议先压缩上下文。",newSessionMenu: "新建对话",chooseAgent: "选择 Agent",chooseModel: "选择模型",