Skip to content

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

feat(core,server,web,docs): background execution with completion reports and kill tools (#376)

Yaowei Zheng3f8d1e8fe184
diff --git a/changelog/unreleased/2026-08-20-background-execution.md b/changelog/unreleased/2026-08-20-background-execution.md
new file mode 100644
index 00000000..ce6f5d97
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-background-execution.md
@@ -0,0 +1,22 @@
+# Background execution with completion reports, and kill tools
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#376](https://github.com/Prism-Shadow/penguin-harness/pull/376)
+
+[中文版](2026-08-20-background-execution.zh.md)
+
+Added a `run_in_background` argument to `exec_command` and `run_subagent`: the call returns its `process_id` / `subagent_id` immediately, and when the task settles its result comes back **as a user message injected by the harness** — the model no longer needs to poll. Added `kill_command` and `kill_subagent` to terminate background sessions, and raised `input_command`'s default empty-poll wait from 5000ms to 120000ms so one poll waits out most builds.
+
+## Details
+
+- The completion report 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 with the report body below it.
+- Delivery: while a Task is running, the report rides the next turn boundary — a Task whose final reply already streamed continues for one more turn to react to it. While the Session is idle, the server starts a new Task carrying the report; SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, and with no subscriber the report joins the next run's input.
+- `kill_command` SIGTERMs the whole process group (SIGKILL after a grace period) and returns the output not yet delivered; `kill_subagent` aborts the run, denies its pending approvals, and removes the session (an idle one too, freeing its concurrency slot). A killed task sends no completion report — the kill's own result carries the outcome.
+- User-role `text` payloads gained an optional `sender` field (`"user" | "parent_agent" | "harness" | "server"`): subagent prompts written by the parent agent are recorded as `sender: "parent_agent"` in the child's Trace, harness-injected completion reports as `sender: "harness"`, and the server's scheduled-task triggers as `sender: "server"`. The field is additive — absent means the human user, which is also the correct reading of every Trace written before it existed — so no migration and no compatibility code is involved, and it never reaches the provider wire.
+- The kernel version advanced (now `2026-08-21`); existing agents adopt the new tools and arguments through the settings page's kernel update (user customizations kept), or keep their stored toolset untouched if they never run it.
+- Fixed the delivery gap for freshly created sessions: the runtime registered the idle-arrival notice listener only on the resume path, so a session created in the same server process never surfaced its completion reports — the chat page sat unrefreshed. Both entry paths now register it, proven by a Playwright end-to-end test (real server, mock LLM: the report banner and the model's follow-up turn appear in an open chat page with no interaction).
+- A background subagent now announces itself at launch: its `session_meta` is forwarded upfront, so the chat page's subagents panel shows the node (and the server registers the child) before any poll; the panel derives a background node's running state from the harness's own notes and settles it when the completion notice, an idle poll, or a kill removes the work.
+- Fixed background subagents parking forever on their first read-write tool: the child's approvals only resolved through a polling window's sink, which a `run_in_background` launch never opens — its commands surfaced as hung or aborted. The launch now attaches its own approval callback as a standing sink, the child's abort signal stays fully its own (only `kill_subagent`, Session end, or eviction ends it), and its messages stream to the frontend live through the launching Session instead of waiting for the first poll. Failures end in a `status: failed` report like any terminal state. Proven end to end with Playwright (success and failure paths, no interaction after the send).
+- The completion notice's chat rendering became a collapsible one-liner in the work group's own "Done" summary-bar form — same chrome, title styling and sticky pinning against the scrollport, drawn from one extracted style source (`disclosure-row.tsx`, whose row/header/card constants the thinking block, tool cards and work group all reference): collapsed it shows only the outcome ("Background command finished" / "Background task failed"); expanding reveals the handle, exit detail and output tail in the tool cards' output styling. On the Trace page a notice-triggered task stays its own round.
diff --git a/changelog/unreleased/2026-08-20-background-execution.zh.md b/changelog/unreleased/2026-08-20-background-execution.zh.md
new file mode 100644
index 00000000..2dd4bade
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-background-execution.zh.md
@@ -0,0 +1,22 @@
+# 后台执行与完成回报,以及 kill 工具
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#376](https://github.com/Prism-Shadow/penguin-harness/pull/376)
+
+[English](2026-08-20-background-execution.md)
+
+为 `exec_command` 与 `run_subagent` 增加了 `run_in_background` 参数:调用立即返回 `process_id` / `subagent_id`,任务结束时其结果**以 Harness 注入的 user message** 送回会话——模型不再需要轮询。新增 `kill_command` 与 `kill_subagent` 用于终止后台会话,并把 `input_command` 空轮询的默认等待从 5000ms 提高到 120000ms,一次轮询即可等完多数构建。
+
+## 细节
+
+- 完成回报以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符)。Web App 将标记块折叠为一行提示,回报正文显示在其下方。
+- 送达时机:Task 进行中时,回报搭乘下一个 turn 边界——最终回复已流式输出的 Task 会再延续一个 turn 来回应它;Session 空闲时,Server 自动以该回报发起新 Task;SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,无订阅者时回报并入下一次 run 的输入。
+- `kill_command` 向整个进程组发 SIGTERM(宽限期后 SIGKILL)并返回尚未送达的输出;`kill_subagent` 中止运行、拒绝其待审批项并移除会话(空闲会话也可移除,腾出并发额度)。被 kill 的任务不再发完成回报——kill 自身的结果已说明结局。
+- user 角色的 `text` payload 增加了可选 `sender` 字段(`"user" | "parent_agent" | "harness" | "server"`):父 Agent 写给 Subagent 的 Prompt 在子 Trace 中记为 `sender: "parent_agent"`,Harness 注入的完成回报记为 `sender: "harness"`,Server 的定时任务触发记为 `sender: "server"`。该字段为纯追加——缺省即真人用户,这也是该字段出现之前所有 Trace 的正确读法——因此不涉及迁移与兼容代码,且不会进入 Provider 请求。
+- 内核版本已推进(现为 `2026-08-21`);既有 Agent 通过设置页的内核更新采纳新工具与新参数(用户自定义保留),不执行则维持原有工具集不变。
+- 修复了新建会话的送达缺口:运行时只在恢复路径注册空闲回报监听,同进程新建的会话完成回报无人接收——聊天页因此不刷新。两条入表路径现在都注册,并有 Playwright 端到端测试证明(真实 server + mock LLM:回报横幅与模型后续轮在打开的聊天页上无操作自动出现)。
+- 后台 Subagent 启动即亮相:其 `session_meta` 在启动时前置转发,聊天页的智能体面板在任何轮询之前就能看到该节点(服务端同步注册);面板依据 Harness 自身的注记推导后台节点的运行状态,完成回报、空闲轮询或 kill 移除都会将其置为已结束。
+- 修复后台 Subagent 在首个读写工具上永久卡死的问题:子会话审批此前只能经轮询窗口的 sink 解决,而 `run_in_background` 启动从不开窗——其命令表现为挂起或 aborted。现在启动时把该调用自身的审批回调挂为常驻 sink,子会话中止信号完全独立(仅 `kill_subagent`、Session 终结或淘汰会结束它),消息经发起 Session 实时流向前端而非等待首次轮询;失败与其他终态一样以 `status: failed` 回报收尾。成功与失败双路径均有 Playwright 端到端验证(发送后零操作)。
+- 完成回报的聊天渲染改为工作分组「运行完毕」摘要行同款的可折叠一行——同底色、同标题样式、同贴顶吸附行为,样式取自单一抽取源(`disclosure-row.tsx`,其行/分组头/卡片类常量由思考块、工具卡与工作分组共同引用):折叠只显示结论(「后台命令完成」/「后台任务失败」),展开以工具卡输出样式呈现句柄、退出详情与输出尾部。轨迹观测页上,回报触发的任务保持独立一轮。
diff --git a/changelog/unreleased/2026-08-21-process-service-url.md b/changelog/unreleased/2026-08-21-process-service-url.md
new file mode 100644
index 00000000..3f7d6550
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-process-service-url.md
@@ -0,0 +1,15 @@
+# Service links on the background-process list
+
+- **Date:** 2026-08-21
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#376](https://github.com/Prism-Shadow/penguin-harness/pull/376)
+
+[中文版](2026-08-21-process-service-url.zh.md)
+
+The chat page's background-process list now shows a clickable link to the service a running process serves, next to its pid. Detection lives in core and has two sources: the command session scans its own output stream incrementally for local URLs (ANSI-stripped, wildcard hosts normalized to `localhost`, the latest hit wins — covering foreground and background runs alike, with no dependence on the model polling), and when the process printed no URL, a listen-port probe of its process group synthesizes `http://localhost:<port>` (linux `ss`+`ps`, macOS `lsof -g`, Windows `Get-NetTCPConnection` + the CIM process tree; multiple ports collapse to the smallest).
+
+## Details
+
+- The printed URL (which may carry a path) always outranks the probed origin. Probes run when the processes list is fetched, TTL-cached per session with a hard per-probe timeout; a failed probe keeps the previous result, a successful empty one clears it.
+- The processes API's rows gained an additive optional `serviceUrl`; the Web App renders it on running rows only, opening in a new tab.
diff --git a/changelog/unreleased/2026-08-21-process-service-url.zh.md b/changelog/unreleased/2026-08-21-process-service-url.zh.md
new file mode 100644
index 00000000..a24e775f
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-process-service-url.zh.md
@@ -0,0 +1,15 @@
+# 后台进程列表的服务链接
+
+- **Date:** 2026-08-21
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#376](https://github.com/Prism-Shadow/penguin-harness/pull/376)
+
+[English](2026-08-21-process-service-url.md)
+
+会话页的后台进程列表在 pid 旁新增了可点击的服务链接,指向运行中进程所服务的地址。检测在 core 层完成,双源:命令会话对自身输出流做增量本机 URL 扫描(剥 ANSI、监听通配主机归一为 `localhost`、取最新命中——前台与后台运行天然同覆盖,不依赖模型轮询);进程没打印 URL 时,按其进程组做监听端口探测并合成 `http://localhost:<port>`(linux 用 `ss`+`ps`,macOS 用 `lsof -g`,Windows 用 `Get-NetTCPConnection` + CIM 进程树;多个端口取最小)。
+
+## 细节
+
+- 输出打印的 URL(可能带路径)始终优先于端口探测合成的地址。探测在拉取进程列表时触发,按会话 TTL 缓存并带单次探测硬超时;探测失败保留旧结果,探测成功但无监听则清除。
+- 进程 API 的行以追加方式新增可选 `serviceUrl`;Web App 仅在运行中的行渲染,新标签页打开。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 73565c85..94a88f48 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -58,6 +58,7 @@ 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,
@@ -698,6 +699,14 @@ export class Agent {
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;
@@ -720,7 +729,9 @@ export class Agent {
// Trace, so replay never duplicates it. Later rounds (input_subagent
// follow-up prompts) come through this same generator and are forwarded the
// same way.
- const input = userText(prompt);
+ // 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 } : {}),
@@ -737,9 +748,9 @@ export class Agent {
};
// Tool exposure is capped by depth: a (leaf) child Agent that has reached the
- // max spawn depth no longer gets run_subagent or input_subagent (the latter
- // depends on the subagent_id produced by the former, so exposing it alone is
- // meaningless).
+ // 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).
const canSpawn = subagentDepth < MAX_SUBAGENT_DEPTH;
const baseToolConfig = buildToolConfig(this.state);
// Select tool entries by the session model's type (marked via forModel: vision
@@ -749,7 +760,10 @@ export class Agent {
let customTools = selectBuiltinToolsForModel(baseToolConfig.customTools, modelVision);
if (!canSpawn) {
customTools = customTools.filter(
- (d) => d.name !== SUBAGENT_NAME && d.name !== INPUT_SUBAGENT_NAME,
+ (d) =>
+ d.name !== SUBAGENT_NAME &&
+ d.name !== INPUT_SUBAGENT_NAME &&
+ d.name !== KILL_SUBAGENT_NAME,
);
}
const toolConfig = { ...baseToolConfig, customTools };
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 726a1829..6af9c9cf 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -238,6 +238,16 @@ export interface ContextEngineDeps {
* degrades a failure into text saying the images were dropped.
*/
foldInputImages?: (messages: OmniMessage[]) => Promise<OmniMessage[]>;
+ /**
+ * Background-task completion notices (harness user messages the Session queues when a
+ * `run_in_background` task settles — see Session's notice queue). Pull seam: the engine
+ * drains at every input-assembly point — run start included — yielding each message to the
+ * output stream and writing it to Trace (like steering, this text never reached the
+ * consumer any other way); `pending` is the boundary peek that keeps a discard/summary
+ * from ending the run while notices still wait. Absent = no notice source (tests,
+ * standalone embedders).
+ */
+ backgroundNotices?: { drain(): OmniMessage[]; pending(): number };
}
const isImageMessage = (m: OmniMessage): boolean =>
@@ -467,6 +477,31 @@ export class ContextEngine {
/** Whether a `run` is currently in flight (gates `steer`; compaction does not count). */
private taskRunning = false;
+ /** Whether a `run` is in flight (the Session's notice routing keys on this: a running task delivers notices at the next boundary; an idle one goes through the host). */
+ get isTaskRunning(): boolean {
+ return this.taskRunning;
+ }
+
+ /** Background notices still waiting at the source (boundary peek; see ContextEngineDeps.backgroundNotices). */
+ private pendingNoticeCount(): number {
+ return this.deps.backgroundNotices?.pending() ?? 0;
+ }
+
+ /**
+ * Drains queued background-task notices into the stream: each is yielded and written to
+ * Trace (mid-run input the consumer has never seen, same rationale as deliverSteering),
+ * and returned for the caller to append to the next request input. Delivered BEFORE
+ * steering at every assembly point — the user's own words come last.
+ */
+ private async *deliverBackgroundNotices(): AsyncGenerator<OmniMessage, OmniMessage[]> {
+ const messages = this.deps.backgroundNotices?.drain() ?? [];
+ for (const msg of messages) {
+ yield msg;
+ await this.write(msg);
+ }
+ return messages;
+ }
+
constructor(private readonly deps: ContextEngineDeps) {
this.pendingBootstrapRecords = deps.bootstrapRecords ?? null;
this.maxTurns = deps.maxTurns ?? -1;
@@ -650,8 +685,11 @@ export class ContextEngine {
let turnCount = 0;
// Each turn's LLM input: the first turn is the Prompt, later turns are the previous turn's
- // tool outputs.
+ // tool outputs. Background notices that arrived while the session sat idle (and were not
+ // taken by the host as their own task input) ride the first request, behind the Prompt.
let nextInput: OmniMessage[] = input;
+ const startNotices = yield* this.deliverBackgroundNotices();
+ if (startNotices.length > 0) nextInput = [...nextInput, ...startNotices];
for (;;) {
// max_turns guard: emit a length notice and stop once exceeded. A non-positive cap
@@ -776,9 +814,9 @@ export class ContextEngine {
const mode = this.deps.compaction!.mode;
if (mode === "discard") {
// Once discarded, the current Task can't continue: defer until the Task really
- // ends (mid-Task, or steering still queued that must continue the loop). The
- // queue is only peeked here — delivery happens at the input assembly below.
- if (!midTask && this.steeringQueue.length === 0) {
+ // ends (mid-Task, or steering/notices still queued that must continue the loop).
+ // The queues are only peeked here — delivery happens at the input assembly below.
+ if (!midTask && this.steeringQueue.length === 0 && this.pendingNoticeCount() === 0) {
yield* this.discardContext(compactionReason);
return;
}
@@ -789,10 +827,11 @@ export class ContextEngine {
signal,
);
if (result.status === "completed") {
- // Boundary check against the **live** queue: steering may have arrived during
- // the multi-second compaction request and must not be swallowed (no await sits
- // between this check and the return, so the window cannot reopen).
- if (!midTask && this.steeringQueue.length === 0) {
+ // Boundary check against the **live** queues: steering or a background notice
+ // may have arrived during the multi-second compaction request and must not be
+ // swallowed (no await sits between this check and the return, so the window
+ // cannot reopen).
+ if (!midTask && this.steeringQueue.length === 0 && this.pendingNoticeCount() === 0) {
// Task boundary: the summary is merged with the next user Prompt as the new
// context's first input.
this.pendingSummary = result.summary!;
@@ -805,8 +844,11 @@ export class ContextEngine {
// steering (including anything that arrived during the compaction request) is
// delivered right after the summary as standalone [user_steering] user turns.
await this.write(result.summary!);
- const steering = yield* this.deliverSteering();
- nextInput = [result.summary!, ...steering];
+ const injected = [
+ ...(yield* this.deliverBackgroundNotices()),
+ ...(yield* this.deliverSteering()),
+ ];
+ nextInput = [result.summary!, ...injected];
continue;
}
// failed or aborted: keep the original context and Trace index — the compaction is
@@ -839,20 +881,24 @@ export class ContextEngine {
}
}
- // Next-input assembly — the steering delivery point: everything queued so far becomes
- // standalone [user_steering] user messages riding alongside this turn's tool outputs
- // (or alone as the continuation input when the turn produced no tool calls, instead of
- // ending the Task — subject to the max-turns guard at the top of the loop).
- const steering = yield* this.deliverSteering();
- // No tool_call this turn and no steering left -> the Task ends (the final reply has
+ // Next-input assembly — the injection delivery point: queued background notices
+ // (harness user messages) and steering ([user_steering] user messages) ride alongside
+ // this turn's tool outputs (or alone as the continuation input when the turn produced
+ // no tool calls, instead of ending the Task — subject to the max-turns guard at the
+ // top of the loop). Notices first; the user's own words come last.
+ const injected = [
+ ...(yield* this.deliverBackgroundNotices()),
+ ...(yield* this.deliverSteering()),
+ ];
+ // No tool_call this turn and nothing injected -> the Task ends (the final reply has
// already been streamed out). A compaction stash, if any, rides the next run.
- if (!midTask && steering.length === 0) return;
+ if (!midTask && injected.length === 0) return;
// Anything a failed boundary compaction stashed (synthesized repair outputs from
// rejected attempts) rides the very next request, ahead of the turn outputs so
// tool_results stay contiguous and first.
const stashed = this.pendingCarryOver;
this.pendingCarryOver = [];
- nextInput = [...stashed, ...turn.toolOutputs, ...steering];
+ nextInput = [...stashed, ...turn.toolOutputs, ...injected];
if (nextInput.length === 0) return;
}
}
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index 484b03f2..3ec6adf3 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -30,6 +30,7 @@ import { partialToolCallOutput, toolCallOutput } from "../omnimessage/index.js";
import type { McpServerConnectResult, OmniMessage, StopReason } from "../omnimessage/index.js";
import type {
BackgroundCommandInfo,
+ BackgroundTaskDoneEvent,
EnvironmentConfig,
EnvironmentInterface,
ToolConfig,
@@ -126,6 +127,11 @@ export class Environment implements EnvironmentInterface {
...config.services,
commandSessions: this.commandSessions,
subagentSessions: this.subagentSessions,
+ // Completion reports of run_in_background launches converge here; the Session attaches
+ // the single consumer via setBackgroundTaskListener (events before that are buffered).
+ backgroundDone: (event: BackgroundTaskDoneEvent) => this.emitBackgroundDone(event),
+ // Live-forwarded background-subagent messages, same single-consumer pattern.
+ backgroundForward: (msg: OmniMessage) => this.emitBackgroundForward(msg),
};
// Assemble the tools supported by config into BuiltinTool instances; unrecognized tool
// names are skipped (neither exposed to the LLM nor executable).
@@ -147,11 +153,55 @@ export class Environment implements EnvironmentInterface {
/** Releases runtime resources held by Environment: finalizes all managed background sessions (command and subagent) and closes MCP clients (stdio server processes included). Idempotent. */
dispose(): void {
+ // Suppress completion reports first: dispose kills the remaining background sessions, and
+ // their exits must not masquerade as task completions after the Session has ended.
+ this.bgDisposed = true;
+ this.bgBuffer = [];
+ this.bgFwdBuffer = [];
this.commandSessions.dispose();
this.subagentSessions.dispose();
this.mcp?.closeQuietly();
}
+ // Background completion reports: a single listener (the owning Session), with events fired
+ // before the attach buffered so a fast completion is never lost between construction and wiring.
+ private bgListener: ((event: BackgroundTaskDoneEvent) => void) | null = null;
+ private bgBuffer: BackgroundTaskDoneEvent[] = [];
+ private bgDisposed = false;
+
+ private emitBackgroundDone(event: BackgroundTaskDoneEvent): void {
+ if (this.bgDisposed) return;
+ if (this.bgListener) this.bgListener(event);
+ else this.bgBuffer.push(event);
+ }
+
+ /** Attaches the single background-completion listener, flushing buffered events (see EnvironmentInterface). */
+ setBackgroundTaskListener(listener: (event: BackgroundTaskDoneEvent) => void): void {
+ this.bgListener = listener;
+ const buffered = this.bgBuffer;
+ this.bgBuffer = [];
+ for (const event of buffered) this.emitBackgroundDone(event);
+ }
+
+ // Live-forwarded background-subagent messages: same single-listener + buffer-until-attach
+ // pattern as the completion reports above.
+ private bgFwdListener: ((msg: OmniMessage) => void) | null = null;
+ private bgFwdBuffer: OmniMessage[] = [];
+
+ private emitBackgroundForward(msg: OmniMessage): void {
+ if (this.bgDisposed) return;
+ if (this.bgFwdListener) this.bgFwdListener(msg);
+ else this.bgFwdBuffer.push(msg);
+ }
+
+ /** Attaches the single background-message listener, flushing buffered messages (see EnvironmentInterface). */
+ setBackgroundMessageListener(listener: (msg: OmniMessage) => void): void {
+ this.bgFwdListener = listener;
+ const buffered = this.bgFwdBuffer;
+ this.bgFwdBuffer = [];
+ for (const msg of buffered) this.emitBackgroundForward(msg);
+ }
+
/** Background command processes registered by exec_command (still-listed exited ones included; the host UI filters as it sees fit). */
listBackgroundCommands(): BackgroundCommandInfo[] {
return this.commandSessions.list().map(({ processId, session }) => ({
@@ -161,9 +211,22 @@ export class Environment implements EnvironmentInterface {
cwd: session.cwd,
startedAt: session.startedAt,
running: session.running,
+ ...(session.serviceUrl !== null ? { serviceUrl: session.serviceUrl } : {}),
}));
}
+ /** Refreshes the listen-port probes behind serviceUrl (running sessions only; each internally TTL-cached and time-bounded — see EnvironmentInterface). */
+ async probeBackgroundCommandServices(): Promise<void> {
+ await Promise.all(
+ this.commandSessions.list().map(({ session }) => session.refreshServiceProbe()),
+ );
+ }
+
+ /** Whether a managed subagent session is mid-round (see EnvironmentInterface.hasRunningBackgroundSubagents). */
+ hasRunningBackgroundSubagents(): boolean {
+ return this.subagentSessions.hasRunning();
+ }
+
/** 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/background/index.ts b/packages/core/src/environment/tools/background/index.ts
index 6f55a7da..6bcb6d3e 100644
--- a/packages/core/src/environment/tools/background/index.ts
+++ b/packages/core/src/environment/tools/background/index.ts
@@ -3,6 +3,6 @@
*/
export { BackgroundRegistry } from "./registry.js";
export type { BackgroundTask } from "./registry.js";
-export { clampYield } from "./limits.js";
+export { clampYield, tailForReport, reportLabel } from "./limits.js";
export { WakeSignal } from "./wake-signal.js";
export { CappedTextBuffer } from "./capped-buffer.js";
diff --git a/packages/core/src/environment/tools/background/limits.ts b/packages/core/src/environment/tools/background/limits.ts
index 2e7a745d..40a32a9c 100644
--- a/packages/core/src/environment/tools/background/limits.ts
+++ b/packages/core/src/environment/tools/background/limits.ts
@@ -21,3 +21,21 @@ export function clampYield(raw: unknown, fallback: number, timeoutMs?: number):
if (timeoutMs === undefined || timeoutMs <= 0) return lower;
return Math.min(lower, Math.max(timeoutMs - TIMEOUT_MARGIN_MS, MIN_YIELD_MS));
}
+
+/** Cap (characters) on the output tail a background completion report carries. */
+export const DONE_REPORT_OUTPUT_CAP = 4000;
+
+/** Keeps the LAST `cap` characters (a run's verdict sits at the end), prefixing a drop marker when truncated. */
+export function tailForReport(text: string, cap: number = DONE_REPORT_OUTPUT_CAP): string {
+ if (text.length <= cap) return text;
+ return `[earlier output dropped: exceeded ${cap} chars]\n${text.slice(text.length - cap)}`;
+}
+
+/** Cap (characters) on a completion report's label (the command / prompt excerpt). */
+const REPORT_LABEL_CAP = 120;
+
+/** First line of `text`, truncated to the label cap with an ellipsis. */
+export function reportLabel(text: string): string {
+ const line = text.split("\n", 1)[0] ?? "";
+ return line.length <= REPORT_LABEL_CAP ? line : `${line.slice(0, REPORT_LABEL_CAP - 1)}…`;
+}
diff --git a/packages/core/src/environment/tools/command/index.ts b/packages/core/src/environment/tools/command/index.ts
index 7c55bf4c..c7db5fe9 100644
--- a/packages/core/src/environment/tools/command/index.ts
+++ b/packages/core/src/environment/tools/command/index.ts
@@ -11,3 +11,12 @@ export {
DEFAULT_WRITE_YIELD_MS,
DEFAULT_EMPTY_POLL_YIELD_MS,
} from "./limits.js";
+export { ServiceUrlScanner, extractLastLocalUrl } from "./service-url.js";
+export {
+ parsePsPids,
+ parseSsListenPorts,
+ parseLsofListenPorts,
+ parseWindowsProbe,
+ probeGroupListenPorts,
+} from "./port-probe.js";
+export type { ListenSocket } from "./port-probe.js";
diff --git a/packages/core/src/environment/tools/command/limits.ts b/packages/core/src/environment/tools/command/limits.ts
index cc338ec8..7f687f41 100644
--- a/packages/core/src/environment/tools/command/limits.ts
+++ b/packages/core/src/environment/tools/command/limits.ts
@@ -11,5 +11,10 @@
export const DEFAULT_EXEC_YIELD_MS = 60_000;
/** Default wait duration (milliseconds) for `input_command` when there's a write. */
export const DEFAULT_WRITE_YIELD_MS = 250;
-/** Default wait duration (milliseconds) for `input_command` on an empty poll. */
-export const DEFAULT_EMPTY_POLL_YIELD_MS = 5_000;
+/**
+ * Default wait duration (milliseconds) for `input_command` on an empty poll: a default-length
+ * poll waits out most builds/test runs in one call instead of ping-ponging short polls (data
+ * still streams as it arrives — the wait only ends early on exit). Must stay below
+ * `input_command`'s `timeoutMs` minus the clamp margin (see ../background/limits.ts).
+ */
+export const DEFAULT_EMPTY_POLL_YIELD_MS = 120_000;
diff --git a/packages/core/src/environment/tools/command/port-probe.ts b/packages/core/src/environment/tools/command/port-probe.ts
new file mode 100644
index 00000000..5e96111c
--- /dev/null
+++ b/packages/core/src/environment/tools/command/port-probe.ts
@@ -0,0 +1,206 @@
+/**
+ * Listen-port probing for command sessions — the fallback behind output scanning (see
+ * service-url.ts): a server that prints no URL can still be found by asking the OS which
+ * ports the session's process group / process tree is listening on.
+ *
+ * Per platform, using only stock tooling:
+ * - linux: `ps -o pid= -g <pgid>` for the group's pids (the session leader is the group,
+ * see ManagedSession's `detached` spawn) + `ss -ltnp` for listening sockets with owner
+ * pids (iproute2; unprivileged output covers the user's own processes, which the
+ * session's children are);
+ * - darwin: `lsof -a -g <pgid> -iTCP -sTCP:LISTEN -n -P -Fpn` — lsof filters by process
+ * group itself and `-F` output is machine-readable;
+ * - win32: PowerShell `Get-NetTCPConnection -State Listen` + `Get-CimInstance
+ * Win32_Process` as one JSON payload; the tree is walked from the session's root pid
+ * (no process groups on Windows — same ancestry rule the kill path's `taskkill /t`
+ * uses).
+ *
+ * Probes are best-effort and bounded: one short-lived child process with a hard timeout,
+ * every failure (missing tool, non-zero exit, unparseable output) collapsing to null —
+ * "don't know", distinct from "no listeners" (an empty list), so callers keep a
+ * previously known URL over a transient failure. The pure parsers are exported for
+ * fixture tests; only the linux path gets a live integration test.
+ */
+import { execFile } from "node:child_process";
+
+/** Hard cap (ms) on one probe child process: the poll path must never hang on a stuck tool. */
+const PROBE_TIMEOUT_MS = 1_500;
+
+/** One listening socket attributed to a pid. */
+export interface ListenSocket {
+ port: number;
+ pid: number;
+}
+
+/** `ps -o pid= -g <pgid>` output → the group's pids (one per line, whitespace-padded). */
+export function parsePsPids(output: string): number[] {
+ const pids: number[] = [];
+ for (const line of output.split("\n")) {
+ const n = Number.parseInt(line.trim(), 10);
+ if (Number.isInteger(n) && n > 0) pids.push(n);
+ }
+ return pids;
+}
+
+/**
+ * `ss -ltnp` output → listening sockets with their owner pids. A line reads
+ * `LISTEN 0 511 *:5173 *:* users:(("node",pid=123,fd=23),("node",pid=124,fd=23))`;
+ * the local-address column's port suffix and every `pid=` in the users list are taken
+ * (a socket shared by a forked pair lists them all).
+ */
+export function parseSsListenPorts(output: string): ListenSocket[] {
+ const sockets: ListenSocket[] = [];
+ for (const line of output.split("\n")) {
+ // Columns: State Recv-Q Send-Q Local:Port Peer:Port Process — the header row and any
+ // non-listen state fail the first-column check.
+ const cols = line.trim().split(/\s+/);
+ if (cols[0] !== "LISTEN" || cols.length < 4) continue;
+ const addr = /:(\d{1,5})$/.exec(cols[3]!);
+ const port = addr ? Number.parseInt(addr[1]!, 10) : NaN;
+ if (!Number.isInteger(port) || port <= 0) continue;
+ for (const m of line.matchAll(/pid=(\d+)/g)) {
+ sockets.push({ port, pid: Number.parseInt(m[1]!, 10) });
+ }
+ }
+ return sockets;
+}
+
+/**
+ * `lsof -Fpn` output → listening sockets. `-F` emits one field per line: `p<pid>` opens a
+ * process paragraph, each `n<addr>` names a socket (`*:5173`, `127.0.0.1:8080`,
+ * `[::1]:9090`) attributed to the current paragraph's pid.
+ */
+export function parseLsofListenPorts(output: string): ListenSocket[] {
+ const sockets: ListenSocket[] = [];
+ let pid = 0;
+ for (const line of output.split("\n")) {
+ if (line.startsWith("p")) {
+ const n = Number.parseInt(line.slice(1), 10);
+ pid = Number.isInteger(n) && n > 0 ? n : 0;
+ continue;
+ }
+ if (!line.startsWith("n") || pid === 0) continue;
+ const m = /:(\d{1,5})$/.exec(line.trim());
+ if (!m) continue;
+ const port = Number.parseInt(m[1]!, 10);
+ if (Number.isInteger(port) && port > 0) sockets.push({ port, pid });
+ }
+ return sockets;
+}
+
+/** Shapes of the one-shot PowerShell probe's JSON payload (ConvertTo-Json collapses single-element arrays to the bare object). */
+interface WindowsProbePayload {
+ c?:
+ | { LocalPort?: number; OwningProcess?: number }
+ | { LocalPort?: number; OwningProcess?: number }[];
+ p?:
+ | { ProcessId?: number; ParentProcessId?: number }
+ | { ProcessId?: number; ParentProcessId?: number }[];
+}
+
+function asArray<T>(value: T | T[] | undefined): T[] {
+ if (value === undefined) return [];
+ return Array.isArray(value) ? value : [value];
+}
+
+/**
+ * The PowerShell probe's JSON → ports listened on by `rootPid`'s process tree. The tree
+ * is walked from the root over ParentProcessId edges (pid reuse makes this an
+ * approximation, same as every tree-kill on Windows).
+ */
+export function parseWindowsProbe(json: string, rootPid: number): number[] | null {
+ let payload: WindowsProbePayload;
+ try {
+ payload = JSON.parse(json) as WindowsProbePayload;
+ } catch {
+ return null;
+ }
+ const children = new Map<number, number[]>();
+ for (const proc of asArray(payload.p)) {
+ if (typeof proc.ProcessId !== "number" || typeof proc.ParentProcessId !== "number") continue;
+ const list = children.get(proc.ParentProcessId) ?? [];
+ list.push(proc.ProcessId);
+ children.set(proc.ParentProcessId, list);
+ }
+ const tree = new Set<number>([rootPid]);
+ const queue = [rootPid];
+ while (queue.length > 0) {
+ for (const child of children.get(queue.shift()!) ?? []) {
+ if (!tree.has(child)) {
+ tree.add(child);
+ queue.push(child);
+ }
+ }
+ }
+ const ports: number[] = [];
+ for (const conn of asArray(payload.c)) {
+ if (typeof conn.LocalPort !== "number" || typeof conn.OwningProcess !== "number") continue;
+ if (tree.has(conn.OwningProcess)) ports.push(conn.LocalPort);
+ }
+ return ports;
+}
+
+/** Runs one probe child with the hard timeout; null on any failure (missing tool, non-zero exit, timeout). */
+function run(cmd: string, args: string[]): Promise<string | null> {
+ return new Promise((resolve) => {
+ execFile(
+ cmd,
+ args,
+ { timeout: PROBE_TIMEOUT_MS, windowsHide: true, encoding: "utf8" },
+ (err, stdout) => resolve(err ? null : stdout),
+ );
+ });
+}
+
+/**
+ * Ports the session's process group / tree is listening on. `null` = the probe failed
+ * ("don't know" — keep any previously known result); `[]` = it succeeded and found no
+ * listeners (a stale URL should clear). Deduplicated, ascending.
+ */
+export async function probeGroupListenPorts(
+ pid: number,
+ platform: NodeJS.Platform = process.platform,
+): Promise<number[] | null> {
+ let sockets: ListenSocket[] | null = null;
+ let owned: Set<number> | null = null;
+ if (platform === "linux") {
+ const [ps, ss] = await Promise.all([
+ run("ps", ["-o", "pid=", "-g", String(pid)]),
+ run("ss", ["-ltnp"]),
+ ]);
+ if (ps === null || ss === null) return null;
+ owned = new Set(parsePsPids(ps));
+ sockets = parseSsListenPorts(ss);
+ } else if (platform === "darwin") {
+ const out = await run("lsof", [
+ "-a",
+ "-g",
+ String(pid),
+ "-iTCP",
+ "-sTCP:LISTEN",
+ "-n",
+ "-P",
+ "-Fpn",
+ ]);
+ // lsof exits 1 when nothing matches; that is indistinguishable from failure here, so a
+ // null darwin probe conservatively reads as "don't know" rather than "no listeners".
+ if (out === null) return null;
+ sockets = parseLsofListenPorts(out);
+ } else if (platform === "win32") {
+ const script =
+ "@{c=@(Get-NetTCPConnection -State Listen|Select-Object LocalPort,OwningProcess);" +
+ "p=@(Get-CimInstance Win32_Process|Select-Object ProcessId,ParentProcessId)}" +
+ "|ConvertTo-Json -Depth 3 -Compress";
+ const out = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", script]);
+ if (out === null) return null;
+ const ports = parseWindowsProbe(out, pid);
+ return ports === null ? null : [...new Set(ports)].sort((a, b) => a - b);
+ } else {
+ return null;
+ }
+ const ports = new Set<number>();
+ for (const socket of sockets) {
+ if (owned === null || owned.has(socket.pid)) ports.add(socket.port);
+ }
+ return [...ports].sort((a, b) => a - b);
+}
diff --git a/packages/core/src/environment/tools/command/service-url.ts b/packages/core/src/environment/tools/command/service-url.ts
new file mode 100644
index 00000000..ecf57a71
--- /dev/null
+++ b/packages/core/src/environment/tools/command/service-url.ts
@@ -0,0 +1,79 @@
+/**
+ * Service-URL detection for command sessions: a dev server the conversation starts usually
+ * prints its local URL ("Local: http://localhost:5173/"). The session scans its own output
+ * stream as it is produced — core sees every chunk whether the command runs foreground or
+ * background, so detection never depends on the model polling or on what reaches the
+ * transcript. The scan is incremental: each chunk is inspected together with a small
+ * carry-over tail of the previous one, so a URL (or the ANSI escape wrapping it) split
+ * across chunk boundaries is still recognized; the LATEST hit wins — a server that
+ * restarts on another port replaces the earlier URL, and output that prints none leaves
+ * the last one standing.
+ */
+
+/**
+ * Local-service URL: only hosts that mean "this machine" — a link to a remote host in
+ * some log line is not the process's own service. Port and path are optional (a proxy on
+ * port 80 prints a bare origin).
+ */
+const LOCAL_URL_RE =
+ /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::\d{1,5})?(?:\/[^\s"'`<>()[\]]*)?/gi;
+
+/** ANSI CSI (colors, cursor) and OSC (title, hyperlink) sequences, which dev servers wrap around their URLs. */
+// eslint-disable-next-line no-control-regex
+const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
+
+/** Punctuation a sentence context glues onto a printed URL; the path's own trailing slash stays. */
+const TRAILING_PUNCT_RE = /[.,;:!?'"]+$/;
+
+function stripAnsi(text: string): string {
+ return text.replace(ANSI_RE, "");
+}
+
+/** `0.0.0.0` / `[::]` are listen-side wildcards, not clickable hosts; rewrite them to localhost. */
+function normalizeHost(url: string): string {
+ return url
+ .replace(/^(https?:\/\/)0\.0\.0\.0(?=[:/]|$)/i, "$1localhost")
+ .replace(/^(https?:\/\/)\[::\](?=[:/]|$)/i, "$1localhost");
+}
+
+/**
+ * The last local-service URL printed in `text`, ANSI-stripped, host-normalized and with
+ * sentence punctuation trimmed; null when the text prints none.
+ */
+export function extractLastLocalUrl(text: string): string | null {
+ const clean = stripAnsi(text);
+ let last: string | null = null;
+ for (const m of clean.matchAll(LOCAL_URL_RE)) {
+ const trimmed = m[0].replace(TRAILING_PUNCT_RE, "");
+ if (trimmed.length > 0) last = trimmed;
+ }
+ return last === null ? null : normalizeHost(last);
+}
+
+/**
+ * Carry-over tail (characters) re-scanned with the next chunk. Long enough for any
+ * realistic printed URL plus the ANSI wrapping around it; a match inside the carry that a
+ * later chunk extends (the boundary cut it mid-URL) simply re-matches longer and replaces
+ * itself under the latest-hit rule.
+ */
+const CARRY_CHARS = 256;
+
+/** Incremental scanner over one session's output stream (see the module doc). */
+export class ServiceUrlScanner {
+ private carry = "";
+ private latest: string | null = null;
+
+ /** Feeds one output chunk; cheap enough to sit on the write path (window ≤ carry + chunk). */
+ push(chunk: string): void {
+ if (chunk.length === 0) return;
+ const window = this.carry + chunk;
+ const found = extractLastLocalUrl(window);
+ if (found !== null) this.latest = found;
+ this.carry = window.length > CARRY_CHARS ? window.slice(window.length - CARRY_CHARS) : window;
+ }
+
+ /** The latest local-service URL the stream printed; null before any hit. */
+ get url(): string | null {
+ return this.latest;
+ }
+}
diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.ts
index 7c947d61..bc3e4d85 100644
--- a/packages/core/src/environment/tools/command/session.ts
+++ b/packages/core/src/environment/tools/command/session.ts
@@ -29,6 +29,8 @@ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import type { ToolResult } from "../types.js";
import { CappedTextBuffer, WakeSignal } from "../background/index.js";
import { sessionShell } from "./shell.js";
+import { ServiceUrlScanner } from "./service-url.js";
+import { probeGroupListenPorts } from "./port-probe.js";
/** Process-group semantics are available on POSIX; Windows falls back to signaling the child process directly. */
const SUPPORTS_PROCESS_GROUP = process.platform !== "win32";
@@ -167,6 +169,7 @@ export class ManagedSession {
}
private handleData(chunk: string): void {
+ this.urlScanner.push(chunk);
this.buffer.append(chunk);
this.wakeSignal.notify();
}
@@ -175,14 +178,86 @@ export class ManagedSession {
this.exited = true;
this.exitInfo = exit;
this.wakeSignal.notify();
+ this.fireExitWatchers();
}
private handleError(err: Error): void {
if (this.exited) return;
this.spawnError = err;
this.exited = true; // A spawn failure is also treated as a terminal state
this.wakeSignal.notify();
+ this.fireExitWatchers();
}
+ // One-shot exit watchers (run_in_background completion reports). Consumed on fire; a
+ // watcher armed after exit fires on a microtask, so the caller never misses a fast command.
+ private exitWatchers: Array<() => void> = [];
+ private fireExitWatchers(): void {
+ const watchers = this.exitWatchers;
+ this.exitWatchers = [];
+ for (const cb of watchers) cb();
+ }
+
+ /** Registers a one-shot callback for the foreground process's terminal state (exit or spawn failure); fires immediately (microtask) when already terminal. */
+ onceExited(cb: () => void): void {
+ if (this.exited) {
+ queueMicrotask(cb);
+ return;
+ }
+ this.exitWatchers.push(cb);
+ }
+
+ /** Clears armed exit watchers (a deliberate kill already reports its outcome synchronously, so the completion report is disarmed first). */
+ clearExitWatchers(): void {
+ this.exitWatchers = [];
+ }
+
+ /** Synchronously drains the yet-undelivered output (the same buffer `collect` serves) — used to build completion reports without an async window. */
+ drainPending(): string {
+ return this.buffer.drain();
+ }
+
+ // Service-URL detection, two sources with a fixed priority: the URL the process itself
+ // printed (incremental output scan — carries a path, always fresher in meaning) wins over
+ // the listen-port probe's synthesized origin (see port-probe.ts).
+ private readonly urlScanner = new ServiceUrlScanner();
+ private probedUrl: string | null = null;
+ private probedAt = 0;
+ private probeInFlight: Promise<void> | null = null;
+
+ /** The session's detected service URL: the last one its output printed, else the probed listen-port origin; null when neither source has one. */
+ get serviceUrl(): string | null {
+ return this.urlScanner.url ?? this.probedUrl;
+ }
+
+ /**
+ * Refreshes the listen-port probe when it could matter: only while running, only when the
+ * output scan has no hit, at most once per TTL, one probe in flight. Multiple listening
+ * ports collapse to the smallest — dev servers own one meaningful low port, while helper
+ * processes open ephemeral high ones, and the choice stays stable across probes. A failed
+ * probe ("don't know") keeps the previous result; a successful empty one clears it.
+ */
+ refreshServiceProbe(): Promise<void> {
+ if (!this.running || this.urlScanner.url !== null || this.pid === null) {
+ return Promise.resolve();
+ }
+ if (this.probeInFlight) return this.probeInFlight;
+ if (Date.now() - this.probedAt < ManagedSession.PROBE_TTL_MS) return Promise.resolve();
+ this.probeInFlight = probeGroupListenPorts(this.pid)
+ .then((ports) => {
+ this.probedAt = Date.now();
+ if (ports === null) return;
+ this.probedUrl = ports.length > 0 ? `http://localhost:${ports[0]}` : null;
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ this.probeInFlight = null;
+ });
+ return this.probeInFlight;
+ }
+
+ /** Probe cache TTL (ms): a fraction of the process panel's poll interval, so each poll refreshes at most one probe per session. */
+ private static readonly PROBE_TTL_MS = 5_000;
+
/** Whether the command is still running (hasn't exited, spawn hasn't failed). */
get running(): boolean {
return !this.exited;
diff --git a/packages/core/src/environment/tools/exec-command.ts b/packages/core/src/environment/tools/exec-command.ts
index f4ec85e7..95ef7ca0 100644
--- a/packages/core/src/environment/tools/exec-command.ts
+++ b/packages/core/src/environment/tools/exec-command.ts
@@ -24,7 +24,8 @@ import type { OmniMessage } from "../../omnimessage/index.js";
import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import { DEFAULT_EXEC_YIELD_MS, resultForExit } from "./command/index.js";
-import { clampYield } from "./background/index.js";
+import type { ManagedSession } from "./command/index.js";
+import { clampYield, reportLabel, tailForReport } from "./background/index.js";
/** Tool name constant (used only inside this tool module, not exposed to Environment). */
export const EXEC_COMMAND_NAME = "exec_command";
@@ -71,6 +72,7 @@ export function createExecCommandTool(
typeof rawWorkdir === "string" && rawWorkdir.length > 0
? path.resolve(ctx.workspaceDir, rawWorkdir)
: ctx.workspaceDir;
+ const background = args["run_in_background"] === true;
const yieldMs = clampYield(
args["yield_time_ms"],
DEFAULT_EXEC_YIELD_MS,
@@ -89,6 +91,21 @@ export function createExecCommandTool(
return { stopReason: "failed" };
}
+ // 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.
+ if (background) {
+ const id = manager.register(session);
+ armCommandDoneReport(session, id, services);
+ return {
+ 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]`,
+ };
+ }
+
// On interruption, kill the whole process group (background children included) to
// avoid orphans; once the process moves to background this listener is removed in finally.
const onAbort = (): void => session.kill();
@@ -121,3 +138,37 @@ 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
+ * disposed Environment drops the event (see Environment.emitBackgroundDone).
+ */
+export function armCommandDoneReport(
+ session: ManagedSession,
+ processId: string,
+ services?: EnvironmentServices,
+): void {
+ const notify = services?.backgroundDone;
+ if (!notify) return;
+ session.onceExited(() => {
+ const exit = session.exit;
+ const failed =
+ session.error !== null || exit?.signal != null || (exit !== null && exit.code !== 0);
+ const detail = session.error
+ ? `spawn error: ${session.error.message}`
+ : exit?.signal != null
+ ? `terminated by signal ${exit.signal}`
+ : `exit code ${exit?.code ?? "unknown"}`;
+ notify({
+ kind: "command",
+ id: processId,
+ label: reportLabel(session.cmd),
+ status: failed ? "failed" : "completed",
+ detail,
+ output: tailForReport(session.drainPending()),
+ });
+ });
+}
diff --git a/packages/core/src/environment/tools/kill-command.ts b/packages/core/src/environment/tools/kill-command.ts
new file mode 100644
index 00000000..2d6acbe8
--- /dev/null
+++ b/packages/core/src/environment/tools/kill-command.ts
@@ -0,0 +1,77 @@
+/**
+ * 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
new file mode 100644
index 00000000..44f879a0
--- /dev/null
+++ b/packages/core/src/environment/tools/kill-subagent.ts
@@ -0,0 +1,68 @@
+/**
+ * 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 f9cef066..6ff4119a 100644
--- a/packages/core/src/environment/tools/registry.ts
+++ b/packages/core/src/environment/tools/registry.ts
@@ -18,8 +18,10 @@ 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";
@@ -40,8 +42,10 @@ 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 67acd657..66ab0cc3 100644
--- a/packages/core/src/environment/tools/run-subagent.ts
+++ b/packages/core/src/environment/tools/run-subagent.ts
@@ -20,7 +20,9 @@
* Approval: `run_subagent` itself is a read-write tool (`rw`), so its invocation requires Human
* approval; the child session's tool approval requests are forwarded to the same Human within
* the window via the session's approval queue (tagged with origin), and queued for the next
- * access while running in the background. An interruption within the startup window kills the
+ * access while a promoted session runs in the background. A `run_in_background` launch instead
+ * attaches this call's own approval callback as a standing sink (see the branch below) — the
+ * child never parks waiting for a poll. An interruption within the startup window kills the
* child session per exec_command semantics; precheck errors such as exceeding the depth limit or
* a nonexistent agent are expressed by the runner as a throw, and collapsed to failed.
* Docs: /docs/tools § "Subagents".
@@ -40,7 +42,7 @@ import {
resultForSubagentExit,
} from "./subagent/index.js";
import { collectWindow } from "./subagent/collect.js";
-import { clampYield } from "./background/index.js";
+import { clampYield, reportLabel, tailForReport } from "./background/index.js";
/** Tool name constant (used only within this tool module, never exposed to Environment). */
export const SUBAGENT_NAME = "run_subagent";
@@ -111,6 +113,7 @@ export function createSubagentTool(
return { stopReason: "failed" };
}
const thinkingLevel = rawThinkingLevel as ThinkingLevelName | undefined;
+ const background = args.run_in_background === true;
const yieldMs = clampYield(
args.yield_time_ms,
DEFAULT_SUBAGENT_YIELD_MS,
@@ -145,6 +148,38 @@ export function createSubagentTool(
return { stopReason: "failed" };
}
+ // run_in_background: no collect window — register immediately, arm the completion
+ // 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
+ // forwarding tap below (its own Trace stays the durable record).
+ if (background) {
+ const id = manager.register(session);
+ armSubagentDoneReport(session, id, prompt, services);
+ // Decouple the child's lifecycle from this call: a standing approval sink (this
+ // call's own ctx.approve — without it the child's first read-write tool would park
+ // 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.
+ if (approve) session.setPersistentApprovalSink(approve);
+ const forward = services?.backgroundForward;
+ if (forward) session.setMessageTap(forward);
+ // Forward the child's session_meta upfront (run skips its own copy): the frontend's
+ // subagents panel and the server's subagent registry learn of the child at launch,
+ // not at the first input_subagent access.
+ const meta = session.takeMeta();
+ if (meta) yield meta;
+ session.startRun(prompt);
+ return {
+ 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]`,
+ };
+ }
+
// An interruption within the startup window kills the child session (consistent with
// exec_command); once switched to background, this listener is removed in `finally`.
const onAbort = (): void => session.kill();
@@ -183,3 +218,31 @@ 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).
+ */
+export function armSubagentDoneReport(
+ session: ManagedSubagentSession,
+ subagentId: string,
+ prompt: string,
+ services?: EnvironmentServices,
+): void {
+ const notify = services?.backgroundDone;
+ if (!notify) return;
+ session.onSettled(() => {
+ const exit = session.exit;
+ notify({
+ kind: "subagent",
+ id: subagentId,
+ label: reportLabel(prompt),
+ status: exit?.status ?? "completed",
+ detail: exit?.note ?? "",
+ output: tailForReport(session.drainText()),
+ });
+ });
+}
diff --git a/packages/core/src/environment/tools/subagent/session-manager.ts b/packages/core/src/environment/tools/subagent/session-manager.ts
index 8da66306..ac48e964 100644
--- a/packages/core/src/environment/tools/subagent/session-manager.ts
+++ b/packages/core/src/environment/tools/subagent/session-manager.ts
@@ -36,6 +36,16 @@ export class SubagentSessionManager {
return this.registry.makeRoom(false);
}
+ /**
+ * Whether any managed subagent session is mid-round. Hosts use it the same way they use a
+ * running background command: a child that outlives the call which launched it must keep
+ * its Session's runtime entry alive, or its completion report and live messages land on an
+ * object nobody holds any more.
+ */
+ hasRunning(): boolean {
+ return this.registry.list().some(({ task }) => task.running);
+ }
+
/**
* Registers a still-running session as a background session, allocating and returning a
* unique `subagent_id`: `subagent-<last 8 hex of child Session id>` (falls back to random on
@@ -56,6 +66,13 @@ 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 7c0e7dc4..af5e90ce 100644
--- a/packages/core/src/environment/tools/subagent/session.ts
+++ b/packages/core/src/environment/tools/subagent/session.ts
@@ -70,6 +70,21 @@ export class ManagedSubagentSession {
private sink: { approve: ApproveFn; detached: Promise<void> } | null = null;
private sinkEpoch = 0;
private pumpingApprovals = false;
+ /**
+ * Standing approval sink for background-launched sessions (`run_in_background`): the
+ * launching call's own `ctx.approve`, consulted whenever no window sink is attached. A
+ * background child has no parent tool call waiting on it, so without this its first
+ * read-write tool parks at the approval queue forever — the "background subagent's
+ * commands never run" failure. Window sinks (an active run_subagent/input_subagent
+ * call) still take precedence while attached.
+ */
+ private persistentApprove: ApproveFn | null = null;
+ /**
+ * Live forwarding tap for background-launched sessions: child messages go here the moment
+ * the pump produces them instead of waiting in the message buffer for the next poll. Set
+ * once at launch; anything already buffered flushes through it first (order preserved).
+ */
+ private forwardTap: ((msg: OmniMessage) => void) | null = null;
// Single wake point: new message / run finished / new approval request all wake a waiting waitWake through it.
private readonly wakeSignal = new WakeSignal();
@@ -83,6 +98,11 @@ export class ManagedSubagentSession {
return this.handle.sessionId;
}
+ /** One-shot take of the child's origin-tagged session_meta (see SubagentHandle.takeMeta); null when the handle predates the seam or the meta already went out. */
+ takeMeta(): OmniMessage | null {
+ return this.handle.takeMeta?.() ?? null;
+ }
+
/** Whether a round of the task is currently running. */
get running(): boolean {
return this.isRunning;
@@ -134,6 +154,41 @@ export class ManagedSubagentSession {
this.wakeSignal.notify();
}
+ // 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.
+ 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. */
+ onSettled(cb: () => void): void {
+ this.settleWatcher = cb;
+ if (!this.isRunning && this.exitInfo !== null) queueMicrotask(() => this.fireSettleWatcher());
+ }
+
+ /** Disarms the completion-report watcher (deliberate kill / dispose). */
+ clearSettleWatcher(): void {
+ this.settleWatcher = null;
+ }
+
+ /** Attaches the standing approval sink of a background launch (see persistentApprove) and drains anything already queued. */
+ setPersistentApprovalSink(approve: ApproveFn): void {
+ this.persistentApprove = approve;
+ void this.pumpApprovals();
+ }
+
+ /** 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;
+ this.messages = [];
+ this.forwardTap = tap;
+ for (const msg of backlog) tap(msg);
+ }
+
+ private fireSettleWatcher(): void {
+ const cb = this.settleWatcher;
+ if (cb && !this.killed) cb();
+ }
+
/** Waits for "woken up" or `ms` to expire, whichever comes first. */
async waitWake(ms: number): Promise<void> {
await this.wakeSignal.wait(ms);
@@ -232,10 +287,17 @@ export class ManagedSubagentSession {
this.isRunning = false;
if (this.killed) this.handle.dispose();
this.wakeSignal.notify();
+ this.fireSettleWatcher();
}
}
private bufferMessage(msg: OmniMessage): void {
+ // A live tap (background launch) replaces buffering outright: the frontend receives the
+ // message immediately, and a later poll must not deliver a second copy.
+ if (this.forwardTap) {
+ this.forwardTap(msg);
+ return;
+ }
this.messages.push(msg);
// Overflow drops the oldest: only affects frontend replay — the child Session's Trace and text buffer are unaffected.
if (this.messages.length > MESSAGE_BUFFER_CAP) this.messages.shift();
@@ -270,25 +332,36 @@ export class ManagedSubagentSession {
}
/**
- * Hands the request at the head of the queue to the currently attached approval sink, one at a
- * time. Stops when the window ends (the sink is detached); unresolved requests stay queued for
- * the next sink; if a consultation already in flight resolves late, the decision still takes
+ * Hands the request at the head of the queue to an approval sink, one at a time: the
+ * window sink of an active run_subagent/input_subagent call when attached, else the
+ * standing sink of a background launch (persistentApprove). A window consultation stops
+ * when the window ends (the sink is detached) — unresolved requests stay queued for the
+ * next sink; a standing consultation simply awaits the decision (there is no window to
+ * end). If a consultation already in flight resolves late, the decision still takes
* effect via settle.
*/
private async pumpApprovals(): Promise<void> {
if (this.pumpingApprovals) return;
this.pumpingApprovals = true;
try {
- while (this.sink && this.approvals.length > 0) {
- const sink = this.sink;
+ while ((this.sink !== null || this.persistentApprove !== null) && this.approvals.length > 0) {
const req = this.approvals[0]!;
+ const sink = this.sink;
+ if (sink === null) {
+ await this.persistentApprove!(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)
+ );
+ continue;
+ }
const answer = sink.approve(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)
+ () => this.settle(req, "deny"),
);
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
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 85acb1c0..924aca76 100644
--- a/packages/core/src/interfaces.ts
+++ b/packages/core/src/interfaces.ts
@@ -238,6 +238,14 @@ export interface LLMInterface {
export interface SubagentHandle {
/** The child Session's id: the origin hop of messages produced by run; `subagent_id` is derived from its tail for the frontend to correlate. */
sessionId: string;
+ /**
+ * One-shot take of the child's origin-tagged `session_meta`: a background launch
+ * (run_subagent with `run_in_background`) forwards it synchronously so hosts learn of the
+ * child before any collect window runs; `run` then skips its own meta forwarding. Null
+ * once taken (or once `run` already sent it). Optional — older embedders' handles simply
+ * leave background launches without an upfront meta.
+ */
+ takeMeta?(): OmniMessage | null;
/**
* Runs one turn of a task on the child Session. Emitted child-session messages **all already
* carry the origin marker** (the child Session id); the first message of the first run is the
@@ -331,6 +339,41 @@ export interface EnvironmentServices {
commandSessions?: CommandSessionManager;
/** Registry of background subagent sessions (shared by `run_subagent` / `input_subagent`); constructed and injected internally by Environment. */
subagentSessions?: SubagentSessionManager;
+ /**
+ * Sink for background-task completion reports (`run_in_background` launches): tools arm a
+ * completion watcher that calls this when the task settles; Environment forwards it to the
+ * listener the Session attached (see EnvironmentInterface.setBackgroundTaskListener).
+ * Injected internally by Environment.
+ */
+ backgroundDone?: (event: BackgroundTaskDoneEvent) => void;
+ /**
+ * Live forwarding sink for background-launched subagents: the child's origin-tagged
+ * messages flow here the moment its pump produces them, so hosts can stream them to the
+ * frontend past the launching turn's end (display copies only — the child's own Trace is
+ * the durable record). Injected internally by Environment; forwarded to the listener the
+ * Session attached (see EnvironmentInterface.setBackgroundMessageListener).
+ */
+ backgroundForward?: (msg: OmniMessage) => void;
+}
+
+/**
+ * Completion report of one background-launched task (`exec_command` / `run_subagent` with
+ * `run_in_background`), emitted when the task settles and delivered to the Session as a
+ * harness user message (see Session's background-notice queue).
+ */
+export interface BackgroundTaskDoneEvent {
+ /** Which background family settled. */
+ kind: "command" | "subagent";
+ /** The registry handle the model holds: `process_id` or `subagent_id`. */
+ id: string;
+ /** What was launched: the command string, or the subagent prompt's first line (display only, truncated by the producer). */
+ label: string;
+ /** Terminal status of the run. */
+ status: "completed" | "failed";
+ /** One-line terminal detail (exit code / signal / subagent note); empty when there is none. */
+ detail: string;
+ /** Tail of the yet-undelivered output at settle time (capped by the producer); empty when nothing was pending. */
+ output: string;
}
/** Docs: /docs/interfaces § "ToolExecutionRequest and EnvironmentConfig". */
@@ -405,6 +448,13 @@ export interface BackgroundCommandInfo {
cwd: string;
startedAt: number;
running: boolean;
+ /**
+ * The service the process serves, when one was detected: the last local URL its output
+ * printed (may carry a path), else `http://localhost:<port>` synthesized from a listen-port
+ * probe of its process group (refresh via `probeBackgroundCommandServices`). Absent when
+ * neither source has one.
+ */
+ serviceUrl?: string;
}
/**
@@ -426,6 +476,32 @@ export interface EnvironmentInterface {
listBackgroundCommands?(): BackgroundCommandInfo[];
/** Kills one background command process by id (whole process group); false when the id is unknown. Optional, like listBackgroundCommands. */
killBackgroundCommand?(processId: string): boolean;
+ /**
+ * Whether a background subagent session is mid-round. Hosts pin a Session's runtime entry
+ * on it: a `run_in_background` child outlives the call that launched it, and evicting the
+ * Session while it works strands its completion report and live messages. Optional, like
+ * listBackgroundCommands.
+ */
+ hasRunningBackgroundSubagents?(): boolean;
+ /**
+ * Refreshes the listen-port probe behind `BackgroundCommandInfo.serviceUrl` for running
+ * sessions whose output printed no URL (TTL-cached and time-bounded per session; see
+ * command/port-probe.ts). Hosts call it before reading the list when they want probed
+ * URLs; the list itself stays synchronous. Optional, like listBackgroundCommands.
+ */
+ probeBackgroundCommandServices?(): Promise<void>;
+ /**
+ * Attaches the single listener for background-task completion reports (`run_in_background`
+ * launches). Events fired before a listener exists are buffered and flushed on attach; after
+ * `dispose()` no further events fire. Optional — environments without background tools omit it.
+ */
+ setBackgroundTaskListener?(listener: (event: BackgroundTaskDoneEvent) => void): void;
+ /**
+ * Attaches the single listener for live-forwarded background-subagent messages (see
+ * EnvironmentServices.backgroundForward). Same buffering and dispose semantics as
+ * setBackgroundTaskListener. Optional.
+ */
+ setBackgroundMessageListener?(listener: (msg: OmniMessage) => void): void;
/** Releases runtime resources held by the environment (e.g. managed long-running command sessions); called by the host when the Session ends. Optional, idempotent. */
dispose?(): void;
}
diff --git a/packages/core/src/omnimessage/builders.ts b/packages/core/src/omnimessage/builders.ts
index 05caccee..5d994dd9 100644
--- a/packages/core/src/omnimessage/builders.ts
+++ b/packages/core/src/omnimessage/builders.ts
@@ -39,6 +39,7 @@ import type {
StreamEventType,
SubagentPayload,
TextPayload,
+ TextSender,
ThinkingPayload,
TokenCounts,
TokenUsagePayload,
@@ -95,7 +96,12 @@ export function textMessage(
});
}
-export const userText = (text: string): OmniMessage<TextPayload> => textMessage("user", text);
+/** User-role text. `sender` marks non-human origins (the parent agent's subagent prompt, a harness or server injection); omitted = the human user, and the field stays absent. */
+export const userText = (text: string, sender?: TextSender): OmniMessage<TextPayload> => {
+ const msg = textMessage("user", text);
+ if (sender !== undefined && sender !== "user") msg.payload.sender = sender;
+ return msg;
+};
export const assistantText = (
text: string,
diff --git a/packages/core/src/omnimessage/markers/origin-blocks.ts b/packages/core/src/omnimessage/markers/origin-blocks.ts
index fff5c4a1..e540260f 100644
--- a/packages/core/src/omnimessage/markers/origin-blocks.ts
+++ b/packages/core/src/omnimessage/markers/origin-blocks.ts
@@ -282,6 +282,70 @@ export function parseModelSwitchMessage(text: string): ModelSwitchOrigin | null
return origin.sessionId ? origin : null;
}
+// ---------------------------------------------------------------------------
+// [background_task_done] — completion report of a run_in_background task
+// ---------------------------------------------------------------------------
+
+/** Structured facts of one background-task completion (the block's field lines). */
+export interface BackgroundTaskDone {
+ /** Which background family finished. */
+ kind: "command" | "subagent";
+ /** The registry handle the model already holds: `process_id` or `subagent_id`. */
+ id: string;
+ /** Terminal status of the run. */
+ status: "completed" | "failed";
+ /** One-line terminal detail (exit code / signal / subagent note); empty when there is none. */
+ detail: string;
+}
+
+/**
+ * Harness-injected user message reporting that a background task finished (`exec_command` /
+ * `run_subagent` launched with `run_in_background`): the `[background_task_done]` block carries
+ * the structured facts, and the body after it is the display text — what the task was, followed
+ * by the tail of its yet-undelivered output (already capped by the producer). The frontend
+ * collapses the block into a one-line notice (the Trace page shows it verbatim); the model reads
+ * the whole thing.
+ */
+export function buildBackgroundTaskDoneMessage(done: BackgroundTaskDone, body: string): string {
+ const block = markerBlock(
+ MARKER_TAGS.backgroundTaskDone,
+ [
+ "Automatic notification from the harness, not the user: a background task you started has finished.",
+ `kind: ${done.kind}`,
+ `id: ${done.id}`,
+ `status: ${done.status}`,
+ ...(done.detail ? [`detail: ${done.detail}`] : []),
+ ].join("\n"),
+ );
+ return body ? `${block}\n\n${body}` : block;
+}
+
+const BACKGROUND_DONE_PATTERNS = dualFormPatterns(
+ MARKER_TAGS.backgroundTaskDone,
+ "\\n([\\s\\S]*?)\\n",
+);
+
+/**
+ * Inverse of `buildBackgroundTaskDoneMessage`: returns the completion facts and the body when
+ * the message **starts with** a `[background_task_done]` block, otherwise null. Prefix-block
+ * semantics like `[scheduled_task]`: the body after the block is returned for normal rendering.
+ */
+export function parseBackgroundTaskDoneMessage(
+ text: string,
+): { done: BackgroundTaskDone; rest: string } | null {
+ const m = matchDualForm(BACKGROUND_DONE_PATTERNS, text);
+ if (!m || m.index !== 0) return null;
+ const done: BackgroundTaskDone = { kind: "command", id: "", status: "completed", detail: "" };
+ for (const [key, value] of fieldLines(m[1]!, ["kind", "id", "status", "detail"])) {
+ if (key === "kind" && (value === "command" || value === "subagent")) done.kind = value;
+ else if (key === "id") done.id = value;
+ else if (key === "status" && (value === "completed" || value === "failed")) done.status = value;
+ else if (key === "detail") done.detail = value;
+ }
+ if (!done.id) return null;
+ return { done, rest: text.slice(m[0].length).replace(/^\n+/, "") };
+}
+
// ---------------------------------------------------------------------------
// Shared predicate over the whole-message origin blocks
// ---------------------------------------------------------------------------
diff --git a/packages/core/src/omnimessage/markers/tags.ts b/packages/core/src/omnimessage/markers/tags.ts
index df5a79a8..edb4ddf7 100644
--- a/packages/core/src/omnimessage/markers/tags.ts
+++ b/packages/core/src/omnimessage/markers/tags.ts
@@ -25,6 +25,8 @@ export const MARKER_TAGS = {
handoffFrom: "handoff_from",
/** Scheduled-task trigger origin block (server scheduler). */
scheduledTask: "scheduled_task",
+ /** Background-task completion report injected as a harness user message (exec_command / run_subagent with run_in_background). */
+ backgroundTaskDone: "background_task_done",
/** `/model` switch origin block, first message of the continued conversation (Web). */
modelSwitchFrom: "model_switch_from",
/** AGENTS.md wrapper inside the system prompt (static template text). */
@@ -52,4 +54,5 @@ export const TITLE_NOISE_TAGS: readonly string[] = [
MARKER_TAGS.scheduledTask,
MARKER_TAGS.modelSwitchFrom,
MARKER_TAGS.goal,
+ MARKER_TAGS.backgroundTaskDone,
];
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index 3ae0f010..539f7aa0 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -123,10 +123,22 @@ export interface SessionMetaPayload {
*/
export type Fidelity = Record<string, unknown>;
+/**
+ * Who produced a user-role text: the human user, the parent agent driving a subagent session
+ * (run_subagent / input_subagent prompts, `"parent_agent"`), the harness's automatic
+ * injections (background-task completion reports, `"harness"`), or the hosting server's own
+ * triggers (scheduled tasks, `"server"`). Absent = `"user"` — Traces written before this
+ * field existed carry only human input on the user side, so the default is also the
+ * historically correct reading.
+ */
+export type TextSender = "user" | "parent_agent" | "harness" | "server";
+
export interface TextPayload {
type: "text";
role: Role;
text: string;
+ /** Origin of a user-role text (never sent to the provider); absent = the human user. See {@link TextSender}. */
+ sender?: TextSender;
stop_reason?: StopReason;
/** Provider-fidelity payload (e.g. `phase` for GPT-5 segment markers, `signature`), kept as-is and restored verbatim. */
fidelity?: Fidelity;
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index 0bbba59a..98d16e18 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -19,10 +19,12 @@
*/
import {
abortEvent,
+ buildBackgroundTaskDoneMessage,
mcpConnectBegin,
mcpConnectEnd,
sessionMeta,
toolListReady,
+ userText,
} from "./omnimessage/index.js";
import type {
McpServerConnectResult,
@@ -36,6 +38,7 @@ import { runGoalLoop } from "./goal/goal-loop.js";
import { goalFinishedOf } from "./goal/goal-stream.js";
import type {
BackgroundCommandInfo,
+ BackgroundTaskDoneEvent,
EnvironmentInterface,
LLMInterface,
ToolPermission,
@@ -160,6 +163,28 @@ function raceAbort<T>(
const TITLE_USER_MATERIAL_LIMIT = 2000;
const TITLE_ASSISTANT_MATERIAL_LIMIT = 1000;
+/**
+ * A background-task completion event as the harness user message that reports it: the
+ * `[background_task_done]` block carries the structured facts, the body the display text —
+ * what settled, then the tail of its yet-undelivered output. `sender: "harness"` marks the
+ * non-human origin in the Trace.
+ */
+function backgroundDoneNotice(event: BackgroundTaskDoneEvent): OmniMessage {
+ const what = event.kind === "command" ? "Background command" : "Background subagent";
+ const idField = event.kind === "command" ? "process_id" : "subagent_id";
+ const verb = event.status === "completed" ? "finished" : "failed";
+ const detail = event.detail ? ` — ${event.detail}` : "";
+ const head = `${what} ${verb}: \`${event.label}\` (${idField} ${event.id})${detail}`;
+ const body = event.output.trim() ? `${head}\n\n${event.output}` : head;
+ return userText(
+ buildBackgroundTaskDoneMessage(
+ { kind: event.kind, id: event.id, status: event.status, detail: event.detail },
+ body,
+ ),
+ "harness",
+ );
+}
+
/**
* Accumulates title material: the body text of complete text messages from the main session
* (no origin) — thinking and tool calls naturally don't count — and stops once the cap is hit.
@@ -233,6 +258,19 @@ export class Session {
private titleAssistantText = "";
/** Material-frozen flag: becomes true once the first Task containing user text finishes; subsequent runs stop accumulating. */
private titleMaterialFrozen = false;
+ /**
+ * Background-task completion notices not yet delivered (harness user messages built from
+ * the Environment's completion events). Single source of truth for delivery: a running
+ * Task's engine drains it at every input-assembly boundary (yield + Trace write + request
+ * input); an idle Session fires `noticeListener` so the host can take the queue
+ * (`takeBackgroundNotices`) and submit it as an ordinary task — whichever consumes first,
+ * each notice is delivered exactly once. With neither, the next run's start drains it.
+ */
+ private pendingNotices: OmniMessage[] = [];
+ /** Idle-arrival signal for the host (see `onBackgroundNotice`); null until a host subscribes. */
+ private noticeListener: (() => void) | null = null;
+ /** Live background-subagent message subscriber (see `onBackgroundMessage`); null until a host subscribes — messages are display copies and drop without one. */
+ private bgMessageListener: ((msg: OmniMessage) => void) | null = null;
constructor(config: SessionConfig) {
this.sessionId = config.meta.session_id;
@@ -270,7 +308,20 @@ export class Session {
// isn't given the function, which is all the engine needs to know about the subject.
...(config.modelHasVision ? {} : { foldInputImages: this.foldImages }),
sessionMeta: this.meta,
+ // Background completion notices: the engine pulls from the Session's queue at every
+ // input-assembly boundary (see pendingNotices for the exactly-once contract).
+ backgroundNotices: {
+ drain: () => this.pendingNotices.splice(0),
+ pending: () => this.pendingNotices.length,
+ },
};
+ // Completion events of run_in_background launches flow from the Environment into the
+ // notice queue (events fired before this attach are buffered by the Environment).
+ config.environment.setBackgroundTaskListener?.((event) => this.handleBackgroundDone(event));
+ // Live-forwarded background-subagent messages flow straight to the host's subscriber —
+ // display copies only (the child's own Trace is the durable record), so with no
+ // subscriber they are simply dropped.
+ config.environment.setBackgroundMessageListener?.((msg) => this.bgMessageListener?.(msg));
}
/**
@@ -695,11 +746,62 @@ export class Session {
return this.environment.listBackgroundCommands?.() ?? [];
}
+ /** Refreshes the listen-port probes behind `BackgroundCommandInfo.serviceUrl` (see EnvironmentInterface.probeBackgroundCommandServices). No-op for environments without it. */
+ async probeBackgroundCommandServices(): Promise<void> {
+ await this.environment.probeBackgroundCommandServices?.();
+ }
+
/** Kills one of this Session's background command processes (whole process group); false when the id is unknown. */
killBackgroundCommand(processId: string): boolean {
return this.environment.killBackgroundCommand?.(processId) ?? false;
}
+ /** Whether a background subagent of this Session is mid-round (see EnvironmentInterface.hasRunningBackgroundSubagents). */
+ hasRunningBackgroundSubagents(): boolean {
+ return this.environment.hasRunningBackgroundSubagents?.() ?? false;
+ }
+
+ /** Queues a background completion event as a harness user notice; a running Task delivers it at the next boundary, otherwise the host is signaled (see pendingNotices). */
+ private handleBackgroundDone(event: BackgroundTaskDoneEvent): void {
+ this.pendingNotices.push(backgroundDoneNotice(event));
+ if (!(this.engine?.isTaskRunning ?? false)) this.noticeListener?.();
+ }
+
+ /**
+ * Subscribes the host's idle-arrival signal for background completion notices: called
+ * (without payload) whenever a notice is queued while no Task is running. The host then
+ * takes the queue with `takeBackgroundNotices` and submits it as an ordinary task — a host
+ * that never subscribes still gets delivery on the next run's start. One listener; a later
+ * call replaces the earlier one.
+ */
+ onBackgroundNotice(listener: () => void): void {
+ this.noticeListener = listener;
+ }
+
+ /**
+ * Takes the queued background completion notices (harness user messages) for submission as
+ * a task's input. Empties the queue — the caller owns delivery of what it took; anything
+ * queued after this call is signaled/drained separately.
+ */
+ takeBackgroundNotices(): OmniMessage[] {
+ return this.pendingNotices.splice(0);
+ }
+
+ /** Whether completion notices are still queued (hosts use it to keep a Session's runtime entry alive until they are delivered). */
+ hasPendingBackgroundNotices(): boolean {
+ return this.pendingNotices.length > 0;
+ }
+
+ /**
+ * Subscribes the host to live-forwarded background-subagent messages (origin-tagged, the
+ * same stream a foreground collect window would relay): the server publishes them to the
+ * session's event channel so the frontend sees a background child working in real time.
+ * One listener; a later call replaces the earlier one.
+ */
+ onBackgroundMessage(listener: (msg: OmniMessage) => void): void {
+ this.bgMessageListener = listener;
+ }
+
/**
* Releases runtime resources held by the Session: kills long-running command sessions
* managed by the Environment. The host calls this when the Session ends (CLI exit, Web
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 9ecfdff2..8040d02e 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -684,6 +684,11 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
description:
"How long to wait for the command before yielding. If it is still running when this elapses, the tool returns the output so far plus a process_id, and the command keeps running in the background (drive it with input_command). Defaults to 60000; minimum 250, capped below the tool timeout.",
},
+ 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.",
+ },
},
required: ["description", "cmd"],
},
@@ -716,7 +721,7 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
yield_time_ms: {
type: "number",
description:
- "How long to wait for new output or exit before returning. Non-empty writes default to 250; empty polls default to 5000. Minimum 250, capped below the tool timeout.",
+ "How long to wait for new output or exit before returning. Non-empty writes default to 250; empty polls default to 120000 so one poll waits out most builds (output still streams as it arrives, and the wait ends early on exit — pass a smaller value to peek at a long-lived process). Minimum 250, capped below the tool timeout.",
},
},
required: ["description", "process_id"],
@@ -727,6 +732,30 @@ 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:
@@ -771,6 +800,11 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {
description:
"How long to wait for the subagent before yielding. If it is still working when this elapses, the tool returns the output so far plus a subagent_id, and the subagent keeps running in the background (drive it with input_subagent). Defaults to 300000; minimum 250, capped below the tool timeout.",
},
+ 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.",
+ },
},
required: ["description", "prompt"],
},
@@ -815,6 +849,30 @@ 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 3b2e12db..5d2736f5 100644
--- a/packages/core/src/state/kernel-history.ts
+++ b/packages/core/src/state/kernel-history.ts
@@ -26,7 +26,7 @@ import type { SystemConfig } from "./default-config.js";
* pinned-hash test enforces both directions (bump without new hashes, or changed defaults
* without a bump, both fail).
*/
-export const KERNEL_VERSION = "2026-08-20";
+export const KERNEL_VERSION = "2026-08-21";
/**
* Identity / user-data fields excluded from kernel management: never hashed, never written
@@ -145,9 +145,13 @@ export function isKernelOutdated(kernelVersion: string | null | undefined): bool
* (issue #306): only the `tools.builtin.run_subagent` leaf changed.
* - `"2026-08-19"` — the `max` thinking level joined the ladder, widening `run_subagent`'s
* `thinking_level` enum: again only the `tools.builtin.run_subagent` leaf changed.
- * - `"2026-08-20"` (current) — the seeded `compaction.max_context_length` rose to 256000,
- * with the per-model `context_window` cap as its backstop: only the
+ * - `"2026-08-20"` — the seeded `compaction.max_context_length` rose to 256000, with the
+ * per-model `context_window` cap as its backstop: only the
* `compaction.max_context_length` leaf changed.
+ * - `"2026-08-21"` (current) — 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 (five `tools.builtin.*` leaves
+ * changed or appeared).
*
* Generations older than the seeded ones cannot be fully reconstructed; their values match
* no recorded hash and are conservatively kept by a kernel update (restore-default-config is
@@ -328,6 +332,46 @@ export const KERNEL_HASH_HISTORY: Readonly<Record<string, Readonly<Record<string
"tools.builtin.describe_image":
"fad6d0cdd483eb53b5d243c0508024ab3b708ce6d3c81933acd291f05d4a265f",
},
+ "2026-08-21": {
+ system_prompt: "de8952daede04db17400c5cd59b279eccf523cf2d8a0ecedfa37a96de7925b44",
+ max_turns: "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "model.max_tokens": "492f431bae35265f2e5f4ed49bd8c58dda912431be561504846988d00d05d117",
+ "model.thinking_level": "60d4c90eee5e731df8d3ef2891de541d2e755ff8ee9db358e26bdec49f6e0db9",
+ "model.timeoutMs": "4f9f73b34c5b89879aad65a48025f3187dd9ce6dc3d4e88eecb2fc79227350f1",
+ "compaction.max_context_length":
+ "b412afcc00967650c9e51efd8cdc35ae59d3d6c30234331b7bf75b382d982ee9",
+ "compaction.max_session_turns":
+ "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "compaction.mode": "e58fac0b4b9c0f29b3d224da119dff5f6517a40d139faf92e309705b98bd410a",
+ "compaction.prompt": "8ed55781e8071083f8246ed70d9e063ee729d3872d5bc6a2bedfa9c99aed6ae5",
+ "memory.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "memory.prompt": "9380e2382e5dd3d37a6470b0bc0d27c9ed113fa9a54ff78122784c57a16b992c",
+ "memory.workspace_prompt": "76c5a8e18a568f471593ef1da6d75d2596f27619cb877703b2dd28bb0554e0d5",
+ "vault.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "vault.prompt": "66e607aa4e205413f1816a677bed31af2d8c24218e71b55adba54aff5aa094ce",
+ "skills.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "skills.prompt": "42934d17f5dd9c02dfa7c1d37f255dea92bd36905c96a54775c65ef7db713bd9",
+ "schedules.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "schedules.prompt": "3c690ff9bb3e4d423b2d5dfce74f5890d52bf8ae159cfe135a671ac3d46da75a",
+ "tools.builtin.read_file": "858f128945421043f5f373c908a0ee081e93e9413debaa49c8c7af1c1c76db3c",
+ "tools.builtin.edit_file": "165a3e2dabe3d13200a1670f3c23ed2d6561c508439db1972db066719f3549ef",
+ "tools.builtin.write_file": "c98253bd5a3b6ff021accda91af016a809a9b50ce56f38a3ed60eeb673c0b130",
+ "tools.builtin.exec_command":
+ "c7cf0639eb9434b2eecdd064aabeead52e22c966ddce348f987c744e93f9686f",
+ "tools.builtin.input_command":
+ "071daddb34cba05556cda2b6a87d18d5bd73fb863e6e3bd62f033626fbabf017",
+ "tools.builtin.kill_command":
+ "1d35d3be0408349c0bb099c442abfde3975c720e2c85cda3c2b749b359bef891",
+ "tools.builtin.run_subagent":
+ "6d890081b3dcd0405bab35590ee5d85c1ffa4815faf3b1b4de62b2617da77ec6",
+ "tools.builtin.input_subagent":
+ "22cc4648d773e8422e80a12a7a095b00b7f7eb01ab5a9ea080858dcd7517b4e3",
+ "tools.builtin.kill_subagent":
+ "8d8c11a1ae565b9b8334a498c5fc5b8903a2f657ac4e46d1c3dc9b7288e12ce4",
+ "tools.builtin.read_image": "05b797a88df1e6a90fb3da67ec654b206f8d81291f89d160a505620afcea38bb",
+ "tools.builtin.describe_image":
+ "fad6d0cdd483eb53b5d243c0508024ab3b708ce6d3c81933acd291f05d4a265f",
+ },
};
/**
diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.ts
new file mode 100644
index 00000000..f9df3794
--- /dev/null
+++ b/packages/core/test/background-execution.test.ts
@@ -0,0 +1,654 @@
+/**
+ * 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
+ * `sender` marking on user texts.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+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";
+import {
+ abortEvent,
+ assistantText,
+ buildBackgroundTaskDoneMessage,
+ emptyTokenCounts,
+ parseBackgroundTaskDoneMessage,
+ partialText,
+ stripLeadingMarkerBlocks,
+ toolCall,
+ tokenUsage,
+ userText,
+} from "../src/omnimessage/index.js";
+import { Session } from "../src/index.js";
+import type {
+ OmniMessage,
+ SessionMetaPayload,
+ TextPayload,
+ ToolCallPayload,
+} from "../src/omnimessage/index.js";
+import type {
+ ApproveFn,
+ BackgroundTaskDoneEvent,
+ EnvironmentInterface,
+ GenerativeModelParameters,
+ LLMInterface,
+ LLMOutcome,
+ SubagentHandle,
+ SubagentRunner,
+ ToolConfig,
+ ToolDefinitionConfig,
+} from "../src/interfaces.js";
+import type { ToolExecutionContext } from "../src/environment/tools/types.js";
+
+// ---------------------------------------------------------------------------
+// Shared helpers
+// ---------------------------------------------------------------------------
+
+function toolDef(name: string, extra: Partial<ToolDefinitionConfig> = {}): ToolDefinitionConfig {
+ return {
+ name,
+ description: `${name} test`,
+ permission: "rw",
+ maxOutputLength: 16000,
+ ...extra,
+ };
+}
+
+function commandToolConfig(): ToolConfig {
+ return {
+ customTools: [toolDef("exec_command"), toolDef("input_command"), toolDef("kill_command")],
+ mcpServers: [],
+ };
+}
+
+interface FinalOutput {
+ output: string;
+ stopReason?: string;
+}
+
+async function runTool(
+ env: Environment,
+ name: string,
+ args: Record<string, unknown>,
+): Promise<FinalOutput> {
+ let last: OmniMessage | null = null;
+ for await (const msg of env.executeTool({
+ toolCall: toolCall({ name, arguments: JSON.stringify(args), toolCallId: `call_${name}` }),
+ })) {
+ if ((msg.payload as { type?: string }).type === "tool_call_output") last = msg;
+ }
+ const p = (last?.payload ?? {}) as { output?: string; stop_reason?: string };
+ return { output: p.output ?? "", stopReason: p.stop_reason };
+}
+
+function extractProcessId(output: string): string {
+ const m = output.match(/process_id (proc-[0-9a-f]+)/);
+ expect(m, `expected a process_id in: ${JSON.stringify(output)}`).toBeTruthy();
+ return m![1]!;
+}
+
+const cleanups: Array<() => Promise<void> | void> = [];
+afterEach(async () => {
+ while (cleanups.length) await cleanups.pop()!();
+});
+
+async function makeEnv(): Promise<{ env: Environment; dir: string }> {
+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-bg-"));
+ const env = new Environment({ workspaceDir: dir, toolConfig: commandToolConfig() });
+ cleanups.push(async () => {
+ env.dispose();
+ // Retries: background commands keep this dir as their cwd, and on Windows a just-killed
+ // process releases that lock asynchronously — an immediate recursive rm hits EBUSY.
+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
+ });
+ return { env, dir };
+}
+
+/** Waits until the predicate holds (events arrive from real process exits). */
+async function waitFor(pred: () => boolean, timeoutMs = 5000): Promise<void> {
+ await vi.waitFor(
+ () => {
+ if (!pred()) throw new Error("condition not met yet");
+ },
+ { timeout: timeoutMs, interval: 20 },
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Marker block and sender field
+// ---------------------------------------------------------------------------
+
+describe("[background_task_done] marker and the sender field", () => {
+ it("build/parse round-trips the completion facts and the body", () => {
+ const text = buildBackgroundTaskDoneMessage(
+ { kind: "command", id: "proc-12ab34cd", status: "failed", detail: "exit code 2" },
+ "`pnpm test` — exit code 2\n\ntail output",
+ );
+ const parsed = parseBackgroundTaskDoneMessage(text);
+ expect(parsed).not.toBeNull();
+ expect(parsed!.done).toEqual({
+ kind: "command",
+ id: "proc-12ab34cd",
+ status: "failed",
+ detail: "exit code 2",
+ });
+ expect(parsed!.rest).toBe("`pnpm test` — exit code 2\n\ntail output");
+ // Detail omitted -> parsed back as empty.
+ const bare = buildBackgroundTaskDoneMessage(
+ { kind: "subagent", id: "subagent-1", status: "completed", detail: "" },
+ "",
+ );
+ expect(parseBackgroundTaskDoneMessage(bare)!.done.detail).toBe("");
+ });
+
+ it("only parses as a leading block, and the title stripper removes it", () => {
+ const block = buildBackgroundTaskDoneMessage(
+ { kind: "command", id: "proc-1", status: "completed", detail: "" },
+ "body",
+ );
+ expect(parseBackgroundTaskDoneMessage(`hello\n${block}`)).toBeNull();
+ expect(stripLeadingMarkerBlocks(block)).toBe("body");
+ });
+
+ it("userText marks non-human senders and leaves human input unmarked", () => {
+ expect((userText("hi").payload as TextPayload).sender).toBeUndefined();
+ expect((userText("hi", "user").payload as TextPayload).sender).toBeUndefined();
+ expect((userText("hi", "parent_agent").payload as TextPayload).sender).toBe("parent_agent");
+ expect((userText("hi", "harness").payload as TextPayload).sender).toBe("harness");
+ expect((userText("hi", "server").payload as TextPayload).sender).toBe("server");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// exec_command run_in_background + kill_command
+// ---------------------------------------------------------------------------
+
+describe("exec_command run_in_background", () => {
+ it("returns a process_id immediately and reports completion with the output tail", async () => {
+ const { env } = await makeEnv();
+ const events: BackgroundTaskDoneEvent[] = [];
+ env.setBackgroundTaskListener((e) => events.push(e));
+ const res = await runTool(env, "exec_command", {
+ cmd: "printf 'bg output'; exit 0",
+ run_in_background: true,
+ });
+ expect(res.stopReason).toBe("completed");
+ const id = extractProcessId(res.output);
+ expect(res.output).toContain("will arrive as a user message");
+ await waitFor(() => events.length === 1);
+ const e = events[0]!;
+ expect(e).toMatchObject({ kind: "command", id, status: "completed", detail: "exit code 0" });
+ expect(e.output).toContain("bg output");
+ expect(e.label).toContain("printf 'bg output'");
+ });
+
+ it("reports a non-zero exit as failed with the exit code", async () => {
+ const { env } = await makeEnv();
+ const events: BackgroundTaskDoneEvent[] = [];
+ env.setBackgroundTaskListener((e) => events.push(e));
+ await runTool(env, "exec_command", { cmd: "exit 3", run_in_background: true });
+ await waitFor(() => events.length === 1);
+ expect(events[0]).toMatchObject({ status: "failed", detail: "exit code 3" });
+ });
+
+ it("buffers events fired before the listener attaches", async () => {
+ const { env } = await makeEnv();
+ const res = await runTool(env, "exec_command", {
+ cmd: "printf early; exit 0",
+ run_in_background: true,
+ });
+ extractProcessId(res.output);
+ // Let the process exit with no listener attached, then attach.
+ await new Promise((r) => setTimeout(r, 300));
+ const events: BackgroundTaskDoneEvent[] = [];
+ env.setBackgroundTaskListener((e) => events.push(e));
+ await waitFor(() => events.length === 1);
+ expect(events[0]!.output).toContain("early");
+ });
+
+ it("kill_command terminates a running background command without a completion report", async () => {
+ const { env } = await makeEnv();
+ const events: BackgroundTaskDoneEvent[] = [];
+ env.setBackgroundTaskListener((e) => events.push(e));
+ const res = await runTool(env, "exec_command", {
+ cmd: "printf 'pre http://localhost:5199/\\n'; sleep 30",
+ run_in_background: true,
+ });
+ const id = extractProcessId(res.output);
+ // Wait for the pre-kill output to reach the session buffer kill_command drains. A fixed
+ // sleep raced the pipe on loaded Windows runners, and that buffer is not readable without
+ // draining it — so wait on the URL scanner instead: ManagedSession pushes each chunk to
+ // 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 });
+ expect(killed.stopReason).toBe("completed");
+ expect(killed.output).toContain("pre");
+ expect(killed.output).toContain(`process ${id} killed`);
+ // The kill-caused exit must not masquerade as a task completion.
+ 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 });
+ expect(again.stopReason).toBe("failed");
+ });
+
+ it("kill_command fails on an unknown process_id", async () => {
+ const { env } = await makeEnv();
+ const res = await runTool(env, "kill_command", { process_id: "proc-deadbeef" });
+ expect(res.stopReason).toBe("failed");
+ expect(res.output).toContain("unknown process_id");
+ });
+
+ it("dispose suppresses pending completion reports", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-bg-"));
+ cleanups.push(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }));
+ const env = new Environment({ workspaceDir: dir, toolConfig: commandToolConfig() });
+ const events: BackgroundTaskDoneEvent[] = [];
+ env.setBackgroundTaskListener((e) => events.push(e));
+ await runTool(env, "exec_command", { cmd: "sleep 30", run_in_background: true });
+ env.dispose(); // kills the process; its exit must not report
+ await new Promise((r) => setTimeout(r, 400));
+ expect(events).toHaveLength(0);
+ });
+});
+
+describe("input_command defaults", () => {
+ it("the default empty-poll wait is 120000ms", () => {
+ expect(DEFAULT_EMPTY_POLL_YIELD_MS).toBe(120_000);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// run_subagent run_in_background + kill_subagent (fake runner)
+// ---------------------------------------------------------------------------
+
+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";
+
+type RunInput = { prompt: string; signal?: AbortSignal; approve?: ApproveFn };
+
+function runnerOf(run: (input: RunInput) => AsyncGenerator<OmniMessage>): SubagentRunner {
+ return {
+ async spawn() {
+ // Mirrors the composition layer's one-shot meta seam (SubagentHandle.takeMeta).
+ let metaSent = false;
+ const handle: SubagentHandle = {
+ sessionId: HOP,
+ takeMeta() {
+ if (metaSent) return null;
+ metaSent = true;
+ return withHop({
+ timestamp: new Date().toISOString(),
+ type: "session_meta",
+ payload: { session_id: HOP },
+ } as unknown as OmniMessage);
+ },
+ run,
+ dispose() {},
+ };
+ return handle;
+ },
+ };
+}
+
+async function drive(
+ tool: ReturnType<typeof createSubagentTool>,
+ args: Record<string, unknown>,
+ ctx: ToolExecutionContext = CTX,
+): Promise<{ output: string; stopReason?: string; note: string; yielded: OmniMessage[] }> {
+ const gen = tool.execute(args, ctx);
+ let output = "";
+ const yielded: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) {
+ const r = res.value ?? undefined;
+ return { output, stopReason: r?.stopReason, note: r?.note ?? "", yielded };
+ }
+ yielded.push(res.value);
+ const p = res.value.payload as { type?: string; event_type?: string; output?: string };
+ if (p.type === "partial_tool_call_output" && p.event_type === "delta" && p.output) {
+ output += p.output;
+ }
+ }
+}
+
+function extractSubagentId(text: string): string {
+ const m = text.match(/subagent_id (subagent-[0-9a-f]+)/);
+ expect(m, `expected a subagent_id in: ${JSON.stringify(text)}`).toBeTruthy();
+ return m![1]!;
+}
+
+describe("run_subagent run_in_background", () => {
+ it("returns a subagent_id immediately and reports each round's completion", async () => {
+ const manager = new SubagentSessionManager();
+ cleanups.push(() => manager.dispose());
+ // Each round blocks on its own gate, so the test controls when a round settles.
+ 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}`));
+ });
+ 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: "long analysis task",
+ run_in_background: true,
+ });
+ expect(res.stopReason).toBe("completed");
+ const id = extractSubagentId(res.note);
+ expect(res.note).toContain("will arrive as a user message");
+ // The child's session_meta is forwarded at launch (origin-tagged), so the frontend's
+ // subagents panel and the server's registry learn of it before any poll.
+ const metas = res.yielded.filter((m) => m.type === "session_meta");
+ expect(metas).toHaveLength(1);
+ expect(metas[0]!.origin).toEqual([HOP]);
+ expect(events).toHaveLength(0); // still running behind the gate
+ // A mid-round child pins its Session's runtime entry against idle eviction: evicting it
+ // would strand the completion report and the live message stream.
+ expect(manager.hasRunning()).toBe(true);
+ await waitFor(() => gates.has("long analysis task"));
+ gates.get("long analysis task")!();
+ await waitFor(() => events.length === 1);
+ expect(manager.hasRunning()).toBe(false);
+ expect(events[0]).toMatchObject({ kind: "subagent", id, status: "completed" });
+ expect(events[0]!.output).toContain("answer to: long analysis task");
+ expect(events[0]!.label).toBe("long analysis task");
+
+ // A follow-up round through input_subagent that outlives the poll window reports again
+ // on settle, carrying the text the window never delivered.
+ const input = createInputSubagentTool(SUB_INPUT_DEF, services);
+ const follow = await drive(input, {
+ subagent_id: id,
+ prompt: "second round",
+ yield_time_ms: 250,
+ });
+ expect(follow.stopReason).toBe("completed");
+ expect(follow.note).toContain("still running");
+ await waitFor(() => gates.has("second round"));
+ gates.get("second round")!();
+ await waitFor(() => events.length === 2);
+ expect(events[1]!.output).toContain("answer to: second round");
+ });
+
+ it("kill_subagent aborts a running background subagent without a completion report", async () => {
+ const manager = new SubagentSessionManager();
+ cleanups.push(() => manager.dispose());
+ const runner = runnerOf(async function* ({ signal }) {
+ await new Promise<void>((resolve) => {
+ if (signal?.aborted) return resolve();
+ signal?.addEventListener("abort", () => resolve(), { once: true });
+ });
+ yield withHop(assistantText("late"));
+ });
+ 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: "will be killed", 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();
+ await new Promise((r) => setTimeout(r, 100));
+ expect(events).toHaveLength(0);
+ });
+
+ it("a failing background subagent still reports (status failed) and taps its messages live", async () => {
+ const manager = new SubagentSessionManager();
+ cleanups.push(() => manager.dispose());
+ const runner = runnerOf(async function* () {
+ // A child-session failure surfaces as an origin-tagged abort event, never a throw.
+ yield withHop(abortEvent("llm request failed after 5 retries"));
+ });
+ const events: BackgroundTaskDoneEvent[] = [];
+ const tapped: OmniMessage[] = [];
+ const services = {
+ subagentRunner: runner,
+ subagentSessions: manager,
+ backgroundDone: (e: BackgroundTaskDoneEvent) => events.push(e),
+ backgroundForward: (m: OmniMessage) => tapped.push(m),
+ };
+ const tool = createSubagentTool(SUB_DEF, services);
+ const res = await drive(tool, { prompt: "will fail", run_in_background: true });
+ extractSubagentId(res.note);
+ await waitFor(() => events.length === 1);
+ expect(events[0]).toMatchObject({ kind: "subagent", status: "failed" });
+ expect(events[0]!.detail).toContain("aborted");
+ // The failure event reached the live tap too (origin-tagged), not a poll buffer.
+ expect(tapped.some((m) => (m.payload as { type?: string }).type === "abort")).toBe(true);
+ });
+
+ it("a background child's approvals resolve through the launching call's standing sink", async () => {
+ const manager = new SubagentSessionManager();
+ cleanups.push(() => manager.dispose());
+ const decisions: string[] = [];
+ const runner = runnerOf(async function* ({ approve }) {
+ const tc = withHop(toolCall({ name: "exec_command", arguments: "{}", toolCallId: "c1" }));
+ const d = await approve!(tc as OmniMessage<ToolCallPayload>);
+ decisions.push(d);
+ yield withHop(partialText("delta", `approved:${d}`));
+ });
+ const events: BackgroundTaskDoneEvent[] = [];
+ const services = {
+ subagentRunner: runner,
+ subagentSessions: manager,
+ backgroundDone: (e: BackgroundTaskDoneEvent) => events.push(e),
+ };
+ const tool = createSubagentTool(SUB_DEF, services);
+ const approveSpy: ApproveFn = async () => "allow";
+ const res = await drive(
+ tool,
+ { prompt: "needs approval", run_in_background: true },
+ { ...CTX, approve: approveSpy },
+ );
+ extractSubagentId(res.note);
+ // Without the standing sink this parks forever: the child's first approval request has
+ // no collect window to consult through.
+ await waitFor(() => decisions.length === 1);
+ expect(decisions[0]).toBe("allow");
+ await waitFor(() => events.length === 1);
+ expect(events[0]!.status).toBe("completed");
+ });
+
+ it("kill_subagent fails on an unknown subagent_id", 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" });
+ expect(res.stopReason).toBe("failed");
+ expect(res.output).toContain("unknown subagent_id");
+ });
+});
+
+/** Tags a message with the child hop, as the SubagentHandle contract requires. */
+function withHop<M extends OmniMessage>(msg: M): M {
+ return { ...msg, origin: [HOP] };
+}
+
+// ---------------------------------------------------------------------------
+// Engine boundary delivery of queued notices
+// ---------------------------------------------------------------------------
+
+/** A fake LLM that always answers with a plain final reply (no tool calls). */
+class ReplyLLM implements LLMInterface {
+ calls = 0;
+ inputs: OmniMessage[][] = [];
+ async *streamGenerate(
+ params: GenerativeModelParameters,
+ ): AsyncGenerator<OmniMessage, LLMOutcome> {
+ this.calls += 1;
+ this.inputs.push(params.newMessages);
+ yield assistantText(`reply ${this.calls}`);
+ yield tokenUsage(emptyTokenCounts(), { cache_read: 0, cache_write: 0, output: 1, total: 2 });
+ return { status: "completed" };
+ }
+}
+
+const idleEnvironment: EnvironmentInterface = {
+ listTools: async () => [],
+ executeTool: async function* () {
+ throw new Error("not used");
+ },
+ toolPermission: () => undefined,
+};
+
+const allow: ApproveFn = async () => "allow";
+
+describe("ContextEngine background-notice delivery", () => {
+ it("delivers notices queued before the run with the first request input", async () => {
+ const llm = new ReplyLLM();
+ const queue: OmniMessage[] = [userText("[notice] task one done", "harness")];
+ const engine = new ContextEngine({
+ llm,
+ environment: idleEnvironment,
+ backgroundNotices: { drain: () => queue.splice(0), pending: () => queue.length },
+ });
+ const streamed: OmniMessage[] = [];
+ for await (const msg of engine.run([userText("hello")], { approve: allow })) streamed.push(msg);
+ expect(llm.calls).toBe(1);
+ const texts = llm.inputs[0]!.map((m) => (m.payload as { text?: string }).text);
+ expect(texts).toEqual(["hello", "[notice] task one done"]);
+ // The notice is also yielded to the consumer (mid-run input the render layer never saw).
+ expect(
+ streamed.some((m) => (m.payload as { text?: string }).text === "[notice] task one done"),
+ ).toBe(true);
+ });
+
+ it("a notice arriving mid-run extends the task by one turn to react to it", async () => {
+ const llm = new ReplyLLM();
+ const queue: OmniMessage[] = [];
+ const engine = new ContextEngine({
+ llm,
+ environment: idleEnvironment,
+ backgroundNotices: { drain: () => queue.splice(0), pending: () => queue.length },
+ });
+ const gen = engine.run([userText("hello")], { approve: allow });
+ // Push the notice once the first request is in flight: after the first streamed message.
+ let pushed = false;
+ for await (const msg of gen) {
+ void msg;
+ if (!pushed) {
+ pushed = true;
+ queue.push(userText("[notice] finished late", "harness"));
+ }
+ }
+ // Turn 1 answered, then the notice forced turn 2 whose input is exactly the notice.
+ expect(llm.calls).toBe(2);
+ const texts = llm.inputs[1]!.map((m) => (m.payload as { text?: string }).text);
+ expect(texts).toEqual(["[notice] finished late"]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Session wiring: environment events → notice queue → host signal
+// ---------------------------------------------------------------------------
+
+const META: SessionMetaPayload = {
+ session_id: "session-bg-1",
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 1000,
+ system_prompt: "sp",
+ agent_state: "/tmp/state",
+ workspace: "/tmp/w",
+};
+const IMAGES = { imagesDir: "/tmp/scratchpad/session-bg-1", modelHasVision: true } as const;
+
+/** Fake environment that exposes the background listener attach so tests can fire events. */
+function listenerEnvironment(): {
+ environment: EnvironmentInterface;
+ fire: (e: BackgroundTaskDoneEvent) => void;
+} {
+ let listener: ((e: BackgroundTaskDoneEvent) => void) | null = null;
+ return {
+ environment: {
+ ...idleEnvironment,
+ setBackgroundTaskListener: (cb) => (listener = cb),
+ },
+ fire: (e) => listener?.(e),
+ };
+}
+
+const DONE_EVENT: BackgroundTaskDoneEvent = {
+ kind: "command",
+ id: "proc-11aa22bb",
+ status: "completed",
+ detail: "exit code 0",
+ label: "sleep 1",
+ output: "done!",
+};
+
+describe("Session background notices", () => {
+ it("queues an idle-arrival as a harness user message and signals the host", async () => {
+ const { environment, fire } = listenerEnvironment();
+ const session = new Session({
+ meta: META,
+ ...IMAGES,
+ bootstrap: async () => ({ tools: [], llm: new ReplyLLM(), mcp: [] }),
+ mcpServers: [],
+ environment,
+ });
+ let signaled = 0;
+ session.onBackgroundNotice(() => (signaled += 1));
+ fire(DONE_EVENT);
+ expect(signaled).toBe(1);
+ const taken = session.takeBackgroundNotices();
+ expect(taken).toHaveLength(1);
+ const p = taken[0]!.payload as TextPayload;
+ expect(p.role).toBe("user");
+ expect(p.sender).toBe("harness");
+ const parsed = parseBackgroundTaskDoneMessage(p.text);
+ expect(parsed!.done).toMatchObject({ kind: "command", id: "proc-11aa22bb" });
+ expect(parsed!.rest).toContain("`sleep 1`");
+ expect(parsed!.rest).toContain("done!");
+ // Taking empties the queue, and the pending flag (the host's eviction pin) tracks it.
+ expect(session.hasPendingBackgroundNotices()).toBe(false);
+ fire(DONE_EVENT);
+ expect(session.hasPendingBackgroundNotices()).toBe(true);
+ session.takeBackgroundNotices();
+ expect(session.takeBackgroundNotices()).toHaveLength(0);
+ expect(session.hasPendingBackgroundNotices()).toBe(false);
+ });
+
+ it("delivers a queued notice on the next run without a host signal for running tasks", async () => {
+ const { environment, fire } = listenerEnvironment();
+ const llm = new ReplyLLM();
+ const session = new Session({
+ meta: META,
+ ...IMAGES,
+ bootstrap: async () => ({ tools: [], llm, mcp: [] }),
+ mcpServers: [],
+ environment,
+ });
+ fire(DONE_EVENT); // no listener registered: stays queued
+ const streamed: OmniMessage[] = [];
+ for await (const msg of session.run([userText("hi")])) streamed.push(msg);
+ expect(llm.calls).toBe(1);
+ const texts = llm.inputs[0]!.map((m) => (m.payload as { text?: string }).text ?? "");
+ expect(texts[0]).toBe("hi");
+ expect(texts[1]).toContain("[background_task_done]");
+ });
+});
diff --git a/packages/core/test/markers.test.ts b/packages/core/test/markers.test.ts
index 4f302c95..264aa174 100644
--- a/packages/core/test/markers.test.ts
+++ b/packages/core/test/markers.test.ts
@@ -70,6 +70,7 @@ describe("marker block primitives", () => {
MARKER_TAGS.scheduledTask,
MARKER_TAGS.modelSwitchFrom,
MARKER_TAGS.goal,
+ MARKER_TAGS.backgroundTaskDone,
]);
});
});
diff --git a/packages/core/test/service-url.test.ts b/packages/core/test/service-url.test.ts
new file mode 100644
index 00000000..7a76404a
--- /dev/null
+++ b/packages/core/test/service-url.test.ts
@@ -0,0 +1,275 @@
+/**
+ * Service-URL detection tests: the pure URL extractor, the incremental output-stream
+ * scanner (chunk and ANSI boundaries), the per-platform listen-port probe parsers over
+ * fixtures, a live linux probe against a real listener, and the ManagedSession /
+ * Environment wiring (output scan wins over the probe; the list carries serviceUrl).
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { createServer, type Server } from "node:net";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { Environment } from "../src/environment/index.js";
+import {
+ CommandSessionManager,
+ ServiceUrlScanner,
+ extractLastLocalUrl,
+ parseLsofListenPorts,
+ parsePsPids,
+ parseSsListenPorts,
+ parseWindowsProbe,
+ probeGroupListenPorts,
+} from "../src/environment/tools/command/index.js";
+import type { ToolConfig } from "../src/interfaces.js";
+
+const ESC = String.fromCharCode(0x1b);
+
+describe("extractLastLocalUrl", () => {
+ it("finds a plain localhost URL with port and path", () => {
+ expect(extractLastLocalUrl("Local: http://localhost:5173/app/ ready")).toBe(
+ "http://localhost:5173/app/",
+ );
+ });
+
+ it("strips ANSI color and hyperlink wrapping around the URL", () => {
+ const text = ` ${ESC}[32m➜${ESC}[39m Local: ${ESC}[36mhttp://localhost:5173/${ESC}[39m`;
+ expect(extractLastLocalUrl(text)).toBe("http://localhost:5173/");
+ const osc = `${ESC}]8;;http://localhost:9999/${ESC}\\http://localhost:5173/${ESC}]8;;${ESC}\\`;
+ expect(extractLastLocalUrl(osc)).toBe("http://localhost:5173/");
+ });
+
+ it("takes the last URL when several are printed", () => {
+ const text = "http://localhost:3000/ then restarted on http://localhost:3001/";
+ expect(extractLastLocalUrl(text)).toBe("http://localhost:3001/");
+ });
+
+ it("normalizes listen-side wildcard hosts to localhost", () => {
+ expect(extractLastLocalUrl("on http://0.0.0.0:8080")).toBe("http://localhost:8080");
+ expect(extractLastLocalUrl("on http://[::]:8080")).toBe("http://localhost:8080");
+ });
+
+ it("keeps loopback hosts as printed", () => {
+ expect(extractLastLocalUrl("http://127.0.0.1:9090/x")).toBe("http://127.0.0.1:9090/x");
+ expect(extractLastLocalUrl("http://[::1]:9090")).toBe("http://[::1]:9090");
+ });
+
+ it("trims sentence punctuation but keeps the path's own slash", () => {
+ expect(extractLastLocalUrl("Listening on http://localhost:4000/.")).toBe(
+ "http://localhost:4000/",
+ );
+ });
+
+ it("accepts https and a port-less origin", () => {
+ expect(extractLastLocalUrl("at https://localhost/admin")).toBe("https://localhost/admin");
+ });
+
+ it("ignores remote hosts and URL-less text", () => {
+ expect(extractLastLocalUrl("see https://example.com:5173/")).toBeNull();
+ expect(extractLastLocalUrl("compiled in 130ms")).toBeNull();
+ });
+});
+
+describe("ServiceUrlScanner (incremental)", () => {
+ it("finds a URL split across chunk boundaries", () => {
+ const s = new ServiceUrlScanner();
+ s.push(" Local: http://loca");
+ s.push("lhost:5173/app");
+ s.push("/ ready\n");
+ expect(s.url).toBe("http://localhost:5173/app/");
+ });
+
+ it("re-extends a match the boundary cut mid-URL (latest hit wins)", () => {
+ const s = new ServiceUrlScanner();
+ s.push("on http://localhost:51");
+ // The cut prefix is itself a well-formed URL; the continuation must replace it.
+ expect(s.url).toBe("http://localhost:51");
+ s.push("73/deep/path");
+ expect(s.url).toBe("http://localhost:5173/deep/path");
+ });
+
+ it("survives an ANSI escape split across chunks", () => {
+ const s = new ServiceUrlScanner();
+ s.push(`Local: ${ESC}[3`);
+ s.push("6mhttp://localhost:3000/");
+ s.push(`${ESC}[39m\n`);
+ expect(s.url).toBe("http://localhost:3000/");
+ });
+
+ it("keeps the latest URL across pushes and stays null without one", () => {
+ const s = new ServiceUrlScanner();
+ expect(s.url).toBeNull();
+ s.push("http://localhost:3000/\n");
+ s.push("x".repeat(2000)); // far beyond the carry window
+ s.push("restarted on http://localhost:3001/\n");
+ expect(s.url).toBe("http://localhost:3001/");
+ s.push("plain build output\n");
+ expect(s.url).toBe("http://localhost:3001/");
+ });
+});
+
+describe("port-probe parsers", () => {
+ it("parsePsPids reads one pid per padded line", () => {
+ expect(parsePsPids(" 123\n 124\n\n")).toEqual([123, 124]);
+ });
+
+ it("parseSsListenPorts reads ports and every owner pid, skipping the header", () => {
+ const out = [
+ "State Recv-Q Send-Q Local Address:Port Peer Address:Port Process",
+ 'LISTEN 0 511 *:5173 *:* users:(("node",pid=123,fd=23))',
+ 'LISTEN 0 4096 127.0.0.1:8080 0.0.0.0:* users:(("python3",pid=999,fd=3))',
+ 'LISTEN 0 511 [::1]:9231 [::]:* users:(("node",pid=123,fd=30),("node",pid=124,fd=30))',
+ "",
+ ].join("\n");
+ expect(parseSsListenPorts(out)).toEqual([
+ { port: 5173, pid: 123 },
+ { port: 8080, pid: 999 },
+ { port: 9231, pid: 123 },
+ { port: 9231, pid: 124 },
+ ]);
+ });
+
+ it("parseLsofListenPorts attributes -F name lines to the current pid paragraph", () => {
+ const out = ["p123", "n*:5173", "n127.0.0.1:8080", "p456", "n[::1]:9090", ""].join("\n");
+ expect(parseLsofListenPorts(out)).toEqual([
+ { port: 5173, pid: 123 },
+ { port: 8080, pid: 123 },
+ { port: 9090, pid: 456 },
+ ]);
+ });
+
+ it("parseWindowsProbe walks the process tree from the root pid", () => {
+ const json = JSON.stringify({
+ c: [
+ { LocalPort: 5173, OwningProcess: 300 },
+ { LocalPort: 9999, OwningProcess: 999 },
+ ],
+ p: [
+ { ProcessId: 200, ParentProcessId: 100 },
+ { ProcessId: 300, ParentProcessId: 200 },
+ { ProcessId: 999, ParentProcessId: 1 },
+ ],
+ });
+ expect(parseWindowsProbe(json, 100)).toEqual([5173]);
+ });
+
+ it("parseWindowsProbe handles ConvertTo-Json's single-object collapse and bad JSON", () => {
+ const json = JSON.stringify({
+ c: { LocalPort: 80, OwningProcess: 50 },
+ p: { ProcessId: 50, ParentProcessId: 10 },
+ });
+ expect(parseWindowsProbe(json, 10)).toEqual([80]);
+ expect(parseWindowsProbe("not json", 10)).toBeNull();
+ });
+
+ it("probeGroupListenPorts answers null on an unsupported platform", async () => {
+ expect(await probeGroupListenPorts(1, "freebsd" as NodeJS.Platform)).toBeNull();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Live wiring: output scan on the session, probe fallback, list field
+// ---------------------------------------------------------------------------
+
+const cleanups: Array<() => Promise<void> | void> = [];
+afterEach(async () => {
+ while (cleanups.length) await cleanups.pop()!();
+});
+
+function toolConfig(): ToolConfig {
+ return {
+ customTools: [
+ {
+ name: "exec_command",
+ description: "run",
+ permission: "rw",
+ maxOutputLength: 16000,
+ },
+ ],
+ mcpServers: [],
+ };
+}
+
+async function waitFor(pred: () => boolean, timeoutMs = 4000): Promise<void> {
+ const start = Date.now();
+ while (!pred()) {
+ if (Date.now() - start > timeoutMs) throw new Error("waitFor timed out");
+ await new Promise((r) => setTimeout(r, 25));
+ }
+}
+
+describe("session service-url wiring", () => {
+ it("scans the output stream (foreground and background alike) and surfaces serviceUrl on the list", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-url-"));
+ const env = new Environment({ workspaceDir: dir, toolConfig: toolConfig() });
+ cleanups.push(async () => {
+ env.dispose();
+ // Retries: the command launched below keeps this dir as its cwd, and on Windows a
+ // just-killed process releases that lock asynchronously — an immediate recursive rm
+ // hits EBUSY. fs.rm retries those with a linear backoff.
+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
+ });
+ // Launch via the tool path with run_in_background: the model never polls, yet the URL
+ // must still be picked up — core sees the output stream directly.
+ const gen = env.executeTool({
+ toolCall: {
+ timestamp: new Date().toISOString(),
+ type: "model_msg",
+ payload: {
+ type: "tool_call",
+ role: "assistant",
+ name: "exec_command",
+ arguments: JSON.stringify({
+ cmd: "printf 'Local: http://0.0.0.0:5199/app\\n'; sleep 30",
+ run_in_background: true,
+ }),
+ tool_call_id: "tc_url",
+ },
+ },
+ });
+ for await (const _ of gen) void _;
+ await waitFor(() => env.listBackgroundCommands().some((p) => p.serviceUrl !== undefined));
+ const info = env.listBackgroundCommands()[0]!;
+ expect(info.running).toBe(true);
+ expect(info.serviceUrl).toBe("http://localhost:5199/app");
+ });
+
+ it("linux: probes the process group's listening port when the output printed no URL", async () => {
+ if (process.platform !== "linux") return; // live probe exercised on linux only; other platforms are covered by the parser fixtures
+ // A real listener inside a detached session: `node -e` opens a server on a port the
+ // test picked, prints nothing, and stays alive until killed.
+ const server = await new Promise<Server>((resolve, reject) => {
+ const s = createServer();
+ s.once("error", reject);
+ s.listen(0, "127.0.0.1", () => resolve(s));
+ });
+ const probePort = (server.address() as { port: number }).port;
+ await new Promise<void>((r) => server.close(() => r()));
+
+ const manager = new CommandSessionManager();
+ const session = manager.spawn({
+ cmd: `node -e "require('net').createServer().listen(${probePort}, '127.0.0.1', () => {}); setInterval(() => {}, 1000)"`,
+ cwd: tmpdir(),
+ });
+ cleanups.push(() => {
+ session.kill();
+ manager.dispose();
+ });
+ await waitFor(() => session.running && session.pid !== null);
+ // The child needs a moment to bind; retry the raw probe until it sees the port (the
+ // session-level refresh below then answers from a fresh TTL window).
+ let ports: number[] | null = null;
+ const deadline = Date.now() + 5000;
+ for (;;) {
+ ports = await probeGroupListenPorts(session.pid!);
+ if (ports !== null && ports.includes(probePort)) break;
+ if (Date.now() > deadline) break;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(ports).not.toBeNull();
+ expect(ports!).toContain(probePort);
+
+ // And the session-level refresh composes the origin (no scanned URL to outrank it).
+ await session.refreshServiceProbe();
+ expect(session.serviceUrl).toBe(`http://localhost:${ports![0]}`);
+ });
+});
diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.ts
index 07b3561c..35acd28e 100644
--- a/packages/core/test/state.test.ts
+++ b/packages/core/test/state.test.ts
@@ -252,8 +252,10 @@ describe("buildToolConfig", () => {
"write_file",
"exec_command",
"input_command",
+ "kill_command",
"run_subagent",
"input_subagent",
+ "kill_subagent",
"read_image",
"describe_image",
]);
@@ -262,12 +264,12 @@ describe("buildToolConfig", () => {
expect(exec.timeoutMs).toBe(120000);
expect(exec.maxOutputLength).toBe(16000);
expect((exec.parameters as { required?: string[] }).required).toEqual(["description", "cmd"]);
- // The four command/subagent tools declare the description call argument in config,
+ // The command/subagent tools declare the description call argument in config,
// toggled by the per-entry call_description field (default true).
expect(exec.call_description).toBe(true);
expect(
Object.keys((exec.parameters as { properties: Record<string, unknown> }).properties),
- ).toEqual(["description", "cmd", "workdir", "yield_time_ms"]);
+ ).toEqual(["description", "cmd", "workdir", "yield_time_ms", "run_in_background"]);
const write = cfg.customTools.find((t) => t.name === "input_command")!;
expect(write.permission).toBe("rw");
expect(write.call_description).toBe(true);
@@ -380,8 +382,10 @@ describe("buildToolConfig", () => {
"write_file",
"exec_command",
"input_command",
+ "kill_command",
"run_subagent",
"input_subagent",
+ "kill_subagent",
"read_image",
"describe_image",
]);
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index 6ddd07f4..f3e2603c 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -144,6 +144,8 @@ interface EnvironmentServices {
visionDescriber?: VisionDescriberService; // needed by describe_image on text-only models
commandSessions?: CommandSessionManager; // long-running command session registry (built by Environment)
subagentSessions?: SubagentSessionManager;// background subagent session registry (likewise)
+ backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // completion-report sink for run_in_background launches (likewise)
+ backgroundForward?: (msg: OmniMessage) => void; // live message tap of a background subagent (likewise)
}
interface MCPServerConfig {
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index 6967551f..9a66b94a 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -144,6 +144,8 @@ interface EnvironmentServices {
visionDescriber?: VisionDescriberService; // text-only 模型的 describe_image 所需
commandSessions?: CommandSessionManager; // 长驻命令会话登记表(Environment 内部构造)
subagentSessions?: SubagentSessionManager;// 后台 Subagent 会话登记表(同上)
+ backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // run_in_background 完成回报的汇聚点(同上)
+ backgroundForward?: (msg: OmniMessage) => void; // 后台 Subagent 消息的实时转发出口(同上)
}
interface MCPServerConfig {
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index a93c715e..acaa1d89 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -58,6 +58,7 @@ interface TextPayload {
type: "text";
role: "user" | "assistant";
text: string;
+ sender?: "user" | "parent_agent" | "harness" | "server"; // who produced a user-role text; absent = the human user
fidelity?: Fidelity; // e.g. { phase } segment marker (GPT-5), { signature }
stop_reason?: StopReason;
}
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index da100d74..0e3db2db 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -58,6 +58,7 @@ interface TextPayload {
type: "text";
role: "user" | "assistant";
text: string;
+ sender?: "user" | "parent_agent" | "harness" | "server"; // user 角色文本的来源;缺省 = 真人用户
fidelity?: Fidelity; // 如 { phase } 分段标记(GPT-5)、{ signature }
stop_reason?: StopReason;
}
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 2becce54..922f2481 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -204,7 +204,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode
| POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle |
| POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error |
| POST | /compact | Trigger context compaction: 202; 409 when there is nothing to compact, the reason carried by the code — `compaction_not_configured` (this Agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet), `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart reports availability from its Trace, so an existing conversation stays compactable without running a Task first |
-| GET | /processes | Background processes the conversation started (`exec_command`s promoted past their yield window). Served from the active runtime only — an evicted or never-loaded session truthfully reports an empty list |
+| GET | /processes | Background processes the conversation started (`exec_command`s promoted past their yield window). Served from the active runtime only — an evicted or never-loaded session truthfully reports an empty list. Rows carry `serviceUrl` when a served address was detected (the last local URL the output printed, else a listen-port probe of the process group, refreshed on each fetch) |
| POST | /processes/:processId/kill | Stop one background process (SIGTERM to the whole process group, SIGKILL after a grace period); the entry drops from the list. 404 `process_not_found` when it is gone |
| DELETE | /processes/:processId | Remove one **exited** process entry from the list: 409 `process_running` while it still runs (stop it instead), 404 `process_not_found` when it is already gone. The entry leaves the runtime registry with the output captured from it, so `input_command` on that `process_id` fails afterwards |
| GET | /files?path= | Browse the Workspace directory |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index e27ebd11..0892b8d4 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -204,7 +204,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入
| POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 |
| POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) |
| POST | /compact | 触发上下文压缩:202;无可压缩内容返回 409,具体原因由 code 承载——`compaction_not_configured`(该 Agent 没有配置压缩)、`nothing_to_compact`(当前上下文尚未完成一轮对话)、`already_compacted`(上次压缩后还没有新的对话)。服务重启后恢复的 Session 依据 Trace 判断可压缩性,因此已有对话无需先跑一次 Task 即可压缩 |
-| GET | /processes | 对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`)。仅来自活跃运行时——被回收或从未装载的会话如实返回空列表 |
+| GET | /processes | 对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`)。仅来自活跃运行时——被回收或从未装载的会话如实返回空列表。检测到进程所服务地址时行内附 `serviceUrl`(取输出打印的最后一个本机 URL,否则按进程组做监听端口探测,每次拉取时刷新) |
| POST | /processes/:processId/kill | 停止一个后台进程(对整个进程组先 SIGTERM、宽限期后 SIGKILL),条目随之从列表消失;已不存在时 404 `process_not_found` |
| DELETE | /processes/:processId | 从列表移除一个**已退出**的进程条目:仍在运行时 409 `process_running`(应改用停止),已不存在时 404 `process_not_found`。条目连同该进程已捕获的输出一起离开运行时注册表,此后对该 `process_id` 调用 `input_command` 会失败 |
| GET | /files?path= | 浏览 Workspace 目录 |
diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.md
index f5d5e1f9..20734d0d 100644
--- a/packages/docs/content/tools.en.md
+++ b/packages/docs/content/tools.en.md
@@ -72,41 +72,46 @@ Each tool is described by one `ToolDefinitionConfig`:
## Built-in tools
-There are 9 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):
+There are 11 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 |
| `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 |
| `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 the file tools 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 (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.
### Call descriptions
-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.
+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.
### 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`:
+`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:
```text
exec_command(cmd)
├─ finishes within the foreground window (yield_time_ms, default 60000)
│ ──► full output + exit code
- └─ still running ──► backgrounds, returns output so far + process_id
- │
- input_command(process_id[, chars]) ──► write stdin / send Ctrl-C / poll
- └─ loop until the command exits
+ ├─ still running ──► backgrounds, returns output so far + process_id
+ │ │
+ │ input_command(process_id[, chars]) ──► write stdin / send Ctrl-C / poll
+ │ └─ 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)
```
-Both tools' arguments (explicit keys):
+The tools' arguments (explicit keys):
```ts
// exec_command
@@ -114,6 +119,7 @@ Both tools' arguments (explicit keys):
cmd: string; // required: the shell command to run
workdir?: string; // working directory; defaults to the Workspace root, relative paths resolve against it
yield_time_ms?: number; // foreground wait; default 60000, minimum 250, capped below the tool timeout
+ run_in_background?: boolean; // true = return process_id immediately; completion arrives as a user message
description: string; // required while call_description is on: one sentence shown to the user while the call runs, emitted first
}
@@ -121,7 +127,13 @@ Both 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
- yield_time_ms?: number; // wait; defaults 250 for writes, 5000 for empty polls
+ 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
}
```
@@ -163,7 +175,7 @@ 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.
+`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).
```ts
// run_subagent
@@ -174,6 +186,7 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
provider?: string; // the provider group model_id belongs to; required whenever model_id is given
thinking_level?: string; // "low" | "medium" | "high" | "xhigh" | "max"; omit to inherit the parent Session's level
yield_time_ms?: number; // foreground wait; default 300000
+ run_in_background?: boolean; // true = return subagent_id immediately; completion arrives as a user message
description: string; // required while call_description is on
}
@@ -184,6 +197,12 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
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.
@@ -208,6 +227,14 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
}
```
+### Background completion reports
+
+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.
+
+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.
+
### Background session caps
| Session type | Cap | Eviction |
diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.md
index ba8ace97..2dc88363 100644
--- a/packages/docs/content/tools.zh.md
+++ b/packages/docs/content/tools.zh.md
@@ -72,40 +72,45 @@ Recovery 文件保存 Environment 收到的未经脱敏的工具文本。误读
## 内置工具
-共 9 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):
+共 11 个内置工具(装配入口 `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` 终止命令会话(整个进程组),返回尚未送达的输出 |
| `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,返回尚未送达的文本 |
| `read_image` | r | 60000 | 读取图片并作为图像内容返回(vision 模型) |
| `describe_image` | r | 90000 | 由 `vision_model` 代读图片并返回文字回答(text-only 模型) |
-注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):本工具集之前创建的 Agent 不会自动获得文件工具——需手工编辑该 Agent 的 `system_config.yaml`,把新条目补进去(可从 `packages/core/src/state/default-config.ts` 的默认定义复制)。
+注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(文件工具、`kill_command`、`kill_subagent`)与新增参数(`run_in_background`)——需手工编辑该 Agent 的 `system_config.yaml`,把新条目补进去(可从 `packages/core/src/state/default-config.ts` 的默认定义复制)。
### 调用描述
-命令 / 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` 参数本身已说明用途。
+命令 / 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` 参数本身已说明用途。
### 命令会话
-`exec_command` 先在前台等待;命令超过 `yield_time_ms` 仍未结束时转入后台,返回已有输出和一个 `process_id`,之后用 `input_command` 驱动:
+`exec_command` 先在前台等待;命令超过 `yield_time_ms` 仍未结束时转入后台,返回已有输出和一个 `process_id`,之后用 `input_command` 驱动。传 `run_in_background: true` 则完全跳过前台窗口:调用立即返回 `process_id`,进程退出时其结果以自动 user message 送达(见[后台完成回报](#后台完成回报))。两种方式启动的会话都可用 `kill_command` 终止:
```text
exec_command(cmd)
├─ 前台窗口(yield_time_ms,默认 60000)内结束 ──► 完整输出 + 退出码
- └─ 未结束 ──► 转入后台,返回已有输出 + process_id
- │
- input_command(process_id[, chars]) ──► 写 stdin / 发 Ctrl-C / 轮询
- └─ 循环驱动,直至命令退出
+ ├─ 未结束 ──► 转入后台,返回已有输出 + process_id
+ │ │
+ │ input_command(process_id[, chars]) ──► 写 stdin / 发 Ctrl-C / 轮询
+ │ └─ 循环驱动,直至命令退出
+ └─ run_in_background: true ──► 立即返回 process_id
+ └─ 退出时:完成回报以 user message 送达
+ kill_command(process_id) ──► 向进程组发 SIGTERM(宽限期后 SIGKILL)
```
-两个工具的参数(明确键名):
+各工具的参数(明确键名):
```ts
// exec_command
@@ -113,6 +118,7 @@ exec_command(cmd)
cmd: string; // 必填:要执行的 shell 命令
workdir?: string; // 工作目录;缺省为 Workspace 根,相对路径按其解析
yield_time_ms?: number; // 前台等待时长;默认 60000,最小 250,上限受工具超时约束
+ run_in_background?: boolean; // true = 立即返回 process_id;完成回报以 user message 送达
description: string; // 开关开启时必填:一句话说明,最先输出,调用运行期间展示给用户
}
@@ -120,7 +126,13 @@ exec_command(cmd)
{
process_id: string; // 必填:exec_command 返回的命令会话 id
chars?: string; // 写入 stdin 的字符;单独发送 "\u0003" 传递 Ctrl-C;缺省仅轮询
- yield_time_ms?: number; // 等待时长;有写入默认 250,空轮询默认 5000
+ yield_time_ms?: number; // 等待时长;有写入默认 250,空轮询默认 120000(一次轮询等完多数构建;想快速查看可传更小值)
+ description: string; // 开关开启时必填
+}
+
+// kill_command
+{
+ process_id: string; // 必填:要终止的命令会话(已退出的会话也会被移除)
description: string; // 开关开启时必填
}
```
@@ -161,7 +173,7 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
### Subagent
-`run_subagent` 把一段能一次说清的子任务交给子 Agent 执行,同样是两段式:前台窗口(默认 300000ms)过后转入后台并返回 `subagent_id`,由 `input_subagent` 轮询或追加 Prompt;子 Agent 的待审批项会在轮询等待期间浮出。
+`run_subagent` 把一段能一次说清的子任务交给子 Agent 执行,同样是两段式:前台窗口(默认 300000ms)过后转入后台并返回 `subagent_id`,由 `input_subagent` 轮询或追加 Prompt;子 Agent 的待审批项会在轮询等待期间浮出。传 `run_in_background: true` 则立即返回 `subagent_id`,每轮完成都以自动 user message 送达(见[后台完成回报](#后台完成回报));`kill_subagent` 中止并移除后台 Subagent(空闲的也可移除,腾出并发额度)。
```ts
// run_subagent
@@ -172,6 +184,7 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
provider?: string; // model_id 所属的 provider 组;给出 model_id 时必填
thinking_level?: string; // "low" | "medium" | "high" | "xhigh" | "max";缺省继承父 Session 的思考等级
yield_time_ms?: number; // 前台等待时长;默认 300000
+ run_in_background?: boolean; // true = 立即返回 subagent_id;完成回报以 user message 送达
description: string; // 开关开启时必填
}
@@ -182,6 +195,12 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
yield_time_ms?: number; // 等待时长;有追加默认 300000,空轮询默认 10000
description: string; // 开关开启时必填
}
+
+// kill_subagent
+{
+ subagent_id: string; // 必填:要中止并移除的后台 Subagent
+ description: string; // 开关开启时必填
+}
```
- 深度上限为 1:Subagent 不能再派生 Subagent。
@@ -206,6 +225,14 @@ 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 自身的结果已说明结局。
+
+后台 Subagent 的生命周期与发起它的调用解耦:中止信号只属于它自己(仅 `kill_subagent`、Session 终结或注册表淘汰会结束它),其消息经发起 Session 实时流向前端(与前台窗口转发同一条 origin 通道),工具审批经发起调用自身的审批回调作为常驻 sink 解决——`allow-all` 下即发即忘可全程无人值守,失败也以 `status: failed` 的回报收尾,而不是子会话永久卡住。
+
### 后台会话上限
| 会话类型 | 上限 | 淘汰策略 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 5c1edc9e..916aea96 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -59,7 +59,7 @@ Pinning is offered only in the active list — the archived, subagent and schedu
The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. Below those:
-- **Processes** — background processes the conversation started (`exec_command`s promoted past their yield window), one row each with the command, start time and pid. Running rows carry a **Stop** button (kills the whole process group and drops the row); exited rows keep their "exited" label and carry a **Remove** button that deletes the entry from the list. Removal is immediate and final: the entry leaves the runtime registry together with the output captured from that process, so afterwards the model can no longer be asked to read it — keep the row until you are done with its output.
+- **Processes** — background processes the conversation started (`exec_command`s promoted past their yield window), one row each with the command, start time and pid — plus, on running rows, a link to the service the process serves when one was detected (the last local URL its output printed, else a listen-port probe of its process group). Running rows carry a **Stop** button (kills the whole process group and drops the row); exited rows keep their "exited" label and carry a **Remove** button that deletes the entry from the list. Removal is immediate and final: the entry leaves the runtime registry together with the output captured from that process, so afterwards the model can no longer be asked to read it — keep the row until you are done with its output.
- **Trace file** — the Session's current Trace file, shown as its file name on a single line: clicking the name opens the Trace Browser focused on this session, and the button beside it copies the full path.
Copy buttons across the app confirm at the button itself: the copy icon flips to a check mark for a moment (no "Copied" text label).
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 380695a8..d5a5875f 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -59,7 +59,7 @@ penguin web
工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。其下还有两节:
-- **会话进程**——对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`),逐行显示命令、启动时间与 pid。运行中的行带「停止」按钮(杀停整个进程组并把该行从列表移除);已退出的行保留「已退出」标注,并带「移除」按钮,可把该条目从列表删除。移除立即生效且不可撤销:条目连同该进程已捕获的输出一起离开运行时注册表,之后无法再让模型读取那段输出——输出还有用时请先留着这一行。
+- **会话进程**——对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`),逐行显示命令、启动时间与 pid;运行中的行在检测到进程所服务的地址时,还会附上可点击的服务链接(取其输出打印的最后一个本机 URL,否则对其进程组做监听端口探测)。运行中的行带「停止」按钮(杀停整个进程组并把该行从列表移除);已退出的行保留「已退出」标注,并带「移除」按钮,可把该条目从列表删除。移除立即生效且不可撤销:条目连同该进程已捕获的输出一起离开运行时注册表,之后无法再让模型读取那段输出——输出还有用时请先留着这一行。
- **轨迹文件**——会话当前的 Trace 文件,单行仅显示文件名:点击文件名跳转到聚焦本会话的轨迹观测页,旁边的按钮复制完整路径。
全站的复制按钮在按钮自身给出反馈:复制成功后图标短暂切换为对勾(不再显示「已复制」文字)。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 018d7e2e..24d6082e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1409,6 +1409,8 @@ export interface SessionProcessInfo {
cwd: string;
startedAt: string;
running: boolean;
+ /** The service the process serves, when detected: the last local URL its output printed, else an origin probed from its listening ports. */
+ serviceUrl?: string;
}
export interface SessionProcessesResponse {
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index edcc9bbf..d1122c54 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -1028,8 +1028,11 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// from the ACTIVE runtime only: an evicted or never-loaded session truthfully reports
// none — the environment that owned them is gone, and resurrecting an entry could only
// ever produce an empty list anyway.
- app.get("/:sessionId/processes", (c) => {
+ app.get("/:sessionId/processes", async (c) => {
const row = resolveSession(c);
+ // Refresh the listen-port probes first, so the first fetch already carries a probed
+ // serviceUrl (core bounds each probe with its own timeout and TTL cache).
+ await deps.manager.probeProcessServices(row.sessionId);
const processes = deps.manager.listProcesses(row.sessionId).map((p) => ({
processId: p.processId,
pid: p.pid,
@@ -1037,6 +1040,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
cwd: p.cwd,
startedAt: new Date(p.startedAt).toISOString(),
running: p.running,
+ ...(p.serviceUrl !== undefined ? { serviceUrl: p.serviceUrl } : {}),
}));
return c.json({ processes } satisfies SessionProcessesResponse);
});
diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.ts
index 3f6ca966..b889e764 100644
--- a/packages/server/src/runtime/scheduler.ts
+++ b/packages/server/src/runtime/scheduler.ts
@@ -416,7 +416,8 @@ export class Scheduler {
const firedAt = new Date(this.now()).toISOString();
try {
await this.deps.runner.startTask(sessionId, [
- userText(scheduledMessage(def.name, firedAt, def.prompt)),
+ // sender "server": in the Trace this user turn was injected by the server's scheduler, not typed by a human.
+ userText(scheduledMessage(def.name, firedAt, def.prompt), "server"),
]);
} catch (err) {
this.deps.errors.record({
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index b85351b4..34c9e88b 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -140,10 +140,27 @@ export interface RuntimeSession {
material?: { userText: string; assistantText: string };
signal?: AbortSignal;
}): Promise<SessionTitleResult>;
+ /**
+ * Subscribes the idle-arrival signal for background-task completion notices (core
+ * `Session.onBackgroundNotice`): fired when a `run_in_background` launch settles while no
+ * Task is running — the manager then takes the queue and submits it as an ordinary task.
+ * Optional: test fakes may omit it.
+ */
+ onBackgroundNotice?(listener: () => void): void;
+ /** Takes the queued background completion notices as task input (core `Session.takeBackgroundNotices`). Optional, like onBackgroundNotice. */
+ takeBackgroundNotices?(): OmniMessage[];
+ /** Whether completion notices are still queued (core `Session.hasPendingBackgroundNotices`); pins the entry against idle eviction. Optional, like onBackgroundNotice. */
+ hasPendingBackgroundNotices?(): boolean;
+ /** Refreshes the listen-port probes behind the process list's `serviceUrl` (core `Session.probeBackgroundCommandServices`). Optional: test fakes may omit it. */
+ probeBackgroundCommandServices?(): Promise<void>;
+ /** Subscribes live-forwarded background-subagent messages (core `Session.onBackgroundMessage`); the manager publishes them to the session channel. Optional: test fakes may omit it. */
+ onBackgroundMessage?(listener: (msg: OmniMessage) => void): void;
/** Background command processes owned by the Session's environment (core `Session.listBackgroundCommands`). Optional: test fakes may omit it. */
listBackgroundCommands?(): BackgroundCommandInfo[];
/** Kills one background command process (core `Session.killBackgroundCommand`); false when the id is unknown. Optional, like listBackgroundCommands. */
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;
/** Releases environment resources — kills the remaining background processes (core `Session.dispose`). Optional, idempotent. */
dispose?(): void;
}
@@ -551,6 +568,45 @@ export class SessionManager {
pendingSteering: [],
lastActivityMs: Date.now(),
});
+ // Same wiring as ensureEntry: adopt IS the entry path for a session created in this
+ // process (POST /sessions), and a listener registered only on the loader path left
+ // freshly created sessions unable to deliver idle-arrival completion reports.
+ this.registerNoticeListener(row.sessionId, session);
+ }
+
+ /**
+ * Subscribes the background hooks on a runtime Session entering the active table — every
+ * insertion path must call it (ensureEntry's loads, adopt's fresh creations):
+ * - the idle-arrival signal for completion notices (mid-run arrivals are delivered inside
+ * 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.
+ */
+ private registerNoticeListener(sessionId: string, session: RuntimeSession): void {
+ session.onBackgroundNotice?.(() => void this.startBackgroundNoticeTask(sessionId));
+ session.onBackgroundMessage?.((msg) => this.forwardBackgroundMessage(sessionId, msg));
+ }
+
+ /** Publishes one live background-subagent message and records its usage (fire-and-forget; the child's own Trace is the durable record). */
+ private forwardBackgroundMessage(sessionId: string, msg: OmniMessage): void {
+ const entry = this.entries.get(sessionId);
+ if (!entry) return;
+ // A child producing messages IS session activity: without this stamp the idle sweep
+ // measures only the launching task, and a long background run ages into eviction.
+ entry.lastActivityMs = Date.now();
+ this.deps.channels.get(entry.sessionId).publish(msg);
+ const ctx: UsageContext = {
+ projectId: entry.projectId,
+ agentId: entry.agentId,
+ sessionId: entry.sessionId,
+ provider: entry.provider,
+ modelId: entry.modelId,
+ };
+ void this.deps.recorder.record(ctx, msg).catch((err: unknown) => {
+ this.log(`[usage] Insert failed: ${err instanceof Error ? err.message : String(err)}`);
+ this.deps.errors?.record({ source: "usage", err, ctx, code: "usage_insert_failed" });
+ });
}
/**
@@ -1100,6 +1156,16 @@ export class SessionManager {
return this.entries.get(sessionId)?.session.listBackgroundCommands?.() ?? [];
}
+ /**
+ * Refreshes the listen-port probes behind the process list's `serviceUrl` (core
+ * `Session.probeBackgroundCommandServices`): called by the processes route before
+ * listing, so the first fetch already carries probed URLs. Bounded by core's own probe
+ * timeout and TTL; a session that isn't loaded has no processes to probe.
+ */
+ async probeProcessServices(sessionId: string): Promise<void> {
+ await this.entries.get(sessionId)?.session.probeBackgroundCommandServices?.();
+ }
+
/** Kills one background command process of a loaded session; false when the session isn't loaded or the id is unknown. */
killProcess(sessionId: string, processId: string): boolean {
const entry = this.entries.get(sessionId);
@@ -1257,6 +1323,13 @@ export class SessionManager {
// environment, so the process list and its stop control would go blind while the
// OS process kept running. Exited-but-listed processes don't pin anything.
if (entry.session.listBackgroundCommands?.().some((p) => p.running)) continue;
+ // A background subagent still working pins it for the same reason: a run_in_background
+ // child outlives the call that launched it, and its completion report and live messages
+ // are delivered through the very Session object eviction would drop.
+ if (entry.session.hasRunningBackgroundSubagents?.()) continue;
+ // Undelivered background completion notices pin the entry too: they live in the core
+ // Session object, so evicting it would silently drop them.
+ if (entry.session.hasPendingBackgroundNotices?.()) continue;
if (now - entry.lastActivityMs <= idleMs) continue;
this.entries.delete(key);
}
@@ -1376,9 +1449,46 @@ export class SessionManager {
lastActivityMs: Date.now(),
};
this.entries.set(currentId, entry);
+ this.registerNoticeListener(currentId, session);
return entry;
}
+ /**
+ * Auto-start of queued background completion notices: called when core signals an
+ * idle-session arrival, and from drive's finally for notices that raced a run's exit.
+ * Revalidates under the session lock; only an idle entry launches, and only when the
+ * queue is non-empty — a busy entry skips, because the running/queued task's engine
+ * drains the same queue at its own boundaries (each notice is delivered exactly once).
+ */
+ private async startBackgroundNoticeTask(sessionId: string): Promise<void> {
+ try {
+ await this.withLock(sessionId, async () => {
+ if (this.closed || this.deletingSessions.has(sessionId)) return;
+ const row = this.deps.sessions.findById(sessionId);
+ if (row && this.deletingAgents.has(agentKey(row.projectId, row.agentId))) return;
+ const entry = this.entries.get(sessionId);
+ if (!entry) {
+ // The runtime entry left the active table between the signal and this lock —
+ // the queued notices left with the released Session object. Say so instead of
+ // dropping the report invisibly (the sweep pins entries with pending notices,
+ // so this is a genuine anomaly worth a trace in the log).
+ this.log(`[background] notice for ${sessionId} dropped: runtime entry not loaded`);
+ return;
+ }
+ // Busy or queued-behind: not a loss — the running/next run's engine drains the
+ // same notice queue at its own input-assembly boundaries.
+ if (entry.status !== "idle" || entry.followUps.length > 0) return;
+ const input = entry.session.takeBackgroundNotices?.() ?? [];
+ if (input.length === 0) return;
+ this.launchTask(entry, input);
+ });
+ } catch (err) {
+ this.log(
+ `[background] notice task start failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ }
+
/**
* Drive the output stream in the background: publish each message + persist usage +
* persist LLM/tool errors; on completion (including errors) resets to idle and pushes
@@ -1585,6 +1695,10 @@ export class SessionManager {
// the next queued input auto-starts as an ordinary task. Fire-and-forget — it
// revalidates under the session lock.
if (entry.followUps.length > 0) void this.startQueuedFollowUp(entry.sessionId);
+ // Background completion notices that raced this run's exit (arrived after its last
+ // input-assembly boundary): start their delivery task now. No-op when a follow-up
+ // just launched — that run's engine drains the same queue.
+ else void this.startBackgroundNoticeTask(entry.sessionId);
}
}
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index e954cf9d..3fcb3581 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -8,23 +8,37 @@
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { DatabaseSync } from "node:sqlite";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
import {
+ Environment,
+ Session,
abortEvent,
approvalDecision,
assistantText,
compactionBegin,
compactionEnd,
+ emptyTokenCounts,
requestBegin,
requestEnd,
sessionMeta,
thinkingMessage,
+ tokenUsage,
toolCall,
toolCallOutput,
userSteeringText,
userText,
withOrigin,
} from "@prismshadow/penguin-core";
-import type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";
+import type {
+ ApproveFn,
+ GenerativeModelParameters,
+ LLMInterface,
+ LLMOutcome,
+ OmniMessage,
+ TextPayload,
+} from "@prismshadow/penguin-core";
import { openDatabase } from "../src/db/database.js";
import { HttpError } from "../src/http/errors.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
@@ -287,6 +301,207 @@ describe("session-manager", () => {
expect(seen).toEqual(["high", undefined]);
});
+ it("a background notice arriving while idle auto-starts a task carrying the taken notices", async () => {
+ sessions.updateApprovalMode("session-1", "allow-all");
+ let noticeCb: (() => void) | null = null;
+ const queue: OmniMessage[] = [];
+ const runInputs: OmniMessage[][] = [];
+ const fake: RuntimeSession = {
+ sessionId: "session-1",
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ onBackgroundNotice: (cb) => (noticeCb = cb),
+ takeBackgroundNotices: () => queue.splice(0),
+ async *run(input: OmniMessage[]) {
+ runInputs.push(input);
+ yield assistantText("ok");
+ },
+ async *compact(): AsyncGenerator<OmniMessage> {},
+ };
+ const manager = makeManager(loaderOf(fake));
+ // First task loads the entry (which registers the notice listener) and finishes.
+ await manager.startTask("session-1", [userText("hi")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle" && runInputs.length === 1);
+ expect(noticeCb).not.toBeNull();
+
+ // A completion notice lands while idle: the manager takes the queue and starts a task with it.
+ const events = capture("session-1");
+ const notice = userText("[background_task_done]\nkind: command\n[/background_task_done]");
+ queue.push(notice);
+ noticeCb!();
+ await waitFor(() => manager.statusOf("session-1") === "idle" && runInputs.length === 2);
+ expect(runInputs[1]).toEqual([notice]);
+ expect(queue).toHaveLength(0);
+ // The notice input was published to subscribers like any task input.
+ expect(events.some((e) => e.data.includes("background_task_done"))).toBe(true);
+
+ // An empty queue signal is a no-op (no phantom task).
+ noticeCb!();
+ await new Promise((r) => setTimeout(r, 50));
+ expect(runInputs).toHaveLength(2);
+ });
+
+ it("live-forwarded background-subagent messages publish to the channel and record usage", async () => {
+ let forward: ((msg: OmniMessage) => void) | null = null;
+ const fake: RuntimeSession = {
+ sessionId: "session-1",
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ onBackgroundMessage: (cb) => (forward = cb),
+ async *run() {},
+ async *compact(): AsyncGenerator<OmniMessage> {},
+ };
+ const manager = makeManager(loaderOf(fake));
+ manager.adopt(sessions.findById("session-1")!, fake);
+ expect(forward).not.toBeNull();
+ const events = capture("session-1");
+ const child = withOrigin(assistantText("child progress"), "session-child-1");
+ forward!(child);
+ expect(events.some((e) => e.data.includes("child progress"))).toBe(true);
+ // Usage recording rode along (same recorder drive uses).
+ expect(recorded).toContain(child);
+ });
+
+ it("adopt registers the notice listener too (a freshly created session, no loader involved)", async () => {
+ // Regression guard: POST /sessions enters the active table through adopt, not
+ // ensureEntry — a listener registered only on the loader path left brand-new sessions
+ // unable to deliver idle-arrival completion reports (the real-app no-notification bug).
+ sessions.updateApprovalMode("session-1", "allow-all");
+ let noticeCb: (() => void) | null = null;
+ const queue: OmniMessage[] = [];
+ const runInputs: OmniMessage[][] = [];
+ const fake: RuntimeSession = {
+ sessionId: "session-1",
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ onBackgroundNotice: (cb) => (noticeCb = cb),
+ takeBackgroundNotices: () => queue.splice(0),
+ async *run(input: OmniMessage[]) {
+ runInputs.push(input);
+ yield assistantText("ok");
+ },
+ async *compact(): AsyncGenerator<OmniMessage> {},
+ };
+ const manager = makeManager(loaderOf(fake));
+ const row = sessions.findById("session-1")!;
+ manager.adopt(row, fake);
+ expect(noticeCb).not.toBeNull();
+ queue.push(userText("[background_task_done]\nkind: command\n[/background_task_done]"));
+ noticeCb!();
+ await waitFor(() => manager.statusOf("session-1") === "idle" && runInputs.length === 1);
+ expect(queue).toHaveLength(0);
+ });
+
+ it("end-to-end: a run_in_background command finishing after idle reaches the event channel as a harness user message", async () => {
+ // Full production chain with the REAL core pieces — Session, engine, Environment and an
+ // actual OS process — under the real SessionManager (loaded via the loader, which is
+ // what registers the notice listener). Only the LLM is scripted. This is the frontend's
+ // exact feed: the channel events asserted on are what SSE relays byte-for-byte.
+ sessions.updateApprovalMode("session-1", "allow-all");
+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-bge2e-"));
+ const environment = new Environment({
+ workspaceDir: dir,
+ toolConfig: {
+ customTools: [
+ {
+ name: "exec_command",
+ description: "run",
+ permission: "rw",
+ timeoutMs: 120000,
+ maxOutputLength: 16000,
+ },
+ ],
+ mcpServers: [],
+ },
+ });
+ // Turn 1: launch a command that outlives the task; turn 2: final reply (task ends,
+ // session idle, process still running); turn 3 is the auto-started notice task.
+ const llm = new (class implements LLMInterface {
+ calls = 0;
+ inputs: OmniMessage[][] = [];
+ async *streamGenerate(
+ params: GenerativeModelParameters,
+ ): AsyncGenerator<OmniMessage, LLMOutcome> {
+ this.calls += 1;
+ this.inputs.push(params.newMessages);
+ if (this.calls === 1) {
+ yield toolCall({
+ name: "exec_command",
+ arguments: JSON.stringify({
+ cmd: "printf 'serving'; sleep 1",
+ run_in_background: true,
+ }),
+ toolCallId: "tc_bg",
+ stopReason: "completed",
+ });
+ } else {
+ yield assistantText(`reply ${this.calls}`);
+ }
+ yield tokenUsage(emptyTokenCounts(), {
+ cache_read: 0,
+ cache_write: 0,
+ output: 1,
+ total: 2,
+ });
+ return { status: "completed" };
+ }
+ })();
+ const session = new Session({
+ meta: {
+ session_id: "session-1",
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 100000,
+ system_prompt: "sp",
+ agent_state: dir,
+ workspace: dir,
+ },
+ bootstrap: async () => ({ tools: await environment.listTools(), llm, mcp: [] }),
+ mcpServers: [],
+ environment,
+ imagesDir: path.join(dir, "images"),
+ modelHasVision: true,
+ });
+ try {
+ const manager = makeManager(loaderOf(session as unknown as RuntimeSession));
+ const events = capture("session-1");
+ await manager.startTask("session-1", [userText("start a dev server")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle" && llm.calls === 2, 5000);
+ // The task is over, the background process is still alive, and no notice exists yet —
+ // what follows is genuinely the idle-arrival path.
+ expect(events.some((e) => e.data.includes("background_task_done"))).toBe(false);
+
+ // The process exits ~1s in: the completion report must land on the channel as a
+ // harness user message and auto-start a task the model answers.
+ await waitFor(() => events.some((e) => e.data.includes("background_task_done")), 8000);
+ const notice = events.find((e) => e.data.includes("background_task_done"))!;
+ expect(notice.data).toContain('"sender":"harness"');
+ expect(notice.data).toContain('"role":"user"');
+ expect(notice.data).toContain("serving");
+ await waitFor(() => llm.calls === 3 && manager.statusOf("session-1") === "idle", 5000);
+ const turn3 = llm.inputs[2]!.map((m) => (m.payload as { text?: string }).text ?? "");
+ expect(turn3.join("\n")).toContain("[background_task_done]");
+ // The auto task's state flips were broadcast too (the frontend's input gating):
+ // one running per task, so the notice task makes it at least two.
+ const running = events.filter(
+ (e) => e.data.includes('"type":"task_state"') && e.data.includes('"state":"running"'),
+ );
+ expect(running.length).toBeGreaterThan(1);
+ } finally {
+ session.dispose();
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
it("a level pinned on the Session applies to later Tasks that carry none (a request's own level still wins)", async () => {
sessions.updateApprovalMode("session-1", "allow-all");
const seen: (string | undefined)[] = [];
@@ -972,6 +1187,57 @@ describe("session-manager", () => {
await waitFor(() => manager.statusOf("session-1") === "idle");
});
+ it("sweepIdle: a working background subagent pins the entry, and its live messages count as activity", async () => {
+ // A run_in_background child outlives the task that launched it. Evicting the entry
+ // while it works drops the very Session its completion report is queued on.
+ let running = true;
+ let loads = 0;
+ let forward: ((msg: OmniMessage) => void) | null = null;
+ const fake = (): RuntimeSession => ({
+ sessionId: "session-1",
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ hasRunningBackgroundSubagents: () => running,
+ onBackgroundMessage: (cb) => (forward = cb),
+ async *run() {},
+ async *compact(): AsyncGenerator<OmniMessage> {},
+ });
+ const manager = makeManager({
+ load: async () => {
+ loads++;
+ return fake();
+ },
+ });
+ manager.adopt(ROW, fake());
+ const long = 31 * 60 * 1000;
+
+ // Far past the idle timeout, but the child is still working: the entry stays.
+ manager.sweepIdle(Date.now() + long, 30 * 60 * 1000);
+ sessions.updateApprovalMode("session-1", "allow-all");
+ await manager.startTask("session-1", [userText("a")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ expect(loads).toBe(0);
+
+ // The child streaming is activity in its own right, so the idle clock restarts with it.
+ expect(forward).not.toBeNull();
+ const before = Date.now();
+ forward!(withOrigin(assistantText("child progress"), "session-child-1"));
+ manager.sweepIdle(before + long, 30 * 60 * 1000);
+ await manager.startTask("session-1", [userText("b")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ expect(loads).toBe(0);
+
+ // Once it settles, the entry is an ordinary idle one again and evicts on schedule.
+ running = false;
+ manager.sweepIdle(Date.now() + long, 30 * 60 * 1000);
+ await manager.startTask("session-1", [userText("c")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ expect(loads).toBe(1);
+ });
+
it("compact: sets compacting, output goes to the channel, returns to idle at the end", async () => {
const manager = makeManager(loaderOf(approvalFakeSession("session-1")));
const events = capture("session-1");
diff --git a/packages/server/test/session-processes.test.ts b/packages/server/test/session-processes.test.ts
index 88957d68..e89e57fe 100644
--- a/packages/server/test/session-processes.test.ts
+++ b/packages/server/test/session-processes.test.ts
@@ -26,6 +26,7 @@ function processesFakeSession(
sessionId: string,
procs: BackgroundCommandInfo[],
kills: string[],
+ probes?: string[],
): RuntimeSession {
return {
sessionId,
@@ -37,6 +38,9 @@ function processesFakeSession(
async *run(_input: OmniMessage[], _opts: { approve: ApproveFn; signal: AbortSignal }) {},
async *compact() {},
listBackgroundCommands: () => [...procs],
+ probeBackgroundCommandServices: async () => {
+ probes?.push(sessionId);
+ },
killBackgroundCommand: (processId: string) => {
const i = procs.findIndex((p) => p.processId === processId);
if (i === -1) return false;
@@ -53,6 +57,7 @@ describe("session processes routes", () => {
let outsider: ReturnType<typeof apiClient>;
let procs: BackgroundCommandInfo[];
let kills: string[];
+ let probes: string[];
const sessionRow = (sessionId: string): SessionRow => ({
sessionId,
@@ -81,6 +86,7 @@ describe("session processes routes", () => {
cwd: "/tmp/w",
startedAt: STARTED_AT,
running: true,
+ serviceUrl: "http://localhost:5173/",
},
{
processId: "proc-22222222",
@@ -92,8 +98,9 @@ describe("session processes routes", () => {
},
];
kills = [];
+ probes = [];
t.deps.sessionsRepo.insert(sessionRow(SID));
- t.deps.manager.adopt(sessionRow(SID), processesFakeSession(SID, procs, kills));
+ t.deps.manager.adopt(sessionRow(SID), processesFakeSession(SID, procs, kills, probes));
// A second session with no runtime entry: truthfully reports no processes.
t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED));
});
@@ -113,6 +120,7 @@ describe("session processes routes", () => {
cwd: "/tmp/w",
startedAt: new Date(STARTED_AT).toISOString(),
running: true,
+ serviceUrl: "http://localhost:5173/",
},
{
processId: "proc-22222222",
@@ -124,6 +132,9 @@ describe("session processes routes", () => {
},
]);
+ // The route refreshed the listen-port probes before listing (first fetch carries probed URLs).
+ expect(probes).toEqual([SID]);
+
const unloaded = await api.get(`/api/sessions/${SID_UNLOADED}/processes`);
expect(unloaded.status).toBe(200);
expect(((await unloaded.json()) as SessionProcessesResponse).processes).toEqual([]);
diff --git a/packages/web/e2e/background-notify.spec.mjs b/packages/web/e2e/background-notify.spec.mjs
new file mode 100644
index 00000000..ac760f37
--- /dev/null
+++ b/packages/web/e2e/background-notify.spec.mjs
@@ -0,0 +1,72 @@
+/**
+ * Background completion notification, end to end in the real app: a task launches an
+ * exec_command with run_in_background and finishes while the command still runs; when the
+ * command exits, the harness-injected [background_task_done] user message must appear in
+ * the OPEN chat page — collapsed into the one-line notice banner — followed by the model's
+ * acknowledgement turn, with NO manual interaction in between. Also checks the launched
+ * command shows up in the session's process list like any promoted background process.
+ * Mock branches: "background notify test" in mock-llm.mjs.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "bgnotifyuser";
+const P = "password123";
+
+test("a run_in_background completion reaches the open chat page unprompted", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ // allow-all: the exec runs without a manual approval stop.
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+ const sessionId = sess.session.sessionId;
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("background notify test");
+ await page.getByRole("button", { name: "发送" }).click();
+
+ // Turn 2 closes the task while the background command is still running.
+ await expect(page.getByText("Started in the background; the report will follow.")).toBeVisible({
+ timeout: 30_000,
+ });
+
+ // The launched command is a normal background process: the header stats show a running
+ // service (same registry as the promoted-past-yield path).
+ const detailsBtn = page.locator('button[title="Session 信息"]');
+ await expect(detailsBtn.locator('span[title="1 个运行中的服务"]')).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // From here on: NO interaction. The command exits ~6s in; the harness user message must
+ // appear as the collapsed one-line banner, and the model's acknowledgement turn after it.
+ await expect(page.getByText("后台命令完成")).toBeVisible({ timeout: 30_000 });
+ await expect(
+ page.getByText("Acknowledged: the background command finished (bg-ack)."),
+ ).toBeVisible({ timeout: 30_000 });
+});
diff --git a/packages/web/e2e/background-subagent.spec.mjs b/packages/web/e2e/background-subagent.spec.mjs
new file mode 100644
index 00000000..db5784d8
--- /dev/null
+++ b/packages/web/e2e/background-subagent.spec.mjs
@@ -0,0 +1,115 @@
+/**
+ * Background subagent, end to end in the real app: the parent launches run_subagent with
+ * run_in_background and closes its task while the child still works (its exec_command
+ * sleeps ~1s). With no interaction after that: the subagents panel must show the child
+ * (live, then settled), the child's streamed activity must be visible, the completion
+ * report must arrive as the collapsed notice, and the child's own trace must contain a
+ * successfully completed exec_command — not an aborted or denied one.
+ * Mock branches: "background subagent test" in mock-llm.mjs.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "bgsubuser";
+const P = "password123";
+
+test("a run_in_background subagent runs to completion and reports back unprompted", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+ const sessionId = sess.session.sessionId;
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("background subagent test");
+ await page.getByRole("button", { name: "发送" }).click();
+
+ // The parent's task closes while the child still runs.
+ await expect(page.getByText("Subagent dispatched in the background.")).toBeVisible({
+ timeout: 30_000,
+ });
+
+ // The subagents panel knows the child exists (auto-open on spawn, or via the toggle).
+ const agentsToggle = page.getByRole("button", { name: "智能体面板" });
+ if ((await agentsToggle.getAttribute("aria-expanded")) !== "true") {
+ await agentsToggle.click();
+ }
+ await expect(page.getByRole("heading", { name: "智能体面板" })).toBeVisible();
+
+ // No interaction from here: the child's live activity streams in (its exec_command call
+ // is visible without any poll), then the completion notice and the model's follow-up.
+ await expect(page.getByText("后台任务完成")).toBeVisible({ timeout: 30_000 });
+ await expect(
+ page.getByText("Acknowledged: the background command finished (bg-ack)."),
+ ).toBeVisible({ timeout: 30_000 });
+});
+
+test("a failing background subagent still reports back with the failed state", async ({ page }) => {
+ await provisionAndLogin(page.request, "bgsubfail", P);
+
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },
+ },
+ ],
+ },
+ });
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+ await page.goto(`${BASE}/chat/${sess.session.sessionId}`);
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("background subagent fail test");
+ await page.getByRole("button", { name: "发送" }).click();
+ await expect(page.getByText("Failing subagent dispatched in the background.")).toBeVisible({
+ timeout: 30_000,
+ });
+
+ // The child's request is rejected as an auth failure (never retried): its run fails at
+ // once — and the failed completion report must still reach the open page unprompted.
+ await expect(page.getByText("后台任务失败")).toBeVisible({ timeout: 30_000 });
+ await expect(
+ page.getByText("Acknowledged: the background command finished (bg-ack)."),
+ ).toBeVisible({ timeout: 30_000 });
+});
diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjs
index 09c73ece..0507debd 100644
--- a/packages/web/e2e/mock-llm.mjs
+++ b/packages/web/e2e/mock-llm.mjs
@@ -27,6 +27,8 @@ import http from "node:http";
/** The run_subagent prompt; also the marker the mock uses to detect "this is the child session's own request". */
const SUBAGENT_PROMPT = "Count the TODO items in the repository";
+/** Background-subagent FAILURE prompt: the child session's every request is rejected 400, so its run fails after the retry ladder. */
+const SUBAGENT_FAIL_PROMPT = "Fail the TODO count on purpose";
const PORT = Number(process.env.MOCK_PORT || 8931);
@@ -144,6 +146,24 @@ const server = http.createServer((req, res) => {
return;
}
+ // Background-subagent FAILURE case (background-subagent.spec): the child session's own
+ // requests (its context is just the fail prompt) are rejected 401 invalid_api_key —
+ // classified `auth`, which the engine never retries, so the child's run fails at once
+ // and the FAILED completion report must still arrive promptly (a retryable failure
+ // would climb the full ~60s reconnect ladder first — same terminal state, just slow).
+ // Gated on !isTitle so the failed child's title request falls back quietly.
+ if (
+ flat.includes(SUBAGENT_FAIL_PROMPT) &&
+ !flat.includes("background subagent fail test") &&
+ !isTitle
+ ) {
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(
+ JSON.stringify({ error: { code: "invalid_api_key", message: "mock child failure" } }),
+ );
+ return;
+ }
+
// "Quota give-up" test case: EVERY request is rejected 403 with the quota code — the
// spec clicks the reconnect countdown's give-up button mid-wait, so the conversation
// must never recover on its own (the abort ends it instead).
@@ -279,6 +299,84 @@ const server = http.createServer((req, res) => {
return;
}
+ // Background-notify test case (background-notify.spec): turn 1 launches a command with
+ // run_in_background (returns a process_id immediately); turn 2 closes the task while
+ // the command is still running; ~2s later the command exits and the harness injects a
+ // [background_task_done] user message that auto-starts a task — whose turn is keyed on
+ // the LAST message (the whole-history flags can't shadow it) and acknowledges.
+ const lastText = JSON.stringify(messages[messages.length - 1] ?? {});
+ if (lastText.includes("background_task_done")) {
+ block(res, 0, { type: "text", text: "" }, [
+ { type: "text_delta", text: "Acknowledged: the background command finished (bg-ack)." },
+ ]);
+ messageStop(res, "end_turn", 9);
+ return;
+ }
+ if (flat.includes("background subagent fail test")) {
+ if (!hasToolResult) {
+ block(res, 0, { type: "tool_use", id: "toolu_bgsubf_1", name: "run_subagent", input: {} }, [
+ { type: "input_json_delta", partial_json: '{"prompt": ' },
+ {
+ type: "input_json_delta",
+ partial_json: `${JSON.stringify(SUBAGENT_FAIL_PROMPT)}, "run_in_background": true}`,
+ },
+ ]);
+ messageStop(res, "tool_use", 15);
+ return;
+ }
+ block(res, 0, { type: "text", text: "" }, [
+ { type: "text_delta", text: "Failing subagent dispatched in the background." },
+ ]);
+ messageStop(res, "end_turn", 11);
+ return;
+ }
+
+ // Background-subagent test case (background-subagent.spec): the parent launches the
+ // subagent with run_in_background and closes its turn; the child branch (isSubagentTurn)
+ // runs its usual exec_command (sleep 1) then reports. The completion arrives as a
+ // [background_task_done] user message handled by the lastText branch above.
+ if (flat.includes("background subagent test")) {
+ if (!hasToolResult) {
+ setTimeout(() => {
+ block(
+ res,
+ 0,
+ { type: "tool_use", id: "toolu_bgsub_1", name: "run_subagent", input: {} },
+ [
+ { type: "input_json_delta", partial_json: '{"prompt": ' },
+ {
+ type: "input_json_delta",
+ partial_json: `${JSON.stringify(SUBAGENT_PROMPT)}, "run_in_background": true}`,
+ },
+ ],
+ );
+ messageStop(res, "tool_use", 15);
+ }, 300);
+ return;
+ }
+ block(res, 0, { type: "text", text: "" }, [
+ { type: "text_delta", text: "Subagent dispatched in the background." },
+ ]);
+ messageStop(res, "end_turn", 11);
+ return;
+ }
+
+ if (flat.includes("background notify test")) {
+ if (!hasToolResult) {
+ block(res, 0, { type: "tool_use", id: "toolu_bgn_1", name: "exec_command", input: {} }, [
+ { type: "input_json_delta", partial_json: '{"cmd": "echo bg-notify; sleep 6",' },
+ { type: "input_json_delta", partial_json: ' "run_in_background": true}' },
+ ]);
+ messageStop(res, "tool_use", 14);
+ return;
+ }
+ block(res, 0, { type: "text", text: "" }, [
+ { type: "text_delta", text: "Started in the background; the report will follow." },
+ ]);
+ messageStop(res, "end_turn", 11);
+ return;
+ }
+
if (isSubagentTurn) {
// Child turn 1: one tool call before reporting (see the header comment — the child needs
// its own approval point for the nested-approval e2e). The command sleeps ~1s so the
diff --git a/packages/web/src/features/chat/agent-handoff.ts b/packages/web/src/features/chat/agent-handoff.ts
index 5fc1c432..2420590f 100644
--- a/packages/web/src/features/chat/agent-handoff.ts
+++ b/packages/web/src/features/chat/agent-handoff.ts
@@ -17,11 +17,13 @@ import { buildHandoffMessage, buildModelSwitchMessage } from "@prismshadow/pengu
import type { AgentSummary } from "@prismshadow/penguin-server/api";
export {
+ parseBackgroundTaskDoneMessage,
parseHandoffMessage,
parseModelSwitchMessage,
parseScheduledMessage,
} from "@prismshadow/penguin-core/markers";
export type {
+ BackgroundTaskDone,
HandoffOrigin,
ModelSwitchOrigin,
ScheduledOrigin,
diff --git a/packages/web/src/features/chat/agent-topology.ts b/packages/web/src/features/chat/agent-topology.ts
index e4cb8dc4..e6066b02 100644
--- a/packages/web/src/features/chat/agent-topology.ts
+++ b/packages/web/src/features/chat/agent-topology.ts
@@ -20,6 +20,10 @@
* text measurement; graphs are small (≲15 nodes) and the view scrolls horizontally on overflow.
*/
import type { ChatItem, StreamModel } from "../../lib/omni/stream-model";
+import { parseBackgroundTaskDoneMessage } from "./agent-handoff";
+
+/** Marker tag of a harness completion notice; the cheap prefilter before the marker parse. */
+const BACKGROUND_DONE_TAG = "background_task_done";
export interface TopologyNode {
sessionId: string;
@@ -52,15 +56,45 @@ export interface TopologyNode {
elapsedMs?: number;
}
-/** Index of the latest Task's first item (the last user_text/user_image — the reducer's "starts a new Task" predicate); 0 when there is none (mid-stream join). */
+/**
+ * Whether an item opens a new PANEL scope. The reducer's "starts a new Task" predicate
+ * (user_text/user_image), minus one exception: a `[background_task_done]` harness notice does
+ * start a chat Task (its auto-run answers it), but for the topology it belongs to the Task
+ * that launched the background work — slicing there would split a background subagent's spawn
+ * from its completion and reset the panel the moment the report lands.
+ */
+function isScopeStart(item: ChatItem): boolean {
+ if (item.kind === "user_image") return true;
+ if (item.kind !== "user_text") return false;
+ // Cheap reject first: these predicates run over every item on every render, and the marker
+ // parse is two full-text regex scans — only text that actually carries the tag pays for it.
+ if (!item.text.includes(`[${BACKGROUND_DONE_TAG}]`)) return true;
+ return parseBackgroundTaskDoneMessage(item.text) === null;
+}
+
+/** Index of the latest Task's first item (see isScopeStart); 0 when there is none (mid-stream join). */
export function latestTaskStart(items: readonly ChatItem[]): number {
for (let i = items.length - 1; i >= 0; i--) {
- const kind = items[i]!.kind;
- if (kind === "user_text" || kind === "user_image") return i;
+ if (isScopeStart(items[i]!)) return i;
}
return 0;
}
+/**
+ * Task starts as the STREAM MODEL counts them — every user_text/user_image, notices included,
+ * so the number stays 1:1 with the reducer's own `startTask` calls. The header's cost tracker
+ * keys its Task-boundary fold on exactly that (see header-stats.ts): a notice-triggered task
+ * zeroes the model's per-Task usage buckets, so a count that skipped it would drop the finished
+ * Task's live cost without ever folding it into the settled base.
+ */
+export function modelTaskStartCount(items: readonly ChatItem[]): number {
+ let n = 0;
+ for (const item of items) {
+ if (item.kind === "user_text" || item.kind === "user_image") n += 1;
+ }
+ return n;
+}
+
/**
* Count of Task-starting user items (the reducer's startTask predicate: user_text/user_image —
* steering chips and internal injections such as compaction summaries never become such items,
@@ -70,7 +104,7 @@ export function latestTaskStart(items: readonly ChatItem[]): number {
export function taskStartCount(items: readonly ChatItem[]): number {
let n = 0;
for (const item of items) {
- if (item.kind === "user_text" || item.kind === "user_image") n += 1;
+ if (isScopeStart(item)) n += 1;
}
return n;
}
@@ -143,16 +177,14 @@ export function extractTopologyForChild(
// the latest Task). Same "starts a new Task" predicate as latestTaskStart.
let start = 0;
for (let i = at; i >= 0; i--) {
- const kind = items[i]!.kind;
- if (kind === "user_text" || kind === "user_image") {
+ if (isScopeStart(items[i]!)) {
start = i;
break;
}
}
let end = items.length;
for (let i = at + 1; i < items.length; i++) {
- const kind = items[i]!.kind;
- if (kind === "user_text" || kind === "user_image") {
+ if (isScopeStart(items[i]!)) {
end = i;
break;
}
@@ -162,6 +194,40 @@ export function extractTopologyForChild(
});
}
+/** Launch note of a run_in_background subagent: binds the card to its registry handle. */
+const BG_SUBAGENT_LAUNCH_RE =
+ /\[subagent running in background with subagent_id (subagent-[0-9a-f]+)/;
+
+/**
+ * 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
+ * "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.
+ */
+function backgroundSubagentStates(slice: readonly ChatItem[]): Map<string, "running" | "done"> {
+ const states = new Map<string, "running" | "done">();
+ for (const item of slice) {
+ if (item.kind === "user_text") {
+ const done = parseBackgroundTaskDoneMessage(item.text);
+ if (done !== null && done.done.kind === "subagent") states.set(done.done.id, "done");
+ continue;
+ }
+ if (item.kind !== "tool_call" || item.output.length === 0) continue;
+ for (const m of item.output.matchAll(
+ /\[subagent (?:running in background|still running) with subagent_id (subagent-[0-9a-f]+)/g,
+ )) {
+ states.set(m[1]!, "running");
+ }
+ for (const m of item.output.matchAll(
+ /\[subagent idle with subagent_id (subagent-[0-9a-f]+)|\[subagent (subagent-[0-9a-f]+) (?:aborted and removed|was idle; session removed)/g,
+ )) {
+ states.set(m[1] ?? m[2]!, "done");
+ }
+ }
+ return states;
+}
+
/** Shared walker behind both extractions: builds the node list from one Task slice of the main items. */
function extractFromSlice(
slice: readonly ChatItem[],
@@ -218,13 +284,17 @@ function extractFromSlice(
walk(child.items, sessionId, origin);
};
+ const bgStates = backgroundSubagentStates(slice);
const walk = (items: readonly ChatItem[], parentId: string, parentOrigin: string[]): void => {
for (const item of items) {
if (item.kind === "tool_call" && item.subagent && item.subagentSessionId) {
+ // A background launch's card completes immediately, so its running state comes from
+ // the harness's own notes about the handle instead of the card's output stream.
+ const bgId = BG_SUBAGENT_LAUNCH_RE.exec(item.output)?.[1] ?? null;
addChild(
item.subagentSessionId,
item.subagent,
- !item.outputComplete,
+ bgId !== null ? bgStates.get(bgId) !== "done" : !item.outputComplete,
parentId,
parentOrigin,
agentIdFromRunSubagentArgs(item.argumentsText),
diff --git a/packages/web/src/features/chat/background-done-banner.tsx b/packages/web/src/features/chat/background-done-banner.tsx
new file mode 100644
index 00000000..75df8a87
--- /dev/null
+++ b/packages/web/src/features/chat/background-done-banner.tsx
@@ -0,0 +1,33 @@
+/**
+ * Completion notice of a background task (`[background_task_done]`, a harness-injected user
+ * message reporting that a run_in_background command/subagent settled): a standalone card in
+ * the work group's own form — collapsed it reads exactly like a settled "Done" group header
+ * (same chrome, title styling, sticky pinning against the scrollport), showing only the
+ * outcome label; expanded, the report body (registry handle, what ran, exit detail, output
+ * tail) renders in the tool cards' output styling. The Trace page shows the raw marker text
+ * as-is.
+ */
+import { S } from "../../lib/strings";
+import type { BackgroundTaskDone } from "./agent-handoff";
+import { StatusIcon } from "../../components/ui/status-icon";
+import {
+ DISCLOSURE_CARD_CLASS,
+ DISCLOSURE_OUTPUT_PRE_CLASS,
+ DisclosureRow,
+} from "./disclosure-row";
+
+export function BackgroundDoneBanner({ done, body }: { done: BackgroundTaskDone; body: string }) {
+ const ok = done.status === "completed";
+ return (
+ <div className={DISCLOSURE_CARD_CLASS}>
+ <DisclosureRow
+ variant="header"
+ sticky
+ icon={<StatusIcon state={ok ? "done" : "failed"} label={done.status} />}
+ label={S.chat.backgroundDone(done.kind, ok)}
+ >
+ <pre className={DISCLOSURE_OUTPUT_PRE_CLASS}>{body ? `${done.id}\n${body}` : done.id}</pre>
+ </DisclosureRow>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 64a6ad28..faf3716b 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -85,7 +85,7 @@ import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
import { MessageStream } from "./message-stream";
import type { StreamRenderContext } from "./message-stream";
import type { ForkTarget } from "./task-stats-line";
-import { latestTaskHasSubagent, taskStartCount } from "./agent-topology";
+import { latestTaskHasSubagent, modelTaskStartCount, taskStartCount } from "./agent-topology";
import { ChatInput } from "./chat-input";
import {
compactionTally,
@@ -1581,7 +1581,11 @@ export function ChatPage() {
stream.model,
advanceCostStat(costHoldRef.current, {
sessionId: selected?.sessionId ?? null,
- taskCount,
+ // The cost tracker's Task boundary is the MODEL's, not the panel's: a completion notice
+ // opens a new Task (zeroing the per-Task usage buckets) even though the panel keeps it
+ // inside the launching Task's scope, so it must be counted here or the finished half's
+ // live cost is dropped instead of folded.
+ taskCount: modelTaskStartCount(stream.model.items),
taskOpen: stream.model.taskOpen,
loading: stream.loading,
liveUsd: liveTaskUsd,
@@ -1885,9 +1889,26 @@ export function ChatPage() {
<span className="block truncate font-mono text-xs" title={p.cmd}>
{p.cmd}
</span>
- <span className="block text-[11px] text-gray-400 dark:text-gray-500">
+ <span className="block truncate text-[11px] text-gray-400 dark:text-gray-500">
{formatDateTime(p.startedAt)}
{p.pid !== null && ` · pid ${p.pid}`}
+ {/* Detected service URL (output scan or port probe), running rows
+ only — an exited process serves nothing to open. Scheme dropped
+ at this size; the tooltip and the link carry the full URL. */}
+ {p.running && p.serviceUrl !== undefined && (
+ <>
+ {" · "}
+ <a
+ href={p.serviceUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={p.serviceUrl}
+ className="text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-700 hover:decoration-gray-500 dark:text-gray-400 dark:decoration-gray-600 dark:hover:text-gray-200"
+ >
+ {p.serviceUrl.replace(/^https?:\/\//i, "")}
+ </a>
+ </>
+ )}
</span>
</span>
{p.running ? (
diff --git a/packages/web/src/features/chat/disclosure-row.tsx b/packages/web/src/features/chat/disclosure-row.tsx
new file mode 100644
index 00000000..bbff2b1c
--- /dev/null
+++ b/packages/web/src/features/chat/disclosure-row.tsx
@@ -0,0 +1,121 @@
+/**
+ * The shared "collapsible one-liner" shell: a full-width row — status icon, label, optional
+ * trailing detail, chevron — that expands to a caller-styled body. Extracted verbatim from
+ * the thinking block so every disclosure row in the transcript (thinking, the background
+ * completion notice) shares one source of truth for width, padding, both color states and
+ * the chevron interaction, and cannot drift apart. The tool cards keep their own richer row
+ * structure but reference the same class constants below.
+ */
+import { useRef, useState } from "react";
+import type { ReactNode } from "react";
+import { Chevron } from "../../components/ui/chevron";
+
+/**
+ * The row itself (collapsed and expanded state share it; the hover tone is the "open or
+ * close me" affordance). Byte-identical to the class the thinking block and tool-card rows
+ * carried before the extraction.
+ */
+export const DISCLOSURE_ROW_CLASS =
+ "flex w-full items-center gap-2 bg-white px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800";
+
+/**
+ * Stacked-sticky positioning for rows living inside the work group: while a row's expanded
+ * body scrolls, the row pins right below the stuck group header (top-4 = the header's -top-4
+ * offset + its 2rem height). Standalone rows (a single-row card) omit it.
+ */
+export const DISCLOSURE_ROW_STICKY_CLASS = "sticky top-4 z-[4]";
+
+/** The row's text label (the thinking block's exact label styling). */
+export const DISCLOSURE_LABEL_CLASS = "shrink-0 text-xs text-gray-500 dark:text-gray-400";
+
+/**
+ * The header-family row — the work group's "Running / Done" summary bar (its exact chrome:
+ * gray ground, taller padding, stronger hover). A standalone disclosure that should read
+ * like a settled work group (the background completion notice) uses this variant.
+ */
+export const DISCLOSURE_HEADER_ROW_CLASS =
+ "flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800";
+
+/** Header-level sticky positioning (the work-group header's own: pins against the message list's scrollport, one z level above the nested rows). */
+export const DISCLOSURE_HEADER_STICKY_CLASS = "sticky -top-4 z-[5]";
+
+/** The header-family title (the work-group header's title styling, minus the state-dependent color the caller appends). */
+export const DISCLOSURE_HEADER_TITLE_CLASS =
+ "shrink-0 text-[11px] font-semibold uppercase tracking-wide";
+
+/**
+ * Expanded plain-text body, the tool cards' output styling (an exec_command's expanded
+ * output): a bordered mono <pre> block. Referenced by tool-call-card and every disclosure
+ * body that shows raw output.
+ */
+export const DISCLOSURE_OUTPUT_PRE_CLASS =
+ "max-h-72 overflow-auto whitespace-pre-wrap border-t border-gray-100 px-3 py-2 text-xs leading-5 text-gray-600 dark:border-gray-800 dark:text-gray-300";
+
+/**
+ * The card container a row (or group of rows) sits in — the work group's exact chrome.
+ * A standalone disclosure row wraps itself in one so its width and framing match the
+ * neighboring groups.
+ */
+export const DISCLOSURE_CARD_CLASS =
+ "anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900";
+
+export function DisclosureRow({
+ icon,
+ label,
+ trailing,
+ variant = "row",
+ sticky = false,
+ defaultOpen = false,
+ children,
+}: {
+ /** Leading status icon slot (a StatusIcon, matching the thinking/tool rows). */
+ icon: ReactNode;
+ /** The row's one-line label (DISCLOSURE_LABEL_CLASS, or the header title styling for the header variant). */
+ label: string;
+ /** Optional detail between the label and the spacer (duration, a failure tag). */
+ trailing?: ReactNode;
+ /**
+ * "row" = a line inside the work group (the thinking block's form); "header" = the work
+ * group's own summary-bar form (the background notice's standalone card).
+ */
+ variant?: "row" | "header";
+ /** Pins the row while its body scrolls: nested rows under the stuck group header, a header against the scrollport (per variant). */
+ sticky?: boolean;
+ defaultOpen?: boolean;
+ /** Expanded body; the caller styles it (md body, output <pre>, …). */
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(defaultOpen);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const header = variant === "header";
+ const rowClass = header ? DISCLOSURE_HEADER_ROW_CLASS : DISCLOSURE_ROW_CLASS;
+ const stickyClass = header ? DISCLOSURE_HEADER_STICKY_CLASS : DISCLOSURE_ROW_STICKY_CLASS;
+ const labelClass = header
+ ? `${DISCLOSURE_HEADER_TITLE_CLASS} text-gray-500 dark:text-gray-400`
+ : DISCLOSURE_LABEL_CLASS;
+ return (
+ <div ref={rootRef}>
+ <button
+ type="button"
+ onClick={() => {
+ // Collapsing while the row is stuck: its real top sits above the fold — land the
+ // view back on the row (nearest = no movement for expanding / in-view collapse).
+ const willClose = open;
+ setOpen((v) => !v);
+ if (willClose) {
+ requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));
+ }
+ }}
+ aria-expanded={open}
+ className={`${sticky ? `${stickyClass} ` : ""}${rowClass}`}
+ >
+ {icon}
+ <span className={labelClass}>{label}</span>
+ {trailing}
+ <span className="min-w-0 flex-1" />
+ <Chevron open={open} className="text-gray-400" />
+ </button>
+ {open && children}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index ae77983e..b669f517 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -27,7 +27,9 @@ import { HandoffBanner, ModelSwitchBanner } from "./handoff-banner";
import { ScheduledBanner } from "./scheduled-banner";
import { SkillsBanner } from "./skills-banner";
import { AttachedFilesBanner } from "./attached-files-banner";
+import { BackgroundDoneBanner } from "./background-done-banner";
import {
+ parseBackgroundTaskDoneMessage,
parseHandoffMessage,
parseModelSwitchMessage,
parseScheduledMessage,
@@ -170,6 +172,12 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
// Source block for a chat opened by the /model switch: collapsed into a single-line switch notice, clickable to jump back to the source conversation.
const modelSwitch = parseModelSwitchMessage(item.text);
if (modelSwitch) return <ModelSwitchBanner origin={modelSwitch} />;
+ // Harness-injected completion notice of a run_in_background task: collapsed into a
+ // one-line banner with the report body below it (the raw block shows on the Trace page).
+ const backgroundDone = parseBackgroundTaskDoneMessage(item.text);
+ if (backgroundDone) {
+ return <BackgroundDoneBanner done={backgroundDone.done} body={backgroundDone.rest} />;
+ }
// A goal round's [goal] protocol prefix: collapsed into a round notice; the body after
// it (round 1: the user's original input, skill blocks and all; later rounds: the
// objective) continues down the normal parsing chain (the Trace shows the raw block).
diff --git a/packages/web/src/features/chat/thinking-block.tsx b/packages/web/src/features/chat/thinking-block.tsx
index 001ab019..6606e199 100644
--- a/packages/web/src/features/chat/thinking-block.tsx
+++ b/packages/web/src/features/chat/thinking-block.tsx
@@ -1,21 +1,20 @@
/**
* Thinking block: one row within the "Reasoning & Tools" group — status
- * icon + "Thinking" + elapsed time, click to expand the full thinking text. Shares the same row
- * style and set of running-state icons (in progress / done / failed) as tool cards.
+ * icon + "Thinking" + elapsed time, click to expand the full thinking text. Built on the
+ * shared disclosure shell (disclosure-row.tsx), so its row metrics and color states are the
+ * same source every other disclosure row uses; shares the running-state icons (in progress /
+ * done / failed) with tool cards.
*/
-import { useRef, useState } from "react";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import type { ThinkingItem } from "../../lib/omni/stream-model";
-import { Chevron } from "../../components/ui/chevron";
import { StatusIcon } from "../../components/ui/status-icon";
import type { RunState } from "../../components/ui/status-icon";
+import { DisclosureRow } from "./disclosure-row";
import { LiveDuration } from "./live-duration";
import { Md } from "./md";
export function ThinkingBlock({ item }: { item: ThinkingItem }) {
- const [open, setOpen] = useState(false);
- const rootRef = useRef<HTMLDivElement>(null);
const failed = item.stopReason !== undefined && item.stopReason !== "completed";
const state: RunState = item.streaming ? "running" : failed ? "failed" : "done";
const stateLabel = item.streaming
@@ -25,44 +24,26 @@ export function ThinkingBlock({ item }: { item: ThinkingItem }) {
: S.chat.workDone;
return (
- <div ref={rootRef}>
- {/* Stacked sticky, second level: while this row's expanded body scrolls, the row pins
- right BELOW the stuck group header (top-4 = the header's -top-4 offset + its 2rem
- height) — the bar directly above the content is always the section the reader is
- in, never a skipped level; rows push each other out at their section boundaries.
- The background must be opaque for the stuck state (at rest it matches the card). */}
- <button
- type="button"
- onClick={() => {
- // Collapsing while the row is stuck: its real top sits above the fold — land the
- // view back on the row (nearest = no movement for expanding / in-view collapse).
- const willClose = open;
- setOpen((v) => !v);
- if (willClose) {
- requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));
- }
- }}
- aria-expanded={open}
- className="sticky top-4 z-[4] flex w-full items-center gap-2 bg-white px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
- >
- <StatusIcon state={state} label={stateLabel} />
- <span className="shrink-0 text-xs text-gray-500 dark:text-gray-400">{S.chat.thinking}</span>
- <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">
- {item.streaming ? (
- <LiveDuration sinceMs={item.startedAtMs} />
- ) : item.durationMs !== undefined ? (
- humanizeDuration(item.durationMs)
- ) : null}
- </span>
- {failed && <span className="font-mono text-xs text-gray-400">[{item.stopReason}]</span>}
- <span className="min-w-0 flex-1" />
- <Chevron open={open} className="text-gray-400" />
- </button>
- {open && (
- <div className="md-body anim-fade mx-3 mb-2 rounded-md bg-gray-50 px-3 py-2 text-sm leading-relaxed text-gray-600 dark:bg-gray-900/60 dark:text-gray-400">
- <Md text={item.thinking} streaming={item.streaming} />
- </div>
- )}
- </div>
+ <DisclosureRow
+ sticky
+ icon={<StatusIcon state={state} label={stateLabel} />}
+ label={S.chat.thinking}
+ trailing={
+ <>
+ <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">
+ {item.streaming ? (
+ <LiveDuration sinceMs={item.startedAtMs} />
+ ) : item.durationMs !== undefined ? (
+ humanizeDuration(item.durationMs)
+ ) : null}
+ </span>
+ {failed && <span className="font-mono text-xs text-gray-400">[{item.stopReason}]</span>}
+ </>
+ }
+ >
+ <div className="md-body anim-fade mx-3 mb-2 rounded-md bg-gray-50 px-3 py-2 text-sm leading-relaxed text-gray-600 dark:bg-gray-900/60 dark:text-gray-400">
+ <Md text={item.thinking} streaming={item.streaming} />
+ </div>
+ </DisclosureRow>
);
}
diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsx
index bfe544ec..9495b204 100644
--- a/packages/web/src/features/chat/tool-call-card.tsx
+++ b/packages/web/src/features/chat/tool-call-card.tsx
@@ -21,6 +21,11 @@ import { stripAnsi } from "../../lib/strip-ansi";
import { approvalKey } from "../../lib/omni/stream-model";
import type { ToolCallItem } from "../../lib/omni/stream-model";
import { Chevron } from "../../components/ui/chevron";
+import {
+ DISCLOSURE_OUTPUT_PRE_CLASS,
+ DISCLOSURE_ROW_CLASS,
+ DISCLOSURE_ROW_STICKY_CLASS,
+} from "./disclosure-row";
import { ZoomableImage } from "../../components/ui/image-zoom";
import { StatusIcon } from "../../components/ui/status-icon";
import type { RunState } from "../../components/ui/status-icon";
@@ -282,7 +287,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen
requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));
}
}}
- className="sticky top-4 z-[4] flex w-full items-center gap-2 bg-white px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
+ className={`${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}
>
<StatusIcon state={state} label={stateLabel} />
<span className="shrink-0 truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-300">
@@ -364,7 +369,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen
</pre>
)}
{(item.output || item.outputStreaming) && (
- <pre className="max-h-72 overflow-auto whitespace-pre-wrap border-t border-gray-100 px-3 py-2 text-xs leading-5 text-gray-600 dark:border-gray-800 dark:text-gray-300">
+ <pre className={DISCLOSURE_OUTPUT_PRE_CLASS}>
{output}
{item.outputStreaming && <span className="animate-pulse">▌</span>}
</pre>
diff --git a/packages/web/src/features/chat/work-group.tsx b/packages/web/src/features/chat/work-group.tsx
index 0c4b8539..a6cccfe5 100644
--- a/packages/web/src/features/chat/work-group.tsx
+++ b/packages/web/src/features/chat/work-group.tsx
@@ -21,6 +21,12 @@ import { useEffect, useRef, useState } from "react";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import { Chevron } from "../../components/ui/chevron";
+import {
+ DISCLOSURE_CARD_CLASS,
+ DISCLOSURE_HEADER_ROW_CLASS,
+ DISCLOSURE_HEADER_STICKY_CLASS,
+ DISCLOSURE_HEADER_TITLE_CLASS,
+} from "./disclosure-row";
import { StatusIcon } from "../../components/ui/status-icon";
import { approvalKey } from "../../lib/omni/stream-model";
import type { ChatItem } from "../../lib/omni/stream-model";
@@ -94,10 +100,7 @@ export function WorkGroup({
// the exact same clipping (rounded corners included) without creating a scroll
// container, and a sticky element never leaves its containing block, so the stuck
// header itself is never clipped.
- <div
- ref={rootRef}
- className="anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900"
- >
+ <div ref={rootRef} className={DISCLOSURE_CARD_CLASS}>
{/* Group header: a distinct title bar (solid background), on a separate layer from the
step rows below it. Sticky against the message list's scrollport so a long expanded
group can be collapsed from anywhere inside it — without this, finding the start of
@@ -130,12 +133,12 @@ export function WorkGroup({
requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));
}
}}
- className="sticky -top-4 z-[5] flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800"
+ className={`${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}
>
<StatusIcon state={active ? "running" : "done"} />
{/* The title doubles as status: "Running" while in progress, "Done" when finished. */}
<span
- className={`shrink-0 text-[11px] font-semibold uppercase tracking-wide ${active ? toneInk.busy : "text-gray-500 dark:text-gray-400"}`}
+ className={`${DISCLOSURE_HEADER_TITLE_CLASS} ${active ? toneInk.busy : "text-gray-500 dark:text-gray-400"}`}
>
{active ? S.chat.workRunning : S.chat.workDone}
</span>
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index fcdea3d2..da9d3d6c 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1449,6 +1449,15 @@ Scenarios:
/** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
modelLockedHint: "Type /model to switch models",
scheduledFrom: (name: string) => `Triggered by scheduled task "${name}"`,
+ /** One-line notice of a `[background_task_done]` harness message (run_in_background completion): the collapsed row's whole label. */
+ backgroundDone: (kind: "command" | "subagent", ok: boolean) =>
+ kind === "command"
+ ? ok
+ ? "Background command finished"
+ : "Background command failed"
+ : ok
+ ? "Background task finished"
+ : "Background task failed",
emptyGreeting: "Start a new conversation",
/** Unified step-row titles (same header idiom as workRunning/workDone). */
mcpConnectTitle: "MCP connect",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 962bf77d..dafd1a72 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1404,6 +1404,15 @@ Benchmark:
/** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
modelLockedHint: "输入 /model 切换模型",
scheduledFrom: (name: string) => `由定时任务「${name}」触发`,
+ /** One-line notice of a `[background_task_done]` harness message (run_in_background completion): the collapsed row's whole label. */
+ backgroundDone: (kind: "command" | "subagent", ok: boolean): string =>
+ kind === "command"
+ ? ok
+ ? "后台命令完成"
+ : "后台命令失败"
+ : ok
+ ? "后台任务完成"
+ : "后台任务失败",
emptyGreeting: "开始一段新对话",
/** Unified step-row titles (same header idiom as workRunning/workDone). */
mcpConnectTitle: "MCP 连接",
diff --git a/packages/web/test/agent-topology.test.ts b/packages/web/test/agent-topology.test.ts
index 5de4674c..cc5dc04c 100644
--- a/packages/web/test/agent-topology.test.ts
+++ b/packages/web/test/agent-topology.test.ts
@@ -11,6 +11,7 @@ import { describe, expect, it, vi } from "vitest";
import {
approvalDecision,
assistantText,
+ buildBackgroundTaskDoneMessage,
imageUrlMessage,
sessionMeta,
toolCall,
@@ -37,6 +38,7 @@ import {
latestTaskStart,
layoutTopology,
modelAtOrigin,
+ modelTaskStartCount,
NODE_H,
NODE_W,
PAD,
@@ -494,3 +496,76 @@ describe("layoutTopology", () => {
expect(layout.height).toBe(PAD * 2 + NODE_H);
});
});
+
+describe("background subagents in the topology", () => {
+ const LAUNCH = (id: string) =>
+ `[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]`;
+ const DONE = (id: string) =>
+ buildBackgroundTaskDoneMessage(
+ { kind: "subagent", id, status: "completed", detail: "" },
+ "Background subagent finished",
+ );
+
+ /** A run_in_background spawn: meta forwarded at launch, then the card completes immediately with the launch note. */
+ function spawnBackground(m: StreamModel, toolCallId: string, sessionId: string, id: string) {
+ pushMessage(m, toolCall({ name: "run_subagent", arguments: '{"prompt":"bg"}', toolCallId }));
+ pushMessage(m, approvalDecision("allow", toolCallId));
+ pushMessage(m, withOrigin(meta(sessionId), sessionId));
+ pushMessage(m, toolCallOutput({ output: LAUNCH(id), toolCallId }));
+ }
+
+ it("stays running after its card completes, and settles on the completion notice without leaving the panel scope", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("go"));
+ spawnBackground(m, "t1", "session-child-12ab34cd", "subagent-12ab34cd");
+ let nodes = extractTopology(m, "root", false);
+ expect(nodes).toHaveLength(2);
+ expect(nodes[1]).toMatchObject({ sessionId: "session-child-12ab34cd", running: true });
+
+ // The harness notice starts a chat Task but not a panel scope: the child stays in the
+ // slice and reads settled.
+ pushMessage(m, userText(DONE("subagent-12ab34cd")));
+ nodes = extractTopology(m, "root", false);
+ expect(nodes).toHaveLength(2);
+ expect(nodes[1]!.running).toBe(false);
+ });
+
+ it("idle polls and kill notes settle it; a follow-up round's still-running note flips it back", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("go"));
+ spawnBackground(m, "t1", "session-child-99aa88bb", "subagent-99aa88bb");
+ pushMessage(m, toolCall({ name: "input_subagent", arguments: "{}", toolCallId: "t2" }));
+ pushMessage(m, approvalDecision("allow", "t2"));
+ pushMessage(
+ m,
+ toolCallOutput({
+ output:
+ "[subagent idle with subagent_id subagent-99aa88bb; send a follow-up prompt to continue]",
+ toolCallId: "t2",
+ }),
+ );
+ expect(extractTopology(m, "root", false)[1]!.running).toBe(false);
+
+ pushMessage(m, toolCall({ name: "input_subagent", arguments: "{}", toolCallId: "t3" }));
+ pushMessage(m, approvalDecision("allow", "t3"));
+ pushMessage(
+ m,
+ toolCallOutput({
+ output: "[subagent still running with subagent_id subagent-99aa88bb]",
+ toolCallId: "t3",
+ }),
+ );
+ expect(extractTopology(m, "root", false)[1]!.running).toBe(true);
+ });
+
+ it("taskStartCount and latestTaskStart ignore completion notices", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("go"));
+ pushMessage(m, userText(DONE("subagent-0011aabb")));
+ expect(taskStartCount(m.items)).toBe(1);
+ expect(latestTaskStart(m.items)).toBe(0);
+ // The model's own count still sees both: the notice DID open a Task there (and zeroed the
+ // per-Task usage buckets), which is what the header's cost fold keys on.
+ expect(modelTaskStartCount(m.items)).toBe(2);
+ });
+});