@yandy0725/pi-subagents 0.6.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
@@ -13,7 +13,7 @@ A [pi](https://pi.dev) extension providing a focused, in-process sub-agent core
13
13
  - **Graceful turn limits** — agents get a "wrap up" warning before hard abort
14
14
  - **Case-insensitive types** — `"explore"`, `"Explore"`, `"EXPLORE"` all work
15
15
  - **Fuzzy model selection** — specify models by name (`"haiku"`, `"sonnet"`) instead of full IDs
16
- - **Model tiers** — pick `fast` / `standard` / `advanced` and map each tier to a real model in config, instead of naming a model per call
16
+ - **Model tiers** — map `fast` / `standard` / `advanced` to real models in config; the agent is guided to pick the configured model per task
17
17
  - **Context inheritance** — optionally fork the parent conversation into a sub-agent
18
18
  - **Styled notifications** — background results render as themed notification boxes
19
19
  - **Event bus** — lifecycle events (`subagents:created`, `started`, `completed`, `failed`, `steered`, `compacted`) via `pi.events`
@@ -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`
@@ -75,10 +91,10 @@ Launch a sub-agent.
75
91
  | `prompt` | string | yes | The task for the agent |
76
92
  | `description` | string | yes | Short 3-5 word summary (shown in UI) |
77
93
  | `subagent_type` | string | yes | Agent type (built-in or custom) |
78
- | `model` | string | no | Model override (`provider/modelId` or fuzzy name). Mutually exclusive with `model_tier` |
79
- | `model_tier` | string | no | Capability tier: `fast` / `standard` / `advanced`. Mutually exclusive with `model` |
94
+ | `model` | string | no | Model override (`provider/modelId` or fuzzy name) |
80
95
  | `thinking` | string | no | off / minimal / low / medium / high / xhigh |
81
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) |
82
98
  | `run_in_background` | boolean | no | Run without blocking |
83
99
  | `resume` | string | no | Agent ID to resume a previous session |
84
100
  | `inherit_context` | boolean | no | Fork parent conversation into agent |
@@ -104,8 +120,10 @@ Send a steering message to a running agent.
104
120
 
105
121
  ## Model Tiers
106
122
 
107
- The `subagent` tool accepts `model_tier` as an alternative to `model`: the caller asks for a
108
- capability class and each user decides which real model sits behind it.
123
+ Instead of hardcoding model IDs, you can map capability tiers to concrete models in
124
+ `subagents.json`. The mapping feeds the `subagent` tool's prompt guidelines, which tell the
125
+ agent which model to pass via the `model` parameter — there is no `model_tier` tool
126
+ parameter.
109
127
 
110
128
  | Tier | Intent |
111
129
  |------|--------|
@@ -127,17 +145,16 @@ override one tier without restating the others:
127
145
  }
128
146
  ```
129
147
 
130
- Tier values go through the same resolver as `model`, so `provider/modelId` and fuzzy names
131
- (e.g. `"haiku"`) both work. `model` and `model_tier` are mutually exclusive, and calling a
132
- tier that is not configured returns an error naming the file to fix — a tier request is
133
- never silently downgraded to the parent model. If an agent type pins `model` in its
134
- frontmatter, that model wins over both parameters.
148
+ Because the agent copies the mapped value into `model`, it goes through the same resolver as
149
+ any other model value: `provider/modelId` and fuzzy names (e.g. `"haiku"`) both work. Tiers
150
+ without a mapping are omitted from the guidelines — nothing is silently substituted for
151
+ them. If an agent type pins `model` in its frontmatter, that model always wins.
135
152
 
136
153
  ## Commands
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
@@ -13,7 +13,7 @@
13
13
  - **优雅轮次限制** — 代理在硬中止前收到"收尾"警告
14
14
  - **大小写不敏感** — `"explore"`、`"Explore"`、`"EXPLORE"` 均可
15
15
  - **模糊模型选择** — 按名称(`"haiku"`、`"sonnet"`)而非完整 ID 指定模型
16
- - **模型分层** — 用 `fast` / `standard` / `advanced` 档位代替逐次点名模型,每档对应的真实模型写在配置里
16
+ - **模型分层** — 在配置里把 `fast` / `standard` / `advanced` 档位映射到真实模型,代理按提示选择对应模型
17
17
  - **上下文继承** — 可选择将父对话分叉给子代理
18
18
  - **风格化通知** — 后台结果渲染为主题化通知框
19
19
  - **事件总线** — 通过 `pi.events` 发出生命周期事件(`subagents:created`、`started`、`completed`、`failed`、`steered`、`compacted`)
@@ -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`
@@ -75,10 +91,10 @@ max_turns: 30
75
91
  | `prompt` | string | 是 | 代理要执行的任务 |
76
92
  | `description` | string | 是 | 3-5 词简短描述(UI 中显示) |
77
93
  | `subagent_type` | string | 是 | 代理类型(内置或自定义) |
78
- | `model` | string | 否 | 模型覆盖(`provider/modelId` 或模糊名称;与 `model_tier` 互斥) |
79
- | `model_tier` | string | 否 | 能力档位:`fast` / `standard` / `advanced`(与 `model` 互斥) |
94
+ | `model` | string | 否 | 模型覆盖(`provider/modelId` 或模糊名称) |
80
95
  | `thinking` | string | 否 | off / minimal / low / medium / high / xhigh |
81
96
  | `max_turns` | number | 否 | 最大代理轮次(默认无限制) |
97
+ | `timeout` | number | 否 | 墙钟硬性时限(秒);到点即终止代理并返回已产出的部分输出(默认无限制) |
82
98
  | `run_in_background` | boolean | 否 | 后台运行不阻塞 |
83
99
  | `resume` | string | 否 | 恢复之前会话的代理 ID |
84
100
  | `inherit_context` | boolean | 否 | 将父对话分叉给子代理 |
@@ -104,8 +120,9 @@ max_turns: 30
104
120
 
105
121
  ## 模型分层
106
122
 
107
- `subagent` 工具除 `model` 外还接受 `model_tier`:调用方只表达"要什么档位的模型",
108
- 由使用者在配置里决定每档对应哪个真实模型。
123
+ 除了直接写模型 ID,还可以在 `subagents.json` 中把能力档位映射到真实模型。映射会生成
124
+ `subagent` 工具的 prompt guidelines,告诉代理每个档位应通过 `model` 参数传哪个模型——
125
+ 不存在 `model_tier` 工具参数。
109
126
 
110
127
  | 档位 | 定位 |
111
128
  |------|------|
@@ -126,15 +143,15 @@ max_turns: 30
126
143
  }
127
144
  ```
128
145
 
129
- 档位取值与 `model` 走同一套解析,`provider/modelId` 和模糊名称(如 `"haiku"`)都可以。
130
- `model` 与 `model_tier` 互斥;调用未配置的档位会直接报错并指出该改哪个文件——不会静默
131
- 降级为父模型。若代理类型的 frontmatter 固定了 `model`,该模型优先于两个参数。
146
+ 代理会把映射值复制到 `model`,因此与普通 `model` 值走同一套解析:`provider/modelId` 与
147
+ 模糊名称(如 `"haiku"`)都可以。未配置的档位不会出现在提示里——不会有其他模型被静默
148
+ 顶替。若代理类型的 frontmatter 固定了 `model`,该模型始终优先。
132
149
 
133
150
  ## 命令
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.6.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,
@@ -2,9 +2,9 @@ import type { AgentConfig, ThinkingLevel } from "../types";
2
2
 
3
3
  interface AgentInvocationParams {
4
4
  model?: string;
5
- model_tier?: string;
6
5
  thinking?: string;
7
6
  max_turns?: number;
7
+ timeout?: number;
8
8
  run_in_background?: boolean;
9
9
  inherit_context?: boolean;
10
10
  }
@@ -12,25 +12,21 @@ interface AgentInvocationParams {
12
12
  export function resolveAgentInvocationConfig(
13
13
  agentConfig: AgentConfig | undefined,
14
14
  params: AgentInvocationParams,
15
- /**
16
- * Model reference already resolved from `params.model_tier` by the caller
17
- * (spawn-config resolves the tier so it can surface config errors). Precedence
18
- * matches `params.model`: agent config wins, then params, then the tier.
19
- */
20
- tierModel?: string,
21
15
  ): {
22
16
  modelInput?: string;
23
17
  modelFromParams: boolean;
24
18
  thinking?: ThinkingLevel;
25
19
  maxTurns?: number;
20
+ timeout?: number;
26
21
  inheritContext: boolean;
27
22
  runInBackground: boolean;
28
23
  } {
29
24
  return {
30
- modelInput: agentConfig?.model ?? params.model ?? tierModel,
31
- modelFromParams: agentConfig?.model == null && (params.model ?? tierModel) != null,
25
+ modelInput: agentConfig?.model ?? params.model,
26
+ modelFromParams: agentConfig?.model == null && params.model != null,
32
27
  thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
33
28
  maxTurns: agentConfig?.maxTurns ?? params.max_turns,
29
+ timeout: agentConfig?.timeout ?? params.timeout,
34
30
  inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
35
31
  runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
36
32
  };
@@ -1,10 +1,11 @@
1
1
  /**
2
- * model-tiers.ts — Capability/cost tiers for the subagent tool's `model_tier` param.
2
+ * model-tiers.ts — Capability/cost tier vocabulary for subagent model selection.
3
3
  *
4
- * A tier is an indirection: the calling agent asks for a class of model
5
- * (`fast` | `standard` | `advanced`) and the user decides which real model each
6
- * class maps to in `subagents.json` (`modelTiers`). See README for the intended
7
- * semantics of each tier.
4
+ * A tier is a user-facing class of model (`fast` | `standard` | `advanced`).
5
+ * Users map each tier to a real model in `subagents.json` (`modelTiers`); the
6
+ * mapping is surfaced to the agent through the `subagent` tool's prompt
7
+ * guidelines so it can pass the configured model via the `model` parameter.
8
+ * There is no `model_tier` tool parameter. See README for tier semantics.
8
9
  */
9
10
 
10
11
  export const MODEL_TIERS = ["fast", "standard", "advanced"] as const;
@@ -14,53 +15,9 @@ export type ModelTier = (typeof MODEL_TIERS)[number];
14
15
  /** Partial tier → model mapping as configured in `subagents.json`. */
15
16
  export type ModelTierMap = Partial<Record<ModelTier, string>>;
16
17
 
17
- /**
18
- * Case-insensitively map a raw value to a canonical tier.
19
- * Returns undefined for unknown names and non-strings.
20
- */
21
- export function normalizeModelTier(value: unknown): ModelTier | undefined {
22
- if (typeof value !== "string") return undefined;
23
- const lower = value.trim().toLowerCase();
24
- return (MODEL_TIERS as readonly string[]).includes(lower) ? (lower as ModelTier) : undefined;
25
- }
26
-
27
- /** Successful resolution — `model` is the configured model reference, not a Model instance. */
28
- export interface ModelTierResolutionResult {
29
- model: string;
30
- error?: undefined;
31
- }
32
-
33
- /** Failed resolution: unknown tier name or no mapping configured for a known tier. */
34
- export interface ModelTierResolutionError {
35
- model?: undefined;
36
- error: string;
37
- }
38
-
39
- export type ModelTierResolution = ModelTierResolutionResult | ModelTierResolutionError;
40
-
41
- /** Where users configure the tier map — repeated in error messages. */
42
- const SETTINGS_HINT = "Configure it in .pi/subagents.json or ~/.pi/agent/subagents.json";
43
-
44
- /**
45
- * Resolve a `model_tier` param value to the model reference configured for it.
46
- * An unknown tier or an unconfigured mapping is an explicit error — a tier
47
- * request is never silently downgraded to another model.
48
- */
49
- export function resolveModelTier(input: unknown, tiers: ModelTierMap | undefined): ModelTierResolution {
50
- const tier = normalizeModelTier(input);
51
- if (!tier) {
52
- return {
53
- error: `Unknown model tier: "${String(input)}". Valid tiers: ${MODEL_TIERS.join(", ")}.`,
54
- };
55
- }
56
-
57
- const configured = tiers?.[tier];
58
- const model = typeof configured === "string" ? configured.trim() : "";
59
- if (!model) {
60
- return {
61
- error: `Model tier "${tier}" is not configured. ${SETTINGS_HINT}, e.g. {"modelTiers": {"${tier}": "provider/modelId"}}.`,
62
- };
63
- }
64
-
65
- return { model };
66
- }
18
+ /** LLM-facing intent of each tier — mirrors the README table. */
19
+ export const MODEL_TIER_INTENTS: Record<ModelTier, string> = {
20
+ fast: "cheapest, fastest, least capable",
21
+ standard: "balanced default",
22
+ advanced: "most capable, most expensive",
23
+ };
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
  }