Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c696e04e81 | ||
|
|
f684971262 | ||
|
|
18f7243fd3 | ||
|
|
9fb0ba2990 | ||
|
|
6d341a14be | ||
|
|
422cf087ee | ||
|
|
e78baddda1 | ||
|
|
e33c0d8e82 | ||
|
|
3261623f90 | ||
|
|
758f999f9b | ||
|
|
e8be967295 | ||
|
|
5b519775f5 | ||
|
|
965a76b531 | ||
|
|
35ddbc4ab1 | ||
|
|
1fa4219b48 | ||
|
|
5faee6114b | ||
|
|
0b837b8ef1 | ||
|
|
19d1329ac5 | ||
|
|
5b8cfdbf05 |
No files matched your search
@@ -35,3 +35,5 @@ node_modules/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -18,6 +18,7 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
port: 3773,
|
||||
...overrides,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
}),
|
||||
@@ -32,10 +33,11 @@ const makeEnvironmentAuthLayer = (overrides?: Partial<ServerConfig.ServerConfig[
|
||||
|
||||
const makeCookieRequest = (
|
||||
sessionToken: string,
|
||||
cookieName = "t3_session",
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
[cookieName]: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
@@ -100,6 +102,39 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses the port-specific web cookie when sibling instance cookies are present", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const pairingCredential = yield* serverAuth.issuePairingCredential();
|
||||
const exchanged = yield* serverAuth.createBrowserSession(
|
||||
pairingCredential.credential,
|
||||
requestMetadata,
|
||||
);
|
||||
const request = {
|
||||
cookies: {
|
||||
t3_session: "session-owned-by-the-canonical-instance",
|
||||
t3_session_7446: exchanged.sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
} as unknown as Parameters<
|
||||
EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]
|
||||
>[0];
|
||||
|
||||
const verified = yield* serverAuth.authenticateHttpRequest(request);
|
||||
|
||||
expect(verified.sessionId.length).toBeGreaterThan(0);
|
||||
expect(verified.subject).toBe("one-time-token");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthLayer({
|
||||
mode: "web",
|
||||
port: 13773,
|
||||
authCookiePort: 7446,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not exchange ordinary pairing grants for administrative access tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
|
||||
@@ -75,6 +75,42 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("isolates browser session cookies for web servers on non-default ports", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_7446");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 7446,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses the browser-facing port when a reverse proxy changes the port", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_7446");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
authCookiePort: 7446,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -40,7 +40,7 @@ export const make = Effect.gen(function* () {
|
||||
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
port: config.authCookiePort ?? config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -469,7 +469,7 @@ export const make = Effect.gen(function* () {
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
port: serverConfig.authCookiePort ?? serverConfig.port,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
import { deriveAuthClientMetadata, resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
describe("resolveSessionCookieName", () => {
|
||||
it("preserves the legacy cookie name for the canonical web port", () => {
|
||||
expect(resolveSessionCookieName({ mode: "web", port: 3773 })).toBe("t3_session");
|
||||
});
|
||||
|
||||
it("isolates web sessions on non-default ports", () => {
|
||||
expect(resolveSessionCookieName({ mode: "web", port: 7446 })).toBe("t3_session_7446");
|
||||
expect(resolveSessionCookieName({ mode: "web", port: 7447 })).toBe("t3_session_7447");
|
||||
});
|
||||
|
||||
it("keeps desktop sessions isolated by port", () => {
|
||||
expect(resolveSessionCookieName({ mode: "desktop", port: 3773 })).toBe("t3_session_3773");
|
||||
expect(resolveSessionCookieName({ mode: "desktop", port: 7446 })).toBe("t3_session_7446");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
|
||||
@@ -8,13 +8,15 @@ import * as NodeCrypto from "node:crypto";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
import { DEFAULT_PORT } from "../config.ts";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
if (input.mode === "web" && input.port === DEFAULT_PORT) {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
|
||||
@@ -92,6 +92,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_LOG_LEVEL: "Warn",
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4001",
|
||||
T3CODE_AUTH_COOKIE_PORT: "7446",
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
@@ -111,6 +112,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
...defaultObservabilityConfig,
|
||||
mode: "desktop",
|
||||
port: 4001,
|
||||
authCookiePort: 7446,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -141,6 +143,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(8788),
|
||||
authCookiePort: Option.some(9443),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
@@ -162,6 +165,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_LOG_LEVEL: "Warn",
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4001",
|
||||
T3CODE_AUTH_COOKIE_PORT: "7446",
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: join(NodeOS.tmpdir(), "ignored-base"),
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
@@ -181,6 +185,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
authCookiePort: 9443,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
|
||||
@@ -26,6 +26,13 @@ export const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const authCookiePortFlag = Flag.integer("auth-cookie-port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription(
|
||||
"Browser-facing port used to namespace auth cookies when a reverse proxy exposes a different port.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
@@ -103,6 +110,10 @@ const EnvServerConfig = Config.all({
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
authCookiePort: Config.port("T3CODE_AUTH_COOKIE_PORT").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
@@ -135,6 +146,7 @@ const EnvServerConfig = Config.all({
|
||||
export interface CliServerFlags {
|
||||
readonly mode: Option.Option<ServerConfig.RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly authCookiePort?: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly cwd: Option.Option<string>;
|
||||
@@ -164,6 +176,7 @@ export const projectLocationFlags = {
|
||||
export const sharedServerCommandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
authCookiePort: authCookiePortFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
cwd: Argument.string("cwd").pipe(
|
||||
@@ -214,6 +227,7 @@ export const resolveServerConfig = (
|
||||
const normalizedFlags = {
|
||||
mode: flags.mode ?? Option.none(),
|
||||
port: flags.port ?? Option.none(),
|
||||
authCookiePort: flags.authCookiePort ?? Option.none(),
|
||||
host: flags.host ?? Option.none(),
|
||||
baseDir: flags.baseDir ?? Option.none(),
|
||||
cwd: flags.cwd ?? Option.none(),
|
||||
@@ -257,6 +271,12 @@ export const resolveServerConfig = (
|
||||
},
|
||||
},
|
||||
);
|
||||
const explicitlyConfiguredAuthCookiePort = Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.authCookiePort,
|
||||
Option.fromUndefinedOr(env.authCookiePort),
|
||||
),
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
|
||||
() => undefined,
|
||||
@@ -326,6 +346,9 @@ export const resolveServerConfig = (
|
||||
),
|
||||
() => 443,
|
||||
);
|
||||
const authCookiePort =
|
||||
explicitlyConfiguredAuthCookiePort ??
|
||||
(tailscaleServeEnabled ? tailscaleServePort : undefined);
|
||||
const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
@@ -356,6 +379,7 @@ export const resolveServerConfig = (
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
mode,
|
||||
port,
|
||||
...(authCookiePort !== undefined ? { authCookiePort } : {}),
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -383,6 +407,7 @@ export const resolveCliAuthConfig = (
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
authCookiePort: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: flags.baseDir,
|
||||
cwd: Option.none(),
|
||||
|
||||
@@ -67,6 +67,7 @@ export class ServerConfig extends Context.Service<
|
||||
readonly otlpServiceName: string;
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly authCookiePort?: number;
|
||||
readonly host: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly baseDir: string;
|
||||
|
||||
@@ -1652,6 +1652,117 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replaces an assistant snapshot between legacy appended deltas", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-07-24T12:00:00.000Z";
|
||||
const projectId = ProjectId.make("project-replacement");
|
||||
const threadId = ThreadId.make("thread-replacement");
|
||||
const messageId = MessageId.make("assistant-replacement");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-replacement-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: projectId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-replacement-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-replacement-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId,
|
||||
title: "Project Replacement",
|
||||
workspaceRoot: "/tmp/project-replacement",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-replacement-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-replacement-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-replacement-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId,
|
||||
title: "Thread Replacement",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "hermes",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const appendMessage = (input: {
|
||||
eventNumber: number;
|
||||
text: string;
|
||||
streaming: boolean;
|
||||
textOperation?: "replace";
|
||||
}) =>
|
||||
eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make(`evt-replacement-${input.eventNumber}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make(`cmd-replacement-${input.eventNumber}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-replacement-${input.eventNumber}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
role: "assistant",
|
||||
text: input.text,
|
||||
turnId: null,
|
||||
streaming: input.streaming,
|
||||
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendMessage({ eventNumber: 3, text: "Hello wor", streaming: true });
|
||||
yield* appendMessage({
|
||||
eventNumber: 4,
|
||||
text: "Hello there",
|
||||
streaming: true,
|
||||
textOperation: "replace",
|
||||
});
|
||||
yield* appendMessage({ eventNumber: 5, text: "!", streaming: true });
|
||||
yield* appendMessage({ eventNumber: 6, text: "", streaming: false });
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>`
|
||||
SELECT
|
||||
text,
|
||||
is_streaming AS "isStreaming"
|
||||
FROM projection_thread_messages
|
||||
WHERE message_id = ${messageId}
|
||||
`;
|
||||
assert.equal(messageRows.length, 1);
|
||||
assert.equal(messageRows[0]?.text, "Hello there!");
|
||||
assert.isFalse(Boolean(messageRows[0]?.isStreaming));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolves turn-count conflicts when checkpoint completion rewrites provisional turns",
|
||||
() =>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
mergeAssistantMessageText,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
ThreadId,
|
||||
@@ -886,15 +887,14 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
const previousMessage = Option.getOrUndefined(existingMessage);
|
||||
const nextText = Option.match(existingMessage, {
|
||||
onNone: () => event.payload.text,
|
||||
onSome: (message) => {
|
||||
if (event.payload.streaming) {
|
||||
return `${message.text}${event.payload.text}`;
|
||||
}
|
||||
if (event.payload.text.length === 0) {
|
||||
return message.text;
|
||||
}
|
||||
return event.payload.text;
|
||||
},
|
||||
onSome: (message) =>
|
||||
mergeAssistantMessageText(message.text, {
|
||||
text: event.payload.text,
|
||||
streaming: event.payload.streaming,
|
||||
...(event.payload.textOperation !== undefined
|
||||
? { textOperation: event.payload.textOperation }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
|
||||
@@ -477,6 +477,49 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
effectIt.effect("adopts a recovered active provider turn while binding a pending start", () =>
|
||||
Effect.gen(function* () {
|
||||
const recoveredTurnId = asTurnId("turn-recovered-during-start");
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
startSessionEffect: (session) =>
|
||||
Effect.succeed({
|
||||
...session,
|
||||
status: "running",
|
||||
activeTurnId: recoveredTurnId,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-recovered-provider-turn"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-recovered-provider-turn"),
|
||||
role: "user",
|
||||
text: "steer the recovered turn",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
const readModel = yield* Effect.promise(() => harness.readModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
expect(thread?.session?.activeTurnId).toBe(recoveredTurnId);
|
||||
expect(thread?.latestTurn).toMatchObject({
|
||||
turnId: recoveredTurnId,
|
||||
state: "running",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("projects starting before a slow provider session finishes", () =>
|
||||
Effect.gen(function* () {
|
||||
const releaseStart = yield* Deferred.make<void>();
|
||||
@@ -1181,6 +1224,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";
|
||||
|
||||
@@ -527,8 +527,7 @@ const make = Effect.gen(function* () {
|
||||
providerName: session.provider,
|
||||
providerInstanceId: session.providerInstanceId,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
updatedAt: session.updatedAt,
|
||||
},
|
||||
|
||||
@@ -27,6 +27,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
@@ -35,7 +36,9 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
@@ -192,7 +195,10 @@ async function waitForThread(
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
|
||||
| OrchestrationEngineService
|
||||
| ProviderRuntimeIngestionService
|
||||
| ProjectionSnapshotQuery
|
||||
| ProjectionTurnRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -234,9 +240,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provide(RepositoryIdentityResolver.layer),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionTurnLayer = ProjectionTurnRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(projectionTurnLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
@@ -247,6 +257,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
const turnRepository = await runtime.runPromise(Effect.service(ProjectionTurnRepository));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
|
||||
const drain = () => Effect.runPromise(ingestion.drain);
|
||||
@@ -315,6 +326,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
emit: provider.emit,
|
||||
setProviderSession: provider.setSession,
|
||||
turnRepository,
|
||||
drain,
|
||||
};
|
||||
}
|
||||
@@ -946,6 +958,209 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("replaces streaming assistant text from authoritative snapshots without changing identity", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const itemId = asItemId("item-streaming-snapshot");
|
||||
const turnId = asTurnId("turn-streaming-snapshot");
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-streaming-snapshot-delta"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "draft",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.snapshot",
|
||||
eventId: asEventId("evt-streaming-snapshot-replace"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
text: "authoritative",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-streaming-snapshot-tail"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " answer",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-streaming-snapshot-completed"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === `assistant:${itemId}` &&
|
||||
message.text === "authoritative answer" &&
|
||||
!message.streaming,
|
||||
),
|
||||
);
|
||||
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("applies repeated empty snapshots idempotently to a streaming assistant message", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const itemId = asItemId("item-empty-snapshot");
|
||||
const turnId = asTurnId("turn-empty-snapshot");
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-empty-snapshot-delta"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "remove me",
|
||||
},
|
||||
});
|
||||
for (const eventId of ["evt-empty-snapshot-one", "evt-empty-snapshot-two"]) {
|
||||
harness.emit({
|
||||
type: "content.snapshot",
|
||||
eventId: asEventId(eventId),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
text: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-empty-snapshot-completed"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === `assistant:${itemId}` && message.text === "" && !message.streaming,
|
||||
),
|
||||
);
|
||||
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("authoritatively replaces buffered assistant text before completion", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const itemId = asItemId("item-buffered-snapshot");
|
||||
const turnId = asTurnId("turn-buffered-snapshot");
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-buffered-snapshot-delta"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "draft",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.snapshot",
|
||||
eventId: asEventId("evt-buffered-snapshot-replace"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
text: "final",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-buffered-snapshot-tail"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " answer",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-buffered-snapshot-completed"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === `assistant:${itemId}` &&
|
||||
message.text === "final answer" &&
|
||||
!message.streaming,
|
||||
),
|
||||
);
|
||||
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses assistant item completion detail when no assistant deltas were streamed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
@@ -1573,6 +1788,85 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(threadAfterSteer.latestTurn?.state).toBe("running");
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"consumes a follow-up pending start when Hermes acknowledges the active turn",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const threadId = asThreadId("thread-1");
|
||||
const activeTurnId = asTurnId("turn-hermes-active");
|
||||
const followUpMessageId = asMessageId("msg-hermes-follow-up");
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId,
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-hermes-active-turn-started"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt,
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
});
|
||||
yield* Effect.promise(() =>
|
||||
waitForThread(
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
threadId,
|
||||
),
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-hermes-follow-up"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: followUpMessageId,
|
||||
role: "user",
|
||||
text: "steer the active Hermes turn",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
const pendingBeforeAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
|
||||
threadId,
|
||||
});
|
||||
expect(Option.getOrUndefined(pendingBeforeAck)?.messageId).toBe(followUpMessageId);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-hermes-follow-up-ack"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
|
||||
const pendingAfterAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
|
||||
threadId,
|
||||
});
|
||||
const activeTurn = yield* harness.turnRepository.getByTurnId({
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
});
|
||||
expect(Option.isNone(pendingAfterAck)).toBe(true);
|
||||
expect(Option.getOrUndefined(activeTurn)?.pendingMessageId).toBe(followUpMessageId);
|
||||
}),
|
||||
);
|
||||
|
||||
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
@@ -1873,6 +2167,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";
|
||||
@@ -2452,6 +2837,65 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("replaces a spilled buffered projection when an authoritative snapshot arrives", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const itemId = asItemId("item-buffer-spill-snapshot");
|
||||
const turnId = asTurnId("turn-buffer-spill-snapshot");
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-buffer-spill-before-snapshot"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "x".repeat(40_000),
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.snapshot",
|
||||
eventId: asEventId("evt-buffer-spill-snapshot"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
text: "authoritative after spill",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-buffer-spill-snapshot-completed"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === `assistant:${itemId}` &&
|
||||
message.text === "authoritative after spill" &&
|
||||
!message.streaming,
|
||||
),
|
||||
);
|
||||
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
@@ -2758,6 +3202,147 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("upserts status_text provider item lifecycle into one meaningful activity", async () => {
|
||||
const harness = await createHarness();
|
||||
const itemId = asItemId("item-generic-activity");
|
||||
const turnId = asTurnId("turn-generic-activity");
|
||||
|
||||
harness.emit({
|
||||
type: "item.started",
|
||||
eventId: asEventId("evt-generic-activity-started"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "status_text",
|
||||
status: "inProgress",
|
||||
title: "Reading skill hermes-agent",
|
||||
detail: "Opening the skill instructions.",
|
||||
data: { unsafeRawPayload: "not projected" },
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.updated",
|
||||
eventId: asEventId("evt-generic-activity-updated"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "status_text",
|
||||
status: "inProgress",
|
||||
title: "Reading skill hermes-agent",
|
||||
detail: "Parsing the workflow.",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-generic-activity-completed"),
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "status_text",
|
||||
status: "completed",
|
||||
title: "Read skill hermes-agent",
|
||||
detail: "Skill instructions loaded.",
|
||||
},
|
||||
});
|
||||
|
||||
const activityId = `provider:hermes:item:${itemId}`;
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) =>
|
||||
activity.id === activityId &&
|
||||
activity.payload &&
|
||||
typeof activity.payload === "object" &&
|
||||
(activity.payload as Record<string, unknown>).status === "completed",
|
||||
),
|
||||
);
|
||||
const activities = thread.activities.filter((activity) => activity.id === activityId);
|
||||
const activity = activities[0];
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activities).toHaveLength(1);
|
||||
expect(activity?.kind).toBe("provider.activity");
|
||||
expect(activity?.tone).toBe("info");
|
||||
expect(activity?.summary).toBe("Skill instructions loaded.");
|
||||
expect(payload).toMatchObject({
|
||||
itemType: "status_text",
|
||||
status: "completed",
|
||||
providerItemId: itemId,
|
||||
title: "Read skill hermes-agent",
|
||||
detail: "Skill instructions loaded.",
|
||||
});
|
||||
expect(payload?.data).toBeUndefined();
|
||||
});
|
||||
|
||||
// Regression: `unknown` is the canonical "could not classify this item"
|
||||
// sentinel and adapters rely on it being INERT. CodexAdapter deliberately
|
||||
// emits it for item.updated; routing generic activity through it put rows
|
||||
// summarized as the literal string "Provider activity" into Codex threads.
|
||||
// Renderable status text has its own item type (`status_text`) instead.
|
||||
it("does not create activities for the unknown item sentinel", async () => {
|
||||
const harness = await createHarness();
|
||||
const itemId = asItemId("item-codex-unknown");
|
||||
const turnId = asTurnId("turn-codex-unknown");
|
||||
|
||||
harness.emit({
|
||||
type: "item.updated",
|
||||
eventId: asEventId("evt-codex-unknown-updated"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "unknown",
|
||||
status: "inProgress",
|
||||
},
|
||||
});
|
||||
// A tool item after it gives the poll something real to settle on, so the
|
||||
// assertion is "the unknown item produced nothing" rather than a race.
|
||||
harness.emit({
|
||||
type: "item.started",
|
||||
eventId: asEventId("evt-codex-unknown-tool"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId,
|
||||
itemId: asItemId("item-codex-tool"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "inProgress",
|
||||
title: "ls",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started",
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
thread.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === `provider:codex:item:${itemId}`,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
thread.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "provider.activity",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type AssistantDeliveryMode,
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
@@ -306,6 +307,47 @@ function requestKindFromCanonicalRequestType(
|
||||
}
|
||||
}
|
||||
|
||||
function genericProviderActivityId(event: ProviderRuntimeEvent): EventId {
|
||||
return EventId.make(
|
||||
event.itemId
|
||||
? `provider:${event.provider}:item:${event.itemId}`
|
||||
: `provider:${event.provider}:event:${event.eventId}`,
|
||||
);
|
||||
}
|
||||
|
||||
function genericProviderActivity(
|
||||
event: Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ type: "item.started" | "item.updated" | "item.completed" }
|
||||
>,
|
||||
maybeSequence: { readonly sequence?: number },
|
||||
): OrchestrationThreadActivity {
|
||||
const title = event.payload.title ? truncateDetail(event.payload.title, 120) : undefined;
|
||||
const detail = event.payload.detail ? truncateDetail(event.payload.detail) : undefined;
|
||||
const status =
|
||||
event.payload.status ?? (event.type === "item.completed" ? "completed" : "inProgress");
|
||||
|
||||
return {
|
||||
id: genericProviderActivityId(event),
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "provider.activity",
|
||||
// Status text is the interesting part here; the title is a generic label
|
||||
// ("Hermes activity"). Prefer the detail so the row reads as the status the
|
||||
// provider is actually reporting.
|
||||
summary: detail ? truncateDetail(detail, 120) : (title ?? "Working…"),
|
||||
payload: {
|
||||
itemType: event.payload.itemType,
|
||||
status,
|
||||
...(event.itemId ? { providerItemId: event.itemId } : {}),
|
||||
...(title ? { title } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
};
|
||||
}
|
||||
|
||||
export function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
taskTitle?: string,
|
||||
@@ -614,6 +656,9 @@ export function runtimeEventToActivities(
|
||||
}
|
||||
|
||||
case "item.updated": {
|
||||
if (event.payload.itemType === "status_text") {
|
||||
return [genericProviderActivity(event, maybeSequence)];
|
||||
}
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
}
|
||||
@@ -637,6 +682,9 @@ export function runtimeEventToActivities(
|
||||
}
|
||||
|
||||
case "item.completed": {
|
||||
if (event.payload.itemType === "status_text") {
|
||||
return [genericProviderActivity(event, maybeSequence)];
|
||||
}
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
}
|
||||
@@ -659,6 +707,9 @@ export function runtimeEventToActivities(
|
||||
}
|
||||
|
||||
case "item.started": {
|
||||
if (event.payload.itemType === "status_text") {
|
||||
return [genericProviderActivity(event, maybeSequence)];
|
||||
}
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
}
|
||||
@@ -899,6 +950,9 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const replaceBufferedAssistantText = (messageId: MessageId, text: string) =>
|
||||
Cache.set(bufferedAssistantTextByMessageId, messageId, text);
|
||||
|
||||
const takeBufferedAssistantText = (messageId: MessageId) =>
|
||||
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
|
||||
Effect.flatMap((existingText) =>
|
||||
@@ -1343,6 +1397,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 +1422,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 +1439,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 +1451,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(
|
||||
@@ -1457,6 +1517,10 @@ const make = Effect.gen(function* () {
|
||||
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
|
||||
? event.payload.delta
|
||||
: undefined;
|
||||
const assistantSnapshot =
|
||||
event.type === "content.snapshot" && event.payload.streamKind === "assistant_text"
|
||||
? event.payload.text
|
||||
: undefined;
|
||||
const proposedPlanDelta =
|
||||
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
|
||||
|
||||
@@ -1501,6 +1565,53 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
if (assistantSnapshot !== undefined) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const assistantMessageId = yield* getOrCreateAssistantMessageId({
|
||||
threadId: thread.id,
|
||||
event,
|
||||
...(turnId ? { turnId } : {}),
|
||||
});
|
||||
if (turnId) {
|
||||
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
);
|
||||
if (assistantDeliveryMode === "buffered") {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const hasProjectedMessage =
|
||||
findMessageById(detailedThread?.messages ?? [], assistantMessageId) !== undefined;
|
||||
if (hasProjectedMessage) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.replace",
|
||||
commandId: yield* providerCommandId(event, "assistant-snapshot-buffer-spill"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
text: assistantSnapshot,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
yield* clearBufferedAssistantText(assistantMessageId);
|
||||
} else {
|
||||
yield* replaceBufferedAssistantText(assistantMessageId, assistantSnapshot);
|
||||
}
|
||||
} else {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.replace",
|
||||
commandId: yield* providerCommandId(event, "assistant-snapshot"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
text: assistantSnapshot,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
yield* clearBufferedAssistantText(assistantMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
const pauseForUserTurnId =
|
||||
event.type === "request.opened" || event.type === "user-input.requested"
|
||||
? toTurnId(event.turnId)
|
||||
@@ -1634,7 +1745,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,73 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("assistant message replacement", (it) => {
|
||||
it.effect("emits a streaming replacement message event", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-07-24T12:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-replacement");
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(now), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("command-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-replacement"),
|
||||
title: "Replacement",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "hermes",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const decided = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.message.assistant.replace",
|
||||
commandId: CommandId.make("command-message-replace"),
|
||||
threadId,
|
||||
messageId: MessageId.make("assistant:message-1"),
|
||||
text: "Hello there",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const event = Array.isArray(decided) ? decided[0] : decided;
|
||||
if (event?.type !== "thread.message-sent") {
|
||||
throw new Error("expected thread.message-sent");
|
||||
}
|
||||
expect(event.payload.text).toBe("Hello there");
|
||||
expect(event.payload.streaming).toBe(true);
|
||||
expect(event.payload.textOperation).toBe("replace");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1018,6 +1018,34 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.message.assistant.replace": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.messageId,
|
||||
role: "assistant",
|
||||
text: command.text,
|
||||
turnId: command.turnId ?? null,
|
||||
streaming: true,
|
||||
textOperation: "replace",
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.message.assistant.complete": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -488,6 +488,83 @@ describe("orchestration projector", () => {
|
||||
expect(message?.updatedAt).toBe(completeAt);
|
||||
});
|
||||
|
||||
it("replaces an assistant snapshot between legacy appended deltas", async () => {
|
||||
const createdAt = "2026-02-23T09:00:00.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
model: "hermes",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const messageEvent = (input: {
|
||||
sequence: number;
|
||||
text: string;
|
||||
streaming: boolean;
|
||||
textOperation?: "replace";
|
||||
}) =>
|
||||
makeEvent({
|
||||
sequence: input.sequence,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: `cmd-message-${input.sequence}`,
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "assistant:msg-replace",
|
||||
role: "assistant",
|
||||
text: input.text,
|
||||
turnId: "turn-1",
|
||||
streaming: input.streaming,
|
||||
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
let projected = afterCreate;
|
||||
for (const event of [
|
||||
messageEvent({ sequence: 2, text: "Hello wor", streaming: true }),
|
||||
messageEvent({
|
||||
sequence: 3,
|
||||
text: "Hello there",
|
||||
streaming: true,
|
||||
textOperation: "replace",
|
||||
}),
|
||||
messageEvent({ sequence: 4, text: "!", streaming: true }),
|
||||
messageEvent({ sequence: 5, text: "", streaming: false }),
|
||||
]) {
|
||||
projected = await Effect.runPromise(projectEvent(projected, event));
|
||||
}
|
||||
|
||||
const message = projected.threads[0]?.messages[0];
|
||||
expect(message?.text).toBe("Hello there!");
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes reverted turn messages from in-memory thread snapshot", async () => {
|
||||
const createdAt = "2026-02-23T10:00:00.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
mergeAssistantMessageText,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationMessage,
|
||||
OrchestrationSession,
|
||||
@@ -471,11 +472,13 @@ export function projectEvent(
|
||||
entry.id === message.id
|
||||
? {
|
||||
...entry,
|
||||
text: message.streaming
|
||||
? `${entry.text}${message.text}`
|
||||
: message.text.length > 0
|
||||
? message.text
|
||||
: entry.text,
|
||||
text: mergeAssistantMessageText(entry.text, {
|
||||
text: message.text,
|
||||
streaming: message.streaming,
|
||||
...(payload.textOperation !== undefined
|
||||
? { textOperation: payload.textOperation }
|
||||
: {}),
|
||||
}),
|
||||
streaming: message.streaming,
|
||||
updatedAt: message.updatedAt,
|
||||
turnId: message.turnId,
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
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",
|
||||
// The slug stays `DEFAULT_HERMES_MODEL` no matter what the plugin
|
||||
// reports: threads bind to it, and letting it follow Hermes' current
|
||||
// config would orphan every thread whose model changed on the Hermes
|
||||
// side. The reported model is used only as the human-facing name, so
|
||||
// the picker says "gpt-5.6-terra" instead of a generic placeholder.
|
||||
// Falls back to "Hermes" when no plugin has connected yet or the
|
||||
// plugin predates the `model` field on `connection.hello`.
|
||||
models: [
|
||||
{
|
||||
slug: DEFAULT_HERMES_MODEL,
|
||||
name: status?.model ?? "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;
|
||||
}),
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,911 @@
|
||||
import {
|
||||
EventId,
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HermesGatewayRequestId,
|
||||
HermesGatewayResumeCursor,
|
||||
HermesGatewaySessionId,
|
||||
ProviderDriverKind,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type CanonicalRequestType,
|
||||
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);
|
||||
|
||||
/**
|
||||
* Hermes never queues. When the gateway socket is down there is nothing on the
|
||||
* far side to accept work, and a queued turn would silently start minutes later
|
||||
* against a thread the user has moved on from. Every send path fails
|
||||
* immediately with this text so the failure names the fix rather than showing
|
||||
* up as a generic protocol error or a 30s request timeout.
|
||||
*/
|
||||
const offlineDetail = (instanceId: ProviderInstanceId) =>
|
||||
`Hermes is offline — the '${instanceId}' gateway plugin is not connected. Start the gateway on the Hermes host (\`hermes gateway restart\`), then retry.`;
|
||||
|
||||
/**
|
||||
* `turns` exists only to answer `readThread`, which no Hermes call site reaches
|
||||
* today. Retaining every completed item for the life of the process is an
|
||||
* unbounded leak in service of that dead path, so the accumulator keeps a
|
||||
* hard-capped tail of the most recent turns/items and `readThread` reports what
|
||||
* it still holds. Raising these bounds is a deliberate decision, not something
|
||||
* that should drift with thread length.
|
||||
*/
|
||||
const MAX_RETAINED_TURNS = 8;
|
||||
const MAX_RETAINED_ITEMS_PER_TURN = 32;
|
||||
|
||||
type HermesAdapterShape = ProviderAdapterShape<
|
||||
ProviderAdapterRequestError | ProviderAdapterSessionNotFoundError | ProviderAdapterValidationError
|
||||
>;
|
||||
|
||||
interface PendingInteraction {
|
||||
readonly requestId: string;
|
||||
readonly turnId: TurnId;
|
||||
readonly requestType: CanonicalRequestType;
|
||||
}
|
||||
|
||||
interface SessionContext {
|
||||
hermesSessionId: HermesGatewaySessionId;
|
||||
readonly turns: Array<{ readonly id: TurnId; readonly items: Array<unknown> }>;
|
||||
/**
|
||||
* Approval and user-input requests T3 has shown but Hermes has not resolved.
|
||||
* The plugin holds its side in plain dicts, so a plugin restart forgets them
|
||||
* and any decision sent afterwards comes back `request-not-found`, parking
|
||||
* the turn forever. Tracking them here lets a reconnect close them out.
|
||||
*/
|
||||
readonly pendingApprovals: Map<string, PendingInteraction>;
|
||||
readonly pendingUserInputs: Map<string, PendingInteraction>;
|
||||
session: ProviderSession;
|
||||
}
|
||||
|
||||
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 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 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 requireConnected = (method: string) =>
|
||||
Effect.gen(function* (): Effect.fn.Return<void, ProviderAdapterRequestError> {
|
||||
const connected = yield* broker.isConnected(input.instanceId);
|
||||
if (!connected) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail: offlineDetail(input.instanceId),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const updateSession = (context: SessionContext, patch: Partial<ProviderSession>) => {
|
||||
context.session = {
|
||||
...context.session,
|
||||
...patch,
|
||||
updatedAt: nowIso(),
|
||||
};
|
||||
};
|
||||
|
||||
const clearActiveTurn = (
|
||||
context: SessionContext,
|
||||
patch: Omit<Partial<ProviderSession>, "activeTurnId">,
|
||||
) => {
|
||||
const { activeTurnId: _activeTurnId, ...session } = context.session;
|
||||
context.session = { ...session, ...patch, updatedAt: nowIso() };
|
||||
};
|
||||
|
||||
const trackTurn = (context: SessionContext, turnId: TurnId) => {
|
||||
if (context.turns.some((turn) => turn.id === turnId)) return;
|
||||
context.turns.push({ id: turnId, items: [] });
|
||||
while (context.turns.length > MAX_RETAINED_TURNS) context.turns.shift();
|
||||
};
|
||||
|
||||
const recordCompletedItem = (context: SessionContext, turnId: string, payload: unknown) => {
|
||||
const turn = context.turns.find((entry) => entry.id === turnId);
|
||||
if (!turn) return;
|
||||
turn.items.push(payload);
|
||||
while (turn.items.length > MAX_RETAINED_ITEMS_PER_TURN) turn.items.shift();
|
||||
};
|
||||
|
||||
/**
|
||||
* Every session-scoped plugin frame names the session it belongs to. If we do
|
||||
* not hold that session — because the thread was stopped, or the plugin is
|
||||
* still emitting for a session we already tore down — the frame has no thread
|
||||
* context on this side, and forwarding it would inject deltas and item rows
|
||||
* into a thread T3 no longer tracks. `session.exited` always guarded this;
|
||||
* the guard belongs on every session-scoped frame.
|
||||
*/
|
||||
const contextMatchesSession = (
|
||||
context: SessionContext | undefined,
|
||||
message: { readonly sessionId: HermesGatewaySessionId },
|
||||
): context is SessionContext => context?.hermesSessionId === message.sessionId;
|
||||
|
||||
const toRuntimeEvent = (message: PluginMessage) =>
|
||||
Effect.gen(function* (): Effect.fn.Return<
|
||||
ProviderRuntimeEvent | undefined,
|
||||
ProviderAdapterRequestError
|
||||
> {
|
||||
if (!("threadId" in message)) return undefined;
|
||||
const context = sessions.get(message.threadId);
|
||||
switch (message.type) {
|
||||
case "session.ready":
|
||||
return undefined;
|
||||
case "turn.started": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: TurnId.make(message.turnId),
|
||||
});
|
||||
trackTurn(context, TurnId.make(message.turnId));
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "turn.started",
|
||||
payload: {},
|
||||
};
|
||||
}
|
||||
case "content.delta": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: message.streamKind,
|
||||
delta: message.delta,
|
||||
...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "content.snapshot": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "content.snapshot",
|
||||
payload: {
|
||||
streamKind: message.streamKind,
|
||||
text: message.text,
|
||||
...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "item.started":
|
||||
case "item.updated":
|
||||
case "item.completed": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
const data = sanitizeHermesItemData(message.itemType, message.data);
|
||||
const payload = {
|
||||
itemType: message.itemType,
|
||||
...(message.status ? { status: message.status } : {}),
|
||||
...(message.title ? { title: message.title } : {}),
|
||||
...(message.detail ? { detail: message.detail } : {}),
|
||||
...(data ? { data } : {}),
|
||||
};
|
||||
if (message.type === "item.completed") {
|
||||
recordCompletedItem(context, message.turnId, payload);
|
||||
}
|
||||
return { ...(yield* eventBase(message)), type: message.type, payload };
|
||||
}
|
||||
case "request.opened": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
context.pendingApprovals.set(message.requestId, {
|
||||
requestId: message.requestId,
|
||||
turnId: TurnId.make(message.turnId),
|
||||
requestType: message.requestType,
|
||||
});
|
||||
const args = sanitizeHermesRequestArgs(message.requestType, message.args);
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: message.requestType,
|
||||
...(message.detail ? { detail: message.detail } : {}),
|
||||
...(args ? { args } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "request.resolved": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
context.pendingApprovals.delete(message.requestId);
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: message.requestType,
|
||||
...(message.decision ? { decision: message.decision } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "user-input.requested": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
context.pendingUserInputs.set(message.requestId, {
|
||||
requestId: message.requestId,
|
||||
turnId: TurnId.make(message.turnId),
|
||||
requestType: "tool_user_input",
|
||||
});
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "user-input.requested",
|
||||
payload: { questions: message.questions },
|
||||
};
|
||||
}
|
||||
case "user-input.resolved": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
context.pendingUserInputs.delete(message.requestId);
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "user-input.resolved",
|
||||
payload: { answers: message.answers },
|
||||
};
|
||||
}
|
||||
case "turn.completed": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
if (context.session.activeTurnId === message.turnId) {
|
||||
clearActiveTurn(context, { status: message.state === "failed" ? "error" : "ready" });
|
||||
}
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: message.state,
|
||||
...(message.stopReason !== undefined ? { stopReason: message.stopReason } : {}),
|
||||
...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "turn.aborted": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
if (context.session.activeTurnId === message.turnId) {
|
||||
clearActiveTurn(context, { status: "ready" });
|
||||
}
|
||||
return {
|
||||
...(yield* eventBase(message)),
|
||||
type: "turn.aborted",
|
||||
payload: { reason: message.reason },
|
||||
};
|
||||
}
|
||||
case "session.exited": {
|
||||
if (!contextMatchesSession(context, message)) return undefined;
|
||||
clearActiveTurn(context, { status: message.recoverable ? "error" : "closed" });
|
||||
const base = yield* eventBase(message);
|
||||
// A session Hermes has exited is gone on both sides. Dropping it here
|
||||
// is what keeps the sessions map from growing without bound across a
|
||||
// long-lived process's reconnect cycles.
|
||||
sessions.delete(message.threadId);
|
||||
return {
|
||||
...base,
|
||||
type: "session.exited",
|
||||
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,
|
||||
);
|
||||
|
||||
/**
|
||||
* Close out every interaction the user could still be looking at.
|
||||
*
|
||||
* The plugin keeps `_approval_requests` / `_user_input_requests` in plain
|
||||
* dicts, so a plugin restart forgets them: any decision the user makes
|
||||
* afterwards is answered `request-not-found` and the turn waits on a reply
|
||||
* that can never arrive. We deliberately do not decide on the user's behalf —
|
||||
* each request is marked resolved with no decision, which clears the pending
|
||||
* badge, and a warning row explains why it disappeared.
|
||||
*/
|
||||
const cancelPendingInteractions = (context: SessionContext, reason: string) =>
|
||||
Effect.gen(function* () {
|
||||
const approvals = Array.from(context.pendingApprovals.values());
|
||||
const userInputs = Array.from(context.pendingUserInputs.values());
|
||||
context.pendingApprovals.clear();
|
||||
context.pendingUserInputs.clear();
|
||||
if (approvals.length === 0 && userInputs.length === 0) return;
|
||||
for (const pending of approvals) {
|
||||
yield* emit({
|
||||
...(yield* eventBase({
|
||||
threadId: context.session.threadId,
|
||||
turnId: pending.turnId,
|
||||
requestId: pending.requestId,
|
||||
})),
|
||||
type: "request.resolved",
|
||||
payload: { requestType: pending.requestType },
|
||||
});
|
||||
}
|
||||
for (const pending of userInputs) {
|
||||
yield* emit({
|
||||
...(yield* eventBase({
|
||||
threadId: context.session.threadId,
|
||||
turnId: pending.turnId,
|
||||
requestId: pending.requestId,
|
||||
})),
|
||||
type: "user-input.resolved",
|
||||
payload: { answers: {} },
|
||||
});
|
||||
}
|
||||
yield* emit({
|
||||
...(yield* eventBase({ threadId: context.session.threadId })),
|
||||
type: "runtime.warning",
|
||||
payload: {
|
||||
message: `${approvals.length + userInputs.length} pending Hermes request(s) were cancelled without a decision: ${reason} Nothing was approved or denied on your behalf — ask again to re-run the step.`,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Settle a thread whose turn did not survive the reconnect.
|
||||
*
|
||||
* Without this the turn stays "running" forever: Hermes never sends a
|
||||
* terminal frame for a turn its restarted plugin no longer knows about, and
|
||||
* orchestration's conflict gate rejects any later frame naming it. A failed
|
||||
* `turn.completed` is the terminal event orchestration already folds into
|
||||
* thread state.
|
||||
*/
|
||||
const settleDeadTurn = (context: SessionContext, turnId: TurnId, message: string) =>
|
||||
Effect.gen(function* () {
|
||||
clearActiveTurn(context, { status: "error", lastError: message });
|
||||
yield* emit({
|
||||
...(yield* eventBase({ threadId: context.session.threadId, turnId })),
|
||||
type: "turn.completed",
|
||||
payload: { state: "failed", errorMessage: message },
|
||||
});
|
||||
});
|
||||
|
||||
const resumeSessionAfterReconnect = (context: SessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = context.session.threadId;
|
||||
const previousTurnId = context.session.activeTurnId;
|
||||
yield* cancelPendingInteractions(
|
||||
context,
|
||||
"the Hermes gateway reconnected and the plugin no longer holds them.",
|
||||
);
|
||||
const outcome = yield* broker
|
||||
.request(input.instanceId, {
|
||||
type: "session.ensure",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: yield* requestId,
|
||||
threadId,
|
||||
resumeSessionId: context.hermesSessionId,
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
// Anything other than a clean session.ready leaves us unable to tell
|
||||
// whether Hermes is still generating, with no channel to ask. Leaving the
|
||||
// thread "running" would hang it, so it settles with the reason spelled
|
||||
// out instead.
|
||||
const failure =
|
||||
outcome._tag === "Failure"
|
||||
? `Hermes could not resume this thread after reconnecting: ${outcome.failure.detail}`
|
||||
: outcome.success.type === "protocol.error"
|
||||
? `Hermes rejected the resume for this thread: ${outcome.success.message}`
|
||||
: outcome.success.type !== "session.ready" || outcome.success.threadId !== threadId
|
||||
? `Hermes returned '${outcome.success.type}' instead of session.ready while resuming this thread.`
|
||||
: undefined;
|
||||
if (failure !== undefined) {
|
||||
if (previousTurnId) return yield* settleDeadTurn(context, previousTurnId, failure);
|
||||
updateSession(context, { status: "error", lastError: failure });
|
||||
return;
|
||||
}
|
||||
if (outcome._tag !== "Success" || outcome.success.type !== "session.ready") return;
|
||||
const ready = outcome.success;
|
||||
|
||||
// The session may have been stopped or exited while the request was in
|
||||
// flight; do not resurrect it.
|
||||
if (sessions.get(threadId) !== context) return;
|
||||
|
||||
// Hermes owns the session id and a restarted plugin mints a new one.
|
||||
// Adopting it is what keeps the inbound context guard matching.
|
||||
context.hermesSessionId = ready.sessionId;
|
||||
updateSession(context, {
|
||||
resumeCursor: {
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
sessionId: ready.sessionId,
|
||||
} satisfies HermesGatewayResumeCursor,
|
||||
});
|
||||
|
||||
const activeTurnId = ready.activeTurnId;
|
||||
if (activeTurnId !== undefined) {
|
||||
// The turn outlived the socket. Keep streaming into it and emit nothing
|
||||
// disruptive — what follows belongs to the turn the UI already renders.
|
||||
updateSession(context, { status: "running", activeTurnId });
|
||||
trackTurn(context, activeTurnId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousTurnId) {
|
||||
yield* settleDeadTurn(
|
||||
context,
|
||||
previousTurnId,
|
||||
"The Hermes gateway reconnected without this turn — it did not survive the disconnect.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
updateSession(context, { status: "ready" });
|
||||
});
|
||||
|
||||
/**
|
||||
* The reconnect trigger. Protocol v2 already carries `activeTurnId` on
|
||||
* `session.ready` for exactly this case, but nothing re-issued
|
||||
* `session.ensure` after a drop — so a surviving turn's eventual
|
||||
* `turn.completed` arrived for a turn orchestration had written off, was
|
||||
* rejected by its conflict gate, and the thread never settled.
|
||||
*/
|
||||
// Track the connection identity, not merely whether we are connected. A
|
||||
// plugin restart usually REPLACES the socket: the old one dies as the new
|
||||
// one is accepted, so exactly one `connected` status is published and a
|
||||
// connectedness edge never fires. The plugin's session map is per-process,
|
||||
// so skipping the re-ensure there leaves T3 holding a session the new
|
||||
// process has never heard of, and its next turn.start is rejected with
|
||||
// "Call session.ensure before starting a turn" — a dead thread.
|
||||
//
|
||||
// Starts null rather than reading the current generation: sessions are only
|
||||
// created after this point, so the first status we observe has nothing to
|
||||
// resume, and treating it as new is harmless.
|
||||
let seenGeneration: number | null = null;
|
||||
yield* broker.streamStatuses.pipe(
|
||||
Stream.filter((status) => status.instanceId === input.instanceId),
|
||||
Stream.runForEach((status) =>
|
||||
Effect.gen(function* () {
|
||||
const generation = status.connectionGeneration;
|
||||
const reconnected =
|
||||
status.status === "connected" && generation !== null && generation !== seenGeneration;
|
||||
// Only advance on a live connection: holding the last generation
|
||||
// through an offline gap means the reconnect still registers as new.
|
||||
if (generation !== null) seenGeneration = generation;
|
||||
if (!reconnected) return;
|
||||
// Forked, NOT awaited. `Stream.runForEach` processes status events
|
||||
// serially, and the resume issues `session.ensure` — a correlated
|
||||
// request whose reply is delivered by the broker's message stream.
|
||||
// Awaiting it here holds up this handler, and the deadlock is only
|
||||
// broken by the 30s request timeout, after which the thread is left
|
||||
// with no session and every turn fails "Call session.ensure before
|
||||
// starting a turn". Resuming off the handler lets the reply land.
|
||||
yield* Effect.forEach(
|
||||
Array.from(sessions.values()),
|
||||
(context) =>
|
||||
resumeSessionAfterReconnect(context).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider.hermes.resume-after-reconnect-failed", {
|
||||
instanceId: input.instanceId,
|
||||
threadId: context.session.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ discard: true },
|
||||
).pipe(Effect.forkScoped);
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const startSession: HermesAdapterShape["startSession"] = Effect.fn("startSession")(
|
||||
function* (sessionInput) {
|
||||
yield* requireConnected("session.ensure");
|
||||
if (sessionInput.providerInstanceId && sessionInput.providerInstanceId !== input.instanceId) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
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 activeTurnId = response.activeTurnId;
|
||||
const session = {
|
||||
provider: PROVIDER,
|
||||
providerInstanceId: input.instanceId,
|
||||
status: activeTurnId === undefined ? "ready" : "running",
|
||||
runtimeMode: sessionInput.runtimeMode,
|
||||
...(sessionInput.cwd !== undefined ? { cwd: sessionInput.cwd } : {}),
|
||||
...(sessionInput.modelSelection?.model ? { model: sessionInput.modelSelection.model } : {}),
|
||||
...(activeTurnId !== undefined ? { activeTurnId } : {}),
|
||||
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: activeTurnId === undefined ? [] : [{ id: activeTurnId, items: [] }],
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
});
|
||||
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 method = activeTurnId ? "turn.steer" : "turn.start";
|
||||
// Checked before the request so an offline gateway fails immediately with
|
||||
// an actionable message instead of parking on the broker's request timeout.
|
||||
yield* requireConnected(method);
|
||||
const turnId = activeTurnId ?? TurnId.make(`hermes-turn-${yield* randomId}`);
|
||||
const outboundRequestId = yield* requestId;
|
||||
const response = yield* broker.request(input.instanceId, {
|
||||
type: activeTurnId ? "turn.steer" : "turn.start",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: outboundRequestId,
|
||||
threadId: turnInput.threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
turnId,
|
||||
text,
|
||||
});
|
||||
if (response.type !== "turn.started") {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail:
|
||||
response.type === "protocol.error"
|
||||
? response.message
|
||||
: `Expected turn.started, received '${response.type}'.`,
|
||||
});
|
||||
}
|
||||
updateSession(context, { status: "running", activeTurnId: turnId });
|
||||
trackTurn(context, 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* requireConnected("turn.interrupt");
|
||||
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* requireConnected("approval.respond");
|
||||
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,
|
||||
});
|
||||
context.pendingApprovals.delete(selectedRequestId);
|
||||
}),
|
||||
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* requireConnected("user-input.respond");
|
||||
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,
|
||||
});
|
||||
context.pendingUserInputs.delete(selectedRequestId);
|
||||
}),
|
||||
stopSession: (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* findContext(threadId);
|
||||
if (!(yield* broker.isConnected(input.instanceId))) {
|
||||
// The stop was never delivered: Hermes still owns this thread and
|
||||
// keeps generating. Deleting our state here would orphan it — frames
|
||||
// arriving after a reconnect would have no session to match, and the
|
||||
// user would have no way to stop it. Keep the session so the reconnect
|
||||
// path can resume it and a later stop can actually land.
|
||||
updateSession(context, { status: "error", lastError: offlineDetail(input.instanceId) });
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session.stop",
|
||||
detail: offlineDetail(input.instanceId),
|
||||
});
|
||||
}
|
||||
yield* broker.send(input.instanceId, {
|
||||
type: "session.stop",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: yield* requestId,
|
||||
threadId,
|
||||
sessionId: context.hermesSessionId,
|
||||
});
|
||||
updateSession(context, { status: "closed" });
|
||||
sessions.delete(threadId);
|
||||
}),
|
||||
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,
|
||||
// Bounded to the most recent turns/items — older history lives in the
|
||||
// orchestration projections, not in adapter memory.
|
||||
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) =>
|
||||
// A stop that could not be delivered (typically: the gateway is
|
||||
// offline) must not abort the sweep or fail shutdown. The session is
|
||||
// deliberately left in place rather than orphaned.
|
||||
adapter.stopSession(threadId).pipe(
|
||||
Effect.catchTag("ProviderAdapterRequestError", (error) =>
|
||||
Effect.logWarning("provider.hermes.stop-session-undeliverable", {
|
||||
instanceId: input.instanceId,
|
||||
threadId,
|
||||
detail: error.detail,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ discard: true },
|
||||
),
|
||||
streamEvents: Stream.fromPubSub(events),
|
||||
};
|
||||
|
||||
// Deliberately NOT `stopAll()`. Hermes sessions live in a separate process
|
||||
// that outlives this one, and `session.stop` makes the plugin drop the
|
||||
// thread from its active set — so tearing down on shutdown meant every
|
||||
// thread open when T3 restarted came back unusable: the next turn.start was
|
||||
// rejected with "Call session.ensure before starting a turn", with no way to
|
||||
// recover from the UI. Threads created after the restart worked, which is
|
||||
// what made it look like a resume bug rather than a shutdown bug.
|
||||
//
|
||||
// Dropping local state without telling the plugin is the correct shutdown:
|
||||
// the resume cursor is persisted, and the next turn re-issues session.ensure
|
||||
// against the session Hermes still holds. Explicit user-initiated stops
|
||||
// still go through `stopSession` and do end the remote session.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
sessions.clear();
|
||||
}),
|
||||
);
|
||||
return adapter;
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Live {@link HermesConnectionRegistry}. See the service module for why this
|
||||
* state is memory-only and how generation fencing works.
|
||||
*
|
||||
* @module Layers/HermesConnectionRegistry
|
||||
*/
|
||||
import type { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import type {
|
||||
HermesActiveConnection,
|
||||
HermesConnectionRegistry,
|
||||
HermesInstanceLiveness,
|
||||
HermesLivenessStatusFields,
|
||||
HermesObservedConnection,
|
||||
} from "../Services/HermesConnectionRegistry.ts";
|
||||
|
||||
/** Strip the transport/scope/generation from a connection to keep as `lastSeen`. */
|
||||
const toObserved = (connection: HermesActiveConnection): HermesObservedConnection => ({
|
||||
pluginVersion: connection.pluginVersion,
|
||||
hermesVersion: connection.hermesVersion,
|
||||
capabilities: connection.capabilities,
|
||||
model: connection.model,
|
||||
connectedAt: connection.connectedAt,
|
||||
activeSessionCount: connection.activeSessionCount,
|
||||
});
|
||||
|
||||
/**
|
||||
* Project liveness into the status fields it owns. Prefers the live connection,
|
||||
* falls back to `lastSeen`, and finally to whatever the incompatible plugin
|
||||
* advertised.
|
||||
*/
|
||||
export const livenessStatusFields = (
|
||||
liveness: HermesInstanceLiveness | undefined,
|
||||
): HermesLivenessStatusFields => {
|
||||
const observed = liveness?.connection ?? liveness?.lastSeen;
|
||||
return {
|
||||
lastConnectedAt: observed?.connectedAt ?? null,
|
||||
pluginVersion: observed?.pluginVersion ?? liveness?.upgradeRequired?.pluginVersion ?? null,
|
||||
hermesVersion: observed?.hermesVersion ?? liveness?.upgradeRequired?.hermesVersion ?? null,
|
||||
model: observed?.model ?? liveness?.upgradeRequired?.model ?? null,
|
||||
activeSessionCount: liveness?.connection?.activeSessionCount ?? 0,
|
||||
protocolVersion:
|
||||
observed?.capabilities.protocolVersion ?? liveness?.upgradeRequired?.protocolVersion ?? null,
|
||||
capabilities: observed?.capabilities ?? null,
|
||||
// Exposed so consumers can tell a replacement (old socket dies as a new
|
||||
// one is accepted, publishing a single `connected` status) from a
|
||||
// continuous connection. Watching connectedness alone cannot.
|
||||
connectionGeneration: liveness?.connection?.generation ?? null,
|
||||
connected: liveness?.connection !== undefined,
|
||||
upgradeRequired: liveness?.upgradeRequired !== undefined,
|
||||
};
|
||||
};
|
||||
|
||||
export const makeHermesConnectionRegistry = Effect.gen(function* () {
|
||||
const states = yield* Ref.make(new Map<ProviderInstanceId, HermesInstanceLiveness>());
|
||||
const generation = yield* Ref.make(0);
|
||||
|
||||
/** Write liveness for one instance, dropping the entry when it goes empty. */
|
||||
const setLiveness = (
|
||||
current: ReadonlyMap<ProviderInstanceId, HermesInstanceLiveness>,
|
||||
instanceId: ProviderInstanceId,
|
||||
liveness: HermesInstanceLiveness,
|
||||
) => {
|
||||
const next = new Map(current);
|
||||
if (
|
||||
liveness.connection === undefined &&
|
||||
liveness.lastSeen === undefined &&
|
||||
liveness.upgradeRequired === undefined
|
||||
) {
|
||||
next.delete(instanceId);
|
||||
} else {
|
||||
next.set(instanceId, liveness);
|
||||
}
|
||||
return next;
|
||||
};
|
||||
|
||||
const liveness = (instanceId: ProviderInstanceId) =>
|
||||
Ref.get(states).pipe(Effect.map((current) => current.get(instanceId)));
|
||||
|
||||
const accept: HermesConnectionRegistry["accept"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1);
|
||||
// The connection scope is a child of nothing in particular: it is closed
|
||||
// explicitly on disconnect/replace so per-connection fibers (ping) die
|
||||
// exactly with the connection they belong to.
|
||||
const scope = yield* Scope.make();
|
||||
const connection: HermesActiveConnection = {
|
||||
...input.observed,
|
||||
generation: nextGeneration,
|
||||
transport: input.transport,
|
||||
scope,
|
||||
};
|
||||
|
||||
const displaced = yield* Ref.modify(states, (current) => {
|
||||
const found = current.get(input.instanceId);
|
||||
return [
|
||||
found?.connection,
|
||||
setLiveness(current, input.instanceId, {
|
||||
connection,
|
||||
lastSeen: toObserved(connection),
|
||||
// Accepting a compatible connection clears any stale
|
||||
// upgrade-required observation for this instance.
|
||||
upgradeRequired: undefined,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
return { generation: nextGeneration, displaced };
|
||||
});
|
||||
|
||||
const markUpgradeRequired: HermesConnectionRegistry["markUpgradeRequired"] = (input) =>
|
||||
Ref.modify(states, (current) => {
|
||||
const found = current.get(input.instanceId);
|
||||
return [
|
||||
found?.connection,
|
||||
setLiveness(current, input.instanceId, {
|
||||
connection: undefined,
|
||||
lastSeen: found?.lastSeen,
|
||||
upgradeRequired: input.upgradeRequired,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
const recordSessionCount: HermesConnectionRegistry["recordSessionCount"] = (
|
||||
registration,
|
||||
activeSessionCount,
|
||||
) =>
|
||||
Ref.modify(states, (current) => {
|
||||
const found = current.get(registration.instanceId);
|
||||
// Fence inside the update so a replacement that lands between a read and
|
||||
// this write cannot be clobbered.
|
||||
if (found?.connection?.generation !== registration.generation) {
|
||||
return [false, current] as const;
|
||||
}
|
||||
const connection: HermesActiveConnection = { ...found.connection, activeSessionCount };
|
||||
return [
|
||||
true,
|
||||
setLiveness(current, registration.instanceId, {
|
||||
...found,
|
||||
connection,
|
||||
lastSeen: toObserved(connection),
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
const disconnect: HermesConnectionRegistry["disconnect"] = (registration) =>
|
||||
Effect.gen(function* () {
|
||||
const retired = yield* Ref.modify(states, (current) => {
|
||||
const found = current.get(registration.instanceId);
|
||||
if (found?.connection?.generation !== registration.generation) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
return [
|
||||
found.connection,
|
||||
setLiveness(current, registration.instanceId, {
|
||||
connection: undefined,
|
||||
lastSeen: toObserved(found.connection),
|
||||
upgradeRequired: found.upgradeRequired,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (retired) yield* Scope.close(retired.scope, Exit.void).pipe(Effect.ignore);
|
||||
return retired;
|
||||
});
|
||||
|
||||
const clearConnection: HermesConnectionRegistry["clearConnection"] = (instanceId) =>
|
||||
Effect.gen(function* () {
|
||||
const cleared = yield* Ref.modify(states, (current) => {
|
||||
const found = current.get(instanceId);
|
||||
if (!found?.connection) return [undefined, current] as const;
|
||||
return [
|
||||
found.connection,
|
||||
setLiveness(current, instanceId, {
|
||||
connection: undefined,
|
||||
lastSeen: toObserved(found.connection),
|
||||
upgradeRequired: found.upgradeRequired,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (cleared) yield* Scope.close(cleared.scope, Exit.void).pipe(Effect.ignore);
|
||||
return cleared;
|
||||
});
|
||||
|
||||
const forget = (instanceId: ProviderInstanceId) =>
|
||||
Effect.gen(function* () {
|
||||
const dropped = yield* Ref.modify(states, (current) => {
|
||||
const found = current.get(instanceId);
|
||||
if (!found) return [undefined, current] as const;
|
||||
const next = new Map(current);
|
||||
next.delete(instanceId);
|
||||
return [found.connection, next] as const;
|
||||
});
|
||||
if (dropped) yield* Scope.close(dropped.scope, Exit.void).pipe(Effect.ignore);
|
||||
});
|
||||
|
||||
return {
|
||||
liveness,
|
||||
accept,
|
||||
markUpgradeRequired,
|
||||
recordSessionCount,
|
||||
disconnect,
|
||||
clearConnection,
|
||||
forget,
|
||||
isConnected: (instanceId) =>
|
||||
liveness(instanceId).pipe(Effect.map((found) => found?.connection !== undefined)),
|
||||
transport: (instanceId) =>
|
||||
liveness(instanceId).pipe(Effect.map((found) => found?.connection?.transport)),
|
||||
} satisfies HermesConnectionRegistry;
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Live {@link HermesEnrollmentStore}. See the service module for the token
|
||||
* rules this upholds.
|
||||
*
|
||||
* @module Layers/HermesEnrollmentStore
|
||||
*/
|
||||
import { HermesGatewayEnrollmentToken, type ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import type {
|
||||
HermesEnrollmentStore,
|
||||
PendingEnrollment,
|
||||
} from "../Services/HermesEnrollmentStore.ts";
|
||||
|
||||
const ENROLLMENT_TOKEN_BYTES = 32;
|
||||
|
||||
export interface MakeHermesEnrollmentStoreOptions {
|
||||
readonly ttl: Duration.Duration;
|
||||
}
|
||||
|
||||
export const makeHermesEnrollmentStore = (
|
||||
options: MakeHermesEnrollmentStoreOptions,
|
||||
): Effect.Effect<HermesEnrollmentStore, never, Crypto.Crypto> =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const enrollments = yield* Ref.make(new Map<string, PendingEnrollment>());
|
||||
|
||||
const mint: HermesEnrollmentStore["mint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const bytes = yield* crypto.randomBytes(ENROLLMENT_TOKEN_BYTES).pipe(Effect.orDie);
|
||||
const token = HermesGatewayEnrollmentToken.make(Encoding.encodeBase64Url(bytes));
|
||||
const expiresAtMillis = (yield* Clock.currentTimeMillis) + Duration.toMillis(options.ttl);
|
||||
|
||||
yield* Ref.update(enrollments, (current) => {
|
||||
const next = new Map(current);
|
||||
// Minting supersedes this instance's previous tokens so only the
|
||||
// newest unconsumed token is redeemable.
|
||||
for (const [pendingToken, pending] of current) {
|
||||
if (pending.input.instanceId === input.instanceId) next.delete(pendingToken);
|
||||
}
|
||||
return next.set(token, { input, expiresAtMillis });
|
||||
});
|
||||
|
||||
return { token, expiresAtMillis };
|
||||
});
|
||||
|
||||
const peek: HermesEnrollmentStore["peek"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const found = (yield* Ref.get(enrollments)).get(token);
|
||||
if (!found) return undefined;
|
||||
return found.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : found;
|
||||
});
|
||||
|
||||
const consume: HermesEnrollmentStore["consume"] = (token, expected) =>
|
||||
Effect.gen(function* () {
|
||||
// Compare-and-swap: delete only if the entry is still the exact object
|
||||
// the caller authenticated against, so a concurrent redemption or a
|
||||
// re-mint in between cannot be consumed by this caller.
|
||||
const claimed = yield* Ref.modify(enrollments, (current) => {
|
||||
const found = current.get(token);
|
||||
if (found !== expected) return [undefined, current] as const;
|
||||
const next = new Map(current);
|
||||
next.delete(token);
|
||||
return [found, next] as const;
|
||||
});
|
||||
if (claimed === undefined) return undefined;
|
||||
// Re-check expiry after winning the swap: the entry may have aged out
|
||||
// between authentication and consumption.
|
||||
return claimed.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : claimed;
|
||||
});
|
||||
|
||||
const forget = (instanceId: ProviderInstanceId) =>
|
||||
Ref.update(enrollments, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const [token, pending] of current) {
|
||||
if (pending.input.instanceId === instanceId) next.delete(token);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const sweep = Clock.currentTimeMillis.pipe(
|
||||
Effect.flatMap((now) =>
|
||||
Ref.update(enrollments, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const [token, pending] of current) {
|
||||
if (pending.expiresAtMillis < now) next.delete(token);
|
||||
}
|
||||
return next.size === current.size ? current : next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
mint,
|
||||
peek,
|
||||
consume,
|
||||
forget,
|
||||
sweep,
|
||||
size: Ref.get(enrollments).pipe(Effect.map((current) => current.size)),
|
||||
} satisfies HermesEnrollmentStore;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
HERMES_DRIVER_KIND,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { deriveProviderInstanceConfigMap } from "./ProviderInstanceRegistryHydration.ts";
|
||||
|
||||
it("does not synthesize a legacy default Hermes instance", () => {
|
||||
const instances = deriveProviderInstanceConfigMap(DEFAULT_SERVER_SETTINGS);
|
||||
|
||||
assert.isUndefined(instances[ProviderInstanceId.make("hermes")]);
|
||||
assert.equal(instances[ProviderInstanceId.make("codex")]?.driver, "codex");
|
||||
});
|
||||
|
||||
it("preserves an explicit Hermes instance whose id matches the driver default", () => {
|
||||
const instanceId = ProviderInstanceId.make("hermes");
|
||||
const instances = deriveProviderInstanceConfigMap({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: HERMES_DRIVER_KIND,
|
||||
displayName: "Research Hermes",
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(instances[instanceId], {
|
||||
driver: HERMES_DRIVER_KIND,
|
||||
displayName: "Research Hermes",
|
||||
enabled: true,
|
||||
config: {},
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,8 @@
|
||||
* `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
|
||||
* routing slug), we synthesize an envelope from the legacy field. The
|
||||
* registry decodes both flavours through the same `configSchema` and ends
|
||||
* up with one uniform `ProviderInstance` per entry.
|
||||
* up with one uniform `ProviderInstance` per entry. Drivers such as Hermes
|
||||
* that require an explicitly paired remote instance opt out of synthesis.
|
||||
*
|
||||
* Explicit `providerInstances` entries always win — users can already
|
||||
* override the legacy `providers.<kind>` blob by authoring a
|
||||
@@ -43,6 +44,7 @@
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
HERMES_DRIVER_KIND,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceConfigMap,
|
||||
ServerSettings,
|
||||
@@ -62,9 +64,10 @@ import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistry
|
||||
*
|
||||
* Strategy:
|
||||
* 1. Copy all explicit `settings.providerInstances` entries verbatim.
|
||||
* 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
|
||||
* is *not* already in the explicit map, synthesize an entry from the
|
||||
* matching legacy `settings.providers.<kind>` blob.
|
||||
* 2. For each legacy-compatible built-in driver whose
|
||||
* `defaultInstanceIdForDriver(id)` key is *not* already in the explicit
|
||||
* map, synthesize an entry from the matching legacy
|
||||
* `settings.providers.<kind>` blob.
|
||||
*
|
||||
* The returned map is the input the registry consumes; pure & exported
|
||||
* separately so the hydration logic can be exercised by unit tests
|
||||
@@ -82,6 +85,12 @@ export const deriveProviderInstanceConfigMap = (
|
||||
// config always wins over the legacy mirror.
|
||||
continue;
|
||||
}
|
||||
if (driver.driverKind === HERMES_DRIVER_KIND) {
|
||||
// Hermes is configured only through explicit gateway instances. A
|
||||
// synthesized legacy default would resurrect a revoked-and-removed
|
||||
// instance in settings and provider pickers.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only built-in drivers have a legacy mirror; the registry's
|
||||
// `providers` struct is keyed on the same literal slug as
|
||||
|
||||
@@ -280,20 +280,24 @@ function makeMutableServerSettingsService(
|
||||
return Effect.gen(function* () {
|
||||
const settingsRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.unbounded<ContractServerSettings>();
|
||||
const updateSettingsWith = (
|
||||
update: (current: ContractServerSettings) => Parameters<typeof applyServerSettingsPatch>[1],
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(settingsRef);
|
||||
const next = applyServerSettingsPatch(current, update(current));
|
||||
encodeServerSettings(next);
|
||||
yield* Ref.set(settingsRef, next);
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
});
|
||||
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(settingsRef);
|
||||
const next = applyServerSettingsPatch(current, patch);
|
||||
encodeServerSettings(next);
|
||||
yield* Ref.set(settingsRef, next);
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
}),
|
||||
updateSettings: (patch) => updateSettingsWith(() => patch),
|
||||
updateSettingsWith,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changes);
|
||||
},
|
||||
|
||||
@@ -1280,6 +1280,170 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
|
||||
}
|
||||
}
|
||||
|
||||
yield* advanceTestClock(50);
|
||||
routing.codex.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-runtime-status-stale-completion"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-from-an-older-request"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
|
||||
const afterStaleCompletion = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(afterStaleCompletion), true);
|
||||
if (Option.isSome(afterStaleCompletion)) {
|
||||
assert.equal(afterStaleCompletion.value.status, "running");
|
||||
const payload = afterStaleCompletion.value.runtimePayload;
|
||||
assert.equal(payload !== null && typeof payload === "object", true);
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
assert.equal(
|
||||
"activeTurnId" in payload ? payload.activeTurnId : undefined,
|
||||
`turn-${String(session.threadId)}`,
|
||||
);
|
||||
assert.equal(
|
||||
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
|
||||
"turn.completed",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
routing.codex.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-runtime-status-active-completion"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId(`turn-${String(session.threadId)}`),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
|
||||
const afterActiveCompletion = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(afterActiveCompletion), true);
|
||||
if (Option.isSome(afterActiveCompletion)) {
|
||||
assert.equal(afterActiveCompletion.value.status, "running");
|
||||
const payload = afterActiveCompletion.value.runtimePayload;
|
||||
assert.equal(payload !== null && typeof payload === "object", true);
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
|
||||
assert.equal("cwd" in payload ? payload.cwd : undefined, session.cwd);
|
||||
assert.equal(
|
||||
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
|
||||
"turn.completed",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A *failed* completion of the active turn must persist "error". This
|
||||
// shared a ternary branch with turn.started and wrote "running" for every
|
||||
// settled turn, failed ones included.
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
attachments: [],
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
routing.codex.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-runtime-status-failed-completion"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.500Z",
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId(`turn-${String(session.threadId)}`),
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: "Hermes could not resume this thread after reconnecting.",
|
||||
},
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
|
||||
const afterFailedCompletion = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(afterFailedCompletion), true);
|
||||
if (Option.isSome(afterFailedCompletion)) {
|
||||
assert.equal(afterFailedCompletion.value.status, "error");
|
||||
const payload = afterFailedCompletion.value.runtimePayload;
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
|
||||
}
|
||||
}
|
||||
|
||||
// A matching turn.aborted settles the same way, minus the error.
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello once more",
|
||||
attachments: [],
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
routing.codex.emit({
|
||||
type: "turn.aborted",
|
||||
eventId: asEventId("evt-runtime-status-active-abort"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.750Z",
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId(`turn-${String(session.threadId)}`),
|
||||
payload: { reason: "interrupted" },
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
|
||||
const afterAbort = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(afterAbort), true);
|
||||
if (Option.isSome(afterAbort)) {
|
||||
assert.equal(afterAbort.value.status, "running");
|
||||
const payload = afterAbort.value.runtimePayload;
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
|
||||
assert.equal(
|
||||
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
|
||||
"turn.aborted",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
routing.codex.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-runtime-status-session-exit"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
threadId: session.threadId,
|
||||
payload: {
|
||||
exitKind: "error",
|
||||
recoverable: true,
|
||||
},
|
||||
});
|
||||
yield* advanceTestClock(50);
|
||||
|
||||
const afterSessionExit = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(afterSessionExit), true);
|
||||
if (Option.isSome(afterSessionExit)) {
|
||||
assert.equal(afterSessionExit.value.status, "error");
|
||||
const payload = afterSessionExit.value.runtimePayload;
|
||||
assert.equal(payload !== null && typeof payload === "object", true);
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
|
||||
assert.equal(
|
||||
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
|
||||
"session.exited",
|
||||
);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -162,6 +162,19 @@ function readPersistedCwd(
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function readPersistedActiveTurnId(
|
||||
runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
|
||||
): string | null | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const rawActiveTurnId =
|
||||
"activeTurnId" in runtimePayload ? runtimePayload.activeTurnId : undefined;
|
||||
return typeof rawActiveTurnId === "string" || rawActiveTurnId === null
|
||||
? rawActiveTurnId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const dieOnMissingBindingInstanceId = (
|
||||
operation: string,
|
||||
payload: {
|
||||
@@ -281,6 +294,84 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const persistRuntimeLifecycle = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
event.type !== "turn.started" &&
|
||||
event.type !== "turn.completed" &&
|
||||
event.type !== "turn.aborted" &&
|
||||
event.type !== "session.exited"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const binding = Option.getOrUndefined(yield* directory.getBinding(event.threadId));
|
||||
if (!binding || event.providerInstanceId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
binding.provider !== event.provider ||
|
||||
binding.providerInstanceId !== event.providerInstanceId
|
||||
) {
|
||||
yield* Effect.logWarning("provider.session.runtime.lifecycle-binding-mismatch", {
|
||||
threadId: event.threadId,
|
||||
eventProvider: event.provider,
|
||||
eventProviderInstanceId: event.providerInstanceId,
|
||||
bindingProvider: binding.provider,
|
||||
bindingProviderInstanceId: binding.providerInstanceId,
|
||||
eventType: event.type,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const persistedActiveTurnId = readPersistedActiveTurnId(binding.runtimePayload);
|
||||
const terminalMatchesActiveTurn =
|
||||
(event.type === "turn.completed" || event.type === "turn.aborted") &&
|
||||
event.turnId !== undefined &&
|
||||
persistedActiveTurnId === event.turnId;
|
||||
const isSessionExit = event.type === "session.exited";
|
||||
// `turn.started` and a terminal event that closes the active turn are
|
||||
// opposite transitions and must not share a branch. Folded together they
|
||||
// persisted "running" for every settled turn — including a *failed* one,
|
||||
// which is the lie this split removes.
|
||||
//
|
||||
// A non-failed terminal still writes "running": this status describes the
|
||||
// session, not the turn (`toRuntimeStatus` maps both ready and running to
|
||||
// it), and the settled turn is expressed by `activeTurnId: null` below.
|
||||
// "stopped" is reserved for sessions that are actually gone — the reaper
|
||||
// skips those, so using it for an idle session would strand it.
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
: terminalMatchesActiveTurn
|
||||
? event.type === "turn.completed" && event.payload.state === "failed"
|
||||
? "error"
|
||||
: "running"
|
||||
: isSessionExit
|
||||
? event.payload.recoverable === true || event.payload.exitKind === "error"
|
||||
? "error"
|
||||
: "stopped"
|
||||
: undefined;
|
||||
const activeTurnId =
|
||||
event.type === "turn.started"
|
||||
? (event.turnId ?? persistedActiveTurnId)
|
||||
: terminalMatchesActiveTurn || isSessionExit
|
||||
? null
|
||||
: persistedActiveTurnId;
|
||||
|
||||
yield* directory.upsert({
|
||||
threadId: event.threadId,
|
||||
provider: event.provider,
|
||||
providerInstanceId: event.providerInstanceId,
|
||||
...(status !== undefined ? { status } : {}),
|
||||
runtimePayload: {
|
||||
...(activeTurnId !== undefined ? { activeTurnId } : {}),
|
||||
lastRuntimeEvent: event.type,
|
||||
lastRuntimeEventAt: event.createdAt,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const processRuntimeEvent = (
|
||||
source: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
@@ -293,7 +384,22 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
increment(providerRuntimeEventsTotal, {
|
||||
provider: canonicalEvent.provider,
|
||||
eventType: canonicalEvent.type,
|
||||
}).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
persistRuntimeLifecycle(canonicalEvent).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider.session.runtime.lifecycle-persist-failed", {
|
||||
threadId: canonicalEvent.threadId,
|
||||
provider: canonicalEvent.provider,
|
||||
providerInstanceId: canonicalEvent.providerInstanceId,
|
||||
eventType: canonicalEvent.type,
|
||||
errorTag: causeErrorTag(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.andThen(publishRuntimeEvent(canonicalEvent)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Live {@link RequestCorrelator} implementation.
|
||||
*
|
||||
* Generic over the owner key (the route a request travels over) and the
|
||||
* response payload, so this is reusable by any provider with correlated
|
||||
* request/response framing — see the module docs on the service for why the
|
||||
* interrupt-safety and sweeping guarantees live here rather than at call sites.
|
||||
*
|
||||
* @module Layers/RequestCorrelator
|
||||
*/
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import { ProviderAdapterRequestError } from "../Errors.ts";
|
||||
import type { RequestCorrelator, RequestCorrelatorSend } from "../Services/RequestCorrelator.ts";
|
||||
|
||||
interface PendingRequest<Owner, Response> {
|
||||
readonly owner: Owner;
|
||||
readonly method: string;
|
||||
readonly registeredAtMillis: number;
|
||||
readonly deferred: Deferred.Deferred<Response, ProviderAdapterRequestError>;
|
||||
}
|
||||
|
||||
export interface MakeRequestCorrelatorOptions {
|
||||
/** Provider name stamped onto `ProviderAdapterRequestError`. */
|
||||
readonly provider: string;
|
||||
/** Default response timeout when a request does not override it. */
|
||||
readonly timeout: Duration.Duration;
|
||||
/**
|
||||
* Entries older than this are reaped by `sweep`. Comfortably larger than
|
||||
* `timeout` so the sweeper only ever catches entries whose own timeout
|
||||
* pipeline failed to run — a normal slow request is never stolen from
|
||||
* underneath its awaiting fiber.
|
||||
*/
|
||||
readonly maxAge: Duration.Duration;
|
||||
}
|
||||
|
||||
export const makeRequestCorrelator = <Owner, Response>(
|
||||
options: MakeRequestCorrelatorOptions,
|
||||
): Effect.Effect<RequestCorrelator<Owner, Response>> =>
|
||||
Effect.gen(function* () {
|
||||
const pending = yield* Ref.make(new Map<string, PendingRequest<Owner, Response>>());
|
||||
|
||||
const requestError = (method: string, detail: string) =>
|
||||
new ProviderAdapterRequestError({ provider: options.provider, method, detail });
|
||||
|
||||
/** Remove one entry by id. Safe to call when it is already gone. */
|
||||
const release = (requestId: string) =>
|
||||
Ref.update(pending, (current) => {
|
||||
if (!current.has(requestId)) return current;
|
||||
const next = new Map(current);
|
||||
next.delete(requestId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const request = (input: RequestCorrelatorSend<Owner>) =>
|
||||
Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<Response, ProviderAdapterRequestError>();
|
||||
const registeredAtMillis = yield* Clock.currentTimeMillis;
|
||||
|
||||
// Registration and the send must not be interruptible independently of
|
||||
// the cleanup that removes the entry. `uninterruptibleMask` closes the
|
||||
// window: the registration is applied, `restore` re-enables interrupts
|
||||
// only inside the awaiting pipeline, and `ensuring` guarantees release
|
||||
// regardless of how that pipeline exits.
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.update(pending, (current) =>
|
||||
new Map(current).set(input.requestId, {
|
||||
owner: input.owner,
|
||||
method: input.method,
|
||||
registeredAtMillis,
|
||||
deferred,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* input.send.pipe(Effect.tapError(() => release(input.requestId)));
|
||||
|
||||
return yield* restore(Deferred.await(deferred)).pipe(
|
||||
Effect.timeout(input.timeout ?? options.timeout),
|
||||
Effect.mapError((error) =>
|
||||
error._tag === "TimeoutError"
|
||||
? requestError(input.method, `${options.provider} request timed out.`)
|
||||
: error,
|
||||
),
|
||||
Effect.ensuring(release(input.requestId)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const complete = (requestId: string, response: Response) =>
|
||||
Ref.modify(pending, (current) => {
|
||||
const found = current.get(requestId);
|
||||
if (!found) return [undefined, current] as const;
|
||||
const next = new Map(current);
|
||||
next.delete(requestId);
|
||||
return [found, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((found) =>
|
||||
found === undefined
|
||||
? Effect.succeed(false)
|
||||
: Deferred.succeed(found.deferred, response).pipe(Effect.as(true)),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Extract every entry matching `select`, then fail their deferreds. The
|
||||
* extraction is a single `Ref.modify` so two concurrent failures cannot
|
||||
* both claim the same entry.
|
||||
*/
|
||||
const failMatching = (
|
||||
select: (entry: PendingRequest<Owner, Response>) => boolean,
|
||||
detail: (entry: PendingRequest<Owner, Response>) => string,
|
||||
) =>
|
||||
Ref.modify(pending, (current) => {
|
||||
const claimed: Array<PendingRequest<Owner, Response>> = [];
|
||||
const next = new Map(current);
|
||||
for (const [requestId, entry] of current) {
|
||||
if (!select(entry)) continue;
|
||||
claimed.push(entry);
|
||||
next.delete(requestId);
|
||||
}
|
||||
return [claimed, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((claimed) =>
|
||||
Effect.forEach(
|
||||
claimed,
|
||||
(entry) => Deferred.fail(entry.deferred, requestError(entry.method, detail(entry))),
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const failOwner = (owner: Owner, detail: string) =>
|
||||
failMatching(
|
||||
(entry) => entry.owner === owner,
|
||||
() => detail,
|
||||
);
|
||||
|
||||
const sweep = Clock.currentTimeMillis.pipe(
|
||||
Effect.flatMap((now) =>
|
||||
failMatching(
|
||||
(entry) => now - entry.registeredAtMillis >= Duration.toMillis(options.maxAge),
|
||||
() => `${options.provider} request was abandoned before it completed.`,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
request,
|
||||
complete,
|
||||
failOwner,
|
||||
sweep,
|
||||
pendingCount: Ref.get(pending).pipe(Effect.map((current) => current.size)),
|
||||
} satisfies RequestCorrelator<Owner, Response>;
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* HermesConnectionRegistry — owner of **volatile** Hermes gateway liveness.
|
||||
*
|
||||
* Everything in here is deliberately memory-only and is never persisted:
|
||||
* the live connection, its transport, `lastSeen`, `activeSessionCount`, the
|
||||
* reported model, and the `upgrade-required` observation.
|
||||
*
|
||||
* Why liveness must not be persisted
|
||||
* ----------------------------------
|
||||
* `ProviderInstanceRegistryLive.reconcile` structurally compares each
|
||||
* `ProviderInstanceConfig` envelope and closes the instance scope on **any**
|
||||
* change. Closing that scope runs `HermesAdapter`'s finalizer, which calls
|
||||
* `stopAll()` and sends `session.stop` to Hermes for every live thread. So
|
||||
* writing something like `connectedAt` into the instance config on every
|
||||
* connect would tear down every Hermes session on every reconnect.
|
||||
*
|
||||
* The broker (and therefore this registry) is a top-level layer that survives
|
||||
* reconcile, which makes it the correct owner of liveness. The accepted
|
||||
* consequence is that after a T3 server restart the UI reports "never
|
||||
* connected" until the plugin dials back in. That is intended.
|
||||
*
|
||||
* Generation fencing
|
||||
* ------------------
|
||||
* Every accepted connection gets a monotonically increasing generation. All
|
||||
* post-acceptance mutations are fenced on it, and the comparison happens
|
||||
* *inside* the `Ref` update rather than as a separate read, so a replacement
|
||||
* landing concurrently cannot be clobbered by a stale writer (TOCTOU).
|
||||
*
|
||||
* @module HermesConnectionRegistry
|
||||
*/
|
||||
import type {
|
||||
HermesGatewayCapabilities,
|
||||
HermesGatewayInstanceStatus,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import type {
|
||||
HermesGatewayConnectionRegistration,
|
||||
HermesGatewayTransport,
|
||||
} from "./HermesGatewayBroker.ts";
|
||||
|
||||
/** Observed facts about a plugin connection, independent of its transport. */
|
||||
export interface HermesObservedConnection {
|
||||
readonly pluginVersion: string;
|
||||
readonly hermesVersion: string;
|
||||
readonly capabilities: HermesGatewayCapabilities;
|
||||
/** Model reported at handshake. Null when the plugin predates the field. */
|
||||
readonly model: string | null;
|
||||
readonly connectedAt: string;
|
||||
readonly activeSessionCount: number;
|
||||
}
|
||||
|
||||
export interface HermesActiveConnection extends HermesObservedConnection {
|
||||
readonly generation: number;
|
||||
readonly transport: HermesGatewayTransport;
|
||||
/**
|
||||
* Scope tied to this connection's lifetime. Per-connection fibers (the ping
|
||||
* loop) are forked into it, so they die exactly when the connection does.
|
||||
*/
|
||||
readonly scope: Scope.Closeable;
|
||||
}
|
||||
|
||||
export interface HermesUpgradeRequired {
|
||||
readonly pluginVersion: string;
|
||||
readonly hermesVersion: string;
|
||||
readonly protocolVersion: number;
|
||||
readonly model: string | null;
|
||||
}
|
||||
|
||||
/** Volatile per-instance liveness. Absent entry means "nothing observed yet". */
|
||||
export interface HermesInstanceLiveness {
|
||||
readonly connection?: HermesActiveConnection | undefined;
|
||||
readonly lastSeen?: HermesObservedConnection | undefined;
|
||||
readonly upgradeRequired?: HermesUpgradeRequired | undefined;
|
||||
}
|
||||
|
||||
export interface HermesAcceptedConnection {
|
||||
readonly generation: number;
|
||||
/**
|
||||
* The connection this one displaced, if any. The caller is responsible for
|
||||
* closing it — the registry never touches a transport itself, so callers can
|
||||
* order the close against failing pending requests.
|
||||
*/
|
||||
readonly displaced: HermesActiveConnection | undefined;
|
||||
}
|
||||
|
||||
export interface HermesConnectionRegistry {
|
||||
/** Current liveness for one instance, or `undefined` if nothing observed. */
|
||||
readonly liveness: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesInstanceLiveness | undefined>;
|
||||
|
||||
/** Accept a connection, assigning it the next generation. */
|
||||
readonly accept: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly transport: HermesGatewayTransport;
|
||||
readonly observed: HermesObservedConnection;
|
||||
}) => Effect.Effect<HermesAcceptedConnection>;
|
||||
|
||||
/**
|
||||
* Record an incompatible plugin. Clears any live connection for the instance
|
||||
* and returns it so the caller can close it.
|
||||
*/
|
||||
readonly markUpgradeRequired: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly upgradeRequired: HermesUpgradeRequired;
|
||||
}) => Effect.Effect<HermesActiveConnection | undefined>;
|
||||
|
||||
/**
|
||||
* Update the active session count. Generation-fenced; returns `false` when
|
||||
* the registration is stale, in which case nothing was written.
|
||||
*/
|
||||
readonly recordSessionCount: (
|
||||
registration: HermesGatewayConnectionRegistration,
|
||||
activeSessionCount: number,
|
||||
) => Effect.Effect<boolean>;
|
||||
|
||||
/**
|
||||
* Retire a connection, demoting it to `lastSeen`. Generation-fenced;
|
||||
* returns the retired connection, or `undefined` when the registration is
|
||||
* stale (already replaced) and nothing was changed.
|
||||
*/
|
||||
readonly disconnect: (
|
||||
registration: HermesGatewayConnectionRegistration,
|
||||
) => Effect.Effect<HermesActiveConnection | undefined>;
|
||||
|
||||
/**
|
||||
* Clear the live connection for an instance regardless of generation, e.g.
|
||||
* on revoke. Returns it so the caller can close the transport.
|
||||
*/
|
||||
readonly clearConnection: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesActiveConnection | undefined>;
|
||||
|
||||
/** Drop all liveness for an instance (on remove). */
|
||||
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
|
||||
|
||||
/** Whether a live connection exists. */
|
||||
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
|
||||
|
||||
/** Live transport for an instance, if connected. */
|
||||
readonly transport: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayTransport | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the status fields owned by liveness. The durable half (nickname,
|
||||
* connectorUrl, revoked) is layered on by the broker, which reads it from
|
||||
* settings.
|
||||
*/
|
||||
export type HermesLivenessStatusFields = Pick<
|
||||
HermesGatewayInstanceStatus,
|
||||
| "lastConnectedAt"
|
||||
| "pluginVersion"
|
||||
| "hermesVersion"
|
||||
| "model"
|
||||
| "activeSessionCount"
|
||||
| "protocolVersion"
|
||||
| "capabilities"
|
||||
| "connectionGeneration"
|
||||
> & {
|
||||
readonly connected: boolean;
|
||||
readonly upgradeRequired: boolean;
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* HermesEnrollmentStore — the mint/consume/expire lifecycle of one-time
|
||||
* enrollment tokens.
|
||||
*
|
||||
* Separated from the broker so the token rules live in one place:
|
||||
*
|
||||
* - A token is redeemable exactly once. Consumption is compare-and-swap:
|
||||
* the entry is deleted only if it is still byte-identical to the one the
|
||||
* caller authenticated against, and expiry is re-checked afterwards, so
|
||||
* two concurrent redemptions cannot both win.
|
||||
* - Minting a token for an instance invalidates that instance's previous
|
||||
* tokens, so only the newest unconsumed token is ever redeemable.
|
||||
* - Tokens expire from memory on a sweep, not only lazily at redemption.
|
||||
* Redemption-time expiry alone let any operator-scoped client grow the
|
||||
* map without bound by calling createEnrollment in a loop.
|
||||
*
|
||||
* @module HermesEnrollmentStore
|
||||
*/
|
||||
import type {
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayEnrollmentToken,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export interface PendingEnrollment {
|
||||
readonly input: HermesGatewayCreateEnrollmentInput;
|
||||
readonly expiresAtMillis: number;
|
||||
}
|
||||
|
||||
export interface HermesEnrollmentStore {
|
||||
/**
|
||||
* Mint a token for `input`, invalidating any prior unconsumed token for the
|
||||
* same instance. Returns the token and its absolute expiry.
|
||||
*/
|
||||
readonly mint: (
|
||||
input: HermesGatewayCreateEnrollmentInput,
|
||||
) => Effect.Effect<
|
||||
{ readonly token: HermesGatewayEnrollmentToken; readonly expiresAtMillis: number },
|
||||
never
|
||||
>;
|
||||
|
||||
/**
|
||||
* Look up a token without consuming it. Returns `undefined` when the token
|
||||
* is unknown or already expired — the caller authenticates against this
|
||||
* value and later passes it back to `consume`.
|
||||
*/
|
||||
readonly peek: (token: string) => Effect.Effect<PendingEnrollment | undefined>;
|
||||
|
||||
/**
|
||||
* Compare-and-swap consumption. Deletes the entry only if it is still
|
||||
* identical to `expected`, then re-checks expiry. Returns the consumed
|
||||
* enrollment, or `undefined` if it was raced away or expired in between.
|
||||
*/
|
||||
readonly consume: (
|
||||
token: string,
|
||||
expected: PendingEnrollment,
|
||||
) => Effect.Effect<PendingEnrollment | undefined>;
|
||||
|
||||
/** Drop every unconsumed token belonging to `instanceId`. */
|
||||
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
|
||||
|
||||
/** Drop every expired token. Run periodically; bounds memory. */
|
||||
readonly sweep: Effect.Effect<void>;
|
||||
|
||||
/** Number of unconsumed tokens. Exposed for tests and diagnostics. */
|
||||
readonly size: Effect.Effect<number>;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import type {
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayEnrollmentResult,
|
||||
HermesGatewayInstanceStatus,
|
||||
HermesGatewayPluginToT3Message,
|
||||
HermesGatewayRemoveInstanceResult,
|
||||
HermesGatewayRenameInstanceInput,
|
||||
HermesGatewayRenameInstanceResult,
|
||||
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 renameInstance: (
|
||||
input: HermesGatewayRenameInstanceInput,
|
||||
) => Effect.Effect<HermesGatewayRenameInstanceResult, HermesGatewayManagementError>;
|
||||
readonly revokeInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayRevokeInstanceResult, HermesGatewayManagementError>;
|
||||
readonly removeInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<HermesGatewayRemoveInstanceResult, 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(),
|
||||
renameInstance: unavailable,
|
||||
revokeInstance: unavailable,
|
||||
removeInstance: unavailable,
|
||||
registerConnection: unavailable,
|
||||
receive: unavailable,
|
||||
disconnect: unavailable,
|
||||
request: unavailable,
|
||||
send: unavailable,
|
||||
isConnected: () => Effect.succeed(false),
|
||||
stream: Stream.empty,
|
||||
streamStatuses: Stream.empty,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* RequestCorrelator — generic request/response correlation over a one-way
|
||||
* message transport.
|
||||
*
|
||||
* Nothing in here is Hermes-specific. Any provider that speaks a protocol
|
||||
* where a request carries an id and the reply echoes it can use this: register
|
||||
* a pending entry, write the request, await the correlated reply, and have the
|
||||
* entry torn down on success, failure, timeout, or interrupt.
|
||||
*
|
||||
* The correlator owns three guarantees the call sites used to hand-roll:
|
||||
*
|
||||
* 1. **No interrupt window.** Registration happens uninterruptibly and the
|
||||
* await pipeline is wrapped in `ensuring`, so there is no point at which
|
||||
* an interrupt can leave an entry in the map with nobody to clean it up.
|
||||
* 2. **Age-based sweeping.** An entry whose awaiting fiber died abnormally
|
||||
* is reaped by `sweep` instead of leaking for the process lifetime.
|
||||
* 3. **Owner-scoped failure.** When a connection drops, every request routed
|
||||
* over it fails immediately rather than waiting out its timeout.
|
||||
*
|
||||
* @module RequestCorrelator
|
||||
*/
|
||||
import type * as Duration from "effect/Duration";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { ProviderAdapterRequestError } from "../Errors.ts";
|
||||
|
||||
export interface RequestCorrelatorSend<Owner> {
|
||||
/**
|
||||
* The logical route the request travels over. Used to fail an entire group
|
||||
* of in-flight requests at once when that route dies (see `failOwner`).
|
||||
*/
|
||||
readonly owner: Owner;
|
||||
/** Correlation key. Must match the id echoed on the response. */
|
||||
readonly requestId: string;
|
||||
/** Protocol method name, surfaced on errors for diagnostics. */
|
||||
readonly method: string;
|
||||
/** Writes the request. Registration is already in place when this runs. */
|
||||
readonly send: Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
/** Overrides the correlator's default response timeout. */
|
||||
readonly timeout?: Duration.Duration | undefined;
|
||||
}
|
||||
|
||||
export interface RequestCorrelator<Owner, Response> {
|
||||
/**
|
||||
* Register, send, and await the correlated response. Cleans up the pending
|
||||
* entry on every exit path, including interrupt.
|
||||
*/
|
||||
readonly request: (
|
||||
input: RequestCorrelatorSend<Owner>,
|
||||
) => Effect.Effect<Response, ProviderAdapterRequestError>;
|
||||
|
||||
/**
|
||||
* Resolve a pending request. Returns `false` when no entry was waiting,
|
||||
* which lets callers distinguish a correlated reply from an unsolicited one.
|
||||
*/
|
||||
readonly complete: (requestId: string, response: Response) => Effect.Effect<boolean>;
|
||||
|
||||
/** Fail every pending request registered against `owner`. */
|
||||
readonly failOwner: (owner: Owner, detail: string) => Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* Fail pending entries older than the configured max age. Safety net for
|
||||
* entries whose awaiting fiber died without running its own cleanup.
|
||||
*/
|
||||
readonly sweep: Effect.Effect<void>;
|
||||
|
||||
/** Number of in-flight requests. Exposed for tests and diagnostics. */
|
||||
readonly pendingCount: Effect.Effect<number>;
|
||||
}
|
||||
@@ -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();
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -563,6 +563,7 @@ const buildAppUnderTest = (options?: {
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
updateSettingsWith: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.serverSettings,
|
||||
}),
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -90,6 +90,55 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(settingsLayer));
|
||||
});
|
||||
|
||||
it.effect("does not report post-commit materialization failure as an update failure", () => {
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: "provider environment secret",
|
||||
description: "Secret backend unavailable after settings commit.",
|
||||
});
|
||||
const cause = new ServerSecretStore.SecretStoreReadError({
|
||||
resource: "provider environment secret",
|
||||
cause: platformCause,
|
||||
});
|
||||
const configLayer = Layer.fresh(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-server-settings-post-commit-failure-test-",
|
||||
}),
|
||||
);
|
||||
const settingsLayer = ServerSettingsModule.layer.pipe(
|
||||
Layer.provide(makeFailingSecretStoreLayer(cause)),
|
||||
Layer.provideMerge(configLayer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const hermesId = ProviderInstanceId.make("hermes_remote");
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
'{"providerInstances":{"hermes_remote":{"driver":"hermes","displayName":"Remote Hermes","config":{}},"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}',
|
||||
);
|
||||
|
||||
const next = yield* serverSettings.updateSettingsWith((current) => {
|
||||
const providerInstances = { ...current.providerInstances };
|
||||
delete providerInstances[hermesId];
|
||||
return { providerInstances };
|
||||
});
|
||||
|
||||
assert.isUndefined(next.providerInstances[hermesId]);
|
||||
assert.equal(
|
||||
next.providerInstances[ProviderInstanceId.make("codex_personal")]?.environment?.[0]?.value,
|
||||
"",
|
||||
);
|
||||
const persisted = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.notInclude(persisted, "hermes_remote");
|
||||
assert.include(persisted, "codex_personal");
|
||||
}).pipe(Effect.provide(settingsLayer));
|
||||
});
|
||||
|
||||
it.effect("decodes nested settings patches", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.deepEqual(
|
||||
|
||||
@@ -125,6 +125,15 @@ export class ServerSettingsService extends Context.Service<
|
||||
patch: ServerSettingsPatch,
|
||||
) => Effect.Effect<ServerSettings, ServerSettingsError>;
|
||||
|
||||
/**
|
||||
* Compute and persist a patch while holding the settings write lock.
|
||||
* Use this for read-modify-write operations on whole-map fields such as
|
||||
* `providerInstances`, so concurrent settings edits are preserved.
|
||||
*/
|
||||
readonly updateSettingsWith: (
|
||||
update: (current: ServerSettings) => ServerSettingsPatch,
|
||||
) => Effect.Effect<ServerSettings, ServerSettingsError>;
|
||||
|
||||
/** Stream of settings change events. */
|
||||
readonly streamChanges: Stream.Stream<ServerSettings>;
|
||||
}
|
||||
@@ -144,17 +153,24 @@ const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
: {}),
|
||||
});
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
|
||||
const writeSemaphore = yield* Semaphore.make(1);
|
||||
const updateSettingsWith = (update: (current: ServerSettings) => ServerSettingsPatch) =>
|
||||
writeSemaphore.withPermits(1)(
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) =>
|
||||
applyServerSettingsPatch(currentSettings, update(currentSettings)),
|
||||
),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
),
|
||||
updateSettings: (patch) => updateSettingsWith(() => patch),
|
||||
updateSettingsWith,
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsService["Service"];
|
||||
});
|
||||
@@ -556,6 +572,35 @@ const make = Effect.gen(function* () {
|
||||
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
const updateSettingsWith = (update: (current: ServerSettings) => ServerSettingsPatch) =>
|
||||
writeSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getSettingsFromCache;
|
||||
const nextPersisted = yield* persistProviderEnvironmentSecrets(
|
||||
current,
|
||||
applyServerSettingsPatch(current, update(current)),
|
||||
);
|
||||
const next = yield* normalizeServerSettings(nextPersisted);
|
||||
yield* writeSettingsAtomically(next);
|
||||
yield* Cache.set(settingsCache, cacheKey, next);
|
||||
yield* emitChange(next);
|
||||
const materialized = yield* materializeProviderEnvironmentSecrets(next).pipe(
|
||||
Effect.catch((error: ServerSettingsError) =>
|
||||
Effect.logWarning(
|
||||
"settings update committed but provider environment secrets could not be materialized",
|
||||
{
|
||||
operation: error.operation,
|
||||
providerInstanceId: error.providerInstanceId,
|
||||
environmentVariable: error.environmentVariable,
|
||||
cause: error.cause,
|
||||
},
|
||||
).pipe(Effect.as(next)),
|
||||
),
|
||||
);
|
||||
return resolveTextGenerationProvider(materialized);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
start,
|
||||
ready: Deferred.await(startedDeferred),
|
||||
@@ -563,22 +608,8 @@ const make = Effect.gen(function* () {
|
||||
Effect.flatMap(materializeProviderEnvironmentSecrets),
|
||||
Effect.map(resolveTextGenerationProvider),
|
||||
),
|
||||
updateSettings: (patch) =>
|
||||
writeSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getSettingsFromCache;
|
||||
const nextPersisted = yield* persistProviderEnvironmentSecrets(
|
||||
current,
|
||||
applyServerSettingsPatch(current, patch),
|
||||
);
|
||||
const next = yield* normalizeServerSettings(nextPersisted);
|
||||
yield* writeSettingsAtomically(next);
|
||||
yield* Cache.set(settingsCache, cacheKey, next);
|
||||
yield* emitChange(next);
|
||||
const materialized = yield* materializeProviderEnvironmentSecrets(next);
|
||||
return resolveTextGenerationProvider(materialized);
|
||||
}),
|
||||
),
|
||||
updateSettings: (patch) => updateSettingsWith(() => patch),
|
||||
updateSettingsWith,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub).pipe(
|
||||
Stream.mapEffect((settings) =>
|
||||
|
||||
@@ -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,12 @@ 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.hermesGatewayRenameInstance, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.hermesGatewayRevokeInstance, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.hermesGatewayRemoveInstance, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope],
|
||||
[WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope],
|
||||
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
|
||||
@@ -420,6 +427,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 +1529,42 @@ 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.hermesGatewayRenameInstance]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayRenameInstance,
|
||||
hermesGatewayBroker.renameInstance(input),
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.hermesGatewayRevokeInstance]: ({ instanceId }) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayRevokeInstance,
|
||||
hermesGatewayBroker.revokeInstance(instanceId),
|
||||
{ "rpc.aggregate": "hermes-gateway" },
|
||||
),
|
||||
[WS_METHODS.hermesGatewayRemoveInstance]: ({ instanceId }) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.hermesGatewayRemoveInstance,
|
||||
hermesGatewayBroker.removeInstance(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,184 @@
|
||||
import type { HermesGatewayConnectionState, 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;
|
||||
|
||||
/**
|
||||
* Hermes thread bindings outlive a removed gateway, so a new gateway must
|
||||
* never derive its routing identity from a reusable display name. The UUID is
|
||||
* generated once by the dialog and remains stable across enrollment retries.
|
||||
*/
|
||||
export function createHermesProviderInstanceId(label: string, randomUuid: () => string) {
|
||||
const suffix = randomUuid()
|
||||
.replace(/[^a-zA-Z0-9]/gu, "")
|
||||
.toLowerCase();
|
||||
if (suffix.length === 0) {
|
||||
throw new Error("Could not generate a Hermes instance ID.");
|
||||
}
|
||||
const labelSlug = label
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/gu, "-")
|
||||
.replace(/^-+|-+$/gu, "")
|
||||
.slice(0, 44);
|
||||
const shortSuffix = suffix.slice(0, 12);
|
||||
return labelSlug ? `hermes-${labelSlug}-${shortSuffix}` : `hermes-${shortSuffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command that installs the gateway plugin into the Hermes profile.
|
||||
*
|
||||
* Installation is a manual step performed on the Hermes host — T3 has no
|
||||
* remote access to it — so the dialog documents the command rather than
|
||||
* implying anything happens automatically. The script symlinks this repository
|
||||
* checkout into `~/.hermes/plugins` and enables the plugin.
|
||||
*/
|
||||
export const HERMES_PLUGIN_INSTALL_COMMAND = "./integrations/hermes-t3-gateway/install.sh" as const;
|
||||
|
||||
/**
|
||||
* Activates the pairing. The gateway only constructs the platform adapter at
|
||||
* startup, so it keeps reporting offline until it is restarted.
|
||||
*/
|
||||
export const HERMES_GATEWAY_RESTART_COMMAND = "hermes gateway restart" as const;
|
||||
|
||||
export function isHermesInstanceRemovedError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "instance-removed"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop an instance the dialog itself just wrote, without clobbering anything
|
||||
* that changed underneath it.
|
||||
*
|
||||
* Used to roll back the settings write when Hermes enrollment fails. The
|
||||
* server is authoritative between the write and the rollback, so this reads
|
||||
* the *latest* map rather than restoring a captured pre-write snapshot — that
|
||||
* would silently revert instances added by another client in between. If the
|
||||
* id is already gone, or has been replaced by a different config object, the
|
||||
* write is not ours to undo and `null` signals "no rollback needed".
|
||||
*/
|
||||
export function rollbackProviderInstances<T>(input: {
|
||||
readonly latest: Readonly<Record<string, T>>;
|
||||
readonly instanceId: string;
|
||||
readonly written: T;
|
||||
}): Record<string, T> | null {
|
||||
const current = input.latest[input.instanceId];
|
||||
if (current === undefined) return null;
|
||||
if (current !== input.written) return null;
|
||||
const next = { ...input.latest };
|
||||
delete next[input.instanceId];
|
||||
return next;
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presentation state of the post-enrollment "waiting for Hermes" panel.
|
||||
*
|
||||
* `waiting` is the expected steady state immediately after the command is
|
||||
* generated — the user still has to paste it and restart the gateway — so it
|
||||
* is deliberately not modelled as an error. `expired` and `blocked` are the
|
||||
* two states that need a fresh command, and `connected` is terminal success.
|
||||
*/
|
||||
export type HermesWaitingPhase = "waiting" | "connected" | "blocked" | "expired";
|
||||
|
||||
export interface HermesWaitingState {
|
||||
readonly phase: HermesWaitingPhase;
|
||||
readonly statusLabelState: HermesGatewayConnectionState;
|
||||
/** True while T3 legitimately has nothing to report yet. */
|
||||
readonly isPending: boolean;
|
||||
/** True when the only way forward is minting a replacement command. */
|
||||
readonly needsNewCommand: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve what the waiting panel should show.
|
||||
*
|
||||
* Connection wins over expiry: once the gateway has dialled in, the one-time
|
||||
* token has already been consumed and its expiry is irrelevant. `revoked` and
|
||||
* `upgrade-required` are surfaced ahead of the generic wait because neither
|
||||
* resolves by waiting longer.
|
||||
*/
|
||||
export function resolveHermesWaitingState(input: {
|
||||
readonly connectionState: HermesGatewayConnectionState | null;
|
||||
readonly isExpired: boolean;
|
||||
}): HermesWaitingState {
|
||||
if (input.connectionState === "connected") {
|
||||
return {
|
||||
phase: "connected",
|
||||
statusLabelState: "connected",
|
||||
isPending: false,
|
||||
needsNewCommand: false,
|
||||
};
|
||||
}
|
||||
if (input.connectionState === "upgrade-required" || input.connectionState === "revoked") {
|
||||
return {
|
||||
phase: "blocked",
|
||||
statusLabelState: input.connectionState,
|
||||
isPending: false,
|
||||
needsNewCommand: input.connectionState === "revoked",
|
||||
};
|
||||
}
|
||||
if (input.isExpired) {
|
||||
return {
|
||||
phase: "expired",
|
||||
statusLabelState: input.connectionState ?? "offline",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: "waiting",
|
||||
statusLabelState: input.connectionState ?? "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
};
|
||||
}
|
||||
|
||||
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,48 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveWizardNavigation } from "./AddProviderInstanceDialog.logic";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
createHermesProviderInstanceId,
|
||||
isHermesInstanceRemovedError,
|
||||
isOwnedHermesEnrollmentRetry,
|
||||
resolveHermesWaitingState,
|
||||
resolveWizardNavigation,
|
||||
rollbackProviderInstances,
|
||||
validateProviderInstanceIdForWizard,
|
||||
} from "./AddProviderInstanceDialog.logic";
|
||||
|
||||
describe("Hermes provider instance identity", () => {
|
||||
it("keeps the readable label prefix while adding a stable random suffix", () => {
|
||||
expect(
|
||||
createHermesProviderInstanceId("Research Team", () => "019f99cc-30d4-72c4-b3dd-2ee59cecb856"),
|
||||
).toBe("hermes-research-team-019f99cc30d4");
|
||||
});
|
||||
|
||||
it("never reuses an ID when a later dialog uses the same label", () => {
|
||||
expect(
|
||||
createHermesProviderInstanceId("Research", () => "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
|
||||
).not.toBe(
|
||||
createHermesProviderInstanceId("Research", () => "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
|
||||
);
|
||||
});
|
||||
|
||||
it("stays within the provider instance ID length limit for long labels", () => {
|
||||
const instanceId = createHermesProviderInstanceId(
|
||||
"A very long research Hermes display name that should be truncated before persistence",
|
||||
() => "019f99cc-30d4-72c4-b3dd-2ee59cecb856",
|
||||
);
|
||||
|
||||
expect(instanceId.length).toBeLessThanOrEqual(64);
|
||||
expect(instanceId).toMatch(/^hermes-[a-z0-9-]+-[a-z0-9]{12}$/u);
|
||||
});
|
||||
|
||||
it("recognizes a server tombstone rejection so the dialog can rotate its nonce", () => {
|
||||
expect(isHermesInstanceRemovedError({ code: "instance-removed" })).toBe(true);
|
||||
expect(isHermesInstanceRemovedError({ code: "nickname-conflict" })).toBe(false);
|
||||
expect(isHermesInstanceRemovedError(new Error("instance removed"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWizardNavigation", () => {
|
||||
const invalidId = { instanceIdError: "Instance ID is required." };
|
||||
@@ -42,3 +84,154 @@ 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");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rollbackProviderInstances", () => {
|
||||
interface TestInstance {
|
||||
readonly driver: string;
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
const written: TestInstance = { driver: "hermes", enabled: true };
|
||||
const other: TestInstance = { driver: "codex", enabled: true };
|
||||
|
||||
it("removes only the instance this dialog wrote", () => {
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": written, codex_work: other },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toEqual({ codex_work: other });
|
||||
});
|
||||
|
||||
it("preserves instances another client added between the write and the rollback", () => {
|
||||
const concurrent: TestInstance = { driver: "claude", enabled: true };
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": written, "added-elsewhere": concurrent },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toEqual({ "added-elsewhere": concurrent });
|
||||
});
|
||||
|
||||
it("does nothing when the id is already gone or was replaced by a different config", () => {
|
||||
expect(
|
||||
rollbackProviderInstances({ latest: { codex_work: other }, instanceId: "hermes-a", written }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": { ...written } },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHermesWaitingState", () => {
|
||||
it("treats a not-yet-dialled-in gateway as an expected pending wait, not an error", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: null, isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "offline", isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "connecting", isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "connecting",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("flips to connected and ignores expiry once the gateway has dialled in", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: "connected", isExpired: true })).toEqual({
|
||||
phase: "connected",
|
||||
statusLabelState: "connected",
|
||||
isPending: false,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("offers a fresh command when the one-time token expired unused", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: "offline", isExpired: true })).toEqual({
|
||||
phase: "expired",
|
||||
statusLabelState: "offline",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces upgrade-required and revoked ahead of waiting, since neither resolves by waiting", () => {
|
||||
expect(
|
||||
resolveHermesWaitingState({ connectionState: "upgrade-required", isExpired: false }),
|
||||
).toEqual({
|
||||
phase: "blocked",
|
||||
statusLabelState: "upgrade-required",
|
||||
isPending: false,
|
||||
// A protocol upgrade needs a new plugin, not a new token.
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "revoked", isExpired: false })).toEqual({
|
||||
phase: "blocked",
|
||||
statusLabelState: "revoked",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
canRemoveHermesGatewayInstance,
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
hermesGatewayLifecycleAction,
|
||||
hermesGatewayProviderSignal,
|
||||
hermesGatewayStatusGuidance,
|
||||
hermesGatewayStatusLabel,
|
||||
isHermesEnrollmentExpired,
|
||||
isHermesInstanceNotFoundError,
|
||||
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("only offers permanent removal after credentials are revoked", () => {
|
||||
expect(canRemoveHermesGatewayInstance("connected")).toBe(false);
|
||||
expect(canRemoveHermesGatewayInstance("offline")).toBe(false);
|
||||
expect(canRemoveHermesGatewayInstance("revoked")).toBe(true);
|
||||
});
|
||||
|
||||
it("offers setup cleanup only for a structured missing-instance response", () => {
|
||||
expect(isHermesInstanceNotFoundError({ code: "instance-not-found" })).toBe(true);
|
||||
expect(isHermesInstanceNotFoundError(new Error("Network unavailable"))).toBe(false);
|
||||
expect(isHermesInstanceNotFoundError({ code: "internal-error" })).toBe(false);
|
||||
|
||||
expect(hermesGatewayLifecycleAction({ status: "offline", instanceNotFound: true })).toBe(
|
||||
"remove-setup",
|
||||
);
|
||||
expect(hermesGatewayLifecycleAction({ status: "offline", instanceNotFound: false })).toBe(
|
||||
"revoke",
|
||||
);
|
||||
expect(hermesGatewayLifecycleAction({ status: "connected", instanceNotFound: false })).toBe(
|
||||
"revoke",
|
||||
);
|
||||
expect(hermesGatewayLifecycleAction({ status: "revoked", instanceNotFound: false })).toBe(
|
||||
"remove-instance",
|
||||
);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes waiting-state helpers", () => {
|
||||
it("tells the user the restart is expected rather than reporting a bare status", () => {
|
||||
expect(hermesGatewayStatusGuidance("offline")).toContain("hermes gateway restart");
|
||||
expect(hermesGatewayStatusGuidance("connected")).toContain("connected");
|
||||
});
|
||||
|
||||
it("makes upgrade-required actionable by naming the plugin reinstall", () => {
|
||||
const guidance = hermesGatewayStatusGuidance("upgrade-required");
|
||||
expect(guidance).toContain("plugin");
|
||||
expect(guidance).toContain("install script");
|
||||
});
|
||||
|
||||
it("points a revoked gateway at a new pairing command", () => {
|
||||
expect(hermesGatewayStatusGuidance("revoked")).toContain("new command");
|
||||
});
|
||||
|
||||
it("expires a one-time token at its deadline but trusts the server on garbage input", () => {
|
||||
const expiresAt = "2026-07-24T12:00:00.000Z";
|
||||
const expiryMillis = Date.parse(expiresAt);
|
||||
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis - 1)).toBe(false);
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis)).toBe(true);
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis + 60_000)).toBe(true);
|
||||
expect(isHermesEnrollmentExpired("not-a-date", expiryMillis)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hermesGatewayProviderSignal", () => {
|
||||
const provider = (
|
||||
instanceId: string,
|
||||
status: "authenticated" | "unauthenticated",
|
||||
checkedAt = "2026-07-24T12:00:00.000Z",
|
||||
) =>
|
||||
({
|
||||
instanceId,
|
||||
driver: "hermes",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status, type: "gateway", label: "Hermes" },
|
||||
checkedAt,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
}) as never;
|
||||
|
||||
it("reports a connected gateway from the pushed provider snapshot", () => {
|
||||
expect(
|
||||
hermesGatewayProviderSignal([provider("hermes-a", "authenticated")], "hermes-a"),
|
||||
).toEqual({ present: true, connected: true, revision: "2026-07-24T12:00:00.000Z" });
|
||||
});
|
||||
|
||||
it("distinguishes an enrolled-but-not-yet-dialled-in gateway from a missing one", () => {
|
||||
expect(
|
||||
hermesGatewayProviderSignal([provider("hermes-a", "unauthenticated")], "hermes-a"),
|
||||
).toEqual({ present: true, connected: false, revision: "2026-07-24T12:00:00.000Z" });
|
||||
expect(hermesGatewayProviderSignal([], "hermes-a")).toEqual({
|
||||
present: false,
|
||||
connected: false,
|
||||
revision: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("changes revision when a republished snapshot leaves the connected flag untouched", () => {
|
||||
// An `upgrade-required` transition closes the connection, so `connected`
|
||||
// stays false across the republish; only `revision` moves.
|
||||
const before = hermesGatewayProviderSignal(
|
||||
[provider("hermes-a", "unauthenticated")],
|
||||
"hermes-a",
|
||||
);
|
||||
const after = hermesGatewayProviderSignal(
|
||||
[provider("hermes-a", "unauthenticated", "2026-07-24T12:05:00.000Z")],
|
||||
"hermes-a",
|
||||
);
|
||||
|
||||
expect(after.connected).toBe(before.connected);
|
||||
expect(after.revision).not.toBe(before.revision);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { HermesGatewayConnectionState, ServerProvider } 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";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Actionable follow-up for each connection state.
|
||||
*
|
||||
* `upgrade-required` in particular is not a transient condition: the plugin
|
||||
* negotiated an incompatible protocol version and the connection was closed,
|
||||
* so the user has to reinstall the plugin rather than wait.
|
||||
*/
|
||||
export function hermesGatewayStatusGuidance(status: HermesGatewayConnectionState): string {
|
||||
switch (status) {
|
||||
case "connected":
|
||||
return "Hermes is connected. You can start sending it messages.";
|
||||
case "connecting":
|
||||
return "Hermes is completing its handshake with T3 Code.";
|
||||
case "upgrade-required":
|
||||
return "This Hermes host runs an incompatible T3 Code gateway plugin. Re-run the install script on that host to update the plugin, then run 'hermes gateway restart'.";
|
||||
case "revoked":
|
||||
return "This gateway's credential was revoked. Generate a new command to pair it again.";
|
||||
case "offline":
|
||||
return "Hermes has not dialled in yet. Run the command on the Hermes host, then run 'hermes gateway restart'.";
|
||||
}
|
||||
}
|
||||
|
||||
export function canRemoveHermesGatewayInstance(status: HermesGatewayConnectionState): boolean {
|
||||
return status === "revoked";
|
||||
}
|
||||
|
||||
/**
|
||||
* Coarse liveness read of a Hermes instance taken from the server-pushed
|
||||
* provider snapshot.
|
||||
*
|
||||
* `ServerProvider` already streams to every client over `subscribeServerConfig`
|
||||
* whenever the broker publishes a gateway status change, so surfaces that only
|
||||
* need "has Hermes dialled in yet?" can flip off it without polling. The
|
||||
* snapshot deliberately does not carry the full `HermesGatewayConnectionState`,
|
||||
* so callers that need `upgrade-required` / `revoked` still read the
|
||||
* authoritative status once this signal changes.
|
||||
*/
|
||||
export interface HermesGatewayProviderSignal {
|
||||
readonly present: boolean;
|
||||
readonly connected: boolean;
|
||||
/**
|
||||
* Changes on every republished snapshot, including ones whose connected flag
|
||||
* is unchanged. `upgrade-required` closes the connection, so it looks
|
||||
* identical to "still offline" through `connected` alone — watching this
|
||||
* instead means such a transition still triggers an authoritative re-read.
|
||||
*/
|
||||
readonly revision: string | null;
|
||||
}
|
||||
|
||||
export function hermesGatewayProviderSignal(
|
||||
providers: readonly ServerProvider[],
|
||||
instanceId: string,
|
||||
): HermesGatewayProviderSignal {
|
||||
const provider = providers.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (provider === undefined) return { present: false, connected: false, revision: null };
|
||||
return {
|
||||
present: true,
|
||||
connected: provider.auth.status === "authenticated",
|
||||
revision: provider.checkedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function isHermesInstanceNotFoundError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "instance-not-found"
|
||||
);
|
||||
}
|
||||
|
||||
export function hermesGatewayLifecycleAction(input: {
|
||||
readonly status: HermesGatewayConnectionState;
|
||||
readonly instanceNotFound: boolean;
|
||||
}): "revoke" | "remove-instance" | "remove-setup" {
|
||||
if (input.instanceNotFound) return "remove-setup";
|
||||
return canRemoveHermesGatewayInstance(input.status) ? "remove-instance" : "revoke";
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a one-time enrollment token has aged out.
|
||||
*
|
||||
* An unparseable timestamp is treated as still valid: the server is the real
|
||||
* authority on expiry, and refusing to show a command the user may well be
|
||||
* able to run would be worse than letting the paste fail loudly.
|
||||
*/
|
||||
export function isHermesEnrollmentExpired(expiresAt: string, nowMillis: number): boolean {
|
||||
const expiryMillis = new Date(expiresAt).getTime();
|
||||
if (Number.isNaN(expiryMillis)) return false;
|
||||
return expiryMillis <= nowMillis;
|
||||
}
|
||||
|
||||
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,346 @@
|
||||
"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,
|
||||
Trash2Icon,
|
||||
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,
|
||||
hermesGatewayLifecycleAction,
|
||||
hermesGatewayStatusLabel,
|
||||
isHermesInstanceNotFoundError,
|
||||
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;
|
||||
readonly onRemoved?: (() => void) | undefined;
|
||||
}) {
|
||||
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 removeInstance = useAtomCommand(serverEnvironment.hermesGatewayRemoveInstance, {
|
||||
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 [instanceNotFound, setInstanceNotFound] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<
|
||||
"status" | "enroll" | "revoke" | "remove" | 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);
|
||||
setInstanceNotFound(false);
|
||||
if (shouldApplyHermesConnectorStatusUrl(connectorUrlHasLocalEditsRef.current)) {
|
||||
setConnectorUrl(result.value.connectorUrl);
|
||||
}
|
||||
setError(null);
|
||||
} else {
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
if (isHermesInstanceNotFoundError(failure)) {
|
||||
setStatus(null);
|
||||
setInstanceNotFound(true);
|
||||
setError(null);
|
||||
} else if (!quiet) {
|
||||
setError(messageFromUnknownError(failure));
|
||||
}
|
||||
}
|
||||
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);
|
||||
setInstanceNotFound(false);
|
||||
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 handleRemove = async () => {
|
||||
if (environmentId === null) return;
|
||||
setPendingAction("remove");
|
||||
setError(null);
|
||||
const result = await removeInstance({
|
||||
environmentId,
|
||||
input: { instanceId: props.instanceId },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
props.onRemoved?.();
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: instanceNotFound ? "Hermes setup removed" : "Hermes instance removed",
|
||||
description:
|
||||
"Existing threads remain readable and stay bound to this unavailable instance.",
|
||||
});
|
||||
} else {
|
||||
setError(messageFromUnknownError(squashAtomCommandFailure(result)));
|
||||
setPendingAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const connectionState = status?.status ?? "offline";
|
||||
const lifecycleAction = hermesGatewayLifecycleAction({
|
||||
status: connectionState,
|
||||
instanceNotFound,
|
||||
});
|
||||
const canRemove = lifecycleAction !== "revoke";
|
||||
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}
|
||||
{instanceNotFound ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This setup has no enrolled Hermes gateway. Create an enrollment or remove the setup.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{lifecycleAction !== "remove-instance" ? (
|
||||
<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}
|
||||
{canRemove ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isBusy || environmentId === null}
|
||||
onClick={() => void handleRemove()}
|
||||
>
|
||||
{pendingAction === "remove" ? <LoaderIcon className="animate-spin" /> : <Trash2Icon />}
|
||||
{lifecycleAction === "remove-setup" ? "Remove setup" : "Remove instance"}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isBusy || 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("allows Hermes display names to change without changing the instance id", () => {
|
||||
expect(isProviderInstanceDisplayNameEditable("hermes")).toBe(true);
|
||||
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.length > 0;
|
||||
}
|
||||
|
||||
function ProviderAuthEmail(props: {
|
||||
readonly email: string | undefined;
|
||||
readonly prefix?: string;
|
||||
@@ -335,6 +345,7 @@ interface ProviderInstanceCardProps {
|
||||
* `{ onDelete: undefined }` are treated as distinct shapes.
|
||||
*/
|
||||
readonly onDelete?: (() => void) | undefined;
|
||||
readonly onHermesRemoved?: (() => void) | undefined;
|
||||
/**
|
||||
* Optional outer reset button rendered next to the driver icon. Built-in
|
||||
* default slots supply a reset-to-factory control here; custom instances
|
||||
@@ -384,6 +395,7 @@ export function ProviderInstanceCard({
|
||||
onExpandedChange,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onHermesRemoved,
|
||||
headerAction,
|
||||
hiddenModels,
|
||||
favoriteModels,
|
||||
@@ -394,6 +406,11 @@ export function ProviderInstanceCard({
|
||||
onRunUpdate,
|
||||
isUpdating = false,
|
||||
}: ProviderInstanceCardProps) {
|
||||
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
|
||||
const renameHermesInstance = useAtomCommand(serverEnvironment.hermesGatewayRenameInstance, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [isRenaming, setIsRenaming] = 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 +430,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
|
||||
? hermesNickname === "Hermes"
|
||||
? "Hermes"
|
||||
: `Hermes · ${hermesNickname}`
|
||||
: configuredDisplayName || driverOption?.label || String(instance.driver);
|
||||
const accentColor = normalizeProviderAccentColor(instance.accentColor);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
|
||||
onCopy: ({ providerName }) => {
|
||||
@@ -454,6 +484,40 @@ export function ProviderInstanceCard({
|
||||
|
||||
const updateDisplayName = (value: string) => {
|
||||
const trimmed = value.trim();
|
||||
if (isHermes) {
|
||||
if (trimmed.length === 0) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Hermes name is required",
|
||||
description: "Choose a unique name for this Hermes instance.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (environmentId === null) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not rename Hermes instance",
|
||||
description: "Reconnect this browser to the T3 server and try again.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
setIsRenaming(true);
|
||||
const result = await renameHermesInstance({
|
||||
environmentId,
|
||||
input: { instanceId, nickname: trimmed },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not rename Hermes instance",
|
||||
description: messageFromUnknownError(squashAtomCommandFailure(result)),
|
||||
});
|
||||
}
|
||||
setIsRenaming(false);
|
||||
})();
|
||||
return;
|
||||
}
|
||||
const { displayName: _omit, ...rest } = instance;
|
||||
onUpdate(
|
||||
trimmed.length > 0
|
||||
@@ -554,7 +618,7 @@ export function ProviderInstanceCard({
|
||||
{headerAction}
|
||||
</span>
|
||||
) : null}
|
||||
{onDelete ? (
|
||||
{onDelete && !isHermes ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -730,22 +794,29 @@ 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}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
Optional label shown in the provider list.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{isProviderInstanceDisplayNameEditable(String(instance.driver)) ? (
|
||||
<div>
|
||||
<label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
|
||||
<span className="text-xs font-medium text-foreground">
|
||||
{isHermes ? "Hermes name" : "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}
|
||||
disabled={isRenaming}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
{isHermes
|
||||
? "Shown in provider and model pickers. The instance binding does not change."
|
||||
: "Optional label shown in the provider list."}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<ProviderAccentColorPicker
|
||||
@@ -757,14 +828,22 @@ export function ProviderInstanceCard({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ProviderEnvironmentSection
|
||||
environment={instance.environment ?? []}
|
||||
onChange={updateEnvironment}
|
||||
{isHermes ? (
|
||||
<HermesGatewayInstanceSection
|
||||
instanceId={instanceId}
|
||||
nickname={hermesNickname}
|
||||
onRemoved={onHermesRemoved}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<ProviderEnvironmentSection
|
||||
environment={instance.environment ?? []}
|
||||
onChange={updateEnvironment}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{driverOption ? (
|
||||
{driverOption && !isHermes ? (
|
||||
<ProviderSettingsForm
|
||||
definition={driverOption}
|
||||
value={instance.config}
|
||||
@@ -774,7 +853,7 @@ export function ProviderInstanceCard({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{driverOption !== undefined ? (
|
||||
{driverOption !== undefined && !isHermes ? (
|
||||
<ProviderModelsSection
|
||||
instanceId={instanceId}
|
||||
driverKind={driverKind}
|
||||
@@ -788,7 +867,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 +876,7 @@ export function ProviderInstanceCard({
|
||||
edited from this surface.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
@@ -8,10 +8,18 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
isExplicitProviderInstanceOnly,
|
||||
isProjectGroupingEnabled,
|
||||
projectGroupingModeFromToggle,
|
||||
} from "./SettingsPanels.logic";
|
||||
|
||||
describe("provider instance materialization", () => {
|
||||
it("requires Hermes instances to be explicitly enrolled", () => {
|
||||
expect(isExplicitProviderInstanceOnly(ProviderDriverKind.make("hermes"))).toBe(true);
|
||||
expect(isExplicitProviderInstanceOnly(ProviderDriverKind.make("codex"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project grouping toggle", () => {
|
||||
it("enables repository grouping and disables into separate projects", () => {
|
||||
expect(isProjectGroupingEnabled("repository")).toBe(true);
|
||||
|
||||
@@ -20,6 +20,15 @@ export function projectGroupingModeFromToggle(
|
||||
return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway-backed Hermes instances only exist after enrollment creates an
|
||||
* explicit provider instance. Unlike local CLI drivers, Hermes has no useful
|
||||
* built-in default process to synthesize from legacy provider settings.
|
||||
*/
|
||||
export function isExplicitProviderInstanceOnly(driver: ProviderDriverKind): boolean {
|
||||
return driver === "hermes";
|
||||
}
|
||||
|
||||
const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
|
||||
|
||||
export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
|
||||
|
||||
@@ -84,6 +84,7 @@ import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
isExplicitProviderInstanceOnly,
|
||||
isProjectGroupingEnabled,
|
||||
projectGroupingModeFromToggle,
|
||||
readLastEnabledProjectGroupingMode,
|
||||
@@ -1125,11 +1126,12 @@ export function ProviderSettingsPanel() {
|
||||
);
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
),
|
||||
!isExplicitProviderInstanceOnly(providerSettings.provider) &&
|
||||
(providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
)),
|
||||
);
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
@@ -1320,6 +1322,13 @@ export function ProviderSettingsPanel() {
|
||||
});
|
||||
};
|
||||
|
||||
const cleanupRemovedProviderInstancePreferences = (id: ProviderInstanceId) => {
|
||||
updateSettings({
|
||||
providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderModelPreferences = (
|
||||
instanceId: ProviderInstanceId,
|
||||
next: {
|
||||
@@ -1499,6 +1508,7 @@ export function ProviderSettingsPanel() {
|
||||
}
|
||||
}}
|
||||
onDelete={row.isDefault ? undefined : () => deleteProviderInstance(row.instanceId)}
|
||||
onHermesRemoved={() => cleanupRemovedProviderInstancePreferences(row.instanceId)}
|
||||
headerAction={headerAction}
|
||||
hiddenModels={modelPreferences.hiddenModels}
|
||||
favoriteModels={favoriteModels}
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -55,4 +55,72 @@ describe("writeTextToClipboard", () => {
|
||||
await expect(writeTextToClipboard("", "plan")).resolves.toBe(false);
|
||||
expect(writeText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// `navigator.clipboard` only exists in a secure context, so it is undefined
|
||||
// over plain http — which is how T3 is reached on a LAN or Tailscale host.
|
||||
// Without the legacy fallback every copy button on such an origin silently
|
||||
// does nothing, including the one handing over a pairing command.
|
||||
it("falls back to execCommand in an insecure context", async () => {
|
||||
const execCommand = vi.fn(() => true);
|
||||
vi.stubGlobal("window", {});
|
||||
vi.stubGlobal("navigator", {});
|
||||
const appended: Array<Record<string, unknown>> = [];
|
||||
const makeElement = () => {
|
||||
const element: Record<string, unknown> = {
|
||||
style: {},
|
||||
value: "",
|
||||
setAttribute: () => {},
|
||||
select: () => {},
|
||||
setSelectionRange: () => {},
|
||||
remove: () => {},
|
||||
};
|
||||
return element;
|
||||
};
|
||||
vi.stubGlobal("document", {
|
||||
createElement: () => {
|
||||
const element = makeElement();
|
||||
appended.push(element);
|
||||
return element;
|
||||
},
|
||||
body: { appendChild: () => {} },
|
||||
activeElement: null,
|
||||
execCommand,
|
||||
});
|
||||
|
||||
await expect(writeTextToClipboard("hermes t3 connect --url x", "command")).resolves.toBe(true);
|
||||
expect(execCommand).toHaveBeenCalledWith("copy");
|
||||
});
|
||||
|
||||
it("falls back to execCommand when a secure-context write is rejected", async () => {
|
||||
const writeText = vi.fn(() => Promise.reject(new Error("denied")));
|
||||
const execCommand = vi.fn(() => true);
|
||||
vi.stubGlobal("window", {});
|
||||
vi.stubGlobal("navigator", { clipboard: { writeText } });
|
||||
const appended: Array<Record<string, unknown>> = [];
|
||||
const makeElement = () => {
|
||||
const element: Record<string, unknown> = {
|
||||
style: {},
|
||||
value: "",
|
||||
setAttribute: () => {},
|
||||
select: () => {},
|
||||
setSelectionRange: () => {},
|
||||
remove: () => {},
|
||||
};
|
||||
return element;
|
||||
};
|
||||
vi.stubGlobal("document", {
|
||||
createElement: () => {
|
||||
const element = makeElement();
|
||||
appended.push(element);
|
||||
return element;
|
||||
},
|
||||
body: { appendChild: () => {} },
|
||||
activeElement: null,
|
||||
execCommand,
|
||||
});
|
||||
|
||||
await expect(writeTextToClipboard("value", "command")).resolves.toBe(true);
|
||||
expect(writeText).toHaveBeenCalled();
|
||||
expect(execCommand).toHaveBeenCalledWith("copy");
|
||||
});
|
||||
});
|
||||
@@ -24,12 +24,51 @@ export class ClipboardWriteError extends Schema.TaggedErrorClass<ClipboardWriteE
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy via the legacy `document.execCommand` path.
|
||||
*
|
||||
* `navigator.clipboard` only exists in a secure context, so it is undefined
|
||||
* over plain http — which is exactly how T3 is reached on a LAN or Tailscale
|
||||
* host. Without this fallback every copy button on such an origin silently
|
||||
* does nothing, including the ones handing over a pairing command the user
|
||||
* cannot reasonably retype.
|
||||
*/
|
||||
function writeTextWithExecCommand(value: string): boolean {
|
||||
if (typeof document === "undefined") return false;
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = value;
|
||||
// Keep it off-screen and non-interactive, but still focusable: a hidden or
|
||||
// display:none element cannot be selected, which is what execCommand needs.
|
||||
textarea.setAttribute("readonly", "");
|
||||
textarea.setAttribute("aria-hidden", "true");
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.top = "-9999px";
|
||||
textarea.style.opacity = "0";
|
||||
const previouslyFocused = document.activeElement;
|
||||
document.body.appendChild(textarea);
|
||||
try {
|
||||
textarea.select();
|
||||
textarea.setSelectionRange(0, value.length);
|
||||
return document.execCommand("copy");
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
textarea.remove();
|
||||
// Duck-typed rather than `instanceof HTMLElement`: the global is absent in
|
||||
// non-DOM environments, where a bare reference throws instead of being
|
||||
// falsy — and losing focus is never worth failing a copy over.
|
||||
const restoreFocus = (previouslyFocused as unknown as { focus?: unknown } | null)?.focus;
|
||||
if (typeof restoreFocus === "function") {
|
||||
restoreFocus.call(previouslyFocused);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeTextToClipboard(value: string, target = "text") {
|
||||
if (
|
||||
typeof window === "undefined" ||
|
||||
typeof navigator === "undefined" ||
|
||||
!navigator.clipboard?.writeText
|
||||
) {
|
||||
const hasClipboardApi = typeof navigator !== "undefined" && !!navigator.clipboard?.writeText;
|
||||
// `document` is only needed for the legacy fallback, so it is not required
|
||||
// when the async Clipboard API is present.
|
||||
if (typeof window === "undefined" || (!hasClipboardApi && typeof document === "undefined")) {
|
||||
throw new ClipboardApiUnavailableError({
|
||||
target,
|
||||
});
|
||||
@@ -37,15 +76,25 @@ export async function writeTextToClipboard(value: string, target = "text") {
|
||||
|
||||
if (!value) return false;
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
throw new ClipboardWriteError({
|
||||
target,
|
||||
cause,
|
||||
});
|
||||
if (hasClipboardApi) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
// A rejected write (permissions policy, no user activation) can still
|
||||
// succeed through the legacy path, so fall through rather than fail.
|
||||
if (writeTextWithExecCommand(value)) return true;
|
||||
throw new ClipboardWriteError({
|
||||
target,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (writeTextWithExecCommand(value)) return true;
|
||||
throw new ClipboardApiUnavailableError({
|
||||
target,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCopyToClipboard<TContext = void>({
|
||||
|
||||
@@ -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,45 @@ 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",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows an edited name for an explicit Hermes instance using the legacy default id", () => {
|
||||
const [entry] = deriveProviderInstanceEntries([
|
||||
provider({
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
instanceId: "hermes",
|
||||
displayName: "Research",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entry?.displayName).toBe("Hermes · Research");
|
||||
expect(entry?.instanceId).toBe("hermes");
|
||||
});
|
||||
});
|
||||
|
||||
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,14 @@ function resolveInstanceDisplayName(
|
||||
): string {
|
||||
const trimmedSnapshotName = snapshot.displayName?.trim();
|
||||
const kindLabel = driverKindLabel(driverKind);
|
||||
if (driverKind === "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 +345,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,21 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveDevProxyTarget } from "./viteHelpers";
|
||||
|
||||
describe("resolveDevProxyTarget", () => {
|
||||
it("keeps the dev proxy on the private backend when the browser URL is public", () => {
|
||||
const browserWebSocketUrl = "wss://siva.example.test:7446";
|
||||
const privateProxyUrl = "http://localhost:13773";
|
||||
|
||||
expect(resolveDevProxyTarget(privateProxyUrl)).toBe("http://localhost:13773/");
|
||||
expect(resolveDevProxyTarget(privateProxyUrl)).not.toBe(
|
||||
resolveDevProxyTarget(browserWebSocketUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("converts websocket schemes and strips paths", () => {
|
||||
expect(resolveDevProxyTarget("ws://localhost:13773/api/hermes-gateway/ws?token=test")).toBe(
|
||||
"http://localhost:13773/",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
export function resolveDevProxyTarget(rawUrl: string | undefined) {
|
||||
if (!rawUrl) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol === "ws:") {
|
||||
url.protocol = "http:";
|
||||
} else if (url.protocol === "wss:") {
|
||||
url.protocol = "https:";
|
||||
}
|
||||
url.pathname = "";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url.toString();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+43
-28
@@ -8,6 +8,7 @@ import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
import { resolveDevProxyTarget } from "./src/viteHelpers";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
@@ -15,6 +16,18 @@ Object.assign(process.env, repoEnv);
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const configuredDevProxyUrl = process.env.T3CODE_DEV_PROXY_URL?.trim();
|
||||
const configuredDevServerUrl = (() => {
|
||||
const rawValue = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!rawValue) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return new URL(rawValue);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -65,28 +78,7 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(wsUrl);
|
||||
if (url.protocol === "ws:") {
|
||||
url.protocol = "http:";
|
||||
} else if (url.protocol === "wss:") {
|
||||
url.protocol = "https:";
|
||||
}
|
||||
url.pathname = "";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url.toString();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredDevProxyUrl ?? configuredWsUrl);
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
@@ -145,6 +137,11 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
...(configuredDevServerUrl
|
||||
? {
|
||||
allowedHosts: [configuredDevServerUrl.hostname],
|
||||
}
|
||||
: {}),
|
||||
...(devProxyTarget
|
||||
? {
|
||||
proxy: {
|
||||
@@ -152,24 +149,42 @@ export default defineConfig(() => {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
// `ws: true` because /api carries the Hermes gateway socket at
|
||||
// /api/hermes-gateway/ws alongside plain HTTP routes.
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
// The client's RPC socket. Without a forwarding rule the upgrade
|
||||
// is answered by Vite rather than the server, so a browser told
|
||||
// to use the public origin (`--public-url`) connects to the Vite
|
||||
// port and every RPC fails — the whole app reports the server as
|
||||
// not connected. Loopback dev never hit this because the client
|
||||
// talks to the server port directly.
|
||||
"/ws": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host,
|
||||
clientPort: port,
|
||||
// Follow the browser-facing dev origin when reverse-proxied, while
|
||||
// preserving the explicit loopback config used by Electron.
|
||||
protocol: configuredDevServerUrl?.protocol === "https:" ? "wss" : "ws",
|
||||
host: configuredDevServerUrl?.hostname ?? host,
|
||||
clientPort: configuredDevServerUrl
|
||||
? Number(
|
||||
configuredDevServerUrl.port ||
|
||||
(configuredDevServerUrl.protocol === "https:" ? "443" : "80"),
|
||||
)
|
||||
: port,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
|
||||
- Pass dev-runner flags directly after the root task name, for example:
|
||||
`vp run dev --home-dir /tmp/t3code-dev`
|
||||
- For a reverse-proxied remote dev origin, pass `--public-url` so browser HTTP,
|
||||
WebSocket, HMR, allowed-host, and port-scoped auth-cookie settings stay aligned:
|
||||
`vp run dev --public-url https://siva.example.test:7446`
|
||||
- `vp run start` — Runs the production server (serves built web app as static files).
|
||||
- `vp run build` — Builds contracts, web app, and server.
|
||||
- `vp run typecheck` — Strict TypeScript checks for all packages.
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# Hermes event compatibility inventory
|
||||
|
||||
The plugin deliberately uses only the public Hermes plugin and platform-adapter
|
||||
surfaces audited at Hermes Agent upstream commit `62e07223` (v0.19.0).
|
||||
|
||||
Audited surfaces, all present at that commit:
|
||||
|
||||
| Surface | Location at 62e07223 |
|
||||
| ---------------------------------------- | ------------------------------------ |
|
||||
| `save_env_value` / `get_env_path` | `hermes_cli/config.py:8137` / `:688` |
|
||||
| `load_config_readonly` | `hermes_cli/config.py:7415` |
|
||||
| `build_session_key` | `gateway/session.py:1029` |
|
||||
| `resolve_gateway_approval` | `tools/approval.py:2073` |
|
||||
| `resolve_gateway_clarify` | `tools/clarify_gateway.py:160` |
|
||||
| `register_platform` (`**entry_kwargs`) | `hermes_cli/plugins.py:931` |
|
||||
| `/steer` active-run handler | `gateway/run.py:11280` |
|
||||
| Home-channel notice text | `gateway/run.py:13780` |
|
||||
| Active-command inline dispatch | `gateway/platforms/base.py:4926` |
|
||||
| User-plugin path `$HERMES_HOME/plugins/` | `hermes_cli/plugins.py:10`, `:1350` |
|
||||
|
||||
This inventory describes gateway wire protocol v2. Protocol v2 adds active-turn
|
||||
recovery in `session.ready` and authoritative `content.snapshot` replacement;
|
||||
older server/plugin pairs are rejected during the handshake.
|
||||
|
||||
## Mapped in the initial scope
|
||||
|
||||
| Hermes surface | T3 gateway event |
|
||||
| -------------------------------------------- | ---------------------------------------------- |
|
||||
| Cumulative `send` / `edit_message` output | `content.delta` / `content.snapshot` |
|
||||
| Final stream edit | `item.completed`, `turn.completed` |
|
||||
| `pre_tool_call` / `post_tool_call` hooks | Typed `item.started` / `item.completed` |
|
||||
| Live adapter status text | `status_text` activity item |
|
||||
| `load_config_readonly()["model"]["default"]` | Optional `model` on `connection.hello` |
|
||||
| `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. The current adapter maps it to `assistant_text`; Hermes reasoning,
|
||||
plan, and command-output stream categories are not publicly exposed here.
|
||||
- Prefix-extending cumulative edits emit `content.delta`; edits that revise or
|
||||
clear already-emitted text emit an authoritative `content.snapshot`.
|
||||
- Hermes' exact first-chat T3 home-channel notice is suppressed at the adapter
|
||||
output boundary. The plugin does not assign a home channel or redirect
|
||||
proactive delivery; other Hermes platform notices pass through unchanged.
|
||||
This match is **exact string equality**, which is fragile: Hermes builds the
|
||||
notice inline from an f-string (`gateway/run.py:13780`) rather than exporting
|
||||
a constant, so any wording change upstream silently stops the suppression and
|
||||
the notice reaches the transcript. Re-verified byte-for-byte at 62e07223 by
|
||||
reconstructing the f-string with `platform_name="t3"` (`Platform("t3").value`
|
||||
→ `"t3"`, `.title()` → `"T3"`) and the non-Slack `/sethome` branch; it still
|
||||
matches. A regression test pins the literal.
|
||||
- Hermes' documented tool hook surface exposes a `task_id`, tool name,
|
||||
arguments, string result, and duration. Verified at 62e07223: the runtime
|
||||
additionally supplies `session_id`, `tool_call_id`, `turn_id`,
|
||||
`api_request_id`, and `middleware_trace` on both hooks
|
||||
(`hermes_cli/plugins.py:2146` for `pre_tool_call`, `model_tools.py:1050` for
|
||||
`post_tool_call`), and `post_tool_call` also supplies `status`, `error_type`,
|
||||
and `error_message`. The adapter consumes `session_id`, `tool_call_id`, and
|
||||
`status` 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.
|
||||
- `post_tool_call` passes `result` as `Any`, not a guaranteed `str` — the
|
||||
adapter never forwards it, so the looser type is inert here.
|
||||
- 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
|
||||
(`gateway/platforms/base.py:4926`). The plugin captures that response in the
|
||||
originating steering request's async context and suppresses it from the
|
||||
transcript. Because a steer targets a _running_ turn, the capture is
|
||||
correlated by the steering `requestId` — which the base adapter passes back
|
||||
as `reply_to` via `_reply_anchor_for_event` — and not by `chat_id`. Genuine
|
||||
assistant output emitted on the same thread during the steer window carries a
|
||||
different correlation id and reaches the transcript untouched.
|
||||
- The plugin acknowledges T3 only when the audited Hermes success response
|
||||
begins with `⏩ Steer queued`. That prefix is likewise matched against an
|
||||
inline f-string (`gateway/run.py:11280`) rather than an exported constant, so
|
||||
it carries the same drift risk as the home-channel notice. Confirmed present
|
||||
at 62e07223. Unknown future response shapes fail closed with `protocol.error`
|
||||
rather than completing the turn.
|
||||
- Hermes' configured default model is read once per handshake from the
|
||||
documented read-only accessor `load_config_readonly()["model"]["default"]`.
|
||||
That accessor returns the shared process-wide config cache and its docstring
|
||||
forbids mutation, so the plugin copies out only a trimmed string. Any failure
|
||||
— missing key, import error, older Hermes — omits the optional `model` field
|
||||
from `connection.hello` rather than sending null or empty.
|
||||
- Attachments are not accepted. They are the first planned post-stability
|
||||
feature; the capability is reserved and fixed to `false` in protocol v2.
|
||||
@@ -0,0 +1,87 @@
|
||||
# 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.
|
||||
|
||||
The gateway wire protocol is v2. The T3 server and Hermes plugin must be updated
|
||||
together; mismatched versions fail the connection handshake closed.
|
||||
|
||||
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
|
||||
|
||||
Run the install script. It symlinks this directory into the active Hermes
|
||||
profile's user-plugin directory and enables the plugin:
|
||||
|
||||
```bash
|
||||
./integrations/hermes-t3-gateway/install.sh
|
||||
```
|
||||
|
||||
The script is safe to re-run: an existing correct symlink is left in place, and
|
||||
enabling an already-enabled plugin is a no-op. It installs into
|
||||
`$HERMES_HOME/plugins/` when `HERMES_HOME` is set, and `~/.hermes/plugins/`
|
||||
otherwise. It fails with instructions if `hermes` is not on `PATH`, and refuses
|
||||
to replace a real directory already sitting at the target path.
|
||||
|
||||
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. Run `hermes gateway restart` after
|
||||
enrollment. `hermes t3 status` reports the local enrollment without revealing
|
||||
the credential.
|
||||
|
||||
The handshake also reports Hermes' configured default model so T3 can show a
|
||||
truthful label in its picker. It is read-only — Hermes owns model selection —
|
||||
and is omitted entirely if it cannot be read.
|
||||
|
||||
## Initial scope
|
||||
|
||||
- Text input and live assistant streaming
|
||||
- Authoritative text replacement when Hermes revises cumulative streamed output
|
||||
- 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
|
||||
|
||||
T3 threads are session-only in the initial scope. The adapter suppresses Hermes' exact
|
||||
first-chat `/sethome` notice without assigning a home channel or redirecting
|
||||
cron and cross-platform delivery.
|
||||
|
||||
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"]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,333 @@
|
||||
"""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 PROTOCOL_VERSION, WEBSOCKET_PATH, connection_hello, iso_now
|
||||
|
||||
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))
|
||||
|
||||
# Read until the reply to THIS hello arrives. The handshake is not
|
||||
# guaranteed to be the only frame in flight — the server may already be
|
||||
# probing liveness — and treating whatever arrives first as the reply
|
||||
# tears down the connection that was just established, in a loop.
|
||||
deadline = asyncio.get_running_loop().time() + timeout
|
||||
while True:
|
||||
remaining = deadline - asyncio.get_running_loop().time()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("T3 did not answer the gateway handshake in time")
|
||||
raw = await asyncio.wait_for(socket.recv(), timeout=remaining)
|
||||
message = json.loads(raw)
|
||||
if not isinstance(message, dict):
|
||||
raise TypeError("T3 returned a non-object handshake frame")
|
||||
if message.get("type") == "ping":
|
||||
# Answer inline: the read loop that normally handles this has not
|
||||
# started yet, and an unanswered ping counts against liveness.
|
||||
await socket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "pong",
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"requestId": message.get("requestId"),
|
||||
"sentAt": message.get("sentAt") or iso_now(),
|
||||
},
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
continue
|
||||
if message.get("requestId") != hello["requestId"]:
|
||||
# Some other correlated frame raced the handshake; keep waiting for
|
||||
# ours rather than failing the whole connection.
|
||||
logger.debug(
|
||||
"Ignoring a non-handshake frame while authenticating: %s",
|
||||
message.get("type"),
|
||||
)
|
||||
continue
|
||||
break
|
||||
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") != PROTOCOL_VERSION:
|
||||
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._handlers: set[asyncio.Task[None]] = set()
|
||||
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)
|
||||
|
||||
def _spawn_handler(self, message: dict[str, Any]) -> None:
|
||||
"""Run one command handler off the read loop.
|
||||
|
||||
asyncio only holds a weak reference to tasks, so the handle is kept
|
||||
until completion — otherwise a long turn can be garbage collected
|
||||
mid-flight. Failures are logged rather than surfacing as bare
|
||||
"task exception was never retrieved" warnings.
|
||||
"""
|
||||
task = asyncio.create_task(self._on_message(message))
|
||||
self._handlers.add(task)
|
||||
|
||||
def _finished(completed: asyncio.Task[None]) -> None:
|
||||
self._handlers.discard(completed)
|
||||
if completed.cancelled():
|
||||
return
|
||||
error = completed.exception()
|
||||
if error is not None:
|
||||
logger.warning(
|
||||
"T3 gateway command handler failed: %s", error, exc_info=error
|
||||
)
|
||||
|
||||
task.add_done_callback(_finished)
|
||||
|
||||
async def _send_pong(self, ping: dict[str, Any]) -> None:
|
||||
"""Answer a liveness probe without going through command dispatch."""
|
||||
request_id = ping.get("requestId")
|
||||
if not request_id:
|
||||
return
|
||||
try:
|
||||
await self.send(
|
||||
{
|
||||
"type": "pong",
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"requestId": request_id,
|
||||
"sentAt": ping.get("sentAt") or iso_now(),
|
||||
}
|
||||
)
|
||||
except Exception: # noqa: BLE001 - a failed pong must not kill the read loop
|
||||
logger.debug("Failed to answer a T3 liveness ping", exc_info=True)
|
||||
|
||||
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 not isinstance(message, dict):
|
||||
continue
|
||||
# Liveness is answered inline; it never touches Hermes.
|
||||
if message.get("type") == "ping":
|
||||
await self._send_pong(message)
|
||||
continue
|
||||
# Commands are dispatched WITHOUT awaiting them. A handler
|
||||
# awaits Hermes — `turn.start` blocks for the whole agent
|
||||
# turn — and awaiting it here would stop reading the
|
||||
# socket, so a ping sent mid-turn would not even be read,
|
||||
# let alone answered, and T3 would close a healthy
|
||||
# connection as half-open. Ordering within a session is
|
||||
# still preserved by the plugin's own per-thread state.
|
||||
self._spawn_handler(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)
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/bin/sh
|
||||
# Install the T3 Code gateway plugin into the active Hermes profile.
|
||||
#
|
||||
# Symlinks this directory into "$HERMES_HOME/plugins/hermes-t3-gateway" (the
|
||||
# documented user-plugin path, hermes_cli/plugins.py:10) and enables it.
|
||||
# Safe to re-run: an existing correct symlink is left alone, and enabling an
|
||||
# already-enabled plugin is a no-op in Hermes.
|
||||
|
||||
set -eu
|
||||
|
||||
PLUGIN_NAME="hermes-t3-gateway"
|
||||
SOURCE_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
|
||||
HERMES_HOME_DIR=${HERMES_HOME:-"$HOME/.hermes"}
|
||||
PLUGINS_DIR="$HERMES_HOME_DIR/plugins"
|
||||
TARGET="$PLUGINS_DIR/$PLUGIN_NAME"
|
||||
|
||||
if ! command -v hermes >/dev/null 2>&1; then
|
||||
cat >&2 <<EOF
|
||||
✗ \`hermes\` was not found on PATH.
|
||||
|
||||
This script installs a plugin into an existing Hermes Agent install; it
|
||||
cannot create one. Install Hermes Agent first, then make sure its CLI is on
|
||||
PATH (a default install puts it in ~/.local/bin):
|
||||
|
||||
export PATH="\$HOME/.local/bin:\$PATH"
|
||||
|
||||
Then re-run: $0
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$PLUGINS_DIR"
|
||||
|
||||
if [ -L "$TARGET" ]; then
|
||||
CURRENT=$(readlink "$TARGET")
|
||||
if [ "$CURRENT" = "$SOURCE_DIR" ]; then
|
||||
echo "• Already linked: $TARGET -> $SOURCE_DIR"
|
||||
else
|
||||
echo "• Relinking $TARGET (was -> $CURRENT)"
|
||||
rm -f "$TARGET"
|
||||
ln -s "$SOURCE_DIR" "$TARGET"
|
||||
fi
|
||||
elif [ -e "$TARGET" ]; then
|
||||
cat >&2 <<EOF
|
||||
✗ $TARGET already exists and is not a symlink.
|
||||
|
||||
Refusing to replace it — it may be a real plugin install with local changes.
|
||||
Inspect it, then remove or rename it and re-run this script:
|
||||
|
||||
ls -la "$TARGET"
|
||||
EOF
|
||||
exit 1
|
||||
else
|
||||
ln -s "$SOURCE_DIR" "$TARGET"
|
||||
echo "• Linked $TARGET -> $SOURCE_DIR"
|
||||
fi
|
||||
|
||||
echo "• Enabling $PLUGIN_NAME"
|
||||
# --no-allow-tool-override: this plugin registers a platform adapter and two
|
||||
# observer hooks. It never replaces a built-in tool, and passing the flag keeps
|
||||
# the run non-interactive instead of stopping on the consent prompt.
|
||||
hermes plugins enable "$PLUGIN_NAME" --no-allow-tool-override
|
||||
|
||||
cat <<EOF
|
||||
|
||||
✓ $PLUGIN_NAME is installed and enabled.
|
||||
|
||||
Next steps:
|
||||
|
||||
1. In T3 Code, open the Hermes instance settings, choose "Add Hermes", enter
|
||||
a nickname, and copy the generated enrollment command. Paste and run it:
|
||||
|
||||
hermes t3 connect --url <t3-url> --token <one-time-token>
|
||||
|
||||
2. Restart the gateway so it picks up the new connection:
|
||||
|
||||
hermes gateway restart
|
||||
|
||||
Verify anytime with: hermes t3 status
|
||||
EOF
|
||||
@@ -0,0 +1,24 @@
|
||||
name: hermes-t3-gateway
|
||||
label: T3 Code
|
||||
kind: platform
|
||||
version: 0.2.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,200 @@
|
||||
"""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 = 2
|
||||
PLUGIN_VERSION = "0.2.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 configured_model() -> str | None:
|
||||
"""Return Hermes' configured default model, or None when unavailable.
|
||||
|
||||
Reads `hermes_cli.config.load_config_readonly()`, the documented read-only
|
||||
accessor. That function returns the *shared, process-wide cached* config
|
||||
dict, so nothing here mutates it or hands a nested structure to a caller
|
||||
that might: only a trimmed string copy of `model.default` leaves this
|
||||
function.
|
||||
|
||||
Every failure mode — no Hermes on the path, an older Hermes without the
|
||||
accessor, a config with no model section — degrades to None so the field is
|
||||
omitted from the handshake rather than sent as null or empty.
|
||||
"""
|
||||
try:
|
||||
from hermes_cli.config import load_config_readonly
|
||||
|
||||
model = load_config_readonly().get("model", {}).get("default")
|
||||
except Exception: # noqa: BLE001 - model reporting must never break the handshake
|
||||
return None
|
||||
if not isinstance(model, str):
|
||||
return None
|
||||
trimmed = model.strip()
|
||||
return trimmed or None
|
||||
|
||||
|
||||
def connection_hello(
|
||||
*,
|
||||
hermes_version: str,
|
||||
authentication: dict[str, str],
|
||||
hello_request_id: str | None = None,
|
||||
model: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
resolved_model = model if model is not None else configured_model()
|
||||
hello: dict[str, Any] = {
|
||||
"type": "connection.hello",
|
||||
"requestId": hello_request_id or request_id(),
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"pluginVersion": PLUGIN_VERSION,
|
||||
"hermesVersion": hermes_version,
|
||||
"capabilities": dict(CAPABILITIES),
|
||||
"authentication": authentication,
|
||||
}
|
||||
# Optional on the wire: omit entirely rather than send null/empty so a
|
||||
# server that has the field still falls back to its generic label.
|
||||
if resolved_model:
|
||||
hello["model"] = resolved_model
|
||||
return hello
|
||||
|
||||
|
||||
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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,265 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import contextlib
|
||||
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"]
|
||||
|
||||
|
||||
async def _immediate(value):
|
||||
return value
|
||||
|
||||
|
||||
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": 2,
|
||||
"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_accepted_handshake_rejects_an_incompatible_protocol(self):
|
||||
socket = FakeSocket(
|
||||
{
|
||||
"type": "connection.accepted",
|
||||
"protocolVersion": 1,
|
||||
"instanceId": "provider-instance",
|
||||
"nickname": "Research",
|
||||
}
|
||||
)
|
||||
with self.assertRaisesRegex(RuntimeError, "incompatible version"):
|
||||
await connection.authenticate_socket(
|
||||
socket,
|
||||
authentication={
|
||||
"type": "instance-credential",
|
||||
"instanceId": "provider-instance",
|
||||
"credential": "secret",
|
||||
},
|
||||
hermes_version="0.19.0",
|
||||
)
|
||||
|
||||
async def test_rejected_handshake_fails_closed(self):
|
||||
socket = FakeSocket(
|
||||
{
|
||||
"type": "connection.rejected",
|
||||
"code": "version-incompatible",
|
||||
"message": "upgrade required",
|
||||
"expectedProtocolVersion": 2,
|
||||
}
|
||||
)
|
||||
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")
|
||||
|
||||
async def test_handshake_survives_a_ping_racing_the_reply(self):
|
||||
"""A ping may arrive before `connection.accepted`.
|
||||
|
||||
The server starts probing liveness on its own schedule, so the first
|
||||
frame after hello is not guaranteed to be the handshake reply.
|
||||
Treating it as one tore down the freshly established connection and
|
||||
reconnected in a loop — the plugin logged "unexpected requestId" while
|
||||
the server logged missed pongs.
|
||||
"""
|
||||
class RacingSocket:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self._frames = None
|
||||
|
||||
async def send(self, value):
|
||||
self.sent.append(json.loads(value))
|
||||
|
||||
async def recv(self):
|
||||
if self._frames is None:
|
||||
hello_id = self.sent[0]["requestId"]
|
||||
self._frames = iter(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"type": "ping",
|
||||
"protocolVersion": 2,
|
||||
"requestId": "server-ping-1",
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"type": "connection.accepted",
|
||||
"protocolVersion": 2,
|
||||
"requestId": hello_id,
|
||||
"instanceId": "provider-instance",
|
||||
"nickname": "Hermes",
|
||||
}
|
||||
),
|
||||
]
|
||||
)
|
||||
return next(self._frames)
|
||||
|
||||
socket = RacingSocket()
|
||||
accepted = await connection.authenticate_socket(
|
||||
socket,
|
||||
authentication={
|
||||
"type": "instance-credential",
|
||||
"instanceId": "provider-instance",
|
||||
"credential": "secret",
|
||||
},
|
||||
hermes_version="0.19.0",
|
||||
)
|
||||
self.assertEqual(accepted["type"], "connection.accepted")
|
||||
pongs = [f for f in socket.sent if f.get("type") == "pong"]
|
||||
self.assertEqual(len(pongs), 1, "the racing ping must still be answered")
|
||||
self.assertEqual(pongs[0]["requestId"], "server-ping-1")
|
||||
|
||||
async def test_ping_is_answered_while_a_command_handler_is_blocked(self):
|
||||
"""A ping must not queue behind command dispatch.
|
||||
|
||||
`_on_message` awaits Hermes: `turn.start` blocks for the whole agent
|
||||
turn. If the real read loop awaited that before reading the next
|
||||
frame, a ping arriving mid-turn would go unanswered for minutes and
|
||||
T3 would close a healthy socket as half-open — which is what happened
|
||||
in practice. This drives `_supervise` itself so the loop under test is
|
||||
the one that ships.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
blocked = asyncio.Event()
|
||||
released = asyncio.Event()
|
||||
|
||||
class BlockingSocket:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
async def send(self, value):
|
||||
self.sent.append(json.loads(value))
|
||||
|
||||
async def recv(self):
|
||||
return json.dumps(
|
||||
{
|
||||
"type": "connection.accepted",
|
||||
"protocolVersion": 2,
|
||||
"requestId": self.sent[0]["requestId"],
|
||||
"instanceId": "provider-instance",
|
||||
"nickname": "Hermes",
|
||||
}
|
||||
)
|
||||
|
||||
async def close(self):
|
||||
return None
|
||||
|
||||
def __aiter__(self):
|
||||
async def frames():
|
||||
yield json.dumps({"type": "turn.start", "requestId": "turn-1"})
|
||||
yield json.dumps(
|
||||
{"type": "ping", "protocolVersion": 2, "requestId": "ping-1"}
|
||||
)
|
||||
await released.wait()
|
||||
|
||||
return frames()
|
||||
|
||||
socket = BlockingSocket()
|
||||
|
||||
async def on_message(message):
|
||||
# Stands in for Hermes running a turn: does not return while the
|
||||
# test checks whether the pong went out regardless.
|
||||
blocked.set()
|
||||
await released.wait()
|
||||
|
||||
conn = connection.T3GatewayConnection(
|
||||
url="ws://t3.example/api/hermes-gateway/ws",
|
||||
instance_id="provider-instance",
|
||||
credential="secret",
|
||||
hermes_version="0.19.0",
|
||||
on_message=on_message,
|
||||
)
|
||||
|
||||
original_open = connection._open_socket
|
||||
connection._open_socket = lambda url: _immediate(socket)
|
||||
try:
|
||||
self.assertTrue(await conn.connect(timeout=2))
|
||||
await asyncio.wait_for(blocked.wait(), timeout=2)
|
||||
# Let the read loop reach the queued ping while on_message is stuck.
|
||||
for _ in range(10):
|
||||
await asyncio.sleep(0)
|
||||
pongs = [f for f in socket.sent if f.get("type") == "pong"]
|
||||
self.assertEqual(
|
||||
len(pongs), 1, "the ping must be answered while a command is blocked"
|
||||
)
|
||||
self.assertEqual(pongs[0]["requestId"], "ping-1")
|
||||
finally:
|
||||
connection._open_socket = original_open
|
||||
released.set()
|
||||
await conn.disconnect()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,136 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def fake_hermes_config(loader):
|
||||
"""Install a stand-in `hermes_cli.config` for the duration of a test."""
|
||||
saved = {
|
||||
name: sys.modules.get(name) for name in ("hermes_cli", "hermes_cli.config")
|
||||
}
|
||||
package = types.ModuleType("hermes_cli")
|
||||
package.__path__ = []
|
||||
config = types.ModuleType("hermes_cli.config")
|
||||
if loader is not None:
|
||||
config.load_config_readonly = loader
|
||||
package.config = config
|
||||
sys.modules["hermes_cli"] = package
|
||||
sys.modules["hermes_cli.config"] = config
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name, module in saved.items():
|
||||
if module is None:
|
||||
sys.modules.pop(name, None)
|
||||
else:
|
||||
sys.modules[name] = module
|
||||
|
||||
|
||||
class ProtocolTests(unittest.TestCase):
|
||||
def test_hello_matches_v2_contract(self):
|
||||
hello = protocol.connection_hello(
|
||||
hermes_version="0.19.0",
|
||||
authentication={"type": "enrollment-token", "token": "once"},
|
||||
hello_request_id="request-1",
|
||||
model="gpt-5.6-terra",
|
||||
)
|
||||
self.assertEqual(hello["type"], "connection.hello")
|
||||
self.assertEqual(hello["requestId"], "request-1")
|
||||
self.assertEqual(hello["protocolVersion"], 2)
|
||||
self.assertFalse(hello["capabilities"]["attachments"])
|
||||
self.assertTrue(hello["capabilities"]["streaming"])
|
||||
self.assertEqual(hello["model"], "gpt-5.6-terra")
|
||||
|
||||
def test_hello_reports_the_configured_hermes_model(self):
|
||||
config = {"model": {"default": "gpt-5.6-terra"}}
|
||||
|
||||
with fake_hermes_config(lambda: config):
|
||||
hello = protocol.connection_hello(
|
||||
hermes_version="0.19.0",
|
||||
authentication={"type": "enrollment-token", "token": "once"},
|
||||
)
|
||||
|
||||
self.assertEqual(hello["model"], "gpt-5.6-terra")
|
||||
# `load_config_readonly` returns the shared process-wide cache; the
|
||||
# lookup must never mutate it.
|
||||
self.assertEqual(config, {"model": {"default": "gpt-5.6-terra"}})
|
||||
|
||||
def test_hello_omits_model_when_hermes_cannot_report_one(self):
|
||||
def missing_section():
|
||||
return {"agent": {}}
|
||||
|
||||
def older_hermes():
|
||||
raise ImportError("load_config_readonly is unavailable")
|
||||
|
||||
for loader in (missing_section, older_hermes, None):
|
||||
with self.subTest(loader=getattr(loader, "__name__", "absent")):
|
||||
with fake_hermes_config(loader):
|
||||
hello = protocol.connection_hello(
|
||||
hermes_version="0.19.0",
|
||||
authentication={
|
||||
"type": "enrollment-token",
|
||||
"token": "once",
|
||||
},
|
||||
)
|
||||
# Omitted entirely — never null or empty.
|
||||
self.assertNotIn("model", hello)
|
||||
|
||||
def test_configured_model_ignores_blank_and_non_string_values(self):
|
||||
for value in ("", " ", None, 5, {"default": "nested"}):
|
||||
config = {"model": {"default": value}}
|
||||
with (
|
||||
self.subTest(value=value),
|
||||
fake_hermes_config(lambda config=config: config),
|
||||
):
|
||||
self.assertIsNone(protocol.configured_model())
|
||||
|
||||
def test_server_frame_validation_is_closed(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported"):
|
||||
protocol.validate_server_frame({"type": "made.up", "protocolVersion": 2})
|
||||
with self.assertRaisesRegex(ValueError, "version"):
|
||||
# Protocol v1 peers must upgrade before sending runtime frames.
|
||||
protocol.validate_server_frame({"type": "ping", "protocolVersion": 1})
|
||||
|
||||
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,30 @@ 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,
|
||||
}),
|
||||
hermesGatewayRenameInstance: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-rename-instance",
|
||||
tag: WS_METHODS.hermesGatewayRenameInstance,
|
||||
}),
|
||||
hermesGatewayRevokeInstance: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-revoke-instance",
|
||||
tag: WS_METHODS.hermesGatewayRevokeInstance,
|
||||
}),
|
||||
hermesGatewayRemoveInstance: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:hermes-gateway-remove-instance",
|
||||
tag: WS_METHODS.hermesGatewayRemoveInstance,
|
||||
}),
|
||||
updateProvider: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:update-provider",
|
||||
tag: WS_METHODS.serverUpdateProvider,
|
||||
|
||||
@@ -319,6 +319,54 @@ describe("applyThreadDetailEvent", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Regression: a `replace` snapshot supersedes the text we hold rather than
|
||||
// appending to it, even while `streaming` is true. Providers that emit
|
||||
// revisable cumulative output (Hermes) revise mid-turn; appending rendered
|
||||
// "Hello worldHello, world!" in the browser until a refresh pulled the
|
||||
// corrected text from the server projection.
|
||||
it("replaces text when the payload is an authoritative snapshot", () => {
|
||||
const threadWithMessage: OrchestrationThread = {
|
||||
...baseThread,
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("msg-2"),
|
||||
role: "assistant",
|
||||
text: "Hello world",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T06:00:00.000Z",
|
||||
updatedAt: "2026-04-01T06:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = applyThreadDetailEvent(threadWithMessage, {
|
||||
...baseEventFields,
|
||||
sequence: 7,
|
||||
occurredAt: "2026-04-01T06:01:00.000Z",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make("msg-2"),
|
||||
role: "assistant",
|
||||
text: "Hello, world!",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
streaming: true,
|
||||
textOperation: "replace",
|
||||
createdAt: "2026-04-01T06:00:00.000Z",
|
||||
updatedAt: "2026-04-01T06:01:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.kind).toBe("updated");
|
||||
if (result.kind === "updated") {
|
||||
expect(result.thread.messages).toHaveLength(1);
|
||||
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
|
||||
}
|
||||
});
|
||||
|
||||
it("updates latestTurn for assistant messages with a turn", () => {
|
||||
const result = applyThreadDetailEvent(baseThread, {
|
||||
...baseEventFields,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
OrchestrationThreadActivity,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeAssistantMessageText } from "@t3tools/contracts";
|
||||
|
||||
export type ThreadDetailReducerResult =
|
||||
| { readonly kind: "updated"; readonly thread: OrchestrationThread }
|
||||
@@ -246,11 +247,13 @@ export function applyThreadDetailEvent(
|
||||
? entry
|
||||
: {
|
||||
...entry,
|
||||
text: message.streaming
|
||||
? `${entry.text}${message.text}`
|
||||
: message.text.length > 0
|
||||
? message.text
|
||||
: entry.text,
|
||||
text: mergeAssistantMessageText(entry.text, {
|
||||
text: message.text,
|
||||
streaming: message.streaming,
|
||||
...(event.payload.textOperation !== undefined
|
||||
? { textOperation: event.payload.textOperation }
|
||||
: {}),
|
||||
}),
|
||||
streaming: message.streaming,
|
||||
...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
|
||||
...(message.streaming ? {} : { updatedAt: message.updatedAt }),
|
||||
|
||||
@@ -559,6 +559,7 @@ describe("EnvironmentThreads", () => {
|
||||
|
||||
expect(Option.isNone(recovered.error)).toBe(true);
|
||||
expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
|
||||
expect(yield* Ref.get(harness.loaderCalls)).toBe(1);
|
||||
expect(yield* Ref.get(harness.retryCount)).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ import { EnvironmentSupervisor } from "../connection/supervisor.ts";
|
||||
import * as ConnectionWakeups from "../connection/wakeups.ts";
|
||||
import { EnvironmentCacheStore } from "../platform/persistence.ts";
|
||||
import { subscribeDynamic } from "../rpc/client.ts";
|
||||
import type { RpcSession } from "../rpc/session.ts";
|
||||
import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
|
||||
import { parseThreadKey, threadKey } from "./entities.ts";
|
||||
import { applyThreadDetailEvent } from "./threadReducer.ts";
|
||||
@@ -79,6 +80,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
const lastSequence = yield* SubscriptionRef.make(
|
||||
Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
|
||||
);
|
||||
const snapshotSession = yield* Ref.make<RpcSession | undefined>(undefined);
|
||||
const awaitingCompletion = yield* Ref.make(false);
|
||||
const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
|
||||
|
||||
@@ -253,24 +255,30 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
|
||||
let current = yield* SubscriptionRef.get(state);
|
||||
if (Option.isNone(current.data) && current.status !== "deleted") {
|
||||
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
SubscriptionRef.changes(supervisor.prepared).pipe(
|
||||
Stream.filter(Option.isSome),
|
||||
Stream.map((value) => value.value),
|
||||
Stream.runHead,
|
||||
Effect.map(Option.getOrThrow),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
|
||||
if (Option.isSome(httpSnapshot)) {
|
||||
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
|
||||
current = yield* SubscriptionRef.get(state);
|
||||
const shouldLoadSnapshot = yield* Ref.modify(snapshotSession, (previous) => [
|
||||
previous !== session,
|
||||
session,
|
||||
]);
|
||||
if (shouldLoadSnapshot) {
|
||||
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
SubscriptionRef.changes(supervisor.prepared).pipe(
|
||||
Stream.filter(Option.isSome),
|
||||
Stream.map((value) => value.value),
|
||||
Stream.runHead,
|
||||
Effect.map(Option.getOrThrow),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
|
||||
if (Option.isSome(httpSnapshot)) {
|
||||
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
|
||||
current = yield* SubscriptionRef.get(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
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.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
model: "gpt-5.6-terra",
|
||||
connectionGeneration: 3,
|
||||
activeSessionCount: 2,
|
||||
protocolVersion: 2,
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
});
|
||||
expect(connected.status).toBe("connected");
|
||||
expect(connected.activeSessionCount).toBe(2);
|
||||
expect(connected.model).toBe("gpt-5.6-terra");
|
||||
|
||||
// A plugin that predates the `model` field still produces a valid status;
|
||||
// the picker falls back to the generic label rather than failing to decode.
|
||||
const withoutModel = decodeInstanceStatus({ ...connected, model: null });
|
||||
expect(withoutModel.model).toBeNull();
|
||||
|
||||
const upgradeRequired = decodeInstanceStatus({
|
||||
...connected,
|
||||
status: "upgrade-required",
|
||||
protocolVersion: 3,
|
||||
capabilities: null,
|
||||
});
|
||||
expect(upgradeRequired.protocolVersion).toBe(3);
|
||||
expect(upgradeRequired.capabilities).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes gateway handshake", () => {
|
||||
it("accepts one-time enrollment authentication", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-1",
|
||||
protocolVersion: 2,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
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: 2,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
model: "gpt-5.6-terra",
|
||||
authentication: {
|
||||
type: "instance-credential",
|
||||
instanceId: "hermes-research",
|
||||
credential: "persistent-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.authentication.type).toBe("instance-credential");
|
||||
expect(hello.model).toBe("gpt-5.6-terra");
|
||||
});
|
||||
|
||||
// The plugin ships separately from the server, so a plugin that predates the
|
||||
// `model` field must still complete the handshake rather than failing the
|
||||
// frame decoder. T3 falls back to the generic model label.
|
||||
it("accepts a hello from a plugin that reports no model", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-no-model",
|
||||
protocolVersion: 2,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
authentication: {
|
||||
type: "instance-credential",
|
||||
instanceId: "hermes-research",
|
||||
credential: "persistent-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.model).toBeUndefined();
|
||||
});
|
||||
|
||||
it("decodes a future-version hello so the broker can reject it explicitly", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-future",
|
||||
protocolVersion: 3,
|
||||
pluginVersion: "0.3.0",
|
||||
hermesVersion: "2.0.0",
|
||||
capabilities: {
|
||||
protocolVersion: 3,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: true,
|
||||
},
|
||||
authentication: {
|
||||
type: "enrollment-token",
|
||||
token: "enroll-secret",
|
||||
},
|
||||
});
|
||||
|
||||
expect(hello.protocolVersion).toBe(3);
|
||||
expect(hello.capabilities.protocolVersion).toBe(3);
|
||||
});
|
||||
|
||||
it("reserves attachments for a future protocol version", () => {
|
||||
expect(() =>
|
||||
decodeCapabilities({
|
||||
protocolVersion: 2,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: true,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("T3 to Hermes v2 messages", () => {
|
||||
it("decodes session creation and opaque resume cursors", () => {
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "session.ensure",
|
||||
protocolVersion: 2,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
resumeSessionId: "opaque/hermes/session/value",
|
||||
}).type,
|
||||
).toBe("session.ensure");
|
||||
|
||||
expect(
|
||||
decodeResumeCursor({
|
||||
protocolVersion: 2,
|
||||
sessionId: "opaque/hermes/session/value",
|
||||
}).sessionId,
|
||||
).toBe("opaque/hermes/session/value");
|
||||
});
|
||||
|
||||
it("decodes start and steering as distinct turn operations", () => {
|
||||
const context = {
|
||||
protocolVersion: 2,
|
||||
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: 2,
|
||||
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: 2,
|
||||
requestId: "stop-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
}).type,
|
||||
).toBe("session.stop");
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "ping",
|
||||
protocolVersion: 2,
|
||||
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",
|
||||
// Protocol v1 peers must upgrade before sending post-handshake frames.
|
||||
protocolVersion: 1,
|
||||
requestId: "ping-1",
|
||||
sentAt: "2026-07-23T12:00:00.000Z",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes to T3 v2 events", () => {
|
||||
const turnContext = {
|
||||
protocolVersion: 2,
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
};
|
||||
|
||||
it("decodes session readiness, turn start, streaming text, and completion", () => {
|
||||
const legacyReady = decodePluginMessage({
|
||||
type: "session.ready",
|
||||
protocolVersion: 2,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
resumed: false,
|
||||
});
|
||||
expect(legacyReady.type).toBe("session.ready");
|
||||
const activeReady = decodePluginMessage({
|
||||
type: "session.ready",
|
||||
protocolVersion: 2,
|
||||
requestId: "ensure-2",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
resumed: true,
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
expect(activeReady.type).toBe("session.ready");
|
||||
if (activeReady.type !== "session.ready") {
|
||||
throw new Error("expected session.ready");
|
||||
}
|
||||
expect(activeReady.activeTurnId).toBe("turn-1");
|
||||
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");
|
||||
const snapshot = decodePluginMessage({
|
||||
type: "content.snapshot",
|
||||
streamKind: "assistant_text",
|
||||
text: "",
|
||||
itemId: "message-1",
|
||||
contentIndex: 0,
|
||||
...turnContext,
|
||||
});
|
||||
expect(snapshot.type).toBe("content.snapshot");
|
||||
if (snapshot.type !== "content.snapshot") {
|
||||
throw new Error("expected content.snapshot");
|
||||
}
|
||||
expect(snapshot.text).toBe("");
|
||||
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,631 @@
|
||||
/**
|
||||
* 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 = 2 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 v2 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 v2 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),
|
||||
/**
|
||||
* The model the connected plugin reported at handshake, surfaced so the
|
||||
* provider picker can name the model Hermes actually runs instead of a
|
||||
* placeholder. Null when no plugin has connected yet, or when the connected
|
||||
* plugin predates the `model` field on `connection.hello`.
|
||||
*/
|
||||
model: Schema.NullOr(TrimmedNonEmptyString),
|
||||
/**
|
||||
* Monotonic id of the underlying connection, or null while offline.
|
||||
*
|
||||
* Consumers must key "this is a different plugin process now" off this
|
||||
* rather than off `status` transitioning through `offline`. A replacement —
|
||||
* the old socket dying as a new one is accepted — publishes a single
|
||||
* `connected` status, so a connectedness edge detector never fires and
|
||||
* anything that must be re-established per connection (notably
|
||||
* `session.ensure`) is silently skipped.
|
||||
*/
|
||||
connectionGeneration: Schema.NullOr(NonNegativeInt),
|
||||
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 HermesGatewayRenameInstanceResult = HermesGatewayInstanceStatus;
|
||||
export type HermesGatewayRenameInstanceResult = typeof HermesGatewayRenameInstanceResult.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 HermesGatewayRemoveInstanceInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
});
|
||||
export type HermesGatewayRemoveInstanceInput = typeof HermesGatewayRemoveInstanceInput.Type;
|
||||
|
||||
export const HermesGatewayRemoveInstanceResult = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
});
|
||||
export type HermesGatewayRemoveInstanceResult = typeof HermesGatewayRemoveInstanceResult.Type;
|
||||
|
||||
export const HermesGatewayManagementOperation = Schema.Literals([
|
||||
"create-enrollment",
|
||||
"get-status",
|
||||
"list-instances",
|
||||
"rename-instance",
|
||||
"revoke-instance",
|
||||
"remove-instance",
|
||||
]);
|
||||
export type HermesGatewayManagementOperation = typeof HermesGatewayManagementOperation.Type;
|
||||
|
||||
export const HermesGatewayManagementErrorCode = Schema.Literals([
|
||||
"instance-not-found",
|
||||
"nickname-conflict",
|
||||
"invalid-connector-url",
|
||||
"instance-revoked",
|
||||
"instance-removed",
|
||||
"instance-not-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 v2 frames use the literal v2 schema.
|
||||
*/
|
||||
export const HermesGatewayConnectionHello = Schema.Struct({
|
||||
type: Schema.Literal("connection.hello"),
|
||||
requestId: HermesGatewayRequestId,
|
||||
protocolVersion: PositiveInt,
|
||||
pluginVersion: TrimmedNonEmptyString,
|
||||
hermesVersion: TrimmedNonEmptyString,
|
||||
capabilities: HermesGatewayHelloCapabilities,
|
||||
authentication: HermesGatewayAuthentication,
|
||||
/**
|
||||
* The model Hermes is configured to run, reported so T3 can show something
|
||||
* truthful in the picker instead of a placeholder. Read-only — Hermes owns
|
||||
* model selection, and T3 declares `sessionModelSwitch: "unsupported"`.
|
||||
*
|
||||
* Optional so a plugin that predates this field still connects: an absent
|
||||
* value degrades to the generic label rather than failing the handshake.
|
||||
*/
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
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,
|
||||
activeTurnId: Schema.optional(TurnId),
|
||||
});
|
||||
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 HermesGatewayContentSnapshot = Schema.Struct({
|
||||
type: Schema.Literal("content.snapshot"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
...HermesGatewayTurnContext.fields,
|
||||
itemId: Schema.optional(HermesGatewayItemId),
|
||||
streamKind: HermesGatewayContentStreamKind,
|
||||
text: Schema.String,
|
||||
contentIndex: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
export type HermesGatewayContentSnapshot = typeof HermesGatewayContentSnapshot.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,
|
||||
HermesGatewayContentSnapshot,
|
||||
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",
|
||||
};
|
||||
@@ -813,6 +813,16 @@ const ThreadMessageAssistantDeltaCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadMessageAssistantReplaceCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.message.assistant.replace"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
text: Schema.String,
|
||||
turnId: Schema.optional(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadMessageAssistantCompleteCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.message.assistant.complete"),
|
||||
commandId: CommandId,
|
||||
@@ -863,6 +873,7 @@ const ThreadRevertCompleteCommand = Schema.Struct({
|
||||
const InternalOrchestrationCommand = Schema.Union([
|
||||
ThreadSessionSetCommand,
|
||||
ThreadMessageAssistantDeltaCommand,
|
||||
ThreadMessageAssistantReplaceCommand,
|
||||
ThreadMessageAssistantCompleteCommand,
|
||||
ThreadProposedPlanUpsertCommand,
|
||||
ThreadTurnDiffCompleteCommand,
|
||||
@@ -1028,10 +1039,45 @@ export const ThreadMessageSentPayload = Schema.Struct({
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
streaming: Schema.Boolean,
|
||||
textOperation: Schema.optional(Schema.Literal("replace")),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
/**
|
||||
* The single append-vs-replace rule for assistant message text.
|
||||
*
|
||||
* Three projections consume `thread.message-sent` — the server projector, the
|
||||
* server projection pipeline, and the live client reducer — and each one has to
|
||||
* fold an incoming payload into the text it already holds. Hand-writing that
|
||||
* fold per projection is how `textOperation: "replace"` shipped to two of the
|
||||
* three: browsers appended revised snapshots (rendering `"Hello worldHello,
|
||||
* world!"`) until a refresh pulled the corrected text from the server.
|
||||
*
|
||||
* Every projection calls this instead. A new payload field that changes text
|
||||
* semantics is added here once, and no projection can silently miss it.
|
||||
*
|
||||
* Rules, in order:
|
||||
* - `replace` — an authoritative snapshot supersedes what we hold. Providers
|
||||
* that emit revisable cumulative output (Hermes) rely on this.
|
||||
* - `streaming` — an incremental delta appends.
|
||||
* - empty non-streaming text — a terminal event carrying no text keeps what we
|
||||
* already have rather than blanking the message.
|
||||
* - otherwise — the payload is the whole text.
|
||||
*/
|
||||
export const mergeAssistantMessageText = (
|
||||
existingText: string,
|
||||
payload: {
|
||||
readonly text: string;
|
||||
readonly streaming: boolean;
|
||||
readonly textOperation?: "replace" | undefined;
|
||||
},
|
||||
): string => {
|
||||
if (payload.textOperation === "replace") return payload.text;
|
||||
if (payload.streaming) return `${existingText}${payload.text}`;
|
||||
return payload.text.length > 0 ? payload.text : existingText;
|
||||
};
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
|
||||
@@ -69,6 +69,34 @@ describe("ProviderRuntimeEvent", () => {
|
||||
expect(parsed.payload.planMarkdown).toBe("# Ship it");
|
||||
});
|
||||
|
||||
it("decodes authoritative content snapshots, including empty text", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "content.snapshot",
|
||||
eventId: "event-content-snapshot-1",
|
||||
provider: "hermes",
|
||||
providerInstanceId: "hermes-research",
|
||||
sessionId: "runtime-session-1",
|
||||
createdAt: "2026-02-28T00:00:00.000Z",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
itemId: "message-1",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
text: "",
|
||||
contentIndex: 0,
|
||||
summaryIndex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.type).toBe("content.snapshot");
|
||||
if (parsed.type !== "content.snapshot") {
|
||||
throw new Error("expected content.snapshot");
|
||||
}
|
||||
expect(parsed.payload.text).toBe("");
|
||||
expect(parsed.payload.contentIndex).toBe(0);
|
||||
expect(parsed.payload.summaryIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("decodes user-input.requested with structured questions", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
|
||||
@@ -128,6 +128,11 @@ export const CanonicalItemType = Schema.Literals([
|
||||
"review_exited",
|
||||
"context_compaction",
|
||||
"error",
|
||||
// Free-form provider status line ("Thinking…", "Searching the web…").
|
||||
// Deliberately distinct from `unknown`: adapters use `unknown` as the
|
||||
// "could not classify this item" sentinel and rely on it being inert, so
|
||||
// renderable status text needs its own type rather than riding that one.
|
||||
"status_text",
|
||||
"unknown",
|
||||
]);
|
||||
export type CanonicalItemType = typeof CanonicalItemType.Type;
|
||||
@@ -170,6 +175,7 @@ const ProviderRuntimeEventType = Schema.Literals([
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"content.delta",
|
||||
"content.snapshot",
|
||||
"request.opened",
|
||||
"request.resolved",
|
||||
"user-input.requested",
|
||||
@@ -220,6 +226,7 @@ const ItemStartedType = Schema.Literal("item.started");
|
||||
const ItemUpdatedType = Schema.Literal("item.updated");
|
||||
const ItemCompletedType = Schema.Literal("item.completed");
|
||||
const ContentDeltaType = Schema.Literal("content.delta");
|
||||
const ContentSnapshotType = Schema.Literal("content.snapshot");
|
||||
const RequestOpenedType = Schema.Literal("request.opened");
|
||||
const RequestResolvedType = Schema.Literal("request.resolved");
|
||||
const UserInputRequestedType = Schema.Literal("user-input.requested");
|
||||
@@ -418,6 +425,14 @@ const ContentDeltaPayload = Schema.Struct({
|
||||
});
|
||||
export type ContentDeltaPayload = typeof ContentDeltaPayload.Type;
|
||||
|
||||
export const ContentSnapshotPayload = Schema.Struct({
|
||||
streamKind: RuntimeContentStreamKind,
|
||||
text: Schema.String,
|
||||
contentIndex: Schema.optional(Schema.Int),
|
||||
summaryIndex: Schema.optional(Schema.Int),
|
||||
});
|
||||
export type ContentSnapshotPayload = typeof ContentSnapshotPayload.Type;
|
||||
|
||||
const RequestOpenedPayload = Schema.Struct({
|
||||
requestType: CanonicalRequestType,
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -791,6 +806,13 @@ const ProviderRuntimeContentDeltaEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeContentDeltaEvent = typeof ProviderRuntimeContentDeltaEvent.Type;
|
||||
|
||||
const ProviderRuntimeContentSnapshotEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ContentSnapshotType,
|
||||
payload: ContentSnapshotPayload,
|
||||
});
|
||||
export type ProviderRuntimeContentSnapshotEvent = typeof ProviderRuntimeContentSnapshotEvent.Type;
|
||||
|
||||
const ProviderRuntimeRequestOpenedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RequestOpenedType,
|
||||
@@ -989,6 +1011,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeItemUpdatedEvent,
|
||||
ProviderRuntimeItemCompletedEvent,
|
||||
ProviderRuntimeContentDeltaEvent,
|
||||
ProviderRuntimeContentSnapshotEvent,
|
||||
ProviderRuntimeRequestOpenedEvent,
|
||||
ProviderRuntimeRequestResolvedEvent,
|
||||
ProviderRuntimeUserInputRequestedEvent,
|
||||
|
||||
@@ -59,6 +59,20 @@ import {
|
||||
OrchestrationRpcSchemas,
|
||||
} from "./orchestration.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import {
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
HermesGatewayEnrollmentResult,
|
||||
HermesGatewayGetInstanceStatusInput,
|
||||
HermesGatewayInstanceStatus,
|
||||
HermesGatewayListInstancesResult,
|
||||
HermesGatewayManagementError,
|
||||
HermesGatewayRemoveInstanceInput,
|
||||
HermesGatewayRemoveInstanceResult,
|
||||
HermesGatewayRenameInstanceInput,
|
||||
HermesGatewayRenameInstanceResult,
|
||||
HermesGatewayRevokeInstanceInput,
|
||||
HermesGatewayRevokeInstanceResult,
|
||||
} from "./hermesGateway.ts";
|
||||
import {
|
||||
RelayClientInstallFailedError,
|
||||
RelayClientInstallProgressEventSchema,
|
||||
@@ -219,6 +233,14 @@ export const WS_METHODS = {
|
||||
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
|
||||
serverSignalProcess: "server.signalProcess",
|
||||
|
||||
// Hermes gateway instance management
|
||||
hermesGatewayCreateEnrollment: "hermesGateway.createEnrollment",
|
||||
hermesGatewayGetInstanceStatus: "hermesGateway.getInstanceStatus",
|
||||
hermesGatewayListInstances: "hermesGateway.listInstances",
|
||||
hermesGatewayRenameInstance: "hermesGateway.renameInstance",
|
||||
hermesGatewayRevokeInstance: "hermesGateway.revokeInstance",
|
||||
hermesGatewayRemoveInstance: "hermesGateway.removeInstance",
|
||||
|
||||
// Cloud environment methods
|
||||
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
|
||||
cloudInstallRelayClient: "cloud.installRelayClient",
|
||||
@@ -334,6 +356,48 @@ 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 WsHermesGatewayRenameInstanceRpc = Rpc.make(WS_METHODS.hermesGatewayRenameInstance, {
|
||||
payload: HermesGatewayRenameInstanceInput,
|
||||
success: HermesGatewayRenameInstanceResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsHermesGatewayRevokeInstanceRpc = Rpc.make(WS_METHODS.hermesGatewayRevokeInstance, {
|
||||
payload: HermesGatewayRevokeInstanceInput,
|
||||
success: HermesGatewayRevokeInstanceResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsHermesGatewayRemoveInstanceRpc = Rpc.make(WS_METHODS.hermesGatewayRemoveInstance, {
|
||||
payload: HermesGatewayRemoveInstanceInput,
|
||||
success: HermesGatewayRemoveInstanceResult,
|
||||
error: Schema.Union([HermesGatewayManagementError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, {
|
||||
payload: Schema.Struct({}),
|
||||
success: RelayClientStatusSchema,
|
||||
@@ -713,6 +777,12 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetProcessDiagnosticsRpc,
|
||||
WsServerGetProcessResourceHistoryRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsHermesGatewayCreateEnrollmentRpc,
|
||||
WsHermesGatewayGetInstanceStatusRpc,
|
||||
WsHermesGatewayListInstancesRpc,
|
||||
WsHermesGatewayRenameInstanceRpc,
|
||||
WsHermesGatewayRevokeInstanceRpc,
|
||||
WsHermesGatewayRemoveInstanceRpc,
|
||||
WsCloudGetRelayClientStatusRpc,
|
||||
WsCloudInstallRelayClientRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
|
||||
@@ -389,6 +389,49 @@ 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.
|
||||
*
|
||||
* What this config *does* carry is the durable half of a paired gateway:
|
||||
* `connectorUrl` and `revoked`. Together with the envelope's `displayName`
|
||||
* they are the enrollment facts that must survive a restart. They live here —
|
||||
* a normal read-modify-write settings field — rather than in the secret store,
|
||||
* which has no listing API, no index, and no transactions.
|
||||
*
|
||||
* The credential itself deliberately stays in `ServerSecretStore`; that is
|
||||
* what it is for. And volatile liveness (last connection time, session count,
|
||||
* plugin/Hermes versions, reported model) is deliberately **absent**: it lives
|
||||
* only in broker memory, because the provider instance registry closes an
|
||||
* instance's scope whenever this envelope changes, which would stop every live
|
||||
* Hermes session on every reconnect.
|
||||
*
|
||||
* Both fields are hidden from the provider settings form: they are managed
|
||||
* through the Hermes enrollment flow, not hand-edited.
|
||||
*/
|
||||
export const HermesSettings = makeProviderSettingsSchema({
|
||||
enabled: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
/**
|
||||
* The connector URL shown in the enrollment command. Optional so an
|
||||
* instance that has been configured but never enrolled decodes cleanly.
|
||||
*/
|
||||
connectorUrl: Schema.optionalKey(TrimmedString).pipe(
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
/**
|
||||
* Whether the gateway credential has been revoked. Absent means "not
|
||||
* revoked", so pre-existing envelopes decode without migration.
|
||||
*/
|
||||
revoked: Schema.optionalKey(Schema.Boolean).pipe(
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
});
|
||||
export type HermesSettings = typeof HermesSettings.Type;
|
||||
|
||||
export const ObservabilitySettings = Schema.Struct({
|
||||
otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
@@ -433,6 +476,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 +580,12 @@ const OpenCodeSettingsPatch = Schema.Struct({
|
||||
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
});
|
||||
|
||||
const HermesSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
connectorUrl: Schema.optionalKey(TrimmedString),
|
||||
revoked: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
export const ServerSettingsPatch = Schema.Struct({
|
||||
// Server settings
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
@@ -558,6 +608,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
|
||||
|
||||
@@ -61,6 +61,20 @@ const devServerInput = {
|
||||
runArgs: ["--inspect", "secret-token-value"],
|
||||
} as const;
|
||||
|
||||
const defaultCreateEnvInput = {
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
} as const;
|
||||
|
||||
it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
describe("getDevRunnerModeArgs", () => {
|
||||
it.effect("lets Vite+ honor the desktop dev task graph", () =>
|
||||
@@ -147,6 +161,67 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("configures remote dev targets and cookie isolation from one public URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
publicUrl: new URL("https://siva.example.test:7446"),
|
||||
});
|
||||
|
||||
assert.equal(env.VITE_DEV_SERVER_URL, "https://siva.example.test:7446");
|
||||
assert.equal(env.VITE_HTTP_URL, "https://siva.example.test:7446");
|
||||
assert.equal(env.VITE_WS_URL, "wss://siva.example.test:7446");
|
||||
assert.equal(env.T3CODE_DEV_PROXY_URL, "http://localhost:13773");
|
||||
assert.equal(env.T3CODE_AUTH_COOKIE_PORT, "7446");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects public URLs that are not HTTP origins", () =>
|
||||
Effect.gen(function* () {
|
||||
const unsupportedProtocol = yield* Effect.flip(
|
||||
createDevRunnerEnv({
|
||||
...defaultCreateEnvInput,
|
||||
publicUrl: new URL("ftp://siva.example.test:7446"),
|
||||
}),
|
||||
);
|
||||
const pathUrl = yield* Effect.flip(
|
||||
createDevRunnerEnv({
|
||||
...defaultCreateEnvInput,
|
||||
publicUrl: new URL("https://siva.example.test:7446/app"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(unsupportedProtocol._tag, "DevRunnerPublicUrlError");
|
||||
assert.equal(unsupportedProtocol.reason, "unsupported-protocol");
|
||||
assert.equal(pathUrl._tag, "DevRunnerPublicUrlError");
|
||||
assert.equal(pathUrl.reason, "not-an-origin");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects conflicting public and explicit dev URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
createDevRunnerEnv({
|
||||
...defaultCreateEnvInput,
|
||||
devUrl: new URL("http://localhost:7331"),
|
||||
publicUrl: new URL("https://siva.example.test:7446"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "DevRunnerConflictingUrlOptionsError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows browser auto-open to be explicitly enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
|
||||
+97
-3
@@ -81,6 +81,29 @@ export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<Dev
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRunnerPublicUrlError extends Schema.TaggedErrorClass<DevRunnerPublicUrlError>()(
|
||||
"DevRunnerPublicUrlError",
|
||||
{
|
||||
reason: Schema.Literals(["unsupported-protocol", "not-an-origin"]),
|
||||
protocol: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.reason === "unsupported-protocol"
|
||||
? `Public URL must use HTTP or HTTPS; received protocol "${this.protocol}".`
|
||||
: "Public URL must be an origin without credentials, a path, query parameters, or a fragment.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRunnerConflictingUrlOptionsError extends Schema.TaggedErrorClass<DevRunnerConflictingUrlOptionsError>()(
|
||||
"DevRunnerConflictingUrlOptionsError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Use either --public-url or --dev-url, not both.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<DevRunnerPortExhaustedError>()(
|
||||
"DevRunnerPortExhaustedError",
|
||||
{
|
||||
@@ -131,6 +154,8 @@ export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunner
|
||||
export const DevRunnerError = Schema.Union([
|
||||
DevRunnerConfigurationError,
|
||||
DevRunnerInvalidPortOffsetError,
|
||||
DevRunnerPublicUrlError,
|
||||
DevRunnerConflictingUrlOptionsError,
|
||||
DevRunnerPortExhaustedError,
|
||||
DevRunnerProcessError,
|
||||
DevRunnerProcessExitError,
|
||||
@@ -153,6 +178,11 @@ const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
|
||||
Config.url(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
|
||||
Config.int(name).pipe(
|
||||
Config.option,
|
||||
@@ -227,6 +257,7 @@ interface CreateDevRunnerEnvInput {
|
||||
readonly host: string | undefined;
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly publicUrl?: URL | undefined;
|
||||
}
|
||||
|
||||
export function createDevRunnerEnv({
|
||||
@@ -241,18 +272,68 @@ export function createDevRunnerEnv({
|
||||
host,
|
||||
port,
|
||||
devUrl,
|
||||
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
|
||||
publicUrl,
|
||||
}: CreateDevRunnerEnvInput): Effect.Effect<
|
||||
NodeJS.ProcessEnv,
|
||||
DevRunnerPublicUrlError | DevRunnerConflictingUrlOptionsError,
|
||||
Path.Path
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
|
||||
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
|
||||
const isDesktopMode = mode === "dev:desktop";
|
||||
const configuredPublicUrl = isDesktopMode ? undefined : publicUrl;
|
||||
|
||||
if (configuredPublicUrl !== undefined && devUrl !== undefined) {
|
||||
return yield* new DevRunnerConflictingUrlOptionsError();
|
||||
}
|
||||
if (
|
||||
configuredPublicUrl !== undefined &&
|
||||
configuredPublicUrl.protocol !== "http:" &&
|
||||
configuredPublicUrl.protocol !== "https:"
|
||||
) {
|
||||
return yield* new DevRunnerPublicUrlError({
|
||||
reason: "unsupported-protocol",
|
||||
protocol: configuredPublicUrl.protocol,
|
||||
});
|
||||
}
|
||||
if (
|
||||
configuredPublicUrl !== undefined &&
|
||||
(configuredPublicUrl.username !== "" ||
|
||||
configuredPublicUrl.password !== "" ||
|
||||
configuredPublicUrl.pathname !== "/" ||
|
||||
configuredPublicUrl.search !== "" ||
|
||||
configuredPublicUrl.hash !== "")
|
||||
) {
|
||||
return yield* new DevRunnerPublicUrlError({
|
||||
reason: "not-an-origin",
|
||||
protocol: configuredPublicUrl.protocol,
|
||||
});
|
||||
}
|
||||
|
||||
const publicHttpUrl = configuredPublicUrl?.origin;
|
||||
const publicWsUrl =
|
||||
configuredPublicUrl === undefined
|
||||
? undefined
|
||||
: (() => {
|
||||
const url = new URL(configuredPublicUrl);
|
||||
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
||||
return url.origin;
|
||||
})();
|
||||
const publicPort =
|
||||
configuredPublicUrl === undefined
|
||||
? undefined
|
||||
: Number(
|
||||
configuredPublicUrl.port || (configuredPublicUrl.protocol === "https:" ? "443" : "80"),
|
||||
);
|
||||
|
||||
const output: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
PORT: String(webPort),
|
||||
VITE_DEV_SERVER_URL:
|
||||
publicHttpUrl ??
|
||||
devUrl?.toString() ??
|
||||
`http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
|
||||
};
|
||||
@@ -265,8 +346,12 @@ export function createDevRunnerEnv({
|
||||
|
||||
if (!isDesktopMode) {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
output.T3CODE_DEV_PROXY_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_HTTP_URL = publicHttpUrl ?? `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = publicWsUrl ?? `ws://localhost:${serverPort}`;
|
||||
if (publicPort !== undefined) {
|
||||
output.T3CODE_AUTH_COOKIE_PORT = String(publicPort);
|
||||
}
|
||||
} else {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
|
||||
@@ -479,6 +564,7 @@ interface DevRunnerCliInput {
|
||||
readonly host: string | undefined;
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly publicUrl?: URL | undefined;
|
||||
readonly dryRun: boolean;
|
||||
readonly runArgs: ReadonlyArray<string>;
|
||||
}
|
||||
@@ -517,6 +603,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
host: input.host,
|
||||
port: input.port,
|
||||
devUrl: input.devUrl,
|
||||
publicUrl: input.publicUrl,
|
||||
});
|
||||
|
||||
const selectionSuffix =
|
||||
@@ -627,6 +714,13 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
publicUrl: Flag.string("public-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription(
|
||||
"Browser-facing HTTP(S) origin for remote dev access; also namespaces auth cookies by its public port.",
|
||||
),
|
||||
Flag.withFallbackConfig(optionalUrlConfig("T3CODE_PUBLIC_URL")),
|
||||
),
|
||||
dryRun: Flag.boolean("dry-run").pipe(
|
||||
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
|
||||
Flag.withDefault(false),
|
||||
|
||||
Reference in new issue
Block a user