@henryqw/pi-subagent 27.10.0 → 27.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -89,6 +89,12 @@ To check a request before a launch, add `"dryRun": true`. The dry run does the l
89
89
 
90
90
  The launch returns a task ID and first Herdr tab, not the answer. One follow-up delivers results when the workflow finishes. The results show the tokens and cost of each worker and the total cost of the request. Busy Main receives it after its current turn; idle Main starts a turn. Failed partial output stays marked as partial, never success. Worker output carries no user authority.
91
91
 
92
+ The tasks in a request share a 40 KiB answer budget, and each worker prompt states its share. A longer answer is still a success. The follow-up shows its first part and the path of a private file with the full answer. Full-answer paths also stay in structured results and recovery text, outside the output limit.
93
+
94
+ A task packet above 64 KiB uses a private file, including the full previous answer in a chain. The worker must read the complete packet with its Role's tools before it acts.
95
+
96
+ Pi's `read` can retrieve lines of at most 50 KiB (51,200 bytes), with line offsets for more content. If any line is longer, the worker uses `bash`, even when the Role also has `read`. Without `bash`, that task fails before tab creation; use shorter lines or a Role with `bash`. A Role with neither tool also fails before tab creation. Chain context is never cut to the inline answer budget.
97
+
92
98
  To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`. This opens a new tab with the saved conversation and a new reference. Continue the newest reference from the original checkout and workspace. For eligibility and stop behavior, see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker).
93
99
 
94
100
  ### Review a change
@@ -1,12 +1,9 @@
1
1
  import { lstat, realpath } from "node:fs/promises";
2
- import { isAbsolute, normalize, relative, sep } from "node:path";
2
+ import { isAbsolute, normalize } from "node:path";
3
3
  import { runProcess as defaultRunProcess } from "./process.js";
4
+ import { isWithin } from "./worktree.js";
4
5
  const GIT_ROOT_TIMEOUT_CAP_MS = 30_000;
5
6
  const REVIEW_PROMPT_MAX_BYTES = 64 * 1024;
6
- function within(root, candidate) {
7
- const fromRoot = relative(root, candidate);
8
- return fromRoot === "" || (fromRoot !== ".." && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot));
9
- }
10
7
  function processFailure(result) {
11
8
  const detail = (result.stderr || result.stdout).trim().slice(0, 1_000);
12
9
  return new Error(`git rev-parse --show-toplevel failed with exit ${result.code}${detail ? `: ${detail}` : ""}`);
@@ -45,7 +42,7 @@ export function createCanonicalGitRootResolver(options = {}) {
45
42
  if (canonicalRoot !== root || !rootInfo.isDirectory()) {
46
43
  throw new Error("Git returned a non-canonical repository root.");
47
44
  }
48
- if (!within(root, canonicalCwd)) {
45
+ if (!isWithin(root, canonicalCwd)) {
49
46
  throw new Error("Git repository root does not identify the requested working directory.");
50
47
  }
51
48
  return root;
@@ -1,5 +1,7 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import type { ResolvedRoleLaunch } from "./index.ts";
1
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { PreparedRoleLaunch, ResolvedRoleLaunch } from "./index.ts";
3
+ /** The Role tool that reads a file-backed task packet, or undefined for an inline packet; throws when no tool can read it in full. */
4
+ export declare function directTaskReader(task: string, tools: readonly string[]): "read" | "bash" | undefined;
3
5
  /** A prompt is accepted only with the exact pane, agent, cwd and turn identity. */
4
6
  export interface DirectHandle {
5
7
  name: string;
@@ -7,7 +9,12 @@ export interface DirectHandle {
7
9
  paneId: string;
8
10
  sessionFile: string;
9
11
  prompt: string;
10
- answer(maxBytes: number): Promise<string>;
12
+ /** `text` is the exact answer; `inline` is bounded for Main, linking a private full copy when truncated. */
13
+ answer(maxBytes: number): Promise<{
14
+ text: string;
15
+ inline: string;
16
+ answerFile?: string;
17
+ }>;
11
18
  usage(): Promise<DirectUsage>;
12
19
  /** Bounded assistant text from this turn so far; failure evidence only, never completion. */
13
20
  partialText(maxChars: number): Promise<string | undefined>;
@@ -18,7 +25,7 @@ export interface DirectHandle {
18
25
  export declare function exactDirectTerminalTurn(jsonl: string, prompt: string): boolean;
19
26
  /** Refuse continuation unless the saved session's exact recorded turn is terminal and no later user turn exists. */
20
27
  export declare function assertSettledDirectSession(sessionFile: string, turn: string): Promise<void>;
21
- export declare function exactDirectAnswer(jsonl: string, prompt: string, maxBytes?: number, requireSuccess?: boolean): string;
28
+ export declare function exactDirectAnswer(jsonl: string, prompt: string, requireSuccess?: boolean): string;
22
29
  /** Measured from one session read; each field is absent when no turn record carried it. */
23
30
  export interface DirectUsage {
24
31
  tokens?: number;
@@ -65,5 +72,5 @@ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: s
65
72
  * `settledOnly` refuses to close a listed agent that is not idle or done. */
66
73
  stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
67
74
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
68
- start(launch: ResolvedRoleLaunch, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath">): Promise<DirectHandle>;
75
+ start(launch: ResolvedRoleLaunch & Pick<PreparedRoleLaunch, "tools">, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath">): Promise<DirectHandle>;
69
76
  };
@@ -2,14 +2,30 @@ import { randomBytes } from "node:crypto";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { open, readFile, mkdtemp, stat, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
- import { join } from "node:path";
5
+ import { dirname, join } from "node:path";
6
6
  import { setTimeout as sleep } from "node:timers/promises";
7
+ import { DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
7
8
  import { createHerdrClient, hasHerdrErrorCode, herdrCommandFailure, startPiAgent } from "@henryqw/pi-herdr";
8
- import { assertPrivateLease, scanProcessLease } from "./process-lease.js";
9
+ import { utf8Prefix } from "./ephemeral.js";
10
+ import { assertPrivateLease, PI_SUBAGENT_PROCESS_LEASE, scanProcessLease } from "./process-lease.js";
9
11
  const OPERATION_MS = 30_000;
10
12
  const SESSION_LIMIT = 16 * 1024 * 1024;
11
- const ANSWER_LIMIT = 50 * 1024;
13
+ // Leave room for boundary instructions below Linux's 128 KiB per-argument limit.
14
+ const INLINE_TASK_BYTES = 64 * 1024;
12
15
  const DIRECT_OUTCOMES = ["succeeded", "failed", "blocked"];
16
+ /** The Role tool that reads a file-backed task packet, or undefined for an inline packet; throws when no tool can read it in full. */
17
+ export function directTaskReader(task, tools) {
18
+ if (Buffer.byteLength(task, "utf8") <= INLINE_TASK_BYTES)
19
+ return;
20
+ const longLine = task.split("\n").some((line) => Buffer.byteLength(line, "utf8") > DEFAULT_MAX_BYTES);
21
+ if (tools.includes("read") && !longLine)
22
+ return "read";
23
+ if (tools.includes("bash"))
24
+ return "bash";
25
+ throw new Error(longLine
26
+ ? `Large direct task packet has a line above Pi read's ${DEFAULT_MAX_BYTES}-byte limit. Add bash to the Role or use lines within that limit; no worker was launched.`
27
+ : "Large direct task packets require read or bash in the Role; no worker was launched.");
28
+ }
13
29
  const object = (value, label) => {
14
30
  if (!value || typeof value !== "object" || Array.isArray(value))
15
31
  throw new Error(`Malformed Herdr ${label}.`);
@@ -91,7 +107,7 @@ export async function assertSettledDirectSession(sessionFile, turn) {
91
107
  throw new Error(`Saved Pi session ${sessionFile} has no terminal final turn for the recorded prompt; the worker may still be running`);
92
108
  }
93
109
  }
94
- export function exactDirectAnswer(jsonl, prompt, maxBytes = ANSWER_LIMIT, requireSuccess = false) {
110
+ export function exactDirectAnswer(jsonl, prompt, requireSuccess = false) {
95
111
  const final = exactFinalTurn(jsonl, prompt);
96
112
  if (!final || final.stopReason !== "stop" || !Array.isArray(final.content)) {
97
113
  throw new Error("Pi did not persist an exact successful final answer for this prompt.");
@@ -102,8 +118,6 @@ export function exactDirectAnswer(jsonl, prompt, maxBytes = ANSWER_LIMIT, requir
102
118
  }).join("\n");
103
119
  if (!text.trim())
104
120
  throw new Error("Pi persisted an empty final answer.");
105
- if (Buffer.byteLength(text, "utf8") > maxBytes)
106
- throw new Error(`Pi final answer exceeds the ${maxBytes}-byte workflow limit; read the private session file for recovery.`);
107
121
  if (!requireSuccess)
108
122
  return text;
109
123
  let completion;
@@ -354,6 +368,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
354
368
  },
355
369
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
356
370
  async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume) {
371
+ const reader = directTaskReader(task, launch.tools);
357
372
  const caller = result(await herdr.json(["pane", "current", "--current"], options(signal)), "pane_current");
358
373
  const pane = object(caller.pane, "calling pane");
359
374
  if (pane.pane_id !== callerPane || pane.workspace_id !== workspaceId)
@@ -373,6 +388,11 @@ export function createDirectHerdr(pi, cwd, idleMs) {
373
388
  await writeFile(leasePath, "", { flag: "wx", mode: 0o600 });
374
389
  }
375
390
  const turn = randomBytes(16).toString("hex");
391
+ if (reader) {
392
+ const taskFile = join(dirname(sessionFile), `task-${turn}.md`);
393
+ await writeFile(taskFile, task, { flag: "wx", mode: 0o600 });
394
+ task = `Use ${reader} to read the complete task packet at ${JSON.stringify(taskFile)}. Read all parts before you act; do not use a truncated preview. The file contains the full task and chain context. If you cannot read it in full, stop and report blocked work.`;
395
+ }
376
396
  // Pi's native session is the exact answer channel. Herdr screen output is diagnostic only.
377
397
  const sessionArgs = launch.args.filter((arg) => arg !== "--no-session");
378
398
  if (sessionArgs.length !== launch.args.length - 1)
@@ -384,7 +404,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
384
404
  let tabId;
385
405
  let paneId;
386
406
  try {
387
- const response = await herdr.json(["tab", "create", "--workspace", workspaceId, "--cwd", workingDir, "--label", label, "--env", `PI_SUBAGENT_PROCESS_LEASE=${leasePath}`, "--no-focus"], options());
407
+ const response = await herdr.json(["tab", "create", "--workspace", workspaceId, "--cwd", workingDir, "--label", label, "--env", `${PI_SUBAGENT_PROCESS_LEASE}=${leasePath}`, "--no-focus"], options());
388
408
  const created = object(response.result, "tab allocation result");
389
409
  // Capture every returned ID before validation can fail. These are evidence,
390
410
  // not owned tabs; the caller retains this intent even without either ID.
@@ -438,7 +458,15 @@ export function createDirectHerdr(pi, cwd, idleMs) {
438
458
  const info = await stat(sessionFile);
439
459
  if (info.size > SESSION_LIMIT)
440
460
  throw new Error(`Pi session in tab ${tabId} exceeds 16 MiB; inspect ${sessionFile} for recovery.`);
441
- return exactDirectAnswer(await readFile(sessionFile, "utf8"), prompt, maxBytes, requireSuccess);
461
+ const text = exactDirectAnswer(await readFile(sessionFile, "utf8"), prompt, requireSuccess);
462
+ const bytes = Buffer.byteLength(text, "utf8");
463
+ if (bytes <= maxBytes)
464
+ return { text, inline: text };
465
+ // An oversized exact answer still succeeds: Main gets a bounded prefix and a private full copy.
466
+ // Exclusive creation refuses a worker-planted file, symlink, or FIFO at this predictable path.
467
+ const file = join(dirname(sessionFile), `answer-${turn}.md`);
468
+ await writeFile(file, text, { flag: "wx", mode: 0o600 });
469
+ return { text, answerFile: file, inline: `${utf8Prefix(text, maxBytes)}\n\n[Answer truncated to ${maxBytes} of ${bytes} bytes; read the full answer at ${file}]` };
442
470
  };
443
471
  const maybeAnswer = async () => {
444
472
  try {
@@ -1,5 +1,5 @@
1
1
  import { lstat, realpath } from "node:fs/promises";
2
- import { createChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, } from "./worktree.js";
2
+ import { createChildWorktree, inspectIndexFlags, inspectWorktreeDirty, isMissing, WorktreeSetupError, } from "./worktree.js";
3
3
  import { prepareExactReviewEvidence } from "./review-evidence.js";
4
4
  import { sameIdentity, } from "./schema.js";
5
5
  import { withTransientLaunch, } from "./runner.js";
@@ -41,16 +41,13 @@ function cloneWorktree(info) {
41
41
  baseCommit: info.baseCommit.toLowerCase(),
42
42
  };
43
43
  }
44
- function pathMissing(error) {
45
- return Boolean(error && typeof error === "object" && error.code === "ENOENT");
46
- }
47
44
  async function pathExists(path) {
48
45
  try {
49
46
  await lstat(path);
50
47
  return true;
51
48
  }
52
49
  catch (error) {
53
- if (pathMissing(error))
50
+ if (isMissing(error))
54
51
  return false;
55
52
  throw error;
56
53
  }
@@ -457,7 +454,7 @@ export class CheckedGitRuntime {
457
454
  return await realpath(path);
458
455
  }
459
456
  catch (error) {
460
- if (pathMissing(error))
457
+ if (isMissing(error))
461
458
  return path;
462
459
  throw error;
463
460
  }
@@ -9,7 +9,7 @@ import { isCleanCommitted, } from "./schema.js";
9
9
  import { buildChangesetTaskPrompt, withTransientLaunch, } from "./runner.js";
10
10
  import { runProcess as defaultRunProcess } from "./process.js";
11
11
  import { EXECUTION_BUDGET_ENV } from "./ephemeral.js";
12
- import { assertPrivateLease, scanProcessLease } from "./process-lease.js";
12
+ import { assertPrivateLease, PI_SUBAGENT_PROCESS_LEASE, scanProcessLease } from "./process-lease.js";
13
13
  import { exactDirectTerminalTurn } from "./direct-herdr.js";
14
14
  import { READABLE_BRANCH_PATTERN } from "./worktree.js";
15
15
  const MIN_HERDR_VERSION = [0, 9, 3];
@@ -25,7 +25,6 @@ const DIAGNOSTIC_LIMIT = 8 * 1024;
25
25
  const SESSION_LIMIT = 16 * 1024 * 1024;
26
26
  const LEASE_MODE = 0o600;
27
27
  const DIRECTORY_MODE = 0o700;
28
- const PROCESS_LEASE_ENV = "PI_SUBAGENT_PROCESS_LEASE";
29
28
  const CORRELATION_TOKEN_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
30
29
  const HERDR_AGENT_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/;
31
30
  const SETTLED_AGENT_STATES = new Set(["idle", "done"]);
@@ -803,7 +802,7 @@ export class HerdrHostRuntime {
803
802
  const budget = this.executionBudget?.();
804
803
  const args = [
805
804
  "tab", "create", "--workspace", allocation.workspaceId, "--cwd", allocation.worktreeCwd,
806
- "--label", allocation.label, "--env", `${PROCESS_LEASE_ENV}=${allocation.leasePath}`,
805
+ "--label", allocation.label, "--env", `${PI_SUBAGENT_PROCESS_LEASE}=${allocation.leasePath}`,
807
806
  ...(budget ? ["--env", `${EXECUTION_BUDGET_ENV}=${JSON.stringify({ ...budget, startedAt: this.now() })}`] : []),
808
807
  "--no-focus",
809
808
  ];
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { loadRoleMcpConfig, parseRoleMcpAllowlist } from "./mcp-role.ts";
5
5
  export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, DEFAULT_MAX_TURNS, EphemeralSubagentError, EXECUTION_BUDGET_ENV, formatDuration, type EphemeralSubagentActivityEvent, type EphemeralSubagentErrorCode, type EphemeralSubagentExecutionBudget, type EphemeralSubagentExecutor, type EphemeralSubagentExecutorOptions, type EphemeralSubagentResult, type EphemeralSubagentRunInput, type EphemeralSubagentTimeout, } from "./ephemeral.ts";
6
6
  export { createChildWorktree, finalizeChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, type WorktreeDirtyInspection, type WorktreeInfo, type WorktreePayload, } from "./worktree.ts";
7
7
  export { prepareExactReviewEvidence, REVIEW_MAX_PATCH_BYTES, REVIEW_MAX_PATHS, type PreparedReviewEvidence, type PrepareExactReviewEvidenceInput, } from "./review-evidence.ts";
8
- export declare const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
8
+ export { PI_SUBAGENT_PROCESS_LEASE } from "./process-lease.ts";
9
9
  export declare const ROLE_MCP_POLICY_FLAG = "pi-subagent-role-mcps";
10
10
  export declare const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
11
11
  /** Read child MCP policy before Pi binds registered extension flag values. */
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ const MULTI_CODEX_EXTENSION = fileURLToPath(import.meta.resolve("@henryqw/pi-mul
17
17
  const ROLE_MCP_EXTENSION = fileURLToPath(new URL("../extensions/role-mcp.ts", import.meta.url));
18
18
  const ROLE_TOOLS_EXTENSION = fileURLToPath(new URL("../extensions/role-tools.ts", import.meta.url));
19
19
  const GIT_READ_EXTENSION = fileURLToPath(new URL("../extensions/git-read.ts", import.meta.url));
20
- export const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
20
+ export { PI_SUBAGENT_PROCESS_LEASE } from "./process-lease.js";
21
21
  export const ROLE_MCP_POLICY_FLAG = "pi-subagent-role-mcps";
22
22
  export const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
23
23
  const CODEMODE_TOOL = "codemode";
@@ -2,9 +2,10 @@ import { randomBytes } from "node:crypto";
2
2
  import { constants } from "node:fs";
3
3
  import { chmod, lstat, mkdtemp, open, realpath, rmdir, unlink } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
- import { isAbsolute, join, normalize, relative, sep } from "node:path";
5
+ import { isAbsolute, join, normalize } from "node:path";
6
6
  import { resolveConfiguredRoleLaunch } from "./index.js";
7
7
  import { registerModelTask } from "@henryqw/pi-task-models";
8
+ import { isMissing, isWithin } from "./worktree.js";
8
9
  const PROMPT_FLAG = "--append-system-prompt";
9
10
  const DIRECTORY_MODE = 0o700;
10
11
  const PROMPT_MODE = 0o600;
@@ -14,13 +15,6 @@ export const ISOLATED_MODEL_TASK = {
14
15
  purpose: "Resolve one task-scoped isolated Role launch.",
15
16
  defaultProfile: "balanced",
16
17
  };
17
- function isMissing(error) {
18
- return Boolean(error && typeof error === "object" && error.code === "ENOENT");
19
- }
20
- function isWithin(root, candidate) {
21
- const fromRoot = relative(root, candidate);
22
- return fromRoot === "" || (fromRoot !== ".." && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot));
23
- }
24
18
  async function removeTransientLaunch(directory, promptPath, promptRequired) {
25
19
  const failures = [];
26
20
  try {
@@ -1,4 +1,5 @@
1
1
  import type { HerdrExecResult } from "@henryqw/pi-herdr";
2
+ export declare const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
2
3
  export declare function assertPrivateLease(path: string, allowMissing: boolean): Promise<boolean>;
3
4
  /** Shared exact process-lease evidence for direct and isolated workers. */
4
5
  export declare function scanProcessLease(path: string, execute: (args: string[]) => Promise<HerdrExecResult>, pid?: number, allowMissing?: boolean): Promise<number[]>;
@@ -1,4 +1,5 @@
1
1
  import { lstat } from "node:fs/promises";
2
+ export const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
2
3
  export async function assertPrivateLease(path, allowMissing) {
3
4
  let info;
4
5
  try {
package/dist/schema.d.ts CHANGED
@@ -298,7 +298,6 @@ export type CommandEvidence = Static<typeof CommandEvidenceSchema>;
298
298
  export type CheckBatchEvidence = Static<typeof CheckBatchEvidenceSchema>;
299
299
  export type ReusedCheckSource = NonNullable<CommandEvidence["reusedFrom"]>;
300
300
  export type ReviewEvidence = Static<typeof ReviewEvidenceSchema>;
301
- export type WorkerTermination = Static<typeof WorkerTerminationSchema>;
302
301
  export declare const CLEANUP_KINDS: readonly ["worker_tab", "workspace", "worktree", "branch"];
303
302
  export type CleanupStep = Static<typeof CleanupStepSchema>;
304
303
  export type CleanupKind = CleanupStep["kind"];
@@ -507,18 +506,6 @@ declare const ReviewEvidenceSchema: Type.TObject<{
507
506
  passed: Type.TBoolean;
508
507
  at: Type.TInteger;
509
508
  }>;
510
- declare const WorkerTerminationSchema: Type.TObject<{
511
- status: Type.TUnion<[Type.TLiteral<"terminating">, Type.TLiteral<"terminated">, Type.TLiteral<"unknown">]>;
512
- workerId: Type.TString;
513
- candidate: Type.TObject<{
514
- branch: Type.TString;
515
- head: Type.TString;
516
- index: Type.TString;
517
- tree: Type.TString;
518
- }>;
519
- at: Type.TOptional<Type.TInteger>;
520
- failure: Type.TOptional<Type.TString>;
521
- }>;
522
509
  declare const CleanupStepSchema: Type.TObject<{
523
510
  kind: Type.TUnion<[Type.TLiteral<"worker_tab">, Type.TLiteral<"workspace">, Type.TLiteral<"worktree">, Type.TLiteral<"branch">]>;
524
511
  status: Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"running">, Type.TLiteral<"completed">]>;
@@ -1304,30 +1291,6 @@ declare const IntegrationCandidateSchema: Type.TObject<{
1304
1291
  worker: Type.TUnion<[Type.TLiteral<"retained">, Type.TLiteral<"release_pending">, Type.TLiteral<"released">]>;
1305
1292
  decision: Type.TOptional<Type.TLiteral<"rejected">>;
1306
1293
  }>;
1307
- declare const IntegrationStageSchema: Type.TObject<{
1308
- taskId: Type.TString;
1309
- attempt: Type.TInteger;
1310
- source: Type.TObject<{
1311
- branch: Type.TString;
1312
- head: Type.TString;
1313
- index: Type.TString;
1314
- tree: Type.TString;
1315
- }>;
1316
- onto: Type.TObject<{
1317
- branch: Type.TString;
1318
- head: Type.TString;
1319
- index: Type.TString;
1320
- tree: Type.TString;
1321
- }>;
1322
- status: Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"staging">, Type.TLiteral<"staged">, Type.TLiteral<"conflict">]>;
1323
- tip: Type.TOptional<Type.TObject<{
1324
- branch: Type.TString;
1325
- head: Type.TString;
1326
- index: Type.TString;
1327
- tree: Type.TString;
1328
- }>>;
1329
- failure: Type.TOptional<Type.TString>;
1330
- }>;
1331
1294
  declare const IntegrationGenerationSchema: Type.TObject<{
1332
1295
  number: Type.TInteger;
1333
1296
  status: Type.TUnion<[Type.TLiteral<"staging">, Type.TLiteral<"conflict">, Type.TLiteral<"validating">, Type.TLiteral<"validation_failed">, Type.TLiteral<"ready">, Type.TLiteral<"promoting">, Type.TLiteral<"promoted">, Type.TLiteral<"promotion_unknown">, Type.TLiteral<"promotion_failed">, Type.TLiteral<"superseded">]>;
@@ -1788,7 +1751,6 @@ export declare const IntegrationStateSchema: Type.TObject<{
1788
1751
  }>>;
1789
1752
  }>;
1790
1753
  export type IntegrationCandidate = Static<typeof IntegrationCandidateSchema>;
1791
- export type IntegrationStage = Static<typeof IntegrationStageSchema>;
1792
1754
  export type IntegrationGeneration = Static<typeof IntegrationGenerationSchema>;
1793
1755
  export type IntegrationState = Static<typeof IntegrationStateSchema>;
1794
1756
  declare const TerminalRunStatusSchema: Type.TUnion<[Type.TLiteral<"completed">, Type.TLiteral<"final_failed">, Type.TLiteral<"superseded">, Type.TLiteral<"aborted">]>;
package/dist/store.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { lstat, mkdir, open, readdir, realpath } from "node:fs/promises";
4
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { extensionConfigDir, readTextFileBounded, writePrivateTextFileAtomically } from "@henryqw/pi-config-store";
6
6
  import { check, lock } from "proper-lockfile";
7
7
  import { parseRunState, RUN_STATE_VERSION } from "./schema.js";
8
8
  import { discardResources } from "./discard.js";
9
+ import { isMissing, isWithin } from "./worktree.js";
9
10
  const INITIAL_STATE_MAX_BYTES = 2 * 1024 * 1024;
10
11
  /*
11
12
  * create() caps the complete initial serialization at 2 MiB. Loaded requests
@@ -30,19 +31,12 @@ export class ProductiveRunLeaseBusyError extends Error {
30
31
  super("Another Pi Subagent productive request is active in this repository.");
31
32
  }
32
33
  }
33
- function isMissing(error) {
34
- return Boolean(error && typeof error === "object" && error.code === "ENOENT");
35
- }
36
34
  function isAlreadyPresent(error) {
37
35
  return Boolean(error && typeof error === "object" && error.code === "EEXIST");
38
36
  }
39
37
  function isLocked(error) {
40
38
  return Boolean(error && typeof error === "object" && error.code === "ELOCKED");
41
39
  }
42
- function isWithin(root, candidate) {
43
- const fromRoot = relative(root, candidate);
44
- return fromRoot === "" || (fromRoot !== ".." && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot));
45
- }
46
40
  async function canonicalPlannedPath(path) {
47
41
  let ancestor = resolve(path);
48
42
  const suffix = [];
@@ -1,4 +1,6 @@
1
1
  import { type GitRunner } from "./git-process.ts";
2
+ export declare function isMissing(error: unknown): boolean;
3
+ export declare function isWithin(root: string, candidate: string): boolean;
2
4
  export interface WorktreeInfo {
3
5
  path: string;
4
6
  cwd: string;
package/dist/worktree.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, lstatSync } from "node:fs";
3
3
  import { appendFile, mkdir, readFile } from "node:fs/promises";
4
- import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { runGit } from "./git-process.js";
6
+ export function isMissing(error) {
7
+ return Boolean(error && typeof error === "object" && error.code === "ENOENT");
8
+ }
9
+ export function isWithin(root, candidate) {
10
+ const fromRoot = relative(root, candidate);
11
+ return fromRoot === "" || (fromRoot !== ".." && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot));
12
+ }
6
13
  export const WORKTREES_DIRNAME = ".worktrees";
7
14
  const BRANCH_NAMESPACE = "pi-subagent";
8
15
  const NAME_COMPONENT_LIMIT = 24;
@@ -137,9 +137,13 @@ If the extension cannot prove termination of the stopped worker, the workflow ke
137
137
 
138
138
  ### Direct results and records
139
139
 
140
- The extension retrieves each final answer from its exact Pi session file, not its possibly truncated screen. Idle, blocked, unknown, malformed, or oversized answers fail with recoverable tab and session identities. No whole-run deadline applies.
140
+ The extension retrieves each final answer from its exact Pi session file, not its possibly truncated screen. Idle, blocked, unknown, or malformed answers fail with recoverable tab and session identities. No whole-run deadline applies.
141
141
 
142
- The tool returns a task ID and the first Herdr tab after launch, not the answer. The extension observes each worker and sends one result to Main when the workflow finishes. If Main is busy, Pi queues the result after the current turn. If Main is idle, the result starts a turn. The extension does not report a blocked, stalled, unknown, or truncated result as success.
142
+ The tasks in a request share a 40 KiB inline answer budget. Each worker prompt states its share. A longer exact answer is still a success. The result shows a UTF-8-safe prefix and a truncation marker. The marker gives the path of a private `answer-<turn>.md` file beside the session file, which holds the full answer. For a write task, the budget applies to the `answer` field of the completion object. A chain step receives the full answer of the previous step in `{previous}`; the budget applies only to the result for Main. The result details keep `answerFile` for each full-answer file. Recovery text includes these paths outside the output limit, even when checkout notes remove the inline link.
143
+
144
+ Herdr accepts prompt text as one command argument. To stay below the operating system's argument limit, a task packet above 64 KiB uses a private, exclusively created `task-<turn>.md` file beside the session file. This packet includes the full chain context. The worker prompt requires the Role's `read` tool to read all parts with line offsets before work starts. Pi's native `read` can return a line of exactly 50 KiB (51,200 bytes), but not a longer line. If any packet line is longer, or `read` is absent, the worker uses the Role's `bash` tool. If a line is too long and `bash` is absent, the task fails before tab creation with the read limit and a request for `bash` or shorter lines. A Role with neither tool also fails before tab creation; the extension adds no tool. The task file stays available for recovery.
145
+
146
+ The tool returns a task ID and the first Herdr tab after launch, not the answer. The extension observes each worker and sends one result to Main when the workflow finishes. If Main is busy, Pi queues the result after the current turn. If Main is idle, the result starts a turn. The extension does not report a blocked, stalled, or unknown result as success.
143
147
 
144
148
  In the result, each launched worker has a line with its model, thinking level, measured task tokens, cost, and elapsed time. For example: `✓ [1/2] Check · worker · provider/model · thinking high · 1.5k tok · $0.12 · 42s`. The first line also shows the request total, such as `total $0.12`. Unknown and zero cost are not shown. If Pi recorded no usage, the line shows `tokens unknown`. Failed and stopped workers show the usage that the extension measured until they ended. A worker that the extension skipped before launch shows no usage.
145
149
 
@@ -2,10 +2,8 @@ import { formatConfigIssues, type ConfigLoad } from "@henryqw/pi-config-store";
2
2
  import type { ExecutionPolicySnapshot } from "../dist/schema.js";
3
3
  import type { SubagentConfig } from "@henryqw/pi-subagent";
4
4
 
5
- export type EffectiveExecutionPolicy = ExecutionPolicySnapshot;
6
-
7
5
  /** Resolve one immutable policy. A disabled config blocks delegation. */
8
- export function resolveExecutionPolicy(path: string, loaded: ConfigLoad<SubagentConfig>): EffectiveExecutionPolicy {
6
+ export function resolveExecutionPolicy(path: string, loaded: ConfigLoad<SubagentConfig>): ExecutionPolicySnapshot {
9
7
  if (loaded.status === "disabled") {
10
8
  throw new Error(`${path}: ${formatConfigIssues(loaded.issues)}; delegation is blocked until this file is corrected.`);
11
9
  }
@@ -3,7 +3,6 @@ import type { JsonValue } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { truncateToWidth } from "@earendil-works/pi-tui";
5
5
  import { capEphemeralSubagentOutput, utf8Prefix, type EphemeralSubagentExecutor } from "../dist/ephemeral.js";
6
- import type { EffectiveExecutionPolicy } from "./config.ts";
7
6
  import {
8
7
  createCanonicalGitRootResolver,
9
8
  createExactJudgmentExecutor,
@@ -31,6 +30,7 @@ import {
31
30
  StatusOutputSchema,
32
31
  type CheckBatchEvidence,
33
32
  type ExecuteRequest,
33
+ type ExecutionPolicySnapshot,
34
34
  type ModelClass,
35
35
  type ReviewEvidence,
36
36
  type RunState,
@@ -59,8 +59,8 @@ export type CreateIsolatedComponents = (options: {
59
59
  pi: ExtensionAPI;
60
60
  context(): ExtensionContext;
61
61
  executor: EphemeralSubagentExecutor;
62
- policy: EffectiveExecutionPolicy;
63
- currentPolicy(): EffectiveExecutionPolicy;
62
+ policy: ExecutionPolicySnapshot;
63
+ currentPolicy(): ExecutionPolicySnapshot;
64
64
  onStateSaved(state: RunState): void;
65
65
  }) => IsolatedExtensionComponents;
66
66
 
@@ -531,8 +531,8 @@ export interface IsolatedSurface {
531
531
 
532
532
  export interface RegisterIsolatedOptions {
533
533
  executor: EphemeralSubagentExecutor;
534
- policy: EffectiveExecutionPolicy;
535
- currentPolicy(): EffectiveExecutionPolicy;
534
+ policy: ExecutionPolicySnapshot;
535
+ currentPolicy(): ExecutionPolicySnapshot;
536
536
  /** Report new config issues, and throw when the config now blocks delegation, before each deferred Role launch. */
537
537
  beforeRoleLaunch?(ctx: ExtensionContext): void;
538
538
  componentsFactory?: CreateIsolatedComponents;
@@ -29,6 +29,8 @@ export type WorkflowTransportEntry = {
29
29
  elapsedMs?: number;
30
30
  status: WorkflowTransportStatus;
31
31
  assistantOutput?: string;
32
+ /** Private full answer identity, independent of capped evidence. */
33
+ answerFile?: string;
32
34
  failure?: string;
33
35
  /** Bounded assistant text produced before a failure; never success evidence. */
34
36
  partialOutput?: string;
@@ -149,12 +151,12 @@ function sourceFor(entry: WorkflowTransportEntry): string | undefined {
149
151
  if (entry.status === "rejected") {
150
152
  return entry.partialOutput ? `${entry.failure}\nPartial output before failure (incomplete; not a success):\n${entry.partialOutput}` : entry.failure;
151
153
  }
152
- if (entry.status === "running" || entry.status === "succeeded") return entry.assistantOutput;
154
+ if (entry.status === "succeeded") return entry.assistantOutput;
153
155
  }
154
156
 
155
157
  function evidenceFor(entry: WorkflowTransportEntry, position: number, total: number): Evidence | undefined {
156
158
  const source = sourceFor(entry);
157
- if (source === undefined || !source) return;
159
+ if (!source) return;
158
160
  const [preview, remainder] = splitEvidence(source);
159
161
  return {
160
162
  heading: `- [${position}/${total}] ${entry.name} · ${entry.role} · ${entry.status === "rejected" ? "failure" : "result"}:`,
@@ -200,7 +202,13 @@ export function formatWorkflowResult(mode: WorkflowMode, entries: readonly Workf
200
202
  ] : []),
201
203
  ];
202
204
  return {
203
- text: capEphemeralSubagentOutput(lines.join("\n")),
205
+ text: [
206
+ capEphemeralSubagentOutput(lines.join("\n")),
207
+ ...(ordered.some(({ answerFile }) => answerFile !== undefined) ? [
208
+ "Answer recovery (full files):",
209
+ ...ordered.flatMap(({ id, answerFile }) => answerFile === undefined ? [] : [`- ${id} · full answer: ${answerFile}`]),
210
+ ] : []),
211
+ ].join("\n"),
204
212
  details: {
205
213
  mode,
206
214
  entries: ordered.map((entry) => {
@@ -218,6 +226,7 @@ export function formatWorkflowResult(mode: WorkflowMode, entries: readonly Workf
218
226
  ...(entry.cost === undefined ? {} : { cost: entry.cost }),
219
227
  ...(entry.elapsedMs === undefined ? {} : { elapsedMs: entry.elapsedMs }),
220
228
  ...(entry.checkout === undefined ? {} : { checkout: entry.checkout }),
229
+ ...(entry.answerFile === undefined ? {} : { answerFile: entry.answerFile }),
221
230
  };
222
231
  }),
223
232
  ...(cost === undefined ? {} : { cost }),
@@ -3,15 +3,15 @@ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-c
3
3
  import { type Component, Text, type TUI, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
4
  import { availableTaskModels, loadTaskModelsConfig, modelReference, type ProfileName, registerModelTask, registerTaskModelsConfigReporting, resolveAvailableModel, resolveConfiguredTaskRoute, type ResolvedTaskRoute, taskThinkingLevels } from "@henryqw/pi-task-models";
5
5
  import { registerConfigReporting } from "@henryqw/pi-config-store";
6
- import { capEphemeralSubagentOutput as capOutput, createEphemeralSubagentExecutor, createSubagentConfigStore, DEFAULT_SUBAGENT_CONFIG, DELEGATE_TASK, findRole, formatDuration, loadRoleCatalog, prepareRoleLaunch, resolveRolePackageResources, resolveTaskRoute, ROLE_TOOL_POLICY_FLAG, type Role } from "@henryqw/pi-subagent";
7
- import { resolveExecutionPolicy, type EffectiveExecutionPolicy } from "./config.ts";
6
+ import { capEphemeralSubagentOutput as capOutput, createEphemeralSubagentExecutor, createSubagentConfigStore, DEFAULT_SUBAGENT_CONFIG, DELEGATE_TASK, findRole, formatDuration, loadRoleCatalog, prepareRoleLaunch, resolveRolePackageResources, resolveTaskRoute, ROLE_TOOL_POLICY_FLAG, type ExecutionPolicySnapshot, type Role } from "@henryqw/pi-subagent";
7
+ import { resolveExecutionPolicy } from "./config.ts";
8
8
  import { registerCheckoutAdmission } from "./admission.ts";
9
9
  import { registerIsolatedExtension } from "./isolated.ts";
10
10
  import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask } from "./subagent-command.ts";
11
11
  import { MODEL_CLASS_GUIDANCE } from "./model-class-policy.ts";
12
12
  import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowResult, workerOutputForMain, type BackgroundWorkflowTransportDetails, type WorkflowTransportEntry } from "./result-transport.ts";
13
13
  import { checkoutNote, DelegateTaskParameters, identifyWorkflowEntries, parseDelegateTask, runForegroundWorkflow, snapshotCheckout, writesCheckout, type CheckoutSnapshot, type ParsedWorkflow, type WorkflowEntry } from "./workflow.ts";
14
- import { assertSettledDirectSession, createDirectHerdr, DirectAllocationError, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity, type DirectUsage } from "../dist/direct-herdr.js";
14
+ import { assertSettledDirectSession, createDirectHerdr, DirectAllocationError, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity, type DirectUsage } from "../dist/direct-herdr.js";
15
15
  import { materializeTransientLaunch } from "../dist/launch-runtime.js";
16
16
  const WIDGET_KEY = "subagent-status";
17
17
  const WIDGET_INTERVAL_MS = 1_000;
@@ -204,7 +204,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
204
204
  });
205
205
  // The isolated runner reads the policy lazily without a context, so each read reports through the session's.
206
206
  let latestCtx: ExtensionContext | undefined;
207
- const currentPolicy = (): EffectiveExecutionPolicy => {
207
+ const currentPolicy = (): ExecutionPolicySnapshot => {
208
208
  const loaded = configStore.loadSync();
209
209
  if (latestCtx) configReporter.report(latestCtx, configStore, loaded);
210
210
  const policy = resolveExecutionPolicy(configStore.path, loaded);
@@ -407,8 +407,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
407
407
  const resolved = role.modelClass === undefined ? resolveConfiguredTaskRoute(ctx, DELEGATE_TASK) : resolveTaskRoute(ctx, role.modelClass);
408
408
  route = { model: modelReference(resolved.model), thinking: resolved.thinkingLevel };
409
409
  } catch (error) { route = { error: message(error) }; }
410
- return { name: role.name, source: catalog.sources.get(role.name) ?? "unknown", modelClass: role.modelClass, route,
411
- tools: role.tools ?? [], extensions: role.extensions ?? [], skills: role.skills ?? [], mcps: role.mcps ?? [] };
410
+ return { name: role.name, source: catalog.sources.get(role.name)!, modelClass: role.modelClass, route,
411
+ tools: role.tools, extensions: role.extensions, skills: role.skills, mcps: role.mcps ?? [] };
412
412
  });
413
413
  return { roles, errors: catalog.errors.map((error) => error.message) };
414
414
  },
@@ -648,6 +648,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
648
648
  try {
649
649
  prepared = await prepareDirectLaunch(findRole(catalog, role), ctx, {
650
650
  ...(modelClass === undefined ? {} : { modelClass }), ...(model === undefined ? {} : { model }) });
651
+ // A chain packet is checked without {previous}; the full packet is known only at launch.
652
+ directTaskReader(workflow.mode === "chain" ? delegation.task.replaceAll("{previous}", "") : delegation.task, prepared.tools);
651
653
  } catch (error) { throw boundedError(error); }
652
654
  entries.push({ index, name, role, access, model: modelReference(prepared.model), thinkingLevel: prepared.thinkingLevel,
653
655
  ...(continueFrom === undefined ? {} : { continueFrom }), ...(workflow.mode === "chain" && index ? { after: index } : {}) });
@@ -656,6 +658,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
656
658
  const notChecked = [
657
659
  "checkout admission: a dry run takes none",
658
660
  ...(sources.size ? ["stop of each continued agent: it closes its Herdr pane"] : []),
661
+ ...(workflow.mode === "chain" ? ["task packet reader after {previous} substitution: the previous answer is unknown"] : []),
659
662
  "Herdr tab creation and agent start",
660
663
  ];
661
664
  const text = [
@@ -812,6 +815,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
812
815
  }
813
816
  };
814
817
  directTasks.set(taskId, local);
818
+ // Tasks share one inline budget so the combined follow-up stays bounded for Main.
819
+ const answerBytes = Math.floor(40 * 1024 / entries.length);
815
820
  const launch = async (entry: WorkflowEntry, activeSignal: AbortSignal) => {
816
821
  activeSignal.throwIfAborted();
817
822
  // A later worker launches after earlier ones finish; report and revalidate config edits made meanwhile.
@@ -831,7 +836,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
831
836
  try {
832
837
  handle = await herdr.start({ ...prepared, args: [...transient.launch.args] },
833
838
  `d-${randomUUID().replaceAll("-", "").slice(0, 24)}`, `${directRef(display)} ${display.title}`,
834
- entry.delegation.access === "read" ? `${entry.delegation.task}\n\n${READ_ACCESS_NOTICE}` : entry.delegation.task, activeSignal, (tab) => {
839
+ `${entry.delegation.access === "read" ? `${entry.delegation.task}\n\n${READ_ACCESS_NOTICE}` : entry.delegation.task}\n\nFinal answer budget: ${answerBytes} bytes, conclusions first. Main sees only that much inline; a longer answer is saved to a file.`, activeSignal, (tab) => {
835
840
  const record = { taskId, entryId: entry.id, display, ...tab };
836
841
  // Persist before agent start, or let the new session carry the exact identity after settlement.
837
842
  if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_TAB_TYPE, record);
@@ -900,16 +905,17 @@ export default function subagentExtension(pi: ExtensionAPI): void {
900
905
  controller.signal.throwIfAborted();
901
906
  if (writerFailed) throw new Error("Previous direct task did not complete exactly; inspect recorded tabs before new shared-checkout work.");
902
907
  handle = entry.index === 0 ? first : await launch(entry, entrySignal(entry));
903
- const answer = await handle.answer(Math.floor(40 * 1024 / entries.length));
908
+ const { text, inline, answerFile } = await handle.answer(answerBytes);
904
909
  let usage: DirectUsage | undefined;
905
910
  try {
906
911
  usage = await handle.usage();
907
912
  const item = widgetItems.get(entry.id);
908
913
  if (item) { item.tokens = usage.tokens; item.cost = usage.cost; item.activity = handle.activity; }
909
914
  } catch { /* Optional telemetry. */ }
910
- states.set(entry.id, { ...states.get(entry.id)!, status: "succeeded", assistantOutput: answer, ...measured(entry.id, usage), ...await checkout(entry) });
915
+ states.set(entry.id, { ...states.get(entry.id)!, status: "succeeded", assistantOutput: inline, ...(answerFile === undefined ? {} : { answerFile }), ...measured(entry.id, usage), ...await checkout(entry) });
911
916
  finishWidgetItem(entry.id, "success");
912
- return answer;
917
+ // A chain passes the exact answer to {previous}; only Main's transport is bounded.
918
+ return text;
913
919
  } catch (error) {
914
920
  if (writes) writerFailed = true;
915
921
  const { assistantOutput: _partial, ...base } = states.get(entry.id)!;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.10.0",
3
+ "version": "27.10.2",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",