pi-better-server 0.2.2 → 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.
- package/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/shared-ssh-core/index.ts +30 -1
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
package/src/server.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
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,16 @@ 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 { WorkQueryExecutor } from "./runtime/query-executor.ts";
|
|
19
24
|
|
|
20
25
|
export interface DaemonOptions extends Partial<LifecycleConfig> {
|
|
21
26
|
/** Defaults to `~/.pi/agent/server` (or `$PI_SERVER_DIR`). */
|
|
@@ -30,6 +35,10 @@ export interface DaemonOptions extends Partial<LifecycleConfig> {
|
|
|
30
35
|
now?: () => number;
|
|
31
36
|
/** Brief protection between hello/readiness and creation of a session. */
|
|
32
37
|
startupGraceMs?: number;
|
|
38
|
+
/** CLI-owned process shutdown budget; never used to reclaim a different owner. */
|
|
39
|
+
onDraining?: () => void;
|
|
40
|
+
/** Trusted fault-injection seam; never exposed through the socket protocol. */
|
|
41
|
+
cancellationFault?: (stage: import("./runtime/cancellation.ts").CancellationStage) => void;
|
|
33
42
|
}
|
|
34
43
|
|
|
35
44
|
export interface Daemon {
|
|
@@ -56,7 +65,7 @@ function socketIsLive(path: string): Promise<boolean> {
|
|
|
56
65
|
}
|
|
57
66
|
|
|
58
67
|
export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon> {
|
|
59
|
-
const serverDir = canonicalStateDir(options.serverDir ?? defaultServerDir());
|
|
68
|
+
const serverDir = runtimeRoot(getAgentDir(), canonicalStateDir(options.serverDir ?? defaultServerDir())).serverDir;
|
|
60
69
|
const socketPath = socketPathFor(serverDir);
|
|
61
70
|
const log = options.log ?? (() => undefined);
|
|
62
71
|
ensureServerDir(serverDir);
|
|
@@ -79,8 +88,17 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
79
88
|
const owner = inspectDaemonOwner(serverDir);
|
|
80
89
|
const instanceId = owner.status === "live" ? owner.owner.token : undefined;
|
|
81
90
|
admitDaemonStartup({ canonicalServerDir: serverDir, agentDir: getAgentDir(), build, intent: startupIntentFromEnv(process.env) });
|
|
82
|
-
|
|
83
|
-
|
|
91
|
+
let cancellations: RuntimeCancellation | undefined;
|
|
92
|
+
if (hasPendingCancellation(getAgentDir())) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
|
|
93
|
+
let workModel: WorkQueryExecutor | undefined;
|
|
94
|
+
const work = () => {
|
|
95
|
+
if (!workModel) {
|
|
96
|
+
workModel = new WorkQueryExecutor(realpathSync(getAgentDir()), instanceId!);
|
|
97
|
+
}
|
|
98
|
+
return workModel;
|
|
99
|
+
};
|
|
100
|
+
const registry = new SessionRegistry({ serverDir, sessionOptions: options.sessionOptions, eventLog: options.eventLog, log, sessionIdleMs: config.sessionIdleMs, now, workClient: () => createLocalWorkClient(work(), realpathSync(getAgentDir())) });
|
|
101
|
+
cleanupStartup = async () => { await registry.shutdown(); await cancellations?.close(); await workModel?.close(); };
|
|
84
102
|
await registry.resumeAll();
|
|
85
103
|
const nativeHost = new NativeClientHost(registry);
|
|
86
104
|
// Structural port permits independent integration with the shared maintenance owner.
|
|
@@ -108,6 +126,12 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
108
126
|
const dispatches = new Set<Promise<void>>();
|
|
109
127
|
let inFlight = 0;
|
|
110
128
|
let draining = false;
|
|
129
|
+
let idleStopping = false;
|
|
130
|
+
const runtimeClients = new Map<Socket, string>();
|
|
131
|
+
let guardianBinding: { socket: Socket; identity: import("./daemon-owner.ts").DaemonOwnerIdentity } | undefined;
|
|
132
|
+
let observationUnavailable = false;
|
|
133
|
+
let runtimeZeroSince: number | undefined = now();
|
|
134
|
+
let hostedUsed = registry.activeCount > 0;
|
|
111
135
|
let zeroSince: number | undefined = registry.activeCount === 0 ? now() : undefined;
|
|
112
136
|
let startupUntil = 0;
|
|
113
137
|
const server: Server = createServer((socket) => {
|
|
@@ -117,6 +141,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
117
141
|
};
|
|
118
142
|
const control = new ConnectionControl(send);
|
|
119
143
|
let greeted = false;
|
|
144
|
+
let workQueries: ReturnType<WorkQueryExecutor["connect"]> | undefined;
|
|
145
|
+
let runtimeInFlight = 0;
|
|
120
146
|
|
|
121
147
|
const dispatch = async (line: string): Promise<void> => {
|
|
122
148
|
let command: Record<string, unknown>;
|
|
@@ -143,10 +169,10 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
143
169
|
return;
|
|
144
170
|
}
|
|
145
171
|
if (type === "hello") {
|
|
146
|
-
const verdict = checkHello(command, { build, instanceId, safeUpgrade });
|
|
172
|
+
const verdict = checkHello(command, { build, instanceId, safeUpgrade, runtimeLifecycle: true, agentDir: realpathSync(getAgentDir()) });
|
|
147
173
|
if (verdict.ok) {
|
|
148
174
|
reconnectControllers.set(control, Array.isArray(command.capabilities) && command.capabilities.includes("runtime-reconnect-v1"));
|
|
149
|
-
if (!greeted) startupUntil = Math.max(startupUntil, now() + startupGraceMs);
|
|
175
|
+
if (!greeted && command.runtimeRoot === undefined) startupUntil = Math.max(startupUntil, now() + startupGraceMs);
|
|
150
176
|
greeted = true;
|
|
151
177
|
return reply({ data: verdict.data });
|
|
152
178
|
}
|
|
@@ -154,7 +180,70 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
154
180
|
socket.end(); // an incompatible client gets the reason, then the door
|
|
155
181
|
return;
|
|
156
182
|
}
|
|
183
|
+
if (type === "runtime_get_status") {
|
|
184
|
+
if (!greeted) throw new Error("runtime_get_status requires hello");
|
|
185
|
+
// Status observes the last inventory; only idle shutdown requests a fresh liveness check.
|
|
186
|
+
const observation = workModel?.observation();
|
|
187
|
+
return reply({ data: { agentDir: realpathSync(getAgentDir()), serverDir, instanceId, build, nodeVersion: process.versions.node,
|
|
188
|
+
capabilities: ["runtime-status-v1"], hostedSessions: registry.activeCount, lifecycle: config,
|
|
189
|
+
guardianBinding: guardianBinding?.identity ?? null,
|
|
190
|
+
workObservation: observation ? { status: observation.status, reason: observation.reason, observedAt: observation.observedAt } : null,
|
|
191
|
+
livenessReasons: [...[...runtimeClients.values()].map(id => ({ kind: "connection", id })),
|
|
192
|
+
...registry.list().filter(session => session.live).map(session => ({ kind: "hosted-session", id: session.sessionId })),
|
|
193
|
+
...(observation?.reasons ?? [])],
|
|
194
|
+
nextIdleDeadline: runtimeClients.size > 0 || registry.activeCount > 0 ? null
|
|
195
|
+
: hostedUsed ? config.daemonIdleMs === 0 || zeroSince === undefined ? null : zeroSince + config.daemonIdleMs
|
|
196
|
+
: runtimeZeroSince === undefined ? null : runtimeZeroSince + config.runtimeIdleMs } });
|
|
197
|
+
}
|
|
198
|
+
if (type === "runtime_cancel_task" || type === "runtime_query_cancellation" || type === "runtime_cancellation_status") {
|
|
199
|
+
if (!greeted) throw new Error("not_accepted: cancellation requires hello");
|
|
200
|
+
if (runtimeInFlight >= 32) throw new Error("not_accepted: too many in-flight runtime requests");
|
|
201
|
+
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
202
|
+
runtimeInFlight++;
|
|
203
|
+
try {
|
|
204
|
+
cancellations ??= new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
|
|
205
|
+
return reply({ data: await cancellations.handle(command) });
|
|
206
|
+
} finally { runtimeInFlight--; }
|
|
207
|
+
}
|
|
208
|
+
if (type === "runtime_register_client") {
|
|
209
|
+
if (!greeted) throw new Error("runtime_register_client requires hello");
|
|
210
|
+
if (typeof command.clientId !== "string" || !command.clientId || command.clientId.length > 256) throw new Error("Invalid runtime client identity");
|
|
211
|
+
runtimeClients.set(socket, command.clientId);
|
|
212
|
+
runtimeZeroSince = undefined;
|
|
213
|
+
return reply({ data: { clientId: command.clientId } });
|
|
214
|
+
}
|
|
215
|
+
if (type === "runtime_guardian_bind") {
|
|
216
|
+
if (!greeted) throw new Error("runtime_guardian_bind requires hello");
|
|
217
|
+
validateDaemonOwnerIdentity(command.server);
|
|
218
|
+
validateDaemonOwnerIdentity(command.guardian);
|
|
219
|
+
const current = inspectDaemonOwner(serverDir);
|
|
220
|
+
const guardian = inspectDaemonOwner(serverDir, "guardian-owner");
|
|
221
|
+
if (current.status !== "live" || guardian.status !== "live"
|
|
222
|
+
|| !ownerIdentityVerified(current.owner) || !ownerIdentityVerified(guardian.owner)
|
|
223
|
+
|| !sameOwner(current.owner, command.server) || !sameOwner(guardian.owner, command.guardian)
|
|
224
|
+
|| current.owner.token !== instanceId) throw new Error("runtime-unhealthy: exact guardian/server identity could not be verified");
|
|
225
|
+
guardianBinding = { socket, identity: guardian.owner };
|
|
226
|
+
return reply({ data: { server: current.owner, guardian: guardian.owner } });
|
|
227
|
+
}
|
|
157
228
|
if (type === "runtime_upgrade_status") return reply({ data: readActivationJournal(serverDir) ?? null });
|
|
229
|
+
if (["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_metrics"].includes(type)) {
|
|
230
|
+
if (!greeted) throw new Error(`${type} requires hello`);
|
|
231
|
+
if (id && id.length > 128) throw new Error("Runtime request ID exceeds 128 characters");
|
|
232
|
+
if (runtimeInFlight >= 32) throw new Error("runtime-unhealthy: too many in-flight queries; resync and retry");
|
|
233
|
+
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
234
|
+
runtimeInFlight++;
|
|
235
|
+
try {
|
|
236
|
+
workQueries ??= work().connect(socket);
|
|
237
|
+
const data = await workQueries.handle(command);
|
|
238
|
+
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
239
|
+
// Snapshot JSON is encoded in the worker; only the small envelope runs here.
|
|
240
|
+
const envelope = JSON.stringify({ id, type: "response", command: type, success: true });
|
|
241
|
+
if (!socket.destroyed) socket.write(envelope.slice(0, -1) + ',"data":' + data.json + "}\n");
|
|
242
|
+
return;
|
|
243
|
+
} finally {
|
|
244
|
+
runtimeInFlight--;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
158
247
|
if (type === "runtime_upgrade") {
|
|
159
248
|
if (!safeUpgrade || !build) throw new Error("This daemon cannot safely activate managed runtimes");
|
|
160
249
|
if (typeof command.operationId !== "string" || typeof command.runtime !== "object" || !command.runtime) throw new Error("Invalid upgrade request");
|
|
@@ -254,7 +343,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
254
343
|
} finally {
|
|
255
344
|
releaseSessionOperation?.();
|
|
256
345
|
inFlight--;
|
|
257
|
-
if (registry.activeCount > 0) zeroSince = undefined;
|
|
346
|
+
if (registry.activeCount > 0) { zeroSince = undefined; hostedUsed = true; }
|
|
258
347
|
else zeroSince ??= now();
|
|
259
348
|
}
|
|
260
349
|
};
|
|
@@ -277,13 +366,19 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
277
366
|
socket.on("data", (chunk: string) => decoder.push(chunk));
|
|
278
367
|
socket.on("error", () => undefined);
|
|
279
368
|
socket.on("close", () => {
|
|
369
|
+
workQueries?.close();
|
|
280
370
|
sockets.delete(socket);
|
|
371
|
+
runtimeClients.delete(socket);
|
|
372
|
+
if (guardianBinding?.socket === socket) guardianBinding = undefined;
|
|
373
|
+
if (runtimeClients.size === 0) runtimeZeroSince ??= now();
|
|
281
374
|
reconnectControllers.delete(control);
|
|
282
375
|
control.dispose();
|
|
283
376
|
});
|
|
284
377
|
});
|
|
285
378
|
|
|
286
379
|
cleanupStartup = async () => {
|
|
380
|
+
await cancellations?.close();
|
|
381
|
+
await workModel?.close();
|
|
287
382
|
for (const socket of sockets) socket.destroy();
|
|
288
383
|
server.close();
|
|
289
384
|
await registry.shutdown();
|
|
@@ -350,10 +445,28 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
350
445
|
return;
|
|
351
446
|
}
|
|
352
447
|
zeroSince ??= now();
|
|
353
|
-
if (
|
|
448
|
+
if (runtimeClients.size > 0) return;
|
|
449
|
+
runtimeZeroSince ??= now();
|
|
450
|
+
if (hostedUsed ? (config.daemonIdleMs === 0 || now() - zeroSince < config.daemonIdleMs || now() < startupUntil)
|
|
451
|
+
: (now() - runtimeZeroSince < config.runtimeIdleMs || now() < startupUntil)) return;
|
|
452
|
+
// Recheck durable activity before fencing admission; observation never adopts a writer.
|
|
453
|
+
if (draining) return;
|
|
454
|
+
try {
|
|
455
|
+
if ((await work().livenessReasons()).length > 0) {
|
|
456
|
+
runtimeZeroSince = undefined;
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
} catch (error) {
|
|
460
|
+
// The executor already bounds query deadlines and terminates failed workers.
|
|
461
|
+
// Unknown obligations cannot keep an otherwise detached runtime alive forever.
|
|
462
|
+
// Stop only the management layer; leave runner evidence and writer leases intact.
|
|
463
|
+
observationUnavailable = true;
|
|
464
|
+
log(`runtime observation unavailable at idle shutdown: ${String(error)}`);
|
|
465
|
+
}
|
|
354
466
|
// No create/open can slip between this check and the synchronous admission fence.
|
|
355
|
-
if (inFlight > 0 || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
|
|
467
|
+
if (runtimeClients.size > 0 || registry.activeCount > 0 || inFlight > 0 || cancellations?.busy || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
|
|
356
468
|
draining = true;
|
|
469
|
+
idleStopping = true;
|
|
357
470
|
log("idle timeout with no active sessions; shutting down");
|
|
358
471
|
})().finally(() => { maintenance = undefined; });
|
|
359
472
|
return maintenance.then(() => draining ? daemon.stop() : undefined);
|
|
@@ -362,6 +475,12 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
362
475
|
const pendingMaintenance = maintenance;
|
|
363
476
|
stopped ??= (async () => {
|
|
364
477
|
draining = true;
|
|
478
|
+
options.onDraining?.();
|
|
479
|
+
if (idleStopping) {
|
|
480
|
+
const temporary = join(serverDir, `idle-stop-${instanceId}.tmp`);
|
|
481
|
+
writeFileSync(temporary, JSON.stringify({ token: instanceId, pid: process.pid }), { mode: 0o600 });
|
|
482
|
+
renameSync(temporary, join(serverDir, "idle-stop-intent.json"));
|
|
483
|
+
}
|
|
365
484
|
if (timer) clearInterval(timer);
|
|
366
485
|
await pendingMaintenance?.catch(error => log(`maintenance interrupted during shutdown: ${String(error)}`));
|
|
367
486
|
if (upgradeCommitted) {
|
|
@@ -374,19 +493,24 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
374
493
|
const closed = new Promise<void>((resolve) => server.close(() => resolve()));
|
|
375
494
|
for (const socket of sockets) socket.destroy();
|
|
376
495
|
await closed;
|
|
496
|
+
await cancellations?.close();
|
|
497
|
+
await workModel?.close();
|
|
377
498
|
await registry.shutdown();
|
|
378
499
|
await Promise.allSettled([...dispatches]);
|
|
379
500
|
if (existsSync(socketPath)) unlinkSync(socketPath);
|
|
501
|
+
const checkpoint = join(serverDir, `clean-stop-${instanceId}.tmp`);
|
|
502
|
+
writeFileSync(checkpoint, JSON.stringify({ pid: process.pid, token: instanceId, reason: "clean-stop", observation: observationUnavailable ? "unavailable" : "verified" }), { mode: 0o600 });
|
|
503
|
+
renameSync(checkpoint, join(serverDir, "clean-stop.json"));
|
|
380
504
|
releaseOwner();
|
|
381
505
|
finishClosed();
|
|
382
506
|
})();
|
|
383
507
|
return stopped;
|
|
384
508
|
},
|
|
385
509
|
};
|
|
386
|
-
const durations = [config.sessionIdleMs, config.daemonIdleMs].filter(value => value > 0);
|
|
510
|
+
const durations = [config.sessionIdleMs, config.daemonIdleMs, config.runtimeIdleMs].filter(value => value > 0);
|
|
387
511
|
if (safeUpgrade) durations.push(1_000);
|
|
388
512
|
if (durations.length) {
|
|
389
|
-
timer = setInterval(() => { void daemon.sweepIdle().catch(error => log(`lifecycle maintenance failed: ${String(error)}`)); }, Math.max(5, Math.min(
|
|
513
|
+
timer = setInterval(() => { void daemon.sweepIdle().catch(error => log(`lifecycle maintenance failed: ${String(error)}`)); }, Math.max(5, Math.min(1_000, ...durations)));
|
|
390
514
|
timer.unref();
|
|
391
515
|
}
|
|
392
516
|
return daemon;
|
package/src/session-activity.ts
CHANGED
|
@@ -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) => {
|
|
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
|
|
|
@@ -90,6 +90,7 @@ export interface SshMuxControllerOptions extends ResolvedSshCommand {
|
|
|
90
90
|
runner: RemoteRunner;
|
|
91
91
|
sessionScope: string;
|
|
92
92
|
controlPathRoot?: string;
|
|
93
|
+
platform?: NodeJS.Platform;
|
|
93
94
|
}
|
|
94
95
|
|
|
95
96
|
export interface SshMuxStatus {
|
|
@@ -101,7 +102,6 @@ export interface SshMuxStatus {
|
|
|
101
102
|
}
|
|
102
103
|
|
|
103
104
|
export interface SshMuxEnsureResult extends SshMuxStatus {
|
|
104
|
-
state: "up";
|
|
105
105
|
reused: boolean;
|
|
106
106
|
}
|
|
107
107
|
|
|
@@ -340,6 +340,35 @@ export function defaultSshControlPathRoot(): string {
|
|
|
340
340
|
*/
|
|
341
341
|
export function createSshMuxController(options: SshMuxControllerOptions): SshMuxController {
|
|
342
342
|
const sessionScope = requireValue(options.sessionScope, "ssh mux sessionScope is required").trim();
|
|
343
|
+
// Native Windows OpenSSH cannot provide a working ControlMaster socket.
|
|
344
|
+
if ((options.platform ?? process.platform) === "win32") {
|
|
345
|
+
const commandResult: CommandResult = {
|
|
346
|
+
exitCode: null, signal: null, stdout: "", stderr: "", startedAt: 0, endedAt: 0,
|
|
347
|
+
};
|
|
348
|
+
const disabled: SshMuxStatus = {
|
|
349
|
+
state: "down",
|
|
350
|
+
target: options.identity.target,
|
|
351
|
+
controlPath: "",
|
|
352
|
+
detail: "SSH multiplexing is disabled on Windows; commands use independent connections.",
|
|
353
|
+
commandResult,
|
|
354
|
+
};
|
|
355
|
+
const unsupportedForward = async (): Promise<SshMuxForwardResult> => {
|
|
356
|
+
throw new SshMuxError("SSH Unix socket forwarding is not supported on Windows without ControlMaster.", commandResult);
|
|
357
|
+
};
|
|
358
|
+
return {
|
|
359
|
+
controlPath: "",
|
|
360
|
+
forwardUnixSocket: unsupportedForward,
|
|
361
|
+
cancelUnixSocketForward: unsupportedForward,
|
|
362
|
+
status: async () => disabled,
|
|
363
|
+
ensure: async () => ({ ...disabled, reused: false }),
|
|
364
|
+
cleanup: async () => ({ ...disabled, state: "not_running" }),
|
|
365
|
+
withMux: (commandSpec) => muxCommandSpec(commandSpec, options.identity.target, [
|
|
366
|
+
"-o", "ControlMaster=no",
|
|
367
|
+
"-o", "ControlPersist=no",
|
|
368
|
+
"-o", "ControlPath=none",
|
|
369
|
+
], true),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
343
372
|
const controlPathRoot = resolve(options.controlPathRoot ?? defaultSshControlPathRoot());
|
|
344
373
|
const controlPath = join(controlPathRoot, `cm-${muxIdentityHash(options.identity, sessionScope)}`);
|
|
345
374
|
if (Buffer.byteLength(controlPath) > MAX_SSH_CONTROL_PATH_BYTES) {
|
|
@@ -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 "../
|
|
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
|
|
415
|
-
|
|
416
|
-
|
|
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)!;
|
package/src/startup/ensure.ts
CHANGED
|
@@ -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
|
|
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 = "";
|
package/src/startup/install.ts
CHANGED
|
@@ -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