@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/docs/workspace.md CHANGED
@@ -1,85 +1,9 @@
1
- # Checked workspace tasks
1
+ # Existing workspace repositories
2
2
 
3
- Use one worker to change several explicitly selected Git repositories in a non-Git workspace. The worker receives an absolute worktree map. It does not need sibling-relative paths.
4
-
5
- ```mermaid
6
- flowchart LR
7
- S[Explicit repository set] --> W[One worker, separate owned worktrees]
8
- W --> C[Check the complete candidate set]
9
- C --> I[Stage and check the complete integration set]
10
- I --> P[Preflight every Main target]
11
- P --> R[Promote serially and save each receipt]
12
- R --> X[Reconcile a partial result explicitly]
13
- ```
14
-
15
- ## Request
16
-
17
- ```json
18
- {
19
- "mode": "isolated",
20
- "id": "change-contract",
21
- "goal": "Change the service and client together.",
22
- "repositories": { "service": "/work/app/service", "client": "/work/app/client" },
23
- "tasks": [{
24
- "id": "change", "kind": "changeset", "role": "implementer", "modelClass": "balanced",
25
- "requirements": "Change and test both sides of the contract.",
26
- "deliverable": "Clean committed candidates in both selected worktrees.",
27
- "dependsOn": [], "contextFrom": [],
28
- "inputs": { "contract": "/work/app/contract.txt" },
29
- "checks": [
30
- { "repository": "service", "command": "pnpm", "args": ["test"] },
31
- { "repository": "client", "command": "pnpm", "args": ["test"] }
32
- ]
33
- }],
34
- "finalChecks": [
35
- { "repository": "service", "command": "pnpm", "args": ["test"] },
36
- { "repository": "client", "command": "pnpm", "args": ["test"] }
37
- ]
38
- }
39
- ```
40
-
41
- Call from `/work/app`. Each repository must be a canonical direct child with its own `.git` directory. Select 1 to 8 repositories. Aliases, linked worktrees, nested repositories, Git environment overrides, and repositories with Git submodules are not supported.
42
-
43
- Workspace mode supports exactly one changeset task. It rejects text tasks, dependencies, task judgment, and final judgment. It has no automatic correction, retry, refresh, or restaging. The existing single-repository graph remains unchanged when `repositories` is absent.
44
-
45
- Every selected repository needs task checks and final checks. Select commands that test that repository. The complete final command list must contain at most 32 entries. Checks must leave the tracked and untracked state clean. If the committed root `package.json` has a test script, that script is pinned from the exact Main base commit. Dirty Main files do not change the pinned script. All task and final checks reject a changed pinned script, regardless of the command name, path, or arguments. Repositories without a root manifest or test script can use their native check commands.
46
-
47
- `PI_SUBAGENT_REPOSITORIES` contains the absolute repository-to-worktree map as JSON, which is a structured text format. `PI_SUBAGENT_INPUTS` contains the input-name-to-copy map. Check commands receive both environment variables. Task checks use worker worktrees; final checks use integration worktrees. The complete repository set is checked before and after commands, including unchanged members.
48
-
49
- ## Root inputs
50
-
51
- `inputs` selects up to 8 canonical regular files inside the workspace but outside every Git repository. Each file can contain at most 64 KiB. Directories and symlinks are rejected. Each request stores separate private read-only copies. A later request can select different inputs or new contents.
52
-
53
- The worker gets copy paths, not permission to edit original inputs. Their content identities are checked with every complete-set inspection. A changed source or copy blocks validation and promotion. Inputs never become Git candidates and are never promoted or restored. This is not a sandbox: an authorized tool can bypass file permissions. A detected input change requires manual inspection.
54
-
55
- ## Integration and recovery
56
-
57
- Use `subagent_workspace` from the workspace root. Workspace records use their own state version; they do not change existing single-repository records. `/subagent` does not list workspace requests. Existing prune checks protect their retained repository resources.
58
-
59
- | Action | Required fields | Result |
60
- | --- | --- | --- |
61
- | `status` | `id` | Read saved state without mutations. |
62
- | `stage` | `id`, `expected` | Select the complete checked candidate map from `candidates`. Create an integration worktree in every repository. |
63
- | `validate` | `id`, `expected` | Check the complete integration map from `tips`. |
64
- | `promote` | `id`, `expected` | Preflight every target, then promote the exact passing `tips` serially. |
65
- | `reconcile` | `id` | Inspect interrupted stage or promotion intents without replay. |
66
- | `abort` | `id` | Stop the exact task-wide worker and retain all Git work. |
67
- | `cleanup` | `id` | Remove only fully promoted, clean, exactly owned resources. |
68
-
69
- `expected` must include every repository and its exact branch, commit, index tree, and committed tree. Partial maps are rejected. Status retains per-repository candidates, stages, intents, and promotion receipts.
70
-
71
- Dirty Main files are preserved. Worker execution can start from the committed Main identities while Main is dirty. Staging and promotion require all Main targets to be clean and unchanged. Each promotion receipt is saved before the next repository can move. All targets are checked again between promotions.
72
-
73
- **Promotion is not atomic.** A later repository can fail after an earlier repository moved. No rollback is attempted. After an interrupted promotion, call `reconcile`. It compares each uncertain target with its saved endpoints. A target at the promoted endpoint gets a receipt; a target still at its base becomes pending. Then explicitly call `promote` with the complete `tips` to continue. No proven promotion is repeated. Any other Main state requires manual reconciliation.
74
-
75
- A crash during allocation does not grant ownership. Uncertain allocations and worker prompts are retained and are never adopted or replayed automatically. A completed exact merge can be reconciled after manual conflict resolution. An unstarted merge or incomplete allocation needs manual inspection and a new request. Failed and aborted work is retained; automatic discard is not available.
76
-
77
- Worker observation uses the request's saved `childMaxMs` maximum runtime and `childIdleMs` idle limit. Only complete Pi session messages renew the idle limit; the maximum runtime does not renew. When a limit expires, the runner saves prompt failure evidence and attempts exact worker termination with a separate safety budget. Unproved termination stays visible for recovery. Every repository worktree is retained, and uncertain prompts are not replayed. These are worker limits, not a deadline for the complete request.
78
-
79
- An active `abort` can first report a busy lifecycle lock while cancellation settles. Inspect status and repeat `abort` after the active operation ends. Session replacement cancels local observation and suppresses stale delivery, but preserves saved recovery identities.
80
-
81
- ## Direct work
3
+ Select 1 to 8 existing repositories with a `repositories` map from short names to canonical paths. Each selected repository must be a direct child of the workspace.
82
4
 
83
5
  Direct requests can also supply the top-level `repositories` map. Each task uses the same selected set. A write request reserves the workspace and every selected checkout together until all exact owned workers are proved stopped. A conflict in one member refuses the whole reservation. The result labels each repository's change report or stale-read warning.
84
6
 
85
7
  Direct selection rejects `paths` and `continueFrom`. Scope comes from the task packet. Root-file writes are not authorized by repository selection. Direct work has no checked integration, rollback, or sandbox. Other sessions and external processes are outside process-local admission.
8
+
9
+ Use `subagent_workspace` with `action: "status"` to inspect previously saved multi-repository work. Use the explicit `action: "cleanup"` to release resources only after every repository has a promotion receipt. Cleanup requires proved worker termination, unchanged clean Main targets, and exact owned clean resources. It retains failed, aborted, dirty, changed, or uncertain work and reports why. Repeat cleanup to continue after a blocked step. This tool does not start or resume work, allocate resources, stage changes, or promote them.
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { dirname, isAbsolute, normalize } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
- import { isProcessLeaseIdentity } from "../dist/process-lease.js";
4
+ import { isProcessLeaseIdentity, type ProcessLeaseIdentity } from "../dist/process-lease.js";
5
5
  import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
6
6
  import * as herdr from "@henryqw/pi-herdr";
7
7
  export { registerCheckoutAdmission } from "@henryqw/pi-herdr";
@@ -11,7 +11,7 @@ const JOURNAL = "subagent-direct-admission";
11
11
  const checkoutToolCanWrite = herdr.checkoutToolCanWrite ?? ((name: string, input: unknown, direct: (input: unknown) => boolean) =>
12
12
  name === "delegate_task" ? direct(input) : !["read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode"].includes(name));
13
13
  type Record = { version: 1; sessionId: string; taskId: string; token: string; checkouts: string[]; state: "held" | "released";
14
- proof?: "not-dispatched" | "unproved" | "stopped"; resources?: unknown[]; release?: "proved" | "user-unproved";
14
+ proof?: "not-dispatched" | "unproved" | "stopped"; resources?: unknown[]; release?: "proved" | "user-unproved" | "agent-scanned";
15
15
  waiver?: { identity: string; evidence: string } };
16
16
  const owner = (record: Record) => JSON.stringify([JOURNAL, record.sessionId, record.taskId, record.token]);
17
17
  const text = (value: unknown): value is string => typeof value === "string" && value.length > 0 && !value.includes("\0");
@@ -23,9 +23,9 @@ const parse = (value: unknown): Record => {
23
23
  || new Set(record.checkouts).size !== record.checkouts.length
24
24
  || (record.resources !== undefined && !Array.isArray(record.resources))
25
25
  || (record.proof !== undefined && (!["not-dispatched", "unproved", "stopped"].includes(record.proof) || !Array.isArray(record.resources)))
26
- || (record.state === "released" ? !["proved", "user-unproved"].includes(record.release ?? "") : record.release !== undefined)
26
+ || (record.state === "released" ? !["proved", "user-unproved", "agent-scanned"].includes(record.release ?? "") : record.release !== undefined)
27
27
  || (record.release === "proved" && !["not-dispatched", "stopped"].includes(record.proof ?? ""))
28
- || (record.release === "user-unproved" ? !text(record.waiver?.identity) || !text(record.waiver?.evidence) : record.waiver !== undefined)) throw new Error("Malformed direct admission journal entry.");
28
+ || (record.release === "user-unproved" || record.release === "agent-scanned" ? !text(record.waiver?.identity) || !text(record.waiver?.evidence) : record.waiver !== undefined)) throw new Error("Malformed direct admission journal entry.");
29
29
  return record;
30
30
  };
31
31
  const sameSet = (a: Record, b: Record) => a.checkouts.length === b.checkouts.length && a.checkouts.every((path, index) => path === b.checkouts[index]);
@@ -39,11 +39,13 @@ const hasProof = (record: Record, entries: readonly SessionEntry[]) => {
39
39
  if (!resources) return false;
40
40
  if (record.proof === "not-dispatched") return !resources.length && !resourceEntries(record, entries).length;
41
41
  if (record.proof !== "stopped" || !resources.length) return false;
42
- if (resources.every((resource) => resource?.kind === "native-intent")) {
42
+ if (resources.every((resource) => resource?.kind === "native-intent" || resource?.kind === "native-process")) {
43
43
  const keys = new Set<string>();
44
44
  const saved = resourceEntries(record, entries);
45
- if (saved.length !== resources.length) return false;
46
- return resources.every((resource) => {
45
+ // A native-process resource only adds the PID of a saved native intent.
46
+ const intents = resources.filter((resource) => resource.kind === "native-intent");
47
+ if (saved.length !== intents.length || !resources.every((resource) => resource.kind === "native-intent" || nativeProcess(resource, intents))) return false;
48
+ return intents.every((resource) => {
47
49
  if (!["entryId", "sessionFile", "leasePath", "turn", "cwd", "role"].every((key) => text(resource[key]))
48
50
  || !isProcessLeaseIdentity(resource.leaseIdentity)
49
51
  || !["sessionFile", "leasePath", "cwd"].every((key) => isAbsolute(resource[key]) && normalize(resource[key]) === resource[key])
@@ -90,6 +92,26 @@ const hasProof = (record: Record, entries: readonly SessionEntry[]) => {
90
92
  });
91
93
  };
92
94
 
95
+ const nativeProcess = (resource: any, intents: any[]) => Number.isSafeInteger(resource.pid) && resource.pid > 1 && Number.isSafeInteger(resource.spawnedAt)
96
+ && intents.filter((intent) => intent.entryId === resource.entryId && intent.leasePath === resource.leasePath).length === 1;
97
+
98
+ /** Worker processes that Main may stop and prove absent after a restart. Each native worker must have held its lease
99
+ * from spawn and have a saved PID; any other saved resource (legacy tab, allocation, continuation) returns undefined. */
100
+ export function agentLeases(record: { resources?: unknown[] }): { leasePath: string; leaseIdentity: ProcessLeaseIdentity; pid: number; spawnedAt: number }[] | undefined {
101
+ const resources = (record.resources ?? []) as any[];
102
+ const intents = resources.filter((resource) => resource?.kind === "native-intent");
103
+ const processes = resources.filter((resource) => resource?.kind === "native-process");
104
+ const valid = intents.length > 0 && intents.length + processes.length === resources.length
105
+ && intents.every((resource) => resource.spawnLease === true && text(resource.leasePath) && isAbsolute(resource.leasePath)
106
+ && normalize(resource.leasePath) === resource.leasePath && isProcessLeaseIdentity(resource.leaseIdentity)
107
+ && processes.filter((item) => item.entryId === resource.entryId && item.leasePath === resource.leasePath).length === 1)
108
+ && processes.every((resource) => nativeProcess(resource, intents));
109
+ return valid ? intents.map((intent) => {
110
+ const saved = processes.find((item) => item.entryId === intent.entryId && item.leasePath === intent.leasePath)!;
111
+ return { leasePath: intent.leasePath, leaseIdentity: intent.leaseIdentity, pid: saved.pid, spawnedAt: saved.spawnedAt };
112
+ }) : undefined;
113
+ }
114
+
93
115
  const identity = (record: Record) => `${record.sessionId}/${record.taskId}/${record.token}`;
94
116
  const evidence = (record: Record, entries: readonly SessionEntry[]) => {
95
117
  const sources = (record.resources ?? []).flatMap((resource: any) => resource?.kind === "continuation-sources" && Array.isArray(resource.sources) ? resource.sources : []);
@@ -125,7 +147,8 @@ function replay(entries: readonly SessionEntry[]): Map<string, Record> {
125
147
  const { release, waiver, ...checkpoint } = record;
126
148
  if (!isDeepStrictEqual({ ...checkpoint, state: "held" }, previous)
127
149
  || (release === "proved" ? !hasProof(previous!, entries)
128
- : waiver!.identity !== identity(previous!) || waiver!.evidence !== evidence(previous!, entries))) {
150
+ : waiver!.identity !== identity(previous!) || waiver!.evidence !== evidence(previous!, entries)
151
+ || (release === "agent-scanned" && !agentLeases(previous!)))) {
129
152
  throw new Error("Direct release has incomplete or changed proof or user consent; protection retained.");
130
153
  }
131
154
  } else held.add(JSON.stringify(record));
@@ -228,12 +251,14 @@ export function registerDirectAdmission(pi: ExtensionAPI, canWrite: (input: unkn
228
251
  claims.add(key); // Claim before the first dialog, not after confirmation.
229
252
  return {
230
253
  close: () => { claims.delete(key); },
231
- release(kind: "proved" | "user-unproved", typedIdentity?: string) {
254
+ /** `agent-scanned`: Main proved that every saved process lease is empty; the receipt keeps the reviewed evidence. */
255
+ release(kind: "proved" | "user-unproved" | "agent-scanned", typedIdentity?: string) {
232
256
  requireReady();
233
257
  if (!claims.has(key) || !valid()) throw new Error("Direct recovery scope or evidence changed; protection retained.");
234
258
  if (kind === "proved" && !hasProof(reviewed, ctx.sessionManager.getEntries())) throw new Error("Worker termination is unproved; protection retained.");
235
- if (kind === "user-unproved" && typedIdentity !== identity(reviewed)) throw new Error("Exact typed reservation identity is required; protection retained.");
236
- save({ ...reviewed, state: "released", release: kind, ...(kind === "user-unproved"
259
+ if (kind !== "proved" && typedIdentity !== identity(reviewed)) throw new Error("Exact typed reservation identity is required; protection retained.");
260
+ if (kind === "agent-scanned" && !agentLeases(reviewed)) throw new Error("Only native workers that held their lease from spawn permit an agent release; protection retained.");
261
+ save({ ...reviewed, state: "released", release: kind, ...(kind !== "proved"
237
262
  ? { waiver: { identity: typedIdentity!, evidence: savedEvidence } } : {}) });
238
263
  admission.complete(key);
239
264
  },
@@ -0,0 +1,91 @@
1
+ """Keep acceptance commands in the group owned by the verification witness."""
2
+ import ctypes
3
+ import errno
4
+ import os
5
+ import sys
6
+
7
+
8
+ def confine_group():
9
+ if sys.platform == 'darwin':
10
+ # Darwin spawn attributes can select a new session or process group.
11
+ # Ordinary fork/exec children inherit this policy and the current group.
12
+ sandbox = ctypes.CDLL('/usr/lib/libsandbox.1.dylib')
13
+ error = ctypes.c_char_p()
14
+ profile = b'(version 1)(allow default)(deny syscall-unix (syscall-number SYS_setsid SYS_setpgid SYS_posix_spawn))'
15
+ if sandbox.sandbox_init(profile, 0, ctypes.byref(error)) != 0:
16
+ raise RuntimeError(error.value or 'cannot install the macOS process policy')
17
+ return
18
+
19
+ if sys.platform != 'linux':
20
+ raise RuntimeError('unsupported acceptance check platform')
21
+ # libseccomp selects the syscall numbers for the native architecture.
22
+ seccomp = ctypes.CDLL('libseccomp.so.2')
23
+ allow = 0x7fff0000 # SCMP_ACT_ALLOW
24
+ deny = 0x00050000 # SCMP_ACT_ERRNO
25
+ seccomp.seccomp_init.restype = ctypes.c_void_p
26
+ context = ctypes.c_void_p(seccomp.seccomp_init(allow))
27
+ if not context:
28
+ raise RuntimeError('cannot create the Linux process policy')
29
+ try:
30
+ # clone3 takes an indirect flags pointer. ENOSYS selects the normal
31
+ # clone fallback, where seccomp can inspect namespace flags directly.
32
+ class Comparison(ctypes.Structure):
33
+ _fields_ = [('arg', ctypes.c_uint), ('op', ctypes.c_uint),
34
+ ('mask', ctypes.c_uint64), ('value', ctypes.c_uint64)]
35
+
36
+ for name in ('setsid', 'setpgid', 'unshare', 'setns', 'clone3', 'clone'):
37
+ number = seccomp.seccomp_syscall_resolve_name(name.encode())
38
+ if number == -1:
39
+ raise RuntimeError('cannot identify syscall ' + name)
40
+ # Linux s390 uses its second clone argument for the flags.
41
+ flags = Comparison(1 if os.uname().machine in ('s390', 's390x') else 0,
42
+ 7, 0x20000000, 0x20000000) # MASKED_EQ CLONE_NEWPID
43
+ action = deny | (errno.ENOSYS if name == 'clone3' else errno.EPERM)
44
+ rc = seccomp.seccomp_rule_add_array(context, action, number, int(name == 'clone'),
45
+ ctypes.byref(flags) if name == 'clone' else None)
46
+ if rc != 0:
47
+ raise RuntimeError('cannot restrict syscall ' + name)
48
+ if seccomp.seccomp_load(context) != 0:
49
+ raise RuntimeError('cannot install the Linux process policy')
50
+ finally:
51
+ seccomp.seccomp_release(context)
52
+
53
+
54
+ def reap_witness(command):
55
+ # A container's PID 1 may never reap orphans. Adopt them above the witness
56
+ # so its kernel group-existence check can observe the final process exit.
57
+ if ctypes.CDLL(None).prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER
58
+ raise RuntimeError('cannot adopt verification descendants')
59
+ witness = os.fork()
60
+ if witness == 0:
61
+ os.execv(command[0], command)
62
+ os.close(3) # Only the witness owns the lease and the Node control channel.
63
+ os.close(int(os.environ['NODE_CHANNEL_FD']))
64
+ status = 1
65
+ while True:
66
+ try:
67
+ pid, raw_status = os.wait()
68
+ except ChildProcessError:
69
+ return status
70
+ if pid == witness:
71
+ status = os.WEXITSTATUS(raw_status) if os.WIFEXITED(raw_status) else 128 + os.WTERMSIG(raw_status)
72
+
73
+
74
+ if sys.argv[1] == 'reap':
75
+ sys.exit(reap_witness(sys.argv[2:]))
76
+
77
+ try:
78
+ # The supervisor distinguishes launcher errors from a check's nonzero exit.
79
+ os.set_inheritable(3, False)
80
+ confine_group()
81
+ try:
82
+ os.setpgid(0, os.getpgrp())
83
+ except PermissionError:
84
+ pass
85
+ else:
86
+ raise RuntimeError('kernel process-group restriction was not enforced')
87
+ os.write(3, b'ready\n')
88
+ os.execvp(sys.argv[2], sys.argv[2:])
89
+ except Exception as error:
90
+ os.write(3, ('error: ' + str(error)[:512]).encode('utf-8', errors='replace'))
91
+ sys.exit(1)
@@ -0,0 +1,42 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ // This process is the check's group leader. A separate supervisor holds the
5
+ // lease until this whole group is empty, including after the leader exits.
6
+ const [timeoutText, executable, ...args] = process.argv.slice(2);
7
+ const timeout = Number(timeoutText);
8
+ const stop = () => {
9
+ // The leader is still a member, so this group ID cannot have been reused.
10
+ process.kill(-process.pid, "SIGKILL");
11
+ };
12
+ process.on("message", (message) => { if (message === "stop") stop(); });
13
+ const deadline = setTimeout(stop, timeout);
14
+ const launcher = fileURLToPath(new URL("./direct-check-exec.py", import.meta.url));
15
+ const child = spawn("/usr/bin/python3", ["-I", launcher, "check", executable, ...args], { stdio: ["ignore", "inherit", "inherit", "pipe"] });
16
+ let startup = "", result, spawnError;
17
+ child.stdio[3].setEncoding("utf8");
18
+ child.stdio[3].on("data", (chunk) => { startup += chunk; });
19
+ child.once("error", (error) => { spawnError = error.message; });
20
+ child.once("close", (code, signal) => {
21
+ if (spawnError || startup !== "ready\n") result = { error: `Verification launch failed: ${spawnError ?? (startup.trim() || "containment was not confirmed")}` };
22
+ else result = signal ? { error: `Verification ended by ${signal}.` } : { code };
23
+ });
24
+
25
+ function poll() {
26
+ if (result) {
27
+ // ps runs in a different group, so it cannot make this group appear busy.
28
+ const scan = spawnSync("/bin/ps", ["-A", "-o", "pid=", "-o", "pgid=", "-o", "stat="],
29
+ { encoding: "utf8", detached: true, timeout: 1000, maxBuffer: 4 * 1024 * 1024 });
30
+ if (!scan.error && scan.status === 0 && !scan.stderr.trim()) {
31
+ const lines = scan.stdout.trim().split(/\r?\n/);
32
+ const rows = lines.map((line) => /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(line));
33
+ if (rows.length && rows.every(Boolean) && !rows.some((row) => Number(row[2]) === process.pid && Number(row[1]) !== process.pid && !row[3].startsWith("Z"))) {
34
+ clearTimeout(deadline);
35
+ if (process.connected) process.send(result, () => process.disconnect());
36
+ return;
37
+ }
38
+ }
39
+ }
40
+ setTimeout(poll, 50);
41
+ }
42
+ poll();
@@ -0,0 +1,34 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ // This supervisor retains descriptor 3 outside the check's process group.
5
+ // It never signals a saved group ID: only the group's live leader can do that.
6
+ const [timeoutText, ...args] = process.argv.slice(2);
7
+ const leader = spawn(process.execPath, [fileURLToPath(new URL("./direct-check-supervisor.mjs", import.meta.url)), timeoutText, ...args],
8
+ { detached: true, stdio: ["ignore", "inherit", "inherit", "ignore", "ipc"] });
9
+ let result, exited = false, spawnError;
10
+ leader.on("message", (message) => { result = message; });
11
+ leader.on("error", (error) => { if (!leader.pid) { spawnError = error.message; exited = true; } });
12
+ leader.on("exit", () => { exited = true; });
13
+ const stop = () => { if (leader.connected) leader.send("stop", () => {}); };
14
+ process.on("message", (message) => { if (message === "stop") stop(); });
15
+ const deadline = setTimeout(stop, Number(timeoutText));
16
+
17
+ function poll() {
18
+ if (exited) {
19
+ let empty = !leader.pid;
20
+ if (leader.pid) {
21
+ // The kernel checks the whole group atomically. A process-table
22
+ // snapshot can miss a child created while the table is being read.
23
+ try { process.kill(-leader.pid, 0); }
24
+ catch (error) { empty = error.code === "ESRCH"; }
25
+ }
26
+ if (empty) {
27
+ clearTimeout(deadline);
28
+ if (process.connected) process.send(result ?? { error: spawnError ?? "Verification group ended without an exit result." }, () => process.disconnect());
29
+ return;
30
+ }
31
+ }
32
+ setTimeout(poll, 50);
33
+ }
34
+ poll();
@@ -1,11 +1,12 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync } from "node:fs";
2
3
  import { mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { dirname, join } from "node:path";
5
6
  import type { PreparedRoleLaunch } from "@henryqw/pi-subagent";
6
7
  import { exactDirectAnswer, directTaskReader } from "../dist/direct-herdr.js";
7
8
  import { materializeTransientLaunch } from "../dist/launch-runtime.js";
8
- import { EphemeralSubagentError, utf8Prefix, type EphemeralSubagentExecutor } from "../dist/ephemeral.js";
9
+ import { EphemeralSubagentError, utf8Prefix, type EphemeralSubagentExecutor, type EphemeralSubagentActivityEvent } from "../dist/ephemeral.js";
9
10
  import { PI_SUBAGENT_PROCESS_LEASE, processLeaseIdentity, type ProcessLeaseIdentity } from "../dist/process-lease.js";
10
11
 
11
12
  export type NativeSession = { sessionFile: string; leasePath: string; leaseIdentity: ProcessLeaseIdentity; turn: string; cwd: string; role: string };
@@ -21,16 +22,23 @@ export async function runNativeDirect(input: {
21
22
  write: boolean;
22
23
  requireSuccess: boolean;
23
24
  onProcessEnd: (reason: "not-started" | "exited") => void;
25
+ onSpawn?: (session: NativeSession, pid: number) => void;
24
26
  prepare: () => Promise<PreparedRoleLaunch>;
25
27
  source?: NativeSession;
26
28
  onSession: (session: NativeSession) => void;
29
+ onTokens: (tokens: number) => void;
30
+ onActivity: (event: EphemeralSubagentActivityEvent) => void;
27
31
  onUsage: (usage: { totalTokens: number; cost: { total: number } }) => void;
28
32
  }): Promise<{ text: string; inline: string; answerFile?: string }> {
29
33
  let transient: Awaited<ReturnType<typeof materializeTransientLaunch>> | undefined;
34
+ // The worker inherits this descriptor at spawn, so the lease names the live worker from its first instruction.
35
+ // Main closes its own copy when the worker process ends, before any lease scan can see Main as a holder.
36
+ let descriptor: number | undefined;
37
+ const closeDescriptor = () => { if (descriptor !== undefined) { const fd = descriptor; descriptor = undefined; closeSync(fd); } };
30
38
  let session!: NativeSession;
31
39
  let prompt = "";
32
40
  try {
33
- const result = await input.executor.run({ signal: input.signal, onProcessEnd: input.onProcessEnd, prepare: async () => {
41
+ const result = await input.executor.run({ signal: input.signal, retryReadOnlySpawn: !input.write, onProcessEnd: (reason) => { closeDescriptor(); input.onProcessEnd(reason); }, onSpawn: (pid) => input.onSpawn?.(session, pid), onTokens: input.onTokens, onActivity: input.onActivity, prepare: async () => {
34
42
  const prepared = await input.prepare();
35
43
  input.signal.throwIfAborted();
36
44
  const directory = input.source ? dirname(input.source.sessionFile) : await mkdtemp(join(tmpdir(), "pi-subagent-native-"));
@@ -38,6 +46,10 @@ export async function runNativeDirect(input: {
38
46
  const leasePath = input.source?.leasePath ?? join(directory, "process.lease");
39
47
  if (!input.source) await writeFile(leasePath, "", { flag: "wx", mode: 0o600 });
40
48
  const leaseIdentity = await processLeaseIdentity(leasePath, input.source?.leaseIdentity);
49
+ closeDescriptor();
50
+ descriptor = openSync(leasePath, constants.O_RDONLY | constants.O_NOFOLLOW);
51
+ const opened = fstatSync(descriptor, { bigint: true });
52
+ if (String(opened.dev) !== leaseIdentity.device || String(opened.ino) !== leaseIdentity.inode) throw new Error("Opened process lease differs from its saved identity.");
41
53
  session = { sessionFile: input.source?.sessionFile ?? join(directory, "session.jsonl"), leasePath, leaseIdentity, turn, cwd: input.cwd, role: input.role };
42
54
  let task = input.task;
43
55
  const reader = directTaskReader(task, prepared.tools);
@@ -56,7 +68,7 @@ export async function runNativeDirect(input: {
56
68
  if (args.length !== transient.launch.args.length - 1) throw new Error("Role launch must contain exactly one --no-session option.");
57
69
  input.signal.throwIfAborted();
58
70
  input.onSession(session);
59
- return { launch: { args: [...args, "--session", session.sessionFile], env: { ...prepared.env, [PI_SUBAGENT_PROCESS_LEASE]: leasePath } }, task: prompt.slice(6), cwd: input.cwd };
71
+ return { launch: { args: [...args, "--session", session.sessionFile], env: { ...prepared.env, [PI_SUBAGENT_PROCESS_LEASE]: leasePath } }, task: prompt.slice(6), cwd: input.cwd, leaseFd: descriptor };
60
72
  } });
61
73
  if (result.usage) input.onUsage(result.usage);
62
74
  if (result.outcome !== "success") throw new Error(result.errorMessage || result.stderr || `Native Pi exited with ${result.exitCode} (${result.stopReason ?? "unknown"}).`);
@@ -66,12 +78,12 @@ export async function runNativeDirect(input: {
66
78
  const bytes = Buffer.byteLength(text);
67
79
  if (bytes <= input.answerBytes) return { text, inline: text };
68
80
  const answerFile = join(dirname(session.sessionFile), `answer-${session.turn}.md`);
69
- await writeFile(answerFile, text, { flag: "wx", mode: 0o600 });
81
+ await writeFile(answerFile, text, { flag: "wx", mode: 0o400, flush: true });
70
82
  return { text, inline: `${utf8Prefix(text, input.answerBytes)}\n\n[Answer truncated to ${input.answerBytes} of ${bytes} bytes; full answer saved]`, answerFile };
71
83
  } catch (error) {
72
84
  if (error instanceof EphemeralSubagentError && error.usage) input.onUsage(error.usage);
73
85
  throw error;
74
86
  } finally {
75
- if (transient) await transient.cleanup();
87
+ try { closeDescriptor(); } finally { if (transient) await transient.cleanup(); }
76
88
  }
77
89
  }
@@ -0,0 +1,189 @@
1
+ import { utf8Prefix } from "../dist/ephemeral.js";
2
+ import { claimOwner } from "./direct-owner.ts";
3
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { parseSessionEntries, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import type { BackgroundWorkflowTransportDetails } from "./result-transport.ts";
8
+
9
+ export const DIRECT_RESULT_TYPE = "subagent-direct-result";
10
+ export const DIRECT_OUTBOX_ANCHOR = "subagent-direct-outbox-anchor";
11
+ export type DirectCompletion = { customType: typeof DIRECT_RESULT_TYPE; content: string; display: boolean; details: BackgroundWorkflowTransportDetails & { tabs?: readonly unknown[]; sessions?: readonly unknown[] } };
12
+ type RecordData = { version: 1; sessionId: string; anchor: string; originEntry?: string; result: DirectCompletion };
13
+ type Scope = { sessionId: string; sessionFile: string; anchor: string; originEntry?: string };
14
+ type BatchDetails = { completions: DirectCompletion[] };
15
+
16
+ export function completionDetails(details: unknown): BackgroundWorkflowTransportDetails[] {
17
+ if (!details || typeof details !== "object") return [];
18
+ const value = details as Partial<BatchDetails & BackgroundWorkflowTransportDetails>;
19
+ if (Array.isArray(value.completions)) return value.completions.flatMap((item) => completionDetails(item?.details));
20
+ return typeof value.taskId === "string" && Array.isArray(value.entries) && value.outcome ? [value as BackgroundWorkflowTransportDetails] : [];
21
+ }
22
+
23
+ function writeRecord(dir: string, path: string, text: string) {
24
+ const temp = join(dir, `.${randomUUID()}.tmp`);
25
+ let fd: number | undefined;
26
+ try {
27
+ fd = openSync(temp, "wx", 0o600);
28
+ writeFileSync(fd, text);
29
+ fsyncSync(fd);
30
+ closeSync(fd); fd = undefined;
31
+ renameSync(temp, path);
32
+ const parent = openSync(dir, "r");
33
+ try { fsyncSync(parent); } finally { closeSync(parent); }
34
+ } finally {
35
+ if (fd !== undefined) closeSync(fd);
36
+ if (existsSync(temp)) unlinkSync(temp);
37
+ }
38
+ }
39
+
40
+ const BATCH_BYTES = 4096;
41
+
42
+ function batchMessage(ready: DirectCompletion[], dir: string) {
43
+ const headers = ready.map(({ details }) => `${details.taskId} ${details.outcome}${details.recovery ? " (recovery needed)" : ""}`);
44
+ const joined = (previews: string[]) => headers.map((header, i) => previews[i] ? `${header}\n${previews[i]}` : header).join("\n\n");
45
+ const bodies = ready.map((item) => item.content);
46
+ const headerBytes = Buffer.byteLength(joined([]));
47
+ const bodyBytes = bodies.reduce((sum, body) => sum + Buffer.byteLength(body) + 1, 0);
48
+ if (headerBytes + bodyBytes <= BATCH_BYTES) return { content: joined(bodies), details: { completions: ready } };
49
+
50
+ const directory = JSON.stringify(dir);
51
+ const location = `Full results: read <workflow ID>.json in ${directory}.\n`;
52
+ const available = BATCH_BYTES - Buffer.byteLength(location) - headerBytes - ready.length;
53
+ let content: string;
54
+ let previews: string[] = [];
55
+ if (available >= 0) {
56
+ const share = Math.floor(available / ready.length);
57
+ previews = bodies.map((body) => utf8Prefix(body, share));
58
+ content = location + joined(previews);
59
+ } else {
60
+ // Keep all receipts in this turn even when their identifiers exceed the model preview budget.
61
+ const listing = JSON.stringify(ready.map(({ details }) => ({ file: `${details.taskId}.json`, outcome: details.outcome, recovery: Boolean(details.recovery) })), null, 2);
62
+ const name = `batch-${createHash("sha256").update(listing).digest("hex")}.txt`;
63
+ writeRecord(dir, join(dir, name), listing);
64
+ const relative = `${name} in the active session file's sibling .subagent-outbox directory`;
65
+ const label = `${ready.length} direct workflows finished. Read the status and result file list: `;
66
+ const path = JSON.stringify(join(dir, name));
67
+ content = label + (Buffer.byteLength(label + path) <= BATCH_BYTES ? path : relative);
68
+ }
69
+ return { content, details: { completions: ready.map((item, i) => ({ ...item, content: previews[i] ?? "" })) } };
70
+ }
71
+
72
+ /** Each immutable file is a completion, never a delivery acknowledgement. */
73
+ export function createDirectOutbox(pi: ExtensionAPI, report: (message: string) => void) {
74
+ const unsaved = new Map<string, { scope: Scope; record: RecordData }>();
75
+ const attempted = new Set<string>();
76
+ const owners = new Map<string, string>();
77
+ let ownerToken = randomUUID();
78
+ const acknowledged = new Set<string>();
79
+ const suspended = new Set<string>();
80
+ let ctx: ExtensionContext | undefined;
81
+ let active = false;
82
+ let turn = false;
83
+ let ranSinceSettlement = false;
84
+ let scheduled = false;
85
+ const directory = (file: string) => `${file}.subagent-outbox`;
86
+ const key = (scope: Scope, id: string) => `${scope.sessionFile}\0${id}`;
87
+ const releaseOwner = (id: string) => {
88
+ const owner = owners.get(id);
89
+ if (!owner) return;
90
+ try { writeFileSync(join(owner, "released"), "", { mode: 0o600, flush: true }); owners.delete(id); }
91
+ catch (error) { report(`Direct delivery ownership release failed: ${String(error)}`); }
92
+ };
93
+ const save = (scope: Scope, record: RecordData) => {
94
+ const dir = directory(scope.sessionFile);
95
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
96
+ const path = join(dir, `${record.result.details.taskId}.json`);
97
+ writeRecord(dir, path, JSON.stringify(record));
98
+ };
99
+ const retryUnsaved = () => {
100
+ for (const [id, item] of unsaved) {
101
+ try { save(item.scope, item.record); unsaved.delete(id); }
102
+ catch (error) { report(`Direct completion could not be saved: ${String(error)}`); }
103
+ }
104
+ };
105
+ const flush = () => {
106
+ if (!active || turn || !ctx) return;
107
+ const current = ctx;
108
+ const sessionFile = current.sessionManager.getSessionFile();
109
+ if (!sessionFile) return;
110
+ retryUnsaved();
111
+ const dir = directory(sessionFile);
112
+ if (!existsSync(dir)) return;
113
+ const branch = current.sessionManager.getBranch();
114
+ const anchors = new Set(branch.filter((entry) => entry.type === "custom" && entry.customType === DIRECT_OUTBOX_ANCHOR).map((entry) => entry.id));
115
+ const delivered = new Set(branch.flatMap((entry) => entry.type === "custom_message" && entry.customType === DIRECT_RESULT_TYPE ? completionDetails(entry.details).map(({ taskId }) => taskId) : []));
116
+ const ready: DirectCompletion[] = [];
117
+ let persistedReceipts: Set<string> | undefined;
118
+ let names: string[];
119
+ try { names = readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); }
120
+ catch (error) { report(`Direct completion outbox cannot be read: ${String(error)}`); return; }
121
+ for (const name of names) {
122
+ if (delivered.has(name.slice(0, -5))) continue;
123
+ try {
124
+ const record = JSON.parse(readFileSync(join(dir, name), "utf8")) as RecordData;
125
+ if (record.version !== 1 || completionDetails(record.result?.details).length !== 1 || typeof record.anchor !== "string" || typeof record.sessionId !== "string" || record.result.customType !== DIRECT_RESULT_TYPE || typeof record.result.content !== "string" || typeof record.result.display !== "boolean" || name !== `${record.result.details.taskId}.json`) throw new Error(`Invalid outbox record ${name}`);
126
+ const id = record.result.details.taskId;
127
+ const recordKey = key({ sessionFile, sessionId: record.sessionId, anchor: record.anchor }, id);
128
+ if (record.sessionId !== current.sessionManager.getSessionId() || !anchors.has(record.anchor) || (record.originEntry !== undefined && !branch.some((entry) => entry.id === record.originEntry)) || delivered.has(id) || acknowledged.has(recordKey) || attempted.has(recordKey) || suspended.has(recordKey) || unsaved.has(recordKey)) continue;
129
+ if (!owners.has(recordKey)) {
130
+ const owner = claimOwner(dir, `${id}.delivery`, ownerToken);
131
+ if (!owner) continue;
132
+ // A successor can have loaded its session before the previous sender saved the receipt.
133
+ if (owner !== join(dir, `${id}.delivery`) && existsSync(sessionFile)) {
134
+ persistedReceipts ??= new Set(parseSessionEntries(readFileSync(sessionFile, "utf8")).flatMap((entry) =>
135
+ entry.type === "custom_message" && entry.customType === DIRECT_RESULT_TYPE ? completionDetails(entry.details).map((detail) => detail.taskId) : []));
136
+ if (persistedReceipts.has(id)) { acknowledged.add(recordKey); continue; }
137
+ }
138
+ owners.set(recordKey, owner);
139
+ }
140
+ ready.push(record.result);
141
+ } catch (error) { report(`Direct completion outbox record ${name} cannot be read: ${String(error)}`); }
142
+ }
143
+ if (!ready.length) return;
144
+ const ids = ready.map((item) => key({ sessionFile, sessionId: current.sessionManager.getSessionId(), anchor: "" }, item.details.taskId));
145
+ for (const id of ids) attempted.add(id);
146
+ try {
147
+ const message = ready.length === 1 ? ready[0]! : { customType: DIRECT_RESULT_TYPE, display: true, ...batchMessage(ready, dir) };
148
+ pi.sendMessage<unknown>(message, { triggerTurn: true, deliverAs: "followUp" });
149
+ }
150
+ catch (error) { for (const id of ids) { attempted.delete(id); releaseOwner(id); } report(`Direct completion delivery failed: ${String(error)}`); }
151
+ };
152
+ const schedule = () => {
153
+ if (scheduled) return;
154
+ scheduled = true;
155
+ setImmediate(() => { scheduled = false; flush(); });
156
+ };
157
+ return {
158
+ anchor(context: ExtensionContext): Scope {
159
+ const sessionFile = context.sessionManager.getSessionFile();
160
+ if (!sessionFile) throw new Error("Native asynchronous completion requires a saved session file.");
161
+ const token = randomUUID();
162
+ pi.appendEntry(DIRECT_OUTBOX_ANCHOR, { token });
163
+ const entry = context.sessionManager.getBranch().find((item) => item.type === "custom" && item.customType === DIRECT_OUTBOX_ANCHOR && (item.data as { token?: string })?.token === token);
164
+ if (!entry) throw new Error("Native completion anchor was not saved on the current branch.");
165
+ return { sessionId: context.sessionManager.getSessionId(), sessionFile, anchor: entry.id };
166
+ },
167
+ complete(scope: Scope, result: DirectCompletion, deliver: boolean) {
168
+ const record: RecordData = { version: 1, sessionId: scope.sessionId, anchor: scope.anchor, originEntry: scope.originEntry, result };
169
+ if (!deliver) suspended.add(key(scope, result.details.taskId));
170
+ try { save(scope, record); }
171
+ catch (error) { unsaved.set(key(scope, result.details.taskId), { scope, record }); report(`Direct completion could not be saved: ${String(error)}`); }
172
+ schedule();
173
+ },
174
+ activate(context: ExtensionContext) { ctx = context; active = true; turn = false; attempted.clear(); suspended.clear(); schedule(); },
175
+ branch(context: ExtensionContext) { for (const id of owners.keys()) releaseOwner(id); ctx = context; turn = false; attempted.clear(); suspended.clear(); schedule(); },
176
+ startTurn() { turn = true; ranSinceSettlement = true; },
177
+ endTurn(context: ExtensionContext) { ctx = context; turn = false; flush(); },
178
+ settled(context: ExtensionContext) {
179
+ ctx = context; turn = false;
180
+ if (ranSinceSettlement && !context.hasPendingMessages?.()) attempted.clear();
181
+ ranSinceSettlement = false; schedule();
182
+ },
183
+ shutdown() {
184
+ active = false; turn = false;
185
+ for (const id of owners.keys()) releaseOwner(id);
186
+ ownerToken = randomUUID();
187
+ },
188
+ };
189
+ }