@henryqw/pi-subagent 27.10.1 → 27.10.3

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,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;
@@ -32,11 +39,6 @@ export interface DirectToolActivity {
32
39
  durationMs?: number;
33
40
  };
34
41
  }
35
- export declare function directSessionUsage(jsonl: string, prompt: string): DirectUsage & {
36
- activity?: DirectToolActivity;
37
- };
38
- /** The last `maxChars` of assistant text in the exact prompt's turn; ignores a partial trailing entry. */
39
- export declare function directPartialText(jsonl: string, prompt: string, maxChars: number): string | undefined;
40
42
  /** One reader per handle; only complete, valid lines advance the byte offset. */
41
43
  export declare function createDirectSessionReader(sessionFile: string, prompt: string): Pick<DirectHandle, "usage" | "partialText" | "activity">;
42
44
  /** `turn` is the prompt's random turn identity; it proves which session turn a record owns.
@@ -65,5 +67,5 @@ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: s
65
67
  * `settledOnly` refuses to close a listed agent that is not idle or done. */
66
68
  stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
67
69
  /** `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>;
70
+ 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
71
  };
@@ -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";
9
+ import { utf8Prefix } from "./ephemeral.js";
8
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;
@@ -202,21 +216,6 @@ class DirectSessionState {
202
216
  return chars.length <= maxChars ? chars.join("") : `…${chars.slice(-maxChars).join("")}`;
203
217
  }
204
218
  }
205
- function parseDirectSession(jsonl, prompt) {
206
- const state = new DirectSessionState(prompt);
207
- for (const line of jsonl.split("\n"))
208
- if (!state.consume(line))
209
- break;
210
- return state;
211
- }
212
- // Ignore a partial trailing JSONL entry while the child is writing it.
213
- export function directSessionUsage(jsonl, prompt) {
214
- return parseDirectSession(jsonl, prompt).usage();
215
- }
216
- /** The last `maxChars` of assistant text in the exact prompt's turn; ignores a partial trailing entry. */
217
- export function directPartialText(jsonl, prompt, maxChars) {
218
- return parseDirectSession(jsonl, prompt).partialText(maxChars);
219
- }
220
219
  /** One reader per handle; only complete, valid lines advance the byte offset. */
221
220
  export function createDirectSessionReader(sessionFile, prompt) {
222
221
  let offset = 0;
@@ -354,6 +353,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
354
353
  },
355
354
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
356
355
  async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume) {
356
+ const reader = directTaskReader(task, launch.tools);
357
357
  const caller = result(await herdr.json(["pane", "current", "--current"], options(signal)), "pane_current");
358
358
  const pane = object(caller.pane, "calling pane");
359
359
  if (pane.pane_id !== callerPane || pane.workspace_id !== workspaceId)
@@ -373,6 +373,11 @@ export function createDirectHerdr(pi, cwd, idleMs) {
373
373
  await writeFile(leasePath, "", { flag: "wx", mode: 0o600 });
374
374
  }
375
375
  const turn = randomBytes(16).toString("hex");
376
+ if (reader) {
377
+ const taskFile = join(dirname(sessionFile), `task-${turn}.md`);
378
+ await writeFile(taskFile, task, { flag: "wx", mode: 0o600 });
379
+ 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.`;
380
+ }
376
381
  // Pi's native session is the exact answer channel. Herdr screen output is diagnostic only.
377
382
  const sessionArgs = launch.args.filter((arg) => arg !== "--no-session");
378
383
  if (sessionArgs.length !== launch.args.length - 1)
@@ -438,7 +443,15 @@ export function createDirectHerdr(pi, cwd, idleMs) {
438
443
  const info = await stat(sessionFile);
439
444
  if (info.size > SESSION_LIMIT)
440
445
  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);
446
+ const text = exactDirectAnswer(await readFile(sessionFile, "utf8"), prompt, requireSuccess);
447
+ const bytes = Buffer.byteLength(text, "utf8");
448
+ if (bytes <= maxBytes)
449
+ return { text, inline: text };
450
+ // An oversized exact answer still succeeds: Main gets a bounded prefix and a private full copy.
451
+ // Exclusive creation refuses a worker-planted file, symlink, or FIFO at this predictable path.
452
+ const file = join(dirname(sessionFile), `answer-${turn}.md`);
453
+ await writeFile(file, text, { flag: "wx", mode: 0o600 });
454
+ return { text, answerFile: file, inline: `${utf8Prefix(text, maxBytes)}\n\n[Answer truncated to ${maxBytes} of ${bytes} bytes; read the full answer at ${file}]` };
442
455
  };
443
456
  const maybeAnswer = async () => {
444
457
  try {
@@ -1,5 +1,5 @@
1
1
  import { type CheckCommand, type ReviewEvidence, type TaskAttempt, type TaskRequest, type WorktreeAllocationIntent, type WorktreeAllocationPlan, type WorkspaceIdentity } from "./schema.ts";
2
- import { type AllocationReconciliation, type CheckRunResult, type GitRuntime, type InFlightTaskCandidateInspection, type InFlightTaskCandidateInspector, type TaskCandidateInspector, type OperationContext, type ReviewResult, type TransientLaunchHandle, type WorktreeAllocationResult, type VerifiedLaunch } from "./runner.ts";
2
+ import { type AllocationReconciliation, type CheckRunResult, type GitRuntime, type InFlightTaskCandidateInspection, type InFlightTaskCandidateInspector, type OperationContext, type ReviewResult, type TransientLaunchHandle, type WorktreeAllocationResult, type VerifiedLaunch } from "./runner.ts";
3
3
  type ProcessResult = {
4
4
  code: number;
5
5
  killed: boolean;
@@ -33,7 +33,7 @@ export interface CheckedGitRuntimeOptions {
33
33
  runProcess?: DirectProcessRunner;
34
34
  executeReview?: ExactReviewExecutor;
35
35
  }
36
- export declare class CheckedGitRuntime implements GitRuntime, TaskCandidateInspector, InFlightTaskCandidateInspector {
36
+ export declare class CheckedGitRuntime implements GitRuntime, InFlightTaskCandidateInspector {
37
37
  private readonly execute;
38
38
  private readonly executeReview?;
39
39
  private readonly mainOperationTails;
package/dist/runner.d.ts CHANGED
@@ -199,13 +199,6 @@ export interface HostRuntime {
199
199
  failure: string;
200
200
  }>;
201
201
  }
202
- export interface TaskCandidateInspector {
203
- inspectTaskCandidate(input: {
204
- root: string;
205
- task: TaskRequest;
206
- attempt: TaskAttempt;
207
- }, context: OperationContext): Promise<WorkspaceIdentity>;
208
- }
209
202
  export interface InFlightTaskCandidateInspection {
210
203
  candidate: WorkspaceIdentity;
211
204
  clean: boolean;
@@ -219,6 +212,11 @@ export interface InFlightTaskCandidateInspector {
219
212
  }, context: OperationContext): Promise<InFlightTaskCandidateInspection>;
220
213
  }
221
214
  export interface GitRuntime {
215
+ inspectTaskCandidate(input: {
216
+ root: string;
217
+ task: TaskRequest;
218
+ attempt: TaskAttempt;
219
+ }, context: OperationContext): Promise<WorkspaceIdentity>;
222
220
  inspectMain(input: {
223
221
  root: string;
224
222
  }, context: OperationContext): Promise<WorkspaceIdentity>;
@@ -315,7 +313,7 @@ export declare class IsolatedRunner {
315
313
  private readonly currentPolicy;
316
314
  private readonly productiveLifecycles;
317
315
  private readonly followupControls;
318
- constructor(coordinatorRuntime: CoordinatorRuntime, hostRuntime: HostRuntime, gitRuntime: GitRuntime & TaskCandidateInspector, store: FileRunStore | undefined, textExecutor: EphemeralSubagentExecutor, policy?: ExecutionPolicySnapshot, currentPolicy?: () => ExecutionPolicySnapshot, integrationGit?: IntegrationGit);
316
+ constructor(coordinatorRuntime: CoordinatorRuntime, hostRuntime: HostRuntime, gitRuntime: GitRuntime, store: FileRunStore | undefined, textExecutor: EphemeralSubagentExecutor, policy?: ExecutionPolicySnapshot, currentPolicy?: () => ExecutionPolicySnapshot, integrationGit?: IntegrationGit);
319
317
  listRequests(root: string): Promise<{
320
318
  requests: Array<{
321
319
  id: string;
@@ -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
 
@@ -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;
@@ -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 }),
@@ -11,7 +11,7 @@ import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask
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;
@@ -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.1",
3
+ "version": "27.10.3",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",