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,229 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import { Readable, Transform } from "node:stream";
|
|
3
|
+
import type { Config } from "./config";
|
|
4
|
+
import type { Approval, Attachment, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
|
|
5
|
+
import { DeliveryError } from "./delivery";
|
|
6
|
+
import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_ATTACHMENT, MAX_GATEWAY_FRAME, readGatewayJson, type GatewayResult } from "./gateway-protocol";
|
|
7
|
+
import type { GatewayReceipt, QueuedEvent } from "./gateway-store";
|
|
8
|
+
|
|
9
|
+
export interface GatewayHeadMessenger extends Messenger {
|
|
10
|
+
requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Transport-only head adapter. Detaching never logs out the actual accounts. */
|
|
14
|
+
class GatewayMessenger implements GatewayHeadMessenger {
|
|
15
|
+
private readonly clientId = crypto.randomUUID();
|
|
16
|
+
private readonly socketPath: string;
|
|
17
|
+
private readonly token: string;
|
|
18
|
+
private handlers?: Parameters<Messenger["start"]>[0];
|
|
19
|
+
private events?: IncomingMessage;
|
|
20
|
+
private stopped = false;
|
|
21
|
+
private reconnectTimer?: ReturnType<typeof setTimeout>;
|
|
22
|
+
private delivery: Promise<void> = Promise.resolve();
|
|
23
|
+
private intakeReady = false;
|
|
24
|
+
private connecting?: Promise<void>;
|
|
25
|
+
private reconnectDelay = 250;
|
|
26
|
+
|
|
27
|
+
constructor(config: Config) {
|
|
28
|
+
this.socketPath = gatewayPaths(config).socketPath;
|
|
29
|
+
this.token = process.env.OMP_SUPERAGENT_GATEWAY_TOKEN ?? "";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
private options() { return { token: this.token, clientId: this.clientId }; }
|
|
33
|
+
private call<T>(endpoint: string, body: unknown, signal?: AbortSignal): Promise<T> {
|
|
34
|
+
if (this.stopped) return Promise.reject(new DeliveryError("Gateway client is stopped", "rejected"));
|
|
35
|
+
return gatewayCall<T>(this.socketPath, endpoint, body, { ...this.options(), signal });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async start(handlers: Parameters<Messenger["start"]>[0]): Promise<void> {
|
|
39
|
+
if (this.handlers || this.stopped) throw new Error("Gateway messenger cannot be started twice");
|
|
40
|
+
if (!this.token) throw new DeliveryError("Head was not launched by its Gateway", "rejected");
|
|
41
|
+
this.handlers = handlers;
|
|
42
|
+
try {
|
|
43
|
+
await this.connect();
|
|
44
|
+
// Return before the native-approval gate, like the actual adapters. The
|
|
45
|
+
// head must attach/reconcile native UI before enabling any admission.
|
|
46
|
+
void (handlers.ready ?? Promise.resolve()).then(async () => {
|
|
47
|
+
if (this.stopped) return;
|
|
48
|
+
this.intakeReady = true;
|
|
49
|
+
await this.call("/ready", {});
|
|
50
|
+
}).catch(() => { this.events?.destroy(); });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
await this.stop();
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private connect(): Promise<void> {
|
|
58
|
+
if (this.connecting) return this.connecting;
|
|
59
|
+
this.connecting = this.openEvents().finally(() => { this.connecting = undefined; });
|
|
60
|
+
return this.connecting;
|
|
61
|
+
}
|
|
62
|
+
private async openEvents(): Promise<void> {
|
|
63
|
+
await this.call("/attach", { pid: process.pid, resumed: this.intakeReady });
|
|
64
|
+
const events = await gatewayRequest(this.socketPath, "/events", undefined, this.options());
|
|
65
|
+
if (events.statusCode !== 200) {
|
|
66
|
+
const result = await readGatewayJson(events) as GatewayResult;
|
|
67
|
+
throw new DeliveryError(result.error ?? "Gateway event stream rejected", result.certainty ?? "rejected");
|
|
68
|
+
}
|
|
69
|
+
if (this.stopped) { events.destroy(); return; }
|
|
70
|
+
this.events = events;
|
|
71
|
+
void this.consume(events).catch(() => { events.destroy(); }).finally(() => {
|
|
72
|
+
if (this.events !== events) return;
|
|
73
|
+
this.events = undefined;
|
|
74
|
+
this.scheduleReconnect();
|
|
75
|
+
});
|
|
76
|
+
if (this.intakeReady) await this.call("/ready", {});
|
|
77
|
+
}
|
|
78
|
+
private scheduleReconnect(): void {
|
|
79
|
+
if (this.stopped || this.reconnectTimer) return;
|
|
80
|
+
this.reconnectTimer = setTimeout(() => {
|
|
81
|
+
this.reconnectTimer = undefined;
|
|
82
|
+
void this.connect().catch(() => { this.scheduleReconnect(); });
|
|
83
|
+
}, this.reconnectDelay);
|
|
84
|
+
this.reconnectTimer.unref();
|
|
85
|
+
}
|
|
86
|
+
private async consume(stream: IncomingMessage): Promise<void> {
|
|
87
|
+
const disconnected = new AbortController();
|
|
88
|
+
stream.once("close", () => disconnected.abort());
|
|
89
|
+
if (stream.destroyed) disconnected.abort();
|
|
90
|
+
let pending = Buffer.alloc(0);
|
|
91
|
+
for await (const chunk of stream) {
|
|
92
|
+
pending = Buffer.concat([pending, Buffer.from(chunk)]);
|
|
93
|
+
let newline: number;
|
|
94
|
+
while ((newline = pending.indexOf(10)) >= 0) {
|
|
95
|
+
if (newline > MAX_GATEWAY_FRAME) throw new Error("Gateway event frame exceeds size limit");
|
|
96
|
+
const frame = JSON.parse(pending.subarray(0, newline).toString("utf8")) as QueuedEvent;
|
|
97
|
+
pending = pending.subarray(newline + 1);
|
|
98
|
+
// Inbox IDs are deduplicated by the head. Previously attempted native
|
|
99
|
+
// answers instead require exact original-state reconciliation.
|
|
100
|
+
this.delivery = this.delivery.catch(() => {}).then(async () => {
|
|
101
|
+
if (this.stopped || !this.handlers) return;
|
|
102
|
+
disconnected.signal.throwIfAborted();
|
|
103
|
+
let outcome: GatewayReceipt = "accepted";
|
|
104
|
+
try {
|
|
105
|
+
const event = frame.event;
|
|
106
|
+
if (event.kind === "message") await this.handlers.message(event.input);
|
|
107
|
+
else if (event.kind === "answer") {
|
|
108
|
+
const reconciled = frame.reconciliation
|
|
109
|
+
? await this.handlers.reconcileAnswer?.(event.approvalId, event.route) ?? "unresolved" : "retry";
|
|
110
|
+
if (reconciled === "retry") await this.handlers.answer(event.approvalId, event.response, event.route);
|
|
111
|
+
else outcome = reconciled;
|
|
112
|
+
}
|
|
113
|
+
else if (event.kind === "restart") {
|
|
114
|
+
if (!this.handlers.restart) throw new Error("Gateway restart outcome handler is unavailable");
|
|
115
|
+
const { kind: _, ...notice } = event;
|
|
116
|
+
await this.handlers.restart(notice);
|
|
117
|
+
}
|
|
118
|
+
else await this.handlers.reconnect?.();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
outcome = error instanceof DeliveryError && error.certainty === "rejected" ? "rejected" : "unresolved";
|
|
121
|
+
}
|
|
122
|
+
// A handler may finish after its Gateway has been replaced. Its
|
|
123
|
+
// receipt belongs only to this stream; redelivery reconciles the
|
|
124
|
+
// durable outcome after reattachment instead of ACKing a new server.
|
|
125
|
+
disconnected.signal.throwIfAborted();
|
|
126
|
+
// A poison input stays visible and ordered without a tight retry loop.
|
|
127
|
+
this.reconnectDelay = outcome === "unresolved" ? Math.min(this.reconnectDelay * 2, 30_000) : 250;
|
|
128
|
+
await this.call("/receipt", { sequence: frame.sequence, outcome }, disconnected.signal);
|
|
129
|
+
});
|
|
130
|
+
await this.delivery;
|
|
131
|
+
}
|
|
132
|
+
if (pending.length > MAX_GATEWAY_FRAME) throw new Error("Gateway event frame exceeds size limit");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private effect<T>(operation: string, args: unknown[]): Promise<T> {
|
|
137
|
+
return this.call<T>("/effect", { id: crypto.randomUUID(), operation, args });
|
|
138
|
+
}
|
|
139
|
+
requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord> { return this.call("/restart", request); }
|
|
140
|
+
send(output: OutputRecord): Promise<string> { return this.effect("send", [output]); }
|
|
141
|
+
setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
|
|
142
|
+
return this.effect("setActivity", [{ route: message.route, messageId: message.messageId }, activity]);
|
|
143
|
+
}
|
|
144
|
+
showApproval(approval: Approval): Promise<string> { return this.effect("showApproval", [approval]); }
|
|
145
|
+
dismissApproval(approval: Approval): Promise<void> { return this.effect("dismissApproval", [approval]); }
|
|
146
|
+
canCreateThread(route: Route, appliedTags?: readonly string[]): Promise<boolean> {
|
|
147
|
+
return this.effect("canCreateThread", appliedTags === undefined ? [route] : [route, appliedTags]);
|
|
148
|
+
}
|
|
149
|
+
createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route> {
|
|
150
|
+
return this.effect("createThread", appliedTags !== undefined ? [route, title, sourceMessageId ?? null, appliedTags]
|
|
151
|
+
: sourceMessageId !== undefined ? [route, title, sourceMessageId] : [route, title]);
|
|
152
|
+
}
|
|
153
|
+
inspectThread(route: Route): Promise<ThreadInfo> { return this.effect("inspectThread", [route]); }
|
|
154
|
+
updateThread(route: Route, update: ThreadUpdate): Promise<ThreadInfo> { return this.effect("updateThread", [route, update]); }
|
|
155
|
+
inspectDiscordContext(route: Route): Promise<DiscordContext> { return this.effect("inspectDiscordContext", [route]); }
|
|
156
|
+
discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
|
|
157
|
+
fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> { return this.effect("fetchAfter", [route, messageId]); }
|
|
158
|
+
|
|
159
|
+
async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
|
|
160
|
+
if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
|
|
161
|
+
if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
|
|
162
|
+
throw new DeliveryError("Invalid attachment size", "rejected");
|
|
163
|
+
const incoming = await gatewayRequest(this.socketPath, "/attachment", { route, attachment }, { ...this.options(), signal });
|
|
164
|
+
if (incoming.headers["x-gateway-attachment-protocol"] !== "1") {
|
|
165
|
+
const result = await readGatewayJson(incoming) as GatewayResult;
|
|
166
|
+
throw new DeliveryError(result.error ?? "Attachment rejected", result.certainty ?? "uncertain");
|
|
167
|
+
}
|
|
168
|
+
let bytes = 0;
|
|
169
|
+
const header = Buffer.allocUnsafe(4);
|
|
170
|
+
let headerBytes = 0;
|
|
171
|
+
let remaining = 0;
|
|
172
|
+
let complete = false;
|
|
173
|
+
const bounded = new Transform({
|
|
174
|
+
transform(chunk: Buffer, _encoding, callback) {
|
|
175
|
+
let offset = 0;
|
|
176
|
+
while (offset < chunk.length) {
|
|
177
|
+
if (complete) { callback(new Error("Attachment data followed its completion frame")); return; }
|
|
178
|
+
if (!remaining) {
|
|
179
|
+
const count = Math.min(4 - headerBytes, chunk.length - offset);
|
|
180
|
+
chunk.copy(header, headerBytes, offset, offset + count);
|
|
181
|
+
headerBytes += count;
|
|
182
|
+
offset += count;
|
|
183
|
+
if (headerBytes < 4) continue;
|
|
184
|
+
remaining = header.readUInt32BE();
|
|
185
|
+
headerBytes = 0;
|
|
186
|
+
if (!remaining) { complete = true; continue; }
|
|
187
|
+
if (bytes + remaining > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes + remaining > MAX_GATEWAY_ATTACHMENT) {
|
|
188
|
+
callback(new Error("Attachment stream exceeds declared size"));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const count = Math.min(remaining, chunk.length - offset);
|
|
193
|
+
if (count) this.push(chunk.subarray(offset, offset + count));
|
|
194
|
+
offset += count;
|
|
195
|
+
remaining -= count;
|
|
196
|
+
bytes += count;
|
|
197
|
+
}
|
|
198
|
+
callback();
|
|
199
|
+
},
|
|
200
|
+
flush(callback) {
|
|
201
|
+
callback(!complete || remaining || headerBytes || attachment.size !== null && bytes !== attachment.size
|
|
202
|
+
? new Error("Attachment stream ended without a complete delivery receipt") : undefined);
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
incoming.on("error", error => bounded.destroy(error));
|
|
206
|
+
incoming.on("aborted", () => bounded.destroy(new Error("Attachment stream was interrupted")));
|
|
207
|
+
bounded.on("close", () => incoming.destroy());
|
|
208
|
+
incoming.pipe(bounded);
|
|
209
|
+
const headers = new Headers();
|
|
210
|
+
const contentType = incoming.headers["content-type"];
|
|
211
|
+
const contentLength = incoming.headers["x-gateway-attachment-length"];
|
|
212
|
+
if (typeof contentType === "string") headers.set("content-type", contentType);
|
|
213
|
+
if (typeof contentLength === "string") headers.set("content-length", contentLength);
|
|
214
|
+
return new Response(Readable.toWeb(bounded) as ReadableStream<Uint8Array>, { status: incoming.statusCode ?? 502, headers });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async stop(): Promise<void> {
|
|
218
|
+
if (this.stopped) return;
|
|
219
|
+
// Detach is best effort, never a messenger/server shutdown request.
|
|
220
|
+
try { await this.call("/detach", {}); } catch { /* Gateway may be unavailable. */ }
|
|
221
|
+
this.stopped = true;
|
|
222
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
223
|
+
this.events?.destroy();
|
|
224
|
+
this.events = undefined;
|
|
225
|
+
this.handlers = undefined;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function createGatewayMessenger(config: Config): GatewayHeadMessenger { return new GatewayMessenger(config); }
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { request, type IncomingMessage } from "node:http";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { lstat } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import type { Config } from "./config";
|
|
6
|
+
import { DeliveryError } from "./delivery";
|
|
7
|
+
import type { GatewayStatus } from "./gateway-server";
|
|
8
|
+
|
|
9
|
+
export const MAX_GATEWAY_FRAME = 16 * 1024 * 1024;
|
|
10
|
+
export const MAX_GATEWAY_ATTACHMENT = 20 * 1024 * 1024;
|
|
11
|
+
export interface GatewayResult { ok: boolean; value?: unknown; error?: string; certainty?: "rejected" | "uncertain"; retryAfterMs?: number }
|
|
12
|
+
|
|
13
|
+
export function gatewayPaths(config: Pick<Config, "stateDir">) {
|
|
14
|
+
const socketPath = join(config.stateDir, "run", "gateway.sock");
|
|
15
|
+
if (Buffer.byteLength(socketPath) > 100) throw new Error("stateDir is too long for the Gateway socket");
|
|
16
|
+
return { socketPath, logPath: join(config.stateDir, "logs", "gateway.log") };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function gatewayStatus(config: Config): Promise<GatewayStatus | null> {
|
|
20
|
+
const path = gatewayPaths(config).socketPath;
|
|
21
|
+
if (!existsSync(path)) return null;
|
|
22
|
+
return gatewayCall<GatewayStatus>(path, "/status");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function trustedGatewaySocket(socketPath: string): Promise<{ dev: number; ino: number }> {
|
|
26
|
+
const directory = await lstat(dirname(socketPath));
|
|
27
|
+
const stat = await lstat(socketPath);
|
|
28
|
+
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() ||
|
|
29
|
+
(directory.mode & 0o777) !== 0o700 || !stat.isSocket() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
|
|
30
|
+
throw new DeliveryError("Gateway endpoint is not a private owned Unix socket", "rejected");
|
|
31
|
+
return { dev: stat.dev, ino: stat.ino };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function readGatewayJson(stream: IncomingMessage): Promise<unknown> {
|
|
35
|
+
let bytes = 0;
|
|
36
|
+
const chunks: Buffer[] = [];
|
|
37
|
+
for await (const chunk of stream) {
|
|
38
|
+
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
39
|
+
bytes += data.length;
|
|
40
|
+
if (bytes > MAX_GATEWAY_FRAME) throw new DeliveryError("Gateway frame exceeds size limit", "rejected");
|
|
41
|
+
chunks.push(data);
|
|
42
|
+
}
|
|
43
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** One attempt only. A lost response is never converted to a known rejection. */
|
|
47
|
+
export async function gatewayRequest(socketPath: string, endpoint: string, body?: unknown, options: {
|
|
48
|
+
token?: string; clientId?: string; signal?: AbortSignal; timeoutMs?: number;
|
|
49
|
+
} = {}): Promise<IncomingMessage> {
|
|
50
|
+
const before = await trustedGatewaySocket(socketPath);
|
|
51
|
+
const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
|
|
52
|
+
if (data && data.length > MAX_GATEWAY_FRAME) throw new DeliveryError("Gateway frame exceeds size limit", "rejected");
|
|
53
|
+
const { promise, resolve, reject } = Promise.withResolvers<IncomingMessage>();
|
|
54
|
+
let answered = false;
|
|
55
|
+
const req = request({ socketPath, path: endpoint, method: body === undefined ? "GET" : "POST",
|
|
56
|
+
headers: { ...(data ? { "content-type": "application/json", "content-length": data.length } : {}),
|
|
57
|
+
...(options.token ? { authorization: `Bearer ${options.token}` } : {}),
|
|
58
|
+
...(options.clientId ? { "x-gateway-client": options.clientId } : {}) }, signal: options.signal,
|
|
59
|
+
}, response => {
|
|
60
|
+
answered = true;
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
void trustedGatewaySocket(socketPath).then(after => {
|
|
63
|
+
if (before.dev !== after.dev || before.ino !== after.ino) {
|
|
64
|
+
response.destroy();
|
|
65
|
+
reject(new DeliveryError("Gateway socket changed during request", "uncertain"));
|
|
66
|
+
} else resolve(response);
|
|
67
|
+
}, error => { response.destroy(); reject(error); });
|
|
68
|
+
});
|
|
69
|
+
const timer = setTimeout(() => req.destroy(new Error("Gateway request timed out")), options.timeoutMs ?? 30_000);
|
|
70
|
+
timer.unref();
|
|
71
|
+
req.on("error", () => {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (!answered) reject(new DeliveryError("Gateway request outcome uncertain", "uncertain"));
|
|
74
|
+
});
|
|
75
|
+
if (data) req.write(data);
|
|
76
|
+
req.end();
|
|
77
|
+
return promise;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function gatewayCall<T>(socketPath: string, endpoint: string, body?: unknown, options?: Parameters<typeof gatewayRequest>[3]): Promise<T> {
|
|
81
|
+
const response = await gatewayRequest(socketPath, endpoint, body, options);
|
|
82
|
+
const result = await readGatewayJson(response) as GatewayResult;
|
|
83
|
+
if (!result.ok) throw new DeliveryError(result.error ?? "Gateway rejected operation", result.certainty ?? "uncertain", result.retryAfterMs);
|
|
84
|
+
return result.value as T;
|
|
85
|
+
}
|
|
@@ -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
|
+
}
|