fix: finish Hermes reconnect and split gateway state by durability
The transport reconnected but the session did not. `session.ready` has carried `activeTurnId` since v2 for exactly this case, yet nothing re-issued `session.ensure` after a drop: the surviving turn's eventual `turn.completed` arrived for a turn orchestration had written off, was rejected by the conflict gate, and the thread never settled. The adapter now watches connection status and, on an offline→connected edge, re-issues `session.ensure` for every live session. A turn that outlived the socket keeps streaming into the message the UI already renders; one that did not is settled with a terminal event naming the cause, as is a failed or misdirected ensure. Hermes owns session ids, so a restarted plugin's new id is adopted and written back into the resume cursor. Pending approvals cannot survive a plugin restart — they live in plain dicts there — so on reconnect they are resolved with no decision plus a warning that nothing was approved or denied on the user's behalf, rather than leaving a prompt whose answer returns request-not-found and parks the turn. Instance state is now split by durability. The credential stays in the secret store; nickname, connector URL and revocation move into the provider instance config; liveness stays in memory. That split is forced: the instance registry structurally compares config envelopes and closes the instance scope on any change, which runs the adapter finalizer and stops every live session — so persisting `connectedAt` would have torn down every session on every reconnect. A test pins the settings envelope as unchanged across connect, session-count report, and disconnect. That move deletes both nickname-scan loops, both ignored rollback paths in rename, the closure-over-let side channel, the per-connect file rewrite, and the tombstone leak. Boot migrates pre-existing blobs into settings and only then deletes them, keeping credentials for instances that are still configured; orphans are found by scanning, since an orphan is by definition unreachable by name. Verified against two real orphans found on this machine, one carrying liveness from a protocol-v1 plugin. Also: extract RequestCorrelator (generic, no Hermes types), HermesConnectionRegistry and HermesEnrollmentStore; replace the single global semaphore with per-instance enrollment locking so a slow secret write no longer blocks every other instance's handshake; implement the ping loop the protocol always specified and the plugin already answered, sized to detect a half-open socket inside the request timeout that would otherwise mask it; sweep expired tokens and abandoned requests; block offline sends with an actionable message instead of a 30s timeout; keep an undeliverable stop from orphaning a session Hermes still runs; bound the turn buffer; and stop persisting "running" for a failed turn. Server suite 1675 passing, up from 1660 with no regressions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
3261623f90
commit
e33c0d8e82
14 files changed
+3255
-1626
No files matched your search
@@ -93,10 +93,17 @@ export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
|
||||
? { 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,
|
||||
|
||||
@@ -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<ProviderRuntimeEvent> }) =>
|
||||
Effect.gen(function* () {
|
||||
const seen: Array<ProviderRuntimeEvent> = [];
|
||||
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<HermesGatewayT3ToPluginMessage> = [];
|
||||
const brokerEvents = yield* PubSub.unbounded<HermesGatewayEnvelope>();
|
||||
const brokerStatuses = yield* PubSub.unbounded<HermesGatewayInstanceStatus>();
|
||||
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)),
|
||||
);
|
||||
@@ -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<unknown> }>;
|
||||
/**
|
||||
* 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<string, PendingInteraction>;
|
||||
readonly pendingUserInputs: Map<string, PendingInteraction>;
|
||||
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<void, ProviderAdapterRequestError> {
|
||||
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<ProviderSession>) => {
|
||||
context.session = {
|
||||
...context.session,
|
||||
@@ -170,6 +218,40 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input
|
||||
};
|
||||
};
|
||||
|
||||
const clearActiveTurn = (
|
||||
context: SessionContext,
|
||||
patch: Omit<Partial<ProviderSession>, "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),
|
||||
};
|
||||
|
||||
|
||||
@@ -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<ProviderInstanceId, HermesInstanceLiveness>());
|
||||
const generation = yield* Ref.make(0);
|
||||
|
||||
/** Write liveness for one instance, dropping the entry when it goes empty. */
|
||||
const setLiveness = (
|
||||
current: ReadonlyMap<ProviderInstanceId, HermesInstanceLiveness>,
|
||||
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;
|
||||
});
|
||||
@@ -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<HermesEnrollmentStore, never, Crypto.Crypto> =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const enrollments = yield* Ref.make(new Map<string, PendingEnrollment>());
|
||||
|
||||
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;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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"),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Owner, Response> {
|
||||
readonly owner: Owner;
|
||||
readonly method: string;
|
||||
readonly registeredAtMillis: number;
|
||||
readonly deferred: Deferred.Deferred<Response, ProviderAdapterRequestError>;
|
||||
}
|
||||
|
||||
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 = <Owner, Response>(
|
||||
options: MakeRequestCorrelatorOptions,
|
||||
): Effect.Effect<RequestCorrelator<Owner, Response>> =>
|
||||
Effect.gen(function* () {
|
||||
const pending = yield* Ref.make(new Map<string, PendingRequest<Owner, Response>>());
|
||||
|
||||
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<Owner>) =>
|
||||
Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<Response, ProviderAdapterRequestError>();
|
||||
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<Owner, Response>) => boolean,
|
||||
detail: (entry: PendingRequest<Owner, Response>) => string,
|
||||
) =>
|
||||
Ref.modify(pending, (current) => {
|
||||
const claimed: Array<PendingRequest<Owner, Response>> = [];
|
||||
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<Owner, Response>;
|
||||
});
|
||||
@@ -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<HermesInstanceLiveness | undefined>;
|
||||
|
||||
/** Accept a connection, assigning it the next generation. */
|
||||
readonly accept: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly transport: HermesGatewayTransport;
|
||||
readonly observed: HermesObservedConnection;
|
||||
}) => Effect.Effect<HermesAcceptedConnection>;
|
||||
|
||||
/**
|
||||
* 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<HermesActiveConnection | undefined>;
|
||||
|
||||
/**
|
||||
* 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<boolean>;
|
||||
|
||||
/**
|
||||
* 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<HermesActiveConnection | undefined>;
|
||||
|
||||
/**
|
||||
* 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<HermesActiveConnection | undefined>;
|
||||
|
||||
/** Drop all liveness for an instance (on remove). */
|
||||
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
|
||||
|
||||
/** Whether a live connection exists. */
|
||||
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
|
||||
|
||||
/** Live transport for an instance, if connected. */
|
||||
readonly transport: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayTransport | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
};
|
||||
@@ -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<PendingEnrollment | undefined>;
|
||||
|
||||
/**
|
||||
* 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<PendingEnrollment | undefined>;
|
||||
|
||||
/** Drop every unconsumed token belonging to `instanceId`. */
|
||||
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
|
||||
|
||||
/** Drop every expired token. Run periodically; bounds memory. */
|
||||
readonly sweep: Effect.Effect<void>;
|
||||
|
||||
/** Number of unconsumed tokens. Exposed for tests and diagnostics. */
|
||||
readonly size: Effect.Effect<number>;
|
||||
}
|
||||
@@ -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<Owner> {
|
||||
/**
|
||||
* 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<void, ProviderAdapterRequestError>;
|
||||
/** Overrides the correlator's default response timeout. */
|
||||
readonly timeout?: Duration.Duration | undefined;
|
||||
}
|
||||
|
||||
export interface RequestCorrelator<Owner, Response> {
|
||||
/**
|
||||
* Register, send, and await the correlated response. Cleans up the pending
|
||||
* entry on every exit path, including interrupt.
|
||||
*/
|
||||
readonly request: (
|
||||
input: RequestCorrelatorSend<Owner>,
|
||||
) => Effect.Effect<Response, ProviderAdapterRequestError>;
|
||||
|
||||
/**
|
||||
* 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<boolean>;
|
||||
|
||||
/** Fail every pending request registered against `owner`. */
|
||||
readonly failOwner: (owner: Owner, detail: string) => Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* 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<void>;
|
||||
|
||||
/** Number of in-flight requests. Exposed for tests and diagnostics. */
|
||||
readonly pendingCount: Effect.Effect<number>;
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
Reference in new issue
Block a user