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,289 @@
1
+ import { readFileSync, readdirSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { join } from "node:path";
4
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
+ import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
6
+ import { Type } from "@sinclair/typebox";
7
+ import { configuredPlatforms, loadConfig } from "./config";
8
+ import { createGatewayMessenger } from "./gateway-client";
9
+ import { Superagent } from "./runtime";
10
+ import { Store } from "./store";
11
+ import { sameLaneModel } from "./lane-models";
12
+ import { NativePresetManager } from "./native-presets";
13
+ import { publishNativeSession } from "./native-sessions";
14
+ import { MODEL_PRESET_NAMES, WORKFLOW_NAMES } from "./contracts";
15
+
16
+ function readHeadReferences(directory: string): string[] {
17
+ return readdirSync(directory, { withFileTypes: true })
18
+ .sort((left, right) => left.name.localeCompare(right.name))
19
+ .flatMap(entry => {
20
+ const path = join(directory, entry.name);
21
+ if (entry.isDirectory()) return readHeadReferences(path);
22
+ return entry.isFile() && entry.name.endsWith(".md") ? [readFileSync(path, "utf8")] : [];
23
+ });
24
+ }
25
+
26
+ // Required operating policy, not optional discovery or compactable chat history.
27
+ // Missing/unreadable files fail extension loading rather than silently omitting policy.
28
+ const headInstructions = [
29
+ readFileSync(new URL("../skills/head/SKILL.md", import.meta.url), "utf8"),
30
+ ...readHeadReferences(fileURLToPath(new URL("../skills/head/references/", import.meta.url))),
31
+ ];
32
+ const managerTools: Record<string, true> = {
33
+ head_recovery: true,
34
+ lane_models: true, lane_init_presets: true, lane_set_model: true,
35
+ lane_start: true, lane_inspect: true, lane_message: true,
36
+ lane_pause: true, lane_resume: true, lane_close: true,
37
+ };
38
+ const result = (value: unknown) => ({
39
+ content: [{ type: "text" as const, text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
40
+ details: {},
41
+ });
42
+ const workflowSchema = Type.Optional(Type.Object({
43
+ name: Type.Union(WORKFLOW_NAMES.map(name => Type.Literal(name))),
44
+ reason: Type.String({ minLength: 1 }),
45
+ }, { additionalProperties: false }));
46
+
47
+ export default function superagentExtension(pi: ExtensionAPI): void {
48
+ const role = process.env.OMP_SUPERAGENT_ROLE;
49
+ if (role !== "head") return;
50
+ // Subagents inherit environment but must not acquire the head's controller.
51
+ let runtime: Superagent | undefined;
52
+ let loading: Promise<void> | undefined;
53
+ let closed = false;
54
+ let startupError: unknown;
55
+ let timer: ReturnType<typeof setTimeout> | undefined;
56
+ let stopHostReady: (() => void) | undefined;
57
+ let presets: Promise<NativePresetManager> | undefined;
58
+ const requireRuntime = (ctx: ExtensionContext) => {
59
+ if (ctx.agent.kind !== "main") throw new Error("Lane management is restricted to the main superagent head");
60
+ if (!runtime) throw new Error(startupError ? `Superagent startup failed: ${String(startupError)}` : "Superagent is starting; retry once startup completes");
61
+ return runtime;
62
+ };
63
+ const nativePresets = (ctx: ExtensionContext): Promise<NativePresetManager> => {
64
+ requireRuntime(ctx);
65
+ return presets ??= Settings.loadReadOnly({ cwd: ctx.cwd }).then(settings => new NativePresetManager(
66
+ settings,
67
+ async () => {
68
+ const allowed = await requireRuntime(ctx).availableModels();
69
+ const identities = new Set(allowed.map(model => JSON.stringify([model.provider, model.id])));
70
+ return ctx.models.list().filter(model => identities.has(JSON.stringify([model.provider, model.id])));
71
+ },
72
+ provider => ctx.modelRegistry.hasConcreteAuth(provider),
73
+ ));
74
+ };
75
+ pi.on("before_agent_start", async (event, ctx) => {
76
+ if (ctx.agent.kind !== "main") return;
77
+ return { systemPrompt: [
78
+ ...event.systemPrompt,
79
+ ...headInstructions,
80
+ ] };
81
+ });
82
+
83
+ pi.on("session_start", async (_event, ctx) => {
84
+ if (ctx.agent.kind === "main") return;
85
+ // Subtract only our authority; never restore a default list or activate a
86
+ // native tool that the operator removed from this particular task session.
87
+ const active = pi.getActiveTools();
88
+ const scoped = active.filter(name => !Object.hasOwn(managerTools, name));
89
+ if (scoped.length !== active.length) await pi.setActiveTools(scoped);
90
+ });
91
+ pi.on("tool_call", (event, ctx) => {
92
+ if (event.toolName === "head_recovery" && ctx.agent.kind !== "main")
93
+ return { block: true, reason: "HEAD recovery is restricted to the original main head" };
94
+ if (!runtime?.headRecoveryActive()) return;
95
+ if (ctx.agent.kind !== "main" || event.toolName !== "head_recovery") {
96
+ runtime.blockHeadRecoveryTool();
97
+ return { block: true, reason: "The isolated HEAD recovery turn permits only head_recovery; original work is not replayed" };
98
+ }
99
+ });
100
+ pi.on("turn_end", (_event, ctx) => {
101
+ // Abort after the hook has delivered its block/tool result, not inside
102
+ // tool_call: native abort can release an awaiting hook without its result.
103
+ // Native prompt bounds remain authoritative; no watchdog or turn budget.
104
+ if (ctx.agent.kind === "main" && runtime?.headRecoveryActive()) ctx.abort();
105
+ });
106
+ pi.registerTool({
107
+ name: "head_recovery", label: "Decide isolated HEAD recovery", approval: "write", loadMode: "essential",
108
+ description: "Only during the runtime's internal same-HEAD recovery turn: propose hold or evidence-backed release of its exact original request. Native code validates receipt/session/file/generation and stable original-run evidence. Never replays work, discards uncertainty, or claims user-task acceptance.",
109
+ parameters: Type.Object({
110
+ attemptId: Type.String({ minLength: 1 }),
111
+ decision: Type.Union([Type.Literal("release"), Type.Literal("hold")]),
112
+ evidenceEntryIds: Type.Array(Type.String({ minLength: 1 })),
113
+ reason: Type.String({ minLength: 1 }),
114
+ }, { additionalProperties: false }),
115
+ async execute(_id, params, _signal, _onUpdate, ctx) {
116
+ return result(await requireRuntime(ctx).decideHeadRecovery(params));
117
+ },
118
+ });
119
+ pi.registerTool({
120
+ name: "lane_models", label: "Inspect lane model candidates", approval: "read", loadMode: "essential",
121
+ description: "Inspect the user's native OMP presets/roles plus enabled authenticated chat-model candidates and safe capability/cost metadata. Selectors accept preset:high, preset:middle, preset:low, any other observed native preset name after preset:, native roles such as @smol, or exact provider/model. Omit selectors to list all coding candidates. Consult native eval judge as advisory; the head chooses. No credentials/endpoints or fabricated quality/speed ranks.",
122
+ parameters: Type.Object({ selectors: Type.Optional(Type.Array(Type.String(), { minItems: 1 })) }),
123
+ async execute(_id, params, _signal, _onUpdate, ctx) {
124
+ const available = await requireRuntime(ctx).availableModels();
125
+ const manager = await nativePresets(ctx);
126
+ const inspection = await manager.inspect();
127
+ const current = ctx.models.current();
128
+ const resolutions = params.selectors ? await Promise.all(params.selectors.map(async selector => {
129
+ if (selector.startsWith("preset:")) {
130
+ try {
131
+ const resolved = await manager.resolve(selector.slice("preset:".length));
132
+ return { selector, preset: resolved.preset, model: available.find(candidate => sameLaneModel(candidate, resolved.model)) ?? null };
133
+ } catch (error) {
134
+ return { selector, model: null, error: error instanceof Error ? error.message : String(error) };
135
+ }
136
+ }
137
+ return { selector, model: available.find(candidate => sameLaneModel(candidate, ctx.models.resolve(selector))) ?? null };
138
+ })) : undefined;
139
+ const selected = resolutions
140
+ ? [...new Map(resolutions.flatMap(item => item.model ? [[JSON.stringify([item.model.provider, item.model.id]), item.model] as const] : [])).values()]
141
+ : available;
142
+ return result({
143
+ current: current ? { provider: current.provider, id: current.id } : null,
144
+ candidates: selected,
145
+ nativePresets: inspection,
146
+ ...(resolutions ? { resolutions } : {}),
147
+ guidance: "Catalog cost/capability facts are not measured speed, quality, quota, or permission. Consult native judge for substantive/uncertain routing; the head remains responsible for the final choice. Judge usage and fallback belong to native OMP, not this catalog.",
148
+ });
149
+ },
150
+ });
151
+ pi.registerTool({
152
+ name: "lane_init_presets", label: "Initialize missing native model presets", approval: "write", loadMode: "essential",
153
+ description: "First-head setup only: create missing native OMP high/middle/low presets from judged head choices. Each preset snapshots existing roles/thinking and changes only its own default model. Existing presets, active/default/judge roles and model definitions are preserved. This deliberate initial save persists native presets; ordinary lane selection/change never does. Do not claim a performance tier from the name.",
154
+ parameters: Type.Object({
155
+ choices: Type.Object(Object.fromEntries(MODEL_PRESET_NAMES.map(name => [name, Type.Optional(Type.Object({
156
+ model: Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) }),
157
+ reason: Type.String({ minLength: 1 }),
158
+ }))])), { minProperties: 1, additionalProperties: false }),
159
+ }),
160
+ async execute(_id, params, _signal, _onUpdate, ctx) {
161
+ return result(await (await nativePresets(ctx)).initialize(params.choices));
162
+ },
163
+ });
164
+ pi.registerTool({
165
+ name: "lane_start", label: "Start independent work", loadMode: "essential", approval: "exec",
166
+ description: "Bind an independent topic to its own OMP session at an explicit cwd. By default create a supported native thread/topic, or reuse the source's existing binding; unsupported private chats use a logical topic. For a clearly new topic inside an existing thread, supply its same authorized parent as destination with threadId:null and no topicId to create a sibling. An existing independent destination binds directly. Do not ask the user to run /new merely to create a topic. Consult lane_models and native judge; choose exactly one model {provider,id} or native preset name, with concise modelReason. The resolved model and full preset snapshot persist; retries/global edits do not retarget the lane. Optional workflow {name,reason} is explicit head selection within the user's authorized objective, never inferred from brief/report prose. It binds to this source/handoff; conflicting retries reject. Native capability/permissions own activation; ULW arming does not create a goal. Returns queued identity, not completion. Small main work stays direct. sourceId is the original trusted request ID.",
167
+ parameters: Type.Object({
168
+ sourceId: Type.String(), title: Type.String(), cwd: Type.String(),
169
+ kickoff: Type.String({ minLength: 1, description: "A concise message in the user's language stating the concrete approach. Delivered in the work topic before native lane execution; failed or uncertain delivery holds execution." }),
170
+ model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
171
+ preset: Type.Optional(Type.String({ minLength: 1 })),
172
+ modelReason: Type.String({ minLength: 1 }),
173
+ brief: Type.Optional(Type.String()), acceptance: Type.Optional(Type.Array(Type.String())),
174
+ workflow: workflowSchema,
175
+ destination: Type.Optional(Type.Object({
176
+ platform: Type.Union([Type.Literal("discord"), Type.Literal("telegram"), Type.Literal("slack")]),
177
+ accountId: Type.String(), authorityId: Type.String(),
178
+ guildId: Type.Union([Type.String(), Type.Null()]), channelId: Type.String(),
179
+ threadId: Type.Union([Type.String(), Type.Null()]),
180
+ topicId: Type.Optional(Type.String()),
181
+ })),
182
+ }),
183
+ async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).startLane(params)); },
184
+ });
185
+ pi.registerTool({
186
+ name: "lane_set_model", label: "Change an idle lane model", approval: "exec",
187
+ description: "Explicitly change one idle lane's model or full native preset snapshot without changing global OMP settings, the head, or other lanes. Requires a received authorized sourceId, exactly one model/preset and modelReason. Refuses active work, approvals/services/goals or unresolved submissions. Uses durable intent and native readback; do not blindly repeat an uncertain change.",
188
+ parameters: Type.Object({
189
+ id: Type.String(), sourceId: Type.String(),
190
+ model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
191
+ preset: Type.Optional(Type.String({ minLength: 1 })),
192
+ modelReason: Type.String({ minLength: 1 }),
193
+ }),
194
+ async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).changeModel(params)); },
195
+ });
196
+ pi.registerTool({
197
+ name: "lane_inspect", label: "Inspect independent work", approval: "read",
198
+ description: "List managed lanes or read one lane's actual runtime state. Does not read unrelated OMP sessions.",
199
+ parameters: Type.Object({ id: Type.Optional(Type.String()) }),
200
+ async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).inspect(params.id)); },
201
+ });
202
+ pi.registerTool({
203
+ name: "lane_message", label: "Message independent work", approval: "exec",
204
+ description: "Durably admit a follow-up to a specific open lane. Ordinary same-topic follow-ups steer an active native run by default; idle or ineligible work remains queued. Do not require a separate user /steer command. sourceId identifies the original received user instruction for duplicate suppression. Optional workflow {name,reason} is explicit head selection within that objective; text/quotes/reports never select one. Workflow selections remain serialized, not steered into an active run. The exact workflow/source/handoff is durable and conflicting retries reject. Admission is not execution or completion.",
205
+ parameters: Type.Object({ id: Type.String(), text: Type.String(), sourceId: Type.String(), workflow: workflowSchema }),
206
+ async execute(_id, params, _signal, _onUpdate, ctx) {
207
+ await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow);
208
+ return result("Follow-up durably queued.");
209
+ },
210
+ });
211
+ pi.registerTool({
212
+ name: "lane_pause", label: "Pause independent work", approval: "exec",
213
+ description: "Persist pause intent and stop the lane's current turn. Does not claim ongoing external services have been destroyed.",
214
+ parameters: Type.Object({ id: Type.String() }),
215
+ async execute(_id, params, _signal, _onUpdate, ctx) { await requireRuntime(ctx).pause(params.id); return result(await requireRuntime(ctx).inspect(params.id)); },
216
+ });
217
+ pi.registerTool({
218
+ name: "lane_resume", label: "Resume independent work", approval: "exec",
219
+ description: "Explicitly resume a paused lane and its native goal under a received sourceId. Preserves the model, budgets and original objective; never clears uncertain submissions or retries an uncertain external action.",
220
+ parameters: Type.Object({ id: Type.String(), sourceId: Type.String() }),
221
+ async execute(_id, params, _signal, _onUpdate, ctx) { await requireRuntime(ctx).resume(params.id, params.sourceId); return result(await requireRuntime(ctx).inspect(params.id)); },
222
+ });
223
+ pi.registerTool({
224
+ name: "lane_close", label: "Close independent work", approval: "write",
225
+ description: "Record a verified outcome or authorized cancellation. Must name evidence you actually checked. This does not authorize merge/publish and never deletes worktrees.",
226
+ parameters: Type.Object({
227
+ id: Type.String(), outcome: Type.Union([Type.Literal("completed"), Type.Literal("cancelled")]), evidence: Type.String(),
228
+ }),
229
+ async execute(_id, params, _signal, _onUpdate, ctx) { await requireRuntime(ctx).closeLane(params.id, params.outcome, params.evidence); return result(await requireRuntime(ctx).inspect(params.id)); },
230
+ });
231
+ pi.registerCommand("superagent", {
232
+ description: "Inspect the running messenger head and its lanes.",
233
+ async handler(_args, ctx) { ctx.ui.notify(JSON.stringify(await requireRuntime(ctx).inspect(), null, 2), "info"); },
234
+ });
235
+ pi.on("session_start", async (_event, ctx) => {
236
+ if (ctx.agent.kind !== "main" || loading || closed) return;
237
+ const configPath = process.env.OMP_SUPERAGENT_CONFIG;
238
+ if (!configPath || !process.env.OMP_SUPERAGENT_HOST_SOCKET)
239
+ throw new Error("Start this extension with omp-sa start and its owned stock OMP host");
240
+ // Native startup precedes the private pipe owner's socket readiness.
241
+ // Activate only after that exact owner has materialized and verified us.
242
+ stopHostReady = pi.events.on("superagent:host-ready", () => {
243
+ if (timer || loading || closed) return;
244
+ timer = setTimeout(() => {
245
+ loading = (async () => {
246
+ const config = await loadConfig(configPath);
247
+ const store = new Store(join(config.stateDir, "coordination.sqlite"));
248
+ let messenger: ReturnType<typeof createGatewayMessenger>;
249
+ try {
250
+ for (const lane of store.lanes()) await publishNativeSession(lane.sessionFile, lane.cwd);
251
+ messenger = createGatewayMessenger(config);
252
+ } catch (error) {
253
+ store.close();
254
+ throw error;
255
+ }
256
+ const candidate = new Superagent(config, store, messenger, fileURLToPath(new URL("./lane-extension.ts", import.meta.url)), error => {
257
+ pi.logger.error(`Superagent: ${error instanceof Error ? error.message : String(error)}`);
258
+ }, {
259
+ resolvePreset: async (name, thinkingContext) => (await nativePresets(ctx)).resolve(name, thinkingContext),
260
+ inspectPresets: async () => (await nativePresets(ctx)).inspect(),
261
+ persistPreset: async selection => (await nativePresets(ctx)).persistSelection(selection),
262
+ requestRestart: request => messenger.requestRestart(request),
263
+ });
264
+ try {
265
+ runtime = candidate;
266
+ await candidate.start();
267
+ if (closed) { await candidate.stop(); return; }
268
+ ctx.ui.setStatus("superagent", `Gateway: ${configuredPlatforms(config).join(", ")}; preset readiness: omp-sa status`);
269
+ } catch (error) {
270
+ runtime = undefined;
271
+ await candidate.stop().catch(() => {});
272
+ throw error;
273
+ }
274
+ })().catch(error => {
275
+ startupError = error;
276
+ pi.logger.error(`Superagent startup failed: ${error instanceof Error ? error.message : String(error)}`);
277
+ ctx.ui.setStatus("superagent", "startup failed; see host log");
278
+ });
279
+ }, 0);
280
+ });
281
+ });
282
+ pi.on("session_shutdown", async () => {
283
+ closed = true;
284
+ stopHostReady?.();
285
+ if (timer) clearTimeout(timer);
286
+ await loading;
287
+ await runtime?.stop();
288
+ });
289
+ }
@@ -0,0 +1,222 @@
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, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Route } 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): Promise<boolean> { return this.effect("canCreateThread", [route]); }
147
+ createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route> {
148
+ return this.effect("createThread", [route, title, sourceMessageId]);
149
+ }
150
+ fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> { return this.effect("fetchAfter", [route, messageId]); }
151
+
152
+ async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
153
+ if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
154
+ if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
155
+ throw new DeliveryError("Invalid attachment size", "rejected");
156
+ const incoming = await gatewayRequest(this.socketPath, "/attachment", { route, attachment }, { ...this.options(), signal });
157
+ if (incoming.headers["x-gateway-attachment-protocol"] !== "1") {
158
+ const result = await readGatewayJson(incoming) as GatewayResult;
159
+ throw new DeliveryError(result.error ?? "Attachment rejected", result.certainty ?? "uncertain");
160
+ }
161
+ let bytes = 0;
162
+ const header = Buffer.allocUnsafe(4);
163
+ let headerBytes = 0;
164
+ let remaining = 0;
165
+ let complete = false;
166
+ const bounded = new Transform({
167
+ transform(chunk: Buffer, _encoding, callback) {
168
+ let offset = 0;
169
+ while (offset < chunk.length) {
170
+ if (complete) { callback(new Error("Attachment data followed its completion frame")); return; }
171
+ if (!remaining) {
172
+ const count = Math.min(4 - headerBytes, chunk.length - offset);
173
+ chunk.copy(header, headerBytes, offset, offset + count);
174
+ headerBytes += count;
175
+ offset += count;
176
+ if (headerBytes < 4) continue;
177
+ remaining = header.readUInt32BE();
178
+ headerBytes = 0;
179
+ if (!remaining) { complete = true; continue; }
180
+ if (bytes + remaining > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes + remaining > MAX_GATEWAY_ATTACHMENT) {
181
+ callback(new Error("Attachment stream exceeds declared size"));
182
+ return;
183
+ }
184
+ }
185
+ const count = Math.min(remaining, chunk.length - offset);
186
+ if (count) this.push(chunk.subarray(offset, offset + count));
187
+ offset += count;
188
+ remaining -= count;
189
+ bytes += count;
190
+ }
191
+ callback();
192
+ },
193
+ flush(callback) {
194
+ callback(!complete || remaining || headerBytes || attachment.size !== null && bytes !== attachment.size
195
+ ? new Error("Attachment stream ended without a complete delivery receipt") : undefined);
196
+ },
197
+ });
198
+ incoming.on("error", error => bounded.destroy(error));
199
+ incoming.on("aborted", () => bounded.destroy(new Error("Attachment stream was interrupted")));
200
+ bounded.on("close", () => incoming.destroy());
201
+ incoming.pipe(bounded);
202
+ const headers = new Headers();
203
+ const contentType = incoming.headers["content-type"];
204
+ const contentLength = incoming.headers["x-gateway-attachment-length"];
205
+ if (typeof contentType === "string") headers.set("content-type", contentType);
206
+ if (typeof contentLength === "string") headers.set("content-length", contentLength);
207
+ return new Response(Readable.toWeb(bounded) as ReadableStream<Uint8Array>, { status: incoming.statusCode ?? 502, headers });
208
+ }
209
+
210
+ async stop(): Promise<void> {
211
+ if (this.stopped) return;
212
+ // Detach is best effort, never a messenger/server shutdown request.
213
+ try { await this.call("/detach", {}); } catch { /* Gateway may be unavailable. */ }
214
+ this.stopped = true;
215
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
216
+ this.events?.destroy();
217
+ this.events = undefined;
218
+ this.handlers = undefined;
219
+ }
220
+ }
221
+
222
+ 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
+ }