pi-better-server 0.2.4 → 0.4.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 (109) hide show
  1. package/package.json +6 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +165 -0
  5. package/scripts/test-on-pi.sh +21 -3
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +48 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +7 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +182 -0
  16. package/src/runtime/cancellation.ts +99 -0
  17. package/src/runtime/catalog-admission.ts +50 -0
  18. package/src/runtime/catalog.ts +133 -0
  19. package/src/runtime/client.ts +111 -0
  20. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  21. package/src/runtime/domain/assignment-observation.mjs +120 -0
  22. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  23. package/src/runtime/domain/assignment-projection.mjs +245 -0
  24. package/src/runtime/domain/background/conditions.mjs +93 -0
  25. package/src/runtime/domain/background/process-identity.mjs +110 -0
  26. package/src/runtime/domain/background/process.mjs +511 -0
  27. package/src/runtime/domain/background/registry.mjs +374 -0
  28. package/src/runtime/domain/background/snapshot.mjs +73 -0
  29. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  30. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  31. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  32. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  33. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  34. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  35. package/src/runtime/domain/background/types.mjs +3 -0
  36. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  37. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  38. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  39. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  40. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  41. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  42. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  43. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  44. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  45. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  46. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  47. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  48. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  49. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  50. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  51. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  52. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  53. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  54. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  55. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  56. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  57. package/src/runtime/domain/coordinator/index.mjs +50 -0
  58. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  59. package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
  60. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  61. package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
  62. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  63. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  64. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  65. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  66. package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
  67. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  68. package/src/runtime/domain/coordinator/src/store.mjs +245 -0
  69. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  70. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  71. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  72. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  73. package/src/runtime/domain/health-observation.d.mts +3 -0
  74. package/src/runtime/domain/health-observation.mjs +613 -0
  75. package/src/runtime/domain/health-surface.mjs +279 -0
  76. package/src/runtime/domain/log-cursor.mjs +148 -0
  77. package/src/runtime/domain/log-paths.mjs +13 -0
  78. package/src/runtime/domain/parse.d.mts +2 -0
  79. package/src/runtime/domain/parse.mjs +1173 -0
  80. package/src/runtime/domain/process-status.d.mts +1 -0
  81. package/src/runtime/domain/process-status.mjs +25 -0
  82. package/src/runtime/domain/session-store.d.mts +2 -0
  83. package/src/runtime/domain/session-store.mjs +489 -0
  84. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  85. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  86. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  87. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  88. package/src/runtime/domain/widget.d.mts +1 -0
  89. package/src/runtime/domain/widget.mjs +250 -0
  90. package/src/runtime/guardian.ts +189 -0
  91. package/src/runtime/health-config.ts +27 -0
  92. package/src/runtime/local-client.ts +34 -0
  93. package/src/runtime/mutation-store.ts +34 -0
  94. package/src/runtime/queries.ts +76 -0
  95. package/src/runtime/query-executor.ts +277 -0
  96. package/src/runtime/query-worker.mjs +119 -0
  97. package/src/runtime/read-model.ts +409 -0
  98. package/src/runtime/result-supervision.ts +63 -0
  99. package/src/runtime/root.ts +29 -0
  100. package/src/runtime/socket.ts +10 -0
  101. package/src/runtime/status-cli.ts +11 -0
  102. package/src/runtime/work-client.d.mts +14 -0
  103. package/src/runtime/work-client.mjs +102 -0
  104. package/src/server.ts +199 -14
  105. package/src/session-activity.ts +22 -2
  106. package/src/startup/activation.ts +32 -5
  107. package/src/startup/ensure.ts +13 -1
  108. package/src/startup/install.ts +2 -0
  109. package/src/version.ts +4 -0
@@ -0,0 +1,133 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { loadCatalog, saveDefinition, resetRuntimeToBundled, resetUserDefinition, listScopedAgents } from "./domain/catalog/catalog-store.mjs";
3
+ import { withAgentSessionSettings, saveAgentSessionDefaults } from "./domain/catalog/agent-session-settings.mjs";
4
+ import { saveSkillExposure } from "./domain/catalog/catalog-skill-edits.mjs";
5
+ import { parseDefinition } from "./domain/catalog/catalog-schema.mjs";
6
+ import { CatalogAdmission } from "./catalog-admission.ts";
7
+ import { overlayDigest } from "./domain/catalog/catalog-overlay.mjs";
8
+ import { watch, type FSWatcher } from "node:fs";
9
+ import { dirname } from "node:path";
10
+
11
+ /** One server-owned filesystem catalog; registrations belong to the live socket. */
12
+ export class SharedCatalog {
13
+ private agentDir: string;
14
+ readonly admission: CatalogAdmission;
15
+ private observers = new Set<() => void>();
16
+ private timer?: ReturnType<typeof setInterval>;
17
+ private pending?: ReturnType<typeof setTimeout>;
18
+ private watchers = new Map<string, { watcher: FSWatcher; references: number }>();
19
+ constructor(agentDir: string, instanceId: string) { this.agentDir = agentDir; this.admission = new CatalogAdmission(agentDir, instanceId); }
20
+
21
+ observe(read: () => any, emit: (snapshot: any) => void) {
22
+ if (this.observers.size >= 64) throw new Error("catalog-subscription-limit");
23
+ let revision: string | undefined, seq = 0;
24
+ const watched: string[] = [];
25
+ const initial = read();
26
+ const paths = new Set<string>([this.agentDir, ...[...initial.roles, ...initial.agents].map(([, entry]: any) => dirname(entry.path))]);
27
+ const notify = () => { this.pending ??= setTimeout(() => { this.pending = undefined; for (const reconcile of this.observers) reconcile(); }, 50); this.pending.unref(); };
28
+ for (const path of paths) {
29
+ const existing = this.watchers.get(path);
30
+ if (existing) { existing.references++; watched.push(path); continue; }
31
+ try {
32
+ const watcher = watch(path, { persistent: false }, notify); watcher.on("error", notify);
33
+ this.watchers.set(path, { watcher, references: 1 }); watched.push(path);
34
+ } catch { /* Bounded reconciliation also discovers newly created paths. */ }
35
+ }
36
+ const reconcile = () => {
37
+ let snapshot;
38
+ try { snapshot = read(); } catch { snapshot = { revision: "revoked", status: "revoked", roles: [], agents: [], diagnostics: [] }; }
39
+ if (snapshot.revision === revision) return;
40
+ revision = snapshot.revision;
41
+ emit({ ...snapshot, seq: ++seq });
42
+ };
43
+ revision = initial.revision;
44
+ this.observers.add(reconcile);
45
+ this.timer ??= setInterval(() => { for (const reconcile of this.observers) reconcile(); }, 1000);
46
+ this.timer.unref();
47
+ return { snapshot: { ...initial, seq }, close: () => {
48
+ this.observers.delete(reconcile);
49
+ for (const path of watched) { const entry = this.watchers.get(path); if (entry && --entry.references === 0) { entry.watcher.close(); this.watchers.delete(path); } }
50
+ if (!this.observers.size) { clearInterval(this.timer); this.timer = undefined; clearTimeout(this.pending); this.pending = undefined; }
51
+ } };
52
+ }
53
+
54
+ connection() {
55
+ let registration: { cwd: string; sessionId: string; projectAccess: boolean; authority?: unknown } | undefined;
56
+ const location = () => {
57
+ if (!registration) throw new Error("catalog-unregistered: register a workspace first");
58
+ if (realpathSync(registration.cwd) !== registration.cwd) throw new Error("catalog-workspace-changed");
59
+ if (!registration.authority) throw new Error("catalog-authority-refused: register through the Pi host adapter");
60
+ const grant = this.admission.verify(registration.authority);
61
+ if (grant && (grant.cwd !== registration.cwd || grant.sessionId !== registration.sessionId)) throw new Error("catalog-scope-refused");
62
+ return { cwd: registration.cwd, userRoot: this.agentDir, projectTrusted: registration.projectAccess && grant.projectTrusted === true };
63
+ };
64
+ return (command: Record<string, unknown>) => {
65
+ if (command.type === "runtime_register_catalog") {
66
+ if (typeof command.cwd !== "string" || typeof command.sessionId !== "string" || !command.sessionId) throw new Error("Invalid catalog registration");
67
+ registration = { cwd: realpathSync(command.cwd), sessionId: command.sessionId, projectAccess: command.projectAccess !== "deny", authority: command.authority };
68
+ location();
69
+ return { cwd: registration.cwd, sessionId: registration.sessionId, projectTrusted: location().projectTrusted };
70
+ }
71
+ const loc = location();
72
+ if (command.type === "runtime_get_catalog_scope") {
73
+ if (command.scope !== "user" && command.scope !== "project") throw new Error("Invalid catalog scope");
74
+ return listScopedAgents(loc, command.scope);
75
+ }
76
+ const snapshot = loadCatalog(loc);
77
+ if (command.type === "runtime_get_catalog") {
78
+ const overlay = validateOverlay(command.overlay);
79
+ if (registration?.authority && command.overlay !== undefined) {
80
+ const grant = this.admission.verify(registration.authority);
81
+ const digest = overlayDigest(overlay);
82
+ if (digest !== grant.overlayDigest) throw new Error("catalog-overlay-refused");
83
+ }
84
+ const view = withAgentSessionSettings(snapshot, overlay);
85
+ return { ...view, roles: [...view.roles], agents: [...view.agents] };
86
+ }
87
+ if (command.type !== "runtime_edit_catalog") throw new Error("Unknown catalog command");
88
+ if (!registration?.authority) throw new Error("catalog-authority-refused: edits require a live host grant");
89
+ // No await between comparison and atomic domain write: cooperating clients
90
+ // serialize here. External writers do not participate in this transaction.
91
+ if (typeof command.expectedRevision !== "string" || command.expectedRevision !== snapshot.revision) throw new Error("catalog-conflict: content revision changed; reload before editing");
92
+ const id = command.catalogId;
93
+ if (typeof id !== "string") throw new Error("Invalid catalog id");
94
+ const entry = snapshot.roles.get(id) ?? snapshot.agents.get(id);
95
+ if (command.action === "reset-runtime" || command.action === "reset-definition") {
96
+ if (!entry) throw new Error("Catalog definition not found");
97
+ const reset = command.action === "reset-runtime" ? resetRuntimeToBundled : resetUserDefinition;
98
+ return reset({ ...loc, id, expectedPath: entry.path, expectedDigest: entry.contentDigest });
99
+ }
100
+ if (command.action === "preferences") {
101
+ return saveAgentSessionDefaults(snapshot, id, validateOverlay({ [id]: command.preferences }), loc);
102
+ }
103
+ if (command.action === "skills") {
104
+ if (!entry) throw new Error("Catalog definition not found");
105
+ const edit = command.edit as { mode?: string; paths?: unknown } | undefined;
106
+ if (!edit || !["inherit", "none", "explicit"].includes(edit.mode ?? "") || edit.mode === "explicit" && (!Array.isArray(edit.paths) || !edit.paths.every(p => typeof p === "string"))) throw new Error("Invalid skill edit");
107
+ return saveSkillExposure({ ...loc, entry: { id, winningSource: { path: entry.path, contentDigest: entry.contentDigest } } }, edit as import("./domain/catalog/catalog-schema.mjs").SkillExposureEdit);
108
+ }
109
+ if (command.action === "definition") {
110
+ if (command.scope !== "user" && command.scope !== "project") throw new Error("Catalog scope must be user or project; builtins are read-only");
111
+ if (command.scope === "project" && !loc.projectTrusted) throw new Error("catalog-untrusted: project writes refused");
112
+ if (typeof command.markdown !== "string") throw new Error("Definition must be Markdown");
113
+ const parsed = parseDefinition(command.markdown);
114
+ if (!parsed.definition || parsed.diagnostics.some(d => d.blocking) || parsed.definition.id !== id) throw new Error("Invalid catalog definition: " + parsed.diagnostics.map(d => d.message).join(" "));
115
+ return saveDefinition({ ...loc, definition: parsed.definition, scope: command.scope, replace: command.replace === true });
116
+ }
117
+ throw new Error("Unknown catalog edit action");
118
+ };
119
+ }
120
+ }
121
+
122
+ function validateOverlay(value: unknown): import("./domain/catalog/agent-session-settings.mjs").AgentSessionOverrides {
123
+ if (value === undefined) return {};
124
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid catalog overlay");
125
+ for (const [id, patch] of Object.entries(value)) {
126
+ if (!/^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id) || !patch || typeof patch !== "object" || Array.isArray(patch)) throw new Error("Invalid catalog overlay");
127
+ for (const [key, item] of Object.entries(patch)) {
128
+ if (key === "model" ? item !== null && (typeof item !== "string" || !/^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(item))
129
+ : key !== "effort" || item !== null && !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(item as string)) throw new Error("Invalid catalog preference");
130
+ }
131
+ }
132
+ return value as import("./domain/catalog/agent-session-settings.mjs").AgentSessionOverrides;
133
+ }
@@ -0,0 +1,111 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, openSync, readFileSync } from "node:fs";
3
+ import { connect } from "node:net";
4
+ import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ import { stageRuntime } from "../startup/install.ts";
8
+ import { inspectDaemonOwner } from "../daemon-owner.ts";
9
+ import type { RunRemote, ServerArtifact } from "../startup/managed-types.ts";
10
+ import { runtimeRoot } from "./root.ts";
11
+ import { socketPathFor } from "./socket.ts";
12
+ export { WorkClient } from "./work-client.mjs";
13
+
14
+ export interface RuntimeOptions {
15
+ agentDir: string;
16
+ serverDir?: string;
17
+ installRoot?: string;
18
+ timeoutMs?: number;
19
+ signal?: AbortSignal;
20
+ onProgress?: (stage: string) => void;
21
+ offline?: boolean;
22
+ }
23
+
24
+ /** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
25
+ export async function runtimeStatus(socketPath: string, agentDir: string, artifact: ServerArtifact, timeoutMs = 2000): Promise<any> {
26
+ return new Promise((resolve, reject) => {
27
+ const socket = connect(socketPath);
28
+ const timer = setTimeout(() => { socket.destroy(); reject(new Error(`runtime-unhealthy: no response at ${socketPath}; inspect the live owner`)); }, timeoutMs);
29
+ let buffer = "", greeted = false;
30
+ const fail = (error: Error) => { clearTimeout(timer); socket.destroy(); reject(error); };
31
+ socket.on("error", fail);
32
+ socket.on("end", () => fail(new Error("runtime-unavailable: server closed the connection")));
33
+ socket.on("connect", () => socket.write(JSON.stringify({ id: "hello", type: "hello", protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-status-v1"] }) + "\n"));
34
+ socket.setEncoding("utf8");
35
+ socket.on("data", (chunk: string) => {
36
+ buffer += chunk;
37
+ if (buffer.length > 1024 * 1024) return fail(new Error("runtime-unhealthy: response exceeds 1 MiB"));
38
+ while (buffer.includes("\n")) {
39
+ const index = buffer.indexOf("\n"), line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
40
+ try {
41
+ const reply = JSON.parse(line);
42
+ if (!reply.success) throw new Error(reply.error ?? "runtime-unavailable");
43
+ const data = reply.data;
44
+ if (!greeted) {
45
+ if (reply.id !== "hello" || data?.protocolVersion !== 1 || data.agentDir !== agentDir
46
+ || data.build?.contentId !== artifact.build.contentId || data.nodeVersion !== artifact.build.nodeVersion
47
+ || !data.capabilities?.includes("runtime-status-v1") || !data.instanceId) throw new Error("capability-mismatch: root, pinned build, Node or runtime capability differs; update the installed packages together");
48
+ greeted = true;
49
+ socket.write(JSON.stringify({ id: "status", type: "runtime_get_status" }) + "\n");
50
+ } else {
51
+ if (reply.id !== "status") throw new Error("runtime-unhealthy: unexpected response");
52
+ clearTimeout(timer); socket.destroy(); resolve(data);
53
+ }
54
+ } catch (error) { return fail(error as Error); }
55
+ }
56
+ });
57
+ });
58
+ }
59
+
60
+ const runLocal: RunRemote = (command, input, timeoutMs) => new Promise((resolve, reject) => {
61
+ const child = spawn("/bin/sh", ["-c", command], { stdio: "pipe", timeout: timeoutMs });
62
+ let stdout = "", stderr = "";
63
+ child.stdout.on("data", chunk => { stdout += chunk; });
64
+ child.stderr.on("data", chunk => { stderr += chunk; });
65
+ child.on("error", reject);
66
+ child.stdin.on("error", () => undefined);
67
+ child.on("close", (exitCode, signal) => resolve({ stdout, stderr, exitCode, timedOut: signal === "SIGTERM" }));
68
+ child.stdin.end(input);
69
+ });
70
+
71
+ export async function ensureRuntime(options: RuntimeOptions): Promise<any> {
72
+ options.signal?.throwIfAborted();
73
+ const timeoutMs = options.timeoutMs ?? 15000;
74
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) throw new Error("Runtime timeout must be from 1 to 120000 ms");
75
+ const platform = `${process.platform}-${process.arch}`;
76
+ const directory = fileURLToPath(new URL("../../artifacts/", import.meta.url));
77
+ let artifact: ServerArtifact;
78
+ try {
79
+ const manifest = JSON.parse(readFileSync(join(directory, `${platform}.json`), "utf8"));
80
+ artifact = { ...manifest, bytes: readFileSync(join(directory, `${platform}.gz`)) };
81
+ } catch (error) { throw new Error(`runtime-unavailable: cannot read pinned artifact for ${platform}; reinstall the standalone package. ${String(error)}`); }
82
+ const { decodeServerArtifact } = await import("../startup/artifact.ts");
83
+ decodeServerArtifact(artifact);
84
+ const root = runtimeRoot(options.agentDir, options.serverDir ?? join(options.agentDir, "server"));
85
+ const socketPath = socketPathFor(root.serverDir);
86
+ const query = () => runtimeStatus(socketPath, root.agentDir, artifact, Math.min(timeoutMs, 2000));
87
+ try { return await query(); }
88
+ catch (error) {
89
+ if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
90
+ }
91
+ const owner = inspectDaemonOwner(root.serverDir);
92
+ if (owner.status === "live" || owner.status === "ambiguous") throw new Error(`runtime-unhealthy: existing ${owner.status} owner at ${root.serverDir}; no replacement was started`);
93
+ let runtime;
94
+ try { runtime = await stageRuntime({ run: runLocal, artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline }); }
95
+ catch (error) { throw new Error(`runtime-unavailable: ${String(error)}. Connect to the network to cache the pinned runtime, or repair the reported corrupt cache; no fallback manager was started.`); }
96
+ const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
97
+ try {
98
+ const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
99
+ for (const key of ["NODE_OPTIONS", "PI_SERVER_ACTIVATION_ID", "PI_SERVER_ROLLBACK_OPERATION_ID", "PI_SERVER_ROLLBACK_PERMIT"]) delete (env as NodeJS.ProcessEnv)[key];
100
+ const child = spawn(runtime.node, [runtime.entrypoint, "--agent", "pi"], { cwd: root.serverDir, env, detached: true, stdio: ["ignore", fd, fd] });
101
+ child.on("error", () => undefined); child.unref();
102
+ } finally { closeSync(fd); }
103
+ const deadline = Date.now() + timeoutMs;
104
+ while (Date.now() < deadline) {
105
+ options.signal?.throwIfAborted();
106
+ try { return await query(); }
107
+ catch (error) { if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
108
+ await delay(50, undefined, { signal: options.signal });
109
+ }
110
+ throw new Error(`runtime-unavailable: startup timed out; inspect ${join(root.serverDir, "daemon.log")}; owner was not replaced`);
111
+ }
@@ -0,0 +1 @@
1
+ export function createAssignmentReader(path: string): { revision(): string; beginSnapshot(): { revision: string; release(): void }; read(owner: any): any; conversationRevisions(): Map<string, string> | undefined; close(): void };
@@ -0,0 +1,120 @@
1
+ // Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
2
+ import { createRequire } from "node:module";
3
+ import { createHash } from "node:crypto";
4
+
5
+ /** Read-only, bounded projection input. Never creates/migrates a database. */
6
+ export function readAssignmentWaits(path, owner, connection) {
7
+ let db;
8
+ try {
9
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
10
+ db = connection ?? new DatabaseSync(path, { readOnly: true });
11
+ // v4 adds repair accounting; the observed wait/outcome fields are unchanged.
12
+ if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
13
+ return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
14
+ }
15
+ const rows = db.prepare(`SELECT wait_id, generation, phase, phase_reason,
16
+ acknowledgement_json, cancel_epoch FROM waits
17
+ WHERE owner_kind = 'worker-conversation' AND owner_session_id = ? AND owner_workspace = ?
18
+ ${owner.assignmentId ? "AND json_extract(origin_json, '$.assignmentRef') = ?" : `AND (
19
+ EXISTS (SELECT 1 FROM json_each(?) AS attempt
20
+ WHERE attempt.value = json_extract(waits.origin_json, '$.attemptId')
21
+ OR attempt.value = json_extract(waits.park_json, '$.attemptId'))
22
+ OR EXISTS (SELECT 1 FROM resume_claims AS claim, json_each(?) AS attempt
23
+ WHERE claim.wait_id = waits.wait_id AND claim.generation = waits.generation
24
+ AND claim.attempt_id = attempt.value)
25
+ OR EXISTS (SELECT 1 FROM json_each(?) AS ref
26
+ WHERE json_extract(ref.value, '$.waitId') = waits.wait_id
27
+ AND json_extract(ref.value, '$.generation') = waits.generation)
28
+ )`}
29
+ ORDER BY created_at DESC, generation DESC LIMIT 100`).all(owner.sessionId, owner.workspace,
30
+ ...(owner.assignmentId ? [owner.assignmentId] : [JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.waitRefs ?? [])]));
31
+ const record = owner.assignmentId ? db.prepare("SELECT record_json FROM assignment_outcomes WHERE assignment_id = ?").get(owner.assignmentId) : null;
32
+ const outcome = record ? JSON.parse(record.record_json) : null;
33
+ if (outcome && (outcome.owner.sessionId !== owner.sessionId || outcome.owner.workspace !== owner.workspace)) throw new Error("Foreign assignment outcome");
34
+ return { verified: true, outcome, waits: rows.map((row) => ({
35
+ waitId: row.wait_id, generation: row.generation, phase: row.phase,
36
+ reason: row.phase_reason, cancelEpoch: row.cancel_epoch,
37
+ acknowledgement: row.acknowledgement_json ? JSON.parse(row.acknowledgement_json) : null,
38
+ })) };
39
+ } catch {
40
+ return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
41
+ } finally {
42
+ if (!connection) db?.close();
43
+ }
44
+ }
45
+
46
+ /** A root read model owns this connection; ordinary observers remain one-shot. */
47
+ export function createAssignmentReader(path) {
48
+ let db;
49
+ let identity;
50
+ let snapshot = false;
51
+ const statements = new Map();
52
+ return {
53
+ revision() {
54
+ const { statSync } = createRequire(import.meta.url)("node:fs");
55
+ const stat = statSync(path, { bigint: true });
56
+ const next = `${stat.dev}:${stat.ino}`;
57
+ if (identity !== next) {
58
+ if (snapshot) throw new Error("Coordinator identity changed during observation");
59
+ db?.close();
60
+ db = undefined;
61
+ statements.clear();
62
+ identity = next;
63
+ }
64
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
65
+ db ??= new DatabaseSync(path, { readOnly: true });
66
+ return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
67
+ },
68
+ beginSnapshot() {
69
+ this.revision();
70
+ if (snapshot) throw new Error("Coordinator snapshot already open");
71
+ db.exec("BEGIN");
72
+ snapshot = true;
73
+ const release = () => {
74
+ if (!snapshot) return;
75
+ try { db.exec("ROLLBACK"); } finally { snapshot = false; }
76
+ };
77
+ try {
78
+ // Pin the WAL read view before recording its revision; other writers keep advancing.
79
+ db.prepare("SELECT count(*) FROM sqlite_schema").get();
80
+ return { revision: this.revision(), release };
81
+ } catch (error) { release(); throw error; }
82
+ },
83
+ read(owner) {
84
+ try {
85
+ this.revision();
86
+ return readAssignmentWaits(path, owner, { prepare(sql) {
87
+ if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
88
+ return statements.get(sql);
89
+ } });
90
+ } catch {
91
+ return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
92
+ }
93
+ },
94
+ conversationRevisions() {
95
+ try {
96
+ this.revision();
97
+ if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
98
+ const hashes = new Map();
99
+ const add = (sessionId, workspace, value) => {
100
+ const key = JSON.stringify([sessionId, workspace]);
101
+ if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
102
+ hashes.get(key).update(JSON.stringify(value));
103
+ };
104
+ // One source pass per changed database revision, instead of one
105
+ // projection/query/log parse for every historical attempt.
106
+ for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
107
+ FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
108
+ FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
109
+ add(row.owner_session_id, row.owner_workspace, row);
110
+ }
111
+ for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
112
+ const record = JSON.parse(row.record_json);
113
+ add(record.owner.sessionId, record.owner.workspace, record);
114
+ }
115
+ return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
116
+ } catch { return undefined; }
117
+ },
118
+ close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
119
+ };
120
+ }
@@ -0,0 +1 @@
1
+ export function createAssignmentProjector(options?: { attempts?: any[]; observe?: (owner: any) => any }): (meta: any, processStatus?: string) => any;
@@ -0,0 +1,245 @@
1
+ // Generated from packages/pi-better-subagents/assignment-projection.mjs. Do not edit directly.
2
+ import { createHash } from "node:crypto";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { readFileSync, readdirSync, statSync } from "node:fs";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { readAssignmentWaits } from "./assignment-observation.mjs";
8
+
9
+ export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
10
+ const observations = new AsyncLocalStorage();
11
+
12
+ /** Bind an immutable observation to one read call, never to a supervision loop. */
13
+ export function withAssignmentObservations(rows, read) {
14
+ return observations.run(new Map(rows.map(row => [row.meta.id, row.assignment])), read);
15
+ }
16
+
17
+ /** A projection revision is a content-addressed semantic token, not a clock. */
18
+ export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
19
+ const waits = observation.waits;
20
+ const pending = waits.find((wait) => !["consumed", "cancelled"].includes(wait.phase));
21
+ let state;
22
+ let reason;
23
+ if (observation.outcome) {
24
+ state = { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[observation.outcome.outcome];
25
+ reason = observation.outcome.reason;
26
+ } else if (waits[0]?.phase === "cancelled") {
27
+ state = "cancelled";
28
+ reason = waits[0]?.reason || "Assignment explicitly cancelled.";
29
+ } else if (!observation.verified && (meta.operations || meta.park)) {
30
+ state = "waiting";
31
+ reason = observation.reason;
32
+ } else if (pending) {
33
+ state = "waiting";
34
+ reason = pending.reason || (pending.phase === "ready" || pending.phase === "resuming"
35
+ ? "Dependency evidence awaits worker interpretation."
36
+ : "Waiting for dependencies and supervised continuation.");
37
+ } else if (meta.status === "killed") {
38
+ state = "cancelled";
39
+ reason = "Assignment explicitly cancelled.";
40
+ } else if (processStatus === "running") {
41
+ state = "running";
42
+ reason = "Worker is advancing the assignment.";
43
+ } else if (meta.status === "failed") {
44
+ state = "failed";
45
+ reason = meta.failureReason || "Worker execution failed; retained evidence is available.";
46
+ } else if (meta.status === "completed" && !String(meta.lifecycleClassification ?? "").startsWith("incomplete") && (!meta.park || waits.some((wait) =>
47
+ wait.acknowledgement?.disposition === "assignment-complete"))) {
48
+ state = "completed";
49
+ reason = "Assigned work and required interpretation are complete.";
50
+ } else {
51
+ state = "waiting";
52
+ reason = meta.park && waits.some((wait) => wait.phase === "consumed")
53
+ ? "Dependency interpretation recorded; assignment completion is not yet proven."
54
+ : "Execution outcome is unverified; supervised reconciliation is required.";
55
+ }
56
+ reason = String(reason ?? "Assignment state is unverified.").slice(0, 512);
57
+ const evidence = waits.slice(0, 8).map((wait) => `wait:${wait.waitId}:${wait.generation}`);
58
+ evidence.push(`run:${meta.id}:output.log`, `run:${meta.id}:meta.json`);
59
+ const revision = createHash("sha256").update(JSON.stringify([meta.rootRunId ?? meta.id, meta.id, state, reason, evidence])).digest("hex").slice(0, 16);
60
+ return { state, reason, revision, attemptId: meta.id, processStatus,
61
+ termination: !["running", "orphaned", "lost", "exited"].includes(processStatus)
62
+ && (typeof meta.exitCode === "number" || meta.signal) ? "attempt exit recorded" : "unproven",
63
+ evidence, verified: observation.verified };
64
+ }
65
+
66
+ /** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
67
+ export function assignmentFor(meta, processStatus = meta.status, options = {}) {
68
+ return createAssignmentProjector(options)(meta, processStatus);
69
+ }
70
+
71
+ function readAttempt(base, id) {
72
+ try {
73
+ const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
74
+ return candidate && typeof candidate === "object" ? candidate : undefined;
75
+ } catch { /* A partial unrelated record must not hide a continuation. */ }
76
+ }
77
+
78
+ const attemptIndexes = new Map();
79
+ const UNCOMMITTED_RETRY_MS = 1_000;
80
+ const conversationKey = (sessionId, cwd) => JSON.stringify([sessionId, cwd]);
81
+
82
+ function removeIdentity(index, id) {
83
+ const key = index.identities.get(id);
84
+ if (key === undefined) return;
85
+ index.identities.delete(id);
86
+ const group = index.byConversation.get(key);
87
+ group.delete(id);
88
+ if (!group.size) index.byConversation.delete(key);
89
+ }
90
+
91
+ function setIdentity(index, id, candidate) {
92
+ const key = conversationKey(candidate.sessionId, candidate.cwd);
93
+ if (index.identities.get(id) === key) return;
94
+ removeIdentity(index, id);
95
+ index.identities.set(id, key);
96
+ let group = index.byConversation.get(key);
97
+ if (!group) index.byConversation.set(key, group = new Set());
98
+ group.add(id);
99
+ }
100
+
101
+ function runsSignature(base) {
102
+ try {
103
+ const stat = statSync(join(base, "runs"), { bigint: true });
104
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
105
+ } catch { return undefined; }
106
+ }
107
+
108
+ function prepareAttemptIndex(options) {
109
+ const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
110
+ const signature = runsSignature(base);
111
+ if (!signature) {
112
+ attemptIndexes.delete(base);
113
+ return { index: { base, byConversation: new Map() } };
114
+ }
115
+ let index = attemptIndexes.get(base);
116
+ let initialAttempts;
117
+ if (!index) {
118
+ let ids;
119
+ try { ids = new Set(readdirSync(join(base, "runs"))); }
120
+ catch { return { index: { base, byConversation: new Map() } }; }
121
+ index = { base, signature, ids, identities: new Map(), byConversation: new Map(),
122
+ uncommitted: new Set(), nextRetryAt: Date.now() + UNCOMMITTED_RETRY_MS };
123
+ initialAttempts = new Map();
124
+ for (const id of ids) {
125
+ const candidate = readAttempt(base, id);
126
+ if (candidate) {
127
+ setIdentity(index, id, candidate);
128
+ initialAttempts.set(id, candidate);
129
+ }
130
+ else index.uncommitted.add(id);
131
+ }
132
+ attemptIndexes.set(base, index);
133
+ if (attemptIndexes.size > 8) attemptIndexes.delete(attemptIndexes.keys().next().value);
134
+ } else if (index.signature !== signature) {
135
+ let ids;
136
+ try { ids = new Set(readdirSync(join(base, "runs"))); }
137
+ catch {
138
+ attemptIndexes.delete(base);
139
+ return { index: { base, byConversation: new Map() } };
140
+ }
141
+ for (const id of index.ids) {
142
+ if (ids.has(id)) continue;
143
+ removeIdentity(index, id);
144
+ index.uncommitted.delete(id);
145
+ }
146
+ for (const id of ids) {
147
+ if (index.ids.has(id)) continue;
148
+ const candidate = readAttempt(base, id);
149
+ if (candidate) setIdentity(index, id, candidate);
150
+ else index.uncommitted.add(id);
151
+ }
152
+ index.ids = ids;
153
+ index.signature = signature;
154
+ }
155
+ if (Date.now() >= index.nextRetryAt) {
156
+ for (const id of index.uncommitted) {
157
+ const candidate = readAttempt(base, id);
158
+ if (!candidate) continue;
159
+ setIdentity(index, id, candidate);
160
+ index.uncommitted.delete(id);
161
+ }
162
+ index.nextRetryAt = Date.now() + UNCOMMITTED_RETRY_MS;
163
+ }
164
+ return { index, initialAttempts };
165
+ }
166
+
167
+ function readConversationAttempts(index, meta, initialAttempts) {
168
+ const matches = [];
169
+ for (const id of index.byConversation.get(conversationKey(meta.sessionId, meta.cwd)) ?? []) {
170
+ const fresh = initialAttempts?.get(id) ?? readAttempt(index.base, id);
171
+ if (!fresh) {
172
+ removeIdentity(index, id);
173
+ index.uncommitted.add(id);
174
+ continue;
175
+ }
176
+ setIdentity(index, id, fresh);
177
+ if (fresh.sessionId === meta.sessionId && fresh.cwd === meta.cwd) matches.push(fresh);
178
+ }
179
+ return matches;
180
+ }
181
+
182
+ /** One synchronous UI refresh shares a snapshot; the next refresh reads disk again. */
183
+ export function createAssignmentProjector(options = {}) {
184
+ let prepared;
185
+ const snapshots = new Map();
186
+ const readSnapshot = (meta) => {
187
+ if (options.attempts) return options.attempts;
188
+ const key = conversationKey(meta.sessionId, meta.cwd);
189
+ if (!snapshots.has(key)) {
190
+ prepared ??= prepareAttemptIndex(options);
191
+ snapshots.set(key, readConversationAttempts(prepared.index, meta, prepared.initialAttempts));
192
+ }
193
+ return snapshots.get(key);
194
+ };
195
+ return (meta, processStatus = meta.status) => observations.getStore()?.get(meta.id) ?? assignmentFromSnapshot(meta, processStatus, options,
196
+ () => readSnapshot(meta));
197
+ }
198
+
199
+ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
200
+ const attempts = new Map([[meta.id, meta]]);
201
+ let current = meta;
202
+ if (meta.operations || meta.park) {
203
+ for (const candidate of readSnapshot()) {
204
+ if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
205
+ && (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
206
+ }
207
+ }
208
+ // Conversation roots survive explicit follow-ups. Only automatic resume edges
209
+ // join attempts into one assignment; manual continuation starts a new one.
210
+ const lineage = new Map([[meta.id, meta]]);
211
+ let ancestor = meta;
212
+ while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
213
+ ancestor = attempts.get(ancestor.resumedFrom);
214
+ lineage.set(ancestor.id, ancestor);
215
+ }
216
+ let added;
217
+ do {
218
+ added = false;
219
+ for (const candidate of attempts.values()) {
220
+ if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
221
+ lineage.set(candidate.id, candidate);
222
+ added = true;
223
+ }
224
+ }
225
+ } while (added);
226
+ for (const candidate of lineage.values()) {
227
+ if (candidate.startedAt > current.startedAt) current = candidate;
228
+ }
229
+ const status = current.id === meta.id ? processStatus : current.status;
230
+ const sessionId = current.operations?.conversationId ?? current.sessionId;
231
+ const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
232
+ ? (options.observe ?? ((owner) => readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"), owner)))(
233
+ { sessionId, workspace: current.operations?.workspace ?? current.cwd,
234
+ ...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
235
+ attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
236
+ attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
237
+ ? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
238
+ : current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
239
+ : { verified: true, waits: [] });
240
+ return projectAssignment(current, status, observation);
241
+ }
242
+
243
+ export function assignmentDiagnostic(assignment, options = {}) {
244
+ return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}.${options.includeEvidence === false ? "" : ` Evidence: ${assignment.evidence.join(", ")}`}`;
245
+ }