@henryqw/pi-subagent 30.1.0 → 31.1.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 (41) hide show
  1. package/CONTEXT.md +2 -2
  2. package/README.md +19 -23
  3. package/dist/direct-herdr.d.ts +5 -0
  4. package/dist/direct-herdr.js +9 -1
  5. package/dist/ephemeral.d.ts +9 -3
  6. package/dist/ephemeral.js +70 -11
  7. package/dist/herdr-runtime.js +4 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/native-host.d.ts +96 -0
  11. package/dist/native-host.js +243 -0
  12. package/dist/runner.d.ts +8 -1
  13. package/dist/runner.js +22 -15
  14. package/dist/schema.d.ts +71 -2
  15. package/dist/schema.js +14 -1
  16. package/dist/workspace-schema.d.ts +11 -0
  17. package/dist/workspace.d.ts +5 -2
  18. package/dist/workspace.js +58 -29
  19. package/docs/measurement.md +12 -1
  20. package/docs/orchestration-architecture.html +4 -4
  21. package/docs/orchestration-architecture.svg +2 -2
  22. package/docs/orchestration.md +72 -259
  23. package/docs/workspace.md +4 -80
  24. package/extensions/admission.ts +36 -11
  25. package/extensions/direct-check-exec.py +91 -0
  26. package/extensions/direct-check-supervisor.mjs +42 -0
  27. package/extensions/direct-check-witness.mjs +34 -0
  28. package/extensions/direct-native.ts +17 -5
  29. package/extensions/direct-outbox.ts +189 -0
  30. package/extensions/direct-owner.ts +49 -0
  31. package/extensions/direct-verification.ts +73 -0
  32. package/extensions/isolated.ts +25 -301
  33. package/extensions/prerequisite-evidence.ts +81 -0
  34. package/extensions/result-transport.ts +6 -4
  35. package/extensions/subagent-command.ts +12 -7
  36. package/extensions/subagent.ts +378 -499
  37. package/extensions/workflow-recovery.ts +359 -0
  38. package/extensions/workflow.ts +156 -40
  39. package/extensions/workspace.ts +16 -74
  40. package/package.json +2 -2
  41. package/skills/pi-subagent/SKILL.md +15 -37
package/dist/workspace.js CHANGED
@@ -7,6 +7,8 @@ import { lock } from "proper-lockfile";
7
7
  import { Check } from "typebox/value";
8
8
  import { CheckedGitRuntime } from "./git-runtime.js";
9
9
  import { IntegrationGit } from "./integration-git.js";
10
+ import { HerdrHostRuntime } from "./herdr-runtime.js";
11
+ import { NativeHostRuntime } from "./native-host.js";
10
12
  import { FileRunStore } from "./store.js";
11
13
  import { runProcess } from "./process.js";
12
14
  import { runGit } from "./git-process.js";
@@ -70,6 +72,39 @@ export async function workspacePruneOwners(checkouts, agentDir) {
70
72
  }
71
73
  return owners;
72
74
  }
75
+ function workspaceDirectory(root, id, agentDir) {
76
+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id.length > 80)
77
+ throw new Error("Invalid workspace request ID.");
78
+ const directory = resolve(extensionConfigDir("pi-subagent", agentDir), "workspace-state", hash(root), id);
79
+ if (directory === root || directory.startsWith(`${root}/`))
80
+ throw new Error("Workspace state must be outside the workspace.");
81
+ return directory;
82
+ }
83
+ export async function readWorkspaceStatus(cwd, id, agentDir) {
84
+ const root = await realpath(cwd), path = join(workspaceDirectory(root, id, agentDir), "state.json");
85
+ const stat = await lstat(path);
86
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || await realpath(path) !== path)
87
+ throw new Error("Workspace state is not an exact private regular file.");
88
+ const state = parseWorkspaceState(JSON.parse(await readTextFileBounded(path, 2 * 1024 * 1024)));
89
+ if (state.root !== root || state.request.id !== id)
90
+ throw new Error("Workspace state address changed.");
91
+ return state;
92
+ }
93
+ /** Construct a runner for saved cleanup without enabling launches or allocation. */
94
+ export function createWorkspaceCleanupRunner(agentDir) {
95
+ const disabled = () => { throw new Error("Workspace cleanup cannot launch or allocate resources."); };
96
+ const coordinator = { now: disabled, randomToken: disabled, preflight: disabled, acquireLaunch: disabled };
97
+ const executor = { run: disabled, withLimits: disabled };
98
+ const git = new CheckedGitRuntime();
99
+ const herdr = new HerdrHostRuntime({ inspectInFlightTaskCandidate: git.inspectInFlightTaskCandidate.bind(git) });
100
+ const host = new NativeHostRuntime(herdr, coordinator, executor, git, agentDir);
101
+ const runner = new WorkspaceRunner({ coordinator, host: () => host, policy: disabled, agentDir, git });
102
+ return { action: async (value, cwd, signal) => {
103
+ if (!value || typeof value !== "object" || !("action" in value) || value.action !== "cleanup")
104
+ throw new Error("This runner supports only workspace cleanup.");
105
+ return await runner.action(value, cwd, signal);
106
+ } };
107
+ }
73
108
  /** A whole repository set is the validation unit. Git mutations remain serial, never atomic. */
74
109
  export class WorkspaceRunner {
75
110
  git;
@@ -83,33 +118,19 @@ export class WorkspaceRunner {
83
118
  this.integration = options.integration ?? new IntegrationGit();
84
119
  this.store = new FileRunStore(options.agentDir);
85
120
  }
86
- directory(root, id) {
87
- if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id.length > 80)
88
- throw new Error("Invalid workspace request ID.");
89
- const directory = resolve(extensionConfigDir("pi-subagent", this.options.agentDir), "workspace-state", hash(root), id);
90
- if (directory === root || directory.startsWith(`${root}/`))
91
- throw new Error("Workspace state must be outside the workspace.");
92
- return directory;
93
- }
94
121
  async save(state) {
95
122
  parseWorkspaceState(state);
96
123
  const text = JSON.stringify(state);
97
124
  if (Buffer.byteLength(text) > 2 * 1024 * 1024)
98
125
  throw new Error("Workspace state exceeds 2 MiB; resources are retained.");
99
- await writePrivateTextFileAtomically(join(this.directory(state.root, state.request.id), "state.json"), text);
126
+ await writePrivateTextFileAtomically(join(workspaceDirectory(state.root, state.request.id, this.options.agentDir), "state.json"), text);
127
+ this.options.onStateSaved?.(state);
100
128
  }
101
129
  async status(cwd, id) {
102
- const root = await realpath(cwd), path = join(this.directory(root, id), "state.json");
103
- const stat = await lstat(path);
104
- if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || await realpath(path) !== path)
105
- throw new Error("Workspace state is not an exact private regular file.");
106
- const state = parseWorkspaceState(JSON.parse(await readTextFileBounded(path, 2 * 1024 * 1024)));
107
- if (state.root !== root || state.request.id !== id)
108
- throw new Error("Workspace state address changed.");
109
- return state;
130
+ return readWorkspaceStatus(cwd, id, this.options.agentDir);
110
131
  }
111
132
  async locked(scope, id, operation) {
112
- const directory = this.directory(scope.root, id);
133
+ const directory = workspaceDirectory(scope.root, id, this.options.agentDir);
113
134
  await mkdir(directory, { recursive: true, mode: 0o700 });
114
135
  if (await realpath(directory) !== directory)
115
136
  throw new Error("Workspace state directory is not canonical.");
@@ -156,7 +177,7 @@ export class WorkspaceRunner {
156
177
  }
157
178
  async execute(value, cwd, signal = new AbortController().signal, accepted) {
158
179
  const plan = await this.plan(value, cwd, signal);
159
- await this.options.preflightHost(plan.scope.root, context(signal));
180
+ await this.options.preflightHost?.(plan.scope.root, context(signal));
160
181
  return await this.locked(plan.scope, plan.request.id, async () => {
161
182
  const { request, scope, bases, scripts } = plan;
162
183
  const policy = this.options.policy();
@@ -166,7 +187,7 @@ export class WorkspaceRunner {
166
187
  state.repositories[name] = { ...repo, base: bases[name], ...(scripts[name] === undefined ? {} : { testScript: scripts[name] }),
167
188
  attempt: { number: 1, waveNumber: 1, waveBase: bases[name], correlationToken: randomBytes(12).toString("hex"), allocationGeneration: 1, allocations: [], prompts: [], cleanup: CLEANUP_KINDS.map((kind) => ({ kind, status: "pending" })) } };
168
189
  // Exclusive creation prevents replay, including a prior crash before the first allocation.
169
- const file = await open(join(this.directory(scope.root, request.id), "state.json"), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
190
+ const file = await open(join(workspaceDirectory(scope.root, request.id, this.options.agentDir), "state.json"), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
170
191
  try {
171
192
  await file.writeFile(JSON.stringify(parseWorkspaceState(state)));
172
193
  await file.sync();
@@ -174,7 +195,7 @@ export class WorkspaceRunner {
174
195
  finally {
175
196
  await file.close();
176
197
  }
177
- const directory = await open(this.directory(scope.root, request.id), "r");
198
+ const directory = await open(workspaceDirectory(scope.root, request.id, this.options.agentDir), "r");
178
199
  try {
179
200
  await directory.sync();
180
201
  }
@@ -190,7 +211,7 @@ export class WorkspaceRunner {
190
211
  const bytes = await readFile(await workspaceInputPath(scope, source));
191
212
  if (bytes.length > 64 * 1024)
192
213
  throw new Error("Workspace input grew beyond 64 KiB.");
193
- const path = join(this.directory(scope.root, request.id), `input-${name}`);
214
+ const path = join(workspaceDirectory(scope.root, request.id, this.options.agentDir), `input-${name}`);
194
215
  state.inputs[name] = { source, path, digest: hash(bytes) };
195
216
  await this.save(state);
196
217
  const input = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400);
@@ -240,7 +261,7 @@ export class WorkspaceRunner {
240
261
  if (repo.common !== state.repositories[name].common)
241
262
  throw new Error(`Repository identity changed: ${name}.`);
242
263
  for (const [name, input] of Object.entries(state.inputs)) {
243
- if (input.path !== join(this.directory(state.root, state.request.id), `input-${name}`) || input.source !== state.request.tasks[0].inputs?.[name])
264
+ if (input.path !== join(workspaceDirectory(state.root, state.request.id, this.options.agentDir), `input-${name}`) || input.source !== state.request.tasks[0].inputs?.[name])
244
265
  throw new Error("Workspace input identity changed.");
245
266
  await workspaceInputPath(scope, input.source);
246
267
  for (const path of [input.source, input.path]) {
@@ -285,7 +306,7 @@ export class WorkspaceRunner {
285
306
  const task = workerTask(state.request), attempt = Object.values(state.repositories)[0].attempt, host = this.options.host(state.policy);
286
307
  const paths = this.paths(state, false);
287
308
  const goal = `${state.request.goal}\n\nRead-only input copies (never promote these files):\n${JSON.stringify(Object.fromEntries(Object.entries(state.inputs).map(([name, input]) => [name, input.path])))}\n\nCheck repository labels refer to this absolute worktree map:\n${JSON.stringify(paths)}`;
288
- for (const kind of ["workspace", "worker_tab", "agent"]) {
309
+ for (const kind of host.allocationKinds?.(attempt) ?? ["workspace", "worker_tab", "agent"]) {
289
310
  const plan = await host.planHostAllocation({ requestId: state.request.id, goal, kind, task, attempt }, context(signal));
290
311
  const intent = { ...plan, generation: 1, token: attempt.correlationToken, status: "allocating" };
291
312
  attempt.allocations.push(intent);
@@ -296,6 +317,8 @@ export class WorkspaceRunner {
296
317
  acquireLaunch: () => this.options.coordinator.acquireLaunch(task.role, task.modelClass, context(signal)) }, context(signal));
297
318
  intent.status = result.outcome === "owned" ? "owned" : result.outcome;
298
319
  if (result.outcome === "owned") {
320
+ if (intent.kind === "native" && result.kind === "native")
321
+ intent.leaseIdentity = result.leaseIdentity;
299
322
  if (intent.kind === "workspace" && result.kind === "workspace")
300
323
  Object.assign(intent, { workspaceId: result.workspaceId, rootTabId: result.rootTabId, rootPaneId: result.rootPaneId });
301
324
  if (intent.kind === "worker_tab" && result.kind === "worker_tab")
@@ -307,8 +330,8 @@ export class WorkspaceRunner {
307
330
  if (result.outcome !== "owned")
308
331
  throw new Error(result.failure);
309
332
  }
310
- const agent = attempt.allocations.find((item) => item.kind === "agent");
311
- if (!agent || agent.kind !== "agent")
333
+ const agent = attempt.allocations.find((item) => item.kind === "agent" || item.kind === "native");
334
+ if (!agent)
312
335
  throw new Error("Worker identity is missing.");
313
336
  const preCandidate = branchBase(Object.values(state.repositories)[0]);
314
337
  attempt.prompts.push({ kind: "initial", status: "submitting", preCandidate, at: Date.now() });
@@ -317,7 +340,7 @@ export class WorkspaceRunner {
317
340
  const observation = new DeadlineScope(this.options.coordinator.now() + state.policy.childMaxMs, () => this.options.coordinator.now(), signal);
318
341
  const prompt = attempt.prompts[0];
319
342
  try {
320
- const result = await observation.call((operation) => host.runWorker({ goal, contexts: [], task, attempt, workerId: agent.agentName,
343
+ const result = await observation.call((operation) => host.runWorker({ policy: state.policy, goal, contexts: [], task, attempt, workerId: agent.agentName,
321
344
  kind: "initial", preCandidate, workspacePaths: paths, idleMs: state.policy.childIdleMs }, operation));
322
345
  if (result.outcome !== "candidate") {
323
346
  prompt.status = result.outcome === "not_prompted" ? "not_sent" : result.outcome === "unknown" || result.outcome === "interrupted" ? "ambiguous" : "settled";
@@ -359,10 +382,10 @@ export class WorkspaceRunner {
359
382
  const attempt = primary.attempt;
360
383
  if (attempt.termination?.status === "terminated")
361
384
  return;
362
- const agent = attempt.allocations.find((item) => item.kind === "agent");
385
+ const agent = attempt.allocations.find((item) => item.kind === "agent" || item.kind === "native");
363
386
  if (!agent)
364
387
  return;
365
- if (agent.kind !== "agent" || agent.status !== "owned")
388
+ if (agent.status !== "owned")
366
389
  throw new Error("Agent allocation is uncertain; manual host reconciliation is required. All worktrees are retained.");
367
390
  const host = this.options.host(state.policy), input = { task: workerTask(state.request), attempt, workerId: agent.agentName, candidate: attempt.candidate ?? branchBase(Object.values(state.repositories)[0]) };
368
391
  attempt.termination = { status: "terminating", workerId: agent.agentName, candidate: input.candidate };
@@ -585,7 +608,13 @@ export class WorkspaceRunner {
585
608
  async cleanup(state, signal) {
586
609
  if (state.status !== "promoted" && state.status !== "cleaned")
587
610
  throw new Error("Workspace cleanup requires all repositories to be promoted. Failed and aborted work stays retained for manual inspection.");
611
+ if (!state.candidates || !state.tips || Object.values(state.repositories).some((repo) => repo.promotion?.status !== "promoted" || !repo.promotion.mainAfter || repo.allocation !== "owned" || !repo.integration))
612
+ throw new Error("Workspace cleanup requires complete promotion receipts and owned integration worktrees.");
613
+ for (const repo of Object.values(state.repositories))
614
+ owned(repo.attempt);
588
615
  await this.stop(state);
616
+ if (Object.values(state.repositories)[0].attempt.termination?.status !== "terminated")
617
+ throw new Error("Workspace cleanup requires proved worker termination.");
589
618
  await this.preflightMain(state, true, signal);
590
619
  const first = Object.values(state.repositories)[0], host = this.options.host(state.policy);
591
620
  first.cleanup ??= [];
@@ -1,6 +1,6 @@
1
1
  # Direct delegation measurement
2
2
 
3
- Pi Subagent runs native Pi workers through Herdr. Billion Context build `0.0.1373-master.1f3fcb5` also starts a native Pi child on a Pi host. Its Pi path passes the task through standard input, reads child output, and keeps the full result separately. Despite the tool name `acp_delegate`, this path does not need an Agent Client Protocol handshake. Pi Subagent reuses its existing session reader, concurrency limits, model routes, and checkout protection.
3
+ The version 30 measurements below used native Pi workers through Herdr. Billion Context build `0.0.1373-master.1f3fcb5` also starts a native Pi child on a Pi host. Its Pi path passes the task through standard input, reads child output, and keeps the full result separately. Despite the tool name `acp_delegate`, this path does not need an Agent Client Protocol handshake. Pi Subagent reuses its existing session reader, concurrency limits, model routes, and checkout protection.
4
4
 
5
5
  ## Parent result benchmark
6
6
 
@@ -60,3 +60,14 @@ Two bounded repository tasks ran once per tool on 2026-12-04. Each run used a fr
60
60
  Both research answers identified four calls against a three-call default and cited the inclusive loop bound. Both reviewers found that a failed refresh returns expired cached data. Pi Subagent also found that a successful refresh can return an already expired session. The latter defect was scored after the run against the fixture contract. All four usage fields came from saved assistant messages. Cache writes were zero. Total tokens count cached input each time the model read it. The table measures token traffic, not billing. The Billion Context parent made one additional read to retrieve each worker's answer.
61
61
 
62
62
  Separately, the serialized model-facing `delegate_task` schema fell from 11,219 to 6,753 bytes, or 3,144 to 1,981 `o200k_base` tokens. This compares the initial reactivation with the final tool contract. Providers can encode schemas differently. The strict per-mode parsers still validate the actual request.
63
+
64
+ ## Version 31 completion batching
65
+
66
+ Two scripted readers finished during the same Main turn. Each returned the same answer and reported 15 simulated worker tokens. Both versions completed both reads without human input.
67
+
68
+ | Implementation | Main wake-ups | Elapsed time |
69
+ | --- | ---: | ---: |
70
+ | Before batching | 2 | 143 ms |
71
+ | With batching | 1 | 669 ms |
72
+
73
+ These figures come from one paired local run. The fixture did not call a model provider. It measures delivery frequency and cannot establish total token savings or typical latency.
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Pi Subagent isolated workflow</title>
6
+ <title>Pi Subagent 30 historical isolated workflow</title>
7
7
  <link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=Geist:wght@400;500;600&amp;family=Geist+Mono:wght@400;500;600&amp;display=swap" rel="stylesheet">
8
8
  <style>
9
9
  * { box-sizing: border-box; }
@@ -16,10 +16,10 @@
16
16
  </head>
17
17
  <body>
18
18
  <main class="frame">
19
- <h1>Stage ready candidates before all workers finish</h1>
19
+ <h1>Version 30 isolated workflow (historical)</h1>
20
20
  <div class="diagram-scroll">
21
21
  <svg width="1280" height="720" viewBox="0 0 1280 720" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="orchestration-architecture-title orchestration-architecture-desc">
22
- <title id="orchestration-architecture-title">Pi Subagent isolated workflow</title>
22
+ <title id="orchestration-architecture-title">Pi Subagent 30 historical isolated workflow</title>
23
23
  <desc id="orchestration-architecture-desc">Workers commit checked candidates for Main to stage while siblings run, advance dependent waves, validate the combined tip, and explicitly promote into unchanged clean Main.</desc>
24
24
  <defs>
25
25
  <style>
@@ -49,7 +49,7 @@
49
49
  </marker>
50
50
  </defs>
51
51
  <rect width="1280" height="720" fill="#f0eee9"/>
52
- <text class="section" x="40" y="120">CANDIDATE PRODUCTION</text>
52
+ <text class="section" x="40" y="120">VERSION 30 ONLY · CANDIDATE PRODUCTION</text>
53
53
  <text class="section" x="40" y="320">MAIN'S EXPLICIT ACTIONS</text>
54
54
 
55
55
  <!-- Draw connectors and their labels before nodes. -->
@@ -1,6 +1,6 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
2
  <svg width="1280" height="720" viewBox="0 0 1280 720" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="orchestration-architecture-title orchestration-architecture-desc" id="orchestration-architecture-root">
3
- <title id="orchestration-architecture-title">Pi Subagent isolated workflow</title>
3
+ <title id="orchestration-architecture-title">Pi Subagent 30 historical isolated workflow</title>
4
4
  <desc id="orchestration-architecture-desc">Workers commit checked candidates for Main to stage while siblings run, advance dependent waves, validate the combined tip, and explicitly promote into unchanged clean Main.</desc>
5
5
  <defs>
6
6
  <style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=Geist:wght@400;500;600&amp;family=Geist+Mono:wght@400;500;600&amp;family=Noto+Serif:ital@0;1&amp;family=Noto+Sans+KR:wght@400;500;600&amp;family=Noto+Serif+KR:wght@400&amp;family=Noto+Sans+TC:wght@400;500;600&amp;family=Noto+Serif+TC:wght@400&amp;display=swap');
@@ -50,7 +50,7 @@
50
50
  </marker>
51
51
  </defs>
52
52
  <rect width="1280" height="720" fill="#f0eee9"/>
53
- <text class="section" x="40" y="120">CANDIDATE PRODUCTION</text>
53
+ <text class="section" x="40" y="120">VERSION 30 ONLY · CANDIDATE PRODUCTION</text>
54
54
  <text class="section" x="40" y="320">MAIN'S EXPLICIT ACTIONS</text>
55
55
 
56
56
  <!-- Draw connectors and their labels before nodes. -->