@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.
- package/CONTEXT.md +2 -2
- package/README.md +20 -22
- package/dist/ephemeral.d.ts +7 -3
- package/dist/ephemeral.js +59 -11
- package/dist/herdr-runtime.js +4 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/native-host.d.ts +96 -0
- package/dist/native-host.js +243 -0
- package/dist/runner.d.ts +8 -1
- package/dist/runner.js +22 -15
- package/dist/schema.d.ts +71 -2
- package/dist/schema.js +14 -1
- package/dist/workspace-schema.d.ts +11 -0
- package/dist/workspace.d.ts +5 -2
- package/dist/workspace.js +58 -29
- package/docs/measurement.md +12 -1
- package/docs/orchestration-architecture.html +4 -4
- package/docs/orchestration-architecture.svg +2 -2
- package/docs/orchestration.md +69 -258
- package/docs/workspace.md +4 -80
- package/extensions/direct-check-exec.py +91 -0
- package/extensions/direct-check-supervisor.mjs +42 -0
- package/extensions/direct-check-witness.mjs +34 -0
- package/extensions/direct-native.ts +5 -3
- package/extensions/direct-outbox.ts +189 -0
- package/extensions/direct-owner.ts +49 -0
- package/extensions/direct-verification.ts +73 -0
- package/extensions/isolated.ts +25 -301
- package/extensions/prerequisite-evidence.ts +81 -0
- package/extensions/result-transport.ts +6 -4
- package/extensions/subagent-command.ts +12 -7
- package/extensions/subagent.ts +302 -495
- package/extensions/workflow-recovery.ts +359 -0
- package/extensions/workflow.ts +156 -40
- package/extensions/workspace.ts +16 -74
- package/package.json +8 -8
- package/skills/pi-subagent/SKILL.md +15 -37
|
@@ -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();
|
|
@@ -5,7 +5,7 @@ import { dirname, join } from "node:path";
|
|
|
5
5
|
import type { PreparedRoleLaunch } from "@henryqw/pi-subagent";
|
|
6
6
|
import { exactDirectAnswer, directTaskReader } from "../dist/direct-herdr.js";
|
|
7
7
|
import { materializeTransientLaunch } from "../dist/launch-runtime.js";
|
|
8
|
-
import { EphemeralSubagentError, utf8Prefix, type EphemeralSubagentExecutor } from "../dist/ephemeral.js";
|
|
8
|
+
import { EphemeralSubagentError, utf8Prefix, type EphemeralSubagentExecutor, type EphemeralSubagentActivityEvent } from "../dist/ephemeral.js";
|
|
9
9
|
import { PI_SUBAGENT_PROCESS_LEASE, processLeaseIdentity, type ProcessLeaseIdentity } from "../dist/process-lease.js";
|
|
10
10
|
|
|
11
11
|
export type NativeSession = { sessionFile: string; leasePath: string; leaseIdentity: ProcessLeaseIdentity; turn: string; cwd: string; role: string };
|
|
@@ -24,13 +24,15 @@ export async function runNativeDirect(input: {
|
|
|
24
24
|
prepare: () => Promise<PreparedRoleLaunch>;
|
|
25
25
|
source?: NativeSession;
|
|
26
26
|
onSession: (session: NativeSession) => void;
|
|
27
|
+
onTokens: (tokens: number) => void;
|
|
28
|
+
onActivity: (event: EphemeralSubagentActivityEvent) => void;
|
|
27
29
|
onUsage: (usage: { totalTokens: number; cost: { total: number } }) => void;
|
|
28
30
|
}): Promise<{ text: string; inline: string; answerFile?: string }> {
|
|
29
31
|
let transient: Awaited<ReturnType<typeof materializeTransientLaunch>> | undefined;
|
|
30
32
|
let session!: NativeSession;
|
|
31
33
|
let prompt = "";
|
|
32
34
|
try {
|
|
33
|
-
const result = await input.executor.run({ signal: input.signal, onProcessEnd: input.onProcessEnd, prepare: async () => {
|
|
35
|
+
const result = await input.executor.run({ signal: input.signal, retryReadOnlySpawn: !input.write, onProcessEnd: input.onProcessEnd, onTokens: input.onTokens, onActivity: input.onActivity, prepare: async () => {
|
|
34
36
|
const prepared = await input.prepare();
|
|
35
37
|
input.signal.throwIfAborted();
|
|
36
38
|
const directory = input.source ? dirname(input.source.sessionFile) : await mkdtemp(join(tmpdir(), "pi-subagent-native-"));
|
|
@@ -66,7 +68,7 @@ export async function runNativeDirect(input: {
|
|
|
66
68
|
const bytes = Buffer.byteLength(text);
|
|
67
69
|
if (bytes <= input.answerBytes) return { text, inline: text };
|
|
68
70
|
const answerFile = join(dirname(session.sessionFile), `answer-${session.turn}.md`);
|
|
69
|
-
await writeFile(answerFile, text, { flag: "wx", mode:
|
|
71
|
+
await writeFile(answerFile, text, { flag: "wx", mode: 0o400, flush: true });
|
|
70
72
|
return { text, inline: `${utf8Prefix(text, input.answerBytes)}\n\n[Answer truncated to ${input.answerBytes} of ${bytes} bytes; full answer saved]`, answerFile };
|
|
71
73
|
} catch (error) {
|
|
72
74
|
if (error instanceof EphemeralSubagentError && error.usage) input.onUsage(error.usage);
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
const HANDOFF_LIMIT = 64;
|
|
7
|
+
|
|
8
|
+
export function ownerAlive(owner: { host: string; pid: number }) {
|
|
9
|
+
if (owner.host !== hostname()) return true; // A different host cannot prove the original process stopped.
|
|
10
|
+
try { process.kill(owner.pid, 0); return true; }
|
|
11
|
+
catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function claimOwner(root: string, name: string, token: string): string | undefined {
|
|
15
|
+
let target = join(root, name);
|
|
16
|
+
const candidate = join(root, `.${randomUUID()}.claim`);
|
|
17
|
+
mkdirSync(candidate, { mode: 0o700 });
|
|
18
|
+
try {
|
|
19
|
+
const fd = openSync(join(candidate, "owner.json"), "wx", 0o600);
|
|
20
|
+
try { writeFileSync(fd, JSON.stringify({ host: hostname(), pid: process.pid, token })); fsyncSync(fd); }
|
|
21
|
+
finally { closeSync(fd); }
|
|
22
|
+
const candidateDir = openSync(candidate, "r");
|
|
23
|
+
try { fsyncSync(candidateDir); } finally { closeSync(candidateDir); }
|
|
24
|
+
for (let generation = 0; generation < HANDOFF_LIMIT; generation++) {
|
|
25
|
+
try {
|
|
26
|
+
renameSync(candidate, target);
|
|
27
|
+
const parent = openSync(root, "r");
|
|
28
|
+
try { fsyncSync(parent); } finally { closeSync(parent); }
|
|
29
|
+
return target;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (!["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
32
|
+
const ownerData = readFileSync(join(target, "owner.json"), "utf8");
|
|
33
|
+
const owner = JSON.parse(ownerData) as { host: string; pid: number; token?: string };
|
|
34
|
+
if (!owner || typeof owner.host !== "string" || !Number.isSafeInteger(owner.pid) || owner.pid < 1) return undefined;
|
|
35
|
+
if (owner.host === hostname() && owner.pid === process.pid && owner.token === token && !existsSync(join(target, "released"))) return target;
|
|
36
|
+
if (ownerAlive(owner) && !existsSync(join(target, "released"))) return undefined;
|
|
37
|
+
// Each immutable predecessor determines exactly one successor slot.
|
|
38
|
+
const predecessor = createHash("sha256").update(target).update("\0").update(ownerData).digest("hex");
|
|
39
|
+
target = join(root, `${name}.${predecessor}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
throw new Error("Recovery handoff generation limit reached.");
|
|
43
|
+
} finally {
|
|
44
|
+
if (existsSync(candidate)) {
|
|
45
|
+
try { unlinkSync(join(candidate, "owner.json")); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
46
|
+
try { rmdirSync(candidate); } catch { /* Retain a failed cleanup. */ }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { open } from "node:fs/promises";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { processLeaseIdentity } from "../dist/process-lease.js";
|
|
6
|
+
import type { NativeSession } from "./direct-native.ts";
|
|
7
|
+
import { VERIFICATION_LIMITS, type Delegation } from "./workflow.ts";
|
|
8
|
+
|
|
9
|
+
type Check = NonNullable<Delegation["verification"]>["checks"][number];
|
|
10
|
+
export type VerificationProof = { state: "pending" | "proved" | "lost" };
|
|
11
|
+
|
|
12
|
+
/** A private supervisor holds the exact lease until the check group is empty. */
|
|
13
|
+
export async function runAcceptanceCheck(check: Check, session: NativeSession, signal: AbortSignal, scope: () => boolean, onWitness?: (proof: VerificationProof) => void): Promise<{ code: number; output: string }> {
|
|
14
|
+
signal.throwIfAborted();
|
|
15
|
+
if (!scope()) throw new Error("Verification scope changed before launch.");
|
|
16
|
+
if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("Verification process groups require macOS or Linux.");
|
|
17
|
+
const file = await open(session.leasePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
18
|
+
try {
|
|
19
|
+
const identity = await processLeaseIdentity(session.leasePath, session.leaseIdentity);
|
|
20
|
+
const actual = await file.stat({ bigint: true });
|
|
21
|
+
if (String(actual.dev) !== identity.device || String(actual.ino) !== identity.inode) throw new Error("Verification lease descriptor changed.");
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
if (!scope()) throw new Error("Verification scope changed before launch.");
|
|
24
|
+
return await new Promise((resolve, reject) => {
|
|
25
|
+
const witnessArgs = [fileURLToPath(new URL("./direct-check-witness.mjs", import.meta.url)), String(check.timeoutMs), check.executable, ...check.args];
|
|
26
|
+
const linux = process.platform === "linux";
|
|
27
|
+
const args = linux ? ["-I", fileURLToPath(new URL("./direct-check-exec.py", import.meta.url)), "reap", process.execPath, ...witnessArgs] : witnessArgs;
|
|
28
|
+
const child = spawn(linux ? "/usr/bin/python3" : process.execPath, args,
|
|
29
|
+
{ cwd: session.cwd, stdio: ["ignore", "pipe", "pipe", file.fd, "ipc"], detached: true });
|
|
30
|
+
let settled = false, interrupted = "", size = 0, truncated = false;
|
|
31
|
+
let result: { code?: number; error?: string } | undefined;
|
|
32
|
+
const chunks: Buffer[] = [];
|
|
33
|
+
const collect = (chunk: Buffer) => {
|
|
34
|
+
const remaining = VERIFICATION_LIMITS.outputBytes - size;
|
|
35
|
+
if (remaining > 0) { const part = chunk.subarray(0, remaining); chunks.push(part); size += part.length; }
|
|
36
|
+
if (chunk.length > remaining) truncated = true;
|
|
37
|
+
};
|
|
38
|
+
child.stdout!.on("data", collect);
|
|
39
|
+
child.stderr!.on("data", collect);
|
|
40
|
+
const proof: VerificationProof = { state: "pending" };
|
|
41
|
+
onWitness?.(proof);
|
|
42
|
+
child.on("message", (message) => {
|
|
43
|
+
if (message && typeof message === "object") result = message as typeof result;
|
|
44
|
+
});
|
|
45
|
+
const lost = () => { if (proof.state === "pending") proof.state = "lost"; };
|
|
46
|
+
child.once("error", lost);
|
|
47
|
+
// The message proves the group is empty; exit proves the witness no longer holds the lease.
|
|
48
|
+
child.once("exit", () => { if (proof.state === "pending") proof.state = result ? "proved" : "lost"; });
|
|
49
|
+
let hard: ReturnType<typeof setTimeout> | undefined;
|
|
50
|
+
const stop = (reason: string) => {
|
|
51
|
+
if (interrupted) return;
|
|
52
|
+
interrupted = reason;
|
|
53
|
+
if (child.connected) child.send("stop", () => {});
|
|
54
|
+
hard = setTimeout(() => finish(new Error(`${reason}; process exit was not observed.`)), 2000);
|
|
55
|
+
};
|
|
56
|
+
const abort = () => stop("Verification cancelled");
|
|
57
|
+
const timer = setTimeout(() => stop("Verification timed out"), check.timeoutMs);
|
|
58
|
+
const finish = (error?: Error, code?: number | null, termination?: NodeJS.Signals | null) => {
|
|
59
|
+
if (settled) return;
|
|
60
|
+
settled = true;
|
|
61
|
+
clearTimeout(timer); if (hard) clearTimeout(hard);
|
|
62
|
+
signal.removeEventListener("abort", abort);
|
|
63
|
+
child.stdout!.destroy(); child.stderr!.destroy();
|
|
64
|
+
if (error || interrupted || code !== 0 || termination || !result || typeof result.code !== "number") reject(error ?? new Error(interrupted || result?.error || `Verification supervisor ended without an exit result${termination ? ` (${termination})` : ""}.`));
|
|
65
|
+
else resolve({ code: result.code, output: Buffer.concat(chunks).toString("utf8") + (truncated ? "\n[output truncated]" : "") });
|
|
66
|
+
};
|
|
67
|
+
child.once("error", (error) => finish(error));
|
|
68
|
+
child.once("close", (code, termination) => finish(undefined, code, termination));
|
|
69
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
70
|
+
if (signal.aborted) abort();
|
|
71
|
+
});
|
|
72
|
+
} finally { await file.close(); }
|
|
73
|
+
}
|