Skip to content

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

feat: subagents take mid-run steering and a per-run stop from the model and the panel (#433)

Yaowei Zhengd4c27099ad77
diff --git a/changelog/unreleased/2026-08-24-subagent-steering.md b/changelog/unreleased/2026-08-24-subagent-steering.md
new file mode 100644
index 00000000..b728b421
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-subagent-steering.md
@@ -0,0 +1,109 @@
+# Subagents take mid-run messages and a per-run stop — from the model and from the panel
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#433](https://github.com/Prism-Shadow/penguin-harness/pull/433)
+- **Issue:** [#272](https://github.com/Prism-Shadow/penguin-harness/issues/272), [#274](https://github.com/Prism-Shadow/penguin-harness/issues/274)
+
+[中文版](2026-08-24-subagent-steering.zh.md)
+
+A subagent used to be a fire-and-observe affair: `input_subagent` rejected a prompt while
+the child was still running, and the panel offered no way to correct or stop a child at
+all — stopping the main agent left its children running. Both gaps close with one
+mechanism: the same steering channel a user already has into the main session, applied to
+the child session, reachable by the model and the human alike.
+
+## For the model (`input_subagent`)
+
+- A `prompt` sent while the child **runs** is now injected mid-run as a steering message —
+ delivered as a `[user_steering]` message at the child's next step, written to the child's
+ Trace with sender `parent_agent`, streamed live to the panel. The old "still running"
+ error is gone (it remains only for third-party SDK handles that predate steering).
+- New `abort` argument: stops the child's **current run only**, like a user pressing stop —
+ the session survives for steering and follow-up prompts, unlike `kill_subagent`'s
+ terminate-and-remove. Combined with a `prompt`, the aborted run settles first and the
+ prompt starts a fresh round: interrupt and redirect in one call.
+- `input_subagent`'s model-facing output is now the child's **most recent complete reply** —
+ an idempotent "what it last said" snapshot on every access, instead of an incremental
+ delta drain (completion reports carry the same snapshot; the frontend's live rendering
+ still flows through the origin-tagged messages).
+- A released `subagent_id` **revives automatically** when the model messages it again: the
+ registry keeps a tombstone (child session id + spawn-time agent) per registration, and the
+ same resume path the panel uses brings the session back under the same id. The only error
+ left is an id this conversation never allocated.
+- The tool descriptions teach all of it. The built-in default change advances the config
+ kernel version (`2026-08-24`); existing Agents keep their stored descriptions until a
+ kernel update or restore-defaults, while the behavior itself applies to every session
+ immediately.
+
+## No kill for subagents; commands fold kill into input_command
+
+A subagent session is like the main agent: always resumable, never destroyed — so the kill
+notion is gone. `kill_subagent` is **removed** (stopping a run is `abort`; releasing an idle
+session is just freeing its slot, and a released id revives on the next message). A command's
+process IS a real OS object that gets destroyed, so its termination becomes a parameter:
+`kill_command` merges into `input_command` as `kill: true` (disarm the completion report,
+drain undelivered output, SIGTERM→SIGKILL the process group, drop the session — exactly the
+old tool's behavior). No backward compatibility is kept for the two removed tool names: a
+stale stored config's entries simply stop assembling, and a model calling them gets the
+standard unknown-tool failure. An explicitly aborted subagent round also sends no completion
+report — the aborter reads the outcome directly.
+
+## For the user (subagents panel)
+
+- The selected child is driven by the **same composer as the main conversation** (a subagent
+ variant of the one component): text body, skills and slash skill commands, a per-turn
+ thinking level (applies to the round the message starts), the context ring showing 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 judged by. The stop control is the
+ composer's running-state stop face, right where the main conversation has it. Goal mode,
+ image/file attachments, `/model`, `/agent`, `/compact` and the follow-up queue are not
+ offered — a child has no semantics for them.
+- A message is a user input on the child **whatever its state**: steering while it runs, a
+ follow-up round while it is idle — and when the session was already released (finished in
+ a foreground window, killed, or the server restarted), it is **revived** through the
+ resume-session path: same history, model and Workspace, re-managed under the parent (the
+ model can address it again by its `subagent_id`), and the message starts its next round.
+ "This subagent has ended" is no longer a dead end; the only error left is a session whose
+ record no longer exists.
+- Two endpoints serve this (`POST /api/sessions/:id/subagents/:childSessionId/message` with
+ optional `thinkingLevel`, and `…/abort`), routed through the parent session's runtime —
+ loaded on demand like a task would, so it works after a restart. Children are reachable
+ from spawn (a child still inside `run_subagent`'s foreground window included), and the
+ first host-path touch attaches the live forwarding tap, so a panel-driven child streams
+ to the frontend without waiting for the model's next poll.
+- The panel stays put: it shows the most recent Task that actually spawned subagents, so a
+ plain follow-up message no longer wipes the graph — a new Task takes the panel over the
+ moment it spawns its own child.
+- The thinking picker shows what the child actually runs at while untouched: the user's own
+ pick for this child, else the spawning call's explicit `thinking_level`, else the parent
+ session's effective level (what the child inherited); only an explicit pick rides the send.
+- A panel-started round sends **no background completion report** to the main conversation:
+ reports cover model-initiated rounds only (the `run_in_background` launch and
+ `input_subagent` follow-ups) — the user talking to a child is not dispatched work, and the
+ main agent no longer receives "background task finished" notices for it. The round's
+ answer text stays in the model-facing buffer for the model's next poll.
+
+## Child approvals reach the user
+
+A background child that hit a tool approval used to get auto-denied — the parent task's end
+converged every pending approval, and a child with no active poll window had no way to ask.
+Both halves are fixed: the web server now attaches a session-lifetime fallback approval sink
+(child approvals with no window and no background-launch standing sink escalate to the user
+as ordinary approval cards, the parent session sitting idle included), and a parent task
+ending or being stopped converges only the **main** session's approvals — an origin-tagged
+child approval stays pending, and its card stays rendered, until the user decides. The CLI
+keeps the poll-window-only semantics (it attaches no fallback sink).
+
+## Live child states (issue #274)
+
+Child running marks were previously inferred by parsing tool-output text
+(`still running` / `idle` notes), which froze the checkmark, stopped the elapsed timer,
+and flickered the status after `input_subagent` revived a finished child. Run state is now
+structural: every child run start/settle pings the host, the server folds
+`{sessionId, running}` of all live children into `task_state` events and the SSE subscribe
+snapshot, and the panel consults that first — the text heuristics remain only as the
+fallback for dead runtimes, old servers, and historical sessions. The delivered
+`[user_steering]` message also keeps the queued input's sender, so the child's Trace
+records who interjected.
diff --git a/changelog/unreleased/2026-08-24-subagent-steering.zh.md b/changelog/unreleased/2026-08-24-subagent-steering.zh.md
new file mode 100644
index 00000000..12eac893
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-subagent-steering.zh.md
@@ -0,0 +1,40 @@
+# 子智能体支持运行中插话与逐轮停止——模型与面板同一通道
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#433](https://github.com/Prism-Shadow/penguin-harness/pull/433)
+- **Issue:** [#272](https://github.com/Prism-Shadow/penguin-harness/issues/272), [#274](https://github.com/Prism-Shadow/penguin-harness/issues/274)
+
+[English](2026-08-24-subagent-steering.md)
+
+此前子智能体是「发射后只能旁观」:`input_subagent` 对仍在运行的子会话直接拒绝 prompt,面板上更没有任何纠偏或停止子智能体的手段——停掉主智能体后子智能体依然在跑。这次用同一套机制补齐两侧:把用户对主会话已有的 steering 通道原样用到子会话上,模型与人都能触达。
+
+## 模型侧(`input_subagent`)
+
+- 子会话**运行中**发送的 `prompt` 现在作为 steering 插话注入——在子会话下一步以 `[user_steering]` 消息送达、写入子 Trace(sender 记为 `parent_agent`)、实时流到面板。原「still running」报错不再出现(仅对早于 steering 的第三方 SDK handle 保留)。
+- 新增 `abort` 参数:只停止子会话**当前这一轮**,等价于用户按停止——会话保留、可继续插话或续跑,与 `kill_subagent` 的「终止并移除」相区分。与 `prompt` 同给时先等被中止的一轮收束、再以该 prompt 开新一轮:一次调用完成打断并改道。
+- `input_subagent` 的模型面输出改为子会话**最近一条完整回复**——每次访问都是「它最后说了什么」的幂等快照,而非增量 delta 排空(完成回报携带同一快照;前端实时渲染仍经 origin 消息流)。
+- 已释放的 `subagent_id` 在模型再次发消息时**自动复活**:注册表按次记录墓碑(子 Session id + 派生时 agent),与面板同一条 resume 路径把会话按原 id 找回来。唯一剩下的报错是本对话从未分配过的 id。
+- 工具描述同步教会模型全部用法。内置默认变更照例前进配置内核版本(`2026-08-24`);存量 Agent 的已存描述在内核更新或还原默认前保持不变,行为本身对所有会话立即生效。
+
+## Subagent 没有 kill;命令的 kill 併入 input_command
+
+子会话与主 Agent 同构:永远可 resume、不存在销毁——kill 概念因此取消。`kill_subagent` **删除**(停一轮是 `abort`;释放空闲会话只是腾并发额度,已释放的 id 下次收到消息即复活)。命令的进程是真实会被销毁的 OS 对象,终止因此变成参数:`kill_command` 併入 `input_command` 的 `kill: true`(先解除完成回报监视、排空未交付输出、整进程组 SIGTERM→SIGKILL 并移除会话——与原工具行为一致)。两个被删工具名不留兼容:存量配置里的旧条目不再装配,模型按旧名调用得到标准的未知工具报错。被显式 `abort` 结束的子会话轮同样不发完成回报——打断者当场读到结局。
+
+## 用户侧(智能体面板)
+
+- 选中的子会话由**与主对话相同的 composer**驱动(同一组件的子会话变体):正文、技能与 slash 技能命令、per-turn 思考等级(作用于这条消息开启的一轮)、显示子会话自身用量的上下文圆环、锁定模型徽标,以及审批模式选择——它读写父会话的模式,子会话审批本就按其判定。停止就是 composer 的运行态停止面,与主对话同位。goal 模式、图片/文件附件、`/model`、`/agent`、`/compact` 与排队 follow-up 不提供——子会话没有这些语义。
+- 发消息就是对子会话的一次用户输入,**无论其状态**:运行中即插话,空闲即续跑一轮;会话已被释放时(前台窗口内跑完、被 kill、或服务端重启过)则经 **resume 口径复活**——沿用其历史、模型与 Workspace,重新纳管回父会话(模型也能重新以 `subagent_id` 触达),这条消息随即开启它的下一轮。「该子智能体已结束」不再是死胡同;唯一剩下的报错是会话记录已不存在。
+- 两个端点承载(`POST /api/sessions/:id/subagents/:childSessionId/message`(可选 `thinkingLevel`)与 `…/abort`),经父会话运行时路由——按需装载(与发任务同一条 get-or-resume 路径),重启后照样可用。子会话自派生起即可触达(含仍在 `run_subagent` 前台窗口内的),宿主路径首次触达即挂实时转发 tap,面板驱动的子会话不必等模型下次轮询即实时上屏。
+- 面板不再乱跳:默认展示最近一次**真正派生过子智能体**的 Task,普通追问消息不再清空调用图——新 Task 一旦派生自己的子智能体即接管面板。
+- 思考等级选择器在未触碰时显示子会话**实际运行的等级**:用户对该子会话的选择 > 派生调用显式 `thinking_level` > 父会话生效等级(即继承值);仅显式选择随消息发送。
+- 面板发起的轮**不给主对话发后台完成回报**:回报只覆盖模型自己发起的轮(`run_in_background` 启动轮与 `input_subagent` 续跑轮)——用户和子智能体说话不是模型派发的工作,主智能体不再为此收到「后台任务完成」通知;该轮答案文本留在模型面缓冲,模型下次轮询照常取得。
+
+## 子会话审批上报用户
+
+后台子会话撞上工具审批时此前会被自动拒绝——父任务结束会收敛全部未决审批,而没有活跃轮询窗口的子会话根本无处提问。两半都已修复:Web 服务端为每个会话运行时挂**会话生命周期的兜底审批出口**(没有窗口、也没有后台启动常驻出口的子会话审批,作为普通审批卡直接上报用户,父会话空闲时亦然);父任务结束或被停止时只收敛**主会话**自身的审批——带 origin 的子会话审批保持待决、审批卡持续显示,直到用户决定。CLI 未挂兜底出口,保持窗口内审批的旧口径。
+
+## 子会话状态实况(issue #274)
+
+面板此前靠解析工具输出文本(`still running` / `idle` 注记)推断子会话运行态,`input_subagent` 复活已结束的子会话后就会出现对勾冻结、耗时停走、「运行中 / 运行完毕」反复闪烁。运行态改为结构化实况:每轮启动与收束都上报宿主,服务端把全部存活子会话的 `{sessionId, running}` 并入 `task_state` 事件与 SSE 订阅快照,面板优先采用实况——文本启发只作为已死运行时、旧服务端与历史会话的回退。steering 送达消息还保留入队消息的 sender,子 Trace 由此记得是谁在插话。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 29307803..183110bf 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -58,11 +58,11 @@ import type {
} from "./omnimessage/index.js";
import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";
import { INPUT_SUBAGENT_NAME } from "./environment/tools/input-subagent.js";
-import { KILL_SUBAGENT_NAME } from "./environment/tools/kill-subagent.js";
import type { CompactionSettings } from "./engine/context-engine.js";
import type {
GenerativeModelConfig,
ProxyEnvPolicy,
+ SubagentHandle,
SubagentRunner,
ThinkingLevelName,
ToolDefinition,
@@ -700,68 +700,102 @@ export class Agent {
subagentDepth: subagentDepth + 1,
source: "subagent",
});
- // All child-session messages are tagged with an origin (the child Session id,
- // prepended as one hop from outer to inner); the first turn forwards the
- // child's session_meta first (including agent_state and other metadata) so the
- // parent frontend can recognize the nested session (for rendering, stats,
- // approval visibility); the parent Trace skips these accordingly (the child
- // Session has its own Trace, linked by session id).
- const hop: MessageOrigin = childSession.sessionId;
- let metaSent = false;
- return {
- sessionId: hop,
- // One-shot upfront meta for background launches (see SubagentHandle.takeMeta):
- // shares metaSent with run, so the meta reaches the parent stream exactly once
- // whichever side sends it first.
- takeMeta() {
- if (metaSent) return null;
- metaSent = true;
- return withOrigin(childSession.metaMessage, hop);
- },
- async *run({ prompt, signal, approve }) {
- if (!metaSent) {
- metaSent = true;
- yield withOrigin(childSession.metaMessage, hop);
- }
- // Pass through the parent's approval callback: the child Session inherits
- // the parent Agent's approval mode (with no callback, the child engine
- // defaults to deny). The tool_call received for approval also carries the
- // origin, so the approval UI can identify which tool a subagent is calling.
- const childApprove = approve
- ? (tc: OmniMessage<ToolCallPayload>) => approve(withOrigin(tc, hop))
- : undefined;
- // The engine writes a run's input to the CHILD's own Trace but never replays
- // it to its consumer (a session's normal caller typed that input itself) —
- // here the consumer is the PARENT, whose frontend has never seen the child's
- // prompt. Forward the input message itself (origin-tagged, ahead of the run's
- // output) so the live nested view shows the child's user side exactly like a
- // reloaded one (history expansion splices the child Trace, which carries this
- // same message). The parent engine drops origin messages from the parent
- // Trace, so replay never duplicates it. Later rounds (input_subagent
- // follow-up prompts) come through this same generator and are forwarded the
- // same way.
- // sender "parent_agent": in the child's Trace this user turn came from the
- // parent agent (run_subagent's prompt / input_subagent's follow-up), not a human.
- const input = userText(prompt, "parent_agent");
- yield withOrigin(input, hop);
- for await (const msg of childSession.run([input], {
- ...(signal ? { signal } : {}),
- ...(childApprove ? { approve: childApprove } : {}),
- })) {
- yield withOrigin(msg, hop);
- }
- },
- dispose() {
- childSession.dispose();
- },
- };
+ return subagentHandleFor(childSession);
+ },
+ // Revival: a RELEASED child session resumes with its own history, model and Workspace
+ // (resumeSession semantics) — reached by the panel and by input_subagent on a released
+ // id alike. The owning Agent comes from the caller's record (the host's session
+ // registry, or the spawn-time tombstone); omitted or self-owned reuses the parent
+ // Agent instance.
+ async resume({ agentId, sessionId }) {
+ if (agentId !== undefined) assertValidId("agent_id", agentId);
+ const childAgent =
+ agentId === undefined || agentId === parentAgentId
+ ? parentAgent
+ : await createAgent({
+ root,
+ projectId,
+ agentId,
+ ...(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),
+ });
+ const childSession = await childAgent.resumeSession({ sessionId });
+ return subagentHandleFor(childSession);
},
};
+ /**
+ * Wraps a child Session as a SubagentHandle — shared by spawn and resume. All
+ * child-session messages are tagged with an origin (the child Session id, prepended as
+ * one hop from outer to inner); the first turn forwards the child's session_meta first
+ * (including agent_state and other metadata) so the parent frontend can recognize the
+ * nested session (for rendering, stats, approval visibility); the parent Trace skips
+ * these accordingly (the child Session has its own Trace, linked by session id).
+ */
+ function subagentHandleFor(childSession: Session): SubagentHandle {
+ const hop: MessageOrigin = childSession.sessionId;
+ let metaSent = false;
+ return {
+ sessionId: hop,
+ // One-shot upfront meta for background launches (see SubagentHandle.takeMeta):
+ // shares metaSent with run, so the meta reaches the parent stream exactly once
+ // whichever side sends it first.
+ takeMeta() {
+ if (metaSent) return null;
+ metaSent = true;
+ return withOrigin(childSession.metaMessage, hop);
+ },
+ async *run({ prompt, signal, approve, thinkingLevel: turnThinkingLevel }) {
+ if (!metaSent) {
+ metaSent = true;
+ yield withOrigin(childSession.metaMessage, hop);
+ }
+ // Pass through the parent's approval callback: the child Session inherits
+ // the parent Agent's approval mode (with no callback, the child engine
+ // defaults to deny). The tool_call received for approval also carries the
+ // origin, so the approval UI can identify which tool a subagent is calling.
+ const childApprove = approve
+ ? (tc: OmniMessage<ToolCallPayload>) => approve(withOrigin(tc, hop))
+ : undefined;
+ // The engine writes a run's input to the CHILD's own Trace but never replays
+ // it to its consumer (a session's normal caller typed that input itself) —
+ // here the consumer is the PARENT, whose frontend has never seen the child's
+ // prompt. Forward the input message itself (origin-tagged, ahead of the run's
+ // output) so the live nested view shows the child's user side exactly like a
+ // reloaded one (history expansion splices the child Trace, which carries this
+ // same message). The parent engine drops origin messages from the parent
+ // Trace, so replay never duplicates it. Later rounds (input_subagent
+ // follow-up prompts) come through this same generator and are forwarded the
+ // same way.
+ // sender "parent_agent": in the child's Trace this user turn came from the
+ // parent agent (run_subagent's prompt / input_subagent's follow-up), not a human.
+ const input = userText(prompt, "parent_agent");
+ yield withOrigin(input, hop);
+ for await (const msg of childSession.run([input], {
+ ...(signal ? { signal } : {}),
+ ...(childApprove ? { approve: childApprove } : {}),
+ ...(turnThinkingLevel !== undefined ? { thinkingLevel: turnThinkingLevel } : {}),
+ })) {
+ yield withOrigin(msg, hop);
+ }
+ },
+ // Mid-run steering rides the child Session's own steering queue — the same
+ // mechanism a user steers the main session with. The queued message keeps its
+ // caller-chosen sender ("parent_agent" from input_subagent, none from a human
+ // panel), and the delivered [user_steering] message streams back out through
+ // `run` with the origin hop like every other child message.
+ steer(messages) {
+ return childSession.steer(messages);
+ },
+ 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, input_subagent or kill_subagent
- // (the latter two depend on the subagent_id produced by the former, so exposing
- // them alone is meaningless).
+ // 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
@@ -774,7 +808,9 @@ export class Agent {
(d) =>
d.name !== SUBAGENT_NAME &&
d.name !== INPUT_SUBAGENT_NAME &&
- d.name !== KILL_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 };
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 422614c3..b07d0fc6 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -66,6 +66,7 @@ import type {
OmniMessage,
StopReason,
TextPayload,
+ TextSender,
ThinkingPayload,
TokenCounts,
TokenUsagePayload,
@@ -619,11 +620,17 @@ export class ContextEngine {
const fold = input.some(isImageMessage) ? this.deps.foldInputImages : undefined;
const messages = fold ? await fold(input) : input;
const texts: string[] = [];
+ // The delivered [user_steering] message keeps the queued input's sender: a parent agent
+ // steering its child (input_subagent) records as "parent_agent" in the child's Trace,
+ // while human steering keeps the field absent — origin stays a structural fact.
+ let sender: TextSender | undefined;
const rest: OmniMessage[] = [];
for (const msg of messages) {
- const p = msg.payload as { type?: string; role?: string; text?: string };
- if (p.type === "text" && p.role === "user") texts.push(p.text ?? "");
- else rest.push(msg);
+ const p = msg.payload as { type?: string; role?: string; text?: string; sender?: TextSender };
+ if (p.type === "text" && p.role === "user") {
+ texts.push(p.text ?? "");
+ sender ??= p.sender;
+ } else rest.push(msg);
}
// `foldInputImages` is public API, so a third-party adapter can return something else, and
// both ways it can break lose the picture: an image that survived the fold goes to the one
@@ -633,7 +640,7 @@ export class ContextEngine {
if (fold && (rest.some(isImageMessage) || texts.length === 0)) {
throw new Error("foldInputImages must return the input's images folded into a user text.");
}
- return [userText(userSteeringText(texts.join("\n\n"))), ...rest];
+ return [userText(userSteeringText(texts.join("\n\n")), sender), ...rest];
}
/** The actual Task loop behind `run` (split out so run's finally can close the steering window on every exit path). */
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index b34e132d..0461b378 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -28,13 +28,18 @@
* Docs: /docs/tools § "Execution contract".
*/
import path from "node:path";
-import { partialToolCallOutput, toolCallOutput } from "../omnimessage/index.js";
+import { partialToolCallOutput, toolCallOutput, userText } from "../omnimessage/index.js";
import type { McpServerConnectResult, OmniMessage, StopReason } from "../omnimessage/index.js";
import type {
+ ApproveFn,
BackgroundCommandInfo,
+ BackgroundSubagentInfo,
BackgroundTaskDoneEvent,
EnvironmentConfig,
EnvironmentInterface,
+ SubagentMessageOptions,
+ SubagentMessageOutcome,
+ SubagentRunner,
ToolConfig,
ToolDefinition,
ToolExecutionRequest,
@@ -44,7 +49,7 @@ import type { BuiltinTool, ToolResult } from "./tools/types.js";
import { BUILTIN_TOOL_FACTORIES } from "./tools/registry.js";
import { McpToolProvider } from "./mcp/provider.js";
import { CommandSessionManager } from "./tools/command/index.js";
-import { SubagentSessionManager } from "./tools/subagent/index.js";
+import { ManagedSubagentSession, SubagentSessionManager } from "./tools/subagent/index.js";
import {
TRUNCATED_TOOL_OUTPUT_FILE_LIMIT_BYTES,
TruncatedToolOutputArchive,
@@ -146,6 +151,8 @@ export class Environment implements EnvironmentInterface {
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;
constructor(config: EnvironmentConfig) {
this.workspaceDir = config.workspaceDir;
@@ -165,6 +172,7 @@ export class Environment implements EnvironmentInterface {
...(config.proxyEnv !== undefined ? { proxyEnv: config.proxyEnv } : {}),
});
this.subagentSessions = new SubagentSessionManager();
+ this.subagentRunner = config.services?.subagentRunner ?? null;
const services = {
...config.services,
commandSessions: this.commandSessions,
@@ -269,6 +277,120 @@ export class Environment implements EnvironmentInterface {
return this.subagentSessions.hasRunning();
}
+ /** All live subagent child sessions, foreground-window ones included (see EnvironmentInterface.listBackgroundSubagents). */
+ listBackgroundSubagents(): BackgroundSubagentInfo[] {
+ return this.subagentSessions.listLive();
+ }
+
+ /**
+ * Host-initiated message to one child session — a user's input on the child, whatever its
+ * state: steering mid-run, a follow-up run when idle, a revival through the runner when the
+ * session is no longer live (see EnvironmentInterface.sendToBackgroundSubagent). Converges
+ * on the same managed-session channel input_subagent uses; the message carries no sender
+ * (human origin), unlike the model path's "parent_agent". `opts.thinkingLevel` pins only a
+ * round this call starts — steering cannot change the round already in flight.
+ */
+ async sendToBackgroundSubagent(
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome> {
+ const session = this.subagentSessions.bySessionId(childSessionId);
+ if (!session) return this.resumeAndRun(childSessionId, text, opts);
+ this.attachHostTap(session);
+ if (session.steer([userText(text)])) return "steered";
+ if (session.running) return "busy";
+ 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(text, {
+ ...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),
+ suppressDoneReport: true,
+ });
+ } catch {
+ return "gone";
+ }
+ return "started";
+ }
+
+ /**
+ * The resume fallback of sendToBackgroundSubagent: revives the released child Session
+ * (resumeSession semantics via SubagentRunner.resume), re-manages it — live index,
+ * background registration (so the model can address it again by subagent_id), forwarding
+ * tap, and the host approval fallback via track — and starts its next round with the text.
+ */
+ private async resumeAndRun(
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome> {
+ const agentId = opts?.resume?.agentId;
+ const runner = this.subagentRunner;
+ if (agentId === undefined || !runner?.resume || this.subagentSessions.isDisposed) {
+ return "gone";
+ }
+ // Same admission rule as a spawn: never evict a running child to make room.
+ if (!this.subagentSessions.makeRoom()) return "busy";
+ let session: ManagedSubagentSession;
+ try {
+ session = new ManagedSubagentSession(
+ await runner.resume({ agentId, sessionId: childSessionId }),
+ { resumeAgentId: agentId },
+ );
+ } catch {
+ return "gone"; // No trace to resume from, or the agent is gone: nothing to revive.
+ }
+ this.subagentSessions.track(session);
+ this.subagentSessions.register(session);
+ this.attachHostTap(session);
+ try {
+ // Host-initiated like the started path: no completion notice at the parent.
+ session.startRun(text, {
+ ...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),
+ suppressDoneReport: true,
+ });
+ } catch {
+ return "gone";
+ }
+ return "resumed";
+ }
+
+ /** Host-initiated abort of one child session's current run (see EnvironmentInterface.abortBackgroundSubagentRun). */
+ abortBackgroundSubagentRun(childSessionId: string): boolean {
+ const session = this.subagentSessions.bySessionId(childSessionId);
+ if (!session) return false;
+ this.attachHostTap(session);
+ return session.abortRun();
+ }
+
+ /** Attaches the single subagent run-state listener (see EnvironmentInterface.setSubagentStateListener). */
+ setSubagentStateListener(listener: () => void): void {
+ this.subagentSessions.setStateListener(() => {
+ if (!this.bgDisposed) listener();
+ });
+ }
+
+ /** Attaches the host's session-lifetime fallback approval sink for child sessions (see EnvironmentInterface.setSubagentApprovalFallback). */
+ setSubagentApprovalFallback(approve: ApproveFn): void {
+ this.subagentSessions.setApprovalFallback((toolCall) =>
+ this.bgDisposed ? Promise.resolve("deny") : approve(toolCall),
+ );
+ }
+
+ /**
+ * A host touching a child proves a live-forwarding consumer exists, so attach the message
+ * tap on first touch: the child's messages then reach the frontend the moment they are
+ * produced instead of waiting for the model's next poll. Model-facing text buffering and
+ * poll semantics are unchanged; background launches already attached this tap at launch.
+ */
+ private attachHostTap(session: {
+ hasMessageTap: boolean;
+ setMessageTap(tap: (msg: OmniMessage) => void): void;
+ }): void {
+ if (session.hasMessageTap) return;
+ session.setMessageTap((msg) => this.emitBackgroundForward(msg));
+ }
+
/** Kills one background command process (whole process group) and drops it from the registry; false when the id is unknown. */
killBackgroundCommand(processId: string): boolean {
return this.commandSessions.kill(processId);
diff --git a/packages/core/src/environment/tools/exec-command.ts b/packages/core/src/environment/tools/exec-command.ts
index 95ef7ca0..0a4a44d3 100644
--- a/packages/core/src/environment/tools/exec-command.ts
+++ b/packages/core/src/environment/tools/exec-command.ts
@@ -94,7 +94,7 @@ export function createExecCommandTool(
// run_in_background: no collect window at all — register immediately, arm the completion
// report, and hand back the process_id. When the foreground process exits, the report
// reaches the conversation as a harness user message (see armCommandDoneReport); the
- // model can still poll/steer it with input_command or stop it with kill_command meanwhile.
+ // model can still poll/steer it — or terminate it — with input_command meanwhile.
if (background) {
const id = manager.register(session);
armCommandDoneReport(session, id, services);
@@ -102,7 +102,7 @@ export function createExecCommandTool(
stopReason: "completed",
note:
`[command running in background with process_id ${id}; its completion will arrive ` +
- `as a user message — no need to poll. Use input_command to interact or kill_command to stop it]`,
+ `as a user message — no need to poll. Use input_command to interact (kill: true stops it)]`,
};
}
@@ -143,7 +143,7 @@ export function createExecCommandTool(
* Arms the completion report of a background-launched command: when the foreground process
* reaches a terminal state, the report (id, exit facts, tail of the yet-undelivered output)
* goes to `services.backgroundDone` — the Session turns it into a harness user message.
- * `kill_command` disarms it first (a deliberate kill reports its outcome synchronously), and a
+ * input_command's kill disarms it first (a deliberate kill reports its outcome synchronously), and a
* disposed Environment drops the event (see Environment.emitBackgroundDone).
*/
export function armCommandDoneReport(
diff --git a/packages/core/src/environment/tools/input-command.ts b/packages/core/src/environment/tools/input-command.ts
index e9ec4198..1467c5da 100644
--- a/packages/core/src/environment/tools/input-command.ts
+++ b/packages/core/src/environment/tools/input-command.ts
@@ -9,6 +9,13 @@
* running, returns the same `process_id`; once exited, returns the trailing output and exit
* status and cleans up the session.
*
+ * `kill: true` terminates the session instead (a process is a real OS object — unlike a
+ * subagent session, it IS destroyed): the pending completion report is disarmed first (this
+ * call reads the outcome right here), the yet-undelivered output drains as this call's own
+ * output, then the whole process group is killed (SIGTERM, escalating to SIGKILL) and the
+ * session leaves the registry. Works on already-exited sessions too (reports the recorded
+ * exit and removes the row).
+ *
* Shares the same `CommandSessionManager` injected by Environment with exec_command. An
* interruption only cancels this poll — **it does not kill the background process** (the process
* was started independently earlier; interrupting one poll shouldn't kill it as a side effect).
@@ -65,6 +72,31 @@ export function createInputCommandTool(
return { stopReason: "failed" };
}
+ // Termination path (kill: true): disarm the report, drain, kill the group, drop the row.
+ if (args["kill"] === true) {
+ session.clearExitWatchers();
+ const pending = session.drainPending();
+ if (pending) yield delta(pending);
+ const wasRunning = session.running;
+ const exit = session.exit;
+ manager.kill(processId);
+ if (wasRunning) {
+ return {
+ stopReason: "completed",
+ note: `[process ${processId} killed (SIGTERM to the process group, SIGKILL after a grace period)]`,
+ };
+ }
+ const status = session.error
+ ? `spawn error: ${session.error.message}`
+ : exit?.signal != null
+ ? `terminated by signal ${exit.signal}`
+ : `exit code ${exit?.code ?? "unknown"}`;
+ return {
+ stopReason: "completed",
+ note: `[process ${processId} had already exited (${status}); session removed]`,
+ };
+ }
+
const chars = typeof args["chars"] === "string" ? (args["chars"] as string) : "";
const empty = chars.length === 0;
const yieldMs = clampYield(
diff --git a/packages/core/src/environment/tools/input-subagent.ts b/packages/core/src/environment/tools/input-subagent.ts
index b7f84e7d..18bacc6e 100644
--- a/packages/core/src/environment/tools/input-subagent.ts
+++ b/packages/core/src/environment/tools/input-subagent.ts
@@ -2,28 +2,34 @@
* input_subagent —— accesses a subagent session that `run_subagent` moved to the background
* (BuiltinTool).
*
- * Finds the session by `subagent_id`: when `prompt` is empty, nothing is written — it just
- * polls (collecting subagent messages and text deltas buffered during the background period,
- * or waiting for the run to end); when non-empty and the subagent is idle, it's fed in as a new
- * user message to continue on the same child Session (long-running subagent, multi-turn
- * conversation); when non-empty but the subagent is still running, it errors, suggesting to
- * poll first. Within the window, queued approval requests from the child session are also
- * passed through (see subagent/session.ts).
+ * A message here is the parent agent's input on the child, exactly like a user's input on any
+ * agent: when `prompt` is empty it just polls; when non-empty and the subagent is idle, it
+ * continues the same child Session with a new round; when non-empty and the subagent is still
+ * RUNNING, it is queued as a steering message on the child's own steering queue — the same
+ * mechanism a user steers the main session with, delivered as a `[user_steering]` message at
+ * the child's next input assembly. The boolean `abort` argument aborts the child's CURRENT
+ * run only; combined with a non-empty `prompt` it interrupts and redirects — the prompt
+ * starts a fresh round once the aborted one settles. Within the window, queued approval
+ * requests from the child session are also passed through (see subagent/session.ts).
*
- * Difference from `input_command`: once a round of work finishes, the session is **not
- * removed** (kept to receive a follow-up prompt) — it's only released when the parent Session
- * ends, or evicted as an idle session once concurrency is full. Interruption only aborts this
- * particular access, **it never kills the child session** (the subagent was launched
- * independently earlier; the user interrupting one poll shouldn't kill it along the way).
+ * The model-facing output is the child's latest COMPLETE assistant text — every access reads
+ * as "what it last said", not an incremental delta drain (live rendering still flows to the
+ * frontend through the origin-tagged messages).
+ *
+ * Unlike a command's process, a subagent session is never destroyed: a released `subagent_id`
+ * (idle eviction freed its slot) is resumed through the runner and continues — there is no
+ * kill notion here, and interruption only aborts this particular access. The session leaves
+ * for good only with the parent Session itself.
* Docs: /docs/tools § "Subagents".
*/
-import { partialToolCallOutput } from "../../omnimessage/index.js";
+import { partialToolCallOutput, userText } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import {
DEFAULT_SUBAGENT_POLL_YIELD_MS,
DEFAULT_SUBAGENT_YIELD_MS,
+ ManagedSubagentSession,
resultForSubagentExit,
} from "./subagent/index.js";
import { approvalHint } from "./run-subagent.js";
@@ -59,11 +65,36 @@ export function createInputSubagentTool(
yield delta('Missing required argument "subagent_id" for input_subagent.');
return { stopReason: "failed" };
}
- const session = manager.get(subagentId);
+ let session = manager.get(subagentId);
+ if (!session) {
+ // A subagent session is never destroyed the way a process is: an id whose session
+ // left the registry (idle release) resumes through the runner — the same revival the
+ // panel gets. Only an id this parent never allocated, or a missing/failed resume,
+ // still errors.
+ const clue = manager.releasedInfo(subagentId);
+ const runner = services?.subagentRunner;
+ if (clue && runner?.resume && !manager.isDisposed && manager.makeRoom()) {
+ try {
+ const handle = await runner.resume({
+ sessionId: clue.sessionId,
+ ...(clue.agentId !== undefined ? { agentId: clue.agentId } : {}),
+ });
+ const revived = new ManagedSubagentSession(handle, {
+ ...(clue.agentId !== undefined ? { resumeAgentId: clue.agentId } : {}),
+ });
+ manager.track(revived);
+ manager.register(revived); // The id derives from the session tail: same handle as before.
+ session = revived;
+ yield delta(`[subagent ${subagentId} resumed]\n`);
+ } catch {
+ session = undefined;
+ }
+ }
+ }
if (!session) {
yield delta(
`[input_subagent error: unknown subagent_id ${subagentId} ` +
- `(the session may have finished and been cleared)]`,
+ `(not from this conversation, or its session could not be resumed)]`,
);
return { stopReason: "failed" };
}
@@ -78,35 +109,62 @@ export function createInputSubagentTool(
if (signal?.aborted) return { stopReason: "aborted" };
- // Continue with a follow-up prompt (empty prompt just polls). New input is not accepted
- // while running: poll first to collect progress.
+ // Abort the child's CURRENT run (per-run scope; the session survives). Waiting for the
+ // aborted round to settle keeps the follow-up prompt path below deterministic — the
+ // wait is bounded by this call's own signal (timeout/interruption).
+ if (args["abort"] === true) {
+ if (session.abortRun()) {
+ yield delta(`[aborting subagent ${subagentId}'s current run]\n`);
+ while (session.running && signal?.aborted !== true) await session.waitWake(200);
+ } else {
+ yield delta(`[subagent ${subagentId} was already idle; nothing to abort]\n`);
+ }
+ if (signal?.aborted) return { stopReason: "aborted" };
+ }
+
+ // A non-empty prompt: steering while the child runs (the child's own steering queue —
+ // the same mechanism a user steers the main session with; sender "parent_agent" like
+ // the follow-up prompts), a follow-up run while it is idle. steer() itself answers
+ // false on an idle child, so the running/idle race settles on whichever side is true
+ // at delivery.
if (!empty) {
- if (session.running) {
+ if (session.steer([userText(prompt, "parent_agent")])) {
+ yield delta(`[steering message queued for subagent ${subagentId}]\n`);
+ } else if (!session.running) {
+ // startRun expresses edge cases like already-disposed via throw, collapsed here into failed (the tool never throws outward).
+ try {
+ session.startRun(prompt);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ yield delta(`[input_subagent error: ${message}]`);
+ return { stopReason: "failed" };
+ }
+ } else {
+ // Running, but the handle predates steering (an older embedder's SubagentRunner).
yield delta(
`[input_subagent error: subagent ${subagentId} is still running; ` +
`poll with an empty prompt to collect progress first]`,
);
return { stopReason: "failed" };
}
- // startRun expresses edge cases like already-disposed via throw, collapsed here into failed (the tool never throws outward).
- try {
- session.startRun(prompt);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- yield delta(`[input_subagent error: ${message}]`);
- return { stopReason: "failed" };
- }
}
+ // Text deltas do not mirror into this tool's output (includeText: false): the model
+ // reads the child's latest COMPLETE assistant text below — an idempotent "what it last
+ // said" snapshot — instead of an incremental delta drain. Messages and approvals still
+ // flow through the window as before.
yield* collectWindow(session, {
yieldMs,
toolCallId,
+ includeText: false,
...(signal ? { signal } : {}),
...(approve ? { approve } : {}),
});
- // Interruption only aborts this access, it doesn't kill the child session.
+ // Interruption only aborts this access, it doesn't end the child session.
if (signal?.aborted) return { stopReason: "aborted" };
+ const latest = session.lastAssistantText;
+ if (latest !== null) yield delta(latest);
if (session.running) {
return {
stopReason: "completed",
diff --git a/packages/core/src/environment/tools/kill-command.ts b/packages/core/src/environment/tools/kill-command.ts
deleted file mode 100644
index 2d6acbe8..00000000
--- a/packages/core/src/environment/tools/kill-command.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * kill_command — terminates a background command session started by `exec_command` (BuiltinTool).
- *
- * Finds the session by `process_id`, disarms any pending completion report (the killer reads
- * the outcome right here — a trailing "task done" user message would only repeat it), drains
- * the yet-undelivered output as this tool's own output, then kills the whole process group
- * (SIGTERM, escalating to SIGKILL — see ManagedSession.kill) and drops the session from the
- * registry. Works on already-exited sessions too: those just report the recorded exit status
- * and are removed. Unknown process_id fails with an explanation.
- * Docs: /docs/tools § "Command sessions".
- */
-import { partialToolCallOutput } from "../../omnimessage/index.js";
-import type { OmniMessage } from "../../omnimessage/index.js";
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
-import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
-
-/** Tool name constant. */
-export const KILL_COMMAND_NAME = "kill_command";
-
-export function createKillCommandTool(
- definition: ToolDefinitionConfig,
- services?: EnvironmentServices,
-): BuiltinTool {
- const manager = services?.commandSessions;
- return {
- name: KILL_COMMAND_NAME,
- definition,
- async *execute(
- args: Record<string, unknown>,
- ctx: ToolExecutionContext,
- ): AsyncGenerator<OmniMessage, ToolResult | void> {
- const { toolCallId } = ctx;
- const delta = (output: string): OmniMessage =>
- partialToolCallOutput({ eventType: "delta", output, toolCallId });
-
- if (!manager) {
- yield delta("[kill_command unavailable: no command session manager configured]");
- return { stopReason: "failed" };
- }
- const processId = args["process_id"];
- if (typeof processId !== "string" || processId.length === 0) {
- yield delta('Missing required argument "process_id" for kill_command.');
- return { stopReason: "failed" };
- }
- const session = manager.get(processId);
- if (!session) {
- yield delta(
- `[kill_command error: unknown process_id ${processId} (the session may have exited and been cleared)]`,
- );
- return { stopReason: "failed" };
- }
-
- // Disarm before killing: the exit this kill causes must not fire a completion report.
- session.clearExitWatchers();
- const pending = session.drainPending();
- if (pending) yield delta(pending);
- const wasRunning = session.running;
- const exit = session.exit;
- manager.kill(processId);
- if (wasRunning) {
- return {
- stopReason: "completed",
- note: `[process ${processId} killed (SIGTERM to the process group, SIGKILL after a grace period)]`,
- };
- }
- const status = session.error
- ? `spawn error: ${session.error.message}`
- : exit?.signal != null
- ? `terminated by signal ${exit.signal}`
- : `exit code ${exit?.code ?? "unknown"}`;
- return {
- stopReason: "completed",
- note: `[process ${processId} had already exited (${status}); session removed]`,
- };
- },
- };
-}
diff --git a/packages/core/src/environment/tools/kill-subagent.ts b/packages/core/src/environment/tools/kill-subagent.ts
deleted file mode 100644
index 44f879a0..00000000
--- a/packages/core/src/environment/tools/kill-subagent.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * kill_subagent — terminates a background subagent session started by `run_subagent`
- * (BuiltinTool).
- *
- * Finds the session by `subagent_id`, disarms any pending completion report (the killer reads
- * the outcome right here), drains the yet-undelivered answer text as this tool's own output,
- * then aborts the run (denying pending approvals, releasing the child Session — see
- * ManagedSubagentSession.kill) and drops it from the registry. An idle background subagent is
- * removed the same way, freeing its concurrency slot. Unknown subagent_id fails with an
- * explanation. The child Session's own Trace keeps everything it produced before the kill.
- * Docs: /docs/tools § "Subagents".
- */
-import { partialToolCallOutput } from "../../omnimessage/index.js";
-import type { OmniMessage } from "../../omnimessage/index.js";
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
-import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
-
-/** Tool name constant. */
-export const KILL_SUBAGENT_NAME = "kill_subagent";
-
-export function createKillSubagentTool(
- definition: ToolDefinitionConfig,
- services?: EnvironmentServices,
-): BuiltinTool {
- const manager = services?.subagentSessions;
- return {
- name: KILL_SUBAGENT_NAME,
- definition,
- async *execute(
- args: Record<string, unknown>,
- ctx: ToolExecutionContext,
- ): AsyncGenerator<OmniMessage, ToolResult | void> {
- const { toolCallId } = ctx;
- const delta = (output: string): OmniMessage =>
- partialToolCallOutput({ eventType: "delta", output, toolCallId });
-
- if (!manager) {
- yield delta("[kill_subagent unavailable: no subagent session manager configured]");
- return { stopReason: "failed" };
- }
- const subagentId = args["subagent_id"];
- if (typeof subagentId !== "string" || subagentId.length === 0) {
- yield delta('Missing required argument "subagent_id" for kill_subagent.');
- return { stopReason: "failed" };
- }
- const session = manager.get(subagentId);
- if (!session) {
- yield delta(
- `[kill_subagent error: unknown subagent_id ${subagentId} (the session may have finished and been cleared)]`,
- );
- return { stopReason: "failed" };
- }
-
- // Disarm before killing: the settle this kill causes must not fire a completion report.
- session.clearSettleWatcher();
- const pending = session.drainText();
- if (pending) yield delta(pending);
- const wasRunning = session.running;
- manager.kill(subagentId);
- return {
- stopReason: "completed",
- note: wasRunning
- ? `[subagent ${subagentId} aborted and removed; its own trace keeps the work done so far]`
- : `[subagent ${subagentId} was idle; session removed]`,
- };
- },
- };
-}
diff --git a/packages/core/src/environment/tools/registry.ts b/packages/core/src/environment/tools/registry.ts
index 6ff4119a..f9cef066 100644
--- a/packages/core/src/environment/tools/registry.ts
+++ b/packages/core/src/environment/tools/registry.ts
@@ -18,10 +18,8 @@ import { EDIT_FILE_NAME, createEditFileTool } from "./edit-file.js";
import { WRITE_FILE_NAME, createWriteFileTool } from "./write-file.js";
import { EXEC_COMMAND_NAME, createExecCommandTool } from "./exec-command.js";
import { INPUT_COMMAND_NAME, createInputCommandTool } from "./input-command.js";
-import { KILL_COMMAND_NAME, createKillCommandTool } from "./kill-command.js";
import { SUBAGENT_NAME, createSubagentTool } from "./run-subagent.js";
import { INPUT_SUBAGENT_NAME, createInputSubagentTool } from "./input-subagent.js";
-import { KILL_SUBAGENT_NAME, createKillSubagentTool } from "./kill-subagent.js";
import { READ_IMAGE_NAME, createReadImageTool } from "./read-image.js";
import { DESCRIBE_IMAGE_NAME, createDescribeImageTool } from "./describe-image.js";
@@ -42,10 +40,8 @@ export const BUILTIN_TOOL_FACTORIES: Record<string, BuiltinToolFactory> = {
[WRITE_FILE_NAME]: createWriteFileTool,
[EXEC_COMMAND_NAME]: createExecCommandTool,
[INPUT_COMMAND_NAME]: createInputCommandTool,
- [KILL_COMMAND_NAME]: createKillCommandTool,
[SUBAGENT_NAME]: createSubagentTool,
[INPUT_SUBAGENT_NAME]: createInputSubagentTool,
- [KILL_SUBAGENT_NAME]: createKillSubagentTool,
[READ_IMAGE_NAME]: createReadImageTool,
// describe_image: the text-only-model variant of read_image (hands the image to the
// configured vision model for description, returns text).
diff --git a/packages/core/src/environment/tools/run-subagent.ts b/packages/core/src/environment/tools/run-subagent.ts
index 66ab0cc3..d3a4e0c9 100644
--- a/packages/core/src/environment/tools/run-subagent.ts
+++ b/packages/core/src/environment/tools/run-subagent.ts
@@ -141,7 +141,14 @@ export function createSubagentTool(
...(provider !== undefined ? { provider } : {}),
...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
});
- session = new ManagedSubagentSession(handle);
+ session = new ManagedSubagentSession(handle, {
+ // Spawn-time owner for the revival tombstone (undefined = a self-spawn of this Agent).
+ ...(agentId !== undefined ? { resumeAgentId: agentId } : {}),
+ });
+ // Live index from the moment of spawn (before any registration): host paths — the
+ // subagents panel's steer/abort — reach this child by its session id even while it
+ // still runs inside this call's foreground collect window.
+ manager.track(session);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
yield* fail(`[run_subagent error: ${message}]`);
@@ -152,7 +159,7 @@ export function createSubagentTool(
// report (fires at the end of every round until the session is killed), start the run,
// and hand back the subagent_id. The completion reaches the conversation as a harness
// user message; the model can still poll or follow up with input_subagent, or stop it
- // with kill_subagent. The child's messages stream to the host live through the
+ // input_subagent (abort included). The child's messages stream to the host live through the
// forwarding tap below (its own Trace stays the durable record).
if (background) {
const id = manager.register(session);
@@ -162,7 +169,7 @@ export function createSubagentTool(
// at the approval queue forever, since no collect window ever attaches one) and a
// live message tap, so the child streams to the frontend past this turn's end. The
// child's abort signal is its own (ManagedSubagentSession.abortCtrl) — only
- // kill_subagent, dispose, or registry eviction ends it.
+ // dispose or registry eviction ends it (and a released session can be revived).
if (approve) session.setPersistentApprovalSink(approve);
const forward = services?.backgroundForward;
if (forward) session.setMessageTap(forward);
@@ -176,7 +183,7 @@ export function createSubagentTool(
stopReason: "completed",
note:
`[subagent running in background with subagent_id ${id}; its completion will arrive ` +
- `as a user message — no need to poll. Use input_subagent to interact or kill_subagent to stop it]`,
+ `as a user message — no need to poll. Use input_subagent to interact (abort: true stops its current run)]`,
};
}
@@ -220,11 +227,15 @@ export function createSubagentTool(
}
/**
- * Arms the completion report of a background-launched subagent: at the end of every round
- * (input_subagent follow-ups included) the report — id, terminal status, tail of the
- * yet-undelivered answer text — goes to `services.backgroundDone`, which the Session turns
- * into a harness user message. `kill_subagent` disarms it first, and a killed/disposed
- * session never fires (see ManagedSubagentSession.onSettled).
+ * Arms the completion report of a background-launched subagent: at the end of every
+ * MODEL-initiated round (the launch itself and input_subagent follow-ups) the report — id,
+ * terminal status, tail of the yet-undelivered answer text — goes to
+ * `services.backgroundDone`, which the Session turns into a harness user message. Rounds the
+ * HOST starts (the panel's message on an idle child) stay silent: they are the user's own
+ * conversation with the child, not dispatched work awaiting a result (see
+ * ManagedSubagentSession.startRun's suppressDoneReport), and so does a round ended by an
+ * explicit abort (input_subagent's `abort` / the panel's stop — the aborter sees the outcome
+ * directly; see abortRun). A disposed session never fires (see ManagedSubagentSession.onSettled).
*/
export function armSubagentDoneReport(
session: ManagedSubagentSession,
@@ -236,13 +247,16 @@ export function armSubagentDoneReport(
if (!notify) return;
session.onSettled(() => {
const exit = session.exit;
+ // Drain the delta buffer regardless (bounded memory); the report itself carries the
+ // child's latest complete utterance — the same snapshot input_subagent returns.
+ session.drainText();
notify({
kind: "subagent",
id: subagentId,
label: reportLabel(prompt),
status: exit?.status ?? "completed",
detail: exit?.note ?? "",
- output: tailForReport(session.drainText()),
+ output: tailForReport(session.lastAssistantText ?? ""),
});
});
}
diff --git a/packages/core/src/environment/tools/subagent/collect.ts b/packages/core/src/environment/tools/subagent/collect.ts
index e316e0ab..7f972aa4 100644
--- a/packages/core/src/environment/tools/subagent/collect.ts
+++ b/packages/core/src/environment/tools/subagent/collect.ts
@@ -16,9 +16,23 @@ import type { ManagedSubagentSession } from "./session.js";
export async function* collectWindow(
session: ManagedSubagentSession,
- opts: { yieldMs: number; toolCallId: string; signal?: AbortSignal; approve?: ApproveFn },
+ opts: {
+ yieldMs: number;
+ toolCallId: string;
+ signal?: AbortSignal;
+ approve?: ApproveFn;
+ /**
+ * Whether the child's text deltas mirror into this tool's own output (default true —
+ * run_subagent's launch window streams the forming answer live). input_subagent passes
+ * false: its model-facing output is the child's latest COMPLETE assistant text, emitted
+ * once at the end, so every access reads as "what it last said" instead of an
+ * incremental delta drain. The buffer still drains either way (bounded memory).
+ */
+ includeText?: boolean;
+ },
): AsyncGenerator<OmniMessage> {
const { yieldMs, toolCallId, signal, approve } = opts;
+ const includeText = opts.includeText ?? true;
const delta = (output: string): OmniMessage =>
partialToolCallOutput({ eventType: "delta", output, toolCallId });
const detach = approve ? session.attachApprovalSink(approve) : null;
@@ -31,7 +45,7 @@ export async function* collectWindow(
for (;;) {
for (const m of session.drainMessages()) yield m;
const text = session.drainText();
- if (text) yield delta(text);
+ if (text && includeText) yield delta(text);
if (!session.running) break;
if (signal?.aborted) break;
const remaining = yieldMs - (Date.now() - start);
@@ -44,7 +58,7 @@ export async function* collectWindow(
// Final drain: there may still be a tail buffer right when the run finishes/yields.
for (const m of session.drainMessages()) yield m;
const tail = session.drainText();
- if (tail) yield delta(tail);
+ if (tail && includeText) yield delta(tail);
} finally {
signal?.removeEventListener("abort", onAbort);
detach?.();
diff --git a/packages/core/src/environment/tools/subagent/session-manager.ts b/packages/core/src/environment/tools/subagent/session-manager.ts
index ac48e964..e558563d 100644
--- a/packages/core/src/environment/tools/subagent/session-manager.ts
+++ b/packages/core/src/environment/tools/subagent/session-manager.ts
@@ -9,6 +9,7 @@
* evicted; if there's still no room, the tool rejects spawning a new one.
* Docs: /docs/tools § "Background session caps".
*/
+import type { ApproveFn, BackgroundSubagentInfo } from "../../../interfaces.js";
import { BackgroundRegistry } from "../background/index.js";
import type { ManagedSubagentSession } from "./session.js";
@@ -25,12 +26,79 @@ export class SubagentSessionManager {
idPrefix: "subagent",
maxTasks: MAX_SESSIONS,
});
+ /**
+ * Live index by child Session id: EVERY spawned session, tracked from spawn — children
+ * still inside a foreground collect window included, so host paths (the subagents panel)
+ * can steer or abort them before any `subagent_id` exists. Dead entries drop lazily on
+ * access; `subagent_id` is still allocated only at background registration.
+ */
+ private readonly live = new Set<ManagedSubagentSession>();
+ /** Single aggregate run-state listener (the Environment's notifier); pinged on any child's run start/settle. */
+ private stateListener: (() => void) | null = null;
+ /** Host fallback approval sink, applied to every tracked session (see EnvironmentInterface.setSubagentApprovalFallback). */
+ private approvalFallback: ApproveFn | null = null;
/** Whether the manager has been disposed (the host Session has ended). */
get isDisposed(): boolean {
return this.registry.isDisposed;
}
+ /** Enters a freshly spawned session into the live index and wires its run-state pings into the aggregate listener. */
+ track(session: ManagedSubagentSession): void {
+ this.live.add(session);
+ session.onStateChange(() => this.stateListener?.());
+ if (this.approvalFallback) session.setFallbackApprovalSink(this.approvalFallback);
+ }
+
+ /** Attaches the host fallback approval sink, applying it to already-tracked live sessions too. */
+ setApprovalFallback(approve: ApproveFn): void {
+ this.approvalFallback = approve;
+ for (const session of [...this.live]) {
+ if (session.disposed) {
+ this.live.delete(session);
+ continue;
+ }
+ session.setFallbackApprovalSink(approve);
+ }
+ }
+
+ /** Attaches the single aggregate run-state listener (see track). */
+ setStateListener(listener: () => void): void {
+ this.stateListener = listener;
+ }
+
+ /** Looks up a live session by its child Session id (foreground-window ones included); undefined when none. */
+ bySessionId(sessionId: string): ManagedSubagentSession | undefined {
+ let found: ManagedSubagentSession | undefined;
+ for (const session of [...this.live]) {
+ if (session.disposed) {
+ this.live.delete(session);
+ continue;
+ }
+ if (session.sessionId === sessionId) found = session;
+ }
+ return found;
+ }
+
+ /** All live child sessions for a host UI (see BackgroundSubagentInfo); registry handles resolve where the session was promoted. */
+ listLive(): BackgroundSubagentInfo[] {
+ const handles = new Map<ManagedSubagentSession, string>();
+ for (const { id, task } of this.registry.list()) handles.set(task, id);
+ const out: BackgroundSubagentInfo[] = [];
+ for (const session of [...this.live]) {
+ if (session.disposed) {
+ this.live.delete(session);
+ continue;
+ }
+ out.push({
+ sessionId: session.sessionId,
+ subagentId: handles.get(session) ?? null,
+ running: session.running,
+ });
+ }
+ return out;
+ }
+
/** Whether there's still room for a new background session (evicting a completed, idle one if needed; never evicts a running one). */
makeRoom(): boolean {
return this.registry.makeRoom(false);
@@ -58,7 +126,24 @@ export class SubagentSessionManager {
// completed, idle ones); if still no room, register anyway, tolerating a brief overshoot
// (see MAX_SESSIONS).
this.registry.makeRoom(false);
- return this.registry.register(session, session.sessionId.slice(-8));
+ const id = this.registry.register(session, session.sessionId.slice(-8));
+ // Tombstone for the revival path: a subagent session is never destroyed the way a process
+ // is — releasing it (idle eviction) only frees the slot, and this record lets a later
+ // input_subagent on the same id resume the child instead of erroring. Parent-session
+ // lifetime, one small record per registration.
+ this.registered.set(id, {
+ sessionId: session.sessionId,
+ ...(session.resumeAgentId !== undefined ? { agentId: session.resumeAgentId } : {}),
+ });
+ return id;
+ }
+
+ /** Ever-registered index by subagent_id (see register): the resume clue for ids whose session left the registry. */
+ private readonly registered = new Map<string, { sessionId: string; agentId?: string }>();
+
+ /** The resume clue for a subagent_id no longer in the registry; undefined for ids this parent session never allocated. */
+ releasedInfo(subagentId: string): { sessionId: string; agentId?: string } | undefined {
+ return this.registered.get(subagentId);
}
/** Looks up a session by subagent_id and refreshes its access time; returns undefined if not found. */
@@ -66,13 +151,6 @@ export class SubagentSessionManager {
return this.registry.get(subagentId);
}
- /** Kills a background subagent by id (aborts its run, denies pending approvals, releases the child Session) and drops it from the registry; false when the id is unknown. */
- kill(subagentId: string): boolean {
- if (this.registry.get(subagentId) === undefined) return false;
- this.registry.remove(subagentId);
- return true;
- }
-
/** Disposes: removes the fallback registration and finalizes all sessions (the process 'exit' fallback is hooked by the registry itself). Idempotent. */
dispose(): void {
this.registry.dispose();
diff --git a/packages/core/src/environment/tools/subagent/session.ts b/packages/core/src/environment/tools/subagent/session.ts
index af5e90ce..4facb030 100644
--- a/packages/core/src/environment/tools/subagent/session.ts
+++ b/packages/core/src/environment/tools/subagent/session.ts
@@ -23,6 +23,11 @@
* the request stays queued, and a late-arriving decision still takes effect (settled guard,
* first to arrive wins).
*
+ * Mid-run control: `steer` queues a message on the child Session's own steering queue (the
+ * mechanism a user steers the main session with), and `abortRun` aborts only the current
+ * round via a per-run AbortController — the session survives both for follow-up prompts.
+ * The model (input_subagent) and the host (subagents panel) converge on these same methods.
+ *
* Cleanup: `kill()` aborts the current run via AbortSignal, denies all pending approvals, and
* releases child Session resources; idempotent. The child Session runs in-process, so there's no
* need for a separate synchronous hard-kill path (its command sessions are reaped by their own
@@ -30,7 +35,7 @@
*/
import type { OmniMessage } from "../../../omnimessage/index.js";
import type { ApprovalDecision, ToolCallPayload } from "../../../omnimessage/index.js";
-import type { ApproveFn, SubagentHandle } from "../../../interfaces.js";
+import type { ApproveFn, SubagentHandle, ThinkingLevelName } from "../../../interfaces.js";
import type { ToolResult } from "../types.js";
import { CappedTextBuffer, WakeSignal } from "../background/index.js";
@@ -58,6 +63,12 @@ export class ManagedSubagentSession {
private readonly handle: SubagentHandle;
private readonly abortCtrl = new AbortController();
+ /**
+ * Abort scope of the CURRENT run only: `abortRun` (input_subagent's `abort`, the panel's
+ * stop button) fires this one, ending the round the way a user's stop ends a main-session
+ * Task — the session itself survives for steering and follow-up runs, unlike `kill`.
+ */
+ private runCtrl: AbortController | null = null;
private messages: OmniMessage[] = [];
private readonly textBuffer = new CappedTextBuffer(OUTPUT_BUFFER_CAP, "earlier subagent output");
@@ -89,10 +100,18 @@ export class ManagedSubagentSession {
// Single wake point: new message / run finished / new approval request all wake a waiting waitWake through it.
private readonly wakeSignal = new WakeSignal();
- constructor(handle: SubagentHandle) {
+ constructor(handle: SubagentHandle, opts?: { resumeAgentId?: string }) {
this.handle = handle;
+ this.resumeAgentId = opts?.resumeAgentId;
}
+ /**
+ * The owning Agent recorded at spawn/resume for the revival path (undefined = the parent
+ * Agent's own, i.e. a self-spawn): a released session's registry tombstone carries it so a
+ * later input_subagent on the same id can resume the child (see SubagentSessionManager).
+ */
+ readonly resumeAgentId: string | undefined;
+
/** Child Session id (one hop of a message's origin); `subagent_id` is derived from its tail so the frontend can correlate it. */
get sessionId(): string {
return this.handle.sessionId;
@@ -123,17 +142,70 @@ export class ManagedSubagentSession {
return this.messages.length > 0 || !this.textBuffer.isEmpty;
}
+ /** Whether the session has been killed/disposed (used by the manager's live index to drop dead entries lazily). */
+ get disposed(): boolean {
+ return this.killed;
+ }
+
/**
* Starts a new round of the task on the child Session (async pump, doesn't block the caller).
- * Throws if already disposed or still running (converted to an explanatory output by the
- * caller).
+ * `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
+ * 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(prompt: string): void {
+ startRun(
+ prompt: string,
+ opts?: { thinkingLevel?: ThinkingLevelName; 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;
this.exitInfo = null;
- void this.pump(prompt);
+ this.reportCurrentRun = opts?.suppressDoneReport !== true;
+ this.runCtrl = new AbortController();
+ this.notifyState();
+ void this.pump(prompt, this.runCtrl, opts?.thinkingLevel);
+ }
+
+ /**
+ * Queues a steering message for the current run (the same channel a user steers the main
+ * session with — see SubagentHandle.steer). False when idle, killed, or the handle predates
+ * steering: the caller then falls back to a follow-up run or reports "not running".
+ */
+ steer(messages: OmniMessage[]): boolean {
+ if (this.killed || !this.isRunning) return false;
+ return this.handle.steer?.(messages) ?? false;
+ }
+
+ /**
+ * Aborts the CURRENT run only (see runCtrl); the session stays alive for steering and
+ * follow-up prompts. False when no run is in flight. The exit lands asynchronously through
+ * the pump (status failed with an aborted note), so callers observe settlement via
+ * waitWake/running like any other run end.
+ */
+ abortRun(): boolean {
+ if (this.killed || !this.isRunning) return false;
+ // An abort is always an explicit actor's gesture whose outcome that actor sees directly
+ // (the input_subagent call's own result, or the panel the user pressed stop on): the
+ // settling round must not additionally fire a completion report at the parent.
+ this.reportCurrentRun = false;
+ this.runCtrl?.abort();
+ 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;
+
+ /** Attaches the single run-state listener (the manager's aggregate notifier). */
+ onStateChange(cb: () => void): void {
+ this.stateListener = cb;
+ }
+
+ private notifyState(): void {
+ this.stateListener?.();
}
/** Takes the buffered child-session messages (already tagged with origin, for the parent tool to forward). */
@@ -149,6 +221,14 @@ export class ManagedSubagentSession {
return this.textBuffer.drain();
}
+ /** The child's most recent complete assistant text, across every round; null before it says anything (see the pump). */
+ private lastAnswer: string | null = null;
+
+ /** What the child last said — the idempotent snapshot input_subagent returns and a completion report carries. */
+ get lastAssistantText(): string | null {
+ return this.lastAnswer;
+ }
+
/** External wakeup (e.g. the parent tool call was aborted): makes a waiting `waitWake` return immediately. */
wakeup(): void {
this.wakeSignal.notify();
@@ -156,7 +236,7 @@ export class ManagedSubagentSession {
// Settle watcher (run_in_background completion reports): fires at the end of EVERY round of a
// background-launched session (later input_subagent rounds included), until disarmed. A kill
- // through the kill_subagent tool disarms first — the killer already reports the outcome.
+ // by an explicit per-run abort stays silent — the aborter reads the outcome directly.
private settleWatcher: (() => void) | null = null;
/** Arms the completion-report watcher (replacing any previous one); fires immediately (microtask) when the session is already idle with a terminal state. */
@@ -176,6 +256,30 @@ export class ManagedSubagentSession {
void this.pumpApprovals();
}
+ /**
+ * Host-provided session-lifetime fallback approval sink (see
+ * EnvironmentInterface.setSubagentApprovalFallback): consulted when neither a window sink
+ * nor a background launch's standing sink exists, so a child's approval escalates to the
+ * user instead of parking until the model's next poll. Lowest precedence of the three.
+ */
+ private fallbackApprove: ApproveFn | null = null;
+
+ /** Attaches the host fallback approval sink (see fallbackApprove) and drains anything already queued. */
+ setFallbackApprovalSink(approve: ApproveFn): void {
+ this.fallbackApprove = approve;
+ void this.pumpApprovals();
+ }
+
+ /** The active standing sink: a background launch's own, else the host fallback; null without either. */
+ private standingApprove(): ApproveFn | null {
+ return this.persistentApprove ?? this.fallbackApprove;
+ }
+
+ /** Whether a live forwarding tap is attached (host paths attach one on first touch; see setMessageTap). */
+ get hasMessageTap(): boolean {
+ return this.forwardTap !== null;
+ }
+
/** Attaches the live forwarding tap of a background launch (see forwardTap), flushing the buffered backlog through it in order. */
setMessageTap(tap: (msg: OmniMessage) => void): void {
const backlog = this.messages;
@@ -184,9 +288,12 @@ export class ManagedSubagentSession {
for (const msg of backlog) tap(msg);
}
+ /** Whether the round in flight (or the last one) should fire the settle watcher: false for host-initiated rounds (see startRun). */
+ private reportCurrentRun = true;
+
private fireSettleWatcher(): void {
const cb = this.settleWatcher;
- if (cb && !this.killed) cb();
+ if (cb && !this.killed && this.reportCurrentRun) cb();
}
/** Waits for "woken up" or `ms` to expire, whichever comes first. */
@@ -235,14 +342,20 @@ export class ManagedSubagentSession {
// -------------------------------------------------------------------------
/** Drives one round of `handle.run`: buffers messages and text, settling the terminal state when it ends. */
- private async pump(prompt: string): Promise<void> {
+ private async pump(
+ prompt: string,
+ runCtrl: AbortController,
+ thinkingLevel?: ThinkingLevelName,
+ ): Promise<void> {
let wroteAny = false;
let childAbort: string | null = null;
try {
+ // Either scope ends the round: the session-lifetime kill, or this run's own abort.
for await (const msg of this.handle.run({
prompt,
- signal: this.abortCtrl.signal,
+ signal: AbortSignal.any([this.abortCtrl.signal, runCtrl.signal]),
approve: this.childApprove,
+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
})) {
this.bufferMessage(msg);
if ((msg.origin?.length ?? 0) === 1) {
@@ -266,6 +379,17 @@ export class ManagedSubagentSession {
) {
wroteAny = true;
this.appendText(p.text);
+ } else if (
+ p.type === "text" &&
+ (p as { role?: string }).role === "assistant" &&
+ typeof p.text === "string" &&
+ p.text
+ ) {
+ // The child's most recent COMPLETE utterance: what input_subagent hands the model
+ // and what a completion report carries — an idempotent "what it last said"
+ // snapshot rather than an incremental delta drain.
+ wroteAny = true;
+ this.lastAnswer = p.text;
}
}
this.wakeSignal.notify();
@@ -287,6 +411,7 @@ export class ManagedSubagentSession {
this.isRunning = false;
if (this.killed) this.handle.dispose();
this.wakeSignal.notify();
+ this.notifyState();
this.fireSettleWatcher();
}
}
@@ -344,11 +469,11 @@ export class ManagedSubagentSession {
if (this.pumpingApprovals) return;
this.pumpingApprovals = true;
try {
- while ((this.sink !== null || this.persistentApprove !== null) && this.approvals.length > 0) {
+ while ((this.sink !== null || this.standingApprove() !== null) && this.approvals.length > 0) {
const req = this.approvals[0]!;
const sink = this.sink;
if (sink === null) {
- await this.persistentApprove!(req.toolCall).then(
+ await this.standingApprove()!(req.toolCall).then(
(d) => this.settle(req, d),
() => this.settle(req, "deny"), // An approval sink error is treated as a denial (avoids leaving the child session stuck forever)
);
@@ -361,7 +486,7 @@ export class ManagedSubagentSession {
await Promise.race([answer, sink.detached]);
if (req.settled) continue;
if (this.sink && this.sink !== sink) continue; // The sink was replaced by a new call: retry with the new sink
- if (this.persistentApprove !== null) continue; // Window gone but a standing sink exists: fall through to it next round
+ if (this.standingApprove() !== null) continue; // Window gone but a standing sink exists: fall through to it next round
break; // The sink was detached and still unresolved: stay queued for the next sink
}
} finally {
diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts
index 8404d1c1..83ab910a 100644
--- a/packages/core/src/interfaces.ts
+++ b/packages/core/src/interfaces.ts
@@ -296,7 +296,17 @@ 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>;
+ /**
+ * Queues a steering message for the child Session's running Task (the same mechanism as a
+ * user steering the main session: delivered as a `[user_steering]` user message at the
+ * child's next input assembly). Returns false when no run is in flight — the caller then
+ * falls back to a follow-up run. Optional so older embedders' handles keep compiling; a
+ * handle without it simply reports "not steerable".
+ */
+ steer?(messages: OmniMessage[]): boolean;
/** Releases runtime resources held by the child Session (e.g. its managed command sessions). Idempotent. */
dispose(): void;
}
@@ -349,6 +359,15 @@ export interface SubagentRunner {
*/
thinkingLevel?: ThinkingLevelName;
}): Promise<SubagentHandle>;
+ /**
+ * Revives a released child Session by id (`resumeSession` semantics: its own history,
+ * model and Workspace) and hands back a handle for re-management — the revival path shared
+ * by the host (see SubagentMessageOptions.resume) and by input_subagent on a released
+ * `subagent_id`. `agentId` names the owning Agent; omitted = the parent Agent's own (a
+ * self-spawn's child). A missing or unrecoverable session is expressed by throwing.
+ * Optional — a runner without it simply leaves revival unavailable.
+ */
+ resume?(input: { agentId?: string; sessionId: string }): Promise<SubagentHandle>;
}
/**
@@ -495,6 +514,43 @@ export interface BackgroundCommandInfo {
serviceUrl?: string;
}
+/**
+ * One live subagent child session owned by the environment: the child Session id (the origin
+ * hop the frontend already correlates by), the registry handle when the session was promoted
+ * to the background (null while it only lives inside a foreground collect window), and
+ * whether a round is currently running.
+ */
+export interface BackgroundSubagentInfo {
+ sessionId: string;
+ subagentId: string | null;
+ running: boolean;
+}
+
+/**
+ * Outcome of a host-initiated subagent message (`sendToBackgroundSubagent`): `steered` = the
+ * child was mid-run and the text was queued as a steering message; `started` = the child was
+ * idle and the text began a follow-up run on the same child Session; `resumed` = no live
+ * child bore the id, so the session was revived through `SubagentRunner.resume` and the text
+ * began its next round; `busy` = the child cannot take the message right now (mid-run on a
+ * handle that predates steering, or no room to re-manage a resumed session); `gone` = no
+ * live child and no way to resume (resume not requested/available, or the session's record
+ * is unrecoverable).
+ */
+export type SubagentMessageOutcome = "steered" | "started" | "resumed" | "busy" | "gone";
+
+/** 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
+ * re-managed, and the text starts its next round. `agentId` names the Agent that owns the
+ * child session (the host reads it from its session registry).
+ */
+ resume?: { agentId: string };
+}
+
/**
* Environment interface: executes approved tool calls within the Workspace.
* `executeTool` yields `partial_tool_call_output` as an async generator and ends with exactly one
@@ -521,6 +577,44 @@ export interface EnvironmentInterface {
* listBackgroundCommands.
*/
hasRunningBackgroundSubagents?(): boolean;
+ /**
+ * All live subagent child sessions (foreground-window ones included), for a host UI's
+ * subagents panel. Optional, like listBackgroundCommands.
+ */
+ listBackgroundSubagents?(): BackgroundSubagentInfo[];
+ /**
+ * Host-initiated message to one child session, by child Session id: steering while the
+ * child runs, a follow-up run while it is idle, a revival (`opts.resume`) when the session
+ * is no longer live (see SubagentMessageOutcome/SubagentMessageOptions). The human and the
+ * model (`input_subagent`) converge on the managed session's same channel. Optional.
+ */
+ sendToBackgroundSubagent?(
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome>;
+ /**
+ * Host-initiated abort of one child session's CURRENT run (the child-session equivalent of
+ * the user's stop button): the session survives for follow-ups — a subagent session is
+ * never destroyed. False when the child is unknown or idle. Optional.
+ */
+ abortBackgroundSubagentRun?(childSessionId: string): 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 —
+ * the event carries no payload, so state reads stay race-free against the listing.
+ * Optional, same single-listener pattern as setBackgroundTaskListener.
+ */
+ setSubagentStateListener?(listener: () => void): void;
+ /**
+ * Attaches the host's session-lifetime fallback approval sink for child sessions: a child
+ * approval with no window sink (an active run_subagent/input_subagent call) and no
+ * background-launch standing sink is consulted through this instead of waiting for the
+ * model's next poll — the host escalates it to the user, the parent session idle included.
+ * Window sinks and standing sinks keep precedence while present. Optional: hosts that
+ * never attach one (e.g. the CLI) keep the poll-window-only approval semantics.
+ */
+ setSubagentApprovalFallback?(approve: ApproveFn): void;
/**
* Refreshes the listen-port probe behind `BackgroundCommandInfo.serviceUrl` for running
* sessions whose output printed no URL (TTL-cached and time-bounded per session; see
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index d549cade..df1881e0 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -37,7 +37,11 @@ import { imagesToScratchpadPaths } from "./internal/session-support.js";
import { runGoalLoop } from "./goal/goal-loop.js";
import { goalFinishedOf } from "./goal/goal-stream.js";
import type {
+ ApproveFn,
BackgroundCommandInfo,
+ BackgroundSubagentInfo,
+ SubagentMessageOptions,
+ SubagentMessageOutcome,
BackgroundTaskDoneEvent,
CommandPolicyConfig,
EnvironmentInterface,
@@ -800,6 +804,42 @@ export class Session {
return this.environment.hasRunningBackgroundSubagents?.() ?? false;
}
+ /** All live subagent child sessions of this Session's Environment, for a host UI's subagents panel (see EnvironmentInterface.listBackgroundSubagents). */
+ listBackgroundSubagents(): BackgroundSubagentInfo[] {
+ return this.environment.listBackgroundSubagents?.() ?? [];
+ }
+
+ /**
+ * Host-initiated message to one child session by its Session id — the user's input on the
+ * child, whatever its state: steering while it runs, a follow-up run while it is idle, a
+ * revival when it is no longer live (see EnvironmentInterface.sendToBackgroundSubagent).
+ * The human (panel) and the model (input_subagent) converge on the same channel.
+ */
+ async sendToBackgroundSubagent(
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome> {
+ return (
+ (await this.environment.sendToBackgroundSubagent?.(childSessionId, text, opts)) ?? "gone"
+ );
+ }
+
+ /** Host-initiated abort of one child session's current run — the session survives for follow-ups (see EnvironmentInterface.abortBackgroundSubagentRun). */
+ abortBackgroundSubagentRun(childSessionId: string): boolean {
+ return this.environment.abortBackgroundSubagentRun?.(childSessionId) ?? false;
+ }
+
+ /** Attaches the host's session-lifetime fallback approval sink for child sessions (see EnvironmentInterface.setSubagentApprovalFallback). */
+ setSubagentApprovalFallback(approve: ApproveFn): void {
+ this.environment.setSubagentApprovalFallback?.(approve);
+ }
+
+ /** Attaches the single listener for subagent run-state changes; the host re-reads `listBackgroundSubagents` on each ping (see EnvironmentInterface.setSubagentStateListener). */
+ onSubagentState(listener: () => void): void {
+ this.environment.setSubagentStateListener?.(listener);
+ }
+
/** Queues a background completion event; a running Task delivers it at the next boundary, otherwise the host is signaled (see pendingNotices). */
private handleBackgroundDone(event: BackgroundTaskDoneEvent): void {
this.pendingNotices.push(event);
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index d4b575bf..8c735b57 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -691,7 +691,7 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
run_in_background: {
type: "boolean",
description:
- "Run the command in the background: return a process_id immediately without waiting. When it exits, its result arrives as an automatic user message — no polling needed. Use for long builds or work you want to continue past; interact via input_command, stop via kill_command. Defaults to false.",
+ "Run the command in the background: return a process_id immediately without waiting. When it exits, its result arrives as an automatic user message — no polling needed. Use for long builds or work you want to continue past; interact via input_command (kill: true terminates it). Defaults to false.",
},
},
required: ["description", "cmd"],
@@ -704,7 +704,7 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
{
name: "input_command",
description:
- "Interact with a running command session started by exec_command: write to its stdin, send Ctrl-C, or poll for new output. Identify the session with its process_id.",
+ "Interact with a running command session started by exec_command: write to its stdin, send Ctrl-C, poll for new output, or terminate it with kill: true. Identify the session with its process_id.",
parameters: {
type: "object",
properties: {
@@ -722,6 +722,11 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
description:
'Characters to write to the command\'s stdin. Send "\\u0003" alone to deliver Ctrl-C (SIGINT); mixing it with other characters is an error. Empty (the default) writes nothing and only polls for new output and exit status.',
},
+ kill: {
+ type: "boolean",
+ description:
+ "Terminate the command session: kills the whole process group (SIGTERM, then SIGKILL), returns any output not yet delivered, and removes the session — an already-exited session is just removed with its recorded exit status. Defaults to false.",
+ },
yield_time_ms: {
type: "number",
description:
@@ -736,30 +741,6 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
timeoutMs: 130000,
maxOutputLength: 16000,
},
- {
- name: "kill_command",
- description:
- "Terminate a background command session started by exec_command: kills the whole process group (SIGTERM, then SIGKILL) and returns any output not yet delivered. Also removes an already-exited session. Identify the session with its process_id.",
- parameters: {
- type: "object",
- properties: {
- description: {
- type: "string",
- description:
- "Required, and emit it first, before the other arguments: it is shown to the user while the call runs. One short sentence describing what this call is doing and why, written in the user's language.",
- },
- process_id: {
- type: "string",
- description: "The process_id returned by exec_command for the command session.",
- },
- },
- required: ["description", "process_id"],
- },
- permission: "rw",
- call_description: true,
- timeoutMs: 30000,
- maxOutputLength: 16000,
- },
{
name: "run_subagent",
description:
@@ -807,7 +788,7 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
run_in_background: {
type: "boolean",
description:
- "Start the subagent in the background: return a subagent_id immediately without waiting. When it finishes, its answer arrives as an automatic user message — no polling needed. Good for dispatching parallel subtasks; interact via input_subagent, stop via kill_subagent. Defaults to false.",
+ "Start the subagent in the background: return a subagent_id immediately without waiting. When it finishes, its answer arrives as an automatic user message — no polling needed. Good for dispatching parallel subtasks; message or steer it mid-run (and abort its current run) via input_subagent. Defaults to false.",
},
},
required: ["description", "prompt"],
@@ -821,7 +802,7 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
{
name: "input_subagent",
description:
- "Interact with a background subagent started by run_subagent: poll for new output, or send a follow-up prompt once it is idle to continue the same subagent session. Identify the session with its subagent_id. Pending tool approvals of the subagent are surfaced while this tool is waiting.",
+ "Talk to a subagent started by run_subagent, exactly like a user talking to an agent: a prompt sent while it is RUNNING is delivered mid-run as a steering message (use it to correct course without waiting); sent while it is idle, the prompt continues the same session as a follow-up task. Set abort=true to stop the current run (the session survives; combine with a prompt to interrupt and redirect). The output is the subagent's most recent complete reply. A subagent session is never destroyed: a subagent_id whose session was released resumes automatically when you message it. Pending tool approvals of the subagent are surfaced while this tool is waiting.",
parameters: {
type: "object",
properties: {
@@ -837,7 +818,12 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
prompt: {
type: "string",
description:
- "A follow-up task for the subagent, delivered as a new user message on the same session. Only accepted when the subagent is idle (its previous run finished). Empty (the default) sends nothing and only polls for new output and status.",
+ "A message for the subagent. While it is running, it is injected mid-run as a steering interjection the subagent absorbs at its next step (course corrections, extra context, an early stop request). While it is idle, it starts a follow-up task on the same session. Empty (the default) sends nothing and only polls for new output and status.",
+ },
+ abort: {
+ type: "boolean",
+ description:
+ "Abort the subagent's CURRENT run, like a user pressing stop: the run ends but the session stays available for steering and follow-up prompts. With a non-empty prompt, the aborted run settles first and the prompt then starts a fresh run — interrupt and redirect. Defaults to false; a no-op when the subagent is already idle.",
},
yield_time_ms: {
type: "number",
@@ -853,30 +839,6 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
timeoutMs: 600000,
maxOutputLength: 16000,
},
- {
- name: "kill_subagent",
- description:
- "Terminate a background subagent started by run_subagent: aborts its run (denying its pending approvals), returns any answer text not yet delivered, and removes the session. Also removes an idle background subagent, freeing its slot. Identify the session with its subagent_id.",
- parameters: {
- type: "object",
- properties: {
- description: {
- type: "string",
- description:
- "Required, and emit it first, before the other arguments: it is shown to the user while the call runs. One short sentence describing what this call is doing and why, written in the user's language.",
- },
- subagent_id: {
- type: "string",
- description: "The subagent_id returned by run_subagent for the background subagent.",
- },
- },
- required: ["description", "subagent_id"],
- },
- permission: "rw",
- call_description: true,
- timeoutMs: 30000,
- maxOutputLength: 16000,
- },
// The image-reading tools are mutually exclusive based on the session model's type
// (marked via each entry's forModel, filtered at assembly time): read_image is designed
// for vision models (the image is fed back as image content); describe_image is designed
diff --git a/packages/core/src/state/kernel-history.ts b/packages/core/src/state/kernel-history.ts
index 0ce2cdbd..b74c138c 100644
--- a/packages/core/src/state/kernel-history.ts
+++ b/packages/core/src/state/kernel-history.ts
@@ -22,7 +22,7 @@ import { createHash } from "node:crypto";
* change without it moving. (The reverse — moving it with no default change — is inert rather
* than an error: nothing is keyed by version, so there is no table to fall out of sync with.)
*/
-export const KERNEL_VERSION = "2026-08-21";
+export const KERNEL_VERSION = "2026-08-24";
function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -170,16 +170,20 @@ export function isKernelOutdated(kernelVersion: string | null | undefined): bool
* `thinking_level` enum: the tools tab moved again.
* - `2026-08-20` — the seeded `compaction.max_context_length` rose to 256000, with the
* per-model `context_window` cap as its backstop: the runtime tab moved.
- * - `2026-08-21` (current) — background execution: `exec_command` / `run_subagent` gained
+ * - `2026-08-21` — background execution: `exec_command` / `run_subagent` gained
* `run_in_background`, `input_command`'s empty-poll default became 120000ms, and the
* `kill_command` / `kill_subagent` tools joined the set, moving the tools tab; alongside
* them the memory prompt was reworded to name when a fact is worth saving (PR #397), moving
* the memory tab.
+ * - `2026-08-24` (current) — the kill notion left: `kill_command` folded into `input_command`
+ * as its `kill` parameter, `kill_subagent` was removed outright (a subagent session is never
+ * destroyed — `input_subagent` resumes a released id), and `input_subagent` gained `abort`
+ * and now returns the subagent's latest reply: the tools tab moved.
*/
export const KERNEL_DEFAULT_TAB_HASHES: Readonly<Record<KernelTab, string>> = {
prompt: "048198c37b8d7840352c225fdfcb15baf2679973c6eab4bf400d492daf6ce254",
runtime: "c952d44ecdd6790e17f02bc1b5056118b56ec7f0987dc2cbe950f6051fddbd20",
- tools: "8bbd336ff1f3fc283c4e11e54d43dd2bfe4ba2458577bf9eb3b6e3d7be4f3cde",
+ tools: "c24bcf47b1377e9da4dcfb69a1f7240dcdbfff2d420df5db0a5eaec2b7d4087d",
skills: "7e343aa692e5eaeadfc8add6bb375fb50ac33ef81ebe460490fc219b0f3d707f",
memory: "53d190390829cc0132bb12e468a6891f2e0576ec0c4022a9b4a5d9233666900d",
vault: "19bd36a6d4ab442b66583c423450602b817990a9a79bafa21c9b6137fb6b47d8",
@@ -208,6 +212,7 @@ export const KERNEL_SUPERSEDED_TAB_HASHES: KernelSupersededTabHashes = {
"238440586ad2e075bde04948cf8dc9876301da538aafeb8926cd9c6a5738081b", // before run_subagent's `thinking_level` (#306)
"c719f2fe8a25bc5c644a4e1a78d26cf960dd0561efc453614af2e395000ed4de", // before `max` joined the ladder
"074248073c5fe89537ff257cc5d5662159288fc79ede7703eded6b440b4e38e9", // before background execution and the kill tools
+ "8bbd336ff1f3fc283c4e11e54d43dd2bfe4ba2458577bf9eb3b6e3d7be4f3cde", // before the kill tools folded into the input tools
],
// The memory prompt's wording before #397 named when a fact is worth saving.
memory: ["c28acdda755552967cd0c99ba4ced407eddfa843b3dce228a965da4674676dc7"],
diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.ts
index 764c28f7..1da2bd79 100644
--- a/packages/core/test/background-execution.test.ts
+++ b/packages/core/test/background-execution.test.ts
@@ -1,7 +1,7 @@
/**
* Behavior tests for background execution: `run_in_background` on exec_command /
* run_subagent, the completion-report pipeline (Environment listener → Session notice
- * queue → engine boundary delivery), the kill_command / kill_subagent tools, and the
+ * queue → engine boundary delivery), input_command's kill termination, and the
* `sender` marking on user texts.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -11,7 +11,6 @@ import path from "node:path";
import { Environment } from "../src/environment/index.js";
import { createSubagentTool } from "../src/environment/tools/run-subagent.js";
import { createInputSubagentTool } from "../src/environment/tools/input-subagent.js";
-import { createKillSubagentTool } from "../src/environment/tools/kill-subagent.js";
import { SubagentSessionManager } from "../src/environment/tools/subagent/index.js";
import { DEFAULT_EMPTY_POLL_YIELD_MS } from "../src/environment/tools/command/index.js";
import { ContextEngine } from "../src/engine/context-engine.js";
@@ -233,7 +232,7 @@ describe("exec_command run_in_background", () => {
expect(events[0]!.output).toContain("early");
});
- it("kill_command terminates a running background command without a completion report", async () => {
+ it("input_command kill terminates a running background command without a completion report", async () => {
const { env } = await makeEnv();
const events: BackgroundTaskDoneEvent[] = [];
env.setBackgroundTaskListener((e) => events.push(e));
@@ -248,7 +247,7 @@ describe("exec_command run_in_background", () => {
// the scanner immediately before appending it to that buffer, so a detected serviceUrl
// proves the line is already buffered.
await waitFor(() => env.listBackgroundCommands().some((p) => p.serviceUrl !== undefined));
- const killed = await runTool(env, "kill_command", { process_id: id });
+ const killed = await runTool(env, "input_command", { process_id: id, kill: true });
expect(killed.stopReason).toBe("completed");
expect(killed.output).toContain("pre");
expect(killed.output).toContain(`process ${id} killed`);
@@ -256,15 +255,20 @@ describe("exec_command run_in_background", () => {
await new Promise((r) => setTimeout(r, 400));
expect(events).toHaveLength(0);
// And the session is gone from the registry.
- const again = await runTool(env, "kill_command", { process_id: id });
+ const again = await runTool(env, "input_command", { process_id: id, kill: true });
expect(again.stopReason).toBe("failed");
});
- it("kill_command fails on an unknown process_id", async () => {
+ it("input_command kill fails on an unknown process_id; the legacy kill_command name is an unknown tool", async () => {
const { env } = await makeEnv();
- const res = await runTool(env, "kill_command", { process_id: "proc-deadbeef" });
+ const res = await runTool(env, "input_command", { process_id: "proc-deadbeef", kill: true });
expect(res.stopReason).toBe("failed");
expect(res.output).toContain("unknown process_id");
+ // A stale stored config may still carry the removed tool; the registry no longer
+ // assembles it, so a model call collapses to the standard unknown-tool failure.
+ const legacy = await runTool(env, "kill_command", { process_id: "proc-deadbeef" });
+ expect(legacy.stopReason).toBe("failed");
+ expect(legacy.output).toContain("Unknown tool: kill_command");
});
it("dispose suppresses pending completion reports", async () => {
@@ -292,7 +296,6 @@ describe("input_command defaults", () => {
const SUB_DEF = toolDef("run_subagent");
const SUB_INPUT_DEF = toolDef("input_subagent");
-const SUB_KILL_DEF = toolDef("kill_subagent");
const CTX: ToolExecutionContext = { workspaceDir: "/tmp/ws", toolCallId: "call_1" };
const HOP = "session-child-12ab34cd";
@@ -359,6 +362,7 @@ describe("run_subagent run_in_background", () => {
const runner = runnerOf(async function* ({ prompt }) {
await new Promise<void>((r) => gates.set(prompt, r));
yield withHop(partialText("delta", `answer to: ${prompt}`));
+ yield withHop(assistantText(`answer to: ${prompt}`));
});
const events: BackgroundTaskDoneEvent[] = [];
const services = {
@@ -407,7 +411,53 @@ describe("run_subagent run_in_background", () => {
expect(events[1]!.output).toContain("answer to: second round");
});
- it("kill_subagent aborts a running background subagent without a completion report", async () => {
+ it("a HOST-started round stays silent: no completion report for the user's own message", async () => {
+ const manager = new SubagentSessionManager();
+ cleanups.push(() => manager.dispose());
+ const gates = new Map<string, () => void>();
+ const runner = runnerOf(async function* ({ prompt }) {
+ await new Promise<void>((r) => gates.set(prompt, r));
+ yield withHop(partialText("delta", `answer to: ${prompt}`));
+ yield withHop(assistantText(`answer to: ${prompt}`));
+ });
+ const events: BackgroundTaskDoneEvent[] = [];
+ const services = {
+ subagentRunner: runner,
+ subagentSessions: manager,
+ backgroundDone: (e: BackgroundTaskDoneEvent) => events.push(e),
+ };
+ const tool = createSubagentTool(SUB_DEF, services);
+ const res = await drive(tool, { prompt: "dispatched work", run_in_background: true });
+ const id = extractSubagentId(res.note);
+ await waitFor(() => gates.has("dispatched work"));
+ gates.get("dispatched work")!();
+ await waitFor(() => events.length === 1);
+
+ // The user messages the idle child from the panel: their conversation, not dispatched
+ // work — the parent must not be notified when it settles.
+ const session = manager.get(id)!;
+ session.startRun("user says hi", { suppressDoneReport: true });
+ await waitFor(() => gates.has("user says hi"));
+ gates.get("user says hi")!();
+ await waitFor(() => !session.running);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(events).toHaveLength(1);
+
+ // The next MODEL-initiated round reports again (the watcher stayed armed).
+ const input = createInputSubagentTool(SUB_INPUT_DEF, services);
+ const follow = await drive(input, {
+ subagent_id: id,
+ prompt: "model round",
+ yield_time_ms: 250,
+ });
+ expect(follow.stopReason).toBe("completed");
+ await waitFor(() => gates.has("model round"));
+ gates.get("model round")!();
+ await waitFor(() => events.length === 2);
+ expect(events[1]!.output).toContain("answer to: model round");
+ });
+
+ it("input_subagent abort ends a running background round without a completion report", async () => {
const manager = new SubagentSessionManager();
cleanups.push(() => manager.dispose());
const runner = runnerOf(async function* ({ signal }) {
@@ -424,13 +474,15 @@ describe("run_subagent run_in_background", () => {
backgroundDone: (e: BackgroundTaskDoneEvent) => events.push(e),
};
const tool = createSubagentTool(SUB_DEF, services);
- const res = await drive(tool, { prompt: "will be killed", run_in_background: true });
+ const res = await drive(tool, { prompt: "will be aborted", run_in_background: true });
const id = extractSubagentId(res.note);
- const kill = createKillSubagentTool(SUB_KILL_DEF, services);
- const killed = await drive(kill, { subagent_id: id });
- expect(killed.stopReason).toBe("completed");
- expect(killed.note).toContain("aborted and removed");
- expect(manager.get(id)).toBeUndefined();
+ const input = createInputSubagentTool(SUB_INPUT_DEF, services);
+ const stopped = await drive(input, { subagent_id: id, abort: true, yield_time_ms: 3000 });
+ expect(stopped.output).toContain(`aborting subagent ${id}'s current run`);
+ expect(stopped.note).toContain(`subagent idle with subagent_id ${id}`);
+ // The session survives — a subagent has no kill notion, only its rounds end.
+ expect(manager.get(id)).toBeDefined();
+ // The abort-caused settle must not masquerade as a task completion.
await new Promise((r) => setTimeout(r, 100));
expect(events).toHaveLength(0);
});
@@ -492,11 +544,11 @@ describe("run_subagent run_in_background", () => {
expect(events[0]!.status).toBe("completed");
});
- it("kill_subagent fails on an unknown subagent_id", async () => {
+ it("input_subagent fails on an id this conversation never allocated (nothing to resume)", async () => {
const manager = new SubagentSessionManager();
cleanups.push(() => manager.dispose());
- const kill = createKillSubagentTool(SUB_KILL_DEF, { subagentSessions: manager });
- const res = await drive(kill, { subagent_id: "subagent-deadbeef" });
+ const input = createInputSubagentTool(SUB_INPUT_DEF, { subagentSessions: manager });
+ const res = await drive(input, { subagent_id: "subagent-deadbeef" });
expect(res.stopReason).toBe("failed");
expect(res.output).toContain("unknown subagent_id");
});
diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts
index ddf436df..10397523 100644
--- a/packages/core/test/engine.test.ts
+++ b/packages/core/test/engine.test.ts
@@ -2588,6 +2588,29 @@ describe("ContextEngine mid-run steering ([user_steering])", () => {
expect(engine.steer([userText("late")])).toBe(false);
});
+ it("the delivered [user_steering] message keeps the queued input's sender", async () => {
+ const llm = new FakeLLM();
+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_steer_sender" });
+ const engine = new ContextEngine({ llm, environment: steeringEnvironment(), trace });
+
+ // A parent agent steering its child (input_subagent) queues with sender "parent_agent";
+ // human steering leaves the field absent. Both must survive to the delivered message —
+ // origin is a structural fact the child's Trace records.
+ const approve: ApproveFn = async () => {
+ expect(engine.steer([userText("adjust course", "parent_agent")])).toBe(true);
+ expect(engine.steer([userText("human note")])).toBe(true);
+ return "allow";
+ };
+ const all = await collectRun(engine, [userText("go")], approve);
+
+ const delivered = all
+ .map((m) => m.payload as { role?: string; text?: string; sender?: string })
+ .filter((p) => p.role === "user" && (p.text ?? "").startsWith("[user_steering]"));
+ expect(delivered).toHaveLength(2);
+ expect(delivered[0]!.sender).toBe("parent_agent");
+ expect(delivered[1]!.sender).toBeUndefined();
+ });
+
it("unsteer withdraws a queued entry before delivery; refuses once drained or idle", async () => {
const llm = new FakeLLM();
const trace = new Writer({ tracesDir: traces, sessionId: "sess_unsteer" });
diff --git a/packages/core/test/kernel-version.test.ts b/packages/core/test/kernel-version.test.ts
index 3d8c7b9b..052d9b26 100644
--- a/packages/core/test/kernel-version.test.ts
+++ b/packages/core/test/kernel-version.test.ts
@@ -299,9 +299,7 @@ describe("applyKernelUpdate", () => {
const config = mutableConfig(defaultSystemConfig());
delete config.kernel_version;
const tools = config.tools as { builtin: Array<Record<string, unknown>> };
- tools.builtin = tools.builtin.filter(
- (t) => t.name !== "kill_command" && t.name !== "kill_subagent",
- );
+ tools.builtin = tools.builtin.slice(0, -1); // an old default, missing a tool added since
const supersededTabs: KernelSupersededTabHashes = { tools: [kernelTabHash(config, "tools")!] };
await seedConfig(config);
diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.ts
index 8f93bd88..8730ab0e 100644
--- a/packages/core/test/state.test.ts
+++ b/packages/core/test/state.test.ts
@@ -253,10 +253,8 @@ describe("buildToolConfig", () => {
"write_file",
"exec_command",
"input_command",
- "kill_command",
"run_subagent",
"input_subagent",
- "kill_subagent",
"read_image",
"describe_image",
]);
@@ -383,10 +381,8 @@ describe("buildToolConfig", () => {
"write_file",
"exec_command",
"input_command",
- "kill_command",
"run_subagent",
"input_subagent",
- "kill_subagent",
"read_image",
"describe_image",
]);
diff --git a/packages/core/test/subagent.test.ts b/packages/core/test/subagent.test.ts
index b295d606..1e7db9d3 100644
--- a/packages/core/test/subagent.test.ts
+++ b/packages/core/test/subagent.test.ts
@@ -3,13 +3,20 @@
* polling, resuming with an appended Prompt, the approval queue, and lifecycle finalization.
*/
import { afterEach, describe, expect, it } from "vitest";
+import { Environment } from "../src/environment/index.js";
import { createSubagentTool } from "../src/environment/tools/run-subagent.js";
import { createInputSubagentTool } from "../src/environment/tools/input-subagent.js";
import {
ManagedSubagentSession,
SubagentSessionManager,
} from "../src/environment/tools/subagent/index.js";
-import { abortEvent, partialText, toolCall, withOrigin } from "../src/omnimessage/index.js";
+import {
+ abortEvent,
+ assistantText,
+ partialText,
+ toolCall,
+ withOrigin,
+} from "../src/omnimessage/index.js";
import { collectWindow } from "../src/environment/tools/subagent/collect.js";
import type { MessageOrigin, OmniMessage } from "../src/omnimessage/index.js";
import type {
@@ -401,9 +408,11 @@ describe("run_subagent backgrounding + input_subagent", () => {
await Promise.race([gate, aborted(signal)]);
if (signal?.aborted) return;
yield withOrigin(partialText("delta", `end:${prompt}`), HOP);
+ yield withOrigin(assistantText(`start:${prompt} end:${prompt}`), HOP);
return;
}
yield withOrigin(partialText("delta", `ran:${prompt}`), HOP);
+ yield withOrigin(assistantText(`ran:${prompt}`), HOP);
};
return { run, release, prompts };
}
@@ -467,7 +476,7 @@ describe("run_subagent backgrounding + input_subagent", () => {
expect(child.prompts).toEqual(["one", "two"]);
});
- it("rejects a follow-up prompt while the subagent is still running", async () => {
+ it("rejects a mid-run prompt when the handle predates steering", async () => {
const child = gatedChild();
const { services } = makeServices(runnerOf(child.run));
const runTool = createSubagentTool(DEF, services);
@@ -504,6 +513,7 @@ describe("run_subagent backgrounding + input_subagent", () => {
)
: "deny";
yield withOrigin(partialText("delta", `approved:${decision}`), HOP);
+ yield withOrigin(assistantText(`approved:${decision}`), HOP);
});
const { services } = makeServices(runner);
// The start call has no approve: once the window ends and it backgrounds, the child
@@ -623,3 +633,394 @@ describe("run_subagent backgrounding + input_subagent", () => {
}
});
});
+
+describe("subagent steering and per-run abort", () => {
+ /**
+ * A steer-capable child: round 1 pends until released or aborted (an abort emits the
+ * child's abort event, as a real interrupted child session does); later rounds finish
+ * immediately. Records every prompt and steering delivery.
+ */
+ function steerableChild(): {
+ runner: SubagentRunner;
+ prompts: string[];
+ steers: OmniMessage[][];
+ release: () => void;
+ } {
+ const prompts: string[] = [];
+ const steers: OmniMessage[][] = [];
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const runner: SubagentRunner = {
+ async spawn() {
+ const handle: SubagentHandle = {
+ sessionId: HOP,
+ async *run({ prompt, signal }): AsyncGenerator<OmniMessage> {
+ prompts.push(prompt);
+ if (prompts.length === 1) {
+ yield withOrigin(partialText("delta", `start:${prompt} `), HOP);
+ await Promise.race([gate, aborted(signal)]);
+ if (signal?.aborted) {
+ yield withOrigin(abortEvent("run aborted"), HOP);
+ return;
+ }
+ yield withOrigin(partialText("delta", `end:${prompt}`), HOP);
+ yield withOrigin(assistantText(`end:${prompt}`), HOP);
+ return;
+ }
+ yield withOrigin(partialText("delta", `ran:${prompt}`), HOP);
+ yield withOrigin(assistantText(`ran:${prompt}`), HOP);
+ },
+ steer(messages) {
+ steers.push(messages);
+ return true;
+ },
+ dispose() {},
+ };
+ return handle;
+ },
+ };
+ return { runner, prompts, steers, release: () => release() };
+ }
+
+ it("queues a mid-run prompt as a steering message with the parent_agent sender", async () => {
+ const child = steerableChild();
+ const { services } = makeServices(child.runner);
+ const runTool = createSubagentTool(DEF, services);
+ const { result: started } = await collectWithReturn(
+ runTool.execute({ prompt: "task", yield_time_ms: 250 }, CTX),
+ );
+ const id = extractSubagentId(started);
+
+ const writeTool = createInputSubagentTool(INPUT_DEF, services);
+ const { out, result } = await collectWithReturn(
+ writeTool.execute({ subagent_id: id, prompt: "go left", yield_time_ms: 250 }, CTX),
+ );
+ expect(ownDeltas(out)).toContain(`steering message queued for subagent ${id}`);
+ expect(result?.stopReason).toBe("completed");
+ expect(result?.note).toContain("still running");
+ expect(child.steers).toHaveLength(1);
+ const payload = child.steers[0]![0]!.payload as { text?: string; sender?: string };
+ expect(payload.text).toBe("go left");
+ expect(payload.sender).toBe("parent_agent");
+ // No new round was started: the prompt rode the running one.
+ expect(child.prompts).toEqual(["task"]);
+ child.release();
+ });
+
+ it("abort ends only the current run; the session survives for a follow-up", async () => {
+ const child = steerableChild();
+ const { services, manager } = makeServices(child.runner);
+ const runTool = createSubagentTool(DEF, services);
+ const { result: started } = await collectWithReturn(
+ runTool.execute({ prompt: "task", yield_time_ms: 250 }, CTX),
+ );
+ const id = extractSubagentId(started);
+
+ const writeTool = createInputSubagentTool(INPUT_DEF, services);
+ const { out, result } = await collectWithReturn(
+ writeTool.execute({ subagent_id: id, abort: true, yield_time_ms: 3000 }, CTX),
+ );
+ expect(ownDeltas(out)).toContain(`aborting subagent ${id}'s current run`);
+ // The aborted round settles as failed with the child's abort reason; the session is kept.
+ expect(result?.stopReason).toBe("failed");
+ expect(result?.note).toContain("subagent aborted");
+ expect(result?.note).toContain(`subagent idle with subagent_id ${id}`);
+ expect(manager.get(id)).toBeDefined();
+
+ const followUp = await collectWithReturn(
+ writeTool.execute({ subagent_id: id, prompt: "again", yield_time_ms: 3000 }, CTX),
+ );
+ expect(ownDeltas(followUp.out)).toContain("ran:again");
+ expect(followUp.result?.stopReason).toBe("completed");
+ expect(child.prompts).toEqual(["task", "again"]);
+ });
+
+ it("abort with a prompt interrupts and redirects in one call", async () => {
+ const child = steerableChild();
+ const { services } = makeServices(child.runner);
+ const runTool = createSubagentTool(DEF, services);
+ const { result: started } = await collectWithReturn(
+ runTool.execute({ prompt: "task", yield_time_ms: 250 }, CTX),
+ );
+ const id = extractSubagentId(started);
+
+ const writeTool = createInputSubagentTool(INPUT_DEF, services);
+ const { out, result } = await collectWithReturn(
+ writeTool.execute(
+ { subagent_id: id, abort: true, prompt: "redirect", yield_time_ms: 3000 },
+ CTX,
+ ),
+ );
+ expect(ownDeltas(out)).toContain("ran:redirect");
+ expect(result?.stopReason).toBe("completed");
+ expect(child.prompts).toEqual(["task", "redirect"]);
+ // The redirect ran fresh — nothing was delivered as steering.
+ expect(child.steers).toHaveLength(0);
+ });
+
+ it("abort on an idle subagent is a harmless no-op", async () => {
+ const child = steerableChild();
+ const { services } = makeServices(child.runner);
+ const runTool = createSubagentTool(DEF, services);
+ const { result: started } = await collectWithReturn(
+ runTool.execute({ prompt: "task", yield_time_ms: 250 }, CTX),
+ );
+ const id = extractSubagentId(started);
+ child.release();
+ const writeTool = createInputSubagentTool(INPUT_DEF, services);
+ await collectWithReturn(writeTool.execute({ subagent_id: id, yield_time_ms: 3000 }, CTX));
+
+ const { out, result } = await collectWithReturn(
+ writeTool.execute({ subagent_id: id, abort: true, yield_time_ms: 250 }, CTX),
+ );
+ expect(ownDeltas(out)).toContain("already idle; nothing to abort");
+ expect(result?.stopReason).toBe("completed");
+ });
+
+ it("exposes list/steer/abort to the host via Environment, converging on the same channel", async () => {
+ const child = steerableChild();
+ const env = new Environment({
+ workspaceDir: "/tmp/ws",
+ toolConfig: { customTools: [DEF], mcpServers: [] },
+ services: { subagentRunner: child.runner },
+ });
+ try {
+ let pings = 0;
+ env.setSubagentStateListener(() => {
+ pings += 1;
+ });
+ const forwarded: OmniMessage[] = [];
+ env.setBackgroundMessageListener((msg) => forwarded.push(msg));
+
+ // Spawn through the real tool path; the window expires with the child still running.
+ const gen = env.executeTool({
+ toolCall: toolCall({
+ name: "run_subagent",
+ arguments: JSON.stringify({ prompt: "task", yield_time_ms: 250 }),
+ toolCallId: "c_env",
+ }),
+ });
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) break;
+ }
+
+ expect(env.listBackgroundSubagents()).toEqual([
+ { sessionId: HOP, subagentId: `subagent-${HOP.slice(-8)}`, running: true },
+ ]);
+
+ // Host steering while running: human sender (field absent), same handle channel.
+ expect(await env.sendToBackgroundSubagent(HOP, "from the panel")).toBe("steered");
+ expect(child.steers).toHaveLength(1);
+ const payload = child.steers[0]![0]!.payload as { text?: string; sender?: string };
+ expect(payload.text).toBe("from the panel");
+ expect(payload.sender).toBeUndefined();
+
+ // 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);
+ expect(pings).toBeGreaterThan(0);
+
+ // Host message on the idle child starts a follow-up round; its messages reach the
+ // frontend live through the tap the first host touch attached.
+ expect(await env.sendToBackgroundSubagent(HOP, "round two")).toBe("started");
+ await until(() => env.listBackgroundSubagents()[0]?.running === false);
+ expect(child.prompts).toEqual(["task", "round two"]);
+ await until(() =>
+ forwarded.some((m) => {
+ const p = m.payload as { type?: string; text?: string };
+ return p.type === "partial_text" && (p.text ?? "").includes("ran:round two");
+ }),
+ );
+
+ expect(await env.sendToBackgroundSubagent("session-unknown", "x")).toBe("gone");
+ expect(env.abortBackgroundSubagentRun("session-unknown")).toBe(false);
+ } finally {
+ env.dispose();
+ }
+ });
+
+ it("escalates a windowless child approval through the host fallback sink", async () => {
+ const runner = runnerOf(async function* ({ approve }: RunInput) {
+ yield withOrigin(partialText("delta", "working "), HOP);
+ const decision = approve
+ ? await approve(
+ withOrigin(toolCall({ name: "exec_command", arguments: "{}", toolCallId: "t1" }), HOP),
+ )
+ : "deny";
+ yield withOrigin(partialText("delta", `approved:${decision}`), HOP);
+ yield withOrigin(assistantText(`approved:${decision}`), HOP);
+ });
+ const env = new Environment({
+ workspaceDir: "/tmp/ws",
+ toolConfig: { customTools: [DEF], mcpServers: [] },
+ services: { subagentRunner: runner },
+ });
+ try {
+ const consulted: string[] = [];
+ env.setSubagentApprovalFallback(async (tc) => {
+ consulted.push(tc.payload.tool_call_id);
+ return "allow";
+ });
+ // The spawning call carries NO approve: no window sink, no background-launch standing
+ // sink — previously this approval parked until the model's next poll. With the host
+ // fallback it resolves inside the window and the child finishes normally.
+ const gen = env.executeTool({
+ toolCall: toolCall({
+ name: "run_subagent",
+ arguments: JSON.stringify({ prompt: "task", yield_time_ms: 3000 }),
+ toolCallId: "c_fallback",
+ }),
+ });
+ const out: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) break;
+ out.push(res.value);
+ }
+ const complete = out[out.length - 1]!.payload as { output?: string };
+ expect(complete.output).toContain("approved:allow");
+ expect(consulted).toEqual(["t1"]);
+ } finally {
+ env.dispose();
+ }
+ });
+
+ 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> {
+ prompts.push(prompt);
+ levels.push(thinkingLevel);
+ yield withOrigin(partialText("delta", `ran:${prompt}`), HOP);
+ };
+ const runner: SubagentRunner = {
+ async spawn() {
+ return { sessionId: HOP, run, dispose() {} };
+ },
+ async resume(input) {
+ resumes.push(input);
+ return { sessionId: HOP, run, dispose() {} };
+ },
+ };
+ const env = new Environment({
+ workspaceDir: "/tmp/ws",
+ toolConfig: { customTools: [DEF], mcpServers: [] },
+ services: { subagentRunner: runner },
+ });
+ try {
+ // The child finishes inside the foreground window: never registered, killed at the end
+ // of the call — released, exactly the state the panel later messages into.
+ const gen = env.executeTool({
+ toolCall: toolCall({
+ name: "run_subagent",
+ arguments: JSON.stringify({ prompt: "task" }),
+ toolCallId: "c_resume",
+ }),
+ });
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) break;
+ }
+ expect(env.listBackgroundSubagents()).toEqual([]);
+
+ // Without the resume option the child is simply gone; with it, the session revives,
+ // re-registers (the model can address it again), and runs the message as a new round.
+ expect(await env.sendToBackgroundSubagent(HOP, "wake up")).toBe("gone");
+ expect(
+ await env.sendToBackgroundSubagent(HOP, "wake up", {
+ thinkingLevel: "high",
+ resume: { agentId: "owner_agent" },
+ }),
+ ).toBe("resumed");
+ expect(resumes).toEqual([{ agentId: "owner_agent", sessionId: HOP }]);
+ 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();
+ }
+ });
+
+ it("input_subagent revives a released id through the runner (a subagent is never destroyed)", async () => {
+ const prompts: string[] = [];
+ const resumes: { agentId?: string; sessionId: string }[] = [];
+ const run = async function* ({ prompt }: RunInput): AsyncGenerator<OmniMessage> {
+ prompts.push(prompt);
+ yield withOrigin(assistantText(`ran:${prompt}`), HOP);
+ };
+ const runner: SubagentRunner = {
+ async spawn() {
+ return { sessionId: HOP, run, dispose() {} };
+ },
+ async resume(input) {
+ resumes.push(input);
+ return { sessionId: HOP, run, dispose() {} };
+ },
+ };
+ const { services, manager } = makeServices(runner);
+
+ // Register the target, let its round settle, then fill the registry so capacity
+ // eviction RELEASES it (frees the slot — nothing is destroyed).
+ const target = new ManagedSubagentSession({ sessionId: HOP, run, dispose() {} });
+ target.startRun("first");
+ await until(() => !target.running);
+ manager.track(target);
+ const id = manager.register(target);
+ for (let i = 0; i < 8; i += 1) {
+ const filler = new ManagedSubagentSession({
+ sessionId: `session-filler-0000000${i}`,
+ run,
+ dispose() {},
+ });
+ filler.startRun("filler");
+ await until(() => !filler.running);
+ manager.register(filler);
+ }
+ expect(manager.get(id)).toBeUndefined();
+
+ // The model messages the released id: the tombstone resumes the child (self-spawn — no
+ // agentId recorded) and the prompt runs as its next round on the same handle.
+ const input = createInputSubagentTool(INPUT_DEF, services);
+ const { out, result } = await collectWithReturn(
+ input.execute({ subagent_id: id, prompt: "again", yield_time_ms: 3000 }, CTX),
+ );
+ expect(ownDeltas(out)).toContain(`[subagent ${id} resumed]`);
+ expect(ownDeltas(out)).toContain("ran:again");
+ expect(result?.stopReason).toBe("completed");
+ expect(resumes).toEqual([{ sessionId: HOP }]);
+ expect(prompts).toContain("again");
+ expect(manager.get(id)).toBeDefined();
+ });
+
+ it("tracks live sessions by child session id from spawn to kill", () => {
+ const manager = new SubagentSessionManager();
+ managers.push(manager);
+ const session = new ManagedSubagentSession({
+ sessionId: HOP,
+ // eslint-disable-next-line require-yield
+ async *run({ signal }: RunInput): AsyncGenerator<OmniMessage> {
+ await aborted(signal);
+ },
+ dispose() {},
+ });
+ manager.track(session);
+ // Reachable by session id before any background registration (no subagent_id yet).
+ expect(manager.bySessionId(HOP)).toBe(session);
+ expect(manager.listLive()).toEqual([{ sessionId: HOP, subagentId: null, running: false }]);
+
+ session.startRun("occupy");
+ const id = manager.register(session);
+ expect(manager.listLive()).toEqual([{ sessionId: HOP, subagentId: id, running: true }]);
+
+ session.kill();
+ expect(manager.bySessionId(HOP)).toBeUndefined();
+ expect(manager.listLive()).toEqual([]);
+ });
+});
diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.md
index d5eca9e1..a8b2ee1a 100644
--- a/packages/docs/content/tools.en.md
+++ b/packages/docs/content/tools.en.md
@@ -72,31 +72,29 @@ Each tool is described by one `ToolDefinitionConfig`:
## Built-in tools
-There are 11 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):
+There are 9 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):
| Tool | Permission | Timeout (ms) | Purpose |
| --- | --- | --- | --- |
| `exec_command` | rw | 120000 | Run a shell command in the Workspace via `bash -lc`, streaming stdout/stderr |
-| `input_command` | rw | 130000 | Drive a running command by `process_id`: write stdin, send Ctrl-C, poll output |
-| `kill_command` | rw | 30000 | Terminate a command session by `process_id` (whole process group), returning undelivered output |
+| `input_command` | rw | 130000 | Drive a command session by `process_id`: write stdin, send Ctrl-C, poll output, or terminate it (`kill: true`) |
| `read_file` | r | 30000 | Read a text file as a line-numbered (`cat -n`) window, paged by offset/limit |
| `edit_file` | rw | 30000 | Exact-string replacement in an existing file, echoing a verification snippet |
| `write_file` | rw | 30000 | Create or overwrite a whole file, creating parent directories as needed |
| `run_subagent` | rw | 600000 | Delegate a self-contained subtask to a child Agent in the same Workspace |
-| `input_subagent` | rw | 600000 | Poll a background subagent, or send a follow-up prompt once it is idle |
-| `kill_subagent` | rw | 30000 | Abort a background subagent by `subagent_id` and remove it, returning undelivered text |
+| `input_subagent` | rw | 600000 | Poll a background subagent, steer it mid-run, stop its current run, or continue it with a follow-up prompt |
| `read_image` | r | 60000 | Read an image and return it as image content (vision models) |
| `describe_image` | r | 90000 | Have the configured `vision_model` read the image and answer in text (text-only models) |
-Note that an existing agent's persisted `tools.builtin` list is frozen as written (the settings UI edits rows but adds none): agents created before this toolset do not pick up newer tools (the file tools, `kill_command`, `kill_subagent`) or newer arguments (`run_in_background`) automatically — hand-edit the agent's `system_config.yaml` and add the new entries (copy them from the default definitions in `packages/core/src/state/default-config.ts`) to adopt them.
+Note that an existing agent's persisted `tools.builtin` list is frozen as written (the settings UI edits rows but adds none): agents created before this toolset do not pick up newer tools (e.g. the file tools) or newer arguments (`run_in_background`, `kill`, `abort`) automatically — and entries for since-removed tools (`kill_command`, `kill_subagent`) simply stop assembling: a model calling them gets the standard unknown-tool failure — hand-edit the agent's `system_config.yaml` and add the new entries (copy them from the default definitions in `packages/core/src/state/default-config.ts`) to adopt them.
### Call descriptions
-The command/subagent tools (`exec_command`, `input_command`, `kill_command`, `run_subagent`, `input_subagent`, `kill_subagent`) take a `description` argument: one model-written sentence about what the call is doing, shown by the CLI and Web UI while the call runs. The argument is declared as a normal `description` property in each entry's `parameters` in `system_config.yaml` (tool schemas live entirely in the editable config), and it is **required** there — a tool that offers the argument always gets one, so the frontends can pick a call's display form from the schema instead of guessing while the arguments stream; the model is also asked to emit it first. The per-entry `call_description` field toggles the whole thing — missing = kept, `call_description: false` filters the property (and its `required` entry) out of the schema at assembly time (in-memory only, the YAML is never rewritten). The file tools don't take it — their `file_path` argument is self-describing.
+The command/subagent tools (`exec_command`, `input_command`, `run_subagent`, `input_subagent`) take a `description` argument: one model-written sentence about what the call is doing, shown by the CLI and Web UI while the call runs. The argument is declared as a normal `description` property in each entry's `parameters` in `system_config.yaml` (tool schemas live entirely in the editable config), and it is **required** there — a tool that offers the argument always gets one, so the frontends can pick a call's display form from the schema instead of guessing while the arguments stream; the model is also asked to emit it first. The per-entry `call_description` field toggles the whole thing — missing = kept, `call_description: false` filters the property (and its `required` entry) out of the schema at assembly time (in-memory only, the YAML is never rewritten). The file tools don't take it — their `file_path` argument is self-describing.
### Command sessions
-`exec_command` waits in the foreground first; if the command outruns `yield_time_ms` it moves to the background and the call returns the output so far plus a `process_id`, driven from then on by `input_command`. With `run_in_background: true` it skips the foreground window entirely: the call returns the `process_id` immediately, and when the process exits its result arrives as an automatic user message (see [Background completion reports](#background-completion-reports)). `kill_command` terminates a session either way:
+`exec_command` waits in the foreground first; if the command outruns `yield_time_ms` it moves to the background and the call returns the output so far plus a `process_id`, driven from then on by `input_command`. With `run_in_background: true` it skips the foreground window entirely: the call returns the `process_id` immediately, and when the process exits its result arrives as an automatic user message (see [Background completion reports](#background-completion-reports)). `input_command` with `kill: true` terminates a session either way — a process is a real OS object that IS destroyed, so termination is a parameter of the access tool rather than a tool of its own:
```text
exec_command(cmd)
@@ -108,7 +106,7 @@ exec_command(cmd)
│ └─ loop until the command exits
└─ run_in_background: true ──► returns process_id immediately
└─ on exit: completion report arrives as a user message
- kill_command(process_id) ──► SIGTERM the process group (SIGKILL after a grace period)
+ input_command(process_id, kill: true) ──► SIGTERM the process group (SIGKILL after a grace period)
```
The tools' arguments (explicit keys):
@@ -127,15 +125,10 @@ The tools' arguments (explicit keys):
{
process_id: string; // required: the command-session id returned by exec_command
chars?: string; // characters for stdin; send "\u0003" alone to deliver Ctrl-C; empty = poll only
+ kill?: boolean; // true = terminate: kill the whole process group, return undelivered output, remove the session
yield_time_ms?: number; // wait; defaults 250 for writes, 120000 for empty polls (one poll waits out most builds; pass a smaller value to peek)
description: string; // required while call_description is on
}
-
-// kill_command
-{
- process_id: string; // required: the command session to terminate (already-exited sessions are removed too)
- description: string; // required while call_description is on
-}
```
On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the foreground command. On Windows there is no console signal delivery to a piped child process, so Ctrl-C degrades to a hard kill of the whole command session tree (`taskkill /t /f`) — the foreground command and every child it started terminate, instead of the foreground command being interrupted.
@@ -175,7 +168,9 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
### Subagents
-`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` for polling or follow-up prompts; the child's pending approvals surface while the poll waits. With `run_in_background: true` the call returns the `subagent_id` immediately and every round's completion arrives as an automatic user message (see [Background completion reports](#background-completion-reports)); `kill_subagent` aborts and removes a background subagent (an idle one is removed too, freeing its slot).
+`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.
```ts
// run_subagent
@@ -193,16 +188,12 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
// input_subagent
{
subagent_id: string; // required: the background Subagent id returned by run_subagent
- prompt?: string; // follow-up task, accepted only while the child Session is idle; empty = poll only
+ prompt?: string; // steering interjection while the child runs; a follow-up round while it is idle; empty = poll only
+ abort?: boolean; // stop the child's CURRENT run (session kept; the aborted round sends no completion report); with a prompt: interrupt and redirect
yield_time_ms?: number; // wait; defaults 300000 with a prompt, 10000 for empty polls
description: string; // required while call_description is on
}
-// kill_subagent
-{
- subagent_id: string; // required: the background subagent to abort and remove
- description: string; // required while call_description is on
-}
```
- Depth is capped at 1: a subagent cannot spawn another subagent.
@@ -231,9 +222,9 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
A task launched with `run_in_background: true` reports its completion as a **user message injected by the harness** — the model does not need to poll. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).
-Delivery: while a Task is running, the report rides the next turn boundary — a final reply already streaming does not lose it, the Task simply continues for one more turn to react. While the Session is idle, the hosting server starts a new Task carrying the report (SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get it prepended to the next run). A task stopped through `kill_command` / `kill_subagent` sends no report — the kill's own result already carries the outcome.
+Delivery: while a Task is running, the report rides the next turn boundary — a final reply already streaming does not lose it, the Task simply continues for one more turn to react. While the Session is idle, the hosting server starts a new Task carrying the report (SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get it prepended to the next run). A command terminated through `input_command`'s `kill` sends no report — that call's own result already carries the outcome — and neither does a subagent round ended by an explicit `abort` (the aborter reads the outcome directly). Reports cover **model-initiated rounds only** — the `run_in_background` launch and `input_subagent` follow-ups; a round the user starts from the subagents panel is their own conversation with the child and sends no report (its answer text stays in the model-facing buffer for the next poll).
-A background subagent's lifecycle is decoupled from the call that launched it: its abort signal is its own (only `kill_subagent`, Session end, or registry eviction ends it), its messages stream to the frontend live through the launching Session (same origin-tagged channel a foreground window relays), and its tool approvals resolve through the launching call's own approval callback as a standing sink — so an `allow-all` launch runs unattended, and a failure still ends in a `status: failed` report rather than a child parked forever.
+A background subagent's lifecycle is decoupled from the call that launched it: its abort scope is its own (a per-run `abort` ends a round; the session itself leaves only with the parent Session, and even a capacity-released one can be revived), its messages stream to the frontend live through the launching Session (same origin-tagged channel a foreground window relays), and its tool approvals resolve through the launching call's own approval callback as a standing sink — so an `allow-all` launch runs unattended, and a failure still ends in a `status: failed` report rather than a child parked forever.
### Background session caps
@@ -259,6 +250,8 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDec
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).
+A subagent child's approval is never auto-denied by the parent's task ending. On the Web server, a session-lifetime fallback approval sink escalates any child approval that has no active poll window and no background-launch standing sink straight to the user (the parent session sitting idle included), and a parent task ending or being stopped converges only the **main** session's pending approvals — an origin-tagged child approval stays pending, and its card stays on screen, until the user decides. Hosts that attach no such sink (the CLI) keep the poll-window-only semantics: the child's requests queue until a `run_subagent` / `input_subagent` call is active.
+
## Custom tools & MCP
The `tools.builtin` array in `system_config.yaml` declares the toolset with entries of the same `ToolDefinitionConfig` shape. The semantics are **wholesale replacement, not merging**: omit the section entirely to keep the full default toolset; once written, the default list is replaced and every tool you keep must carry its complete definition (including the `parameters` JSON Schema — a tool's schema comes entirely from config). `tools.mcpServers` carries the MCP Server configuration, covered in the next section. See also [Configuration](/configuration).
diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.md
index e55017d4..cd56d98f 100644
--- a/packages/docs/content/tools.zh.md
+++ b/packages/docs/content/tools.zh.md
@@ -72,31 +72,29 @@ Recovery 文件保存 Environment 收到的未经脱敏的工具文本。误读
## 内置工具
-共 11 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):
+共 9 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):
| 工具 | 权限 | 超时(ms) | 用途 |
| --- | --- | --- | --- |
| `exec_command` | rw | 120000 | 在 Workspace 内以 `bash -lc` 运行命令,流式返回 stdout/stderr |
-| `input_command` | rw | 130000 | 按 `process_id` 驱动运行中的命令:写 stdin、发 Ctrl-C、轮询输出 |
-| `kill_command` | rw | 30000 | 按 `process_id` 终止命令会话(整个进程组),返回尚未送达的输出 |
+| `input_command` | rw | 130000 | 按 `process_id` 驱动命令会话:写 stdin、发 Ctrl-C、轮询输出,或终止(`kill: true`) |
| `read_file` | r | 30000 | 按 `cat -n` 风格带行号读取文本文件,以 offset/limit 分页 |
| `edit_file` | rw | 30000 | 对既有文件做精确字符串替换,回显校验片段 |
| `write_file` | rw | 30000 | 新建或整体覆写文件,按需创建父目录 |
| `run_subagent` | rw | 600000 | 把自包含子任务委派给同 Workspace 的子 Agent |
-| `input_subagent` | rw | 600000 | 轮询后台 Subagent,或在其空闲时追加后续 Prompt |
-| `kill_subagent` | rw | 30000 | 按 `subagent_id` 中止并移除后台 Subagent,返回尚未送达的文本 |
+| `input_subagent` | rw | 600000 | 轮询后台 Subagent、运行中插话、停止其当前轮,或在其空闲时追加后续 Prompt |
| `read_image` | r | 60000 | 读取图片并作为图像内容返回(vision 模型) |
| `describe_image` | r | 90000 | 由 `vision_model` 代读图片并返回文字回答(text-only 模型) |
-注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(文件工具、`kill_command`、`kill_subagent`)与新增参数(`run_in_background`)——需手工编辑该 Agent 的 `system_config.yaml`,把新条目补进去(可从 `packages/core/src/state/default-config.ts` 的默认定义复制)。
+注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(如文件工具)与新增参数(`run_in_background`、`kill`、`abort`),已移除工具(`kill_command`、`kill_subagent`)的存量条目则不再装配——模型按旧名调用得到标准的未知工具报错;采纳新条目需手工编辑该 Agent 的 `system_config.yaml`(可从 `packages/core/src/state/default-config.ts` 的默认定义复制),或走「更新内核」。
### 调用描述
-命令 / Subagent 类工具(`exec_command`、`input_command`、`kill_command`、`run_subagent`、`input_subagent`、`kill_subagent`)带 `description` 参数:由模型写一句"本次调用在做什么",CLI 与 Web 在调用运行期间展示给用户。该参数作为普通的 `description` 属性直接写在各条目的 `parameters` 中(工具 schema 完全存于可编辑配置),并且是**必填**的——提供该参数的工具每次调用都会带上它,前端据 schema 即可确定这次调用的展示形态,无需在参数流式过程中猜测;同时要求模型最先输出它。整个参数由条目级 `call_description` 字段控制——缺省保留,写 `call_description: false` 时装配阶段将该属性连同其 `required` 项一起从 schema 中滤除(仅内存内,不改写 YAML)。文件工具不带此参数——其 `file_path` 参数本身已说明用途。
+命令 / Subagent 类工具(`exec_command`、`input_command`、`run_subagent`、`input_subagent`)带 `description` 参数:由模型写一句"本次调用在做什么",CLI 与 Web 在调用运行期间展示给用户。该参数作为普通的 `description` 属性直接写在各条目的 `parameters` 中(工具 schema 完全存于可编辑配置),并且是**必填**的——提供该参数的工具每次调用都会带上它,前端据 schema 即可确定这次调用的展示形态,无需在参数流式过程中猜测;同时要求模型最先输出它。整个参数由条目级 `call_description` 字段控制——缺省保留,写 `call_description: false` 时装配阶段将该属性连同其 `required` 项一起从 schema 中滤除(仅内存内,不改写 YAML)。文件工具不带此参数——其 `file_path` 参数本身已说明用途。
### 命令会话
-`exec_command` 先在前台等待;命令超过 `yield_time_ms` 仍未结束时转入后台,返回已有输出和一个 `process_id`,之后用 `input_command` 驱动。传 `run_in_background: true` 则完全跳过前台窗口:调用立即返回 `process_id`,进程退出时其结果以自动 user message 送达(见[后台完成回报](#后台完成回报))。两种方式启动的会话都可用 `kill_command` 终止:
+`exec_command` 先在前台等待;命令超过 `yield_time_ms` 仍未结束时转入后台,返回已有输出和一个 `process_id`,之后用 `input_command` 驱动。传 `run_in_background: true` 则完全跳过前台窗口:调用立即返回 `process_id`,进程退出时其结果以自动 user message 送达(见[后台完成回报](#后台完成回报))。两种方式启动的会话都可用 `input_command` 的 `kill: true` 终止——进程是真实的 OS 对象、确会销毁,终止因此是访问工具的一个参数而非独立工具:
```text
exec_command(cmd)
@@ -107,7 +105,7 @@ exec_command(cmd)
│ └─ 循环驱动,直至命令退出
└─ run_in_background: true ──► 立即返回 process_id
└─ 退出时:完成回报以 user message 送达
- kill_command(process_id) ──► 向进程组发 SIGTERM(宽限期后 SIGKILL)
+ input_command(process_id, kill: true) ──► 对进程组 SIGTERM(宽限后 SIGKILL)
```
各工具的参数(明确键名):
@@ -130,11 +128,6 @@ exec_command(cmd)
description: string; // 开关开启时必填
}
-// kill_command
-{
- process_id: string; // 必填:要终止的命令会话(已退出的会话也会被移除)
- description: string; // 开关开启时必填
-}
```
POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Windows 无法向管道子进程投递控制台信号,Ctrl-C 因此退化为整棵命令会话进程树的强杀(`taskkill /t /f`)——前台命令及其启动的所有子进程一并终止,而不是仅中断前台命令。
@@ -173,7 +166,9 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
### Subagent
-`run_subagent` 把一段能一次说清的子任务交给子 Agent 执行,同样是两段式:前台窗口(默认 300000ms)过后转入后台并返回 `subagent_id`,由 `input_subagent` 轮询或追加 Prompt;子 Agent 的待审批项会在轮询等待期间浮出。传 `run_in_background: true` 则立即返回 `subagent_id`,每轮完成都以自动 user message 送达(见[后台完成回报](#后台完成回报));`kill_subagent` 中止并移除后台 Subagent(空闲的也可移除,腾出并发额度)。
+`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 的同一通道;面板的运行标识以服务端实况为准,不再从对话文本推断。
```ts
// run_subagent
@@ -191,16 +186,12 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
// input_subagent
{
subagent_id: string; // 必填:run_subagent 返回的后台 Subagent id
- prompt?: string; // 追加任务,仅在子 Session 空闲时接受;缺省仅轮询
+ prompt?: string; // 运行中即插话(steering);空闲时即续跑一轮;缺省仅轮询
+ abort?: boolean; // 停止子会话当前这一轮(会话保留,被中止的轮不发完成回报);与 prompt 同给即打断并改道
yield_time_ms?: number; // 等待时长;有追加默认 300000,空轮询默认 10000
description: string; // 开关开启时必填
}
-// kill_subagent
-{
- subagent_id: string; // 必填:要中止并移除的后台 Subagent
- description: string; // 开关开启时必填
-}
```
- 深度上限为 1:Subagent 不能再派生 Subagent。
@@ -229,9 +220,9 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
以 `run_in_background: true` 启动的任务在结束时,以**Harness 注入的 user message** 回报完成——模型无需轮询。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。
-送达时机:Task 进行中时,回报搭乘下一个 turn 边界——即使最终回复已在流式输出,Task 也会为回应它再延续一个 turn。Session 空闲时,托管 Server 自动以该回报发起新 Task(SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,否则回报并入下一次 run 的输入)。经 `kill_command` / `kill_subagent` 终止的任务不发回报——kill 自身的结果已说明结局。
+送达时机:Task 进行中时,回报搭乘下一个 turn 边界——即使最终回复已在流式输出,Task 也会为回应它再延续一个 turn。Session 空闲时,托管 Server 自动以该回报发起新 Task(SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,否则回报并入下一次 run 的输入)。经 `input_command` 的 `kill` 终止的命令不发回报——该调用自身的结果已说明结局;被显式 `abort` 结束的子会话轮同样不发(打断者当场读到结局)。回报只覆盖**模型自己发起的轮**——`run_in_background` 的启动轮与 `input_subagent` 的续跑轮;用户从智能体面板发起的轮是用户与子会话自己的对话,不发回报(该轮答案文本留在模型面缓冲,下次轮询照常取得)。
-后台 Subagent 的生命周期与发起它的调用解耦:中止信号只属于它自己(仅 `kill_subagent`、Session 终结或注册表淘汰会结束它),其消息经发起 Session 实时流向前端(与前台窗口转发同一条 origin 通道),工具审批经发起调用自身的审批回调作为常驻 sink 解决——`allow-all` 下即发即忘可全程无人值守,失败也以 `status: failed` 的回报收尾,而不是子会话永久卡住。
+后台 Subagent 的生命周期与发起它的调用解耦:中止范围只属于它自己(逐轮 `abort` 只结束一轮;会话只随父 Session 终结,容量释放的也可复活),其消息经发起 Session 实时流向前端(与前台窗口转发同一条 origin 通道),工具审批经发起调用自身的审批回调作为常驻 sink 解决——`allow-all` 下即发即忘可全程无人值守,失败也以 `status: failed` 的回报收尾,而不是子会话永久卡住。
### 后台会话上限
@@ -257,6 +248,8 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDec
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) 的工具执行阶段。
+子会话的审批不会因父任务结束而被自动拒绝。Web 服务端为每个会话运行时挂一个**会话生命周期的兜底审批出口**:没有活跃轮询窗口、也没有后台启动常驻出口的子会话审批请求直接上报用户(父会话空闲时亦然);父任务结束或被停止时只收敛**主会话**自身的未决审批——带 origin 的子会话审批保持待决、审批卡持续显示,直到用户决定。未挂兜底出口的宿主(CLI)保持旧口径:子会话请求排队,等 `run_subagent` / `input_subagent` 调用活跃时透传。
+
## 自定义与 MCP
`system_config.yaml` 的 `tools.builtin` 数组以 `ToolDefinitionConfig` 同构条目声明工具集。注意语义是**整体替换而非合并**:整段省略时使用完整默认工具集;一旦写出,默认列表即被替换,要保留的每个工具都必须携带完整定义(含 `parameters` JSON Schema——工具的参数 schema 完全来自配置)。`tools.mcpServers` 承载 MCP Server 配置,见下节。另见 [配置参考](/configuration)。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 3047671d..8de1d50d 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1447,6 +1447,32 @@ export interface PendingFollowUpInfo {
files: number;
}
+/**
+ * One live subagent child of a session's runtime, carried on `task_state` events and the SSE
+ * subscribe snapshot: the child Session id (the origin hop the stream already correlates by),
+ * its background registry handle (null while it only lives inside a foreground collect
+ * window), and whether a round is currently running. Only an ACTIVE parent runtime reports
+ * children — after a server restart the in-process children are gone, and the empty list is
+ * the truth.
+ */
+export interface SubagentRuntimeInfo {
+ sessionId: string;
+ subagentId: string | null;
+ running: boolean;
+}
+
+/**
+ * Response of POST /api/sessions/:sessionId/subagents/:childSessionId/message — a user input
+ * on the child, whatever its state: `steered` = queued as a mid-run interjection, `started` =
+ * began a follow-up run on the idle child, `resumed` = the released child session was revived
+ * (resume-session semantics) and the message began its next round. The failure shapes are
+ * HTTP statuses instead: 404 when the child's session record does not exist or cannot be
+ * revived, 409 when the child cannot take the message right now.
+ */
+export interface SubagentMessageResponse {
+ outcome: "steered" | "started" | "resumed";
+}
+
/**
* Response of the two recall endpoints — DELETE /api/sessions/:id/steer/:steerId and
* DELETE /api/sessions/:id/follow-ups/:followUpId: the withdrawn message's original content,
@@ -1521,6 +1547,12 @@ export type ServerEvent =
pendingSteering?: PendingSteeringInfo[];
/** Queued follow-up tasks awaiting auto-start (absent = none): per-entry content + recall handle, alongside the `queued` count. */
pendingFollowUps?: PendingFollowUpInfo[];
+ /**
+ * Live subagent children of this session's runtime (absent = none): the panel renders
+ * child running marks from this structural liveness instead of parsing tool-output
+ * text. Refreshed on every child run start/settle.
+ */
+ subagents?: SubagentRuntimeInfo[];
}
/** The model-generated title after the first turn has been persisted (for in-place list updates). */
| { type: "session_title"; sessionId: string; title: string }
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index d1122c54..3717d6b0 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -27,6 +27,7 @@ import type {
SessionProcessesResponse,
SessionResponse,
SessionsResponse,
+ SubagentMessageResponse,
RetryNowResponse,
TaskCreateResponse,
} from "../../api/types.js";
@@ -822,15 +823,18 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// approval requests.
const pendingSteering = deps.manager.pendingSteeringOf(row.sessionId);
const pendingFollowUps = deps.manager.pendingFollowUpsOf(row.sessionId);
+ const subagents = deps.manager.subagentsOf(row.sessionId);
const initialEvents: ServerEvent[] = [
{
type: "task_state",
state: deps.manager.statusOf(row.sessionId),
queued: deps.manager.pendingFollowUpCount(row.sessionId),
- // Undelivered steering and queued follow-ups ride the snapshot too, so the composer's
- // queued hints (and what they say) survive a reload.
+ // Undelivered steering, queued follow-ups and live subagent children ride the
+ // snapshot too, so the composer's queued hints and the panel's running marks
+ // survive a reload.
...(pendingSteering.length > 0 ? { pendingSteering } : {}),
...(pendingFollowUps.length > 0 ? { pendingFollowUps } : {}),
+ ...(subagents.length > 0 ? { subagents } : {}),
},
...deps.manager.pendingApprovals(row.sessionId).map((p) => ({
type: "approval_request" as const,
@@ -968,6 +972,52 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json((await recalledResponse(recall)) satisfies RecalledMessageResponse);
});
+ // 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
+ // 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.
+ app.post("/:sessionId/subagents/:childSessionId/message", async (c) => {
+ const row = resolveSession(c);
+ 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"),
+ text,
+ thinkingLevel,
+ );
+ if (outcome === "gone") {
+ throw new HttpError(
+ 404,
+ "subagent_gone",
+ "This subagent session no longer exists and could not be revived.",
+ );
+ }
+ if (outcome === "busy") {
+ throw new HttpError(
+ 409,
+ "subagent_busy",
+ "This subagent cannot take a message right now; try again in a moment.",
+ );
+ }
+ return c.json({ outcome } satisfies SubagentMessageResponse);
+ });
+
+ // Panel stop for one subagent child (#272): aborts the child's CURRENT run only — the
+ // session survives for steering and follow-ups — a subagent session is never destroyed.
+ // 202 aborted; 204 when the child is already idle or unknown (both
+ // are "nothing left to stop", and the panel treats them alike).
+ app.post("/:sessionId/subagents/:childSessionId/abort", (c) => {
+ const row = resolveSession(c);
+ const aborted = deps.manager.abortSubagentRun(row.sessionId, pathParam(c, "childSessionId"));
+ return c.body(null, aborted ? 202 : 204);
+ });
+
// Recall a queued follow-up task back to the composer (#287): removes it from the queue
// before it auto-starts and returns its original content (with the thinking level it was
// queued with). 409 not_pending once it already started (or the id is unknown).
diff --git a/packages/server/src/runtime/approvals.ts b/packages/server/src/runtime/approvals.ts
index 03dd5bb0..cdb8abb0 100644
--- a/packages/server/src/runtime/approvals.ts
+++ b/packages/server/src/runtime/approvals.ts
@@ -76,6 +76,18 @@ export class ApprovalRegistry {
denyAll(): void {
for (const entry of [...this.pending.values()]) entry.resolve("deny");
}
+
+ /**
+ * Task-boundary convergence: deny only the MAIN session's pending approvals (no origin).
+ * An origin-tagged approval belongs to a subagent child that outlives the parent's task —
+ * the child is still blocked on the question, so it stays pending for the user; it is
+ * denied only with the child itself (kill/dispose paths use denyAll).
+ */
+ denyMain(): void {
+ for (const entry of [...this.pending.values()]) {
+ if (entry.origin === undefined || entry.origin.length === 0) entry.resolve("deny");
+ }
+ }
}
/**
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index f841dd7f..a8625099 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -42,11 +42,14 @@ import {
import type {
ApproveFn,
BackgroundCommandInfo,
+ BackgroundSubagentInfo,
CompactAvailability,
OmniMessage,
ProxyEnvPolicy,
SessionMetaPayload,
SessionTitleResult,
+ SubagentMessageOptions,
+ SubagentMessageOutcome,
TextPayload,
ThinkingLevelName,
} from "@prismshadow/penguin-core";
@@ -161,6 +164,20 @@ export interface RuntimeSession {
killBackgroundCommand?(processId: string): boolean;
/** Whether a background subagent is mid-round (core `Session.hasRunningBackgroundSubagents`); pins the entry against idle eviction. Optional, like listBackgroundCommands. */
hasRunningBackgroundSubagents?(): boolean;
+ /** All live subagent child sessions of the Session's environment (core `Session.listBackgroundSubagents`). Optional, like listBackgroundCommands. */
+ listBackgroundSubagents?(): BackgroundSubagentInfo[];
+ /** Host message to one child session — steering mid-run, a follow-up run when idle, a revival when released (core `Session.sendToBackgroundSubagent`). Optional. */
+ sendToBackgroundSubagent?(
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome>;
+ /** Subscribes the host's session-lifetime fallback approval sink for child sessions (core `Session.setSubagentApprovalFallback`). Optional. */
+ 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;
+ /** 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. */
dispose?(): void;
}
@@ -508,6 +525,54 @@ export class SessionManager {
return (this.entries.get(sessionId)?.pendingSteering ?? []).map((p) => p.info);
}
+ /**
+ * Live subagent children of an ACTIVE runtime entry (empty when the session is not loaded
+ * — after a restart there is no in-process child left to report, so empty is the truth).
+ * Rides `task_state` events and the SSE subscribe snapshot; the panel renders child
+ * running marks from this instead of parsing tool-output text.
+ */
+ subagentsOf(sessionId: string): BackgroundSubagentInfo[] {
+ return this.entries.get(sessionId)?.session.listBackgroundSubagents?.() ?? [];
+ }
+
+ /**
+ * Host message to one child session — 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 is no longer live (core `Session.sendToBackgroundSubagent`). The
+ * parent runtime itself is loaded on demand (ensureEntry — the same get-or-resume path a
+ * task uses), so messaging a child of a long-idle conversation works after a restart too;
+ * the resume fallback names the child's owning Agent from its own session row, which must
+ * belong to the parent's project.
+ */
+ async sendToSubagent(
+ sessionId: string,
+ childSessionId: string,
+ text: string,
+ thinkingLevel?: ThinkingLevelName,
+ ): Promise<SubagentMessageOutcome> {
+ const entry = await this.ensureEntry(sessionId);
+ entry.lastActivityMs = Date.now();
+ const childRow = this.deps.sessions.findById(childSessionId);
+ const resume =
+ childRow && childRow.projectId === entry.projectId
+ ? { agentId: childRow.agentId }
+ : undefined;
+ return (
+ (await entry.session.sendToBackgroundSubagent?.(childSessionId, text, {
+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
+ ...(resume ? { resume } : {}),
+ })) ?? "gone"
+ );
+ }
+
+ /** 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);
+ if (!entry) return false;
+ entry.lastActivityMs = Date.now();
+ return entry.session.abortBackgroundSubagentRun?.(childSessionId) ?? false;
+ }
+
/** Queued follow-up tasks awaiting auto-start, as their display/recall info (id + content summary). */
pendingFollowUpsOf(sessionId: string): PendingFollowUpInfo[] {
return (this.entries.get(sessionId)?.followUps ?? []).map(followUpInfo);
@@ -581,11 +646,43 @@ export class SessionManager {
* the run by core; this signal is the only trigger left when the session sits idle);
* - live-forwarded background-subagent messages, published to the session channel (the
* same feed SSE relays) and recorded for usage — a background child streams to the
- * frontend in real time past the launching turn's end, until its terminal state.
+ * frontend in real time past the launching turn's end, until its terminal state;
+ * - subagent run-state changes, republished as `task_state` so the panel's running
+ * marks track child rounds structurally instead of parsing tool-output text.
*/
private registerNoticeListener(sessionId: string, session: RuntimeSession): void {
session.onBackgroundNotice?.(() => void this.startBackgroundNoticeTask(sessionId));
session.onBackgroundMessage?.((msg) => this.forwardBackgroundMessage(sessionId, msg));
+ session.onSubagentState?.(() => {
+ const entry = this.entries.get(sessionId);
+ if (entry) this.publishState(entry, entry.status);
+ });
+ // The entry-lifetime approve doubles as the children's fallback approval sink: a child
+ // approval with no window and no background-launch standing sink escalates to the user
+ // (SSE approval_request) instead of parking until the model's next poll — the parent
+ // session idle included.
+ const entry = this.entries.get(sessionId);
+ if (entry) session.setSubagentApprovalFallback?.(this.entryApprove(entry));
+ }
+
+ /**
+ * The entry-lifetime approval callback: the registry, the per-decision approval-mode
+ * re-read, and the SSE escalation are all entry-scoped, so one instance serves every run
+ * of the entry and the children's session-lifetime fallback sink alike.
+ */
+ private entryApprove(entry: RuntimeEntry): ApproveFn {
+ return makeApprove({
+ // Re-reads approval_mode from the DB on every decision (a PATCH takes effect immediately).
+ getMode: () => this.deps.sessions.findById(entry.sessionId)?.approvalMode ?? "always-ask",
+ toolPermission: (name) => entry.session.toolPermission(name),
+ registry: entry.approvals,
+ publishRequest: (pending) =>
+ this.publishEvent(entry, {
+ type: "approval_request",
+ toolCall: pending.toolCall,
+ ...(pending.origin !== undefined ? { origin: pending.origin } : {}),
+ }),
+ });
}
/** Publishes one live background-subagent message and records its usage (fire-and-forget; the child's own Trace is the durable record). */
@@ -764,17 +861,7 @@ export class SessionManager {
entry.pendingInputs = [...entry.pendingInputs, ...args.input];
entry.pendingBootstrap = [];
this.publishState(entry, "running");
- const approve = makeApprove({
- getMode: () => this.deps.sessions.findById(entry.sessionId)?.approvalMode ?? "always-ask",
- toolPermission: (name) => entry.session.toolPermission(name),
- registry: entry.approvals,
- publishRequest: (pending) =>
- this.publishEvent(entry, {
- type: "approval_request",
- toolCall: pending.toolCall,
- ...(pending.origin !== undefined ? { origin: pending.origin } : {}),
- }),
- });
+ const approve = this.entryApprove(entry);
const goalId = this.deps.goals?.create({
sessionId: entry.sessionId,
projectId: entry.projectId,
@@ -938,18 +1025,7 @@ export class SessionManager {
for (const msg of input) channel.publish(msg);
this.publishState(entry, "running");
- const approve = makeApprove({
- // Re-reads approval_mode from the DB on every decision (a PATCH takes effect immediately).
- getMode: () => this.deps.sessions.findById(entry.sessionId)?.approvalMode ?? "always-ask",
- toolPermission: (name) => entry.session.toolPermission(name),
- registry: entry.approvals,
- publishRequest: (pending) =>
- this.publishEvent(entry, {
- type: "approval_request",
- toolCall: pending.toolCall,
- ...(pending.origin !== undefined ? { origin: pending.origin } : {}),
- }),
- });
+ const approve = this.entryApprove(entry);
const gen = entry.session.run(input, {
approve,
signal: ac.signal,
@@ -1142,7 +1218,9 @@ export class SessionManager {
abortTask(sessionId: string): boolean {
const entry = this.entries.get(sessionId);
if (!entry || !entry.abort) return false;
- entry.approvals.denyAll();
+ // Deny only the MAIN session's pending approvals: an approval blocks the run the user is
+ // stopping. A subagent child survives the parent's stop, and so does its question.
+ entry.approvals.denyMain();
entry.abort.abort();
return true;
}
@@ -1683,7 +1761,9 @@ export class SessionManager {
// to the Trace, so its held input (and the aborted connect pair) are the only copy
// a reload can show until the next run carries the input forward and persists it.
// Runs that issued a request already cleared them at their first request_begin.
- entry.approvals.denyAll();
+ // Main approvals only: an origin-tagged approval belongs to a subagent child that
+ // outlives this task — it stays pending for the user (see ApprovalRegistry.denyMain).
+ entry.approvals.denyMain();
entry.status = "idle";
entry.abort = null;
entry.running = null;
@@ -1795,8 +1875,10 @@ export class SessionManager {
}
private publishState(entry: RuntimeEntry, state: SessionStatus): void {
- // Every state flip also reports the queued follow-up count and the undelivered steering
- // mirror, so subscribers can render both hints without a dedicated event type.
+ // Every state flip also reports the queued follow-up count, the undelivered steering
+ // mirror, and the live subagent children, so subscribers can render all three hints
+ // without a dedicated event type.
+ const subagents = entry.session.listBackgroundSubagents?.() ?? [];
this.publishEvent(entry, {
type: "task_state",
state,
@@ -1807,6 +1889,7 @@ export class SessionManager {
...(entry.followUps.length > 0
? { pendingFollowUps: entry.followUps.map(followUpInfo) }
: {}),
+ ...(subagents.length > 0 ? { subagents } : {}),
});
// The same flip again, this time on the user channel and carrying the Session id: a tab
// subscribes to the ONE conversation it has open, so the event above can never move any
diff --git a/packages/server/test/session-subagents.test.ts b/packages/server/test/session-subagents.test.ts
new file mode 100644
index 00000000..b97fbad5
--- /dev/null
+++ b/packages/server/test/session-subagents.test.ts
@@ -0,0 +1,269 @@
+/**
+ * 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
+ * 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,
+ * 204 when the child is idle/unknown (nothing left to stop);
+ * - `task_state` republished with the live `subagents` listing on every child state ping,
+ * and the SSE subscribe snapshot carrying the same listing;
+ * - 404 for foreign/unknown sessions (the shared resolveSession semantics).
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { toolCall, withOrigin } from "@prismshadow/penguin-core";
+import type { BackgroundSubagentInfo, OmniMessage } from "@prismshadow/penguin-core";
+import { ApprovalRegistry } from "../src/runtime/approvals.js";
+import type {
+ ApproveFn,
+ SubagentMessageOptions,
+ SubagentMessageOutcome,
+} from "@prismshadow/penguin-core";
+import type { ServerEvent, SubagentMessageResponse } from "../src/api/types.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SID = "session-2026-08-24-10-00-00-ccdd0041";
+const CHILD_RUNNING = "session-2026-08-24-10-01-00-child001";
+const CHILD_IDLE = "session-2026-08-24-10-01-00-child002";
+const CHILD_RELEASED = "session-2026-08-24-10-01-00-child003";
+
+interface SentMessage {
+ childSessionId: string;
+ text: string;
+ opts?: SubagentMessageOptions;
+}
+
+/** Fake Session over a mutable child list; message/abort mutate it like core's manager would. */
+function subagentsFakeSession(
+ sessionId: string,
+ children: BackgroundSubagentInfo[],
+ sent: SentMessage[],
+ aborts: string[],
+ stateListeners: (() => void)[],
+): RuntimeSession {
+ return {
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run(_input: OmniMessage[], _opts: { approve: ApproveFn; signal: AbortSignal }) {},
+ async *compact() {},
+ listBackgroundSubagents: () => children.map((c) => ({ ...c })),
+ sendToBackgroundSubagent: async (
+ childSessionId: string,
+ text: string,
+ opts?: SubagentMessageOptions,
+ ): Promise<SubagentMessageOutcome> => {
+ sent.push({ childSessionId, text, ...(opts !== undefined ? { opts } : {}) });
+ const child = children.find((c) => c.sessionId === childSessionId);
+ if (!child) {
+ // The released child revives only when the host resolved an owning agent for it —
+ // exactly core's resume-fallback condition.
+ if (opts?.resume) {
+ children.push({ sessionId: childSessionId, subagentId: null, running: true });
+ return "resumed";
+ }
+ return "gone";
+ }
+ if (child.running) return "steered";
+ child.running = true;
+ return "started";
+ },
+ abortBackgroundSubagentRun: (childSessionId: string): boolean => {
+ const child = children.find((c) => c.sessionId === childSessionId);
+ if (!child || !child.running) return false;
+ aborts.push(childSessionId);
+ child.running = false;
+ return true;
+ },
+ onSubagentState: (listener: () => void) => {
+ stateListeners.push(listener);
+ },
+ setSubagentApprovalFallback: () => {},
+ };
+}
+
+describe("session subagent routes and liveness", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let children: BackgroundSubagentInfo[];
+ let sent: SentMessage[];
+ let aborts: string[];
+ let stateListeners: (() => void)[];
+
+ const sessionRow = (sessionId: string): SessionRow => ({
+ sessionId,
+ projectId: "subuser-default_project",
+ agentId: "default_agent",
+ modelId: "m1",
+ provider: "custom",
+ workspace: "/tmp/w",
+ approvalMode: "always-ask",
+ title: null,
+ createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
+ });
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "subuser");
+ const other = await provisionUser(t.app, "outsider_s");
+ api = apiClient(t.app, cookie);
+ outsider = apiClient(t.app, other.cookie);
+ children = [
+ { sessionId: CHILD_RUNNING, subagentId: "subagent-child001", running: true },
+ { sessionId: CHILD_IDLE, subagentId: null, running: false },
+ ];
+ sent = [];
+ aborts = [];
+ stateListeners = [];
+ t.deps.sessionsRepo.insert(sessionRow(SID));
+ t.deps.manager.adopt(
+ sessionRow(SID),
+ subagentsFakeSession(SID, children, sent, aborts, stateListeners),
+ );
+ // A released child with its own session row: the message route resolves its owning agent
+ // from this row and asks core to revive it.
+ t.deps.sessionsRepo.insert(sessionRow(CHILD_RELEASED));
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("message: steering while the child runs, a follow-up run while it is idle", async () => {
+ const mid = await api.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/message`, {
+ text: "focus on the tests",
+ });
+ expect(mid.status).toBe(200);
+ expect((await mid.json()) as SubagentMessageResponse).toEqual({ outcome: "steered" });
+
+ 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" });
+
+ 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");
+ });
+
+ it("message: a released child with a session row revives (outcome resumed, owning agent resolved)", async () => {
+ const res = await api.post(`/api/sessions/${SID}/subagents/${CHILD_RELEASED}/message`, {
+ text: "wake up",
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as SubagentMessageResponse).toEqual({ outcome: "resumed" });
+ // The route resolved the child's owning agent from its own session row.
+ expect(sent[0]!.opts?.resume).toEqual({ agentId: "default_agent" });
+ });
+
+ it("message: 404 subagent_gone when no session row backs the child; 400 without text", async () => {
+ const ghost = await api.post(`/api/sessions/${SID}/subagents/session-ghost/message`, {
+ text: "hello",
+ });
+ expect(ghost.status).toBe(404);
+ expect(((await ghost.json()) as { error: { code: string } }).error.code).toBe("subagent_gone");
+ // No row for the ghost child, so no resume option reached core.
+ expect(sent[0]!.opts?.resume).toBeUndefined();
+
+ const empty = await api.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/message`, {
+ text: " ",
+ });
+ expect(empty.status).toBe(400);
+ expect(sent).toHaveLength(1);
+ });
+
+ it("abort: 202 ends the running child's round; 204 when idle or unknown", async () => {
+ const res = await api.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/abort`, {});
+ expect(res.status).toBe(202);
+ expect(aborts).toEqual([CHILD_RUNNING]);
+
+ const again = await api.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/abort`, {});
+ expect(again.status).toBe(204);
+ const ghost = await api.post(`/api/sessions/${SID}/subagents/session-ghost/abort`, {});
+ expect(ghost.status).toBe(204);
+ expect(aborts).toEqual([CHILD_RUNNING]);
+ });
+
+ it("republishes task_state with the live subagents listing on every child state ping", async () => {
+ const events: ServerEvent[] = [];
+ t.deps.channels.get(SID).subscribe((evt) => {
+ if (evt.event === "server_event") events.push(JSON.parse(evt.data) as ServerEvent);
+ });
+ expect(stateListeners).toHaveLength(1);
+
+ children[0]!.running = false;
+ stateListeners[0]!();
+ const state = events.find((e) => e.type === "task_state");
+ expect(state).toBeDefined();
+ expect(state && state.type === "task_state" ? state.subagents : undefined).toEqual([
+ { sessionId: CHILD_RUNNING, subagentId: "subagent-child001", running: false },
+ { sessionId: CHILD_IDLE, subagentId: null, running: false },
+ ]);
+ });
+
+ it("the SSE subscribe snapshot carries the live subagents listing", async () => {
+ const res = await api.get(`/api/sessions/${SID}/stream`);
+ expect(res.status).toBe(200);
+ const reader = res.body!.getReader();
+ const { value } = await reader.read();
+ await reader.cancel();
+ const frame = new TextDecoder().decode(value);
+ expect(frame).toContain('"type":"task_state"');
+ expect(frame).toContain(`"subagents":[{"sessionId":"${CHILD_RUNNING}"`);
+ });
+
+ it("denyMain resolves only origin-less approvals; a child's stays pending for the user", async () => {
+ const registry = new ApprovalRegistry();
+ const main = registry.wait(
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "m1" }),
+ );
+ const child = registry.wait(
+ withOrigin(
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "c1" }),
+ "session-child",
+ ),
+ );
+ // The task-boundary convergence (run end / user stop): the main approval dies with its
+ // run, the subagent child's question survives — its session is still blocked on it.
+ registry.denyMain();
+ expect(await main).toBe("deny");
+ expect(registry.size).toBe(1);
+ expect(registry.decide("c1", "allow")).toBe(true);
+ expect(await child).toBe("allow");
+ });
+
+ it("foreign and unknown sessions → 404 (same auth semantics as the other session routes)", async () => {
+ expect(
+ (
+ await outsider.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/message`, {
+ text: "x",
+ })
+ ).status,
+ ).toBe(404);
+ expect(
+ (await outsider.post(`/api/sessions/${SID}/subagents/${CHILD_RUNNING}/abort`, {})).status,
+ ).toBe(404);
+ expect(
+ (
+ await api.post(`/api/sessions/session-ghost/subagents/${CHILD_RUNNING}/message`, {
+ text: "x",
+ })
+ ).status,
+ ).toBe(404);
+ expect(sent).toEqual([]);
+ expect(aborts).toEqual([]);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index c0ea1660..188975fb 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -88,6 +88,7 @@ import type {
RecalledMessageResponse,
RetryNowResponse,
SteerRequest,
+ SubagentMessageResponse,
TaskCreateRequest,
TaskCreateResponse,
TraceAnalysisResponse,
@@ -574,6 +575,25 @@ 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,
+) =>
+ apiFetch<SubagentMessageResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/subagents/${encodeURIComponent(childSessionId)}/message`,
+ { method: "POST", body: { text, ...(thinkingLevel ? { thinkingLevel } : {}) } },
+ );
+
+/** 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). */
+export const abortSubagent = (sessionId: string, childSessionId: string) =>
+ apiFetch<void>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/subagents/${encodeURIComponent(childSessionId)}/abort`,
+ { method: "POST", body: {} },
+ );
+
/** Recall an undelivered steering message back to the composer (#287): returns its original content; 409 not_pending once it was delivered to the model. */
export const recallSteer = (sessionId: string, steerId: string) =>
apiFetch<RecalledMessageResponse>(
diff --git a/packages/web/src/features/chat/agent-topology.ts b/packages/web/src/features/chat/agent-topology.ts
index ee191993..64ec06e1 100644
--- a/packages/web/src/features/chat/agent-topology.ts
+++ b/packages/web/src/features/chat/agent-topology.ts
@@ -3,9 +3,10 @@
* test/agent-topology.test.ts; rendering lives in agent-topology-view.tsx — same split as the
* usage charts' chart-geom.ts / chart-svg.tsx).
*
- * Extraction walks a single Task's slice of the main model — by default the LATEST Task (from
- * the last user_text / user_image item — the same "starts a new Task" predicate the reducer
- * uses; user_steering never starts one), or, for a chip clicked on an older turn, the
+ * Extraction walks a single Task's slice of the main model — by default the most recent
+ * Task that REFERENCES A SUBAGENT (task boundaries from the "starts a new Task" predicate
+ * the reducer uses — user_text / user_image; user_steering never starts one — so a plain
+ * user message never wipes the panel), or, for a chip clicked on an older turn, the
* HISTORICAL Task slice containing that chip's child (extractTopologyForChild). It collects
* spawned children from bound run_subagent tool cards and standalone SubagentItems, then
* recurses into each child model's own items for deeper spawns. Nodes are deduped by session id
@@ -31,6 +32,8 @@ export interface TopologyNode {
agentId: string | null;
/** The spawning call's model-written `description` — what this child was asked to do; null for the root, a standalone item, or when the model omitted it. */
description: string | null;
+ /** The spawning call's explicit `thinking_level` argument; null = inherited from the parent session (and for the root/standalone items). The panel composer's display fallback. */
+ spawnThinkingLevel: string | null;
/** Still running — the spawning card's output hasn't completed (root: the Task's own running state; a standalone item has no card, so it reads as done). */
running: boolean;
/** 0 = the main session; +1 per spawn hop. */
@@ -143,15 +146,62 @@ export function descriptionFromRunSubagentArgs(argsJson: string): string | null
return runSubagentArg(argsJson, "description");
}
-/** Extract the latest Task's spawn tree: root first, then children in DFS preorder (document order). */
+/** Whether one Task slice `[start, end)` references any spawned child (a bound run_subagent card or a standalone SubagentItem). */
+function sliceHasSubagent(items: readonly ChatItem[], start: number, end: number): boolean {
+ for (let i = start; i < end; i++) {
+ const item = items[i]!;
+ if ((item.kind === "tool_call" && item.subagent !== undefined) || item.kind === "subagent") {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Extract the panel's default spawn tree: the most recent Task that actually references a
+ * subagent — a plain user message must not wipe the graph, so when the latest Task has no
+ * spawns the walk pins the newest one that does (the latest Task takes over the moment it
+ * spawns its own child; with no subagent-bearing Task at all, the latest Task's empty graph
+ * stands). Root first, then children in DFS preorder (document order). `liveStates` is the
+ * server's structural child liveness (task_state.subagents, session id → running): when it
+ * knows a child, it overrides the text heuristics below — dead/unloaded runtimes and old
+ * servers simply leave the map empty and the heuristics stand.
+ */
export function extractTopology(
model: StreamModel,
rootSessionId: string,
taskRunning: boolean,
+ liveStates?: ReadonlyMap<string, boolean>,
): TopologyNode[] {
- return extractFromSlice(model.items.slice(latestTaskStart(model.items)), rootSessionId, {
- running: taskRunning,
- });
+ const items = model.items;
+ let start = latestTaskStart(items);
+ let end = items.length;
+ if (!sliceHasSubagent(items, start, end)) {
+ for (let cursor = start; cursor > 0;) {
+ let prevStart = 0;
+ for (let i = cursor - 1; i >= 0; i--) {
+ if (isScopeStart(items[i]!)) {
+ prevStart = i;
+ break;
+ }
+ }
+ if (sliceHasSubagent(items, prevStart, cursor)) {
+ start = prevStart;
+ end = cursor;
+ break;
+ }
+ if (prevStart === 0) break;
+ cursor = prevStart;
+ }
+ }
+ return extractFromSlice(
+ items.slice(start, end),
+ rootSessionId,
+ // A pinned older Task has ended by definition (the next user message closed it): its
+ // root never reads as running.
+ { running: end === items.length && taskRunning },
+ liveStates,
+ );
}
/**
@@ -168,6 +218,7 @@ export function extractTopologyForChild(
rootSessionId: string,
taskRunning: boolean,
childSessionId: string,
+ liveStates?: ReadonlyMap<string, boolean>,
): TopologyNode[] | null {
const items = model.items;
const at = items.findIndex(
@@ -193,9 +244,12 @@ export function extractTopologyForChild(
break;
}
}
- return extractFromSlice(items.slice(start, end), rootSessionId, {
- running: end === items.length && taskRunning,
- });
+ return extractFromSlice(
+ items.slice(start, end),
+ rootSessionId,
+ { running: end === items.length && taskRunning },
+ liveStates,
+ );
}
/** Launch note of a run_in_background subagent: binds the card to its registry handle. */
@@ -205,7 +259,8 @@ const BG_SUBAGENT_LAUNCH_RE =
/**
* Terminal knowledge about background subagents in one scope slice, from the notes the
* harness itself writes: the `[background_task_done]` notice (kind subagent), an
- * input_subagent poll reporting the session idle, and kill_subagent's removal notes all mean
+ * input_subagent poll reporting the session idle, and legacy kill_subagent removal notes
+ * (historical traces) all mean
* "no longer running"; a later `still running` poll (or a follow-up round) flips it back.
* Ids are the registry handles (`subagent-<hex8>`); last mention wins, in item order.
*/
@@ -239,6 +294,7 @@ function extractFromSlice(
slice: readonly ChatItem[],
rootSessionId: string,
root: { running: boolean },
+ liveStates?: ReadonlyMap<string, boolean>,
): TopologyNode[] {
const nodes: TopologyNode[] = [
{
@@ -246,6 +302,7 @@ function extractFromSlice(
agentId: null,
// The root was not spawned by anyone, so there is no spawning call to describe.
description: null,
+ spawnThinkingLevel: null,
running: root.running,
depth: 0,
origin: [],
@@ -262,6 +319,7 @@ function extractFromSlice(
parentOrigin: string[],
argsAgentId: string | null,
argsDescription: string | null,
+ argsThinkingLevel: string | null,
): void => {
if (seen.has(sessionId)) return;
seen.add(sessionId);
@@ -279,7 +337,11 @@ function extractFromSlice(
sessionId,
agentId: child.meta?.agentId ?? argsAgentId,
description: argsDescription,
- running,
+ spawnThinkingLevel: argsThinkingLevel,
+ // Server liveness wins over the text heuristics whenever it knows this child: an
+ // input_subagent revival or a panel-started round flips it running again the moment
+ // the child's state pings (issue #274's frozen checkmark and stopped timer).
+ running: liveStates?.get(sessionId) ?? running,
depth: origin.length,
origin,
parentId,
@@ -305,10 +367,11 @@ function extractFromSlice(
parentOrigin,
agentIdFromRunSubagentArgs(item.argumentsText),
descriptionFromRunSubagentArgs(item.argumentsText),
+ runSubagentArg(item.argumentsText, "thinking_level"),
);
} else if (item.kind === "subagent") {
- // A standalone child has no spawning card in this stream, so neither argument is available.
- addChild(item.sessionId, item.model, false, parentId, parentOrigin, null, null);
+ // A standalone child has no spawning card in this stream, so no argument is available.
+ addChild(item.sessionId, item.model, false, parentId, parentOrigin, null, null, null);
}
}
};
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index 0d745843..dd5b2196 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -871,6 +871,7 @@ export function ChatInput({
onRetryModelAuth,
onNewSession,
controlRef,
+ variant = "session",
}: {
status: SessionStatus;
/**
@@ -937,7 +938,8 @@ export function ChatInput({
*/
onHandoff?: (target: AgentSummary, input: TaskInputPart[]) => Promise<boolean>;
onStop: () => Promise<void>;
- onCompact: () => Promise<void>;
+ /** Manual context compaction (/compact). Optional: without it the command is not offered (the subagent variant has no compaction surface). */
+ onCompact?: () => Promise<void>;
/** Currently selected model reference ((provider, modelId) is the unique key); null = not yet chosen. */
modelRef: ModelRefDto | null;
/**
@@ -1055,6 +1057,16 @@ export function ChatInput({
modelAuthDead?: boolean;
/** Navigates to the Models page (where the credential is actually fixed); renders the notice's primary button when supplied. */
onOpenModels?: () => void;
+ /**
+ * Which surface this composer serves. `"session"` (default) is the main conversation with
+ * every affordance. `"subagent"` drives one subagent child from the panel: the same body,
+ * skills, slash skill commands, thinking level, approval mode, context ring and model badge
+ * — minus what a child has no semantics for (goal mode, image/file attachments and the "+"
+ * menu carrying them, paste/drop file intake; /compact and the follow-up queue are already
+ * gated by their absent callbacks). The model badge is inert here: a child cannot switch
+ * model or agent, so there is no locked-model hint to click for.
+ */
+ variant?: "session" | "subagent";
/**
* Clears the auth-dead state and re-enables the composer for another attempt (the state
* re-arms on the next auth failure). The escape hatch for credential changes the
@@ -1294,6 +1306,12 @@ export function ChatInput({
const canMidRunSend = steerAction || queueAction;
const midRunSendLabel = midRun === "queue" ? S.chat.followUpSend : S.chat.steerSend;
const stopAction = isStopAction(status, midRun);
+ // Locked-model badge text (session and subagent variants): the catalog's display name when
+ // the model is known, the raw id otherwise.
+ const lockedModelLabel = (() => {
+ const m = models?.find((x) => sameModelRef(x, modelRef));
+ return m ? modelLabel(m) : (modelRef?.modelId ?? "…");
+ })();
// Queued hint: shown after a successful steer until the message shows up in the stream
// (steeringDeliveredCount increases past the baseline captured at queue time) or the run
// stops being observable (task no longer running).
@@ -1437,22 +1455,31 @@ export function ChatInput({
onTextChange?.(next);
};
return [
- {
- cmd: "/compact",
- desc: S.chat.compact,
- run: () => {
- clearInput();
- void onCompact();
- },
- },
- {
- cmd: "/goal",
- desc: S.chat.goalModeDesc,
- run: () => {
- clearInput();
- toggleGoal(!goalOn);
- },
- },
+ ...(onCompact
+ ? [
+ {
+ cmd: "/compact",
+ desc: S.chat.compact,
+ run: () => {
+ clearInput();
+ void onCompact();
+ },
+ },
+ ]
+ : []),
+ // Goal mode is a main-session concept: the subagent variant offers no way in.
+ ...(variant === "session"
+ ? [
+ {
+ cmd: "/goal",
+ desc: S.chat.goalModeDesc,
+ run: () => {
+ clearInput();
+ toggleGoal(!goalOn);
+ },
+ },
+ ]
+ : []),
// Model switch (active idle session only — the parent passes onSwitchModel just there;
// draft state has its own model picker). Gated on the model list being loaded: without
// it the picker would open empty. Running the command consumes the /model token (like
@@ -1987,6 +2014,9 @@ export function ChatInput({
};
const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
+ // The subagent variant takes text only: a pasted file/image falls through to the
+ // browser's default handling (which drops the binary and keeps any text).
+ if (variant !== "session") return;
const files: File[] = [];
for (const item of e.clipboardData.items) {
if (item.kind === "file") {
@@ -2048,6 +2078,7 @@ export function ChatInput({
* so the refusal is said out loud instead of silently swallowing the files.
*/
const addDroppedFiles = (dropped: File[]) => {
+ if (variant !== "session") return; // Text-only surface: drops have nowhere to go.
const batch = splitDroppedFiles(dropped);
if (batch.images.length > 0) addFiles(batch.images);
if (batch.files.length > 0) {
@@ -2070,7 +2101,7 @@ export function ChatInput({
kept while a Task runs), so dropping works exactly when there is a composer to attach
to — but bounded to the enclosing ChatDropRegion, so only the chat area reacts.
Dropped files go through addDroppedFiles into the same intake as the "+" menu. */}
- <FileDropZone onFiles={addDroppedFiles} />
+ {variant === "session" && <FileDropZone onFiles={addDroppedFiles} />}
{/* Slash command menu (triggered by typing /; /compact plus one entry per installed skill).
Height is capped to the room measured above the composer (see upwardMaxH) with internal
scrolling, so a long skill list never pushes the menu's top edge out of view; the active
@@ -2587,47 +2618,49 @@ export function ChatInput({
never disables). The uploads live in here rather than as their own toolbar
buttons: one 8x8 slot instead of three, which is the difference between the
phone row scrolling and not. */}
- <PlusMenu
- items={[
- {
- key: "image",
- icon: IMAGE_ICON,
- label: S.chat.uploadImage,
- // Without vision the images still send — as scratchpad file paths — so the
- // entry stays usable and the hint says what will happen instead. Goal mode
- // sends them that way on any model, since the objective is re-injected as
- // text every round.
- desc: vision && !goalOn ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,
- active: images.length > 0,
- onSelect: () => imageInputRef.current?.click(),
- },
- {
- key: "file",
- icon: PAPERCLIP_ICON,
- label: S.chat.uploadFile,
- // The description doubles as the explanation of where the file ends up:
- // it is filed into the session scratchpad and reached by path, never
- // inlined into the conversation.
- desc: S.chat.uploadFileDesc,
- active: attachments.length > 0,
- // Unlike images, a file cannot ride a goal: nothing folds it into the
- // objective that every round re-injects, so the server refuses it.
- disabled: goalOn,
- onSelect: () => attachmentInputRef.current?.click(),
- },
- {
- key: "goal",
- icon: GOAL_ICON,
- label: S.chat.goalMode,
- desc: S.chat.goalModeDesc,
- active: goalOn,
- disabled: running || compacting || busy,
- onSelect: () => toggleGoal(!goalOn),
- },
- ]}
- footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}
- direction={models && onChangeModel ? "down" : "up"}
- />
+ {variant === "session" && (
+ <PlusMenu
+ items={[
+ {
+ key: "image",
+ icon: IMAGE_ICON,
+ label: S.chat.uploadImage,
+ // Without vision the images still send — as scratchpad file paths — so the
+ // entry stays usable and the hint says what will happen instead. Goal mode
+ // sends them that way on any model, since the objective is re-injected as
+ // text every round.
+ desc: vision && !goalOn ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,
+ active: images.length > 0,
+ onSelect: () => imageInputRef.current?.click(),
+ },
+ {
+ key: "file",
+ icon: PAPERCLIP_ICON,
+ label: S.chat.uploadFile,
+ // The description doubles as the explanation of where the file ends up:
+ // it is filed into the session scratchpad and reached by path, never
+ // inlined into the conversation.
+ desc: S.chat.uploadFileDesc,
+ active: attachments.length > 0,
+ // Unlike images, a file cannot ride a goal: nothing folds it into the
+ // objective that every round re-injects, so the server refuses it.
+ disabled: goalOn,
+ onSelect: () => attachmentInputRef.current?.click(),
+ },
+ {
+ key: "goal",
+ icon: GOAL_ICON,
+ label: S.chat.goalMode,
+ desc: S.chat.goalModeDesc,
+ active: goalOn,
+ disabled: running || compacting || busy,
+ onSelect: () => toggleGoal(!goalOn),
+ },
+ ]}
+ footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}
+ direction={models && onChangeModel ? "down" : "up"}
+ />
+ )}
<ApprovalModeSelect
value={approvalMode}
onChange={onChangeApprovalMode}
@@ -2691,6 +2724,19 @@ export function ChatInput({
onChange={onChangeModel}
disabled={busy}
/>
+ ) : variant === "subagent" ? (
+ /* Subagent composer: the child runs whatever model it was spawned with, and no
+ /model command exists here — so the badge is pure display, nothing to click. */
+ <span
+ title={modelRef?.modelId ?? ""}
+ className="flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 rounded-md px-1 text-gray-400 dark:text-gray-500"
+ >
+ <ProviderLogo
+ provider={modelRef?.provider ?? "custom"}
+ className="h-4 w-4 shrink-0"
+ />
+ <span className="hidden min-w-0 truncate @md:block">{lockedModelLabel}</span>
+ </span>
) : (
/* Read-only display in session state: both the logo and the name come from the
Session DTO's paired fields (no prefix parsing). A button rather than a plain
@@ -2710,12 +2756,7 @@ export function ChatInput({
provider={modelRef?.provider ?? "custom"}
className="h-4 w-4 shrink-0"
/>
- <span className="hidden min-w-0 truncate @md:block">
- {(() => {
- const m = models?.find((x) => sameModelRef(x, modelRef));
- return m ? modelLabel(m) : (modelRef?.modelId ?? "…");
- })()}
- </span>
+ <span className="hidden min-w-0 truncate @md:block">{lockedModelLabel}</span>
</button>
)}
{/* One action button, never two: while running an empty composer means "Stop"
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 25d72e44..c1427d91 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -1475,6 +1475,12 @@ export function ChatPage() {
ctx={ctx}
focusRequest={subagentFocus}
taskScope={subagentTaskScope}
+ subagents={stream.subagents}
+ models={models?.models ?? []}
+ approvalMode={selected.approvalMode}
+ onChangeApprovalMode={onChangeApprovalMode}
+ modeSaving={modeSaving}
+ parentThinkingLevel={sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel)}
/>
);
case "workspace":
diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsx
index ddae9709..589743eb 100644
--- a/packages/web/src/features/chat/subagents-view.tsx
+++ b/packages/web/src/features/chat/subagents-view.tsx
@@ -6,11 +6,12 @@
* streaming, nested tool cards, chips for deeper spawns, and pending approvals all keep
* working inside the panel.
*
- * Which Task: the LATEST by default (toolbar open / session switch — a new Task then resets
- * the graph to its own agents as it streams); a chip click pins `taskScope` to that chip's
- * Task instead (the chat page's subagentTaskScope), so a chip on an older turn shows that turn's
- * HISTORICAL graph via extractTopologyForChild — falling back to the latest Task when the
- * anchor is no longer referenced (e.g. a resync swapped the model).
+ * Which Task: the most recent SUBAGENT-BEARING one by default — a plain user message never
+ * wipes the graph; a new Task takes over the moment it spawns its own child (see
+ * extractTopology). A chip click pins `taskScope` to that chip's Task instead (the chat
+ * page's subagentTaskScope), so a chip on an older turn shows that turn's HISTORICAL graph
+ * via extractTopologyForChild — falling back to the default scope when the anchor is no
+ * longer referenced (e.g. a resync swapped the model).
*
* Selection: an explicit chip click (focusRequest) or a node click wins; with no explicit
* choice the first child of the displayed Task is auto-focused (so opening the panel while a
@@ -21,9 +22,20 @@
*/
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router";
-import type { SessionInfo } from "@prismshadow/penguin-server/api";
+import type {
+ ApprovalMode,
+ ModelInfo,
+ SessionInfo,
+ SkillMetadataItem,
+ SubagentRuntimeInfo,
+ TaskInputPart,
+} from "@prismshadow/penguin-server/api";
+import { ApiError } from "../../api/client";
+import { abortSubagent, getAgentSkills, messageSubagent } from "../../api/endpoints";
+import { toastError } from "../../components/ui/toast";
import { S } from "../../lib/strings";
-import type { StreamModel } from "../../lib/omni/stream-model";
+import type { NestedSessionMeta, StreamModel } from "../../lib/omni/stream-model";
+import { ChatInput } from "./chat-input";
import { AgentAvatar } from "../../components/ui/agent-avatar";
import { EmptyState } from "../../components/ui/empty-state";
import { GlyphIcon } from "../../components/ui/glyph-icon";
@@ -58,6 +70,12 @@ export function SubagentsView({
ctx,
focusRequest,
taskScope,
+ subagents,
+ models,
+ approvalMode,
+ onChangeApprovalMode,
+ modeSaving,
+ parentThinkingLevel,
}: {
session: SessionInfo;
model: StreamModel;
@@ -69,6 +87,16 @@ export function SubagentsView({
focusRequest: Selection | null;
/** Displayed Task scope (the chat page's subagentTaskScope): null = latest; an anchor pins the historical Task containing that child. */
taskScope: { anchorSessionId: string } | null;
+ /** Live subagent children from the server's task_state (structural liveness): overrides the topology's text heuristics; empty for dead runtimes. */
+ subagents: SubagentRuntimeInfo[];
+ /** Project model list (the child composer's locked-model badge and context-window lookup). */
+ models: ModelInfo[];
+ /** The PARENT session's approval mode — child approvals are judged by it (the same value the main composer edits). */
+ approvalMode: ApprovalMode;
+ onChangeApprovalMode: (mode: ApprovalMode) => void;
+ modeSaving: boolean;
+ /** The parent session's effective thinking level ("" = unknown): the child composer's display fallback — a child inherits it at spawn unless the spawning call pinned its own. */
+ parentThinkingLevel: string;
}) {
const { agents, setCurrentAgentId } = useProject();
const { sessions } = useSessions();
@@ -82,16 +110,29 @@ export function SubagentsView({
}
}, [focusRequest]);
+ // Structural child liveness from the server (session id → running): the topology consults
+ // it before its text heuristics, so revived and panel-started rounds read correctly.
+ const liveStates = useMemo(
+ () => new Map(subagents.map((s) => [s.sessionId, s.running])),
+ [subagents],
+ );
+
const nodes = useMemo(
() =>
// A pinned scope (chip click) shows THAT Task's graph — historical or latest alike; when
// its anchor is no longer referenced in the stream, fall back to the latest Task.
(taskScope
- ? extractTopologyForChild(model, session.sessionId, taskRunning, taskScope.anchorSessionId)
- : null) ?? extractTopology(model, session.sessionId, taskRunning),
+ ? extractTopologyForChild(
+ model,
+ session.sessionId,
+ taskRunning,
+ taskScope.anchorSessionId,
+ liveStates,
+ )
+ : null) ?? extractTopology(model, session.sessionId, taskRunning, liveStates),
// version is the model's change signal (items mutate in place).
// eslint-disable-next-line react-hooks/exhaustive-deps
- [model, version, session.sessionId, taskRunning, taskScope],
+ [model, version, session.sessionId, taskRunning, taskScope, liveStates],
);
// No explicit selection yet: auto-focus the displayed Task's first child (null when none spawned).
@@ -231,8 +272,169 @@ export function SubagentsView({
/>
)}
</div>
+ {/* Keyed by child too: switching nodes must not carry a half-typed message over. */}
+ <SubagentComposer
+ key={`composer-${active.sessionId}`}
+ sessionId={session.sessionId}
+ childSessionId={active.sessionId}
+ running={activeRunning}
+ meta={activeModel.meta}
+ contextNow={activeModel.stats.contextNow}
+ deliveredInputs={countDeliveredInputs(activeModel)}
+ models={models}
+ approvalMode={approvalMode}
+ onChangeApprovalMode={onChangeApprovalMode}
+ modeSaving={modeSaving}
+ fallbackThinkingLevel={activeNode?.spawnThinkingLevel ?? parentThinkingLevel}
+ />
</>
)}
</div>
);
}
+
+/**
+ * User-side inputs already visible in the child's stream (follow-up prompts and delivered
+ * steering interjections alike): the composer's "queued" hint retires when this grows past
+ * its value at queue time — whichever way the message reached the child.
+ */
+function countDeliveredInputs(model: StreamModel): number {
+ let n = 0;
+ for (const item of model.items) {
+ if (item.kind === "user_text" || item.kind === "user_steering") n += 1;
+ }
+ return n;
+}
+
+/**
+ * The selected child's composer (#272): the SAME ChatInput as the main conversation, in its
+ * subagent variant — body, skills and slash skill commands, per-turn thinking level, context
+ * ring (the child's own usage), locked-model badge, and the approval-mode selector (the
+ * PARENT session's mode — child approvals are judged by it). Send semantics are a user input
+ * on the child, whatever its state: steering while it runs, a follow-up round while idle, a
+ * revival (resume-session) when it was released; the stop face on the action button aborts
+ * only the child's current run. All of it lands on the same core channel input_subagent uses.
+ */
+function SubagentComposer({
+ sessionId,
+ childSessionId,
+ running,
+ meta,
+ contextNow,
+ deliveredInputs,
+ models,
+ approvalMode,
+ onChangeApprovalMode,
+ modeSaving,
+ fallbackThinkingLevel,
+}: {
+ sessionId: string;
+ childSessionId: string;
+ running: boolean;
+ meta: NestedSessionMeta | null;
+ contextNow: number;
+ deliveredInputs: number;
+ models: ModelInfo[];
+ approvalMode: ApprovalMode;
+ onChangeApprovalMode: (mode: ApprovalMode) => void;
+ modeSaving: boolean;
+ /** Display fallback for the thinking picker while the user hasn't picked: the spawn call's explicit level, else the parent session's effective level (what the child inherited). */
+ fallbackThinkingLevel: string;
+}) {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+ // Skills of the CHILD's agent (it may differ from the parent's): candidates for the
+ // toolbar dropdown and the slash menu; a failed fetch reads as no skills.
+ const [skills, setSkills] = useState<SkillMetadataItem[]>([]);
+ useEffect(() => {
+ let stale = false;
+ setSkills([]);
+ const agentId = meta?.agentId;
+ if (!projectId || !agentId) return;
+ getAgentSkills(projectId, agentId)
+ .then((res) => {
+ if (!stale) setSkills(res.skills);
+ })
+ .catch(() => undefined);
+ return () => {
+ stale = true;
+ };
+ }, [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.
+ const [turnLevel, setTurnLevel] = useState("");
+
+ const modelRef = meta ? { provider: meta.provider, modelId: meta.modelId } : null;
+ const contextWindow = modelRef
+ ? models.find((m) => m.provider === modelRef.provider && m.modelId === modelRef.modelId)
+ ?.contextWindow
+ : undefined;
+
+ const send = (text: string) =>
+ messageSubagent(sessionId, childSessionId, text, turnLevel || undefined);
+ const sendFailure = (err: unknown): void => {
+ toastError(
+ err instanceof ApiError && err.code === "subagent_gone"
+ ? S.subagentPanel.subagentGone
+ : err instanceof Error
+ ? err.message
+ : String(err),
+ );
+ };
+
+ return (
+ <div className="shrink-0 border-t border-gray-100 px-2 pb-2 pt-2 dark:border-gray-800/60">
+ <ChatInput
+ variant="subagent"
+ status={running ? "running" : "idle"}
+ onSend={async (input: TaskInputPart[]) => {
+ const text = input
+ .filter((p): p is { type: "text"; text: string } => p.type === "text")
+ .map((p) => p.text)
+ .join("\n\n")
+ .trim();
+ if (!text) return false;
+ try {
+ await send(text);
+ return true;
+ } catch (err) {
+ sendFailure(err);
+ return false;
+ }
+ }}
+ onSteer={async (text: string) => {
+ try {
+ await send(text);
+ // steered/started/resumed alike: the message reached the child (the race where
+ // the round settled mid-send simply started the next one). The queued hint
+ // retires when the child's stream shows the delivered input.
+ return "queued";
+ } catch (err) {
+ sendFailure(err);
+ return "failed";
+ }
+ }}
+ steeringDeliveredCount={deliveredInputs}
+ onStop={async () => {
+ await abortSubagent(sessionId, childSessionId).catch(() => undefined);
+ }}
+ 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).
+ turnThinkingLevel={turnLevel || fallbackThinkingLevel}
+ onChangeTurnThinkingLevel={setTurnLevel}
+ {...(contextWindow !== undefined ? { contextWindow } : {})}
+ contextNow={contextNow}
+ vision={false}
+ approvalMode={approvalMode}
+ onChangeApprovalMode={onChangeApprovalMode}
+ modeSaving={modeSaving}
+ agents={[]}
+ skills={skills}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.ts
index a4476047..9fa40d8c 100644
--- a/packages/web/src/features/chat/use-session-stream.ts
+++ b/packages/web/src/features/chat/use-session-stream.ts
@@ -21,6 +21,7 @@ import type {
PendingFollowUpInfo,
PendingSteeringInfo,
SessionStatus,
+ SubagentRuntimeInfo,
} from "@prismshadow/penguin-server/api";
import { getGoal, getMe, getMessages } from "../../api/endpoints";
import { openSessionStream } from "../../api/sse";
@@ -66,6 +67,12 @@ export interface SessionStreamState {
pendingSteering: PendingSteeringInfo[];
/** Queued follow-up tasks (from task_state events): per-entry content + recall handle; empty on old servers (the count above still renders a plain hint). */
pendingFollowUps: PendingFollowUpInfo[];
+ /**
+ * Live subagent children of this session's runtime (from task_state events and the
+ * subscribe snapshot): the panel's structural running marks. Empty for dead/unloaded
+ * runtimes and on old servers — the topology then falls back to its text heuristics.
+ */
+ subagents: SubagentRuntimeInfo[];
/**
* Timestamp (ms) of the last main-session auth failure (request_end with status "auth"),
* or null. Derived from the model, so it survives history replay and resets when
@@ -118,6 +125,7 @@ export function useSessionStream(
const [queuedFollowUps, setQueuedFollowUps] = useState(0);
const [pendingSteering, setPendingSteering] = useState<PendingSteeringInfo[]>([]);
const [pendingFollowUps, setPendingFollowUps] = useState<PendingFollowUpInfo[]>([]);
+ const [subagents, setSubagents] = useState<SubagentRuntimeInfo[]>([]);
const [error, setError] = useState<string | null>(null);
const [pendingTick, setPendingTick] = useState(0);
const [goal, setGoal] = useState<GoalBannerState | null>(null);
@@ -197,6 +205,7 @@ export function useSessionStream(
setQueuedFollowUps(0);
setPendingSteering([]);
setPendingFollowUps([]);
+ setSubagents([]);
setLoading(false);
setError(null);
setGoal(null);
@@ -214,6 +223,7 @@ export function useSessionStream(
setQueuedFollowUps(0);
setPendingSteering([]);
setPendingFollowUps([]);
+ setSubagents([]);
setPendingTick((t) => t + 1);
// Restore an in-flight goal's banner (only when still active — a long-finished goal
@@ -242,6 +252,7 @@ export function useSessionStream(
onQueuedFollowUps: setQueuedFollowUps,
onPendingSteering: setPendingSteering,
onPendingFollowUps: setPendingFollowUps,
+ onSubagents: setSubagents,
onLoading: setLoading,
onError: setError,
onModelChange: bump,
@@ -326,6 +337,7 @@ export function useSessionStream(
queuedFollowUps,
pendingSteering,
pendingFollowUps,
+ subagents,
lastAuthFailureMs: (controllerRef.current?.model ?? placeholderRef.current).lastAuthFailureMs,
dismissModelAuthDead,
pendingApprovals: controllerRef.current?.pendingApprovals ?? EMPTY_PENDING,
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index 6aa153b2..171b994f 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -36,6 +36,7 @@ import type {
MessagesLiveTail,
MessagesPageInfo,
PendingFollowUpInfo,
+ SubagentRuntimeInfo,
PendingSteeringInfo,
ServerEvent,
SessionStatus,
@@ -124,6 +125,8 @@ export interface StreamControllerDeps {
onPendingSteering?: (items: PendingSteeringInfo[]) => void;
/** Queued follow-up tasks carried on task_state events (absent = none): each entry's content + recall handle, alongside the count. */
onPendingFollowUps?: (items: PendingFollowUpInfo[]) => void;
+ /** Live subagent children carried on task_state events (absent = none): the panel's structural running marks — no tool-output text parsing for live sessions. */
+ onSubagents?: (items: SubagentRuntimeInfo[]) => void;
onLoading: (loading: boolean) => void;
/** History load failure message (null = clear). */
onError: (message: string | null) => void;
@@ -245,12 +248,28 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
outlineOffset = page.earlierTurns;
};
+ /** Full clear (resync rebuilds): the server resends every still-pending approval_request on the same connection, child ones included. */
const clearPending = (): void => {
if (pending.size === 0) return;
pending.clear();
deps.onPendingChange();
};
+ // Main-session approvals only (the task-idle flip): an origin-tagged approval belongs to a
+ // subagent child that outlives the parent's task — the server keeps it pending across idle
+ // (see the registry's denyMain), so dropping its card here would hide a question that
+ // still blocks the child. Child cards leave via their approval_decision instead.
+ const clearMainPending = (): void => {
+ let dropped = false;
+ for (const [key, entry] of [...pending]) {
+ if (entry.origin === undefined || entry.origin.length === 0) {
+ pending.delete(key);
+ dropped = true;
+ }
+ }
+ if (dropped) deps.onPendingChange();
+ };
+
const feedOmni = (msg: OmniMessage, dedup: Set<string> | null): void => {
// The SDK has already produced an approval_decision: sync the pending-approvals table (keyed by the origin composite key).
if (isEventMessage(msg) && msg.payload.type === "approval_decision") {
@@ -294,10 +313,13 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
deps.onQueuedFollowUps?.(ev.queued ?? 0);
deps.onPendingSteering?.(ev.pendingSteering ?? []);
deps.onPendingFollowUps?.(ev.pendingFollowUps ?? []);
+ deps.onSubagents?.(ev.subagents ?? []);
if (ev.state === "idle") {
- // Task ended (or the snapshot confirms idle): finalize the current Task's stats; pending approvals have already converged server-side.
+ // Task ended (or the snapshot confirms idle): finalize the current Task's stats.
+ // The main session's approvals converged server-side with the run; a subagent
+ // child's stay pending — and rendered — until the user decides.
notifyTaskIdle(model);
- clearPending();
+ clearMainPending();
deps.onModelChange();
}
return;
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 413bcda3..dc43ad40 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1686,6 +1686,7 @@ Scenarios:
nodeRunning: "running",
nodeDone: "done",
openAsSession: "Jump to this session",
+ subagentGone: "This subagent session no longer exists and could not be revived",
},
files: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 2f3aa95f..756c48a8 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1644,6 +1644,8 @@ Benchmark:
nodeDone: "已完成",
/** Identity-strip jump: opens the selected subagent's own Session in the chat area. */
openAsSession: "跳转到该会话",
+ /** The child's session record no longer exists and could not be revived. */
+ subagentGone: "该子会话已不存在,无法恢复",
},
files: {
diff --git a/packages/web/test/agent-topology.test.ts b/packages/web/test/agent-topology.test.ts
index fffd967d..ab07b0f8 100644
--- a/packages/web/test/agent-topology.test.ts
+++ b/packages/web/test/agent-topology.test.ts
@@ -109,6 +109,46 @@ describe("extractTopology", () => {
expect(nodes[1]!.running).toBe(false);
});
+ it("pins the most recent subagent-bearing Task: a plain user message does not wipe the graph", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("go"));
+ spawnChild(m, "t1", "child1");
+ pushMessage(m, toolCallOutput({ output: "done", toolCallId: "t1" }));
+ pushMessage(m, assistantText("answered"));
+
+ // Two plain follow-up messages with no spawns: the panel keeps showing child1's Task —
+ // its root reads as ended (the next user message closed that Task).
+ pushMessage(m, userText("thanks"));
+ pushMessage(m, assistantText("np"));
+ pushMessage(m, userText("one more question"));
+ let nodes = extractTopology(m, "root", true);
+ expect(nodes.map((n) => n.sessionId)).toEqual(["root", "child1"]);
+ expect(nodes[0]!.running).toBe(false);
+
+ // The moment a new Task spawns its own child, it takes the panel over.
+ spawnChild(m, "t2", "child2");
+ nodes = extractTopology(m, "root", true);
+ expect(nodes.map((n) => n.sessionId)).toEqual(["root", "child2"]);
+ });
+
+ it("server liveness overrides the text heuristics whenever it knows the child (issue #274)", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("go"));
+ spawnChild(m, "t1", "child1");
+ // The card completed long ago — the heuristic reads done — but the runtime reports the
+ // child running again (an input_subagent revival or a panel-started round).
+ pushMessage(m, toolCallOutput({ output: "done", toolCallId: "t1" }));
+ const live = new Map([["child1", true]]);
+ expect(extractTopology(m, "root", false, live)[1]!.running).toBe(true);
+
+ // The reverse: a card that still looks running settles the moment the server says idle.
+ const idle = new Map([["child1", false]]);
+ expect(extractTopology(m, "root", true, idle)[1]!.running).toBe(false);
+
+ // A child the server does not know (dead runtime, old server) keeps the heuristic.
+ expect(extractTopology(m, "root", false, new Map())[1]!.running).toBe(false);
+ });
+
it("prefers the child's own session_meta capture (agent_state path) over the call-argument agent id", () => {
const m = createStreamModel();
pushMessage(m, userText("go"));
@@ -163,14 +203,17 @@ describe("extractTopology", () => {
expect(nodes[1]).toMatchObject({ sessionId: "childX", running: false, parentId: "root" });
});
- it("shows only the latest Task's spawns: a new user message resets the graph to the root", () => {
+ it("a new user message keeps the previous subagent Task pinned until its own spawn takes over", () => {
const m = createStreamModel();
pushMessage(m, userText("task 1"));
spawnChild(m, "t1", "child1");
pushMessage(m, toolCallOutput({ output: "done", toolCallId: "t1" }));
+ // Task 2 starts with no spawns of its own: the panel stays on Task 1's graph (root ended).
pushMessage(m, userText("task 2"));
- expect(extractTopology(m, "root", true).map((n) => n.sessionId)).toEqual(["root"]);
+ const pinned = extractTopology(m, "root", true);
+ expect(pinned.map((n) => n.sessionId)).toEqual(["root", "child1"]);
+ expect(pinned[0]!.running).toBe(false);
spawnChild(m, "t2", "child2");
expect(extractTopology(m, "root", true).map((n) => n.sessionId)).toEqual(["root", "child2"]);