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
package/src/server.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { chmodSync, existsSync, realpathSync, unlinkSync } from "node:fs";
1
+ import { createLocalWorkClient } from "./runtime/local-client.ts";
2
+ import { chmodSync, existsSync, realpathSync, unlinkSync, writeFileSync, renameSync } from "node:fs";
3
+ import { join } from "node:path";
2
4
  import { connect, createServer, type Server, type Socket } from "node:net";
3
5
  import { getAgentDir, type RpcCommand } from "@earendil-works/pi-coding-agent";
4
6
  import { CompanionManager, type CompanionManagerOptions } from "./companion.ts";
@@ -9,13 +11,19 @@ import { MoveService } from "./move/service.ts";
9
11
  import { CONTROL_COMMANDS, DAEMON_COMMANDS, encodeLine, failure, LineDecoder, MOVE_COMMANDS, type MoveCommand, type ServerMessage } from "./protocol.ts";
10
12
  import { SessionRegistry, type SessionRegistryOptions } from "./registry.ts";
11
13
  import { NativeClientHost, NATIVE_HOST_COMMANDS } from "./remote-client/host.ts";
12
- import { claimDaemonOwner, inspectDaemonOwner } from "./daemon-owner.ts";
14
+ import { claimDaemonOwner, inspectDaemonOwner, ownerIdentityVerified, sameOwner, validateDaemonOwnerIdentity } from "./daemon-owner.ts";
13
15
  import { readOwnBuild, readStagedRuntime } from "./startup/artifact.ts";
14
16
  import { canonicalStateDir, commitActivationStop, compatibleUpgrade, hasActivationReservations, readActivationJournal } from "./startup/activation.ts";
15
17
  import { admitDaemonStartup, startupIntentFromEnv } from "./startup/admission.ts";
16
18
  import type { IdleSessionsLease, UpgradeRequest } from "./startup/managed-types.ts";
17
19
  import { HostedSession } from "./hosted-session.ts";
18
20
  import { readLifecycleConfig, type LifecycleConfig } from "./lifecycle-config.ts";
21
+ import { runtimeRoot } from "./runtime/root.ts";
22
+ import { RuntimeCancellation, hasPendingCancellation } from "./runtime/cancellation.ts";
23
+ import { RuntimeResultSupervision, hasResultSupervision } from "./runtime/result-supervision.ts";
24
+ import { SharedCatalog } from "./runtime/catalog.ts";
25
+ import { mutationStoreMetrics } from "./runtime/mutation-store.ts";
26
+ import { WorkQueryExecutor } from "./runtime/query-executor.ts";
19
27
 
20
28
  export interface DaemonOptions extends Partial<LifecycleConfig> {
21
29
  /** Defaults to `~/.pi/agent/server` (or `$PI_SERVER_DIR`). */
@@ -30,6 +38,10 @@ export interface DaemonOptions extends Partial<LifecycleConfig> {
30
38
  now?: () => number;
31
39
  /** Brief protection between hello/readiness and creation of a session. */
32
40
  startupGraceMs?: number;
41
+ /** CLI-owned process shutdown budget; never used to reclaim a different owner. */
42
+ onDraining?: () => void;
43
+ /** Trusted fault-injection seam; never exposed through the socket protocol. */
44
+ cancellationFault?: (stage: import("./runtime/cancellation.ts").CancellationStage) => void;
33
45
  }
34
46
 
35
47
  export interface Daemon {
@@ -56,7 +68,7 @@ function socketIsLive(path: string): Promise<boolean> {
56
68
  }
57
69
 
58
70
  export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon> {
59
- const serverDir = canonicalStateDir(options.serverDir ?? defaultServerDir());
71
+ const serverDir = runtimeRoot(getAgentDir(), canonicalStateDir(options.serverDir ?? defaultServerDir())).serverDir;
60
72
  const socketPath = socketPathFor(serverDir);
61
73
  const log = options.log ?? (() => undefined);
62
74
  ensureServerDir(serverDir);
@@ -79,8 +91,40 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
79
91
  const owner = inspectDaemonOwner(serverDir);
80
92
  const instanceId = owner.status === "live" ? owner.owner.token : undefined;
81
93
  admitDaemonStartup({ canonicalServerDir: serverDir, agentDir: getAgentDir(), build, intent: startupIntentFromEnv(process.env) });
82
- const registry = new SessionRegistry({ serverDir, sessionOptions: options.sessionOptions, eventLog: options.eventLog, log, sessionIdleMs: config.sessionIdleMs, now });
83
- cleanupStartup = () => registry.shutdown();
94
+ let cancellations: RuntimeCancellation | undefined;
95
+ let resultSupervision: RuntimeResultSupervision | undefined;
96
+ const resultPortKey = Symbol.for("pi-better-server:result-supervision-ports-v1");
97
+ const resultPorts: Map<string, any> = (globalThis as any)[resultPortKey] ??= new Map();
98
+ const resultRoot = realpathSync(getAgentDir());
99
+ const resultPort = { status() {
100
+ resultSupervision ??= new RuntimeResultSupervision(resultRoot, instanceId!);
101
+ resultSupervision.reconcile();
102
+ return { hostId: resultSupervision.hostId, epoch: resultSupervision.epoch, reason: resultSupervision.reason };
103
+ } };
104
+ let workModel: WorkQueryExecutor | undefined;
105
+ let registry!: SessionRegistry;
106
+ cleanupStartup = async () => {
107
+ try { await registry?.shutdown(); }
108
+ finally {
109
+ try { await cancellations?.close(); }
110
+ finally {
111
+ resultSupervision?.close();
112
+ if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
113
+ await workModel?.close();
114
+ }
115
+ }
116
+ };
117
+ if (hasResultSupervision(getAgentDir())) resultSupervision = new RuntimeResultSupervision(resultRoot, instanceId!);
118
+ resultPorts.set(resultRoot, resultPort);
119
+ if (hasPendingCancellation(getAgentDir())) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
120
+ const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!);
121
+ const work = () => {
122
+ if (!workModel) {
123
+ workModel = new WorkQueryExecutor(realpathSync(getAgentDir()), instanceId!);
124
+ }
125
+ return workModel;
126
+ };
127
+ registry = new SessionRegistry({ serverDir, sessionOptions: options.sessionOptions, eventLog: options.eventLog, log, sessionIdleMs: config.sessionIdleMs, now, workClient: () => createLocalWorkClient(work(), realpathSync(getAgentDir())) });
84
128
  await registry.resumeAll();
85
129
  const nativeHost = new NativeClientHost(registry);
86
130
  // Structural port permits independent integration with the shared maintenance owner.
@@ -108,6 +152,12 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
108
152
  const dispatches = new Set<Promise<void>>();
109
153
  let inFlight = 0;
110
154
  let draining = false;
155
+ let idleStopping = false;
156
+ const runtimeClients = new Map<Socket, string>();
157
+ let guardianBinding: { socket: Socket; identity: import("./daemon-owner.ts").DaemonOwnerIdentity } | undefined;
158
+ let observationUnavailable = false;
159
+ let runtimeZeroSince: number | undefined = now();
160
+ let hostedUsed = registry.activeCount > 0;
111
161
  let zeroSince: number | undefined = registry.activeCount === 0 ? now() : undefined;
112
162
  let startupUntil = 0;
113
163
  const server: Server = createServer((socket) => {
@@ -117,6 +167,10 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
117
167
  };
118
168
  const control = new ConnectionControl(send);
119
169
  let greeted = false;
170
+ const catalogCommand = catalog.connection();
171
+ let catalogSubscription: { close(): void } | undefined;
172
+ let workQueries: ReturnType<WorkQueryExecutor["connect"]> | undefined;
173
+ let runtimeInFlight = 0;
120
174
 
121
175
  const dispatch = async (line: string): Promise<void> => {
122
176
  let command: Record<string, unknown>;
@@ -143,10 +197,10 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
143
197
  return;
144
198
  }
145
199
  if (type === "hello") {
146
- const verdict = checkHello(command, { build, instanceId, safeUpgrade });
200
+ const verdict = checkHello(command, { build, instanceId, safeUpgrade, runtimeLifecycle: true, agentDir: realpathSync(getAgentDir()) });
147
201
  if (verdict.ok) {
148
202
  reconnectControllers.set(control, Array.isArray(command.capabilities) && command.capabilities.includes("runtime-reconnect-v1"));
149
- if (!greeted) startupUntil = Math.max(startupUntil, now() + startupGraceMs);
203
+ if (!greeted && command.runtimeRoot === undefined) startupUntil = Math.max(startupUntil, now() + startupGraceMs);
150
204
  greeted = true;
151
205
  return reply({ data: verdict.data });
152
206
  }
@@ -154,7 +208,98 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
154
208
  socket.end(); // an incompatible client gets the reason, then the door
155
209
  return;
156
210
  }
211
+ if (type === "runtime_get_status") {
212
+ if (!greeted) throw new Error("runtime_get_status requires hello");
213
+ // Status observes the last inventory; only idle shutdown requests a fresh liveness check.
214
+ const observation = workModel?.observation();
215
+ return reply({ data: { agentDir: realpathSync(getAgentDir()), serverDir, instanceId, build, nodeVersion: process.versions.node,
216
+ capabilities: ["runtime-status-v1"], hostedSessions: registry.activeCount, lifecycle: config,
217
+ guardianBinding: guardianBinding?.identity ?? null,
218
+ workObservation: observation ? { status: observation.status, reason: observation.reason, observedAt: observation.observedAt } : null,
219
+ livenessReasons: [...[...runtimeClients.values()].map(id => ({ kind: "connection", id })),
220
+ ...registry.list().filter(session => session.live).map(session => ({ kind: "hosted-session", id: session.sessionId })),
221
+ ...(observation?.reasons ?? [])],
222
+ livenessObservation: observation ?? { status: "unobserved", reasons: [], observedAt: null },
223
+ nextIdleDeadline: runtimeClients.size > 0 || registry.activeCount > 0 ? null
224
+ : hostedUsed ? config.daemonIdleMs === 0 || zeroSince === undefined ? null : zeroSince + config.daemonIdleMs
225
+ : runtimeZeroSince === undefined ? null : runtimeZeroSince + config.runtimeIdleMs } });
226
+ }
227
+ if (type === "runtime_result_supervision") {
228
+ if (!greeted) throw new Error("not_accepted: supervision requires hello");
229
+ if (Object.keys(command).some(key => !["id", "type"].includes(key))) throw new Error("not_accepted: unsupported supervision field");
230
+ return reply({ data: resultPort.status() });
231
+ }
232
+ if (type === "runtime_cancel_task" || type === "runtime_query_cancellation" || type === "runtime_cancellation_status") {
233
+ if (!greeted) throw new Error("not_accepted: cancellation requires hello");
234
+ if (runtimeInFlight >= 32) throw new Error("not_accepted: too many in-flight runtime requests");
235
+ if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
236
+ runtimeInFlight++;
237
+ try {
238
+ cancellations ??= new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
239
+ return reply({ data: await cancellations.handle(command) });
240
+ } finally { runtimeInFlight--; }
241
+ }
242
+ if (type === "runtime_bind_catalog_host") {
243
+ if (!greeted) throw new Error(`${type} requires hello`);
244
+ catalog.admission.bind(command.authority, socket);
245
+ return reply({ data: { bound: true } });
246
+ }
247
+ if (type === "runtime_subscribe_catalog") {
248
+ if (!greeted) throw new Error(`${type} requires hello`);
249
+ catalogSubscription?.close();
250
+ const subscription = catalog.observe(() => catalogCommand({ type: "runtime_get_catalog", overlay: command.overlay }), snapshot => {
251
+ if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
252
+ send({ type: "event", event: { type: "runtime_catalog_snapshot", snapshot } } as unknown as ServerMessage);
253
+ });
254
+ catalogSubscription = subscription;
255
+ return reply({ data: subscription.snapshot });
256
+ }
257
+ if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog"].includes(type)) {
258
+ if (!greeted) throw new Error(`${type} requires hello`);
259
+ return reply({ data: catalogCommand(command) });
260
+ }
261
+ if (type === "runtime_register_client") {
262
+ if (!greeted) throw new Error("runtime_register_client requires hello");
263
+ if (typeof command.clientId !== "string" || !command.clientId || command.clientId.length > 256) throw new Error("Invalid runtime client identity");
264
+ runtimeClients.set(socket, command.clientId);
265
+ runtimeZeroSince = undefined;
266
+ return reply({ data: { clientId: command.clientId } });
267
+ }
268
+ if (type === "runtime_guardian_bind") {
269
+ if (!greeted) throw new Error("runtime_guardian_bind requires hello");
270
+ validateDaemonOwnerIdentity(command.server);
271
+ validateDaemonOwnerIdentity(command.guardian);
272
+ const current = inspectDaemonOwner(serverDir);
273
+ const guardian = inspectDaemonOwner(serverDir, "guardian-owner");
274
+ if (current.status !== "live" || guardian.status !== "live"
275
+ || !ownerIdentityVerified(current.owner) || !ownerIdentityVerified(guardian.owner)
276
+ || !sameOwner(current.owner, command.server) || !sameOwner(guardian.owner, command.guardian)
277
+ || current.owner.token !== instanceId) throw new Error("runtime-unhealthy: exact guardian/server identity could not be verified");
278
+ guardianBinding = { socket, identity: guardian.owner };
279
+ return reply({ data: { server: current.owner, guardian: guardian.owner } });
280
+ }
157
281
  if (type === "runtime_upgrade_status") return reply({ data: readActivationJournal(serverDir) ?? null });
282
+ if (["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_metrics"].includes(type)) {
283
+ if (!greeted) throw new Error(`${type} requires hello`);
284
+ if (id && id.length > 128) throw new Error("Runtime request ID exceeds 128 characters");
285
+ if (runtimeInFlight >= 32) throw new Error("runtime-unhealthy: too many in-flight queries; resync and retry");
286
+ if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
287
+ runtimeInFlight++;
288
+ try {
289
+ workQueries ??= work().connect(socket);
290
+ const data = await workQueries.handle(command);
291
+ if (type === "runtime_get_metrics") {
292
+ return reply({ data: { ...JSON.parse(data.json), mutationSqlite: mutationStoreMetrics(getAgentDir()) } });
293
+ }
294
+ if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
295
+ // Snapshot JSON is encoded in the worker; only the small envelope runs here.
296
+ const envelope = JSON.stringify({ id, type: "response", command: type, success: true });
297
+ if (!socket.destroyed) socket.write(envelope.slice(0, -1) + ',"data":' + data.json + "}\n");
298
+ return;
299
+ } finally {
300
+ runtimeInFlight--;
301
+ }
302
+ }
158
303
  if (type === "runtime_upgrade") {
159
304
  if (!safeUpgrade || !build) throw new Error("This daemon cannot safely activate managed runtimes");
160
305
  if (typeof command.operationId !== "string" || typeof command.runtime !== "object" || !command.runtime) throw new Error("Invalid upgrade request");
@@ -254,7 +399,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
254
399
  } finally {
255
400
  releaseSessionOperation?.();
256
401
  inFlight--;
257
- if (registry.activeCount > 0) zeroSince = undefined;
402
+ if (registry.activeCount > 0) { zeroSince = undefined; hostedUsed = true; }
258
403
  else zeroSince ??= now();
259
404
  }
260
405
  };
@@ -277,13 +422,23 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
277
422
  socket.on("data", (chunk: string) => decoder.push(chunk));
278
423
  socket.on("error", () => undefined);
279
424
  socket.on("close", () => {
425
+ catalogSubscription?.close();
426
+ catalog.admission.close(socket);
427
+ workQueries?.close();
280
428
  sockets.delete(socket);
429
+ runtimeClients.delete(socket);
430
+ if (guardianBinding?.socket === socket) guardianBinding = undefined;
431
+ if (runtimeClients.size === 0) runtimeZeroSince ??= now();
281
432
  reconnectControllers.delete(control);
282
433
  control.dispose();
283
434
  });
284
435
  });
285
436
 
286
437
  cleanupStartup = async () => {
438
+ await cancellations?.close();
439
+ resultSupervision?.close();
440
+ if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
441
+ await workModel?.close();
287
442
  for (const socket of sockets) socket.destroy();
288
443
  server.close();
289
444
  await registry.shutdown();
@@ -350,10 +505,28 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
350
505
  return;
351
506
  }
352
507
  zeroSince ??= now();
353
- if (config.daemonIdleMs === 0 || now() - zeroSince < config.daemonIdleMs || now() < startupUntil) return;
508
+ if (runtimeClients.size > 0) return;
509
+ runtimeZeroSince ??= now();
510
+ if (hostedUsed ? (config.daemonIdleMs === 0 || now() - zeroSince < config.daemonIdleMs || now() < startupUntil)
511
+ : (now() - runtimeZeroSince < config.runtimeIdleMs || now() < startupUntil)) return;
512
+ // Recheck durable activity before fencing admission; observation never adopts a writer.
513
+ if (draining) return;
514
+ try {
515
+ if ((await work().livenessReasons()).length > 0) {
516
+ runtimeZeroSince = undefined;
517
+ return;
518
+ }
519
+ } catch (error) {
520
+ // The executor already bounds query deadlines and terminates failed workers.
521
+ // Unknown obligations cannot keep an otherwise detached runtime alive forever.
522
+ // Stop only the management layer; leave runner evidence and writer leases intact.
523
+ observationUnavailable = true;
524
+ log(`runtime observation unavailable at idle shutdown: ${String(error)}`);
525
+ }
354
526
  // No create/open can slip between this check and the synchronous admission fence.
355
- if (inFlight > 0 || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
527
+ if (runtimeClients.size > 0 || registry.activeCount > 0 || inFlight > 0 || cancellations?.busy || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
356
528
  draining = true;
529
+ idleStopping = true;
357
530
  log("idle timeout with no active sessions; shutting down");
358
531
  })().finally(() => { maintenance = undefined; });
359
532
  return maintenance.then(() => draining ? daemon.stop() : undefined);
@@ -362,6 +535,12 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
362
535
  const pendingMaintenance = maintenance;
363
536
  stopped ??= (async () => {
364
537
  draining = true;
538
+ options.onDraining?.();
539
+ if (idleStopping) {
540
+ const temporary = join(serverDir, `idle-stop-${instanceId}.tmp`);
541
+ writeFileSync(temporary, JSON.stringify({ token: instanceId, pid: process.pid }), { mode: 0o600 });
542
+ renameSync(temporary, join(serverDir, "idle-stop-intent.json"));
543
+ }
365
544
  if (timer) clearInterval(timer);
366
545
  await pendingMaintenance?.catch(error => log(`maintenance interrupted during shutdown: ${String(error)}`));
367
546
  if (upgradeCommitted) {
@@ -374,25 +553,31 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
374
553
  const closed = new Promise<void>((resolve) => server.close(() => resolve()));
375
554
  for (const socket of sockets) socket.destroy();
376
555
  await closed;
556
+ await cancellations?.close();
557
+ resultSupervision?.close();
558
+ if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
559
+ await workModel?.close();
377
560
  await registry.shutdown();
378
561
  await Promise.allSettled([...dispatches]);
379
562
  if (existsSync(socketPath)) unlinkSync(socketPath);
563
+ const checkpoint = join(serverDir, `clean-stop-${instanceId}.tmp`);
564
+ writeFileSync(checkpoint, JSON.stringify({ pid: process.pid, token: instanceId, reason: "clean-stop", observation: observationUnavailable ? "unavailable" : "verified" }), { mode: 0o600 });
565
+ renameSync(checkpoint, join(serverDir, "clean-stop.json"));
380
566
  releaseOwner();
381
567
  finishClosed();
382
568
  })();
383
569
  return stopped;
384
570
  },
385
571
  };
386
- const durations = [config.sessionIdleMs, config.daemonIdleMs].filter(value => value > 0);
572
+ const durations = [config.sessionIdleMs, config.daemonIdleMs, config.runtimeIdleMs].filter(value => value > 0);
387
573
  if (safeUpgrade) durations.push(1_000);
388
574
  if (durations.length) {
389
- timer = setInterval(() => { void daemon.sweepIdle().catch(error => log(`lifecycle maintenance failed: ${String(error)}`)); }, Math.max(5, Math.min(30_000, ...durations)));
575
+ timer = setInterval(() => { void daemon.sweepIdle().catch(error => log(`lifecycle maintenance failed: ${String(error)}`)); }, Math.max(5, Math.min(1_000, ...durations)));
390
576
  timer.unref();
391
577
  }
392
578
  return daemon;
393
579
  } catch (error) {
394
- await cleanupStartup();
395
- releaseOwner();
580
+ try { await cleanupStartup(); } finally { releaseOwner(); }
396
581
  throw error;
397
582
  }
398
583
  }
@@ -14,7 +14,13 @@ export class SessionActivity {
14
14
  private readonly runtimeUnsubscribers = new Set<() => void>();
15
15
  /** Extensions share the host bus, but their subscriptions end at each loader reload. */
16
16
  readonly runtimeEvents: EventBus = {
17
- emit: (channel, data) => { if (!this.runtimeRevoked && !this.disposed) this.events.emit(channel, data); },
17
+ emit: (channel, data) => {
18
+ if (this.runtimeRevoked || this.disposed) {
19
+ if (channel === "pi-better-runtime:connect") (data as { reject?: (error: Error) => void })?.reject?.(new Error("runtime-unavailable: hosted session revoked"));
20
+ return;
21
+ }
22
+ this.events.emit(channel, data);
23
+ },
18
24
  on: (channel, handler) => {
19
25
  if (this.disposed || this.runtimeRevoked) return () => undefined;
20
26
  const unsubscribe = this.events.on(channel, (data) => {
@@ -56,11 +62,21 @@ export class SessionActivity {
56
62
  private readonly enterCommand: () => () => void;
57
63
  private pendingHandlers = 0;
58
64
  private runtimeRevoked = false;
65
+ private readonly workClients = new Set<{ close(): void }>();
59
66
 
60
- constructor(log: (message: string) => void, enterTool: () => () => void = () => () => undefined, enterCommand = enterTool) {
67
+ constructor(log: (message: string) => void, enterTool: () => () => void = () => () => undefined, enterCommand = enterTool, workClient?: () => import("./runtime/work-client.mjs").WorkClient) {
61
68
  this.enterTool = enterTool;
62
69
  this.enterCommand = enterCommand;
63
70
  this.log = log;
71
+ this.events.on("pi-better-runtime:connect", (request: any) => {
72
+ if (!workClient || this.disposed || this.runtimeRevoked || typeof request?.accept !== "function") return;
73
+ try {
74
+ const client = workClient();
75
+ this.workClients.add(client);
76
+ client.onChange(() => { if (client.closed) this.workClients.delete(client); });
77
+ request.accept(client);
78
+ } catch (error) { request.reject?.(error); }
79
+ });
64
80
  this.events.on("pi-better-goal:register-provider", (value) => {
65
81
  const provider = value as ActivityProvider | undefined;
66
82
  if (!provider || typeof provider.id !== "string" || typeof provider.getActivity !== "function" || this.disposed) return;
@@ -102,6 +118,8 @@ export class SessionActivity {
102
118
 
103
119
  /** After shutdown, before any new factories run; the host admission guard has already proved idleness. */
104
120
  resetRuntime(): void {
121
+ for (const client of this.workClients) client.close();
122
+ this.workClients.clear();
105
123
  for (const unsubscribe of this.unsubscribers.values()) unsubscribe();
106
124
  this.unsubscribers.clear();
107
125
  for (const unsubscribe of this.runtimeUnsubscribers) unsubscribe();
@@ -113,6 +131,8 @@ export class SessionActivity {
113
131
  /** A fenced runtime cannot receive late bus callbacks or register new background providers. */
114
132
  revokeRuntime(): void {
115
133
  this.runtimeRevoked = true;
134
+ for (const client of this.workClients) client.close();
135
+ this.workClients.clear();
116
136
  for (const unsubscribe of this.runtimeUnsubscribers) unsubscribe();
117
137
  }
118
138
 
@@ -6,7 +6,7 @@ import { setTimeout as delay } from "node:timers/promises";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { DaemonClient } from "../client.ts";
8
8
  import { claimDaemonOwner, inspectDaemonOwner, ownerIsAlive, validateDaemonOwnerIdentity, type DaemonOwnerIdentity } from "../daemon-owner.ts";
9
- import { socketPathFor } from "../paths.ts";
9
+ import { socketPathFor } from "../runtime/socket.ts";
10
10
  import type { Readiness } from "./ensure.ts";
11
11
  import type { ActivationResult, IdleSessionsLease, ServerBuild, StagedRuntime, UpgradeRequest } from "./managed-types.ts";
12
12
  import { homedir } from "node:os";
@@ -273,6 +273,15 @@ export const defaultActivationPorts: ActivationPorts = {
273
273
  finally { clearTimeout(timer); client.close(); }
274
274
  },
275
275
  async launch(request, options = { adopt: true }) {
276
+ // Server owner release precedes its process exit and the guardian's release.
277
+ // Preserve the old recovery owner until it observes that exact clean exit.
278
+ const deadline = Date.now() + 5000;
279
+ while (inspectDaemonOwner(request.serverDir, "guardian-owner").status === "live") {
280
+ const owner = inspectDaemonOwner(request.serverDir);
281
+ if (owner.status === "live" || owner.status === "ambiguous") throw new Error("runtime-unhealthy: existing server owner still prevents activation");
282
+ if (Date.now() >= deadline) throw new Error("runtime-unhealthy: previous guardian has not released ownership; no replacement launched");
283
+ await delay(25);
284
+ }
276
285
  const env: NodeJS.ProcessEnv = { ...process.env, PI_SERVER_AGENT: "pi", PI_SERVER_DIR: request.serverDir, PI_CODING_AGENT_DIR: request.agentDir,
277
286
  PI_SERVER_RUNTIME_MANIFEST: request.runtime.manifestPath };
278
287
  delete env.PI_SERVER_ACTIVATION_ID;
@@ -297,9 +306,13 @@ export const defaultActivationPorts: ActivationPorts = {
297
306
  /** Executed in a detached host process; the exclusive lock is never aged out. */
298
307
  export async function runActivationWorker(request: UpgradeRequest, ports: ActivationPorts = defaultActivationPorts): Promise<ActivationResult> {
299
308
  const serverDir = canonicalStateDir(request.serverDir);
309
+ // Contending claims are transient coordinator metadata, not existing daemon
310
+ // state. Keep them out of the root inventory used for empty-namespace proof.
311
+ const stagingDir = join(serverDir, RESERVATIONS);
312
+ mkdirSync(stagingDir, { recursive: true, mode: 0o700 });
300
313
  let release: () => void;
301
314
  for (let attempt = 0; ; attempt++) {
302
- try { release = claimDaemonOwner(serverDir, LOCK); break; }
315
+ try { release = claimDaemonOwner(serverDir, LOCK, stagingDir); break; }
303
316
  catch (error) {
304
317
  const journal = readActivationJournal(serverDir);
305
318
  // A staged journal can still name the abandoned build while the coordinator
@@ -396,6 +409,16 @@ export async function runActivationWorker(request: UpgradeRequest, ports: Activa
396
409
  save(journal);
397
410
  return result(journal);
398
411
  }
412
+ // Once scheduled, this exact daemon owns the durable stop transition.
413
+ // Repeated hellos can time out during activity observation and abandon its coordinator.
414
+ if (scheduled && journal.phase === "prepared") {
415
+ const owner = inspectDaemonOwner(serverDir);
416
+ if (owner.status === "live" && sameOwner(owner.owner, journal.previousOwner)) {
417
+ await ports.pause();
418
+ journal = readActivationJournal(serverDir)!;
419
+ continue;
420
+ }
421
+ }
399
422
  const probe = await ports.probe(serverDir);
400
423
  journal = readActivationJournal(serverDir)!;
401
424
  if (committed(journal.phase)) break;
@@ -411,9 +434,13 @@ export async function runActivationWorker(request: UpgradeRequest, ports: Activa
411
434
  if (!old || !compatibleUpgrade(old, journal.desiredBuild)) return defer(journal, "Unsafe SDK downgrade or incompatible protocol; activation deferred");
412
435
  journal.previousBuild = old;
413
436
  journal.previousOwner = owner.owner;
414
- journal.phase = "prepared";
415
- journal.reason = "Waiting for idle sessions and reconnect-capable controllers";
416
- save(journal);
437
+ if (journal.phase !== "prepared") {
438
+ journal.phase = "prepared";
439
+ journal.reason = "Waiting for idle sessions and reconnect-capable controllers";
440
+ save(journal);
441
+ }
442
+ // Once prepared, the daemon owns the stop transition. Re-publishing our
443
+ // snapshot could overwrite its stopping commitment while this probe ran.
417
444
  if (!scheduled) { await ports.schedule(journal); scheduled = true; }
418
445
  await ports.pause();
419
446
  journal = readActivationJournal(serverDir)!;
@@ -11,6 +11,7 @@ import { readActiveRuntime, activateStagedRuntime, type ActivateOptions } from "
11
11
  import { readOwnBuild, readStagedRuntime } from "./artifact.ts";
12
12
  import { checkStartupAdmission } from "./admission.ts";
13
13
  import { PROTOCOL_VERSION, type HelloData } from "../protocol.ts";
14
+ import { runtimeRoot } from "../runtime/root.ts";
14
15
 
15
16
  export interface Readiness {
16
17
  version: 1;
@@ -67,7 +68,16 @@ export async function ensureDaemon(options: EnsureOptions): Promise<Readiness> {
67
68
  abortCheck(options.signal);
68
69
  const timeoutMs = options.timeoutMs ?? 15_000;
69
70
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 120_000) throw new Error("Ensure timeout must be an integer from 1 to 120000 ms");
70
- const serverDir = existsSync(options.serverDir) ? realpathSync(options.serverDir) : resolve(options.serverDir);
71
+ const requested = existsSync(options.serverDir) ? realpathSync(options.serverDir) : resolve(options.serverDir);
72
+ const serverDir = existsSync(join(options.agentDir, "server-registration-v1.json")) ? runtimeRoot(options.agentDir, options.serverDir).serverDir : requested;
73
+ if (requested !== serverDir) {
74
+ try {
75
+ await health(socketPathFor(requested), Math.min(2000, timeoutMs), options);
76
+ throw new Error(`runtime-unhealthy: explicit endpoint ${requested} conflicts with registered runtime ${serverDir}`);
77
+ } catch (error) {
78
+ if (!absent(error)) throw new Error(`Server health at explicit endpoint ${requested}: ${String(error)}. Existing listener was not replaced.`);
79
+ }
80
+ }
71
81
  const socketPath = socketPathFor(serverDir);
72
82
  const deadline = Date.now() + timeoutMs;
73
83
  const ready = (hello: HelloData): Readiness => ({ version: 1, agent: "pi", serverDir, socketPath, hello });
@@ -84,6 +94,8 @@ export async function ensureDaemon(options: EnsureOptions): Promise<Readiness> {
84
94
  throw new Error(`Server runtime at ${serverDir} is incompatible: ${error instanceof Error ? error.message : String(error)}. Update/register a compatible installed runtime; no daemon was launched.`);
85
95
  }
86
96
  checkStartupAdmission({ canonicalServerDir: serverDir, agentDir: options.agentDir, build: selected?.build ?? readOwnBuild(), intent: { kind: "ordinary" } });
97
+ const registered = runtimeRoot(options.agentDir, options.serverDir).serverDir;
98
+ if (registered !== serverDir) return ensureDaemon({ ...options, serverDir: registered });
87
99
  if (Date.now() >= deadline) throw new Error(`Server readiness timed out at ${socketPath} before launch`);
88
100
  const logPath = join(serverDir, "daemon.log");
89
101
  let exitDetail = "";
@@ -11,6 +11,7 @@ export interface StageRuntimeOptions {
11
11
  signal?: AbortSignal;
12
12
  installRoot?: string;
13
13
  onProgress?: (stage: string) => void;
14
+ offline?: boolean;
14
15
  }
15
16
 
16
17
  async function download(url: string, integrity: string, signal?: AbortSignal): Promise<Buffer> {
@@ -125,6 +126,7 @@ printf 'reuse\\n'`, undefined, 120_000);
125
126
  if (cachedState === "absent" && archiveState !== "absent") throw new Error("Runtime staging: cached release disappeared during verification");
126
127
  const reuse = cachedState === "reuse";
127
128
  if (!reuse) {
129
+ if (options.offline) throw new Error(`Offline cache miss: pinned Node ${artifact.build.nodeVersion} and runtime ${artifact.build.contentId} are not cached at ${finalRoot}; connect once to install them`);
128
130
  onProgress?.("node-download");
129
131
  signal?.throwIfAborted();
130
132
  const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
package/src/version.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Kept equal to package.json `version`; a test pins that. */
2
+ export const SERVER_VERSION = "0.4.0";
3
+
4
+ export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };