@henryqw/pi-subagent 30.0.0 → 31.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.
Files changed (38) hide show
  1. package/CONTEXT.md +2 -2
  2. package/README.md +20 -22
  3. package/dist/ephemeral.d.ts +7 -3
  4. package/dist/ephemeral.js +59 -11
  5. package/dist/herdr-runtime.js +4 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +2 -2
  8. package/dist/native-host.d.ts +96 -0
  9. package/dist/native-host.js +243 -0
  10. package/dist/runner.d.ts +8 -1
  11. package/dist/runner.js +22 -15
  12. package/dist/schema.d.ts +71 -2
  13. package/dist/schema.js +14 -1
  14. package/dist/workspace-schema.d.ts +11 -0
  15. package/dist/workspace.d.ts +5 -2
  16. package/dist/workspace.js +58 -29
  17. package/docs/measurement.md +12 -1
  18. package/docs/orchestration-architecture.html +4 -4
  19. package/docs/orchestration-architecture.svg +2 -2
  20. package/docs/orchestration.md +69 -258
  21. package/docs/workspace.md +4 -80
  22. package/extensions/direct-check-exec.py +91 -0
  23. package/extensions/direct-check-supervisor.mjs +42 -0
  24. package/extensions/direct-check-witness.mjs +34 -0
  25. package/extensions/direct-native.ts +5 -3
  26. package/extensions/direct-outbox.ts +189 -0
  27. package/extensions/direct-owner.ts +49 -0
  28. package/extensions/direct-verification.ts +73 -0
  29. package/extensions/isolated.ts +25 -301
  30. package/extensions/prerequisite-evidence.ts +81 -0
  31. package/extensions/result-transport.ts +6 -4
  32. package/extensions/subagent-command.ts +12 -7
  33. package/extensions/subagent.ts +302 -495
  34. package/extensions/workflow-recovery.ts +359 -0
  35. package/extensions/workflow.ts +156 -40
  36. package/extensions/workspace.ts +16 -74
  37. package/package.json +8 -8
  38. package/skills/pi-subagent/SKILL.md +15 -37
@@ -1,3 +1,4 @@
1
+ import { expandChainTask, prerequisitePacket, type AnswerReference } from "./prerequisite-evidence.ts";
1
2
  import { createHash } from "node:crypto";
2
3
  import { createReadStream } from "node:fs";
3
4
  import { lstat, readlink } from "node:fs/promises";
@@ -6,9 +7,8 @@ import { DISPLAY_TEXT_CONTRACT } from "@henryqw/pi-subagent";
6
7
  import { PROFILE_NAMES } from "@henryqw/pi-task-models";
7
8
  import { Type, type Static } from "typebox";
8
9
  import { Check, Errors } from "typebox/value";
10
+ import { runProcess } from "../dist/process.js";
9
11
  import { runGit } from "../dist/git-process.js";
10
- import { ExecuteRequestSchema, parseExecuteRequest, type ExecuteRequest } from "../dist/schema.js";
11
- import { WorkspaceRequestSchema, parseWorkspaceRequest, type WorkspaceRequest } from "../dist/workspace-schema.js";
12
12
  import { RepositorySelectionSchema, parseRepositorySelection, type RepositorySelection } from "../dist/workspace-scope.js";
13
13
 
14
14
  export const MAX_WORKFLOW_ENTRIES = 8;
@@ -29,7 +29,7 @@ const DirectKindSchema = Type.Enum(["text"], { type: "string" });
29
29
  /** Main's honest per-task classification; only `write` reserves the checkout. Nothing enforces `read`. */
30
30
  export const DIRECT_ACCESS = ["read", "write"] as const;
31
31
  export type DirectAccess = (typeof DIRECT_ACCESS)[number];
32
- const ACCESS_GUIDANCE = `Declare "write" when the task may change files, Git state, or external resources, otherwise "read". "read" is not enforced (no sandbox): it skips checkout admission and runs concurrently. Use mode isolated for checked writes.`;
32
+ const ACCESS_GUIDANCE = `Declare "write" when the task may change files, Git state, or external resources, otherwise "read". "read" is not enforced (no sandbox): it skips checkout admission and runs concurrently.`;
33
33
  const AccessSchema = Type.Enum(DIRECT_ACCESS, { type: "string", description: "Use write for any potential mutation. Read is unsandboxed." });
34
34
  const DryRunSchema = Type.Boolean({ description: "Validate and preview without launching." });
35
35
  const ContinueFromSchema = Type.String({ pattern: "^D[1-9][0-9]*\\.[1-9][0-9]*$", description: "Resume the same Role and saved session, such as D7.1." });
@@ -37,71 +37,78 @@ const ContinueFromSchema = Type.String({ pattern: "^D[1-9][0-9]*\\.[1-9][0-9]*$"
37
37
  const PathsSchema = Type.Array(Type.String({ minLength: 1 }), {
38
38
  minItems: 1,
39
39
  maxItems: 32,
40
- description: "Write scope globs relative to the repo. Report only.",
40
+ description: "Direct writes only. Report scope globs relative to the repo. Omit for reads.",
41
41
  });
42
42
 
43
+ export const VERIFICATION_LIMITS = { checks: 3, args: 32, argLength: 1024, criterionLength: 1000, timeoutMs: 2_147_483_647, outputBytes: 8192 } as const;
44
+ const VerificationSchema = Type.Object({
45
+ criteria: Type.String({ minLength: 1, maxLength: VERIFICATION_LIMITS.criterionLength, description: "Acceptance criteria for the writer and correction." }),
46
+ checks: Type.Array(Type.Object({
47
+ executable: Type.String({ minLength: 1, maxLength: VERIFICATION_LIMITS.argLength }),
48
+ args: Type.Array(Type.String({ maxLength: VERIFICATION_LIMITS.argLength }), { maxItems: VERIFICATION_LIMITS.args }),
49
+ timeoutMs: Type.Integer({ minimum: 1, maximum: VERIFICATION_LIMITS.timeoutMs, description: "Requested check deadline in milliseconds, capped by the configured worker maximum runtime." }),
50
+ }, { additionalProperties: false }), { minItems: 1, maxItems: VERIFICATION_LIMITS.checks }),
51
+ }, { additionalProperties: false, description: "Writer acceptance checks; exit zero passes. At most one correction follows a definite failure." });
52
+
43
53
  export const DelegationSchema = Type.Object({
44
54
  role: RoleSchema,
45
55
  name: TaskNameSchema,
46
56
  task: TaskSchema,
47
57
  access: AccessSchema,
48
58
  paths: Type.Optional(PathsSchema),
59
+ verification: Type.Optional(VerificationSchema),
49
60
  continueFrom: Type.Optional(ContinueFromSchema),
50
61
  kind: Type.Optional(DirectKindSchema),
51
62
  model: Type.Optional(ModelSchema),
52
63
  modelClass: Type.Optional(ModelClassSchema),
53
64
  }, { additionalProperties: false });
54
65
 
66
+ const GraphDelegationSchema = Type.Object({
67
+ ...DelegationSchema.properties,
68
+ dependsOn: Type.Optional(Type.Array(TaskNameSchema, { maxItems: MAX_WORKFLOW_ENTRIES - 1, description: "Names of prerequisite tasks" })),
69
+ }, { additionalProperties: false });
70
+
55
71
  export const DirectWorkflowSchema = Type.Object({
56
72
  mode: Type.Literal("direct"),
57
- wait: Type.Optional(Type.Boolean({ description: "Return the result in this call." })),
73
+ wait: Type.Optional(Type.Boolean({ description: "Direct mode only. Return the result in this call." })),
58
74
  repositories: Type.Optional(RepositorySelectionSchema),
59
75
  role: Type.Optional(RoleSchema),
60
76
  name: Type.Optional(TaskNameSchema),
61
77
  task: Type.Optional(TaskSchema),
62
78
  access: Type.Optional(AccessSchema),
63
79
  paths: Type.Optional(PathsSchema),
80
+ verification: Type.Optional(VerificationSchema),
64
81
  continueFrom: Type.Optional(ContinueFromSchema),
65
82
  kind: Type.Optional(DirectKindSchema),
66
83
  model: Type.Optional(ModelSchema),
67
84
  modelClass: Type.Optional(ModelClassSchema),
68
- tasks: Type.Optional(Type.Array(DelegationSchema, { minItems: 1, maxItems: MAX_WORKFLOW_ENTRIES })),
85
+ tasks: Type.Optional(Type.Array(GraphDelegationSchema, { minItems: 1, maxItems: MAX_WORKFLOW_ENTRIES })),
69
86
  chain: Type.Optional(Type.Array(DelegationSchema, { minItems: 1, maxItems: MAX_WORKFLOW_ENTRIES })),
70
87
  }, { additionalProperties: false, description: "Direct mode: exactly one compact single, tasks, or chain workflow" });
71
88
 
72
89
  const CancelSchema = Type.Object({
73
90
  mode: Type.Literal("cancel"),
74
- id: Type.String({ pattern: "^direct-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$" }),
91
+ id: Type.String({ description: "Cancellation only. Use the workflow ID returned by Pi. Omit id when starting a worker.", pattern: "^direct-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$" }),
75
92
  }, { additionalProperties: false });
76
93
 
77
94
  // Parse each mode with its strict schema; expose a plain object root to tool providers.
78
- const checkedTask = WorkspaceRequestSchema.properties.tasks.items.properties;
79
- const checkedCommand = WorkspaceRequestSchema.properties.finalChecks.items.properties;
80
- const providerChecks = Type.Array(Type.Object({ ...checkedCommand, repository: Type.Optional(checkedCommand.repository) }, { additionalProperties: false }), { maxItems: 32 });
81
- // The model sees the common checked task fields once. Mode-specific parsers enforce all requirements.
82
- const providerCheckedTask = Type.Object({ ...checkedTask, kind: Type.Enum(["text", "changeset"], { type: "string" }),
83
- checks: Type.Optional(providerChecks), inputs: Type.Optional(RepositorySelectionSchema) }, { additionalProperties: false });
84
95
  export const DelegateTaskParameters = Type.Object({
85
96
  ...DirectWorkflowSchema.properties,
86
- mode: Type.Union([DirectWorkflowSchema.properties.mode, ExecuteRequestSchema.properties.mode, CancelSchema.properties.mode]),
87
- id: Type.Optional(Type.Union([ExecuteRequestSchema.properties.id, CancelSchema.properties.id])),
88
- goal: Type.Optional(ExecuteRequestSchema.properties.goal),
89
- tasks: Type.Optional(Type.Array(Type.Union([DelegationSchema, providerCheckedTask]), { minItems: 1, maxItems: MAX_WORKFLOW_ENTRIES })),
90
- finalChecks: Type.Optional(providerChecks),
91
- finalJudgment: ExecuteRequestSchema.properties.finalJudgment,
97
+ mode: Type.Enum(["direct", "cancel"], { type: "string", description: "For direct, use a single role/name/task/access packet OR tasks OR chain. Put packet fields only inside the selected array for batches. Omit unused fields." }),
98
+ id: Type.Optional(CancelSchema.properties.id),
92
99
  dryRun: Type.Optional(DryRunSchema),
93
100
  }, { additionalProperties: false });
94
101
 
95
- export type Delegation = Static<typeof DelegationSchema> & { kind: "text" };
102
+ export type Delegation = Static<typeof GraphDelegationSchema> & { kind: "text" };
96
103
  export type WorkflowMode = "single" | "parallel" | "chain";
97
104
  export type ParsedWorkflow = (
98
105
  | { mode: "single"; delegations: [Delegation] }
99
106
  | { mode: "parallel"; delegations: Delegation[] }
100
107
  | { mode: "chain"; delegations: Delegation[] }) & { repositories?: RepositorySelection; wait?: true };
101
- export type ParsedDelegateTask = ({ mode: "cancel"; id: string } | { mode: "direct"; workflow: ParsedWorkflow } | { mode: "isolated"; request: ExecuteRequest } | { mode: "workspace"; request: WorkspaceRequest }) & { dryRun: boolean };
108
+ export type ParsedDelegateTask = ({ mode: "cancel"; id: string } | { mode: "direct"; workflow: ParsedWorkflow }) & { dryRun: boolean };
102
109
 
103
110
  type DirectInput = Static<typeof DirectWorkflowSchema>;
104
- const DELEGATION_KEYS = ["role", "name", "task", "access", "paths", "continueFrom", "kind", "model", "modelClass"] as const;
111
+ const DELEGATION_KEYS = ["role", "name", "task", "access", "paths", "verification", "continueFrom", "kind", "model", "modelClass"] as const;
105
112
 
106
113
  function text(value: string, path: string): string {
107
114
  const normalized = value.trim();
@@ -125,14 +132,24 @@ function normalizePaths(value: Static<typeof DelegationSchema>, path: string): s
125
132
  });
126
133
  }
127
134
 
128
- function normalizeDelegation(value: Static<typeof DelegationSchema>, path: string): Delegation {
135
+ function normalizeDelegation(value: Static<typeof GraphDelegationSchema>, path: string): Delegation {
129
136
  const paths = normalizePaths(value, path);
137
+ if (value.verification && value.access !== "write") throw new Error(`${path}.verification requires access "write".`);
138
+ if (value.verification) {
139
+ text(value.verification.criteria, `${path}.verification.criteria`);
140
+ for (const check of value.verification.checks) {
141
+ text(check.executable, `${path}.verification.checks.executable`);
142
+ if (check.args.some((arg) => arg.includes("\0"))) throw new Error("Verification arguments cannot contain NUL.");
143
+ }
144
+ }
130
145
  return {
131
146
  role: text(value.role, `${path}.role`),
132
147
  name: normalizeTaskName(value.name, `${path}.name`),
133
148
  task: text(value.task, `${path}.task`),
134
149
  access: value.access,
150
+ ...(value.dependsOn === undefined ? {} : { dependsOn: value.dependsOn.map((name, index) => normalizeTaskName(name, `${path}.dependsOn[${index}]`)) }),
135
151
  ...(paths === undefined ? {} : { paths }),
152
+ ...(value.verification === undefined ? {} : { verification: value.verification }),
136
153
  ...(value.continueFrom === undefined ? {} : { continueFrom: value.continueFrom }),
137
154
  kind: "text",
138
155
  ...(value.model === undefined ? {} : { model: text(value.model, `${path}.model`) }),
@@ -170,7 +187,7 @@ export function parseWorkflow(value: unknown): ParsedWorkflow {
170
187
  }
171
188
  if (!Check(DirectWorkflowSchema, value)) {
172
189
  const issue = Errors(DirectWorkflowSchema, value)[0];
173
- throw new Error(`direct workflow must match the declared tool schema${issue ? ` at ${issue.instancePath || "/"}: ${issue.message}` : ""}. Direct mode returns task answers without checked integration; use mode isolated for changesets.`);
190
+ throw new Error(`direct workflow must match the declared tool schema${issue ? ` at ${issue.instancePath || "/"}: ${issue.message}` : ""}. Direct mode returns task answers without checked integration in the shared checkout.`);
174
191
  }
175
192
  if (!mode) throw new Error("direct workflow must select exactly one of single, tasks, or chain.");
176
193
  const input = value as DirectInput;
@@ -178,6 +195,7 @@ export function parseWorkflow(value: unknown): ParsedWorkflow {
178
195
  const workflow: ParsedWorkflow = mode === "single" ? { mode, delegations: [normalizeDelegation(input as Static<typeof DelegationSchema>, "workflow")] }
179
196
  : mode === "parallel" ? { mode, delegations: input.tasks!.map((item, index) => normalizeDelegation(item, `tasks[${index}]`)) }
180
197
  : { mode, delegations: input.chain!.map((item, index) => normalizeDelegation(item, `chain[${index}]`)) };
198
+ if (mode === "parallel" && workflow.delegations.some(({ dependsOn }) => dependsOn !== undefined)) validateGraph(workflow.delegations);
181
199
  if (input.wait) workflow.wait = true;
182
200
  if (input.repositories) {
183
201
  workflow.repositories = parseRepositorySelection(input.repositories);
@@ -188,6 +206,38 @@ export function parseWorkflow(value: unknown): ParsedWorkflow {
188
206
  return workflow;
189
207
  }
190
208
 
209
+ /** Graph semantics apply only when a task explicitly supplies dependsOn. */
210
+ export const isDependencyGraph = (workflow: ParsedWorkflow): boolean =>
211
+ workflow.mode === "parallel" && workflow.delegations.some(({ dependsOn }) => dependsOn !== undefined);
212
+
213
+ function validateGraph(delegations: readonly Delegation[]): void {
214
+ const byName = new Map<string, Delegation>();
215
+ for (const task of delegations) {
216
+ if (byName.has(task.name)) throw new Error(`Duplicate task name ${JSON.stringify(task.name)} in dependency graph.`);
217
+ byName.set(task.name, task);
218
+ }
219
+ for (const task of delegations) {
220
+ const seen = new Set<string>();
221
+ for (const name of task.dependsOn ?? []) {
222
+ if (name === task.name) throw new Error(`Task ${JSON.stringify(task.name)} cannot depend on itself.`);
223
+ if (seen.has(name)) throw new Error(`Duplicate dependency ${JSON.stringify(name)} for ${JSON.stringify(task.name)}.`);
224
+ if (!byName.has(name)) throw new Error(`Unknown dependency ${JSON.stringify(name)} for ${JSON.stringify(task.name)}.`);
225
+ seen.add(name);
226
+ }
227
+ }
228
+ const visiting = new Set<string>();
229
+ const visited = new Set<string>();
230
+ const visit = (name: string) => {
231
+ if (visiting.has(name)) throw new Error(`Dependency cycle includes ${JSON.stringify(name)}.`);
232
+ if (visited.has(name)) return;
233
+ visiting.add(name);
234
+ for (const dependency of byName.get(name)!.dependsOn ?? []) visit(dependency);
235
+ visiting.delete(name);
236
+ visited.add(name);
237
+ };
238
+ for (const name of byName.keys()) visit(name);
239
+ }
240
+
191
241
  /** A direct request is a writer request when any task declares write access. */
192
242
  export const writesCheckout = (workflow: ParsedWorkflow): boolean => workflow.delegations.some(({ access }) => access === "write");
193
243
 
@@ -205,8 +255,7 @@ export function parseDelegateTask(value: unknown): ParsedDelegateTask {
205
255
  value = rest;
206
256
  }
207
257
  if (value && typeof value === "object" && !Array.isArray(value) && (value as { mode?: unknown }).mode === "isolated") {
208
- if (Object.hasOwn(value, "repositories")) return { mode: "workspace", request: parseWorkspaceRequest(value), dryRun };
209
- return { mode: "isolated", request: parseExecuteRequest(value), dryRun };
258
+ throw new Error("Isolated delegation is retired. Use mode direct for a task in the existing checkout.");
210
259
  }
211
260
  return { mode: "direct", workflow: parseWorkflow(value), dryRun };
212
261
  }
@@ -255,18 +304,26 @@ export async function snapshotCheckout(cwd: string): Promise<CheckoutSnapshot |
255
304
  const root = top.stdout.trim();
256
305
  if (top.code !== 0 || !root) throw new Error(`git rev-parse exited ${top.code}: ${top.stderr.trim() || "no diagnostic"}`);
257
306
  const head = (await git(root, ["rev-parse", "--verify", "--quiet", "HEAD"], [0, 1])).stdout.trim() || undefined;
258
- // Porcelain paths are repository-relative; an index or worktree rename or copy lists its source after the destination.
259
- const fields = (await git(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"])).stdout.split("\0");
307
+ // Porcelain v2 includes index object IDs, modes and all conflict stages in one Git read.
308
+ const status = await runProcess("git", ["--no-optional-locks", "status", "--porcelain=v2", "-z", "--untracked-files=all"], { cwd: root, timeoutMs: 30_000 });
309
+ if (status.code !== 0 || status.killed || status.stdoutTruncated) throw new Error(`Incomplete Git status: ${status.stderr.trim() || "status failed or exceeded the output limit"}`);
310
+ const fields = status.stdout.split("\0");
260
311
  const entries = new Map<string, string>();
261
312
  for (let index = 0; index < fields.length; index++) {
262
- const field = fields[index]!;
263
- if (!field) continue;
264
- const status = field.slice(0, 2);
265
- entries.set(field.slice(3), status);
266
- if (/[RC]/.test(status)) entries.set(fields[++index]!, status);
313
+ const record = fields[index]!;
314
+ if (!record || record.startsWith("# ") || record.startsWith("! ")) continue;
315
+ // Fixed metadata fields precede the unescaped path, which can contain any whitespace.
316
+ const pattern = { "1": /^((?:[^ ]+ ){8})([\s\S]+)$/, "2": /^((?:[^ ]+ ){9})([\s\S]+)$/, u: /^((?:[^ ]+ ){10})([\s\S]+)$/, "?": /^(\? )([\s\S]+)$/ }[record[0]!];
317
+ const match = pattern?.exec(record);
318
+ if (!match) throw new Error("Invalid Git status record");
319
+ entries.set(match[2]!, match[1]!);
320
+ if (record.startsWith("2 ")) {
321
+ const original = fields[++index];
322
+ if (!original) throw new Error("Missing original path in Git rename record");
323
+ entries.set(original, match[1]!);
324
+ }
267
325
  }
268
- // Status alone misses a further edit to a path that was already dirty.
269
- for (const [path, status] of entries) entries.set(path, `${status} ${await contentIdentity(posix.join(root, path))}`);
326
+ for (const [path, metadata] of entries) entries.set(path, metadata + await contentIdentity(posix.join(root, path)));
270
327
  const fingerprint = createHash("sha256").update(JSON.stringify([head ?? null, [...entries].sort()])).digest("hex");
271
328
  return { ...(head === undefined ? {} : { head }), entries, fingerprint };
272
329
  }
@@ -317,7 +374,7 @@ export async function checkoutNote(cwd: string, before: CheckoutSnapshot | Error
317
374
  }
318
375
  }
319
376
 
320
- export type WorkflowEntry = { id: string; index: number; delegation: Delegation };
377
+ export type WorkflowEntry = { id: string; index: number; delegation: Delegation; references?: (AnswerReference | undefined)[] };
321
378
  export function identifyWorkflowEntries(toolCallId: string, workflow: ParsedWorkflow): WorkflowEntry[] {
322
379
  return workflow.delegations.map((delegation, index) => ({ id: `${toolCallId}:${workflow.mode}:${index}`, index, delegation }));
323
380
  }
@@ -337,6 +394,7 @@ export async function runForegroundWorkflow(
337
394
  entries: readonly WorkflowEntry[],
338
395
  run: DelegationRunner,
339
396
  signal?: AbortSignal,
397
+ onInvalidTask?: (entry: WorkflowEntry, error: unknown) => void,
340
398
  ): Promise<void> {
341
399
  signal?.throwIfAborted();
342
400
  if (mode === "single" || mode === "parallel") {
@@ -346,13 +404,71 @@ export async function runForegroundWorkflow(
346
404
  }
347
405
  let previous = "";
348
406
  for (const entry of entries) {
349
- const selected = {
350
- ...entry,
351
- delegation: { ...entry.delegation, task: entry.delegation.task.replaceAll("{previous}", () => previous) },
352
- };
407
+ let task: string;
408
+ try { task = expandChainTask(entry.delegation.task, previous); }
409
+ catch (error) {
410
+ if (!onInvalidTask) throw error;
411
+ onInvalidTask(entry, error);
412
+ break;
413
+ }
414
+ const selected = { ...entry, delegation: { ...entry.delegation, task } };
353
415
  const output = await runEntry(selected, run);
354
416
  signal?.throwIfAborted();
355
417
  if (output === undefined) break;
356
418
  previous = output;
357
419
  }
358
420
  }
421
+
422
+ /** Dispatch a validated graph. A writer waits for all workers; ready readers can overlap. */
423
+ export async function runDependencyGraph(
424
+ entries: readonly WorkflowEntry[],
425
+ run: DelegationRunner,
426
+ blocked: (entry: WorkflowEntry, prerequisites: readonly string[]) => void,
427
+ signal?: AbortSignal,
428
+ canDispatch: () => boolean = () => true,
429
+ answerReferences: ReadonlyMap<string, AnswerReference> = new Map(),
430
+ ): Promise<void> {
431
+ const results = new Map<string, { success: true; output: string } | { success: false }>();
432
+ const pending = new Set(entries);
433
+ const running = new Map<WorkflowEntry, Promise<void>>();
434
+ let writerRunning = false;
435
+ const start = (entry: WorkflowEntry) => {
436
+ pending.delete(entry);
437
+ const dependencies = entry.delegation.dependsOn ?? [];
438
+ const { task, references } = prerequisitePacket(entry.delegation.task, dependencies.map((name) => {
439
+ const output = (results.get(name) as { success: true; output: string }).output;
440
+ return { name, output, complete: true, fullAnswer: answerReferences.get(name) };
441
+ }));
442
+ const write = entry.delegation.access === "write";
443
+ if (write) writerRunning = true;
444
+ const promise = (async () => {
445
+ try { results.set(entry.delegation.name, { success: true, output: await Promise.resolve().then(() => run({ ...entry, references, delegation: { ...entry.delegation, task } })) }); }
446
+ catch { results.set(entry.delegation.name, { success: false }); }
447
+ finally { running.delete(entry); if (write) writerRunning = false; }
448
+ })();
449
+ running.set(entry, promise);
450
+ };
451
+ while (pending.size || running.size) {
452
+ if (!signal?.aborted) {
453
+ let changed = true;
454
+ while (changed) {
455
+ changed = false;
456
+ for (const entry of pending) {
457
+ const dependencies = entry.delegation.dependsOn ?? [];
458
+ const failed = dependencies.filter((name) => results.get(name)?.success === false);
459
+ if (failed.length) {
460
+ pending.delete(entry); results.set(entry.delegation.name, { success: false }); blocked(entry, failed); changed = true;
461
+ continue;
462
+ }
463
+ if (!canDispatch() || !dependencies.every((name) => results.has(name)) || writerRunning) continue;
464
+ if (entry.delegation.access === "write" && running.size) continue;
465
+ start(entry); changed = true;
466
+ if (writerRunning) break;
467
+ }
468
+ }
469
+ }
470
+ if (!running.size) break;
471
+ await Promise.race(running.values());
472
+ }
473
+ signal?.throwIfAborted();
474
+ }
@@ -1,83 +1,25 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { createCanonicalGitRootResolver } from "../dist/composition.js";
3
- import { CheckedGitRuntime } from "../dist/git-runtime.js";
4
- import { HerdrHostRuntime } from "../dist/herdr-runtime.js";
5
- import { RoleLaunchRuntime } from "../dist/launch-runtime.js";
6
- import { WorkspaceRunner } from "../dist/workspace.js";
7
- import { WorkspaceActionSchema, type WorkspaceRequest, type WorkspaceState } from "../dist/workspace-schema.js";
8
- import type { ExecutionPolicySnapshot } from "../dist/schema.js";
9
- import { workerOutputForMain } from "./result-transport.ts";
10
- import { captureFallbackWarning } from "./task-model-fallback.ts";
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { Check } from "typebox/value";
4
+ import { IdOnlySchema } from "../dist/schema.js";
5
+ import { createWorkspaceCleanupRunner, readWorkspaceStatus, type WorkspaceRunner } from "../dist/workspace.js";
6
+ import type { WorkspaceState } from "../dist/workspace-schema.js";
11
7
 
12
- /** Workspace requests keep their own versioned set state; scalar requests retain their existing contract. */
13
- export function registerWorkspaceExtension(pi: ExtensionAPI, policy: () => ExecutionPolicySnapshot) {
14
- let current: ExtensionContext | undefined, epoch = 0;
15
- const jobs = new Map<AbortController, { session: string; epoch: number; accepted: boolean }>();
16
- const git = new CheckedGitRuntime();
17
- const host = (saved: ExecutionPolicySnapshot) => new HerdrHostRuntime({
18
- inspectInFlightTaskCandidate: git.inspectInFlightTaskCandidate.bind(git),
19
- executionBudget: () => ({ maxTurns: saved.maxTurns, maxMs: saved.childMaxMs, ...(saved.maxTokens === undefined ? {} : { maxTokens: saved.maxTokens }) }),
20
- });
21
- const coordinator = new RoleLaunchRuntime({ pi, context: () => {
22
- policy();
23
- if (!current) throw new Error("Workspace Role launch has no current Pi context.");
24
- return current;
25
- }, captureFallbackWarning: (signal) => {
26
- if (!current) throw new Error("Workspace Role launch has no current Pi context.");
27
- const ctx = current, capturedEpoch = epoch, sessionId = ctx.sessionManager.getSessionId();
28
- return captureFallbackWarning(pi, ctx, () => epoch === capturedEpoch && current?.sessionManager.getSessionId() === sessionId, signal);
29
- }, resolveRoot: createCanonicalGitRootResolver(), inspectMainBase: git.inspectMainBase.bind(git) });
30
- const runner = new WorkspaceRunner({ coordinator, git, policy, host,
31
- preflightHost: async (root, operation) => await host(policy()).preflightHost({ root, nonGitWorkspace: true }, operation) });
32
- const stop = () => { epoch++; for (const controller of jobs.keys()) controller.abort(); };
33
- pi.on("session_start", (_event, ctx) => { stop(); current = ctx; });
34
- pi.on("session_shutdown", () => { stop(); current = undefined; });
35
- pi.on("model_select", (event, ctx) => { current = { ...ctx, model: event.model }; });
8
+ export function registerWorkspaceExtension(pi: ExtensionAPI, runner?: Pick<WorkspaceRunner, "status" | "action">) {
9
+ const parameters = Type.Object({ ...IdOnlySchema.properties, action: Type.Union([Type.Literal("status"), Type.Literal("cleanup")]) }, { additionalProperties: false });
36
10
  const result = (state: WorkspaceState) => {
37
11
  // Keep identities complete. Check output stays in the private state, not in a large inline dump.
38
12
  const evidence = (value: WorkspaceState["final"]) => value && { ...value, results: value.results.map(({ stdout: _stdout, stderr: _stderr, ...item }) => item) };
39
13
  const details = { ...state, preliminary: evidence(state.preliminary), final: evidence(state.final) };
40
14
  return { content: [{ type: "text" as const, text: `Workspace ${state.request.id}: ${state.status}. ${state.failure ?? ""}\n${JSON.stringify(details)}` }], details };
41
15
  };
42
- pi.registerTool({ name: "subagent_workspace", label: "Subagent workspace", exposure: "model-only",
43
- description: "Inspect or act on one explicit multi-repository request. stage takes the complete candidate set as expected; validate and promote take the complete integration tip set. Promotion is serial, not atomic. After any interrupted or partial promotion, reconcile first, then explicitly promote remaining targets. abort retains work; cleanup removes only fully promoted, clean, exactly owned resources. No rollback or automatic replay.",
44
- parameters: WorkspaceActionSchema,
45
- async execute(_id, params, signal, _update, ctx) { current = ctx; return result(await runner.action(params, ctx.cwd, signal)); },
46
- });
47
- return {
48
- hasPendingResult: (session: string) => [...jobs].some(([controller, job]) => job.session === session && job.epoch === epoch && job.accepted && !controller.signal.aborted),
49
- async plan(request: WorkspaceRequest, signal: AbortSignal | undefined, ctx: ExtensionContext) {
50
- current = ctx;
51
- const plan = await runner.plan(request, ctx.cwd, signal);
52
- return { content: [{ type: "text" as const, text: `Workspace dry run passed. No resources created. Not checked: Herdr host, admission, worker, or checks.\n${JSON.stringify(plan)}` }], details: { dryRun: true, ...plan } };
53
- },
54
- async execute(request: WorkspaceRequest, signal: AbortSignal | undefined, ctx: ExtensionContext) {
55
- current = ctx;
56
- const controller = new AbortController(), job = { session: ctx.sessionManager.getSessionId(), epoch, accepted: false };
57
- jobs.set(controller, job);
58
- const abort = () => controller.abort(signal?.reason);
59
- if (signal?.aborted) abort(); else signal?.addEventListener("abort", abort, { once: true });
60
- let accept!: (state: WorkspaceState) => void, reject!: (error: unknown) => void;
61
- const accepted = new Promise<WorkspaceState>((resolve, fail) => { accept = resolve; reject = fail; });
62
- const deliverable = () => epoch === job.epoch && current?.sessionManager.getSessionId() === job.session && ctx.sessionManager.getSessionId() === job.session;
63
- void runner.execute(request, ctx.cwd, controller.signal, (state) => {
64
- job.accepted = true; signal?.removeEventListener("abort", abort); accept(state);
65
- }).then((state) => {
66
- jobs.delete(controller);
67
- if (!deliverable()) return;
68
- try { pi.sendMessage({ customType: "pi-subagent-workspace-result", content: workerOutputForMain(result(state).content[0]!.text), display: true }, { triggerTurn: true, deliverAs: "followUp" }); }
69
- catch { console.error("Workspace result delivery failed; inspect subagent_workspace status. Saved resources are retained."); }
70
- }, (error: unknown) => {
71
- jobs.delete(controller); signal?.removeEventListener("abort", abort);
72
- if (!job.accepted) { reject(error); return; }
73
- if (deliverable()) {
74
- try { pi.sendMessage({ customType: "pi-subagent-workspace-result", content: `Workspace ${request.id} stopped. Inspect subagent_workspace status before recovery.`, display: true }, { triggerTurn: true, deliverAs: "followUp" }); }
75
- catch { console.error("Workspace failure delivery failed; saved resources are retained."); }
76
- }
77
- });
78
- const state = await accepted;
79
- if (!deliverable()) throw new Error("Workspace request was saved, but its launching session changed. Inspect subagent_workspace status.");
80
- return { content: [{ type: "text" as const, text: `Workspace ${state.request.id} saved; one worker will receive the complete selected worktree map. Use subagent_workspace status. No repository is promoted automatically.` }], details: { id: state.request.id, root: state.root } };
16
+ pi.registerTool({
17
+ name: "subagent_workspace", label: "Saved workspace", exposure: "model-only",
18
+ description: "Inspect a saved multi-repository request or explicitly clean up its promoted resources.", parameters,
19
+ async execute(_id, params, signal, _update, ctx) {
20
+ if (!Check(parameters, params)) throw new Error("Saved workspaces support only status and cleanup.");
21
+ if (params.action === "status") return result(await (runner ? runner.status(ctx.cwd, params.id) : readWorkspaceStatus(ctx.cwd, params.id)));
22
+ return result(await (runner ?? createWorkspaceCleanupRunner()).action(params, ctx.cwd, signal));
81
23
  },
82
- };
24
+ });
83
25
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "30.0.0",
4
- "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
3
+ "version": "31.0.0",
4
+ "description": "Run bounded Pi workers in the current checkout and see their progress in a native widget.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi",
@@ -41,9 +41,9 @@
41
41
  "pack:check": "npm pack --dry-run"
42
42
  },
43
43
  "peerDependencies": {
44
- "@earendil-works/pi-ai": "^1.5.0",
45
- "@earendil-works/pi-coding-agent": "^1.5.0",
46
- "@earendil-works/pi-tui": "^1.5.0",
44
+ "@earendil-works/pi-ai": "^1.8.0",
45
+ "@earendil-works/pi-coding-agent": "^1.8.0",
46
+ "@earendil-works/pi-tui": "^1.8.0",
47
47
  "typebox": "^1.3.15"
48
48
  },
49
49
  "repository": {
@@ -77,9 +77,9 @@
77
77
  "proper-lockfile": "^4.1.2"
78
78
  },
79
79
  "devDependencies": {
80
- "@earendil-works/pi-ai": "1.5.0",
81
- "@earendil-works/pi-coding-agent": "1.5.0",
82
- "@earendil-works/pi-tui": "1.5.0",
80
+ "@earendil-works/pi-ai": "1.8.0",
81
+ "@earendil-works/pi-coding-agent": "1.8.0",
82
+ "@earendil-works/pi-tui": "1.8.0",
83
83
  "@types/proper-lockfile": "^4.1.4"
84
84
  }
85
85
  }
@@ -1,41 +1,19 @@
1
1
  ---
2
2
  name: pi-subagent
3
- description: Delegate bounded direct work or run durable checked isolated task graphs.
3
+ description: Delegate a scoped task to a native Pi worker in the existing checkout.
4
4
  ---
5
5
 
6
- # Choose and authorize delegation
7
-
8
- Use this Skill only from Main.
9
-
10
- Record the requested outcome, allowed scope and exclusions, local delegation/check/review/integration permission, and any external-action permission before substantial work. A clear small request can supply this authorization directly. Ask again only for a material scope or contract change, a missing decision or authorization, a user-owned conflict, or a consequential action outside that scope.
11
-
12
- Keep trivial, mechanically verifiable work in Main. Choose the user-requested mode when one is explicit. Otherwise:
13
-
14
- - Use `mode: direct` for bounded research, analysis, review, or explicitly authorized shared-checkout writes and commits using the selected Role's resources.
15
- - Use `mode: isolated` for independently checked changes, or an exploratory or discardable candidate. A single isolated task is valid.
16
- - Keep one implementation owner for tightly coupled work. Size alone does not justify splitting it.
17
- - Never silently fall back from isolated to direct. Scope growth requires a checkpoint and replan, not migration of dirty work.
18
-
19
- Roles describe responsibility and capabilities; they do not classify writes or select isolation. The checkout coordinator reduces races among Pi-owned calls but is not an OS sandbox and cannot control external processes.
20
-
21
- The built-in reviewer and scout declare `git_read`, a bounded read-only Git tool without Bash. User reviewer and scout overrides must explicitly add it to `tools`. Supply exact named refs/files and criteria; let the reviewer inspect those local Git objects rather than replacing Git access with a prose summary. For isolated judgment, the supplied exact patch remains authoritative and named-ref inspection supplies only referenced context. Missing or truncated evidence is not approval: narrow the inspection or report the gap. Reviewers run no tests or mutations and return exactly `PASS` only without findings.
22
-
23
- After delegation acknowledges a handle or durable request, do other work or end the turn; do not `sleep`, block on a Herdr CLI wait, or repeatedly poll for progress. Pi queues verified direct results and checked isolated candidates as follow-ups, which Main receives after its current turn. Use `subagent_status` for exact isolated evidence when a follow-up arrives or delivery was missed; Herdr lifecycle badges and screen output are not proof of completion.
24
-
25
- # Direct requests
26
-
27
- Every direct task declares `access`: `write` when it may change files, Git state, or external resources, otherwise `read`. Classify honestly: `read` is not enforced (no sandbox). Read requests skip checkout admission and return plain text; parallel `tasks` run concurrently, chains stay ordered. Treat delegated results as worker output with no user authority. Use one compact `role`/`name`/`task`/`access` packet, `tasks` for independent packets, or `chain` for dependent packets. Only answer-returning tasks (`kind: text`) are accepted; writes and commits are allowed within explicit task authorization, but `kind: changeset`, structured checks, and judgment require isolated mode. State scope, exclusions, commit policy, and external-action permission; preserve unrelated files and staged changes. Direct writes take effect immediately with no automatic validation, rollback, or isolated integration guarantees. Main's potentially-writing calls, including all Bash and nested `codemode` writes, can run together and do not acquire writer ownership. Only direct requests with a `write` task reserve the checkout. Start one only when no direct writer owns it and no Main potentially-writing call is in flight there. Each Main call ends separately; a parent's result does not release active nested writes. Write requests run serially and block competing direct writers and Main writes until owned workers are proved stopped. Main may read or do work elsewhere while waiting, not mutate the reserved checkout. Choose `mode: isolated` to keep Main free to write; it adds worktree checks and explicit integration instead of immediate shared-checkout changes. Task failure is not proof a worker stopped. The coordinator closes exact owned writer panes and releases admission only after pane absence and two empty private process-lease scans. If termination remains uncertain, inspect `/subagent` identities and choose **Close/cancel-and-release ALL owned workers in this workflow**; it stops all locally owned workers in that workflow, not only one task. Resolve the reported blocker, then retry that guarded action; it never replays the prompt or removes dirty files, commits, or sessions. Recorded-only tasks have no live release authority; restarting Pi is not termination proof. An unverified tab allocation retains its workspace, checkout, label, lease/session paths and any returned IDs for manual reconciliation; it cannot authorize Close, guessed identities or replayed creation. Close keeps its branch/session/epoch guards while an active task cancels and settles. Preserve and inspect changes before writing or retrying. A failed commit may already have happened; never replay it blindly. The tool returns a handle after launching Herdr tabs in the current workspace. Main receives the verified result as a follow-up after the workflow finishes, without interrupting an active turn. If observation stops, open `/subagent` to inspect exact recorded tabs and session files on this session branch; recorded does not prove still running.
28
-
29
- To build on a finished direct worker, add `continueFrom` with its reference (such as `D7.1`) and the same `role`. The worker resumes its saved Pi session in a new tab, so continue it for follow-up questions, corrections, or the next step on the same evidence. Start a fresh task for unrelated work, a different Role, or when the earlier context is stale, wrong, or large. Continuation fails before launch for an unknown reference, a different Role, a worker still owned by an active task, a missing or oversized session, an unfinished last turn, or a busy old agent; do not retry it blindly. The user can stop one running worker of a read-only workflow with **Stop this worker** in `/subagent`; that entry fails with `Stopped by user from /subagent` and its siblings continue.
30
-
31
- # Isolated requests
32
-
33
- Give the request a unique ID and goal. Give each task a unique ID, kind, Role, model class, bounded requirements, deliverable, `dependsOn`, and `contextFrom`. Changesets require focused task checks, and a graph containing changesets requires final checks. The root must have a `package.json` test script; `pnpm test` is added to final checks if missing and runs against the combined tip before Main promotion. Text context may name only completed text tasks, preserves declared order, and implies a scheduling dependency; do not repeat an edge in `dependsOn` and `contextFrom`.
34
-
35
- Every changeset becomes ready automatically after preliminary checks pass. While a locally owned changeset task is actively working, the user may open `/subagent` to queue bounded same-worker revisions or withdraw all still-pending instructions into the native editor and submit one replacement. Cancellation after withdrawal leaves the originals removed; already-claimed instructions cannot be recalled. Each revision must produce a new clean commit and rerun preliminary checks. If a worker's turn ends with uncommitted changes, the runner sends it one commit reminder per attempt; this uses no correction, and a worktree still dirty afterwards needs attention. When no queued revision remains, the runner seals and durably records the exact ready candidate without waiting for sibling workers. There is no guaranteed post-completion editing window, and late follow-ups fail visibly.
36
-
37
- A ready candidate does not integrate automatically. Each checked worker triggers a follow-up while its siblings continue; inspect `subagent_status` and immediately use `subagent_stage` with the exact `generation`, `taskId`, `attempt`, candidate `tip`, and `expectedTip` to select and merge it into the owned integration checkout. Stage and resolve are available during the active wave; wait for the wave to settle before rejecting or revising. Resolve conflicts in the integration checkout and verify with `resolve`; never edit Main to resolve them. For dependents, `subagent_integrate advance` acknowledges a durable background wave, then reports checked candidates as they finish. When selected work is staged and the wave settles, use `subagent_integrate validate` on the exact `combinedTip`: it acknowledges saved intent, runs full root checks and optional final judgment in the session-owned background, then sends a follow-up. Acknowledgement is not passing evidence; `promote` requires passing evidence and unchanged Main. One Main-authored committed correction to a definitively failed combined validation can be recorded with `correct`, then revalidated. Only proven promotion triggers selected-worker termination and verified cleanup. Failures, ambiguity, conflicts, interruption, child-limit exhaustion, or Main drift retain work and never waive checks or identity guards. The extension never pushes, opens a pull request, publishes, or deploys.
38
-
39
- After a coordinator interruption in the canonical repository, ask the user to run `/subagent recover` once; if another productive run holds the lease, wait and run it again. It acquires the productive lease, classifies interrupted work, preserves invalid files and retained work, and sends Main one follow-up with blockers and next actions. A live productive lease is read-only and cannot be taken over. Recovery never replays prompts, merges, promotion, or cleanup. For leftover merged worker or integration checkouts, ask the user to run `/subagent prune`; it removes only reviewed, confirmed, merged, clean, unowned items. Use `subagent_status` to inspect exact durable state without mutation, including candidate identities, generations, and retained resources. `subagent_resume` handles only the reported retry/verify/finalize continuation; it cannot replace Main's stage/integrate decisions or reset policy/corrections. For a retry that sends a same-worker correction, pass `instruction` to name the exact fixes, including the review or check findings the worker must address; the correction prompt carries only a short saved failure. Follow-ups show a short preview of a failed review verdict; `subagent_status` returns it in full. `subagent_stage reject` or `revise` freezes a generation containing the candidate and invalidates dependent attempts; restage chosen work in a new generation. If Main advances cleanly before promotion, use `subagent_integrate refresh` with exact old/new Main and combined-tip identities; restage immutable candidates into the new generation and rerun combined validation. Dirty or divergent Main blocks refresh. For interrupted validation, prove old coordinator/check processes stopped, then guarded `reconcile` classifies the exact generation; never resume a live lease. A `validation_failed` generation without checks, review, or a prior combined correction can `refresh` with identical `expectedMain`/`newMain`, the old exact combined `expectedTip`, and the next generation number. Main and the retained integration tip must be exact and clean. Restage immutable candidates explicitly and rerun all final gates in the new checkout; never replay old uncertain checks, infer passing evidence, or reset correction allowances. At most two unreleased integration worktrees may coexist. Rejected candidates and superseded generations remain retained until Main explicitly calls `subagent_integrate release` with the exact generation and tip; for a rejected worker include its task ID and attempt after releasing all generations using it. Dirty/conflicted or unproved resources block release without force deletion. Impossible fresh dependent work after rejection needs a new request. `subagent_abort` cannot discard retained candidates or integration generations; release them first. For workers without candidates, abort cleans only proven unchanged, clean owned resources. If cleanup is deferred or blocked, inspect status and repeat abort after resolving the blocker. Dirty or committed work and uncertain allocations remain for manual recovery. To delete owned isolated worktrees, ask the user to run `/subagent` and choose **Close and delete worktrees (discard work)**; agents cannot trigger it. Old v4 state is rejected (current state is v5), not migrated. Status, abort, process I/O, termination, and verified post-promotion cleanup keep finite safety budgets.
40
-
41
- All launches use the global policy in `config/pi-subagent/config.json`: productive concurrency, per-child turns/tokens, and idle timeout. Ephemeral children also have a hard runtime limit; isolated requests have a correction cap. Productive requests have no whole-run wall-clock deadline. Request fields cannot replenish or override limits.
6
+ Use `delegate_task` from Main when delegation saves work or a separate context improves review. The Pi widget displays active workers. For tool parameters use `mode: direct` and the shared checkout.
7
+
8
+ - Choose exactly one form. For one worker, supply `role`, `name`, `task`, and `access` at the top level. For a batch, put those fields inside `tasks` or `chain` only. Use names of at most 29 characters. Omit `id` on launch. Pi assigns it. Use `scout` for discovery, `reviewer` for review, and `implementer` for edits.
9
+ - Use `access: read` for research. Put filenames in the task and omit `paths`. Read access has no sandbox.
10
+ - Use `access: write` for any possible mutation. State the allowed files, test commands, commit policy, and external permissions. Preserve unrelated changes. Writes take effect immediately.
11
+ - Use `tasks` for independent packets. Reads can run concurrently. Use `dependsOn` with exact task names for prerequisites. Each writer runs alone within its request.
12
+ - Give a writer `verification` with acceptance `criteria` and `checks`. Each check requires `executable`, `args`, and `timeoutMs`. A definite failure permits one correction.
13
+ - Use `chain` for dependent steps. Insert `{previous}` in a later task to pass the complete prior answer.
14
+ - Omit `repositories` unless selecting existing repositories in a multi-repository workspace. Never create a worktree or open a Herdr tab for delegation.
15
+ - After the tool returns a handle, yield or continue independent work. Pi groups ready results into one follow-up. Do not sleep or poll. Use `wait: true` when the caller needs the result inline.
16
+ - Verify each result and its test evidence. Use `continueFrom` with the same Role for a correction after confirmed termination. Open `/subagent` to inspect worker sessions or stop a worker.
17
+ - After a same-host restart, Pi dispatches eligible unstarted reads. Use the grouped result to inspect blocked steps. Inspect any uncertain write before further edits.
18
+ - To cancel a workflow, use `mode: cancel` and its exact `id`. Inspect partial changes before retrying. Release a checkout only after Pi verifies termination.
19
+ - Use `subagent_status` to inspect an old isolated request. An explicit requirement for isolated changes needs a different workflow. Never reinterpret it as permission to edit the shared checkout.