@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.
@@ -64,6 +64,8 @@ export interface SubagentExecution {
64
64
  getWorkspaceProvider?: () => WorkspaceProvider | undefined;
65
65
  model?: Model<any>;
66
66
  maxTurns?: number;
67
+ /** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
68
+ timeoutSeconds?: number;
67
69
  thinkingLevel?: ThinkingLevel;
68
70
  parentSession?: ParentSessionInfo;
69
71
  signal?: AbortSignal;
@@ -144,6 +146,10 @@ export class Subagent {
144
146
  return this._promise;
145
147
  }
146
148
 
149
+ // Timeout guard — started at run() after markRunning, cleared on every terminal path.
150
+ private _timeoutHandle: ReturnType<typeof setTimeout> | undefined;
151
+ private _timedOut = false;
152
+
147
153
  private readonly execution: SubagentExecution;
148
154
  private readonly listeners = new RunListeners();
149
155
  private readonly workspaceBracket: WorkspaceBracket;
@@ -256,6 +262,7 @@ export class Subagent {
256
262
  this.markRunning(Date.now());
257
263
  this.execution.observer?.onStarted?.(this);
258
264
  this.listeners.wireSignal(this.execution.signal, () => this.abort());
265
+ this.startTimeoutGuard();
259
266
 
260
267
  // Guard the await so the no-provider path stays synchronous, preserving
261
268
  // the original run() timing: the factory is called in the same turn as
@@ -270,6 +277,7 @@ export class Subagent {
270
277
  invocation: this.invocation,
271
278
  });
272
279
  } catch (err) {
280
+ this.clearTimeoutGuard();
273
281
  this.markError(err);
274
282
  this.listeners.release();
275
283
  this.execution.observer?.onRunFinished?.(this);
@@ -292,6 +300,15 @@ export class Subagent {
292
300
  return;
293
301
  }
294
302
 
303
+ // Timeout fired before the session existed: the controller had no listener
304
+ // (forwardAbortSignal is wired inside runTurnLoop), so nothing was killed.
305
+ // Fail fast instead of running a turn loop the budget already exhausted.
306
+ if (this._timedOut) {
307
+ this.disposeSession();
308
+ this.failRun(new Error(`Timed out after ${this.execution.timeoutSeconds}s before the session started`));
309
+ return;
310
+ }
311
+
295
312
  this.flushPendingSteers();
296
313
  this.listeners.attachObserver(
297
314
  subscribeSubagentObserver(this.subagentSession, this.state, {
@@ -440,11 +457,37 @@ export class Subagent {
440
457
  */
441
458
  abort(): boolean {
442
459
  if (this.status !== "running") return false;
460
+ // A stopped run has no use for a deadline: without this, a timer firing
461
+ // during the abort unwind would stamp a timeout note on a user-stopped run.
462
+ this.clearTimeoutGuard();
443
463
  this.abortController.abort();
444
464
  this.markStopped();
445
465
  return true;
446
466
  }
447
467
 
468
+ /** Start the wall-clock timeout guard (no-op when no timeout is configured). */
469
+ private startTimeoutGuard(): void {
470
+ // Guard on > 0 so an unnormalized 0/negative/NaN can never arm a timer.
471
+ const seconds = Number(this.execution.timeoutSeconds);
472
+ if (!(seconds > 0)) return;
473
+ this._timeoutHandle = setTimeout(() => {
474
+ // Fire the controller without markStopped(): the abort flows through
475
+ // forwardAbortSignal into session.abort(), and the turn loop settles
476
+ // through the aborted path (status "aborted", not "stopped").
477
+ this._timedOut = true;
478
+ this.abortController.abort();
479
+ }, seconds * 1000);
480
+ this._timeoutHandle.unref();
481
+ }
482
+
483
+ /** Clear the timeout guard (idempotent; safe after it already fired). */
484
+ private clearTimeoutGuard(): void {
485
+ if (this._timeoutHandle) {
486
+ clearTimeout(this._timeoutHandle);
487
+ this._timeoutHandle = undefined;
488
+ }
489
+ }
490
+
448
491
  /**
449
492
  * Buffer a steer message for delivery once the session is ready.
450
493
  * Called internally from steer() before the session is ready.
@@ -472,11 +515,17 @@ export class Subagent {
472
515
 
473
516
  /** Complete a run: release listeners, dispose the workspace, status transition, notify observer. */
474
517
  completeRun(result: TurnLoopResult): void {
518
+ this.clearTimeoutGuard();
475
519
  this.listeners.release();
476
520
 
477
521
  const finalStatus: SubagentStatus = result.aborted ? "aborted" : result.steered ? "steered" : "completed";
522
+ const responseText = result.responseText;
523
+ const timeoutNote =
524
+ this._timedOut && finalStatus === "aborted"
525
+ ? `⏱ Timed out after ${this.execution.timeoutSeconds}s — output may be truncated.\n\n`
526
+ : "";
478
527
  const finalResult =
479
- result.responseText + this.workspaceBracket.dispose({ status: finalStatus, description: this.description });
528
+ timeoutNote + responseText + this.workspaceBracket.dispose({ status: finalStatus, description: this.description });
480
529
 
481
530
  if (result.aborted) this.markAborted(finalResult);
482
531
  else if (result.steered) this.markSteered(finalResult);
@@ -492,6 +541,7 @@ export class Subagent {
492
541
 
493
542
  /** Fail a run: mark error, release listeners, best-effort workspace dispose, notify observer. */
494
543
  failRun(err: unknown): void {
544
+ this.clearTimeoutGuard();
495
545
  this.markError(err);
496
546
  this.listeners.release();
497
547
 
@@ -1,7 +1,8 @@
1
1
  /**
2
- * turn-limits.ts — Pure turn-limit normalization for subagent execution.
2
+ * turn-limits.ts — Pure run-limit normalization for subagent execution
3
+ * (max turns and wall-clock timeout).
3
4
  *
4
- * Extracted from agent-runner.ts (issue #265) so the turn-counting policy has a
5
+ * Extracted from agent-runner.ts (issue #265) so the run-limit policy has a
5
6
  * focused home independent of session assembly. Consumed by the subagent tool's
6
7
  * spawn-config resolution and by the turn loop in SubagentSession.
7
8
  */
@@ -11,3 +12,9 @@ export function normalizeMaxTurns(n: number | undefined): number | undefined {
11
12
  if (n == null || n === 0) return undefined;
12
13
  return Math.max(1, n);
13
14
  }
15
+
16
+ /** Normalize a wall-clock timeout in seconds. undefined or 0 = unlimited, otherwise minimum 1. Non-finite → unlimited. */
17
+ export function normalizeTimeoutSeconds(s: number | undefined): number | undefined {
18
+ if (s == null || !Number.isFinite(s) || s === 0) return undefined;
19
+ return Math.max(1, s);
20
+ }
@@ -32,7 +32,7 @@ export function getStatusLabel(status: string, error?: string): string {
32
32
  case "error":
33
33
  return `Error: ${error ?? "unknown"}`;
34
34
  case "aborted":
35
- return "Aborted (max turns exceeded)";
35
+ return "Aborted (hard limit exceeded)";
36
36
  case "steered":
37
37
  return "Wrapped up (turn limit)";
38
38
  case "stopped":
@@ -9,6 +9,7 @@ import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
9
9
  import type { WorkspaceProvider } from "../lifecycle/workspace";
10
10
  import type { SpawnOptions, SubagentRecord, SubagentsService } from "../service/service";
11
11
  import type { ModelRegistry } from "../session/model-resolver";
12
+ import { normalizeTimeoutSeconds } from "../lifecycle/turn-limits";
12
13
  import { resolveModelName } from "../tools/spawn-config";
13
14
  import type { SessionContext, Subagent, ThinkingLevel, AgentInvocation } from "../types";
14
15
 
@@ -76,6 +77,9 @@ export class SubagentsServiceAdapter implements SubagentsService {
76
77
  description,
77
78
  model,
78
79
  maxTurns: options?.maxTurns,
80
+ // Normalize at the boundary: the documented 0/undefined = unlimited contract
81
+ // must hold for cross-extension callers that skip the tool path.
82
+ timeoutSeconds: normalizeTimeoutSeconds(options?.timeoutSeconds),
79
83
  thinkingLevel: options?.thinkingLevel,
80
84
  inheritContext: options?.inheritContext,
81
85
  bypassQueue: options?.bypassQueue,
@@ -57,6 +57,8 @@ export interface SpawnOptions {
57
57
  description?: string;
58
58
  model?: string;
59
59
  maxTurns?: number;
60
+ /** Hard wall-clock timeout in seconds (0/undefined = unlimited). Normalize before passing, or pass an already-normalized value. */
61
+ timeoutSeconds?: number;
60
62
  thinkingLevel?: string;
61
63
  inheritContext?: boolean;
62
64
  foreground?: boolean;
@@ -1,50 +1,65 @@
1
1
  /**
2
- * prompts.ts — System prompt builder for agents.
2
+ * prompts.ts — System prompt assembly for agents.
3
+ *
4
+ * Two shapes, one per `prompt_mode`:
5
+ *
6
+ * - "append": the harness renders the base system prompt for the child's OWN
7
+ * tool set (tool list, guidelines, skills, AGENTS.md, SYSTEM.md, date/cwd)
8
+ * and this module only contributes a section appended to it.
9
+ * - "replace": this module owns the whole prompt. The caller's rendered prompt
10
+ * is deliberately NOT reused — it carries the caller's tool list and
11
+ * guidelines, its cwd/date, and project context the child suppresses.
12
+ *
13
+ * Both shapes emit an `<active_agent name="..."/>` tag so downstream extensions
14
+ * can resolve per-agent policy by parsing the child's system prompt.
3
15
  */
4
16
 
5
17
  import type { EnvInfo } from "../session/env";
6
18
  import type { AgentPromptConfig } from "../types";
7
19
 
8
20
  /**
9
- * Build the system prompt for an agent from its config.
10
- *
11
- * Both modes place the shared/stable parent prompt (or `genericBase` when no
12
- * parent is available) first so the LLM's KV cache can reuse the inherited
13
- * prefix across all subagent invocations.
14
- *
15
- * - "replace" mode: parent/genericBase + active_agent tag + env header +
16
- * config.systemPrompt. No `<sub_agent_context>` bridge and no
17
- * `<agent_instructions>` wrapper — the custom prompt has full control and
18
- * the final say.
19
- * - "append" mode: parent/genericBase + sub-agent context bridge +
20
- * active_agent tag + env header + config.systemPrompt (wrapped in
21
- * `<agent_instructions>` when non-empty).
22
- * - "append" with empty systemPrompt: pure parent clone.
23
- *
24
- * Both modes include an `<active_agent name="${config.name}"/>` tag so
25
- * downstream extensions can resolve per-agent policy inside the child session
26
- * by parsing the system prompt.
27
- * The tag follows the cacheable parent prefix in both modes.
28
- *
29
- * @param parentSystemPrompt The parent agent's effective system prompt.
21
+ * Fallback prompt for a replace agent whose body is empty — nothing else uses
22
+ * it. It asserts no role and no capability: in replace mode the body IS the
23
+ * spec, and a generic persona prepended to it would mislabel read-only or
24
+ * non-coding agents (and is the only capability text the model would see, since
25
+ * replace mode renders no tool list). Only the `tools` allowlist grants abilities.
30
26
  */
31
- export function buildAgentPrompt(
32
- config: AgentPromptConfig,
33
- cwd: string,
34
- env: EnvInfo,
35
- parentSystemPrompt?: string,
36
- ): string {
37
- const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
27
+ const emptyBodyFallback = `# Role
28
+ Your role is defined by the instructions below.
29
+ Your available tools are the ones exposed to you in this session; respect any restrictions stated below.
30
+ Do what has been asked; nothing more, nothing less.`;
38
31
 
39
- const envBlock = `# Environment
40
- Working directory: ${cwd}
32
+ /** Environment header shared by both modes. cwd and date are rendered by the harness. */
33
+ function environmentBlock(env: EnvInfo): string {
34
+ return `# Environment
41
35
  ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
42
36
  Platform: ${env.platform}`;
37
+ }
43
38
 
44
- const identity = parentSystemPrompt ?? genericBase;
39
+ /**
40
+ * Build the complete system prompt for a "replace" agent:
41
+ * active_agent tag → env header → the agent body verbatim.
42
+ *
43
+ * Only an empty body gets `emptyBodyFallback` in front of it; a non-empty body is the
44
+ * agent's whole spec, so nothing generic is prepended. No `<sub_agent_context>`
45
+ * bridge and no `<agent_instructions>` wrapper either: this is not an addendum
46
+ * to someone else's prompt.
47
+ */
48
+ export function buildReplacePrompt(config: AgentPromptConfig, env: EnvInfo): string {
49
+ const identity = config.systemPrompt.trim() ? "" : `${emptyBodyFallback}\n\n`;
50
+ return `${identity}<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}\n\n${config.systemPrompt}`;
51
+ }
45
52
 
46
- if (config.promptMode === "append") {
47
- const bridge = `<sub_agent_context>
53
+ /**
54
+ * Build the section appended to the harness-rendered base prompt for an
55
+ * "append" agent: sub-agent bridge → active_agent tag → env header → the agent
56
+ * body wrapped in `<agent_instructions>` (omitted when the body is empty).
57
+ *
58
+ * Carries no leading separator: the harness joins it onto the base prompt with
59
+ * its own blank line, so adding one here would stack into extra empty lines.
60
+ */
61
+ export function buildAppendSection(config: AgentPromptConfig, env: EnvInfo): string {
62
+ const bridge = `<sub_agent_context>
48
63
  You are operating as a sub-agent invoked to handle a specific task.
49
64
  - Make independent tool calls in parallel
50
65
  - Use absolute file paths
@@ -52,27 +67,9 @@ You are operating as a sub-agent invoked to handle a specific task.
52
67
  - Be concise but complete
53
68
  </sub_agent_context>`;
54
69
 
55
- const customSection = config.systemPrompt.trim()
56
- ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
57
- : "";
58
-
59
- // Place shared/stable content first so the LLM's KV cache can reuse the
60
- // inherited prefix across all subagent invocations. The parent prompt is
61
- // placed verbatim (no wrapper tag) so it forms an identical byte prefix
62
- // with the parent session, maximising KV cache hits. The <active_agent>
63
- // tag and env block vary per call and are placed after the cached prefix.
64
- return `${identity}\n\n${bridge}\n\n${activeAgentTag}${envBlock}${customSection}`;
65
- }
70
+ const customSection = config.systemPrompt.trim()
71
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
72
+ : "";
66
73
 
67
- // "replace" mode — parent/genericBase prefix first for KV cache reuse, then
68
- // the active_agent tag, env block, and the config's full system prompt.
69
- // Unlike append mode, no <sub_agent_context> bridge or <agent_instructions>
70
- // wrapper is injected — the custom prompt retains full control.
71
- return `${identity}\n\n${activeAgentTag}${envBlock}\n\n${config.systemPrompt}`;
74
+ return `${bridge}\n\n<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}${customSection}`;
72
75
  }
73
-
74
- /** Fallback base prompt when parent system prompt is unavailable (both modes). */
75
- const genericBase = `# Role
76
- You are a general-purpose coding agent for complex, multi-step tasks.
77
- You have full access to read, write, edit files, and execute commands.
78
- Do what has been asked; nothing more, nothing less.`;
@@ -25,7 +25,8 @@ import type { AgentPromptConfig, SubagentType, ThinkingLevel } from "../types";
25
25
  * at the edge (`create-subagent-session.ts`) or stubs in tests.
26
26
  */
27
27
  export interface AssemblerIO {
28
- buildAgentPrompt: (config: AgentPromptConfig, cwd: string, env: EnvInfo, parentPrompt?: string) => string;
28
+ buildReplacePrompt: (config: AgentPromptConfig, env: EnvInfo) => string;
29
+ buildAppendSection: (config: AgentPromptConfig, env: EnvInfo) => string;
29
30
  }
30
31
 
31
32
  /**
@@ -40,8 +41,6 @@ export interface AssemblerIO {
40
41
  export interface AssemblerContext {
41
42
  /** Parent working directory (overridable via options.cwd). */
42
43
  cwd: string;
43
- /** Parent's effective system prompt (for append-mode agents). */
44
- parentSystemPrompt: string;
45
44
  /** Parent's current model instance (fallback when agent config has no model). */
46
45
  parentModel?: unknown;
47
46
  /** Model registry for resolving config.model strings. */
@@ -72,8 +71,10 @@ export interface AssemblerOptions {
72
71
  export interface SessionConfig {
73
72
  /** Resolved working directory (`options.cwd ?? ctx.cwd`). */
74
73
  effectiveCwd: string;
75
- /** Fully-assembled system prompt string (ready for `systemPromptOverride`). */
76
- systemPrompt: string;
74
+ /** Prompt mode declared by the agent; decides how the caller wires the resource loader. */
75
+ promptMode: "replace" | "append";
76
+ /** Mode-specific text: the complete system prompt for "replace", the appended section for "append". */
77
+ promptSection: string;
77
78
  /** Built-in tool name allowlist for this agent type. */
78
79
  toolNames: string[];
79
80
  /**
@@ -149,8 +150,12 @@ export function assembleSessionConfig(
149
150
 
150
151
  const toolNames = registry.getToolNamesForType(type);
151
152
 
152
- // Build system prompt from the resolved agent config
153
- const systemPrompt = io.buildAgentPrompt(agentConfig, effectiveCwd, env, ctx.parentSystemPrompt);
153
+ // Assemble the prompt text: "replace" owns the whole prompt, "append" only
154
+ // contributes a section on top of the harness-rendered base prompt.
155
+ const promptSection =
156
+ agentConfig.promptMode === "replace"
157
+ ? io.buildReplacePrompt(agentConfig, env)
158
+ : io.buildAppendSection(agentConfig, env);
154
159
 
155
160
  // Model resolution: explicit option > config model string > parent model
156
161
  const model = options.model ?? resolveDefaultModel(ctx.parentModel, ctx.modelRegistry, agentConfig.model);
@@ -163,7 +168,8 @@ export function assembleSessionConfig(
163
168
 
164
169
  return {
165
170
  effectiveCwd,
166
- systemPrompt,
171
+ promptMode: agentConfig.promptMode,
172
+ promptSection,
167
173
  toolNames,
168
174
  model,
169
175
  thinkingLevel,
package/src/settings.ts CHANGED
@@ -14,12 +14,15 @@ export interface SubagentsSettings {
14
14
  * `/agents` → Settings input prompt explicitly says "0 = unlimited".
15
15
  */
16
16
  defaultMaxTurns?: number;
17
+ /** Default wall-clock timeout in seconds for spawned agents. 0 = unlimited. */
18
+ defaultTimeoutSeconds?: number;
17
19
  graceTurns?: number;
18
20
  /**
19
- * Capability/cost tier → real model mapping for the `subagent` tool's
20
- * `model_tier` param. Tier names are fixed (`fast` | `standard` | `advanced`);
21
- * values accept anything `resolveModel` understands (e.g. "provider/modelId"
22
- * or a fuzzy name like "haiku").
21
+ * Capability/cost tier → real model mapping. Used only to generate the
22
+ * `subagent` tool's prompt guidelines, which tell the agent which model to
23
+ * pass via `model` for each capability level. Tier names are fixed
24
+ * (`fast` | `standard` | `advanced`); values accept anything `resolveModel`
25
+ * understands (e.g. "provider/modelId" or a fuzzy name like "haiku").
23
26
  */
24
27
  modelTiers?: ModelTierMap;
25
28
  }
@@ -36,6 +39,7 @@ const DEFAULT_GRACE_TURNS = 5;
36
39
  */
37
40
  export class SettingsManager {
38
41
  private _defaultMaxTurns: number | undefined = undefined;
42
+ private _defaultTimeoutSeconds: number | undefined = undefined;
39
43
  private _graceTurns: number = DEFAULT_GRACE_TURNS;
40
44
  private _maxConcurrent: number = DEFAULT_MAX_CONCURRENT;
41
45
  private _modelTiers: ModelTierMap = {};
@@ -66,6 +70,20 @@ export class SettingsManager {
66
70
  }
67
71
  }
68
72
 
73
+ // ── defaultTimeoutSeconds: 0 or undefined → unlimited (undefined); else max(1, n) ──
74
+
75
+ get defaultTimeoutSeconds(): number | undefined {
76
+ return this._defaultTimeoutSeconds;
77
+ }
78
+
79
+ set defaultTimeoutSeconds(n: number | undefined) {
80
+ if (n == null || n === 0) {
81
+ this._defaultTimeoutSeconds = undefined;
82
+ } else {
83
+ this._defaultTimeoutSeconds = Math.max(1, n);
84
+ }
85
+ }
86
+
69
87
  // ── graceTurns: minimum 1 ──
70
88
 
71
89
  get graceTurns(): number {
@@ -86,7 +104,7 @@ export class SettingsManager {
86
104
  this._maxConcurrent = Math.max(1, n);
87
105
  }
88
106
 
89
- // ── modelTiers: tier → model map for the subagent tool's model_tier param ──
107
+ // ── modelTiers: tier → model map used to generate the subagent prompt guidelines ──
90
108
 
91
109
  get modelTiers(): ModelTierMap {
92
110
  return this._modelTiers;
@@ -103,6 +121,9 @@ export class SettingsManager {
103
121
  const settings = loadSettings(this.agentDir, this.cwd);
104
122
  if (typeof settings.maxConcurrent === "number") this.maxConcurrent = settings.maxConcurrent;
105
123
  if (typeof settings.defaultMaxTurns === "number") this.defaultMaxTurns = settings.defaultMaxTurns;
124
+ if (typeof settings.defaultTimeoutSeconds === "number") {
125
+ this.defaultTimeoutSeconds = settings.defaultTimeoutSeconds;
126
+ }
106
127
  if (typeof settings.graceTurns === "number") this.graceTurns = settings.graceTurns;
107
128
  this._modelTiers = settings.modelTiers ? { ...settings.modelTiers } : {};
108
129
  this.emit("subagents:settings_loaded", { settings });
@@ -115,10 +136,17 @@ export class SettingsManager {
115
136
  * `modelTiers` is omitted when empty so hand-edited tier maps are only
116
137
  * rewritten (not replaced with an empty object) when they exist.
117
138
  */
118
- snapshot(): { maxConcurrent: number; defaultMaxTurns: number; graceTurns: number; modelTiers?: ModelTierMap } {
139
+ snapshot(): {
140
+ maxConcurrent: number;
141
+ defaultMaxTurns: number;
142
+ defaultTimeoutSeconds: number;
143
+ graceTurns: number;
144
+ modelTiers?: ModelTierMap;
145
+ } {
119
146
  return {
120
147
  maxConcurrent: this._maxConcurrent,
121
148
  defaultMaxTurns: this._defaultMaxTurns ?? 0,
149
+ defaultTimeoutSeconds: this._defaultTimeoutSeconds ?? 0,
122
150
  graceTurns: this._graceTurns,
123
151
  ...(Object.keys(this._modelTiers).length > 0 ? { modelTiers: { ...this._modelTiers } } : {}),
124
152
  };
@@ -144,6 +172,16 @@ export class SettingsManager {
144
172
  return this.saveAndNotify(`Default max turns set to ${label}`);
145
173
  }
146
174
 
175
+ /**
176
+ * Set defaultTimeoutSeconds, persist, and return the toast.
177
+ * Pass 0 for unlimited (maps to undefined internally).
178
+ */
179
+ applyDefaultTimeoutSeconds(n: number): { message: string; level: "info" | "warning" } {
180
+ this.defaultTimeoutSeconds = n === 0 ? undefined : n; // setter normalizes further
181
+ const label = this.defaultTimeoutSeconds == null ? "unlimited" : `${this.defaultTimeoutSeconds}s`;
182
+ return this.saveAndNotify(`Default timeout set to ${label}`);
183
+ }
184
+
147
185
  /**
148
186
  * Set graceTurns, persist, and return the toast.
149
187
  */
@@ -169,6 +207,7 @@ export class SettingsManager {
169
207
  // that any realistic power-user setting passes through.
170
208
  const MAX_CONCURRENT_CEILING = 1024;
171
209
  const MAX_TURNS_CEILING = 10_000;
210
+ const MAX_TIMEOUT_SECONDS_CEILING = 86_400;
172
211
  const GRACE_TURNS_CEILING = 1_000;
173
212
 
174
213
  /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
@@ -190,6 +229,13 @@ function sanitize(raw: unknown): SubagentsSettings {
190
229
  ) {
191
230
  out.defaultMaxTurns = r.defaultMaxTurns as number;
192
231
  }
232
+ if (
233
+ Number.isInteger(r.defaultTimeoutSeconds) &&
234
+ (r.defaultTimeoutSeconds as number) >= 0 &&
235
+ (r.defaultTimeoutSeconds as number) <= MAX_TIMEOUT_SECONDS_CEILING
236
+ ) {
237
+ out.defaultTimeoutSeconds = r.defaultTimeoutSeconds as number;
238
+ }
193
239
  if (
194
240
  Number.isInteger(r.graceTurns) &&
195
241
  (r.graceTurns as number) >= 1 &&
@@ -4,7 +4,7 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
5
  import { Type } from "typebox";
6
6
  import type { AgentTypeRegistry } from "../config/agent-types";
7
- import { MODEL_TIERS, type ModelTierMap } from "../config/model-tiers";
7
+ import { MODEL_TIERS, MODEL_TIER_INTENTS, type ModelTierMap } from "../config/model-tiers";
8
8
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
9
9
  import type { AgentSpawnConfig } from "../lifecycle/subagent-manager";
10
10
  import { spawnBackground } from "../tools/background-spawner";
@@ -40,14 +40,18 @@ export interface AgentToolRuntime {
40
40
  /** Narrow settings accessor — only the fields the Agent tool reads. */
41
41
  export type AgentToolSettings = {
42
42
  readonly defaultMaxTurns: number | undefined;
43
+ readonly defaultTimeoutSeconds: number | undefined;
43
44
  readonly maxConcurrent: number;
44
45
  readonly modelTiers?: ModelTierMap;
45
46
  };
46
47
 
47
- /** LLM-facing summary of which tiers are configured, e.g. `fast → deepseek-flash`. */
48
- function buildTierListText(tiers: ModelTierMap | undefined): string {
49
- const configured = MODEL_TIERS.filter((tier) => tiers?.[tier]).map((tier) => `${tier} → ${tiers?.[tier]}`);
50
- return configured.length > 0 ? configured.join(", ") : "none configured";
48
+ /** LLM-facing guidance to map a capability tier to the model to pass via the `model` parameter, or undefined when none configured. */
49
+ function buildTierGuideline(tiers: ModelTierMap | undefined): string | undefined {
50
+ const configured = MODEL_TIERS.filter((tier) => tiers?.[tier]).map(
51
+ (tier) => `${tier} → ${tiers?.[tier]} (${MODEL_TIER_INTENTS[tier]})`,
52
+ );
53
+ if (configured.length === 0) return undefined;
54
+ 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(", ")}.`;
51
55
  }
52
56
 
53
57
  // ---- Class ----
@@ -121,13 +125,14 @@ export class AgentTool {
121
125
  toToolDefinition() {
122
126
  const typeListText = this.typeListText;
123
127
  const availableTypesText = this.availableTypesText;
124
- const tierListText = buildTierListText(this.settings.modelTiers);
128
+ const tierGuideline = buildTierGuideline(this.settings.modelTiers);
125
129
  const registry = this.registry;
126
130
 
127
131
  return defineTool({
128
132
  name: "subagent" as const,
129
133
  label: "Subagent",
130
134
  promptSnippet: "subagent: Launch a specialized agent for complex, multi-step tasks.",
135
+ ...(tierGuideline ? { promptGuidelines: [tierGuideline] } : {}),
131
136
  description: `Launch a new agent to handle complex, multi-step tasks autonomously.
132
137
 
133
138
  The subagent tool launches specialized agents that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
@@ -143,8 +148,8 @@ Guidelines:
143
148
  - Use resume with an agent ID to continue a previous agent's work.
144
149
  - Use steer_subagent to send mid-run messages to a running background agent.
145
150
  - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
146
- - Use model_tier to pick a preconfigured capability tier instead of naming a model — never pass both. Tiers: fast (cheapest, fastest, least capable), standard (balanced default), advanced (most capable, most expensive). Configured: ${tierListText}.
147
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.
148
153
  - Use inherit_context if the agent needs the parent conversation history.
149
154
  `,
150
155
  parameters: Type.Object({
@@ -160,13 +165,7 @@ Guidelines:
160
165
  model: Type.Optional(
161
166
  Type.String({
162
167
  description:
163
- 'Optional model override. Accepts "provider/modelId" or fuzzy name (e.g. "haiku", "sonnet"). Omit to use the agent type\'s default. Mutually exclusive with model_tier.',
164
- }),
165
- ),
166
- model_tier: Type.Optional(
167
- Type.Union([Type.Literal("fast"), Type.Literal("standard"), Type.Literal("advanced")], {
168
- description:
169
- 'Optional capability tier: "fast" (cheapest and fastest, least capable), "standard" (balanced default), or "advanced" (most capable, most expensive). Mutually exclusive with model. The real model behind each tier is configured in subagents.json (modelTiers).',
168
+ 'Optional model override. Accepts "provider/modelId" or fuzzy name (e.g. "haiku", "sonnet"). Omit to use the agent type\'s default.',
170
169
  }),
171
170
  ),
172
171
  thinking: Type.Optional(
@@ -180,6 +179,13 @@ Guidelines:
180
179
  minimum: 1,
181
180
  }),
182
181
  ),
182
+ timeout: Type.Optional(
183
+ Type.Number({
184
+ description:
185
+ "Hard wall-clock limit in seconds. When exceeded, the agent is terminated immediately and only partial output is returned. Use as a safety net for tasks that could run away (long builds, hanging commands); omit for unlimited.",
186
+ minimum: 1,
187
+ }),
188
+ ),
183
189
  run_in_background: Type.Optional(
184
190
  Type.Boolean({
185
191
  description:
@@ -32,6 +32,7 @@ export function spawnBackground(manager: BackgroundManagerDeps, params: Backgrou
32
32
  description: execution.description,
33
33
  model: execution.model,
34
34
  maxTurns: execution.effectiveMaxTurns,
35
+ timeoutSeconds: execution.effectiveTimeoutSeconds,
35
36
  inheritContext: execution.inheritContext,
36
37
  thinkingLevel: execution.thinking,
37
38
  isBackground: true,
@@ -74,6 +74,7 @@ export async function runForeground(
74
74
  description: execution.description,
75
75
  model: execution.model,
76
76
  maxTurns: execution.effectiveMaxTurns,
77
+ timeoutSeconds: execution.effectiveTimeoutSeconds,
77
78
  inheritContext: execution.inheritContext,
78
79
  thinkingLevel: execution.thinking,
79
80
  invocation: execution.agentInvocation,
@@ -6,7 +6,7 @@ import { type AgentDetails, formatTokens } from "../ui/display";
6
6
  export function getStatusNote(status: string): string {
7
7
  switch (status) {
8
8
  case "aborted":
9
- return " (aborted \u2014 max turns exceeded, output may be incomplete)";
9
+ return " (aborted \u2014 hard limit exceeded, output may be incomplete)";
10
10
  case "steered":
11
11
  return " (wrapped up \u2014 reached turn limit)";
12
12
  case "stopped":
@@ -85,7 +85,7 @@ export function renderFailed(details: AgentDetails, theme: Theme): string {
85
85
  if (details.status === "error") {
86
86
  line += `\n${theme.fg("error", ` \u23BF Error: ${details.error ?? "unknown"}`)}`;
87
87
  } else {
88
- line += `\n${theme.fg("warning", " \u23BF Aborted (max turns exceeded)")}`;
88
+ line += `\n${theme.fg("warning", " \u23BF Aborted (hard limit exceeded)")}`;
89
89
  }
90
90
  return line;
91
91
  }