@yandy0725/pi-subagents 0.7.0 → 0.9.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 +29 -3
- package/README.zh.md +29 -3
- package/index.ts +1 -1
- package/package.json +4 -4
- package/src/config/custom-agents.ts +1 -0
- package/src/config/invocation-config.ts +3 -0
- package/src/index.ts +4 -4
- package/src/lifecycle/create-subagent-session.ts +46 -30
- package/src/lifecycle/parent-snapshot.ts +0 -3
- package/src/lifecycle/subagent-manager.ts +3 -29
- package/src/lifecycle/subagent-session.ts +28 -0
- package/src/lifecycle/subagent.ts +55 -46
- package/src/lifecycle/turn-limits.ts +9 -2
- package/src/observation/notification.ts +1 -1
- package/src/service/service-adapter.ts +4 -6
- package/src/service/service.ts +4 -26
- package/src/session/prompts.ts +53 -56
- package/src/session/session-config.ts +19 -17
- package/src/settings.ts +46 -1
- package/src/tools/agent-tool.ts +9 -0
- package/src/tools/background-spawner.ts +1 -0
- package/src/tools/foreground-runner.ts +1 -0
- package/src/tools/helpers.ts +1 -1
- package/src/tools/result-renderer.ts +1 -1
- package/src/tools/spawn-config.ts +6 -2
- package/src/types.ts +4 -1
- package/src/ui/display.ts +3 -2
- package/src/ui/subagents-settings.ts +17 -0
- package/src/lifecycle/workspace-bracket.ts +0 -59
- package/src/lifecycle/workspace.ts +0 -47
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 |
|
|
47
|
-
| `Explore` | read, bash, grep, find, ls |
|
|
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 |
|
|
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/index.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { default } from "./src/index.js";
|
|
2
|
-
export { getSubagentsService, type SubagentsService
|
|
2
|
+
export { getSubagentsService, type SubagentsService } from "./src/service/service.js";
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.9.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.
|
|
41
|
+
"@biomejs/biome": "^2.6.2",
|
|
42
42
|
"@types/node": "^26.6.5",
|
|
43
|
-
"typebox": "^1.3
|
|
43
|
+
"typebox": "^1.4.3",
|
|
44
44
|
"typescript": "~7.0.2",
|
|
45
|
-
"vitest": "^5.0.
|
|
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 {
|
|
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
|
-
|
|
98
|
+
buildReplacePrompt,
|
|
99
|
+
buildAppendSection,
|
|
99
100
|
},
|
|
100
101
|
},
|
|
101
102
|
exec: (cmd, args, opts) => pi.exec(cmd, args, opts),
|
|
@@ -109,7 +110,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
109
110
|
|
|
110
111
|
const manager = new SubagentManager({
|
|
111
112
|
createSubagentSession: (params) => createSubagentSession(params, subagentSessionDeps),
|
|
112
|
-
baseCwd: process.cwd(),
|
|
113
113
|
observer,
|
|
114
114
|
limiter,
|
|
115
115
|
getRunConfig: () => settings,
|
|
@@ -162,7 +162,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
162
162
|
const subagentsSettings = new SubagentsSettingsHandler(settings);
|
|
163
163
|
|
|
164
164
|
pi.registerCommand("subagents:settings", {
|
|
165
|
-
description: "Configure subagent settings (concurrency, turn limits)",
|
|
165
|
+
description: "Configure subagent settings (concurrency, turn limits, timeouts)",
|
|
166
166
|
handler: async (_args, ctx) => {
|
|
167
167
|
await subagentsSettings.handle({ ui: ctx.ui });
|
|
168
168
|
},
|
|
@@ -7,9 +7,8 @@
|
|
|
7
7
|
* and apply the recursion guard. It returns a fully usable `SubagentSession` —
|
|
8
8
|
* `Subagent` then only coordinates (turn loop, steer, dispose).
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* createSession), so threading the provider through here would be a relay smell.
|
|
10
|
+
* Every child runs in the parent's cwd: `snapshot.cwd` feeds detectEnv,
|
|
11
|
+
* assembleSessionConfig and createSession directly.
|
|
13
12
|
*/
|
|
14
13
|
|
|
15
14
|
import type { Model } from "@earendil-works/pi-ai";
|
|
@@ -19,7 +18,7 @@ import type { ChildLifecyclePublisher } from "../lifecycle/child-lifecycle";
|
|
|
19
18
|
import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
|
|
20
19
|
import { SubagentSession } from "../lifecycle/subagent-session";
|
|
21
20
|
import type { EnvInfo } from "../session/env";
|
|
22
|
-
import { type AssemblerIO, assembleSessionConfig } from "../session/session-config";
|
|
21
|
+
import { type AssemblerIO, assembleSessionConfig, type SessionConfig } from "../session/session-config";
|
|
23
22
|
import type { ParentSessionInfo, ShellExec, SubagentType, ThinkingLevel } from "../types";
|
|
24
23
|
|
|
25
24
|
/** Names of tools registered by this extension that subagents must NOT inherit. */
|
|
@@ -83,7 +82,7 @@ export interface CreateSessionOptions {
|
|
|
83
82
|
export interface EnvironmentIO {
|
|
84
83
|
detectEnv: (exec: ShellExec, cwd: string) => Promise<EnvInfo>;
|
|
85
84
|
getAgentDir: () => string;
|
|
86
|
-
deriveSessionDir: (parentSessionFile: string | undefined,
|
|
85
|
+
deriveSessionDir: (parentSessionFile: string | undefined, cwd: string) => string;
|
|
87
86
|
}
|
|
88
87
|
|
|
89
88
|
/**
|
|
@@ -124,14 +123,42 @@ export interface SubagentSessionDeps {
|
|
|
124
123
|
export interface CreateSubagentSessionParams {
|
|
125
124
|
snapshot: ParentSnapshot;
|
|
126
125
|
type: SubagentType;
|
|
127
|
-
/** Resolved workspace cwd; undefined → parent cwd. */
|
|
128
|
-
cwd?: string;
|
|
129
126
|
/** Parent session identity (file path + session ID). */
|
|
130
127
|
parentSession?: ParentSessionInfo;
|
|
131
128
|
model?: Model<any>;
|
|
132
129
|
thinkingLevel?: ThinkingLevel;
|
|
133
130
|
}
|
|
134
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Map a session config onto resource-loader options.
|
|
134
|
+
*
|
|
135
|
+
* "append": no system-prompt override, so the harness renders the base prompt
|
|
136
|
+
* for the child's own tool set (tool list, tool guidelines, skills, AGENTS.md,
|
|
137
|
+
* SYSTEM.md, APPEND_SYSTEM.md, date/cwd); we only append our section, keeping
|
|
138
|
+
* any APPEND_SYSTEM.md content ahead of it.
|
|
139
|
+
*
|
|
140
|
+
* "replace": we own the whole prompt, so the system prompt is overridden and
|
|
141
|
+
* both context files and the append file are suppressed.
|
|
142
|
+
*
|
|
143
|
+
* Exported (and kept free of IO) so the harness contract it depends on can be
|
|
144
|
+
* exercised against a real DefaultResourceLoader instead of a mock.
|
|
145
|
+
*/
|
|
146
|
+
export function buildResourceLoaderOptions(cfg: SessionConfig, agentDir: string): ResourceLoaderOptions {
|
|
147
|
+
const isReplace = cfg.promptMode === "replace";
|
|
148
|
+
return {
|
|
149
|
+
cwd: cfg.cwd,
|
|
150
|
+
agentDir,
|
|
151
|
+
noPromptTemplates: true,
|
|
152
|
+
noThemes: true,
|
|
153
|
+
noContextFiles: isReplace,
|
|
154
|
+
// Written out instead of spread conditionals: a conditional spread defeats
|
|
155
|
+
// TypeScript's excess-property check, and a typo here would silently fall
|
|
156
|
+
// back to append semantics (the bug this change exists to fix).
|
|
157
|
+
systemPromptOverride: isReplace ? () => cfg.promptSection : undefined,
|
|
158
|
+
appendSystemPromptOverride: isReplace ? () => [] : (base: string[]) => [...base, cfg.promptSection],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
135
162
|
/**
|
|
136
163
|
* Build a born-complete SubagentSession: assemble config, create the SDK
|
|
137
164
|
* session, publish lifecycle events, bind extensions, apply the recursion guard.
|
|
@@ -144,21 +171,18 @@ export async function createSubagentSession(
|
|
|
144
171
|
const parentSessionId = params.parentSession?.parentSessionId;
|
|
145
172
|
deps.lifecycle.spawning({ agentName: type, parentSessionId });
|
|
146
173
|
|
|
147
|
-
//
|
|
148
|
-
const
|
|
149
|
-
const env = await deps.io.detectEnv(deps.exec, effectiveCwd);
|
|
174
|
+
// detectEnv runs before assembly, so it reads the cwd from the snapshot directly.
|
|
175
|
+
const env = await deps.io.detectEnv(deps.exec, snapshot.cwd);
|
|
150
176
|
|
|
151
177
|
// Assemble session configuration (synchronous, no SDK objects).
|
|
152
178
|
const cfg = assembleSessionConfig(
|
|
153
179
|
type,
|
|
154
180
|
{
|
|
155
181
|
cwd: snapshot.cwd,
|
|
156
|
-
parentSystemPrompt: snapshot.systemPrompt,
|
|
157
182
|
parentModel: snapshot.model,
|
|
158
183
|
modelRegistry: snapshot.modelRegistry,
|
|
159
184
|
},
|
|
160
185
|
{
|
|
161
|
-
cwd: params.cwd,
|
|
162
186
|
model: params.model,
|
|
163
187
|
thinkingLevel: params.thinkingLevel,
|
|
164
188
|
},
|
|
@@ -170,35 +194,27 @@ export async function createSubagentSession(
|
|
|
170
194
|
const agentDir = deps.io.getAgentDir();
|
|
171
195
|
|
|
172
196
|
// Children always load the parent's extensions and skills.
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
//
|
|
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
|
-
});
|
|
197
|
+
//
|
|
198
|
+
// "append" lets the harness render the base prompt for the child's own tool
|
|
199
|
+
// set (tool list, tool guidelines, skills, AGENTS.md, SYSTEM.md, date/cwd)
|
|
200
|
+
// and appends our section to it. "replace" owns the whole prompt, so context
|
|
201
|
+
// files and the append file are suppressed.
|
|
202
|
+
const loader = deps.io.createResourceLoader(buildResourceLoaderOptions(cfg, agentDir));
|
|
187
203
|
await loader.reload();
|
|
188
204
|
|
|
189
205
|
// Create a persisted SessionManager so transcripts are written in Pi's
|
|
190
206
|
// official JSONL format. Falls back to a temp directory when the parent
|
|
191
207
|
// session is not persisted (e.g. headless/API mode).
|
|
192
|
-
const sessionDir = deps.io.deriveSessionDir(params.parentSession?.parentSessionFile, cfg.
|
|
193
|
-
const sessionManager = deps.io.createSessionManager(cfg.
|
|
208
|
+
const sessionDir = deps.io.deriveSessionDir(params.parentSession?.parentSessionFile, cfg.cwd);
|
|
209
|
+
const sessionManager = deps.io.createSessionManager(cfg.cwd, sessionDir);
|
|
194
210
|
sessionManager.newSession({ parentSession: params.parentSession?.parentSessionId });
|
|
195
211
|
const sessionId = sessionManager.getSessionId();
|
|
196
212
|
|
|
197
213
|
const { session } = await deps.io.createSession({
|
|
198
|
-
cwd: cfg.
|
|
214
|
+
cwd: cfg.cwd,
|
|
199
215
|
agentDir,
|
|
200
216
|
sessionManager,
|
|
201
|
-
settingsManager: deps.io.createSettingsManager(cfg.
|
|
217
|
+
settingsManager: deps.io.createSettingsManager(cfg.cwd, agentDir),
|
|
202
218
|
modelRegistry: snapshot.modelRegistry,
|
|
203
219
|
model: cfg.model,
|
|
204
220
|
tools: cfg.toolNames,
|
|
@@ -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!,
|
|
@@ -15,7 +15,6 @@ import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
|
|
|
15
15
|
import { Subagent, type SubagentLifecycleObserver } from "../lifecycle/subagent";
|
|
16
16
|
import type { SubagentSession } from "../lifecycle/subagent-session";
|
|
17
17
|
import { SubagentState, type SubagentStatus } from "../lifecycle/subagent-state";
|
|
18
|
-
import type { WorkspaceProvider } from "../lifecycle/workspace";
|
|
19
18
|
|
|
20
19
|
import type { RunConfig } from "../runtime";
|
|
21
20
|
import type { AgentInvocation, CompactionInfo, ParentSessionInfo, SubagentType, ThinkingLevel } from "../types";
|
|
@@ -57,8 +56,6 @@ export interface SubagentManagerOptions {
|
|
|
57
56
|
createSubagentSession: (params: CreateSubagentSessionParams) => Promise<SubagentSession>;
|
|
58
57
|
/** Concurrency limiter — schedules background run thunks FIFO against the limit. */
|
|
59
58
|
limiter: ConcurrencyLimiter;
|
|
60
|
-
/** Base working directory handed to a workspace provider (the parent cwd). */
|
|
61
|
-
baseCwd: string;
|
|
62
59
|
getRunConfig?: () => RunConfig;
|
|
63
60
|
observer?: SubagentManagerObserver;
|
|
64
61
|
}
|
|
@@ -67,6 +64,8 @@ export interface AgentSpawnConfig {
|
|
|
67
64
|
description: string;
|
|
68
65
|
model?: Model<any>;
|
|
69
66
|
maxTurns?: number;
|
|
67
|
+
/** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
|
|
68
|
+
timeoutSeconds?: number;
|
|
70
69
|
inheritContext?: boolean;
|
|
71
70
|
thinkingLevel?: ThinkingLevel;
|
|
72
71
|
isBackground?: boolean;
|
|
@@ -94,19 +93,10 @@ export class SubagentManager {
|
|
|
94
93
|
private readonly observer?: SubagentManagerObserver;
|
|
95
94
|
private readonly createSubagentSession: (params: CreateSubagentSessionParams) => Promise<SubagentSession>;
|
|
96
95
|
private readonly limiter: ConcurrencyLimiter;
|
|
97
|
-
private readonly baseCwd: string;
|
|
98
96
|
private getRunConfig?: () => RunConfig;
|
|
99
|
-
private _workspaceProvider?: WorkspaceProvider;
|
|
100
|
-
|
|
101
|
-
/** The registered workspace provider, or undefined when none is registered. */
|
|
102
|
-
get workspaceProvider(): WorkspaceProvider | undefined {
|
|
103
|
-
return this._workspaceProvider;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
97
|
constructor(options: SubagentManagerOptions) {
|
|
107
98
|
this.createSubagentSession = options.createSubagentSession;
|
|
108
99
|
this.limiter = options.limiter;
|
|
109
|
-
this.baseCwd = options.baseCwd;
|
|
110
100
|
this.observer = options.observer;
|
|
111
101
|
this.getRunConfig = options.getRunConfig;
|
|
112
102
|
// Cleanup completed agents after 10 minutes (but keep sessions for resume)
|
|
@@ -114,21 +104,6 @@ export class SubagentManager {
|
|
|
114
104
|
this.cleanupInterval.unref();
|
|
115
105
|
}
|
|
116
106
|
|
|
117
|
-
/**
|
|
118
|
-
* Register the single workspace provider. Throws if one is already
|
|
119
|
-
* registered (chaining is out of scope — see ADR 0002). Returns a disposer
|
|
120
|
-
* that clears the slot only if this provider is still the active one.
|
|
121
|
-
*/
|
|
122
|
-
registerWorkspaceProvider(provider: WorkspaceProvider): () => void {
|
|
123
|
-
if (this._workspaceProvider) {
|
|
124
|
-
throw new Error("A WorkspaceProvider is already registered; only one is supported.");
|
|
125
|
-
}
|
|
126
|
-
this._workspaceProvider = provider;
|
|
127
|
-
return () => {
|
|
128
|
-
if (this._workspaceProvider === provider) this._workspaceProvider = undefined;
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
107
|
/** Compose a per-agent lifecycle observer from manager and spawn-config concerns. */
|
|
133
108
|
private buildObserver(options: AgentSpawnConfig): SubagentLifecycleObserver {
|
|
134
109
|
return {
|
|
@@ -172,12 +147,11 @@ export class SubagentManager {
|
|
|
172
147
|
createSubagentSession: this.createSubagentSession,
|
|
173
148
|
snapshot,
|
|
174
149
|
prompt,
|
|
175
|
-
baseCwd: this.baseCwd,
|
|
176
150
|
observer: this.buildObserver(options),
|
|
177
151
|
getRunConfig: this.getRunConfig,
|
|
178
|
-
getWorkspaceProvider: () => this._workspaceProvider,
|
|
179
152
|
model: options.model,
|
|
180
153
|
maxTurns: options.maxTurns,
|
|
154
|
+
timeoutSeconds: options.timeoutSeconds,
|
|
181
155
|
thinkingLevel: options.thinkingLevel,
|
|
182
156
|
parentSession: options.parentSession,
|
|
183
157
|
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
|
}
|