feat: add Hermes gateway provider
This commit is contained in:
48 files changed
+7441
-313
No files matched your search
@@ -1181,6 +1181,62 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("reuses a cwd-bookkept Hermes session for active follow-up guidance", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "hermes",
|
||||
},
|
||||
});
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-hermes-guidance-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-hermes-guidance-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
providerInstanceId: ProviderInstanceId.make("hermes"),
|
||||
});
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-hermes-guidance-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-hermes-guidance-2"),
|
||||
role: "user",
|
||||
text: "follow up",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession).toHaveBeenCalledTimes(1);
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restarts an existing Codex thread on a compatible requested instance", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -1873,6 +1873,97 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("treats turn.aborted as terminal and finalizes buffered assistant text", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const turnId = asTurnId("turn-aborted-buffered");
|
||||
const itemId = asItemId("item-aborted-buffered");
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-before-abort"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "running" && thread.session.activeTurnId === turnId,
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-content-before-abort"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "partial response",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.aborted",
|
||||
eventId: asEventId("evt-turn-aborted"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
payload: {
|
||||
reason: "Interrupted by user.",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.activeTurnId === null &&
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === `assistant:${itemId}` &&
|
||||
message.text === "partial response" &&
|
||||
!message.streaming,
|
||||
),
|
||||
);
|
||||
expect(thread.session?.lastError).toBeNull();
|
||||
|
||||
const nextTurnId = asTurnId("turn-after-abort");
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-after-abort"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: nextTurnId,
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "running" && entry.session.activeTurnId === nextTurnId,
|
||||
);
|
||||
harness.emit({
|
||||
type: "turn.aborted",
|
||||
eventId: asEventId("evt-stale-turn-aborted"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
payload: {
|
||||
reason: "Late abort for the previous turn.",
|
||||
},
|
||||
});
|
||||
await harness.drain();
|
||||
const afterStaleAbort = await harness.readModel();
|
||||
const activeThread = afterStaleAbort.threads.find(
|
||||
(entry) => entry.id === ThreadId.make("thread-1"),
|
||||
);
|
||||
expect(activeThread?.session?.status).toBe("running");
|
||||
expect(activeThread?.session?.activeTurnId).toBe(nextTurnId);
|
||||
});
|
||||
|
||||
it("flushes and completes buffered assistant text when an approval request opens", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -1343,6 +1343,7 @@ const make = Effect.gen(function* () {
|
||||
case "turn.started":
|
||||
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
|
||||
case "turn.completed":
|
||||
case "turn.aborted":
|
||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||
return false;
|
||||
}
|
||||
@@ -1367,7 +1368,8 @@ const make = Effect.gen(function* () {
|
||||
event.type === "session.exited" ||
|
||||
event.type === "thread.started" ||
|
||||
event.type === "turn.started" ||
|
||||
event.type === "turn.completed"
|
||||
event.type === "turn.completed" ||
|
||||
event.type === "turn.aborted"
|
||||
) {
|
||||
const status = (() => {
|
||||
switch (event.type) {
|
||||
@@ -1383,6 +1385,8 @@ const make = Effect.gen(function* () {
|
||||
return normalizeRuntimeTurnState(event.payload.state) === "failed"
|
||||
? "error"
|
||||
: "ready";
|
||||
case "turn.aborted":
|
||||
return "ready";
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
@@ -1393,7 +1397,9 @@ const make = Effect.gen(function* () {
|
||||
const nextActiveTurnId =
|
||||
event.type === "turn.started"
|
||||
? (eventTurnId ?? null)
|
||||
: event.type === "turn.completed" || event.type === "session.exited"
|
||||
: event.type === "turn.completed" ||
|
||||
event.type === "turn.aborted" ||
|
||||
event.type === "session.exited"
|
||||
? null
|
||||
: event.type === "session.state.changed" &&
|
||||
!sessionStatusAllowsActiveTurn(
|
||||
@@ -1634,7 +1640,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
if (event.type === "turn.completed" || event.type === "turn.aborted") {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
DEFAULT_HERMES_MODEL,
|
||||
HERMES_DRIVER_KIND,
|
||||
HermesSettings,
|
||||
TextGenerationError,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
|
||||
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
export type HermesDriverEnv = Crypto.Crypto;
|
||||
|
||||
const unsupportedTextGeneration = (
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes gateway instances do not support utility text generation.",
|
||||
}),
|
||||
);
|
||||
|
||||
const makeTextGeneration = (): TextGenerationShape => ({
|
||||
generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"),
|
||||
generatePrContent: () => unsupportedTextGeneration("generatePrContent"),
|
||||
generateBranchName: () => unsupportedTextGeneration("generateBranchName"),
|
||||
generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"),
|
||||
});
|
||||
|
||||
export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
|
||||
driverKind: HERMES_DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "Hermes",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: HermesSettings,
|
||||
defaultConfig: () => decodeHermesSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, enabled }) =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* HermesGatewayBroker;
|
||||
const adapter = yield* makeHermesAdapter({ instanceId });
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: HERMES_DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const maintenanceCapabilities = makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: HERMES_DRIVER_KIND,
|
||||
packageName: null,
|
||||
});
|
||||
const getSnapshot = Effect.gen(function* () {
|
||||
const connected = yield* broker.isConnected(instanceId);
|
||||
const status = yield* broker
|
||||
.getInstanceStatus(instanceId)
|
||||
.pipe(Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined)));
|
||||
return {
|
||||
instanceId,
|
||||
driver: HERMES_DRIVER_KIND,
|
||||
...(displayName ? { displayName } : {}),
|
||||
...(accentColor ? { accentColor } : {}),
|
||||
continuation: { groupKey: continuationIdentity.continuationKey },
|
||||
showInteractionModeToggle: false,
|
||||
requiresNewThreadForModelChange: true,
|
||||
enabled,
|
||||
installed: true,
|
||||
version: status?.hermesVersion ?? null,
|
||||
status: !enabled ? "disabled" : connected ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connected ? "authenticated" : "unauthenticated",
|
||||
type: "gateway",
|
||||
label: status?.nickname ?? displayName ?? "Hermes",
|
||||
},
|
||||
checkedAt: DateTime.formatIso(DateTime.nowUnsafe()),
|
||||
...(!connected && enabled
|
||||
? { message: "Hermes is offline. Reconnect its T3 Code gateway plugin." }
|
||||
: {}),
|
||||
availability: "available",
|
||||
models: [
|
||||
{
|
||||
slug: DEFAULT_HERMES_MODEL,
|
||||
name: "Hermes",
|
||||
isCustom: false,
|
||||
isDefault: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} satisfies ServerProvider;
|
||||
});
|
||||
const snapshot = {
|
||||
maintenanceCapabilities,
|
||||
getSnapshot,
|
||||
refresh: getSnapshot,
|
||||
streamChanges: broker.streamStatuses.pipe(
|
||||
Stream.filter((status) => status.instanceId === instanceId),
|
||||
Stream.mapEffect(() => getSnapshot),
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: HERMES_DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration: makeTextGeneration(),
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,171 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HermesGatewayRequestId,
|
||||
HermesGatewaySessionId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type HermesGatewayT3ToPluginMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
HermesGatewayBroker,
|
||||
type HermesGatewayBrokerShape,
|
||||
type HermesGatewayEnvelope,
|
||||
} from "../Services/HermesGatewayBroker.ts";
|
||||
import {
|
||||
makeHermesAdapter,
|
||||
sanitizeHermesItemData,
|
||||
sanitizeHermesRequestArgs,
|
||||
shouldProjectHermesTurnStarted,
|
||||
} from "./HermesAdapter.ts";
|
||||
|
||||
it("sanitizes persisted gateway payloads and suppresses steering acknowledgements", () => {
|
||||
assert.deepEqual(
|
||||
sanitizeHermesItemData("command_execution", {
|
||||
command: "git status",
|
||||
cwd: "/workspace",
|
||||
arbitrarySecret: "drop-me",
|
||||
result: { unbounded: true },
|
||||
}),
|
||||
{ command: "git status", cwd: "/workspace" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
sanitizeHermesRequestArgs("command_execution_approval", {
|
||||
command: "git push",
|
||||
arbitrarySecret: "drop-me",
|
||||
}),
|
||||
{ command: "git push" },
|
||||
);
|
||||
const steerRequestId = HermesGatewayRequestId.make("steer-request");
|
||||
const startRequestId = HermesGatewayRequestId.make("start-request");
|
||||
const pendingSteerRequestIds = new Set([steerRequestId]);
|
||||
assert.isFalse(shouldProjectHermesTurnStarted(pendingSteerRequestIds, steerRequestId));
|
||||
assert.isTrue(shouldProjectHermesTurnStarted(pendingSteerRequestIds, startRequestId));
|
||||
assert.isFalse(pendingSteerRequestIds.has(steerRequestId));
|
||||
});
|
||||
|
||||
it.effect("keeps cwd local while forwarding turn text byte-for-byte and steering follow-ups", () =>
|
||||
Effect.gen(function* () {
|
||||
const instanceId = ProviderInstanceId.make("hermes_remote");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const sessionId = HermesGatewaySessionId.make("session-1");
|
||||
const sent: Array<HermesGatewayT3ToPluginMessage> = [];
|
||||
const brokerEvents = yield* PubSub.unbounded<HermesGatewayEnvelope>();
|
||||
const broker: HermesGatewayBrokerShape = {
|
||||
createEnrollment: () => Effect.die(new Error("unused")),
|
||||
getInstanceStatus: () => Effect.die(new Error("unused")),
|
||||
listInstances: Effect.succeed([]),
|
||||
revokeInstance: () => 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") {
|
||||
return Effect.succeed({
|
||||
type: "session.ready",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: message.requestId,
|
||||
threadId: message.threadId,
|
||||
sessionId,
|
||||
resumed: false,
|
||||
});
|
||||
}
|
||||
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.succeed(true),
|
||||
stream: Stream.fromPubSub(brokerEvents),
|
||||
streamStatuses: Stream.empty,
|
||||
};
|
||||
const adapter = yield* makeHermesAdapter({ instanceId }).pipe(
|
||||
Effect.provideService(HermesGatewayBroker, broker),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
providerInstanceId: instanceId,
|
||||
cwd: "/must/not/leak",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal(session.cwd, "/must/not/leak");
|
||||
const sessionEnsure = sent.find((message) => message.type === "session.ensure");
|
||||
assert.isFalse(sessionEnsure !== undefined && "cwd" in sessionEnsure);
|
||||
|
||||
const original = " /help keep all whitespace \n";
|
||||
yield* adapter.sendTurn({ threadId, input: original });
|
||||
const turnStart = sent.find((message) => message.type === "turn.start");
|
||||
assert.equal(turnStart?.type === "turn.start" ? turnStart.text : undefined, original);
|
||||
|
||||
if (!turnStart || turnStart.type !== "turn.start") {
|
||||
return yield* Effect.die(new Error("turn.start was not sent"));
|
||||
}
|
||||
const startEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* PubSub.publish(brokerEvents, {
|
||||
instanceId,
|
||||
message: {
|
||||
type: "turn.started",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: turnStart.requestId,
|
||||
threadId,
|
||||
sessionId,
|
||||
turnId: turnStart.turnId,
|
||||
},
|
||||
});
|
||||
const startEvent = Option.getOrUndefined(yield* Fiber.join(startEventFiber));
|
||||
assert.equal(startEvent?.type, "turn.started");
|
||||
|
||||
yield* adapter.sendTurn({ threadId, input: "follow up" });
|
||||
const turnSteer = sent.find((message) => message.type === "turn.steer");
|
||||
if (!turnSteer || turnSteer.type !== "turn.steer") {
|
||||
return yield* Effect.die(new Error("turn.steer was not sent"));
|
||||
}
|
||||
const nextEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* PubSub.publish(brokerEvents, {
|
||||
instanceId,
|
||||
message: {
|
||||
type: "turn.started",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: turnSteer.requestId,
|
||||
threadId,
|
||||
sessionId,
|
||||
turnId: turnSteer.turnId,
|
||||
},
|
||||
});
|
||||
yield* PubSub.publish(brokerEvents, {
|
||||
instanceId,
|
||||
message: {
|
||||
type: "content.delta",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
threadId,
|
||||
sessionId,
|
||||
turnId: turnSteer.turnId,
|
||||
streamKind: "assistant_text",
|
||||
delta: "continued",
|
||||
},
|
||||
});
|
||||
const nextEvent = Option.getOrUndefined(yield* Fiber.join(nextEventFiber));
|
||||
assert.equal(nextEvent?.type, "content.delta");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -0,0 +1,562 @@
|
||||
import {
|
||||
EventId,
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HermesGatewayRequestId,
|
||||
HermesGatewayResumeCursor,
|
||||
HermesGatewaySessionId,
|
||||
ProviderDriverKind,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type HermesGatewayPluginToT3Message,
|
||||
type ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("hermes");
|
||||
const isResumeCursor = Schema.is(HermesGatewayResumeCursor);
|
||||
|
||||
type HermesAdapterShape = ProviderAdapterShape<
|
||||
ProviderAdapterRequestError | ProviderAdapterSessionNotFoundError | ProviderAdapterValidationError
|
||||
>;
|
||||
|
||||
interface SessionContext {
|
||||
readonly hermesSessionId: HermesGatewaySessionId;
|
||||
readonly turns: Array<{ readonly id: TurnId; readonly items: Array<unknown> }>;
|
||||
session: ProviderSession;
|
||||
}
|
||||
|
||||
type PluginMessage = Exclude<HermesGatewayPluginToT3Message, { readonly type: "connection.hello" }>;
|
||||
|
||||
const nowIso = () => DateTime.formatIso(DateTime.nowUnsafe());
|
||||
const MAX_PERSISTED_GATEWAY_FIELD_CHARS = 4_096;
|
||||
|
||||
const boundedString = (value: unknown) =>
|
||||
typeof value === "string" && value.length <= MAX_PERSISTED_GATEWAY_FIELD_CHARS
|
||||
? value
|
||||
: undefined;
|
||||
|
||||
const asRecord = (value: unknown) =>
|
||||
typeof value === "object" && value !== null
|
||||
? (value as Readonly<Record<string, unknown>>)
|
||||
: undefined;
|
||||
|
||||
export const sanitizeHermesItemData = (
|
||||
itemType: Extract<PluginMessage, { readonly type: "item.started" }>["itemType"],
|
||||
value: unknown,
|
||||
) => {
|
||||
const record = asRecord(value);
|
||||
if (!record) return undefined;
|
||||
const fields =
|
||||
itemType === "command_execution"
|
||||
? ["command", "cwd"]
|
||||
: itemType === "file_change"
|
||||
? ["path"]
|
||||
: itemType === "web_search"
|
||||
? ["query"]
|
||||
: itemType === "image_view"
|
||||
? ["path"]
|
||||
: itemType === "mcp_tool_call"
|
||||
? ["server", "operation"]
|
||||
: [];
|
||||
const sanitized = Object.fromEntries(
|
||||
fields.flatMap((field) => {
|
||||
const value = boundedString(record[field]);
|
||||
return value === undefined ? [] : [[field, value]];
|
||||
}),
|
||||
);
|
||||
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
|
||||
};
|
||||
|
||||
export const sanitizeHermesRequestArgs = (
|
||||
requestType: Extract<PluginMessage, { readonly type: "request.opened" }>["requestType"],
|
||||
value: unknown,
|
||||
) => {
|
||||
const record = asRecord(value);
|
||||
if (!record) return undefined;
|
||||
const fields =
|
||||
requestType === "command_execution_approval" || requestType === "exec_command_approval"
|
||||
? ["command", "cwd"]
|
||||
: requestType === "file_read_approval" ||
|
||||
requestType === "file_change_approval" ||
|
||||
requestType === "apply_patch_approval"
|
||||
? ["path"]
|
||||
: [];
|
||||
const sanitized = Object.fromEntries(
|
||||
fields.flatMap((field) => {
|
||||
const value = boundedString(record[field]);
|
||||
return value === undefined ? [] : [[field, value]];
|
||||
}),
|
||||
);
|
||||
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
|
||||
};
|
||||
|
||||
export const shouldProjectHermesTurnStarted = (
|
||||
pendingSteerRequestIds: Set<HermesGatewayRequestId>,
|
||||
incomingRequestId: HermesGatewayRequestId,
|
||||
) => !pendingSteerRequestIds.delete(incomingRequestId);
|
||||
|
||||
export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
}) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const broker = yield* HermesGatewayBroker;
|
||||
const events = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, SessionContext>();
|
||||
const pendingSteerRequestIds = new Set<HermesGatewayRequestId>();
|
||||
|
||||
const randomId = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "crypto/randomUUIDv4",
|
||||
detail: "Failed to generate a Hermes runtime identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const requestId = randomId.pipe(
|
||||
Effect.map((value) => HermesGatewayRequestId.make(`t3-${value}`)),
|
||||
);
|
||||
const eventBase = (message: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
}) =>
|
||||
randomId.pipe(
|
||||
Effect.map((value) => ({
|
||||
eventId: EventId.make(value),
|
||||
provider: PROVIDER,
|
||||
providerInstanceId: input.instanceId,
|
||||
threadId: message.threadId,
|
||||
createdAt: nowIso(),
|
||||
...(message.turnId ? { turnId: TurnId.make(message.turnId) } : {}),
|
||||
...(message.itemId ? { itemId: RuntimeItemId.make(message.itemId) } : {}),
|
||||
...(message.requestId ? { requestId: RuntimeRequestId.make(message.requestId) } : {}),
|
||||
})),
|
||||
);
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => PubSub.publish(events, event).pipe(Effect.asVoid);
|
||||
|
||||
const findContext = (threadId: ThreadId) =>
|
||||
Effect.gen(function* (): Effect.fn.Return<SessionContext, ProviderAdapterSessionNotFoundError> {
|
||||
const context = sessions.get(threadId);
|
||||
if (!context) {
|
||||
return yield* new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
});
|
||||
}
|
||||
return context;
|
||||
});
|
||||
|
||||
const updateSession = (context: SessionContext, patch: Partial<ProviderSession>) => {
|
||||
context.session = {
|
||||
...context.session,
|
||||
...patch,
|
||||
updatedAt: nowIso(),
|
||||
};
|
||||
};
|
||||
|
||||
const toRuntimeEvent = (message: PluginMessage) =>
|
||||
Effect.gen(function* (): Effect.fn.Return<
|
||||
ProviderRuntimeEvent | undefined,
|
||||
ProviderAdapterRequestError
|
||||
> {
|
||||
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": {
|
||||
const isSteeringAcknowledgement = !shouldProjectHermesTurnStarted(
|
||||
pendingSteerRequestIds,
|
||||
message.requestId,
|
||||
);
|
||||
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 (isSteeringAcknowledgement) return undefined;
|
||||
return {
|
||||
...base,
|
||||
type: "turn.started",
|
||||
payload: {},
|
||||
};
|
||||
}
|
||||
case "content.delta":
|
||||
return {
|
||||
...base,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: message.streamKind,
|
||||
delta: message.delta,
|
||||
...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}),
|
||||
},
|
||||
};
|
||||
case "item.started":
|
||||
case "item.updated":
|
||||
case "item.completed": {
|
||||
const data = sanitizeHermesItemData(message.itemType, message.data);
|
||||
const payload = {
|
||||
itemType: message.itemType,
|
||||
...(message.status ? { status: message.status } : {}),
|
||||
...(message.title ? { title: message.title } : {}),
|
||||
...(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 };
|
||||
}
|
||||
case "request.opened": {
|
||||
const args = sanitizeHermesRequestArgs(message.requestType, message.args);
|
||||
return {
|
||||
...base,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: message.requestType,
|
||||
...(message.detail ? { detail: message.detail } : {}),
|
||||
...(args ? { args } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "request.resolved":
|
||||
return {
|
||||
...base,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: message.requestType,
|
||||
...(message.decision ? { decision: message.decision } : {}),
|
||||
},
|
||||
};
|
||||
case "user-input.requested":
|
||||
return {
|
||||
...base,
|
||||
type: "user-input.requested",
|
||||
payload: { questions: message.questions },
|
||||
};
|
||||
case "user-input.resolved":
|
||||
return {
|
||||
...base,
|
||||
type: "user-input.resolved",
|
||||
payload: { answers: message.answers },
|
||||
};
|
||||
case "turn.completed":
|
||||
if (context) {
|
||||
updateSession(context, { status: message.state === "failed" ? "error" : "ready" });
|
||||
const { activeTurnId: _activeTurnId, ...session } = context.session;
|
||||
context.session = session;
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: message.state,
|
||||
...(message.stopReason !== undefined ? { stopReason: message.stopReason } : {}),
|
||||
...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
|
||||
},
|
||||
};
|
||||
case "turn.aborted":
|
||||
if (context) {
|
||||
const { activeTurnId: _activeTurnId, ...session } = context.session;
|
||||
context.session = { ...session, status: "ready", updatedAt: nowIso() };
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
type: "turn.aborted",
|
||||
payload: { reason: message.reason },
|
||||
};
|
||||
case "session.exited":
|
||||
if (context) updateSession(context, { status: message.recoverable ? "error" : "closed" });
|
||||
return {
|
||||
...base,
|
||||
type: "session.exited",
|
||||
payload: {
|
||||
...(message.reason ? { reason: message.reason } : {}),
|
||||
recoverable: message.recoverable,
|
||||
exitKind: message.recoverable ? "error" : "graceful",
|
||||
},
|
||||
};
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
|
||||
yield* broker.stream.pipe(
|
||||
Stream.filter((envelope) => envelope.instanceId === input.instanceId),
|
||||
Stream.runForEach((envelope) =>
|
||||
toRuntimeEvent(envelope.message).pipe(
|
||||
Effect.flatMap((event) => (event ? emit(event) : Effect.void)),
|
||||
),
|
||||
),
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
if (sessionInput.providerInstanceId && sessionInput.providerInstanceId !== input.instanceId) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Session targets instance '${sessionInput.providerInstanceId}', expected '${input.instanceId}'.`,
|
||||
});
|
||||
}
|
||||
const resume =
|
||||
sessionInput.resumeCursor === undefined
|
||||
? undefined
|
||||
: isResumeCursor(sessionInput.resumeCursor)
|
||||
? sessionInput.resumeCursor
|
||||
: undefined;
|
||||
if (sessionInput.resumeCursor !== undefined && !resume) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "The Hermes resume cursor is invalid or from an unsupported protocol version.",
|
||||
});
|
||||
}
|
||||
const response = yield* broker.request(input.instanceId, {
|
||||
type: "session.ensure",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: yield* requestId,
|
||||
threadId: sessionInput.threadId,
|
||||
...(resume ? { resumeSessionId: resume.sessionId } : {}),
|
||||
});
|
||||
if (response.type !== "session.ready" || response.threadId !== sessionInput.threadId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session.ensure",
|
||||
detail:
|
||||
response.type === "protocol.error"
|
||||
? response.message
|
||||
: `Expected session.ready, received '${response.type}'.`,
|
||||
});
|
||||
}
|
||||
const createdAt = nowIso();
|
||||
const session = {
|
||||
provider: PROVIDER,
|
||||
providerInstanceId: input.instanceId,
|
||||
status: "ready",
|
||||
runtimeMode: sessionInput.runtimeMode,
|
||||
...(sessionInput.cwd !== undefined ? { cwd: sessionInput.cwd } : {}),
|
||||
...(sessionInput.modelSelection?.model ? { model: sessionInput.modelSelection.model } : {}),
|
||||
threadId: sessionInput.threadId,
|
||||
resumeCursor: {
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
sessionId: response.sessionId,
|
||||
} satisfies HermesGatewayResumeCursor,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
} satisfies ProviderSession;
|
||||
sessions.set(sessionInput.threadId, {
|
||||
session,
|
||||
hermesSessionId: response.sessionId,
|
||||
turns: [],
|
||||
});
|
||||
yield* emit({
|
||||
...(yield* eventBase({ threadId: sessionInput.threadId })),
|
||||
type: "session.started",
|
||||
payload: {
|
||||
message: response.resumed ? "Hermes session resumed" : "Hermes session started",
|
||||
resume: session.resumeCursor,
|
||||
},
|
||||
});
|
||||
yield* emit({
|
||||
...(yield* eventBase({ threadId: sessionInput.threadId })),
|
||||
type: "thread.started",
|
||||
payload: { providerThreadId: response.sessionId },
|
||||
});
|
||||
return session;
|
||||
},
|
||||
);
|
||||
|
||||
const sendTurn: HermesAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (turnInput) {
|
||||
const context = yield* findContext(turnInput.threadId);
|
||||
if (turnInput.attachments && turnInput.attachments.length > 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Hermes gateway attachments are not supported yet.",
|
||||
});
|
||||
}
|
||||
const text = turnInput.input;
|
||||
if (!text || text.trim().length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Hermes turns require text input.",
|
||||
});
|
||||
}
|
||||
const activeTurnId = context.session.activeTurnId;
|
||||
const turnId = activeTurnId ?? TurnId.make(`hermes-turn-${yield* randomId}`);
|
||||
const outboundRequestId = yield* requestId;
|
||||
if (activeTurnId) pendingSteerRequestIds.add(outboundRequestId);
|
||||
const response = yield* broker
|
||||
.request(input.instanceId, {
|
||||
type: activeTurnId ? "turn.steer" : "turn.start",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: outboundRequestId,
|
||||
threadId: turnInput.threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
turnId,
|
||||
text,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tapError(() => Effect.sync(() => pendingSteerRequestIds.delete(outboundRequestId))),
|
||||
);
|
||||
if (response.type !== "turn.started") {
|
||||
pendingSteerRequestIds.delete(outboundRequestId);
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: activeTurnId ? "turn.steer" : "turn.start",
|
||||
detail:
|
||||
response.type === "protocol.error"
|
||||
? response.message
|
||||
: `Expected turn.started, received '${response.type}'.`,
|
||||
});
|
||||
}
|
||||
updateSession(context, { status: "running", activeTurnId: turnId });
|
||||
return {
|
||||
threadId: turnInput.threadId,
|
||||
turnId,
|
||||
resumeCursor: context.session.resumeCursor,
|
||||
};
|
||||
});
|
||||
|
||||
const adapter: HermesAdapterShape = {
|
||||
provider: PROVIDER,
|
||||
capabilities: { sessionModelSwitch: "unsupported" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn: (threadId, selectedTurnId) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* findContext(threadId);
|
||||
const turnId = selectedTurnId ?? context.session.activeTurnId;
|
||||
if (!turnId) return;
|
||||
yield* broker.send(input.instanceId, {
|
||||
type: "turn.interrupt",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: yield* requestId,
|
||||
threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
turnId,
|
||||
});
|
||||
}),
|
||||
respondToRequest: (threadId, selectedRequestId, decision) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* findContext(threadId);
|
||||
if (!context.session.activeTurnId) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "respondToRequest",
|
||||
issue: "The Hermes session has no active turn.",
|
||||
});
|
||||
}
|
||||
yield* broker.send(input.instanceId, {
|
||||
type: "approval.respond",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: HermesGatewayRequestId.make(selectedRequestId),
|
||||
threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
turnId: context.session.activeTurnId,
|
||||
decision,
|
||||
});
|
||||
}),
|
||||
respondToUserInput: (threadId, selectedRequestId, answers) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* findContext(threadId);
|
||||
if (!context.session.activeTurnId) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "respondToUserInput",
|
||||
issue: "The Hermes session has no active turn.",
|
||||
});
|
||||
}
|
||||
yield* broker.send(input.instanceId, {
|
||||
type: "user-input.respond",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: HermesGatewayRequestId.make(selectedRequestId),
|
||||
threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
turnId: context.session.activeTurnId,
|
||||
answers,
|
||||
});
|
||||
}),
|
||||
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,
|
||||
});
|
||||
}
|
||||
updateSession(context, { status: "closed" });
|
||||
sessions.delete(threadId);
|
||||
}),
|
||||
listSessions: () => Effect.sync(() => Array.from(sessions.values(), ({ session }) => session)),
|
||||
hasSession: (threadId) => Effect.sync(() => sessions.has(threadId)),
|
||||
readThread: (threadId) =>
|
||||
findContext(threadId).pipe(
|
||||
Effect.map((context) => ({
|
||||
threadId,
|
||||
turns: context.turns,
|
||||
})),
|
||||
),
|
||||
rollbackThread: (threadId) =>
|
||||
findContext(threadId).pipe(
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "Hermes gateway thread rollback is not supported.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
stopAll: () =>
|
||||
Effect.forEach(Array.from(sessions.keys()), (threadId) => adapter.stopSession(threadId), {
|
||||
discard: true,
|
||||
}),
|
||||
streamEvents: Stream.fromPubSub(events),
|
||||
};
|
||||
|
||||
yield* Effect.addFinalizer(() => adapter.stopAll().pipe(Effect.ignore));
|
||||
return adapter;
|
||||
});
|
||||
@@ -0,0 +1,544 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HermesGatewayCredential,
|
||||
HermesGatewayRequestId,
|
||||
HermesGatewaySessionId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type HermesGatewayConnectionHello,
|
||||
type HermesGatewayT3ToPluginMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { HermesDriver } from "../Drivers/HermesDriver.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import {
|
||||
HermesGatewayBroker,
|
||||
type HermesGatewayTransport,
|
||||
} from "../Services/HermesGatewayBroker.ts";
|
||||
import { HermesGatewayBrokerLive, makeHermesGatewayBroker } from "./HermesGatewayBroker.ts";
|
||||
|
||||
const instanceId = ProviderInstanceId.make("hermes_remote");
|
||||
const otherInstanceId = ProviderInstanceId.make("hermes_other");
|
||||
class HermesTestInstance extends Context.Service<HermesTestInstance, ProviderInstance>()(
|
||||
"t3/provider/Layers/HermesGatewayBroker.test/HermesTestInstance",
|
||||
) {}
|
||||
|
||||
const capabilities = {
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
} as const;
|
||||
|
||||
const makeSecretStore = () => {
|
||||
const values = new Map<string, Uint8Array>();
|
||||
const service: ServerSecretStore.ServerSecretStore["Service"] = {
|
||||
get: (name) => Effect.succeed(Option.fromUndefinedOr(values.get(name))),
|
||||
set: (name, value) => Effect.sync(() => values.set(name, value)).pipe(Effect.asVoid),
|
||||
create: (name, value) => Effect.sync(() => values.set(name, value)).pipe(Effect.asVoid),
|
||||
getOrCreateRandom: (_name, bytes) => Effect.succeed(new Uint8Array(bytes)),
|
||||
remove: (name) => Effect.sync(() => values.delete(name)).pipe(Effect.asVoid),
|
||||
};
|
||||
return service;
|
||||
};
|
||||
|
||||
const makeBroker = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
|
||||
makeHermesGatewayBroker.pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.layerTest({
|
||||
providerInstances: {
|
||||
[instanceId]: { driver: "hermes", displayName: "Remote", config: {} },
|
||||
[otherInstanceId]: { driver: "hermes", displayName: "Other", config: {} },
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const hello = (
|
||||
authentication: HermesGatewayConnectionHello["authentication"],
|
||||
protocolVersion: number = HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
): HermesGatewayConnectionHello => ({
|
||||
type: "connection.hello",
|
||||
requestId: HermesGatewayRequestId.make(`hello-${protocolVersion}`),
|
||||
protocolVersion,
|
||||
pluginVersion: "0.1.0",
|
||||
hermesVersion: "1.0.0",
|
||||
capabilities: { ...capabilities, protocolVersion },
|
||||
authentication,
|
||||
});
|
||||
|
||||
it.effect("authenticates before applying incompatible connection state", () =>
|
||||
Effect.gen(function* () {
|
||||
const secrets = makeSecretStore();
|
||||
const broker = yield* makeBroker(secrets);
|
||||
yield* broker.createEnrollment({
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
nickname: "Default Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const enrollment = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
|
||||
const firstCloses: Array<number> = [];
|
||||
const firstTransport: HermesGatewayTransport = {
|
||||
send: () => Effect.void,
|
||||
close: (code) => Effect.sync(() => firstCloses.push(code)).pipe(Effect.asVoid),
|
||||
};
|
||||
const first = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: enrollment.oneTimeToken }),
|
||||
firstTransport,
|
||||
);
|
||||
assert.isTrue(first.accepted.credential !== undefined);
|
||||
assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected");
|
||||
|
||||
const secondCloses: Array<number> = [];
|
||||
const sent: Array<HermesGatewayT3ToPluginMessage> = [];
|
||||
const secondTransport: HermesGatewayTransport = {
|
||||
send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid),
|
||||
close: (code) => Effect.sync(() => secondCloses.push(code)).pipe(Effect.asVoid),
|
||||
};
|
||||
const second = yield* broker.registerConnection(
|
||||
hello({
|
||||
type: "instance-credential",
|
||||
instanceId,
|
||||
credential: first.accepted.credential!,
|
||||
}),
|
||||
secondTransport,
|
||||
);
|
||||
assert.deepEqual(firstCloses, [4001]);
|
||||
|
||||
const threadId = ThreadId.make("pending-thread");
|
||||
const pendingRequestId = HermesGatewayRequestId.make("pending-session");
|
||||
const pendingRequest = yield* broker
|
||||
.request(instanceId, {
|
||||
type: "session.ensure",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: pendingRequestId,
|
||||
threadId,
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(sent.at(-1)?.type, "session.ensure");
|
||||
|
||||
const malicious = yield* Effect.flip(
|
||||
broker.registerConnection(
|
||||
hello(
|
||||
{
|
||||
type: "instance-credential",
|
||||
instanceId,
|
||||
credential: HermesGatewayCredential.make("not-the-real-credential"),
|
||||
},
|
||||
2,
|
||||
),
|
||||
secondTransport,
|
||||
),
|
||||
);
|
||||
assert.equal(malicious.code, "invalid-authentication");
|
||||
assert.deepEqual(secondCloses, []);
|
||||
assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "connected");
|
||||
assert.isUndefined(pendingRequest.pollUnsafe());
|
||||
|
||||
yield* broker.receive(second, {
|
||||
type: "session.ready",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: pendingRequestId,
|
||||
threadId,
|
||||
sessionId: HermesGatewaySessionId.make("pending-session-id"),
|
||||
resumed: false,
|
||||
});
|
||||
assert.equal((yield* Fiber.join(pendingRequest)).type, "session.ready");
|
||||
|
||||
const incompatible = yield* Effect.flip(
|
||||
broker.registerConnection(
|
||||
hello(
|
||||
{
|
||||
type: "instance-credential",
|
||||
instanceId,
|
||||
credential: first.accepted.credential!,
|
||||
},
|
||||
2,
|
||||
),
|
||||
secondTransport,
|
||||
),
|
||||
);
|
||||
assert.equal(incompatible.code, "version-incompatible");
|
||||
assert.deepEqual(secondCloses, [4004]);
|
||||
assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "upgrade-required");
|
||||
|
||||
const otherEnrollment = yield* broker.createEnrollment({
|
||||
instanceId: otherInstanceId,
|
||||
nickname: "Other Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const incompatibleEnrollment = yield* Effect.flip(
|
||||
broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }, 2),
|
||||
secondTransport,
|
||||
),
|
||||
);
|
||||
assert.equal(incompatibleEnrollment.code, "version-incompatible");
|
||||
const enrolledAfterUpgrade = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }),
|
||||
secondTransport,
|
||||
);
|
||||
assert.equal(enrolledAfterUpgrade.instanceId, otherInstanceId);
|
||||
|
||||
const revoked = yield* broker.revokeInstance(instanceId);
|
||||
assert.equal(revoked.status, "revoked");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("invalidates the previous credential when replacement enrollment begins", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker(makeSecretStore());
|
||||
const enrollment = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const closes: Array<number> = [];
|
||||
const transport: HermesGatewayTransport = {
|
||||
send: () => Effect.void,
|
||||
close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid),
|
||||
};
|
||||
const first = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: enrollment.oneTimeToken }),
|
||||
transport,
|
||||
);
|
||||
const replacement = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
assert.deepEqual(closes, [4001]);
|
||||
|
||||
const staleCredential = yield* Effect.flip(
|
||||
broker.registerConnection(
|
||||
hello({
|
||||
type: "instance-credential",
|
||||
instanceId,
|
||||
credential: first.accepted.credential!,
|
||||
}),
|
||||
transport,
|
||||
),
|
||||
);
|
||||
assert.equal(staleCredential.code, "invalid-authentication");
|
||||
const replacementConnection = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: replacement.oneTimeToken }),
|
||||
transport,
|
||||
);
|
||||
assert.equal(replacementConnection.instanceId, instanceId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts only the newest unconsumed enrollment token for an instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker(makeSecretStore());
|
||||
const older = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const newest = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const transport: HermesGatewayTransport = {
|
||||
send: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const olderTokenError = yield* Effect.flip(
|
||||
broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: older.oneTimeToken }),
|
||||
transport,
|
||||
),
|
||||
);
|
||||
assert.equal(olderTokenError.code, "enrollment-expired");
|
||||
const newestConnection = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: newest.oneTimeToken }),
|
||||
transport,
|
||||
);
|
||||
assert.equal(newestConnection.instanceId, instanceId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("atomically reserves normalized nicknames across concurrent enrollments", () =>
|
||||
Effect.gen(function* () {
|
||||
const storedSecrets = makeSecretStore();
|
||||
const firstPersistStarted = yield* Deferred.make<void>();
|
||||
const releaseFirstPersist = yield* Deferred.make<void>();
|
||||
let metadataPersistCount = 0;
|
||||
const secrets: ServerSecretStore.ServerSecretStore["Service"] = {
|
||||
...storedSecrets,
|
||||
set: (name, value) =>
|
||||
name.startsWith("hermes-gateway-metadata-")
|
||||
? Effect.gen(function* () {
|
||||
metadataPersistCount += 1;
|
||||
if (metadataPersistCount === 1) {
|
||||
yield* Deferred.succeed(firstPersistStarted, undefined);
|
||||
yield* Deferred.await(releaseFirstPersist);
|
||||
}
|
||||
yield* storedSecrets.set(name, value);
|
||||
})
|
||||
: storedSecrets.set(name, value),
|
||||
};
|
||||
const broker = yield* makeBroker(secrets);
|
||||
const firstEnrollment = yield* broker
|
||||
.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Shared Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Deferred.await(firstPersistStarted);
|
||||
const secondEnrollment = yield* broker
|
||||
.createEnrollment({
|
||||
instanceId: otherInstanceId,
|
||||
nickname: " Shared Hermes ",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.equal(metadataPersistCount, 1);
|
||||
|
||||
yield* Deferred.succeed(releaseFirstPersist, undefined);
|
||||
yield* Fiber.join(firstEnrollment);
|
||||
const conflict = yield* Effect.flip(Fiber.join(secondEnrollment));
|
||||
assert.equal(conflict.code, "nickname-conflict");
|
||||
assert.equal(metadataPersistCount, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a revoked instance nickname reserved", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker(makeSecretStore());
|
||||
yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Reserved Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
assert.equal((yield* broker.revokeInstance(instanceId)).status, "revoked");
|
||||
|
||||
const conflict = yield* Effect.flip(
|
||||
broker.createEnrollment({
|
||||
instanceId: otherInstanceId,
|
||||
nickname: " Reserved Hermes ",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
}),
|
||||
);
|
||||
assert.equal(conflict.code, "nickname-conflict");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("finalizes revocation when credential deletion fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const storedSecrets = makeSecretStore();
|
||||
let failRemovals = false;
|
||||
const secrets: ServerSecretStore.ServerSecretStore["Service"] = {
|
||||
...storedSecrets,
|
||||
remove: (name) =>
|
||||
failRemovals
|
||||
? Effect.fail(
|
||||
new ServerSecretStore.SecretStoreRemoveError({
|
||||
resource: `secret ${name}`,
|
||||
cause: new Error("forced credential deletion failure"),
|
||||
}),
|
||||
)
|
||||
: storedSecrets.remove(name),
|
||||
};
|
||||
const broker = yield* makeBroker(secrets);
|
||||
const enrollment = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const closes: Array<number> = [];
|
||||
const sent: Array<HermesGatewayT3ToPluginMessage> = [];
|
||||
const registration = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: enrollment.oneTimeToken }),
|
||||
{
|
||||
send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid),
|
||||
close: (code) => Effect.sync(() => closes.push(code)).pipe(Effect.asVoid),
|
||||
},
|
||||
);
|
||||
const credential = registration.accepted.credential;
|
||||
if (!credential) {
|
||||
return yield* Effect.die(new Error("enrollment did not issue a credential"));
|
||||
}
|
||||
|
||||
const threadId = ThreadId.make("revoke-pending-thread");
|
||||
const pendingRequestId = HermesGatewayRequestId.make("revoke-pending-request");
|
||||
const pendingRequest = yield* broker
|
||||
.request(instanceId, {
|
||||
type: "session.ensure",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: pendingRequestId,
|
||||
threadId,
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(sent.at(-1)?.type, "session.ensure");
|
||||
const statusEvent = yield* Stream.runHead(broker.streamStatuses).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
|
||||
failRemovals = true;
|
||||
const revokeError = yield* Effect.flip(broker.revokeInstance(instanceId));
|
||||
assert.equal(revokeError.code, "persistence-failed");
|
||||
assert.deepEqual(closes, [4003]);
|
||||
assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "revoked");
|
||||
assert.equal(Option.getOrUndefined(yield* Fiber.join(statusEvent))?.status, "revoked");
|
||||
const pendingError = yield* Effect.flip(Fiber.join(pendingRequest));
|
||||
assert.include(pendingError.detail, "revoked");
|
||||
|
||||
const staleReconnect = yield* Effect.flip(
|
||||
broker.registerConnection(hello({ type: "instance-credential", instanceId, credential }), {
|
||||
send: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
assert.equal(staleReconnect.code, "instance-revoked");
|
||||
|
||||
const restartedBroker = yield* makeBroker(secrets);
|
||||
const staleReconnectAfterRestart = yield* Effect.flip(
|
||||
restartedBroker.registerConnection(
|
||||
hello({ type: "instance-credential", instanceId, credential }),
|
||||
{
|
||||
send: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
),
|
||||
);
|
||||
assert.equal(staleReconnectAfterRestart.code, "instance-revoked");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares one live broker between the gateway route and Hermes provider instance", () => {
|
||||
const secrets = makeSecretStore();
|
||||
const providerLayer = Layer.effect(
|
||||
HermesTestInstance,
|
||||
HermesDriver.create({
|
||||
instanceId,
|
||||
displayName: "Remote Hermes",
|
||||
environment: [],
|
||||
enabled: true,
|
||||
config: HermesDriver.defaultConfig(),
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(HermesGatewayBrokerLive),
|
||||
Layer.provide(
|
||||
ServerSettings.layerTest({
|
||||
providerInstances: {
|
||||
[instanceId]: { driver: "hermes", displayName: "Remote", config: {} },
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.succeed(ServerSecretStore.ServerSecretStore, secrets)),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broker = yield* HermesGatewayBroker;
|
||||
const provider = yield* HermesTestInstance;
|
||||
const enrollment = yield* broker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Remote Hermes",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
const sent: Array<HermesGatewayT3ToPluginMessage> = [];
|
||||
const registration = yield* broker.registerConnection(
|
||||
hello({ type: "enrollment-token", token: enrollment.oneTimeToken }),
|
||||
{
|
||||
send: (message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
);
|
||||
assert.equal((yield* provider.snapshot.getSnapshot).status, "ready");
|
||||
|
||||
const threadId = ThreadId.make("shared-broker-thread");
|
||||
const startSession = yield* provider.adapter
|
||||
.startSession({
|
||||
threadId,
|
||||
providerInstanceId: instanceId,
|
||||
runtimeMode: "full-access",
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Effect.yieldNow;
|
||||
const ensure = sent.at(-1);
|
||||
if (!ensure || ensure.type !== "session.ensure") {
|
||||
return yield* Effect.die(new Error("session.ensure did not reach the gateway transport"));
|
||||
}
|
||||
const sessionId = HermesGatewaySessionId.make("shared-broker-session");
|
||||
yield* broker.receive(registration, {
|
||||
type: "session.ready",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: ensure.requestId,
|
||||
threadId,
|
||||
sessionId,
|
||||
resumed: false,
|
||||
});
|
||||
yield* Fiber.join(startSession);
|
||||
|
||||
const sendTurn = yield* provider.adapter
|
||||
.sendTurn({ threadId, input: "hello through the shared broker" })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Effect.yieldNow;
|
||||
const turnStart = sent.at(-1);
|
||||
if (!turnStart || turnStart.type !== "turn.start") {
|
||||
return yield* Effect.die(new Error("turn.start did not reach the gateway transport"));
|
||||
}
|
||||
yield* broker.receive(registration, {
|
||||
type: "turn.started",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: turnStart.requestId,
|
||||
threadId,
|
||||
sessionId,
|
||||
turnId: turnStart.turnId,
|
||||
});
|
||||
assert.equal((yield* Fiber.join(sendTurn)).turnId, turnStart.turnId);
|
||||
}).pipe(Effect.provide(providerLayer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("checks nickname uniqueness from persisted metadata after restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const secrets = makeSecretStore();
|
||||
const firstBroker = yield* makeBroker(secrets);
|
||||
yield* firstBroker.createEnrollment({
|
||||
instanceId,
|
||||
nickname: "Persistent Nickname",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
});
|
||||
|
||||
const restartedBroker = yield* makeBroker(secrets);
|
||||
const error = yield* Effect.flip(
|
||||
restartedBroker.createEnrollment({
|
||||
instanceId: otherInstanceId,
|
||||
nickname: "Persistent Nickname",
|
||||
connectorUrl: "https://t3.example.test",
|
||||
}),
|
||||
);
|
||||
assert.equal(error.code, "nickname-conflict");
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,892 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import {
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HERMES_DRIVER_KIND,
|
||||
defaultInstanceIdForDriver,
|
||||
HermesGatewayCredential,
|
||||
HermesGatewayEnrollmentToken,
|
||||
HermesGatewayCapabilities,
|
||||
HermesGatewayManagementError,
|
||||
type HermesGatewayConnectionHello,
|
||||
type HermesGatewayCreateEnrollmentInput,
|
||||
type HermesGatewayEnrollmentResult,
|
||||
type HermesGatewayInstanceStatus,
|
||||
type HermesGatewayPluginToT3Message,
|
||||
type HermesGatewayRevokeInstanceResult,
|
||||
type HermesGatewayT3ToPluginMessage,
|
||||
type ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterRequestError } from "../Errors.ts";
|
||||
import {
|
||||
HermesGatewayBroker,
|
||||
type HermesGatewayConnectionRegistration,
|
||||
type HermesGatewayEnvelope,
|
||||
type HermesGatewayTransport,
|
||||
type HermesGatewayBrokerShape,
|
||||
} from "../Services/HermesGatewayBroker.ts";
|
||||
|
||||
const ENROLLMENT_TTL = Duration.minutes(10);
|
||||
const REQUEST_TIMEOUT = Duration.seconds(30);
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
const isStrictCapabilities = Schema.is(HermesGatewayCapabilities);
|
||||
|
||||
interface PendingEnrollment {
|
||||
readonly input: HermesGatewayCreateEnrollmentInput;
|
||||
readonly expiresAtMillis: number;
|
||||
}
|
||||
|
||||
interface InstanceMetadata {
|
||||
readonly nickname: string;
|
||||
readonly connectorUrl: string;
|
||||
readonly revoked: boolean;
|
||||
readonly lastSeen?: {
|
||||
readonly pluginVersion: string;
|
||||
readonly hermesVersion: string;
|
||||
readonly capabilities: NonNullable<HermesGatewayInstanceStatus["capabilities"]>;
|
||||
readonly connectedAt: string;
|
||||
readonly activeSessionCount: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface ActiveConnection {
|
||||
readonly generation: number;
|
||||
readonly transport: HermesGatewayTransport;
|
||||
readonly pluginVersion: string;
|
||||
readonly hermesVersion: string;
|
||||
readonly capabilities: NonNullable<HermesGatewayInstanceStatus["capabilities"]>;
|
||||
readonly connectedAt: string;
|
||||
readonly activeSessionCount: number;
|
||||
}
|
||||
|
||||
interface InstanceState {
|
||||
readonly metadata: InstanceMetadata;
|
||||
readonly connection?: ActiveConnection;
|
||||
readonly lastSeen?: Omit<ActiveConnection, "transport" | "generation" | "activeSessionCount"> & {
|
||||
readonly activeSessionCount: number;
|
||||
};
|
||||
readonly upgradeRequired?: {
|
||||
readonly pluginVersion: string;
|
||||
readonly hermesVersion: string;
|
||||
readonly protocolVersion: number;
|
||||
};
|
||||
}
|
||||
|
||||
type PluginMessage = Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>;
|
||||
|
||||
const credentialSecretName = (instanceId: ProviderInstanceId) =>
|
||||
`hermes-gateway-credential-${Buffer.from(instanceId, "utf8").toString("base64url")}`;
|
||||
|
||||
const metadataSecretName = (instanceId: ProviderInstanceId) =>
|
||||
`hermes-gateway-metadata-${Buffer.from(instanceId, "utf8").toString("base64url")}`;
|
||||
|
||||
const managementError = (
|
||||
operation: HermesGatewayManagementError["operation"],
|
||||
code: HermesGatewayManagementError["code"],
|
||||
message: string,
|
||||
instanceId?: ProviderInstanceId,
|
||||
) =>
|
||||
new HermesGatewayManagementError({
|
||||
operation,
|
||||
code,
|
||||
message,
|
||||
...(instanceId ? { instanceId } : {}),
|
||||
});
|
||||
|
||||
const rejection = (
|
||||
requestId: HermesGatewayConnectionHello["requestId"],
|
||||
code: Extract<HermesGatewayT3ToPluginMessage, { readonly type: "connection.rejected" }>["code"],
|
||||
message: string,
|
||||
): Extract<HermesGatewayT3ToPluginMessage, { readonly type: "connection.rejected" }> => ({
|
||||
type: "connection.rejected",
|
||||
requestId,
|
||||
code,
|
||||
message,
|
||||
expectedProtocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
});
|
||||
|
||||
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
|
||||
const credentialsEqual = (left: Uint8Array, right: string) => {
|
||||
const rightBytes = textEncoder.encode(right);
|
||||
return left.byteLength === rightBytes.byteLength && NodeCrypto.timingSafeEqual(left, rightBytes);
|
||||
};
|
||||
|
||||
const statusFromState = (
|
||||
instanceId: ProviderInstanceId,
|
||||
state: InstanceState,
|
||||
): HermesGatewayInstanceStatus => ({
|
||||
...(() => {
|
||||
const observed = state.connection ?? state.lastSeen ?? state.metadata.lastSeen;
|
||||
return {
|
||||
lastConnectedAt: observed?.connectedAt ?? null,
|
||||
pluginVersion: observed?.pluginVersion ?? state.upgradeRequired?.pluginVersion ?? null,
|
||||
hermesVersion: observed?.hermesVersion ?? state.upgradeRequired?.hermesVersion ?? null,
|
||||
activeSessionCount: state.connection?.activeSessionCount ?? 0,
|
||||
protocolVersion:
|
||||
observed?.capabilities.protocolVersion ?? state.upgradeRequired?.protocolVersion ?? null,
|
||||
capabilities: observed?.capabilities ?? null,
|
||||
};
|
||||
})(),
|
||||
instanceId,
|
||||
nickname: state.metadata.nickname,
|
||||
status: state.metadata.revoked
|
||||
? "revoked"
|
||||
: state.upgradeRequired
|
||||
? "upgrade-required"
|
||||
: state.connection
|
||||
? "connected"
|
||||
: "offline",
|
||||
connectorUrl: state.metadata.connectorUrl,
|
||||
});
|
||||
|
||||
export const makeHermesGatewayBroker = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const states = yield* Ref.make(new Map<ProviderInstanceId, InstanceState>());
|
||||
const enrollments = yield* Ref.make(new Map<string, PendingEnrollment>());
|
||||
const pendingRequests = yield* Ref.make(
|
||||
new Map<
|
||||
string,
|
||||
{
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly deferred: Deferred.Deferred<PluginMessage, ProviderAdapterRequestError>;
|
||||
}
|
||||
>(),
|
||||
);
|
||||
const events = yield* PubSub.unbounded<HermesGatewayEnvelope>();
|
||||
const statusEvents = yield* PubSub.unbounded<HermesGatewayInstanceStatus>();
|
||||
const generation = yield* Ref.make(0);
|
||||
const enrollmentSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const publishStatus = (instanceId: ProviderInstanceId, state: InstanceState) =>
|
||||
PubSub.publish(statusEvents, statusFromState(instanceId, state)).pipe(Effect.asVoid);
|
||||
|
||||
const failPendingRequests = (instanceId: ProviderInstanceId, detail: string) =>
|
||||
Effect.gen(function* () {
|
||||
const affected = yield* Ref.modify(pendingRequests, (current) => {
|
||||
const next = new Map(current);
|
||||
const found = Array.from(current.entries()).filter(
|
||||
([, pending]) => pending.instanceId === instanceId,
|
||||
);
|
||||
for (const [requestId] of found) next.delete(requestId);
|
||||
return [found.map(([, pending]) => pending.deferred), next] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
affected,
|
||||
(deferred) =>
|
||||
Deferred.fail(
|
||||
deferred,
|
||||
new ProviderAdapterRequestError({
|
||||
provider: HERMES_DRIVER_KIND,
|
||||
method: "connection",
|
||||
detail,
|
||||
}),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const persistMetadata = (instanceId: ProviderInstanceId, metadata: InstanceMetadata) =>
|
||||
secretStore
|
||||
.set(metadataSecretName(instanceId), textEncoder.encode(JSON.stringify(metadata)))
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError(
|
||||
"create-enrollment",
|
||||
"persistence-failed",
|
||||
"Failed to persist Hermes gateway metadata.",
|
||||
instanceId,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const readMetadata = (instanceId: ProviderInstanceId) =>
|
||||
secretStore.get(metadataSecretName(instanceId)).pipe(
|
||||
Effect.map((stored) => {
|
||||
if (Option.isNone(stored)) return undefined;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(textDecoder.decode(stored.value));
|
||||
if (
|
||||
typeof parsed === "object" &&
|
||||
parsed !== null &&
|
||||
"nickname" in parsed &&
|
||||
typeof parsed.nickname === "string" &&
|
||||
"connectorUrl" in parsed &&
|
||||
typeof parsed.connectorUrl === "string" &&
|
||||
"revoked" in parsed &&
|
||||
typeof parsed.revoked === "boolean"
|
||||
) {
|
||||
return {
|
||||
nickname: parsed.nickname,
|
||||
connectorUrl: parsed.connectorUrl,
|
||||
revoked: parsed.revoked,
|
||||
...("lastSeen" in parsed &&
|
||||
typeof parsed.lastSeen === "object" &&
|
||||
parsed.lastSeen !== null &&
|
||||
"pluginVersion" in parsed.lastSeen &&
|
||||
typeof parsed.lastSeen.pluginVersion === "string" &&
|
||||
"hermesVersion" in parsed.lastSeen &&
|
||||
typeof parsed.lastSeen.hermesVersion === "string" &&
|
||||
"connectedAt" in parsed.lastSeen &&
|
||||
typeof parsed.lastSeen.connectedAt === "string" &&
|
||||
"activeSessionCount" in parsed.lastSeen &&
|
||||
typeof parsed.lastSeen.activeSessionCount === "number" &&
|
||||
"capabilities" in parsed.lastSeen &&
|
||||
isStrictCapabilities(parsed.lastSeen.capabilities)
|
||||
? {
|
||||
lastSeen: {
|
||||
pluginVersion: parsed.lastSeen.pluginVersion,
|
||||
hermesVersion: parsed.lastSeen.hermesVersion,
|
||||
connectedAt: parsed.lastSeen.connectedAt,
|
||||
activeSessionCount: parsed.lastSeen.activeSessionCount,
|
||||
capabilities: parsed.lastSeen.capabilities,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
} satisfies InstanceMetadata;
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
|
||||
const getState = (instanceId: ProviderInstanceId) =>
|
||||
Ref.get(states).pipe(
|
||||
Effect.map((current) => current.get(instanceId)),
|
||||
Effect.flatMap((state) => {
|
||||
if (state) return Effect.succeed(state);
|
||||
return readMetadata(instanceId).pipe(
|
||||
Effect.flatMap((metadata) => {
|
||||
if (!metadata) {
|
||||
return Effect.fail(
|
||||
managementError(
|
||||
"get-status",
|
||||
"instance-not-found",
|
||||
`Hermes gateway instance '${instanceId}' has not been enrolled.`,
|
||||
instanceId,
|
||||
),
|
||||
);
|
||||
}
|
||||
const loaded: InstanceState = { metadata };
|
||||
return Ref.update(states, (current) => new Map(current).set(instanceId, loaded)).pipe(
|
||||
Effect.as(loaded),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const createEnrollment = (input: HermesGatewayCreateEnrollmentInput) =>
|
||||
enrollmentSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const normalizedNickname = input.nickname.trim();
|
||||
const normalizedInput = {
|
||||
...input,
|
||||
nickname: normalizedNickname,
|
||||
} satisfies HermesGatewayCreateEnrollmentInput;
|
||||
const currentSettings = yield* settings.getSettings.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError(
|
||||
"create-enrollment",
|
||||
"internal-error",
|
||||
"Failed to read server settings.",
|
||||
input.instanceId,
|
||||
),
|
||||
),
|
||||
);
|
||||
const configured = currentSettings.providerInstances[input.instanceId];
|
||||
const isDefaultHermesInstance =
|
||||
input.instanceId === defaultInstanceIdForDriver(HERMES_DRIVER_KIND);
|
||||
if ((!configured || configured.driver !== HERMES_DRIVER_KIND) && !isDefaultHermesInstance) {
|
||||
return yield* managementError(
|
||||
"create-enrollment",
|
||||
"instance-not-found",
|
||||
`Provider instance '${input.instanceId}' is not configured with the Hermes driver.`,
|
||||
input.instanceId,
|
||||
);
|
||||
}
|
||||
|
||||
const configuredHermesIds = [
|
||||
defaultInstanceIdForDriver(HERMES_DRIVER_KIND),
|
||||
...Object.entries(currentSettings.providerInstances)
|
||||
.filter(([, config]) => config.driver === HERMES_DRIVER_KIND)
|
||||
.map(([instanceId]) => instanceId as ProviderInstanceId),
|
||||
];
|
||||
const existingStates = yield* Ref.get(states);
|
||||
for (const instanceId of new Set(configuredHermesIds)) {
|
||||
const persistedMetadata = existingStates.has(instanceId)
|
||||
? undefined
|
||||
: yield* readMetadata(instanceId);
|
||||
const state =
|
||||
existingStates.get(instanceId) ??
|
||||
(persistedMetadata ? { metadata: persistedMetadata } : undefined);
|
||||
if (!state) continue;
|
||||
if (instanceId !== input.instanceId && state.metadata.nickname === normalizedNickname) {
|
||||
return yield* managementError(
|
||||
"create-enrollment",
|
||||
"nickname-conflict",
|
||||
`A Hermes gateway named '${normalizedNickname}' already exists.`,
|
||||
input.instanceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const token = HermesGatewayEnrollmentToken.make(
|
||||
Encoding.encodeBase64Url(
|
||||
yield* crypto
|
||||
.randomBytes(32)
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError(
|
||||
"create-enrollment",
|
||||
"internal-error",
|
||||
"Failed to generate an enrollment token.",
|
||||
input.instanceId,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const expiresAtMillis =
|
||||
(yield* Clock.currentTimeMillis) + Duration.toMillis(ENROLLMENT_TTL);
|
||||
const previousState = existingStates.get(input.instanceId);
|
||||
const metadata = {
|
||||
nickname: normalizedNickname,
|
||||
connectorUrl: input.connectorUrl,
|
||||
revoked: false,
|
||||
...(previousState?.metadata.lastSeen
|
||||
? { lastSeen: previousState.metadata.lastSeen }
|
||||
: {}),
|
||||
} satisfies InstanceMetadata;
|
||||
yield* secretStore
|
||||
.remove(credentialSecretName(input.instanceId))
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError(
|
||||
"create-enrollment",
|
||||
"persistence-failed",
|
||||
"Failed to invalidate the previous Hermes gateway credential.",
|
||||
input.instanceId,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (previousState?.connection) {
|
||||
yield* failPendingRequests(
|
||||
input.instanceId,
|
||||
"A new enrollment replaced the active Hermes gateway credential.",
|
||||
);
|
||||
yield* previousState.connection.transport.close(
|
||||
4001,
|
||||
"A new enrollment was created for this instance",
|
||||
);
|
||||
}
|
||||
yield* persistMetadata(input.instanceId, metadata);
|
||||
const enrolledState: InstanceState = {
|
||||
metadata,
|
||||
...(previousState?.lastSeen ? { lastSeen: previousState.lastSeen } : {}),
|
||||
};
|
||||
yield* Ref.update(states, (current) =>
|
||||
new Map(current).set(input.instanceId, enrolledState),
|
||||
);
|
||||
yield* publishStatus(input.instanceId, enrolledState);
|
||||
yield* Ref.update(enrollments, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const [pendingToken, pending] of current) {
|
||||
if (pending.input.instanceId === input.instanceId) {
|
||||
next.delete(pendingToken);
|
||||
}
|
||||
}
|
||||
return next.set(token, { input: normalizedInput, expiresAtMillis });
|
||||
});
|
||||
|
||||
return {
|
||||
instanceId: input.instanceId,
|
||||
expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)),
|
||||
connectorUrl: input.connectorUrl,
|
||||
command: `hermes t3 connect --url ${shellQuote(input.connectorUrl)} --token ${shellQuote(token)}`,
|
||||
oneTimeToken: token,
|
||||
} satisfies HermesGatewayEnrollmentResult;
|
||||
}),
|
||||
);
|
||||
|
||||
const getInstanceStatus = (instanceId: ProviderInstanceId) =>
|
||||
getState(instanceId).pipe(Effect.map((state) => statusFromState(instanceId, state)));
|
||||
|
||||
const listInstances = Effect.gen(function* () {
|
||||
const currentSettings = yield* settings.getSettings.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError("list-instances", "internal-error", "Failed to read server settings."),
|
||||
),
|
||||
);
|
||||
const ids = Array.from(
|
||||
new Set([
|
||||
defaultInstanceIdForDriver(HERMES_DRIVER_KIND),
|
||||
...Object.entries(currentSettings.providerInstances)
|
||||
.filter(([, config]) => config.driver === HERMES_DRIVER_KIND)
|
||||
.map(([id]) => id as ProviderInstanceId),
|
||||
]),
|
||||
);
|
||||
return yield* Effect.forEach(
|
||||
ids,
|
||||
(instanceId) =>
|
||||
getInstanceStatus(instanceId).pipe(
|
||||
Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined)),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.map((values) => values.filter((value) => value !== undefined)));
|
||||
});
|
||||
|
||||
const revokeInstance = (instanceId: ProviderInstanceId) =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* getState(instanceId);
|
||||
const metadata: InstanceMetadata = { ...state.metadata, revoked: true };
|
||||
yield* persistMetadata(instanceId, metadata).pipe(
|
||||
Effect.mapError((error) =>
|
||||
managementError("revoke-instance", error.code, error.message, instanceId),
|
||||
),
|
||||
);
|
||||
const next: InstanceState = {
|
||||
metadata,
|
||||
...(state.lastSeen ? { lastSeen: state.lastSeen } : {}),
|
||||
};
|
||||
yield* Ref.update(states, (current) => new Map(current).set(instanceId, next));
|
||||
if (state.connection) {
|
||||
yield* failPendingRequests(instanceId, "The Hermes gateway credential was revoked.");
|
||||
yield* state.connection.transport.close(4003, "Hermes gateway credential revoked");
|
||||
}
|
||||
yield* publishStatus(instanceId, next);
|
||||
yield* secretStore
|
||||
.remove(credentialSecretName(instanceId))
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
managementError(
|
||||
"revoke-instance",
|
||||
"persistence-failed",
|
||||
"Failed to remove the Hermes gateway credential.",
|
||||
instanceId,
|
||||
),
|
||||
),
|
||||
);
|
||||
return statusFromState(instanceId, next) satisfies HermesGatewayRevokeInstanceResult;
|
||||
});
|
||||
|
||||
const registerConnectionEffect = (
|
||||
hello: HermesGatewayConnectionHello,
|
||||
transport: HermesGatewayTransport,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const strictCapabilities = isStrictCapabilities(hello.capabilities)
|
||||
? hello.capabilities
|
||||
: undefined;
|
||||
|
||||
let instanceId: ProviderInstanceId;
|
||||
let credential: HermesGatewayCredential | undefined;
|
||||
let authenticatedEnrollment: PendingEnrollment | undefined;
|
||||
let state: InstanceState;
|
||||
if (hello.authentication.type === "enrollment-token") {
|
||||
const authentication = hello.authentication;
|
||||
const enrollment = (yield* Ref.get(enrollments)).get(authentication.token);
|
||||
if (!enrollment || enrollment.expiresAtMillis < (yield* Clock.currentTimeMillis)) {
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"enrollment-expired",
|
||||
"The enrollment token is invalid, expired, or already used.",
|
||||
),
|
||||
);
|
||||
}
|
||||
instanceId = enrollment.input.instanceId;
|
||||
authenticatedEnrollment = enrollment;
|
||||
state = yield* getState(instanceId).pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"invalid-authentication",
|
||||
"Unknown Hermes gateway instance.",
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const authentication = hello.authentication;
|
||||
instanceId = authentication.instanceId;
|
||||
state = yield* getState(instanceId).pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"invalid-authentication",
|
||||
"Unknown Hermes gateway instance.",
|
||||
),
|
||||
),
|
||||
);
|
||||
if (state.metadata.revoked) {
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"instance-revoked",
|
||||
"This Hermes gateway instance has been revoked.",
|
||||
),
|
||||
);
|
||||
}
|
||||
const stored = yield* secretStore
|
||||
.get(credentialSecretName(instanceId))
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"internal-error",
|
||||
"Failed to read the gateway credential.",
|
||||
),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(stored) || !credentialsEqual(stored.value, authentication.credential)) {
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"invalid-authentication",
|
||||
"The Hermes gateway credential is invalid.",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (state.metadata.revoked) {
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"instance-revoked",
|
||||
"This Hermes gateway instance has been revoked.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION ||
|
||||
strictCapabilities === undefined
|
||||
) {
|
||||
if (state.connection) {
|
||||
yield* failPendingRequests(
|
||||
instanceId,
|
||||
"The Hermes gateway plugin requires a protocol upgrade.",
|
||||
);
|
||||
yield* state.connection.transport.close(
|
||||
4004,
|
||||
"Hermes gateway protocol version is incompatible",
|
||||
);
|
||||
}
|
||||
const upgradeState: InstanceState = {
|
||||
metadata: state.metadata,
|
||||
...(state.lastSeen ? { lastSeen: state.lastSeen } : {}),
|
||||
upgradeRequired: {
|
||||
pluginVersion: hello.pluginVersion,
|
||||
hermesVersion: hello.hermesVersion,
|
||||
protocolVersion: hello.protocolVersion,
|
||||
},
|
||||
};
|
||||
yield* Ref.update(states, (current) => new Map(current).set(instanceId, upgradeState));
|
||||
yield* publishStatus(instanceId, upgradeState);
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"version-incompatible",
|
||||
`Expected protocol version ${HERMES_GATEWAY_PROTOCOL_VERSION}.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (hello.authentication.type === "enrollment-token" && authenticatedEnrollment) {
|
||||
const authentication = hello.authentication;
|
||||
const enrollment = yield* Ref.modify(enrollments, (current) => {
|
||||
const found = current.get(authentication.token);
|
||||
const next = new Map(current);
|
||||
if (found === authenticatedEnrollment) next.delete(authentication.token);
|
||||
return [found, next] as const;
|
||||
});
|
||||
if (
|
||||
enrollment !== authenticatedEnrollment ||
|
||||
enrollment.expiresAtMillis < (yield* Clock.currentTimeMillis)
|
||||
) {
|
||||
return yield* Effect.fail(
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"enrollment-expired",
|
||||
"The enrollment token is invalid, expired, or already used.",
|
||||
),
|
||||
);
|
||||
}
|
||||
instanceId = enrollment.input.instanceId;
|
||||
credential = HermesGatewayCredential.make(
|
||||
Encoding.encodeBase64Url(
|
||||
yield* crypto
|
||||
.randomBytes(32)
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"internal-error",
|
||||
"Failed to generate the Hermes gateway credential.",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* secretStore
|
||||
.set(credentialSecretName(instanceId), textEncoder.encode(credential))
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"internal-error",
|
||||
"Failed to persist the Hermes gateway credential.",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1);
|
||||
const connectedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const connection = {
|
||||
generation: nextGeneration,
|
||||
transport,
|
||||
pluginVersion: hello.pluginVersion,
|
||||
hermesVersion: hello.hermesVersion,
|
||||
capabilities: strictCapabilities,
|
||||
connectedAt,
|
||||
activeSessionCount: 0,
|
||||
} satisfies ActiveConnection;
|
||||
const lastSeen = {
|
||||
pluginVersion: connection.pluginVersion,
|
||||
hermesVersion: connection.hermesVersion,
|
||||
capabilities: connection.capabilities,
|
||||
connectedAt: connection.connectedAt,
|
||||
activeSessionCount: connection.activeSessionCount,
|
||||
};
|
||||
const connectedMetadata: InstanceMetadata = {
|
||||
...state.metadata,
|
||||
lastSeen,
|
||||
};
|
||||
yield* persistMetadata(instanceId, connectedMetadata).pipe(
|
||||
Effect.mapError(() =>
|
||||
rejection(
|
||||
hello.requestId,
|
||||
"internal-error",
|
||||
"Failed to persist Hermes gateway connection metadata.",
|
||||
),
|
||||
),
|
||||
);
|
||||
if (state.connection) {
|
||||
yield* failPendingRequests(
|
||||
instanceId,
|
||||
"The Hermes gateway connection was replaced by a newer connection.",
|
||||
);
|
||||
yield* state.connection.transport.close(4001, "Replaced by a newer connection");
|
||||
}
|
||||
yield* Ref.update(states, (current) =>
|
||||
new Map(current).set(instanceId, {
|
||||
metadata: connectedMetadata,
|
||||
connection,
|
||||
lastSeen,
|
||||
}),
|
||||
);
|
||||
yield* publishStatus(instanceId, {
|
||||
metadata: connectedMetadata,
|
||||
connection,
|
||||
lastSeen,
|
||||
});
|
||||
|
||||
const accepted = {
|
||||
type: "connection.accepted",
|
||||
requestId: hello.requestId,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
instanceId,
|
||||
nickname: state.metadata.nickname,
|
||||
...(credential ? { credential } : {}),
|
||||
} as const;
|
||||
return {
|
||||
instanceId,
|
||||
generation: nextGeneration,
|
||||
accepted,
|
||||
} satisfies HermesGatewayConnectionRegistration;
|
||||
});
|
||||
|
||||
const registerConnection = (
|
||||
hello: HermesGatewayConnectionHello,
|
||||
transport: HermesGatewayTransport,
|
||||
) =>
|
||||
hello.authentication.type === "enrollment-token"
|
||||
? enrollmentSemaphore.withPermits(1)(registerConnectionEffect(hello, transport))
|
||||
: registerConnectionEffect(hello, transport);
|
||||
|
||||
const receive = (registration: HermesGatewayConnectionRegistration, message: PluginMessage) =>
|
||||
Effect.gen(function* () {
|
||||
const state = (yield* Ref.get(states)).get(registration.instanceId);
|
||||
if (state?.connection?.generation !== registration.generation) return;
|
||||
if (message.type === "connection.status") {
|
||||
yield* Ref.update(states, (current) => {
|
||||
const found = current.get(registration.instanceId);
|
||||
if (found?.connection?.generation !== registration.generation) return current;
|
||||
return new Map(current).set(registration.instanceId, {
|
||||
...found,
|
||||
connection: {
|
||||
...found.connection,
|
||||
activeSessionCount: message.activeSessionCount,
|
||||
},
|
||||
});
|
||||
});
|
||||
const updated = (yield* Ref.get(states)).get(registration.instanceId);
|
||||
if (updated) yield* publishStatus(registration.instanceId, updated);
|
||||
}
|
||||
if ("requestId" in message && message.requestId) {
|
||||
const correlatedRequestId = message.requestId;
|
||||
const pending = yield* Ref.modify(pendingRequests, (current) => {
|
||||
const found = current.get(correlatedRequestId);
|
||||
if (!found) return [undefined, current] as const;
|
||||
const next = new Map(current);
|
||||
next.delete(correlatedRequestId);
|
||||
return [found, next] as const;
|
||||
});
|
||||
if (pending) {
|
||||
yield* Deferred.succeed(pending.deferred, message);
|
||||
}
|
||||
}
|
||||
yield* PubSub.publish(events, {
|
||||
instanceId: registration.instanceId,
|
||||
message,
|
||||
});
|
||||
});
|
||||
|
||||
const disconnect = (registration: HermesGatewayConnectionRegistration) =>
|
||||
Effect.gen(function* () {
|
||||
let disconnected: InstanceState | undefined;
|
||||
yield* Ref.update(states, (current) => {
|
||||
const found = current.get(registration.instanceId);
|
||||
if (found?.connection?.generation !== registration.generation) return current;
|
||||
const next = new Map(current);
|
||||
const lastSeen = {
|
||||
pluginVersion: found.connection.pluginVersion,
|
||||
hermesVersion: found.connection.hermesVersion,
|
||||
capabilities: found.connection.capabilities,
|
||||
connectedAt: found.connection.connectedAt,
|
||||
activeSessionCount: found.connection.activeSessionCount,
|
||||
};
|
||||
disconnected = {
|
||||
metadata: { ...found.metadata, lastSeen },
|
||||
lastSeen,
|
||||
};
|
||||
next.set(registration.instanceId, disconnected);
|
||||
return next;
|
||||
});
|
||||
if (disconnected) {
|
||||
yield* persistMetadata(registration.instanceId, disconnected.metadata).pipe(Effect.ignore);
|
||||
}
|
||||
if (disconnected) yield* publishStatus(registration.instanceId, disconnected);
|
||||
if (disconnected) {
|
||||
yield* failPendingRequests(
|
||||
registration.instanceId,
|
||||
"The Hermes gateway connection disconnected.",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const send = (instanceId: ProviderInstanceId, message: HermesGatewayT3ToPluginMessage) =>
|
||||
Effect.gen(function* () {
|
||||
const state = (yield* Ref.get(states)).get(instanceId);
|
||||
if (!state?.connection) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: "hermes",
|
||||
method: message.type,
|
||||
detail: `Hermes gateway instance '${instanceId}' is offline.`,
|
||||
});
|
||||
}
|
||||
yield* state.connection.transport.send(message);
|
||||
});
|
||||
|
||||
const request = (instanceId: ProviderInstanceId, message: HermesGatewayT3ToPluginMessage) =>
|
||||
Effect.gen(function* () {
|
||||
if (!("requestId" in message) || !message.requestId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: "hermes",
|
||||
method: message.type,
|
||||
detail: "A correlated Hermes gateway request requires a request id.",
|
||||
});
|
||||
}
|
||||
const deferred = yield* Deferred.make<PluginMessage, ProviderAdapterRequestError>();
|
||||
yield* Ref.update(pendingRequests, (current) =>
|
||||
new Map(current).set(message.requestId as string, {
|
||||
instanceId,
|
||||
deferred,
|
||||
}),
|
||||
);
|
||||
yield* send(instanceId, message).pipe(
|
||||
Effect.tapError(() =>
|
||||
Ref.update(pendingRequests, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(message.requestId as string);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* Deferred.await(deferred).pipe(
|
||||
Effect.timeout(REQUEST_TIMEOUT),
|
||||
Effect.mapError((error) =>
|
||||
error._tag === "TimeoutError"
|
||||
? new ProviderAdapterRequestError({
|
||||
provider: "hermes",
|
||||
method: message.type,
|
||||
detail: "Hermes gateway request timed out.",
|
||||
})
|
||||
: error,
|
||||
),
|
||||
Effect.ensuring(
|
||||
Ref.update(pendingRequests, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(message.requestId as string);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const isConnected = (instanceId: ProviderInstanceId) =>
|
||||
Ref.get(states).pipe(
|
||||
Effect.map((current) => current.get(instanceId)?.connection !== undefined),
|
||||
);
|
||||
|
||||
return {
|
||||
createEnrollment,
|
||||
getInstanceStatus,
|
||||
listInstances,
|
||||
revokeInstance,
|
||||
registerConnection,
|
||||
receive,
|
||||
disconnect,
|
||||
request,
|
||||
send,
|
||||
isConnected,
|
||||
stream: Stream.fromPubSub(events),
|
||||
streamStatuses: Stream.fromPubSub(statusEvents),
|
||||
} satisfies HermesGatewayBrokerShape;
|
||||
});
|
||||
|
||||
export const HermesGatewayBrokerLive = Layer.effect(HermesGatewayBroker, makeHermesGatewayBroker);
|
||||
@@ -0,0 +1,101 @@
|
||||
import type {
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayEnrollmentResult,
|
||||
HermesGatewayInstanceStatus,
|
||||
HermesGatewayPluginToT3Message,
|
||||
HermesGatewayRevokeInstanceResult,
|
||||
HermesGatewayT3ToPluginMessage,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { HermesGatewayManagementError } from "@t3tools/contracts";
|
||||
import type { ProviderAdapterRequestError } from "../Errors.ts";
|
||||
|
||||
export interface HermesGatewayTransport {
|
||||
readonly send: (
|
||||
message: HermesGatewayT3ToPluginMessage,
|
||||
) => Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
readonly close: (code: number, reason: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface HermesGatewayConnectionRegistration {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly generation: number;
|
||||
readonly accepted: Extract<
|
||||
HermesGatewayT3ToPluginMessage,
|
||||
{ readonly type: "connection.accepted" }
|
||||
>;
|
||||
}
|
||||
|
||||
export interface HermesGatewayEnvelope {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>;
|
||||
}
|
||||
|
||||
export interface HermesGatewayBrokerShape {
|
||||
readonly createEnrollment: (
|
||||
input: HermesGatewayCreateEnrollmentInput,
|
||||
) => Effect.Effect<HermesGatewayEnrollmentResult, HermesGatewayManagementError>;
|
||||
readonly getInstanceStatus: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayInstanceStatus, HermesGatewayManagementError>;
|
||||
readonly listInstances: Effect.Effect<
|
||||
ReadonlyArray<HermesGatewayInstanceStatus>,
|
||||
HermesGatewayManagementError
|
||||
>;
|
||||
readonly revokeInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayRevokeInstanceResult, HermesGatewayManagementError>;
|
||||
readonly registerConnection: (
|
||||
hello: HermesGatewayConnectionHello,
|
||||
transport: HermesGatewayTransport,
|
||||
) => Effect.Effect<
|
||||
HermesGatewayConnectionRegistration,
|
||||
Extract<HermesGatewayT3ToPluginMessage, { readonly type: "connection.rejected" }>
|
||||
>;
|
||||
readonly receive: (
|
||||
registration: HermesGatewayConnectionRegistration,
|
||||
message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly disconnect: (registration: HermesGatewayConnectionRegistration) => Effect.Effect<void>;
|
||||
readonly request: (
|
||||
instanceId: ProviderInstanceId,
|
||||
message: HermesGatewayT3ToPluginMessage,
|
||||
) => Effect.Effect<
|
||||
Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
|
||||
ProviderAdapterRequestError
|
||||
>;
|
||||
readonly send: (
|
||||
instanceId: ProviderInstanceId,
|
||||
message: HermesGatewayT3ToPluginMessage,
|
||||
) => Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
|
||||
readonly stream: Stream.Stream<HermesGatewayEnvelope>;
|
||||
readonly streamStatuses: Stream.Stream<HermesGatewayInstanceStatus>;
|
||||
}
|
||||
|
||||
const unavailable = () => Effect.die(new Error("HermesGatewayBroker live layer is not installed"));
|
||||
|
||||
export const HermesGatewayBroker = Context.Reference<HermesGatewayBrokerShape>(
|
||||
"t3/provider/Services/HermesGatewayBroker",
|
||||
{
|
||||
defaultValue: () => ({
|
||||
createEnrollment: unavailable,
|
||||
getInstanceStatus: unavailable,
|
||||
listInstances: unavailable(),
|
||||
revokeInstance: unavailable,
|
||||
registerConnection: unavailable,
|
||||
receive: unavailable,
|
||||
disconnect: unavailable,
|
||||
request: unavailable,
|
||||
send: unavailable,
|
||||
isConnected: () => Effect.succeed(false),
|
||||
stream: Stream.empty,
|
||||
streamStatuses: Stream.empty,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -24,6 +24,7 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
|
||||
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
|
||||
import { HermesDriver, type HermesDriverEnv } from "./Drivers/HermesDriver.ts";
|
||||
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
|
||||
@@ -37,6 +38,7 @@ export type BuiltInDriversEnv =
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| GrokDriverEnv
|
||||
| HermesDriverEnv
|
||||
| OpenCodeDriverEnv;
|
||||
|
||||
/**
|
||||
@@ -50,4 +52,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
OpenCodeDriver,
|
||||
HermesDriver,
|
||||
];
|
||||
@@ -0,0 +1,116 @@
|
||||
import {
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayPluginToT3Message,
|
||||
HermesGatewayT3ToPluginMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
|
||||
import {
|
||||
HermesGatewayBroker,
|
||||
type HermesGatewayConnectionRegistration,
|
||||
} from "./Services/HermesGatewayBroker.ts";
|
||||
import { ProviderAdapterRequestError } from "./Errors.ts";
|
||||
|
||||
export const HERMES_GATEWAY_WEBSOCKET_PATH = "/api/hermes-gateway/ws";
|
||||
|
||||
const decodePluginFrame = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(HermesGatewayPluginToT3Message),
|
||||
);
|
||||
const encodeServerFrame = Schema.encodeSync(Schema.fromJsonString(HermesGatewayT3ToPluginMessage));
|
||||
const isConnectionHello = Schema.is(HermesGatewayConnectionHello);
|
||||
|
||||
export const hermesGatewayWebSocketRouteLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* HermesGatewayBroker;
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
HERMES_GATEWAY_WEBSOCKET_PATH,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const socket = yield* Effect.orDie(request.upgrade);
|
||||
const write = yield* socket.writer;
|
||||
const registration = yield* Ref.make<Option.Option<HermesGatewayConnectionRegistration>>(
|
||||
Option.none(),
|
||||
);
|
||||
const transport = {
|
||||
send: (message: HermesGatewayT3ToPluginMessage) =>
|
||||
write(encodeServerFrame(message)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "hermes",
|
||||
method: message.type,
|
||||
detail: "Failed to write a Hermes gateway WebSocket frame.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
close: (code: number, reason: string) =>
|
||||
write(new Socket.CloseEvent(code, reason)).pipe(Effect.ignore),
|
||||
};
|
||||
|
||||
yield* socket
|
||||
.runString((frame) =>
|
||||
Effect.gen(function* () {
|
||||
const message = yield* decodePluginFrame(frame);
|
||||
const current = yield* Ref.get(registration);
|
||||
|
||||
if (Option.isNone(current)) {
|
||||
if (!isConnectionHello(message)) {
|
||||
yield* transport.close(4002, "First message must be connection.hello");
|
||||
return;
|
||||
}
|
||||
const registered = yield* broker
|
||||
.registerConnection(message, transport)
|
||||
.pipe(
|
||||
Effect.tapError((rejected) =>
|
||||
transport
|
||||
.send(rejected)
|
||||
.pipe(Effect.andThen(transport.close(4003, rejected.message))),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(registration, Option.some(registered));
|
||||
yield* transport.send(registered.accepted);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isConnectionHello(message)) {
|
||||
yield* transport.close(4002, "connection.hello may only be sent once");
|
||||
return;
|
||||
}
|
||||
yield* broker.receive(current.value, message);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Rejected Hermes gateway WebSocket frame", { cause }).pipe(
|
||||
Effect.andThen(transport.close(4002, "Invalid Hermes gateway message")),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logDebug("Hermes gateway WebSocket disconnected", { cause }),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Ref.get(registration).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.void,
|
||||
onSome: broker.disconnect,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return HttpServerResponse.empty();
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -21,6 +21,8 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
|
||||
import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
|
||||
import { HermesGatewayBrokerLive } from "./provider/Layers/HermesGatewayBroker.ts";
|
||||
import { hermesGatewayWebSocketRouteLayer } from "./provider/hermesGatewayHttp.ts";
|
||||
import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
|
||||
@@ -287,6 +289,10 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
);
|
||||
|
||||
const HermesProviderRuntimeLive = ProviderInstanceRegistryHydrationLive.pipe(
|
||||
Layer.provideMerge(HermesGatewayBrokerLive),
|
||||
);
|
||||
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
@@ -303,7 +309,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
|
||||
// `providerInstances` hydration merges `settings.providers.<kind>`
|
||||
// with explicit `providerInstances` entries on boot.
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(HermesProviderRuntimeLive),
|
||||
// Shared native/canonical NDJSON writers used by both the per-instance
|
||||
// drivers (native stream, written from inside each `<X>Adapter`) and
|
||||
// `ProviderService` (canonical stream, written after event normalization).
|
||||
@@ -362,6 +368,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
assetRouteLayer,
|
||||
staticAndDevRouteLayer,
|
||||
websocketRpcRouteLayer,
|
||||
hermesGatewayWebSocketRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(
|
||||
|
||||
@@ -78,6 +78,7 @@ import {
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import { HermesGatewayBroker } from "./provider/Services/HermesGatewayBroker.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
@@ -307,6 +308,10 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.hermesGatewayCreateEnrollment, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.hermesGatewayGetInstanceStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.hermesGatewayListInstances, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.hermesGatewayRevokeInstance, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope],
|
||||
[WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope],
|
||||
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
|
||||
@@ -420,6 +425,7 @@ const makeWsRpcLayer = (
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const hermesGatewayBroker = yield* HermesGatewayBroker;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
|
||||
@@ -1521,6 +1527,30 @@ const makeWsRpcLayer = (
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.hermesGatewayCreateEnrollment]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayCreateEnrollment,
|
||||
hermesGatewayBroker.createEnrollment(input),
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.hermesGatewayGetInstanceStatus]: ({ instanceId }) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayGetInstanceStatus,
|
||||
hermesGatewayBroker.getInstanceStatus(instanceId),
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.hermesGatewayListInstances]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayListInstances,
|
||||
hermesGatewayBroker.listInstances,
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.hermesGatewayRevokeInstance]: ({ instanceId }) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayRevokeInstance,
|
||||
hermesGatewayBroker.revokeInstance(instanceId),
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.serverDiscoverSourceControl]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverDiscoverSourceControl,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Icon } from "./Icons";
|
||||
|
||||
/**
|
||||
* Compact local mark for Hermes provider surfaces. The paired wings suggest
|
||||
* Hermes' caduceus without depending on a remote image asset.
|
||||
*/
|
||||
export const HermesIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="none">
|
||||
<path
|
||||
d="M12 3v18M8.5 6.5c-2.8-2.2-5-1.1-5.5-.7.8 2.8 2.6 4.2 5.5 4.2h7c2.9 0 4.7-1.4 5.5-4.2-.5-.4-2.7-1.5-5.5.7M8 14h8M9.5 18h5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.7"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<circle cx="12" cy="3" r="1.4" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
@@ -75,7 +75,10 @@ import { ProviderModelPicker } from "./ProviderModelPicker";
|
||||
import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu";
|
||||
import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
|
||||
import {
|
||||
ComposerPrimaryActions,
|
||||
shouldUseCollapsedHermesRunningActions,
|
||||
} from "./ComposerPrimaryActions";
|
||||
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
@@ -171,9 +174,10 @@ import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
NO_PROVIDER_MODEL_SELECTION,
|
||||
getProviderInstanceComposerUnavailableMessage,
|
||||
isProviderInstanceComposerAvailable,
|
||||
resolveComposerProviderInstanceId,
|
||||
resolveProviderDriverKindForInstanceSelection,
|
||||
resolveSelectableProviderInstanceEntry,
|
||||
sortProviderInstanceEntries,
|
||||
type ProviderInstanceEntry,
|
||||
} from "../../providerInstances";
|
||||
@@ -412,6 +416,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
isComplete: boolean;
|
||||
} | null;
|
||||
isRunning: boolean;
|
||||
allowSendWhileRunning: boolean;
|
||||
showPlanFollowUpPrompt: boolean;
|
||||
promptHasText: boolean;
|
||||
isSendBusy: boolean;
|
||||
@@ -438,6 +443,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
compact={props.compact}
|
||||
pendingAction={props.pendingAction}
|
||||
isRunning={props.isRunning}
|
||||
allowSendWhileRunning={props.allowSendWhileRunning}
|
||||
showPlanFollowUpPrompt={props.showPlanFollowUpPrompt}
|
||||
promptHasText={props.promptHasText}
|
||||
isSendBusy={props.isSendBusy}
|
||||
@@ -776,52 +782,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
// Resolve which configured instance the composer is currently targeting.
|
||||
// Priority:
|
||||
// 1. The composer draft's `activeProvider` — the user's unsaved pick
|
||||
// 1. A started Hermes thread's persisted instance binding. Hermes
|
||||
// sessions cannot be reassigned, including when that instance is
|
||||
// currently missing or disabled.
|
||||
// 2. The composer draft's `activeProvider` — the user's unsaved pick
|
||||
// from the model picker (must win, otherwise the UI appears to
|
||||
// ignore picker selections).
|
||||
// 2. Thread's persisted instance id (server-side saved selection).
|
||||
// 3. Project default's instance id.
|
||||
// 4. First enabled entry matching the current driver kind.
|
||||
// 5. First enabled entry overall / default instance for the kind.
|
||||
// 3. Thread's persisted instance id (server-side saved selection).
|
||||
// 4. Project default's instance id.
|
||||
// 5. First enabled entry matching the current driver kind.
|
||||
// 6. First enabled entry overall / default instance for the kind.
|
||||
//
|
||||
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
|
||||
const candidates: Array<string | null | undefined> = [
|
||||
composerDraft.activeProvider,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue;
|
||||
const match = providerInstanceEntries.find(
|
||||
(entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
|
||||
);
|
||||
if (match) {
|
||||
// When locked to a specific driver kind, ignore persisted instance
|
||||
// ids from a different kind or continuation group.
|
||||
if (lockedProvider && match.driverKind !== lockedProvider) continue;
|
||||
if (
|
||||
lockedContinuationGroupKey &&
|
||||
match.continuationGroupKey !== lockedContinuationGroupKey
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
return match.instanceId;
|
||||
}
|
||||
}
|
||||
const compatibleEntries = providerInstanceEntries.filter(
|
||||
(entry) =>
|
||||
(!lockedProvider || entry.driverKind === lockedProvider) &&
|
||||
(!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey),
|
||||
);
|
||||
const requestedDriverEntries = compatibleEntries.filter(
|
||||
(entry) => entry.driverKind === requestedDriverKind,
|
||||
);
|
||||
return (
|
||||
resolveSelectableProviderInstanceEntry(requestedDriverEntries, undefined)?.instanceId ??
|
||||
resolveSelectableProviderInstanceEntry(compatibleEntries, undefined)?.instanceId ??
|
||||
NO_PROVIDER_MODEL_SELECTION.instanceId
|
||||
);
|
||||
return resolveComposerProviderInstanceId({
|
||||
entries: providerInstanceEntries,
|
||||
draftInstanceId: composerDraft.activeProvider ?? null,
|
||||
threadInstanceId: activeThread?.session?.providerInstanceId,
|
||||
threadModelInstanceId: activeThreadModelSelection?.instanceId,
|
||||
projectInstanceId: activeProjectDefaultModelSelection?.instanceId,
|
||||
requestedDriverKind,
|
||||
lockedProvider,
|
||||
lockedContinuationGroupKey,
|
||||
});
|
||||
}, [
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
@@ -840,12 +822,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
() => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId),
|
||||
[providerInstanceEntries, selectedInstanceId],
|
||||
);
|
||||
const noProviderAvailable = selectedProviderEntry === undefined;
|
||||
const noProviderAvailable =
|
||||
selectedProviderEntry === undefined ||
|
||||
!isProviderInstanceComposerAvailable(selectedProviderEntry);
|
||||
const missingBoundHermesInstanceId =
|
||||
selectedProviderEntry === undefined && lockedProvider === "hermes"
|
||||
? (activeThread?.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId)
|
||||
: undefined;
|
||||
const providerUnavailableMessage = getProviderInstanceComposerUnavailableMessage(
|
||||
selectedProviderEntry,
|
||||
missingBoundHermesInstanceId
|
||||
? {
|
||||
driverKind: ProviderDriverKind.make("hermes"),
|
||||
instanceId: missingBoundHermesInstanceId,
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
// The driver kind follows the instance that will actually run the turn,
|
||||
// which can differ from the persisted selection when that selection is
|
||||
// disabled.
|
||||
const selectedProvider: ProviderDriverKind =
|
||||
selectedProviderEntry?.driverKind ?? requestedDriverKind;
|
||||
const allowHermesSteering = phase === "running" && selectedProvider === "hermes";
|
||||
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadRef: composerDraftTarget,
|
||||
@@ -1216,7 +1214,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
|
||||
);
|
||||
const collapsedComposerPrimaryActionDisabled =
|
||||
phase === "running" ||
|
||||
(phase === "running" && !allowHermesSteering) ||
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
noProviderAvailable ||
|
||||
@@ -1765,7 +1763,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isConnecting ||
|
||||
noProviderAvailable ||
|
||||
environmentUnavailable !== null ||
|
||||
phase === "running"
|
||||
(phase === "running" && !allowHermesSteering)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -1783,6 +1781,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isSendBusy,
|
||||
noProviderAvailable,
|
||||
phase,
|
||||
allowHermesSteering,
|
||||
showPlanFollowUpPrompt,
|
||||
]);
|
||||
|
||||
@@ -2368,29 +2367,56 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? activePendingProgress.customAnswer ||
|
||||
"Type your own answer, or leave this blank to use the selected option"
|
||||
: prompt.trim() ||
|
||||
(noProviderAvailable ? "Enable a provider in Settings" : "Ask anything...")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
|
||||
disabled={collapsedComposerPrimaryActionDisabled}
|
||||
aria-label={collapsedComposerPrimaryActionLabel}
|
||||
onPointerDown={(event) => event.preventDefault()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
submitComposer();
|
||||
}}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M8 3L8 13M8 3L4 7M8 3L12 7"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
(noProviderAvailable ? providerUnavailableMessage : "Ask anything...")}
|
||||
</button>
|
||||
{shouldUseCollapsedHermesRunningActions({
|
||||
isRunning: phase === "running",
|
||||
allowSendWhileRunning: allowHermesSteering,
|
||||
}) ? (
|
||||
<ComposerPrimaryActions
|
||||
compact
|
||||
pendingAction={null}
|
||||
isRunning
|
||||
allowSendWhileRunning
|
||||
showPlanFollowUpPrompt={false}
|
||||
promptHasText={prompt.trim().length > 0}
|
||||
isSendBusy={isSendBusy}
|
||||
isConnecting={isConnecting}
|
||||
isEnvironmentUnavailable={
|
||||
environmentUnavailable !== null ||
|
||||
noProviderAvailable ||
|
||||
projectSelectionRequired
|
||||
}
|
||||
isPreparingWorktree={false}
|
||||
hasSendableContent={composerSendState.hasSendableContent}
|
||||
preserveComposerFocusOnPointerDown
|
||||
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
|
||||
onInterrupt={handleInterruptPrimaryAction}
|
||||
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
|
||||
disabled={collapsedComposerPrimaryActionDisabled}
|
||||
aria-label={collapsedComposerPrimaryActionLabel}
|
||||
onPointerDown={(event) => event.preventDefault()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
submitComposer();
|
||||
}}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M8 3L8 13M8 3L4 7M8 3L12 7"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -2575,7 +2601,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
: projectSelectionRequired
|
||||
? "Choose a project above to start a thread"
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
? providerUnavailableMessage
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
@@ -2643,7 +2669,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
className="shrink-0 gap-2 px-2 text-muted-foreground/70 sm:px-3"
|
||||
>
|
||||
<CircleAlertIcon className="size-4" />
|
||||
No provider available
|
||||
{providerUnavailableMessage}
|
||||
</Button>
|
||||
) : (
|
||||
<ProviderModelPicker
|
||||
@@ -2721,6 +2747,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
activeThreadProviderDisplayName={activeThreadProviderDisplayName}
|
||||
pendingAction={pendingPrimaryAction}
|
||||
isRunning={phase === "running"}
|
||||
allowSendWhileRunning={allowHermesSteering}
|
||||
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
|
||||
promptHasText={prompt.trim().length > 0}
|
||||
isSendBusy={isSendBusy}
|
||||
|
||||
@@ -1,6 +1,45 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
|
||||
import {
|
||||
formatPendingPrimaryActionLabel,
|
||||
resolveRunningPrimaryActionMode,
|
||||
shouldUseCollapsedHermesRunningActions,
|
||||
} from "./ComposerPrimaryActions";
|
||||
|
||||
describe("resolveRunningPrimaryActionMode", () => {
|
||||
it("keeps stop-only behavior for ordinary running providers", () => {
|
||||
expect(resolveRunningPrimaryActionMode({ isRunning: true, allowSendWhileRunning: false })).toBe(
|
||||
"stop",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows steer and stop actions for a running Hermes provider", () => {
|
||||
expect(resolveRunningPrimaryActionMode({ isRunning: true, allowSendWhileRunning: true })).toBe(
|
||||
"steer",
|
||||
);
|
||||
expect(
|
||||
shouldUseCollapsedHermesRunningActions({
|
||||
isRunning: true,
|
||||
allowSendWhileRunning: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not replace collapsed actions for idle or ordinary providers", () => {
|
||||
expect(
|
||||
shouldUseCollapsedHermesRunningActions({
|
||||
isRunning: false,
|
||||
allowSendWhileRunning: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldUseCollapsedHermesRunningActions({
|
||||
isRunning: true,
|
||||
allowSendWhileRunning: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatPendingPrimaryActionLabel", () => {
|
||||
it("returns 'Submitting...' while responding", () => {
|
||||
|
||||
@@ -18,6 +18,7 @@ interface ComposerPrimaryActionsProps {
|
||||
compact: boolean;
|
||||
pendingAction: PendingActionState | null;
|
||||
isRunning: boolean;
|
||||
allowSendWhileRunning?: boolean;
|
||||
showPlanFollowUpPrompt: boolean;
|
||||
promptHasText: boolean;
|
||||
isSendBusy: boolean;
|
||||
@@ -49,6 +50,21 @@ export const formatPendingPrimaryActionLabel = (input: {
|
||||
return input.questionIndex > 0 ? "Submit answers" : "Submit answer";
|
||||
};
|
||||
|
||||
export function resolveRunningPrimaryActionMode(input: {
|
||||
readonly isRunning: boolean;
|
||||
readonly allowSendWhileRunning: boolean;
|
||||
}): "idle" | "stop" | "steer" {
|
||||
if (!input.isRunning) return "idle";
|
||||
return input.allowSendWhileRunning ? "steer" : "stop";
|
||||
}
|
||||
|
||||
export function shouldUseCollapsedHermesRunningActions(input: {
|
||||
readonly isRunning: boolean;
|
||||
readonly allowSendWhileRunning: boolean;
|
||||
}): boolean {
|
||||
return resolveRunningPrimaryActionMode(input) === "steer";
|
||||
}
|
||||
|
||||
const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
|
||||
event.preventDefault();
|
||||
};
|
||||
@@ -57,6 +73,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
compact,
|
||||
pendingAction,
|
||||
isRunning,
|
||||
allowSendWhileRunning = false,
|
||||
showPlanFollowUpPrompt,
|
||||
promptHasText,
|
||||
isSendBusy,
|
||||
@@ -125,7 +142,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
);
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
const runningMode = resolveRunningPrimaryActionMode({ isRunning, allowSendWhileRunning });
|
||||
if (runningMode === "stop") {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -141,6 +159,41 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
);
|
||||
}
|
||||
|
||||
if (runningMode === "steer") {
|
||||
return (
|
||||
<div className={cn("flex items-center justify-end", compact ? "gap-1" : "gap-2")}>
|
||||
<button
|
||||
type="submit"
|
||||
className="flex size-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground shadow-xs transition-all enabled:cursor-pointer hover:bg-primary disabled:pointer-events-none disabled:opacity-30"
|
||||
{...pointerFocusProps}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
|
||||
aria-label="Send guidance to running Hermes turn"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 transition-all hover:bg-destructive"
|
||||
{...pointerFocusProps}
|
||||
onClick={onInterrupt}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
|
||||
<rect x="2" y="2" width="8" height="8" rx="1.5" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (showPlanFollowUpPrompt) {
|
||||
if (promptHasText) {
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { ClaudeAI, CursorIcon, GrokIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { PROVIDER_OPTIONS } from "../../session-logic";
|
||||
import { HermesIcon } from "../HermesIcon";
|
||||
|
||||
export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {
|
||||
[ProviderDriverKind.make("codex")]: OpenAI,
|
||||
@@ -8,6 +9,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
|
||||
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
|
||||
[ProviderDriverKind.make("cursor")]: CursorIcon,
|
||||
[ProviderDriverKind.make("grok")]: GrokIcon,
|
||||
[ProviderDriverKind.make("hermes")]: HermesIcon,
|
||||
};
|
||||
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
|
||||
@@ -1,11 +1,50 @@
|
||||
import type { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
export type WizardNavigation =
|
||||
| { readonly kind: "navigate"; readonly step: number }
|
||||
| { readonly kind: "blocked"; readonly step: number; readonly error: string };
|
||||
|
||||
const IDENTITY_STEP = 1;
|
||||
const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
|
||||
|
||||
export const ADD_PROVIDER_WIZARD_STEPS = ["Driver", "Identity", "Config"] as const;
|
||||
|
||||
export function isOwnedHermesEnrollmentRetry(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly instanceId: string;
|
||||
readonly createdHermesInstanceId: string | null;
|
||||
}): boolean {
|
||||
return (
|
||||
input.driver === "hermes" &&
|
||||
input.createdHermesInstanceId !== null &&
|
||||
input.createdHermesInstanceId === input.instanceId
|
||||
);
|
||||
}
|
||||
|
||||
export function validateProviderInstanceIdForWizard(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly instanceId: string;
|
||||
readonly existingIds: ReadonlySet<string>;
|
||||
readonly createdHermesInstanceId: string | null;
|
||||
}): string | null {
|
||||
if (input.instanceId.length === 0) return "Instance ID is required.";
|
||||
if (input.instanceId.length > 64) return "Instance ID must be 64 characters or fewer.";
|
||||
if (!INSTANCE_ID_PATTERN.test(input.instanceId)) {
|
||||
return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
|
||||
}
|
||||
if (
|
||||
input.existingIds.has(input.instanceId) &&
|
||||
!isOwnedHermesEnrollmentRetry({
|
||||
driver: input.driver,
|
||||
instanceId: input.instanceId,
|
||||
createdHermesInstanceId: input.createdHermesInstanceId,
|
||||
})
|
||||
) {
|
||||
return `An instance named '${input.instanceId}' already exists.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve navigation within the add-provider wizard.
|
||||
*
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveWizardNavigation } from "./AddProviderInstanceDialog.logic";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
isOwnedHermesEnrollmentRetry,
|
||||
resolveWizardNavigation,
|
||||
validateProviderInstanceIdForWizard,
|
||||
} from "./AddProviderInstanceDialog.logic";
|
||||
|
||||
describe("resolveWizardNavigation", () => {
|
||||
const invalidId = { instanceIdError: "Instance ID is required." };
|
||||
@@ -42,3 +48,52 @@ describe("resolveWizardNavigation", () => {
|
||||
expect(resolveWizardNavigation(0, -1, 3, invalidId)).toEqual({ kind: "navigate", step: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes enrollment retry ownership", () => {
|
||||
const existingIds = new Set(["hermes-research", "hermes-existing"]);
|
||||
|
||||
it("allows retrying enrollment for the exact Hermes instance created by this wizard", () => {
|
||||
expect(
|
||||
isOwnedHermesEnrollmentRetry({
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-research",
|
||||
createdHermesInstanceId: "hermes-research",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
validateProviderInstanceIdForWizard({
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-research",
|
||||
existingIds,
|
||||
createdHermesInstanceId: "hermes-research",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("still rejects arbitrary existing instances and non-Hermes reuse", () => {
|
||||
expect(
|
||||
validateProviderInstanceIdForWizard({
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-existing",
|
||||
existingIds,
|
||||
createdHermesInstanceId: "hermes-research",
|
||||
}),
|
||||
).toContain("already exists");
|
||||
expect(
|
||||
validateProviderInstanceIdForWizard({
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
instanceId: "hermes-research",
|
||||
existingIds,
|
||||
createdHermesInstanceId: "hermes-research",
|
||||
}),
|
||||
).toContain("already exists");
|
||||
expect(
|
||||
validateProviderInstanceIdForWizard({
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-research",
|
||||
existingIds,
|
||||
createdHermesInstanceId: null,
|
||||
}),
|
||||
).toContain("already exists");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { CheckIcon, CopyIcon, LoaderIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
type HermesGatewayEnrollmentResult,
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { normalizeProviderAccentColor } from "../../providerInstances";
|
||||
@@ -31,10 +34,20 @@ import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSe
|
||||
import { AnimatedHeight } from "../AnimatedHeight";
|
||||
import {
|
||||
ADD_PROVIDER_WIZARD_STEPS,
|
||||
isOwnedHermesEnrollmentRetry,
|
||||
resolveWizardNavigation,
|
||||
type WizardNavigation,
|
||||
validateProviderInstanceIdForWizard,
|
||||
} from "./AddProviderInstanceDialog.logic";
|
||||
import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
messageFromUnknownError,
|
||||
} from "./HermesGatewayInstanceSection.logic";
|
||||
|
||||
const PROVIDER_ACCENT_SWATCHES = [
|
||||
"#2563eb",
|
||||
@@ -63,10 +76,12 @@ function slugifyLabel(value: string): string {
|
||||
|
||||
function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
|
||||
const slug = slugifyLabel(label);
|
||||
if (driver === "hermes") {
|
||||
return slug ? `hermes-${slug.replaceAll("_", "-")}` : "";
|
||||
}
|
||||
return slug ? `${driver}_${slug}` : "";
|
||||
}
|
||||
|
||||
const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
|
||||
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
|
||||
const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
|
||||
@@ -99,21 +114,6 @@ const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Validate an instance id against the same slug rules the server applies in
|
||||
* `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
|
||||
* Returns a user-facing error string, or `null` if valid.
|
||||
*/
|
||||
function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
|
||||
if (id.length === 0) return "Instance ID is required.";
|
||||
if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
|
||||
if (!INSTANCE_ID_PATTERN.test(id)) {
|
||||
return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
|
||||
}
|
||||
if (existing.has(id)) return `An instance named '${id}' already exists.`;
|
||||
return null;
|
||||
}
|
||||
|
||||
interface AddProviderInstanceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -122,6 +122,13 @@ interface AddProviderInstanceDialogProps {
|
||||
export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
|
||||
const updateServerSettings = useAtomCommand(serverEnvironment.updateSettings, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const createHermesEnrollment = useAtomCommand(serverEnvironment.hermesGatewayCreateEnrollment, {
|
||||
reportFailure: false,
|
||||
});
|
||||
|
||||
const [wizardStep, setWizardStep] = useState(0);
|
||||
const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
|
||||
@@ -134,6 +141,37 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
// Errors are suppressed until the user has tried to submit once. After that
|
||||
// they update live so fixing the problem clears the message in place.
|
||||
const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
|
||||
const [hermesConnectorUrl, setHermesConnectorUrl] = useState(() =>
|
||||
typeof window === "undefined"
|
||||
? "http://localhost/api/hermes-gateway/ws"
|
||||
: defaultHermesConnectorUrl(window.location.origin),
|
||||
);
|
||||
const [hermesEnrollment, setHermesEnrollment] = useState<HermesGatewayEnrollmentResult | null>(
|
||||
null,
|
||||
);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [createdHermesIdentity, setCreatedHermesIdentity] = useState<{
|
||||
readonly instanceId: string;
|
||||
readonly nickname: string;
|
||||
} | null>(null);
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard({
|
||||
target: "Hermes enrollment command",
|
||||
onCopy: () =>
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Hermes command copied",
|
||||
description: "Run it in the terminal where Hermes is installed.",
|
||||
}),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) return;
|
||||
setHermesEnrollment(null);
|
||||
setSaveError(null);
|
||||
setIsSaving(false);
|
||||
setCreatedHermesIdentity(null);
|
||||
}, [open]);
|
||||
|
||||
const existingIds = useMemo(
|
||||
() => new Set(Object.keys(settings.providerInstances ?? {})),
|
||||
@@ -146,7 +184,15 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
() => deriveProviderSettingsFields(driverOption),
|
||||
[driverOption],
|
||||
);
|
||||
const instanceIdError = validateInstanceId(instanceId, existingIds);
|
||||
const instanceIdError =
|
||||
driver === "hermes" && label.trim().length === 0
|
||||
? "Hermes nickname is required."
|
||||
: validateProviderInstanceIdForWizard({
|
||||
driver,
|
||||
instanceId,
|
||||
existingIds,
|
||||
createdHermesInstanceId: createdHermesIdentity?.instanceId ?? null,
|
||||
});
|
||||
const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
|
||||
const previewLabel = label.trim() || `${driverOption.label} Workspace`;
|
||||
const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
|
||||
@@ -179,7 +225,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
const handleSave = async () => {
|
||||
setHasAttemptedSubmit(true);
|
||||
if (instanceIdError !== null) return;
|
||||
|
||||
@@ -195,15 +241,60 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
...(hasConfig ? { config } : {}),
|
||||
};
|
||||
// `ProviderInstanceId.make` revalidates the slug; we've already checked
|
||||
// it via `validateInstanceId`, but going through the brand constructor
|
||||
// it via `validateProviderInstanceIdForWizard`, but going through the brand constructor
|
||||
// keeps the type boundary honest and guards against any future drift in
|
||||
// the slug rules.
|
||||
const brandedId = ProviderInstanceId.make(instanceId);
|
||||
const isOwnedHermesRetry = isOwnedHermesEnrollmentRetry({
|
||||
driver,
|
||||
instanceId,
|
||||
createdHermesInstanceId: createdHermesIdentity?.instanceId ?? null,
|
||||
});
|
||||
const nextMap = {
|
||||
...settings.providerInstances,
|
||||
[brandedId]: nextInstance,
|
||||
};
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setSaveError(null);
|
||||
if (driver === "hermes") {
|
||||
if (environmentId === null) {
|
||||
throw new Error("Connect this browser to a T3 server before pairing Hermes.");
|
||||
}
|
||||
if (!isOwnedHermesRetry) {
|
||||
const settingsResult = await updateServerSettings({
|
||||
environmentId,
|
||||
input: { patch: { providerInstances: nextMap } },
|
||||
});
|
||||
if (settingsResult._tag === "Failure") {
|
||||
throw squashAtomCommandFailure(settingsResult);
|
||||
}
|
||||
setCreatedHermesIdentity({
|
||||
instanceId,
|
||||
nickname: label.trim(),
|
||||
});
|
||||
}
|
||||
const enrollmentResult = await createHermesEnrollment({
|
||||
environmentId,
|
||||
input: {
|
||||
instanceId: brandedId,
|
||||
nickname: createdHermesIdentity?.nickname ?? label.trim(),
|
||||
connectorUrl: hermesConnectorUrl,
|
||||
},
|
||||
});
|
||||
if (enrollmentResult._tag === "Failure") {
|
||||
throw squashAtomCommandFailure(enrollmentResult);
|
||||
}
|
||||
setHermesEnrollment(enrollmentResult.value);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Hermes instance added",
|
||||
description: "Run the one-time command to connect it.",
|
||||
});
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
updateSettings({ providerInstances: nextMap });
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -212,11 +303,15 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
});
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
const message = messageFromUnknownError(error);
|
||||
setSaveError(message);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not add provider instance",
|
||||
description: error instanceof Error ? error.message : "Update failed.",
|
||||
description: message,
|
||||
});
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -230,203 +325,280 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
Configure an additional provider instance — for example, a second Codex install
|
||||
pointed at a different workspace.
|
||||
</DialogDescription>
|
||||
<AddProviderInstanceWizardSteps
|
||||
currentStep={wizardStep}
|
||||
summaries={wizardStepSummaries}
|
||||
instanceIdError={instanceIdError}
|
||||
onNavigation={applyWizardNavigation}
|
||||
/>
|
||||
{hermesEnrollment === null && createdHermesIdentity === null ? (
|
||||
<AddProviderInstanceWizardSteps
|
||||
currentStep={wizardStep}
|
||||
summaries={wizardStepSummaries}
|
||||
instanceIdError={instanceIdError}
|
||||
onNavigation={applyWizardNavigation}
|
||||
/>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
|
||||
<div
|
||||
data-slot="dialog-panel"
|
||||
className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"
|
||||
>
|
||||
<AnimatedHeight>
|
||||
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
|
||||
<div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
|
||||
Driver
|
||||
</div>
|
||||
<RadioGroup
|
||||
value={driver}
|
||||
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
|
||||
aria-labelledby="add-instance-driver-label"
|
||||
className="grid grid-cols-1 gap-2 sm:grid-cols-2"
|
||||
>
|
||||
{DRIVER_OPTIONS.map((option) => {
|
||||
const IconComponent = option.icon;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"
|
||||
>
|
||||
<IconComponent className="size-4 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<RadioPrimitive.Indicator
|
||||
className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
|
||||
aria-hidden
|
||||
>
|
||||
<CheckIcon className="size-3.5 shrink-0" />
|
||||
</RadioPrimitive.Indicator>
|
||||
{option.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm">
|
||||
{option.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
|
||||
const IconComponent = option.icon;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled
|
||||
className={cn(
|
||||
"relative flex cursor-not-allowed items-center gap-3 rounded-lg bg-card/60 px-3 py-3 text-left opacity-55 outline-none ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",
|
||||
)}
|
||||
>
|
||||
<IconComponent
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<Badge variant="warning" size="sm">
|
||||
Coming Soon
|
||||
</Badge>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Label</span>
|
||||
<Input
|
||||
className="bg-background"
|
||||
placeholder="e.g. Work"
|
||||
value={label}
|
||||
onChange={(event) => setLabel(event.target.value)}
|
||||
/>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Shown in the provider list. Optional.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Instance ID</span>
|
||||
<Input
|
||||
className="bg-background"
|
||||
placeholder={`${driver}_work`}
|
||||
value={instanceId}
|
||||
onChange={(event) => {
|
||||
setInstanceIdOverride(event.target.value);
|
||||
}}
|
||||
aria-invalid={showInstanceIdError}
|
||||
/>
|
||||
{showInstanceIdError ? (
|
||||
<span className="text-[11px] text-destructive">{instanceIdError}</span>
|
||||
) : (
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Accent color</span>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
|
||||
onChange={(event) => setAccentColor(event.target.value)}
|
||||
aria-label="Provider instance accent color"
|
||||
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
|
||||
const selected = accentColor.toLowerCase() === swatch;
|
||||
return (
|
||||
<button
|
||||
key={swatch}
|
||||
type="button"
|
||||
className={cn(
|
||||
"size-6 cursor-pointer rounded-full border transition",
|
||||
selected
|
||||
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
|
||||
: "border-black/10 hover:scale-105 dark:border-white/20",
|
||||
)}
|
||||
style={{ backgroundColor: swatch }}
|
||||
onClick={() => setAccentColor(swatch)}
|
||||
aria-label={`Use ${swatch} accent`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{accentColor ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-xs text-muted-foreground"
|
||||
onClick={() => setAccentColor("")}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Optional marker shown in the picker.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{driverSettingsFields.length > 0 ? (
|
||||
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
|
||||
<ProviderSettingsForm
|
||||
definition={driverOption}
|
||||
value={configDraft}
|
||||
idPrefix={`add-provider-${driver}`}
|
||||
variant="dialog"
|
||||
onChange={setConfigDraft}
|
||||
/>
|
||||
</div>
|
||||
) : wizardStep === 2 ? (
|
||||
<div className="grid gap-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This driver has no required configuration. You can add the instance now.
|
||||
{hermesEnrollment ? (
|
||||
<div className="grid gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">Connect Hermes</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This one-time command expires{" "}
|
||||
{formatHermesLastConnected(hermesEnrollment.expiresAt)}.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</AnimatedHeight>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded bg-muted px-2 py-2 text-[11px]">
|
||||
{hermesEnrollment.command}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
onClick={() => copyToClipboard(hermesEnrollment.command, undefined)}
|
||||
aria-label="Copy Hermes enrollment command"
|
||||
>
|
||||
{isCopied ? <CheckIcon /> : <CopyIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
The persistent gateway credential is delivered directly to the plugin and is never
|
||||
shown in T3 Code.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<AnimatedHeight>
|
||||
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
|
||||
<div
|
||||
id="add-instance-driver-label"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Driver
|
||||
</div>
|
||||
<RadioGroup
|
||||
value={driver}
|
||||
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
|
||||
aria-labelledby="add-instance-driver-label"
|
||||
className="grid grid-cols-1 gap-2 sm:grid-cols-2"
|
||||
>
|
||||
{DRIVER_OPTIONS.map((option) => {
|
||||
const IconComponent = option.icon;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"
|
||||
>
|
||||
<IconComponent className="size-4 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<RadioPrimitive.Indicator
|
||||
className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
|
||||
aria-hidden
|
||||
>
|
||||
<CheckIcon className="size-3.5 shrink-0" />
|
||||
</RadioPrimitive.Indicator>
|
||||
{option.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm">
|
||||
{option.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
|
||||
const IconComponent = option.icon;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled
|
||||
className={cn(
|
||||
"relative flex cursor-not-allowed items-center gap-3 rounded-lg bg-card/60 px-3 py-3 text-left opacity-55 outline-none ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",
|
||||
)}
|
||||
>
|
||||
<IconComponent
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<Badge variant="warning" size="sm">
|
||||
Coming Soon
|
||||
</Badge>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Label</span>
|
||||
<Input
|
||||
className="bg-background"
|
||||
placeholder="e.g. Work"
|
||||
value={label}
|
||||
onChange={(event) => setLabel(event.target.value)}
|
||||
/>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Shown in the provider list. Optional.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Instance ID</span>
|
||||
<Input
|
||||
className="bg-background"
|
||||
placeholder={`${driver}_work`}
|
||||
value={instanceId}
|
||||
onChange={(event) => {
|
||||
setInstanceIdOverride(event.target.value);
|
||||
}}
|
||||
aria-invalid={showInstanceIdError}
|
||||
/>
|
||||
{showInstanceIdError ? (
|
||||
<span className="text-[11px] text-destructive">{instanceIdError}</span>
|
||||
) : (
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
|
||||
<span className="text-xs font-medium text-foreground">Accent color</span>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={
|
||||
normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]
|
||||
}
|
||||
onChange={(event) => setAccentColor(event.target.value)}
|
||||
aria-label="Provider instance accent color"
|
||||
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
|
||||
const selected = accentColor.toLowerCase() === swatch;
|
||||
return (
|
||||
<button
|
||||
key={swatch}
|
||||
type="button"
|
||||
className={cn(
|
||||
"size-6 cursor-pointer rounded-full border transition",
|
||||
selected
|
||||
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
|
||||
: "border-black/10 hover:scale-105 dark:border-white/20",
|
||||
)}
|
||||
style={{ backgroundColor: swatch }}
|
||||
onClick={() => setAccentColor(swatch)}
|
||||
aria-label={`Use ${swatch} accent`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{accentColor ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-xs text-muted-foreground"
|
||||
onClick={() => setAccentColor("")}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Optional marker shown in the picker.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{driver === "hermes" && wizardStep === 2 ? (
|
||||
<label className="grid gap-2">
|
||||
<span className="text-xs font-medium text-foreground">Connector URL</span>
|
||||
<Input
|
||||
className="bg-background"
|
||||
value={hermesConnectorUrl}
|
||||
onChange={(event) => setHermesConnectorUrl(event.target.value)}
|
||||
placeholder="wss://t3.example.com/api/hermes-gateway/ws"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Defaults to this browser's origin and works over Tailscale or any
|
||||
reachable network.
|
||||
</span>
|
||||
</label>
|
||||
) : driverSettingsFields.length > 0 ? (
|
||||
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
|
||||
<ProviderSettingsForm
|
||||
definition={driverOption}
|
||||
value={configDraft}
|
||||
idPrefix={`add-provider-${driver}`}
|
||||
variant="dialog"
|
||||
onChange={setConfigDraft}
|
||||
/>
|
||||
</div>
|
||||
) : wizardStep === 2 ? (
|
||||
<div className="grid gap-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This driver has no required configuration. You can add the instance now.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
{saveError ? <p className="text-xs text-destructive">{saveError}</p> : null}
|
||||
{createdHermesIdentity ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The Hermes instance was added. Retry enrollment for this exact instance, or
|
||||
close this dialog and finish pairing from its Settings card.
|
||||
</p>
|
||||
) : null}
|
||||
</AnimatedHeight>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter variant="bare">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (wizardStep === 0) {
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
setWizardStep((step) => Math.max(0, step - 1));
|
||||
}}
|
||||
>
|
||||
{wizardStep === 0 ? "Cancel" : "Back"}
|
||||
</Button>
|
||||
{wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
|
||||
{hermesEnrollment ? (
|
||||
<Button size="sm" onClick={() => onOpenChange(false)}>
|
||||
Done
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (createdHermesIdentity) {
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
if (wizardStep === 0) {
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
setWizardStep((step) => Math.max(0, step - 1));
|
||||
}}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{createdHermesIdentity ? "Close" : wizardStep === 0 ? "Cancel" : "Back"}
|
||||
</Button>
|
||||
)}
|
||||
{hermesEnrollment ? null : wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
|
||||
<Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
|
||||
Next
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="sm" onClick={handleSave}>
|
||||
Add instance
|
||||
<Button size="sm" disabled={isSaving} onClick={() => void handleSave()}>
|
||||
{isSaving ? <LoaderIcon className="animate-spin" /> : null}
|
||||
{isSaving
|
||||
? createdHermesIdentity
|
||||
? "Retrying"
|
||||
: "Adding"
|
||||
: createdHermesIdentity
|
||||
? "Retry enrollment"
|
||||
: "Add instance"}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
hermesGatewayStatusLabel,
|
||||
messageFromUnknownError,
|
||||
shouldApplyHermesConnectorStatusUrl,
|
||||
} from "./HermesGatewayInstanceSection.logic";
|
||||
|
||||
describe("Hermes gateway settings logic", () => {
|
||||
it("uses the current origin with the gateway WebSocket route", () => {
|
||||
expect(defaultHermesConnectorUrl("https://siva.davis7.space:3774/settings")).toBe(
|
||||
"https://siva.davis7.space:3774/api/hermes-gateway/ws",
|
||||
);
|
||||
});
|
||||
|
||||
it("provides useful labels for every connection state", () => {
|
||||
expect(
|
||||
["offline", "connecting", "connected", "upgrade-required", "revoked"].map((status) =>
|
||||
hermesGatewayStatusLabel(status as never),
|
||||
),
|
||||
).toEqual(["Offline", "Connecting", "Connected", "Upgrade required", "Revoked"]);
|
||||
});
|
||||
|
||||
it("keeps invalid server timestamps readable and extracts structured messages", () => {
|
||||
expect(formatHermesLastConnected(null)).toBe("Never");
|
||||
expect(formatHermesLastConnected("not-a-date")).toBe("not-a-date");
|
||||
expect(messageFromUnknownError({ message: "Nickname is already used." })).toBe(
|
||||
"Nickname is already used.",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not replace an in-progress connector URL edit during status polling", () => {
|
||||
expect(shouldApplyHermesConnectorStatusUrl(false)).toBe(true);
|
||||
expect(shouldApplyHermesConnectorStatusUrl(true)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { HermesGatewayConnectionState } from "@t3tools/contracts";
|
||||
|
||||
export const HERMES_GATEWAY_SOCKET_PATH = "/api/hermes-gateway/ws";
|
||||
|
||||
export function defaultHermesConnectorUrl(origin: string): string {
|
||||
return new URL(HERMES_GATEWAY_SOCKET_PATH, origin).toString();
|
||||
}
|
||||
|
||||
export function shouldApplyHermesConnectorStatusUrl(hasLocalEdits: boolean): boolean {
|
||||
return !hasLocalEdits;
|
||||
}
|
||||
|
||||
export function hermesGatewayStatusLabel(status: HermesGatewayConnectionState): string {
|
||||
switch (status) {
|
||||
case "connected":
|
||||
return "Connected";
|
||||
case "connecting":
|
||||
return "Connecting";
|
||||
case "upgrade-required":
|
||||
return "Upgrade required";
|
||||
case "revoked":
|
||||
return "Revoked";
|
||||
case "offline":
|
||||
return "Offline";
|
||||
}
|
||||
}
|
||||
|
||||
export function formatHermesLastConnected(value: string | null): string {
|
||||
if (value === null) return "Never";
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
|
||||
}
|
||||
|
||||
export function messageFromUnknownError(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"message" in error &&
|
||||
typeof error.message === "string" &&
|
||||
error.message.trim()
|
||||
) {
|
||||
return error.message;
|
||||
}
|
||||
return "The Hermes gateway request failed.";
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
"use client";
|
||||
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
type HermesGatewayConnectionState,
|
||||
type HermesGatewayEnrollmentResult,
|
||||
type HermesGatewayInstanceStatus,
|
||||
type ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CheckIcon, CopyIcon, LoaderIcon, RefreshCwIcon, UnplugIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import {
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
hermesGatewayStatusLabel,
|
||||
messageFromUnknownError,
|
||||
shouldApplyHermesConnectorStatusUrl,
|
||||
} from "./HermesGatewayInstanceSection.logic";
|
||||
|
||||
const badgeVariantByStatus: Record<
|
||||
HermesGatewayConnectionState,
|
||||
"success" | "warning" | "error" | "secondary"
|
||||
> = {
|
||||
connected: "success",
|
||||
connecting: "warning",
|
||||
offline: "secondary",
|
||||
"upgrade-required": "warning",
|
||||
revoked: "error",
|
||||
};
|
||||
|
||||
function browserDefaultConnectorUrl() {
|
||||
if (typeof window === "undefined") return "http://localhost/api/hermes-gateway/ws";
|
||||
return defaultHermesConnectorUrl(window.location.origin);
|
||||
}
|
||||
|
||||
export function HermesGatewayInstanceSection(props: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly nickname: string;
|
||||
}) {
|
||||
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
|
||||
const getStatus = useAtomCommand(serverEnvironment.hermesGatewayGetInstanceStatus, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const createEnrollment = useAtomCommand(serverEnvironment.hermesGatewayCreateEnrollment, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const revokeInstance = useAtomCommand(serverEnvironment.hermesGatewayRevokeInstance, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [connectorUrl, setConnectorUrl] = useState(browserDefaultConnectorUrl);
|
||||
const [status, setStatus] = useState<HermesGatewayInstanceStatus | null>(null);
|
||||
const [enrollment, setEnrollment] = useState<HermesGatewayEnrollmentResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pendingAction, setPendingAction] = useState<"status" | "enroll" | "revoke" | null>(null);
|
||||
const connectorUrlHasLocalEditsRef = useRef(false);
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard({
|
||||
target: "Hermes enrollment command",
|
||||
onCopy: () => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Hermes command copied",
|
||||
description: "Run it in the terminal where Hermes is installed.",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const refreshStatus = useCallback(
|
||||
async (quiet = false) => {
|
||||
if (environmentId === null) return;
|
||||
if (!quiet) setPendingAction("status");
|
||||
const result = await getStatus({
|
||||
environmentId,
|
||||
input: { instanceId: props.instanceId },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
setStatus(result.value);
|
||||
if (shouldApplyHermesConnectorStatusUrl(connectorUrlHasLocalEditsRef.current)) {
|
||||
setConnectorUrl(result.value.connectorUrl);
|
||||
}
|
||||
setError(null);
|
||||
} else if (!quiet) {
|
||||
setError(messageFromUnknownError(squashAtomCommandFailure(result)));
|
||||
}
|
||||
if (!quiet) setPendingAction(null);
|
||||
},
|
||||
[environmentId, getStatus, props.instanceId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshStatus();
|
||||
const interval = window.setInterval(() => void refreshStatus(true), 5_000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [refreshStatus]);
|
||||
|
||||
const handleCreateEnrollment = async () => {
|
||||
if (environmentId === null) {
|
||||
setError("Connect this browser to a T3 server before pairing Hermes.");
|
||||
return;
|
||||
}
|
||||
setPendingAction("enroll");
|
||||
setError(null);
|
||||
const result = await createEnrollment({
|
||||
environmentId,
|
||||
input: {
|
||||
instanceId: props.instanceId,
|
||||
nickname: props.nickname,
|
||||
connectorUrl,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
connectorUrlHasLocalEditsRef.current = false;
|
||||
setConnectorUrl(result.value.connectorUrl);
|
||||
setEnrollment(result.value);
|
||||
setStatus((current) =>
|
||||
current
|
||||
? { ...current, connectorUrl: result.value.connectorUrl, status: "offline" }
|
||||
: current,
|
||||
);
|
||||
} else {
|
||||
setError(messageFromUnknownError(squashAtomCommandFailure(result)));
|
||||
}
|
||||
setPendingAction(null);
|
||||
};
|
||||
|
||||
const handleRevoke = async () => {
|
||||
if (environmentId === null) return;
|
||||
setPendingAction("revoke");
|
||||
setError(null);
|
||||
const result = await revokeInstance({
|
||||
environmentId,
|
||||
input: { instanceId: props.instanceId },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
setStatus(result.value);
|
||||
setEnrollment(null);
|
||||
} else {
|
||||
setError(messageFromUnknownError(squashAtomCommandFailure(result)));
|
||||
}
|
||||
setPendingAction(null);
|
||||
};
|
||||
|
||||
const connectionState = status?.status ?? "offline";
|
||||
const isBusy = pendingAction !== null;
|
||||
|
||||
return (
|
||||
<section className="grid gap-4 rounded-lg border border-border/70 bg-muted/15 p-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-foreground">Hermes gateway</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pair an already-running Hermes process over any reachable network.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Badge variant={badgeVariantByStatus[connectionState]} size="sm">
|
||||
{hermesGatewayStatusLabel(connectionState)}
|
||||
</Badge>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
disabled={isBusy || environmentId === null}
|
||||
onClick={() => void refreshStatus()}
|
||||
aria-label="Refresh Hermes gateway status"
|
||||
>
|
||||
<RefreshCwIcon className={pendingAction === "status" ? "animate-spin" : undefined} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="grid gap-1.5">
|
||||
<span className="text-xs font-medium text-foreground">Connector URL</span>
|
||||
<Input
|
||||
value={connectorUrl}
|
||||
onChange={(event) => {
|
||||
connectorUrlHasLocalEditsRef.current = true;
|
||||
setConnectorUrl(event.target.value);
|
||||
}}
|
||||
placeholder="wss://t3.example.com/api/hermes-gateway/ws"
|
||||
spellCheck={false}
|
||||
disabled={connectionState === "revoked"}
|
||||
/>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Defaults to this browser's origin. Tailscale URLs work without special handling.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{status ? (
|
||||
<dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs sm:grid-cols-3">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Last connected</dt>
|
||||
<dd className="text-foreground">{formatHermesLastConnected(status.lastConnectedAt)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Active sessions</dt>
|
||||
<dd className="text-foreground">{status.activeSessionCount}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Protocol</dt>
|
||||
<dd className="text-foreground">{status.protocolVersion ?? "Unknown"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Plugin</dt>
|
||||
<dd className="text-foreground">{status.pluginVersion ?? "Unknown"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Hermes</dt>
|
||||
<dd className="text-foreground">{status.hermesVersion ?? "Unknown"}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
|
||||
{enrollment ? (
|
||||
<div className="grid gap-2 rounded-md border border-border/70 bg-background/80 p-2.5">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-foreground">One-time enrollment command</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Expires {formatHermesLastConnected(enrollment.expiresAt)}. The long-lived credential
|
||||
is issued directly to the plugin and is never shown here.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded bg-muted px-2 py-1.5 text-[11px]">
|
||||
{enrollment.command}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
onClick={() => copyToClipboard(enrollment.command, undefined)}
|
||||
aria-label="Copy Hermes enrollment command"
|
||||
>
|
||||
{isCopied ? <CheckIcon /> : <CopyIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="text-xs text-destructive">{error}</p> : null}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{connectionState !== "revoked" ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={enrollment ? "outline" : "default"}
|
||||
disabled={isBusy || connectorUrl.trim().length === 0 || environmentId === null}
|
||||
onClick={() => void handleCreateEnrollment()}
|
||||
>
|
||||
{pendingAction === "enroll" ? <LoaderIcon className="animate-spin" /> : null}
|
||||
{enrollment ? "Retry enrollment" : "Create enrollment"}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isBusy || connectionState === "revoked" || environmentId === null}
|
||||
onClick={() => void handleRevoke()}
|
||||
>
|
||||
{pendingAction === "revoke" ? <LoaderIcon className="animate-spin" /> : <UnplugIcon />}
|
||||
Revoke
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
import { deriveProviderModelsForDisplay } from "./ProviderInstanceCard";
|
||||
import {
|
||||
deriveProviderModelsForDisplay,
|
||||
isProviderInstanceDisplayNameEditable,
|
||||
} from "./ProviderInstanceCard";
|
||||
|
||||
describe("deriveProviderModelsForDisplay", () => {
|
||||
it("uses current config custom models instead of stale live custom rows", () => {
|
||||
@@ -34,3 +37,11 @@ describe("deriveProviderModelsForDisplay", () => {
|
||||
).toEqual(["server-model", "kept-custom"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isProviderInstanceDisplayNameEditable", () => {
|
||||
it("keeps Hermes nicknames immutable without changing other providers", () => {
|
||||
expect(isProviderInstanceDisplayNameEditable("hermes")).toBe(false);
|
||||
expect(isProviderInstanceDisplayNameEditable("codex")).toBe(true);
|
||||
expect(isProviderInstanceDisplayNameEditable("claudeAgent")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
@@ -26,6 +27,9 @@ import {
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
|
||||
import { normalizeProviderAccentColor } from "../../providerInstances";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
@@ -43,6 +47,8 @@ import { ProviderModelsSection } from "./ProviderModelsSection";
|
||||
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
|
||||
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { HermesGatewayInstanceSection } from "./HermesGatewayInstanceSection";
|
||||
import { messageFromUnknownError } from "./HermesGatewayInstanceSection.logic";
|
||||
import {
|
||||
getProviderVersionAdvisoryPresentation,
|
||||
PROVIDER_STATUS_STYLES,
|
||||
@@ -131,6 +137,10 @@ export function deriveProviderModelsForDisplay(input: {
|
||||
return [...serverModels, ...customModels];
|
||||
}
|
||||
|
||||
export function isProviderInstanceDisplayNameEditable(driver: string): boolean {
|
||||
return driver !== "hermes";
|
||||
}
|
||||
|
||||
function ProviderAuthEmail(props: {
|
||||
readonly email: string | undefined;
|
||||
readonly prefix?: string;
|
||||
@@ -394,6 +404,11 @@ export function ProviderInstanceCard({
|
||||
onRunUpdate,
|
||||
isUpdating = false,
|
||||
}: ProviderInstanceCardProps) {
|
||||
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
|
||||
const revokeHermesInstance = useAtomCommand(serverEnvironment.hermesGatewayRevokeInstance, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const enabled = instance.enabled ?? true;
|
||||
// The server-reported status wins when present; otherwise fall back to
|
||||
// "disabled"/"warning" based on the local `enabled` flag so the dot
|
||||
@@ -413,8 +428,21 @@ export function ProviderInstanceCard({
|
||||
const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
|
||||
const updateCommand = versionAdvisory?.updateCommand ?? null;
|
||||
const FallbackIconComponent = driverOption?.icon;
|
||||
const displayName =
|
||||
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
|
||||
const configuredDisplayName = instance.displayName?.trim();
|
||||
const isHermes = instance.driver === "hermes";
|
||||
const hermesNickname =
|
||||
configuredDisplayName?.replace(/^Hermes\s*[·:–—-]?\s*/u, "").trim() ||
|
||||
(instanceId === "hermes"
|
||||
? "Hermes"
|
||||
: String(instanceId)
|
||||
.replace(/^hermes[-_]?/u, "")
|
||||
.replace(/[-_]+/g, " ")
|
||||
.trim());
|
||||
const displayName = isHermes
|
||||
? instanceId === "hermes" || hermesNickname === "Hermes"
|
||||
? "Hermes"
|
||||
: `Hermes · ${hermesNickname}`
|
||||
: configuredDisplayName || driverOption?.label || String(instance.driver);
|
||||
const accentColor = normalizeProviderAccentColor(instance.accentColor);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
|
||||
onCopy: ({ providerName }) => {
|
||||
@@ -501,6 +529,49 @@ export function ProviderInstanceCard({
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!onDelete || isDeleting) return;
|
||||
if (!isHermes) {
|
||||
onDelete();
|
||||
return;
|
||||
}
|
||||
if (environmentId === null) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not delete Hermes instance",
|
||||
description: "Reconnect this browser to the T3 server so its gateway can be revoked first.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
setIsDeleting(true);
|
||||
const result = await revokeHermesInstance({
|
||||
environmentId,
|
||||
input: { instanceId },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
onDelete();
|
||||
setIsDeleting(false);
|
||||
return;
|
||||
}
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
const wasNeverEnrolled =
|
||||
typeof failure === "object" &&
|
||||
failure !== null &&
|
||||
"code" in failure &&
|
||||
failure.code === "instance-not-found";
|
||||
if (wasNeverEnrolled) {
|
||||
onDelete();
|
||||
setIsDeleting(false);
|
||||
return;
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not delete Hermes instance",
|
||||
description: `${messageFromUnknownError(failure)} The instance was kept so a live gateway credential is not orphaned.`,
|
||||
});
|
||||
setIsDeleting(false);
|
||||
};
|
||||
|
||||
const titleIconNode = driverKind ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
@@ -563,10 +634,15 @@ export function ProviderInstanceCard({
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
disabled={isDeleting}
|
||||
onClick={() => void handleDelete()}
|
||||
aria-label={`Delete provider instance ${instanceId}`}
|
||||
>
|
||||
<Trash2Icon className="size-3" />
|
||||
{isDeleting ? (
|
||||
<LoaderIcon className="size-3 animate-spin" />
|
||||
) : (
|
||||
<Trash2Icon className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
@@ -730,22 +806,38 @@ export function ProviderInstanceCard({
|
||||
<Collapsible open={isExpanded} onOpenChange={onExpandedChange}>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-5 px-3 pb-4 pt-2 sm:px-4">
|
||||
<div>
|
||||
<label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
|
||||
<span className="text-xs font-medium text-foreground">Display name</span>
|
||||
<DraftInput
|
||||
id={`provider-instance-${instanceId}-display-name`}
|
||||
className="mt-1.5"
|
||||
value={instance.displayName ?? ""}
|
||||
onCommit={updateDisplayName}
|
||||
placeholder={driverOption?.label ?? "Instance label"}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{isProviderInstanceDisplayNameEditable(String(instance.driver)) ? (
|
||||
<div>
|
||||
<label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
|
||||
<span className="text-xs font-medium text-foreground">Display name</span>
|
||||
<DraftInput
|
||||
id={`provider-instance-${instanceId}-display-name`}
|
||||
className="mt-1.5"
|
||||
value={instance.displayName ?? ""}
|
||||
onCommit={updateDisplayName}
|
||||
placeholder={driverOption?.label ?? "Instance label"}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
Optional label shown in the provider list.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<span className="text-xs font-medium text-foreground">Hermes nickname</span>
|
||||
<div
|
||||
className="mt-1.5 rounded-md border border-border/70 bg-muted/35 px-3 py-2 text-sm text-foreground"
|
||||
data-hermes-nickname-readonly="true"
|
||||
>
|
||||
{displayName}
|
||||
</div>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
Optional label shown in the provider list.
|
||||
Fixed after creation because this nickname identifies the paired Hermes instance.
|
||||
Delete and re-add the instance to choose a different nickname.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<ProviderAccentColorPicker
|
||||
@@ -757,14 +849,18 @@ export function ProviderInstanceCard({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ProviderEnvironmentSection
|
||||
environment={instance.environment ?? []}
|
||||
onChange={updateEnvironment}
|
||||
/>
|
||||
</div>
|
||||
{isHermes ? (
|
||||
<HermesGatewayInstanceSection instanceId={instanceId} nickname={hermesNickname} />
|
||||
) : (
|
||||
<div>
|
||||
<ProviderEnvironmentSection
|
||||
environment={instance.environment ?? []}
|
||||
onChange={updateEnvironment}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{driverOption ? (
|
||||
{driverOption && !isHermes ? (
|
||||
<ProviderSettingsForm
|
||||
definition={driverOption}
|
||||
value={instance.config}
|
||||
@@ -774,7 +870,7 @@ export function ProviderInstanceCard({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{driverOption !== undefined ? (
|
||||
{driverOption !== undefined && !isHermes ? (
|
||||
<ProviderModelsSection
|
||||
instanceId={instanceId}
|
||||
driverKind={driverKind}
|
||||
@@ -788,7 +884,7 @@ export function ProviderInstanceCard({
|
||||
onFavoriteModelsChange={onFavoriteModelsChange}
|
||||
onModelOrderChange={onModelOrderChange}
|
||||
/>
|
||||
) : (
|
||||
) : driverOption === undefined ? (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This instance uses a driver (
|
||||
@@ -797,7 +893,7 @@ export function ProviderInstanceCard({
|
||||
edited from this surface.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
@@ -3,11 +3,13 @@ import {
|
||||
CodexSettings,
|
||||
CursorSettings,
|
||||
GrokSettings,
|
||||
HermesSettings,
|
||||
OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as Schema from "effect/Schema";
|
||||
import { ClaudeAI, CursorIcon, GrokIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { HermesIcon } from "../HermesIcon";
|
||||
|
||||
type ProviderSettingsSchema = {
|
||||
readonly fields: Readonly<Record<string, Schema.Top>>;
|
||||
@@ -67,6 +69,12 @@ export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] =
|
||||
icon: OpenCodeIcon,
|
||||
settingsSchema: OpenCodeSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("hermes"),
|
||||
label: "Hermes",
|
||||
icon: HermesIcon,
|
||||
settingsSchema: HermesSettings,
|
||||
},
|
||||
];
|
||||
|
||||
export const PROVIDER_CLIENT_DEFINITION_BY_VALUE: Partial<
|
||||
|
||||
@@ -64,7 +64,7 @@ function readInstanceCustomModels(
|
||||
}
|
||||
const legacyProviders = settings.providers as Record<
|
||||
string,
|
||||
{ readonly customModels: ReadonlyArray<string> } | undefined
|
||||
{ readonly customModels?: ReadonlyArray<string> } | undefined
|
||||
>;
|
||||
return legacyProviders[driverKind]?.customModels ?? [];
|
||||
}
|
||||
|
||||
@@ -5,7 +5,10 @@ import {
|
||||
deriveProviderInstanceEntries,
|
||||
getDefaultProviderInstanceModel,
|
||||
isProviderInstancePickerReady,
|
||||
isProviderInstanceComposerAvailable,
|
||||
getProviderInstanceComposerUnavailableMessage,
|
||||
isProviderInstancePickerVisible,
|
||||
resolveComposerProviderInstanceId,
|
||||
resolveDefaultProviderModelSelection,
|
||||
resolveSelectableProviderInstance,
|
||||
resolveProviderDriverKindForInstanceSelection,
|
||||
@@ -68,6 +71,66 @@ describe("isProviderInstancePickerReady", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes composer availability", () => {
|
||||
it("keeps an offline Hermes instance selected but marks it unsendable", () => {
|
||||
const [entry] = deriveProviderInstanceEntries([
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-research",
|
||||
displayName: "Research",
|
||||
status: "error",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entry && isProviderInstanceComposerAvailable(entry)).toBe(false);
|
||||
expect(getProviderInstanceComposerUnavailableMessage(entry)).toContain(
|
||||
"Hermes · Research is offline",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not tighten legacy composer availability for other providers", () => {
|
||||
const [entry] = deriveProviderInstanceEntries([
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
instanceId: "codex",
|
||||
status: "error",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entry && isProviderInstanceComposerAvailable(entry)).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves a missing bound Hermes instance instead of rebinding to another gateway", () => {
|
||||
const missing = ProviderInstanceId.make("hermes-research");
|
||||
const connected = ProviderInstanceId.make("hermes-lab");
|
||||
const entries = deriveProviderInstanceEntries([
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: connected,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(
|
||||
resolveComposerProviderInstanceId({
|
||||
entries,
|
||||
draftInstanceId: null,
|
||||
threadInstanceId: missing,
|
||||
threadModelInstanceId: missing,
|
||||
projectInstanceId: connected,
|
||||
requestedDriverKind: ProviderDriverKind.make("hermes"),
|
||||
lockedProvider: ProviderDriverKind.make("hermes"),
|
||||
lockedContinuationGroupKey: null,
|
||||
}),
|
||||
).toBe(missing);
|
||||
expect(
|
||||
getProviderInstanceComposerUnavailableMessage(undefined, {
|
||||
driverKind: ProviderDriverKind.make("hermes"),
|
||||
instanceId: missing,
|
||||
}),
|
||||
).toContain("hermes-research");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isProviderInstancePickerVisible", () => {
|
||||
it("keeps enabled instances in the rail and removes disabled instances", () => {
|
||||
const [enabledEntry, disabledEntry] = deriveProviderInstanceEntries([
|
||||
@@ -130,6 +193,32 @@ describe("deriveProviderInstanceEntries", () => {
|
||||
expect(entry?.driverKind).toBe("codex");
|
||||
expect(entry?.isDefault).toBe(false);
|
||||
});
|
||||
|
||||
it("formats default and custom Hermes instance labels consistently", () => {
|
||||
const entries = deriveProviderInstanceEntries([
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes",
|
||||
displayName: "Hermes",
|
||||
}),
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-research",
|
||||
displayName: "Research",
|
||||
}),
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes-lab",
|
||||
displayName: "Hermes · Lab",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries.map((entry) => entry.displayName)).toEqual([
|
||||
"Hermes",
|
||||
"Hermes · Research",
|
||||
"Hermes · Lab",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSelectableProviderInstance", () => {
|
||||
|
||||
@@ -74,6 +74,31 @@ export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boo
|
||||
return entry.enabled && entry.isAvailable && entry.status === "ready";
|
||||
}
|
||||
|
||||
/**
|
||||
* Existing providers retain their historical composer behavior while Hermes
|
||||
* requires a live gateway connection. This keeps an offline Hermes thread
|
||||
* selected and readable without allowing a turn to be routed elsewhere.
|
||||
*/
|
||||
export function isProviderInstanceComposerAvailable(entry: ProviderInstanceEntry): boolean {
|
||||
return entry.driverKind !== "hermes" || isProviderInstancePickerReady(entry);
|
||||
}
|
||||
|
||||
export function getProviderInstanceComposerUnavailableMessage(
|
||||
entry: ProviderInstanceEntry | undefined,
|
||||
missingSelection?: {
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
},
|
||||
): string {
|
||||
if (entry?.driverKind === "hermes") {
|
||||
return `${entry.displayName} is offline. Reconnect it in Settings to continue this thread.`;
|
||||
}
|
||||
if (missingSelection?.driverKind === "hermes") {
|
||||
return `Hermes instance '${missingSelection.instanceId}' is unavailable. Restore it in Settings to continue this thread.`;
|
||||
}
|
||||
return "Enable a provider in Settings to send a message.";
|
||||
}
|
||||
|
||||
/** Picker rails contain configured, enabled instances only. */
|
||||
export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
|
||||
return entry.enabled;
|
||||
@@ -139,6 +164,15 @@ function resolveInstanceDisplayName(
|
||||
): string {
|
||||
const trimmedSnapshotName = snapshot.displayName?.trim();
|
||||
const kindLabel = driverKindLabel(driverKind);
|
||||
if (driverKind === "hermes") {
|
||||
if (isDefault) return "Hermes";
|
||||
const candidate =
|
||||
trimmedSnapshotName && trimmedSnapshotName !== kindLabel
|
||||
? trimmedSnapshotName
|
||||
: humanizeInstanceId(instanceId).replace(/^Hermes(?:\s+|$)/u, "");
|
||||
const nickname = candidate.replace(/^Hermes\s*[·:–—-]\s*/u, "").trim();
|
||||
return nickname ? `Hermes · ${nickname}` : "Hermes";
|
||||
}
|
||||
if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
|
||||
return trimmedSnapshotName;
|
||||
}
|
||||
@@ -312,6 +346,66 @@ export function resolveSelectableProviderInstanceEntry(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the instance used by the composer while preserving an existing
|
||||
* Hermes thread's immutable gateway binding. Hermes sessions cannot be moved
|
||||
* to another instance, so a missing or disabled bound instance remains the
|
||||
* exact selection and lets the composer surface its unavailable state instead
|
||||
* of silently routing the next message to another connected Hermes process.
|
||||
*/
|
||||
export function resolveComposerProviderInstanceId(input: {
|
||||
readonly entries: ReadonlyArray<ProviderInstanceEntry>;
|
||||
readonly draftInstanceId: ProviderInstanceId | null;
|
||||
readonly threadInstanceId: ProviderInstanceId | undefined;
|
||||
readonly threadModelInstanceId: ProviderInstanceId | undefined;
|
||||
readonly projectInstanceId: ProviderInstanceId | undefined;
|
||||
readonly requestedDriverKind: ProviderDriverKind;
|
||||
readonly lockedProvider: ProviderDriverKind | null;
|
||||
readonly lockedContinuationGroupKey: string | null;
|
||||
}): ProviderInstanceId {
|
||||
const boundThreadInstanceId = input.threadInstanceId ?? input.threadModelInstanceId;
|
||||
if (input.lockedProvider === "hermes" && boundThreadInstanceId) {
|
||||
return boundThreadInstanceId;
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
input.draftInstanceId,
|
||||
input.threadInstanceId,
|
||||
input.threadModelInstanceId,
|
||||
input.projectInstanceId,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue;
|
||||
const match = input.entries.find(
|
||||
(entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
|
||||
);
|
||||
if (!match) continue;
|
||||
if (input.lockedProvider && match.driverKind !== input.lockedProvider) continue;
|
||||
if (
|
||||
input.lockedContinuationGroupKey &&
|
||||
match.continuationGroupKey !== input.lockedContinuationGroupKey
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
return match.instanceId;
|
||||
}
|
||||
|
||||
const compatibleEntries = input.entries.filter(
|
||||
(entry) =>
|
||||
(!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
|
||||
(!input.lockedContinuationGroupKey ||
|
||||
entry.continuationGroupKey === input.lockedContinuationGroupKey),
|
||||
);
|
||||
const requestedDriverEntries = compatibleEntries.filter(
|
||||
(entry) => entry.driverKind === input.requestedDriverKind,
|
||||
);
|
||||
return (
|
||||
resolveSelectableProviderInstanceEntry(requestedDriverEntries, undefined)?.instanceId ??
|
||||
resolveSelectableProviderInstanceEntry(compatibleEntries, undefined)?.instanceId ??
|
||||
NO_PROVIDER_MODEL_SELECTION.instanceId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the routing key for a selection that may reference an instance
|
||||
* id that no longer exists (e.g. a persisted thread selection after the
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Hermes event compatibility inventory
|
||||
|
||||
The plugin deliberately uses only the public Hermes plugin and platform-adapter
|
||||
surfaces audited at Hermes Agent commit
|
||||
`3910ab28c0892fcf846fc61318d2fd15689eddf1`.
|
||||
|
||||
## Mapped in V1
|
||||
|
||||
| Hermes surface | T3 gateway event |
|
||||
| ----------------------------------------- | ---------------------------------------------- |
|
||||
| Cumulative `send` / `edit_message` output | `content.delta` |
|
||||
| Final stream edit | `item.completed`, `turn.completed` |
|
||||
| `pre_tool_call` / `post_tool_call` hooks | Typed `item.started` / `item.completed` |
|
||||
| Live adapter status text | Generic `unknown` activity item |
|
||||
| `send_exec_approval` | `request.opened` / `request.resolved` |
|
||||
| `send_clarify` | `user-input.requested` / `user-input.resolved` |
|
||||
| `/steer` gateway command | `turn.steer` |
|
||||
| Adapter interrupt event | `turn.interrupt` |
|
||||
|
||||
## Known limitations
|
||||
|
||||
- The platform adapter receives cumulative rendered text, not the underlying
|
||||
token stream category. V1 maps it to `assistant_text`; Hermes reasoning,
|
||||
plan, and command-output stream categories are not publicly exposed here.
|
||||
- The delta contract has no replacement operation. Rare edits that revise
|
||||
already-emitted text become a meaningful generic activity instead of
|
||||
corrupting the T3 transcript.
|
||||
- Hermes' documented tool hook surface exposes a `task_id`, tool name,
|
||||
arguments, string result, and duration. The audited runtime additionally
|
||||
supplies `session_id` and `tool_call_id`; V1 uses them when present and falls
|
||||
back to the documented IDs for older versions. It projects only canonical,
|
||||
whitelisted fields (command/cwd, file path, search query, image path, or MCP
|
||||
server/operation); arbitrary arguments and raw results never cross the wire.
|
||||
- Approval resolution is session-FIFO in Hermes. T3 request IDs identify the UI
|
||||
prompt, then resolve the oldest matching Hermes approval for that session.
|
||||
- The public `clarify` hook is a single question. The wire protocol supports an
|
||||
array so richer structured input can be added without a protocol break.
|
||||
- Hermes session completion has no dedicated platform-adapter callback. The
|
||||
plugin uses the stream consumer's required `finalize=True` edit as the
|
||||
authoritative completion boundary.
|
||||
- Active `/steer` dispatch returns a textual Hermes control acknowledgement
|
||||
through the normal platform `send(..., notify=True)` path. The plugin
|
||||
captures that response in the originating steering request's async context,
|
||||
suppresses it from the transcript, and acknowledges T3 only when the audited
|
||||
Hermes success response begins with `⏩ Steer queued`. Unknown future response
|
||||
shapes fail closed with `protocol.error` rather than completing the turn.
|
||||
- Attachments are not accepted. They are the first planned post-stability
|
||||
feature; the capability is reserved and fixed to `false` in protocol V1.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Hermes T3 Code Gateway
|
||||
|
||||
Experimental Hermes platform plugin for connecting one already-running Hermes
|
||||
process to T3 Code. The plugin makes an outbound WebSocket connection; Hermes
|
||||
does not need to listen on a public port.
|
||||
|
||||
Each T3 thread maps deterministically to one Hermes gateway session. A new T3
|
||||
thread creates a new session identity, later messages use the same identity,
|
||||
active-turn messages use Hermes' native `/steer` path, and stopping a turn does
|
||||
not delete its transcript.
|
||||
|
||||
## Install from this repository
|
||||
|
||||
Copy or symlink this directory into the active Hermes profile:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.hermes/plugins
|
||||
ln -s /path/to/t3code/integrations/hermes-t3-gateway \
|
||||
~/.hermes/plugins/hermes-t3-gateway
|
||||
hermes plugins enable hermes-t3-gateway
|
||||
```
|
||||
|
||||
In T3 Code, open the Hermes instance settings, choose **Add Hermes**, enter a
|
||||
unique nickname, and copy the generated enrollment command. It has this shape:
|
||||
|
||||
```bash
|
||||
hermes t3 connect \
|
||||
--url https://siva.davis7.space:<port> \
|
||||
--token <one-time-token>
|
||||
```
|
||||
|
||||
`--url` accepts an HTTP(S) browser origin or an explicit WS(S) URL. The command
|
||||
normalizes it to `/api/hermes-gateway/ws`, enrolls over the first authenticated
|
||||
`connection.hello` frame, and saves these values with Hermes'
|
||||
profile-aware `save_env_value` helper:
|
||||
|
||||
- `HERMES_T3_GATEWAY_URL`
|
||||
- `HERMES_T3_GATEWAY_INSTANCE_ID`
|
||||
- `HERMES_T3_GATEWAY_CREDENTIAL`
|
||||
- `HERMES_T3_GATEWAY_NICKNAME`
|
||||
|
||||
The long-lived credential is never printed. Restart `hermes gateway` after
|
||||
enrollment. `hermes t3 status` reports the local enrollment without revealing
|
||||
the credential.
|
||||
|
||||
## V1 scope
|
||||
|
||||
- Text input and live assistant streaming
|
||||
- Multiple concurrent Hermes sessions in one process
|
||||
- Active-turn steering and interrupt
|
||||
- Dangerous-command approvals
|
||||
- Structured `clarify` questions
|
||||
- Tool lifecycle activity through Hermes plugin hooks
|
||||
- Reconnect with bounded backoff
|
||||
- Version-incompatible and revoked credentials fail closed
|
||||
|
||||
Attachments intentionally advertise `false`. Adding bounded image/file input is
|
||||
the first post-stability feature and should not reuse arbitrary raw payloads.
|
||||
|
||||
See [COMPATIBILITY.md](./COMPATIBILITY.md) for public Hermes extension-surface
|
||||
limitations.
|
||||
|
||||
## Tests
|
||||
|
||||
The pure protocol and transport tests do not require a live Hermes or T3 server:
|
||||
|
||||
```bash
|
||||
python -m unittest discover \
|
||||
integrations/hermes-t3-gateway/tests \
|
||||
-p 'test_*.py'
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
"""T3 Code gateway plugin registration for Hermes Agent."""
|
||||
# ruff: noqa: N999 - Hermes loads hyphenated plugin directories dynamically.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .adapter import (
|
||||
T3PlatformAdapter,
|
||||
check_requirements,
|
||||
env_enablement,
|
||||
validate_config,
|
||||
)
|
||||
from .cli import register_cli, t3_command
|
||||
|
||||
|
||||
def _pre_tool_call(
|
||||
tool_name: str,
|
||||
args: dict,
|
||||
task_id: str,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
session_id = str(kwargs.get("session_id") or task_id)
|
||||
tool_call_id = str(kwargs.get("tool_call_id") or "")
|
||||
T3PlatformAdapter.route_tool_started(tool_name, args, session_id, tool_call_id)
|
||||
|
||||
|
||||
def _post_tool_call(
|
||||
tool_name: str,
|
||||
args: dict,
|
||||
result: str,
|
||||
task_id: str,
|
||||
duration_ms: int | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
del args
|
||||
session_id = str(kwargs.get("session_id") or task_id)
|
||||
tool_call_id = str(kwargs.get("tool_call_id") or "")
|
||||
status = str(kwargs.get("status") or "")
|
||||
T3PlatformAdapter.route_tool_completed(
|
||||
tool_name, result, session_id, duration_ms, tool_call_id, status
|
||||
)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
ctx.register_platform(
|
||||
name="t3",
|
||||
label="T3 Code",
|
||||
adapter_factory=lambda config: T3PlatformAdapter(config),
|
||||
check_fn=check_requirements,
|
||||
validate_config=validate_config,
|
||||
required_env=[
|
||||
"HERMES_T3_GATEWAY_URL",
|
||||
"HERMES_T3_GATEWAY_INSTANCE_ID",
|
||||
"HERMES_T3_GATEWAY_CREDENTIAL",
|
||||
],
|
||||
env_enablement_fn=env_enablement,
|
||||
max_message_length=120_000,
|
||||
emoji="🔺",
|
||||
pii_safe=True,
|
||||
platform_hint=(
|
||||
"You are chatting through T3 Code. Preserve normal Hermes behavior; "
|
||||
"T3 renders streamed text, tool activity, approvals, and questions."
|
||||
),
|
||||
)
|
||||
ctx.register_cli_command(
|
||||
name="t3",
|
||||
help="Pair and inspect the T3 Code gateway",
|
||||
setup_fn=register_cli,
|
||||
handler_fn=t3_command,
|
||||
description=(
|
||||
"Connect this Hermes process to a named T3 Code provider instance."
|
||||
),
|
||||
)
|
||||
ctx.register_hook("pre_tool_call", _pre_tool_call)
|
||||
ctx.register_hook("post_tool_call", _post_tool_call)
|
||||
|
||||
|
||||
__all__ = ["register"]
|
||||
@@ -0,0 +1,940 @@
|
||||
"""Hermes platform adapter that treats each T3 thread as one Hermes session."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import uuid
|
||||
import weakref
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.base import (
|
||||
BasePlatformAdapter,
|
||||
MessageEvent,
|
||||
MessageType,
|
||||
SendResult,
|
||||
)
|
||||
from gateway.session import build_session_key
|
||||
|
||||
from .cli import CREDENTIAL_ENV, INSTANCE_ID_ENV, NICKNAME_ENV, URL_ENV
|
||||
from .connection import T3GatewayConnection, dependency_available
|
||||
from .protocol import (
|
||||
canonical_tool_data,
|
||||
canonical_tool_item_type,
|
||||
frame,
|
||||
iso_now,
|
||||
item_id,
|
||||
protocol_error,
|
||||
validate_server_frame,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _hermes_version() -> str:
|
||||
try:
|
||||
from hermes_cli import __version__
|
||||
|
||||
return str(__version__)
|
||||
except Exception: # noqa: BLE001 - version discovery must not block loading
|
||||
return "unknown"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TurnState:
|
||||
thread_id: str
|
||||
session_id: str
|
||||
turn_id: str
|
||||
request_id: str
|
||||
message_id: str = field(default_factory=lambda: str(uuid.uuid4()))
|
||||
visible_text: str = ""
|
||||
assistant_started: bool = False
|
||||
tool_items: dict[str, str] = field(default_factory=dict)
|
||||
generic_activity_id: str | None = None
|
||||
generic_activity_detail: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _SteerControlResponse:
|
||||
thread_id: str
|
||||
request_id: str
|
||||
messages: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
_steer_control_response = contextvars.ContextVar[_SteerControlResponse | None](
|
||||
"hermes_t3_steer_control_response",
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
class T3PlatformAdapter(BasePlatformAdapter):
|
||||
"""One process-level T3 connection serving many isolated thread sessions."""
|
||||
|
||||
supports_code_blocks = True
|
||||
supports_status_text = True
|
||||
REQUIRES_EDIT_FINALIZE = True
|
||||
MAX_MESSAGE_LENGTH = 120_000
|
||||
_instances: weakref.WeakSet[T3PlatformAdapter] = weakref.WeakSet()
|
||||
|
||||
def __init__(self, config: PlatformConfig):
|
||||
super().__init__(config, Platform("t3"))
|
||||
extra = config.extra or {}
|
||||
self._url = str(extra.get("url") or os.environ.get(URL_ENV, "")).strip()
|
||||
self._instance_id = str(
|
||||
extra.get("instance_id") or os.environ.get(INSTANCE_ID_ENV, "")
|
||||
).strip()
|
||||
self._credential = str(
|
||||
extra.get("credential") or os.environ.get(CREDENTIAL_ENV, "")
|
||||
).strip()
|
||||
self._nickname = str(
|
||||
extra.get("nickname") or os.environ.get(NICKNAME_ENV, "") or "Hermes"
|
||||
).strip()
|
||||
self._connection: T3GatewayConnection | None = None
|
||||
self._event_loop: asyncio.AbstractEventLoop | None = None
|
||||
self._sessions: dict[str, str] = {}
|
||||
self._active_session_threads: set[str] = set()
|
||||
self._thread_by_session: dict[str, str] = {}
|
||||
self._active_turns: dict[str, _TurnState] = {}
|
||||
self._approval_requests: dict[str, tuple[str, str]] = {}
|
||||
self._user_input_requests: dict[str, tuple[str, str]] = {}
|
||||
type(self)._instances.add(self)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return f"T3 Code ({self._nickname})"
|
||||
|
||||
@property
|
||||
def authorization_is_upstream(self) -> bool:
|
||||
# The only source of inbound messages is T3's instance-authenticated
|
||||
# socket. There is no separate Hermes-side user allowlist.
|
||||
return True
|
||||
|
||||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||||
del is_reconnect
|
||||
if not (self._url and self._instance_id and self._credential):
|
||||
self._set_fatal_error(
|
||||
"t3_not_enrolled",
|
||||
"Run `hermes t3 connect --url <url> --token <token>` first.",
|
||||
retryable=False,
|
||||
)
|
||||
return False
|
||||
self._event_loop = asyncio.get_running_loop()
|
||||
self._connection = T3GatewayConnection(
|
||||
url=self._url,
|
||||
instance_id=self._instance_id,
|
||||
credential=self._credential,
|
||||
hermes_version=_hermes_version(),
|
||||
on_message=self._handle_server_frame,
|
||||
on_state=self._handle_connection_state,
|
||||
)
|
||||
try:
|
||||
connected = await self._connection.connect()
|
||||
except Exception as exc: # noqa: BLE001 - transport supplies typed rejection details
|
||||
self._set_fatal_error("t3_connection_rejected", str(exc), retryable=False)
|
||||
return False
|
||||
if connected:
|
||||
self._mark_connected()
|
||||
await self._send_status()
|
||||
return connected
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self._connection is not None:
|
||||
await self._connection.disconnect()
|
||||
self._connection = None
|
||||
self._mark_disconnected()
|
||||
|
||||
async def send(
|
||||
self,
|
||||
chat_id: str,
|
||||
content: str,
|
||||
reply_to: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SendResult:
|
||||
del reply_to
|
||||
captured = self._capture_steer_control_response(chat_id, content)
|
||||
if captured is not None:
|
||||
return captured
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is None:
|
||||
return SendResult(success=False, error="no active T3 turn")
|
||||
try:
|
||||
await self._emit_assistant_content(turn, content)
|
||||
if bool((metadata or {}).get("notify")):
|
||||
await self._complete_turn(turn)
|
||||
return SendResult(success=True, message_id=turn.message_id)
|
||||
except Exception as exc: # noqa: BLE001 - adapter send must return SendResult
|
||||
return SendResult(success=False, error=str(exc))
|
||||
|
||||
async def edit_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
message_id: str,
|
||||
content: str,
|
||||
*,
|
||||
finalize: bool = False,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SendResult:
|
||||
del metadata
|
||||
captured = self._capture_steer_control_response(chat_id, content)
|
||||
if captured is not None:
|
||||
return captured
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is None:
|
||||
return SendResult(success=False, error="no active T3 turn")
|
||||
try:
|
||||
await self._emit_assistant_content(turn, content)
|
||||
if finalize:
|
||||
await self._complete_turn(turn)
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
except Exception as exc: # noqa: BLE001 - adapter edit must return SendResult
|
||||
return SendResult(success=False, error=str(exc))
|
||||
|
||||
async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
|
||||
return {"name": f"T3 thread {chat_id}", "type": "dm"}
|
||||
|
||||
async def send_typing(
|
||||
self, chat_id: str, metadata: dict[str, Any] | None = None
|
||||
) -> None:
|
||||
del metadata
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is None:
|
||||
return
|
||||
status = getattr(self, "_status_text", {}).get(str(chat_id))
|
||||
if status:
|
||||
await self._emit_generic_activity(turn, status)
|
||||
|
||||
def set_status_text(self, chat_id: str, text: str | None) -> None:
|
||||
super().set_status_text(chat_id, text)
|
||||
if not text:
|
||||
return
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is not None:
|
||||
self._schedule(self._emit_generic_activity(turn, text))
|
||||
|
||||
async def send_exec_approval(
|
||||
self,
|
||||
chat_id: str,
|
||||
command: str,
|
||||
session_key: str,
|
||||
description: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> SendResult:
|
||||
del metadata, kwargs
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is None:
|
||||
return SendResult(success=False, error="no active T3 turn")
|
||||
approval_id = str(uuid.uuid4())
|
||||
self._approval_requests[approval_id] = (session_key, turn.turn_id)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"request.opened",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
requestId=approval_id,
|
||||
requestType="command_execution_approval",
|
||||
detail=description or "Hermes requests permission to run a command",
|
||||
args={"command": command},
|
||||
)
|
||||
)
|
||||
return SendResult(success=True, message_id=approval_id)
|
||||
|
||||
async def send_clarify(
|
||||
self,
|
||||
chat_id: str,
|
||||
question: str,
|
||||
choices: list[Any] | None,
|
||||
clarify_id: str,
|
||||
session_key: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SendResult:
|
||||
del metadata
|
||||
turn = self._active_turns.get(str(chat_id))
|
||||
if turn is None:
|
||||
return SendResult(success=False, error="no active T3 turn")
|
||||
options = []
|
||||
for choice in choices or []:
|
||||
label = str(choice.get("label") if isinstance(choice, dict) else choice)
|
||||
description = (
|
||||
str(choice.get("description") or label)
|
||||
if isinstance(choice, dict)
|
||||
else label
|
||||
)
|
||||
options.append({"label": label, "description": description})
|
||||
self._user_input_requests[clarify_id] = (session_key, turn.turn_id)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"user-input.requested",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
requestId=clarify_id,
|
||||
questions=[
|
||||
{
|
||||
"id": clarify_id,
|
||||
"header": "Hermes",
|
||||
"question": question,
|
||||
"options": options,
|
||||
"multiSelect": False,
|
||||
}
|
||||
],
|
||||
)
|
||||
)
|
||||
return SendResult(success=True, message_id=clarify_id)
|
||||
|
||||
async def _handle_server_frame(self, raw: dict[str, Any]) -> None:
|
||||
request = raw.get("requestId")
|
||||
try:
|
||||
message = validate_server_frame(raw)
|
||||
frame_type = message["type"]
|
||||
if frame_type == "session.ensure":
|
||||
await self._ensure_session(message)
|
||||
elif frame_type == "turn.start":
|
||||
await self._start_turn(message)
|
||||
elif frame_type == "turn.steer":
|
||||
await self._steer_turn(message)
|
||||
elif frame_type == "turn.interrupt":
|
||||
await self._interrupt_turn(message)
|
||||
elif frame_type == "approval.respond":
|
||||
await self._resolve_approval(message)
|
||||
elif frame_type == "user-input.respond":
|
||||
await self._resolve_user_input(message)
|
||||
elif frame_type == "session.stop":
|
||||
await self._stop_session(message)
|
||||
elif frame_type == "ping":
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"pong",
|
||||
requestId=message["requestId"],
|
||||
sentAt=message.get("sentAt") or iso_now(),
|
||||
)
|
||||
)
|
||||
except ValueError as exc:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"unsupported-message",
|
||||
str(exc),
|
||||
recoverable=True,
|
||||
related_request_id=str(request) if request else None,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("T3 gateway command failed")
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"internal-error",
|
||||
str(exc) or type(exc).__name__,
|
||||
recoverable=True,
|
||||
related_request_id=str(request) if request else None,
|
||||
)
|
||||
)
|
||||
|
||||
async def _ensure_session(self, message: dict[str, Any]) -> None:
|
||||
thread_id = str(message["threadId"])
|
||||
source = self._source(thread_id, str(message["requestId"]))
|
||||
session_id = build_session_key(source)
|
||||
resume_id = str(message.get("resumeSessionId") or "")
|
||||
self._sessions[thread_id] = session_id
|
||||
self._active_session_threads.add(thread_id)
|
||||
self._thread_by_session[session_id] = thread_id
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"session.ready",
|
||||
requestId=message["requestId"],
|
||||
threadId=thread_id,
|
||||
sessionId=session_id,
|
||||
resumed=bool(resume_id and resume_id == session_id),
|
||||
)
|
||||
)
|
||||
await self._send_status()
|
||||
|
||||
async def _start_turn(self, message: dict[str, Any]) -> None:
|
||||
thread_id = str(message["threadId"])
|
||||
session_id = self._sessions.get(thread_id)
|
||||
if not session_id or session_id != str(message["sessionId"]):
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"session-not-found",
|
||||
"Call session.ensure before starting a turn.",
|
||||
recoverable=True,
|
||||
related_request_id=str(message["requestId"]),
|
||||
)
|
||||
)
|
||||
return
|
||||
if thread_id in self._active_turns:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"invalid-message",
|
||||
"This Hermes session already has an active turn; use turn.steer.",
|
||||
recoverable=True,
|
||||
related_request_id=str(message["requestId"]),
|
||||
)
|
||||
)
|
||||
return
|
||||
turn = _TurnState(
|
||||
thread_id=thread_id,
|
||||
session_id=session_id,
|
||||
turn_id=str(message["turnId"]),
|
||||
request_id=str(message["requestId"]),
|
||||
)
|
||||
self._active_turns[thread_id] = turn
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"turn.started",
|
||||
requestId=turn.request_id,
|
||||
threadId=thread_id,
|
||||
sessionId=session_id,
|
||||
turnId=turn.turn_id,
|
||||
)
|
||||
)
|
||||
await self._send_status()
|
||||
await self.handle_message(
|
||||
MessageEvent(
|
||||
text=str(message["text"]),
|
||||
message_type=(
|
||||
MessageType.COMMAND
|
||||
if str(message["text"]).lstrip().startswith("/")
|
||||
else MessageType.TEXT
|
||||
),
|
||||
source=self._source(thread_id, turn.request_id),
|
||||
message_id=turn.request_id,
|
||||
metadata={"t3_turn_id": turn.turn_id},
|
||||
)
|
||||
)
|
||||
|
||||
async def _steer_turn(self, message: dict[str, Any]) -> None:
|
||||
turn = self._active_turns.get(str(message["threadId"]))
|
||||
if turn is None or turn.turn_id != str(message["turnId"]):
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"turn-not-active",
|
||||
"The requested Hermes turn is no longer active.",
|
||||
recoverable=True,
|
||||
related_request_id=str(message["requestId"]),
|
||||
)
|
||||
)
|
||||
return
|
||||
# `/steer` is Hermes' official active-run injection surface. The base
|
||||
# adapter dispatches active slash commands inline, then sends the
|
||||
# command's textual acknowledgement back through this adapter with
|
||||
# `notify=True`. Capture that one command response by request context:
|
||||
# it is control traffic, not assistant output and not a turn boundary.
|
||||
control = _SteerControlResponse(
|
||||
thread_id=turn.thread_id,
|
||||
request_id=str(message["requestId"]),
|
||||
)
|
||||
context_token = _steer_control_response.set(control)
|
||||
command_error: Exception | None = None
|
||||
try:
|
||||
await self.handle_message(
|
||||
MessageEvent(
|
||||
text=f"/steer {message['text']}",
|
||||
message_type=MessageType.COMMAND,
|
||||
source=self._source(turn.thread_id, control.request_id),
|
||||
message_id=control.request_id,
|
||||
metadata={"t3_turn_id": turn.turn_id, "t3_steer": True},
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - translate command failures to the wire
|
||||
command_error = exc
|
||||
finally:
|
||||
_steer_control_response.reset(context_token)
|
||||
|
||||
if command_error is not None:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"internal-error",
|
||||
str(command_error) or "Hermes steering failed.",
|
||||
recoverable=True,
|
||||
related_request_id=control.request_id,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
response = control.messages[-1] if control.messages else ""
|
||||
if not response.startswith("⏩ Steer queued"):
|
||||
if response.startswith(("Agent still starting", "No active agent")):
|
||||
error_code = "turn-not-active"
|
||||
elif response.startswith("⚠️ Steer failed"):
|
||||
error_code = "internal-error"
|
||||
else:
|
||||
error_code = "invalid-message"
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
error_code,
|
||||
response or "Hermes did not acknowledge the steering request.",
|
||||
recoverable=True,
|
||||
related_request_id=control.request_id,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# Correlated command acknowledgement. It intentionally reuses the
|
||||
# existing turnId: this is not a second runtime turn. T3 consumes the
|
||||
# steering requestId as its broker acknowledgement and suppresses the
|
||||
# duplicate turn-start lifecycle projection.
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"turn.started",
|
||||
requestId=control.request_id,
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
)
|
||||
)
|
||||
|
||||
def _capture_steer_control_response(
|
||||
self,
|
||||
chat_id: str,
|
||||
content: str,
|
||||
) -> SendResult | None:
|
||||
control = _steer_control_response.get()
|
||||
if control is None or control.thread_id != str(chat_id):
|
||||
return None
|
||||
control.messages.append(str(content))
|
||||
return SendResult(
|
||||
success=True,
|
||||
message_id=f"t3-steer-control-{control.request_id}",
|
||||
)
|
||||
|
||||
async def _interrupt_turn(self, message: dict[str, Any]) -> None:
|
||||
thread_id = str(message["threadId"])
|
||||
turn = self._active_turns.get(thread_id)
|
||||
if turn is None or turn.turn_id != str(message["turnId"]):
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"turn-not-active",
|
||||
"The requested Hermes turn is no longer active.",
|
||||
recoverable=True,
|
||||
related_request_id=str(message["requestId"]),
|
||||
)
|
||||
)
|
||||
return
|
||||
await self.interrupt_session_activity(turn.session_id, thread_id)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"turn.aborted",
|
||||
threadId=thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
reason="Interrupted by T3 Code",
|
||||
)
|
||||
)
|
||||
self._active_turns.pop(thread_id, None)
|
||||
await self._send_status()
|
||||
|
||||
async def _resolve_approval(self, message: dict[str, Any]) -> None:
|
||||
request_id = str(message["requestId"])
|
||||
pending = self._approval_requests.pop(request_id, None)
|
||||
if pending is None:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"request-not-found",
|
||||
"The Hermes approval request is no longer pending.",
|
||||
recoverable=True,
|
||||
related_request_id=request_id,
|
||||
)
|
||||
)
|
||||
return
|
||||
session_key, _turn_id = pending
|
||||
decision = str(message["decision"])
|
||||
choice = {
|
||||
"accept": "once",
|
||||
"acceptForSession": "session",
|
||||
"decline": "deny",
|
||||
"cancel": "deny",
|
||||
}.get(decision, "deny")
|
||||
from tools.approval import resolve_gateway_approval
|
||||
|
||||
resolved = resolve_gateway_approval(session_key, choice)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"request.resolved",
|
||||
threadId=message["threadId"],
|
||||
sessionId=message["sessionId"],
|
||||
turnId=message["turnId"],
|
||||
requestId=request_id,
|
||||
requestType="command_execution_approval",
|
||||
decision=decision,
|
||||
resolution={"resolvedCount": resolved},
|
||||
)
|
||||
)
|
||||
|
||||
async def _resolve_user_input(self, message: dict[str, Any]) -> None:
|
||||
request_id = str(message["requestId"])
|
||||
pending = self._user_input_requests.pop(request_id, None)
|
||||
if pending is None:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"request-not-found",
|
||||
"The Hermes user-input request is no longer pending.",
|
||||
recoverable=True,
|
||||
related_request_id=request_id,
|
||||
)
|
||||
)
|
||||
return
|
||||
answers = message.get("answers") or {}
|
||||
answer = answers.get(request_id) if isinstance(answers, dict) else None
|
||||
if answer is None and isinstance(answers, dict) and answers:
|
||||
answer = next(iter(answers.values()))
|
||||
if isinstance(answer, list):
|
||||
response = ", ".join(str(value) for value in answer)
|
||||
else:
|
||||
response = str(answer or "")
|
||||
from tools.clarify_gateway import resolve_gateway_clarify
|
||||
|
||||
resolved = resolve_gateway_clarify(request_id, response)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"user-input.resolved",
|
||||
threadId=message["threadId"],
|
||||
sessionId=message["sessionId"],
|
||||
turnId=message["turnId"],
|
||||
requestId=request_id,
|
||||
answers=answers,
|
||||
)
|
||||
)
|
||||
if not resolved:
|
||||
logger.warning(
|
||||
"Hermes clarify request %s was no longer pending", request_id
|
||||
)
|
||||
|
||||
async def _stop_session(self, message: dict[str, Any]) -> None:
|
||||
thread_id = str(message["threadId"])
|
||||
session_id = self._sessions.get(thread_id)
|
||||
if session_id is None:
|
||||
await self._send_frame(
|
||||
protocol_error(
|
||||
"session-not-found",
|
||||
"The requested Hermes session is not active in this connection.",
|
||||
recoverable=True,
|
||||
related_request_id=str(message["requestId"]),
|
||||
)
|
||||
)
|
||||
return
|
||||
turn = self._active_turns.pop(thread_id, None)
|
||||
if turn is not None:
|
||||
await self.interrupt_session_activity(session_id, thread_id)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"turn.aborted",
|
||||
threadId=thread_id,
|
||||
sessionId=session_id,
|
||||
turnId=turn.turn_id,
|
||||
reason="Hermes session stopped by T3 Code",
|
||||
)
|
||||
)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"session.exited",
|
||||
threadId=thread_id,
|
||||
sessionId=session_id,
|
||||
reason="Stopped by T3 Code",
|
||||
recoverable=True,
|
||||
)
|
||||
)
|
||||
# Deliberately retain the deterministic mapping and Hermes transcript.
|
||||
# A later session.ensure resumes this same thread/session identity.
|
||||
self._active_session_threads.discard(thread_id)
|
||||
await self._send_status()
|
||||
|
||||
async def _emit_assistant_content(self, turn: _TurnState, content: str) -> None:
|
||||
visible = str(content or "").replace(" ▉", "").replace("▉", "")
|
||||
if not turn.assistant_started:
|
||||
turn.assistant_started = True
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"item.started",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
itemId=turn.message_id,
|
||||
itemType="assistant_message",
|
||||
status="inProgress",
|
||||
title="Hermes response",
|
||||
)
|
||||
)
|
||||
if visible.startswith(turn.visible_text):
|
||||
delta = visible[len(turn.visible_text) :]
|
||||
turn.visible_text = visible
|
||||
if delta:
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"content.delta",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
itemId=turn.message_id,
|
||||
streamKind="assistant_text",
|
||||
delta=delta,
|
||||
contentIndex=0,
|
||||
)
|
||||
)
|
||||
elif visible != turn.visible_text:
|
||||
# Hermes' public platform edit hook exposes cumulative rendered text,
|
||||
# but the v1 T3 delta contract has no replacement operation. Preserve
|
||||
# the valid prefix and report the rare rewrite as generic activity.
|
||||
await self._emit_generic_activity(
|
||||
turn, "Hermes revised already-streamed text; replacement is deferred."
|
||||
)
|
||||
|
||||
async def _complete_turn(self, turn: _TurnState) -> None:
|
||||
if self._active_turns.get(turn.thread_id) is not turn:
|
||||
return
|
||||
if turn.assistant_started:
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"item.completed",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
itemId=turn.message_id,
|
||||
itemType="assistant_message",
|
||||
status="completed",
|
||||
title="Hermes response",
|
||||
)
|
||||
)
|
||||
if turn.generic_activity_id is not None:
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"item.completed",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
itemId=turn.generic_activity_id,
|
||||
itemType="unknown",
|
||||
status="completed",
|
||||
title="Hermes activity",
|
||||
**(
|
||||
{"detail": turn.generic_activity_detail}
|
||||
if turn.generic_activity_detail
|
||||
else {}
|
||||
),
|
||||
)
|
||||
)
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"turn.completed",
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
state="completed",
|
||||
stopReason=None,
|
||||
)
|
||||
)
|
||||
self._active_turns.pop(turn.thread_id, None)
|
||||
await self._send_status()
|
||||
|
||||
async def _emit_generic_activity(self, turn: _TurnState, detail: str) -> None:
|
||||
if not detail:
|
||||
return
|
||||
normalized_detail = str(detail)[:2_000]
|
||||
if turn.generic_activity_detail == normalized_detail:
|
||||
return
|
||||
turn.generic_activity_detail = normalized_detail
|
||||
if turn.generic_activity_id is None:
|
||||
turn.generic_activity_id = item_id()
|
||||
event_type = "item.started"
|
||||
else:
|
||||
event_type = "item.updated"
|
||||
await self._send_frame(
|
||||
frame(
|
||||
event_type,
|
||||
threadId=turn.thread_id,
|
||||
sessionId=turn.session_id,
|
||||
turnId=turn.turn_id,
|
||||
itemId=turn.generic_activity_id,
|
||||
itemType="unknown",
|
||||
status="inProgress",
|
||||
title="Hermes activity",
|
||||
detail=normalized_detail,
|
||||
)
|
||||
)
|
||||
|
||||
def emit_tool_started(
|
||||
self,
|
||||
session_id: str,
|
||||
tool_name: str,
|
||||
args: dict[str, Any],
|
||||
tool_call_id: str = "",
|
||||
) -> None:
|
||||
thread_id = self._thread_by_session.get(str(session_id))
|
||||
turn = self._active_turns.get(thread_id or "")
|
||||
if turn is None:
|
||||
return
|
||||
tool_item_id = item_id()
|
||||
correlation_key = tool_call_id or tool_name
|
||||
turn.tool_items[correlation_key] = tool_item_id
|
||||
data = canonical_tool_data(tool_name, args)
|
||||
payload: dict[str, Any] = {
|
||||
"threadId": turn.thread_id,
|
||||
"sessionId": turn.session_id,
|
||||
"turnId": turn.turn_id,
|
||||
"itemId": tool_item_id,
|
||||
"itemType": canonical_tool_item_type(tool_name),
|
||||
"status": "inProgress",
|
||||
"title": tool_name,
|
||||
}
|
||||
if data is not None:
|
||||
payload["data"] = data
|
||||
self._schedule(
|
||||
self._send_frame(
|
||||
frame(
|
||||
"item.started",
|
||||
**payload,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def emit_tool_completed(
|
||||
self,
|
||||
session_id: str,
|
||||
tool_name: str,
|
||||
result: str,
|
||||
duration_ms: int | None,
|
||||
tool_call_id: str = "",
|
||||
status: str = "",
|
||||
) -> None:
|
||||
thread_id = self._thread_by_session.get(str(session_id))
|
||||
turn = self._active_turns.get(thread_id or "")
|
||||
if turn is None:
|
||||
return
|
||||
correlation_key = tool_call_id or tool_name
|
||||
tool_item_id = turn.tool_items.pop(correlation_key, None) or item_id()
|
||||
del result
|
||||
payload: dict[str, Any] = {
|
||||
"threadId": turn.thread_id,
|
||||
"sessionId": turn.session_id,
|
||||
"turnId": turn.turn_id,
|
||||
"itemId": tool_item_id,
|
||||
"itemType": canonical_tool_item_type(tool_name),
|
||||
"status": "failed" if status == "error" else "completed",
|
||||
"title": tool_name,
|
||||
}
|
||||
if duration_ms is not None:
|
||||
payload["detail"] = f"Completed in {duration_ms} ms"
|
||||
payload["data"] = {"durationMs": duration_ms}
|
||||
self._schedule(
|
||||
self._send_frame(
|
||||
frame(
|
||||
"item.completed",
|
||||
**payload,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def route_tool_started(
|
||||
cls,
|
||||
tool_name: str,
|
||||
args: dict[str, Any],
|
||||
session_id: str,
|
||||
tool_call_id: str = "",
|
||||
) -> None:
|
||||
for instance in list(cls._instances):
|
||||
instance.emit_tool_started(session_id, tool_name, args, tool_call_id)
|
||||
|
||||
@classmethod
|
||||
def route_tool_completed(
|
||||
cls,
|
||||
tool_name: str,
|
||||
result: str,
|
||||
session_id: str,
|
||||
duration_ms: int | None,
|
||||
tool_call_id: str = "",
|
||||
status: str = "",
|
||||
) -> None:
|
||||
for instance in list(cls._instances):
|
||||
instance.emit_tool_completed(
|
||||
session_id,
|
||||
tool_name,
|
||||
result,
|
||||
duration_ms,
|
||||
tool_call_id,
|
||||
status,
|
||||
)
|
||||
|
||||
def _source(self, thread_id: str, message_id: str):
|
||||
return self.build_source(
|
||||
chat_id=thread_id,
|
||||
chat_name=f"T3 thread {thread_id}",
|
||||
chat_type="dm",
|
||||
user_id="t3-code",
|
||||
user_name="T3 Code",
|
||||
message_id=message_id,
|
||||
)
|
||||
|
||||
async def _send_frame(self, message: dict[str, Any]) -> None:
|
||||
connection = self._connection
|
||||
if connection is None:
|
||||
raise ConnectionError("T3 Code gateway is offline")
|
||||
await connection.send(message)
|
||||
|
||||
async def _send_status(self) -> None:
|
||||
if self._connection is None or not self._connection.connected:
|
||||
return
|
||||
await self._send_frame(
|
||||
frame(
|
||||
"connection.status",
|
||||
activeSessionCount=len(self._active_session_threads),
|
||||
)
|
||||
)
|
||||
|
||||
async def _handle_connection_state(
|
||||
self, connected: bool, reason: str | None
|
||||
) -> None:
|
||||
if connected:
|
||||
self._mark_connected()
|
||||
await self._send_status()
|
||||
return
|
||||
self._mark_disconnected()
|
||||
if reason:
|
||||
logger.warning("T3 gateway offline: %s", reason)
|
||||
|
||||
def _schedule(self, coroutine) -> None:
|
||||
loop = self._event_loop
|
||||
if loop is None or loop.is_closed():
|
||||
coroutine.close()
|
||||
return
|
||||
if threading.current_thread() is threading.main_thread():
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
asyncio.run_coroutine_threadsafe(coroutine, loop)
|
||||
else:
|
||||
loop.create_task(coroutine)
|
||||
else:
|
||||
asyncio.run_coroutine_threadsafe(coroutine, loop)
|
||||
|
||||
|
||||
def check_requirements() -> bool:
|
||||
return dependency_available()
|
||||
|
||||
|
||||
def validate_config(config: PlatformConfig) -> bool:
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
return (
|
||||
bool(extra.get("url") or os.environ.get(URL_ENV, ""))
|
||||
and bool(extra.get("instance_id") or os.environ.get(INSTANCE_ID_ENV, ""))
|
||||
and bool(extra.get("credential") or os.environ.get(CREDENTIAL_ENV, ""))
|
||||
)
|
||||
|
||||
|
||||
def env_enablement() -> dict[str, str] | None:
|
||||
url = os.environ.get(URL_ENV, "").strip()
|
||||
instance_id = os.environ.get(INSTANCE_ID_ENV, "").strip()
|
||||
credential = os.environ.get(CREDENTIAL_ENV, "").strip()
|
||||
if not (url and instance_id and credential):
|
||||
return None
|
||||
return {
|
||||
"url": url,
|
||||
"instance_id": instance_id,
|
||||
"credential": credential,
|
||||
"nickname": os.environ.get(NICKNAME_ENV, "").strip() or "Hermes",
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""`hermes t3 connect` enrollment command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
from .connection import ConnectionRejected, enroll_once, websocket_url
|
||||
|
||||
URL_ENV = "HERMES_T3_GATEWAY_URL"
|
||||
INSTANCE_ID_ENV = "HERMES_T3_GATEWAY_INSTANCE_ID"
|
||||
CREDENTIAL_ENV = "HERMES_T3_GATEWAY_CREDENTIAL"
|
||||
NICKNAME_ENV = "HERMES_T3_GATEWAY_NICKNAME"
|
||||
|
||||
|
||||
def _hermes_version() -> str:
|
||||
try:
|
||||
from hermes_cli import __version__
|
||||
|
||||
return str(__version__)
|
||||
except Exception: # noqa: BLE001 - version discovery must not block enrollment
|
||||
return "unknown"
|
||||
|
||||
|
||||
def register_cli(parser: argparse.ArgumentParser) -> None:
|
||||
commands = parser.add_subparsers(dest="t3_command")
|
||||
connect = commands.add_parser(
|
||||
"connect",
|
||||
help="Pair this Hermes process with a named T3 Code provider instance",
|
||||
)
|
||||
connect.add_argument(
|
||||
"--url",
|
||||
required=True,
|
||||
help="T3 browser origin or explicit ws(s) gateway URL",
|
||||
)
|
||||
connect.add_argument(
|
||||
"--token",
|
||||
required=True,
|
||||
help="Short-lived, one-time enrollment token generated by T3 Code",
|
||||
)
|
||||
connect.set_defaults(func=t3_command)
|
||||
|
||||
status = commands.add_parser("status", help="Show local T3 enrollment state")
|
||||
status.set_defaults(func=t3_command)
|
||||
|
||||
|
||||
def t3_command(args) -> None:
|
||||
command = getattr(args, "t3_command", None)
|
||||
if command == "status":
|
||||
_print_status()
|
||||
return
|
||||
if command != "connect":
|
||||
print("Usage: hermes t3 connect --url <t3-url> --token <one-time-token>")
|
||||
return
|
||||
|
||||
url = str(getattr(args, "url", "") or "").strip()
|
||||
token = str(getattr(args, "token", "") or "").strip()
|
||||
try:
|
||||
normalized_url = websocket_url(url)
|
||||
accepted = asyncio.run(
|
||||
enroll_once(
|
||||
url=normalized_url,
|
||||
token=token,
|
||||
hermes_version=_hermes_version(),
|
||||
)
|
||||
)
|
||||
except ConnectionRejected as exc:
|
||||
print(f"✗ T3 enrollment rejected ({exc.code}): {exc}")
|
||||
raise SystemExit(1) from exc
|
||||
except Exception as exc:
|
||||
print(f"✗ Could not enroll with T3 Code: {exc}")
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
values = {
|
||||
URL_ENV: normalized_url,
|
||||
INSTANCE_ID_ENV: str(accepted["instanceId"]),
|
||||
CREDENTIAL_ENV: str(accepted["credential"]),
|
||||
NICKNAME_ENV: str(accepted.get("nickname") or "Hermes"),
|
||||
}
|
||||
try:
|
||||
from hermes_cli.config import get_env_path, save_env_value
|
||||
|
||||
for key, value in values.items():
|
||||
save_env_value(key, value)
|
||||
env_path = get_env_path()
|
||||
except Exception as exc:
|
||||
print(f"✗ Enrollment succeeded, but credentials could not be saved: {exc}")
|
||||
print(" The credential was not printed. Revoke and re-enroll this instance.")
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
# Mirror the newly written values into this process for status output and
|
||||
# tests. A running gateway still needs a restart to construct the adapter.
|
||||
os.environ.update(values)
|
||||
print(f'✓ Connected Hermes to T3 Code as "{values[NICKNAME_ENV]}"')
|
||||
print(f" Instance: {values[INSTANCE_ID_ENV]}")
|
||||
print(f" Gateway: {normalized_url}")
|
||||
print(f" Saved the credential securely in {env_path} (value hidden).")
|
||||
print(" Restart `hermes gateway` to activate the connection.")
|
||||
|
||||
|
||||
def _print_status() -> None:
|
||||
url = os.environ.get(URL_ENV, "").strip()
|
||||
instance_id = os.environ.get(INSTANCE_ID_ENV, "").strip()
|
||||
credential = os.environ.get(CREDENTIAL_ENV, "").strip()
|
||||
nickname = os.environ.get(NICKNAME_ENV, "").strip() or "Hermes"
|
||||
if not (url and instance_id and credential):
|
||||
print("T3 Code: not enrolled")
|
||||
print("Run: hermes t3 connect --url <t3-url> --token <one-time-token>")
|
||||
return
|
||||
print(f"T3 Code: enrolled as {nickname}")
|
||||
print(f" Instance: {instance_id}")
|
||||
print(f" Gateway: {url}")
|
||||
print(" Credential: configured (hidden)")
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover - executable fallback
|
||||
parser = argparse.ArgumentParser(prog="python -m hermes_t3_gateway.cli")
|
||||
register_cli(parser)
|
||||
parsed = parser.parse_args()
|
||||
if not hasattr(parsed, "func"):
|
||||
parser.print_help()
|
||||
sys.exit(2)
|
||||
parsed.func(parsed)
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Outbound authenticated WebSocket connection to a T3 Code server."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from .protocol import WEBSOCKET_PATH, connection_hello
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
import websockets
|
||||
except ImportError: # pragma: no cover - Hermes currently installs websockets
|
||||
websockets = None
|
||||
|
||||
MessageHandler = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
StateHandler = Callable[[bool, str | None], Awaitable[None] | None]
|
||||
|
||||
|
||||
class ConnectionRejected(RuntimeError):
|
||||
def __init__(self, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def websocket_url(url: str) -> str:
|
||||
"""Normalize an HTTP(S) browser origin or WS(S) URL to the gateway route."""
|
||||
raw = (url or "").strip()
|
||||
parsed = urlsplit(raw)
|
||||
scheme = parsed.scheme.lower()
|
||||
if scheme == "https":
|
||||
scheme = "wss"
|
||||
elif scheme == "http":
|
||||
scheme = "ws"
|
||||
if scheme not in {"ws", "wss"} or not parsed.netloc:
|
||||
raise ValueError("URL must use http://, https://, ws://, or wss://")
|
||||
path = parsed.path.rstrip("/")
|
||||
if path != WEBSOCKET_PATH:
|
||||
path = WEBSOCKET_PATH
|
||||
return urlunsplit((scheme, parsed.netloc, path, "", ""))
|
||||
|
||||
|
||||
def dependency_available() -> bool:
|
||||
return websockets is not None
|
||||
|
||||
|
||||
async def _open_socket(url: str):
|
||||
if websockets is None:
|
||||
raise RuntimeError(
|
||||
"The `websockets` package is unavailable. Install the standard "
|
||||
"Hermes Agent dependencies and retry."
|
||||
)
|
||||
return await websockets.connect( # type: ignore[union-attr]
|
||||
websocket_url(url),
|
||||
open_timeout=20,
|
||||
ping_interval=20,
|
||||
ping_timeout=20,
|
||||
close_timeout=5,
|
||||
max_size=2 * 1024 * 1024,
|
||||
)
|
||||
|
||||
|
||||
async def authenticate_socket(
|
||||
socket: Any,
|
||||
*,
|
||||
authentication: dict[str, str],
|
||||
hermes_version: str,
|
||||
timeout: float = 20,
|
||||
) -> dict[str, Any]:
|
||||
hello = connection_hello(
|
||||
hermes_version=hermes_version,
|
||||
authentication=authentication,
|
||||
)
|
||||
await socket.send(json.dumps(hello, separators=(",", ":"), ensure_ascii=False))
|
||||
raw = await asyncio.wait_for(socket.recv(), timeout=timeout)
|
||||
message = json.loads(raw)
|
||||
if not isinstance(message, dict):
|
||||
raise TypeError("T3 returned a non-object handshake frame")
|
||||
if message.get("requestId") != hello["requestId"]:
|
||||
raise RuntimeError("T3 returned a handshake with an unexpected requestId")
|
||||
if message.get("type") == "connection.rejected":
|
||||
raise ConnectionRejected(
|
||||
str(message.get("code") or "internal-error"),
|
||||
str(message.get("message") or "T3 rejected the gateway connection"),
|
||||
)
|
||||
if message.get("type") != "connection.accepted":
|
||||
raise RuntimeError(
|
||||
f"expected connection.accepted, received {message.get('type')!r}"
|
||||
)
|
||||
if message.get("protocolVersion") != 1:
|
||||
raise RuntimeError("T3 accepted the connection with an incompatible version")
|
||||
return message
|
||||
|
||||
|
||||
async def enroll_once(
|
||||
*,
|
||||
url: str,
|
||||
token: str,
|
||||
hermes_version: str,
|
||||
) -> dict[str, Any]:
|
||||
socket = await _open_socket(url)
|
||||
try:
|
||||
accepted = await authenticate_socket(
|
||||
socket,
|
||||
authentication={"type": "enrollment-token", "token": token},
|
||||
hermes_version=hermes_version,
|
||||
)
|
||||
if not accepted.get("instanceId") or not accepted.get("credential"):
|
||||
raise RuntimeError(
|
||||
"T3 accepted enrollment without returning an instance credential"
|
||||
)
|
||||
return accepted
|
||||
finally:
|
||||
await socket.close()
|
||||
|
||||
|
||||
class T3GatewayConnection:
|
||||
"""Reconnectable runtime connection authenticated by an instance credential."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
url: str,
|
||||
instance_id: str,
|
||||
credential: str,
|
||||
hermes_version: str,
|
||||
on_message: MessageHandler,
|
||||
on_state: StateHandler | None = None,
|
||||
):
|
||||
self.url = websocket_url(url)
|
||||
self.instance_id = instance_id
|
||||
self.credential = credential
|
||||
self.hermes_version = hermes_version
|
||||
self._on_message = on_message
|
||||
self._on_state = on_state
|
||||
self._socket: Any = None
|
||||
self._supervisor: asyncio.Task[None] | None = None
|
||||
self._send_lock = asyncio.Lock()
|
||||
self._connected = asyncio.Event()
|
||||
self._first_result: asyncio.Future[bool] | None = None
|
||||
self._stopping = False
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return self._connected.is_set()
|
||||
|
||||
async def connect(self, timeout: float = 30) -> bool:
|
||||
if self._supervisor is not None and not self._supervisor.done():
|
||||
return self.connected
|
||||
self._stopping = False
|
||||
self._first_result = asyncio.get_running_loop().create_future()
|
||||
self._supervisor = asyncio.create_task(
|
||||
self._supervise(), name="hermes-t3-gateway"
|
||||
)
|
||||
try:
|
||||
return await asyncio.wait_for(asyncio.shield(self._first_result), timeout)
|
||||
except TimeoutError:
|
||||
await self.disconnect()
|
||||
return False
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self._stopping = True
|
||||
self._connected.clear()
|
||||
if self._socket is not None:
|
||||
with suppress(Exception):
|
||||
await self._socket.close()
|
||||
self._socket = None
|
||||
if self._supervisor is not None:
|
||||
self._supervisor.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._supervisor
|
||||
self._supervisor = None
|
||||
await self._notify_state(False, None)
|
||||
|
||||
async def send(self, message: dict[str, Any]) -> None:
|
||||
if not self.connected or self._socket is None:
|
||||
raise ConnectionError("T3 Code gateway is offline")
|
||||
encoded = json.dumps(message, separators=(",", ":"), ensure_ascii=False)
|
||||
async with self._send_lock:
|
||||
await self._socket.send(encoded)
|
||||
|
||||
async def _supervise(self) -> None:
|
||||
delay = 1.0
|
||||
while not self._stopping:
|
||||
reason: str | None = None
|
||||
try:
|
||||
socket = await _open_socket(self.url)
|
||||
self._socket = socket
|
||||
await authenticate_socket(
|
||||
socket,
|
||||
authentication={
|
||||
"type": "instance-credential",
|
||||
"instanceId": self.instance_id,
|
||||
"credential": self.credential,
|
||||
},
|
||||
hermes_version=self.hermes_version,
|
||||
)
|
||||
self._connected.set()
|
||||
if self._first_result is not None and not self._first_result.done():
|
||||
self._first_result.set_result(True)
|
||||
await self._notify_state(True, None)
|
||||
delay = 1.0
|
||||
async for raw in socket:
|
||||
message = json.loads(raw)
|
||||
if isinstance(message, dict):
|
||||
await self._on_message(message)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except ConnectionRejected as exc:
|
||||
reason = f"{exc.code}: {exc}"
|
||||
if self._first_result is not None and not self._first_result.done():
|
||||
self._first_result.set_exception(exc)
|
||||
# Revoked credentials and version mismatches need operator
|
||||
# action; reconnecting the same secret can never recover.
|
||||
if exc.code in {
|
||||
"instance-revoked",
|
||||
"invalid-authentication",
|
||||
"version-incompatible",
|
||||
}:
|
||||
self._stopping = True
|
||||
except Exception as exc: # noqa: BLE001 - reconnect every transient transport failure
|
||||
reason = str(exc)
|
||||
logger.warning("T3 gateway connection dropped: %s", exc)
|
||||
finally:
|
||||
self._connected.clear()
|
||||
self._socket = None
|
||||
await self._notify_state(False, reason)
|
||||
if self._stopping:
|
||||
break
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 30.0)
|
||||
|
||||
async def _notify_state(self, connected: bool, reason: str | None) -> None:
|
||||
if self._on_state is None:
|
||||
return
|
||||
try:
|
||||
result = self._on_state(connected, reason)
|
||||
if asyncio.iscoroutine(result):
|
||||
await result
|
||||
except Exception:
|
||||
logger.debug("T3 connection state callback failed", exc_info=True)
|
||||
@@ -0,0 +1,24 @@
|
||||
name: hermes-t3-gateway
|
||||
label: T3 Code
|
||||
kind: platform
|
||||
version: 0.1.0
|
||||
description: >
|
||||
Experimental outbound gateway that exposes one Hermes Agent process as a
|
||||
named T3 Code provider instance over an authenticated WebSocket.
|
||||
author: T3 Tools
|
||||
provides_hooks:
|
||||
- pre_tool_call
|
||||
- post_tool_call
|
||||
optional_env:
|
||||
- name: HERMES_T3_GATEWAY_URL
|
||||
description: "T3 Code server URL used by the outbound gateway connection"
|
||||
prompt: "T3 Code URL"
|
||||
password: false
|
||||
- name: HERMES_T3_GATEWAY_INSTANCE_ID
|
||||
description: "Opaque T3 Code Hermes instance identifier issued at enrollment"
|
||||
prompt: "T3 Code Hermes instance ID"
|
||||
password: false
|
||||
- name: HERMES_T3_GATEWAY_CREDENTIAL
|
||||
description: "Long-lived per-instance credential issued at enrollment"
|
||||
prompt: "T3 Code Hermes credential"
|
||||
password: true
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Pure-Python helpers for the T3 Code ↔ Hermes gateway wire contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
PROTOCOL_VERSION = 1
|
||||
PLUGIN_VERSION = "0.1.0"
|
||||
WEBSOCKET_PATH = "/api/hermes-gateway/ws"
|
||||
|
||||
CAPABILITIES = {
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"streaming": True,
|
||||
"activity": True,
|
||||
"approvals": True,
|
||||
"userInput": True,
|
||||
# First post-stability feature: advertise false until binary/media framing
|
||||
# and bounded attachment transfer are implemented end to end.
|
||||
"attachments": False,
|
||||
}
|
||||
|
||||
SERVER_COMMANDS = frozenset(
|
||||
{
|
||||
"session.ensure",
|
||||
"turn.start",
|
||||
"turn.steer",
|
||||
"turn.interrupt",
|
||||
"approval.respond",
|
||||
"user-input.respond",
|
||||
"session.stop",
|
||||
"ping",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def request_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def item_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def iso_now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def frame(frame_type: str, **payload: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"type": frame_type,
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
**payload,
|
||||
}
|
||||
|
||||
|
||||
def connection_hello(
|
||||
*,
|
||||
hermes_version: str,
|
||||
authentication: dict[str, str],
|
||||
hello_request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"type": "connection.hello",
|
||||
"requestId": hello_request_id or request_id(),
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"pluginVersion": PLUGIN_VERSION,
|
||||
"hermesVersion": hermes_version,
|
||||
"capabilities": dict(CAPABILITIES),
|
||||
"authentication": authentication,
|
||||
}
|
||||
|
||||
|
||||
def protocol_error(
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
recoverable: bool,
|
||||
related_request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"recoverable": recoverable,
|
||||
}
|
||||
if related_request_id:
|
||||
payload["requestId"] = related_request_id
|
||||
return frame("protocol.error", **payload)
|
||||
|
||||
|
||||
def validate_server_frame(message: Any) -> dict[str, Any]:
|
||||
if not isinstance(message, dict):
|
||||
raise TypeError("gateway frame must be a JSON object")
|
||||
frame_type = message.get("type")
|
||||
if frame_type not in SERVER_COMMANDS:
|
||||
raise ValueError(f"unsupported T3 gateway frame: {frame_type!r}")
|
||||
if message.get("protocolVersion") != PROTOCOL_VERSION:
|
||||
raise ValueError(
|
||||
f"unsupported protocol version: {message.get('protocolVersion')!r}"
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
def canonical_tool_item_type(tool_name: str) -> str:
|
||||
normalized = (tool_name or "").strip().lower()
|
||||
if normalized in {"terminal", "execute_code", "shell", "bash"}:
|
||||
return "command_execution"
|
||||
if normalized in {
|
||||
"apply_patch",
|
||||
"write_file",
|
||||
"edit_file",
|
||||
"delete_file",
|
||||
"move_file",
|
||||
}:
|
||||
return "file_change"
|
||||
if normalized.startswith(("mcp", "mcp__")):
|
||||
return "mcp_tool_call"
|
||||
if normalized in {"delegate_task", "spawn_agent", "send_message"}:
|
||||
return "collab_agent_tool_call"
|
||||
if "search" in normalized or normalized in {"web_fetch", "fetch_url"}:
|
||||
return "web_search"
|
||||
if normalized in {"view_image", "open_image"}:
|
||||
return "image_view"
|
||||
return "dynamic_tool_call"
|
||||
|
||||
|
||||
def canonical_tool_data(tool_name: str, args: Any) -> dict[str, Any] | None:
|
||||
"""Project known-safe, canonical fields; never forward arbitrary tool args."""
|
||||
if not isinstance(args, dict):
|
||||
return None
|
||||
item_type = canonical_tool_item_type(tool_name)
|
||||
if item_type == "command_execution":
|
||||
command = args.get("command")
|
||||
cwd = args.get("cwd") or args.get("workdir")
|
||||
projected = {}
|
||||
if isinstance(command, str) and command.strip():
|
||||
projected["command"] = command[:4_000]
|
||||
if isinstance(cwd, str) and cwd.strip():
|
||||
projected["cwd"] = cwd[:1_000]
|
||||
return projected or None
|
||||
if item_type == "file_change":
|
||||
path = args.get("path") or args.get("file_path") or args.get("filename")
|
||||
return (
|
||||
{"path": path[:1_000]} if isinstance(path, str) and path.strip() else None
|
||||
)
|
||||
if item_type == "web_search":
|
||||
query = args.get("query") or args.get("q") or args.get("url")
|
||||
return (
|
||||
{"query": query[:2_000]}
|
||||
if isinstance(query, str) and query.strip()
|
||||
else None
|
||||
)
|
||||
if item_type == "image_view":
|
||||
path = args.get("path") or args.get("image_path")
|
||||
return (
|
||||
{"path": path[:1_000]} if isinstance(path, str) and path.strip() else None
|
||||
)
|
||||
if item_type == "mcp_tool_call":
|
||||
server = args.get("server")
|
||||
operation = args.get("tool") or args.get("operation")
|
||||
projected = {}
|
||||
if isinstance(server, str) and server.strip():
|
||||
projected["server"] = server[:200]
|
||||
if isinstance(operation, str) and operation.strip():
|
||||
projected["operation"] = operation[:200]
|
||||
return projected or None
|
||||
return None
|
||||
@@ -0,0 +1,411 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import enum
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
PACKAGE = "hermes_t3_gateway_adapter_test"
|
||||
|
||||
|
||||
class Platform(str, enum.Enum):
|
||||
T3 = "t3"
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value):
|
||||
if value == "t3":
|
||||
return cls.T3
|
||||
return None
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class PlatformConfig:
|
||||
enabled: bool = True
|
||||
extra: dict = dataclasses.field(default_factory=dict)
|
||||
|
||||
|
||||
class MessageType(enum.Enum):
|
||||
TEXT = "text"
|
||||
COMMAND = "command"
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class MessageEvent:
|
||||
text: str
|
||||
message_type: MessageType
|
||||
source: object
|
||||
message_id: str
|
||||
metadata: dict
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class SendResult:
|
||||
success: bool
|
||||
message_id: str | None = None
|
||||
error: str | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Source:
|
||||
platform: Platform
|
||||
chat_id: str
|
||||
message_id: str
|
||||
|
||||
|
||||
class BasePlatformAdapter:
|
||||
def __init__(self, config, platform):
|
||||
self.config = config
|
||||
self.platform = platform
|
||||
self._status_text = {}
|
||||
self.messages = []
|
||||
self._running = False
|
||||
self._message_handler = None
|
||||
|
||||
def build_source(self, *, chat_id, message_id, **kwargs):
|
||||
return Source(self.platform, str(chat_id), str(message_id))
|
||||
|
||||
async def handle_message(self, event):
|
||||
self.messages.append(event)
|
||||
if (
|
||||
self._message_handler is not None
|
||||
and event.message_type == MessageType.COMMAND
|
||||
and event.text.startswith("/steer ")
|
||||
):
|
||||
# Faithful model of Hermes BasePlatformAdapter's active-command
|
||||
# path: the gateway handler returns a control acknowledgement,
|
||||
# then BasePlatformAdapter sends it through the platform adapter
|
||||
# with notify=True.
|
||||
response = await self._message_handler(event)
|
||||
if response:
|
||||
await self.send(
|
||||
event.source.chat_id,
|
||||
response,
|
||||
metadata={"notify": True},
|
||||
)
|
||||
|
||||
async def interrupt_session_activity(self, session_key, chat_id):
|
||||
self.interrupted = (session_key, chat_id)
|
||||
|
||||
def set_status_text(self, chat_id, text):
|
||||
if text:
|
||||
self._status_text[str(chat_id)] = text
|
||||
else:
|
||||
self._status_text.pop(str(chat_id), None)
|
||||
|
||||
def _mark_connected(self):
|
||||
self._running = True
|
||||
|
||||
def _mark_disconnected(self):
|
||||
self._running = False
|
||||
|
||||
def _set_fatal_error(self, *args, **kwargs):
|
||||
self.fatal_error = (args, kwargs)
|
||||
|
||||
|
||||
def build_session_key(source):
|
||||
return f"agent:main:t3:dm:{source.chat_id}"
|
||||
|
||||
|
||||
def install_fake_hermes_modules():
|
||||
gateway = types.ModuleType("gateway")
|
||||
config = types.ModuleType("gateway.config")
|
||||
config.Platform = Platform
|
||||
config.PlatformConfig = PlatformConfig
|
||||
platforms = types.ModuleType("gateway.platforms")
|
||||
base = types.ModuleType("gateway.platforms.base")
|
||||
base.BasePlatformAdapter = BasePlatformAdapter
|
||||
base.MessageEvent = MessageEvent
|
||||
base.MessageType = MessageType
|
||||
base.SendResult = SendResult
|
||||
session = types.ModuleType("gateway.session")
|
||||
session.build_session_key = build_session_key
|
||||
sys.modules.update(
|
||||
{
|
||||
"gateway": gateway,
|
||||
"gateway.config": config,
|
||||
"gateway.platforms": platforms,
|
||||
"gateway.platforms.base": base,
|
||||
"gateway.session": session,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def load_plugin_modules():
|
||||
install_fake_hermes_modules()
|
||||
package = types.ModuleType(PACKAGE)
|
||||
package.__path__ = [str(ROOT)]
|
||||
sys.modules[PACKAGE] = package
|
||||
for name in ("protocol", "connection", "cli", "adapter"):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
f"{PACKAGE}.{name}", ROOT / f"{name}.py"
|
||||
)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[f"{PACKAGE}.{name}"] = module
|
||||
spec.loader.exec_module(module)
|
||||
return sys.modules[f"{PACKAGE}.adapter"]
|
||||
|
||||
|
||||
adapter_module = load_plugin_modules()
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.connected = True
|
||||
self.messages = []
|
||||
|
||||
async def send(self, message):
|
||||
self.messages.append(message)
|
||||
|
||||
|
||||
class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.adapter = adapter_module.T3PlatformAdapter(
|
||||
PlatformConfig(
|
||||
extra={
|
||||
"url": "wss://t3.example/api/hermes-gateway/ws",
|
||||
"instance_id": "instance",
|
||||
"credential": "credential",
|
||||
}
|
||||
)
|
||||
)
|
||||
self.connection = FakeConnection()
|
||||
self.adapter._connection = self.connection
|
||||
|
||||
async def test_thread_ensure_start_stream_and_complete(self):
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.ensure",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "ensure-1",
|
||||
"threadId": "thread-1",
|
||||
}
|
||||
)
|
||||
ready = self.connection.messages[-2]
|
||||
self.assertEqual(ready["type"], "session.ready")
|
||||
self.assertEqual(ready["sessionId"], "agent:main:t3:dm:thread-1")
|
||||
self.assertEqual(self.connection.messages[-1]["activeSessionCount"], 1)
|
||||
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.start",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "start-1",
|
||||
"threadId": "thread-1",
|
||||
"sessionId": ready["sessionId"],
|
||||
"turnId": "turn-1",
|
||||
"text": "Hello Hermes",
|
||||
}
|
||||
)
|
||||
self.assertEqual(self.adapter.messages[-1].text, "Hello Hermes")
|
||||
await self.adapter.send("thread-1", "Hello", metadata={"expect_edits": True})
|
||||
await self.adapter.edit_message(
|
||||
"thread-1", "message", "Hello world", finalize=True
|
||||
)
|
||||
types_seen = [message["type"] for message in self.connection.messages]
|
||||
self.assertIn("content.delta", types_seen)
|
||||
self.assertIn("turn.completed", types_seen)
|
||||
deltas = [
|
||||
message["delta"]
|
||||
for message in self.connection.messages
|
||||
if message["type"] == "content.delta"
|
||||
]
|
||||
self.assertEqual(deltas, ["Hello", " world"])
|
||||
|
||||
async def test_steer_uses_official_hermes_command(self):
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.ensure",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "ensure-2",
|
||||
"threadId": "thread-2",
|
||||
}
|
||||
)
|
||||
session_id = self.adapter._sessions["thread-2"]
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.start",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "start-2",
|
||||
"threadId": "thread-2",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-2",
|
||||
"text": "Start",
|
||||
}
|
||||
)
|
||||
messages_before_steer = len(self.connection.messages)
|
||||
|
||||
async def accept_steer(_event):
|
||||
return (
|
||||
"⏩ Steer queued — arrives after the next tool call: 'Focus on tests'"
|
||||
)
|
||||
|
||||
self.adapter._message_handler = accept_steer
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.steer",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "steer-2",
|
||||
"threadId": "thread-2",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-2",
|
||||
"text": "Focus on tests",
|
||||
}
|
||||
)
|
||||
self.assertEqual(self.adapter.messages[-1].text, "/steer Focus on tests")
|
||||
self.assertEqual(self.adapter.messages[-1].message_type, MessageType.COMMAND)
|
||||
steer_messages = self.connection.messages[messages_before_steer:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in steer_messages], ["turn.started"]
|
||||
)
|
||||
self.assertEqual(steer_messages[0]["requestId"], "steer-2")
|
||||
self.assertIn("thread-2", self.adapter._active_turns)
|
||||
|
||||
await self.adapter.edit_message(
|
||||
"thread-2",
|
||||
"message",
|
||||
"Actual response after steering",
|
||||
finalize=True,
|
||||
)
|
||||
deltas = [
|
||||
message["delta"]
|
||||
for message in self.connection.messages
|
||||
if message["type"] == "content.delta"
|
||||
]
|
||||
self.assertEqual(deltas, ["Actual response after steering"])
|
||||
self.assertNotIn("thread-2", self.adapter._active_turns)
|
||||
|
||||
async def test_rejected_steer_emits_error_without_completing_active_turn(self):
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.ensure",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "ensure-rejected-steer",
|
||||
"threadId": "thread-rejected-steer",
|
||||
}
|
||||
)
|
||||
session_id = self.adapter._sessions["thread-rejected-steer"]
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.start",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "start-rejected-steer",
|
||||
"threadId": "thread-rejected-steer",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-rejected-steer",
|
||||
"text": "Start",
|
||||
}
|
||||
)
|
||||
messages_before_steer = len(self.connection.messages)
|
||||
|
||||
async def reject_steer(_event):
|
||||
return "Steer rejected (empty payload)."
|
||||
|
||||
self.adapter._message_handler = reject_steer
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.steer",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "steer-rejected",
|
||||
"threadId": "thread-rejected-steer",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-rejected-steer",
|
||||
"text": "Focus on tests",
|
||||
}
|
||||
)
|
||||
|
||||
steer_messages = self.connection.messages[messages_before_steer:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in steer_messages], ["protocol.error"]
|
||||
)
|
||||
self.assertEqual(steer_messages[0]["requestId"], "steer-rejected")
|
||||
self.assertEqual(steer_messages[0]["code"], "invalid-message")
|
||||
self.assertIn("thread-rejected-steer", self.adapter._active_turns)
|
||||
|
||||
await self.adapter.edit_message(
|
||||
"thread-rejected-steer",
|
||||
"message",
|
||||
"Actual response after rejected steering",
|
||||
finalize=True,
|
||||
)
|
||||
self.assertEqual(self.connection.messages[-1]["type"], "connection.status")
|
||||
self.assertNotIn("thread-rejected-steer", self.adapter._active_turns)
|
||||
|
||||
async def test_failed_steer_emits_correlated_internal_error(self):
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.ensure",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "ensure-failed-steer",
|
||||
"threadId": "thread-failed-steer",
|
||||
}
|
||||
)
|
||||
session_id = self.adapter._sessions["thread-failed-steer"]
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.start",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "start-failed-steer",
|
||||
"threadId": "thread-failed-steer",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-failed-steer",
|
||||
"text": "Start",
|
||||
}
|
||||
)
|
||||
messages_before_steer = len(self.connection.messages)
|
||||
|
||||
async def fail_steer(_event):
|
||||
raise RuntimeError("running agent rejected steering")
|
||||
|
||||
self.adapter._message_handler = fail_steer
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "turn.steer",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "steer-failed",
|
||||
"threadId": "thread-failed-steer",
|
||||
"sessionId": session_id,
|
||||
"turnId": "turn-failed-steer",
|
||||
"text": "Focus on tests",
|
||||
}
|
||||
)
|
||||
|
||||
steer_messages = self.connection.messages[messages_before_steer:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in steer_messages], ["protocol.error"]
|
||||
)
|
||||
self.assertEqual(steer_messages[0]["requestId"], "steer-failed")
|
||||
self.assertEqual(steer_messages[0]["code"], "internal-error")
|
||||
self.assertIn("thread-failed-steer", self.adapter._active_turns)
|
||||
|
||||
async def test_session_status_counts_ready_sessions_and_stop_decrements(self):
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.ensure",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "ensure-3",
|
||||
"threadId": "thread-3",
|
||||
}
|
||||
)
|
||||
session_id = self.adapter._sessions["thread-3"]
|
||||
self.assertEqual(self.connection.messages[-1]["activeSessionCount"], 1)
|
||||
await self.adapter._handle_server_frame(
|
||||
{
|
||||
"type": "session.stop",
|
||||
"protocolVersion": 1,
|
||||
"requestId": "stop-3",
|
||||
"threadId": "thread-3",
|
||||
"sessionId": session_id,
|
||||
}
|
||||
)
|
||||
self.assertEqual(self.connection.messages[-1]["type"], "connection.status")
|
||||
self.assertEqual(self.connection.messages[-1]["activeSessionCount"], 0)
|
||||
self.assertEqual(self.adapter._sessions["thread-3"], session_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
PACKAGE = "hermes_t3_gateway_test"
|
||||
|
||||
package = types.ModuleType(PACKAGE)
|
||||
package.__path__ = [str(ROOT)]
|
||||
sys.modules.setdefault(PACKAGE, package)
|
||||
|
||||
for name in ("protocol", "connection"):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
f"{PACKAGE}.{name}", ROOT / f"{name}.py"
|
||||
)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[f"{PACKAGE}.{name}"] = module
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
connection = sys.modules[f"{PACKAGE}.connection"]
|
||||
|
||||
|
||||
class FakeSocket:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
|
||||
async def send(self, value):
|
||||
self.sent.append(json.loads(value))
|
||||
|
||||
async def recv(self):
|
||||
request_id = self.sent[0]["requestId"]
|
||||
return json.dumps({**self.response, "requestId": request_id})
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class ConnectionTests(unittest.IsolatedAsyncioTestCase):
|
||||
def test_url_normalization(self):
|
||||
self.assertEqual(
|
||||
connection.websocket_url("https://t3.example"),
|
||||
"wss://t3.example/api/hermes-gateway/ws",
|
||||
)
|
||||
self.assertEqual(
|
||||
connection.websocket_url("http://siva.davis7.space:8484/"),
|
||||
"ws://siva.davis7.space:8484/api/hermes-gateway/ws",
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
connection.websocket_url("ftp://invalid.example")
|
||||
|
||||
async def test_enrollment_handshake_returns_credential(self):
|
||||
socket = FakeSocket(
|
||||
{
|
||||
"type": "connection.accepted",
|
||||
"protocolVersion": 1,
|
||||
"instanceId": "provider-instance",
|
||||
"nickname": "Research",
|
||||
"credential": "persistent-secret",
|
||||
}
|
||||
)
|
||||
accepted = await connection.authenticate_socket(
|
||||
socket,
|
||||
authentication={"type": "enrollment-token", "token": "once"},
|
||||
hermes_version="0.19.0",
|
||||
)
|
||||
self.assertEqual(accepted["credential"], "persistent-secret")
|
||||
self.assertEqual(
|
||||
socket.sent[0]["authentication"],
|
||||
{"type": "enrollment-token", "token": "once"},
|
||||
)
|
||||
|
||||
async def test_rejected_handshake_fails_closed(self):
|
||||
socket = FakeSocket(
|
||||
{
|
||||
"type": "connection.rejected",
|
||||
"code": "version-incompatible",
|
||||
"message": "upgrade required",
|
||||
"expectedProtocolVersion": 1,
|
||||
}
|
||||
)
|
||||
with self.assertRaises(connection.ConnectionRejected) as raised:
|
||||
await connection.authenticate_socket(
|
||||
socket,
|
||||
authentication={
|
||||
"type": "instance-credential",
|
||||
"instanceId": "provider-instance",
|
||||
"credential": "secret",
|
||||
},
|
||||
hermes_version="0.19.0",
|
||||
)
|
||||
self.assertEqual(raised.exception.code, "version-incompatible")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"t3_gateway_protocol", ROOT / "protocol.py"
|
||||
)
|
||||
assert SPEC and SPEC.loader
|
||||
protocol = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(protocol)
|
||||
|
||||
|
||||
class ProtocolTests(unittest.TestCase):
|
||||
def test_hello_matches_v1_contract(self):
|
||||
hello = protocol.connection_hello(
|
||||
hermes_version="0.19.0",
|
||||
authentication={"type": "enrollment-token", "token": "once"},
|
||||
hello_request_id="request-1",
|
||||
)
|
||||
self.assertEqual(hello["type"], "connection.hello")
|
||||
self.assertEqual(hello["requestId"], "request-1")
|
||||
self.assertEqual(hello["protocolVersion"], 1)
|
||||
self.assertFalse(hello["capabilities"]["attachments"])
|
||||
self.assertTrue(hello["capabilities"]["streaming"])
|
||||
|
||||
def test_server_frame_validation_is_closed(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported"):
|
||||
protocol.validate_server_frame({"type": "made.up", "protocolVersion": 1})
|
||||
with self.assertRaisesRegex(ValueError, "version"):
|
||||
protocol.validate_server_frame({"type": "ping", "protocolVersion": 2})
|
||||
|
||||
def test_tool_types_map_to_canonical_items(self):
|
||||
self.assertEqual(
|
||||
protocol.canonical_tool_item_type("terminal"), "command_execution"
|
||||
)
|
||||
self.assertEqual(
|
||||
protocol.canonical_tool_item_type("apply_patch"), "file_change"
|
||||
)
|
||||
self.assertEqual(
|
||||
protocol.canonical_tool_item_type("custom_vendor_tool"),
|
||||
"dynamic_tool_call",
|
||||
)
|
||||
|
||||
def test_tool_data_never_forwards_arbitrary_args(self):
|
||||
self.assertEqual(
|
||||
protocol.canonical_tool_data(
|
||||
"terminal",
|
||||
{"command": "pytest", "cwd": "/repo", "credential": "secret"},
|
||||
),
|
||||
{"command": "pytest", "cwd": "/repo"},
|
||||
)
|
||||
self.assertIsNone(
|
||||
protocol.canonical_tool_data(
|
||||
"custom_vendor_tool", {"credential": "must-not-cross"}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -315,6 +315,22 @@ export function createServerEnvironmentAtoms<R, E>(
|
||||
key: ({ environmentId }) => environmentId,
|
||||
},
|
||||
}),
|
||||
hermesGatewayCreateEnrollment: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-create-enrollment",
|
||||
tag: WS_METHODS.hermesGatewayCreateEnrollment,
|
||||
}),
|
||||
hermesGatewayGetInstanceStatus: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-get-instance-status",
|
||||
tag: WS_METHODS.hermesGatewayGetInstanceStatus,
|
||||
}),
|
||||
hermesGatewayListInstances: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-list-instances",
|
||||
tag: WS_METHODS.hermesGatewayListInstances,
|
||||
}),
|
||||
hermesGatewayRevokeInstance: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-revoke-instance",
|
||||
tag: WS_METHODS.hermesGatewayRevokeInstance,
|
||||
}),
|
||||
updateProvider: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:update-provider",
|
||||
tag: WS_METHODS.serverUpdateProvider,
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DEFAULT_HERMES_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
HERMES_DRIVER_KIND,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
} from "./model.ts";
|
||||
import {
|
||||
HermesGatewayCapabilities,
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayInstanceStatus,
|
||||
HermesGatewayPluginToT3Message,
|
||||
HermesGatewayResumeCursor,
|
||||
HermesGatewayT3ToPluginMessage,
|
||||
} from "./hermesGateway.ts";
|
||||
import { WS_METHODS } from "./rpc.ts";
|
||||
import { DEFAULT_SERVER_SETTINGS, HermesSettings } from "./settings.ts";
|
||||
|
||||
const decodeCreateEnrollment = Schema.decodeUnknownSync(HermesGatewayCreateEnrollmentInput);
|
||||
const decodeCapabilities = Schema.decodeUnknownSync(HermesGatewayCapabilities);
|
||||
const decodeInstanceStatus = Schema.decodeUnknownSync(HermesGatewayInstanceStatus);
|
||||
const decodeHello = Schema.decodeUnknownSync(HermesGatewayConnectionHello);
|
||||
const decodeResumeCursor = Schema.decodeUnknownSync(HermesGatewayResumeCursor);
|
||||
const decodeT3Message = Schema.decodeUnknownSync(HermesGatewayT3ToPluginMessage);
|
||||
const decodePluginMessage = Schema.decodeUnknownSync(HermesGatewayPluginToT3Message);
|
||||
const decodeHermesSettings = Schema.decodeUnknownSync(HermesSettings);
|
||||
|
||||
describe("Hermes gateway management contracts", () => {
|
||||
it("decodes an enrollment request without deriving identity from the nickname", () => {
|
||||
expect(
|
||||
decodeCreateEnrollment({
|
||||
instanceId: "hermes-research",
|
||||
nickname: " Research ",
|
||||
connectorUrl: " https://siva.davis7.space:3774/hermes ",
|
||||
}),
|
||||
).toEqual({
|
||||
instanceId: "hermes-research",
|
||||
nickname: "Research",
|
||||
connectorUrl: "https://siva.davis7.space:3774/hermes",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid provider ids and non-connector URL schemes", () => {
|
||||
expect(() =>
|
||||
decodeCreateEnrollment({
|
||||
instanceId: "1-hermes",
|
||||
nickname: "Research",
|
||||
connectorUrl: "wss://siva.davis7.space/hermes",
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
decodeCreateEnrollment({
|
||||
instanceId: "hermes-research",
|
||||
nickname: "Research",
|
||||
connectorUrl: "ftp://siva.davis7.space/hermes",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("represents connected and upgrade-required instances for the web UI", () => {
|
||||
const connected = decodeInstanceStatus({
|
||||
instanceId: "hermes-research",
|
||||
nickname: "Research",
|
||||
status: "connected",
|
||||
connectorUrl: "wss://siva.davis7.space/hermes",
|
||||
lastConnectedAt: "2026-07-23T12:00:00.000Z",
|
||||
pluginVersion: "0.1.0",
|
||||
hermesVersion: "1.2.3",
|
||||
activeSessionCount: 2,
|
||||
protocolVersion: 1,
|
||||
capabilities: {
|
||||
protocolVersion: 1,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
});
|
||||
expect(connected.status).toBe("connected");
|
||||
expect(connected.activeSessionCount).toBe(2);
|
||||
|
||||
const upgradeRequired = decodeInstanceStatus({
|
||||
...connected,
|
||||
status: "upgrade-required",
|
||||
protocolVersion: 2,
|
||||
capabilities: null,
|
||||
});
|
||||
expect(upgradeRequired.protocolVersion).toBe(2);
|
||||
expect(upgradeRequired.capabilities).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes gateway handshake", () => {
|
||||
it("accepts one-time enrollment authentication", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-1",
|
||||
protocolVersion: 1,
|
||||
pluginVersion: "0.1.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 1,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
authentication: {
|
||||
type: "enrollment-token",
|
||||
token: "enroll-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.authentication.type).toBe("enrollment-token");
|
||||
});
|
||||
|
||||
it("accepts persistent instance authentication", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-2",
|
||||
protocolVersion: 1,
|
||||
pluginVersion: "0.1.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 1,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
authentication: {
|
||||
type: "instance-credential",
|
||||
instanceId: "hermes-research",
|
||||
credential: "persistent-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.authentication.type).toBe("instance-credential");
|
||||
});
|
||||
|
||||
it("decodes a future-version hello so the broker can reject it explicitly", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-future",
|
||||
protocolVersion: 2,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "2.0.0",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: true,
|
||||
},
|
||||
authentication: {
|
||||
type: "enrollment-token",
|
||||
token: "enroll-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.protocolVersion).toBe(2);
|
||||
expect(hello.capabilities.protocolVersion).toBe(2);
|
||||
});
|
||||
|
||||
it("reserves attachments for a future protocol version", () => {
|
||||
expect(() =>
|
||||
decodeCapabilities({
|
||||
protocolVersion: 1,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: true,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("T3 to Hermes v1 messages", () => {
|
||||
it("decodes session creation and opaque resume cursors", () => {
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "session.ensure",
|
||||
protocolVersion: 1,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
resumeSessionId: "opaque/hermes/session/value",
|
||||
}).type,
|
||||
).toBe("session.ensure");
|
||||
|
||||
expect(
|
||||
decodeResumeCursor({
|
||||
protocolVersion: 1,
|
||||
sessionId: "opaque/hermes/session/value",
|
||||
}).sessionId,
|
||||
).toBe("opaque/hermes/session/value");
|
||||
});
|
||||
|
||||
it("decodes start and steering as distinct turn operations", () => {
|
||||
const context = {
|
||||
protocolVersion: 1,
|
||||
requestId: "turn-command-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
text: "Keep the current turn running, but use this guidance.",
|
||||
};
|
||||
|
||||
expect(decodeT3Message({ type: "turn.start", ...context }).type).toBe("turn.start");
|
||||
expect(decodeT3Message({ type: "turn.steer", ...context }).type).toBe("turn.steer");
|
||||
});
|
||||
|
||||
it("decodes interrupt, approval, structured input, stop, and ping", () => {
|
||||
const turnContext = {
|
||||
protocolVersion: 1,
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
};
|
||||
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "turn.interrupt",
|
||||
requestId: "interrupt-1",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("turn.interrupt");
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "approval.respond",
|
||||
requestId: "approval-1",
|
||||
decision: "acceptForSession",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("approval.respond");
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "user-input.respond",
|
||||
requestId: "question-1",
|
||||
answers: { environment: "production" },
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("user-input.respond");
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "session.stop",
|
||||
protocolVersion: 1,
|
||||
requestId: "stop-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
}).type,
|
||||
).toBe("session.stop");
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "ping",
|
||||
protocolVersion: 1,
|
||||
requestId: "ping-1",
|
||||
sentAt: "2026-07-23T12:00:00.000Z",
|
||||
}).type,
|
||||
).toBe("ping");
|
||||
});
|
||||
|
||||
it("rejects post-handshake frames from another protocol version", () => {
|
||||
expect(() =>
|
||||
decodeT3Message({
|
||||
type: "ping",
|
||||
protocolVersion: 2,
|
||||
requestId: "ping-1",
|
||||
sentAt: "2026-07-23T12:00:00.000Z",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes to T3 v1 events", () => {
|
||||
const turnContext = {
|
||||
protocolVersion: 1,
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
};
|
||||
|
||||
it("decodes session readiness, turn start, streaming text, and completion", () => {
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "session.ready",
|
||||
protocolVersion: 1,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
resumed: false,
|
||||
}).type,
|
||||
).toBe("session.ready");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "turn.started",
|
||||
requestId: "turn-command-1",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("turn.started");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "content.delta",
|
||||
streamKind: "assistant_text",
|
||||
delta: "Hello",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("content.delta");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "turn.completed",
|
||||
state: "completed",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("turn.completed");
|
||||
});
|
||||
|
||||
it("decodes activity lifecycle events with normalized and generic data", () => {
|
||||
for (const type of ["item.started", "item.updated", "item.completed"] as const) {
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type,
|
||||
itemId: "tool-1",
|
||||
itemType: "mcp_tool_call",
|
||||
status: type === "item.completed" ? "completed" : "inProgress",
|
||||
title: "Search",
|
||||
detail: "Looking up the requested information",
|
||||
data: { providerKind: "hermes-native-event" },
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe(type);
|
||||
}
|
||||
});
|
||||
|
||||
it("decodes approvals and structured user-input lifecycle events", () => {
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "request.opened",
|
||||
requestId: "approval-1",
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Run the command?",
|
||||
args: { command: "git status" },
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("request.opened");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "request.resolved",
|
||||
requestId: "approval-1",
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("request.resolved");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "user-input.requested",
|
||||
requestId: "question-1",
|
||||
questions: [
|
||||
{
|
||||
id: "environment",
|
||||
header: "Target",
|
||||
question: "Which environment?",
|
||||
options: [
|
||||
{
|
||||
label: "Staging",
|
||||
description: "Deploy to the staging environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("user-input.requested");
|
||||
expect(
|
||||
decodePluginMessage({
|
||||
type: "user-input.resolved",
|
||||
requestId: "question-1",
|
||||
answers: { environment: "Staging" },
|
||||
...turnContext,
|
||||
}).type,
|
||||
).toBe("user-input.resolved");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes provider integration constants", () => {
|
||||
it("exposes Hermes as a single opaque model in the normal provider picker", () => {
|
||||
expect(DEFAULT_MODEL_BY_PROVIDER[HERMES_DRIVER_KIND]).toBe(DEFAULT_HERMES_MODEL);
|
||||
expect(PROVIDER_DISPLAY_NAMES[HERMES_DRIVER_KIND]).toBe("Hermes");
|
||||
});
|
||||
|
||||
it("keeps Hermes server settings remote-only", () => {
|
||||
expect(decodeHermesSettings({})).toEqual({
|
||||
enabled: true,
|
||||
});
|
||||
expect(DEFAULT_SERVER_SETTINGS.providers.hermes).toEqual({
|
||||
enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("registers the web-management RPC method names", () => {
|
||||
expect(WS_METHODS.hermesGatewayCreateEnrollment).toBe("hermesGateway.createEnrollment");
|
||||
expect(WS_METHODS.hermesGatewayGetInstanceStatus).toBe("hermesGateway.getInstanceStatus");
|
||||
expect(WS_METHODS.hermesGatewayListInstances).toBe("hermesGateway.listInstances");
|
||||
expect(WS_METHODS.hermesGatewayRevokeInstance).toBe("hermesGateway.revokeInstance");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,574 @@
|
||||
/**
|
||||
* Versioned contracts for the T3 Code gateway plugin hosted by Hermes.
|
||||
*
|
||||
* The web-management schemas are intentionally separate from the plugin wire
|
||||
* protocol. Browser clients may receive one-time enrollment tokens, but never
|
||||
* the persistent credential issued directly to the plugin after enrollment.
|
||||
*
|
||||
* @module hermesGateway
|
||||
*/
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
PositiveInt,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ProviderApprovalDecision, ProviderUserInputAnswers } from "./orchestration.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { CanonicalItemType, CanonicalRequestType, UserInputQuestion } from "./providerRuntime.ts";
|
||||
|
||||
export const HERMES_GATEWAY_PROTOCOL_VERSION = 1 as const;
|
||||
|
||||
export const HermesGatewayProtocolVersion = Schema.Literal(HERMES_GATEWAY_PROTOCOL_VERSION);
|
||||
export type HermesGatewayProtocolVersion = typeof HermesGatewayProtocolVersion.Type;
|
||||
|
||||
export const HermesGatewayRequestId = TrimmedNonEmptyString.pipe(
|
||||
Schema.brand("HermesGatewayRequestId"),
|
||||
);
|
||||
export type HermesGatewayRequestId = typeof HermesGatewayRequestId.Type;
|
||||
|
||||
/**
|
||||
* An opaque identifier owned entirely by Hermes. T3 persists and echoes it,
|
||||
* but must not derive routing or other semantics from its contents.
|
||||
*/
|
||||
export const HermesGatewaySessionId = TrimmedNonEmptyString.pipe(
|
||||
Schema.brand("HermesGatewaySessionId"),
|
||||
);
|
||||
export type HermesGatewaySessionId = typeof HermesGatewaySessionId.Type;
|
||||
|
||||
export const HermesGatewayResumeCursor = Schema.Struct({
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
sessionId: HermesGatewaySessionId,
|
||||
});
|
||||
export type HermesGatewayResumeCursor = typeof HermesGatewayResumeCursor.Type;
|
||||
|
||||
export const HermesGatewayItemId = TrimmedNonEmptyString.pipe(Schema.brand("HermesGatewayItemId"));
|
||||
export type HermesGatewayItemId = typeof HermesGatewayItemId.Type;
|
||||
|
||||
export const HermesGatewayEnrollmentToken = TrimmedNonEmptyString.pipe(
|
||||
Schema.brand("HermesGatewayEnrollmentToken"),
|
||||
);
|
||||
export type HermesGatewayEnrollmentToken = typeof HermesGatewayEnrollmentToken.Type;
|
||||
|
||||
export const HermesGatewayCredential = TrimmedNonEmptyString.pipe(
|
||||
Schema.brand("HermesGatewayCredential"),
|
||||
);
|
||||
export type HermesGatewayCredential = typeof HermesGatewayCredential.Type;
|
||||
|
||||
export const HermesGatewayNickname = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
|
||||
export type HermesGatewayNickname = typeof HermesGatewayNickname.Type;
|
||||
|
||||
/**
|
||||
* T3 accepts ordinary HTTP(S) URLs because the plugin command may normalize
|
||||
* them to WebSocket URLs, as well as explicit WS(S) connector URLs.
|
||||
*/
|
||||
export const HermesGatewayConnectorUrl = TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(2_048),
|
||||
Schema.isPattern(/^(?:https?|wss?):\/\/\S+$/i),
|
||||
);
|
||||
export type HermesGatewayConnectorUrl = typeof HermesGatewayConnectorUrl.Type;
|
||||
|
||||
export const HermesGatewayCapabilities = Schema.Struct({
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
streaming: Schema.Boolean,
|
||||
activity: Schema.Boolean,
|
||||
approvals: Schema.Boolean,
|
||||
userInput: Schema.Boolean,
|
||||
attachments: Schema.Literal(false),
|
||||
});
|
||||
export type HermesGatewayCapabilities = typeof HermesGatewayCapabilities.Type;
|
||||
|
||||
/**
|
||||
* Capability advertisement accepted at the initial handshake boundary.
|
||||
*
|
||||
* This deliberately permits capability shapes from a newer protocol so T3 can
|
||||
* return a structured `version-incompatible` rejection instead of failing the
|
||||
* WebSocket frame decoder. Accepted v1 connections must subsequently validate
|
||||
* this advertisement with `HermesGatewayCapabilities`.
|
||||
*/
|
||||
export const HermesGatewayHelloCapabilities = Schema.Struct({
|
||||
protocolVersion: PositiveInt,
|
||||
streaming: Schema.Boolean,
|
||||
activity: Schema.Boolean,
|
||||
approvals: Schema.Boolean,
|
||||
userInput: Schema.Boolean,
|
||||
attachments: Schema.Boolean,
|
||||
});
|
||||
export type HermesGatewayHelloCapabilities = typeof HermesGatewayHelloCapabilities.Type;
|
||||
|
||||
export const HermesGatewayConnectionState = Schema.Literals([
|
||||
"offline",
|
||||
"connecting",
|
||||
"connected",
|
||||
"upgrade-required",
|
||||
"revoked",
|
||||
]);
|
||||
export type HermesGatewayConnectionState = typeof HermesGatewayConnectionState.Type;
|
||||
|
||||
/**
|
||||
* Public instance state used by settings and provider-picker surfaces.
|
||||
*
|
||||
* `protocolVersion` is not restricted to v1 here so the UI can report the
|
||||
* unsupported version observed from a plugin that needs an upgrade.
|
||||
*/
|
||||
export const HermesGatewayInstanceStatus = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
nickname: HermesGatewayNickname,
|
||||
status: HermesGatewayConnectionState,
|
||||
connectorUrl: HermesGatewayConnectorUrl,
|
||||
lastConnectedAt: Schema.NullOr(IsoDateTime),
|
||||
pluginVersion: Schema.NullOr(TrimmedNonEmptyString),
|
||||
hermesVersion: Schema.NullOr(TrimmedNonEmptyString),
|
||||
activeSessionCount: NonNegativeInt,
|
||||
protocolVersion: Schema.NullOr(PositiveInt),
|
||||
capabilities: Schema.NullOr(HermesGatewayCapabilities),
|
||||
});
|
||||
export type HermesGatewayInstanceStatus = typeof HermesGatewayInstanceStatus.Type;
|
||||
|
||||
export const HermesGatewayCreateEnrollmentInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
nickname: HermesGatewayNickname,
|
||||
connectorUrl: HermesGatewayConnectorUrl,
|
||||
});
|
||||
export type HermesGatewayCreateEnrollmentInput = typeof HermesGatewayCreateEnrollmentInput.Type;
|
||||
|
||||
/**
|
||||
* Returned exactly once to the web client. The long-lived plugin credential
|
||||
* is intentionally absent and is delivered only over the authenticated
|
||||
* enrollment socket.
|
||||
*/
|
||||
export const HermesGatewayEnrollmentResult = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
expiresAt: IsoDateTime,
|
||||
connectorUrl: HermesGatewayConnectorUrl,
|
||||
command: TrimmedNonEmptyString,
|
||||
oneTimeToken: HermesGatewayEnrollmentToken,
|
||||
});
|
||||
export type HermesGatewayEnrollmentResult = typeof HermesGatewayEnrollmentResult.Type;
|
||||
|
||||
export const HermesGatewayListInstancesResult = Schema.Array(HermesGatewayInstanceStatus);
|
||||
export type HermesGatewayListInstancesResult = typeof HermesGatewayListInstancesResult.Type;
|
||||
|
||||
export const HermesGatewayGetInstanceStatusInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
});
|
||||
export type HermesGatewayGetInstanceStatusInput = typeof HermesGatewayGetInstanceStatusInput.Type;
|
||||
|
||||
export const HermesGatewayRenameInstanceInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
nickname: HermesGatewayNickname,
|
||||
});
|
||||
export type HermesGatewayRenameInstanceInput = typeof HermesGatewayRenameInstanceInput.Type;
|
||||
|
||||
export const HermesGatewayRevokeInstanceInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
});
|
||||
export type HermesGatewayRevokeInstanceInput = typeof HermesGatewayRevokeInstanceInput.Type;
|
||||
|
||||
export const HermesGatewayRevokeInstanceResult = HermesGatewayInstanceStatus;
|
||||
export type HermesGatewayRevokeInstanceResult = typeof HermesGatewayRevokeInstanceResult.Type;
|
||||
|
||||
export const HermesGatewayManagementOperation = Schema.Literals([
|
||||
"create-enrollment",
|
||||
"get-status",
|
||||
"list-instances",
|
||||
"revoke-instance",
|
||||
]);
|
||||
export type HermesGatewayManagementOperation = typeof HermesGatewayManagementOperation.Type;
|
||||
|
||||
export const HermesGatewayManagementErrorCode = Schema.Literals([
|
||||
"instance-not-found",
|
||||
"nickname-conflict",
|
||||
"invalid-connector-url",
|
||||
"instance-revoked",
|
||||
"persistence-failed",
|
||||
"internal-error",
|
||||
]);
|
||||
export type HermesGatewayManagementErrorCode = typeof HermesGatewayManagementErrorCode.Type;
|
||||
|
||||
export class HermesGatewayManagementError extends Schema.TaggedErrorClass<HermesGatewayManagementError>()(
|
||||
"HermesGatewayManagementError",
|
||||
{
|
||||
operation: HermesGatewayManagementOperation,
|
||||
code: HermesGatewayManagementErrorCode,
|
||||
message: TrimmedNonEmptyString,
|
||||
instanceId: Schema.optional(ProviderInstanceId),
|
||||
},
|
||||
) {}
|
||||
|
||||
const HermesGatewayEnrollmentAuthentication = Schema.Struct({
|
||||
type: Schema.Literal("enrollment-token"),
|
||||
token: HermesGatewayEnrollmentToken,
|
||||
});
|
||||
export type HermesGatewayEnrollmentAuthentication =
|
||||
typeof HermesGatewayEnrollmentAuthentication.Type;
|
||||
|
||||
const HermesGatewayCredentialAuthentication = Schema.Struct({
|
||||
type: Schema.Literal("instance-credential"),
|
||||
instanceId: ProviderInstanceId,
|
||||
credential: HermesGatewayCredential,
|
||||
});
|
||||
export type HermesGatewayCredentialAuthentication =
|
||||
typeof HermesGatewayCredentialAuthentication.Type;
|
||||
|
||||
export const HermesGatewayAuthentication = Schema.Union([
|
||||
HermesGatewayEnrollmentAuthentication,
|
||||
HermesGatewayCredentialAuthentication,
|
||||
]);
|
||||
export type HermesGatewayAuthentication = typeof HermesGatewayAuthentication.Type;
|
||||
|
||||
/**
|
||||
* `protocolVersion` accepts any positive integer at the initial boundary so
|
||||
* T3 can reject incompatible plugins with a structured upgrade response.
|
||||
* Once accepted, all remaining v1 frames use the literal v1 schema.
|
||||
*/
|
||||
export const HermesGatewayConnectionHello = Schema.Struct({
|
||||
type: Schema.Literal("connection.hello"),
|
||||
requestId: HermesGatewayRequestId,
|
||||
protocolVersion: PositiveInt,
|
||||
pluginVersion: TrimmedNonEmptyString,
|
||||
hermesVersion: TrimmedNonEmptyString,
|
||||
capabilities: HermesGatewayHelloCapabilities,
|
||||
authentication: HermesGatewayAuthentication,
|
||||
});
|
||||
export type HermesGatewayConnectionHello = typeof HermesGatewayConnectionHello.Type;
|
||||
|
||||
export const HermesGatewayConnectionAccepted = Schema.Struct({
|
||||
type: Schema.Literal("connection.accepted"),
|
||||
requestId: HermesGatewayRequestId,
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
instanceId: ProviderInstanceId,
|
||||
nickname: HermesGatewayNickname,
|
||||
credential: Schema.optional(HermesGatewayCredential),
|
||||
});
|
||||
export type HermesGatewayConnectionAccepted = typeof HermesGatewayConnectionAccepted.Type;
|
||||
|
||||
export const HermesGatewayConnectionRejectionCode = Schema.Literals([
|
||||
"invalid-authentication",
|
||||
"enrollment-expired",
|
||||
"instance-revoked",
|
||||
"version-incompatible",
|
||||
"internal-error",
|
||||
]);
|
||||
export type HermesGatewayConnectionRejectionCode = typeof HermesGatewayConnectionRejectionCode.Type;
|
||||
|
||||
export const HermesGatewayConnectionRejected = Schema.Struct({
|
||||
type: Schema.Literal("connection.rejected"),
|
||||
requestId: HermesGatewayRequestId,
|
||||
code: HermesGatewayConnectionRejectionCode,
|
||||
message: TrimmedNonEmptyString,
|
||||
expectedProtocolVersion: HermesGatewayProtocolVersion,
|
||||
});
|
||||
export type HermesGatewayConnectionRejected = typeof HermesGatewayConnectionRejected.Type;
|
||||
|
||||
export const HermesGatewayConnectionStatus = Schema.Struct({
|
||||
type: Schema.Literal("connection.status"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
activeSessionCount: NonNegativeInt,
|
||||
});
|
||||
export type HermesGatewayConnectionStatus = typeof HermesGatewayConnectionStatus.Type;
|
||||
|
||||
const HermesGatewaySessionContext = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
sessionId: HermesGatewaySessionId,
|
||||
});
|
||||
|
||||
const HermesGatewayTurnContext = Schema.Struct({
|
||||
...HermesGatewaySessionContext.fields,
|
||||
turnId: TurnId,
|
||||
});
|
||||
|
||||
const HermesGatewayTurnText = Schema.String.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(120_000),
|
||||
);
|
||||
|
||||
export const HermesGatewaySessionEnsure = Schema.Struct({
|
||||
type: Schema.Literal("session.ensure"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
threadId: ThreadId,
|
||||
resumeSessionId: Schema.optional(HermesGatewaySessionId),
|
||||
});
|
||||
export type HermesGatewaySessionEnsure = typeof HermesGatewaySessionEnsure.Type;
|
||||
|
||||
export const HermesGatewayTurnStart = Schema.Struct({
|
||||
type: Schema.Literal("turn.start"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
text: HermesGatewayTurnText,
|
||||
});
|
||||
export type HermesGatewayTurnStart = typeof HermesGatewayTurnStart.Type;
|
||||
|
||||
export const HermesGatewayTurnSteer = Schema.Struct({
|
||||
type: Schema.Literal("turn.steer"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
text: HermesGatewayTurnText,
|
||||
});
|
||||
export type HermesGatewayTurnSteer = typeof HermesGatewayTurnSteer.Type;
|
||||
|
||||
export const HermesGatewayTurnInterrupt = Schema.Struct({
|
||||
type: Schema.Literal("turn.interrupt"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
});
|
||||
export type HermesGatewayTurnInterrupt = typeof HermesGatewayTurnInterrupt.Type;
|
||||
|
||||
export const HermesGatewayApprovalResponse = Schema.Struct({
|
||||
type: Schema.Literal("approval.respond"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
requestId: HermesGatewayRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
});
|
||||
export type HermesGatewayApprovalResponse = typeof HermesGatewayApprovalResponse.Type;
|
||||
|
||||
export const HermesGatewayUserInputResponse = Schema.Struct({
|
||||
type: Schema.Literal("user-input.respond"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
requestId: HermesGatewayRequestId,
|
||||
answers: ProviderUserInputAnswers,
|
||||
});
|
||||
export type HermesGatewayUserInputResponse = typeof HermesGatewayUserInputResponse.Type;
|
||||
|
||||
export const HermesGatewaySessionStop = Schema.Struct({
|
||||
type: Schema.Literal("session.stop"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
...HermesGatewaySessionContext.fields,
|
||||
});
|
||||
export type HermesGatewaySessionStop = typeof HermesGatewaySessionStop.Type;
|
||||
|
||||
export const HermesGatewayPing = Schema.Struct({
|
||||
type: Schema.Literal("ping"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
sentAt: IsoDateTime,
|
||||
});
|
||||
export type HermesGatewayPing = typeof HermesGatewayPing.Type;
|
||||
|
||||
export const HermesGatewaySessionReady = Schema.Struct({
|
||||
type: Schema.Literal("session.ready"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
threadId: ThreadId,
|
||||
sessionId: HermesGatewaySessionId,
|
||||
resumed: Schema.Boolean,
|
||||
});
|
||||
export type HermesGatewaySessionReady = typeof HermesGatewaySessionReady.Type;
|
||||
|
||||
export const HermesGatewayTurnStarted = Schema.Struct({
|
||||
type: Schema.Literal("turn.started"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
});
|
||||
export type HermesGatewayTurnStarted = typeof HermesGatewayTurnStarted.Type;
|
||||
|
||||
export const HermesGatewayContentStreamKind = Schema.Literals([
|
||||
"assistant_text",
|
||||
"reasoning_text",
|
||||
"reasoning_summary_text",
|
||||
"plan_text",
|
||||
"command_output",
|
||||
"unknown",
|
||||
]);
|
||||
export type HermesGatewayContentStreamKind = typeof HermesGatewayContentStreamKind.Type;
|
||||
|
||||
export const HermesGatewayContentDelta = Schema.Struct({
|
||||
type: Schema.Literal("content.delta"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
itemId: Schema.optional(HermesGatewayItemId),
|
||||
streamKind: HermesGatewayContentStreamKind,
|
||||
delta: Schema.String,
|
||||
contentIndex: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
export type HermesGatewayContentDelta = typeof HermesGatewayContentDelta.Type;
|
||||
|
||||
export const HermesGatewayItemStatus = Schema.Literals([
|
||||
"inProgress",
|
||||
"completed",
|
||||
"failed",
|
||||
"declined",
|
||||
]);
|
||||
export type HermesGatewayItemStatus = typeof HermesGatewayItemStatus.Type;
|
||||
|
||||
const HermesGatewayItemLifecycleFields = {
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
itemId: HermesGatewayItemId,
|
||||
itemType: CanonicalItemType,
|
||||
status: Schema.optional(HermesGatewayItemStatus),
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
};
|
||||
|
||||
export const HermesGatewayItemStarted = Schema.Struct({
|
||||
type: Schema.Literal("item.started"),
|
||||
...HermesGatewayItemLifecycleFields,
|
||||
});
|
||||
export type HermesGatewayItemStarted = typeof HermesGatewayItemStarted.Type;
|
||||
|
||||
export const HermesGatewayItemUpdated = Schema.Struct({
|
||||
type: Schema.Literal("item.updated"),
|
||||
...HermesGatewayItemLifecycleFields,
|
||||
});
|
||||
export type HermesGatewayItemUpdated = typeof HermesGatewayItemUpdated.Type;
|
||||
|
||||
export const HermesGatewayItemCompleted = Schema.Struct({
|
||||
type: Schema.Literal("item.completed"),
|
||||
...HermesGatewayItemLifecycleFields,
|
||||
});
|
||||
export type HermesGatewayItemCompleted = typeof HermesGatewayItemCompleted.Type;
|
||||
|
||||
const HermesGatewayInteractionContext = Schema.Struct({
|
||||
...HermesGatewayTurnContext.fields,
|
||||
requestId: HermesGatewayRequestId,
|
||||
});
|
||||
|
||||
export const HermesGatewayRequestOpened = Schema.Struct({
|
||||
type: Schema.Literal("request.opened"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayInteractionContext.fields,
|
||||
requestType: CanonicalRequestType,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
args: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type HermesGatewayRequestOpened = typeof HermesGatewayRequestOpened.Type;
|
||||
|
||||
export const HermesGatewayRequestResolved = Schema.Struct({
|
||||
type: Schema.Literal("request.resolved"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayInteractionContext.fields,
|
||||
requestType: CanonicalRequestType,
|
||||
decision: Schema.optional(TrimmedNonEmptyString),
|
||||
resolution: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type HermesGatewayRequestResolved = typeof HermesGatewayRequestResolved.Type;
|
||||
|
||||
export const HermesGatewayUserInputRequested = Schema.Struct({
|
||||
type: Schema.Literal("user-input.requested"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayInteractionContext.fields,
|
||||
questions: Schema.Array(UserInputQuestion),
|
||||
});
|
||||
export type HermesGatewayUserInputRequested = typeof HermesGatewayUserInputRequested.Type;
|
||||
|
||||
export const HermesGatewayUserInputResolved = Schema.Struct({
|
||||
type: Schema.Literal("user-input.resolved"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayInteractionContext.fields,
|
||||
answers: ProviderUserInputAnswers,
|
||||
});
|
||||
export type HermesGatewayUserInputResolved = typeof HermesGatewayUserInputResolved.Type;
|
||||
|
||||
export const HermesGatewayTurnCompletionState = Schema.Literals(["completed", "failed"]);
|
||||
export type HermesGatewayTurnCompletionState = typeof HermesGatewayTurnCompletionState.Type;
|
||||
|
||||
export const HermesGatewayTurnCompleted = Schema.Struct({
|
||||
type: Schema.Literal("turn.completed"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
state: HermesGatewayTurnCompletionState,
|
||||
stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
errorMessage: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type HermesGatewayTurnCompleted = typeof HermesGatewayTurnCompleted.Type;
|
||||
|
||||
export const HermesGatewayTurnAborted = Schema.Struct({
|
||||
type: Schema.Literal("turn.aborted"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
reason: TrimmedNonEmptyString,
|
||||
});
|
||||
export type HermesGatewayTurnAborted = typeof HermesGatewayTurnAborted.Type;
|
||||
|
||||
export const HermesGatewaySessionExited = Schema.Struct({
|
||||
type: Schema.Literal("session.exited"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewaySessionContext.fields,
|
||||
reason: Schema.optional(TrimmedNonEmptyString),
|
||||
recoverable: Schema.Boolean,
|
||||
});
|
||||
export type HermesGatewaySessionExited = typeof HermesGatewaySessionExited.Type;
|
||||
|
||||
export const HermesGatewayPong = Schema.Struct({
|
||||
type: Schema.Literal("pong"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: HermesGatewayRequestId,
|
||||
sentAt: IsoDateTime,
|
||||
});
|
||||
export type HermesGatewayPong = typeof HermesGatewayPong.Type;
|
||||
|
||||
export const HermesGatewayProtocolErrorCode = Schema.Literals([
|
||||
"invalid-message",
|
||||
"unsupported-message",
|
||||
"session-not-found",
|
||||
"turn-not-active",
|
||||
"request-not-found",
|
||||
"internal-error",
|
||||
]);
|
||||
export type HermesGatewayProtocolErrorCode = typeof HermesGatewayProtocolErrorCode.Type;
|
||||
|
||||
export const HermesGatewayProtocolError = Schema.Struct({
|
||||
type: Schema.Literal("protocol.error"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
requestId: Schema.optional(HermesGatewayRequestId),
|
||||
code: HermesGatewayProtocolErrorCode,
|
||||
message: TrimmedNonEmptyString,
|
||||
recoverable: Schema.Boolean,
|
||||
});
|
||||
export type HermesGatewayProtocolError = typeof HermesGatewayProtocolError.Type;
|
||||
|
||||
export const HermesGatewayT3ToPluginMessage = Schema.Union([
|
||||
HermesGatewayConnectionAccepted,
|
||||
HermesGatewayConnectionRejected,
|
||||
HermesGatewaySessionEnsure,
|
||||
HermesGatewayTurnStart,
|
||||
HermesGatewayTurnSteer,
|
||||
HermesGatewayTurnInterrupt,
|
||||
HermesGatewayApprovalResponse,
|
||||
HermesGatewayUserInputResponse,
|
||||
HermesGatewaySessionStop,
|
||||
HermesGatewayPing,
|
||||
]);
|
||||
export type HermesGatewayT3ToPluginMessage = typeof HermesGatewayT3ToPluginMessage.Type;
|
||||
|
||||
export const HermesGatewayPluginToT3Message = Schema.Union([
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayConnectionStatus,
|
||||
HermesGatewaySessionReady,
|
||||
HermesGatewayTurnStarted,
|
||||
HermesGatewayContentDelta,
|
||||
HermesGatewayItemStarted,
|
||||
HermesGatewayItemUpdated,
|
||||
HermesGatewayItemCompleted,
|
||||
HermesGatewayRequestOpened,
|
||||
HermesGatewayRequestResolved,
|
||||
HermesGatewayUserInputRequested,
|
||||
HermesGatewayUserInputResolved,
|
||||
HermesGatewayTurnCompleted,
|
||||
HermesGatewayTurnAborted,
|
||||
HermesGatewaySessionExited,
|
||||
HermesGatewayPong,
|
||||
HermesGatewayProtocolError,
|
||||
]);
|
||||
export type HermesGatewayPluginToT3Message = typeof HermesGatewayPluginToT3Message.Type;
|
||||
|
||||
export const HermesGatewayWireMessage = Schema.Union([
|
||||
HermesGatewayT3ToPluginMessage,
|
||||
HermesGatewayPluginToT3Message,
|
||||
]);
|
||||
export type HermesGatewayWireMessage = typeof HermesGatewayWireMessage.Type;
|
||||
@@ -27,3 +27,4 @@ export * from "./review.ts";
|
||||
export * from "./preview.ts";
|
||||
export * from "./previewAutomation.ts";
|
||||
export * from "./rpc.ts";
|
||||
export * from "./hermesGateway.ts";
|
||||
@@ -132,8 +132,10 @@ const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
export const HERMES_DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.6-sol";
|
||||
export const DEFAULT_HERMES_MODEL = "hermes";
|
||||
|
||||
/**
|
||||
* Codex default-model preference, most preferred first. The provider snapshot
|
||||
@@ -152,6 +154,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
[CURSOR_DRIVER_KIND]: "auto",
|
||||
[GROK_DRIVER_KIND]: "grok-build",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
[HERMES_DRIVER_KIND]: DEFAULT_HERMES_MODEL,
|
||||
};
|
||||
|
||||
/** Per-provider text generation model defaults. */
|
||||
@@ -218,4 +221,5 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
|
||||
[CURSOR_DRIVER_KIND]: "Cursor",
|
||||
[GROK_DRIVER_KIND]: "Grok",
|
||||
[OPENCODE_DRIVER_KIND]: "OpenCode",
|
||||
[HERMES_DRIVER_KIND]: "Hermes",
|
||||
};
|
||||
@@ -59,6 +59,16 @@ import {
|
||||
OrchestrationRpcSchemas,
|
||||
} from "./orchestration.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import {
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayEnrollmentResult,
|
||||
HermesGatewayGetInstanceStatusInput,
|
||||
HermesGatewayInstanceStatus,
|
||||
HermesGatewayListInstancesResult,
|
||||
HermesGatewayManagementError,
|
||||
HermesGatewayRevokeInstanceInput,
|
||||
HermesGatewayRevokeInstanceResult,
|
||||
} from "./hermesGateway.ts";
|
||||
import {
|
||||
RelayClientInstallFailedError,
|
||||
RelayClientInstallProgressEventSchema,
|
||||
@@ -219,6 +229,12 @@ export const WS_METHODS = {
|
||||
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
|
||||
serverSignalProcess: "server.signalProcess",
|
||||
|
||||
// Hermes gateway instance management
|
||||
hermesGatewayCreateEnrollment: "hermesGateway.createEnrollment",
|
||||
hermesGatewayGetInstanceStatus: "hermesGateway.getInstanceStatus",
|
||||
hermesGatewayListInstances: "hermesGateway.listInstances",
|
||||
hermesGatewayRevokeInstance: "hermesGateway.revokeInstance",
|
||||
|
||||
// Cloud environment methods
|
||||
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
|
||||
cloudInstallRelayClient: "cloud.installRelayClient",
|
||||
@@ -334,6 +350,36 @@ export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess,
|
||||
error: EnvironmentAuthorizationError,
|
||||
});
|
||||
|
||||
export const WsHermesGatewayCreateEnrollmentRpc = Rpc.make(
|
||||
WS_METHODS.hermesGatewayCreateEnrollment,
|
||||
{
|
||||
payload: HermesGatewayCreateEnrollmentInput,
|
||||
success: HermesGatewayEnrollmentResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsHermesGatewayGetInstanceStatusRpc = Rpc.make(
|
||||
WS_METHODS.hermesGatewayGetInstanceStatus,
|
||||
{
|
||||
payload: HermesGatewayGetInstanceStatusInput,
|
||||
success: HermesGatewayInstanceStatus,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsHermesGatewayListInstancesRpc = Rpc.make(WS_METHODS.hermesGatewayListInstances, {
|
||||
payload: Schema.Struct({}),
|
||||
success: HermesGatewayListInstancesResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsHermesGatewayRevokeInstanceRpc = Rpc.make(WS_METHODS.hermesGatewayRevokeInstance, {
|
||||
payload: HermesGatewayRevokeInstanceInput,
|
||||
success: HermesGatewayRevokeInstanceResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, {
|
||||
payload: Schema.Struct({}),
|
||||
success: RelayClientStatusSchema,
|
||||
@@ -713,6 +759,10 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetProcessDiagnosticsRpc,
|
||||
WsServerGetProcessResourceHistoryRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsHermesGatewayCreateEnrollmentRpc,
|
||||
WsHermesGatewayGetInstanceStatusRpc,
|
||||
WsHermesGatewayListInstancesRpc,
|
||||
WsHermesGatewayRevokeInstanceRpc,
|
||||
WsCloudGetRelayClientStatusRpc,
|
||||
WsCloudInstallRelayClientRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
|
||||
@@ -389,6 +389,19 @@ export const OpenCodeSettings = makeProviderSettingsSchema(
|
||||
);
|
||||
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.
|
||||
*/
|
||||
export const HermesSettings = makeProviderSettingsSchema({
|
||||
enabled: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
});
|
||||
export type HermesSettings = typeof HermesSettings.Type;
|
||||
|
||||
export const ObservabilitySettings = Schema.Struct({
|
||||
otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
@@ -433,6 +446,7 @@ export const ServerSettings = Schema.Struct({
|
||||
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
hermes: HermesSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
// New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
|
||||
// are `ProviderInstanceConfig` envelopes. The driver-specific config blob
|
||||
@@ -536,6 +550,10 @@ const OpenCodeSettingsPatch = Schema.Struct({
|
||||
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
});
|
||||
|
||||
const HermesSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
export const ServerSettingsPatch = Schema.Struct({
|
||||
// Server settings
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
@@ -558,6 +576,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
cursor: Schema.optionalKey(CursorSettingsPatch),
|
||||
grok: Schema.optionalKey(GrokSettingsPatch),
|
||||
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
|
||||
hermes: Schema.optionalKey(HermesSettingsPatch),
|
||||
}),
|
||||
),
|
||||
// Whole-map replacement for the new instance config. Patching individual
|
||||
|
||||
Reference in new issue
Block a user