omp-superagent 0.1.10 → 0.1.13
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 +71 -15
- package/README.ko.md +10 -1
- package/README.md +10 -1
- package/THIRD_PARTY_NOTICES.md +35 -436
- package/assets/architecture-dark.svg +7 -12
- package/assets/architecture.ko-dark.svg +7 -12
- package/assets/architecture.ko.svg +7 -12
- package/assets/architecture.mmd +5 -13
- package/assets/architecture.svg +7 -12
- package/config.example.json +1 -0
- package/docs/OPERATIONS.en.md +282 -53
- package/docs/OPERATIONS.md +264 -45
- package/docs/design/execution.md +80 -52
- package/docs/design/messaging.md +113 -32
- package/docs/releases/0.1.11.md +20 -0
- package/docs/releases/0.1.13.md +13 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +13 -11
- package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
- package/scripts/upgrade-evidence-files.mjs +100 -0
- package/scripts/upgrade-evidence.mjs +192 -0
- package/scripts/upgrade-host-wire.mjs +162 -0
- package/skills/head/SKILL.md +12 -3
- package/skills/head/references/routing.md +1 -1
- package/skills/head/references/supervision.md +23 -26
- package/skills/lane/SKILL.md +28 -21
- package/skills/lane/references/workflow.md +15 -17
- package/src/cli.ts +33 -53
- package/src/{config.ts → config/config.ts} +7 -3
- package/src/config/wake-config.ts +36 -0
- package/src/contracts.ts +61 -12
- package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
- package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
- package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
- package/src/extension.ts +43 -25
- package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
- package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
- package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
- package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
- package/src/gateway-config.ts +1 -1
- package/src/gateway-restart-env.ts +3 -3
- package/src/{group-access.ts → group/group-access.ts} +8 -3
- package/src/{group-policy.ts → group/group-policy.ts} +2 -2
- package/src/{group-runner.ts → group/group-runner.ts} +11 -6
- package/src/host-extension.ts +164 -36
- package/src/host-sdk-helper.ts +66 -65
- package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
- package/src/{decisions.ts → lane/decisions.ts} +12 -10
- package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
- package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
- package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
- package/src/{workflow.ts → lane/workflow.ts} +1 -1
- package/src/lane-extension.ts +25 -7
- package/src/managed-memory-helper.ts +2 -2
- package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
- package/src/{delivery.ts → messaging/delivery.ts} +1 -1
- package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
- package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
- package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
- package/src/messaging/messenger-commands.ts +55 -0
- package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
- package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
- package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
- package/src/omp/head-resume.ts +123 -0
- package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
- package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
- package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
- package/src/{host.ts → omp/host.ts} +26 -17
- package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
- package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
- package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
- package/src/omp/native-journal.ts +124 -0
- package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
- package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
- package/src/omp/native-sessions.ts +124 -0
- package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
- package/src/{soul.ts → omp/soul.ts} +2 -2
- package/src/omp/stock-head-launch.ts +31 -0
- package/src/{autostart.ts → operator/autostart.ts} +3 -3
- package/src/{operator.ts → operator/operator.ts} +2 -2
- package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
- package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
- package/src/{setup.ts → operator/setup.ts} +5 -5
- package/src/operator/stop-lane.ts +25 -0
- package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
- package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
- package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
- package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
- package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
- package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
- package/src/{message-order.ts → routing/message-order.ts} +1 -1
- package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
- package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
- package/src/{runtime.ts → runtime/controller.ts} +867 -1213
- package/src/runtime/deferred-routing.ts +106 -0
- package/src/runtime/dm-timeline.ts +194 -0
- package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
- package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
- package/src/runtime/model-journal.ts +119 -0
- package/src/runtime/native-frames.ts +131 -0
- package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
- package/src/runtime/preset-sync.ts +232 -0
- package/src/runtime/preset-watch-paths.ts +137 -0
- package/src/runtime/result-attachments.ts +146 -0
- package/src/storage/deferred-routing.ts +149 -0
- package/src/{store.ts → storage/store.ts} +75 -42
- package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
- package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
- package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
- package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
- package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
- package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
- package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
- package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
- package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
- package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
- package/src/worker-serve-prepare.ts +4 -4
- package/src/board-extension.ts +0 -217
- package/src/board.ts +0 -467
- package/src/gateway-host-helper.ts +0 -13
- package/src/messenger-commands.ts +0 -15
- package/src/native-sessions.ts +0 -34
- /package/src/{credentials.ts → config/credentials.ts} +0 -0
- /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
- /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
- /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
- /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
- /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
- /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
- /package/src/{host-services.ts → omp/host-services.ts} +0 -0
- /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
- /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
- /package/src/{repository.ts → operator/repository.ts} +0 -0
- /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
- /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
- /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
- /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
- /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
- /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
- /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
- /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
- /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
- /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
- /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
- /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
- /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
- /package/upstream/{ulw.json → super.json} +0 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// allow: SIZE_OK — prompt and PR intake jobs share one atomic schedule/control ledger.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { authorizeRoute, type Config } from "
|
|
4
|
-
import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "
|
|
3
|
+
import { authorizeRoute, type Config } from "../config/config";
|
|
4
|
+
import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "../contracts";
|
|
5
5
|
import { describePrIntake, normalizeIntakeRepository } from "./cron-pr-intake";
|
|
6
6
|
import { describeCronSchedule, nextCronTime, parseCronSchedule, type CronSchedule } from "./cron-schedule";
|
|
7
|
-
import { compareMessageIds } from "
|
|
8
|
-
import {
|
|
7
|
+
import { compareMessageIds } from "../routing/message-order";
|
|
8
|
+
import { matchesWrittenCommand } from "../messaging/messenger-commands";
|
|
9
|
+
import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "../pr/pr-intake-mode";
|
|
9
10
|
|
|
10
11
|
const jobsKey = "cron:jobs";
|
|
11
12
|
export const CRON_RUN_PREFIX = "cron-run:";
|
|
@@ -121,14 +122,14 @@ function prModeReceipt(job: CronPrJob, mode: PrIntakeMode): string {
|
|
|
121
122
|
}
|
|
122
123
|
|
|
123
124
|
function prAddRequest(tail: string) {
|
|
124
|
-
const pair = /^"([^"\r\n]+)"[
|
|
125
|
+
const pair = /^"([^"\r\n]+)"[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(tail);
|
|
125
126
|
if (!pair?.[1] || !pair[2]) return null;
|
|
126
127
|
const repository = normalizeIntakeRepository(pair[2]);
|
|
127
128
|
return repository ? { schedule: pair[1].trim(), repository } : null;
|
|
128
129
|
}
|
|
129
130
|
|
|
130
131
|
function originalPrAdd(text: string) {
|
|
131
|
-
const tail = /^\/cron[
|
|
132
|
+
const tail = /^\/cron[^\S\r\n\u2028\u2029]+pr-add[^\S\r\n\u2028\u2029]+(.+)$/u.exec(text.trim())?.[1];
|
|
132
133
|
return tail ? prAddRequest(tail) : null;
|
|
133
134
|
}
|
|
134
135
|
|
|
@@ -216,10 +217,8 @@ export class CronJobs {
|
|
|
216
217
|
const stored = this.store.input(input.id);
|
|
217
218
|
// A voice confirmation can have projected draft text in `text`. It is
|
|
218
219
|
// not a physical owner instruction to open a lane or publish to GitHub.
|
|
219
|
-
const written = stored?.discordOriginalText?.trim().replace(/^<@!?(\d+)>\s*/, (mention, id) =>
|
|
220
|
-
id === route.accountId ? "" : mention).trim();
|
|
221
220
|
return stored !== null && (stored.state === "pending" || stored.state === "done")
|
|
222
|
-
&& (
|
|
221
|
+
&& matchesWrittenCommand(stored)
|
|
223
222
|
&& routeKey(stored.route) === routeKey(route) && stored.messageId === input.messageId
|
|
224
223
|
&& stored.interactionId === input.interactionId && !stored.pickerSelection
|
|
225
224
|
&& (stored.messageId === null ? stored.interactionId !== undefined
|
|
@@ -606,14 +605,23 @@ export class CronJobs {
|
|
|
606
605
|
return id.startsWith(CRON_RUN_PREFIX) && this.store.getMeta(`cron-shell:${id}`) !== null;
|
|
607
606
|
}
|
|
608
607
|
|
|
608
|
+
private scheduled(job: CronJob, boundary: string | null): job is CronJob & { nextAt: number } {
|
|
609
|
+
return job.nextAt !== null && !job.paused && job.stopBoundary === boundary
|
|
610
|
+
&& (job.kind === "pr-intake" ? !job.removed : job.shell !== true);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
hasScheduledWork(): boolean {
|
|
614
|
+
const boundary = this.store.getMeta("head:stop-boundary");
|
|
615
|
+
return this.state().jobs.some(job => this.scheduled(job, boundary) && this.source(job) !== null);
|
|
616
|
+
}
|
|
617
|
+
|
|
609
618
|
poll(now: number): void {
|
|
610
619
|
if (this.store.getMeta("head:restart-fence")) return;
|
|
611
620
|
let state = this.state();
|
|
612
621
|
const boundary = this.store.getMeta("head:stop-boundary");
|
|
613
|
-
|
|
614
|
-
.
|
|
615
|
-
|
|
616
|
-
if (job.kind !== "pr-intake" && job.shell === true) continue;
|
|
622
|
+
const scheduled = state.jobs.filter((job): job is CronJob & { nextAt: number } =>
|
|
623
|
+
this.scheduled(job, boundary) && job.nextAt <= now);
|
|
624
|
+
for (const job of scheduled.sort((left, right) => left.nextAt - right.nextAt)) {
|
|
617
625
|
const source = this.source(job);
|
|
618
626
|
if (!source) continue;
|
|
619
627
|
const last = job.lastRunId ? this.store.input(job.lastRunId) : null;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Type, type Static } from "@sinclair/typebox/type";
|
|
2
2
|
import { Value } from "@sinclair/typebox/value";
|
|
3
|
-
import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "
|
|
3
|
+
import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "../contracts";
|
|
4
4
|
import type { CronJobs, CronPrJob } from "./cron-jobs";
|
|
5
|
-
import { parsePrRef } from "
|
|
6
|
-
import { PrReadError } from "
|
|
7
|
-
import { intakeStatusKey } from "
|
|
5
|
+
import { parsePrRef } from "../pr/pr-github";
|
|
6
|
+
import { PrReadError } from "../pr/pr-github-schema";
|
|
7
|
+
import { intakeStatusKey } from "../pr/pr-intake-work";
|
|
8
8
|
|
|
9
9
|
const offerPrefix = "cron-pr:offer:";
|
|
10
10
|
const githubId = Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }));
|
|
@@ -6,7 +6,7 @@ export type CronSchedule =
|
|
|
6
6
|
| { readonly kind: "calendar"; readonly expression: string; readonly timezone: string };
|
|
7
7
|
|
|
8
8
|
export function parseCronSchedule(text: string, now: number): CronSchedule | null {
|
|
9
|
-
const relative = /^(in|every)
|
|
9
|
+
const relative = /^(in|every)[^\S\r\n\u2028\u2029]+([1-9]\d*)([smhd])$/u.exec(text);
|
|
10
10
|
if (relative) {
|
|
11
11
|
const [, mode, amount, unit] = relative;
|
|
12
12
|
const seconds = Number(amount) * (unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
|
|
@@ -14,8 +14,8 @@ export function parseCronSchedule(text: string, now: number): CronSchedule | nul
|
|
|
14
14
|
if (!Number.isFinite(new Date(now + milliseconds).getTime()) || mode === "every" && seconds < 60) return null;
|
|
15
15
|
return mode === "every" ? { kind: "interval", milliseconds } : { kind: "once", at: now + milliseconds };
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
const date = /^at[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(text)?.[1];
|
|
18
|
+
if (date) {
|
|
19
19
|
if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?:Z|[+-]\d{2}:\d{2})$/.test(date)) return null;
|
|
20
20
|
const day = date.slice(0, 10);
|
|
21
21
|
const midnight = new Date(`${day}T00:00:00Z`);
|
package/src/extension.ts
CHANGED
|
@@ -4,23 +4,25 @@ import { join } from "node:path";
|
|
|
4
4
|
import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
|
|
5
5
|
import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
|
|
6
6
|
import { Type } from "@sinclair/typebox";
|
|
7
|
-
import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
7
|
+
import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config/config";
|
|
8
|
+
import { loadWakeConfig } from "./config/wake-config";
|
|
9
|
+
import { createGatewayMessenger } from "./gateway/gateway-client";
|
|
10
|
+
import { Superagent } from "./runtime/controller";
|
|
11
|
+
import { Store } from "./storage/store";
|
|
12
|
+
import { lanePlacement } from "./lane/lane-rows";
|
|
13
|
+
import { sameLaneModel } from "./lane/lane-models";
|
|
14
|
+
import { NativePresetManager } from "./omp/native-presets";
|
|
15
|
+
import { publishNativeSession, type HostReadyEvent } from "./omp/native-sessions";
|
|
16
|
+
import { isPrReviewLane } from "./pr/pr-intake-review";
|
|
16
17
|
import { MODEL_PRESET_NAMES, WORKFLOW_NAMES } from "./contracts";
|
|
17
|
-
import type { PrWatchCommand } from "./pr-watch";
|
|
18
|
-
import type { LaneWatchCommand } from "./lane-watch";
|
|
19
|
-
import { registerDecisionAsk } from "./decision-tool";
|
|
20
|
-
import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
|
|
21
|
-
import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE,
|
|
22
|
-
|
|
23
|
-
import {
|
|
18
|
+
import type { PrWatchCommand } from "./pr/pr-watch";
|
|
19
|
+
import type { LaneWatchCommand } from "./lane/lane-watch";
|
|
20
|
+
import { registerDecisionAsk } from "./lane/decision-tool";
|
|
21
|
+
import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
|
|
22
|
+
import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, HEAD_SLEEP_PROBE_READY, type HeadSleepProbeReadyEvent,
|
|
23
|
+
type RotationGuardEvent, type RotationProbeEvent } from "./runtime/head-rotation";
|
|
24
|
+
import { readHeadQuota } from "./runtime/head-quota";
|
|
25
|
+
import { soulUpdateSchema } from "./omp/soul";
|
|
24
26
|
|
|
25
27
|
// Inject the role contract, not the references. Resolve the reference directory
|
|
26
28
|
// from this package so a same-name workspace skill cannot change the procedure.
|
|
@@ -62,17 +64,22 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
62
64
|
// Subagents inherit environment but must not acquire the head's controller.
|
|
63
65
|
let runtime: Superagent | undefined;
|
|
64
66
|
let loading: Promise<void> | undefined;
|
|
67
|
+
const hostShutdown = new AbortController();
|
|
65
68
|
let closed = false;
|
|
66
69
|
let startupError: unknown;
|
|
67
70
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
68
71
|
let stopHostReady: (() => void) | undefined;
|
|
72
|
+
const stopSleepProbeReady = pi.events.on(HEAD_SLEEP_PROBE_READY, value => {
|
|
73
|
+
const { respond } = value as HeadSleepProbeReadyEvent;
|
|
74
|
+
respond(runtime?.canProbeHeadSleep() ?? false);
|
|
75
|
+
});
|
|
69
76
|
const stopRotationProbe = pi.events.on(HEAD_ROTATION_PROBE, value => {
|
|
70
|
-
const { state, respond } = value as RotationProbeEvent;
|
|
71
|
-
respond(runtime?.attestHeadRotation(state) ?? Promise.resolve(null));
|
|
77
|
+
const { mode, state, respond } = value as RotationProbeEvent;
|
|
78
|
+
respond(runtime?.attestHeadRotation(state, mode) ?? Promise.resolve(null));
|
|
72
79
|
});
|
|
73
80
|
const stopRotationGuard = pi.events.on(HEAD_ROTATION_GUARD, value => {
|
|
74
|
-
const { id, state, respond } = value as RotationGuardEvent;
|
|
75
|
-
respond(runtime?.guardHeadRotation(id, state) ?? false);
|
|
81
|
+
const { id, mode, state, respond } = value as RotationGuardEvent;
|
|
82
|
+
respond(runtime?.guardHeadRotation(id, state, mode) ?? false);
|
|
76
83
|
});
|
|
77
84
|
let presets: Promise<NativePresetManager> | undefined;
|
|
78
85
|
const requireRuntime = (ctx: ExtensionContext) => {
|
|
@@ -126,6 +133,8 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
126
133
|
if (scoped.length !== active.length) await pi.setActiveTools(scoped);
|
|
127
134
|
});
|
|
128
135
|
pi.on("tool_call", (event, ctx) => {
|
|
136
|
+
if (runtime?.laneDecisionReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_review_decision"))
|
|
137
|
+
return { block: true, reason: "A lane question permits only answering or escalating its original decision" };
|
|
129
138
|
if (runtime?.scopeReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_message"))
|
|
130
139
|
return { block: true, reason: "This assignment review permits only a direct same-lane correction from its verified owner message" };
|
|
131
140
|
if (event.toolName === "soul_update") {
|
|
@@ -513,14 +522,20 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
513
522
|
throw new Error("Start this extension with omp-sa start and its owned stock OMP host");
|
|
514
523
|
// Native startup precedes the private pipe owner's socket readiness.
|
|
515
524
|
// Activate only after that exact owner has materialized and verified us.
|
|
516
|
-
stopHostReady = pi.events.on("superagent:host-ready",
|
|
525
|
+
stopHostReady = pi.events.on("superagent:host-ready", value => {
|
|
517
526
|
if (timer || loading || closed) return;
|
|
518
527
|
timer = setTimeout(() => {
|
|
519
528
|
loading = (async () => {
|
|
520
|
-
const {
|
|
529
|
+
const { nativeProfile, waking } = value as HostReadyEvent;
|
|
530
|
+
if (!nativeProfile) throw new Error("HEAD did not identify its native session storage");
|
|
521
531
|
const restartHash = process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
|
|
522
|
-
if (restartHash
|
|
532
|
+
if (waking && !restartHash) throw new Error("HEAD wake is missing its reserved configuration");
|
|
533
|
+
const snapshot = waking && restartHash
|
|
534
|
+
? { config: await loadWakeConfig(configPath, restartHash, hostShutdown.signal), sourceHash: restartHash }
|
|
535
|
+
: await loadConfigSnapshot(configPath);
|
|
536
|
+
if (restartHash !== undefined && restartHash !== snapshot.sourceHash)
|
|
523
537
|
throw new Error("Gateway configuration changed before replacement HEAD initialization");
|
|
538
|
+
const { config } = snapshot;
|
|
524
539
|
delete process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
|
|
525
540
|
const store = new Store(join(config.stateDir, "coordination.sqlite"));
|
|
526
541
|
let messenger: ReturnType<typeof createGatewayMessenger>;
|
|
@@ -529,9 +544,9 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
529
544
|
if (lane.remote || !lane.sessionId || isPrReviewLane(store, lane.id)) continue;
|
|
530
545
|
const { sessionFile } = hostPaths(config, lane.id);
|
|
531
546
|
if (lane.sessionFile !== sessionFile) throw new Error("Refusing to publish a lane outside its managed session path");
|
|
532
|
-
await publishNativeSession(sessionFile, lane.cwd, lane.sessionId);
|
|
547
|
+
await publishNativeSession(sessionFile, lane.cwd, lane.sessionId, nativeProfile);
|
|
533
548
|
}
|
|
534
|
-
messenger = createGatewayMessenger(config);
|
|
549
|
+
messenger = createGatewayMessenger(config, hostShutdown.signal);
|
|
535
550
|
} catch (error) {
|
|
536
551
|
store.close();
|
|
537
552
|
throw error;
|
|
@@ -579,6 +594,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
579
594
|
throw error;
|
|
580
595
|
}
|
|
581
596
|
})().catch(error => {
|
|
597
|
+
if (closed) return;
|
|
582
598
|
startupError = error;
|
|
583
599
|
pi.logger.error(`Superagent startup failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
584
600
|
ctx.ui.setStatus("superagent", "startup failed; see host log");
|
|
@@ -588,9 +604,11 @@ export default function superagentExtension(pi: ExtensionAPI): void {
|
|
|
588
604
|
});
|
|
589
605
|
pi.on("session_shutdown", async () => {
|
|
590
606
|
closed = true;
|
|
607
|
+
hostShutdown.abort();
|
|
591
608
|
stopHostReady?.();
|
|
592
609
|
stopRotationProbe();
|
|
593
610
|
stopRotationGuard();
|
|
611
|
+
stopSleepProbeReady();
|
|
594
612
|
if (timer) clearTimeout(timer);
|
|
595
613
|
await loading;
|
|
596
614
|
await runtime?.stop();
|
|
@@ -1,35 +1,54 @@
|
|
|
1
1
|
import type { IncomingMessage } from "node:http";
|
|
2
|
-
import
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import type { Config } from "../config/config";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
4
|
-
import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "
|
|
5
|
-
import { DeliveryError } from "
|
|
6
|
-
import {
|
|
5
|
+
import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "../contracts";
|
|
6
|
+
import { DeliveryError } from "../messaging/delivery";
|
|
7
|
+
import {
|
|
8
|
+
gatewayCall, gatewayPaths, GatewaySocketChangedError, MAX_GATEWAY_FRAME, openGatewayEvents, parseInboundAttachmentReceipt,
|
|
9
|
+
type GatewayEventConnection, type GatewaySocketIdentity,
|
|
10
|
+
} from "./gateway-protocol";
|
|
7
11
|
import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
|
|
8
|
-
import type { GroupReply } from "
|
|
9
|
-
import type { DiscordPresenceStatus, MessengerPresenceRequest } from "
|
|
12
|
+
import type { GroupReply } from "../group/group-policy";
|
|
13
|
+
import type { DiscordPresenceStatus, MessengerPresenceRequest } from "../contracts";
|
|
10
14
|
|
|
11
15
|
export interface GatewayHeadMessenger extends Messenger {
|
|
12
16
|
assertRoute(route: Route, purpose?: "history"): Promise<void>;
|
|
13
17
|
requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
|
|
14
18
|
}
|
|
15
19
|
|
|
20
|
+
function retryableHandshake(error: unknown): boolean {
|
|
21
|
+
if (error instanceof GatewaySocketChangedError) return true;
|
|
22
|
+
const cause = error instanceof DeliveryError ? error.cause : error;
|
|
23
|
+
return cause instanceof Error && "code" in cause
|
|
24
|
+
&& ["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(String(cause.code));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function retryableReconnect(error: unknown): boolean {
|
|
28
|
+
return retryableHandshake(error) || (error instanceof DeliveryError && error.certainty === "uncertain");
|
|
29
|
+
}
|
|
30
|
+
|
|
16
31
|
/** Transport-only head adapter. Detaching never logs out the actual accounts. */
|
|
17
32
|
class GatewayMessenger implements GatewayHeadMessenger {
|
|
33
|
+
readonly managesStartupHistory = true;
|
|
18
34
|
private readonly clientId = crypto.randomUUID();
|
|
19
35
|
private readonly socketPath: string;
|
|
20
36
|
private readonly token: string;
|
|
21
37
|
private handlers?: Parameters<Messenger["start"]>[0];
|
|
22
|
-
private events?:
|
|
38
|
+
private events?: GatewayEventConnection;
|
|
23
39
|
private stopped = false;
|
|
24
40
|
private reconnectTimer?: ReturnType<typeof setTimeout>;
|
|
25
41
|
private delivery: Promise<void> = Promise.resolve();
|
|
26
42
|
private intakeReady = false;
|
|
27
43
|
private connecting?: Promise<void>;
|
|
28
44
|
private reconnectDelay = 250;
|
|
45
|
+
private readonly detach = new AbortController();
|
|
46
|
+
private readonly startupSignal: AbortSignal;
|
|
29
47
|
|
|
30
|
-
constructor(config: Config) {
|
|
48
|
+
constructor(config: Config, hostShutdown?: AbortSignal) {
|
|
31
49
|
this.socketPath = gatewayPaths(config).socketPath;
|
|
32
50
|
this.token = process.env.OMP_SUPERAGENT_GATEWAY_TOKEN ?? "";
|
|
51
|
+
this.startupSignal = hostShutdown ? AbortSignal.any([hostShutdown, this.detach.signal]) : this.detach.signal;
|
|
33
52
|
}
|
|
34
53
|
|
|
35
54
|
private options() { return { token: this.token, clientId: this.clientId }; }
|
|
@@ -38,51 +57,81 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
38
57
|
return gatewayCall<T>(this.socketPath, endpoint, body, { ...this.options(), signal });
|
|
39
58
|
}
|
|
40
59
|
|
|
60
|
+
private markReady(expectedSocket: GatewaySocketIdentity): Promise<void> {
|
|
61
|
+
return gatewayCall(this.socketPath, "/ready", {}, { ...this.options(), expectedSocket, signal: this.detach.signal });
|
|
62
|
+
}
|
|
63
|
+
|
|
41
64
|
async start(handlers: Parameters<Messenger["start"]>[0]): Promise<void> {
|
|
42
65
|
if (this.handlers || this.stopped) throw new Error("Gateway messenger cannot be started twice");
|
|
43
66
|
if (!this.token) throw new DeliveryError("Head was not launched by its Gateway", "rejected");
|
|
44
67
|
this.handlers = handlers;
|
|
45
68
|
try {
|
|
46
|
-
|
|
69
|
+
// A reserved Host can become ready while its Gateway is being replaced.
|
|
70
|
+
// Repeat only the authenticated handshake, never a handler or an effect.
|
|
71
|
+
for (;;) {
|
|
72
|
+
this.startupSignal.throwIfAborted();
|
|
73
|
+
try { await this.connect(this.startupSignal); break; }
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (!retryableHandshake(error)) throw error;
|
|
76
|
+
await delay(this.reconnectDelay, undefined, { signal: this.startupSignal, ref: false });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
this.startupSignal.throwIfAborted();
|
|
47
80
|
// Return before the native-approval gate, like the actual adapters. The
|
|
48
81
|
// head must attach/reconcile native UI before enabling any admission.
|
|
49
82
|
void (handlers.ready ?? Promise.resolve()).then(async () => {
|
|
50
83
|
if (this.stopped) return;
|
|
51
84
|
this.intakeReady = true;
|
|
52
|
-
|
|
53
|
-
|
|
85
|
+
const events = this.events;
|
|
86
|
+
// If the stream already disconnected, its replacement will send ready.
|
|
87
|
+
if (!events) return;
|
|
88
|
+
try { await this.markReady(events.socket); }
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (this.events !== events) return;
|
|
91
|
+
this.events = undefined;
|
|
92
|
+
events.stream.destroy();
|
|
93
|
+
if (retryableReconnect(error)) this.scheduleReconnect();
|
|
94
|
+
}
|
|
95
|
+
}, () => { this.events?.stream.destroy(); });
|
|
54
96
|
} catch (error) {
|
|
55
97
|
await this.stop();
|
|
56
98
|
throw error;
|
|
57
99
|
}
|
|
58
100
|
}
|
|
59
101
|
|
|
60
|
-
private connect(): Promise<void> {
|
|
102
|
+
private connect(signal?: AbortSignal): Promise<void> {
|
|
61
103
|
if (this.connecting) return this.connecting;
|
|
62
|
-
this.connecting = this.openEvents().finally(() => { this.connecting = undefined; });
|
|
104
|
+
this.connecting = this.openEvents(signal).finally(() => { this.connecting = undefined; });
|
|
63
105
|
return this.connecting;
|
|
64
106
|
}
|
|
65
|
-
private async openEvents(): Promise<void> {
|
|
66
|
-
await this.
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
107
|
+
private async openEvents(signal = this.detach.signal): Promise<void> {
|
|
108
|
+
const connection = await openGatewayEvents(this.socketPath, {
|
|
109
|
+
...this.options(), pid: process.pid, resumed: this.intakeReady,
|
|
110
|
+
startupHistory: this.handlers?.reserveStartupHistory !== undefined, signal,
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
signal.throwIfAborted();
|
|
114
|
+
if (this.intakeReady) await this.markReady(connection.socket);
|
|
115
|
+
signal.throwIfAborted();
|
|
116
|
+
if (connection.reserveHistory) this.handlers?.reserveStartupHistory?.();
|
|
117
|
+
} catch (error) {
|
|
118
|
+
connection.stream.destroy();
|
|
119
|
+
throw error;
|
|
71
120
|
}
|
|
72
|
-
|
|
73
|
-
this.
|
|
74
|
-
|
|
75
|
-
if (this.events !== events) return;
|
|
121
|
+
this.events = connection;
|
|
122
|
+
void this.consume(connection.stream).catch(() => { connection.stream.destroy(); }).finally(() => {
|
|
123
|
+
if (this.events !== connection) return;
|
|
76
124
|
this.events = undefined;
|
|
77
125
|
this.scheduleReconnect();
|
|
78
126
|
});
|
|
79
|
-
if (this.intakeReady) await this.call("/ready", {});
|
|
80
127
|
}
|
|
81
128
|
private scheduleReconnect(): void {
|
|
82
129
|
if (this.stopped || this.reconnectTimer) return;
|
|
83
130
|
this.reconnectTimer = setTimeout(() => {
|
|
84
131
|
this.reconnectTimer = undefined;
|
|
85
|
-
void this.connect().catch(
|
|
132
|
+
void this.connect().catch(error => {
|
|
133
|
+
if (retryableReconnect(error)) this.scheduleReconnect();
|
|
134
|
+
});
|
|
86
135
|
}, this.reconnectDelay);
|
|
87
136
|
this.reconnectTimer.unref();
|
|
88
137
|
}
|
|
@@ -104,6 +153,7 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
104
153
|
if (this.stopped || !this.handlers) return;
|
|
105
154
|
disconnected.signal.throwIfAborted();
|
|
106
155
|
let outcome: GatewayReceipt = "accepted";
|
|
156
|
+
let retryAfterMs = 0;
|
|
107
157
|
try {
|
|
108
158
|
const event = frame.event;
|
|
109
159
|
if (event.kind === "message") await this.handlers.message(event.input);
|
|
@@ -122,16 +172,18 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
122
172
|
const { kind: _, ...notice } = event;
|
|
123
173
|
await this.handlers.restart(notice);
|
|
124
174
|
}
|
|
125
|
-
else await this.handlers.reconnect?.();
|
|
175
|
+
else await this.handlers.reconnect?.(event.historyRecovery === true ? frame.sequence : false, event.historyPlatform);
|
|
126
176
|
} catch (error) {
|
|
127
177
|
outcome = error instanceof DeliveryError && error.certainty === "rejected" ? "rejected" : "unresolved";
|
|
178
|
+
const retryHint = error instanceof DeliveryError ? error.retryAfterMs : undefined;
|
|
179
|
+
if (outcome === "unresolved" && retryHint !== undefined && Number.isFinite(retryHint)) retryAfterMs = retryHint;
|
|
128
180
|
}
|
|
129
181
|
// A handler may finish after its Gateway has been replaced. Its
|
|
130
182
|
// receipt belongs only to this stream; redelivery reconciles the
|
|
131
183
|
// durable outcome after reattachment instead of ACKing a new server.
|
|
132
184
|
disconnected.signal.throwIfAborted();
|
|
133
185
|
// A poison input stays visible and ordered without a tight retry loop.
|
|
134
|
-
this.reconnectDelay = outcome === "unresolved" ? Math.min(this.reconnectDelay * 2, 30_000) : 250;
|
|
186
|
+
this.reconnectDelay = outcome === "unresolved" ? Math.max(retryAfterMs, Math.min(this.reconnectDelay * 2, 30_000)) : 250;
|
|
135
187
|
await this.call("/receipt", { sequence: frame.sequence, outcome }, disconnected.signal);
|
|
136
188
|
});
|
|
137
189
|
await this.delivery;
|
|
@@ -185,7 +237,9 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
185
237
|
return this.effect("messengerPresence", [request]);
|
|
186
238
|
}
|
|
187
239
|
discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
|
|
188
|
-
fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> {
|
|
240
|
+
fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null> {
|
|
241
|
+
return this.effect("fetchAfter", historySequence === undefined ? [route, messageId] : [route, messageId, historySequence]);
|
|
242
|
+
}
|
|
189
243
|
|
|
190
244
|
async openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt> {
|
|
191
245
|
if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
|
|
@@ -197,14 +251,17 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
197
251
|
|
|
198
252
|
async stop(): Promise<void> {
|
|
199
253
|
if (this.stopped) return;
|
|
200
|
-
// Detach is best effort, never a messenger/server shutdown request.
|
|
201
|
-
try { await this.call("/detach", {}); } catch { /* Gateway may be unavailable. */ }
|
|
202
254
|
this.stopped = true;
|
|
255
|
+
this.detach.abort();
|
|
203
256
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
204
|
-
this.events?.destroy();
|
|
257
|
+
this.events?.stream.destroy();
|
|
205
258
|
this.events = undefined;
|
|
206
259
|
this.handlers = undefined;
|
|
260
|
+
// Detach is best effort, never a messenger/server shutdown request.
|
|
261
|
+
try { await gatewayCall(this.socketPath, "/detach", {}, this.options()); } catch { /* Gateway may be unavailable. */ }
|
|
207
262
|
}
|
|
208
263
|
}
|
|
209
264
|
|
|
210
|
-
export function createGatewayMessenger(config: Config): GatewayHeadMessenger {
|
|
265
|
+
export function createGatewayMessenger(config: Config, hostShutdown?: AbortSignal): GatewayHeadMessenger {
|
|
266
|
+
return new GatewayMessenger(config, hostShutdown);
|
|
267
|
+
}
|
|
@@ -3,12 +3,12 @@ import { constants } from "node:fs";
|
|
|
3
3
|
import { access } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import type { Config } from "
|
|
7
|
-
import type { GatewayRestartRecord } from "
|
|
8
|
-
import { DeliveryError } from "
|
|
6
|
+
import type { Config } from "../config/config";
|
|
7
|
+
import type { GatewayRestartRecord } from "../contracts";
|
|
8
|
+
import { DeliveryError } from "../messaging/delivery";
|
|
9
9
|
import { gatewayCall, gatewayPaths, gatewayStatus } from "./gateway-protocol";
|
|
10
10
|
|
|
11
|
-
const root = fileURLToPath(new URL("
|
|
11
|
+
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
12
12
|
const binary = join(root, "gateway", "bin", `omp-gateway-${process.platform}-${process.arch}`);
|
|
13
13
|
|
|
14
14
|
export async function requireGateway(): Promise<string> {
|
|
@@ -3,15 +3,27 @@ import { request, type IncomingMessage } from "node:http";
|
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { lstat, realpath } from "node:fs/promises";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
|
-
import type { Config } from "
|
|
7
|
-
import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "
|
|
8
|
-
import { DeliveryError } from "
|
|
6
|
+
import type { Config } from "../config/config";
|
|
7
|
+
import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "../contracts";
|
|
8
|
+
import { DeliveryError } from "../messaging/delivery";
|
|
9
9
|
import type { GatewayStatus } from "./gateway-wire";
|
|
10
10
|
|
|
11
11
|
export const MAX_GATEWAY_FRAME = 16 * 1024 * 1024;
|
|
12
12
|
export const MAX_GATEWAY_ATTACHMENT = 20 * 1024 * 1024;
|
|
13
13
|
export const MAX_GATEWAY_ATTACHMENT_BATCH = 40 * 1024 * 1024;
|
|
14
14
|
export interface GatewayResult { ok: boolean; value?: unknown; error?: string; certainty?: "rejected" | "uncertain"; retryAfterMs?: number }
|
|
15
|
+
export type GatewaySocketIdentity = { readonly dev: number; readonly ino: number };
|
|
16
|
+
export type GatewayEventConnection = {
|
|
17
|
+
readonly stream: IncomingMessage;
|
|
18
|
+
readonly socket: GatewaySocketIdentity;
|
|
19
|
+
readonly reserveHistory: boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export class GatewaySocketChangedError extends DeliveryError {
|
|
23
|
+
constructor(certainty: "rejected" | "uncertain") {
|
|
24
|
+
super("Gateway socket changed during request", certainty);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
15
27
|
|
|
16
28
|
export function gatewayPaths(config: Pick<Config, "stateDir">) {
|
|
17
29
|
const socketPath = join(config.stateDir, "run", "gateway.sock");
|
|
@@ -25,7 +37,7 @@ export async function gatewayStatus(config: Config): Promise<GatewayStatus | nul
|
|
|
25
37
|
return gatewayCall<GatewayStatus>(path, "/status");
|
|
26
38
|
}
|
|
27
39
|
|
|
28
|
-
export async function trustedGatewaySocket(socketPath: string): Promise<
|
|
40
|
+
export async function trustedGatewaySocket(socketPath: string): Promise<GatewaySocketIdentity> {
|
|
29
41
|
const directory = await lstat(dirname(socketPath));
|
|
30
42
|
const stat = await lstat(socketPath);
|
|
31
43
|
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() ||
|
|
@@ -34,6 +46,17 @@ export async function trustedGatewaySocket(socketPath: string): Promise<{ dev: n
|
|
|
34
46
|
return { dev: stat.dev, ino: stat.ino };
|
|
35
47
|
}
|
|
36
48
|
|
|
49
|
+
function requireSameSocket(expected: GatewaySocketIdentity, actual: GatewaySocketIdentity, certainty: "rejected" | "uncertain"): void {
|
|
50
|
+
if (expected.dev !== actual.dev || expected.ino !== actual.ino) throw new GatewaySocketChangedError(certainty);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function verifyResponseSocket(socketPath: string, expected: GatewaySocketIdentity): Promise<void> {
|
|
54
|
+
const actual = await trustedGatewaySocket(socketPath).catch(cause => {
|
|
55
|
+
throw new DeliveryError("Gateway socket could not be verified after request", "uncertain", undefined, { cause });
|
|
56
|
+
});
|
|
57
|
+
requireSameSocket(expected, actual, "uncertain");
|
|
58
|
+
}
|
|
59
|
+
|
|
37
60
|
export async function readGatewayJson(stream: IncomingMessage): Promise<unknown> {
|
|
38
61
|
let bytes = 0;
|
|
39
62
|
const chunks: Buffer[] = [];
|
|
@@ -48,32 +71,32 @@ export async function readGatewayJson(stream: IncomingMessage): Promise<unknown>
|
|
|
48
71
|
|
|
49
72
|
/** One attempt only. A lost response is never converted to a known rejection. */
|
|
50
73
|
export async function gatewayRequest(socketPath: string, endpoint: string, body?: unknown, options: {
|
|
51
|
-
token?: string; clientId?: string; signal?: AbortSignal; timeoutMs?: number;
|
|
74
|
+
token?: string; clientId?: string; signal?: AbortSignal; timeoutMs?: number; expectedSocket?: GatewaySocketIdentity;
|
|
52
75
|
} = {}): Promise<IncomingMessage> {
|
|
53
76
|
const before = await trustedGatewaySocket(socketPath);
|
|
77
|
+
if (options.expectedSocket) requireSameSocket(options.expectedSocket, before, "rejected");
|
|
54
78
|
const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
|
|
55
79
|
if (data && data.length > MAX_GATEWAY_FRAME) throw new DeliveryError("Gateway frame exceeds size limit", "rejected");
|
|
56
80
|
const { promise, resolve, reject } = Promise.withResolvers<IncomingMessage>();
|
|
57
81
|
let answered = false;
|
|
58
82
|
const req = request({ socketPath, path: endpoint, method: body === undefined ? "GET" : "POST",
|
|
83
|
+
...(options.expectedSocket ? { agent: false } : {}),
|
|
59
84
|
headers: { ...(data ? { "content-type": "application/json", "content-length": data.length } : {}),
|
|
60
85
|
...(options.token ? { authorization: `Bearer ${options.token}` } : {}),
|
|
61
86
|
...(options.clientId ? { "x-gateway-client": options.clientId } : {}) }, signal: options.signal,
|
|
62
87
|
}, response => {
|
|
63
88
|
answered = true;
|
|
64
89
|
clearTimeout(timer);
|
|
65
|
-
void
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
} else resolve(response);
|
|
70
|
-
}, error => { response.destroy(); reject(error); });
|
|
90
|
+
void verifyResponseSocket(socketPath, before).then(
|
|
91
|
+
() => resolve(response),
|
|
92
|
+
error => { response.destroy(); reject(error); },
|
|
93
|
+
);
|
|
71
94
|
});
|
|
72
95
|
const timer = setTimeout(() => req.destroy(new Error("Gateway request timed out")), options.timeoutMs ?? 30_000);
|
|
73
96
|
timer.unref();
|
|
74
|
-
req.on("error",
|
|
97
|
+
req.on("error", cause => {
|
|
75
98
|
clearTimeout(timer);
|
|
76
|
-
if (!answered) reject(new DeliveryError("Gateway request outcome uncertain", "uncertain"));
|
|
99
|
+
if (!answered) reject(new DeliveryError("Gateway request outcome uncertain", "uncertain", undefined, { cause }));
|
|
77
100
|
});
|
|
78
101
|
if (data) req.write(data);
|
|
79
102
|
req.end();
|
|
@@ -82,11 +105,43 @@ export async function gatewayRequest(socketPath: string, endpoint: string, body?
|
|
|
82
105
|
|
|
83
106
|
export async function gatewayCall<T>(socketPath: string, endpoint: string, body?: unknown, options?: Parameters<typeof gatewayRequest>[3]): Promise<T> {
|
|
84
107
|
const response = await gatewayRequest(socketPath, endpoint, body, options);
|
|
85
|
-
const
|
|
108
|
+
const expected = options?.expectedSocket;
|
|
109
|
+
const json = readGatewayJson(response);
|
|
110
|
+
const result = await (expected ? json.finally(() => verifyResponseSocket(socketPath, expected)) : json) as GatewayResult;
|
|
86
111
|
if (!result.ok) throw new DeliveryError(result.error ?? "Gateway rejected operation", result.certainty ?? "uncertain", result.retryAfterMs);
|
|
87
112
|
return result.value as T;
|
|
88
113
|
}
|
|
89
114
|
|
|
115
|
+
/** An attachment and its event stream must authorize on the same verified inode. */
|
|
116
|
+
export async function openGatewayEvents(socketPath: string, attach: {
|
|
117
|
+
readonly token: string; readonly clientId: string; readonly pid: number; readonly resumed: boolean;
|
|
118
|
+
readonly startupHistory: boolean; readonly signal: AbortSignal;
|
|
119
|
+
}): Promise<GatewayEventConnection> {
|
|
120
|
+
const { pid, resumed, startupHistory, signal, ...auth } = attach;
|
|
121
|
+
const socket = await trustedGatewaySocket(socketPath);
|
|
122
|
+
const options = { ...auth, expectedSocket: socket };
|
|
123
|
+
const attachment = await gatewayCall<unknown>(socketPath, "/attach", {
|
|
124
|
+
pid, resumed, ...(startupHistory ? { startupHistory } : {}),
|
|
125
|
+
}, { ...options, signal });
|
|
126
|
+
let reserveHistory = false;
|
|
127
|
+
if (startupHistory) {
|
|
128
|
+
if (!attachment || typeof attachment !== "object" || !("admissionReady" in attachment)
|
|
129
|
+
|| typeof attachment.admissionReady !== "boolean")
|
|
130
|
+
throw new DeliveryError("Gateway does not support ordered startup history. Restart Gateway and HEAD together using the same installation.", "rejected");
|
|
131
|
+
reserveHistory = !attachment.admissionReady;
|
|
132
|
+
}
|
|
133
|
+
// The delivery stream outlives startup; its owner destroys it at detach.
|
|
134
|
+
signal.throwIfAborted();
|
|
135
|
+
const stream = await gatewayRequest(socketPath, "/events", undefined, options);
|
|
136
|
+
if (stream.statusCode !== 200) {
|
|
137
|
+
try {
|
|
138
|
+
const result = await readGatewayJson(stream).finally(() => verifyResponseSocket(socketPath, socket)) as GatewayResult;
|
|
139
|
+
throw new DeliveryError(result.error ?? "Gateway event stream rejected", result.certainty ?? "rejected");
|
|
140
|
+
} finally { stream.destroy(); }
|
|
141
|
+
}
|
|
142
|
+
return { stream, socket, reserveHistory };
|
|
143
|
+
}
|
|
144
|
+
|
|
90
145
|
/** A spool reply carries only correctly indexed local references, never attachment bytes. */
|
|
91
146
|
export async function parseInboundAttachmentReceipt(
|
|
92
147
|
socketPath: string, batch: InboundAttachmentBatch, value: unknown,
|