omp-superagent 0.0.0-stage → 0.1.2
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/DESIGN.md +1502 -0
- package/LICENSE +21 -0
- package/README.ko.md +198 -0
- package/README.md +224 -2
- package/THIRD_PARTY_NOTICES.md +388 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1178 -0
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +65 -4
- package/scripts/ci.ts +33 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +58 -0
- package/scripts/setup.sh +25 -0
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +100 -0
- package/skills/head/references/model-selection.md +83 -0
- package/skills/head/references/routing.md +181 -0
- package/skills/head/references/supervision.md +122 -0
- package/skills/lane/SKILL.md +66 -0
- package/skills/lane/references/workflow.md +95 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +253 -0
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +266 -0
- package/src/contracts.ts +381 -0
- package/src/credentials.ts +172 -0
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +17 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +1012 -0
- package/src/extension.ts +446 -0
- package/src/gateway-client.ts +229 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +440 -0
- package/src/gateway-store.ts +251 -0
- package/src/gateway.ts +654 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +561 -0
- package/src/host-owner.ts +366 -0
- package/src/host-protocol.ts +144 -0
- package/src/host-services.ts +54 -0
- package/src/host.ts +415 -0
- package/src/installed-omp.ts +71 -0
- package/src/lane-extension.ts +184 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/lane-rows.ts +12 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +143 -0
- package/src/native-presets.ts +370 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +131 -0
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +4229 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +779 -0
- package/src/store.ts +862 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +677 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
|
@@ -0,0 +1,440 @@
|
|
|
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, ThreadUpdate } from "./contracts";
|
|
6
|
+
import { DeliveryError } from "./delivery";
|
|
7
|
+
import { discordPurposeRequest } from "./discord-context";
|
|
8
|
+
import { MAX_GATEWAY_ATTACHMENT, readGatewayJson, type GatewayResult } from "./gateway-protocol";
|
|
9
|
+
import { GatewayStore } from "./gateway-store";
|
|
10
|
+
import type { ManagedUlwStatus } from "./managed-ulw";
|
|
11
|
+
|
|
12
|
+
export interface HeadInitialization {
|
|
13
|
+
sessionId: string;
|
|
14
|
+
state: "checking" | "running" | "complete" | "blocked" | "failed" | "uncertain";
|
|
15
|
+
requestId?: string;
|
|
16
|
+
/** Durable fence survives a crash during a later startup's checking phase. */
|
|
17
|
+
replayBlocked?: boolean;
|
|
18
|
+
detail: string;
|
|
19
|
+
}
|
|
20
|
+
export interface GatewayStatus {
|
|
21
|
+
gateway: { pid: number; ready: boolean; admissionReady: boolean; pendingEvents: number; unresolvedEvents?: number; stopping: boolean };
|
|
22
|
+
head: { pid: number | null; ready: boolean; connected: boolean; socketPath: string; error: string | null;
|
|
23
|
+
initialization?: HeadInitialization };
|
|
24
|
+
ulw?: ManagedUlwStatus;
|
|
25
|
+
restart?: Omit<GatewayRestartRecord, "sessionFile">;
|
|
26
|
+
}
|
|
27
|
+
interface HeadClient { id: string; pid: number; ready: boolean; resumed: boolean; reconciled: boolean; events?: ServerResponse; sequence?: number; reconciliation?: string }
|
|
28
|
+
interface ServerOptions {
|
|
29
|
+
socketPath: string;
|
|
30
|
+
store: GatewayStore;
|
|
31
|
+
messenger: Messenger;
|
|
32
|
+
authorizeHead(pid: number): Promise<void>;
|
|
33
|
+
status(): GatewayStatus;
|
|
34
|
+
stop(): Promise<void>;
|
|
35
|
+
restart?(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
|
|
36
|
+
runRestart?(requestId: string): void;
|
|
37
|
+
onError(error: unknown): void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function failure(error: unknown): GatewayResult {
|
|
41
|
+
return { ok: false, error: error instanceof DeliveryError ? error.message : "Gateway operation failed",
|
|
42
|
+
certainty: error instanceof DeliveryError ? error.certainty : "uncertain",
|
|
43
|
+
...(error instanceof DeliveryError && error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}) };
|
|
44
|
+
}
|
|
45
|
+
function json(response: ServerResponse, value: GatewayResult, status = 200): void {
|
|
46
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
47
|
+
response.end(JSON.stringify(value));
|
|
48
|
+
}
|
|
49
|
+
function record(value: unknown): Record<string, unknown> {
|
|
50
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new DeliveryError("Invalid Gateway request", "rejected");
|
|
51
|
+
return value as Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function threadTags(value: unknown): string[] {
|
|
55
|
+
if (!Array.isArray(value) || value.some(tag => typeof tag !== "string"))
|
|
56
|
+
throw new DeliveryError("Invalid thread tags", "rejected");
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function threadUpdate(value: unknown): ThreadUpdate {
|
|
61
|
+
const update = record(value);
|
|
62
|
+
if (!Object.keys(update).length || Object.keys(update).some(key => !["title", "appliedTags", "archived"].includes(key))
|
|
63
|
+
|| (Object.hasOwn(update, "title") && typeof update.title !== "string")
|
|
64
|
+
|| (Object.hasOwn(update, "archived") && typeof update.archived !== "boolean"))
|
|
65
|
+
throw new DeliveryError("Invalid thread update", "rejected");
|
|
66
|
+
return {
|
|
67
|
+
...(typeof update.title === "string" ? { title: update.title } : {}),
|
|
68
|
+
...(typeof update.archived === "boolean" ? { archived: update.archived } : {}),
|
|
69
|
+
...(Object.hasOwn(update, "appliedTags") ? { appliedTags: threadTags(update.appliedTags) } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Ordinary-code IPC: a fixed Messenger surface, never a native RPC relay. */
|
|
74
|
+
export class GatewayServer {
|
|
75
|
+
readonly initialReady = Promise.withResolvers<void>();
|
|
76
|
+
private readonly server = createServer((request, response) => {
|
|
77
|
+
void this.handle(request, response).catch(error => {
|
|
78
|
+
if (!response.headersSent) json(response, failure(error), 400);
|
|
79
|
+
else response.destroy();
|
|
80
|
+
this.options.onError(error);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
private readonly peers = new Set<Socket>();
|
|
84
|
+
private readonly effects = new Set<Promise<void>>();
|
|
85
|
+
private readonly restartRequests = new Map<string, { request: GatewayRestartRequest; result: Promise<GatewayRestartRecord> }>();
|
|
86
|
+
private readonly restartRuns = new Set<string>();
|
|
87
|
+
private client?: HeadClient;
|
|
88
|
+
private admissionReady = false;
|
|
89
|
+
private socketIdentity?: { dev: number; ino: number };
|
|
90
|
+
private closing = false;
|
|
91
|
+
|
|
92
|
+
constructor(private readonly options: ServerOptions) {
|
|
93
|
+
void this.initialReady.promise.catch(() => {});
|
|
94
|
+
this.server.on("connection", socket => {
|
|
95
|
+
this.peers.add(socket);
|
|
96
|
+
socket.on("error", () => {});
|
|
97
|
+
socket.on("close", () => this.peers.delete(socket));
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
get connected(): boolean { return !!this.client?.events && !this.client.events.destroyed; }
|
|
101
|
+
get headReady(): boolean { return this.connected && !!this.client?.ready && !this.client.reconciliation && this.options.store.unresolved() === 0; }
|
|
102
|
+
get ready(): boolean { return this.admissionReady; }
|
|
103
|
+
|
|
104
|
+
admitMessage(input: Inbound): void {
|
|
105
|
+
const fresh = this.options.store.admit({ kind: "message", input });
|
|
106
|
+
if (fresh && input.messageId !== null && this.options.messenger.setActivity) {
|
|
107
|
+
const message = { route: input.route, messageId: input.messageId };
|
|
108
|
+
const operation = Promise.resolve().then(() => this.options.messenger.setActivity?.(message, "received"));
|
|
109
|
+
this.effects.add(operation);
|
|
110
|
+
void operation.catch(() => this.options.onError(new Error("Message receipt reaction failed")))
|
|
111
|
+
.finally(() => this.effects.delete(operation));
|
|
112
|
+
}
|
|
113
|
+
this.deliver();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private openAdmission(): void {
|
|
117
|
+
if (this.admissionReady) return;
|
|
118
|
+
this.admissionReady = true;
|
|
119
|
+
this.initialReady.resolve();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async listen(): Promise<void> {
|
|
123
|
+
const opened = Promise.withResolvers<void>();
|
|
124
|
+
this.server.once("error", opened.reject);
|
|
125
|
+
this.server.listen(this.options.socketPath, () => opened.resolve());
|
|
126
|
+
await opened.promise;
|
|
127
|
+
this.server.off("error", opened.reject);
|
|
128
|
+
this.server.on("error", this.options.onError);
|
|
129
|
+
await chmod(this.options.socketPath, 0o600);
|
|
130
|
+
const stat = await lstat(this.options.socketPath);
|
|
131
|
+
this.socketIdentity = { dev: stat.dev, ino: stat.ino };
|
|
132
|
+
this.options.store.setMeta("gateway:socket", JSON.stringify({ pid: process.pid, ...this.socketIdentity }));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private authenticated(request: IncomingMessage): string {
|
|
136
|
+
if (request.headers.authorization !== `Bearer ${this.options.store.token()}`)
|
|
137
|
+
throw new DeliveryError("Gateway head authorization required", "rejected");
|
|
138
|
+
const id = request.headers["x-gateway-client"];
|
|
139
|
+
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id)) throw new DeliveryError("Invalid Gateway client", "rejected");
|
|
140
|
+
return id;
|
|
141
|
+
}
|
|
142
|
+
private head(request: IncomingMessage): HeadClient {
|
|
143
|
+
const id = this.authenticated(request);
|
|
144
|
+
if (!this.client || this.client.id !== id) throw new DeliveryError("Gateway client is detached", "rejected");
|
|
145
|
+
return this.client;
|
|
146
|
+
}
|
|
147
|
+
private async handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
148
|
+
const endpoint = request.url;
|
|
149
|
+
if (endpoint === "/status" && request.method === "GET") {
|
|
150
|
+
const status = this.options.status();
|
|
151
|
+
const latest = this.options.store.getRestart();
|
|
152
|
+
const { sessionFile: _, ...restart } = latest ?? {};
|
|
153
|
+
json(response, { ok: true, value: { ...status, ...(latest ? { restart } : {}), gateway: { ...status.gateway, unresolvedEvents: this.options.store.unresolved() } } });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (endpoint === "/stop" && request.method === "POST") {
|
|
157
|
+
await readGatewayJson(request);
|
|
158
|
+
await this.options.stop();
|
|
159
|
+
json(response, { ok: true });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (this.closing) throw new DeliveryError("Gateway is stopping", "rejected");
|
|
163
|
+
if (endpoint === "/attach" && request.method === "POST") {
|
|
164
|
+
const id = this.authenticated(request);
|
|
165
|
+
const data = record(await readGatewayJson(request));
|
|
166
|
+
if (!Number.isSafeInteger(data.pid) || Number(data.pid) < 1) throw new DeliveryError("Invalid head PID", "rejected");
|
|
167
|
+
await this.options.authorizeHead(Number(data.pid));
|
|
168
|
+
if (this.client && this.client.id !== id && this.connected) throw new DeliveryError("A head client is already attached", "rejected");
|
|
169
|
+
if (this.client?.id === id) this.client.events?.destroy();
|
|
170
|
+
const reconciled = this.client?.id === id && this.client.pid === data.pid && this.client.reconciled;
|
|
171
|
+
this.client = { id, pid: Number(data.pid), ready: false, resumed: data.resumed === true, reconciled };
|
|
172
|
+
json(response, { ok: true });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const client = this.head(request);
|
|
176
|
+
if (endpoint === "/events" && request.method === "GET") {
|
|
177
|
+
if (client.events && !client.events.destroyed) throw new DeliveryError("Head event stream already open", "rejected");
|
|
178
|
+
response.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
|
|
179
|
+
response.flushHeaders();
|
|
180
|
+
client.events = response;
|
|
181
|
+
response.on("close", () => {
|
|
182
|
+
if (client.events !== response) return;
|
|
183
|
+
client.events = undefined;
|
|
184
|
+
client.ready = false;
|
|
185
|
+
client.sequence = undefined;
|
|
186
|
+
});
|
|
187
|
+
this.deliver();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (request.method !== "POST") throw new DeliveryError("Unknown Gateway operation", "rejected");
|
|
191
|
+
if (endpoint === "/restart") {
|
|
192
|
+
// Recheck supervised process authority before reading any caller body.
|
|
193
|
+
try { await this.options.authorizeHead(client.pid); }
|
|
194
|
+
catch { throw new DeliveryError("Gateway head authorization rejected", "rejected"); }
|
|
195
|
+
// Native approval reconciliation belongs to this authenticated controller,
|
|
196
|
+
// not to one SSE connection. Quarantine may close that stream after
|
|
197
|
+
// receive durably admits a priority restart but before its async handoff.
|
|
198
|
+
if (!this.admissionReady || !client.reconciled || client.reconciliation)
|
|
199
|
+
throw new DeliveryError("Gateway head is not ready for restart", "rejected");
|
|
200
|
+
await this.restart(record(await readGatewayJson(request)), response);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const data = record(await readGatewayJson(request));
|
|
204
|
+
if (endpoint === "/ready") {
|
|
205
|
+
const wasReady = client.ready;
|
|
206
|
+
client.ready = true;
|
|
207
|
+
if (!wasReady && client.resumed) {
|
|
208
|
+
// A resumed controller's own startup gate is already resolved, but a
|
|
209
|
+
// freshly authenticated adapter has no restored approval card cache.
|
|
210
|
+
// Its initial admission barrier must wait for head reconciliation ACK.
|
|
211
|
+
if (!this.admissionReady) client.reconciliation = crypto.randomUUID();
|
|
212
|
+
this.options.store.admit({ kind: "reconnect", ...(client.reconciliation ? { barrier: client.reconciliation } : {}) });
|
|
213
|
+
} else if (!client.resumed) {
|
|
214
|
+
// A new controller reconciled native approvals before calling /ready.
|
|
215
|
+
this.openAdmission();
|
|
216
|
+
}
|
|
217
|
+
if (!client.reconciliation) client.reconciled = true;
|
|
218
|
+
json(response, { ok: true });
|
|
219
|
+
this.deliver();
|
|
220
|
+
} else if (endpoint === "/receipt") {
|
|
221
|
+
if (!Number.isSafeInteger(data.sequence) || data.sequence !== client.sequence)
|
|
222
|
+
throw new DeliveryError("Gateway receipt is not the outstanding event", "rejected");
|
|
223
|
+
const outstanding = this.options.store.next(client.sequence)?.event;
|
|
224
|
+
const barrier = outstanding?.kind === "reconnect" ? outstanding.barrier : undefined;
|
|
225
|
+
if (data.outcome !== "accepted" && data.outcome !== "rejected" && data.outcome !== "unresolved")
|
|
226
|
+
throw new DeliveryError("Invalid Gateway admission receipt", "rejected");
|
|
227
|
+
const outcome = data.outcome;
|
|
228
|
+
if (barrier && !this.admissionReady && outcome !== "accepted") {
|
|
229
|
+
// Keep the durable reconciliation event pending. Never ACK fresh
|
|
230
|
+
// platform approval replies against an unregistered/empty card cache.
|
|
231
|
+
this.options.store.receipt(Number(data.sequence), "unresolved");
|
|
232
|
+
json(response, { ok: true });
|
|
233
|
+
client.events?.destroy();
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
this.options.store.receipt(Number(data.sequence), outcome);
|
|
237
|
+
client.sequence = undefined;
|
|
238
|
+
if (barrier && barrier === client.reconciliation && outcome === "accepted") {
|
|
239
|
+
client.reconciliation = undefined;
|
|
240
|
+
client.reconciled = true;
|
|
241
|
+
this.openAdmission();
|
|
242
|
+
}
|
|
243
|
+
json(response, { ok: true });
|
|
244
|
+
if (outcome === "unresolved") client.events?.destroy();
|
|
245
|
+
else this.deliver();
|
|
246
|
+
} else if (endpoint === "/detach") {
|
|
247
|
+
client.events?.destroy();
|
|
248
|
+
this.client = undefined;
|
|
249
|
+
json(response, { ok: true });
|
|
250
|
+
} else if (endpoint === "/effect") {
|
|
251
|
+
const task = this.effect(data, response);
|
|
252
|
+
this.effects.add(task);
|
|
253
|
+
try { await task; } finally { this.effects.delete(task); }
|
|
254
|
+
} else if (endpoint === "/attachment") {
|
|
255
|
+
await this.attachment(data, response);
|
|
256
|
+
} else throw new DeliveryError("Unknown Gateway operation", "rejected");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private async restart(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
|
|
260
|
+
const { requestId, inputId, ackOutputId } = data;
|
|
261
|
+
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)
|
|
262
|
+
|| typeof inputId !== "string" || !inputId.trim() || inputId.length > 1024
|
|
263
|
+
|| typeof ackOutputId !== "string" || !ackOutputId.trim() || ackOutputId.length > 1024)
|
|
264
|
+
throw new DeliveryError("Invalid Gateway restart request", "rejected");
|
|
265
|
+
if (!this.options.restart || !this.options.runRestart) throw new DeliveryError("Gateway restart is unavailable", "rejected");
|
|
266
|
+
const request = { requestId, inputId, ackOutputId };
|
|
267
|
+
const prior = this.options.store.getRestart(requestId);
|
|
268
|
+
const pending = this.restartRequests.get(requestId);
|
|
269
|
+
const identity = prior ?? pending?.request;
|
|
270
|
+
const source = this.options.store.getMeta(`gateway:restart-source:${inputId}`);
|
|
271
|
+
if (identity && (identity.inputId !== inputId || identity.ackOutputId !== ackOutputId) || source !== null && source !== requestId)
|
|
272
|
+
throw new DeliveryError("Gateway restart identity conflict", "rejected");
|
|
273
|
+
for (const entry of this.restartRequests.values()) {
|
|
274
|
+
if (entry.request.inputId === inputId && entry.request.requestId !== requestId)
|
|
275
|
+
throw new DeliveryError("Gateway restart identity conflict", "rejected");
|
|
276
|
+
}
|
|
277
|
+
let result: GatewayRestartRecord;
|
|
278
|
+
try {
|
|
279
|
+
if (prior) result = prior;
|
|
280
|
+
else {
|
|
281
|
+
if (!pending) {
|
|
282
|
+
this.options.store.validateRestart(request);
|
|
283
|
+
const operation = Promise.resolve().then(() => this.options.restart!(request));
|
|
284
|
+
this.restartRequests.set(requestId, { request, result: operation });
|
|
285
|
+
}
|
|
286
|
+
try { result = await this.restartRequests.get(requestId)!.result; }
|
|
287
|
+
finally { this.restartRequests.delete(requestId); }
|
|
288
|
+
}
|
|
289
|
+
} catch (error) {
|
|
290
|
+
throw new DeliveryError("Gateway restart request failed", error instanceof DeliveryError ? error.certainty : "uncertain");
|
|
291
|
+
}
|
|
292
|
+
const persisted = this.options.store.getRestart(requestId);
|
|
293
|
+
if (result.requestId !== requestId || result.inputId !== inputId || result.ackOutputId !== ackOutputId
|
|
294
|
+
|| !persisted || persisted.inputId !== inputId || persisted.ackOutputId !== ackOutputId)
|
|
295
|
+
throw new DeliveryError("Gateway restart acceptance was not persisted", "uncertain");
|
|
296
|
+
result = persisted;
|
|
297
|
+
if (response.destroyed) return;
|
|
298
|
+
if (result.state === "accepted") response.once("finish", () => {
|
|
299
|
+
if (this.restartRuns.has(requestId) || this.options.store.getRestart(requestId)?.state !== "accepted") return;
|
|
300
|
+
this.restartRuns.add(requestId);
|
|
301
|
+
try { this.options.runRestart!(requestId); }
|
|
302
|
+
catch { this.options.onError(new Error("Gateway restart execution failed")); }
|
|
303
|
+
});
|
|
304
|
+
json(response, { ok: true, value: result });
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
deliver(): void {
|
|
308
|
+
const client = this.client;
|
|
309
|
+
if (!client?.ready || !client.events || client.events.destroyed || client.sequence !== undefined) return;
|
|
310
|
+
const event = this.options.store.next();
|
|
311
|
+
if (!event) return;
|
|
312
|
+
// A lost callback receipt is ambiguous even if the head disconnects before
|
|
313
|
+
// processing the frame. Reconcile the original native request on redelivery.
|
|
314
|
+
if (event.event.kind === "answer") this.options.store.attempt(event.sequence);
|
|
315
|
+
client.sequence = event.sequence;
|
|
316
|
+
client.events.write(`${JSON.stringify(event)}\n`);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private async effect(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
|
|
320
|
+
const { id, operation, args } = data;
|
|
321
|
+
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || typeof operation !== "string" || !Array.isArray(args))
|
|
322
|
+
throw new DeliveryError("Invalid Gateway effect", "rejected");
|
|
323
|
+
const operations: Record<string, number[]> = { send: [1], setActivity: [2], showApproval: [1], dismissApproval: [1],
|
|
324
|
+
canCreateThread: [1, 2], createThread: [2, 3, 4], inspectThread: [1], updateThread: [2],
|
|
325
|
+
inspectDiscordContext: [1], discordPurpose: [1], fetchAfter: [2] };
|
|
326
|
+
if (!Object.hasOwn(operations, operation) || !operations[operation]!.includes(args.length))
|
|
327
|
+
throw new DeliveryError("Unknown Gateway effect", "rejected");
|
|
328
|
+
const previous = this.options.store.beginEffect(id, operation, args);
|
|
329
|
+
if (!previous.fresh) { json(response, previous.result as GatewayResult); return; }
|
|
330
|
+
let result: GatewayResult;
|
|
331
|
+
try {
|
|
332
|
+
const messenger = this.options.messenger;
|
|
333
|
+
if (operation === "send") {
|
|
334
|
+
const output = record(args[0]);
|
|
335
|
+
if (output.replyTo !== undefined) {
|
|
336
|
+
const reply = record(output.replyTo);
|
|
337
|
+
const source = record(reply.route);
|
|
338
|
+
const destination = record(output.route);
|
|
339
|
+
if (destination.platform !== "discord" || typeof reply.messageId !== "string" || !/^[0-9]{1,20}$/.test(reply.messageId)
|
|
340
|
+
|| ["platform", "accountId", "authorityId", "guildId", "channelId", "threadId"].some(key => source[key] !== destination[key])) {
|
|
341
|
+
throw new DeliveryError("Discord reply requires a real message in the exact destination conversation", "rejected");
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (operation === "setActivity" && args[1] !== "received" && args[1] !== "thinking" && args[1] !== "idle")
|
|
346
|
+
throw new DeliveryError("Invalid message activity", "rejected");
|
|
347
|
+
if (operation === "setActivity" && (typeof record(args[0]).messageId !== "string" || !record(args[0]).messageId))
|
|
348
|
+
throw new DeliveryError("Message activity requires a real message ID", "rejected");
|
|
349
|
+
if (operation === "inspectThread" && !messenger.inspectThread || operation === "updateThread" && !messenger.updateThread)
|
|
350
|
+
throw new DeliveryError("Thread management is unsupported on this transport", "rejected");
|
|
351
|
+
const purpose = operation === "discordPurpose" ? discordPurposeRequest(args[0]) : undefined;
|
|
352
|
+
if (purpose) {
|
|
353
|
+
this.options.store.validateDiscordPurpose(purpose);
|
|
354
|
+
if (!messenger.discordPurpose) throw new DeliveryError("Discord purpose notes are unsupported", "rejected");
|
|
355
|
+
}
|
|
356
|
+
if (operation === "inspectDiscordContext" && !messenger.inspectDiscordContext)
|
|
357
|
+
throw new DeliveryError("Discord context inspection is unsupported", "rejected");
|
|
358
|
+
const value = operation === "send" ? await messenger.send(args[0] as OutputRecord)
|
|
359
|
+
: operation === "setActivity" ? await messenger.setActivity?.(args[0] as MessageReference, args[1] as "received" | "thinking" | "idle")
|
|
360
|
+
: operation === "showApproval" ? await messenger.showApproval(args[0] as Approval)
|
|
361
|
+
: operation === "dismissApproval" ? await messenger.dismissApproval(args[0] as Approval)
|
|
362
|
+
: operation === "canCreateThread" ? await messenger.canCreateThread?.(args[0] as Route, args.length === 2 ? threadTags(args[1]) : undefined) ?? false
|
|
363
|
+
: operation === "createThread" ? await messenger.createThread(args[0] as Route, args[1] as string,
|
|
364
|
+
args[2] == null ? undefined : args[2] as string, args.length === 4 ? threadTags(args[3]) : undefined)
|
|
365
|
+
: operation === "inspectThread" ? await messenger.inspectThread?.(args[0] as Route)
|
|
366
|
+
: operation === "updateThread" ? await messenger.updateThread?.(args[0] as Route, threadUpdate(args[1]))
|
|
367
|
+
: operation === "inspectDiscordContext" ? await messenger.inspectDiscordContext?.(args[0] as Route)
|
|
368
|
+
: purpose ? await messenger.discordPurpose?.(purpose)
|
|
369
|
+
: await messenger.fetchAfter(args[0] as Route, args[1] as string);
|
|
370
|
+
result = { ok: true, value };
|
|
371
|
+
} catch (error) { result = failure(error); }
|
|
372
|
+
// Persistence precedes the receipt; disconnection never cancels or repeats
|
|
373
|
+
// a remote mutation whose outcome may already exist.
|
|
374
|
+
this.options.store.finishEffect(id, result);
|
|
375
|
+
if (!response.destroyed) json(response, result);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private async attachment(data: Record<string, unknown>, response: ServerResponse): Promise<void> {
|
|
379
|
+
const attachment = record(data.attachment) as unknown as Attachment;
|
|
380
|
+
if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
|
|
381
|
+
throw new DeliveryError("Invalid attachment size", "rejected");
|
|
382
|
+
const controller = new AbortController();
|
|
383
|
+
let cancelRead: (() => Promise<void>) | undefined;
|
|
384
|
+
const abort = () => { controller.abort(); void cancelRead?.().catch(() => {}); };
|
|
385
|
+
response.on("close", abort);
|
|
386
|
+
try {
|
|
387
|
+
const upstream = await this.options.messenger.openAttachment(data.route as Route, attachment, controller.signal);
|
|
388
|
+
if (!upstream.body) throw new DeliveryError("Attachment response has no body", "rejected");
|
|
389
|
+
const length = upstream.headers.get("content-length");
|
|
390
|
+
if (length !== null && (!/^\d+$/.test(length) || Number(length) > (attachment.size ?? MAX_GATEWAY_ATTACHMENT)))
|
|
391
|
+
throw new DeliveryError("Attachment response exceeds declared size", "rejected");
|
|
392
|
+
const expectedSize = attachment.size ?? (length === null ? null : Number(length));
|
|
393
|
+
response.writeHead(upstream.status, {
|
|
394
|
+
"content-type": upstream.headers.get("content-type") ?? "application/octet-stream",
|
|
395
|
+
"x-gateway-attachment-protocol": "1",
|
|
396
|
+
...(length === null ? {} : { "x-gateway-attachment-length": length }),
|
|
397
|
+
});
|
|
398
|
+
response.flushHeaders();
|
|
399
|
+
const reader = upstream.body.getReader();
|
|
400
|
+
cancelRead = () => reader.cancel();
|
|
401
|
+
let bytes = 0;
|
|
402
|
+
while (true) {
|
|
403
|
+
const chunk = await reader.read();
|
|
404
|
+
if (chunk.done) break;
|
|
405
|
+
bytes += chunk.value.byteLength;
|
|
406
|
+
if (bytes > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes > MAX_GATEWAY_ATTACHMENT) throw new Error("Attachment stream exceeds declared size");
|
|
407
|
+
if (!chunk.value.byteLength) continue;
|
|
408
|
+
// Socket closure alone is not a completion receipt: some HTTP stacks
|
|
409
|
+
// expose a destroyed response as an empty/truncated successful body.
|
|
410
|
+
const frame = Buffer.allocUnsafe(4);
|
|
411
|
+
frame.writeUInt32BE(chunk.value.byteLength);
|
|
412
|
+
if (!response.write(frame)) await once(response, "drain", { signal: controller.signal });
|
|
413
|
+
if (!response.write(chunk.value)) await once(response, "drain", { signal: controller.signal });
|
|
414
|
+
}
|
|
415
|
+
if (expectedSize !== null && bytes !== expectedSize) throw new Error("Attachment stream was truncated");
|
|
416
|
+
response.end(Buffer.alloc(4));
|
|
417
|
+
} finally {
|
|
418
|
+
response.off("close", abort);
|
|
419
|
+
controller.abort();
|
|
420
|
+
await cancelRead?.().catch(() => {});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async close(): Promise<void> {
|
|
425
|
+
if (this.closing) return;
|
|
426
|
+
this.closing = true;
|
|
427
|
+
this.initialReady.reject(new Error("Gateway closed before initial head readiness"));
|
|
428
|
+
this.client?.events?.destroy();
|
|
429
|
+
this.client = undefined;
|
|
430
|
+
for (const peer of this.peers) peer.destroy();
|
|
431
|
+
const closed = Promise.withResolvers<void>();
|
|
432
|
+
this.server.close(() => closed.resolve());
|
|
433
|
+
await closed.promise;
|
|
434
|
+
await Promise.allSettled(this.effects);
|
|
435
|
+
try {
|
|
436
|
+
const stat = await lstat(this.options.socketPath);
|
|
437
|
+
if (stat.dev === this.socketIdentity?.dev && stat.ino === this.socketIdentity.ino) await unlink(this.options.socketPath);
|
|
438
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
439
|
+
}
|
|
440
|
+
}
|