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
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ import { Database } from "bun:sqlite";
3
+ import { createHash } from "node:crypto";
4
+ import { lstat, readFile } from "node:fs/promises";
5
+ import { join, resolve } from "node:path";
6
+ import { hostPaths, loadConfig, requireMessengerCredentials, type Config } from "./config";
7
+ import { loadCredentials } from "./credentials";
8
+ import type { GatewayRestartRecord } from "./contracts";
9
+ import { GatewayStore } from "./gateway-store";
10
+ import type { GatewayStatus } from "./gateway-server";
11
+ import { gatewayPaths } from "./gateway-protocol";
12
+
13
+ export interface RestartPlan {
14
+ configPath: string;
15
+ stateDir: string;
16
+ configHash: string;
17
+ socket: { pid: number; dev: number; ino: number };
18
+ head: { pid: number; ownerPid: number; sessionId: string; sessionFile: string; dev: number; ino: number };
19
+ runnerPid?: number;
20
+ runnerReady?: boolean;
21
+ launchPid?: number;
22
+ }
23
+ interface Metadata { getMeta(key: string): string | null }
24
+ export function readRestartPlan(store: Metadata, requestId: string): RestartPlan | null {
25
+ return JSON.parse(store.getMeta(`gateway:restart-plan:${requestId}`) ?? "null") as RestartPlan | null;
26
+ }
27
+ export function processAlive(pid: number): boolean {
28
+ try { process.kill(pid, 0); return true; }
29
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error; }
30
+ }
31
+ export async function restartConfigHash(path: string): Promise<string> {
32
+ return createHash("sha256").update(await readFile(path)).digest("hex");
33
+ }
34
+
35
+ /** Durable identity, not a caller-supplied PID, grants permission to resume this exact session. */
36
+ export async function validateRestartPlan(config: Config, record: GatewayRestartRecord | null, plan: RestartPlan | null): Promise<void> {
37
+ if (!record || !plan || resolve(plan.configPath) !== resolve(config.path) || resolve(plan.stateDir) !== resolve(config.stateDir) ||
38
+ record.gatewayPid !== plan.socket.pid || record.headPid !== plan.head.pid ||
39
+ !Number.isSafeInteger(plan.head.ownerPid) || plan.head.ownerPid < 1 ||
40
+ record.sessionId !== plan.head.sessionId || resolve(record.sessionFile) !== resolve(plan.head.sessionFile) ||
41
+ resolve(record.sessionFile) !== resolve(hostPaths(config, "main").sessionFile))
42
+ throw new Error("Restart durable ownership does not match the original configuration and session");
43
+ if (await restartConfigHash(config.path) !== plan.configHash)
44
+ throw new Error("Restart configuration changed; no replacement is authorized");
45
+ // Static native imports run OMP's dotenv loader before the explicit credential boundary.
46
+ const { readSessionHeaderId } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
47
+ if (await readSessionHeaderId(record.sessionFile) !== record.sessionId)
48
+ throw new Error("Restart session identity changed; no replacement is authorized");
49
+ }
50
+
51
+ /** Write even when the predecessor still owns its lifetime lock; never overwrite cancellation/success. */
52
+ function recordFailure(db: Database, requestId: string, reason: string): void {
53
+ db.transaction(() => {
54
+ const row = db.query("SELECT value FROM metadata WHERE key=?").get(`gateway:restart:${requestId}`) as { value: string } | null;
55
+ if (!row) return;
56
+ const record = JSON.parse(row.value) as GatewayRestartRecord;
57
+ if ((record.state !== "accepted" && record.state !== "head-stopped") || readRestartPlan({
58
+ getMeta: key => (db.query("SELECT value FROM metadata WHERE key=?").get(key) as { value: string } | null)?.value ?? null,
59
+ }, requestId)?.runnerPid !== process.pid) return;
60
+ const failed = JSON.stringify({ ...record, state: "failed", reason });
61
+ db.query("UPDATE metadata SET value=? WHERE key=?").run(failed, `gateway:restart:${requestId}`);
62
+ const latest = db.query("SELECT value FROM metadata WHERE key='gateway:restart'").get() as { value: string } | null;
63
+ if (latest && (JSON.parse(latest.value) as GatewayRestartRecord).requestId === requestId)
64
+ db.query("UPDATE metadata SET value=? WHERE key='gateway:restart'").run(failed);
65
+ }).immediate();
66
+ }
67
+
68
+ /** Bounded detached handoff, never a supervisor: wait, launch once through the normal loader, exit. */
69
+ export async function runGatewayRestart(configPath: string, requestId: string, options: {
70
+ timeoutMs?: number;
71
+ /** Original owned directory lets failure receipts survive a removed/changed config file. */
72
+ stateDir?: string;
73
+ /** Real subprocess fixture seam; never persisted or selected by production flags/configuration. */
74
+ launch?: (config: Config, requestId: string) => Promise<GatewayStatus>;
75
+ } = {}): Promise<void> {
76
+ const stateDir = options.stateDir ?? (await loadConfig(configPath)).stateDir;
77
+ const db = new Database(join(stateDir, "coordination.sqlite"), { create: false, strict: true });
78
+ db.run("PRAGMA busy_timeout=5000");
79
+ const metadata: Metadata = {
80
+ getMeta: key => (db.query("SELECT value FROM metadata WHERE key=?").get(key) as { value: string } | null)?.value ?? null,
81
+ };
82
+ let lock: GatewayStore | undefined;
83
+ try {
84
+ const config = await loadConfig(configPath);
85
+ if (resolve(config.stateDir) !== resolve(stateDir)) throw new Error("Restart state directory changed");
86
+ // Resolve credentials before any native module may run its own dotenv loader.
87
+ loadCredentials(config);
88
+ requireMessengerCredentials(config);
89
+ const deadline = Date.now() + (options.timeoutMs ?? 90_000);
90
+ let record: GatewayRestartRecord | null;
91
+ let plan: RestartPlan | null;
92
+ for (;;) {
93
+ record = JSON.parse(metadata.getMeta(`gateway:restart:${requestId}`) ?? "null") as GatewayRestartRecord | null;
94
+ plan = readRestartPlan(metadata, requestId);
95
+ await validateRestartPlan(config, record, plan);
96
+ if (!record || !plan || (record.state !== "accepted" && record.state !== "head-stopped")) return;
97
+ if (metadata.getMeta("gateway:restart-active") !== requestId) throw new Error("Restart is not the active owned intent");
98
+ if (plan.runnerPid !== undefined && plan.runnerPid !== process.pid)
99
+ throw new Error("Restart runner identity changed");
100
+ if (plan.runnerPid === process.pid && !plan.runnerReady) {
101
+ const socket = await lstat(gatewayPaths(config).socketPath);
102
+ if (!socket.isSocket() || socket.uid !== process.getuid?.() || socket.dev !== plan.socket.dev || socket.ino !== plan.socket.ino)
103
+ throw new Error("Predecessor Gateway endpoint changed before successor preparation");
104
+ db.transaction(() => {
105
+ const current = JSON.parse(metadata.getMeta(`gateway:restart:${requestId}`) ?? "null") as GatewayRestartRecord | null;
106
+ const owned = readRestartPlan(metadata, requestId);
107
+ if (!current || (current.state !== "accepted" && current.state !== "head-stopped") || !owned || owned.runnerPid !== process.pid)
108
+ throw new Error("Successor preparation lost request ownership");
109
+ db.query("UPDATE metadata SET value=? WHERE key=?").run(JSON.stringify({ ...owned, runnerReady: true }), `gateway:restart-plan:${requestId}`);
110
+ }).immediate();
111
+ }
112
+ if (record.state === "head-stopped" && processAlive(record.headPid)) throw new Error("Predecessor HEAD shutdown is not confirmed");
113
+ if (record.state === "head-stopped" && plan.runnerPid === process.pid &&
114
+ !processAlive(record.gatewayPid) && !processAlive(plan.head.ownerPid)) {
115
+ try { lock = new GatewayStore(config.stateDir); }
116
+ catch { /* A released process identity is not yet a released lifetime lock. */ }
117
+ if (lock) break;
118
+ }
119
+ if (Date.now() >= deadline) throw new Error("Predecessor did not exit and release its lifetime lock");
120
+ await Bun.sleep(25);
121
+ }
122
+ // The lock serializes final cancellation/identity checks with every normal start.
123
+ const current = lock.getRestart(requestId);
124
+ const currentPlan = readRestartPlan(lock, requestId);
125
+ await validateRestartPlan(config, current, currentPlan);
126
+ if (!current || !currentPlan || current.state !== "head-stopped" || currentPlan.runnerPid !== process.pid ||
127
+ lock.getMeta("gateway:restart-active") !== requestId || currentPlan.launchPid ||
128
+ processAlive(current.gatewayPid) || processAlive(current.headPid) || processAlive(currentPlan.head.ownerPid)) return;
129
+ const socket = JSON.parse(lock.getMeta("gateway:socket") ?? "null") as RestartPlan["socket"] | null;
130
+ if (!socket || socket.pid !== currentPlan.socket.pid || socket.dev !== currentPlan.socket.dev || socket.ino !== currentPlan.socket.ino ||
131
+ lock.getMeta("gateway:head") !== "null") throw new Error("Predecessor endpoint ownership changed");
132
+ lock.close();
133
+ lock = undefined;
134
+ // This import must stay after credential resolution; Gateway imports native OMP modules.
135
+ const { launchGateway } = await import("./gateway");
136
+ const status = await (options.launch ?? launchGateway)(config, requestId);
137
+ const result = JSON.parse(metadata.getMeta(`gateway:restart:${requestId}`) ?? "null") as GatewayRestartRecord | null;
138
+ if (!result || result.state !== "started" || result.successorPid !== status.gateway.pid ||
139
+ result.replacementPid !== status.head.pid || status.gateway.pid === result.gatewayPid || status.head.pid === result.headPid)
140
+ throw new Error("Replacement ownership/readiness was not confirmed");
141
+ } catch {
142
+ recordFailure(db, requestId, "One-shot restart handoff failed or timed out; no retry or forced kill was attempted. Inspect the exact durable request before recovery.");
143
+ } finally { lock?.close(); db.close(); }
144
+ }
145
+
146
+ if (import.meta.main) {
147
+ const at = (name: string) => process.argv[process.argv.indexOf(name) + 1];
148
+ const config = at("--config"), request = at("--request");
149
+ if (!config || !request) process.exitCode = 1;
150
+ else await runGatewayRestart(config, request, { stateDir: at("--state-dir") }).catch(() => { process.exitCode = 1; });
151
+ }
@@ -0,0 +1,392 @@
1
+ import { once } from "node:events";
2
+ import { chmod, lstat, unlink } from "node:fs/promises";
3
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4
+ import type { Socket } from "node:net";
5
+ import type { Approval, Attachment, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageReference, Messenger, OutputRecord, Route } from "./contracts";
6
+ import { DeliveryError } from "./delivery";
7
+ import { MAX_GATEWAY_ATTACHMENT, readGatewayJson, type GatewayResult } from "./gateway-protocol";
8
+ import { GatewayStore } from "./gateway-store";
9
+ import type { ManagedUlwStatus } from "./managed-ulw";
10
+
11
+ export interface HeadInitialization {
12
+ sessionId: string;
13
+ state: "checking" | "running" | "complete" | "blocked" | "failed" | "uncertain";
14
+ requestId?: string;
15
+ /** Durable fence survives a crash during a later startup's checking phase. */
16
+ replayBlocked?: boolean;
17
+ detail: string;
18
+ }
19
+ export interface GatewayStatus {
20
+ gateway: { pid: number; ready: boolean; admissionReady: boolean; pendingEvents: number; unresolvedEvents?: number; stopping: boolean };
21
+ head: { pid: number | null; ready: boolean; connected: boolean; socketPath: string; error: string | null;
22
+ initialization?: HeadInitialization };
23
+ ulw?: ManagedUlwStatus;
24
+ restart?: Omit<GatewayRestartRecord, "sessionFile">;
25
+ }
26
+ interface HeadClient { id: string; pid: number; ready: boolean; resumed: boolean; reconciled: boolean; events?: ServerResponse; sequence?: number; reconciliation?: string }
27
+ interface ServerOptions {
28
+ socketPath: string;
29
+ store: GatewayStore;
30
+ messenger: Messenger;
31
+ authorizeHead(pid: number): Promise<void>;
32
+ status(): GatewayStatus;
33
+ stop(): Promise<void>;
34
+ restart?(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
35
+ runRestart?(requestId: string): void;
36
+ onError(error: unknown): void;
37
+ }
38
+
39
+ function failure(error: unknown): GatewayResult {
40
+ return { ok: false, error: error instanceof DeliveryError ? error.message : "Gateway operation failed",
41
+ certainty: error instanceof DeliveryError ? error.certainty : "uncertain",
42
+ ...(error instanceof DeliveryError && error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}) };
43
+ }
44
+ function json(response: ServerResponse, value: GatewayResult, status = 200): void {
45
+ response.writeHead(status, { "content-type": "application/json" });
46
+ response.end(JSON.stringify(value));
47
+ }
48
+ function record(value: unknown): Record<string, unknown> {
49
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new DeliveryError("Invalid Gateway request", "rejected");
50
+ return value as Record<string, unknown>;
51
+ }
52
+
53
+ /** Ordinary-code IPC: a fixed Messenger surface, never a native RPC relay. */
54
+ export class GatewayServer {
55
+ readonly initialReady = Promise.withResolvers<void>();
56
+ private readonly server = createServer((request, response) => {
57
+ void this.handle(request, response).catch(error => {
58
+ if (!response.headersSent) json(response, failure(error), 400);
59
+ else response.destroy();
60
+ this.options.onError(error);
61
+ });
62
+ });
63
+ private readonly peers = new Set<Socket>();
64
+ private readonly effects = new Set<Promise<void>>();
65
+ private readonly restartRequests = new Map<string, { request: GatewayRestartRequest; result: Promise<GatewayRestartRecord> }>();
66
+ private readonly restartRuns = new Set<string>();
67
+ private client?: HeadClient;
68
+ private admissionReady = false;
69
+ private socketIdentity?: { dev: number; ino: number };
70
+ private closing = false;
71
+
72
+ constructor(private readonly options: ServerOptions) {
73
+ void this.initialReady.promise.catch(() => {});
74
+ this.server.on("connection", socket => {
75
+ this.peers.add(socket);
76
+ socket.on("error", () => {});
77
+ socket.on("close", () => this.peers.delete(socket));
78
+ });
79
+ }
80
+ get connected(): boolean { return !!this.client?.events && !this.client.events.destroyed; }
81
+ get headReady(): boolean { return this.connected && !!this.client?.ready && !this.client.reconciliation && this.options.store.unresolved() === 0; }
82
+ get ready(): boolean { return this.admissionReady; }
83
+
84
+ admitMessage(input: Inbound): void {
85
+ const fresh = this.options.store.admit({ kind: "message", input });
86
+ if (fresh && input.messageId !== null && this.options.messenger.setActivity) {
87
+ const message = { route: input.route, messageId: input.messageId };
88
+ const operation = Promise.resolve().then(() => this.options.messenger.setActivity?.(message, "received"));
89
+ this.effects.add(operation);
90
+ void operation.catch(() => this.options.onError(new Error("Message receipt reaction failed")))
91
+ .finally(() => this.effects.delete(operation));
92
+ }
93
+ this.deliver();
94
+ }
95
+
96
+ private openAdmission(): void {
97
+ if (this.admissionReady) return;
98
+ this.admissionReady = true;
99
+ this.initialReady.resolve();
100
+ }
101
+
102
+ async listen(): Promise<void> {
103
+ const opened = Promise.withResolvers<void>();
104
+ this.server.once("error", opened.reject);
105
+ this.server.listen(this.options.socketPath, () => opened.resolve());
106
+ await opened.promise;
107
+ this.server.off("error", opened.reject);
108
+ this.server.on("error", this.options.onError);
109
+ await chmod(this.options.socketPath, 0o600);
110
+ const stat = await lstat(this.options.socketPath);
111
+ this.socketIdentity = { dev: stat.dev, ino: stat.ino };
112
+ this.options.store.setMeta("gateway:socket", JSON.stringify({ pid: process.pid, ...this.socketIdentity }));
113
+ }
114
+
115
+ private authenticated(request: IncomingMessage): string {
116
+ if (request.headers.authorization !== `Bearer ${this.options.store.token()}`)
117
+ throw new DeliveryError("Gateway head authorization required", "rejected");
118
+ const id = request.headers["x-gateway-client"];
119
+ if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id)) throw new DeliveryError("Invalid Gateway client", "rejected");
120
+ return id;
121
+ }
122
+ private head(request: IncomingMessage): HeadClient {
123
+ const id = this.authenticated(request);
124
+ if (!this.client || this.client.id !== id) throw new DeliveryError("Gateway client is detached", "rejected");
125
+ return this.client;
126
+ }
127
+ private async handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
128
+ const endpoint = request.url;
129
+ if (endpoint === "/status" && request.method === "GET") {
130
+ const status = this.options.status();
131
+ const latest = this.options.store.getRestart();
132
+ const { sessionFile: _, ...restart } = latest ?? {};
133
+ json(response, { ok: true, value: { ...status, ...(latest ? { restart } : {}), gateway: { ...status.gateway, unresolvedEvents: this.options.store.unresolved() } } });
134
+ return;
135
+ }
136
+ if (endpoint === "/stop" && request.method === "POST") {
137
+ await readGatewayJson(request);
138
+ await this.options.stop();
139
+ json(response, { ok: true });
140
+ return;
141
+ }
142
+ if (this.closing) throw new DeliveryError("Gateway is stopping", "rejected");
143
+ if (endpoint === "/attach" && request.method === "POST") {
144
+ const id = this.authenticated(request);
145
+ const data = record(await readGatewayJson(request));
146
+ if (!Number.isSafeInteger(data.pid) || Number(data.pid) < 1) throw new DeliveryError("Invalid head PID", "rejected");
147
+ await this.options.authorizeHead(Number(data.pid));
148
+ if (this.client && this.client.id !== id && this.connected) throw new DeliveryError("A head client is already attached", "rejected");
149
+ if (this.client?.id === id) this.client.events?.destroy();
150
+ const reconciled = this.client?.id === id && this.client.pid === data.pid && this.client.reconciled;
151
+ this.client = { id, pid: Number(data.pid), ready: false, resumed: data.resumed === true, reconciled };
152
+ json(response, { ok: true });
153
+ return;
154
+ }
155
+ const client = this.head(request);
156
+ if (endpoint === "/events" && request.method === "GET") {
157
+ if (client.events && !client.events.destroyed) throw new DeliveryError("Head event stream already open", "rejected");
158
+ response.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
159
+ response.flushHeaders();
160
+ client.events = response;
161
+ response.on("close", () => {
162
+ if (client.events !== response) return;
163
+ client.events = undefined;
164
+ client.ready = false;
165
+ client.sequence = undefined;
166
+ });
167
+ this.deliver();
168
+ return;
169
+ }
170
+ if (request.method !== "POST") throw new DeliveryError("Unknown Gateway operation", "rejected");
171
+ if (endpoint === "/restart") {
172
+ // Recheck supervised process authority before reading any caller body.
173
+ try { await this.options.authorizeHead(client.pid); }
174
+ catch { throw new DeliveryError("Gateway head authorization rejected", "rejected"); }
175
+ // Native approval reconciliation belongs to this authenticated controller,
176
+ // not to one SSE connection. Quarantine may close that stream after
177
+ // receive durably admits a priority restart but before its async handoff.
178
+ if (!this.admissionReady || !client.reconciled || client.reconciliation)
179
+ throw new DeliveryError("Gateway head is not ready for restart", "rejected");
180
+ await this.restart(record(await readGatewayJson(request)), response);
181
+ return;
182
+ }
183
+ const data = record(await readGatewayJson(request));
184
+ if (endpoint === "/ready") {
185
+ const wasReady = client.ready;
186
+ client.ready = true;
187
+ if (!wasReady && client.resumed) {
188
+ // A resumed controller's own startup gate is already resolved, but a
189
+ // freshly authenticated adapter has no restored approval card cache.
190
+ // Its initial admission barrier must wait for head reconciliation ACK.
191
+ if (!this.admissionReady) client.reconciliation = crypto.randomUUID();
192
+ this.options.store.admit({ kind: "reconnect", ...(client.reconciliation ? { barrier: client.reconciliation } : {}) });
193
+ } else if (!client.resumed) {
194
+ // A new controller reconciled native approvals before calling /ready.
195
+ this.openAdmission();
196
+ }
197
+ if (!client.reconciliation) client.reconciled = true;
198
+ json(response, { ok: true });
199
+ this.deliver();
200
+ } else if (endpoint === "/receipt") {
201
+ if (!Number.isSafeInteger(data.sequence) || data.sequence !== client.sequence)
202
+ throw new DeliveryError("Gateway receipt is not the outstanding event", "rejected");
203
+ const outstanding = this.options.store.next(client.sequence)?.event;
204
+ const barrier = outstanding?.kind === "reconnect" ? outstanding.barrier : undefined;
205
+ if (data.outcome !== "accepted" && data.outcome !== "rejected" && data.outcome !== "unresolved")
206
+ throw new DeliveryError("Invalid Gateway admission receipt", "rejected");
207
+ const outcome = data.outcome;
208
+ if (barrier && !this.admissionReady && outcome !== "accepted") {
209
+ // Keep the durable reconciliation event pending. Never ACK fresh
210
+ // platform approval replies against an unregistered/empty card cache.
211
+ this.options.store.receipt(Number(data.sequence), "unresolved");
212
+ json(response, { ok: true });
213
+ client.events?.destroy();
214
+ return;
215
+ }
216
+ this.options.store.receipt(Number(data.sequence), outcome);
217
+ client.sequence = undefined;
218
+ if (barrier && barrier === client.reconciliation && outcome === "accepted") {
219
+ client.reconciliation = undefined;
220
+ client.reconciled = true;
221
+ this.openAdmission();
222
+ }
223
+ json(response, { ok: true });
224
+ if (outcome === "unresolved") client.events?.destroy();
225
+ else this.deliver();
226
+ } else if (endpoint === "/detach") {
227
+ client.events?.destroy();
228
+ this.client = undefined;
229
+ json(response, { ok: true });
230
+ } else if (endpoint === "/effect") {
231
+ const task = this.effect(data, response);
232
+ this.effects.add(task);
233
+ try { await task; } finally { this.effects.delete(task); }
234
+ } else if (endpoint === "/attachment") {
235
+ await this.attachment(data, response);
236
+ } else throw new DeliveryError("Unknown Gateway operation", "rejected");
237
+ }
238
+
239
+ private async restart(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
240
+ const { requestId, inputId, ackOutputId } = data;
241
+ if (typeof requestId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(requestId)
242
+ || typeof inputId !== "string" || !inputId.trim() || inputId.length > 1024
243
+ || typeof ackOutputId !== "string" || !ackOutputId.trim() || ackOutputId.length > 1024)
244
+ throw new DeliveryError("Invalid Gateway restart request", "rejected");
245
+ if (!this.options.restart || !this.options.runRestart) throw new DeliveryError("Gateway restart is unavailable", "rejected");
246
+ const request = { requestId, inputId, ackOutputId };
247
+ const prior = this.options.store.getRestart(requestId);
248
+ const pending = this.restartRequests.get(requestId);
249
+ const identity = prior ?? pending?.request;
250
+ const source = this.options.store.getMeta(`gateway:restart-source:${inputId}`);
251
+ if (identity && (identity.inputId !== inputId || identity.ackOutputId !== ackOutputId) || source !== null && source !== requestId)
252
+ throw new DeliveryError("Gateway restart identity conflict", "rejected");
253
+ for (const entry of this.restartRequests.values()) {
254
+ if (entry.request.inputId === inputId && entry.request.requestId !== requestId)
255
+ throw new DeliveryError("Gateway restart identity conflict", "rejected");
256
+ }
257
+ let result: GatewayRestartRecord;
258
+ try {
259
+ if (prior) result = prior;
260
+ else {
261
+ if (!pending) {
262
+ this.options.store.validateRestart(request);
263
+ const operation = Promise.resolve().then(() => this.options.restart!(request));
264
+ this.restartRequests.set(requestId, { request, result: operation });
265
+ }
266
+ try { result = await this.restartRequests.get(requestId)!.result; }
267
+ finally { this.restartRequests.delete(requestId); }
268
+ }
269
+ } catch (error) {
270
+ throw new DeliveryError("Gateway restart request failed", error instanceof DeliveryError ? error.certainty : "uncertain");
271
+ }
272
+ const persisted = this.options.store.getRestart(requestId);
273
+ if (result.requestId !== requestId || result.inputId !== inputId || result.ackOutputId !== ackOutputId
274
+ || !persisted || persisted.inputId !== inputId || persisted.ackOutputId !== ackOutputId)
275
+ throw new DeliveryError("Gateway restart acceptance was not persisted", "uncertain");
276
+ result = persisted;
277
+ if (response.destroyed) return;
278
+ if (result.state === "accepted") response.once("finish", () => {
279
+ if (this.restartRuns.has(requestId) || this.options.store.getRestart(requestId)?.state !== "accepted") return;
280
+ this.restartRuns.add(requestId);
281
+ try { this.options.runRestart!(requestId); }
282
+ catch { this.options.onError(new Error("Gateway restart execution failed")); }
283
+ });
284
+ json(response, { ok: true, value: result });
285
+ }
286
+
287
+ deliver(): void {
288
+ const client = this.client;
289
+ if (!client?.ready || !client.events || client.events.destroyed || client.sequence !== undefined) return;
290
+ const event = this.options.store.next();
291
+ if (!event) return;
292
+ // A lost callback receipt is ambiguous even if the head disconnects before
293
+ // processing the frame. Reconcile the original native request on redelivery.
294
+ if (event.event.kind === "answer") this.options.store.attempt(event.sequence);
295
+ client.sequence = event.sequence;
296
+ client.events.write(`${JSON.stringify(event)}\n`);
297
+ }
298
+
299
+ private async effect(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
300
+ const { id, operation, args } = data;
301
+ if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || typeof operation !== "string" || !Array.isArray(args))
302
+ throw new DeliveryError("Invalid Gateway effect", "rejected");
303
+ const operations: Record<string, number[]> = { send: [1], setActivity: [2], showApproval: [1], dismissApproval: [1], canCreateThread: [1], createThread: [2, 3], fetchAfter: [2] };
304
+ if (!Object.hasOwn(operations, operation) || !operations[operation]!.includes(args.length))
305
+ throw new DeliveryError("Unknown Gateway effect", "rejected");
306
+ const previous = this.options.store.beginEffect(id, operation, args);
307
+ if (!previous.fresh) { json(response, previous.result as GatewayResult); return; }
308
+ let result: GatewayResult;
309
+ try {
310
+ const messenger = this.options.messenger;
311
+ if (operation === "setActivity" && args[1] !== "received" && args[1] !== "thinking" && args[1] !== "idle")
312
+ throw new DeliveryError("Invalid message activity", "rejected");
313
+ if (operation === "setActivity" && (typeof record(args[0]).messageId !== "string" || !record(args[0]).messageId))
314
+ throw new DeliveryError("Message activity requires a real message ID", "rejected");
315
+ const value = operation === "send" ? await messenger.send(args[0] as OutputRecord)
316
+ : operation === "setActivity" ? await messenger.setActivity?.(args[0] as MessageReference, args[1] as "received" | "thinking" | "idle")
317
+ : operation === "showApproval" ? await messenger.showApproval(args[0] as Approval)
318
+ : operation === "dismissApproval" ? await messenger.dismissApproval(args[0] as Approval)
319
+ : operation === "canCreateThread" ? await messenger.canCreateThread?.(args[0] as Route) ?? false
320
+ : operation === "createThread" ? await messenger.createThread(args[0] as Route, args[1] as string, args[2] as string | undefined)
321
+ : await messenger.fetchAfter(args[0] as Route, args[1] as string);
322
+ result = { ok: true, value };
323
+ } catch (error) { result = failure(error); }
324
+ // Persistence precedes the receipt; disconnection never cancels or repeats
325
+ // a remote mutation whose outcome may already exist.
326
+ this.options.store.finishEffect(id, result);
327
+ if (!response.destroyed) json(response, result);
328
+ }
329
+
330
+ private async attachment(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
331
+ const attachment = record(data.attachment) as unknown as Attachment;
332
+ if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
333
+ throw new DeliveryError("Invalid attachment size", "rejected");
334
+ const controller = new AbortController();
335
+ let cancelRead: (() => Promise<void>) | undefined;
336
+ const abort = () => { controller.abort(); void cancelRead?.().catch(() => {}); };
337
+ response.on("close", abort);
338
+ try {
339
+ const upstream = await this.options.messenger.openAttachment(data.route as Route, attachment, controller.signal);
340
+ if (!upstream.body) throw new DeliveryError("Attachment response has no body", "rejected");
341
+ const length = upstream.headers.get("content-length");
342
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > (attachment.size ?? MAX_GATEWAY_ATTACHMENT)))
343
+ throw new DeliveryError("Attachment response exceeds declared size", "rejected");
344
+ const expectedSize = attachment.size ?? (length === null ? null : Number(length));
345
+ response.writeHead(upstream.status, {
346
+ "content-type": upstream.headers.get("content-type") ?? "application/octet-stream",
347
+ "x-gateway-attachment-protocol": "1",
348
+ ...(length === null ? {} : { "x-gateway-attachment-length": length }),
349
+ });
350
+ response.flushHeaders();
351
+ const reader = upstream.body.getReader();
352
+ cancelRead = () => reader.cancel();
353
+ let bytes = 0;
354
+ while (true) {
355
+ const chunk = await reader.read();
356
+ if (chunk.done) break;
357
+ bytes += chunk.value.byteLength;
358
+ if (bytes > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes > MAX_GATEWAY_ATTACHMENT) throw new Error("Attachment stream exceeds declared size");
359
+ if (!chunk.value.byteLength) continue;
360
+ // Socket closure alone is not a completion receipt: some HTTP stacks
361
+ // expose a destroyed response as an empty/truncated successful body.
362
+ const frame = Buffer.allocUnsafe(4);
363
+ frame.writeUInt32BE(chunk.value.byteLength);
364
+ if (!response.write(frame)) await once(response, "drain", { signal: controller.signal });
365
+ if (!response.write(chunk.value)) await once(response, "drain", { signal: controller.signal });
366
+ }
367
+ if (expectedSize !== null && bytes !== expectedSize) throw new Error("Attachment stream was truncated");
368
+ response.end(Buffer.alloc(4));
369
+ } finally {
370
+ response.off("close", abort);
371
+ controller.abort();
372
+ await cancelRead?.().catch(() => {});
373
+ }
374
+ }
375
+
376
+ async close(): Promise<void> {
377
+ if (this.closing) return;
378
+ this.closing = true;
379
+ this.initialReady.reject(new Error("Gateway closed before initial head readiness"));
380
+ this.client?.events?.destroy();
381
+ this.client = undefined;
382
+ for (const peer of this.peers) peer.destroy();
383
+ const closed = Promise.withResolvers<void>();
384
+ this.server.close(() => closed.resolve());
385
+ await closed.promise;
386
+ await Promise.allSettled(this.effects);
387
+ try {
388
+ const stat = await lstat(this.options.socketPath);
389
+ if (stat.dev === this.socketIdentity?.dev && stat.ino === this.socketIdentity.ino) await unlink(this.options.socketPath);
390
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
391
+ }
392
+ }