@yandy0725/pi-subagents 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,8 +43,8 @@ Foreground agents block until complete. Background agents return an ID immediate
43
43
 
44
44
  | Type | Tools | Model | Description |
45
45
  |------|-------|-------|-------------|
46
- | `general-purpose` | all | inherit | Full parent system prompt — same rules, same conventions |
47
- | `Explore` | read, bash, grep, find, ls | haiku (fallback: inherit) | Fast codebase exploration (read-only) |
46
+ | `general-purpose` | all | inherit | Harness-rendered prompt for the child's own tool set — same conventions, plus the sub-agent bridge |
47
+ | `Explore` | read, bash, grep, find, ls | `deepseek/deepseek-v4-flash` (falls back to the parent model when unavailable) | Fast codebase exploration (read-only) |
48
48
 
49
49
  ## Custom Agents
50
50
 
@@ -57,6 +57,7 @@ tools: read, grep, find, bash
57
57
  model: anthropic/claude-opus-4-6
58
58
  thinking: high
59
59
  max_turns: 30
60
+ timeout: 300
60
61
  ---
61
62
 
62
63
  You are a security auditor. Review code for vulnerabilities...
@@ -64,6 +65,21 @@ You are a security auditor. Review code for vulnerabilities...
64
65
 
65
66
  Agents are discovered from `.pi/agents/<name>.md` (project) and `~/.pi/agent/agents/<name>.md` (global). Project-level overrides global.
66
67
 
68
+ `max_turns` and `timeout` (wall-clock seconds, `0` = unlimited) lock their limits for the agent type: a frontmatter value wins over the per-call parameter.
69
+
70
+ ### Prompt mode
71
+
72
+ `prompt_mode` decides how the agent body relates to the system prompt of the agent that invokes it:
73
+
74
+ | Value | Assembled system prompt | Use when |
75
+ |-------|------------------------|----------|
76
+ | `append` (default) | Harness-rendered prompt for the child's own tool set — which honors `SYSTEM.md` as the base and keeps `APPEND_SYSTEM.md` ahead of our section, and loads `AGENTS.md` — plus `bridge + <active_agent> + environment` + body wrapped in `<agent_instructions>` | The agent should keep the caller's conventions and only add a role on top |
77
+ | `replace` | `<active_agent>` + environment + your body, nothing else — the caller's rendered prompt is never reused (an empty body falls back to a minimal, capability-neutral prompt), but the harness still appends the skills index, the date, and the child's own working directory | The agent needs a self-contained spec: read-only auditors, evaluators, non-coding roles |
78
+
79
+ `replace` is a clean room on purpose: nothing rendered for the caller reaches the agent — not its prompt, tool list or tool guidelines, not the project context files (`AGENTS.md`), not `SYSTEM.md` / `APPEND_SYSTEM.md` — because those describe a different toolset and role. It gets no tool list of its own either: the prompt carries no tool list and no tool guidelines, while the harness still passes the agent's tools to the model directly. That is why prompt mode never widens or narrows capabilities: only the `tools` allowlist does that. Anything the agent needs — including house rules such as language or tool preferences, and tool-usage conventions — must be restated in its body.
80
+
81
+ `append` is the other side of that line: neither mode inherits the caller's tool list. `append` gets the base prompt the harness renders from the agent's **own** tool set (its own tools and guidelines), then the bridge and your body are appended.
82
+
67
83
  ## Tools
68
84
 
69
85
  ### `subagent`
@@ -78,6 +94,7 @@ Launch a sub-agent.
78
94
  | `model` | string | no | Model override (`provider/modelId` or fuzzy name) |
79
95
  | `thinking` | string | no | off / minimal / low / medium / high / xhigh |
80
96
  | `max_turns` | number | no | Max agentic turns (unlimited by default) |
97
+ | `timeout` | number | no | Hard wall-clock limit in seconds; the agent is killed at the deadline and partial output is returned (unlimited by default) |
81
98
  | `run_in_background` | boolean | no | Run without blocking |
82
99
  | `resume` | string | no | Agent ID to resume a previous session |
83
100
  | `inherit_context` | boolean | no | Fork parent conversation into agent |
@@ -137,7 +154,7 @@ them. If an agent type pins `model` in its frontmatter, that model always wins.
137
154
 
138
155
  | Command | Description |
139
156
  |---------|-------------|
140
- | `/subagents:settings` | Configure concurrency, turn limits |
157
+ | `/subagents:settings` | Configure concurrency, turn limits, timeouts |
141
158
  | `/subagents:sessions` | View a subagent's session transcript |
142
159
 
143
160
  The session viewer renders the transcript read-only with Pi's own per-entry
@@ -162,6 +179,15 @@ Background agents are subject to a configurable concurrency limit (default: 4).
162
179
 
163
180
  Settings set via `/subagents:settings` persist in `<cwd>/.pi/subagents.json` (project) and can be overridden globally in `~/.pi/agent/subagents.json`. The same files also hold the [`modelTiers`](#model-tiers) mapping; saving other settings preserves it.
164
181
 
182
+ | Setting | Meaning |
183
+ |---------|---------|
184
+ | `maxConcurrent` | Background agents allowed to run at once |
185
+ | `defaultMaxTurns` | Default max agentic turns (`0` = unlimited) |
186
+ | `defaultTimeoutSeconds` | Default hard wall-clock timeout in seconds (`0` = unlimited, max `86400`) |
187
+ | `graceTurns` | Turns allowed after the wrap-up steer |
188
+
189
+ `defaultMaxTurns` / `defaultTimeoutSeconds` sit at the bottom of the precedence chain: agent frontmatter wins over the per-call parameter, which wins over these defaults.
190
+
165
191
  ## Events
166
192
 
167
193
  Lifecycle events emitted via `pi.events` for other extensions to consume:
package/README.zh.md CHANGED
@@ -43,8 +43,8 @@ subagent({
43
43
 
44
44
  | 类型 | 工具 | 模型 | 描述 |
45
45
  |------|------|------|------|
46
- | `general-purpose` | 全部 | 继承父级 | 完整父级系统提示词——相同规则、相同约定 |
47
- | `Explore` | read, bash, grep, find, ls | haiku(回退:继承) | 快速代码库探索(只读) |
46
+ | `general-purpose` | 全部 | 继承父级 | harness 按子代理自身工具集渲染的提示词——沿用相同约定,外加子代理桥接段 |
47
+ | `Explore` | read, bash, grep, find, ls | `deepseek/deepseek-v4-flash`(不可用时回退父级模型) | 快速代码库探索(只读) |
48
48
 
49
49
  ## 自定义代理
50
50
 
@@ -57,6 +57,7 @@ tools: read, grep, find, bash
57
57
  model: anthropic/claude-opus-4-6
58
58
  thinking: high
59
59
  max_turns: 30
60
+ timeout: 300
60
61
  ---
61
62
 
62
63
  你是一名安全审计员。审查代码漏洞...
@@ -64,6 +65,21 @@ max_turns: 30
64
65
 
65
66
  代理从 `.pi/agents/<name>.md`(项目级)和 `~/.pi/agent/agents/<name>.md`(全局)发现。项目级覆盖全局。
66
67
 
68
+ `max_turns` 与 `timeout`(墙钟秒数,`0` = 无限制)会锁定该代理类型的上限:frontmatter 中的值优先于每次调用传入的参数。
69
+
70
+ ### 提示词模式
71
+
72
+ `prompt_mode` 决定代理正文与“调用它的代理的系统提示词”之间的关系:
73
+
74
+ | 取值 | 组装出的系统提示词 | 适用场景 |
75
+ |------|--------------------|----------|
76
+ | `append`(默认) | harness 按子代理自身工具集渲染的基础提示词(以 `SYSTEM.md` 为基底、把 `APPEND_SYSTEM.md` 保留在我们的追加段之前,并加载 `AGENTS.md`)+ `桥接 + <active_agent> + 环境` + 用 `<agent_instructions>` 包裹的正文 | 代理应沿用调用方的约定,只在其上增加一层角色 |
77
+ | `replace` | `<active_agent>` + 环境 + 你的正文,别无他物——完全不沿用调用方的渲染产物(空正文时回落到一段极简的中性提示词),但 harness 仍会追加 skills 索引、日期与子代理自身的工作目录 | 代理需要一套自洽的规范:只读审计、评估、非编程角色 |
78
+
79
+ `replace` 是刻意的“干净房间”:凡是为调用方渲染的东西都进不来——调用方的提示词、工具清单与工具指引,项目上下文文件(`AGENTS.md`),`SYSTEM.md` / `APPEND_SYSTEM.md`,因为那些描述的是另一套工具集和角色。它也没有属于自己的工具清单:提示词里既没有工具清单也没有工具指引,而工具本身仍由 harness 直接交给模型。正因如此,提示词模式不会增删能力:能做什么只由 `tools` 白名单决定。代理需要的一切——语言、工具偏好这类内部规则,以及工具使用约定——都必须在自己的正文里重申。
80
+
81
+ `append` 是这条线的另一侧:两种模式都不继承调用方的工具清单。`append` 拿到的是 harness 按代理**自身**工具集渲染的基础提示词(自己的工具与指引),随后再追加桥接段与你的正文。
82
+
67
83
  ## 工具
68
84
 
69
85
  ### `subagent`
@@ -78,6 +94,7 @@ max_turns: 30
78
94
  | `model` | string | 否 | 模型覆盖(`provider/modelId` 或模糊名称) |
79
95
  | `thinking` | string | 否 | off / minimal / low / medium / high / xhigh |
80
96
  | `max_turns` | number | 否 | 最大代理轮次(默认无限制) |
97
+ | `timeout` | number | 否 | 墙钟硬性时限(秒);到点即终止代理并返回已产出的部分输出(默认无限制) |
81
98
  | `run_in_background` | boolean | 否 | 后台运行不阻塞 |
82
99
  | `resume` | string | 否 | 恢复之前会话的代理 ID |
83
100
  | `inherit_context` | boolean | 否 | 将父对话分叉给子代理 |
@@ -134,7 +151,7 @@ max_turns: 30
134
151
 
135
152
  | 命令 | 描述 |
136
153
  |------|------|
137
- | `/subagents:settings` | 配置并发数、轮次限制 |
154
+ | `/subagents:settings` | 配置并发数、轮次限制、超时 |
138
155
  | `/subagents:sessions` | 查看子代理的会话记录 |
139
156
 
140
157
  会话查看器以只读方式复用 Pi 自身的逐条消息组件渲染会话记录,并实时跟随运行中的代理。
@@ -155,6 +172,15 @@ max_turns: 30
155
172
 
156
173
  通过 `/subagents:settings` 设置的参数持久化到 `<cwd>/.pi/subagents.json`(项目级),也可在 `~/.pi/agent/subagents.json` 中设置全局默认值。同一批文件也保存 [`modelTiers`](#模型分层) 映射;保存其他设置时会保留它。
157
174
 
175
+ | 设置 | 含义 |
176
+ |------|------|
177
+ | `maxConcurrent` | 允许同时运行的后台代理数 |
178
+ | `defaultMaxTurns` | 默认最大代理轮次(`0` = 无限制) |
179
+ | `defaultTimeoutSeconds` | 默认墙钟硬性超时秒数(`0` = 无限制,最大 `86400`) |
180
+ | `graceTurns` | 收到"收尾"转向后仍允许的轮次 |
181
+
182
+ `defaultMaxTurns` / `defaultTimeoutSeconds` 位于优先级链最末端:代理 frontmatter 优先于每次调用参数,每次调用参数又优先于这两个默认值。
183
+
158
184
  ## 事件
159
185
 
160
186
  通过 `pi.events` 发出的生命周期事件,供其他扩展消费:
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.7.0",
6
+ "version": "0.8.0",
7
7
  "description": "Focused, in-process sub-agent core for pi — autonomous agents plus a typed API and lifecycle events",
8
8
  "license": "MIT",
9
9
  "repository": {
@@ -38,10 +38,10 @@
38
38
  "typebox": "*"
39
39
  },
40
40
  "devDependencies": {
41
- "@biomejs/biome": "^2.5.15",
41
+ "@biomejs/biome": "^2.6.2",
42
42
  "@types/node": "^26.6.5",
43
- "typebox": "^1.3.37",
43
+ "typebox": "^1.4.3",
44
44
  "typescript": "~7.0.2",
45
- "vitest": "^5.0.4"
45
+ "vitest": "^5.0.5"
46
46
  }
47
47
  }
@@ -61,6 +61,7 @@ function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "pro
61
61
  model: str(fm.model),
62
62
  thinking: str(fm.thinking) as ThinkingLevel | undefined,
63
63
  maxTurns: nonNegativeInt(fm.max_turns),
64
+ timeout: nonNegativeInt(fm.timeout),
64
65
  systemPrompt: body.trim(),
65
66
  promptMode: fm.prompt_mode === "replace" ? "replace" : "append",
66
67
  inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
@@ -4,6 +4,7 @@ interface AgentInvocationParams {
4
4
  model?: string;
5
5
  thinking?: string;
6
6
  max_turns?: number;
7
+ timeout?: number;
7
8
  run_in_background?: boolean;
8
9
  inherit_context?: boolean;
9
10
  }
@@ -16,6 +17,7 @@ export function resolveAgentInvocationConfig(
16
17
  modelFromParams: boolean;
17
18
  thinking?: ThinkingLevel;
18
19
  maxTurns?: number;
20
+ timeout?: number;
19
21
  inheritContext: boolean;
20
22
  runInBackground: boolean;
21
23
  } {
@@ -24,6 +26,7 @@ export function resolveAgentInvocationConfig(
24
26
  modelFromParams: agentConfig?.model == null && params.model != null,
25
27
  thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
26
28
  maxTurns: agentConfig?.maxTurns ?? params.max_turns,
29
+ timeout: agentConfig?.timeout ?? params.timeout,
27
30
  inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
28
31
  runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
29
32
  };
package/src/index.ts CHANGED
@@ -36,7 +36,7 @@ import { SubagentsServiceAdapter } from "./service/service-adapter";
36
36
  import { detectEnv } from "./session/env";
37
37
 
38
38
  import { resolveModel } from "./session/model-resolver";
39
- import { buildAgentPrompt } from "./session/prompts";
39
+ import { buildAppendSection, buildReplacePrompt } from "./session/prompts";
40
40
  import { recoverEvictedSubagents } from "./session/recover-subagents";
41
41
  import { deriveSubagentSessionDir } from "./session/session-dir";
42
42
  import { SettingsManager } from "./settings";
@@ -95,7 +95,8 @@ export default function (pi: ExtensionAPI) {
95
95
  createSettingsManager: (cwd, dir) => SdkSettingsManager.create(cwd, dir),
96
96
  createSession: (opts) => createAgentSession(opts as any),
97
97
  assemblerIO: {
98
- buildAgentPrompt,
98
+ buildReplacePrompt,
99
+ buildAppendSection,
99
100
  },
100
101
  },
101
102
  exec: (cmd, args, opts) => pi.exec(cmd, args, opts),
@@ -162,7 +163,7 @@ export default function (pi: ExtensionAPI) {
162
163
  const subagentsSettings = new SubagentsSettingsHandler(settings);
163
164
 
164
165
  pi.registerCommand("subagents:settings", {
165
- description: "Configure subagent settings (concurrency, turn limits)",
166
+ description: "Configure subagent settings (concurrency, turn limits, timeouts)",
166
167
  handler: async (_args, ctx) => {
167
168
  await subagentsSettings.handle({ ui: ctx.ui });
168
169
  },
@@ -19,7 +19,7 @@ import type { ChildLifecyclePublisher } from "../lifecycle/child-lifecycle";
19
19
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
20
20
  import { SubagentSession } from "../lifecycle/subagent-session";
21
21
  import type { EnvInfo } from "../session/env";
22
- import { type AssemblerIO, assembleSessionConfig } from "../session/session-config";
22
+ import { type AssemblerIO, assembleSessionConfig, type SessionConfig } from "../session/session-config";
23
23
  import type { ParentSessionInfo, ShellExec, SubagentType, ThinkingLevel } from "../types";
24
24
 
25
25
  /** Names of tools registered by this extension that subagents must NOT inherit. */
@@ -132,6 +132,36 @@ export interface CreateSubagentSessionParams {
132
132
  thinkingLevel?: ThinkingLevel;
133
133
  }
134
134
 
135
+ /**
136
+ * Map a session config onto resource-loader options.
137
+ *
138
+ * "append": no system-prompt override, so the harness renders the base prompt
139
+ * for the child's own tool set (tool list, tool guidelines, skills, AGENTS.md,
140
+ * SYSTEM.md, APPEND_SYSTEM.md, date/cwd); we only append our section, keeping
141
+ * any APPEND_SYSTEM.md content ahead of it.
142
+ *
143
+ * "replace": we own the whole prompt, so the system prompt is overridden and
144
+ * both context files and the append file are suppressed.
145
+ *
146
+ * Exported (and kept free of IO) so the harness contract it depends on can be
147
+ * exercised against a real DefaultResourceLoader instead of a mock.
148
+ */
149
+ export function buildResourceLoaderOptions(cfg: SessionConfig, agentDir: string): ResourceLoaderOptions {
150
+ const isReplace = cfg.promptMode === "replace";
151
+ return {
152
+ cwd: cfg.effectiveCwd,
153
+ agentDir,
154
+ noPromptTemplates: true,
155
+ noThemes: true,
156
+ noContextFiles: isReplace,
157
+ // Written out instead of spread conditionals: a conditional spread defeats
158
+ // TypeScript's excess-property check, and a typo here would silently fall
159
+ // back to append semantics (the bug this change exists to fix).
160
+ systemPromptOverride: isReplace ? () => cfg.promptSection : undefined,
161
+ appendSystemPromptOverride: isReplace ? () => [] : (base: string[]) => [...base, cfg.promptSection],
162
+ };
163
+ }
164
+
135
165
  /**
136
166
  * Build a born-complete SubagentSession: assemble config, create the SDK
137
167
  * session, publish lifecycle events, bind extensions, apply the recursion guard.
@@ -153,7 +183,6 @@ export async function createSubagentSession(
153
183
  type,
154
184
  {
155
185
  cwd: snapshot.cwd,
156
- parentSystemPrompt: snapshot.systemPrompt,
157
186
  parentModel: snapshot.model,
158
187
  modelRegistry: snapshot.modelRegistry,
159
188
  },
@@ -170,20 +199,12 @@ export async function createSubagentSession(
170
199
  const agentDir = deps.io.getAgentDir();
171
200
 
172
201
  // Children always load the parent's extensions and skills.
173
- // Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md - upstream's
174
- // buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
175
- // would defeat prompt_mode: replace. Parent context, if wanted, reaches the
176
- // subagent via prompt_mode: append (parentSystemPrompt is embedded in
177
- // systemPromptOverride) or inherit_context (conversation).
178
- const loader = deps.io.createResourceLoader({
179
- cwd: cfg.effectiveCwd,
180
- agentDir,
181
- noPromptTemplates: true,
182
- noThemes: true,
183
- noContextFiles: true,
184
- systemPromptOverride: () => cfg.systemPrompt,
185
- appendSystemPromptOverride: () => [],
186
- });
202
+ //
203
+ // "append" lets the harness render the base prompt for the child's own tool
204
+ // set (tool list, tool guidelines, skills, AGENTS.md, SYSTEM.md, date/cwd)
205
+ // and appends our section to it. "replace" owns the whole prompt, so context
206
+ // files and the append file are suppressed.
207
+ const loader = deps.io.createResourceLoader(buildResourceLoaderOptions(cfg, agentDir));
187
208
  await loader.reload();
188
209
 
189
210
  // Create a persisted SessionManager so transcripts are written in Pi's
@@ -12,8 +12,6 @@ import type { SessionContext } from "../types";
12
12
  export interface ParentSnapshot {
13
13
  /** Parent working directory. */
14
14
  cwd: string;
15
- /** Parent's effective system prompt (for append-mode agents). */
16
- systemPrompt: string;
17
15
  /** Parent's current model instance (fallback when agent config has no model). */
18
16
  model: unknown;
19
17
  /** Model registry for resolving config.model strings and creating sessions. */
@@ -35,7 +33,6 @@ export function buildParentSnapshot(ctx: SessionContext, inheritContext?: boolea
35
33
  const parentContext = inheritContext ? buildParentContext(ctx) : undefined;
36
34
  return {
37
35
  cwd: ctx.cwd,
38
- systemPrompt: ctx.getSystemPrompt(),
39
36
  model: ctx.model,
40
37
 
41
38
  modelRegistry: ctx.modelRegistry!,
@@ -67,6 +67,8 @@ export interface AgentSpawnConfig {
67
67
  description: string;
68
68
  model?: Model<any>;
69
69
  maxTurns?: number;
70
+ /** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
71
+ timeoutSeconds?: number;
70
72
  inheritContext?: boolean;
71
73
  thinkingLevel?: ThinkingLevel;
72
74
  isBackground?: boolean;
@@ -178,6 +180,7 @@ export class SubagentManager {
178
180
  getWorkspaceProvider: () => this._workspaceProvider,
179
181
  model: options.model,
180
182
  maxTurns: options.maxTurns,
183
+ timeoutSeconds: options.timeoutSeconds,
181
184
  thinkingLevel: options.thinkingLevel,
182
185
  parentSession: options.parentSession,
183
186
  signal: options.signal,
@@ -79,6 +79,19 @@ export class SubagentSession {
79
79
  async runTurnLoop(prompt: string, opts: TurnLoopOptions): Promise<TurnLoopResult> {
80
80
  const session = this._session;
81
81
 
82
+ // An already-aborted signal must not start a run at all: pi's abort() only
83
+ // reaches an in-flight run, and prompt() starts a fresh AbortController, so
84
+ // aborting an idle session cannot stop the run that follows it.
85
+ if (opts.signal?.aborted) {
86
+ this.meta.lifecycle.completed({
87
+ sessionDir: this.meta.sessionDir,
88
+ agentName: this.meta.agentName,
89
+ aborted: true,
90
+ steered: false,
91
+ });
92
+ return { responseText: getLastAssistantText(session), aborted: true, steered: false };
93
+ }
94
+
82
95
  // Track turns for graceful max_turns enforcement.
83
96
  let turnCount = 0;
84
97
  const maxTurns = normalizeMaxTurns(opts.maxTurns ?? this.meta.agentMaxTurns ?? opts.defaultMaxTurns);
@@ -86,6 +99,11 @@ export class SubagentSession {
86
99
  let aborted = false;
87
100
 
88
101
  const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
102
+ // A wall-clock abort can land while no run is active (prompt preamble,
103
+ // auto-compaction between turns) and be dropped — abort() only reaches an
104
+ // in-flight run. Re-assert on every event so the next window closes.
105
+ if (opts.signal?.aborted) void session.abort();
106
+
89
107
  if (event.type === "turn_end") {
90
108
  turnCount++;
91
109
  if (maxTurns != null) {
@@ -108,6 +126,7 @@ export class SubagentSession {
108
126
 
109
127
  try {
110
128
  await session.prompt(effectivePrompt);
129
+ aborted ||= opts.signal?.aborted === true;
111
130
  this.meta.lifecycle.completed({
112
131
  sessionDir: this.meta.sessionDir,
113
132
  agentName: this.meta.agentName,
@@ -127,6 +146,9 @@ export class SubagentSession {
127
146
  /** Re-prompt the same session (resume); does not emit `completed`. */
128
147
  async resumeTurnLoop(prompt: string, signal?: AbortSignal): Promise<string> {
129
148
  const session = this._session;
149
+ // Same early-return as runTurnLoop: an aborted signal must not start a run.
150
+ if (signal?.aborted) return getLastAssistantText(session);
151
+
130
152
  const collector = collectResponseText(session);
131
153
  const cleanupAbort = forwardAbortSignal(session, signal);
132
154
 
@@ -220,6 +242,8 @@ function getLastAssistantText(session: AgentSession): string {
220
242
 
221
243
  /**
222
244
  * Wire an AbortSignal to abort a session.
245
+ * Fires immediately when the signal is already aborted — addEventListener on a
246
+ * fired signal never fires, so wiring alone would silently drop it.
223
247
  * Returns a cleanup function to remove the listener.
224
248
  */
225
249
  function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () => void {
@@ -227,6 +251,10 @@ function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () =>
227
251
  const onAbort = (): void => {
228
252
  void session.abort();
229
253
  };
254
+ if (signal.aborted) {
255
+ onAbort();
256
+ return () => {};
257
+ }
230
258
  signal.addEventListener("abort", onAbort, { once: true });
231
259
  return () => signal.removeEventListener("abort", onAbort);
232
260
  }
@@ -64,6 +64,8 @@ export interface SubagentExecution {
64
64
  getWorkspaceProvider?: () => WorkspaceProvider | undefined;
65
65
  model?: Model<any>;
66
66
  maxTurns?: number;
67
+ /** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
68
+ timeoutSeconds?: number;
67
69
  thinkingLevel?: ThinkingLevel;
68
70
  parentSession?: ParentSessionInfo;
69
71
  signal?: AbortSignal;
@@ -144,6 +146,10 @@ export class Subagent {
144
146
  return this._promise;
145
147
  }
146
148
 
149
+ // Timeout guard — started at run() after markRunning, cleared on every terminal path.
150
+ private _timeoutHandle: ReturnType<typeof setTimeout> | undefined;
151
+ private _timedOut = false;
152
+
147
153
  private readonly execution: SubagentExecution;
148
154
  private readonly listeners = new RunListeners();
149
155
  private readonly workspaceBracket: WorkspaceBracket;
@@ -256,6 +262,7 @@ export class Subagent {
256
262
  this.markRunning(Date.now());
257
263
  this.execution.observer?.onStarted?.(this);
258
264
  this.listeners.wireSignal(this.execution.signal, () => this.abort());
265
+ this.startTimeoutGuard();
259
266
 
260
267
  // Guard the await so the no-provider path stays synchronous, preserving
261
268
  // the original run() timing: the factory is called in the same turn as
@@ -270,6 +277,7 @@ export class Subagent {
270
277
  invocation: this.invocation,
271
278
  });
272
279
  } catch (err) {
280
+ this.clearTimeoutGuard();
273
281
  this.markError(err);
274
282
  this.listeners.release();
275
283
  this.execution.observer?.onRunFinished?.(this);
@@ -292,6 +300,15 @@ export class Subagent {
292
300
  return;
293
301
  }
294
302
 
303
+ // Timeout fired before the session existed: the controller had no listener
304
+ // (forwardAbortSignal is wired inside runTurnLoop), so nothing was killed.
305
+ // Fail fast instead of running a turn loop the budget already exhausted.
306
+ if (this._timedOut) {
307
+ this.disposeSession();
308
+ this.failRun(new Error(`Timed out after ${this.execution.timeoutSeconds}s before the session started`));
309
+ return;
310
+ }
311
+
295
312
  this.flushPendingSteers();
296
313
  this.listeners.attachObserver(
297
314
  subscribeSubagentObserver(this.subagentSession, this.state, {
@@ -440,11 +457,37 @@ export class Subagent {
440
457
  */
441
458
  abort(): boolean {
442
459
  if (this.status !== "running") return false;
460
+ // A stopped run has no use for a deadline: without this, a timer firing
461
+ // during the abort unwind would stamp a timeout note on a user-stopped run.
462
+ this.clearTimeoutGuard();
443
463
  this.abortController.abort();
444
464
  this.markStopped();
445
465
  return true;
446
466
  }
447
467
 
468
+ /** Start the wall-clock timeout guard (no-op when no timeout is configured). */
469
+ private startTimeoutGuard(): void {
470
+ // Guard on > 0 so an unnormalized 0/negative/NaN can never arm a timer.
471
+ const seconds = Number(this.execution.timeoutSeconds);
472
+ if (!(seconds > 0)) return;
473
+ this._timeoutHandle = setTimeout(() => {
474
+ // Fire the controller without markStopped(): the abort flows through
475
+ // forwardAbortSignal into session.abort(), and the turn loop settles
476
+ // through the aborted path (status "aborted", not "stopped").
477
+ this._timedOut = true;
478
+ this.abortController.abort();
479
+ }, seconds * 1000);
480
+ this._timeoutHandle.unref();
481
+ }
482
+
483
+ /** Clear the timeout guard (idempotent; safe after it already fired). */
484
+ private clearTimeoutGuard(): void {
485
+ if (this._timeoutHandle) {
486
+ clearTimeout(this._timeoutHandle);
487
+ this._timeoutHandle = undefined;
488
+ }
489
+ }
490
+
448
491
  /**
449
492
  * Buffer a steer message for delivery once the session is ready.
450
493
  * Called internally from steer() before the session is ready.
@@ -472,11 +515,17 @@ export class Subagent {
472
515
 
473
516
  /** Complete a run: release listeners, dispose the workspace, status transition, notify observer. */
474
517
  completeRun(result: TurnLoopResult): void {
518
+ this.clearTimeoutGuard();
475
519
  this.listeners.release();
476
520
 
477
521
  const finalStatus: SubagentStatus = result.aborted ? "aborted" : result.steered ? "steered" : "completed";
522
+ const responseText = result.responseText;
523
+ const timeoutNote =
524
+ this._timedOut && finalStatus === "aborted"
525
+ ? `⏱ Timed out after ${this.execution.timeoutSeconds}s — output may be truncated.\n\n`
526
+ : "";
478
527
  const finalResult =
479
- result.responseText + this.workspaceBracket.dispose({ status: finalStatus, description: this.description });
528
+ timeoutNote + responseText + this.workspaceBracket.dispose({ status: finalStatus, description: this.description });
480
529
 
481
530
  if (result.aborted) this.markAborted(finalResult);
482
531
  else if (result.steered) this.markSteered(finalResult);
@@ -492,6 +541,7 @@ export class Subagent {
492
541
 
493
542
  /** Fail a run: mark error, release listeners, best-effort workspace dispose, notify observer. */
494
543
  failRun(err: unknown): void {
544
+ this.clearTimeoutGuard();
495
545
  this.markError(err);
496
546
  this.listeners.release();
497
547
 
@@ -1,7 +1,8 @@
1
1
  /**
2
- * turn-limits.ts — Pure turn-limit normalization for subagent execution.
2
+ * turn-limits.ts — Pure run-limit normalization for subagent execution
3
+ * (max turns and wall-clock timeout).
3
4
  *
4
- * Extracted from agent-runner.ts (issue #265) so the turn-counting policy has a
5
+ * Extracted from agent-runner.ts (issue #265) so the run-limit policy has a
5
6
  * focused home independent of session assembly. Consumed by the subagent tool's
6
7
  * spawn-config resolution and by the turn loop in SubagentSession.
7
8
  */
@@ -11,3 +12,9 @@ export function normalizeMaxTurns(n: number | undefined): number | undefined {
11
12
  if (n == null || n === 0) return undefined;
12
13
  return Math.max(1, n);
13
14
  }
15
+
16
+ /** Normalize a wall-clock timeout in seconds. undefined or 0 = unlimited, otherwise minimum 1. Non-finite → unlimited. */
17
+ export function normalizeTimeoutSeconds(s: number | undefined): number | undefined {
18
+ if (s == null || !Number.isFinite(s) || s === 0) return undefined;
19
+ return Math.max(1, s);
20
+ }
@@ -32,7 +32,7 @@ export function getStatusLabel(status: string, error?: string): string {
32
32
  case "error":
33
33
  return `Error: ${error ?? "unknown"}`;
34
34
  case "aborted":
35
- return "Aborted (max turns exceeded)";
35
+ return "Aborted (hard limit exceeded)";
36
36
  case "steered":
37
37
  return "Wrapped up (turn limit)";
38
38
  case "stopped":
@@ -9,6 +9,7 @@ import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
9
9
  import type { WorkspaceProvider } from "../lifecycle/workspace";
10
10
  import type { SpawnOptions, SubagentRecord, SubagentsService } from "../service/service";
11
11
  import type { ModelRegistry } from "../session/model-resolver";
12
+ import { normalizeTimeoutSeconds } from "../lifecycle/turn-limits";
12
13
  import { resolveModelName } from "../tools/spawn-config";
13
14
  import type { SessionContext, Subagent, ThinkingLevel, AgentInvocation } from "../types";
14
15
 
@@ -76,6 +77,9 @@ export class SubagentsServiceAdapter implements SubagentsService {
76
77
  description,
77
78
  model,
78
79
  maxTurns: options?.maxTurns,
80
+ // Normalize at the boundary: the documented 0/undefined = unlimited contract
81
+ // must hold for cross-extension callers that skip the tool path.
82
+ timeoutSeconds: normalizeTimeoutSeconds(options?.timeoutSeconds),
79
83
  thinkingLevel: options?.thinkingLevel,
80
84
  inheritContext: options?.inheritContext,
81
85
  bypassQueue: options?.bypassQueue,
@@ -57,6 +57,8 @@ export interface SpawnOptions {
57
57
  description?: string;
58
58
  model?: string;
59
59
  maxTurns?: number;
60
+ /** Hard wall-clock timeout in seconds (0/undefined = unlimited). Normalize before passing, or pass an already-normalized value. */
61
+ timeoutSeconds?: number;
60
62
  thinkingLevel?: string;
61
63
  inheritContext?: boolean;
62
64
  foreground?: boolean;
@@ -1,50 +1,65 @@
1
1
  /**
2
- * prompts.ts — System prompt builder for agents.
2
+ * prompts.ts — System prompt assembly for agents.
3
+ *
4
+ * Two shapes, one per `prompt_mode`:
5
+ *
6
+ * - "append": the harness renders the base system prompt for the child's OWN
7
+ * tool set (tool list, guidelines, skills, AGENTS.md, SYSTEM.md, date/cwd)
8
+ * and this module only contributes a section appended to it.
9
+ * - "replace": this module owns the whole prompt. The caller's rendered prompt
10
+ * is deliberately NOT reused — it carries the caller's tool list and
11
+ * guidelines, its cwd/date, and project context the child suppresses.
12
+ *
13
+ * Both shapes emit an `<active_agent name="..."/>` tag so downstream extensions
14
+ * can resolve per-agent policy by parsing the child's system prompt.
3
15
  */
4
16
 
5
17
  import type { EnvInfo } from "../session/env";
6
18
  import type { AgentPromptConfig } from "../types";
7
19
 
8
20
  /**
9
- * Build the system prompt for an agent from its config.
10
- *
11
- * Both modes place the shared/stable parent prompt (or `genericBase` when no
12
- * parent is available) first so the LLM's KV cache can reuse the inherited
13
- * prefix across all subagent invocations.
14
- *
15
- * - "replace" mode: parent/genericBase + active_agent tag + env header +
16
- * config.systemPrompt. No `<sub_agent_context>` bridge and no
17
- * `<agent_instructions>` wrapper — the custom prompt has full control and
18
- * the final say.
19
- * - "append" mode: parent/genericBase + sub-agent context bridge +
20
- * active_agent tag + env header + config.systemPrompt (wrapped in
21
- * `<agent_instructions>` when non-empty).
22
- * - "append" with empty systemPrompt: pure parent clone.
23
- *
24
- * Both modes include an `<active_agent name="${config.name}"/>` tag so
25
- * downstream extensions can resolve per-agent policy inside the child session
26
- * by parsing the system prompt.
27
- * The tag follows the cacheable parent prefix in both modes.
28
- *
29
- * @param parentSystemPrompt The parent agent's effective system prompt.
21
+ * Fallback prompt for a replace agent whose body is empty — nothing else uses
22
+ * it. It asserts no role and no capability: in replace mode the body IS the
23
+ * spec, and a generic persona prepended to it would mislabel read-only or
24
+ * non-coding agents (and is the only capability text the model would see, since
25
+ * replace mode renders no tool list). Only the `tools` allowlist grants abilities.
30
26
  */
31
- export function buildAgentPrompt(
32
- config: AgentPromptConfig,
33
- cwd: string,
34
- env: EnvInfo,
35
- parentSystemPrompt?: string,
36
- ): string {
37
- const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
27
+ const emptyBodyFallback = `# Role
28
+ Your role is defined by the instructions below.
29
+ Your available tools are the ones exposed to you in this session; respect any restrictions stated below.
30
+ Do what has been asked; nothing more, nothing less.`;
38
31
 
39
- const envBlock = `# Environment
40
- Working directory: ${cwd}
32
+ /** Environment header shared by both modes. cwd and date are rendered by the harness. */
33
+ function environmentBlock(env: EnvInfo): string {
34
+ return `# Environment
41
35
  ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
42
36
  Platform: ${env.platform}`;
37
+ }
43
38
 
44
- const identity = parentSystemPrompt ?? genericBase;
39
+ /**
40
+ * Build the complete system prompt for a "replace" agent:
41
+ * active_agent tag → env header → the agent body verbatim.
42
+ *
43
+ * Only an empty body gets `emptyBodyFallback` in front of it; a non-empty body is the
44
+ * agent's whole spec, so nothing generic is prepended. No `<sub_agent_context>`
45
+ * bridge and no `<agent_instructions>` wrapper either: this is not an addendum
46
+ * to someone else's prompt.
47
+ */
48
+ export function buildReplacePrompt(config: AgentPromptConfig, env: EnvInfo): string {
49
+ const identity = config.systemPrompt.trim() ? "" : `${emptyBodyFallback}\n\n`;
50
+ return `${identity}<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}\n\n${config.systemPrompt}`;
51
+ }
45
52
 
46
- if (config.promptMode === "append") {
47
- const bridge = `<sub_agent_context>
53
+ /**
54
+ * Build the section appended to the harness-rendered base prompt for an
55
+ * "append" agent: sub-agent bridge → active_agent tag → env header → the agent
56
+ * body wrapped in `<agent_instructions>` (omitted when the body is empty).
57
+ *
58
+ * Carries no leading separator: the harness joins it onto the base prompt with
59
+ * its own blank line, so adding one here would stack into extra empty lines.
60
+ */
61
+ export function buildAppendSection(config: AgentPromptConfig, env: EnvInfo): string {
62
+ const bridge = `<sub_agent_context>
48
63
  You are operating as a sub-agent invoked to handle a specific task.
49
64
  - Make independent tool calls in parallel
50
65
  - Use absolute file paths
@@ -52,27 +67,9 @@ You are operating as a sub-agent invoked to handle a specific task.
52
67
  - Be concise but complete
53
68
  </sub_agent_context>`;
54
69
 
55
- const customSection = config.systemPrompt.trim()
56
- ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
57
- : "";
58
-
59
- // Place shared/stable content first so the LLM's KV cache can reuse the
60
- // inherited prefix across all subagent invocations. The parent prompt is
61
- // placed verbatim (no wrapper tag) so it forms an identical byte prefix
62
- // with the parent session, maximising KV cache hits. The <active_agent>
63
- // tag and env block vary per call and are placed after the cached prefix.
64
- return `${identity}\n\n${bridge}\n\n${activeAgentTag}${envBlock}${customSection}`;
65
- }
70
+ const customSection = config.systemPrompt.trim()
71
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
72
+ : "";
66
73
 
67
- // "replace" mode — parent/genericBase prefix first for KV cache reuse, then
68
- // the active_agent tag, env block, and the config's full system prompt.
69
- // Unlike append mode, no <sub_agent_context> bridge or <agent_instructions>
70
- // wrapper is injected — the custom prompt retains full control.
71
- return `${identity}\n\n${activeAgentTag}${envBlock}\n\n${config.systemPrompt}`;
74
+ return `${bridge}\n\n<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}${customSection}`;
72
75
  }
73
-
74
- /** Fallback base prompt when parent system prompt is unavailable (both modes). */
75
- const genericBase = `# Role
76
- You are a general-purpose coding agent for complex, multi-step tasks.
77
- You have full access to read, write, edit files, and execute commands.
78
- Do what has been asked; nothing more, nothing less.`;
@@ -25,7 +25,8 @@ import type { AgentPromptConfig, SubagentType, ThinkingLevel } from "../types";
25
25
  * at the edge (`create-subagent-session.ts`) or stubs in tests.
26
26
  */
27
27
  export interface AssemblerIO {
28
- buildAgentPrompt: (config: AgentPromptConfig, cwd: string, env: EnvInfo, parentPrompt?: string) => string;
28
+ buildReplacePrompt: (config: AgentPromptConfig, env: EnvInfo) => string;
29
+ buildAppendSection: (config: AgentPromptConfig, env: EnvInfo) => string;
29
30
  }
30
31
 
31
32
  /**
@@ -40,8 +41,6 @@ export interface AssemblerIO {
40
41
  export interface AssemblerContext {
41
42
  /** Parent working directory (overridable via options.cwd). */
42
43
  cwd: string;
43
- /** Parent's effective system prompt (for append-mode agents). */
44
- parentSystemPrompt: string;
45
44
  /** Parent's current model instance (fallback when agent config has no model). */
46
45
  parentModel?: unknown;
47
46
  /** Model registry for resolving config.model strings. */
@@ -72,8 +71,10 @@ export interface AssemblerOptions {
72
71
  export interface SessionConfig {
73
72
  /** Resolved working directory (`options.cwd ?? ctx.cwd`). */
74
73
  effectiveCwd: string;
75
- /** Fully-assembled system prompt string (ready for `systemPromptOverride`). */
76
- systemPrompt: string;
74
+ /** Prompt mode declared by the agent; decides how the caller wires the resource loader. */
75
+ promptMode: "replace" | "append";
76
+ /** Mode-specific text: the complete system prompt for "replace", the appended section for "append". */
77
+ promptSection: string;
77
78
  /** Built-in tool name allowlist for this agent type. */
78
79
  toolNames: string[];
79
80
  /**
@@ -149,8 +150,12 @@ export function assembleSessionConfig(
149
150
 
150
151
  const toolNames = registry.getToolNamesForType(type);
151
152
 
152
- // Build system prompt from the resolved agent config
153
- const systemPrompt = io.buildAgentPrompt(agentConfig, effectiveCwd, env, ctx.parentSystemPrompt);
153
+ // Assemble the prompt text: "replace" owns the whole prompt, "append" only
154
+ // contributes a section on top of the harness-rendered base prompt.
155
+ const promptSection =
156
+ agentConfig.promptMode === "replace"
157
+ ? io.buildReplacePrompt(agentConfig, env)
158
+ : io.buildAppendSection(agentConfig, env);
154
159
 
155
160
  // Model resolution: explicit option > config model string > parent model
156
161
  const model = options.model ?? resolveDefaultModel(ctx.parentModel, ctx.modelRegistry, agentConfig.model);
@@ -163,7 +168,8 @@ export function assembleSessionConfig(
163
168
 
164
169
  return {
165
170
  effectiveCwd,
166
- systemPrompt,
171
+ promptMode: agentConfig.promptMode,
172
+ promptSection,
167
173
  toolNames,
168
174
  model,
169
175
  thinkingLevel,
package/src/settings.ts CHANGED
@@ -14,6 +14,8 @@ export interface SubagentsSettings {
14
14
  * `/agents` → Settings input prompt explicitly says "0 = unlimited".
15
15
  */
16
16
  defaultMaxTurns?: number;
17
+ /** Default wall-clock timeout in seconds for spawned agents. 0 = unlimited. */
18
+ defaultTimeoutSeconds?: number;
17
19
  graceTurns?: number;
18
20
  /**
19
21
  * Capability/cost tier → real model mapping. Used only to generate the
@@ -37,6 +39,7 @@ const DEFAULT_GRACE_TURNS = 5;
37
39
  */
38
40
  export class SettingsManager {
39
41
  private _defaultMaxTurns: number | undefined = undefined;
42
+ private _defaultTimeoutSeconds: number | undefined = undefined;
40
43
  private _graceTurns: number = DEFAULT_GRACE_TURNS;
41
44
  private _maxConcurrent: number = DEFAULT_MAX_CONCURRENT;
42
45
  private _modelTiers: ModelTierMap = {};
@@ -67,6 +70,20 @@ export class SettingsManager {
67
70
  }
68
71
  }
69
72
 
73
+ // ── defaultTimeoutSeconds: 0 or undefined → unlimited (undefined); else max(1, n) ──
74
+
75
+ get defaultTimeoutSeconds(): number | undefined {
76
+ return this._defaultTimeoutSeconds;
77
+ }
78
+
79
+ set defaultTimeoutSeconds(n: number | undefined) {
80
+ if (n == null || n === 0) {
81
+ this._defaultTimeoutSeconds = undefined;
82
+ } else {
83
+ this._defaultTimeoutSeconds = Math.max(1, n);
84
+ }
85
+ }
86
+
70
87
  // ── graceTurns: minimum 1 ──
71
88
 
72
89
  get graceTurns(): number {
@@ -104,6 +121,9 @@ export class SettingsManager {
104
121
  const settings = loadSettings(this.agentDir, this.cwd);
105
122
  if (typeof settings.maxConcurrent === "number") this.maxConcurrent = settings.maxConcurrent;
106
123
  if (typeof settings.defaultMaxTurns === "number") this.defaultMaxTurns = settings.defaultMaxTurns;
124
+ if (typeof settings.defaultTimeoutSeconds === "number") {
125
+ this.defaultTimeoutSeconds = settings.defaultTimeoutSeconds;
126
+ }
107
127
  if (typeof settings.graceTurns === "number") this.graceTurns = settings.graceTurns;
108
128
  this._modelTiers = settings.modelTiers ? { ...settings.modelTiers } : {};
109
129
  this.emit("subagents:settings_loaded", { settings });
@@ -116,10 +136,17 @@ export class SettingsManager {
116
136
  * `modelTiers` is omitted when empty so hand-edited tier maps are only
117
137
  * rewritten (not replaced with an empty object) when they exist.
118
138
  */
119
- snapshot(): { maxConcurrent: number; defaultMaxTurns: number; graceTurns: number; modelTiers?: ModelTierMap } {
139
+ snapshot(): {
140
+ maxConcurrent: number;
141
+ defaultMaxTurns: number;
142
+ defaultTimeoutSeconds: number;
143
+ graceTurns: number;
144
+ modelTiers?: ModelTierMap;
145
+ } {
120
146
  return {
121
147
  maxConcurrent: this._maxConcurrent,
122
148
  defaultMaxTurns: this._defaultMaxTurns ?? 0,
149
+ defaultTimeoutSeconds: this._defaultTimeoutSeconds ?? 0,
123
150
  graceTurns: this._graceTurns,
124
151
  ...(Object.keys(this._modelTiers).length > 0 ? { modelTiers: { ...this._modelTiers } } : {}),
125
152
  };
@@ -145,6 +172,16 @@ export class SettingsManager {
145
172
  return this.saveAndNotify(`Default max turns set to ${label}`);
146
173
  }
147
174
 
175
+ /**
176
+ * Set defaultTimeoutSeconds, persist, and return the toast.
177
+ * Pass 0 for unlimited (maps to undefined internally).
178
+ */
179
+ applyDefaultTimeoutSeconds(n: number): { message: string; level: "info" | "warning" } {
180
+ this.defaultTimeoutSeconds = n === 0 ? undefined : n; // setter normalizes further
181
+ const label = this.defaultTimeoutSeconds == null ? "unlimited" : `${this.defaultTimeoutSeconds}s`;
182
+ return this.saveAndNotify(`Default timeout set to ${label}`);
183
+ }
184
+
148
185
  /**
149
186
  * Set graceTurns, persist, and return the toast.
150
187
  */
@@ -170,6 +207,7 @@ export class SettingsManager {
170
207
  // that any realistic power-user setting passes through.
171
208
  const MAX_CONCURRENT_CEILING = 1024;
172
209
  const MAX_TURNS_CEILING = 10_000;
210
+ const MAX_TIMEOUT_SECONDS_CEILING = 86_400;
173
211
  const GRACE_TURNS_CEILING = 1_000;
174
212
 
175
213
  /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
@@ -191,6 +229,13 @@ function sanitize(raw: unknown): SubagentsSettings {
191
229
  ) {
192
230
  out.defaultMaxTurns = r.defaultMaxTurns as number;
193
231
  }
232
+ if (
233
+ Number.isInteger(r.defaultTimeoutSeconds) &&
234
+ (r.defaultTimeoutSeconds as number) >= 0 &&
235
+ (r.defaultTimeoutSeconds as number) <= MAX_TIMEOUT_SECONDS_CEILING
236
+ ) {
237
+ out.defaultTimeoutSeconds = r.defaultTimeoutSeconds as number;
238
+ }
194
239
  if (
195
240
  Number.isInteger(r.graceTurns) &&
196
241
  (r.graceTurns as number) >= 1 &&
@@ -40,6 +40,7 @@ export interface AgentToolRuntime {
40
40
  /** Narrow settings accessor — only the fields the Agent tool reads. */
41
41
  export type AgentToolSettings = {
42
42
  readonly defaultMaxTurns: number | undefined;
43
+ readonly defaultTimeoutSeconds: number | undefined;
43
44
  readonly maxConcurrent: number;
44
45
  readonly modelTiers?: ModelTierMap;
45
46
  };
@@ -148,6 +149,7 @@ Guidelines:
148
149
  - Use steer_subagent to send mid-run messages to a running background agent.
149
150
  - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
150
151
  - Use thinking to control extended thinking level.
152
+ - Use timeout (seconds) as a hard safety net for tasks that might run away — the agent is killed at the deadline and output may be truncated.
151
153
  - Use inherit_context if the agent needs the parent conversation history.
152
154
  `,
153
155
  parameters: Type.Object({
@@ -177,6 +179,13 @@ Guidelines:
177
179
  minimum: 1,
178
180
  }),
179
181
  ),
182
+ timeout: Type.Optional(
183
+ Type.Number({
184
+ description:
185
+ "Hard wall-clock limit in seconds. When exceeded, the agent is terminated immediately and only partial output is returned. Use as a safety net for tasks that could run away (long builds, hanging commands); omit for unlimited.",
186
+ minimum: 1,
187
+ }),
188
+ ),
180
189
  run_in_background: Type.Optional(
181
190
  Type.Boolean({
182
191
  description:
@@ -32,6 +32,7 @@ export function spawnBackground(manager: BackgroundManagerDeps, params: Backgrou
32
32
  description: execution.description,
33
33
  model: execution.model,
34
34
  maxTurns: execution.effectiveMaxTurns,
35
+ timeoutSeconds: execution.effectiveTimeoutSeconds,
35
36
  inheritContext: execution.inheritContext,
36
37
  thinkingLevel: execution.thinking,
37
38
  isBackground: true,
@@ -74,6 +74,7 @@ export async function runForeground(
74
74
  description: execution.description,
75
75
  model: execution.model,
76
76
  maxTurns: execution.effectiveMaxTurns,
77
+ timeoutSeconds: execution.effectiveTimeoutSeconds,
77
78
  inheritContext: execution.inheritContext,
78
79
  thinkingLevel: execution.thinking,
79
80
  invocation: execution.agentInvocation,
@@ -6,7 +6,7 @@ import { type AgentDetails, formatTokens } from "../ui/display";
6
6
  export function getStatusNote(status: string): string {
7
7
  switch (status) {
8
8
  case "aborted":
9
- return " (aborted \u2014 max turns exceeded, output may be incomplete)";
9
+ return " (aborted \u2014 hard limit exceeded, output may be incomplete)";
10
10
  case "steered":
11
11
  return " (wrapped up \u2014 reached turn limit)";
12
12
  case "stopped":
@@ -85,7 +85,7 @@ export function renderFailed(details: AgentDetails, theme: Theme): string {
85
85
  if (details.status === "error") {
86
86
  line += `\n${theme.fg("error", ` \u23BF Error: ${details.error ?? "unknown"}`)}`;
87
87
  } else {
88
- line += `\n${theme.fg("warning", " \u23BF Aborted (max turns exceeded)")}`;
88
+ line += `\n${theme.fg("warning", " \u23BF Aborted (hard limit exceeded)")}`;
89
89
  }
90
90
  return line;
91
91
  }
@@ -10,7 +10,7 @@
10
10
  import type { Model } from "@earendil-works/pi-ai";
11
11
  import type { AgentTypeRegistry } from "../config/agent-types";
12
12
  import { resolveAgentInvocationConfig } from "../config/invocation-config";
13
- import { normalizeMaxTurns } from "../lifecycle/turn-limits";
13
+ import { normalizeMaxTurns, normalizeTimeoutSeconds } from "../lifecycle/turn-limits";
14
14
  import { resolveInvocationModel } from "../session/model-resolver";
15
15
  import type { AgentInvocation, SubagentType, ThinkingLevel } from "../types";
16
16
  import { type AgentDetails, buildInvocationTags, getDisplayName, getPromptModeLabel } from "../ui/display";
@@ -46,6 +46,7 @@ export interface SpawnExecution {
46
46
  description: string;
47
47
  model: Model<any> | undefined;
48
48
  effectiveMaxTurns: number | undefined;
49
+ effectiveTimeoutSeconds: number | undefined;
49
50
  thinking: ThinkingLevel | undefined;
50
51
  inheritContext: boolean;
51
52
  runInBackground: boolean;
@@ -81,7 +82,7 @@ export function resolveSpawnConfig(
81
82
  params: Record<string, unknown>,
82
83
  registry: AgentTypeRegistry,
83
84
  modelInfo: ModelInfo,
84
- settings: { readonly defaultMaxTurns: number | undefined },
85
+ settings: { readonly defaultMaxTurns: number | undefined; readonly defaultTimeoutSeconds: number | undefined },
85
86
  ): ResolvedSpawnConfig | SpawnConfigError {
86
87
  const rawType = params.subagent_type as SubagentType;
87
88
  const resolved = registry.resolveType(rawType);
@@ -118,11 +119,13 @@ export function resolveSpawnConfig(
118
119
  const modelName = resolveModelName(model ?? modelInfo.parentModel);
119
120
 
120
121
  const effectiveMaxTurns = normalizeMaxTurns(resolvedConfig.maxTurns ?? settings.defaultMaxTurns);
122
+ const effectiveTimeoutSeconds = normalizeTimeoutSeconds(resolvedConfig.timeout ?? settings.defaultTimeoutSeconds);
121
123
 
122
124
  const agentInvocation: AgentInvocation = {
123
125
  modelName,
124
126
  thinking,
125
127
  maxTurns: normalizeMaxTurns(resolvedConfig.maxTurns),
128
+ timeout: normalizeTimeoutSeconds(resolvedConfig.timeout),
126
129
  inheritContext,
127
130
  runInBackground,
128
131
  };
@@ -146,6 +149,7 @@ export function resolveSpawnConfig(
146
149
  description: params.description as string,
147
150
  model,
148
151
  effectiveMaxTurns,
152
+ effectiveTimeoutSeconds,
149
153
  thinking,
150
154
  inheritContext,
151
155
  runInBackground,
package/src/types.ts CHANGED
@@ -50,6 +50,8 @@ export interface AgentConfig extends AgentIdentity, AgentPromptConfig {
50
50
  model?: string;
51
51
  thinking?: ThinkingLevel;
52
52
  maxTurns?: number;
53
+ /** Wall-clock timeout in seconds; 0 = unlimited. */
54
+ timeout?: number;
53
55
  /** Default for spawn: fork parent conversation. undefined = caller decides. */
54
56
  inheritContext?: boolean;
55
57
  /** Default for spawn: run in background. undefined = caller decides. */
@@ -67,6 +69,8 @@ export interface AgentInvocation {
67
69
  modelName?: string;
68
70
  thinking?: ThinkingLevel;
69
71
  maxTurns?: number;
72
+ /** Normalized wall-clock timeout in seconds (display value; undefined = unlimited). */
73
+ timeout?: number;
70
74
  inheritContext?: boolean;
71
75
  runInBackground?: boolean;
72
76
  }
@@ -83,7 +87,6 @@ export interface SessionContext {
83
87
  readonly cwd: string;
84
88
  readonly model: unknown;
85
89
  readonly modelRegistry: ModelRegistry | undefined;
86
- getSystemPrompt(): string;
87
90
  readonly sessionManager: {
88
91
  getSessionFile(): string | undefined;
89
92
  getSessionId(): string;
package/src/ui/display.ts CHANGED
@@ -117,10 +117,10 @@ export function getDisplayName(type: SubagentType, registry: AgentConfigLookup):
117
117
  return config.displayName ?? config.name;
118
118
  }
119
119
 
120
- /** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
120
+ /** Short label for prompt mode: "append" for append, nothing for replace (the default). */
121
121
  export function getPromptModeLabel(type: SubagentType, registry: AgentConfigLookup): string | undefined {
122
122
  const config = registry.resolveAgentConfig(type);
123
- return config.promptMode === "append" ? "twin" : undefined;
123
+ return config.promptMode === "append" ? "append" : undefined;
124
124
  }
125
125
 
126
126
  /** Mode label is not included — callers add it where they want it. */
@@ -131,6 +131,7 @@ export function buildInvocationTags(invocation: AgentInvocation | undefined): {
131
131
  if (invocation.inheritContext) tags.push("inherit context");
132
132
  if (invocation.runInBackground) tags.push("background");
133
133
  if (invocation.maxTurns != null) tags.push(`max turns: ${invocation.maxTurns}`);
134
+ if (invocation.timeout != null) tags.push(`timeout: ${invocation.timeout}s`);
134
135
  return { modelName: invocation.modelName, tags };
135
136
  }
136
137
 
@@ -4,9 +4,11 @@
4
4
  export interface SubagentsSettingsManager {
5
5
  readonly maxConcurrent: number;
6
6
  readonly defaultMaxTurns: number | undefined;
7
+ readonly defaultTimeoutSeconds: number | undefined;
7
8
  readonly graceTurns: number;
8
9
  applyMaxConcurrent(n: number): { message: string; level: "info" | "warning" };
9
10
  applyDefaultMaxTurns(n: number): { message: string; level: "info" | "warning" };
11
+ applyDefaultTimeoutSeconds(n: number): { message: string; level: "info" | "warning" };
10
12
  applyGraceTurns(n: number): { message: string; level: "info" | "warning" };
11
13
  }
12
14
 
@@ -32,6 +34,7 @@ export class SubagentsSettingsHandler {
32
34
  const choice = await ui.select("Settings", [
33
35
  `Max concurrency (current: ${this.settings.maxConcurrent})`,
34
36
  `Default max turns (current: ${this.settings.defaultMaxTurns ?? "unlimited"})`,
37
+ `Default timeout (current: ${this.settings.defaultTimeoutSeconds != null ? `${this.settings.defaultTimeoutSeconds}s` : "unlimited"})`,
35
38
  `Grace turns (current: ${this.settings.graceTurns})`,
36
39
  ]);
37
40
  if (!choice) return;
@@ -61,6 +64,20 @@ export class SubagentsSettingsHandler {
61
64
  ui.notify("Must be 0 (unlimited) or a positive integer.", "warning");
62
65
  }
63
66
  }
67
+ } else if (choice.startsWith("Default timeout")) {
68
+ const val = await ui.input(
69
+ "Default timeout in seconds (0 = unlimited)",
70
+ String(this.settings.defaultTimeoutSeconds ?? 0),
71
+ );
72
+ if (val) {
73
+ const n = parseInt(val, 10);
74
+ if (n >= 0) {
75
+ const toast = this.settings.applyDefaultTimeoutSeconds(n);
76
+ ui.notify(toast.message, toast.level);
77
+ } else {
78
+ ui.notify("Must be 0 (unlimited) or a positive integer.", "warning");
79
+ }
80
+ }
64
81
  } else if (choice.startsWith("Grace turns")) {
65
82
  const val = await ui.input("Grace turns after wrap-up steer", String(this.settings.graceTurns));
66
83
  if (val) {