pi-better-server 0.2.4 → 0.3.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 (83) hide show
  1. package/package.json +3 -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 +145 -0
  5. package/scripts/test-on-pi.sh +19 -2
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +47 -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 +5 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +173 -0
  16. package/src/runtime/cancellation.ts +95 -0
  17. package/src/runtime/client.ts +111 -0
  18. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  19. package/src/runtime/domain/assignment-observation.mjs +103 -0
  20. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  21. package/src/runtime/domain/assignment-projection.mjs +245 -0
  22. package/src/runtime/domain/background/conditions.mjs +93 -0
  23. package/src/runtime/domain/background/process-identity.mjs +110 -0
  24. package/src/runtime/domain/background/process.mjs +511 -0
  25. package/src/runtime/domain/background/registry.mjs +374 -0
  26. package/src/runtime/domain/background/snapshot.mjs +73 -0
  27. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  28. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  29. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  30. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  31. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  32. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  33. package/src/runtime/domain/background/types.mjs +3 -0
  34. package/src/runtime/domain/coordinator/index.mjs +50 -0
  35. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  36. package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
  37. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  38. package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
  39. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  40. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  41. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  42. package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
  43. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  44. package/src/runtime/domain/coordinator/src/store.mjs +235 -0
  45. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  46. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  47. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  48. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  49. package/src/runtime/domain/health-observation.d.mts +3 -0
  50. package/src/runtime/domain/health-observation.mjs +613 -0
  51. package/src/runtime/domain/health-surface.mjs +279 -0
  52. package/src/runtime/domain/log-cursor.mjs +148 -0
  53. package/src/runtime/domain/log-paths.mjs +13 -0
  54. package/src/runtime/domain/parse.d.mts +2 -0
  55. package/src/runtime/domain/parse.mjs +1173 -0
  56. package/src/runtime/domain/process-status.d.mts +1 -0
  57. package/src/runtime/domain/process-status.mjs +25 -0
  58. package/src/runtime/domain/session-store.d.mts +2 -0
  59. package/src/runtime/domain/session-store.mjs +489 -0
  60. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  61. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  62. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  63. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  64. package/src/runtime/domain/widget.d.mts +1 -0
  65. package/src/runtime/domain/widget.mjs +250 -0
  66. package/src/runtime/guardian.ts +189 -0
  67. package/src/runtime/health-config.ts +27 -0
  68. package/src/runtime/local-client.ts +34 -0
  69. package/src/runtime/queries.ts +76 -0
  70. package/src/runtime/query-executor.ts +228 -0
  71. package/src/runtime/query-worker.mjs +118 -0
  72. package/src/runtime/read-model.ts +357 -0
  73. package/src/runtime/root.ts +29 -0
  74. package/src/runtime/socket.ts +10 -0
  75. package/src/runtime/status-cli.ts +11 -0
  76. package/src/runtime/work-client.d.mts +13 -0
  77. package/src/runtime/work-client.mjs +88 -0
  78. package/src/server.ts +136 -12
  79. package/src/session-activity.ts +22 -2
  80. package/src/startup/activation.ts +32 -5
  81. package/src/startup/ensure.ts +13 -1
  82. package/src/startup/install.ts +2 -0
  83. package/src/version.ts +4 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-server",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -40,8 +40,8 @@
40
40
  ]
41
41
  },
42
42
  "scripts": {
43
- "pretest": "node ../../scripts/sync-shared-ssh-core.mjs",
44
- "prepack": "node ../../scripts/sync-shared-ssh-core.mjs",
43
+ "pretest": "node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-runtime-domain.mjs",
44
+ "prepack": "node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-runtime-domain.mjs",
45
45
  "test": "node --import tsx --import ../../scripts/isolate-registry.mjs --test --test-concurrency=4 test/*.test.ts",
46
46
  "typecheck": "tsc --noEmit",
47
47
  "verify": "npm run typecheck && npm test"
@@ -0,0 +1,7 @@
1
+ import './probe.mjs';
2
+ const { startDaemon } = await import('../../src/server.ts');
3
+ const daemon = await startDaemon({ serverDir: process.env.PI_SERVER_DIR, sessionIdleMs: 0, daemonIdleMs: 0 });
4
+ process.send?.({ type: 'ready', socket: daemon.socketPath });
5
+ process.on('message', message => {
6
+ if (message === 'stop') void daemon.stop().then(() => process.exit(0));
7
+ });
@@ -0,0 +1,10 @@
1
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
2
+ const lag = monitorEventLoopDelay({ resolution: 10 });
3
+ lag.enable();
4
+ process.on('message', message => {
5
+ if (message?.type !== 'resource-sample') return;
6
+ process.send?.({ type: 'resource-sample', id: message.id, pid: process.pid,
7
+ cpu: process.cpuUsage(), rss: process.memoryUsage().rss, usage: process.resourceUsage(),
8
+ lag: { p50: lag.percentile(50) / 1e6, p95: lag.percentile(95) / 1e6, p99: lag.percentile(99) / 1e6 } });
9
+ lag.reset();
10
+ });
@@ -0,0 +1,145 @@
1
+ import assert from 'node:assert/strict';
2
+ import { fork } from 'node:child_process';
3
+ import { once } from 'node:events';
4
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { tmpdir } from 'node:os';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { performance } from 'node:perf_hooks';
9
+ import { setTimeout as delay } from 'node:timers/promises';
10
+ const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
11
+ assert.ok(['darwin', 'linux'].includes(process.platform), 'This measurement requires macOS or Linux');
12
+ const { WorkClient } = await import(`${workspace}/packages/pi-better-server/src/runtime/work-client.mjs`);
13
+ const sdkEntry = import.meta.resolve('@earendil-works/pi-coding-agent');
14
+ const sdkCli = fileURLToPath(new URL('./cli.js', sdkEntry));
15
+ const sdkVersion = JSON.parse(readFileSync(new URL('../package.json', sdkEntry), 'utf8')).version;
16
+ const children = new Set();
17
+ let requestId = 0;
18
+ function waitMessage(child, check, timeout = 20000) {
19
+ return new Promise((resolve, reject) => {
20
+ const timer = setTimeout(() => { cleanup(); reject(new Error(`IPC timeout for ${child.pid}`)); }, timeout);
21
+ const message = value => { if (check(value)) { cleanup(); resolve(value); } };
22
+ const exit = code => { cleanup(); reject(new Error(`Child ${child.pid} exited ${code}`)); };
23
+ function cleanup() { clearTimeout(timer); child.off('message', message); child.off('exit', exit); }
24
+ child.on('message', message); child.once('exit', exit);
25
+ });
26
+ }
27
+ async function sample(child) {
28
+ const id = ++requestId;
29
+ const result = waitMessage(child, m => m.type === 'resource-sample' && m.id === id);
30
+ child.send({ type: 'resource-sample', id });
31
+ return result;
32
+ }
33
+ function track(child) { children.add(child); child.once('exit', () => children.delete(child)); return child; }
34
+ async function stop(child, graceful = false) {
35
+ if (child.exitCode !== null || child.signalCode !== null) return;
36
+ const exited = once(child, 'exit');
37
+ if (graceful) child.send('stop'); else child.kill('SIGTERM');
38
+ const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
39
+ await exited; clearTimeout(timer);
40
+ }
41
+ function distribution(values) {
42
+ const sorted = [...values].sort((a,b) => a-b);
43
+ const percentile = p => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))];
44
+ return { samples: sorted.length, p50: percentile(.5), p95: percentile(.95), p99: percentile(.99), max: sorted.at(-1) };
45
+ }
46
+ const report = { platform: process.platform, arch: process.arch, node: process.version,
47
+ sdk: sdkVersion, scope: 'Real Pi RPC processes with standalone Subagents, control RPC at 10 Hz, seeded read-only work records; no guardian in slice #753.', scenarios: [] };
48
+ try {
49
+ for (const history of [4416, 10000]) {
50
+ const root = realpathSync(mkdtempSync('/tmp/p751-res-'));
51
+ const agent = join(root, 'agent'), transport = join(root, 's'), runs = join(root, 'pi-better-subagents/runs');
52
+ const durable = join(agent, 'subagents'), archives = join(durable, 'attempts');
53
+ mkdirSync(runs, { recursive: true }); mkdirSync(archives, { recursive: true });
54
+ for (let i = 0; i < history; i++) {
55
+ const id = `sa_resource_history_${i}`;
56
+ writeFileSync(join(archives, `${id}.json`), JSON.stringify({ version: 1, meta: {
57
+ id, cwd: root, status: 'completed', startedAt: i, endedAt: i + 1, sessionId: id, callback: false,
58
+ recipe: { version: 1, sessionId: id, cwd: root, sessionDir: join(durable, 'sessions') } } }));
59
+ }
60
+ const env = { ...process.env, PI_CODING_AGENT_DIR: agent,
61
+ PI_SERVER_DIR: transport, PI_SUBAGENT_DURABLE_DIR: durable, TMPDIR: root, TMP: root, TEMP: root,
62
+ PI_OFFLINE: '1', PI_SANDBOX_RECOVERY_SNAPSHOT: 'off' };
63
+ const work = track(fork(new URL('./measure-shared-reads/probe.mjs', import.meta.url), [], { env, execArgv: [], stdio: ['ignore','ignore','inherit','ipc'] }));
64
+ for (let i = 0; i < 2; i++) {
65
+ const id = `sa_resource_active_${i}`; mkdirSync(join(runs, id));
66
+ writeFileSync(join(runs, id, 'meta.json'), JSON.stringify({ id, cwd: root, status: 'running',
67
+ pid: work.pid, spawnPid: process.pid, startedAt: Date.now(), sessionId: id, callback: false, name: `resource-work-${i}` }));
68
+ }
69
+ const server = track(fork(new URL('./measure-shared-reads/daemon.mjs', import.meta.url), [], { env, execArgv: [], stdio: ['ignore','ignore','inherit','ipc'] }));
70
+ const ready = await waitMessage(server, m => m.type === 'ready');
71
+ const control = new WorkClient(ready.socket, agent); await control.ready;
72
+ const pis = [];
73
+ const rebuildLatencies = [];
74
+ const rebuildStarted = performance.now();
75
+ const initial = control.get({ cwd: root, active: true });
76
+ let indexed = await initial;
77
+ while (indexed.status !== 'ready') {
78
+ assert.ok(performance.now() - rebuildStarted < 30000, `Rebuild did not recover: ${indexed.reason}`);
79
+ const began = performance.now(); await control.request('runtime_get_status'); rebuildLatencies.push(performance.now() - began);
80
+ await delay(20); indexed = await control.get({ cwd: root, active: true });
81
+ }
82
+ const rebuildMs = performance.now() - rebuildStarted;
83
+ assert.equal(indexed.activity.active, 2);
84
+ assert.equal((await control.get({ cwd: root, active: false, limit: 1 })).totalMatching, history);
85
+ for (const count of [1, 5, 10]) {
86
+ while (pis.length < count) {
87
+ const pi = track(fork(sdkCli, ['--mode','rpc','--offline','--no-session','--no-extensions',
88
+ '--extension',join(workspace,'packages/pi-better-subagents/index.ts'),
89
+ '--no-skills','--no-prompt-templates','--no-themes'], {
90
+ cwd: root, env, execArgv: ['--import', new URL('./measure-shared-reads/probe.mjs', import.meta.url).href], stdio: ['pipe','pipe','pipe','ipc'] }));
91
+ let stderr = ''; pi.stderr.on('data', chunk => { stderr += chunk; });
92
+ pi.rpc = (type = 'get_state') => new Promise((resolve, reject) => {
93
+ const id = `measure-${++requestId}`;
94
+ const timer = setTimeout(() => { cleanup(); reject(new Error(`Pi RPC timeout: ${stderr}`)); }, 15000);
95
+ let buffer = '';
96
+ const read = chunk => { buffer += chunk; for (;;) {
97
+ const end = buffer.indexOf('\n'); if (end < 0) break;
98
+ const line = buffer.slice(0,end); buffer = buffer.slice(end+1);
99
+ try { const message = JSON.parse(line); if (message.id === id) { cleanup(); resolve(message); return; } } catch {}
100
+ } };
101
+ function cleanup() { clearTimeout(timer); pi.stdout.off('data', read); }
102
+ pi.stdout.on('data', read); pi.stdin.write(JSON.stringify({ id, type }) + '\n');
103
+ });
104
+ await pi.rpc(); pis.push(pi);
105
+ }
106
+ await delay(1200);
107
+ await control.get({ cwd: root, active: true });
108
+ const before = await control.request('runtime_get_metrics');
109
+ const subjects = [...pis, server, work];
110
+ const start = await Promise.all(subjects.map(sample));
111
+ const began = performance.now(), latencies = [];
112
+ const windowMs = count === 10 && history === 10000 ? 60000 : 3000;
113
+ while (performance.now() - began < windowMs) {
114
+ const sent = performance.now(); await Promise.all(pis.map(pi => pi.rpc())); latencies.push(performance.now() - sent);
115
+ await delay(100);
116
+ }
117
+ const elapsedMs = performance.now() - began;
118
+ const end = await Promise.all(subjects.map(sample));
119
+ await control.get({ cwd: root, active: true });
120
+ const after = await control.request('runtime_get_metrics');
121
+ assert.equal(after.metadataReads, before.metadataReads, 'unchanged history must not be reread for more Pi clients');
122
+ assert.equal(after.projections, before.projections, 'unchanged work must not be reprojected for more Pi clients');
123
+ assert.ok(after.inventories - before.inventories <= Math.ceil(elapsedMs / 1000) + 2,
124
+ 'shared compatibility inventory must not multiply with Pi clients');
125
+ assert.ok(after.sqlite.active <= 2, 'read worker must retain the root database budget');
126
+ assert.equal((await control.request('runtime_get_status')).hostedSessions, 0,
127
+ 'ordinary local Pi clients must not create hosted sessions');
128
+ const resources = end.map((value, i) => ({ pid: value.pid, role: i < pis.length ? 'pi' : i === pis.length ? 'server' : 'work',
129
+ cpuMs: ((value.cpu.user - start[i].cpu.user) + (value.cpu.system - start[i].cpu.system))/1000,
130
+ rss: value.rss, fsRead: value.usage.fsRead - start[i].usage.fsRead, fsWrite: value.usage.fsWrite - start[i].usage.fsWrite,
131
+ lagMs: value.lag }));
132
+ const entry = { history, clients: count, elapsedMs, resources,
133
+ totalCpuMs: resources.reduce((sum,r) => sum+r.cpuMs, 0), totalRss: resources.reduce((sum,r) => sum+r.rss, 0),
134
+ rpcMs: distribution(latencies), inventoryDelta: after.inventories-before.inventories,
135
+ metadataReadDelta: after.metadataReads-before.metadataReads, projectionDelta: after.projections-before.projections,
136
+ sqlite: after.sqlite, rebuild: { ms: rebuildMs, controlRpcMs: distribution(rebuildLatencies) } };
137
+ report.scenarios.push(entry); console.log(JSON.stringify(entry));
138
+ }
139
+ await Promise.all(pis.map(pi => stop(pi))); control.close(); await stop(server, true); await stop(work);
140
+ rmSync(root, { recursive: true, force: true });
141
+ }
142
+ const output = process.env.PI_SHARED_READ_REPORT ?? join(tmpdir(), 'pi-shared-read-resources.json');
143
+ writeFileSync(output, JSON.stringify(report, null, 2) + '\n');
144
+ console.log(`Resource report: ${output}`);
145
+ } finally { await Promise.all([...children].map(child => stop(child))); }
@@ -26,9 +26,26 @@ cp "$ROOT_DIR/scripts/isolate-registry.mjs" "$PREFIX/scripts/"
26
26
  cp -R "$PKG_DIR/src" "$PKG_DIR/test" "$PKG_DIR/scripts" "$PKG_DIR/package.json" "$PKG_DIR/tsconfig.json" "$PREFIX/packages/pi-better-server/"
27
27
  [ -d "$PKG_DIR/codex-plugin" ] && cp -R "$PKG_DIR/codex-plugin" "$PREFIX/packages/pi-better-server/"
28
28
  # Background-activity regressions load the real sibling provider against this SDK.
29
- cp -R "$ROOT_DIR/packages/pi-better-subagents" "$PREFIX/packages/pi-better-subagents"
29
+ node --input-type=module - "$ROOT_DIR" "$PREFIX" <<'NODE'
30
+ import { cpSync } from "node:fs";
31
+ import { basename, join } from "node:path";
32
+ for (const name of ["pi-better-subagents", "pi-better-background-tasks", "operation-coordinator"]) {
33
+ cpSync(join(process.argv[2], "packages", name), join(process.argv[3], "packages", name), {
34
+ recursive: true, filter: path => !["node_modules", ".work", ".pi-compat"].includes(basename(path)),
35
+ });
36
+ }
37
+ NODE
38
+ # Install the consumer's declared runtime closure, not just the host's transitives.
39
+ # Its host-provided peers must keep resolving to the requested Pi above.
40
+ (cd "$PREFIX/packages/pi-better-subagents" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
41
+ (cd "$PREFIX/packages/pi-better-background-tasks" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
30
42
 
31
43
  cd "$PREFIX/packages/pi-better-server"
32
44
  installed="$(node -p "require('$PREFIX/node_modules/@earendil-works/pi-coding-agent/package.json').version")"
33
45
  echo "testing against pi-coding-agent $installed"
34
- node --import tsx --import ../../scripts/isolate-registry.mjs --test --test-concurrency=4 test/*.test.ts
46
+ tests=("${@:3}")
47
+ if [ "${#tests[@]}" -eq 0 ]; then tests=(test/*.test.ts); fi
48
+ if [ -n "${TEST_SHARD:-}" ]; then
49
+ tests=("--test-shard=$TEST_SHARD" "${tests[@]}")
50
+ fi
51
+ PI_RUNTIME_PACK_WORKSPACE="$ROOT_DIR" node --import tsx --import ../../scripts/isolate-registry.mjs --test --test-concurrency=4 "${tests[@]}"
package/src/cli.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { parseManagedStartupArgs, resolveAgent, type ServerAgent } from "./cli-args.ts";
4
4
  import { absolutePath, launcherRuntime, registeredRuntime } from "./startup/runtime.ts";
5
+ import { validateDaemonOwnerIdentity } from "./daemon-owner.ts";
5
6
 
6
7
  const log = (message: string): void => void process.stderr.write(`[pi-better-server] ${message}\n`);
7
8
 
@@ -70,15 +71,51 @@ async function main(): Promise<void> {
70
71
  }
71
72
 
72
73
  const serverDir = process.env.PI_SERVER_DIR ? { serverDir: process.env.PI_SERVER_DIR } : {};
74
+ if (agent === "pi" && !process.env.PI_SERVER_GUARDED_CHILD) {
75
+ const { runtimeRoot } = await import("./runtime/root.ts");
76
+ const root = runtimeRoot(process.env.PI_CODING_AGENT_DIR!, process.env.PI_SERVER_DIR!);
77
+ const { runGuardian } = await import("./runtime/guardian.ts");
78
+ const rebind = process.env.PI_SERVER_GUARDIAN_REBIND ? JSON.parse(process.env.PI_SERVER_GUARDIAN_REBIND) : undefined;
79
+ if (rebind) {
80
+ validateDaemonOwnerIdentity(rebind);
81
+ } else {
82
+ const { checkStartupAdmission, startupIntentFromEnv } = await import("./startup/admission.ts");
83
+ const { readOwnBuild } = await import("./startup/artifact.ts");
84
+ checkStartupAdmission({ canonicalServerDir: root.serverDir, agentDir: root.agentDir,
85
+ build: readOwnBuild(), intent: startupIntentFromEnv(process.env) });
86
+ }
87
+ await runGuardian(root.serverDir, rebind);
88
+ return;
89
+ }
90
+ let shutdownBudget: ReturnType<typeof setTimeout> | undefined;
73
91
  const daemon = agent === "codex"
74
92
  ? await (await import("./codex/daemon.ts")).startCodexDaemon({ ...serverDir, log })
75
- : await (await import("./server.ts")).startDaemon({ ...serverDir, log });
93
+ : await (await import("./server.ts")).startDaemon({ ...serverDir, log, onDraining: () => {
94
+ shutdownBudget ??= setTimeout(() => { log("runtime-unavailable: shutdown exceeded 5000ms; writer state remains unverified"); process.exit(1); }, 5000);
95
+ shutdownBudget.unref();
96
+ } });
97
+ if ("closed" in daemon) {
98
+ const { inspectDaemonOwner } = await import("./daemon-owner.ts");
99
+ const owner = inspectDaemonOwner(daemon.serverDir);
100
+ const token = owner.status === "live" ? owner.owner.token : undefined;
101
+ const { maintainGuardian } = await import("./runtime/guardian.ts");
102
+ const stopRecovery = owner.status === "live" ? maintainGuardian(daemon.serverDir, owner.owner) : () => undefined;
103
+ if (process.connected) process.send?.({ type: "runtime-ready", token }, () => undefined);
104
+ void daemon.closed.then(() => {
105
+ if (shutdownBudget) clearTimeout(shutdownBudget);
106
+ stopRecovery();
107
+ if (process.connected) process.send?.({ type: "runtime-clean-stop", token }, () => process.disconnect?.());
108
+ });
109
+ }
76
110
 
77
111
  let stopping = false;
78
112
  const shutdown = (): void => {
79
113
  if (stopping) return;
80
114
  stopping = true;
81
- void daemon.stop().finally(() => process.exit(0));
115
+ void daemon.stop().catch(error => {
116
+ log(`shutdown failed: ${String(error)}`);
117
+ process.exitCode = 1;
118
+ });
82
119
  };
83
120
  process.on("SIGINT", shutdown);
84
121
  process.on("SIGTERM", shutdown);
package/src/client.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { connect, type Socket } from "node:net";
2
- import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
3
- import { SERVER_EXTENSION_VERSIONS } from "./handshake.ts";
2
+ import { SERVER_EXTENSION_VERSIONS } from "./version.ts";
4
3
  import { encodeLine, LineDecoder, PROTOCOL_VERSION, type HelloData } from "./protocol.ts";
5
4
 
6
5
  /** The daemon refused the `hello`; the message is the daemon's own explanation. */
@@ -72,12 +71,18 @@ export class DaemonClient {
72
71
  if (signal?.aborted) throw abortError();
73
72
  const client = new DaemonClient(socket, undefined);
74
73
  if (options.hello === false) return client;
74
+ const hello = { ...options.hello };
75
+ // Explicit cross-SDK discovery does not need ordinary-client SDK defaults.
76
+ if (!Object.hasOwn(hello, "piVersion")) {
77
+ const sdk = await Promise.race([import("@earendil-works/pi-coding-agent"), aborted]);
78
+ hello.piVersion = sdk.VERSION;
79
+ }
80
+ if (signal?.aborted) throw abortError();
75
81
  const response = await Promise.race([client.request({
76
82
  type: "hello",
77
83
  protocolVersion: PROTOCOL_VERSION,
78
- piVersion: PI_VERSION,
79
84
  extensionVersions: { ...SERVER_EXTENSION_VERSIONS },
80
- ...options.hello,
85
+ ...hello,
81
86
  }), aborted]);
82
87
  if (signal?.aborted) throw abortError();
83
88
  if (!response.success) throw new HandshakeError(response.error ?? "daemon rejected the handshake");
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
+ import { execFileSync } from "node:child_process";
4
5
 
5
6
  export interface DaemonOwnerIdentity {
6
7
  pid: number;
@@ -12,13 +13,43 @@ export interface DaemonOwnerIdentity {
12
13
  type Owner = DaemonOwnerIdentity;
13
14
 
14
15
  export function currentOwnerIdentity(token = randomUUID()): DaemonOwnerIdentity {
15
- return { pid: process.pid, token, ...linuxIdentity(process.pid) };
16
+ const { boot, start } = processIdentity(process.pid);
17
+ return { pid: process.pid, token, ...(boot ? { boot } : {}), ...(start ? { start } : {}) };
16
18
  }
17
19
 
18
20
  export function ownerIsAlive(owner: DaemonOwnerIdentity): boolean {
19
21
  return alive(owner);
20
22
  }
21
23
 
24
+ export function sameOwner(left: DaemonOwnerIdentity, right: DaemonOwnerIdentity): boolean {
25
+ return typeof left.start === "string" && left.pid === right.pid && left.token === right.token
26
+ && left.start === right.start && left.boot === right.boot;
27
+ }
28
+
29
+ export function ownerIdentityVerified(owner: DaemonOwnerIdentity): boolean {
30
+ const observed = processIdentity(owner.pid);
31
+ return typeof owner.start === "string" && observed.start === owner.start
32
+ && (process.platform !== "linux" || typeof owner.boot === "string" && owner.boot === observed.boot)
33
+ && alive(owner);
34
+ }
35
+
36
+ /** Matches the existing runner/worker start-token representation, without releasing fences. */
37
+ export function processMatchesStart(pid: number, start: unknown): boolean {
38
+ if (!Number.isSafeInteger(pid) || pid <= 0 || typeof start !== "string") return false;
39
+ if (!/^\d+$/.test(start)) {
40
+ // Background runner claims use ps lstart on both supported platforms;
41
+ // Subagent Linux records use /proc ticks. Compare in the recorded format.
42
+ try {
43
+ const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
44
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
45
+ }).trim();
46
+ return observed.length > 0 && observed === start.trim();
47
+ } catch { return false; }
48
+ }
49
+ const identity = processIdentity(pid);
50
+ return identity.start !== undefined && identity.start === start && alive({ pid, token: "observation", start: identity.start });
51
+ }
52
+
22
53
  export type OwnerInspection =
23
54
  | { status: "missing" | "ambiguous"; reason?: string }
24
55
  | { status: "live" | "dead"; owner: DaemonOwnerIdentity };
@@ -58,28 +89,38 @@ function validateOwner(previous: Owner, name: string, lock: string): void {
58
89
 
59
90
  const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
60
91
 
61
- function linuxIdentity(pid: number): Pick<Owner, "boot" | "start"> {
92
+ function processIdentity(pid: number): Pick<Owner, "boot" | "start"> & { state?: string } {
93
+ if (process.platform === "darwin") {
94
+ try {
95
+ const start = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000 }).trim();
96
+ const stamp = Date.parse(start);
97
+ return Number.isFinite(stamp) ? { start: String(stamp) } : {};
98
+ } catch { return {}; }
99
+ }
62
100
  if (process.platform !== "linux") return {};
63
101
  try {
64
102
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
65
- return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] };
103
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
104
+ return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: fields[19], state: fields[0] };
66
105
  } catch { return {}; }
67
106
  }
68
107
 
69
108
  function alive(owner: Owner): boolean {
70
- const identity = linuxIdentity(owner.pid);
109
+ const identity = processIdentity(owner.pid);
71
110
  if (owner.boot && identity.boot && owner.boot !== identity.boot) return false;
72
111
  if (owner.start && identity.start && owner.start !== identity.start) return false;
112
+ // A kernel-confirmed exited process cannot own a socket even before its parent reaps it.
113
+ if (identity.state === "Z" || identity.state === "X") return false;
73
114
  try { process.kill(owner.pid, 0); return true; }
74
115
  catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
75
116
  }
76
117
 
77
118
  /** Claim ownership before reading the index. A live owner is never reclaimed on a timer. */
78
- export function claimDaemonOwner(serverDir: string, lockName = "daemon-owner"): () => void {
119
+ export function claimDaemonOwner(serverDir: string, lockName = "daemon-owner", stagingDir = serverDir): () => void {
79
120
  const token = randomUUID();
80
121
  const owner = currentOwnerIdentity(token);
81
122
  const lock = join(serverDir, lockName);
82
- const candidate = join(serverDir, `.${lockName}-${token}`);
123
+ const candidate = join(stagingDir, `.${lockName}-${token}`);
83
124
  const name = `owner-${token}.json`;
84
125
  mkdirSync(candidate, { mode: 0o700 });
85
126
  let claimed = false;
package/src/handshake.ts CHANGED
@@ -2,19 +2,17 @@ import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
2
2
  import { readOwnBuild } from "./startup/artifact.ts";
3
3
  import type { ServerBuild } from "./startup/managed-types.ts";
4
4
  import { PROTOCOL_VERSION, type HelloCommand, type HelloData } from "./protocol.ts";
5
+ import { SERVER_EXTENSION_VERSIONS } from "./version.ts";
6
+ export { SERVER_VERSION, SERVER_EXTENSION_VERSIONS } from "./version.ts";
5
7
 
6
- /** Kept equal to package.json `version`; a test pins that. */
7
- export const SERVER_VERSION = "0.2.4";
8
-
9
- export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };
10
-
11
- export interface HelloIdentity { build?: ServerBuild; instanceId?: string; safeUpgrade?: boolean }
8
+ export interface HelloIdentity { build?: ServerBuild; instanceId?: string; safeUpgrade?: boolean; agentDir?: string; runtimeLifecycle?: boolean }
12
9
 
13
10
  export function serverHello(identity: HelloIdentity = {}): HelloData {
14
11
  const build = identity.build ?? readOwnBuild();
15
12
  return { protocolVersion: PROTOCOL_VERSION, piVersion: PI_VERSION, extensionVersions: { ...SERVER_EXTENSION_VERSIONS },
13
+ ...(identity.agentDir ? { agentDir: identity.agentDir, nodeVersion: process.versions.node } : {}),
16
14
  ...(build ? { build } : {}), ...(identity.instanceId ? { instanceId: identity.instanceId } : {}),
17
- capabilities: ["native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
15
+ capabilities: [...(identity.runtimeLifecycle ? ["runtime-client-retention-v1"] : []),...(identity.agentDir ? ["runtime-status-v1", "runtime-state-v1", "runtime-subscriptions-v1", "runtime-background-state-v1", "runtime-cancellation-v1"] : []), "native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
18
16
  ...(identity.safeUpgrade && build && identity.instanceId ? ["safe-upgrade-v1"] : [])] };
19
17
  }
20
18
 
@@ -31,6 +29,9 @@ function majorMinor(version: string): string | undefined {
31
29
  */
32
30
  export function checkHello(command: Record<string, unknown>, identity: HelloIdentity = {}): { ok: true; data: HelloData } | { ok: false; error: string } {
33
31
  const server = serverHello(identity);
32
+ if (command.runtimeRoot !== undefined && command.runtimeRoot !== identity.agentDir) return { ok: false, error: "capability-mismatch: canonical agent root differs" };
33
+ if (command.requiredCapabilities !== undefined && (!Array.isArray(command.requiredCapabilities)
34
+ || !command.requiredCapabilities.every(value => typeof value === "string" && server.capabilities?.includes(value)))) return { ok: false, error: "capability-mismatch: required runtime capability is unavailable" };
34
35
  const { protocolVersion, piVersion, extensionVersions } = command as Partial<HelloCommand>;
35
36
  if (typeof protocolVersion !== "number" || !Number.isInteger(protocolVersion)) {
36
37
  return { ok: false, error: `hello requires an integer protocolVersion; this daemon speaks protocol ${server.protocolVersion}` };
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  export interface LifecycleConfig {
5
5
  sessionIdleMs: number;
6
6
  daemonIdleMs: number;
7
+ runtimeIdleMs: number;
7
8
  }
8
9
 
9
10
  export function readLifecycleConfig(serverDir: string, overrides: Partial<LifecycleConfig> = {}, env = process.env): LifecycleConfig {
@@ -22,7 +23,10 @@ export function readLifecycleConfig(serverDir: string, overrides: Partial<Lifecy
22
23
  }
23
24
  return value;
24
25
  };
26
+ const runtimeIdleMs = duration("runtimeIdleMs", "PI_SERVER_RUNTIME_IDLE_MS", 30_000);
27
+ if (runtimeIdleMs === 0) throw new Error("runtimeIdleMs must be a positive safe integer in milliseconds");
25
28
  return {
29
+ runtimeIdleMs,
26
30
  sessionIdleMs: duration("sessionIdleMs", "PI_SERVER_SESSION_IDLE_MS", 24 * 60 * 60 * 1000),
27
31
  daemonIdleMs: duration("daemonIdleMs", "PI_SERVER_DAEMON_IDLE_MS", 30 * 60 * 1000),
28
32
  };
package/src/paths.ts CHANGED
@@ -1,23 +1,13 @@
1
1
  import { chmodSync, mkdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ export { socketPathFor } from "./runtime/socket.ts";
4
5
 
5
6
  /** Directory that owns the socket and the session index. Override for tests with PI_SERVER_DIR. */
6
7
  export function defaultServerDir(): string {
7
8
  return process.env.PI_SERVER_DIR || join(getAgentDir(), "server");
8
9
  }
9
10
 
10
- /** sockaddr_un.sun_path is 104 bytes on macOS and 108 on Linux; leave room for the NUL. */
11
- const MAX_SOCKET_PATH_BYTES = 103;
12
-
13
- export function socketPathFor(serverDir: string): string {
14
- const path = join(serverDir, "pi-server.sock");
15
- if (Buffer.byteLength(path) > MAX_SOCKET_PATH_BYTES) {
16
- throw new Error(`Socket path is too long for a unix socket (${Buffer.byteLength(path)} > ${MAX_SOCKET_PATH_BYTES} bytes): ${path}. Set PI_SERVER_DIR to a shorter directory.`);
17
- }
18
- return path;
19
- }
20
-
21
11
  export function indexPathFor(serverDir: string): string {
22
12
  return join(serverDir, "sessions.json");
23
13
  }
package/src/protocol.ts CHANGED
@@ -64,6 +64,8 @@ export interface HelloCommand {
64
64
  }
65
65
 
66
66
  export interface HelloData {
67
+ agentDir?: string;
68
+ nodeVersion?: string;
67
69
  protocolVersion: number;
68
70
  piVersion: string;
69
71
  extensionVersions: Record<string, string>;
@@ -121,11 +123,14 @@ export type ControlCommand =
121
123
  | ({ id?: string; type: "extension_ui_response"; sessionId: string; requestId: string } & DialogAnswer);
122
124
 
123
125
  export type ClientCommand = HelloCommand | DaemonCommand | ControlCommand | SessionCommand
126
+ | { id?: string; type: "runtime_cancellation_status" }
127
+ | { id?: string; type: "runtime_cancel_task" | "runtime_query_cancellation"; credential: string }
124
128
  | ({ id?: string; type: "runtime_upgrade" } & UpgradeRequest)
125
129
  | { id?: string; type: "runtime_upgrade_status" }
126
130
  | { id?: string; type: "client_reload"; sessionId: string };
127
131
 
128
132
  export type DaemonResponse =
133
+ | { id?: string; type: "response"; command: "runtime_cancellation_status" | "runtime_cancel_task" | "runtime_query_cancellation"; success: true; data: unknown }
129
134
  | { id?: string; type: "response"; command: "hello"; success: true; data: HelloData }
130
135
  | { id?: string; type: "response"; command: "list_sessions"; success: true; data: { sessions: SessionSummary[] } }
131
136
  | { id?: string; type: "response"; command: "create_session"; success: true; sessionId: string; data: SessionSummary }
package/src/registry.ts CHANGED
@@ -37,6 +37,7 @@ export type CreateSessionRequest = Extract<DaemonCommand, { type: "create_sessio
37
37
 
38
38
  export interface SessionRegistryOptions {
39
39
  serverDir: string;
40
+ workClient?: () => import("./runtime/work-client.mjs").WorkClient;
40
41
  /** Inactivity expiry; zero disables it. Defaults to 24 hours. */
41
42
  sessionIdleMs?: number;
42
43
  now?: () => number;
@@ -375,7 +376,7 @@ export class SessionRegistry {
375
376
  private async start(entry: IndexEntry, manager?: SessionManager, useDefaultModel = false): Promise<HostedSession> {
376
377
  const sessionManager = manager ?? this.reopen(entry);
377
378
  this.maintenance.registerManager(sessionManager);
378
- const activity = new SessionActivity(this.log, () => this.maintenance.enterTool(sessionManager), () => this.maintenance.enterSessionOperation());
379
+ const activity = new SessionActivity(this.log, () => this.maintenance.enterTool(sessionManager), () => this.maintenance.enterSessionOperation(), this.options.workClient);
379
380
  let session: AgentSession | undefined;
380
381
  let hosted: HostedSession | undefined;
381
382
  try {