omp-superagent 0.0.0-stage → 0.1.1

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 (76) hide show
  1. package/DESIGN.md +1361 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +184 -0
  4. package/README.md +205 -2
  5. package/THIRD_PARTY_NOTICES.md +313 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1030 -0
  12. package/docs/releases/0.1.0.md +222 -0
  13. package/docs/releases/0.1.1.md +60 -0
  14. package/package.json +59 -4
  15. package/scripts/check-omp.ts +4 -0
  16. package/scripts/ci.ts +28 -0
  17. package/scripts/prepare-ulw.ts +18 -0
  18. package/scripts/release.ts +50 -0
  19. package/scripts/setup.sh +25 -0
  20. package/skills/head/SKILL.md +259 -0
  21. package/skills/head/references/model-selection.md +263 -0
  22. package/skills/head/references/routing.md +356 -0
  23. package/skills/head/references/supervision.md +312 -0
  24. package/skills/lane/SKILL.md +188 -0
  25. package/skills/lane/references/workflow.md +349 -0
  26. package/src/autostart.ts +295 -0
  27. package/src/board-extension.ts +217 -0
  28. package/src/board.ts +396 -0
  29. package/src/cli.ts +167 -0
  30. package/src/config.ts +191 -0
  31. package/src/contracts.ts +317 -0
  32. package/src/credentials.ts +172 -0
  33. package/src/delivery.ts +7 -0
  34. package/src/dialog.ts +73 -0
  35. package/src/discord-command-registration.ts +201 -0
  36. package/src/discord-commands.ts +29 -0
  37. package/src/discord-markdown.ts +172 -0
  38. package/src/discord.ts +745 -0
  39. package/src/extension.ts +289 -0
  40. package/src/gateway-client.ts +222 -0
  41. package/src/gateway-protocol.ts +85 -0
  42. package/src/gateway-restart.ts +151 -0
  43. package/src/gateway-server.ts +392 -0
  44. package/src/gateway-store.ts +237 -0
  45. package/src/gateway.ts +638 -0
  46. package/src/head-recovery.ts +61 -0
  47. package/src/host-extension.ts +449 -0
  48. package/src/host-owner.ts +350 -0
  49. package/src/host-protocol.ts +136 -0
  50. package/src/host.ts +414 -0
  51. package/src/installed-omp.ts +63 -0
  52. package/src/lane-extension.ts +179 -0
  53. package/src/lane-models.ts +75 -0
  54. package/src/lane-report.ts +70 -0
  55. package/src/managed-ulw-probe.ts +172 -0
  56. package/src/managed-ulw.ts +471 -0
  57. package/src/message-order.ts +21 -0
  58. package/src/messenger-commands.ts +16 -0
  59. package/src/messengers.ts +114 -0
  60. package/src/native-presets.ts +282 -0
  61. package/src/native-sessions.ts +32 -0
  62. package/src/native-settings.ts +129 -0
  63. package/src/repository.ts +12 -0
  64. package/src/runtime.ts +3864 -0
  65. package/src/setup-judge.ts +34 -0
  66. package/src/setup-memory.ts +39 -0
  67. package/src/setup-profiles.ts +84 -0
  68. package/src/setup.ts +300 -0
  69. package/src/slack-command-registration.ts +217 -0
  70. package/src/slack-commands.ts +18 -0
  71. package/src/slack.ts +776 -0
  72. package/src/store.ts +806 -0
  73. package/src/telegram-command-registration.ts +155 -0
  74. package/src/telegram.ts +661 -0
  75. package/src/workflow.ts +94 -0
  76. package/upstream/ulw.json +9 -0
package/src/gateway.ts ADDED
@@ -0,0 +1,638 @@
1
+ #!/usr/bin/env bun
2
+ import { spawn, type ChildProcess } from "node:child_process";
3
+ import { Database } from "bun:sqlite";
4
+ import { constants, existsSync } from "node:fs";
5
+ import { lstat, mkdir, open, unlink } from "node:fs/promises";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
9
+ import { credentialEnvNames, hostPaths, loadConfig, privateDirectory, requireMessengerCredentials, type Config } from "./config";
10
+ import type { GatewayRestartRecord, GatewayRestartRequest, LanePresetSnapshot, Messenger } from "./contracts";
11
+ import { DeliveryError } from "./delivery";
12
+ import { gatewayCall, gatewayPaths, gatewayStatus } from "./gateway-protocol";
13
+ import { GatewayServer, type GatewayStatus } from "./gateway-server";
14
+ import { GatewayStore } from "./gateway-store";
15
+ import { readRestartPlan, restartConfigHash, validateRestartPlan, type RestartPlan } from "./gateway-restart";
16
+ import { connect, startHost } from "./host";
17
+ import { createMessenger } from "./messengers";
18
+ import { activeManagedUlw, managedUlwStatus, readUlwManifest, updateManagedUlw, validateManagedUlwPackage,
19
+ type ManagedUlwStatus } from "./managed-ulw";
20
+
21
+ export { gatewayPaths } from "./gateway-protocol";
22
+ export type { GatewayStatus } from "./gateway-server";
23
+ export interface GatewayOptions {
24
+ messenger?: Messenger;
25
+ onError?: (error: unknown) => void;
26
+ extensionPath?: string;
27
+ /** Isolated fixture package injection, never a production disable switch. */
28
+ managedUlwPath?: string;
29
+ /** Controlled source-refresh fixture; production always uses updateManagedUlw. */
30
+ updateManagedUlw?: () => Promise<ManagedUlwStatus>;
31
+ /** Isolated subprocess fixture seam; production always uses the fixed one-shot helper. */
32
+ launchRestartRunner?: (configPath: string, requestId: string, logFd: number) => ChildProcess;
33
+ /** Only the durable, owned one-shot handoff may supply this identity. */
34
+ restartRequestId?: string;
35
+ }
36
+ interface HeadIdentity { pid: number; ownerPid: number; sessionId: string; sessionFile: string; dev: number; ino: number }
37
+ interface SocketIdentity { pid: number; ownerPid?: number; dev: number; ino: number }
38
+
39
+ function alive(pid: number): boolean {
40
+ try { process.kill(pid, 0); return true; }
41
+ catch (error) {
42
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") return false;
43
+ throw error;
44
+ }
45
+ }
46
+ async function removeDeadSocket(socketPath: string, identity: SocketIdentity | null, kind: "gateway" | "host"): Promise<void> {
47
+ let stat;
48
+ try { stat = await lstat(socketPath); }
49
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
50
+ if (!identity || alive(identity.pid) ||
51
+ kind === "host" && (typeof identity.ownerPid !== "number" || !Number.isSafeInteger(identity.ownerPid) ||
52
+ identity.ownerPid < 1 || alive(identity.ownerPid))
53
+ || !stat.isSocket() || stat.uid !== process.getuid?.() ||
54
+ stat.dev !== identity.dev || stat.ino !== identity.ino)
55
+ throw new Error("Existing endpoint ownership is unresolved; no socket was removed or second host started");
56
+ await unlink(socketPath);
57
+ }
58
+
59
+ /** Owns adapters and exactly one native head; never reads or connects lane sockets. */
60
+ export class GatewayService {
61
+ private readonly store: GatewayStore;
62
+ private readonly messenger: Messenger;
63
+ private readonly server: GatewayServer;
64
+ private readonly report: (error: unknown) => void;
65
+ private head: HeadIdentity | null;
66
+ private transportsReady = false;
67
+ private stopping = false;
68
+ private closed = false;
69
+ private launching = false;
70
+ private error: string | null = null;
71
+ private supervision?: Promise<void>;
72
+ private monitor?: ReturnType<typeof setInterval>;
73
+ private updateMonitor?: ReturnType<typeof setInterval>;
74
+ private updating?: Promise<void>;
75
+ private ulw: ManagedUlwStatus = { revision: null, packagePath: null, upstreamRevision: null,
76
+ checkedAt: null, error: null, updating: false };
77
+ private closing?: Promise<void>;
78
+ private stopTask?: Promise<void>;
79
+ private restartRunning?: Promise<void>;
80
+ private restartAccepting = false;
81
+ private stopGeneration = 0;
82
+ private configHash?: string;
83
+ private readonly signal = () => { void this.stop().catch(this.report); };
84
+
85
+ constructor(readonly config: Config, private readonly options: GatewayOptions = {}) {
86
+ this.report = options.onError ?? (() => console.error("Gateway operation failed; inspect private service state"));
87
+ this.store = new GatewayStore(config.stateDir);
88
+ try {
89
+ this.head = JSON.parse(this.store.getMeta("gateway:head") ?? "null") as HeadIdentity | null;
90
+ this.messenger = options.messenger ?? createMessenger(config, this.store, this.report);
91
+ this.server = new GatewayServer({
92
+ socketPath: gatewayPaths(config).socketPath, store: this.store, messenger: this.messenger,
93
+ authorizeHead: pid => this.authorizeHead(pid), status: () => this.status(), onError: this.report,
94
+ restart: request => this.restart(request), runRestart: requestId => this.runRestart(requestId),
95
+ stop: async () => {
96
+ this.cancelRestart();
97
+ await this.stopHead();
98
+ // Allow the CLI to receive the committed shutdown receipt first.
99
+ setTimeout(() => { void this.close().catch(this.report); }, 25);
100
+ },
101
+ });
102
+ } catch (error) { this.store.close(); throw error; }
103
+ }
104
+
105
+ async start(): Promise<void> {
106
+ try {
107
+ this.configHash = await restartConfigHash(this.config.path);
108
+ if (this.options.restartRequestId) await this.validateReplacement();
109
+ else {
110
+ const active = this.store.getMeta("gateway:restart-active");
111
+ const pending = this.store.getRestart(active || undefined);
112
+ if (pending && (pending.state === "accepted" || pending.state === "head-stopped" || pending.state === "uncertain"))
113
+ throw new Error("An owned restart handoff is pending; ordinary startup cannot adopt it");
114
+ }
115
+ if (this.options.managedUlwPath) {
116
+ this.ulw = { ...this.ulw, packagePath: validateManagedUlwPackage(this.options.managedUlwPath), injected: true };
117
+ if (this.options.updateManagedUlw) void this.refreshUlw();
118
+ } else {
119
+ // Installation is mandatory before service activation. A slow/unreachable
120
+ // upstream must not delay an already prepared Gateway's IPC or head.
121
+ activeManagedUlw();
122
+ this.ulw = managedUlwStatus();
123
+ void this.refreshUlw();
124
+ this.updateMonitor = setInterval(() => { void this.refreshUlw(); }, readUlwManifest().checkIntervalMs);
125
+ this.updateMonitor.unref();
126
+ }
127
+ const path = gatewayPaths(this.config).socketPath;
128
+ const previous = JSON.parse(this.store.getMeta("gateway:socket") ?? "null") as SocketIdentity | null;
129
+ await removeDeadSocket(path, previous, "gateway");
130
+ await this.server.listen();
131
+ await this.messenger.start({
132
+ ready: this.server.initialReady.promise,
133
+ message: async input => { this.server.admitMessage(input); },
134
+ answer: async (approvalId, response, route) => {
135
+ this.store.admit({ kind: "answer", approvalId, response, route }); this.server.deliver();
136
+ },
137
+ reconnect: async () => { this.store.admit({ kind: "reconnect" }); this.server.deliver(); },
138
+ });
139
+ this.transportsReady = true;
140
+ await this.ensureHead();
141
+ if (this.options.restartRequestId) {
142
+ const record = this.store.getRestart(this.options.restartRequestId)!;
143
+ if (record.state !== "head-stopped" || this.stopping || !this.head || this.head.pid === record.headPid || this.head.sessionId !== record.sessionId ||
144
+ resolve(this.head.sessionFile) !== resolve(record.sessionFile))
145
+ throw new Error("Replacement native head identity did not match the restart request");
146
+ this.store.setRestart({ ...record, state: "started", successorPid: process.pid, replacementPid: this.head.pid });
147
+ this.store.setMeta("gateway:restart-active", "");
148
+ }
149
+ this.monitor = setInterval(() => {
150
+ void this.ensureHead().catch(error => { this.error = "Head ownership/startup requires reconciliation"; this.report(error); });
151
+ }, 1_000);
152
+ process.on("SIGTERM", this.signal);
153
+ process.on("SIGINT", this.signal);
154
+ } catch (error) { await this.close(); throw error; }
155
+ }
156
+
157
+ status(): GatewayStatus {
158
+ const live = this.head ? alive(this.head.pid) : false;
159
+ const saved = this.closed ? null : this.store.getMeta("head:preset-bootstrap");
160
+ const recorded: GatewayStatus["head"]["initialization"] = saved ? JSON.parse(saved) : undefined;
161
+ const initialization = recorded?.sessionId === this.head?.sessionId ? recorded : this.head ? {
162
+ sessionId: this.head.sessionId, state: "checking" as const,
163
+ detail: "Waiting for authoritative native HEAD attachment, approval reconciliation and preset inspection.",
164
+ } : undefined;
165
+ return {
166
+ gateway: { pid: process.pid, ready: this.transportsReady && !this.closed,
167
+ admissionReady: this.server.ready, pendingEvents: this.closed ? 0 : this.store.pending(), stopping: this.stopping },
168
+ head: { pid: this.head?.pid ?? null, ready: live && this.server.headReady && initialization?.state === "complete",
169
+ connected: live && this.server.connected, socketPath: hostPaths(this.config, "main").socketPath, error: this.error,
170
+ ...(initialization ? { initialization } : {}) },
171
+ ulw: { ...this.ulw },
172
+ };
173
+ }
174
+
175
+ private refreshUlw(): Promise<void> {
176
+ if (this.updating) return this.updating;
177
+ this.ulw = { ...this.ulw, updating: true };
178
+ this.updating = Promise.resolve().then(() => (this.options.updateManagedUlw ?? updateManagedUlw)()).then(status => { this.ulw = status; }, error => {
179
+ if (this.options.managedUlwPath) {
180
+ this.ulw = { ...this.ulw, updating: false, error: error instanceof Error ? error.message : "Managed ULW update failed" };
181
+ } else {
182
+ try { this.ulw = managedUlwStatus(); }
183
+ catch { this.ulw = { ...this.ulw, updating: false, error: "Managed ULW status is unavailable" }; }
184
+ }
185
+ this.report(error);
186
+ }).finally(() => { this.updating = undefined; });
187
+ return this.updating;
188
+ }
189
+
190
+ private async identifyHead(): Promise<HeadIdentity> {
191
+ const paths = hostPaths(this.config, "main");
192
+ const connection = await connect(paths.socketPath);
193
+ try {
194
+ const state = await connection.client.getState();
195
+ if (resolve(state.sessionFile!) !== resolve(paths.sessionFile)) throw new Error("Main endpoint belongs to another native session");
196
+ const stat = await lstat(paths.socketPath);
197
+ return { pid: state.hostPid!, ownerPid: state.adapterOwnerPid, sessionId: state.sessionId,
198
+ sessionFile: state.sessionFile!, dev: stat.dev, ino: stat.ino };
199
+ } finally { await connection.close(); }
200
+ }
201
+ private sameHead(actual: HeadIdentity, expected: HeadIdentity): boolean {
202
+ return actual.pid === expected.pid && actual.ownerPid === expected.ownerPid && actual.sessionId === expected.sessionId &&
203
+ resolve(actual.sessionFile) === resolve(expected.sessionFile) && actual.dev === expected.dev && actual.ino === expected.ino;
204
+ }
205
+ private async authorizeHead(pid: number): Promise<void> {
206
+ const actual = await this.identifyHead();
207
+ if (actual.pid !== pid || (!this.head && !this.launching) || (this.head && !this.sameHead(actual, this.head)))
208
+ throw new DeliveryError("Gateway client is not the supervised native head", "rejected");
209
+ }
210
+ private ensureHead(): Promise<void> {
211
+ if (this.stopping || this.closed) return Promise.resolve();
212
+ if (this.supervision) return this.supervision;
213
+ this.supervision = this.reconcileHead().finally(() => { this.supervision = undefined; });
214
+ return this.supervision;
215
+ }
216
+ private async reconcileHead(): Promise<void> {
217
+ const paths = hostPaths(this.config, "main");
218
+ if (this.head && alive(this.head.pid)) {
219
+ // A live PID alone is not adoption authority. Probe the saved session and
220
+ // inode each time; a PID reuse or replaced socket is never a second writer.
221
+ const known = this.head;
222
+ try {
223
+ const actual = await this.identifyHead();
224
+ if (!this.sameHead(actual, known)) throw new Error("Known native head identity changed");
225
+ this.error = null;
226
+ return;
227
+ } catch (error) {
228
+ // Losing a probe while this exact owned process dies is normal recovery,
229
+ // not a fatal adapter/ownership error. A still-live PID remains blocked.
230
+ if (alive(known.pid)) throw error;
231
+ }
232
+ }
233
+ await removeDeadSocket(paths.socketPath, this.head, "host");
234
+ this.head = null;
235
+ this.store.setMeta("gateway:head", "null");
236
+ const env = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined));
237
+ for (const name of credentialEnvNames(this.config)) delete env[name];
238
+ delete env.OMP_RPC_SOCKET;
239
+ delete env.OMP_SUPERAGENT_HOST_SOCKET;
240
+ delete env.OMP_SUPERAGENT_NATIVE_SOCKET;
241
+ delete env.OMP_SUPERAGENT_HOST_CONFIG;
242
+ env.OMP_SUPERAGENT_CONFIG = this.config.path;
243
+ env.OMP_SUPERAGENT_ROLE = "head";
244
+ env.OMP_SUPERAGENT_GATEWAY_TOKEN = this.store.token();
245
+ await mkdir(dirname(paths.sessionFile), { recursive: true, mode: 0o700 });
246
+ const restoring = existsSync(paths.sessionFile);
247
+ const sessionId = restoring ? await readSessionHeaderId(paths.sessionFile) : undefined;
248
+ if (sessionId && this.store.getMeta("main:sessionId") && sessionId !== this.store.getMeta("main:sessionId")) {
249
+ throw new Error("Stored head settings belong to a different native session; refusing startup");
250
+ }
251
+ const settingsRecord = sessionId ? this.store.getMeta(`head:model-settings:${sessionId}`) : null;
252
+ const savedSettings: { settings: LanePresetSnapshot; clearedRoles: string[] } | undefined =
253
+ settingsRecord ? JSON.parse(settingsRecord) : undefined;
254
+ this.launching = true;
255
+ try {
256
+ const launched = await startHost({ command: this.config.command, cwd: this.config.headCwd,
257
+ sessionFile: paths.sessionFile, socketPath: paths.socketPath, logPath: paths.logPath,
258
+ extensionPath: this.options.extensionPath ?? fileURLToPath(new URL("./extension.ts", import.meta.url)),
259
+ managedUlwPath: this.options.managedUlwPath,
260
+ env, model: restoring ? undefined : this.config.model,
261
+ ...(savedSettings ? { modelSettings: savedSettings.settings, clearedModelRoles: savedSettings.clearedRoles } : {}),
262
+ subagentConcurrency: Math.floor(this.config.maxSubagents / this.config.maxHosts),
263
+ });
264
+ const identity = await this.identifyHead();
265
+ if (identity.pid !== launched.pid) throw new Error("Launched head ownership changed");
266
+ this.head = identity;
267
+ this.store.setMeta("gateway:head", JSON.stringify(identity));
268
+ this.error = null;
269
+ } finally { this.launching = false; }
270
+ }
271
+
272
+ private stopHead(): Promise<void> {
273
+ if (this.stopTask) return this.stopTask;
274
+ this.stopTask = this.shutdownHead().finally(() => { this.stopTask = undefined; });
275
+ return this.stopTask;
276
+ }
277
+ private async shutdownHead(): Promise<void> {
278
+ if (this.closed) return;
279
+ this.stopping = true;
280
+ await this.supervision;
281
+ if (this.head && alive(this.head.pid)) {
282
+ const head = this.head;
283
+ const actual = await this.identifyHead();
284
+ if (!this.sameHead(actual, head)) { this.stopping = false; throw new Error("Refusing to stop an unowned native host"); }
285
+ const connection = await connect(hostPaths(this.config, "main").socketPath);
286
+ try {
287
+ const result = await connection.request({ type: "shutdown_host" });
288
+ if (!result.success) {
289
+ this.stopping = false;
290
+ throw new DeliveryError(result.error ?? "Native head refused busy shutdown", "rejected");
291
+ }
292
+ } catch (error) {
293
+ // An ambiguous shutdown is not a license to restart or kill the host.
294
+ throw error;
295
+ } finally { await connection.close(); }
296
+ const deadline = Date.now() + 15_000;
297
+ while ((alive(head.pid) || existsSync(hostPaths(this.config, "main").socketPath)) && Date.now() < deadline) await Bun.sleep(25);
298
+ if (alive(head.pid) || existsSync(hostPaths(this.config, "main").socketPath))
299
+ throw new Error("Native head exit/persistence is pending; Gateway supervision remains stopped");
300
+ const receipt = await Bun.file(`${hostPaths(this.config, "main").socketPath}.exit.json`).json();
301
+ if (receipt.pid !== head.pid || receipt.ownerPid !== head.ownerPid || receipt.sessionId !== head.sessionId
302
+ || receipt.sessionFile !== head.sessionFile || receipt.code !== 0 || receipt.signal !== null
303
+ || receipt.persisted !== true || receipt.observationsFlushed !== true)
304
+ throw new Error("Native head exit and durable persistence were not confirmed; Gateway supervision remains stopped");
305
+ }
306
+ this.head = null;
307
+ this.store.setMeta("gateway:head", "null");
308
+ }
309
+ async stop(): Promise<void> {
310
+ this.cancelRestart();
311
+ await this.stopHead();
312
+ await this.close();
313
+ }
314
+
315
+ private cancelRestart(): void {
316
+ if (this.closed) return;
317
+ this.store.setMeta("gateway:operator-stop", crypto.randomUUID());
318
+ this.stopGeneration++;
319
+ const active = this.store.getMeta("gateway:restart-active");
320
+ const record = this.store.getRestart(active || undefined);
321
+ if (!record || (record.gatewayPid !== process.pid && record.successorPid !== process.pid) ||
322
+ (record.state !== "accepted" && record.state !== "head-stopped")) return;
323
+ this.store.setRestart({ ...record, state: "refused", reason: "Explicit operator stop superseded the restart; no successor is authorized." });
324
+ this.store.setMeta("gateway:restart-active", "");
325
+ }
326
+
327
+ private async validateReplacement(): Promise<void> {
328
+ const requestId = this.options.restartRequestId!;
329
+ const record = this.store.getRestart(requestId);
330
+ const plan = readRestartPlan(this.store, requestId);
331
+ await validateRestartPlan(this.config, record, plan);
332
+ if (!record || !plan || record.state !== "head-stopped" || plan.launchPid !== process.pid ||
333
+ record.successorPid !== process.pid || this.store.getMeta("gateway:restart-active") !== requestId ||
334
+ alive(record.gatewayPid) || alive(record.headPid))
335
+ throw new Error("Replacement Gateway has no exact durable launch authority");
336
+ }
337
+
338
+ /** Accept only a sent owner command; the HTTP response must finish before execution. */
339
+ async restart(request: GatewayRestartRequest): Promise<GatewayRestartRecord> {
340
+ this.store.validateRestart(request);
341
+ const existing = this.store.getRestart(request.requestId);
342
+ if (existing) {
343
+ if (existing.inputId !== request.inputId || existing.ackOutputId !== request.ackOutputId)
344
+ throw new DeliveryError("Restart request identity conflict", "rejected");
345
+ return existing;
346
+ }
347
+ if (!this.head) throw new DeliveryError("Owned HEAD is unavailable; restart was not authorized", "rejected");
348
+ const head = this.head;
349
+ const stopGeneration = this.stopGeneration;
350
+ const record: GatewayRestartRecord = { ...request, gatewayPid: process.pid, headPid: head.pid,
351
+ sessionId: head.sessionId, sessionFile: head.sessionFile, state: "accepted" };
352
+ const refuse = (reason: string, outcome: "refused" | "uncertain" = "refused") => {
353
+ const result = { ...record, state: outcome, reason };
354
+ this.store.setRestart(result);
355
+ this.store.admit({ kind: "restart", requestId: request.requestId, outcome, reason });
356
+ this.server.deliver();
357
+ return result;
358
+ };
359
+ const activeId = this.store.getMeta("gateway:restart-active");
360
+ const active = this.store.getRestart(activeId || undefined);
361
+ if (this.closed || this.stopping || this.restartAccepting || active &&
362
+ (active.state === "accepted" || active.state === "head-stopped" || active.state === "uncertain"))
363
+ return refuse("Gateway already has an active or unresolved lifecycle operation; no process was stopped.");
364
+ this.restartAccepting = true;
365
+ this.stopping = true;
366
+ try {
367
+ await this.supervision;
368
+ const fence = JSON.parse(this.store.getMeta("head:restart-fence") ?? "null") as {
369
+ requestId?: string; inputId?: string; ackOutputId?: string; ownerPid?: number; sessionId?: string; sessionFile?: string;
370
+ stopBoundary?: string | null;
371
+ } | null;
372
+ if (!fence || fence.requestId !== request.requestId || fence.inputId !== request.inputId ||
373
+ fence.ackOutputId !== request.ackOutputId || fence.ownerPid !== head.pid || fence.sessionId !== head.sessionId ||
374
+ !fence.sessionFile || resolve(fence.sessionFile) !== resolve(head.sessionFile))
375
+ return refuse("HEAD restart fence does not match the owned request; no process was stopped.");
376
+ if (this.store.getMeta("gateway:operator-stop") !== (fence.stopBoundary ?? null))
377
+ return refuse("An explicit operator stop superseded this original restart intent; no successor is authorized.");
378
+ const actual = await this.identifyHead();
379
+ if (!this.sameHead(actual, head))
380
+ return refuse("Native HEAD ownership changed; no process was stopped.");
381
+ const connection = await connect(hostPaths(this.config, "main").socketPath);
382
+ try {
383
+ const state = await connection.client.getState();
384
+ if (state.hostPid !== head.pid || state.sessionId !== head.sessionId || !state.sessionFile ||
385
+ resolve(state.sessionFile) !== resolve(head.sessionFile))
386
+ return refuse("Native HEAD identity could not be verified; no process was stopped.");
387
+ if (state.isSettled !== true || state.isStreaming !== false || state.isCompacting !== false ||
388
+ state.queuedMessageCount !== 0 || state.hasPendingAsyncWork !== false || state.hasOwnedRunningWork !== false ||
389
+ !Array.isArray(state.pendingUiRequests) || state.pendingUiRequests.length || state.goal === undefined || state.goal?.enabled)
390
+ return refuse("Native HEAD is busy or its idle ownership state is incomplete; no process was stopped.");
391
+ } finally { await connection.close(); }
392
+ const socket = JSON.parse(this.store.getMeta("gateway:socket") ?? "null") as SocketIdentity | null;
393
+ const stat = await lstat(gatewayPaths(this.config).socketPath);
394
+ if (!socket || socket.pid !== process.pid || socket.dev !== stat.dev || socket.ino !== stat.ino)
395
+ return refuse("Gateway endpoint ownership could not be verified; no process was stopped.");
396
+ const plan: RestartPlan = { configPath: this.config.path, stateDir: this.config.stateDir,
397
+ configHash: await restartConfigHash(this.config.path), socket, head };
398
+ if (plan.configHash !== this.configHash)
399
+ return refuse("Gateway configuration changed since activation; no process was stopped or successor authorized.");
400
+ const currentFence = JSON.parse(this.store.getMeta("head:restart-fence") ?? "null") as typeof fence;
401
+ if (stopGeneration !== this.stopGeneration || this.store.getMeta("gateway:operator-stop") !== (fence.stopBoundary ?? null)
402
+ || !currentFence || currentFence.requestId !== request.requestId || currentFence.ownerPid !== head.pid)
403
+ return refuse("An explicit operator stop superseded restart acceptance; no successor was authorized.");
404
+ this.store.setMeta(`gateway:restart-plan:${request.requestId}`, JSON.stringify(plan));
405
+ this.store.setRestart(record);
406
+ this.store.setMeta("gateway:restart-active", request.requestId);
407
+ return record;
408
+ } catch {
409
+ return refuse("Native idle or ownership probe was unavailable; no shutdown was requested.");
410
+ } finally {
411
+ this.restartAccepting = false;
412
+ if (stopGeneration === this.stopGeneration && this.store.getRestart(request.requestId)?.state !== "accepted") this.stopping = false;
413
+ }
414
+ }
415
+
416
+ runRestart(requestId: string): void {
417
+ if (this.restartRunning || this.closed) return;
418
+ const record = this.store.getRestart(requestId);
419
+ if (!record || record.state !== "accepted" || record.gatewayPid !== process.pid) return;
420
+ // Reserve synchronously: duplicate response-finish callbacks cannot shut down twice.
421
+ this.restartRunning = this.executeRestart(record).catch(this.report).finally(() => { this.restartRunning = undefined; });
422
+ }
423
+
424
+ private async executeRestart(record: GatewayRestartRecord): Promise<void> {
425
+ try {
426
+ const actual = await this.identifyHead();
427
+ if (this.store.getRestart(record.requestId)?.state !== "accepted") return;
428
+ const plan = readRestartPlan(this.store, record.requestId);
429
+ if (!plan || !this.sameHead(actual, plan.head))
430
+ throw new DeliveryError("Native HEAD ownership changed; restart was refused without a shutdown", "rejected");
431
+ const paths = gatewayPaths(this.config);
432
+ const log = await open(paths.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
433
+ try {
434
+ const stat = await log.stat();
435
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
436
+ throw new Error("Restart log ownership is invalid");
437
+ if (this.store.getRestart(record.requestId)?.state !== "accepted") return;
438
+ const runner = this.options.launchRestartRunner?.(this.config.path, record.requestId, log.fd) ??
439
+ spawn(process.execPath, ["--no-env-file", fileURLToPath(new URL("./gateway-restart.ts", import.meta.url)),
440
+ "--config", this.config.path, "--state-dir", this.config.stateDir, "--request", record.requestId], {
441
+ cwd: this.config.headCwd, detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
442
+ });
443
+ // Spawn has an asynchronous error receipt. Do not release the lifetime lock until it is known.
444
+ const spawned = Promise.withResolvers<void>();
445
+ runner.once("spawn", spawned.resolve);
446
+ runner.once("error", spawned.reject);
447
+ try { await spawned.promise; }
448
+ catch { throw new DeliveryError("Successor could not be spawned; native shutdown was not requested", "rejected"); }
449
+ if (!runner.pid) throw new Error("Successor runner has no process identity");
450
+ this.store.setMeta(`gateway:restart-plan:${record.requestId}`, JSON.stringify({ ...plan, runnerPid: runner.pid }));
451
+ let exited = false;
452
+ runner.once("exit", () => { exited = true; });
453
+ runner.unref();
454
+ const deadline = Date.now() + 15_000;
455
+ while (!readRestartPlan(this.store, record.requestId)?.runnerReady) {
456
+ const state = this.store.getRestart(record.requestId)?.state;
457
+ if (state === "refused") return;
458
+ if (state !== "accepted") throw new Error("Successor preparation failed or lost its durable request");
459
+ if (exited) throw new DeliveryError("Successor exited before preparation; native shutdown was not requested", "rejected");
460
+ if (Date.now() >= deadline) throw new Error("Successor preparation outcome is unresolved");
461
+ await Bun.sleep(25);
462
+ }
463
+ } finally { await log.close(); }
464
+ const prepared = this.store.getRestart(record.requestId)?.state;
465
+ if (prepared === "refused") return;
466
+ if (prepared !== "accepted") throw new Error("Successor preparation authority changed");
467
+ // Reuse the supervised shutdown boundary only after the one-shot successor
468
+ // durably confirms its own identity. Its ambiguous outcome never authorizes a launch.
469
+ await this.stopHead();
470
+ if (this.store.getRestart(record.requestId)?.state !== "accepted") return;
471
+ this.store.setRestart({ ...record, state: "head-stopped" });
472
+ await this.close();
473
+ } catch (error) {
474
+ if (this.closed) return;
475
+ const saved = this.store.getRestart(record.requestId);
476
+ if (!saved || saved.state === "refused") return;
477
+ const refused = error instanceof DeliveryError && error.certainty === "rejected";
478
+ const reason = refused ? "Restart preparation or native shutdown was refused; no replacement Gateway was launched."
479
+ : "Restart shutdown or successor spawn outcome is uncertain; no automatic retry or forced kill is authorized.";
480
+ this.store.setRestart({ ...saved, state: refused ? "refused" : "uncertain", reason });
481
+ if (refused) this.store.setMeta("gateway:restart-active", "");
482
+ this.store.admit({ kind: "restart", requestId: record.requestId, outcome: refused ? "refused" : "uncertain", reason });
483
+ this.server.deliver();
484
+ if (refused) this.stopping = false;
485
+ }
486
+ }
487
+ close(): Promise<void> {
488
+ if (!this.closing) this.closing = this.detach();
489
+ return this.closing;
490
+ }
491
+ private async detach(): Promise<void> {
492
+ if (this.closed) return;
493
+ this.closed = true;
494
+ if (this.monitor) clearInterval(this.monitor);
495
+ if (this.updateMonitor) clearInterval(this.updateMonitor);
496
+ process.off("SIGTERM", this.signal);
497
+ process.off("SIGINT", this.signal);
498
+ await this.supervision;
499
+ await this.updating;
500
+ await this.server.close();
501
+ try { await this.messenger.stop(); }
502
+ finally { this.transportsReady = false; this.store.close(); }
503
+ }
504
+ }
505
+
506
+ export async function startGateway(config: Config, options: GatewayOptions = {}): Promise<GatewayService> {
507
+ if (!options.restartRequestId) {
508
+ privateDirectory(config.stateDir);
509
+ for (const directory of ["run", "logs", "sessions"]) privateDirectory(join(config.stateDir, directory));
510
+ }
511
+ let service: GatewayService;
512
+ if (options.restartRequestId) {
513
+ // The parent persists the spawned PID while holding the lifetime lock. A
514
+ // scheduled-fast child waits for that exact receipt, never for an arbitrary owner.
515
+ const deadline = Date.now() + 15_000;
516
+ const db = new Database(join(config.stateDir, "coordination.sqlite"), { readonly: true });
517
+ try {
518
+ for (;;) {
519
+ const getMeta = (key: string) => (db.query("SELECT value FROM metadata WHERE key=?").get(key) as { value: string } | null)?.value ?? null;
520
+ const record = JSON.parse(getMeta(`gateway:restart:${options.restartRequestId}`) ?? "null") as GatewayRestartRecord | null;
521
+ const plan = readRestartPlan({ getMeta }, options.restartRequestId);
522
+ if (!record || !plan || record.state !== "head-stopped" || getMeta("gateway:restart-active") !== record.requestId ||
523
+ (plan.launchPid !== undefined && plan.launchPid !== process.pid) ||
524
+ (record.successorPid !== undefined && record.successorPid !== process.pid))
525
+ throw new Error("Replacement launch receipt was cancelled or belongs to another process");
526
+ if (plan.launchPid === process.pid && record.successorPid === process.pid) {
527
+ try { service = new GatewayService(config, options); break; }
528
+ catch (error) {
529
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "SQLITE_BUSY") throw error;
530
+ // Only known pre-activation lock contention is waitable; no effect is retried.
531
+ }
532
+ }
533
+ if (Date.now() >= deadline) throw new Error("Exact restart launch receipt/lifetime lock was not released");
534
+ await Bun.sleep(25);
535
+ }
536
+ } finally { db.close(); }
537
+ } else service = new GatewayService(config, options);
538
+ await service.start();
539
+ return service;
540
+ }
541
+
542
+ export async function stopGateway(config: Config): Promise<void> {
543
+ try { await gatewayCall(gatewayPaths(config).socketPath, "/stop", {}, { timeoutMs: 25_000 }); }
544
+ catch (error) {
545
+ const database = new Database(join(config.stateDir, "coordination.sqlite"), { readonly: true });
546
+ try {
547
+ const row = database.query("SELECT value FROM metadata WHERE key='gateway:restart'").get() as { value: string } | null;
548
+ const restart = row ? JSON.parse(row.value) as GatewayRestartRecord : null;
549
+ if (restart && (restart.state === "accepted" || restart.state === "head-stopped"))
550
+ throw new DeliveryError("Gateway stop was not confirmed during a restart handoff; the successor was not cancelled. Inspect status before retrying stop.", "uncertain");
551
+ } finally { database.close(); }
552
+ throw error;
553
+ }
554
+ }
555
+
556
+ /** Explicit CLI activation only; ordinary commands never start the service. */
557
+ export async function launchGateway(config: Config, restartRequestId?: string, command = [process.execPath, "--no-env-file",
558
+ fileURLToPath(new URL("./gateway.ts", import.meta.url))]): Promise<GatewayStatus> {
559
+ let restart: GatewayRestartRecord | null = null;
560
+ let plan: RestartPlan | null = null;
561
+ let handoff: GatewayStore | undefined;
562
+ if (restartRequestId) {
563
+ handoff = new GatewayStore(config.stateDir);
564
+ try {
565
+ restart = handoff.getRestart(restartRequestId);
566
+ plan = readRestartPlan(handoff, restartRequestId);
567
+ await validateRestartPlan(config, restart, plan);
568
+ if (!restart || !plan || restart.state !== "head-stopped" || plan.runnerPid !== process.pid || plan.launchPid ||
569
+ handoff.getMeta("gateway:restart-active") !== restartRequestId || alive(restart.gatewayPid) ||
570
+ alive(restart.headPid) || alive(plan.head.ownerPid))
571
+ throw new Error("Restart launch authority is no longer valid");
572
+ } catch (error) { handoff.close(); throw error; }
573
+ }
574
+ let running: GatewayStatus | null;
575
+ try { running = await gatewayStatus(config); }
576
+ catch (error) {
577
+ // A private, recorded dead daemon may leave its exact socket behind. The
578
+ // replacement daemon acquires the SQLite lifetime lock before reconciling
579
+ // that inode. Unknown/live endpoints are never bypassed.
580
+ const database = new Database(join(config.stateDir, "coordination.sqlite"), { readonly: true });
581
+ try {
582
+ const row = database.query("SELECT value FROM metadata WHERE key='gateway:socket'").get() as { value: string } | null;
583
+ const previous = row ? JSON.parse(row.value) as SocketIdentity : null;
584
+ if (!previous || alive(previous.pid)) { handoff?.close(); throw error; }
585
+ running = null;
586
+ } finally { database.close(); }
587
+ }
588
+ if (running) {
589
+ handoff?.close();
590
+ if (restartRequestId) throw new Error("Restart cannot return or adopt an existing Gateway endpoint");
591
+ return running;
592
+ }
593
+ requireMessengerCredentials(config);
594
+ privateDirectory(config.stateDir);
595
+ for (const directory of ["run", "logs", "sessions"]) privateDirectory(join(config.stateDir, directory));
596
+ const paths = gatewayPaths(config);
597
+ const log = await open(paths.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
598
+ let child;
599
+ let failure: Error | undefined;
600
+ try {
601
+ const stat = await log.stat();
602
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
603
+ throw new Error("Gateway log must be a private owned regular file");
604
+ child = spawn(command[0]!, [...command.slice(1), "--config", config.path,
605
+ ...(restartRequestId ? ["--restart-request", restartRequestId] : [])], {
606
+ cwd: config.headCwd, detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
607
+ });
608
+ child.once("error", error => { failure = error; });
609
+ child.once("exit", () => { failure = new Error(`Gateway exited during startup; see ${paths.logPath}`); });
610
+ if (handoff && restart && plan && child.pid) {
611
+ handoff.setMeta(`gateway:restart-plan:${restart.requestId}`, JSON.stringify({ ...plan, launchPid: child.pid }));
612
+ handoff.setRestart({ ...restart, successorPid: child.pid });
613
+ }
614
+ child.unref();
615
+ } finally { handoff?.close(); await log.close(); }
616
+ const deadline = Date.now() + 45_000;
617
+ while (Date.now() < deadline) {
618
+ if (failure) throw failure;
619
+ try {
620
+ const status = await gatewayStatus(config);
621
+ if (status && status.gateway.pid === child.pid && status.gateway.ready && status.head.pid &&
622
+ (!restart || status.head.pid !== restart.headPid)) return status;
623
+ } catch { /* A freshly spawned daemon may still be binding/authenticating. */ }
624
+ await Bun.sleep(50);
625
+ }
626
+ // The service may already own a live head. Never kill it on a lost receipt.
627
+ throw new Error(`Gateway startup outcome unresolved; inspect status and ${paths.logPath} before retrying`);
628
+ }
629
+
630
+ if (import.meta.main) {
631
+ const index = process.argv.indexOf("--config");
632
+ if (index < 0 || !process.argv[index + 1]) throw new Error("Gateway requires --config FILE");
633
+ const restartAt = process.argv.indexOf("--restart-request");
634
+ try { await startGateway(await loadConfig(process.argv[index + 1]!), {
635
+ ...(restartAt >= 0 ? { restartRequestId: process.argv[restartAt + 1] } : {}),
636
+ }); }
637
+ catch { console.error("Gateway startup failed; no unowned host/socket was removed"); process.exitCode = 1; }
638
+ }