@henryqw/pi-subagent 7.0.0 → 8.0.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/CONTEXT.md CHANGED
@@ -24,7 +24,7 @@ Provide validated built-in and user Roles, shared task-model Pi launch policy, g
24
24
 
25
25
  ## Invariants
26
26
 
27
- - One Delegated Task creates one ephemeral child process and no saved session. Timeout behavior: `deadline = min(last recognized Pi JSON event + idle timeout, child start + maximum runtime)` (recognized Pi events renew; raw bytes do not; max always terminates). After direct Pi exits, inherited stdout/stderr drain until EOF unless an escaped descendant holds them past short inactivity or a one-second hard deadline. Configurable via the `timeout` object in `~/.pi/agent/config/pi-subagent/pi-subagent.json` (`idleMinutes`, `maxMinutes`; defaults 10/30).
27
+ - One Delegated Task creates one ephemeral child process and no saved session. Execution ends at the first hard budget: attempted turn 51 by default (`maxTurns`, positive safe integer) or `deadline = min(last recognized Pi JSON event + idle timeout, child start + maximum runtime)` (recognized Pi events renew; raw bytes do not; max always terminates). A terminal turn 50 succeeds; attempted continuation rejects with `turn_limit`, accumulated usage, and bounded output. On continuing `turn_end`, the existing child Role tool extension steers the fixed convergence warning once at 80% of completed turns and once at 80% of maximum runtime, combining thresholds first due together and never starting a warning timer or extra turn. After direct Pi exits, inherited stdout/stderr drain until EOF unless an escaped descendant holds them past short inactivity or a one-second hard deadline. Configurable in `~/.pi/agent/config/pi-subagent/pi-subagent.json` (`maxTurns` default 50; `timeout.idleMinutes`/`maxMinutes` defaults 10/30).
28
28
  - Up to five active ephemeral `delegate_task` children run per Main by default, configurable via `maxSubagents` in `~/.pi/agent/config/pi-subagent/pi-subagent.json` or the `PI_SUBAGENT_MAX_SUBAGENTS` environment variable; excess calls wait FIFO. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
29
29
  - Ambient child extensions and Skills stay disabled. Every Role requires `tools`, `extensions`, and `skills` YAML arrays, and every launch installs the Role tool policy. `tools: []` activates no base built-ins but does activate all tools from explicitly selected trusted extension bundles and explicit caller tool additions; `skills: []` selects no separately named Role Skills but trusted selected extension Skills still load; `extensions: []` selects no Role extension bundle. A Role/caller explicitly selected extension is a trusted atomic capability bundle: all tools it registers and all Skills supplied through its Pi package metadata or dynamic `resources_discover` load alongside separately named Role Skills. This intentionally includes the extension's executable lifecycle/prompt behavior; pi-subagent does not infer or externally narrow undocumented dependencies, and loading an extension is not sandboxing. Scope children by selecting fewer trusted extensions; finer granularity requires separate entry points/configuration or an upstream split. Explicit Role/caller tool names still verify against the final filtered registry, while parent-only recursive orchestration tools remain excluded.
30
30
  - Role Skill names resolve through Main's effective Pi Skill registry; unavailable names warn and skip without blocking delegation. Explicit Role/caller tool names verify against the final filtered child registry after explicit provider `session_start` handlers, and unavailable names fail before the first turn.
package/README.md CHANGED
@@ -92,15 +92,16 @@ A rebase that drops all unit commits is a no-op: Flow validates it, skips Review
92
92
 
93
93
  pi-subagent owns the extension-named config directory `~/.pi/agent/config/pi-subagent/`, which holds two kinds of user-owned configuration: one Markdown file per Role (see [Roles](#roles)) and its own optional JSON file below. Model routing is *not* configured here; children resolve routes through the shared `@henryqw/pi-task-models` config at `~/.pi/agent/config/pi-task-models.json`, which stores only explicit task overrides. The local `pi-subagent/delegateTask` declaration supplies the omitted-class default.
94
94
 
95
- `~/.pi/agent/config/pi-subagent/pi-subagent.json` controls the ephemeral child pool and timeouts. All fields are optional; a missing file uses defaults.
95
+ `~/.pi/agent/config/pi-subagent/pi-subagent.json` controls the ephemeral child pool and execution budgets. All fields are optional; a missing file uses defaults.
96
96
 
97
97
  | Field | Required | Possible values | Default |
98
98
  | --- | --- | --- | --- |
99
99
  | `maxSubagents` | No | Safe integer ≥ 1 | `5` |
100
+ | `maxTurns` | No | Safe integer ≥ 1 | `50` |
100
101
  | `timeout.idleMinutes` | No | Positive number of minutes where minutes × 60 000 ms ≤ 2,147,483,647 | `10` |
101
102
  | `timeout.maxMinutes` | No | Positive number within the same ms cap that must be greater than `timeout.idleMinutes`, otherwise the whole `timeout` object falls back to defaults | `30` |
102
103
 
103
- Excess children wait FIFO without consuming child timeout. `PI_SUBAGENT_MAX_SUBAGENTS` overrides `maxSubagents` for the session (positive integer; an invalid value prevents the extension from loading, leaving `delegate_task` unavailable).
104
+ Excess children wait FIFO without consuming child timeout. A terminal response on turn 50 succeeds; an attempted continuation starts no model work and rejects with `turn_limit`. Before a continuing turn, the child receives the execution-budget warning once when completed turns reach 80% and once when elapsed time reaches 80% of the maximum runtime; thresholds first reached together produce one combined warning. `PI_SUBAGENT_MAX_SUBAGENTS` overrides `maxSubagents` for the session (positive integer; an invalid value prevents the extension from loading, leaving `delegate_task` unavailable).
104
105
 
105
106
  This JSON is read leniently: malformed JSON, a non-object root, unknown keys, or invalid values are collected into one warning and the affected settings fall back to defaults; the file is never rewritten.
106
107
 
@@ -153,6 +154,6 @@ A Role explicitly owns base tools, extensions, named Skills, instructions, and o
153
154
 
154
155
  ## Library API
155
156
 
156
- The package root exports Role loading and launch resolution, `createEphemeralSubagentExecutor`, worktree helpers, and generic managed Herdr lifecycle helpers. The ephemeral executor is for code already running inside active Pi; it does not provide standalone Node.js Pi discovery or launch support. After Pi itself exits, it drains inherited stdout/stderr normally but destroys streams still held by escaped descendants after a short inactivity deadline or one-second hard deadline, so they cannot retain a pool permit.
157
+ The package root exports Role loading and launch resolution, `createEphemeralSubagentExecutor`, worktree helpers, and generic managed Herdr lifecycle helpers. The ephemeral executor is for code already running inside active Pi; it does not provide standalone Node.js Pi discovery or launch support. It defaults to a 50-turn hard cap and rejects attempted continuation with `turn_limit` while preserving accumulated usage and bounded output. After Pi itself exits, it drains inherited stdout/stderr normally but destroys streams still held by escaped descendants after a short inactivity deadline or one-second hard deadline, so they cannot retain a pool permit.
157
158
 
158
159
  Use [`docs/orchestration.md`](./docs/orchestration.md#public-role-and-executor-api) for exact API behavior and a post-permit `prepare` example using `resolveRoleLaunch` with a caller-owned Model Task declaration against the latest Pi context.
@@ -1,11 +1,14 @@
1
1
  import type { Usage } from "@earendil-works/pi-ai";
2
2
  import type { PiLaunch } from "./index.ts";
3
+ export declare const DEFAULT_MAX_TURNS = 50;
4
+ export declare const EXECUTION_BUDGET_ENV = "PI_SUBAGENT_EXECUTION_BUDGET";
3
5
  export interface EphemeralSubagentTimeout {
4
6
  idleMs: number;
5
7
  maxMs: number;
6
8
  }
7
9
  export interface EphemeralSubagentExecutorOptions {
8
10
  maxConcurrency: number;
11
+ maxTurns?: number;
9
12
  timeout: EphemeralSubagentTimeout;
10
13
  }
11
14
  export type EphemeralSubagentActivityEvent = {
@@ -44,12 +47,13 @@ export type EphemeralSubagentResult = (EphemeralSubagentResultBase & {
44
47
  }) | (EphemeralSubagentResultBase & {
45
48
  outcome: "failure";
46
49
  });
47
- export type EphemeralSubagentErrorCode = "aborted" | "timeout" | "spawn" | "protocol" | "prepare" | "callback";
50
+ export type EphemeralSubagentErrorCode = "aborted" | "timeout" | "turn_limit" | "spawn" | "protocol" | "prepare" | "callback";
48
51
  export declare class EphemeralSubagentError extends Error {
49
52
  name: string;
50
53
  readonly code: EphemeralSubagentErrorCode;
51
54
  readonly usage?: Usage;
52
- constructor(code: EphemeralSubagentErrorCode, message: string, cause?: unknown, usage?: Usage);
55
+ readonly output?: string;
56
+ constructor(code: EphemeralSubagentErrorCode, message: string, cause?: unknown, usage?: Usage, output?: string);
53
57
  }
54
58
  export interface EphemeralSubagentExecutor {
55
59
  run(input: EphemeralSubagentRunInput): Promise<EphemeralSubagentResult>;
package/dist/ephemeral.js CHANGED
@@ -4,6 +4,8 @@ import { basename } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  const MAX_OUTPUT_BYTES = 50 * 1024;
6
6
  const MAX_JSON_EVENT_BYTES = 1024 * 1024;
7
+ export const DEFAULT_MAX_TURNS = 50;
8
+ export const EXECUTION_BUDGET_ENV = "PI_SUBAGENT_EXECUTION_BUDGET";
7
9
  const MAX_ACTIVITY_TEXT_BYTES = 4 * 1024;
8
10
  // A JSON string byte can take six source bytes (for example, \u0000).
9
11
  const MAX_ACTIVITY_PREFIX_BYTES = 2 * MAX_ACTIVITY_TEXT_BYTES * 6 + 1024;
@@ -43,10 +45,12 @@ export class EphemeralSubagentError extends Error {
43
45
  name = "EphemeralSubagentError";
44
46
  code;
45
47
  usage;
46
- constructor(code, message, cause, usage) {
48
+ output;
49
+ constructor(code, message, cause, usage, output) {
47
50
  super(message, cause === undefined ? undefined : { cause });
48
51
  this.code = code;
49
52
  this.usage = usage;
53
+ this.output = output;
50
54
  }
51
55
  }
52
56
  function positiveDelay(value, field) {
@@ -61,6 +65,9 @@ function validateOptions(options) {
61
65
  if (!Number.isSafeInteger(options.maxConcurrency) || options.maxConcurrency < 1) {
62
66
  throw new RangeError("maxConcurrency must be a positive safe integer.");
63
67
  }
68
+ const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
69
+ if (!Number.isSafeInteger(maxTurns) || maxTurns < 1)
70
+ throw new RangeError("maxTurns must be a positive safe integer.");
64
71
  if (!options.timeout || typeof options.timeout !== "object")
65
72
  throw new TypeError("timeout is required.");
66
73
  const timeout = {
@@ -69,7 +76,7 @@ function validateOptions(options) {
69
76
  };
70
77
  if (timeout.maxMs <= timeout.idleMs)
71
78
  throw new RangeError("timeout.maxMs must be greater than timeout.idleMs.");
72
- return { maxConcurrency: options.maxConcurrency, timeout };
79
+ return { maxConcurrency: options.maxConcurrency, maxTurns, timeout };
73
80
  }
74
81
  function abortError(signal, cause = signal?.reason, usage) {
75
82
  return new EphemeralSubagentError("aborted", "Subagent was aborted.", cause, usage);
@@ -202,7 +209,7 @@ export function createEphemeralSubagentExecutor(options) {
202
209
  }
203
210
  if (input.signal?.aborted)
204
211
  throw abortError(input.signal);
205
- return await runPi(prepared, input, validated.timeout, invocation);
212
+ return await runPi(prepared, input, validated, invocation);
206
213
  }
207
214
  finally {
208
215
  release();
@@ -362,16 +369,23 @@ export function formatDuration(milliseconds) {
362
369
  const minutes = Math.floor(seconds % 3_600 / 60);
363
370
  return hours ? `${hours}h ${minutes}m` : minutes ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
364
371
  }
365
- async function runPi(prepared, input, timeoutPolicy, invocation) {
372
+ async function runPi(prepared, input, budget, invocation) {
366
373
  if (input.signal?.aborted)
367
374
  throw abortError(input.signal);
375
+ const timeoutPolicy = budget.timeout;
368
376
  return await new Promise((resolve, reject) => {
369
377
  const args = [...invocation.args, "--mode", "json", "-p", ...prepared.launch.args, `Task: ${prepared.task}`];
378
+ const startedAt = Date.now();
379
+ const maxDeadline = startedAt + timeoutPolicy.maxMs;
370
380
  let child;
371
381
  try {
372
382
  child = spawn(invocation.command, args, {
373
383
  cwd: prepared.cwd,
374
- env: { ...process.env, ...prepared.launch.env },
384
+ env: {
385
+ ...process.env,
386
+ ...prepared.launch.env,
387
+ [EXECUTION_BUDGET_ENV]: JSON.stringify({ maxTurns: budget.maxTurns, maxMs: timeoutPolicy.maxMs, startedAt }),
388
+ },
375
389
  shell: false,
376
390
  stdio: ["ignore", "pipe", "pipe"],
377
391
  detached: process.platform !== "win32",
@@ -397,8 +411,8 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
397
411
  let spawnError;
398
412
  let protocolError;
399
413
  let aborted = false;
400
- const startedAt = Date.now();
401
- const maxDeadline = startedAt + timeoutPolicy.maxMs;
414
+ let turnLimited = false;
415
+ let startedTurns = 0;
402
416
  let lastEventAt = startedAt;
403
417
  let deadline = Math.min(startedAt + timeoutPolicy.idleMs, maxDeadline);
404
418
  let timedOutAfterMs;
@@ -480,6 +494,11 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
480
494
  : `Subagent timed out after ${formatDuration(timeoutPolicy.idleMs)} without a recognized Pi event.`;
481
495
  reject(new EphemeralSubagentError("timeout", message, new Error(message), accumulatedUsage()));
482
496
  }
497
+ else if (turnLimited) {
498
+ const summary = `Subagent reached its maximum turn limit of ${budget.maxTurns}.`;
499
+ const message = output ? capEphemeralSubagentOutput(`${summary}\n\nLast assistant output:\n${output}`) : summary;
500
+ reject(new EphemeralSubagentError("turn_limit", message, new Error(message), accumulatedUsage(), output));
501
+ }
483
502
  else if (protocolError) {
484
503
  reject(new EphemeralSubagentError("protocol", protocolError.message, protocolError, accumulatedUsage()));
485
504
  }
@@ -551,7 +570,7 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
551
570
  scheduleDeadline();
552
571
  };
553
572
  const processLine = (line) => {
554
- if (!line.trim())
573
+ if (turnLimited || !line.trim())
555
574
  return;
556
575
  let event;
557
576
  try {
@@ -566,6 +585,12 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
566
585
  if (typeof record.type !== "string" || !Object.hasOwn(PI_JSON_EVENTS, record.type))
567
586
  return;
568
587
  observeEvent();
588
+ if (record.type === "turn_start" && ++startedTurns > budget.maxTurns) {
589
+ if (!callbackFailure && !aborted && timedOutAfterMs === undefined)
590
+ turnLimited = true;
591
+ stop(true);
592
+ return;
593
+ }
569
594
  if (record.type === "message_start") {
570
595
  partial.prefix = "";
571
596
  partial.totalBytes = 0;
@@ -690,7 +715,7 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
690
715
  };
691
716
  onStdoutData = (data) => {
692
717
  armPostExitIdleDeadline();
693
- if (callbackFailure || protocolError)
718
+ if (callbackFailure || protocolError || turnLimited)
694
719
  return;
695
720
  let offset = 0;
696
721
  while (offset < data.length) {
@@ -731,7 +756,7 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
731
756
  invokeCallback("onActivity", input.onActivity, activity);
732
757
  }
733
758
  }
734
- if (callbackFailure)
759
+ if (callbackFailure || turnLimited)
735
760
  return;
736
761
  lineParts = [];
737
762
  lineBytes = 0;
@@ -771,13 +796,13 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
771
796
  killTimer.unref();
772
797
  }
773
798
  const abort = () => {
774
- if (timedOutAfterMs !== undefined || childExited)
799
+ if (timedOutAfterMs !== undefined || turnLimited || childExited)
775
800
  return;
776
801
  aborted = true;
777
802
  stop();
778
803
  };
779
804
  function timeout(afterMs, reason) {
780
- if (timedOutAfterMs !== undefined || childExited)
805
+ if (timedOutAfterMs !== undefined || turnLimited || childExited)
781
806
  return;
782
807
  if (reason === "maximum") {
783
808
  if (!aborted) {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { type HerdrExecutor } from "@henryqw/pi-herdr";
3
3
  import { type AvailableModel, type ModelTask, type ProfileName, type ResolvedTaskRoute, type ThinkingLevel } from "@henryqw/pi-task-models";
4
- export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, EphemeralSubagentError, formatDuration, type EphemeralSubagentActivityEvent, type EphemeralSubagentErrorCode, type EphemeralSubagentExecutor, type EphemeralSubagentExecutorOptions, type EphemeralSubagentResult, type EphemeralSubagentRunInput, type EphemeralSubagentTimeout, } from "./ephemeral.ts";
4
+ export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, DEFAULT_MAX_TURNS, EphemeralSubagentError, EXECUTION_BUDGET_ENV, formatDuration, type EphemeralSubagentActivityEvent, type EphemeralSubagentErrorCode, type EphemeralSubagentExecutor, type EphemeralSubagentExecutorOptions, type EphemeralSubagentResult, type EphemeralSubagentRunInput, type EphemeralSubagentTimeout, } from "./ephemeral.ts";
5
5
  export { createChildWorktree, finalizeChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, worktreeContextNote, type WorktreeDirtyInspection, type WorktreeInfo, type WorktreePayload, } from "./worktree.ts";
6
6
  export { prepareExactReviewEvidence, REVIEW_MAX_PATCH_BYTES, REVIEW_MAX_PATHS, type PreparedReviewEvidence, type PrepareExactReviewEvidenceInput, } from "./review-evidence.ts";
7
7
  export declare const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
6
6
  import { createHerdrClient, herdrCommandFailure, hasHerdrErrorCode, startPiAgent } from "@henryqw/pi-herdr";
7
7
  import { modelReference, orderedProfileRoutes, readTaskModelsConfig, resolveConfiguredTaskRoute, resolveTaskModelRoute, } from "@henryqw/pi-task-models";
8
- export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, EphemeralSubagentError, formatDuration, } from "./ephemeral.js";
8
+ export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, DEFAULT_MAX_TURNS, EphemeralSubagentError, EXECUTION_BUDGET_ENV, formatDuration, } from "./ephemeral.js";
9
9
  export { createChildWorktree, finalizeChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, worktreeContextNote, } from "./worktree.js";
10
10
  export { prepareExactReviewEvidence, REVIEW_MAX_PATCH_BYTES, REVIEW_MAX_PATHS, } from "./review-evidence.js";
11
11
  const CODEX_ALIAS = /^openai-codex-(?:[2-9]|[1-9]\d+)$/;
@@ -161,11 +161,12 @@ A loaded `Role` contains `name`, `description`, required normalized `tools`, `ex
161
161
  ```js
162
162
  const executorOptions = {
163
163
  maxConcurrency: 4,
164
+ maxTurns: 50,
164
165
  timeout: { idleMs: 10 * 60_000, maxMs: 30 * 60_000 },
165
166
  };
166
167
  ```
167
168
 
168
- Concurrency is FIFO. `run` accepts optional `signal`, `onUpdate(text)`, `onTokens(number)`, and `onActivity(event)` callbacks plus required `prepare()`. A queued run receives its permit before `prepare` executes, so resource and route resolution can use the latest Pi state. Queued time does not consume child timeout. `maxConcurrency`, `idleMs`, and `maxMs` must be positive; `maxMs` must exceed `idleMs`.
169
+ Concurrency is FIFO. `run` accepts optional `signal`, `onUpdate(text)`, `onTokens(number)`, and `onActivity(event)` callbacks plus required `prepare()`. A queued run receives its permit before `prepare` executes, so resource and route resolution can use the latest Pi state. Queued time does not consume child timeout. `maxConcurrency`, `maxTurns`, `idleMs`, and `maxMs` must be positive; integer limits must be safe integers, `maxMs` must exceed `idleMs`, and omitted `maxTurns` defaults to 50.
169
170
 
170
171
  The executor is **active-Pi-only**. It reuses the currently running Pi invocation and does not locate or support a standalone Node.js Pi installation. Once direct Pi exits, stdout/stderr drain normally until EOF; an escaped descendant retaining either stream is cut off after short output inactivity or a one-second hard deadline so it cannot retain the FIFO permit.
171
172
 
@@ -193,6 +194,7 @@ export function createRunRole(pi) {
193
194
 
194
195
  const executor = createEphemeralSubagentExecutor({
195
196
  maxConcurrency: 4,
197
+ maxTurns: 50,
196
198
  timeout: { idleMs: 10 * 60_000, maxMs: 30 * 60_000 },
197
199
  });
198
200
 
@@ -244,7 +246,7 @@ export function createRunRole(pi) {
244
246
  }
245
247
  ```
246
248
 
247
- `run` resolves to `EphemeralSubagentResult`. Both outcome variants contain `exitCode`, `output`, `stderr`, and optional `stopReason`, `errorMessage`, and `usage`. A launched child/model failure is a typed `{ outcome: "failure", ... }` result. Abort, timeout, spawn, protocol, preparation, and callback failures reject with `EphemeralSubagentError` and a stable `code`. Assistant `output` and `stderr` are bounded, and `usage` contains aggregate child usage when Pi supplies it.
249
+ `run` resolves to `EphemeralSubagentResult`. Both outcome variants contain `exitCode`, `output`, `stderr`, and optional `stopReason`, `errorMessage`, and `usage`. A launched child/model failure is a typed `{ outcome: "failure", ... }` result. Abort, timeout, turn-limit, spawn, protocol, preparation, and callback failures reject with `EphemeralSubagentError` and a stable `code`. A terminal response at `maxTurns` succeeds; an attempted continuation rejects with `turn_limit`, accumulated `usage`, and bounded `output`. The executor supplies the same turn/maximum-runtime budget to the existing child Role tool extension, which steers the fixed convergence warning before another model turn once at each 80% threshold, combines thresholds first due together, and uses no timer or extra turn. Assistant `output` and `stderr` are bounded, and `usage` contains aggregate child usage when Pi supplies it.
248
250
 
249
251
  ### Activity callbacks
250
252
 
@@ -11,6 +11,7 @@ export interface SubagentTimeoutConfig {
11
11
 
12
12
  export interface SubagentConfig {
13
13
  maxSubagents?: number;
14
+ maxTurns?: number;
14
15
  timeout?: SubagentTimeoutConfig;
15
16
  }
16
17
 
@@ -66,16 +67,18 @@ export function readSubagentConfig(agentDir = getAgentDir()): LoadedSubagentConf
66
67
  const problems: string[] = [];
67
68
  const config: SubagentConfig = {};
68
69
  for (const key of Object.keys(record)) {
69
- if (key !== "maxSubagents" && key !== "timeout") {
70
- problems.push(`unknown config key ${JSON.stringify(key)}; expected maxSubagents, timeout`);
70
+ if (key !== "maxSubagents" && key !== "maxTurns" && key !== "timeout") {
71
+ problems.push(`unknown config key ${JSON.stringify(key)}; expected maxSubagents, maxTurns, timeout`);
71
72
  }
72
73
  }
73
74
 
74
- if (record.maxSubagents !== undefined) {
75
- if (typeof record.maxSubagents === "number" && Number.isSafeInteger(record.maxSubagents) && record.maxSubagents >= 1) {
76
- config.maxSubagents = record.maxSubagents;
75
+ for (const key of ["maxSubagents", "maxTurns"] as const) {
76
+ const value = record[key];
77
+ if (value === undefined) continue;
78
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 1) {
79
+ config[key] = value;
77
80
  } else {
78
- problems.push(`maxSubagents must be a safe integer >= 1, got ${JSON.stringify(record.maxSubagents)}`);
81
+ problems.push(`${key} must be a safe integer >= 1, got ${JSON.stringify(value)}`);
79
82
  }
80
83
  }
81
84
 
@@ -795,8 +795,8 @@ export function registerDelegateFlow(pi: ExtensionAPI, runtime: DelegateFlowRunt
795
795
  description: "Run 1–8 independent Implementers in isolated Unit Worktrees, validate and serially fast-forward each tip, with exact review only for units that declare a judgment criterion.",
796
796
  promptSnippet: "Run a deterministic parallel-implementation, serial-verification Flow",
797
797
  promptGuidelines: [
798
- "Use delegate_flow only for cohesive units expected to commute; combine work that overlaps files, APIs, schemas, generated output, package metadata, lockfiles, or invariants.",
799
- "Each unit must include explicit bounded requirements and its authoritative direct command/argument validation gate. Add review only for an explicit judgment that validation cannot establish.",
798
+ "Use delegate_flow only for cohesive units expected to commute: split independent outcomes into units, sequence dependent work outside delegate_flow, and never divide one invariant across multiple units. Combine work that overlaps files, APIs, schemas, generated output, package metadata, lockfiles, or invariants.",
799
+ "Each delegate_flow unit must own one concrete outcome with one focused validation story: include explicit bounded requirements and its authoritative direct command/argument validation gate. If the affected flow or scope is not yet known, perform bounded read-only discovery first. Add review only for an explicit judgment that validation cannot establish.",
800
800
  "If a Flow blocks, inspect its classification and call delegate_flow_continue once with explicit repair guidance; modelClass may replace that one repair's current class.",
801
801
  ],
802
802
  parameters: DelegateFlowSchema,
@@ -1,7 +1,9 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { CHILD_EXCLUDED_TOOL_NAMES, ROLE_TOOL_POLICY_FLAG } from "@henryqw/pi-subagent";
2
+ import { CHILD_EXCLUDED_TOOL_NAMES, EXECUTION_BUDGET_ENV, ROLE_TOOL_POLICY_FLAG } from "@henryqw/pi-subagent";
3
3
 
4
4
  const childExcludedTools: ReadonlySet<string> = new Set(CHILD_EXCLUDED_TOOL_NAMES);
5
+ const WARNING_RATIO = 0.8;
6
+ const WARNING_MESSAGE_TYPE = "pi-subagent-execution-budget";
5
7
 
6
8
  function configuredTools(value: unknown): string[] {
7
9
  if (typeof value !== "string") throw new Error(`${ROLE_TOOL_POLICY_FLAG} must be JSON tool names.`);
@@ -17,6 +19,35 @@ function configuredTools(value: unknown): string[] {
17
19
  return [...new Set(parsed.map((name) => name.trim()))];
18
20
  }
19
21
 
22
+ function executionBudget(value: string | undefined): { maxTurns: number; maxMs: number; startedAt: number } | undefined {
23
+ if (value === undefined) return;
24
+ let parsed: unknown;
25
+ try {
26
+ parsed = JSON.parse(value);
27
+ } catch {
28
+ throw new Error(`${EXECUTION_BUDGET_ENV} must be a JSON execution budget.`);
29
+ }
30
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
31
+ throw new Error(`${EXECUTION_BUDGET_ENV} must be a JSON execution budget.`);
32
+ }
33
+ const budget = parsed as Record<string, unknown>;
34
+ if (Object.keys(budget).length !== 3 || !("maxTurns" in budget) || !("maxMs" in budget) || !("startedAt" in budget)
35
+ || !Number.isSafeInteger(budget.maxTurns) || (budget.maxTurns as number) < 1
36
+ || typeof budget.maxMs !== "number" || !Number.isFinite(budget.maxMs) || budget.maxMs <= 0
37
+ || !Number.isSafeInteger(budget.startedAt) || (budget.startedAt as number) < 0) {
38
+ throw new Error(`${EXECUTION_BUDGET_ENV} must be a JSON execution budget.`);
39
+ }
40
+ return { maxTurns: budget.maxTurns as number, maxMs: budget.maxMs, startedAt: budget.startedAt as number };
41
+ }
42
+
43
+ function expectsAnotherTurn(message: unknown): boolean {
44
+ if (!message || typeof message !== "object" || Array.isArray(message)) return false;
45
+ const record = message as Record<string, unknown>;
46
+ return record.role === "assistant" && Array.isArray(record.content)
47
+ && record.content.some((part) => part && typeof part === "object" && !Array.isArray(part)
48
+ && (part as Record<string, unknown>).type === "toolCall");
49
+ }
50
+
20
51
  export default function roleTools(pi: ExtensionAPI): void {
21
52
  pi.registerFlag(ROLE_TOOL_POLICY_FLAG, {
22
53
  description: "Internal Pi Subagent Role tool policy",
@@ -36,4 +67,29 @@ export default function roleTools(pi: ExtensionAPI): void {
36
67
  throw new Error(`Subagent requested unavailable tools: ${unavailable.join(", ")}. Check spelling and load the provider extension that registers them.`);
37
68
  }
38
69
  });
70
+
71
+ const budget = executionBudget(process.env[EXECUTION_BUDGET_ENV]);
72
+ if (!budget) return;
73
+ const warningTurn = Math.ceil(budget.maxTurns * WARNING_RATIO);
74
+ let completedTurns = 0;
75
+ let turnWarningSent = false;
76
+ let runtimeWarningSent = false;
77
+ pi.on("turn_end", (event) => {
78
+ completedTurns += 1;
79
+ if (!expectsAnotherTurn(event.message)) return;
80
+ const elapsedMs = Math.max(0, Date.now() - budget.startedAt);
81
+ const turnWarningDue = !turnWarningSent && completedTurns >= warningTurn;
82
+ const runtimeWarningDue = !runtimeWarningSent && elapsedMs >= budget.maxMs * WARNING_RATIO;
83
+ if (!turnWarningDue && !runtimeWarningDue) return;
84
+ if (turnWarningDue) turnWarningSent = true;
85
+ if (runtimeWarningDue) runtimeWarningSent = true;
86
+ const remainingTurns = Math.max(0, budget.maxTurns - completedTurns);
87
+ const remainingMinutes = Math.max(0, Math.ceil((budget.maxMs - elapsedMs) / 60_000));
88
+ const maxMinutes = budget.maxMs / 60_000;
89
+ pi.sendMessage({
90
+ customType: WARNING_MESSAGE_TYPE,
91
+ content: `**Execution budget warning:** ${remainingTurns} of ${budget.maxTurns} turns and approximately ${remainingMinutes} of ${maxMinutes} minutes remain before forced termination.\nConverge now: stop expanding scope, complete the highest-priority required work, perform only essential validation, and return a concise final result. If completion is impossible, follow your role’s recovery requirements and report the blocker and exact remaining work. This warning does not change your role, scope, or permissions.`,
92
+ display: true,
93
+ }, { deliverAs: "steer", triggerTurn: false });
94
+ });
39
95
  }
@@ -18,6 +18,7 @@ import {
18
18
  createEphemeralSubagentExecutor,
19
19
  DELEGATE_TASK,
20
20
  createRoleLaunch,
21
+ DEFAULT_MAX_TURNS,
21
22
  EphemeralSubagentError,
22
23
  finalizeChildWorktree,
23
24
  formatDuration,
@@ -331,7 +332,11 @@ export default function subagentExtension(
331
332
  // Explicit policy argument (tests/embedders) wins; otherwise resolve from
332
333
  // config file over defaults.
333
334
  const timeoutPolicy: TimeoutPolicy = overrideTimeoutPolicy ?? resolveTimeoutPolicy(loadedConfig.config.timeout);
334
- const executor = createEphemeralSubagentExecutor({ maxConcurrency: maxActiveSubagents, timeout: timeoutPolicy });
335
+ const executor = createEphemeralSubagentExecutor({
336
+ maxConcurrency: maxActiveSubagents,
337
+ maxTurns: loadedConfig.config.maxTurns ?? DEFAULT_MAX_TURNS,
338
+ timeout: timeoutPolicy,
339
+ });
335
340
  // Background children outlive the launching tool call, so they get their own
336
341
  // abort signal: tied to the session, not to the turn that started them.
337
342
  const backgroundTasks = new Map<string, { controller: AbortController; settled: Promise<void> }>();
@@ -602,8 +607,8 @@ export default function subagentExtension(
602
607
  description: `Delegate one selected single, parallel, or chain workflow of bounded tasks to isolated Pi Subagents. Roles: ${roleSummary()}.`,
603
608
  promptSnippet: "Delegate one bounded single, parallel, or chain workflow to isolated roles",
604
609
  promptGuidelines: [
605
- "Call delegate_task with exactly one mode: role+task for one task, tasks for 1–8 independent parallel tasks, or chain for 1–8 dependent sequential tasks using {previous} for the immediately preceding assistant output.",
606
- "Every delegate_task entry must state its objective, exact scope and exclusions, relevant context and constraints, expected deliverable, and validation; never pass the parent request unchanged.",
610
+ "Call delegate_task with exactly one mode: role+task for one task, tasks for 1–8 independent parallel tasks, or chain for 1–8 dependent sequential tasks using {previous} for the immediately preceding assistant output; split independent, commuting outcomes into parallel entries, sequence dependent work in chain entries, and never divide one invariant across multiple entries.",
611
+ "Every delegate_task entry must own one concrete outcome with one focused validation story: state its objective, exact scope and exclusions, relevant context and constraints, expected deliverable, and validation; if the affected flow or scope is not yet known, perform bounded read-only discovery first; never pass the parent request unchanged.",
607
612
  "For each delegate_task entry, populate model and thinking only for an explicit user override; otherwise choose only modelClass: fast normally, or balanced upfront for obviously complex work. This is Main policy, not runtime enforcement.",
608
613
  "Parallel delegate_task entries must own non-overlapping files. Keep integration and cross-cutting decisions in Main, and use the minimum number of Subagents needed.",
609
614
  "delegate_task background applies to the whole selected workflow and returns before results exist; use it only when the user explicitly asks for non-blocking work.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "7.0.0",
3
+ "version": "8.0.0",
4
4
  "description": "Delegate bounded single, parallel, or chained tasks to isolated Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -39,9 +39,9 @@
39
39
  "pack:check": "npm pack --dry-run"
40
40
  },
41
41
  "peerDependencies": {
42
- "@earendil-works/pi-ai": "^0.84.3",
43
- "@earendil-works/pi-coding-agent": "^0.84.3",
44
- "@earendil-works/pi-tui": "^0.84.3",
42
+ "@earendil-works/pi-ai": "^0.84.4",
43
+ "@earendil-works/pi-coding-agent": "^0.84.4",
44
+ "@earendil-works/pi-tui": "^0.84.4",
45
45
  "typebox": "^1.3.15"
46
46
  },
47
47
  "repository": {
@@ -11,9 +11,9 @@ You are Main, the planner/orchestrator: slice work and call `delegate_flow`. Do
11
11
 
12
12
  Before slicing, identify applicable repository prohibitions. If the request or plan conflicts with them, stop and resolve the conflict before delegation. Copy them into every affected task and into `review` when automated validation cannot establish compliance; never replace repository policy with generic preservation or migration assumptions. When compatibility is disallowed, require deletion of replaced paths and forbid legacy readers, aliases, adapters, dual schemas, deprecation paths, and compatibility fallbacks.
13
13
 
14
- Use the fewest cohesive units. `delegate_flow` is for independent units expected to commute; combine or sequence work that overlaps files, APIs, schemas, generated output, package metadata, lockfiles, or invariants. Dependent work remains outside Flow, in one task or ordinary caller-controlled sequencing.
14
+ Use the fewest cohesive units. `delegate_flow` is for independent units expected to commute: split independent outcomes into units, combine or sequence work that overlaps files, APIs, schemas, generated output, package metadata, lockfiles, or invariants, and never divide one invariant across multiple units. Dependent work remains outside Flow; sequence it in one task or ordinary caller-controlled sequencing.
15
15
 
16
- Give every unit a bounded objective, owned scope and exclusions, and its direct validation command/argument array. Do not pass the parent request unchanged. Use `modelClass: "fast"` normally; use `"balanced"` upfront only for obviously complex work. Add non-empty `review` only for an explicit judgment that automated validation cannot establish. Call `delegate_flow` with 1–8 units; the runtime always supplies the effective Implementer and supplies the Reviewer only when a unit needs review.
16
+ Give every unit a bounded objective, owned scope and exclusions, and its direct validation command/argument array; each delegation must own one concrete outcome with one focused validation story. If the affected flow or scope is not yet known, perform bounded read-only discovery first. Do not pass the parent request unchanged. Use `modelClass: "fast"` normally; use `"balanced"` upfront only for obviously complex work. Add non-empty `review` only for an explicit judgment that automated validation cannot establish. Call `delegate_flow` with 1–8 units; the runtime always supplies the effective Implementer and supplies the Reviewer only when a unit needs review.
17
17
 
18
18
  ## Runtime Flow
19
19