diff --git a/apps/server/src/provider/Drivers/HermesDriver.ts b/apps/server/src/provider/Drivers/HermesDriver.ts index cdaacaa879..073606beb1 100644 --- a/apps/server/src/provider/Drivers/HermesDriver.ts +++ b/apps/server/src/provider/Drivers/HermesDriver.ts @@ -93,10 +93,17 @@ export const HermesDriver: ProviderDriver = { ? { message: "Hermes is offline. Reconnect its T3 Code gateway plugin." } : {}), availability: "available", + // The slug stays `DEFAULT_HERMES_MODEL` no matter what the plugin + // reports: threads bind to it, and letting it follow Hermes' current + // config would orphan every thread whose model changed on the Hermes + // side. The reported model is used only as the human-facing name, so + // the picker says "gpt-5.6-terra" instead of a generic placeholder. + // Falls back to "Hermes" when no plugin has connected yet or the + // plugin predates the `model` field on `connection.hello`. models: [ { slug: DEFAULT_HERMES_MODEL, - name: "Hermes", + name: status?.model ?? "Hermes", isCustom: false, isDefault: true, capabilities: null, diff --git a/apps/server/src/provider/Layers/HermesAdapter.test.ts b/apps/server/src/provider/Layers/HermesAdapter.test.ts index ea371631b9..2230ac71f6 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.test.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.test.ts @@ -1,13 +1,17 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + ApprovalRequestId, HERMES_GATEWAY_PROTOCOL_VERSION, + HermesGatewayItemId, HermesGatewayRequestId, HermesGatewaySessionId, ProviderInstanceId, ThreadId, TurnId, + type HermesGatewayInstanceStatus, type HermesGatewayT3ToPluginMessage, + type ProviderRuntimeEvent, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -15,6 +19,7 @@ import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Stream from "effect/Stream"; +import { ProviderAdapterRequestError } from "../Errors.ts"; import { HermesGatewayBroker, type HermesGatewayBrokerShape, @@ -26,6 +31,48 @@ import { sanitizeHermesRequestArgs, } from "./HermesAdapter.ts"; +/** + * The reconnect trigger is a broker status transition, so these tests drive the + * broker's two streams directly and never touch a real socket or a clock. + */ +const statusFor = ( + instanceId: ProviderInstanceId, + status: HermesGatewayInstanceStatus["status"], +): HermesGatewayInstanceStatus => ({ + instanceId, + nickname: "Hermes", + status, + connectorUrl: "wss://hermes.example/gateway", + lastConnectedAt: null, + pluginVersion: null, + hermesVersion: null, + model: null, + activeSessionCount: 0, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + capabilities: null, +}); + +const collectEvents = (adapter: { readonly streamEvents: Stream.Stream }) => + Effect.gen(function* () { + const seen: Array = []; + const fiber = yield* Stream.runForEach(adapter.streamEvents, (event) => + Effect.sync(() => { + seen.push(event); + }), + ).pipe(Effect.forkChild({ startImmediately: true })); + return { seen, fiber } as const; + }); + +/** + * Fibers settle by explicit rescheduling, never by sleeping: a sleep would make + * these tests time-dependent and flaky under load. + */ +const drain = Effect.gen(function* () { + for (let attempt = 0; attempt < 12; attempt += 1) { + yield* Effect.yieldNow; + } +}); + it("sanitizes persisted gateway payloads", () => { assert.deepEqual( sanitizeHermesItemData("command_execution", { @@ -373,3 +420,492 @@ it.effect("resumes active Hermes turns for steering and projects authoritative s } }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +/** + * Builds an adapter whose broker connectivity and session.ensure response are + * driven per-test, so a reconnect is expressed as: flip `connected`, decide what + * the plugin reports on resume, publish a status event. + */ +const makeReconnectHarness = (options: { + readonly instanceId: ProviderInstanceId; + readonly threadId: ThreadId; + readonly initialSessionId: HermesGatewaySessionId; +}) => + Effect.gen(function* () { + const sent: Array = []; + const brokerEvents = yield* PubSub.unbounded(); + const brokerStatuses = yield* PubSub.unbounded(); + const state = { + connected: true, + // What the plugin reports on the *next* session.ensure. `undefined` + // activeTurnId means the plugin no longer knows about any running turn. + resumeSessionId: options.initialSessionId, + resumeActiveTurnId: undefined as TurnId | undefined, + resumeFails: false, + }; + const broker: HermesGatewayBrokerShape = { + createEnrollment: () => Effect.die(new Error("unused")), + getInstanceStatus: () => Effect.die(new Error("unused")), + listInstances: Effect.succeed([]), + renameInstance: () => Effect.die(new Error("unused")), + revokeInstance: () => Effect.die(new Error("unused")), + removeInstance: () => Effect.die(new Error("unused")), + registerConnection: () => Effect.die(new Error("unused")), + receive: () => Effect.void, + disconnect: () => Effect.void, + request: (_instanceId, message) => { + sent.push(message); + if (message.type === "session.ensure") { + if (state.resumeFails) { + return Effect.fail( + new ProviderAdapterRequestError({ + provider: "hermes", + method: "session.ensure", + detail: "The Hermes gateway connection disconnected.", + }), + ); + } + return Effect.succeed({ + type: "session.ready", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: message.requestId, + threadId: message.threadId, + sessionId: state.resumeSessionId, + resumed: message.resumeSessionId !== undefined, + ...(state.resumeActiveTurnId !== undefined + ? { activeTurnId: state.resumeActiveTurnId } + : {}), + }); + } + if (message.type === "turn.start" || message.type === "turn.steer") { + return Effect.succeed({ + type: "turn.started", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: message.requestId, + threadId: message.threadId, + sessionId: message.sessionId, + turnId: message.turnId, + }); + } + return Effect.die(new Error(`unexpected request ${message.type}`)); + }, + send: (_instanceId, message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), + isConnected: () => Effect.sync(() => state.connected), + stream: Stream.fromPubSub(brokerEvents), + streamStatuses: Stream.fromPubSub(brokerStatuses), + }; + const adapter = yield* makeHermesAdapter({ instanceId: options.instanceId }).pipe( + Effect.provideService(HermesGatewayBroker, broker), + ); + yield* Effect.yieldNow; + + const disconnect = Effect.gen(function* () { + state.connected = false; + yield* PubSub.publish(brokerStatuses, statusFor(options.instanceId, "offline")); + yield* drain; + }); + const reconnect = Effect.gen(function* () { + state.connected = true; + yield* PubSub.publish(brokerStatuses, statusFor(options.instanceId, "connected")); + yield* drain; + }); + + return { adapter, sent, brokerEvents, state, disconnect, reconnect } as const; + }); + +it.effect("re-issues session.ensure on reconnect and keeps streaming a turn that survived", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_survivor"); + const threadId = ThreadId.make("thread-survivor"); + const initialSessionId = HermesGatewaySessionId.make("session-before-drop"); + const harness = yield* makeReconnectHarness({ instanceId, threadId, initialSessionId }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "long running work" }); + const { seen, fiber } = yield* collectEvents(harness.adapter); + + // The socket drops mid-turn. Hermes keeps generating: its plugin still + // holds the turn, so session.ensure reports the same activeTurnId back. + yield* harness.disconnect; + harness.state.resumeActiveTurnId = started.turnId; + yield* harness.reconnect; + + const resumeEnsure = harness.sent.filter((message) => message.type === "session.ensure"); + assert.equal(resumeEnsure.length, 2, "reconnect must re-issue session.ensure"); + const resume = resumeEnsure[1]; + assert.equal( + resume?.type === "session.ensure" ? resume.resumeSessionId : undefined, + initialSessionId, + "resume must carry the stored cursor", + ); + + // The turn survived, so nothing disruptive is emitted and the session keeps + // pointing at the same turn. + assert.isUndefined( + seen.find((event) => event.type === "turn.completed" || event.type === "turn.aborted"), + ); + const session = (yield* harness.adapter.listSessions())[0]; + assert.equal(session?.status, "running"); + assert.equal(session?.activeTurnId, started.turnId); + + // Deltas for the surviving turn still land after the reconnect. + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "content.delta", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId: initialSessionId, + turnId: started.turnId, + streamKind: "assistant_text", + delta: "still going", + }, + }); + yield* drain; + assert.isDefined(seen.find((event) => event.type === "content.delta")); + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("settles the thread when a turn does not survive the reconnect", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_dead_turn"); + const threadId = ThreadId.make("thread-dead-turn"); + const initialSessionId = HermesGatewaySessionId.make("session-dead-turn"); + const harness = yield* makeReconnectHarness({ instanceId, threadId, initialSessionId }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "work that dies" }); + const { seen, fiber } = yield* collectEvents(harness.adapter); + + // The plugin restarted: it comes back with a fresh session and no active + // turn. Hermes will never send a terminal frame for the old turn, so the + // adapter must produce one or the thread hangs forever. + yield* harness.disconnect; + harness.state.resumeSessionId = HermesGatewaySessionId.make("session-after-restart"); + harness.state.resumeActiveTurnId = undefined; + yield* harness.reconnect; + + const terminal = seen.find((event) => event.type === "turn.completed"); + assert.isDefined(terminal, "a dead turn must be settled with a terminal event"); + if (terminal?.type === "turn.completed") { + assert.equal(terminal.turnId, started.turnId); + assert.equal(terminal.payload.state, "failed"); + assert.include(terminal.payload.errorMessage ?? "", "did not survive"); + } + const session = (yield* harness.adapter.listSessions())[0]; + assert.isUndefined(session?.activeTurnId); + assert.equal(session?.status, "error"); + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("settles the thread when session.ensure fails on reconnect", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_resume_failed"); + const threadId = ThreadId.make("thread-resume-failed"); + const initialSessionId = HermesGatewaySessionId.make("session-resume-failed"); + const harness = yield* makeReconnectHarness({ instanceId, threadId, initialSessionId }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "work" }); + const { seen, fiber } = yield* collectEvents(harness.adapter); + + yield* harness.disconnect; + harness.state.resumeFails = true; + yield* harness.reconnect; + + const terminal = seen.find((event) => event.type === "turn.completed"); + assert.isDefined(terminal, "a failed resume must settle rather than hang"); + if (terminal?.type === "turn.completed") { + assert.equal(terminal.turnId, started.turnId); + assert.equal(terminal.payload.state, "failed"); + assert.include(terminal.payload.errorMessage ?? "", "could not resume"); + } + assert.isUndefined((yield* harness.adapter.listSessions())[0]?.activeTurnId); + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("cancels pending approvals and user input on reconnect without deciding", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_pending"); + const threadId = ThreadId.make("thread-pending"); + const sessionId = HermesGatewaySessionId.make("session-pending"); + const harness = yield* makeReconnectHarness({ + instanceId, + threadId, + initialSessionId: sessionId, + }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "needs approval" }); + const { seen, fiber } = yield* collectEvents(harness.adapter); + + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "request.opened", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId, + turnId: started.turnId, + requestId: HermesGatewayRequestId.make("approval-in-flight"), + requestType: "command_execution_approval", + detail: "Hermes wants to run a command", + }, + }); + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "user-input.requested", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId, + turnId: started.turnId, + requestId: HermesGatewayRequestId.make("clarify-in-flight"), + questions: [ + { + id: "clarify-in-flight", + header: "Hermes", + question: "Which branch?", + options: [{ label: "main", description: "main" }], + multiSelect: false, + }, + ], + }, + }); + yield* drain; + + // The plugin restarts and forgets both requests; answering them afterwards + // would come back `request-not-found` and park the turn forever. + yield* harness.disconnect; + harness.state.resumeActiveTurnId = started.turnId; + yield* harness.reconnect; + + const resolvedApproval = seen.find( + (event) => event.type === "request.resolved" && event.requestId === "approval-in-flight", + ); + assert.isDefined(resolvedApproval, "the pending approval must be closed out"); + if (resolvedApproval?.type === "request.resolved") { + assert.equal(resolvedApproval.payload.requestType, "command_execution_approval"); + // Explicit product decision: never approve or deny on the user's behalf. + assert.isUndefined(resolvedApproval.payload.decision); + } + const resolvedUserInput = seen.find( + (event) => event.type === "user-input.resolved" && event.requestId === "clarify-in-flight", + ); + assert.isDefined(resolvedUserInput, "the pending user-input request must be closed out"); + if (resolvedUserInput?.type === "user-input.resolved") { + assert.deepEqual(resolvedUserInput.payload.answers, {}); + } + const warning = seen.find((event) => event.type === "runtime.warning"); + assert.isDefined(warning, "the cancellation must be visible in the thread"); + if (warning?.type === "runtime.warning") { + assert.include(warning.payload.message, "cancelled"); + } + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("fails sends immediately and actionably while the gateway is offline", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_offline"); + const threadId = ThreadId.make("thread-offline"); + const sessionId = HermesGatewaySessionId.make("session-offline"); + const harness = yield* makeReconnectHarness({ + instanceId, + threadId, + initialSessionId: sessionId, + }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + yield* harness.disconnect; + let sentBefore = harness.sent.length; + + // turn.start path. + const startError = yield* Effect.flip( + harness.adapter.sendTurn({ threadId, input: "queue me" }), + ); + assert.equal(startError._tag, "ProviderAdapterRequestError"); + if (startError._tag === "ProviderAdapterRequestError") { + assert.include(startError.detail, "Hermes is offline"); + assert.include(startError.detail, instanceId); + assert.include(startError.detail, "hermes gateway restart"); + } + // Nothing was queued or dispatched — the failure is immediate, not a + // deferred send that lands minutes later against a stale thread. + assert.equal(harness.sent.length, sentBefore); + + // With a turn actually running, the steer and interactive paths must fail + // just as clearly rather than parking on the broker's request timeout. + yield* harness.reconnect; + yield* harness.adapter.sendTurn({ threadId, input: "real work" }); + yield* harness.disconnect; + sentBefore = harness.sent.length; + + const steerError = yield* Effect.flip( + harness.adapter.sendTurn({ threadId, input: "steer me" }), + ); + assert.equal(steerError._tag, "ProviderAdapterRequestError"); + if (steerError._tag === "ProviderAdapterRequestError") { + assert.include(steerError.detail, "Hermes is offline"); + } + + const interruptError = yield* Effect.flip(harness.adapter.interruptTurn(threadId)); + assert.equal(interruptError._tag, "ProviderAdapterRequestError"); + + const approvalError = yield* Effect.flip( + harness.adapter.respondToRequest( + threadId, + ApprovalRequestId.make("approval-while-offline"), + "accept", + ), + ); + assert.equal(approvalError._tag, "ProviderAdapterRequestError"); + + const userInputError = yield* Effect.flip( + harness.adapter.respondToUserInput( + threadId, + ApprovalRequestId.make("clarify-while-offline"), + {}, + ), + ); + assert.equal(userInputError._tag, "ProviderAdapterRequestError"); + + assert.equal(harness.sent.length, sentBefore); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("keeps the session on an undeliverable stop so Hermes is not orphaned", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_stop_offline"); + const threadId = ThreadId.make("thread-stop-offline"); + const sessionId = HermesGatewaySessionId.make("session-stop-offline"); + const harness = yield* makeReconnectHarness({ + instanceId, + threadId, + initialSessionId: sessionId, + }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "work" }); + const { seen, fiber } = yield* collectEvents(harness.adapter); + yield* harness.disconnect; + + const stopError = yield* Effect.flip(harness.adapter.stopSession(threadId)); + assert.equal(stopError._tag, "ProviderAdapterRequestError"); + if (stopError._tag === "ProviderAdapterRequestError") { + assert.include(stopError.detail, "Hermes is offline"); + } + // The stop never reached Hermes, so dropping local state would orphan a + // thread that is still running on the far side. + assert.isTrue(yield* harness.adapter.hasSession(threadId)); + + // stopAll (the shutdown finalizer) must not throw away the session either. + yield* harness.adapter.stopAll(); + assert.isTrue(yield* harness.adapter.hasSession(threadId)); + + // Frames that arrive for the still-live session are forwarded with full + // context rather than dropped or forwarded contextless. + yield* harness.reconnect; + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "content.delta", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId, + turnId: started.turnId, + streamKind: "assistant_text", + delta: "still running on Hermes", + }, + }); + yield* drain; + assert.isDefined(seen.find((event) => event.type === "content.delta")); + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("drops frames for a session it no longer tracks", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_forgotten"); + const threadId = ThreadId.make("thread-forgotten"); + const sessionId = HermesGatewaySessionId.make("session-forgotten"); + const harness = yield* makeReconnectHarness({ + instanceId, + threadId, + initialSessionId: sessionId, + }); + + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + const started = yield* harness.adapter.sendTurn({ threadId, input: "work" }); + yield* harness.adapter.stopSession(threadId); + const { seen, fiber } = yield* collectEvents(harness.adapter); + + // Hermes had frames in flight when the stop landed. With no session to + // match, forwarding them would inject content into a forgotten thread. + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "content.delta", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId, + turnId: started.turnId, + streamKind: "assistant_text", + delta: "orphaned text", + }, + }); + yield* PubSub.publish(harness.brokerEvents, { + instanceId, + message: { + type: "item.completed", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId, + sessionId, + turnId: started.turnId, + itemId: HermesGatewayItemId.make("orphan-item"), + itemType: "command_execution", + }, + }); + yield* drain; + + assert.equal(seen.length, 0, "frames for an untracked session must not be forwarded"); + + yield* Fiber.interrupt(fiber); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/provider/Layers/HermesAdapter.ts b/apps/server/src/provider/Layers/HermesAdapter.ts index 5f3139f270..85281eece4 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.ts @@ -9,6 +9,7 @@ import { RuntimeRequestId, ThreadId, TurnId, + type CanonicalRequestType, type HermesGatewayPluginToT3Message, type ProviderInstanceId, type ProviderRuntimeEvent, @@ -32,13 +33,48 @@ import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts"; const PROVIDER = ProviderDriverKind.make("hermes"); const isResumeCursor = Schema.is(HermesGatewayResumeCursor); +/** + * Hermes never queues. When the gateway socket is down there is nothing on the + * far side to accept work, and a queued turn would silently start minutes later + * against a thread the user has moved on from. Every send path fails + * immediately with this text so the failure names the fix rather than showing + * up as a generic protocol error or a 30s request timeout. + */ +const offlineDetail = (instanceId: ProviderInstanceId) => + `Hermes is offline — the '${instanceId}' gateway plugin is not connected. Start the gateway on the Hermes host (\`hermes gateway restart\`), then retry.`; + +/** + * `turns` exists only to answer `readThread`, which no Hermes call site reaches + * today. Retaining every completed item for the life of the process is an + * unbounded leak in service of that dead path, so the accumulator keeps a + * hard-capped tail of the most recent turns/items and `readThread` reports what + * it still holds. Raising these bounds is a deliberate decision, not something + * that should drift with thread length. + */ +const MAX_RETAINED_TURNS = 8; +const MAX_RETAINED_ITEMS_PER_TURN = 32; + type HermesAdapterShape = ProviderAdapterShape< ProviderAdapterRequestError | ProviderAdapterSessionNotFoundError | ProviderAdapterValidationError >; +interface PendingInteraction { + readonly requestId: string; + readonly turnId: TurnId; + readonly requestType: CanonicalRequestType; +} + interface SessionContext { - readonly hermesSessionId: HermesGatewaySessionId; + hermesSessionId: HermesGatewaySessionId; readonly turns: Array<{ readonly id: TurnId; readonly items: Array }>; + /** + * Approval and user-input requests T3 has shown but Hermes has not resolved. + * The plugin holds its side in plain dicts, so a plugin restart forgets them + * and any decision sent afterwards comes back `request-not-found`, parking + * the turn forever. Tracking them here lets a reconnect close them out. + */ + readonly pendingApprovals: Map; + readonly pendingUserInputs: Map; session: ProviderSession; } @@ -162,6 +198,18 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input return context; }); + const requireConnected = (method: string) => + Effect.gen(function* (): Effect.fn.Return { + const connected = yield* broker.isConnected(input.instanceId); + if (!connected) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method, + detail: offlineDetail(input.instanceId), + }); + } + }); + const updateSession = (context: SessionContext, patch: Partial) => { context.session = { ...context.session, @@ -170,6 +218,40 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input }; }; + const clearActiveTurn = ( + context: SessionContext, + patch: Omit, "activeTurnId">, + ) => { + const { activeTurnId: _activeTurnId, ...session } = context.session; + context.session = { ...session, ...patch, updatedAt: nowIso() }; + }; + + const trackTurn = (context: SessionContext, turnId: TurnId) => { + if (context.turns.some((turn) => turn.id === turnId)) return; + context.turns.push({ id: turnId, items: [] }); + while (context.turns.length > MAX_RETAINED_TURNS) context.turns.shift(); + }; + + const recordCompletedItem = (context: SessionContext, turnId: string, payload: unknown) => { + const turn = context.turns.find((entry) => entry.id === turnId); + if (!turn) return; + turn.items.push(payload); + while (turn.items.length > MAX_RETAINED_ITEMS_PER_TURN) turn.items.shift(); + }; + + /** + * Every session-scoped plugin frame names the session it belongs to. If we do + * not hold that session — because the thread was stopped, or the plugin is + * still emitting for a session we already tore down — the frame has no thread + * context on this side, and forwarding it would inject deltas and item rows + * into a thread T3 no longer tracks. `session.exited` always guarded this; + * the guard belongs on every session-scoped frame. + */ + const contextMatchesSession = ( + context: SessionContext | undefined, + message: { readonly sessionId: HermesGatewaySessionId }, + ): context is SessionContext => context?.hermesSessionId === message.sessionId; + const toRuntimeEvent = (message: PluginMessage) => Effect.gen(function* (): Effect.fn.Return< ProviderRuntimeEvent | undefined, @@ -177,29 +259,26 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input > { if (!("threadId" in message)) return undefined; const context = sessions.get(message.threadId); - const base = yield* eventBase(message); switch (message.type) { case "session.ready": return undefined; case "turn.started": { - if (context) { - updateSession(context, { - status: "running", - activeTurnId: TurnId.make(message.turnId), - }); - if (!context.turns.some((turn) => turn.id === message.turnId)) { - context.turns.push({ id: TurnId.make(message.turnId), items: [] }); - } - } + if (!contextMatchesSession(context, message)) return undefined; + updateSession(context, { + status: "running", + activeTurnId: TurnId.make(message.turnId), + }); + trackTurn(context, TurnId.make(message.turnId)); return { - ...base, + ...(yield* eventBase(message)), type: "turn.started", payload: {}, }; } - case "content.delta": + case "content.delta": { + if (!contextMatchesSession(context, message)) return undefined; return { - ...base, + ...(yield* eventBase(message)), type: "content.delta", payload: { streamKind: message.streamKind, @@ -207,9 +286,11 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input ...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}), }, }; - case "content.snapshot": + } + case "content.snapshot": { + if (!contextMatchesSession(context, message)) return undefined; return { - ...base, + ...(yield* eventBase(message)), type: "content.snapshot", payload: { streamKind: message.streamKind, @@ -217,9 +298,11 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input ...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}), }, }; + } case "item.started": case "item.updated": case "item.completed": { + if (!contextMatchesSession(context, message)) return undefined; const data = sanitizeHermesItemData(message.itemType, message.data); const payload = { itemType: message.itemType, @@ -228,14 +311,21 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input ...(message.detail ? { detail: message.detail } : {}), ...(data ? { data } : {}), }; - const turn = context?.turns.find((entry) => entry.id === message.turnId); - if (turn && message.type === "item.completed") turn.items.push(payload); - return { ...base, type: message.type, payload }; + if (message.type === "item.completed") { + recordCompletedItem(context, message.turnId, payload); + } + return { ...(yield* eventBase(message)), type: message.type, payload }; } case "request.opened": { + if (!contextMatchesSession(context, message)) return undefined; + context.pendingApprovals.set(message.requestId, { + requestId: message.requestId, + turnId: TurnId.make(message.turnId), + requestType: message.requestType, + }); const args = sanitizeHermesRequestArgs(message.requestType, message.args); return { - ...base, + ...(yield* eventBase(message)), type: "request.opened", payload: { requestType: message.requestType, @@ -244,35 +334,47 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input }, }; } - case "request.resolved": + case "request.resolved": { + if (!contextMatchesSession(context, message)) return undefined; + context.pendingApprovals.delete(message.requestId); return { - ...base, + ...(yield* eventBase(message)), type: "request.resolved", payload: { requestType: message.requestType, ...(message.decision ? { decision: message.decision } : {}), }, }; - case "user-input.requested": + } + case "user-input.requested": { + if (!contextMatchesSession(context, message)) return undefined; + context.pendingUserInputs.set(message.requestId, { + requestId: message.requestId, + turnId: TurnId.make(message.turnId), + requestType: "tool_user_input", + }); return { - ...base, + ...(yield* eventBase(message)), type: "user-input.requested", payload: { questions: message.questions }, }; - case "user-input.resolved": + } + case "user-input.resolved": { + if (!contextMatchesSession(context, message)) return undefined; + context.pendingUserInputs.delete(message.requestId); return { - ...base, + ...(yield* eventBase(message)), type: "user-input.resolved", payload: { answers: message.answers }, }; - case "turn.completed": - if (context?.session.activeTurnId === message.turnId) { - updateSession(context, { status: message.state === "failed" ? "error" : "ready" }); - const { activeTurnId: _activeTurnId, ...session } = context.session; - context.session = session; + } + case "turn.completed": { + if (!contextMatchesSession(context, message)) return undefined; + if (context.session.activeTurnId === message.turnId) { + clearActiveTurn(context, { status: message.state === "failed" ? "error" : "ready" }); } return { - ...base, + ...(yield* eventBase(message)), type: "turn.completed", payload: { state: message.state, @@ -280,26 +382,26 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input ...(message.errorMessage ? { errorMessage: message.errorMessage } : {}), }, }; - case "turn.aborted": - if (context?.session.activeTurnId === message.turnId) { - const { activeTurnId: _activeTurnId, ...session } = context.session; - context.session = { ...session, status: "ready", updatedAt: nowIso() }; + } + case "turn.aborted": { + if (!contextMatchesSession(context, message)) return undefined; + if (context.session.activeTurnId === message.turnId) { + clearActiveTurn(context, { status: "ready" }); } return { - ...base, + ...(yield* eventBase(message)), type: "turn.aborted", payload: { reason: message.reason }, }; - case "session.exited": - if (!context || context.hermesSessionId !== message.sessionId) { - return undefined; - } - const { activeTurnId: _activeTurnId, ...session } = context.session; - context.session = { - ...session, - status: message.recoverable ? "error" : "closed", - updatedAt: nowIso(), - }; + } + case "session.exited": { + if (!contextMatchesSession(context, message)) return undefined; + clearActiveTurn(context, { status: message.recoverable ? "error" : "closed" }); + const base = yield* eventBase(message); + // A session Hermes has exited is gone on both sides. Dropping it here + // is what keeps the sessions map from growing without bound across a + // long-lived process's reconnect cycles. + sessions.delete(message.threadId); return { ...base, type: "session.exited", @@ -309,6 +411,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input exitKind: message.recoverable ? "error" : "graceful", }, }; + } default: return undefined; } @@ -324,16 +427,183 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input Effect.forkScoped, ); - const startSession: HermesAdapterShape["startSession"] = Effect.fn("startSession")( - function* (sessionInput) { - const connected = yield* broker.isConnected(input.instanceId); - if (!connected) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.ensure", - detail: `Hermes gateway instance '${input.instanceId}' is offline.`, + /** + * Close out every interaction the user could still be looking at. + * + * The plugin keeps `_approval_requests` / `_user_input_requests` in plain + * dicts, so a plugin restart forgets them: any decision the user makes + * afterwards is answered `request-not-found` and the turn waits on a reply + * that can never arrive. We deliberately do not decide on the user's behalf — + * each request is marked resolved with no decision, which clears the pending + * badge, and a warning row explains why it disappeared. + */ + const cancelPendingInteractions = (context: SessionContext, reason: string) => + Effect.gen(function* () { + const approvals = Array.from(context.pendingApprovals.values()); + const userInputs = Array.from(context.pendingUserInputs.values()); + context.pendingApprovals.clear(); + context.pendingUserInputs.clear(); + if (approvals.length === 0 && userInputs.length === 0) return; + for (const pending of approvals) { + yield* emit({ + ...(yield* eventBase({ + threadId: context.session.threadId, + turnId: pending.turnId, + requestId: pending.requestId, + })), + type: "request.resolved", + payload: { requestType: pending.requestType }, }); } + for (const pending of userInputs) { + yield* emit({ + ...(yield* eventBase({ + threadId: context.session.threadId, + turnId: pending.turnId, + requestId: pending.requestId, + })), + type: "user-input.resolved", + payload: { answers: {} }, + }); + } + yield* emit({ + ...(yield* eventBase({ threadId: context.session.threadId })), + type: "runtime.warning", + payload: { + message: `${approvals.length + userInputs.length} pending Hermes request(s) were cancelled without a decision: ${reason} Nothing was approved or denied on your behalf — ask again to re-run the step.`, + }, + }); + }); + + /** + * Settle a thread whose turn did not survive the reconnect. + * + * Without this the turn stays "running" forever: Hermes never sends a + * terminal frame for a turn its restarted plugin no longer knows about, and + * orchestration's conflict gate rejects any later frame naming it. A failed + * `turn.completed` is the terminal event orchestration already folds into + * thread state. + */ + const settleDeadTurn = (context: SessionContext, turnId: TurnId, message: string) => + Effect.gen(function* () { + clearActiveTurn(context, { status: "error", lastError: message }); + yield* emit({ + ...(yield* eventBase({ threadId: context.session.threadId, turnId })), + type: "turn.completed", + payload: { state: "failed", errorMessage: message }, + }); + }); + + const resumeSessionAfterReconnect = (context: SessionContext) => + Effect.gen(function* () { + const threadId = context.session.threadId; + const previousTurnId = context.session.activeTurnId; + yield* cancelPendingInteractions( + context, + "the Hermes gateway reconnected and the plugin no longer holds them.", + ); + const outcome = yield* broker + .request(input.instanceId, { + type: "session.ensure", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: yield* requestId, + threadId, + resumeSessionId: context.hermesSessionId, + }) + .pipe(Effect.result); + + // Anything other than a clean session.ready leaves us unable to tell + // whether Hermes is still generating, with no channel to ask. Leaving the + // thread "running" would hang it, so it settles with the reason spelled + // out instead. + const failure = + outcome._tag === "Failure" + ? `Hermes could not resume this thread after reconnecting: ${outcome.failure.detail}` + : outcome.success.type === "protocol.error" + ? `Hermes rejected the resume for this thread: ${outcome.success.message}` + : outcome.success.type !== "session.ready" || outcome.success.threadId !== threadId + ? `Hermes returned '${outcome.success.type}' instead of session.ready while resuming this thread.` + : undefined; + if (failure !== undefined) { + if (previousTurnId) return yield* settleDeadTurn(context, previousTurnId, failure); + updateSession(context, { status: "error", lastError: failure }); + return; + } + if (outcome._tag !== "Success" || outcome.success.type !== "session.ready") return; + const ready = outcome.success; + + // The session may have been stopped or exited while the request was in + // flight; do not resurrect it. + if (sessions.get(threadId) !== context) return; + + // Hermes owns the session id and a restarted plugin mints a new one. + // Adopting it is what keeps the inbound context guard matching. + context.hermesSessionId = ready.sessionId; + updateSession(context, { + resumeCursor: { + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + sessionId: ready.sessionId, + } satisfies HermesGatewayResumeCursor, + }); + + const activeTurnId = ready.activeTurnId; + if (activeTurnId !== undefined) { + // The turn outlived the socket. Keep streaming into it and emit nothing + // disruptive — what follows belongs to the turn the UI already renders. + updateSession(context, { status: "running", activeTurnId }); + trackTurn(context, activeTurnId); + return; + } + + if (previousTurnId) { + yield* settleDeadTurn( + context, + previousTurnId, + "The Hermes gateway reconnected without this turn — it did not survive the disconnect.", + ); + return; + } + updateSession(context, { status: "ready" }); + }); + + /** + * The reconnect trigger. Protocol v2 already carries `activeTurnId` on + * `session.ready` for exactly this case, but nothing re-issued + * `session.ensure` after a drop — so a surviving turn's eventual + * `turn.completed` arrived for a turn orchestration had written off, was + * rejected by its conflict gate, and the thread never settled. + */ + let connected = yield* broker.isConnected(input.instanceId); + yield* broker.streamStatuses.pipe( + Stream.filter((status) => status.instanceId === input.instanceId), + Stream.runForEach((status) => + Effect.gen(function* () { + const nowConnected = status.status === "connected"; + const reconnected = nowConnected && !connected; + connected = nowConnected; + if (!reconnected) return; + yield* Effect.forEach( + Array.from(sessions.values()), + (context) => + resumeSessionAfterReconnect(context).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider.hermes.resume-after-reconnect-failed", { + instanceId: input.instanceId, + threadId: context.session.threadId, + cause, + }), + ), + ), + { discard: true }, + ); + }), + ), + Effect.forkScoped, + ); + + const startSession: HermesAdapterShape["startSession"] = Effect.fn("startSession")( + function* (sessionInput) { + yield* requireConnected("session.ensure"); if (sessionInput.providerInstanceId && sessionInput.providerInstanceId !== input.instanceId) { return yield* new ProviderAdapterValidationError({ provider: PROVIDER, @@ -393,6 +663,8 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input session, hermesSessionId: response.sessionId, turns: activeTurnId === undefined ? [] : [{ id: activeTurnId, items: [] }], + pendingApprovals: new Map(), + pendingUserInputs: new Map(), }); yield* emit({ ...(yield* eventBase({ threadId: sessionInput.threadId })), @@ -429,6 +701,10 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input }); } const activeTurnId = context.session.activeTurnId; + const method = activeTurnId ? "turn.steer" : "turn.start"; + // Checked before the request so an offline gateway fails immediately with + // an actionable message instead of parking on the broker's request timeout. + yield* requireConnected(method); const turnId = activeTurnId ?? TurnId.make(`hermes-turn-${yield* randomId}`); const outboundRequestId = yield* requestId; const response = yield* broker.request(input.instanceId, { @@ -443,7 +719,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input if (response.type !== "turn.started") { return yield* new ProviderAdapterRequestError({ provider: PROVIDER, - method: activeTurnId ? "turn.steer" : "turn.start", + method, detail: response.type === "protocol.error" ? response.message @@ -451,6 +727,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input }); } updateSession(context, { status: "running", activeTurnId: turnId }); + trackTurn(context, turnId); return { threadId: turnInput.threadId, turnId, @@ -468,6 +745,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input const context = yield* findContext(threadId); const turnId = selectedTurnId ?? context.session.activeTurnId; if (!turnId) return; + yield* requireConnected("turn.interrupt"); yield* broker.send(input.instanceId, { type: "turn.interrupt", protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, @@ -487,6 +765,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input issue: "The Hermes session has no active turn.", }); } + yield* requireConnected("approval.respond"); yield* broker.send(input.instanceId, { type: "approval.respond", protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, @@ -496,6 +775,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input turnId: context.session.activeTurnId, decision, }); + context.pendingApprovals.delete(selectedRequestId); }), respondToUserInput: (threadId, selectedRequestId, answers) => Effect.gen(function* () { @@ -507,6 +787,7 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input issue: "The Hermes session has no active turn.", }); } + yield* requireConnected("user-input.respond"); yield* broker.send(input.instanceId, { type: "user-input.respond", protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, @@ -516,19 +797,31 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input turnId: context.session.activeTurnId, answers, }); + context.pendingUserInputs.delete(selectedRequestId); }), stopSession: (threadId) => Effect.gen(function* () { const context = yield* findContext(threadId); - if (yield* broker.isConnected(input.instanceId)) { - yield* broker.send(input.instanceId, { - type: "session.stop", - protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, - requestId: yield* requestId, - threadId, - sessionId: context.hermesSessionId, + if (!(yield* broker.isConnected(input.instanceId))) { + // The stop was never delivered: Hermes still owns this thread and + // keeps generating. Deleting our state here would orphan it — frames + // arriving after a reconnect would have no session to match, and the + // user would have no way to stop it. Keep the session so the reconnect + // path can resume it and a later stop can actually land. + updateSession(context, { status: "error", lastError: offlineDetail(input.instanceId) }); + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session.stop", + detail: offlineDetail(input.instanceId), }); } + yield* broker.send(input.instanceId, { + type: "session.stop", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: yield* requestId, + threadId, + sessionId: context.hermesSessionId, + }); updateSession(context, { status: "closed" }); sessions.delete(threadId); }), @@ -538,6 +831,8 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input findContext(threadId).pipe( Effect.map((context) => ({ threadId, + // Bounded to the most recent turns/items — older history lives in the + // orchestration projections, not in adapter memory. turns: context.turns, })), ), @@ -554,9 +849,23 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input ), ), stopAll: () => - Effect.forEach(Array.from(sessions.keys()), (threadId) => adapter.stopSession(threadId), { - discard: true, - }), + Effect.forEach( + Array.from(sessions.keys()), + (threadId) => + // A stop that could not be delivered (typically: the gateway is + // offline) must not abort the sweep or fail shutdown. The session is + // deliberately left in place rather than orphaned. + adapter.stopSession(threadId).pipe( + Effect.catchTag("ProviderAdapterRequestError", (error) => + Effect.logWarning("provider.hermes.stop-session-undeliverable", { + instanceId: input.instanceId, + threadId, + detail: error.detail, + }), + ), + ), + { discard: true }, + ), streamEvents: Stream.fromPubSub(events), }; diff --git a/apps/server/src/provider/Layers/HermesConnectionRegistry.ts b/apps/server/src/provider/Layers/HermesConnectionRegistry.ts new file mode 100644 index 0000000000..944af98671 --- /dev/null +++ b/apps/server/src/provider/Layers/HermesConnectionRegistry.ts @@ -0,0 +1,209 @@ +/** + * Live {@link HermesConnectionRegistry}. See the service module for why this + * state is memory-only and how generation fencing works. + * + * @module Layers/HermesConnectionRegistry + */ +import type { ProviderInstanceId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; + +import type { + HermesActiveConnection, + HermesConnectionRegistry, + HermesInstanceLiveness, + HermesLivenessStatusFields, + HermesObservedConnection, +} from "../Services/HermesConnectionRegistry.ts"; + +/** Strip the transport/scope/generation from a connection to keep as `lastSeen`. */ +const toObserved = (connection: HermesActiveConnection): HermesObservedConnection => ({ + pluginVersion: connection.pluginVersion, + hermesVersion: connection.hermesVersion, + capabilities: connection.capabilities, + model: connection.model, + connectedAt: connection.connectedAt, + activeSessionCount: connection.activeSessionCount, +}); + +/** + * Project liveness into the status fields it owns. Prefers the live connection, + * falls back to `lastSeen`, and finally to whatever the incompatible plugin + * advertised. + */ +export const livenessStatusFields = ( + liveness: HermesInstanceLiveness | undefined, +): HermesLivenessStatusFields => { + const observed = liveness?.connection ?? liveness?.lastSeen; + return { + lastConnectedAt: observed?.connectedAt ?? null, + pluginVersion: observed?.pluginVersion ?? liveness?.upgradeRequired?.pluginVersion ?? null, + hermesVersion: observed?.hermesVersion ?? liveness?.upgradeRequired?.hermesVersion ?? null, + model: observed?.model ?? liveness?.upgradeRequired?.model ?? null, + activeSessionCount: liveness?.connection?.activeSessionCount ?? 0, + protocolVersion: + observed?.capabilities.protocolVersion ?? liveness?.upgradeRequired?.protocolVersion ?? null, + capabilities: observed?.capabilities ?? null, + connected: liveness?.connection !== undefined, + upgradeRequired: liveness?.upgradeRequired !== undefined, + }; +}; + +export const makeHermesConnectionRegistry = Effect.gen(function* () { + const states = yield* Ref.make(new Map()); + const generation = yield* Ref.make(0); + + /** Write liveness for one instance, dropping the entry when it goes empty. */ + const setLiveness = ( + current: ReadonlyMap, + instanceId: ProviderInstanceId, + liveness: HermesInstanceLiveness, + ) => { + const next = new Map(current); + if ( + liveness.connection === undefined && + liveness.lastSeen === undefined && + liveness.upgradeRequired === undefined + ) { + next.delete(instanceId); + } else { + next.set(instanceId, liveness); + } + return next; + }; + + const liveness = (instanceId: ProviderInstanceId) => + Ref.get(states).pipe(Effect.map((current) => current.get(instanceId))); + + const accept: HermesConnectionRegistry["accept"] = (input) => + Effect.gen(function* () { + const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1); + // The connection scope is a child of nothing in particular: it is closed + // explicitly on disconnect/replace so per-connection fibers (ping) die + // exactly with the connection they belong to. + const scope = yield* Scope.make(); + const connection: HermesActiveConnection = { + ...input.observed, + generation: nextGeneration, + transport: input.transport, + scope, + }; + + const displaced = yield* Ref.modify(states, (current) => { + const found = current.get(input.instanceId); + return [ + found?.connection, + setLiveness(current, input.instanceId, { + connection, + lastSeen: toObserved(connection), + // Accepting a compatible connection clears any stale + // upgrade-required observation for this instance. + upgradeRequired: undefined, + }), + ] as const; + }); + + return { generation: nextGeneration, displaced }; + }); + + const markUpgradeRequired: HermesConnectionRegistry["markUpgradeRequired"] = (input) => + Ref.modify(states, (current) => { + const found = current.get(input.instanceId); + return [ + found?.connection, + setLiveness(current, input.instanceId, { + connection: undefined, + lastSeen: found?.lastSeen, + upgradeRequired: input.upgradeRequired, + }), + ] as const; + }); + + const recordSessionCount: HermesConnectionRegistry["recordSessionCount"] = ( + registration, + activeSessionCount, + ) => + Ref.modify(states, (current) => { + const found = current.get(registration.instanceId); + // Fence inside the update so a replacement that lands between a read and + // this write cannot be clobbered. + if (found?.connection?.generation !== registration.generation) { + return [false, current] as const; + } + const connection: HermesActiveConnection = { ...found.connection, activeSessionCount }; + return [ + true, + setLiveness(current, registration.instanceId, { + ...found, + connection, + lastSeen: toObserved(connection), + }), + ] as const; + }); + + const disconnect: HermesConnectionRegistry["disconnect"] = (registration) => + Effect.gen(function* () { + const retired = yield* Ref.modify(states, (current) => { + const found = current.get(registration.instanceId); + if (found?.connection?.generation !== registration.generation) { + return [undefined, current] as const; + } + return [ + found.connection, + setLiveness(current, registration.instanceId, { + connection: undefined, + lastSeen: toObserved(found.connection), + upgradeRequired: found.upgradeRequired, + }), + ] as const; + }); + if (retired) yield* Scope.close(retired.scope, Exit.void).pipe(Effect.ignore); + return retired; + }); + + const clearConnection: HermesConnectionRegistry["clearConnection"] = (instanceId) => + Effect.gen(function* () { + const cleared = yield* Ref.modify(states, (current) => { + const found = current.get(instanceId); + if (!found?.connection) return [undefined, current] as const; + return [ + found.connection, + setLiveness(current, instanceId, { + connection: undefined, + lastSeen: toObserved(found.connection), + upgradeRequired: found.upgradeRequired, + }), + ] as const; + }); + if (cleared) yield* Scope.close(cleared.scope, Exit.void).pipe(Effect.ignore); + return cleared; + }); + + const forget = (instanceId: ProviderInstanceId) => + Effect.gen(function* () { + const dropped = yield* Ref.modify(states, (current) => { + const found = current.get(instanceId); + if (!found) return [undefined, current] as const; + const next = new Map(current); + next.delete(instanceId); + return [found.connection, next] as const; + }); + if (dropped) yield* Scope.close(dropped.scope, Exit.void).pipe(Effect.ignore); + }); + + return { + liveness, + accept, + markUpgradeRequired, + recordSessionCount, + disconnect, + clearConnection, + forget, + isConnected: (instanceId) => + liveness(instanceId).pipe(Effect.map((found) => found?.connection !== undefined)), + transport: (instanceId) => + liveness(instanceId).pipe(Effect.map((found) => found?.connection?.transport)), + } satisfies HermesConnectionRegistry; +}); diff --git a/apps/server/src/provider/Layers/HermesEnrollmentStore.ts b/apps/server/src/provider/Layers/HermesEnrollmentStore.ts new file mode 100644 index 0000000000..6804d45803 --- /dev/null +++ b/apps/server/src/provider/Layers/HermesEnrollmentStore.ts @@ -0,0 +1,106 @@ +/** + * Live {@link HermesEnrollmentStore}. See the service module for the token + * rules this upholds. + * + * @module Layers/HermesEnrollmentStore + */ +import { HermesGatewayEnrollmentToken, type ProviderInstanceId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Crypto from "effect/Crypto"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Ref from "effect/Ref"; + +import type { + HermesEnrollmentStore, + PendingEnrollment, +} from "../Services/HermesEnrollmentStore.ts"; + +const ENROLLMENT_TOKEN_BYTES = 32; + +export interface MakeHermesEnrollmentStoreOptions { + readonly ttl: Duration.Duration; +} + +export const makeHermesEnrollmentStore = ( + options: MakeHermesEnrollmentStoreOptions, +): Effect.Effect => + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const enrollments = yield* Ref.make(new Map()); + + const mint: HermesEnrollmentStore["mint"] = (input) => + Effect.gen(function* () { + const bytes = yield* crypto.randomBytes(ENROLLMENT_TOKEN_BYTES).pipe(Effect.orDie); + const token = HermesGatewayEnrollmentToken.make(Encoding.encodeBase64Url(bytes)); + const expiresAtMillis = (yield* Clock.currentTimeMillis) + Duration.toMillis(options.ttl); + + yield* Ref.update(enrollments, (current) => { + const next = new Map(current); + // Minting supersedes this instance's previous tokens so only the + // newest unconsumed token is redeemable. + for (const [pendingToken, pending] of current) { + if (pending.input.instanceId === input.instanceId) next.delete(pendingToken); + } + return next.set(token, { input, expiresAtMillis }); + }); + + return { token, expiresAtMillis }; + }); + + const peek: HermesEnrollmentStore["peek"] = (token) => + Effect.gen(function* () { + const found = (yield* Ref.get(enrollments)).get(token); + if (!found) return undefined; + return found.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : found; + }); + + const consume: HermesEnrollmentStore["consume"] = (token, expected) => + Effect.gen(function* () { + // Compare-and-swap: delete only if the entry is still the exact object + // the caller authenticated against, so a concurrent redemption or a + // re-mint in between cannot be consumed by this caller. + const claimed = yield* Ref.modify(enrollments, (current) => { + const found = current.get(token); + if (found !== expected) return [undefined, current] as const; + const next = new Map(current); + next.delete(token); + return [found, next] as const; + }); + if (claimed === undefined) return undefined; + // Re-check expiry after winning the swap: the entry may have aged out + // between authentication and consumption. + return claimed.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : claimed; + }); + + const forget = (instanceId: ProviderInstanceId) => + Ref.update(enrollments, (current) => { + const next = new Map(current); + for (const [token, pending] of current) { + if (pending.input.instanceId === instanceId) next.delete(token); + } + return next; + }); + + const sweep = Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + Ref.update(enrollments, (current) => { + const next = new Map(current); + for (const [token, pending] of current) { + if (pending.expiresAtMillis < now) next.delete(token); + } + return next.size === current.size ? current : next; + }), + ), + ); + + return { + mint, + peek, + consume, + forget, + sweep, + size: Ref.get(enrollments).pipe(Effect.map((current) => current.size)), + } satisfies HermesEnrollmentStore; + }); diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts index 8c789200e5..9fc511cd14 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts @@ -2,24 +2,24 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { HERMES_GATEWAY_PROTOCOL_VERSION, - HERMES_DRIVER_KIND, HermesGatewayCredential, HermesGatewayRequestId, HermesGatewaySessionId, - ProviderDriverKind, ProviderInstanceId, ThreadId, type HermesGatewayConnectionHello, type HermesGatewayT3ToPluginMessage, } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; import * as ServerConfig from "../../config.ts"; @@ -28,16 +28,21 @@ import { HermesDriver } from "../Drivers/HermesDriver.ts"; import type { ProviderInstance } from "../ProviderDriver.ts"; import { HermesGatewayBroker, + type HermesGatewayBrokerShape, + type HermesGatewayConnectionRegistration, type HermesGatewayTransport, } from "../Services/HermesGatewayBroker.ts"; -import { HermesGatewayBrokerLive, makeHermesGatewayBroker } from "./HermesGatewayBroker.ts"; +import { + HermesGatewayBrokerLive, + hermesGatewayCredentialSecretName, + hermesGatewayLegacyMetadataSecretName, + makeHermesGatewayBroker, +} from "./HermesGatewayBroker.ts"; const instanceId = ProviderInstanceId.make("hermes_remote"); const otherInstanceId = ProviderInstanceId.make("hermes_other"); const defaultHermesInstanceId = ProviderInstanceId.make("hermes"); -const metadataSecretNameForTest = (id: ProviderInstanceId) => - `hermes-gateway-metadata-${Buffer.from(id, "utf8").toString("base64url")}`; -const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString); + class HermesTestInstance extends Context.Service()( "t3/provider/Layers/HermesGatewayBroker.test/HermesTestInstance", ) {} @@ -63,28 +68,33 @@ const makeSecretStore = () => { return service; }; +const hermesInstances = { + [defaultHermesInstanceId]: { driver: "hermes", displayName: "Hermes", config: {} }, + [instanceId]: { driver: "hermes", displayName: "Remote", config: {} }, + [otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} }, +} as const; + +/** + * Broker over the ambient settings service, so a test can assert on what the + * broker wrote and can build a second broker over the same durable state to + * model a server restart. + */ const makeBroker = (secrets: ServerSecretStore.ServerSecretStore["Service"]) => makeHermesGatewayBroker.pipe( - Effect.provide( - ServerSettings.layerTest({ - providerInstances: { - [defaultHermesInstanceId]: { - driver: "hermes", - displayName: "Hermes", - config: {}, - }, - [instanceId]: { driver: "hermes", displayName: "Remote", config: {} }, - [otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} }, - }, - }), - ), Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), Effect.provide(NodeServices.layer), ); +/** Ambient layer: one settings service shared by the test and its brokers. */ +const testLayer = Layer.mergeAll( + ServerSettings.layerTest({ providerInstances: hermesInstances }), + NodeServices.layer, +); + const hello = ( authentication: HermesGatewayConnectionHello["authentication"], protocolVersion: number = HERMES_GATEWAY_PROTOCOL_VERSION, + overrides: { readonly model?: string } = {}, ): HermesGatewayConnectionHello => ({ type: "connection.hello", requestId: HermesGatewayRequestId.make(`hello-${protocolVersion}`), @@ -93,50 +103,52 @@ const hello = ( hermesVersion: "1.0.0", capabilities: { ...capabilities, protocolVersion }, authentication, + ...(overrides.model !== undefined ? { model: overrides.model } : {}), }); +/** Transport that records everything it is asked to do. */ +const recordingTransport = () => { + const sent: Array = []; + const closes: Array = []; + const transport: HermesGatewayTransport = { + send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), + close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid), + }; + return { sent, closes, transport }; +}; + +const enroll = (broker: HermesGatewayBrokerShape, id: ProviderInstanceId, nickname: string) => + broker.createEnrollment({ + instanceId: id, + nickname, + connectorUrl: "https://t3.example.test", + }); + it.effect("authenticates before applying incompatible connection state", () => Effect.gen(function* () { const secrets = makeSecretStore(); const broker = yield* makeBroker(secrets); - yield* broker.createEnrollment({ - instanceId: defaultHermesInstanceId, - nickname: "Default Hermes", - connectorUrl: "https://t3.example.test", - }); - const enrollment = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); + yield* enroll(broker, defaultHermesInstanceId, "Default Hermes"); + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); - const firstCloses: Array = []; - const firstTransport: HermesGatewayTransport = { - send: () => Effect.void, - close: (code) => Effect.sync(() => firstCloses.push(code)).pipe(Effect.asVoid), - }; - const first = yield* broker.registerConnection( + const first = recordingTransport(); + const registered = yield* broker.registerConnection( hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), - firstTransport, + first.transport, ); - assert.isTrue(first.accepted.credential !== undefined); + assert.isTrue(registered.accepted.credential !== undefined); assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected"); - const secondCloses: Array = []; - const sent: Array = []; - const secondTransport: HermesGatewayTransport = { - send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), - close: (code) => Effect.sync(() => secondCloses.push(code)).pipe(Effect.asVoid), - }; - const second = yield* broker.registerConnection( + const second = recordingTransport(); + const replacement = yield* broker.registerConnection( hello({ type: "instance-credential", instanceId, - credential: first.accepted.credential!, + credential: registered.accepted.credential!, }), - secondTransport, + second.transport, ); - assert.deepEqual(firstCloses, [4001]); + assert.deepEqual(first.closes, [4001]); const threadId = ThreadId.make("pending-thread"); const pendingRequestId = HermesGatewayRequestId.make("pending-session"); @@ -149,8 +161,11 @@ it.effect("authenticates before applying incompatible connection state", () => }) .pipe(Effect.forkChild({ startImmediately: true })); yield* Effect.yieldNow; - assert.equal(sent.at(-1)?.type, "session.ensure"); + assert.equal(second.sent.at(-1)?.type, "session.ensure"); + // A bad credential carried on an incompatible protocol version must be + // rejected for the credential, never for the version: rejecting on version + // first would let an unauthenticated caller knock the instance offline. const malicious = yield* Effect.flip( broker.registerConnection( hello( @@ -161,15 +176,15 @@ it.effect("authenticates before applying incompatible connection state", () => }, 3, ), - secondTransport, + second.transport, ), ); assert.equal(malicious.code, "invalid-authentication"); - assert.deepEqual(secondCloses, []); + assert.deepEqual(second.closes, []); assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected"); assert.isUndefined(pendingRequest.pollUnsafe()); - yield* broker.receive(second, { + yield* broker.receive(replacement, { type: "session.ready", protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: pendingRequestId, @@ -185,62 +200,46 @@ it.effect("authenticates before applying incompatible connection state", () => { type: "instance-credential", instanceId, - credential: first.accepted.credential!, + credential: registered.accepted.credential!, }, 3, ), - secondTransport, + second.transport, ), ); assert.equal(incompatible.code, "version-incompatible"); - assert.deepEqual(secondCloses, [4004]); + assert.deepEqual(second.closes, [4004]); assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "upgrade-required"); - const otherEnrollment = yield* broker.createEnrollment({ - instanceId: otherInstanceId, - nickname: "Other Hermes", - connectorUrl: "https://t3.example.test", - }); + const otherEnrollment = yield* enroll(broker, otherInstanceId, "Other Hermes"); const incompatibleEnrollment = yield* Effect.flip( broker.registerConnection( hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }, 3), - secondTransport, + second.transport, ), ); assert.equal(incompatibleEnrollment.code, "version-incompatible"); const enrolledAfterUpgrade = yield* broker.registerConnection( hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }), - secondTransport, + second.transport, ); assert.equal(enrolledAfterUpgrade.instanceId, otherInstanceId); const revoked = yield* broker.revokeInstance(instanceId); assert.equal(revoked.status, "revoked"); - }), + }).pipe(Effect.provide(testLayer)), ); it.effect("invalidates the previous credential when replacement enrollment begins", () => Effect.gen(function* () { const broker = yield* makeBroker(makeSecretStore()); - const enrollment = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - const closes: Array = []; - const transport: HermesGatewayTransport = { - send: () => Effect.void, - close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid), - }; + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); + const { closes, transport } = recordingTransport(); const first = yield* broker.registerConnection( hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), transport, ); - const replacement = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); + const replacement = yield* enroll(broker, instanceId, "Remote Hermes"); assert.deepEqual(closes, [4001]); const staleCredential = yield* Effect.flip( @@ -259,26 +258,15 @@ it.effect("invalidates the previous credential when replacement enrollment begin transport, ); assert.equal(replacementConnection.instanceId, instanceId); - }), + }).pipe(Effect.provide(testLayer)), ); it.effect("accepts only the newest unconsumed enrollment token for an instance", () => Effect.gen(function* () { const broker = yield* makeBroker(makeSecretStore()); - const older = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - const newest = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - const transport: HermesGatewayTransport = { - send: () => Effect.void, - close: () => Effect.void, - }; + const older = yield* enroll(broker, instanceId, "Remote Hermes"); + const newest = yield* enroll(broker, instanceId, "Remote Hermes"); + const { transport } = recordingTransport(); const olderTokenError = yield* Effect.flip( broker.registerConnection( @@ -292,77 +280,55 @@ it.effect("accepts only the newest unconsumed enrollment token for an instance", transport, ); assert.equal(newestConnection.instanceId, instanceId); - }), + }).pipe(Effect.provide(testLayer)), ); -it.effect("atomically reserves normalized nicknames across concurrent enrollments", () => - Effect.gen(function* () { - const storedSecrets = makeSecretStore(); - const firstPersistStarted = yield* Deferred.make(); - const releaseFirstPersist = yield* Deferred.make(); - let metadataPersistCount = 0; - const secrets: ServerSecretStore.ServerSecretStore["Service"] = { - ...storedSecrets, - set: (name, value) => - name.startsWith("hermes-gateway-metadata-") - ? Effect.gen(function* () { - metadataPersistCount += 1; - if (metadataPersistCount === 1) { - yield* Deferred.succeed(firstPersistStarted, undefined); - yield* Deferred.await(releaseFirstPersist); - } - yield* storedSecrets.set(name, value); - }) - : storedSecrets.set(name, value), - }; - const broker = yield* makeBroker(secrets); - const firstEnrollment = yield* broker - .createEnrollment({ - instanceId, - nickname: "Shared Hermes", - connectorUrl: "https://t3.example.test", - }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(firstPersistStarted); - const secondEnrollment = yield* broker - .createEnrollment({ - instanceId: otherInstanceId, - nickname: " SHARED HERMES ", - connectorUrl: "https://t3.example.test", - }) - .pipe(Effect.forkChild({ startImmediately: true })); - for (let index = 0; index < 10; index += 1) { - yield* Effect.yieldNow; - } - assert.equal(metadataPersistCount, 1); - - yield* Deferred.succeed(releaseFirstPersist, undefined); - yield* Fiber.join(firstEnrollment); - const conflict = yield* Effect.flip(Fiber.join(secondEnrollment)); - assert.equal(conflict.code, "nickname-conflict"); - assert.equal(metadataPersistCount, 1); - }), -); - -it.effect("keeps a revoked instance nickname reserved", () => +it.effect("redeems an enrollment token exactly once under concurrent redemption", () => Effect.gen(function* () { const broker = yield* makeBroker(makeSecretStore()); - yield* broker.createEnrollment({ - instanceId, - nickname: "Reserved Hermes", - connectorUrl: "https://t3.example.test", - }); - assert.equal((yield* broker.revokeInstance(instanceId)).status, "revoked"); + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); - const conflict = yield* Effect.flip( - broker.createEnrollment({ - instanceId: otherInstanceId, - nickname: " Reserved Hermes ", - connectorUrl: "https://t3.example.test", - }), + const raceFirst = yield* broker + .registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + const raceSecond = yield* broker + .registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + + const outcomes = [yield* Fiber.join(raceFirst), yield* Fiber.join(raceSecond)]; + const accepted = outcomes.filter((outcome) => outcome._tag === "Success"); + const rejected = outcomes.filter((outcome) => outcome._tag === "Failure"); + assert.equal(accepted.length, 1); + assert.equal(rejected.length, 1); + assert.equal( + rejected[0]?._tag === "Failure" ? rejected[0].failure.code : "", + "enrollment-expired", ); - assert.equal(conflict.code, "nickname-conflict"); - }), + }).pipe(Effect.provide(testLayer)), +); + +it.effect("expires enrollment tokens from memory without a redemption attempt", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); + + // Past the 10 minute TTL and past a sweep tick. + yield* TestClock.adjust(Duration.minutes(11)); + + const expired = yield* Effect.flip( + broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ), + ); + assert.equal(expired.code, "enrollment-expired"); + }).pipe(Effect.provide(testLayer)), ); it.effect("finalizes revocation when credential deletion fails", () => @@ -382,19 +348,11 @@ it.effect("finalizes revocation when credential deletion fails", () => : storedSecrets.remove(name), }; const broker = yield* makeBroker(secrets); - const enrollment = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - const closes: Array = []; - const sent: Array = []; + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); + const { sent, closes, transport } = recordingTransport(); const registration = yield* broker.registerConnection( hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), - { - send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), - close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid), - }, + transport, ); const credential = registration.accepted.credential; if (!credential) { @@ -427,25 +385,13 @@ it.effect("finalizes revocation when credential deletion fails", () => assert.include(pendingError.detail, "revoked"); const staleReconnect = yield* Effect.flip( - broker.registerConnection(hello({ type: "instance-credential", instanceId, credential }), { - send: () => Effect.void, - close: () => Effect.void, - }), - ); - assert.equal(staleReconnect.code, "instance-revoked"); - - const restartedBroker = yield* makeBroker(secrets); - const staleReconnectAfterRestart = yield* Effect.flip( - restartedBroker.registerConnection( + broker.registerConnection( hello({ type: "instance-credential", instanceId, credential }), - { - send: () => Effect.void, - close: () => Effect.void, - }, + recordingTransport().transport, ), ); - assert.equal(staleReconnectAfterRestart.code, "instance-revoked"); - }), + assert.equal(staleReconnect.code, "instance-revoked"); + }).pipe(Effect.provide(testLayer)), ); it.effect("shares one live broker between the gateway route and Hermes provider instance", () => { @@ -475,18 +421,11 @@ it.effect("shares one live broker between the gateway route and Hermes provider return Effect.gen(function* () { const broker = yield* HermesGatewayBroker; const provider = yield* HermesTestInstance; - const enrollment = yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - const sent: Array = []; + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); + const { sent, transport } = recordingTransport(); const registration = yield* broker.registerConnection( hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), - { - send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), - close: () => Effect.void, - }, + transport, ); assert.equal((yield* provider.snapshot.getSnapshot).status, "ready"); @@ -534,187 +473,272 @@ it.effect("shares one live broker between the gateway route and Hermes provider }).pipe(Effect.provide(providerLayer), Effect.scoped); }); -it.effect("checks nickname uniqueness from persisted metadata after restart", () => +// ── Durable config lives in settings; liveness never does ────────── + +it.effect("stores durable enrollment facts in the provider instance config", () => Effect.gen(function* () { - const secrets = makeSecretStore(); - const firstBroker = yield* makeBroker(secrets); - yield* firstBroker.createEnrollment({ + const broker = yield* makeBroker(makeSecretStore()); + const settings = yield* ServerSettings.ServerSettingsService; + yield* broker.createEnrollment({ instanceId, - nickname: "Persistent Nickname", - connectorUrl: "https://t3.example.test", + nickname: "Durable Hermes", + connectorUrl: "https://durable.example.test", }); - const restartedBroker = yield* makeBroker(secrets); - const error = yield* Effect.flip( - restartedBroker.createEnrollment({ - instanceId: otherInstanceId, - nickname: "Persistent Nickname", - connectorUrl: "https://t3.example.test", - }), - ); - assert.equal(error.code, "nickname-conflict"); - }), + const configured = (yield* settings.getSettings).providerInstances[instanceId]; + assert.equal(configured?.displayName, "Durable Hermes"); + assert.deepEqual(configured?.config, { + connectorUrl: "https://durable.example.test", + revoked: false, + }); + + yield* broker.revokeInstance(instanceId); + assert.deepEqual((yield* settings.getSettings).providerInstances[instanceId]?.config, { + connectorUrl: "https://durable.example.test", + revoked: true, + }); + }).pipe(Effect.provide(testLayer)), ); -it.effect("keeps previous-protocol metadata manageable after restart", () => +it.effect("never writes liveness into settings, so reconnects cannot restart instances", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const settings = yield* ServerSettings.ServerSettingsService; + const enrollment = yield* enroll(broker, instanceId, "Liveness Hermes"); + + const beforeConnect = (yield* settings.getSettings).providerInstances[instanceId]; + const registration = yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ); + yield* broker.receive(registration, { + type: "connection.status", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + activeSessionCount: 3, + }); + + // Connecting and reporting sessions is observable on status... + const connected = yield* broker.getInstanceStatus(instanceId); + assert.equal(connected.status, "connected"); + assert.equal(connected.activeSessionCount, 3); + assert.isNotNull(connected.lastConnectedAt); + + // ...but the settings envelope is unchanged, so the provider instance + // registry sees no config change and never closes the instance scope — + // which would otherwise stop every live Hermes session. + assert.deepEqual((yield* settings.getSettings).providerInstances[instanceId], beforeConnect); + + yield* broker.disconnect(registration); + assert.deepEqual((yield* settings.getSettings).providerInstances[instanceId], beforeConnect); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("reports liveness as offline after a restart until the plugin reconnects", () => Effect.gen(function* () { const secrets = makeSecretStore(); - const previousProtocolVersion = HERMES_GATEWAY_PROTOCOL_VERSION - 1; - const legacyMetadata = (nickname: string) => ({ - nickname, - connectorUrl: "https://t3.example.test", - revoked: false, - lastSeen: { - pluginVersion: "0.1.0", - hermesVersion: "0.19.0", - capabilities: { - ...capabilities, - protocolVersion: previousProtocolVersion, - }, - connectedAt: "2026-07-24T00:00:00.000Z", - activeSessionCount: 0, - }, - }); - yield* secrets.set( - metadataSecretNameForTest(instanceId), - new TextEncoder().encode(encodeUnknownJson(legacyMetadata("Legacy Remote"))), - ); - yield* secrets.set( - metadataSecretNameForTest(otherInstanceId), - new TextEncoder().encode(encodeUnknownJson(legacyMetadata("Legacy Other"))), - ); - const broker = yield* makeBroker(secrets); - const legacyStatus = yield* broker.getInstanceStatus(instanceId); - assert.equal(legacyStatus.protocolVersion, previousProtocolVersion); - assert.isNull(legacyStatus.capabilities); - assert.equal((yield* broker.revokeInstance(instanceId)).status, "revoked"); + const enrollment = yield* enroll(broker, instanceId, "Restart Hermes"); + yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ); + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected"); - const enrollment = yield* broker.createEnrollment({ - instanceId: otherInstanceId, - nickname: "Legacy Other", - connectorUrl: "https://t3.example.test", - }); - assert.equal(enrollment.instanceId, otherInstanceId); - }), + // A fresh broker over the same durable state: enrollment facts survive, + // liveness deliberately does not. + const restarted = yield* makeBroker(secrets); + const status = yield* restarted.getInstanceStatus(instanceId); + assert.equal(status.status, "offline"); + assert.equal(status.nickname, "Restart Hermes"); + assert.equal(status.connectorUrl, "https://t3.example.test"); + assert.isNull(status.lastConnectedAt); + assert.isNull(status.model); + assert.equal(status.activeSessionCount, 0); + }).pipe(Effect.provide(testLayer)), ); -it.effect( - "renames the display label while preserving instance identity and normalized uniqueness", - () => - Effect.gen(function* () { - const broker = yield* makeHermesGatewayBroker; - const settings = yield* ServerSettings.ServerSettingsService; - yield* broker.createEnrollment({ - instanceId, - nickname: "Remote Hermes", - connectorUrl: "https://t3.example.test", - }); - yield* broker.createEnrollment({ - instanceId: otherInstanceId, - nickname: "Other Hermes", - connectorUrl: "https://t3.example.test", - }); +it.effect("surfaces the model reported at handshake and clears it on restart", () => + Effect.gen(function* () { + const secrets = makeSecretStore(); + const broker = yield* makeBroker(secrets); + const enrollment = yield* enroll(broker, instanceId, "Model Hermes"); - const renamed = yield* broker.renameInstance({ - instanceId, - nickname: "Research Hermes", - }); - assert.equal(renamed.instanceId, instanceId); - assert.equal(renamed.nickname, "Research Hermes"); - assert.equal( - (yield* settings.getSettings).providerInstances[instanceId]?.displayName, - "Research Hermes", - ); + assert.isNull((yield* broker.getInstanceStatus(instanceId)).model); - const conflict = yield* Effect.flip( - broker.renameInstance({ - instanceId: otherInstanceId, - nickname: " RESEARCH HERMES ", + yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }, undefined, { + model: "hermes-4-preview", + }), + recordingTransport().transport, + ); + assert.equal((yield* broker.getInstanceStatus(instanceId)).model, "hermes-4-preview"); + + const restarted = yield* makeBroker(secrets); + assert.isNull((yield* restarted.getInstanceStatus(instanceId)).model); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("reports a null model for a plugin that predates the field", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Legacy Model Hermes"); + yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ); + const status = yield* broker.getInstanceStatus(instanceId); + assert.equal(status.status, "connected"); + assert.isNull(status.model); + }).pipe(Effect.provide(testLayer)), +); + +// ── Ping loop ───────────────────────────────────────────────────── + +it.effect("pings an active connection and stays connected while pongs arrive", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Ping Hermes"); + + const sent: Array = []; + const closes: Array = []; + // The registration only exists after registerConnection returns, but the + // ping loop starts inside it — so the responder waits on this gate rather + // than racing it. + const registrationReady = yield* Deferred.make(); + const pongDelivered = yield* Deferred.make(); + const transport: HermesGatewayTransport = { + send: (message) => + Effect.gen(function* () { + sent.push(message); + if (message.type !== "ping") return; + const registration = yield* Deferred.await(registrationReady); + yield* broker.receive(registration, { + type: "pong", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: message.requestId, + sentAt: message.sentAt, + }); + yield* Deferred.succeed(pongDelivered, undefined); }), - ); - assert.equal(conflict.operation, "rename-instance"); - assert.equal(conflict.code, "nickname-conflict"); - assert.equal((yield* broker.getInstanceStatus(otherInstanceId)).nickname, "Other Hermes"); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Remote", config: {} }, - [otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} }, - }, - }), - Layer.succeed(ServerSecretStore.ServerSecretStore, makeSecretStore()), - NodeServices.layer, - ), - ), - ), + close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid), + }; + + const registration = yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + transport, + ); + yield* Deferred.succeed(registrationReady, registration); + + yield* TestClock.adjust(Duration.seconds(25)); + yield* Deferred.await(pongDelivered); + assert.isTrue(sent.some((message) => message.type === "ping")); + assert.deepEqual(closes, []); + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected"); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("marks a half-open connection offline after consecutive missed pongs", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Half Open Hermes"); + + // A half-open socket: writes succeed, nothing ever answers. + const { sent, closes, transport } = recordingTransport(); + yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + transport, + ); + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected"); + + const pending = yield* broker + .request(instanceId, { + type: "session.ensure", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: HermesGatewayRequestId.make("half-open-request"), + threadId: ThreadId.make("half-open-thread"), + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + + // Two probe cycles, each sending a ping that times out unanswered. + yield* TestClock.adjust(Duration.seconds(90)); + + assert.isTrue(sent.filter((message) => message.type === "ping").length >= 2); + assert.deepEqual(closes, [4008]); + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "offline"); + // Pending work fails immediately instead of waiting out its own timeout. + const failure = yield* Effect.flip(Fiber.join(pending)); + assert.include(failure.detail, "stopped responding"); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("stops pinging once the connection is retired", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Retired Hermes"); + const { sent, transport } = recordingTransport(); + const registration = yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + transport, + ); + + yield* broker.disconnect(registration); + const afterDisconnect = sent.length; + // The ping fiber lives in the connection scope, so retiring the connection + // interrupts it rather than leaving it probing a dead socket. + yield* TestClock.adjust(Duration.minutes(2)); + assert.equal(sent.length, afterDisconnect); + }).pipe(Effect.provide(testLayer)), +); + +// ── Management operations ───────────────────────────────────────── + +it.effect("renames the display label while preserving instance identity", () => + Effect.gen(function* () { + const broker = yield* makeBroker(makeSecretStore()); + const settings = yield* ServerSettings.ServerSettingsService; + yield* enroll(broker, instanceId, "Remote Hermes"); + yield* enroll(broker, otherInstanceId, "Other Hermes"); + + const renamed = yield* broker.renameInstance({ + instanceId, + nickname: "Research Hermes", + }); + assert.equal(renamed.instanceId, instanceId); + assert.equal(renamed.nickname, "Research Hermes"); + assert.equal( + (yield* settings.getSettings).providerInstances[instanceId]?.displayName, + "Research Hermes", + ); + + // displayName is a free-text label, exactly like every other provider: + // reusing one is allowed, because the instance id is the identity. + const duplicate = yield* broker.renameInstance({ + instanceId: otherInstanceId, + nickname: " Research Hermes ", + }); + assert.equal(duplicate.instanceId, otherInstanceId); + assert.equal(duplicate.nickname, "Research Hermes"); + assert.equal((yield* broker.getInstanceStatus(instanceId)).nickname, "Research Hermes"); + }).pipe(Effect.provide(testLayer)), ); it.effect("preserves concurrent provider settings edits during rename and removal", () => Effect.gen(function* () { - const storedSecrets = makeSecretStore(); - let metadataGate: - | { - readonly started: Deferred.Deferred; - readonly release: Deferred.Deferred; - } - | undefined; - const secrets: ServerSecretStore.ServerSecretStore["Service"] = { - ...storedSecrets, - set: (name, value) => { - const gate = metadataGate; - if (!gate || !name.startsWith("hermes-gateway-metadata-")) { - return storedSecrets.set(name, value); - } - metadataGate = undefined; - return Effect.gen(function* () { - yield* Deferred.succeed(gate.started, undefined); - yield* Deferred.await(gate.release); - yield* storedSecrets.set(name, value); - }); - }, - }; - const broker = yield* makeHermesGatewayBroker.pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), - ); + const broker = yield* makeBroker(makeSecretStore()); const settings = yield* ServerSettings.ServerSettingsService; - yield* broker.createEnrollment({ - instanceId, - nickname: "Concurrent Hermes", - connectorUrl: "https://t3.example.test", - }); + yield* enroll(broker, instanceId, "Concurrent Hermes"); - const renameStarted = yield* Deferred.make(); - const releaseRename = yield* Deferred.make(); - metadataGate = { started: renameStarted, release: releaseRename }; - const rename = yield* broker - .renameInstance({ instanceId, nickname: "Concurrent Research" }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(renameStarted); + yield* broker.renameInstance({ instanceId, nickname: "Concurrent Research" }); yield* settings.updateSettingsWith((current) => ({ providerInstances: { ...current.providerInstances, codex_concurrent: { driver: "codex", displayName: "Concurrent Codex", config: {} }, }, })); - yield* Deferred.succeed(releaseRename, undefined); - yield* Fiber.join(rename); - assert.equal( - (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex_concurrent")] - ?.displayName, - "Concurrent Codex", - ); yield* broker.revokeInstance(instanceId); - const removeStarted = yield* Deferred.make(); - const releaseRemove = yield* Deferred.make(); - metadataGate = { started: removeStarted, release: releaseRemove }; - const remove = yield* broker - .removeInstance(instanceId) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(removeStarted); + yield* broker.removeInstance(instanceId); yield* settings.updateSettingsWith((current) => ({ providerInstances: { ...current.providerInstances, @@ -725,8 +749,7 @@ it.effect("preserves concurrent provider settings edits during rename and remova }, }, })); - yield* Deferred.succeed(releaseRemove, undefined); - yield* Fiber.join(remove); + const finalSettings = yield* settings.getSettings; assert.equal( finalSettings.providerInstances[ProviderInstanceId.make("codex_concurrent")]?.displayName, @@ -737,42 +760,19 @@ it.effect("preserves concurrent provider settings edits during rename and remova "Concurrent Claude", ); assert.isUndefined(finalSettings.providerInstances[instanceId]); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Remote", config: {} }, - [otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} }, - }, - }), - NodeServices.layer, - ), - ), - ), + }).pipe(Effect.provide(testLayer)), ); -it.effect("tombstones removed instance ids while freeing their nickname", () => +it.effect("requires revocation before removing an enrolled instance", () => Effect.gen(function* () { - const broker = yield* makeHermesGatewayBroker; + const secrets = makeSecretStore(); + const broker = yield* makeBroker(secrets); const settings = yield* ServerSettings.ServerSettingsService; - const enrollment = yield* broker.createEnrollment({ - instanceId, - nickname: "Disposable Hermes", - connectorUrl: "https://t3.example.test", - }); - const transport: HermesGatewayTransport = { - send: () => Effect.void, - close: () => Effect.void, - }; - const registration = yield* broker.registerConnection( + const enrollment = yield* enroll(broker, instanceId, "Disposable Hermes"); + yield* broker.registerConnection( hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), - transport, + recordingTransport().transport, ); - const staleCredential = registration.accepted.credential; - if (!staleCredential) { - return yield* Effect.die(new Error("enrollment did not issue a credential")); - } const liveError = yield* Effect.flip(broker.removeInstance(instanceId)); assert.equal(liveError.operation, "remove-instance"); @@ -786,268 +786,14 @@ it.effect("tombstones removed instance ids while freeing their nickname", () => ); const missing = yield* Effect.flip(broker.getInstanceStatus(instanceId)); assert.equal(missing.code, "instance-not-found"); - - yield* settings.updateSettingsWith((current) => ({ - providerInstances: { - ...current.providerInstances, - [instanceId]: { driver: "hermes", displayName: "Reused Hermes", config: {} }, - }, - })); - const tombstoneError = yield* Effect.flip( - broker.createEnrollment({ - instanceId, - nickname: "Reused Hermes", - connectorUrl: "https://t3.example.test", - }), - ); - assert.equal(tombstoneError.code, "instance-removed"); - assert.isUndefined((yield* settings.getSettings).providerInstances[instanceId]); - assert.isFalse( - (yield* broker.listInstances).some((status) => status.instanceId === instanceId), - ); - const staleConnection = yield* Effect.flip( - broker.registerConnection( - hello({ - type: "instance-credential", - instanceId, - credential: staleCredential, - }), - transport, - ), - ); - assert.equal(staleConnection.code, "invalid-authentication"); - - yield* settings.updateSettingsWith((current) => ({ - providerInstances: { - ...current.providerInstances, - [instanceId]: { driver: "hermes", displayName: "Reused Again", config: {} }, - }, - })); - const restartedBroker = yield* makeHermesGatewayBroker; - const restartedError = yield* Effect.flip( - restartedBroker.createEnrollment({ - instanceId, - nickname: "Reused Hermes", - connectorUrl: "https://t3.example.test", - }), - ); - assert.equal(restartedError.code, "instance-removed"); - assert.isUndefined((yield* settings.getSettings).providerInstances[instanceId]); - - const replacement = yield* broker.createEnrollment({ - instanceId: otherInstanceId, - nickname: "disposable hermes", - connectorUrl: "https://t3.example.test", - }); - assert.equal(replacement.instanceId, otherInstanceId); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Remote", config: {} }, - [otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} }, - }, - }), - Layer.succeed(ServerSecretStore.ServerSecretStore, makeSecretStore()), - NodeServices.layer, - ), - ), - ), -); - -it.effect("keeps the in-memory tombstone when credential cleanup fails", () => - Effect.gen(function* () { - const storedSecrets = makeSecretStore(); - let failCredentialCleanup = false; - const secrets: ServerSecretStore.ServerSecretStore["Service"] = { - ...storedSecrets, - remove: (name) => - failCredentialCleanup && name.startsWith("hermes-gateway-credential-") - ? Effect.fail( - new ServerSecretStore.SecretStoreRemoveError({ - resource: `secret ${name}`, - cause: new Error("forced credential cleanup failure"), - }), - ) - : storedSecrets.remove(name), - }; - const broker = yield* makeHermesGatewayBroker.pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), - ); - const settings = yield* ServerSettings.ServerSettingsService; - yield* broker.createEnrollment({ - instanceId, - nickname: "Cleanup Failure Hermes", - connectorUrl: "https://t3.example.test", - }); - yield* broker.revokeInstance(instanceId); - - failCredentialCleanup = true; - assert.deepEqual(yield* broker.removeInstance(instanceId), { instanceId }); - yield* settings.updateSettingsWith((current) => ({ - providerInstances: { - ...current.providerInstances, - [instanceId]: { driver: "hermes", displayName: "Forbidden Reuse", config: {} }, - }, - })); - const error = yield* Effect.flip( - broker.createEnrollment({ - instanceId, - nickname: "Forbidden Reuse", - connectorUrl: "https://t3.example.test", - }), - ); - assert.equal(error.code, "instance-removed"); - assert.isUndefined((yield* settings.getSettings).providerInstances[instanceId]); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Cleanup Failure Hermes", config: {} }, - }, - }), - NodeServices.layer, - ), - ), - ), -); - -it.effect("keeps the tombstone when settings post-commit materialization degrades", () => { - const storedSecrets = makeSecretStore(); - const sensitiveInstanceId = ProviderInstanceId.make("codex_sensitive"); - let providerEnvironmentReadsBeforeFailure = Number.POSITIVE_INFINITY; - const secrets: ServerSecretStore.ServerSecretStore["Service"] = { - ...storedSecrets, - get: (name) => { - if (!name.startsWith("provider-env-")) return storedSecrets.get(name); - if (providerEnvironmentReadsBeforeFailure <= 0) { - return Effect.fail( - new ServerSecretStore.SecretStoreReadError({ - resource: `secret ${name}`, - cause: new Error("forced post-commit materialization failure"), - }), - ); - } - providerEnvironmentReadsBeforeFailure -= 1; - return storedSecrets.get(name); - }, - }; - const secretLayer = Layer.succeed(ServerSecretStore.ServerSecretStore, secrets); - const configLayer = Layer.fresh( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-hermes-post-commit-settings-test-", - }), - ).pipe(Layer.provide(NodeServices.layer)); - const settingsLayer = ServerSettings.layer.pipe( - Layer.provide(secretLayer), - Layer.provideMerge(configLayer), - Layer.provide(NodeServices.layer), - ); - - return Effect.gen(function* () { - const settings = yield* ServerSettings.ServerSettingsService; - yield* settings.updateSettings({ - providerInstances: { - [instanceId]: { - driver: HERMES_DRIVER_KIND, - displayName: "Post Commit Hermes", - config: {}, - }, - [sensitiveInstanceId]: { - driver: ProviderDriverKind.make("codex"), - environment: [ - { - name: "OPENROUTER_API_KEY", - value: "secret", - sensitive: true, - }, - ], - config: {}, - }, - }, - }); - const broker = yield* makeHermesGatewayBroker; - yield* broker.createEnrollment({ - instanceId, - nickname: "Post Commit Hermes", - connectorUrl: "https://t3.example.test", - }); - yield* broker.revokeInstance(instanceId); - providerEnvironmentReadsBeforeFailure = 1; - assert.deepEqual(yield* broker.removeInstance(instanceId), { instanceId }); - - providerEnvironmentReadsBeforeFailure = Number.POSITIVE_INFINITY; - yield* settings.updateSettingsWith((current) => ({ - providerInstances: { - ...current.providerInstances, - [instanceId]: { - driver: HERMES_DRIVER_KIND, - displayName: "Forbidden Reuse", - config: {}, - }, - }, - })); - const error = yield* Effect.flip( - broker.createEnrollment({ - instanceId, - nickname: "Forbidden Reuse", - connectorUrl: "https://t3.example.test", - }), - ); - assert.equal(error.code, "instance-removed"); - }).pipe( - Effect.provide(Layer.mergeAll(settingsLayer, secretLayer, configLayer, NodeServices.layer)), - ); -}); - -it.effect("migrates legacy default metadata into an explicit visible provider instance", () => - Effect.gen(function* () { - const broker = yield* makeHermesGatewayBroker; - const settings = yield* ServerSettings.ServerSettingsService; - yield* broker.createEnrollment({ - instanceId: defaultHermesInstanceId, - nickname: "Legacy Hermes", - connectorUrl: "https://t3.example.test", - }); - yield* settings.updateSettingsWith((current) => { - const providerInstances = { ...current.providerInstances }; - delete providerInstances[defaultHermesInstanceId]; - return { providerInstances }; - }); - assert.isUndefined((yield* settings.getSettings).providerInstances[defaultHermesInstanceId]); - - yield* makeHermesGatewayBroker; - assert.deepEqual((yield* settings.getSettings).providerInstances[defaultHermesInstanceId], { - driver: HERMES_DRIVER_KIND, - displayName: "Legacy Hermes", - enabled: true, - config: {}, - }); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [defaultHermesInstanceId]: { - driver: "hermes", - displayName: "Hermes", - enabled: true, - config: {}, - }, - }, - }), - Layer.succeed(ServerSecretStore.ServerSecretStore, makeSecretStore()), - NodeServices.layer, - ), - ), - ), + // Removal drops the credential, so a stale one cannot be replayed. + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId)))); + }).pipe(Effect.provide(testLayer)), ); it.effect("removes an explicitly configured Hermes instance that was never enrolled", () => Effect.gen(function* () { - const broker = yield* makeHermesGatewayBroker; + const broker = yield* makeBroker(makeSecretStore()); const settings = yield* ServerSettings.ServerSettingsService; assert.deepEqual(yield* broker.removeInstance(instanceId), { instanceId }); @@ -1056,114 +802,294 @@ it.effect("removes an explicitly configured Hermes instance that was never enrol (yield* Effect.flip(broker.getInstanceStatus(instanceId))).code, "instance-not-found", ); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Never Enrolled", config: {} }, - }, - }), - Layer.succeed(ServerSecretStore.ServerSecretStore, makeSecretStore()), - NodeServices.layer, - ), - ), - ), + }).pipe(Effect.provide(testLayer)), ); -it.effect("fails closed when tombstone metadata cannot be read", () => +it.effect("lists only enrolled Hermes instances", () => Effect.gen(function* () { - const storedSecrets = makeSecretStore(); - let failMetadataReads = false; - const secrets: ServerSecretStore.ServerSecretStore["Service"] = { - ...storedSecrets, - get: (name) => - failMetadataReads && name === metadataSecretNameForTest(instanceId) - ? Effect.fail( - new ServerSecretStore.SecretStoreReadError({ - resource: `secret ${name}`, - cause: new Error("forced metadata read failure"), - }), - ) - : storedSecrets.get(name), - }; - const broker = yield* makeHermesGatewayBroker.pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), - ); - const settings = yield* ServerSettings.ServerSettingsService; - yield* broker.createEnrollment({ - instanceId, - nickname: "Read Failure Hermes", - connectorUrl: "https://t3.example.test", - }); - yield* broker.revokeInstance(instanceId); - yield* broker.removeInstance(instanceId); - yield* settings.updateSettingsWith((current) => ({ - providerInstances: { - ...current.providerInstances, - [instanceId]: { driver: "hermes", displayName: "Reused Hermes", config: {} }, - }, - })); + const broker = yield* makeBroker(makeSecretStore()); + yield* enroll(broker, instanceId, "Listed Hermes"); - failMetadataReads = true; - const restarted = yield* makeHermesGatewayBroker.pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), + assert.deepEqual( + (yield* broker.listInstances).map((status) => status.instanceId), + [instanceId], ); - const error = yield* Effect.flip( - restarted.createEnrollment({ - instanceId, - nickname: "Reused Hermes", - connectorUrl: "https://t3.example.test", + }).pipe(Effect.provide(testLayer)), +); + +// ── Legacy metadata migration ───────────────────────────────────── + +const legacyBlob = (metadata: Record) => + new TextEncoder().encode(JSON.stringify(metadata)); + +it.effect("migrates legacy metadata into settings and deletes the secret file", () => + Effect.gen(function* () { + const secrets = makeSecretStore(); + const secretName = hermesGatewayLegacyMetadataSecretName(instanceId); + yield* secrets.set( + secretName, + legacyBlob({ + nickname: "Legacy Remote", + connectorUrl: "https://legacy.example.test/api/hermes-gateway/ws", + revoked: false, + // Liveness from a v1 plugin. Migration must drop it rather than carry + // it into the config envelope. + lastSeen: { + pluginVersion: "0.1.0", + hermesVersion: "0.19.0", + capabilities: { + protocolVersion: 1, + streaming: true, + activity: true, + approvals: true, + userInput: true, + attachments: false, + }, + connectedAt: "2026-07-24T00:00:00.000Z", + activeSessionCount: 0, + }, }), ); - assert.equal(error.code, "persistence-failed"); - assert.equal( - (yield* settings.getSettings).providerInstances[instanceId]?.displayName, - "Reused Hermes", + yield* secrets.set( + hermesGatewayCredentialSecretName(instanceId), + new TextEncoder().encode("legacy-credential"), + ); + + const broker = yield* makeBroker(secrets); + const settings = yield* ServerSettings.ServerSettingsService; + + assert.deepEqual((yield* settings.getSettings).providerInstances[instanceId]?.config, { + connectorUrl: "https://legacy.example.test/api/hermes-gateway/ws", + revoked: false, + }); + + const status = yield* broker.getInstanceStatus(instanceId); + assert.equal(status.connectorUrl, "https://legacy.example.test/api/hermes-gateway/ws"); + assert.equal(status.status, "offline"); + // Liveness from the blob is not resurrected. + assert.isNull(status.lastConnectedAt); + assert.isNull(status.protocolVersion); + assert.equal(status.activeSessionCount, 0); + + // The blob is gone, but the credential of a still-configured, unrevoked + // instance is kept so its plugin can reconnect. + assert.isTrue(Option.isNone(yield* secrets.get(secretName))); + assert.isTrue(Option.isSome(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId)))); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("deletes tombstoned legacy metadata and its orphaned credential", () => + Effect.gen(function* () { + const secrets = makeSecretStore(); + const secretName = hermesGatewayLegacyMetadataSecretName(instanceId); + // Shape taken from a real orphan found on disk: revoked + removed. The old + // code only ever passed this name to get/set, never remove, so tombstones + // leaked for the lifetime of the install. + yield* secrets.set( + secretName, + legacyBlob({ + nickname: "Research Renamed", + connectorUrl: "https://siva.example.ts.net:7446/api/hermes-gateway/ws", + revoked: true, + removed: true, + }), + ); + yield* secrets.set( + hermesGatewayCredentialSecretName(instanceId), + new TextEncoder().encode("orphaned-credential"), + ); + + const broker = yield* makeBroker(secrets); + const settings = yield* ServerSettings.ServerSettingsService; + + assert.isTrue(Option.isNone(yield* secrets.get(secretName))); + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId)))); + // A tombstone contributes nothing to settings, and the id stays reusable. + assert.deepEqual((yield* settings.getSettings).providerInstances[instanceId]?.config, {}); + assert.isFalse( + (yield* broker.listInstances).some((status) => status.instanceId === instanceId), + ); + }).pipe(Effect.provide(testLayer)), +); + +/** + * Orphan cleanup can only be exercised against a real secrets directory: the + * whole point is that these files belong to instances settings no longer + * mentions, so they are unreachable by name and must be discovered by scanning. + * The two blobs below are verbatim copies of orphans found on a real install. + */ +it.effect("discovers and deletes orphaned legacy metadata left on disk", () => { + const removedInstanceId = ProviderInstanceId.make("hermes-first-hermes-demo-7f63c3052018"); + const renamedInstanceId = ProviderInstanceId.make("hermes-research-e4fcf4b39fa1"); + const configLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-hermes-orphan-migration-test-", + }).pipe(Layer.provide(NodeServices.layer)); + + return Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const secrets = yield* ServerSecretStore.ServerSecretStore; + + const writeOrphan = (id: ProviderInstanceId, metadata: Record) => + Effect.gen(function* () { + yield* secrets.set(hermesGatewayLegacyMetadataSecretName(id), legacyBlob(metadata)); + yield* secrets.set( + hermesGatewayCredentialSecretName(id), + new TextEncoder().encode(`credential-for-${id}`), + ); + }); + + yield* writeOrphan(removedInstanceId, { + nickname: "First Hermes Demo", + connectorUrl: "https://siva.otter-hawksbill.ts.net:7446/api/hermes-gateway/ws", + revoked: true, + lastSeen: { + pluginVersion: "0.1.0", + hermesVersion: "0.19.0", + capabilities: { + protocolVersion: 1, + streaming: true, + activity: true, + approvals: true, + userInput: true, + attachments: false, + }, + connectedAt: "2026-07-25T01:11:26.467Z", + activeSessionCount: 0, + }, + removed: true, + }); + yield* writeOrphan(renamedInstanceId, { + nickname: "Research Renamed", + connectorUrl: "https://siva.otter-hawksbill.ts.net:7446/api/hermes-gateway/ws", + revoked: true, + removed: true, + }); + + // Neither id appears in settings, so name-based lookup alone would miss + // both files entirely. + yield* makeHermesGatewayBroker.pipe( + Effect.provide(ServerSettings.layerTest({ providerInstances: {} })), + ); + + for (const id of [removedInstanceId, renamedInstanceId]) { + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayLegacyMetadataSecretName(id)))); + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(id)))); + } + const remaining = yield* fs.readDirectory(config.secretsDir); + assert.deepEqual( + remaining.filter((entry) => entry.includes("hermes-gateway")), + [], ); }).pipe( Effect.provide( Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Original Hermes", config: {} }, - }, - }), + ServerSecretStore.layer.pipe(Layer.provide(configLayer), Layer.provide(NodeServices.layer)), + configLayer, NodeServices.layer, ), ), - ), + ); +}); + +it.effect("keeps legacy metadata when the settings write fails", () => + Effect.gen(function* () { + const storedSecrets = makeSecretStore(); + const secretName = hermesGatewayLegacyMetadataSecretName(instanceId); + yield* storedSecrets.set( + secretName, + legacyBlob({ + nickname: "Deferred Hermes", + connectorUrl: "https://deferred.example.test", + revoked: false, + }), + ); + + // Deleting the blob is conditional on committing its durable equivalent, + // so a settings failure must leave the input intact for the next boot. + let metadataRemovals = 0; + const secrets: ServerSecretStore.ServerSecretStore["Service"] = { + ...storedSecrets, + remove: (name) => + name === secretName + ? Effect.sync(() => { + metadataRemovals += 1; + }).pipe(Effect.andThen(storedSecrets.remove(name))) + : storedSecrets.remove(name), + }; + + const failingSettings = Layer.effect( + ServerSettings.ServerSettingsService, + ServerSettings.layerTest({ providerInstances: hermesInstances }).pipe( + Layer.build, + Effect.map((context) => { + const inner = Context.get(context, ServerSettings.ServerSettingsService); + return { + ...inner, + updateSettingsWith: () => Effect.die(new Error("settings write failed")), + } satisfies ServerSettings.ServerSettingsService["Service"]; + }), + ), + ); + + yield* makeHermesGatewayBroker.pipe( + Effect.provide(failingSettings), + Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), + Effect.provide(NodeServices.layer), + Effect.scoped, + ); + + assert.equal(metadataRemovals, 0); + assert.isTrue(Option.isSome(yield* storedSecrets.get(secretName))); + }).pipe(Effect.provide(testLayer)), ); -it.effect("fails closed when present Hermes metadata is malformed", () => +it.effect("discards unreadable legacy metadata instead of failing boot", () => + Effect.gen(function* () { + const secrets = makeSecretStore(); + const secretName = hermesGatewayLegacyMetadataSecretName(instanceId); + yield* secrets.set(secretName, new TextEncoder().encode("{not-valid-json")); + + const broker = yield* makeBroker(secrets); + assert.isTrue(Option.isNone(yield* secrets.get(secretName))); + // Boot survives; the instance is simply un-enrolled. + assert.equal( + (yield* Effect.flip(broker.getInstanceStatus(instanceId))).code, + "instance-not-found", + ); + }).pipe(Effect.provide(testLayer)), +); + +it.effect("migrates a revoked legacy instance and drops its credential", () => Effect.gen(function* () { const secrets = makeSecretStore(); yield* secrets.set( - metadataSecretNameForTest(instanceId), - new TextEncoder().encode("{not-valid-json"), - ); - const broker = yield* makeHermesGatewayBroker.pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), - ); - - const error = yield* Effect.flip( - broker.createEnrollment({ - instanceId, - nickname: "Malformed Hermes", - connectorUrl: "https://t3.example.test", + hermesGatewayLegacyMetadataSecretName(instanceId), + legacyBlob({ + nickname: "Revoked Legacy", + connectorUrl: "https://revoked.example.test", + revoked: true, }), ); - assert.equal(error.code, "persistence-failed"); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "hermes", displayName: "Malformed Hermes", config: {} }, - }, + yield* secrets.set( + hermesGatewayCredentialSecretName(instanceId), + new TextEncoder().encode("revoked-credential"), + ); + + const broker = yield* makeBroker(secrets); + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "revoked"); + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId)))); + + const reconnect = yield* Effect.flip( + broker.registerConnection( + hello({ + type: "instance-credential", + instanceId, + credential: HermesGatewayCredential.make("revoked-credential"), }), - NodeServices.layer, + recordingTransport().transport, ), - ), - ), + ); + assert.equal(reconnect.code, "invalid-authentication"); + }).pipe(Effect.provide(testLayer)), ); diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.ts index 8be5c69863..0b43bf906c 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.ts @@ -1,13 +1,52 @@ +/** + * HermesGatewayBroker — enrollment, authentication, and message routing for + * Hermes gateway plugin connections. + * + * State ownership + * --------------- + * The broker splits gateway state three ways, by durability: + * + * - **Credential** → `ServerSecretStore`. A 0600 file is exactly the right + * home for a secret, and nothing else needs to enumerate it. + * + * - **Durable config** (display name, connector URL, revoked) → the Hermes + * provider instance config in `ServerSettings`, written through + * `updateSettingsWith` so the read-modify-write happens under the settings + * write lock and concurrent edits to unrelated instances are preserved. + * This replaced a JSON blob in the secret store, which had no listing API, + * no index, and no transactions — and therefore forced O(N) secret-file + * scans, whole-file rewrites on every connect, and hand-rolled + * compensating writes. + * + * - **Volatile liveness** (connection, transport, lastSeen, session count, + * reported model, upgrade-required) → `HermesConnectionRegistry`, in + * memory only. See that module for why persisting it would stop every live + * Hermes session on every reconnect. + * + * After a T3 restart the UI reports "never connected" until the plugin dials + * back in. That is intended, and is the correct reading of the facts: T3 has + * no live connection until one is re-established. + * + * Locking + * ------- + * There is no global broker lock. Enrollment mutations serialize per-instance; + * `registerConnection` takes no enrollment lock at all, so a slow credential + * write during one instance's enrollment cannot block another instance's + * WebSocket handshake. Where two writers could still race — token redemption, + * connection replacement — correctness comes from compare-and-swap and + * generation fencing rather than from a mutex. + * + * @module HermesGatewayBroker + */ import * as NodeCrypto from "node:crypto"; import { HERMES_GATEWAY_PROTOCOL_VERSION, HERMES_DRIVER_KIND, defaultInstanceIdForDriver, HermesGatewayCredential, - HermesGatewayEnrollmentToken, HermesGatewayCapabilities, - HermesGatewayHelloCapabilities, HermesGatewayManagementError, + ProviderInstanceId, type HermesGatewayConnectionHello, type HermesGatewayCreateEnrollmentInput, type HermesGatewayEnrollmentResult, @@ -18,24 +57,26 @@ import { type HermesGatewayRenameInstanceResult, type HermesGatewayRevokeInstanceResult, type HermesGatewayT3ToPluginMessage, - type ProviderInstanceId, + type ProviderInstanceConfig, } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; -import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterRequestError } from "../Errors.ts"; import { @@ -45,67 +86,85 @@ import { type HermesGatewayTransport, type HermesGatewayBrokerShape, } from "../Services/HermesGatewayBroker.ts"; +import type { HermesObservedConnection } from "../Services/HermesConnectionRegistry.ts"; +import type { PendingEnrollment } from "../Services/HermesEnrollmentStore.ts"; +import { livenessStatusFields, makeHermesConnectionRegistry } from "./HermesConnectionRegistry.ts"; +import { makeHermesEnrollmentStore } from "./HermesEnrollmentStore.ts"; +import { makeRequestCorrelator } from "./RequestCorrelator.ts"; const ENROLLMENT_TTL = Duration.minutes(10); const REQUEST_TIMEOUT = Duration.seconds(30); +/** Safety net for pending requests whose awaiting fiber died abnormally. */ +const REQUEST_MAX_AGE = Duration.seconds(90); +/** How often expired enrollment tokens and abandoned requests are reaped. */ +const SWEEP_INTERVAL = Duration.minutes(1); +/** + * Server→plugin liveness probe. Without it a half-open socket reads as + * "connected" indefinitely: `send` succeeds into the void and the failure only + * surfaces when some unrelated request times out. + * + * These are sized so worst-case detection (first probe immediately, then + * `PING_MAX_MISSED` failures) lands inside `REQUEST_TIMEOUT`. That ordering is + * the whole point: an in-flight request over a dead socket should fail with + * "the connection stopped responding" rather than sit out a generic timeout. + */ +const PING_INTERVAL = Duration.seconds(10); +/** How long a single ping may go unanswered before it counts as missed. */ +const PING_TIMEOUT = Duration.seconds(4); +/** Consecutive missed pings tolerated before the connection is torn down. */ +const PING_MAX_MISSED = 2; + +const CREDENTIAL_BYTES = 32; + const textEncoder = new TextEncoder(); -const textDecoder = new TextDecoder(); const isStrictCapabilities = Schema.is(HermesGatewayCapabilities); - -interface PendingEnrollment { - readonly input: HermesGatewayCreateEnrollmentInput; - readonly expiresAtMillis: number; -} - -const InstanceMetadata = Schema.Struct({ - nickname: Schema.String, - connectorUrl: Schema.String, - revoked: Schema.Boolean, - removed: Schema.optionalKey(Schema.Boolean), - lastSeen: Schema.optionalKey( - Schema.Struct({ - pluginVersion: Schema.String, - hermesVersion: Schema.String, - capabilities: HermesGatewayHelloCapabilities, - connectedAt: Schema.String, - activeSessionCount: Schema.Number, - }), - ), -}); -type InstanceMetadata = typeof InstanceMetadata.Type; -const decodeInstanceMetadata = Schema.decodeUnknownEffect(Schema.fromJsonString(InstanceMetadata)); - -interface ActiveConnection { - readonly generation: number; - readonly transport: HermesGatewayTransport; - readonly pluginVersion: string; - readonly hermesVersion: string; - readonly capabilities: NonNullable; - readonly connectedAt: string; - readonly activeSessionCount: number; -} - -interface InstanceState { - readonly metadata: InstanceMetadata; - readonly connection?: ActiveConnection; - readonly lastSeen?: Omit & { - readonly activeSessionCount: number; - }; - readonly upgradeRequired?: { - readonly pluginVersion: string; - readonly hermesVersion: string; - readonly protocolVersion: number; - }; -} +const isProviderInstanceId = Schema.is(ProviderInstanceId); type PluginMessage = Exclude; +/** + * Durable enrollment facts, read from and written to the Hermes provider + * instance config in settings. + */ +interface InstanceRecord { + readonly nickname: string; + readonly connectorUrl: string; + readonly revoked: boolean; +} + +/** + * A Hermes instance can be *configured* (someone added the envelope) without + * being *enrolled* (no plugin has ever been paired). Only enrollment produces + * a connector URL, so its presence is what distinguishes the two. Status, + * rename, and revoke all require an enrolled instance; create-enrollment and + * remove deliberately accept a merely-configured one. + */ +const isEnrolled = (record: InstanceRecord) => record.connectorUrl !== ""; + const credentialSecretName = (instanceId: ProviderInstanceId) => `hermes-gateway-credential-${Buffer.from(instanceId, "utf8").toString("base64url")}`; -const metadataSecretName = (instanceId: ProviderInstanceId) => +/** Legacy metadata blob location, read once at boot then deleted. */ +const legacyMetadataSecretName = (instanceId: ProviderInstanceId) => `hermes-gateway-metadata-${Buffer.from(instanceId, "utf8").toString("base64url")}`; +/** + * Schema for the legacy secret-store metadata blob. Retained only so boot can + * migrate pre-existing files into settings and delete them; nothing writes it. + */ +const LegacyInstanceMetadata = Schema.Struct({ + nickname: Schema.String, + connectorUrl: Schema.String, + revoked: Schema.Boolean, + removed: Schema.optionalKey(Schema.Boolean), +}); +type LegacyInstanceMetadata = typeof LegacyInstanceMetadata.Type; +const decodeLegacyMetadata = Schema.decodeUnknownEffect( + // The blob also carried a `lastSeen` liveness object. It is intentionally + // dropped: liveness is no longer persisted at all. + Schema.fromJsonString(LegacyInstanceMetadata), +); + const managementError = ( operation: HermesGatewayManagementError["operation"], code: HermesGatewayManagementError["code"], @@ -133,6 +192,11 @@ const rejection = ( const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; +/** + * Constant-time credential comparison. The length pre-check is required: + * `timingSafeEqual` throws on mismatched lengths, and comparing lengths first + * leaks only the length, which is not secret. + */ const credentialsEqual = (left: Uint8Array, right: string) => { const rightBytes = textEncoder.encode(right); return left.byteLength === rightBytes.byteLength && NodeCrypto.timingSafeEqual(left, rightBytes); @@ -140,181 +204,203 @@ const credentialsEqual = (left: Uint8Array, right: string) => { const normalizeNickname = (nickname: string) => nickname.trim(); -const nicknameComparisonKey = (nickname: string) => - normalizeNickname(nickname).normalize("NFKC").toLocaleLowerCase("en-US"); +/** Read a Hermes instance's durable config out of a settings envelope. */ +const readHermesConfig = (config: ProviderInstanceConfig | undefined) => { + if (!config || config.driver !== HERMES_DRIVER_KIND) return undefined; + const raw = config.config; + const blob = raw && typeof raw === "object" ? (raw as Record) : {}; + return { + displayName: config.displayName, + connectorUrl: typeof blob.connectorUrl === "string" ? blob.connectorUrl : undefined, + revoked: blob.revoked === true, + }; +}; -const statusFromState = ( +const recordFrom = ( instanceId: ProviderInstanceId, - state: InstanceState, -): HermesGatewayInstanceStatus => ({ - ...(() => { - const observed = state.connection ?? state.lastSeen ?? state.metadata.lastSeen; - return { - lastConnectedAt: observed?.connectedAt ?? null, - pluginVersion: observed?.pluginVersion ?? state.upgradeRequired?.pluginVersion ?? null, - hermesVersion: observed?.hermesVersion ?? state.upgradeRequired?.hermesVersion ?? null, - activeSessionCount: state.connection?.activeSessionCount ?? 0, - protocolVersion: - observed?.capabilities.protocolVersion ?? state.upgradeRequired?.protocolVersion ?? null, - capabilities: - observed?.capabilities !== undefined && isStrictCapabilities(observed.capabilities) - ? observed.capabilities - : null, - }; - })(), - instanceId, - nickname: state.metadata.nickname, - status: state.metadata.revoked - ? "revoked" - : state.upgradeRequired - ? "upgrade-required" - : state.connection - ? "connected" - : "offline", - connectorUrl: state.metadata.connectorUrl, -}); + config: ProviderInstanceConfig | undefined, +): InstanceRecord | undefined => { + const hermes = readHermesConfig(config); + if (!hermes) return undefined; + return { + nickname: hermes.displayName ?? instanceId, + connectorUrl: hermes.connectorUrl ?? "", + revoked: hermes.revoked, + }; +}; + +/** Merge durable config edits into an existing Hermes envelope. */ +const withHermesConfig = ( + existing: ProviderInstanceConfig, + patch: { + readonly nickname?: string | undefined; + readonly connectorUrl?: string | undefined; + readonly revoked?: boolean | undefined; + }, +): ProviderInstanceConfig => { + const currentConfig = + existing.config && typeof existing.config === "object" + ? (existing.config as Record) + : {}; + return { + ...existing, + ...(patch.nickname !== undefined ? { displayName: patch.nickname } : {}), + config: { + ...currentConfig, + ...(patch.connectorUrl !== undefined ? { connectorUrl: patch.connectorUrl } : {}), + ...(patch.revoked !== undefined ? { revoked: patch.revoked } : {}), + }, + }; +}; export const makeHermesGatewayBroker = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const secretStore = yield* ServerSecretStore.ServerSecretStore; const settings = yield* ServerSettingsService; - const states = yield* Ref.make(new Map()); - const enrollments = yield* Ref.make(new Map()); - const pendingRequests = yield* Ref.make( - new Map< - string, - { - readonly instanceId: ProviderInstanceId; - readonly deferred: Deferred.Deferred; - } - >(), - ); + + const connections = yield* makeHermesConnectionRegistry; + const enrollmentStore = yield* makeHermesEnrollmentStore({ ttl: ENROLLMENT_TTL }); + const correlator = yield* makeRequestCorrelator({ + provider: HERMES_DRIVER_KIND, + timeout: REQUEST_TIMEOUT, + maxAge: REQUEST_MAX_AGE, + }); + const events = yield* PubSub.unbounded(); const statusEvents = yield* PubSub.unbounded(); - const generation = yield* Ref.make(0); - const enrollmentSemaphore = yield* Semaphore.make(1); - const publishStatus = (instanceId: ProviderInstanceId, state: InstanceState) => - PubSub.publish(statusEvents, statusFromState(instanceId, state)).pipe(Effect.asVoid); - - const failPendingRequests = (instanceId: ProviderInstanceId, detail: string) => + /** + * Per-instance enrollment lock. Serializes the read-modify-write of one + * instance's durable config against itself without coupling unrelated + * instances — and, critically, without gating the WebSocket handshake. + */ + const enrollmentLocks = yield* Ref.make(new Map()); + const withInstanceLock = ( + instanceId: ProviderInstanceId, + effect: Effect.Effect, + ) => Effect.gen(function* () { - const affected = yield* Ref.modify(pendingRequests, (current) => { - const next = new Map(current); - const found = Array.from(current.entries()).filter( - ([, pending]) => pending.instanceId === instanceId, - ); - for (const [requestId] of found) next.delete(requestId); - return [found.map(([, pending]) => pending.deferred), next] as const; - }); - yield* Effect.forEach( - affected, - (deferred) => - Deferred.fail( - deferred, - new ProviderAdapterRequestError({ - provider: HERMES_DRIVER_KIND, - method: "connection", - detail, - }), - ), - { discard: true }, - ); + const existing = (yield* Ref.get(enrollmentLocks)).get(instanceId); + const semaphore = existing ?? (yield* Semaphore.make(1)); + if (!existing) { + // Two fibers can reach here concurrently for a new instance; the + // modify below keeps whichever landed first so both share one lock. + const winner = yield* Ref.modify(enrollmentLocks, (current) => { + const found = current.get(instanceId); + if (found) return [found, current] as const; + return [semaphore, new Map(current).set(instanceId, semaphore)] as const; + }); + return yield* winner.withPermits(1)(effect); + } + return yield* semaphore.withPermits(1)(effect); }); - const persistMetadata = (instanceId: ProviderInstanceId, metadata: InstanceMetadata) => - secretStore - .set(metadataSecretName(instanceId), textEncoder.encode(JSON.stringify(metadata))) - .pipe( - Effect.mapError(() => - managementError( - "create-enrollment", - "persistence-failed", - "Failed to persist Hermes gateway metadata.", - instanceId, - ), - ), - ); - - const readMetadata = (instanceId: ProviderInstanceId) => - secretStore.get(metadataSecretName(instanceId)).pipe( - Effect.flatMap((stored) => { - if (Option.isNone(stored)) return Effect.succeed(undefined); - return decodeInstanceMetadata(textDecoder.decode(stored.value)).pipe( - Effect.mapError( - (cause) => - new ServerSecretStore.SecretStoreDecodeError({ - resource: `Hermes gateway metadata for ${instanceId}`, - cause, - }), - ), - ); - }), + const readSettings = (operation: HermesGatewayManagementError["operation"]) => + settings.getSettings.pipe( + Effect.mapError(() => + managementError(operation, "internal-error", "Failed to read server settings."), + ), ); - const getState = (instanceId: ProviderInstanceId) => - Ref.get(states).pipe( - Effect.map((current) => current.get(instanceId)), - Effect.flatMap((state) => { - if (state) { - return state.metadata.removed - ? Effect.fail( - managementError( - "get-status", - "instance-not-found", - `Hermes gateway instance '${instanceId}' has been removed.`, - instanceId, - ), - ) - : Effect.succeed(state); - } - return readMetadata(instanceId).pipe( - Effect.mapError(() => - managementError( - "get-status", - "persistence-failed", - "Failed to read Hermes gateway metadata.", - instanceId, + /** Durable record for one instance, or `undefined` if not a Hermes instance. */ + const readRecord = ( + instanceId: ProviderInstanceId, + operation: HermesGatewayManagementError["operation"], + ) => + readSettings(operation).pipe( + Effect.map((current) => recordFrom(instanceId, current.providerInstances[instanceId])), + ); + + const requireRecord = ( + instanceId: ProviderInstanceId, + operation: HermesGatewayManagementError["operation"], + ) => + readRecord(instanceId, operation).pipe( + Effect.flatMap((record) => + record && isEnrolled(record) + ? Effect.succeed(record) + : Effect.fail( + managementError( + operation, + "instance-not-found", + record + ? `Hermes gateway instance '${instanceId}' has not been enrolled.` + : `Hermes gateway instance '${instanceId}' is not configured.`, + instanceId, + ), ), - ), - Effect.flatMap((metadata) => { - if (!metadata || metadata.removed) { - return Effect.fail( - managementError( - "get-status", - "instance-not-found", - `Hermes gateway instance '${instanceId}' has not been enrolled.`, - instanceId, - ), - ); - } - const loaded: InstanceState = { metadata }; - return Ref.update(states, (current) => new Map(current).set(instanceId, loaded)).pipe( - Effect.as(loaded), - ); - }), - ); + ), + ); + + /** + * Compose a public status from the durable record plus volatile liveness. + * `revoked` wins over everything: a revoked instance is revoked even if a + * stale connection object has not been reaped yet. + */ + const statusOf = (instanceId: ProviderInstanceId, record: InstanceRecord) => + connections.liveness(instanceId).pipe( + Effect.map((liveness) => { + const fields = livenessStatusFields(liveness); + const { connected, upgradeRequired, capabilities, ...rest } = fields; + return { + ...rest, + // A capability shape from a newer protocol is reported as null + // rather than passed through as if T3 understood it. + capabilities: + capabilities !== null && isStrictCapabilities(capabilities) ? capabilities : null, + instanceId, + nickname: record.nickname, + connectorUrl: record.connectorUrl, + status: record.revoked + ? "revoked" + : upgradeRequired + ? "upgrade-required" + : connected + ? "connected" + : "offline", + } satisfies HermesGatewayInstanceStatus; }), ); + const publishStatus = (instanceId: ProviderInstanceId, record: InstanceRecord) => + statusOf(instanceId, record).pipe( + Effect.flatMap((status) => PubSub.publish(statusEvents, status)), + Effect.asVoid, + ); + + /** Publish using whatever durable record settings currently holds. */ + const publishCurrentStatus = ( + instanceId: ProviderInstanceId, + operation: HermesGatewayManagementError["operation"], + ) => + readRecord(instanceId, operation).pipe( + Effect.flatMap((record) => (record ? publishStatus(instanceId, record) : Effect.void)), + Effect.ignore, + ); + + const failPendingRequests = (instanceId: ProviderInstanceId, detail: string) => + correlator.failOwner(instanceId, detail); + + /** + * Tear down a connection: fail its in-flight requests, then close the + * socket. Ordering matters — callers waiting on a request should see the + * specific reason rather than a generic disconnect. + */ + const teardownConnection = ( + instanceId: ProviderInstanceId, + transport: HermesGatewayTransport, + code: number, + reason: string, + ) => failPendingRequests(instanceId, reason).pipe(Effect.andThen(transport.close(code, reason))); + + // ── Management operations ───────────────────────────────────────── + const createEnrollment = (input: HermesGatewayCreateEnrollmentInput) => - enrollmentSemaphore.withPermits(1)( + withInstanceLock( + input.instanceId, Effect.gen(function* () { - const normalizedNickname = normalizeNickname(input.nickname); - const normalizedInput = { - ...input, - nickname: normalizedNickname, - } satisfies HermesGatewayCreateEnrollmentInput; - const currentSettings = yield* settings.getSettings.pipe( - Effect.mapError(() => - managementError( - "create-enrollment", - "internal-error", - "Failed to read server settings.", - input.instanceId, - ), - ), - ); + const nickname = normalizeNickname(input.nickname); + const currentSettings = yield* readSettings("create-enrollment"); const configured = currentSettings.providerInstances[input.instanceId]; if (!configured || configured.driver !== HERMES_DRIVER_KIND) { return yield* managementError( @@ -325,113 +411,9 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } - const existingInputState = - (yield* Ref.get(states)).get(input.instanceId) ?? - (yield* readMetadata(input.instanceId).pipe( - Effect.map((metadata) => (metadata ? { metadata } : undefined)), - Effect.mapError(() => - managementError( - "create-enrollment", - "persistence-failed", - "Failed to read Hermes gateway metadata.", - input.instanceId, - ), - ), - )); - if (existingInputState?.metadata.removed) { - yield* settings - .updateSettingsWith((latest) => { - if (latest.providerInstances[input.instanceId]?.driver !== HERMES_DRIVER_KIND) { - return {}; - } - const providerInstances = { ...latest.providerInstances }; - delete providerInstances[input.instanceId]; - return { providerInstances }; - }) - .pipe( - Effect.mapError(() => - managementError( - "create-enrollment", - "persistence-failed", - `Failed to clean up the reconfigured tombstoned Hermes instance '${input.instanceId}'.`, - input.instanceId, - ), - ), - ); - return yield* managementError( - "create-enrollment", - "instance-removed", - `Hermes gateway instance id '${input.instanceId}' was permanently removed. Create a new instance with a fresh id.`, - input.instanceId, - ); - } - - const configuredHermesIds = Object.entries(currentSettings.providerInstances) - .filter(([, config]) => config.driver === HERMES_DRIVER_KIND) - .map(([instanceId]) => instanceId as ProviderInstanceId); - const existingStates = yield* Ref.get(states); - for (const instanceId of new Set(configuredHermesIds)) { - const persistedMetadata = existingStates.has(instanceId) - ? undefined - : yield* readMetadata(instanceId).pipe( - Effect.mapError(() => - managementError( - "create-enrollment", - "persistence-failed", - "Failed to read Hermes gateway metadata.", - input.instanceId, - ), - ), - ); - const state = - existingStates.get(instanceId) ?? - (persistedMetadata ? { metadata: persistedMetadata } : undefined); - const candidateNickname = - state?.metadata.removed === true - ? undefined - : (state?.metadata.nickname ?? - currentSettings.providerInstances[instanceId]?.displayName); - if ( - instanceId !== input.instanceId && - candidateNickname !== undefined && - nicknameComparisonKey(candidateNickname) === nicknameComparisonKey(normalizedNickname) - ) { - return yield* managementError( - "create-enrollment", - "nickname-conflict", - `A Hermes gateway named '${normalizedNickname}' already exists.`, - input.instanceId, - ); - } - } - - const token = HermesGatewayEnrollmentToken.make( - Encoding.encodeBase64Url( - yield* crypto - .randomBytes(32) - .pipe( - Effect.mapError(() => - managementError( - "create-enrollment", - "internal-error", - "Failed to generate an enrollment token.", - input.instanceId, - ), - ), - ), - ), - ); - const expiresAtMillis = - (yield* Clock.currentTimeMillis) + Duration.toMillis(ENROLLMENT_TTL); - const previousState = existingStates.get(input.instanceId); - const metadata = { - nickname: normalizedNickname, - connectorUrl: input.connectorUrl, - revoked: false, - ...(previousState?.metadata.lastSeen - ? { lastSeen: previousState.metadata.lastSeen } - : {}), - } satisfies InstanceMetadata; + // Invalidate the outgoing credential before anything else: from here + // on the old credential must not authenticate, even if a later step + // fails. yield* secretStore .remove(credentialSecretName(input.instanceId)) .pipe( @@ -444,186 +426,118 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ), ); - if (previousState?.connection) { - yield* failPendingRequests( - input.instanceId, - "A new enrollment replaced the active Hermes gateway credential.", + + yield* settings + .updateSettingsWith((latest) => { + const latestConfigured = latest.providerInstances[input.instanceId]; + if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) return {}; + return { + providerInstances: { + ...latest.providerInstances, + [input.instanceId]: withHermesConfig(latestConfigured, { + nickname, + connectorUrl: input.connectorUrl, + revoked: false, + }), + }, + }; + }) + .pipe( + Effect.mapError(() => + managementError( + "create-enrollment", + "persistence-failed", + "Failed to persist the Hermes gateway enrollment.", + input.instanceId, + ), + ), ); - yield* previousState.connection.transport.close( + + // Any live connection is authenticating with the credential we just + // invalidated, so it can no longer be trusted. + const displaced = yield* connections.clearConnection(input.instanceId); + if (displaced) { + yield* teardownConnection( + input.instanceId, + displaced.transport, 4001, "A new enrollment was created for this instance", ); } - yield* persistMetadata(input.instanceId, metadata); - const enrolledState: InstanceState = { - metadata, - ...(previousState?.lastSeen ? { lastSeen: previousState.lastSeen } : {}), + + const { token, expiresAtMillis } = yield* enrollmentStore.mint({ ...input, nickname }); + + const record: InstanceRecord = { + nickname, + connectorUrl: input.connectorUrl, + revoked: false, }; - yield* Ref.update(states, (current) => - new Map(current).set(input.instanceId, enrolledState), - ); - yield* publishStatus(input.instanceId, enrolledState); - yield* Ref.update(enrollments, (current) => { - const next = new Map(current); - for (const [pendingToken, pending] of current) { - if (pending.input.instanceId === input.instanceId) { - next.delete(pendingToken); - } - } - return next.set(token, { input: normalizedInput, expiresAtMillis }); - }); + yield* publishStatus(input.instanceId, record); return { instanceId: input.instanceId, expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)), connectorUrl: input.connectorUrl, command: `hermes t3 connect --url ${shellQuote(input.connectorUrl)} --token ${shellQuote(token)}`, + // The long-lived credential is structurally absent here: it only + // ever exists on the server→plugin `connection.accepted` frame. oneTimeToken: token, } satisfies HermesGatewayEnrollmentResult; }), ); const getInstanceStatus = (instanceId: ProviderInstanceId) => - getState(instanceId).pipe(Effect.map((state) => statusFromState(instanceId, state))); - - const listInstances = Effect.gen(function* () { - const currentSettings = yield* settings.getSettings.pipe( - Effect.mapError(() => - managementError("list-instances", "internal-error", "Failed to read server settings."), - ), + requireRecord(instanceId, "get-status").pipe( + Effect.flatMap((record) => statusOf(instanceId, record)), ); - const ids = Object.entries(currentSettings.providerInstances) - .filter(([, config]) => config.driver === HERMES_DRIVER_KIND) - .map(([id]) => id as ProviderInstanceId); - return yield* Effect.forEach( - ids, - (instanceId) => - getInstanceStatus(instanceId).pipe( - Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined)), + + const listInstances = readSettings("list-instances").pipe( + Effect.flatMap((currentSettings) => + Effect.forEach( + Object.entries(currentSettings.providerInstances).filter( + ([, config]) => config.driver === HERMES_DRIVER_KIND, ), - { concurrency: "unbounded" }, - ).pipe(Effect.map((values) => values.filter((value) => value !== undefined))); - }); + ([rawId, config]) => { + const instanceId = rawId as ProviderInstanceId; + const record = recordFrom(instanceId, config); + // Configured-but-never-enrolled instances have no gateway status to + // report, so they are omitted rather than listed as offline. + return record && isEnrolled(record) + ? statusOf(instanceId, record) + : Effect.succeed(undefined); + }, + { concurrency: "unbounded" }, + ).pipe(Effect.map((values) => values.filter((value) => value !== undefined))), + ), + ); + /** + * Rename is a pure display-name edit. Instance id is identity; the label is + * free text like every other provider, so there is no uniqueness scan. + */ const renameInstance = (input: HermesGatewayRenameInstanceInput) => - enrollmentSemaphore.withPermits(1)( + withInstanceLock( + input.instanceId, Effect.gen(function* () { - const state = yield* getState(input.instanceId).pipe( + const nickname = normalizeNickname(input.nickname); + yield* requireRecord(input.instanceId, "rename-instance").pipe( Effect.mapError((error) => managementError("rename-instance", error.code, error.message, input.instanceId), ), ); - const normalizedNickname = normalizeNickname(input.nickname); - const currentSettings = yield* settings.getSettings.pipe( - Effect.mapError(() => - managementError( - "rename-instance", - "internal-error", - "Failed to read server settings.", - input.instanceId, - ), - ), - ); - const configured = currentSettings.providerInstances[input.instanceId]; - if (!configured || configured.driver !== HERMES_DRIVER_KIND) { - return yield* managementError( - "rename-instance", - "instance-not-found", - `Provider instance '${input.instanceId}' is not configured with the Hermes driver.`, - input.instanceId, - ); - } - const existingStates = yield* Ref.get(states); - for (const [candidateId, candidateConfig] of Object.entries( - currentSettings.providerInstances, - )) { - if (candidateId === input.instanceId || candidateConfig.driver !== HERMES_DRIVER_KIND) { - continue; - } - const candidateInstanceId = candidateId as ProviderInstanceId; - const persistedMetadata = existingStates.has(candidateInstanceId) - ? undefined - : yield* readMetadata(candidateInstanceId).pipe( - Effect.mapError(() => - managementError( - "rename-instance", - "persistence-failed", - "Failed to read Hermes gateway metadata.", - input.instanceId, - ), - ), - ); - const candidateState = - existingStates.get(candidateInstanceId) ?? - (persistedMetadata ? { metadata: persistedMetadata } : undefined); - const candidateNickname = - candidateState?.metadata.removed === true - ? undefined - : (candidateState?.metadata.nickname ?? candidateConfig.displayName); - if ( - candidateNickname !== undefined && - nicknameComparisonKey(candidateNickname) === nicknameComparisonKey(normalizedNickname) - ) { - return yield* managementError( - "rename-instance", - "nickname-conflict", - `A Hermes gateway named '${normalizedNickname}' already exists.`, - input.instanceId, - ); - } - } - - const metadata: InstanceMetadata = { - ...state.metadata, - nickname: normalizedNickname, - }; - yield* persistMetadata(input.instanceId, metadata).pipe( - Effect.mapError((error) => - managementError("rename-instance", error.code, error.message, input.instanceId), - ), - ); - let settingsUpdate: "pending" | "updated" | "instance-not-found" | "nickname-conflict" = - "pending"; - const readSettingsUpdate = () => settingsUpdate; - yield* settings + const updated = yield* settings .updateSettingsWith((latest) => { const latestConfigured = latest.providerInstances[input.instanceId]; - if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) { - settingsUpdate = "instance-not-found"; - return { providerInstances: latest.providerInstances }; - } - for (const [candidateId, candidateConfig] of Object.entries(latest.providerInstances)) { - if ( - candidateId === input.instanceId || - candidateConfig.driver !== HERMES_DRIVER_KIND || - candidateConfig.displayName === undefined - ) { - continue; - } - if ( - nicknameComparisonKey(candidateConfig.displayName) === - nicknameComparisonKey(normalizedNickname) - ) { - settingsUpdate = "nickname-conflict"; - return { providerInstances: latest.providerInstances }; - } - } - settingsUpdate = "updated"; + if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) return {}; return { providerInstances: { ...latest.providerInstances, - [input.instanceId]: { - ...latestConfigured, - displayName: normalizedNickname, - }, + [input.instanceId]: withHermesConfig(latestConfigured, { nickname }), }, }; }) .pipe( - Effect.tapError(() => - persistMetadata(input.instanceId, state.metadata).pipe(Effect.ignore), - ), Effect.mapError(() => managementError( "rename-instance", @@ -633,51 +547,76 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ), ); - const settingsUpdateResult = readSettingsUpdate(); - if (settingsUpdateResult !== "updated") { - yield* persistMetadata(input.instanceId, state.metadata).pipe(Effect.ignore); + + // The update callback is a pure function of `latest`, so the committed + // settings are the single source of truth for whether it applied — + // no side-channel flag needed. + const record = recordFrom(input.instanceId, updated.providerInstances[input.instanceId]); + if (!record) { return yield* managementError( "rename-instance", - settingsUpdateResult === "pending" ? "internal-error" : settingsUpdateResult, - settingsUpdateResult === "nickname-conflict" - ? `A Hermes gateway named '${normalizedNickname}' already exists.` - : settingsUpdateResult === "instance-not-found" - ? `Provider instance '${input.instanceId}' is no longer configured with the Hermes driver.` - : "Failed to determine the Hermes provider settings update result.", + "instance-not-found", + `Provider instance '${input.instanceId}' is no longer configured with the Hermes driver.`, input.instanceId, ); } - const next: InstanceState = { - ...state, - metadata, - }; - yield* Ref.update(states, (current) => new Map(current).set(input.instanceId, next)); - yield* publishStatus(input.instanceId, next); - return statusFromState(input.instanceId, next) satisfies HermesGatewayRenameInstanceResult; + yield* publishStatus(input.instanceId, record); + return (yield* statusOf( + input.instanceId, + record, + )) satisfies HermesGatewayRenameInstanceResult; }), ); const revokeInstance = (instanceId: ProviderInstanceId) => - enrollmentSemaphore.withPermits(1)( + withInstanceLock( + instanceId, Effect.gen(function* () { - const state = yield* getState(instanceId); - const metadata: InstanceMetadata = { ...state.metadata, revoked: true }; - yield* persistMetadata(instanceId, metadata).pipe( + const existing = yield* requireRecord(instanceId, "revoke-instance").pipe( Effect.mapError((error) => managementError("revoke-instance", error.code, error.message, instanceId), ), ); - const next: InstanceState = { - metadata, - ...(state.lastSeen ? { lastSeen: state.lastSeen } : {}), - }; - yield* Ref.update(states, (current) => new Map(current).set(instanceId, next)); - if (state.connection) { - yield* failPendingRequests(instanceId, "The Hermes gateway credential was revoked."); - yield* state.connection.transport.close(4003, "Hermes gateway credential revoked"); + + yield* settings + .updateSettingsWith((latest) => { + const latestConfigured = latest.providerInstances[instanceId]; + if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) return {}; + return { + providerInstances: { + ...latest.providerInstances, + [instanceId]: withHermesConfig(latestConfigured, { revoked: true }), + }, + }; + }) + .pipe( + Effect.mapError(() => + managementError( + "revoke-instance", + "persistence-failed", + "Failed to persist the Hermes gateway revocation.", + instanceId, + ), + ), + ); + + const record: InstanceRecord = { ...existing, revoked: true }; + yield* enrollmentStore.forget(instanceId); + + const cleared = yield* connections.clearConnection(instanceId); + if (cleared) { + yield* teardownConnection( + instanceId, + cleared.transport, + 4003, + "The Hermes gateway credential was revoked.", + ); } - yield* publishStatus(instanceId, next); + yield* publishStatus(instanceId, record); + + // Credential removal is last and is allowed to fail loudly: revocation + // is already durable in settings, so a reconnect is refused either way. yield* secretStore .remove(credentialSecretName(instanceId)) .pipe( @@ -690,39 +629,17 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ), ); - return statusFromState(instanceId, next) satisfies HermesGatewayRevokeInstanceResult; + + return (yield* statusOf(instanceId, record)) satisfies HermesGatewayRevokeInstanceResult; }), ); const removeInstance = (instanceId: ProviderInstanceId) => - enrollmentSemaphore.withPermits(1)( + withInstanceLock( + instanceId, Effect.gen(function* () { - const currentSettings = yield* settings.getSettings.pipe( - Effect.mapError(() => - managementError( - "remove-instance", - "internal-error", - "Failed to read server settings.", - instanceId, - ), - ), - ); - const configured = currentSettings.providerInstances[instanceId]; - const cachedState = (yield* Ref.get(states)).get(instanceId); - const metadata = - cachedState?.metadata ?? - (yield* readMetadata(instanceId).pipe( - Effect.mapError(() => - managementError( - "remove-instance", - "persistence-failed", - "Failed to read Hermes gateway metadata.", - instanceId, - ), - ), - )); - - if (!metadata && configured?.driver !== HERMES_DRIVER_KIND) { + const record = yield* readRecord(instanceId, "remove-instance"); + if (!record) { return yield* managementError( "remove-instance", "instance-not-found", @@ -730,7 +647,9 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { instanceId, ); } - if (metadata && !metadata.removed && !metadata.revoked) { + // An enrolled instance must be revoked first so its credential is + // invalidated before the config that describes it disappears. + if (isEnrolled(record) && !record.revoked) { return yield* managementError( "remove-instance", "instance-not-revoked", @@ -739,37 +658,14 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } - const tombstone = - metadata && !metadata.removed - ? ({ - ...metadata, - revoked: true, - removed: true, - } satisfies InstanceMetadata) - : metadata; - if (tombstone && !metadata?.removed) { - yield* persistMetadata(instanceId, tombstone).pipe( - Effect.mapError((error) => - managementError("remove-instance", error.code, error.message, instanceId), - ), - ); - } - - const updatedSettings = yield* settings + const updated = yield* settings .updateSettingsWith((current) => { - if (current.providerInstances[instanceId]?.driver !== HERMES_DRIVER_KIND) { - return {}; - } + if (current.providerInstances[instanceId]?.driver !== HERMES_DRIVER_KIND) return {}; const providerInstances = { ...current.providerInstances }; delete providerInstances[instanceId]; return { providerInstances }; }) .pipe( - Effect.tapError(() => - metadata && tombstone !== metadata - ? persistMetadata(instanceId, metadata).pipe(Effect.ignore) - : Effect.void, - ), Effect.mapError(() => managementError( "remove-instance", @@ -779,10 +675,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ), ); - if (updatedSettings.providerInstances[instanceId]?.driver === HERMES_DRIVER_KIND) { - if (metadata && tombstone !== metadata) { - yield* persistMetadata(instanceId, metadata).pipe(Effect.ignore); - } + if (updated.providerInstances[instanceId]?.driver === HERMES_DRIVER_KIND) { return yield* managementError( "remove-instance", "instance-not-found", @@ -790,22 +683,21 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { instanceId, ); } - yield* Ref.update(enrollments, (current) => { - const next = new Map(current); - for (const [token, enrollment] of current) { - if (enrollment.input.instanceId === instanceId) next.delete(token); - } - return next; - }); - yield* Ref.update(states, (current) => { - const next = new Map(current); - if (tombstone) { - next.set(instanceId, { metadata: tombstone }); - } else { - next.delete(instanceId); - } - return next; - }); + + yield* enrollmentStore.forget(instanceId); + const cleared = yield* connections.clearConnection(instanceId); + if (cleared) { + yield* teardownConnection( + instanceId, + cleared.transport, + 4003, + "The Hermes gateway instance was removed.", + ); + } + yield* connections.forget(instanceId); + + // Removing the instance config is the authoritative act; a failure to + // delete the now-unreferenced credential is logged, not surfaced. yield* secretStore.remove(credentialSecretName(instanceId)).pipe( Effect.catch((error) => Effect.logWarning("Failed to clean up a removed Hermes gateway credential", { @@ -818,7 +710,80 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { }), ); - const registerConnectionEffect = ( + // ── Connection lifecycle ────────────────────────────────────────── + + /** + * Ping loop for one connection. Forked into the connection's scope, so it is + * interrupted precisely when that connection is retired or replaced. + * + * A missed pong is not immediately fatal — a busy plugin can be slow — but + * `PING_MAX_MISSED` consecutive misses mean the socket is half-open, and we + * stop pretending otherwise. + */ + const pingLoop = ( + registration: HermesGatewayConnectionRegistration, + transport: HermesGatewayTransport, + ) => + Effect.gen(function* () { + const missed = yield* Ref.make(0); + + const probe = Effect.gen(function* () { + const requestId = `hermes-ping-${registration.instanceId}-${registration.generation}-${yield* Clock.currentTimeMillis}`; + const outcome = yield* correlator + .request({ + owner: registration.instanceId, + requestId, + method: "ping", + timeout: PING_TIMEOUT, + send: transport.send({ + type: "ping", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: requestId as HermesGatewayConnectionHello["requestId"], + sentAt: DateTime.formatIso(yield* DateTime.now), + }), + }) + .pipe(Effect.result); + + if (outcome._tag === "Success") { + yield* Ref.set(missed, 0); + // Healthy: wait a full interval before probing again. + return yield* Effect.sleep(PING_INTERVAL); + } + + const missedCount = yield* Ref.updateAndGet(missed, (value) => value + 1); + // Once a ping is missed, re-probe immediately rather than idling for + // another interval: the point is to confirm or clear the suspicion + // fast enough that in-flight requests get the real reason instead of + // a generic timeout. + if (missedCount < PING_MAX_MISSED) return; + + yield* Effect.logWarning("Hermes gateway connection failed liveness checks", { + instanceId: registration.instanceId, + missedCount, + }); + // Retire before closing: `disconnect` is generation-fenced, so if a + // replacement already landed this is a no-op and we leave it alone. + const retired = yield* connections.disconnect(registration); + if (retired) { + yield* publishCurrentStatus(registration.instanceId, "get-status"); + yield* teardownConnection( + registration.instanceId, + transport, + 4008, + "The Hermes gateway connection stopped responding.", + ); + } + }); + + // First probe runs after one interval — long enough that a plugin which + // just completed the handshake is not immediately re-interrogated. The + // pacing of subsequent probes lives inside `probe` itself, because a + // healthy connection and a suspected-dead one warrant different delays. + yield* Effect.sleep(PING_INTERVAL); + yield* probe.pipe(Effect.forever, Effect.ignoreCause({ log: true })); + }); + + const registerConnection = ( hello: HermesGatewayConnectionHello, transport: HermesGatewayTransport, ) => @@ -827,14 +792,19 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ? hello.capabilities : undefined; + // ── Phase 1: authenticate. Nothing below this line mutates connection + // state, and nothing above it is allowed to. An earlier bug applied + // "incompatible version" state before checking the credential, letting + // an unauthenticated caller knock a healthy instance offline; the test + // "authenticates before applying incompatible connection state" guards + // this ordering. let instanceId: ProviderInstanceId; - let credential: HermesGatewayCredential | undefined; let authenticatedEnrollment: PendingEnrollment | undefined; - let state: InstanceState; + if (hello.authentication.type === "enrollment-token") { const authentication = hello.authentication; - const enrollment = (yield* Ref.get(enrollments)).get(authentication.token); - if (!enrollment || enrollment.expiresAtMillis < (yield* Clock.currentTimeMillis)) { + const enrollment = yield* enrollmentStore.peek(authentication.token); + if (!enrollment) { return yield* Effect.fail( rejection( hello.requestId, @@ -845,36 +815,9 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { } instanceId = enrollment.input.instanceId; authenticatedEnrollment = enrollment; - state = yield* getState(instanceId).pipe( - Effect.mapError(() => - rejection( - hello.requestId, - "invalid-authentication", - "Unknown Hermes gateway instance.", - ), - ), - ); } else { const authentication = hello.authentication; instanceId = authentication.instanceId; - state = yield* getState(instanceId).pipe( - Effect.mapError(() => - rejection( - hello.requestId, - "invalid-authentication", - "Unknown Hermes gateway instance.", - ), - ), - ); - if (state.metadata.revoked) { - return yield* Effect.fail( - rejection( - hello.requestId, - "instance-revoked", - "This Hermes gateway instance has been revoked.", - ), - ); - } const stored = yield* secretStore .get(credentialSecretName(instanceId)) .pipe( @@ -897,16 +840,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { } } - if (state.metadata.revoked) { - return yield* Effect.fail( - rejection( - hello.requestId, - "instance-revoked", - "This Hermes gateway instance has been revoked.", - ), - ); - } - const currentSettings = yield* settings.getSettings.pipe( + const record = yield* readRecord(instanceId, "get-status").pipe( Effect.mapError(() => rejection( hello.requestId, @@ -915,7 +849,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ), ); - if (currentSettings.providerInstances[instanceId]?.driver !== HERMES_DRIVER_KIND) { + if (!record) { return yield* Effect.fail( rejection( hello.requestId, @@ -924,32 +858,39 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ); } + if (record.revoked) { + return yield* Effect.fail( + rejection( + hello.requestId, + "instance-revoked", + "This Hermes gateway instance has been revoked.", + ), + ); + } + // ── Phase 2: the caller is authenticated. State changes may begin. if ( hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION || strictCapabilities === undefined ) { - if (state.connection) { - yield* failPendingRequests( - instanceId, - "The Hermes gateway plugin requires a protocol upgrade.", - ); - yield* state.connection.transport.close( - 4004, - "Hermes gateway protocol version is incompatible", - ); - } - const upgradeState: InstanceState = { - metadata: state.metadata, - ...(state.lastSeen ? { lastSeen: state.lastSeen } : {}), + const displaced = yield* connections.markUpgradeRequired({ + instanceId, upgradeRequired: { pluginVersion: hello.pluginVersion, hermesVersion: hello.hermesVersion, protocolVersion: hello.protocolVersion, + model: hello.model ?? null, }, - }; - yield* Ref.update(states, (current) => new Map(current).set(instanceId, upgradeState)); - yield* publishStatus(instanceId, upgradeState); + }); + if (displaced) { + yield* teardownConnection( + instanceId, + displaced.transport, + 4004, + "The Hermes gateway plugin requires a protocol upgrade.", + ); + } + yield* publishStatus(instanceId, record); return yield* Effect.fail( rejection( hello.requestId, @@ -959,18 +900,14 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } + let credential: HermesGatewayCredential | undefined; if (hello.authentication.type === "enrollment-token" && authenticatedEnrollment) { const authentication = hello.authentication; - const enrollment = yield* Ref.modify(enrollments, (current) => { - const found = current.get(authentication.token); - const next = new Map(current); - if (found === authenticatedEnrollment) next.delete(authentication.token); - return [found, next] as const; - }); - if ( - enrollment !== authenticatedEnrollment || - enrollment.expiresAtMillis < (yield* Clock.currentTimeMillis) - ) { + const consumed = yield* enrollmentStore.consume( + authentication.token, + authenticatedEnrollment, + ); + if (!consumed) { return yield* Effect.fail( rejection( hello.requestId, @@ -979,11 +916,11 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ); } - instanceId = enrollment.input.instanceId; + instanceId = consumed.input.instanceId; credential = HermesGatewayCredential.make( Encoding.encodeBase64Url( yield* crypto - .randomBytes(32) + .randomBytes(CREDENTIAL_BYTES) .pipe( Effect.mapError(() => rejection( @@ -1008,239 +945,256 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } - const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1); - const connectedAt = DateTime.formatIso(yield* DateTime.now); - const connection = { - generation: nextGeneration, - transport, + const observed: HermesObservedConnection = { pluginVersion: hello.pluginVersion, hermesVersion: hello.hermesVersion, capabilities: strictCapabilities, - connectedAt, + model: hello.model ?? null, + connectedAt: DateTime.formatIso(yield* DateTime.now), activeSessionCount: 0, - } satisfies ActiveConnection; - const lastSeen = { - pluginVersion: connection.pluginVersion, - hermesVersion: connection.hermesVersion, - capabilities: connection.capabilities, - connectedAt: connection.connectedAt, - activeSessionCount: connection.activeSessionCount, }; - const connectedMetadata: InstanceMetadata = { - ...state.metadata, - lastSeen, - }; - yield* persistMetadata(instanceId, connectedMetadata).pipe( - Effect.mapError(() => - rejection( - hello.requestId, - "internal-error", - "Failed to persist Hermes gateway connection metadata.", - ), - ), - ); - if (state.connection) { - yield* failPendingRequests( + const accepted = yield* connections.accept({ instanceId, transport, observed }); + if (accepted.displaced) { + yield* teardownConnection( instanceId, + accepted.displaced.transport, + 4001, "The Hermes gateway connection was replaced by a newer connection.", ); - yield* state.connection.transport.close(4001, "Replaced by a newer connection"); } - yield* Ref.update(states, (current) => - new Map(current).set(instanceId, { - metadata: connectedMetadata, - connection, - lastSeen, - }), - ); - yield* publishStatus(instanceId, { - metadata: connectedMetadata, - connection, - lastSeen, - }); - const accepted = { - type: "connection.accepted", - requestId: hello.requestId, - protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + const registration = { instanceId, - nickname: state.metadata.nickname, - ...(credential ? { credential } : {}), - } as const; - return { - instanceId, - generation: nextGeneration, - accepted, - } satisfies HermesGatewayConnectionRegistration; + generation: accepted.generation, + accepted: { + type: "connection.accepted", + requestId: hello.requestId, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId, + nickname: record.nickname, + ...(credential ? { credential } : {}), + }, + } as const satisfies HermesGatewayConnectionRegistration; + + // Liveness probing belongs to this connection's scope, so it is + // interrupted the moment the connection is retired. + const liveness = yield* connections.liveness(instanceId); + if (liveness?.connection?.generation === accepted.generation) { + yield* pingLoop(registration, transport).pipe(Effect.forkIn(liveness.connection.scope)); + } + + yield* publishStatus(instanceId, record); + return registration; }); - const registerConnection = ( - hello: HermesGatewayConnectionHello, - transport: HermesGatewayTransport, - ) => enrollmentSemaphore.withPermits(1)(registerConnectionEffect(hello, transport)); - const receive = (registration: HermesGatewayConnectionRegistration, message: PluginMessage) => Effect.gen(function* () { - const state = (yield* Ref.get(states)).get(registration.instanceId); - if (state?.connection?.generation !== registration.generation) return; if (message.type === "connection.status") { - yield* Ref.update(states, (current) => { - const found = current.get(registration.instanceId); - if (found?.connection?.generation !== registration.generation) return current; - return new Map(current).set(registration.instanceId, { - ...found, - connection: { - ...found.connection, - activeSessionCount: message.activeSessionCount, - }, - }); - }); - const updated = (yield* Ref.get(states)).get(registration.instanceId); - if (updated) yield* publishStatus(registration.instanceId, updated); + // Generation-fenced inside the Ref update; a stale registration is a + // no-op rather than an overwrite. + const applied = yield* connections.recordSessionCount( + registration, + message.activeSessionCount, + ); + if (!applied) return; + yield* publishCurrentStatus(registration.instanceId, "get-status"); + } else { + const liveness = yield* connections.liveness(registration.instanceId); + if (liveness?.connection?.generation !== registration.generation) return; } + if ("requestId" in message && message.requestId) { - const correlatedRequestId = message.requestId; - const pending = yield* Ref.modify(pendingRequests, (current) => { - const found = current.get(correlatedRequestId); - if (!found) return [undefined, current] as const; - const next = new Map(current); - next.delete(correlatedRequestId); - return [found, next] as const; - }); - if (pending) { - yield* Deferred.succeed(pending.deferred, message); - } + yield* correlator.complete(message.requestId, message); } - yield* PubSub.publish(events, { - instanceId: registration.instanceId, - message, - }); + yield* PubSub.publish(events, { instanceId: registration.instanceId, message }); }); const disconnect = (registration: HermesGatewayConnectionRegistration) => Effect.gen(function* () { - let disconnected: InstanceState | undefined; - yield* Ref.update(states, (current) => { - const found = current.get(registration.instanceId); - if (found?.connection?.generation !== registration.generation) return current; - const next = new Map(current); - const lastSeen = { - pluginVersion: found.connection.pluginVersion, - hermesVersion: found.connection.hermesVersion, - capabilities: found.connection.capabilities, - connectedAt: found.connection.connectedAt, - activeSessionCount: found.connection.activeSessionCount, - }; - disconnected = { - metadata: { ...found.metadata, lastSeen }, - lastSeen, - }; - next.set(registration.instanceId, disconnected); - return next; - }); - if (disconnected) { - yield* persistMetadata(registration.instanceId, disconnected.metadata).pipe(Effect.ignore); - } - if (disconnected) yield* publishStatus(registration.instanceId, disconnected); - if (disconnected) { - yield* failPendingRequests( - registration.instanceId, - "The Hermes gateway connection disconnected.", - ); - } + const retired = yield* connections.disconnect(registration); + if (!retired) return; + yield* publishCurrentStatus(registration.instanceId, "get-status"); + yield* failPendingRequests( + registration.instanceId, + "The Hermes gateway connection disconnected.", + ); }); + // ── Messaging ───────────────────────────────────────────────────── + const send = (instanceId: ProviderInstanceId, message: HermesGatewayT3ToPluginMessage) => - Effect.gen(function* () { - const state = (yield* Ref.get(states)).get(instanceId); - if (!state?.connection) { - return yield* new ProviderAdapterRequestError({ - provider: "hermes", - method: message.type, - detail: `Hermes gateway instance '${instanceId}' is offline.`, - }); - } - yield* state.connection.transport.send(message); - }); - - const request = (instanceId: ProviderInstanceId, message: HermesGatewayT3ToPluginMessage) => - Effect.gen(function* () { - if (!("requestId" in message) || !message.requestId) { - return yield* new ProviderAdapterRequestError({ - provider: "hermes", - method: message.type, - detail: "A correlated Hermes gateway request requires a request id.", - }); - } - const deferred = yield* Deferred.make(); - yield* Ref.update(pendingRequests, (current) => - new Map(current).set(message.requestId as string, { - instanceId, - deferred, - }), - ); - yield* send(instanceId, message).pipe( - Effect.tapError(() => - Ref.update(pendingRequests, (current) => { - const next = new Map(current); - next.delete(message.requestId as string); - return next; - }), - ), - ); - return yield* Deferred.await(deferred).pipe( - Effect.timeout(REQUEST_TIMEOUT), - Effect.mapError((error) => - error._tag === "TimeoutError" - ? new ProviderAdapterRequestError({ - provider: "hermes", + connections.transport(instanceId).pipe( + Effect.flatMap((transport) => + transport + ? transport.send(message) + : Effect.fail( + new ProviderAdapterRequestError({ + provider: HERMES_DRIVER_KIND, method: message.type, - detail: "Hermes gateway request timed out.", - }) - : error, - ), - Effect.ensuring( - Ref.update(pendingRequests, (current) => { - const next = new Map(current); - next.delete(message.requestId as string); - return next; - }), - ), - ); - }); - - const isConnected = (instanceId: ProviderInstanceId) => - Ref.get(states).pipe( - Effect.map((current) => current.get(instanceId)?.connection !== undefined), + detail: `Hermes gateway instance '${instanceId}' is offline.`, + }), + ), + ), ); - const defaultInstanceId = defaultInstanceIdForDriver(HERMES_DRIVER_KIND); - yield* Effect.gen(function* () { - const metadata = yield* readMetadata(defaultInstanceId); - if (!metadata || metadata.removed) return; - yield* settings.updateSettingsWith((current) => { - if (current.providerInstances[defaultInstanceId] !== undefined) return {}; - return { - providerInstances: { - ...current.providerInstances, - [defaultInstanceId]: { - driver: HERMES_DRIVER_KIND, - displayName: metadata.nickname, - enabled: true, - config: {}, - }, - }, - }; + const request = (instanceId: ProviderInstanceId, message: HermesGatewayT3ToPluginMessage) => { + if (!("requestId" in message) || !message.requestId) { + return Effect.fail( + new ProviderAdapterRequestError({ + provider: HERMES_DRIVER_KIND, + method: message.type, + detail: "A correlated Hermes gateway request requires a request id.", + }), + ); + } + return correlator.request({ + owner: instanceId, + requestId: message.requestId, + method: message.type, + send: send(instanceId, message), }); + }; + + // ── Boot: migrate legacy metadata, then start sweepers ──────────── + + const LEGACY_METADATA_PREFIX = "hermes-gateway-metadata-"; + + /** + * Recover instance ids from legacy metadata filenames in the secrets + * directory. `ServerSecretStore` has no listing API, and an orphaned blob is + * by definition one that settings no longer references — so without this + * scan the exact files we most need to clean up are unreachable. + * + * Entirely best-effort: no config, no filesystem, or an unreadable directory + * all degrade to "found nothing" rather than failing boot. + */ + const discoverLegacyMetadataInstanceIds = Effect.gen(function* () { + const config = yield* Effect.serviceOption(ServerConfig.ServerConfig); + const fs = yield* Effect.serviceOption(FileSystem.FileSystem); + if (Option.isNone(config) || Option.isNone(fs)) return []; + + const entries = yield* fs.value + .readDirectory(config.value.secretsDir) + .pipe(Effect.orElseSucceed(() => [] as Array)); + + return entries.flatMap((entry) => { + const base = entry.endsWith(".bin") ? entry.slice(0, -".bin".length) : entry; + if (!base.startsWith(LEGACY_METADATA_PREFIX)) return []; + const encoded = base.slice(LEGACY_METADATA_PREFIX.length); + const decodedId = Buffer.from(encoded, "base64url").toString("utf8"); + // Round-trip guard: only accept names this scheme could have produced. + if (Buffer.from(decodedId, "utf8").toString("base64url") !== encoded) return []; + return isProviderInstanceId(decodedId) ? [decodedId] : []; + }); + }).pipe(Effect.orElseSucceed(() => [] as Array)); + + /** + * Fold pre-existing secret-store metadata blobs into settings and delete + * them. Ordering is deliberate: the settings write must succeed before the + * secret file is deleted, so a crash in between re-runs the migration rather + * than losing the enrollment facts. + */ + const migrateLegacyMetadata = Effect.gen(function* () { + const currentSettings = yield* settings.getSettings; + const defaultInstanceId = defaultInstanceIdForDriver(HERMES_DRIVER_KIND); + const candidates = new Set([ + defaultInstanceId, + ...Object.entries(currentSettings.providerInstances) + .filter(([, config]) => config.driver === HERMES_DRIVER_KIND) + .map(([rawId]) => rawId as ProviderInstanceId), + // The real orphans are precisely the ones settings no longer mentions, + // so scanning the secrets directory is the only way to find them. The + // store has no listing API; reading the directory directly is + // best-effort and never fatal. + ...(yield* discoverLegacyMetadataInstanceIds), + ]); + + for (const instanceId of candidates) { + const secretName = legacyMetadataSecretName(instanceId); + const stored = yield* secretStore.get(secretName); + if (Option.isNone(stored)) continue; + + const decoded = yield* decodeLegacyMetadata(new TextDecoder().decode(stored.value)).pipe( + Effect.result, + ); + if (decoded._tag === "Failure") { + yield* Effect.logWarning("Discarding unreadable legacy Hermes gateway metadata", { + instanceId, + }); + yield* secretStore.remove(secretName).pipe(Effect.ignore); + continue; + } + const metadata: LegacyInstanceMetadata = decoded.success; + + const configured = currentSettings.providerInstances[instanceId]; + const isHermesInstance = configured?.driver === HERMES_DRIVER_KIND; + + // A tombstone, or a blob for an instance nobody configures any more, has + // nothing to fold into. Drop the file and the orphaned credential — this + // is the leak the old code never cleaned up, because the tombstone name + // was only ever passed to get/set and never to remove. + if (metadata.removed || !isHermesInstance) { + yield* secretStore.remove(secretName).pipe(Effect.ignore); + yield* secretStore.remove(credentialSecretName(instanceId)).pipe(Effect.ignore); + continue; + } + + const committed = yield* settings + .updateSettingsWith((latest) => { + const latestConfigured = latest.providerInstances[instanceId]; + if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) return {}; + const existing = readHermesConfig(latestConfigured); + return { + providerInstances: { + ...latest.providerInstances, + [instanceId]: withHermesConfig(latestConfigured, { + // Settings already win where they carry a value; the blob only + // fills gaps. + nickname: latestConfigured.displayName ?? metadata.nickname, + connectorUrl: existing?.connectorUrl ?? metadata.connectorUrl, + revoked: existing?.revoked === true ? true : metadata.revoked, + }), + }, + }; + }) + .pipe(Effect.result); + + if (committed._tag === "Failure") { + yield* Effect.logWarning("Deferring Hermes gateway metadata migration", { instanceId }); + continue; + } + + const migrated = recordFrom(instanceId, committed.success.providerInstances[instanceId]); + if (!migrated) { + yield* Effect.logWarning("Deferring Hermes gateway metadata migration", { instanceId }); + continue; + } + + // Only now, with the durable equivalent committed, is the blob + // redundant. The credential is kept: this instance is still configured + // and its plugin must be able to reconnect. + yield* secretStore.remove(secretName).pipe(Effect.ignore); + if (migrated.revoked) { + yield* secretStore.remove(credentialSecretName(instanceId)).pipe(Effect.ignore); + } + } }).pipe( - Effect.catch((error) => - Effect.logWarning("Failed to migrate a legacy Hermes gateway instance into settings", { - instanceId: defaultInstanceId, - error, - }), + Effect.catchCause((cause) => + Effect.logWarning("Failed to migrate legacy Hermes gateway metadata", { cause }), ), ); + yield* migrateLegacyMetadata; + + // Bounded memory: expired tokens and abandoned request entries are reaped + // on a timer rather than only lazily at redemption. + yield* enrollmentStore.sweep.pipe( + Effect.andThen(correlator.sweep), + Effect.repeat(Schedule.spaced(SWEEP_INTERVAL)), + Effect.ignoreCause({ log: true }), + Effect.forkScoped, + ); + return { createEnrollment, getInstanceStatus, @@ -1253,10 +1207,14 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { disconnect, request, send, - isConnected, + isConnected: connections.isConnected, stream: Stream.fromPubSub(events), streamStatuses: Stream.fromPubSub(statusEvents), } satisfies HermesGatewayBrokerShape; }); export const HermesGatewayBrokerLive = Layer.effect(HermesGatewayBroker, makeHermesGatewayBroker); + +/** Exported so tests can seed and assert on migration inputs by exact name. */ +export const hermesGatewayLegacyMetadataSecretName = legacyMetadataSecretName; +export const hermesGatewayCredentialSecretName = credentialSecretName; diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index def796b3ab..6ea5c9a756 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -1346,6 +1346,75 @@ routing.layer("ProviderServiceLive routing", (it) => { } } + // A *failed* completion of the active turn must persist "error". This + // shared a ternary branch with turn.started and wrote "running" for every + // settled turn, failed ones included. + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello again", + attachments: [], + }); + yield* advanceTestClock(50); + routing.codex.emit({ + type: "turn.completed", + eventId: asEventId("evt-runtime-status-failed-completion"), + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:02.500Z", + threadId: session.threadId, + turnId: asTurnId(`turn-${String(session.threadId)}`), + payload: { + state: "failed", + errorMessage: "Hermes could not resume this thread after reconnecting.", + }, + }); + yield* advanceTestClock(50); + + const afterFailedCompletion = yield* runtimeRepository.getByThreadId({ + threadId: session.threadId, + }); + assert.equal(Option.isSome(afterFailedCompletion), true); + if (Option.isSome(afterFailedCompletion)) { + assert.equal(afterFailedCompletion.value.status, "error"); + const payload = afterFailedCompletion.value.runtimePayload; + if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) { + assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null); + } + } + + // A matching turn.aborted settles the same way, minus the error. + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello once more", + attachments: [], + }); + yield* advanceTestClock(50); + routing.codex.emit({ + type: "turn.aborted", + eventId: asEventId("evt-runtime-status-active-abort"), + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:02.750Z", + threadId: session.threadId, + turnId: asTurnId(`turn-${String(session.threadId)}`), + payload: { reason: "interrupted" }, + }); + yield* advanceTestClock(50); + + const afterAbort = yield* runtimeRepository.getByThreadId({ + threadId: session.threadId, + }); + assert.equal(Option.isSome(afterAbort), true); + if (Option.isSome(afterAbort)) { + assert.equal(afterAbort.value.status, "running"); + const payload = afterAbort.value.runtimePayload; + if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) { + assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null); + assert.equal( + "lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined, + "turn.aborted", + ); + } + } + routing.codex.emit({ type: "session.exited", eventId: asEventId("evt-runtime-status-session-exit"), diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 70dc153f84..55a0b7dbf2 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -330,14 +330,28 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( event.turnId !== undefined && persistedActiveTurnId === event.turnId; const isSessionExit = event.type === "session.exited"; + // `turn.started` and a terminal event that closes the active turn are + // opposite transitions and must not share a branch. Folded together they + // persisted "running" for every settled turn — including a *failed* one, + // which is the lie this split removes. + // + // A non-failed terminal still writes "running": this status describes the + // session, not the turn (`toRuntimeStatus` maps both ready and running to + // it), and the settled turn is expressed by `activeTurnId: null` below. + // "stopped" is reserved for sessions that are actually gone — the reaper + // skips those, so using it for an idle session would strand it. const status = - event.type === "turn.started" || terminalMatchesActiveTurn + event.type === "turn.started" ? "running" - : isSessionExit - ? event.payload.recoverable === true || event.payload.exitKind === "error" + : terminalMatchesActiveTurn + ? event.type === "turn.completed" && event.payload.state === "failed" ? "error" - : "stopped" - : undefined; + : "running" + : isSessionExit + ? event.payload.recoverable === true || event.payload.exitKind === "error" + ? "error" + : "stopped" + : undefined; const activeTurnId = event.type === "turn.started" ? (event.turnId ?? persistedActiveTurnId) diff --git a/apps/server/src/provider/Layers/RequestCorrelator.ts b/apps/server/src/provider/Layers/RequestCorrelator.ts new file mode 100644 index 0000000000..2f1a693cfc --- /dev/null +++ b/apps/server/src/provider/Layers/RequestCorrelator.ts @@ -0,0 +1,160 @@ +/** + * Live {@link RequestCorrelator} implementation. + * + * Generic over the owner key (the route a request travels over) and the + * response payload, so this is reusable by any provider with correlated + * request/response framing — see the module docs on the service for why the + * interrupt-safety and sweeping guarantees live here rather than at call sites. + * + * @module Layers/RequestCorrelator + */ +import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; + +import { ProviderAdapterRequestError } from "../Errors.ts"; +import type { RequestCorrelator, RequestCorrelatorSend } from "../Services/RequestCorrelator.ts"; + +interface PendingRequest { + readonly owner: Owner; + readonly method: string; + readonly registeredAtMillis: number; + readonly deferred: Deferred.Deferred; +} + +export interface MakeRequestCorrelatorOptions { + /** Provider name stamped onto `ProviderAdapterRequestError`. */ + readonly provider: string; + /** Default response timeout when a request does not override it. */ + readonly timeout: Duration.Duration; + /** + * Entries older than this are reaped by `sweep`. Comfortably larger than + * `timeout` so the sweeper only ever catches entries whose own timeout + * pipeline failed to run — a normal slow request is never stolen from + * underneath its awaiting fiber. + */ + readonly maxAge: Duration.Duration; +} + +export const makeRequestCorrelator = ( + options: MakeRequestCorrelatorOptions, +): Effect.Effect> => + Effect.gen(function* () { + const pending = yield* Ref.make(new Map>()); + + const requestError = (method: string, detail: string) => + new ProviderAdapterRequestError({ provider: options.provider, method, detail }); + + /** Remove one entry by id. Safe to call when it is already gone. */ + const release = (requestId: string) => + Ref.update(pending, (current) => { + if (!current.has(requestId)) return current; + const next = new Map(current); + next.delete(requestId); + return next; + }); + + const request = (input: RequestCorrelatorSend) => + Effect.gen(function* () { + const deferred = yield* Deferred.make(); + const registeredAtMillis = yield* Clock.currentTimeMillis; + + // Registration and the send must not be interruptible independently of + // the cleanup that removes the entry. `uninterruptibleMask` closes the + // window: the registration is applied, `restore` re-enables interrupts + // only inside the awaiting pipeline, and `ensuring` guarantees release + // regardless of how that pipeline exits. + return yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + yield* Ref.update(pending, (current) => + new Map(current).set(input.requestId, { + owner: input.owner, + method: input.method, + registeredAtMillis, + deferred, + }), + ); + + yield* input.send.pipe(Effect.tapError(() => release(input.requestId))); + + return yield* restore(Deferred.await(deferred)).pipe( + Effect.timeout(input.timeout ?? options.timeout), + Effect.mapError((error) => + error._tag === "TimeoutError" + ? requestError(input.method, `${options.provider} request timed out.`) + : error, + ), + Effect.ensuring(release(input.requestId)), + ); + }), + ); + }); + + const complete = (requestId: string, response: Response) => + Ref.modify(pending, (current) => { + const found = current.get(requestId); + if (!found) return [undefined, current] as const; + const next = new Map(current); + next.delete(requestId); + return [found, next] as const; + }).pipe( + Effect.flatMap((found) => + found === undefined + ? Effect.succeed(false) + : Deferred.succeed(found.deferred, response).pipe(Effect.as(true)), + ), + ); + + /** + * Extract every entry matching `select`, then fail their deferreds. The + * extraction is a single `Ref.modify` so two concurrent failures cannot + * both claim the same entry. + */ + const failMatching = ( + select: (entry: PendingRequest) => boolean, + detail: (entry: PendingRequest) => string, + ) => + Ref.modify(pending, (current) => { + const claimed: Array> = []; + const next = new Map(current); + for (const [requestId, entry] of current) { + if (!select(entry)) continue; + claimed.push(entry); + next.delete(requestId); + } + return [claimed, next] as const; + }).pipe( + Effect.flatMap((claimed) => + Effect.forEach( + claimed, + (entry) => Deferred.fail(entry.deferred, requestError(entry.method, detail(entry))), + { discard: true }, + ), + ), + ); + + const failOwner = (owner: Owner, detail: string) => + failMatching( + (entry) => entry.owner === owner, + () => detail, + ); + + const sweep = Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + failMatching( + (entry) => now - entry.registeredAtMillis >= Duration.toMillis(options.maxAge), + () => `${options.provider} request was abandoned before it completed.`, + ), + ), + ); + + return { + request, + complete, + failOwner, + sweep, + pendingCount: Ref.get(pending).pipe(Effect.map((current) => current.size)), + } satisfies RequestCorrelator; + }); diff --git a/apps/server/src/provider/Services/HermesConnectionRegistry.ts b/apps/server/src/provider/Services/HermesConnectionRegistry.ts new file mode 100644 index 0000000000..a5a2cb7c06 --- /dev/null +++ b/apps/server/src/provider/Services/HermesConnectionRegistry.ts @@ -0,0 +1,166 @@ +/** + * HermesConnectionRegistry — owner of **volatile** Hermes gateway liveness. + * + * Everything in here is deliberately memory-only and is never persisted: + * the live connection, its transport, `lastSeen`, `activeSessionCount`, the + * reported model, and the `upgrade-required` observation. + * + * Why liveness must not be persisted + * ---------------------------------- + * `ProviderInstanceRegistryLive.reconcile` structurally compares each + * `ProviderInstanceConfig` envelope and closes the instance scope on **any** + * change. Closing that scope runs `HermesAdapter`'s finalizer, which calls + * `stopAll()` and sends `session.stop` to Hermes for every live thread. So + * writing something like `connectedAt` into the instance config on every + * connect would tear down every Hermes session on every reconnect. + * + * The broker (and therefore this registry) is a top-level layer that survives + * reconcile, which makes it the correct owner of liveness. The accepted + * consequence is that after a T3 server restart the UI reports "never + * connected" until the plugin dials back in. That is intended. + * + * Generation fencing + * ------------------ + * Every accepted connection gets a monotonically increasing generation. All + * post-acceptance mutations are fenced on it, and the comparison happens + * *inside* the `Ref` update rather than as a separate read, so a replacement + * landing concurrently cannot be clobbered by a stale writer (TOCTOU). + * + * @module HermesConnectionRegistry + */ +import type { + HermesGatewayCapabilities, + HermesGatewayInstanceStatus, + ProviderInstanceId, +} from "@t3tools/contracts"; +import type * as Effect from "effect/Effect"; +import type * as Scope from "effect/Scope"; + +import type { + HermesGatewayConnectionRegistration, + HermesGatewayTransport, +} from "./HermesGatewayBroker.ts"; + +/** Observed facts about a plugin connection, independent of its transport. */ +export interface HermesObservedConnection { + readonly pluginVersion: string; + readonly hermesVersion: string; + readonly capabilities: HermesGatewayCapabilities; + /** Model reported at handshake. Null when the plugin predates the field. */ + readonly model: string | null; + readonly connectedAt: string; + readonly activeSessionCount: number; +} + +export interface HermesActiveConnection extends HermesObservedConnection { + readonly generation: number; + readonly transport: HermesGatewayTransport; + /** + * Scope tied to this connection's lifetime. Per-connection fibers (the ping + * loop) are forked into it, so they die exactly when the connection does. + */ + readonly scope: Scope.Closeable; +} + +export interface HermesUpgradeRequired { + readonly pluginVersion: string; + readonly hermesVersion: string; + readonly protocolVersion: number; + readonly model: string | null; +} + +/** Volatile per-instance liveness. Absent entry means "nothing observed yet". */ +export interface HermesInstanceLiveness { + readonly connection?: HermesActiveConnection | undefined; + readonly lastSeen?: HermesObservedConnection | undefined; + readonly upgradeRequired?: HermesUpgradeRequired | undefined; +} + +export interface HermesAcceptedConnection { + readonly generation: number; + /** + * The connection this one displaced, if any. The caller is responsible for + * closing it — the registry never touches a transport itself, so callers can + * order the close against failing pending requests. + */ + readonly displaced: HermesActiveConnection | undefined; +} + +export interface HermesConnectionRegistry { + /** Current liveness for one instance, or `undefined` if nothing observed. */ + readonly liveness: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + + /** Accept a connection, assigning it the next generation. */ + readonly accept: (input: { + readonly instanceId: ProviderInstanceId; + readonly transport: HermesGatewayTransport; + readonly observed: HermesObservedConnection; + }) => Effect.Effect; + + /** + * Record an incompatible plugin. Clears any live connection for the instance + * and returns it so the caller can close it. + */ + readonly markUpgradeRequired: (input: { + readonly instanceId: ProviderInstanceId; + readonly upgradeRequired: HermesUpgradeRequired; + }) => Effect.Effect; + + /** + * Update the active session count. Generation-fenced; returns `false` when + * the registration is stale, in which case nothing was written. + */ + readonly recordSessionCount: ( + registration: HermesGatewayConnectionRegistration, + activeSessionCount: number, + ) => Effect.Effect; + + /** + * Retire a connection, demoting it to `lastSeen`. Generation-fenced; + * returns the retired connection, or `undefined` when the registration is + * stale (already replaced) and nothing was changed. + */ + readonly disconnect: ( + registration: HermesGatewayConnectionRegistration, + ) => Effect.Effect; + + /** + * Clear the live connection for an instance regardless of generation, e.g. + * on revoke. Returns it so the caller can close the transport. + */ + readonly clearConnection: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + + /** Drop all liveness for an instance (on remove). */ + readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect; + + /** Whether a live connection exists. */ + readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect; + + /** Live transport for an instance, if connected. */ + readonly transport: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; +} + +/** + * Project the status fields owned by liveness. The durable half (nickname, + * connectorUrl, revoked) is layered on by the broker, which reads it from + * settings. + */ +export type HermesLivenessStatusFields = Pick< + HermesGatewayInstanceStatus, + | "lastConnectedAt" + | "pluginVersion" + | "hermesVersion" + | "model" + | "activeSessionCount" + | "protocolVersion" + | "capabilities" +> & { + readonly connected: boolean; + readonly upgradeRequired: boolean; +}; diff --git a/apps/server/src/provider/Services/HermesEnrollmentStore.ts b/apps/server/src/provider/Services/HermesEnrollmentStore.ts new file mode 100644 index 0000000000..ebcbdd134e --- /dev/null +++ b/apps/server/src/provider/Services/HermesEnrollmentStore.ts @@ -0,0 +1,68 @@ +/** + * HermesEnrollmentStore — the mint/consume/expire lifecycle of one-time + * enrollment tokens. + * + * Separated from the broker so the token rules live in one place: + * + * - A token is redeemable exactly once. Consumption is compare-and-swap: + * the entry is deleted only if it is still byte-identical to the one the + * caller authenticated against, and expiry is re-checked afterwards, so + * two concurrent redemptions cannot both win. + * - Minting a token for an instance invalidates that instance's previous + * tokens, so only the newest unconsumed token is ever redeemable. + * - Tokens expire from memory on a sweep, not only lazily at redemption. + * Redemption-time expiry alone let any operator-scoped client grow the + * map without bound by calling createEnrollment in a loop. + * + * @module HermesEnrollmentStore + */ +import type { + HermesGatewayCreateEnrollmentInput, + HermesGatewayEnrollmentToken, + ProviderInstanceId, +} from "@t3tools/contracts"; +import type * as Effect from "effect/Effect"; + +export interface PendingEnrollment { + readonly input: HermesGatewayCreateEnrollmentInput; + readonly expiresAtMillis: number; +} + +export interface HermesEnrollmentStore { + /** + * Mint a token for `input`, invalidating any prior unconsumed token for the + * same instance. Returns the token and its absolute expiry. + */ + readonly mint: ( + input: HermesGatewayCreateEnrollmentInput, + ) => Effect.Effect< + { readonly token: HermesGatewayEnrollmentToken; readonly expiresAtMillis: number }, + never + >; + + /** + * Look up a token without consuming it. Returns `undefined` when the token + * is unknown or already expired — the caller authenticates against this + * value and later passes it back to `consume`. + */ + readonly peek: (token: string) => Effect.Effect; + + /** + * Compare-and-swap consumption. Deletes the entry only if it is still + * identical to `expected`, then re-checks expiry. Returns the consumed + * enrollment, or `undefined` if it was raced away or expired in between. + */ + readonly consume: ( + token: string, + expected: PendingEnrollment, + ) => Effect.Effect; + + /** Drop every unconsumed token belonging to `instanceId`. */ + readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect; + + /** Drop every expired token. Run periodically; bounds memory. */ + readonly sweep: Effect.Effect; + + /** Number of unconsumed tokens. Exposed for tests and diagnostics. */ + readonly size: Effect.Effect; +} diff --git a/apps/server/src/provider/Services/RequestCorrelator.ts b/apps/server/src/provider/Services/RequestCorrelator.ts new file mode 100644 index 0000000000..99682062b7 --- /dev/null +++ b/apps/server/src/provider/Services/RequestCorrelator.ts @@ -0,0 +1,69 @@ +/** + * RequestCorrelator — generic request/response correlation over a one-way + * message transport. + * + * Nothing in here is Hermes-specific. Any provider that speaks a protocol + * where a request carries an id and the reply echoes it can use this: register + * a pending entry, write the request, await the correlated reply, and have the + * entry torn down on success, failure, timeout, or interrupt. + * + * The correlator owns three guarantees the call sites used to hand-roll: + * + * 1. **No interrupt window.** Registration happens uninterruptibly and the + * await pipeline is wrapped in `ensuring`, so there is no point at which + * an interrupt can leave an entry in the map with nobody to clean it up. + * 2. **Age-based sweeping.** An entry whose awaiting fiber died abnormally + * is reaped by `sweep` instead of leaking for the process lifetime. + * 3. **Owner-scoped failure.** When a connection drops, every request routed + * over it fails immediately rather than waiting out its timeout. + * + * @module RequestCorrelator + */ +import type * as Duration from "effect/Duration"; +import type * as Effect from "effect/Effect"; + +import type { ProviderAdapterRequestError } from "../Errors.ts"; + +export interface RequestCorrelatorSend { + /** + * The logical route the request travels over. Used to fail an entire group + * of in-flight requests at once when that route dies (see `failOwner`). + */ + readonly owner: Owner; + /** Correlation key. Must match the id echoed on the response. */ + readonly requestId: string; + /** Protocol method name, surfaced on errors for diagnostics. */ + readonly method: string; + /** Writes the request. Registration is already in place when this runs. */ + readonly send: Effect.Effect; + /** Overrides the correlator's default response timeout. */ + readonly timeout?: Duration.Duration | undefined; +} + +export interface RequestCorrelator { + /** + * Register, send, and await the correlated response. Cleans up the pending + * entry on every exit path, including interrupt. + */ + readonly request: ( + input: RequestCorrelatorSend, + ) => Effect.Effect; + + /** + * Resolve a pending request. Returns `false` when no entry was waiting, + * which lets callers distinguish a correlated reply from an unsolicited one. + */ + readonly complete: (requestId: string, response: Response) => Effect.Effect; + + /** Fail every pending request registered against `owner`. */ + readonly failOwner: (owner: Owner, detail: string) => Effect.Effect; + + /** + * Fail pending entries older than the configured max age. Safety net for + * entries whose awaiting fiber died without running its own cleanup. + */ + readonly sweep: Effect.Effect; + + /** Number of in-flight requests. Exposed for tests and diagnostics. */ + readonly pendingCount: Effect.Effect; +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 8aeed24e98..1e365e27b8 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -393,12 +393,42 @@ export type OpenCodeSettings = typeof OpenCodeSettings.Type; * Hermes is a remotely managed runtime. Its model, process, and session * configuration remain on the paired Hermes instance, so T3 exposes no * binary, home, working-directory, or model settings. + * + * What this config *does* carry is the durable half of a paired gateway: + * `connectorUrl` and `revoked`. Together with the envelope's `displayName` + * they are the enrollment facts that must survive a restart. They live here — + * a normal read-modify-write settings field — rather than in the secret store, + * which has no listing API, no index, and no transactions. + * + * The credential itself deliberately stays in `ServerSecretStore`; that is + * what it is for. And volatile liveness (last connection time, session count, + * plugin/Hermes versions, reported model) is deliberately **absent**: it lives + * only in broker memory, because the provider instance registry closes an + * instance's scope whenever this envelope changes, which would stop every live + * Hermes session on every reconnect. + * + * Both fields are hidden from the provider settings form: they are managed + * through the Hermes enrollment flow, not hand-edited. */ export const HermesSettings = makeProviderSettingsSchema({ enabled: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(true)), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), + /** + * The connector URL shown in the enrollment command. Optional so an + * instance that has been configured but never enrolled decodes cleanly. + */ + connectorUrl: Schema.optionalKey(TrimmedString).pipe( + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + /** + * Whether the gateway credential has been revoked. Absent means "not + * revoked", so pre-existing envelopes decode without migration. + */ + revoked: Schema.optionalKey(Schema.Boolean).pipe( + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), }); export type HermesSettings = typeof HermesSettings.Type; @@ -552,6 +582,8 @@ const OpenCodeSettingsPatch = Schema.Struct({ const HermesSettingsPatch = Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean), + connectorUrl: Schema.optionalKey(TrimmedString), + revoked: Schema.optionalKey(Schema.Boolean), }); export const ServerSettingsPatch = Schema.Struct({