@yandy0725/pi-subagents 0.8.0 → 0.10.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/index.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { default } from "./src/index.js";
2
- export { getSubagentsService, type SubagentsService, type WorkspaceProvider } from "./src/service/service.js";
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.8.0",
6
+ "version": "0.10.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": {
package/src/index.ts CHANGED
@@ -110,7 +110,6 @@ export default function (pi: ExtensionAPI) {
110
110
 
111
111
  const manager = new SubagentManager({
112
112
  createSubagentSession: (params) => createSubagentSession(params, subagentSessionDeps),
113
- baseCwd: process.cwd(),
114
113
  observer,
115
114
  limiter,
116
115
  getRunConfig: () => settings,
@@ -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
- * The factory takes a resolved `cwd` value, never the WorkspaceProvider: `cwd`
11
- * is a value the factory consumes directly (detectEnv, assembleSessionConfig,
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";
@@ -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, effectiveCwd: string) => string;
85
+ deriveSessionDir: (parentSessionFile: string | undefined, cwd: string) => string;
87
86
  }
88
87
 
89
88
  /**
@@ -124,8 +123,6 @@ 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>;
@@ -149,7 +146,7 @@ export interface CreateSubagentSessionParams {
149
146
  export function buildResourceLoaderOptions(cfg: SessionConfig, agentDir: string): ResourceLoaderOptions {
150
147
  const isReplace = cfg.promptMode === "replace";
151
148
  return {
152
- cwd: cfg.effectiveCwd,
149
+ cwd: cfg.cwd,
153
150
  agentDir,
154
151
  noPromptTemplates: true,
155
152
  noThemes: true,
@@ -174,9 +171,8 @@ export async function createSubagentSession(
174
171
  const parentSessionId = params.parentSession?.parentSessionId;
175
172
  deps.lifecycle.spawning({ agentName: type, parentSessionId });
176
173
 
177
- // Resolve working directory upfront - needed for detectEnv before assembly.
178
- const effectiveCwd = params.cwd ?? snapshot.cwd;
179
- 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);
180
176
 
181
177
  // Assemble session configuration (synchronous, no SDK objects).
182
178
  const cfg = assembleSessionConfig(
@@ -187,7 +183,6 @@ export async function createSubagentSession(
187
183
  modelRegistry: snapshot.modelRegistry,
188
184
  },
189
185
  {
190
- cwd: params.cwd,
191
186
  model: params.model,
192
187
  thinkingLevel: params.thinkingLevel,
193
188
  },
@@ -210,16 +205,16 @@ export async function createSubagentSession(
210
205
  // Create a persisted SessionManager so transcripts are written in Pi's
211
206
  // official JSONL format. Falls back to a temp directory when the parent
212
207
  // session is not persisted (e.g. headless/API mode).
213
- const sessionDir = deps.io.deriveSessionDir(params.parentSession?.parentSessionFile, cfg.effectiveCwd);
214
- const sessionManager = deps.io.createSessionManager(cfg.effectiveCwd, sessionDir);
208
+ const sessionDir = deps.io.deriveSessionDir(params.parentSession?.parentSessionFile, cfg.cwd);
209
+ const sessionManager = deps.io.createSessionManager(cfg.cwd, sessionDir);
215
210
  sessionManager.newSession({ parentSession: params.parentSession?.parentSessionId });
216
211
  const sessionId = sessionManager.getSessionId();
217
212
 
218
213
  const { session } = await deps.io.createSession({
219
- cwd: cfg.effectiveCwd,
214
+ cwd: cfg.cwd,
220
215
  agentDir,
221
216
  sessionManager,
222
- settingsManager: deps.io.createSettingsManager(cfg.effectiveCwd, agentDir),
217
+ settingsManager: deps.io.createSettingsManager(cfg.cwd, agentDir),
223
218
  modelRegistry: snapshot.modelRegistry,
224
219
  model: cfg.model,
225
220
  tools: cfg.toolNames,
@@ -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
  }
@@ -96,19 +93,10 @@ export class SubagentManager {
96
93
  private readonly observer?: SubagentManagerObserver;
97
94
  private readonly createSubagentSession: (params: CreateSubagentSessionParams) => Promise<SubagentSession>;
98
95
  private readonly limiter: ConcurrencyLimiter;
99
- private readonly baseCwd: string;
100
96
  private getRunConfig?: () => RunConfig;
101
- private _workspaceProvider?: WorkspaceProvider;
102
-
103
- /** The registered workspace provider, or undefined when none is registered. */
104
- get workspaceProvider(): WorkspaceProvider | undefined {
105
- return this._workspaceProvider;
106
- }
107
-
108
97
  constructor(options: SubagentManagerOptions) {
109
98
  this.createSubagentSession = options.createSubagentSession;
110
99
  this.limiter = options.limiter;
111
- this.baseCwd = options.baseCwd;
112
100
  this.observer = options.observer;
113
101
  this.getRunConfig = options.getRunConfig;
114
102
  // Cleanup completed agents after 10 minutes (but keep sessions for resume)
@@ -116,21 +104,6 @@ export class SubagentManager {
116
104
  this.cleanupInterval.unref();
117
105
  }
118
106
 
119
- /**
120
- * Register the single workspace provider. Throws if one is already
121
- * registered (chaining is out of scope — see ADR 0002). Returns a disposer
122
- * that clears the slot only if this provider is still the active one.
123
- */
124
- registerWorkspaceProvider(provider: WorkspaceProvider): () => void {
125
- if (this._workspaceProvider) {
126
- throw new Error("A WorkspaceProvider is already registered; only one is supported.");
127
- }
128
- this._workspaceProvider = provider;
129
- return () => {
130
- if (this._workspaceProvider === provider) this._workspaceProvider = undefined;
131
- };
132
- }
133
-
134
107
  /** Compose a per-agent lifecycle observer from manager and spawn-config concerns. */
135
108
  private buildObserver(options: AgentSpawnConfig): SubagentLifecycleObserver {
136
109
  return {
@@ -174,10 +147,8 @@ export class SubagentManager {
174
147
  createSubagentSession: this.createSubagentSession,
175
148
  snapshot,
176
149
  prompt,
177
- baseCwd: this.baseCwd,
178
150
  observer: this.buildObserver(options),
179
151
  getRunConfig: this.getRunConfig,
180
- getWorkspaceProvider: () => this._workspaceProvider,
181
152
  model: options.model,
182
153
  maxTurns: options.maxTurns,
183
154
  timeoutSeconds: options.timeoutSeconds,
@@ -2,21 +2,18 @@
2
2
  * subagent.ts — Subagent class: identity, lifecycle status, and per-subagent behavior.
3
3
  *
4
4
  * Status/stats are delegated to the SubagentState value object; listener
5
- * lifecycle to RunListeners; workspace prepare/dispose to WorkspaceBracket.
5
+ * lifecycle to RunListeners.
6
6
  * Behavior (abort, steer buffering) lives here rather than on SubagentManager.
7
7
  */
8
8
 
9
9
  import type { Model } from "@earendil-works/pi-ai";
10
10
  import type { AgentSessionEvent, ToolDefinition } from "@earendil-works/pi-coding-agent";
11
- import { debugLog } from "../debug";
12
11
  import type { CreateSubagentSessionParams } from "../lifecycle/create-subagent-session";
13
12
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
14
13
  import { RunListeners } from "../lifecycle/run-listeners";
15
14
  import type { SubagentSession, TurnLoopResult } from "../lifecycle/subagent-session";
16
15
  import { SubagentState, type SubagentStatus } from "../lifecycle/subagent-state";
17
16
  import type { LifetimeUsage } from "../lifecycle/usage";
18
- import type { WorkspaceProvider } from "../lifecycle/workspace";
19
- import { WorkspaceBracket } from "../lifecycle/workspace-bracket";
20
17
  import { NotificationState } from "../observation/notification-state";
21
18
  import { subscribeSubagentObserver } from "../observation/record-observer";
22
19
  import type { RunConfig } from "../runtime";
@@ -56,12 +53,8 @@ export interface SubagentExecution {
56
53
  snapshot: ParentSnapshot;
57
54
  /** Initial prompt for the turn loop. */
58
55
  prompt: string;
59
- /** Parent working directory handed to a workspace provider's prepare(). */
60
- baseCwd: string;
61
56
  observer?: SubagentLifecycleObserver;
62
57
  getRunConfig?: () => RunConfig;
63
- /** Resolves the registered workspace provider (if any) at run-start. */
64
- getWorkspaceProvider?: () => WorkspaceProvider | undefined;
65
58
  model?: Model<any>;
66
59
  maxTurns?: number;
67
60
  /** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
@@ -152,7 +145,6 @@ export class Subagent {
152
145
 
153
146
  private readonly execution: SubagentExecution;
154
147
  private readonly listeners = new RunListeners();
155
- private readonly workspaceBracket: WorkspaceBracket;
156
148
 
157
149
  subagentSession?: SubagentSession;
158
150
  private _notification?: NotificationState;
@@ -239,9 +231,6 @@ export class Subagent {
239
231
  // Execution machinery — a single mandatory collaborator
240
232
  this.execution = init.execution;
241
233
 
242
- // Per-run lifecycle collaborators
243
- this.workspaceBracket = new WorkspaceBracket(this.execution.getWorkspaceProvider ?? (() => undefined));
244
-
245
234
  // Notification state — created from parentSession.toolCallId if present
246
235
  const toolCallId = init.execution.parentSession?.toolCallId;
247
236
  if (toolCallId) {
@@ -250,9 +239,8 @@ export class Subagent {
250
239
  }
251
240
 
252
241
  /**
253
- * Execute the full agent lifecycle: workspace preparation, session creation
254
- * via the factory, observer wiring, the turn loop, workspace disposal, and
255
- * status transitions.
242
+ * Execute the full agent lifecycle: session creation via the factory,
243
+ * observer wiring, the turn loop, and status transitions.
256
244
  *
257
245
  * Execution is supplied at construction (mandatory), so run() needs no
258
246
  * "not configured" guards. The returned promise always resolves (errors are
@@ -264,32 +252,10 @@ export class Subagent {
264
252
  this.listeners.wireSignal(this.execution.signal, () => this.abort());
265
253
  this.startTimeoutGuard();
266
254
 
267
- // Guard the await so the no-provider path stays synchronous, preserving
268
- // the original run() timing: the factory is called in the same turn as
269
- // spawn() when no workspace provider is registered.
270
- let cwd: string | undefined;
271
- if (this.workspaceBracket.hasProvider()) {
272
- try {
273
- cwd = await this.workspaceBracket.prepare({
274
- agentId: this.id,
275
- agentType: this.type,
276
- baseCwd: this.execution.baseCwd,
277
- invocation: this.invocation,
278
- });
279
- } catch (err) {
280
- this.clearTimeoutGuard();
281
- this.markError(err);
282
- this.listeners.release();
283
- this.execution.observer?.onRunFinished?.(this);
284
- return;
285
- }
286
- }
287
-
288
255
  try {
289
256
  this.subagentSession = await this.execution.createSubagentSession({
290
257
  snapshot: this.execution.snapshot,
291
258
  type: this.type,
292
- cwd,
293
259
  parentSession: this.execution.parentSession,
294
260
  model: this.execution.model,
295
261
  thinkingLevel: this.execution.thinkingLevel,
@@ -513,7 +479,7 @@ export class Subagent {
513
479
  this.listeners.release();
514
480
  }
515
481
 
516
- /** Complete a run: release listeners, dispose the workspace, status transition, notify observer. */
482
+ /** Complete a run: release listeners, status transition, notify observer. */
517
483
  completeRun(result: TurnLoopResult): void {
518
484
  this.clearTimeoutGuard();
519
485
  this.listeners.release();
@@ -524,8 +490,7 @@ export class Subagent {
524
490
  this._timedOut && finalStatus === "aborted"
525
491
  ? `⏱ Timed out after ${this.execution.timeoutSeconds}s — output may be truncated.\n\n`
526
492
  : "";
527
- const finalResult =
528
- timeoutNote + responseText + this.workspaceBracket.dispose({ status: finalStatus, description: this.description });
493
+ const finalResult = timeoutNote + responseText;
529
494
 
530
495
  if (result.aborted) this.markAborted(finalResult);
531
496
  else if (result.steered) this.markSteered(finalResult);
@@ -539,18 +504,12 @@ export class Subagent {
539
504
  this.subagentSession?.dispose();
540
505
  }
541
506
 
542
- /** Fail a run: mark error, release listeners, best-effort workspace dispose, notify observer. */
507
+ /** Fail a run: mark error, release listeners, notify observer. */
543
508
  failRun(err: unknown): void {
544
509
  this.clearTimeoutGuard();
545
510
  this.markError(err);
546
511
  this.listeners.release();
547
512
 
548
- try {
549
- this.workspaceBracket.dispose({ status: "error", description: this.description });
550
- } catch (cleanupErr) {
551
- debugLog("workspace dispose on agent error", cleanupErr);
552
- }
553
-
554
513
  this.execution.observer?.onRunFinished?.(this);
555
514
  }
556
515
  }
@@ -6,7 +6,6 @@
6
6
  */
7
7
 
8
8
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
9
- import type { WorkspaceProvider } from "../lifecycle/workspace";
10
9
  import type { SpawnOptions, SubagentRecord, SubagentsService } from "../service/service";
11
10
  import type { ModelRegistry } from "../session/model-resolver";
12
11
  import { normalizeTimeoutSeconds } from "../lifecycle/turn-limits";
@@ -21,7 +20,6 @@ export interface SubagentManagerLike {
21
20
  abort(id: string): boolean;
22
21
  waitForAll(): Promise<void>;
23
22
  hasRunning(): boolean;
24
- registerWorkspaceProvider(provider: WorkspaceProvider): () => void;
25
23
  }
26
24
 
27
25
  /**
@@ -117,10 +115,6 @@ export class SubagentsServiceAdapter implements SubagentsService {
117
115
  hasRunning(): boolean {
118
116
  return this.manager.hasRunning();
119
117
  }
120
-
121
- registerWorkspaceProvider(provider: WorkspaceProvider): () => void {
122
- return this.manager.registerWorkspaceProvider(provider);
123
- }
124
118
  }
125
119
 
126
120
  /**
@@ -11,29 +11,11 @@
11
11
 
12
12
  import type { SubagentStatus } from "../lifecycle/subagent";
13
13
  import type { LifetimeUsage } from "../lifecycle/usage";
14
- import type {
15
- Workspace,
16
- WorkspaceDisposeOutcome,
17
- WorkspaceDisposeResult,
18
- WorkspacePrepareContext,
19
- WorkspaceProvider,
20
- } from "../lifecycle/workspace";
21
14
 
22
15
  // SubagentStatus is defined in the lifecycle layer (single home) and re-exported
23
- // here for the public API surface — mirrors the LifetimeUsage / workspace pattern.
16
+ // here for the public API surface — mirrors the LifetimeUsage pattern.
24
17
  export type { SubagentStatus } from "../lifecycle/subagent";
25
- // Generative extension seam (ADR 0002, Phase 16 Step 2). The provider type
26
- // and all four collaborator types it references are re-exported by name so
27
- // consumers can import them directly rather than recovering them via
28
- // indexed-access inference (e.g. `Parameters<WorkspaceProvider["prepare"]>[0]`).
29
- export type {
30
- LifetimeUsage,
31
- Workspace,
32
- WorkspaceDisposeOutcome,
33
- WorkspaceDisposeResult,
34
- WorkspacePrepareContext,
35
- WorkspaceProvider,
36
- };
18
+ export type { LifetimeUsage };
37
19
 
38
20
  /** Serializable snapshot of an agent's state — no live session objects. */
39
21
  export interface SubagentRecord {
@@ -88,12 +70,6 @@ export interface SubagentsService {
88
70
  /** Whether any agents are running or queued. */
89
71
  hasRunning(): boolean;
90
72
 
91
- /**
92
- * Register the single workspace provider that supplies a child's working
93
- * directory plus bracketed setup/teardown. Throws if one is already
94
- * registered. Returns a disposer that unregisters the provider.
95
- */
96
- registerWorkspaceProvider(provider: WorkspaceProvider): () => void;
97
73
  }
98
74
 
99
75
  /** Event channel constants for pi.events subscriptions. */
@@ -39,7 +39,7 @@ export interface AssemblerIO {
39
39
  * `resolveDefaultModel`.
40
40
  */
41
41
  export interface AssemblerContext {
42
- /** Parent working directory (overridable via options.cwd). */
42
+ /** Parent working directory — every child runs here. */
43
43
  cwd: string;
44
44
  /** Parent's current model instance (fallback when agent config has no model). */
45
45
  parentModel?: unknown;
@@ -55,8 +55,6 @@ export interface AssemblerContext {
55
55
  * All fields are optional — callers pass only what they have.
56
56
  */
57
57
  export interface AssemblerOptions {
58
- /** Override working directory (e.g. for worktree isolation). */
59
- cwd?: string;
60
58
  /** Explicit model override — wins over agentConfig.model and parent model. */
61
59
  model?: unknown;
62
60
  /** Explicit thinking level — wins over agentConfig.thinking. */
@@ -69,8 +67,8 @@ export interface AssemblerOptions {
69
67
  * with no SDK object references.
70
68
  */
71
69
  export interface SessionConfig {
72
- /** Resolved working directory (`options.cwd ?? ctx.cwd`). */
73
- effectiveCwd: string;
70
+ /** Working directory for the child — the parent's cwd, the only source. */
71
+ cwd: string;
74
72
  /** Prompt mode declared by the agent; decides how the caller wires the resource loader. */
75
73
  promptMode: "replace" | "append";
76
74
  /** Mode-specific text: the complete system prompt for "replace", the appended section for "append". */
@@ -131,7 +129,7 @@ function resolveDefaultModel(
131
129
  *
132
130
  * @param type The subagent type name (case-insensitive registry lookup).
133
131
  * @param ctx Narrow context from the parent session.
134
- * @param options Per-call overrides (cwd, model, thinkingLevel).
132
+ * @param options Per-call overrides (model, thinkingLevel).
135
133
  * @param env Pre-resolved environment info from `detectEnv()`.
136
134
  * @param registry Agent config lookup — provides resolveAgentConfig and getToolNamesForType.
137
135
  * @param io IO collaborators (skill loader, memory builder, prompt builder).
@@ -146,8 +144,6 @@ export function assembleSessionConfig(
146
144
  ): SessionConfig {
147
145
  const agentConfig = registry.resolveAgentConfig(type);
148
146
 
149
- const effectiveCwd = options.cwd ?? ctx.cwd;
150
-
151
147
  const toolNames = registry.getToolNamesForType(type);
152
148
 
153
149
  // Assemble the prompt text: "replace" owns the whole prompt, "append" only
@@ -167,7 +163,7 @@ export function assembleSessionConfig(
167
163
  const agentMaxTurns = agentConfig.maxTurns;
168
164
 
169
165
  return {
170
- effectiveCwd,
166
+ cwd: ctx.cwd,
171
167
  promptMode: agentConfig.promptMode,
172
168
  promptSection,
173
169
  toolNames,
@@ -1,6 +1,7 @@
1
1
  /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions -- Pi SDK types are not fully exported; see upstream Pi SDK for type improvements */
2
2
  import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
3
  import { defineTool } from "@earendil-works/pi-coding-agent";
4
+ import { StringEnum } from "@earendil-works/pi-ai";
4
5
  import { Text } from "@earendil-works/pi-tui";
5
6
  import { Type } from "typebox";
6
7
  import type { AgentTypeRegistry } from "../config/agent-types";
@@ -54,6 +55,21 @@ function buildTierGuideline(tiers: ModelTierMap | undefined): string | undefined
54
55
  return `User-configured subagent model tiers — when a task needs one of these capability levels, pass the mapped model via the model parameter: ${configured.join(", ")}.`;
55
56
  }
56
57
 
58
+ /**
59
+ * 行为纪律(进 system prompt 的 Guidelines,不进 description)。
60
+ *
61
+ * 之前这些写在 `description` 里,同时与参数描述重复(`run_in_background` / `resume` / `model` /
62
+ * `thinking` / `timeout` / `inherit_context` 各说两遍,共 516 字符),而 description 是每工具
63
+ * 各一份、不参与去重。现在只留“何时用 / 怎么配合”这一类,参数细节全交给参数描述。
64
+ */
65
+ const PROMPT_GUIDELINES: readonly string[] = [
66
+ "Use subagent for work that needs its own context or a different model; finish inline work yourself.",
67
+ "For parallel work set run_in_background: true on each agent — sibling foreground calls run concurrently anyway, but they block the current turn and bypass the concurrency limit.",
68
+ "Give each subagent a self-contained prompt; it cannot see the parent conversation unless inherit_context is true.",
69
+ "Subagent results come back as text — summarize them for the user.",
70
+ "Use steer_subagent to redirect a running background agent, and get_subagent_result with wait: true to block for one result.",
71
+ ];
72
+
57
73
  // ---- Class ----
58
74
 
59
75
  export class AgentTool {
@@ -131,27 +147,12 @@ export class AgentTool {
131
147
  return defineTool({
132
148
  name: "subagent" as const,
133
149
  label: "Subagent",
134
- promptSnippet: "subagent: Launch a specialized agent for complex, multi-step tasks.",
135
- ...(tierGuideline ? { promptGuidelines: [tierGuideline] } : {}),
136
- description: `Launch a new agent to handle complex, multi-step tasks autonomously.
137
-
138
- The subagent tool launches specialized agents that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
150
+ promptSnippet: "Launch a specialized agent for complex, multi-step tasks",
151
+ promptGuidelines: tierGuideline ? [...PROMPT_GUIDELINES, tierGuideline] : [...PROMPT_GUIDELINES],
152
+ description: `Launch a subagent that works autonomously on a task.
139
153
 
140
154
  Available agent types:
141
- ${typeListText}
142
-
143
- Guidelines:
144
- - For parallel work, use run_in_background: true on each agent. Foreground calls run sequentially — only one executes at a time.
145
- - Provide clear, detailed prompts so the agent can work autonomously.
146
- - Subagent results are returned as text — summarize them for the user.
147
- - Use run_in_background for work you don't need immediately. You will be notified when it completes.
148
- - Use resume with an agent ID to continue a previous agent's work.
149
- - Use steer_subagent to send mid-run messages to a running background agent.
150
- - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
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.
153
- - Use inherit_context if the agent needs the parent conversation history.
154
- `,
155
+ ${typeListText}`,
155
156
  parameters: Type.Object({
156
157
  prompt: Type.String({
157
158
  description: "The task for the agent to perform.",
@@ -169,8 +170,8 @@ Guidelines:
169
170
  }),
170
171
  ),
171
172
  thinking: Type.Optional(
172
- Type.String({
173
- description: "Thinking level: off, minimal, low, medium, high, xhigh. Overrides agent default.",
173
+ StringEnum(["off", "minimal", "low", "medium", "high", "xhigh"] as const, {
174
+ description: "Thinking level override. Default: inherit the agent type's setting.",
174
175
  }),
175
176
  ),
176
177
  max_turns: Type.Optional(
@@ -90,9 +90,9 @@ export class GetResultTool {
90
90
  return defineTool({
91
91
  name: "get_subagent_result" as const,
92
92
  label: "Get Agent Result",
93
- promptSnippet: "get_subagent_result: Check status and retrieve results from a background agent.",
93
+ promptSnippet: "Check status and retrieve a background subagent's result",
94
94
  description:
95
- "Check status and retrieve results from a background agent. Use the agent ID returned by Agent with run_in_background.",
95
+ "Check status and retrieve the result of a background subagent (agent_id comes from the subagent tool).",
96
96
  parameters: Type.Object({
97
97
  agent_id: Type.String({
98
98
  description: "The agent ID to check.",
@@ -92,7 +92,7 @@ export function buildTypeListText(registry: TypeListRegistry, agentDir: string):
92
92
  ...defaultDescs,
93
93
  ...(customDescs.length > 0 ? ["", "Custom agents:", ...customDescs] : []),
94
94
  "",
95
- `Custom agents can be defined in .pi/agents/<name>.md (project) or ${agentDir}/agents/<name>.md (global) — they are picked up automatically. Project-level agents override global ones. Creating a .md file with the same name as a default agent overrides it.`,
95
+ `Custom agents live in .pi/agents/<name>.md (project) or ${agentDir}/agents/<name>.md (global); a file with a default agent's name overrides it.`,
96
96
  ].join("\n");
97
97
  }
98
98
 
@@ -66,10 +66,8 @@ export class SteerTool {
66
66
  return defineTool({
67
67
  name: "steer_subagent" as const,
68
68
  label: "Steer Agent",
69
- promptSnippet: "steer_subagent: Send a mid-run message to redirect a running background agent.",
70
- description:
71
- "Send a steering message to a running agent. The message will interrupt the agent after its current tool execution " +
72
- "and be injected into its conversation, allowing you to redirect its work mid-run. Only works on running agents.",
69
+ promptSnippet: "Send a mid-run message to redirect a running subagent",
70
+ description: "Send a mid-run steering message to a running subagent.",
73
71
  parameters: Type.Object({
74
72
  agent_id: Type.String({
75
73
  description: "The agent ID to steer (must be currently running).",
@@ -1,59 +0,0 @@
1
- /**
2
- * workspace-bracket.ts — Owned prepare/dispose lifecycle for a child workspace.
3
- *
4
- * Captures the provider resolver (not the provider itself) so provider
5
- * resolution stays lazy at run-start. The prepared Workspace is held
6
- * privately; dispose() centralises the guard and addendum-unwrap so callers
7
- * never reach through to workspace.dispose().resultAddendum directly.
8
- *
9
- * dispose() deliberately does NOT catch errors — the best-effort try/catch
10
- * for failRun() belongs at the call site, preserving the per-caller semantics.
11
- */
12
-
13
- import type {
14
- Workspace,
15
- WorkspaceDisposeOutcome,
16
- WorkspacePrepareContext,
17
- WorkspaceProvider,
18
- } from "../lifecycle/workspace";
19
-
20
- /** Owns the child workspace lifecycle: prepare at run-start, dispose at run-end. */
21
- export class WorkspaceBracket {
22
- private prepared?: Workspace;
23
-
24
- constructor(private readonly resolveProvider: () => WorkspaceProvider | undefined) {}
25
-
26
- /**
27
- * Returns true when a workspace provider is currently registered.
28
- * Use to guard the `await prepare(...)` call and avoid an unnecessary
29
- * microtask boundary in the no-provider path.
30
- */
31
- hasProvider(): boolean {
32
- return this.resolveProvider() !== undefined;
33
- }
34
-
35
- /**
36
- * Resolve the registered provider and prepare the child workspace.
37
- * Returns the workspace's cwd, or undefined when no provider is registered
38
- * or the provider resolves to undefined.
39
- */
40
- async prepare(ctx: WorkspacePrepareContext): Promise<string | undefined> {
41
- const provider = this.resolveProvider();
42
- if (!provider) return undefined;
43
- this.prepared = await provider.prepare(ctx);
44
- return this.prepared?.cwd;
45
- }
46
-
47
- /**
48
- * Dispose the prepared workspace (if any) and return the result addendum
49
- * verbatim. Returns an empty string when no workspace was prepared or when
50
- * the workspace returns no addendum.
51
- *
52
- * Throws propagate — wrap in try/catch at the call site when best-effort
53
- * disposal is desired (e.g. failRun).
54
- */
55
- dispose(outcome: WorkspaceDisposeOutcome): string {
56
- if (!this.prepared) return "";
57
- return this.prepared.dispose(outcome)?.resultAddendum ?? "";
58
- }
59
- }
@@ -1,47 +0,0 @@
1
- /**
2
- * workspace.ts — The single generative extension seam (ADR 0002, Phase 16 Step 2).
3
- *
4
- * "Where does a child run, and what brackets the run?" is a strategy (git
5
- * worktree, container, tmpdir, remote sandbox), not core behavior. The core
6
- * needs only a working directory plus a disposal hook; the default — the
7
- * parent's cwd, with no setup/teardown — is always correct.
8
- *
9
- * Unlike the observational lifecycle events in child-lifecycle.ts, this is a
10
- * *generative* seam: a registered provider returns a value the core consumes
11
- * synchronously at run-start. The core has no knowledge of git or worktrees.
12
- */
13
-
14
- import type { SubagentStatus } from "../lifecycle/subagent";
15
- import type { AgentInvocation, SubagentType } from "../types";
16
-
17
- /** Context the core hands a provider when a child run starts. */
18
- export interface WorkspacePrepareContext {
19
- agentId: string;
20
- agentType: SubagentType;
21
- baseCwd: string;
22
- invocation?: AgentInvocation;
23
- }
24
-
25
- /** Outcome the core reports to a workspace when the run ends. */
26
- export interface WorkspaceDisposeOutcome {
27
- status: SubagentStatus;
28
- description: string;
29
- }
30
-
31
- /** What dispose may hand back for the core to fold into the child result. */
32
- export interface WorkspaceDisposeResult {
33
- /** Appended verbatim to the child's result text — the provider owns the wording. */
34
- resultAddendum?: string;
35
- }
36
-
37
- /** A prepared working directory plus its bracketed teardown. Born complete. */
38
- export interface Workspace {
39
- /** The working directory — already exists when the workspace is handed back. */
40
- readonly cwd: string;
41
- dispose(outcome: WorkspaceDisposeOutcome): WorkspaceDisposeResult | undefined;
42
- }
43
-
44
- /** The single generative seam: supplies a child's workspace. */
45
- export interface WorkspaceProvider {
46
- prepare(ctx: WorkspacePrepareContext): Promise<Workspace | undefined>;
47
- }