feat(server): add Hermes Agent support
Deploy T3 Connect relay / Deploy production relay (push) Has been cancelled
Mobile EAS Production / EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }} (push) Has been cancelled
CI / Check (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Test Server 1 (push) Has been cancelled
CI / Test Server 2 (push) Has been cancelled
CI / Test Server 3 (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Mobile Native Changes (push) Has been cancelled
CI / Release Smoke (push) Has been cancelled
Forward to Cursor hygiene / POST to Cursor (push) Has been cancelled
CI / Mobile Native Static Analysis (push) Has been cancelled
Deploy T3 Connect relay / Deploy production relay (push) Has been cancelled
Mobile EAS Production / EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }} (push) Has been cancelled
CI / Check (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Test Server 1 (push) Has been cancelled
CI / Test Server 2 (push) Has been cancelled
CI / Test Server 3 (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Mobile Native Changes (push) Has been cancelled
CI / Release Smoke (push) Has been cancelled
Forward to Cursor hygiene / POST to Cursor (push) Has been cancelled
CI / Mobile Native Static Analysis (push) Has been cancelled
This commit is contained in:
commit
79b59d5e94
26 files changed
+3732
-18
No files matched your search
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* HermesDriver — `ProviderDriver` for the Hermes Agent (`hermes acp`) runtime.
|
||||
*
|
||||
* Hermes exposes an ACP-based CLI. Model discovery happens during the managed
|
||||
* provider status check via ACP session setup; there is no standalone auth
|
||||
* probe, so a successful discovery doubles as proof of authentication.
|
||||
*
|
||||
* Text generation is supported via the ACP runtime — `makeHermesTextGeneration`
|
||||
* drives `runtime.prompt` with a structured-output schema and collects the
|
||||
* agent's `agent_message_chunk` stream into a single JSON blob.
|
||||
*
|
||||
* @module provider/Drivers/HermesDriver
|
||||
*/
|
||||
import { HermesSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeHermesTextGeneration } from "../../textGeneration/HermesTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
|
||||
import {
|
||||
buildInitialHermesProviderSnapshot,
|
||||
checkHermesProviderStatus,
|
||||
enrichHermesSnapshot,
|
||||
} from "../Layers/HermesProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import {
|
||||
haveProviderSnapshotSettingsChanged,
|
||||
makeProviderSnapshotSettingsSource,
|
||||
type ProviderSnapshotSettings,
|
||||
} from "../providerUpdateSettings.ts";
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
// `ServerConfig` stays in the union even though `create` never yields it
|
||||
// directly: `makeHermesAdapter` reads it for the attachments directory.
|
||||
export type HermesDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "Hermes",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: HermesSettings,
|
||||
defaultConfig: (): HermesSettings => decodeHermesSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
displayName,
|
||||
accentColor,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies HermesSettings;
|
||||
|
||||
const adapter = yield* makeHermesAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
instanceId,
|
||||
});
|
||||
const textGeneration = yield* makeHermesTextGeneration(effectiveConfig, processEnv);
|
||||
|
||||
const checkProvider = checkHermesProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<HermesSettings>>({
|
||||
resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
initialSnapshot: (settings) =>
|
||||
buildInitialHermesProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
|
||||
checkProvider,
|
||||
// Model data comes exclusively from ACP session setup during provider
|
||||
// status checks; enrichment only republishes version advisory metadata.
|
||||
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
|
||||
enrichHermesSnapshot({
|
||||
settings: settings.provider,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities: MAINTENANCE_CAPABILITIES,
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Hermes snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,475 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - the suite writes a real shell wrapper for the mock ACP agent to a temp dir with Node fs/path/url.
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
HermesSettings,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
makeHermesAdapter,
|
||||
resolveRequestedModeId,
|
||||
selectAutoApprovedPermissionOption,
|
||||
selectHermesPermissionOptionId,
|
||||
} from "./HermesAdapter.ts";
|
||||
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const mockAgentCommand = process.execPath;
|
||||
|
||||
async function makeMockHermesWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "hermes-acp-mock-"));
|
||||
const wrapperPath = NodePath.join(dir, "fake-hermes.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await NodeFSP.writeFile(wrapperPath, script, "utf8");
|
||||
await NodeFSP.chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
const hermesAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-hermes-adapter-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeHermesAdapter>[1]) =>
|
||||
makeHermesAdapter(decodeHermesSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("auto-approves with allow_always when the agent offers it", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Always allow", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
assert.equal(optionId, "allow-always");
|
||||
});
|
||||
|
||||
it("auto-approves with allow_once when allow_always is absent", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
assert.equal(optionId, "allow-once");
|
||||
});
|
||||
|
||||
it("auto-approves nothing when the agent offers no allow options", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [{ optionId: "reject-once", name: "Reject", kind: "reject_once" }],
|
||||
});
|
||||
assert.isUndefined(optionId);
|
||||
});
|
||||
|
||||
it("answers a manual decision with the agent's advertised option id", () => {
|
||||
const request = {
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" as const },
|
||||
{ optionId: "permit-always-7", name: "Always allow", kind: "allow_always" as const },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" as const },
|
||||
],
|
||||
};
|
||||
assert.equal(selectHermesPermissionOptionId(request, "accept"), "permit-42");
|
||||
assert.equal(selectHermesPermissionOptionId(request, "acceptForSession"), "permit-always-7");
|
||||
assert.equal(selectHermesPermissionOptionId(request, "decline"), "deny-9");
|
||||
});
|
||||
|
||||
it("treats acceptAlways as a persistent allow, never a rejection", () => {
|
||||
const options = [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" as const },
|
||||
{ optionId: "permit-always-7", name: "Always allow", kind: "allow_always" as const },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" as const },
|
||||
];
|
||||
assert.equal(
|
||||
selectHermesPermissionOptionId(
|
||||
{ sessionId: "mock-session-1", toolCall: { toolCallId: "tool-1" }, options },
|
||||
"acceptAlways",
|
||||
),
|
||||
"permit-always-7",
|
||||
);
|
||||
// Without allow_always the persistent accept degrades to a one-shot allow,
|
||||
// never to the reject option.
|
||||
assert.equal(
|
||||
selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: options.filter((option) => option.kind !== "allow_always"),
|
||||
},
|
||||
"acceptAlways",
|
||||
),
|
||||
"permit-42",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to allow_once for a session accept when allow_always is absent", () => {
|
||||
const optionId = selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
"acceptForSession",
|
||||
);
|
||||
assert.equal(optionId, "permit-42");
|
||||
});
|
||||
|
||||
it("selects no option when the agent advertised none matching the decision", () => {
|
||||
const optionId = selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [{ optionId: "permit-42", name: "Allow once", kind: "allow_once" }],
|
||||
},
|
||||
"decline",
|
||||
);
|
||||
assert.isUndefined(optionId);
|
||||
});
|
||||
|
||||
it("resolves plan interaction mode to the agent's plan mode", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "full-access",
|
||||
modeState: {
|
||||
currentModeId: "implement",
|
||||
availableModes: [
|
||||
{ id: "plan", name: "Plan" },
|
||||
{ id: "implement", name: "Implement" },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "plan");
|
||||
});
|
||||
|
||||
it("resolves approval-required to an approval-shaped mode before implement", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "implement",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask" },
|
||||
{ id: "implement", name: "Implement" },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "ask");
|
||||
});
|
||||
|
||||
// The exact session modes the live `hermes acp` CLI (v0.21) advertises. All
|
||||
// three mention "ask", so approval selection cannot lean on substring order.
|
||||
const liveHermesModes = [
|
||||
{ id: "default", name: "Default", description: "Ask before edits." },
|
||||
{
|
||||
id: "accept_edits",
|
||||
name: "Accept Edits",
|
||||
description: "Auto-allow workspace and /tmp edits; still asks for sensitive paths.",
|
||||
},
|
||||
{
|
||||
id: "dont_ask",
|
||||
name: "Don't Ask",
|
||||
description: "Auto-allow file edits for this session except sensitive paths.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
it("resolves approval-required to the mode that still prompts", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: { currentModeId: "default", availableModes: liveHermesModes },
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("resolves approval-required independently of the order Hermes lists modes in", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [liveHermesModes[2], liveHermesModes[1], liveHermesModes[0]],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("still resolves the implement mode when approvals are not required", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "full-access",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [liveHermesModes[2], liveHermesModes[1], liveHermesModes[0]],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("resolves approval-required to an asking mode that shares no alias with its id", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [
|
||||
{ id: "dont_ask", name: "Don't Ask", description: "Auto-allow." },
|
||||
{ id: "confirm_edits", name: "Confirm Edits", description: "Ask before applying edits." },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "confirm_edits");
|
||||
});
|
||||
|
||||
it("resolves no mode when the agent advertises none", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "full-access",
|
||||
modeState: undefined,
|
||||
});
|
||||
assert.isUndefined(modeId);
|
||||
});
|
||||
|
||||
it.layer(hermesAdapterTestLayer)("HermesAdapter (mock ACP agent)", (it) => {
|
||||
it.effect("rejects rollback without discarding the provider conversation", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-unsupported-rollback");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "Remember this turn", attachments: [] });
|
||||
const originalTurns = [...(yield* adapter.readThread(threadId)).turns];
|
||||
|
||||
assert.isFalse(adapter.capabilities.supportsConversationRollback);
|
||||
const error = yield* adapter.rollbackThread(threadId, 1).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.deepStrictEqual((yield* adapter.readThread(threadId)).turns, originalTurns);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-mock-thread");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-mock-alt",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "hermes");
|
||||
assert.equal(session.model, "grok-mock-alt");
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hello hermes",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
const types = runtimeEvents.map((event) => event.type);
|
||||
|
||||
assert.includeMembers(types, [
|
||||
"session.started",
|
||||
"session.state.changed",
|
||||
"thread.started",
|
||||
"turn.started",
|
||||
"content.delta",
|
||||
"turn.completed",
|
||||
] as const);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never announces a turn whose preparation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-failed-preparation");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
if (String(event.threadId) === String(threadId)) {
|
||||
runtimeEvents.push(event);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Rejected prompt: whitespace-only text with no usable attachments.
|
||||
yield* Effect.flip(adapter.sendTurn({ threadId, input: " \n ", attachments: [] }));
|
||||
|
||||
// Rejected configuration: the mock refuses model ids it never advertised.
|
||||
yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "configure with a model the agent rejects",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "model-the-mock-never-advertises",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Neither failure may surface a turn: a started turn that cannot settle
|
||||
// leaves consumers with a permanently running turn.
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter((event) => event.type === "turn.started"),
|
||||
0,
|
||||
);
|
||||
|
||||
// The claim was released, so a good turn afterwards still runs normally.
|
||||
yield* adapter.sendTurn({ threadId, input: "now a real prompt", attachments: [] });
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter((event) => event.type === "turn.started"),
|
||||
1,
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("merges a sendTurn racing session configuration into the in-flight turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-steer-race");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockHermesWrapper({
|
||||
T3_ACP_EMIT_CONTENT_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "content.delta") {
|
||||
yield* Deferred.succeed(contentDelta, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Steer while the first prompt is still in flight. The steer must
|
||||
// observe the first turn's id — assigned synchronously with the
|
||||
// in-flight increment, before the awaited session configuration — and
|
||||
// merge into it; a second turn.started is the duplicate-turn
|
||||
// regression.
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "start work", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(contentDelta).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
|
||||
const steerSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "steer the running turn", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 12; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
// The steer folded into the running turn: exactly one turn.started,
|
||||
// one distinct turn id. A second of either is the regression.
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
assert.lengthOf(turnStartedEvents, 1);
|
||||
const turnIds = new Set(
|
||||
runtimeEvents
|
||||
.filter((event) => event.type === "turn.started")
|
||||
.map((event) => String(event.turnId)),
|
||||
);
|
||||
assert.equal(turnIds.size, 1);
|
||||
|
||||
// interruptTurn settles both in-flight prompts; stopSession tears the
|
||||
// hung mock child down regardless.
|
||||
yield* adapter.interruptTurn(threadId).pipe(Effect.ignore);
|
||||
yield* Fiber.interrupt(firstSendTurnFiber);
|
||||
yield* Fiber.interrupt(steerSendTurnFiber);
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId).pipe(Effect.ignore);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,346 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HermesSettings } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildHermesProviderSnapshot,
|
||||
checkHermesProviderStatus,
|
||||
getHermesFallbackModels,
|
||||
parseHermesCliVersion,
|
||||
parseHermesVersionOutput,
|
||||
} from "./HermesProvider.ts";
|
||||
|
||||
const decodeHermesSettings = Schema.decodeUnknownSync(HermesSettings);
|
||||
const baseHermesSettings = decodeHermesSettings({ enabled: true });
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
|
||||
});
|
||||
|
||||
const hermesVersionBanner = "Hermes Agent v0.21.0 (2026.8.31) · upstream f98f5e74";
|
||||
|
||||
/**
|
||||
* A minimal newline-delimited JSON-RPC agent whose `session/new` advertises an
|
||||
* empty model catalog — the one shape the shared ACP mock agent cannot
|
||||
* produce.
|
||||
*/
|
||||
const emptyModelsAgentSource = `import * as readline from "node:readline";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin });
|
||||
rl.on("line", (line) => {
|
||||
if (!line.trim()) return;
|
||||
const message = JSON.parse(line);
|
||||
if (message.id === undefined) return;
|
||||
const respond = (result) =>
|
||||
process.stdout.write(\`\${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\\n\`);
|
||||
switch (message.method) {
|
||||
case "initialize":
|
||||
respond({
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
authMethods: [{ id: "custom", name: "Custom", description: null }],
|
||||
});
|
||||
break;
|
||||
case "authenticate":
|
||||
respond({});
|
||||
break;
|
||||
case "session/new":
|
||||
respond({
|
||||
sessionId: "hermes-empty-models",
|
||||
models: { currentModelId: "default", availableModels: [] },
|
||||
});
|
||||
break;
|
||||
default:
|
||||
respond({});
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
/**
|
||||
* Wrap an ACP agent in a shell script that answers `--version` like the real
|
||||
* Hermes CLI. `versionExitCode` breaks the version probe; `acp` selects what
|
||||
* backs the discovery leg.
|
||||
*/
|
||||
const makeMockHermesWrapper = Effect.fn("makeMockHermesWrapper")(function* (options?: {
|
||||
readonly versionExitCode?: number;
|
||||
readonly acp?: "mock-agent" | "empty-models" | "fail";
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fileSystem.makeTempDirectory({
|
||||
directory: NodeOS.tmpdir(),
|
||||
prefix: "hermes-provider-mock-",
|
||||
});
|
||||
|
||||
const acpCommand = yield* Effect.gen(function* () {
|
||||
if (options?.acp === "fail") {
|
||||
return "exit 1";
|
||||
}
|
||||
if (options?.acp === "empty-models") {
|
||||
const agentPath = path.join(dir, "empty-models-agent.mjs");
|
||||
yield* fileSystem.writeFileString(agentPath, emptyModelsAgentSource);
|
||||
return `exec ${["node", agentPath].map((arg) => JSON.stringify(arg)).join(" ")} "$@"`;
|
||||
}
|
||||
const mockAgentPath = yield* resolveMockAgentPath();
|
||||
return `exec ${["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ")} "$@"`;
|
||||
});
|
||||
|
||||
const versionCommand =
|
||||
options?.versionExitCode !== undefined
|
||||
? `exit ${options.versionExitCode}`
|
||||
: `${["printf", "%s\n", hermesVersionBanner]
|
||||
.map((arg) => JSON.stringify(arg))
|
||||
.join(" ")}\n exit 0`;
|
||||
const script = `#!/bin/sh
|
||||
if [ "$1" = "--version" ]; then
|
||||
${versionCommand}
|
||||
fi
|
||||
${acpCommand}
|
||||
`;
|
||||
const wrapperPath = path.join(dir, "fake-hermes.sh");
|
||||
yield* fileSystem.writeFileString(wrapperPath, script);
|
||||
yield* fileSystem.chmod(wrapperPath, 0o755);
|
||||
return { wrapperPath, requestLogPath: path.join(dir, "requests.ndjson") };
|
||||
});
|
||||
|
||||
const missingHermesBinaryPath = "/definitely/not/installed/t3-hermes-agent";
|
||||
const hermesAcpDiscoveryFailedMessage = [
|
||||
"Hermes ACP model discovery failed.",
|
||||
"Hermes may not be configured on this machine yet; run `hermes setup` (or `hermes acp --setup`), then retry.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
|
||||
describe("parseHermesCliVersion", () => {
|
||||
it("extracts the semver from the real `hermes --version` banner, not the build date", () => {
|
||||
expect(parseHermesCliVersion(hermesVersionBanner)).toBe("0.21.0");
|
||||
});
|
||||
|
||||
it("falls back to the generic parser when the version is not v-prefixed", () => {
|
||||
expect(parseHermesCliVersion("hermes 0.21.0")).toBe("0.21.0");
|
||||
});
|
||||
|
||||
it("returns null when no version is present", () => {
|
||||
expect(parseHermesCliVersion("no version here")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseHermesVersionOutput", () => {
|
||||
it("treats a zero exit as a ready probe with unknown auth", () => {
|
||||
expect(
|
||||
parseHermesVersionOutput({
|
||||
stdout: hermesVersionBanner,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a non-zero exit as an error probe", () => {
|
||||
expect(
|
||||
parseHermesVersionOutput({
|
||||
stdout: "",
|
||||
stderr: "boom",
|
||||
code: 1,
|
||||
}),
|
||||
).toMatchObject({
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getHermesFallbackModels", () => {
|
||||
it("publishes the built-in default model plus custom models before ACP discovery", () => {
|
||||
expect(
|
||||
getHermesFallbackModels({
|
||||
customModels: ["anthropic:claude-fable-5"],
|
||||
}).map((model) => model.slug),
|
||||
).toEqual(["default", "anthropic:claude-fable-5"]);
|
||||
});
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("checkHermesProviderStatus", (it) => {
|
||||
it.effect("returns a disabled snapshot without probing the CLI", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
decodeHermesSettings({ enabled: false, binaryPath: missingHermesBinaryPath }),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
enabled: false,
|
||||
installed: false,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a missing Hermes command without attempting ACP discovery", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: missingHermesBinaryPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: [
|
||||
`Hermes Agent command \`${missingHermesBinaryPath}\` was not found.`,
|
||||
`Install the Hermes Agent CLI, make sure \`${missingHermesBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
].join(" "),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips ACP discovery when the version probe exits non-zero", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { wrapperPath, requestLogPath } = yield* makeMockHermesWrapper({ versionExitCode: 1 });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
{ ...baseHermesSettings, binaryPath: wrapperPath },
|
||||
{ ...process.env, T3_ACP_REQUEST_LOG_PATH: requestLogPath },
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
// The ACP mock agent logs every request; an absent log proves the
|
||||
// `parsed.status === "ready"` gate skipped discovery entirely.
|
||||
expect(yield* fileSystem.exists(requestLogPath)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes discovered models and authenticated auth when ACP discovery succeeds", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { wrapperPath, requestLogPath } = yield* makeMockHermesWrapper();
|
||||
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
{ ...baseHermesSettings, binaryPath: wrapperPath },
|
||||
{ ...process.env, T3_ACP_REQUEST_LOG_PATH: requestLogPath },
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
});
|
||||
expect(provider.message).toBeUndefined();
|
||||
// The shared ACP mock agent advertises a fixed grok-flavored catalog.
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
|
||||
// The mock agent logs every request before responding, so the log is
|
||||
// complete by the time the status check resolves.
|
||||
expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("downgrades to warning with fallback models when ACP discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { wrapperPath } = yield* makeMockHermesWrapper({ acp: "fail" });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: wrapperPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: hermesAcpDiscoveryFailedMessage,
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks auth authenticated but warns when discovery returns no models", () =>
|
||||
Effect.gen(function* () {
|
||||
const { wrapperPath } = yield* makeMockHermesWrapper({ acp: "empty-models" });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: wrapperPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "warning",
|
||||
auth: { status: "authenticated" },
|
||||
message: "Hermes ACP model discovery returned no built-in models.",
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("buildHermesProviderSnapshot", () => {
|
||||
it("downgrades ready status to warning when ACP model discovery fails", () => {
|
||||
expect(
|
||||
buildHermesProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
hermesSettings: baseHermesSettings,
|
||||
parsed: {
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
},
|
||||
discoveryWarning: "Hermes ACP model discovery timed out after 15000ms.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "warning",
|
||||
message: "Hermes ACP model discovery timed out after 15000ms.",
|
||||
models: [{ slug: "default", isCustom: false }],
|
||||
});
|
||||
});
|
||||
|
||||
it("publishes discovered models without a warning when discovery succeeds", () => {
|
||||
expect(
|
||||
buildHermesProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
hermesSettings: baseHermesSettings,
|
||||
parsed: {
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
},
|
||||
discoveredModels: [
|
||||
{
|
||||
slug: "moa:default",
|
||||
name: "MoA Default",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({ optionDescriptors: [] }),
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
models: [{ slug: "moa:default", isCustom: false }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
import type {
|
||||
HermesSettings,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { HERMES_DEFAULT_MODEL_SLUG, makeHermesAcpRuntime } from "../acp/HermesAcpSupport.ts";
|
||||
|
||||
const HERMES_PRESENTATION = {
|
||||
displayName: "Hermes",
|
||||
badgeLabel: "Experimental",
|
||||
showInteractionModeToggle: false,
|
||||
} as const;
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
|
||||
const HERMES_VERSION_PROBE_TIMEOUT_MS = 4_000;
|
||||
const HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const HERMES_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Hermes ACP model discovery failed.",
|
||||
"Hermes may not be configured on this machine yet; run `hermes setup` (or `hermes acp --setup`), then retry.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
|
||||
const HERMES_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: HERMES_DEFAULT_MODEL_SLUG,
|
||||
name: "Hermes (configured default)",
|
||||
isCustom: false,
|
||||
isDefault: true,
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
},
|
||||
];
|
||||
|
||||
export function buildInitialHermesProviderSnapshot(
|
||||
hermesSettings: HermesSettings,
|
||||
): Effect.Effect<ServerProviderDraft> {
|
||||
return Effect.gen(function* () {
|
||||
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const models = getHermesFallbackModels(hermesSettings);
|
||||
|
||||
if (!hermesSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Checking Hermes Agent availability...",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function buildHermesDiscoveredModelsFromSessionModelState(
|
||||
modelState: EffectAcpSchema.SessionModelState | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (!modelState || modelState.availableModels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
// Mark the session's current model as the default so the model resolver
|
||||
// binds new sessions to it instead of the catalog's first entry — without
|
||||
// this a session/set_model fires on every start, switching the agent away
|
||||
// from its own configured model.
|
||||
const currentModelId = modelState.currentModelId?.trim();
|
||||
const seen = new Set<string>();
|
||||
return modelState.availableModels.flatMap((model) => {
|
||||
const slug = model.modelId.trim();
|
||||
if (!slug || seen.has(slug)) {
|
||||
return [];
|
||||
}
|
||||
seen.add(slug);
|
||||
return [
|
||||
{
|
||||
slug,
|
||||
name: model.name.trim() || slug,
|
||||
isCustom: false,
|
||||
...(slug === currentModelId ? { isDefault: true } : {}),
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
} satisfies ServerProviderModel,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export const discoverHermesModelsViaAcp = (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const acp = yield* makeHermesAcpRuntime({
|
||||
hermesSettings,
|
||||
...(environment ? { environment } : {}),
|
||||
childProcessSpawner,
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
|
||||
});
|
||||
const started = yield* acp.start();
|
||||
return buildHermesDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
export function getHermesFallbackModels(
|
||||
hermesSettings: Pick<HermesSettings, "customModels">,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return providerModelsFromSettings(
|
||||
HERMES_BUILT_IN_MODELS,
|
||||
hermesSettings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the Hermes Agent version from `hermes --version` output.
|
||||
*
|
||||
* The first line looks like:
|
||||
* `Hermes Agent v0.21.0 (2026.8.31) · upstream f98f5e74`
|
||||
*
|
||||
* The generic parser would grab the parenthesised build date first, so we
|
||||
* prefer the `v`-prefixed semver token and fall back to the generic parser.
|
||||
*/
|
||||
export function parseHermesCliVersion(output: string): string | null {
|
||||
const match = output.match(/\bv(\d+\.\d+\.\d+)\b/);
|
||||
return match?.[1] ?? parseGenericCliVersion(output);
|
||||
}
|
||||
|
||||
export interface HermesVersionResult {
|
||||
readonly version: string | null;
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: ServerProviderAuth;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
|
||||
const parts: Array<string> = [];
|
||||
for (const message of messages) {
|
||||
const trimmed = message?.trim();
|
||||
if (trimmed) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildHermesCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Hermes Agent command \`${binaryPath}\` was not found.`,
|
||||
`Install the Hermes Agent CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildHermesProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly hermesSettings: HermesSettings;
|
||||
readonly parsed: HermesVersionResult;
|
||||
readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
|
||||
readonly discoveryWarning?: string;
|
||||
}): ServerProviderDraft {
|
||||
const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: input.hermesSettings.enabled,
|
||||
checkedAt: input.checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
input.discoveredModels && input.discoveredModels.length > 0
|
||||
? input.discoveredModels
|
||||
: HERMES_BUILT_IN_MODELS,
|
||||
input.hermesSettings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: true,
|
||||
version: input.parsed.version,
|
||||
status:
|
||||
input.discoveryWarning && input.parsed.status === "ready" ? "warning" : input.parsed.status,
|
||||
auth: input.parsed.auth,
|
||||
...(message ? { message } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Interpret `hermes --version` output as a probe result. */
|
||||
export function parseHermesVersionOutput(result: CommandResult): HermesVersionResult {
|
||||
const version = parseHermesCliVersion(`${result.stdout}\n${result.stderr}`);
|
||||
if (result.code !== 0) {
|
||||
return {
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
return { version, status: "ready", auth: { status: "unknown" } };
|
||||
}
|
||||
|
||||
const runHermesVersionCommand = (hermesSettings: HermesSettings, environment?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const command = hermesSettings.binaryPath || "hermes";
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
command,
|
||||
["--version"],
|
||||
environment ? { env: environment } : {},
|
||||
);
|
||||
return yield* spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...(environment ? { env: environment } : { extendEnv: true }),
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const checkHermesProviderStatus = Effect.fn("checkHermesProviderStatus")(function* (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
|
||||
> {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const fallbackModels = getHermesFallbackModels(hermesSettings);
|
||||
|
||||
if (!hermesSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runHermesVersionCommand(hermesSettings, environment).pipe(
|
||||
Effect.timeoutOption(HERMES_VERSION_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
yield* Effect.logWarning("Hermes Agent CLI health check failed.", {
|
||||
errorTag: error._tag,
|
||||
});
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: hermesSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? buildHermesCliCommandMissingMessage(hermesSettings.binaryPath || "hermes")
|
||||
: "Failed to execute Hermes Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: hermesSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but timed out while running `hermes --version`.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseHermesVersionOutput(versionProbe.success.value);
|
||||
// Hermes has no standalone auth probe: `hermes acp` authenticates through the
|
||||
// "custom" method during startup, so a successful ACP discovery doubles as
|
||||
// proof of authentication.
|
||||
let auth: ServerProviderAuth = parsed.auth;
|
||||
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
|
||||
let discoveryWarning: string | undefined;
|
||||
if (parsed.status === "ready") {
|
||||
const discoveryExit = yield* Effect.exit(
|
||||
discoverHermesModelsViaAcp(hermesSettings, environment).pipe(
|
||||
Effect.timeoutOption(HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
|
||||
),
|
||||
);
|
||||
if (Exit.isFailure(discoveryExit)) {
|
||||
yield* Effect.logWarning("Hermes ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = HERMES_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Hermes ACP model discovery timed out after ${HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
discoveryWarning = "Hermes ACP model discovery returned no built-in models.";
|
||||
auth = { status: "authenticated" };
|
||||
} else {
|
||||
discoveredModels = discoveryExit.value;
|
||||
auth = { status: "authenticated" };
|
||||
}
|
||||
}
|
||||
return buildHermesProviderSnapshot({
|
||||
checkedAt,
|
||||
hermesSettings,
|
||||
parsed: { ...parsed, auth },
|
||||
discoveredModels: Option.getOrElse(
|
||||
Option.filter(discoveredModels, (models) => models.length > 0),
|
||||
() => [] as const,
|
||||
),
|
||||
...(discoveryWarning ? { discoveryWarning } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Background maintenance enrichment for a Hermes snapshot.
|
||||
*
|
||||
* Used by `HermesDriver` as the `makeManagedServerProvider.enrichSnapshot`
|
||||
* hook: republishes update/version advisory metadata without performing any
|
||||
* model or capability discovery. Hermes model data comes exclusively from ACP
|
||||
* session setup during provider status checks.
|
||||
*/
|
||||
export const enrichHermesSnapshot = (input: {
|
||||
readonly settings: HermesSettings;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly enableProviderUpdateChecks?: boolean;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
if (!settings.enabled || snapshot.auth.status === "unauthenticated") {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: input.enableProviderUpdateChecks,
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Hermes version advisory enrichment failed", {
|
||||
errorTag: causeErrorTag(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -10,7 +10,7 @@
|
||||
*
|
||||
* 2. **Many drivers, one registry** — the "all drivers slice" describe
|
||||
* block below configures one instance of every shipped driver
|
||||
* (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
|
||||
* (`codex`, `claudeAgent`, `cursor`, `grok`, `hermes`, `opencode`) in a single
|
||||
* `ProviderInstanceConfigMap` and asserts the registry boots them all
|
||||
* without cross-contamination. This proves the driver SPI is uniform
|
||||
* across every provider — any driver plugs into the registry through
|
||||
@@ -18,7 +18,7 @@
|
||||
*
|
||||
* Every instance in these tests is configured with `enabled: false` so the
|
||||
* provider-status checks short-circuit to pending/disabled snapshots
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `hermes` / `opencode`
|
||||
* binaries. That keeps the assertions focused on registry routing
|
||||
* behaviour rather than the runtime details of each provider.
|
||||
*/
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type CodexSettings,
|
||||
type CursorSettings,
|
||||
type GrokSettings,
|
||||
type HermesSettings,
|
||||
type OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfigMap,
|
||||
@@ -53,6 +54,7 @@ import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { HermesDriver } from "../Drivers/HermesDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import * as ModelManifest from "../ModelManifest.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
@@ -133,6 +135,13 @@ const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeHermesConfig = (overrides: Partial<HermesSettings>): HermesSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "hermes",
|
||||
customModels: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "opencode",
|
||||
@@ -468,12 +477,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const claudeId = ProviderInstanceId.make("claude_default");
|
||||
const cursorId = ProviderInstanceId.make("cursor_default");
|
||||
const grokId = ProviderInstanceId.make("grok_default");
|
||||
const hermesId = ProviderInstanceId.make("hermes_default");
|
||||
const openCodeId = ProviderInstanceId.make("opencode_default");
|
||||
|
||||
const codexDriverKind = ProviderDriverKind.make("codex");
|
||||
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
|
||||
const cursorDriverKind = ProviderDriverKind.make("cursor");
|
||||
const grokDriverKind = ProviderDriverKind.make("grok");
|
||||
const hermesDriverKind = ProviderDriverKind.make("hermes");
|
||||
const openCodeDriverKind = ProviderDriverKind.make("opencode");
|
||||
|
||||
const configMap: ProviderInstanceConfigMap = {
|
||||
@@ -504,6 +515,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
enabled: false,
|
||||
config: makeGrokConfig({}),
|
||||
},
|
||||
[hermesId]: {
|
||||
driver: hermesDriverKind,
|
||||
displayName: "Hermes",
|
||||
enabled: false,
|
||||
config: makeHermesConfig({}),
|
||||
},
|
||||
[openCodeId]: {
|
||||
driver: openCodeDriverKind,
|
||||
displayName: "OpenCode",
|
||||
@@ -513,7 +530,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
};
|
||||
|
||||
const { registry } = yield* makeProviderInstanceRegistry<BuiltInDriversEnv>({
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
|
||||
drivers: [
|
||||
CodexDriver,
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
HermesDriver,
|
||||
OpenCodeDriver,
|
||||
],
|
||||
configMap,
|
||||
});
|
||||
|
||||
@@ -523,9 +547,9 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(unavailable).toEqual([]);
|
||||
|
||||
const instances = yield* registry.listInstances;
|
||||
expect(instances).toHaveLength(5);
|
||||
expect(instances).toHaveLength(6);
|
||||
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
|
||||
[codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
|
||||
[codexId, claudeId, cursorId, grokId, hermesId, openCodeId].toSorted(),
|
||||
);
|
||||
|
||||
// Instance lookup by id resolves each instance to its own bundle —
|
||||
@@ -535,16 +559,19 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const claude = yield* registry.getInstance(claudeId);
|
||||
const cursor = yield* registry.getInstance(cursorId);
|
||||
const grok = yield* registry.getInstance(grokId);
|
||||
const hermes = yield* registry.getInstance(hermesId);
|
||||
const openCode = yield* registry.getInstance(openCodeId);
|
||||
expect(codex?.driverKind).toBe(codexDriverKind);
|
||||
expect(claude?.driverKind).toBe(claudeDriverKind);
|
||||
expect(cursor?.driverKind).toBe(cursorDriverKind);
|
||||
expect(grok?.driverKind).toBe(grokDriverKind);
|
||||
expect(hermes?.driverKind).toBe(hermesDriverKind);
|
||||
expect(openCode?.driverKind).toBe(openCodeDriverKind);
|
||||
expect(codex?.displayName).toBe("Codex");
|
||||
expect(claude?.displayName).toBe("Claude");
|
||||
expect(cursor?.displayName).toBe("Cursor");
|
||||
expect(grok?.displayName).toBe("Grok");
|
||||
expect(hermes?.displayName).toBe("Hermes");
|
||||
expect(openCode?.displayName).toBe("OpenCode");
|
||||
|
||||
// Every instance owns its own set of closures — no sharing across
|
||||
@@ -557,6 +584,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.adapter,
|
||||
cursor!.adapter,
|
||||
grok!.adapter,
|
||||
hermes!.adapter,
|
||||
openCode!.adapter,
|
||||
];
|
||||
expect(new Set(adapters).size).toBe(adapters.length);
|
||||
@@ -565,6 +593,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.textGeneration,
|
||||
cursor!.textGeneration,
|
||||
grok!.textGeneration,
|
||||
hermes!.textGeneration,
|
||||
openCode!.textGeneration,
|
||||
];
|
||||
expect(new Set(textGenerations).size).toBe(textGenerations.length);
|
||||
@@ -573,6 +602,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.snapshot,
|
||||
cursor!.snapshot,
|
||||
grok!.snapshot,
|
||||
hermes!.snapshot,
|
||||
openCode!.snapshot,
|
||||
];
|
||||
expect(new Set(snapshots).size).toBe(snapshots.length);
|
||||
@@ -613,6 +643,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(grokSnapshot.enabled).toBe(false);
|
||||
expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
|
||||
|
||||
const hermesSnapshot = yield* hermes!.snapshot.getSnapshot;
|
||||
expect(hermesSnapshot.instanceId).toBe(hermesId);
|
||||
expect(hermesSnapshot.driver).toBe(hermesDriverKind);
|
||||
expect(hermesSnapshot.enabled).toBe(false);
|
||||
expect(hermesSnapshot.continuation?.groupKey).toBe(
|
||||
`${hermesDriverKind}:instance:${hermesId}`,
|
||||
);
|
||||
|
||||
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
|
||||
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
|
||||
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
|
||||
|
||||
@@ -2244,6 +2244,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
// `providerInstances` keys are branded `ProviderInstanceId`;
|
||||
@@ -2356,6 +2357,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
}),
|
||||
@@ -2472,6 +2474,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
providerInstances: {
|
||||
@@ -2542,6 +2545,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
hermes: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -2616,6 +2622,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
"codex",
|
||||
"cursor",
|
||||
"grok",
|
||||
"hermes",
|
||||
"opencode",
|
||||
]);
|
||||
assert.strictEqual(cursorProvider?.enabled, false);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* HermesAdapter — shape type for the Hermes provider adapter.
|
||||
*
|
||||
* The driver model ({@link ../Drivers/HermesDriver}) bundles one adapter per
|
||||
* instance as a captured closure, so this module only retains the shape
|
||||
* interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module HermesAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* HermesAdapterShape — per-instance Hermes adapter contract.
|
||||
*/
|
||||
export interface HermesAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Optional integration check against a real `hermes acp` install.
|
||||
* Enable with: T3_HERMES_ACP_PROBE=1 vp test run HermesAcpCliProbe
|
||||
* Set T3_HERMES_LIVE_TURN=1 to also send a small prompt to the real model.
|
||||
*
|
||||
* Set T3_HERMES_ACP_PROBE_BINARY to run a hermes binary that is not on
|
||||
* PATH (a wrapper script that proxies stdio to a remote install works,
|
||||
* since ACP is pure stdio).
|
||||
*
|
||||
* The probe assumes the hermes runtime is already configured with model
|
||||
* credentials (`hermes setup`). The prompt turn calls the real model, so
|
||||
* it can take tens of seconds.
|
||||
*/
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { makeHermesAcpRuntime } from "./HermesAcpSupport.ts";
|
||||
|
||||
const probeBinaryPath = process.env.T3_HERMES_ACP_PROBE_BINARY || "hermes";
|
||||
|
||||
// The session cwd must exist wherever the hermes process actually runs:
|
||||
// `hermes acp` rejects `session/new` for a nonexistent cwd, and with a
|
||||
// remote wrapper binary a per-run local temp directory does not exist on
|
||||
// the remote host. `os.tmpdir()` exists everywhere a local install runs
|
||||
// and resolves to /tmp on the hosts a POSIX ssh shim targets;
|
||||
// T3_HERMES_ACP_PROBE_CWD overrides it when that assumption breaks.
|
||||
const probeCwd = process.env.T3_HERMES_ACP_PROBE_CWD || NodeOS.tmpdir();
|
||||
|
||||
const makeProbeRuntime = Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return yield* makeHermesAcpRuntime({
|
||||
hermesSettings: { binaryPath: probeBinaryPath },
|
||||
environment: process.env,
|
||||
childProcessSpawner,
|
||||
cwd: probeCwd,
|
||||
clientInfo: { name: "t3-hermes-probe", version: "0.0.0" },
|
||||
});
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_HERMES_ACP_PROBE === "1")("Hermes ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real hermes acp", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.initializeResult).toBeDefined();
|
||||
expect(typeof started.sessionId).toBe("string");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// Hermes spends a long thinking phase on even trivial prompts, so a real
|
||||
// turn regularly exceeds the suite's default test timeout. The probe is
|
||||
// env-gated and never runs in CI, so a generous explicit budget is safe.
|
||||
it.effect.skipIf(process.env.T3_HERMES_LIVE_TURN !== "1")(
|
||||
"finishes a real Hermes turn and streams its answer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
yield* runtime.start();
|
||||
const chunks: string[] = [];
|
||||
const events = yield* Stream.runForEach(runtime.getEvents(), (event) => {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
return Deferred.succeed(event.acknowledge, undefined);
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
chunks.push(event.text);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
const result = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "Reply exactly HERMES_T3_OK. Do not use any tools." }],
|
||||
});
|
||||
yield* runtime.drainEvents;
|
||||
expect(result.stopReason).toBe("end_turn");
|
||||
// Hermes's thinking-heavy turns don't reliably echo the exact token
|
||||
// (unlike the Grok probe) — assert streamed output arrived, not its
|
||||
// wording.
|
||||
expect(chunks.join("").length).toBeGreaterThan(0);
|
||||
yield* Fiber.interrupt(events);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
300_000,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { applyHermesAcpModelSelection, buildHermesAcpSpawnInput } from "./HermesAcpSupport.ts";
|
||||
|
||||
describe("buildHermesAcpSpawnInput", () => {
|
||||
it("spawns the configured binary with the acp subcommand", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "/opt/hermes" }, "/tmp/project", {
|
||||
PATH: "/usr/bin",
|
||||
});
|
||||
|
||||
expect(spawn).toEqual({
|
||||
command: "/opt/hermes",
|
||||
args: ["acp"],
|
||||
cwd: "/tmp/project",
|
||||
env: {
|
||||
PATH: "/usr/bin",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default binary name", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "" }, "/tmp/project");
|
||||
expect(spawn.command).toBe("hermes");
|
||||
});
|
||||
|
||||
it("falls back when settings are absent", () => {
|
||||
const spawn = buildHermesAcpSpawnInput(null, "/tmp/project");
|
||||
expect(spawn.command).toBe("hermes");
|
||||
});
|
||||
|
||||
it("omits env entirely when no environment is provided", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "/opt/hermes" }, "/tmp/project");
|
||||
expect(spawn).toEqual({
|
||||
command: "/opt/hermes",
|
||||
args: ["acp"],
|
||||
cwd: "/tmp/project",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyHermesAcpModelSelection", () => {
|
||||
it.effect("passes the model id to session/set_model verbatim", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-opus-5",
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual(["anthropic:claude-fable-5"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never sends the default product slug as an ACP model id", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-fable-5",
|
||||
model: "default",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips session/set_model when the session is already on the model", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-fable-5",
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps set_model failures through mapError", () =>
|
||||
Effect.gen(function* () {
|
||||
const acpFailure = new EffectAcpErrors.AcpTransportError({
|
||||
detail: "set_model exploded",
|
||||
cause: new Error("set_model exploded"),
|
||||
});
|
||||
const runtime = {
|
||||
setSessionModel: () => Effect.fail(acpFailure),
|
||||
};
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: undefined,
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => ({ mapped: true as const, cause }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure).toEqual({ mapped: true, cause: acpFailure });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { HermesSettings } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
/** Auth method advertised by `hermes acp` for pre-configured runtime credentials. */
|
||||
const HERMES_AUTH_METHOD_ID = "custom";
|
||||
|
||||
/**
|
||||
* The product slug T3 publishes for "whatever model Hermes is configured to
|
||||
* use". It is never a real ACP model id, so it must never reach
|
||||
* `session/set_model` — selecting it keeps the session on its current model.
|
||||
*/
|
||||
export const HERMES_DEFAULT_MODEL_SLUG = "default";
|
||||
|
||||
type HermesAcpRuntimeHermesSettings = Pick<HermesSettings, "binaryPath">;
|
||||
|
||||
interface HermesAcpRuntimeInput extends Omit<
|
||||
AcpSessionRuntime.AcpSessionRuntimeOptions,
|
||||
"authMethodId" | "clientCapabilities" | "spawn"
|
||||
> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly hermesSettings: HermesAcpRuntimeHermesSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export function buildHermesAcpSpawnInput(
|
||||
hermesSettings: HermesAcpRuntimeHermesSettings | null | undefined,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): AcpSessionRuntime.AcpSpawnInput {
|
||||
return {
|
||||
command: hermesSettings?.binaryPath || "hermes",
|
||||
args: ["acp"],
|
||||
cwd,
|
||||
...(environment ? { env: environment } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const makeHermesAcpRuntime = (
|
||||
input: HermesAcpRuntimeInput,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildHermesAcpSpawnInput(input.hermesSettings, input.cwd, input.environment),
|
||||
authMethodId: HERMES_AUTH_METHOD_ID,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
});
|
||||
|
||||
export interface HermesAcpModelSelectionErrorContext {
|
||||
readonly cause: EffectAcpErrors.AcpError;
|
||||
}
|
||||
|
||||
type HermesAcpModelSelectionRuntime = Pick<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
"setSessionModel"
|
||||
>;
|
||||
|
||||
export function currentHermesModelIdFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): string | undefined {
|
||||
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a model selection to a live Hermes ACP session. Hermes model ids
|
||||
* (e.g. `anthropic:claude-fable-5`) go to `session/set_model` verbatim —
|
||||
* there is no trait suffix to strip and no reasoning metadata to attach.
|
||||
* Nothing is sent when the selection is empty, is the `default` product slug
|
||||
* (which stands for the session's already-configured model, not a real ACP
|
||||
* id), or already matches the session's current model — a redundant
|
||||
* `session/set_model` risks a rejection for ids the agent reports as current
|
||||
* but does not advertise as switchable.
|
||||
*
|
||||
* `session/set_config_option` is not usable here: the real `hermes acp`
|
||||
* binary treats configId `"model"` as a silent no-op (it always returns
|
||||
* `{ configOptions: [] }`, even for invalid values), so model changes must
|
||||
* go through the unstable `session/set_model` capability instead.
|
||||
*/
|
||||
export function applyHermesAcpModelSelection<E>(input: {
|
||||
readonly runtime: HermesAcpModelSelectionRuntime;
|
||||
readonly currentModelId: string | undefined;
|
||||
readonly model: string;
|
||||
readonly mapError: (context: HermesAcpModelSelectionErrorContext) => E;
|
||||
}): Effect.Effect<void, E> {
|
||||
const requestedModelId = input.model.trim();
|
||||
if (
|
||||
requestedModelId.length === 0 ||
|
||||
requestedModelId === HERMES_DEFAULT_MODEL_SLUG ||
|
||||
requestedModelId === input.currentModelId
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return input.runtime.setSessionModel(requestedModelId).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError((cause) => input.mapError({ cause })),
|
||||
);
|
||||
}
|
||||
@@ -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 { AntigravityDriver, type AntigravityDriverEnv } from "./Drivers/AntigravityDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
@@ -38,6 +39,7 @@ export type BuiltInDriversEnv =
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| GrokDriverEnv
|
||||
| HermesDriverEnv
|
||||
| OpenCodeDriverEnv
|
||||
| AntigravityDriverEnv;
|
||||
|
||||
@@ -51,6 +53,7 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
HermesDriver,
|
||||
OpenCodeDriver,
|
||||
AntigravityDriver,
|
||||
];
|
||||
@@ -617,10 +617,11 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
'{"providerInstances":{"cursor_work":{"driver":"cursor","config":{}},"grok":{"driver":"grok","config":{}},"opencode_work":{"driver":"opencode","config":{"serverUrl":"http://127.0.0.1:4096"}},"opencode_unused":{"driver":"opencode","config":{}}}}',
|
||||
'{"providerInstances":{"cursor_work":{"driver":"cursor","config":{}},"grok":{"driver":"grok","config":{}},"hermes":{"driver":"hermes","config":{}},"opencode_work":{"driver":"opencode","config":{"serverUrl":"http://127.0.0.1:4096"}},"opencode_unused":{"driver":"opencode","config":{}}}}',
|
||||
);
|
||||
yield* recordProviderUsage("cursor", "cursor_work");
|
||||
yield* recordProviderUsage("grok", null);
|
||||
yield* recordProviderUsage("hermes", null);
|
||||
yield* recordProviderUsage("opencode", "opencode_work");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
@@ -628,6 +629,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
assert.isTrue(settings.providers.cursor.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor_work")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("hermes")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("opencode_work")]?.enabled);
|
||||
const unused = settings.providerInstances[ProviderInstanceId.make("opencode_unused")];
|
||||
assert.isDefined(unused);
|
||||
@@ -642,18 +644,21 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
'{"providers":{"grok":{"enabled":false},"opencode":{"enabled":false},"cursor":{"enabled":false}},"providerInstances":{"grok":{"driver":"grok","enabled":false,"config":{}},"opencode":{"driver":"opencode","config":{"enabled":false}},"cursor":{"driver":"cursor","enabled":false,"config":{}}}}',
|
||||
'{"providers":{"grok":{"enabled":false},"hermes":{"enabled":false},"opencode":{"enabled":false},"cursor":{"enabled":false}},"providerInstances":{"grok":{"driver":"grok","enabled":false,"config":{}},"hermes":{"driver":"hermes","enabled":false,"config":{}},"opencode":{"driver":"opencode","config":{"enabled":false}},"cursor":{"driver":"cursor","enabled":false,"config":{}}}}',
|
||||
);
|
||||
yield* recordProviderUsage("grok");
|
||||
yield* recordProviderUsage("hermes");
|
||||
yield* recordProviderUsage("opencode");
|
||||
yield* recordProviderUsage("cursor");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
|
||||
assert.isFalse(settings.providers.grok.enabled);
|
||||
assert.isFalse(settings.providers.hermes.enabled);
|
||||
assert.isFalse(settings.providers.opencode.enabled);
|
||||
assert.isFalse(settings.providers.cursor.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("hermes")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("opencode")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("cursor")]?.enabled);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
@@ -705,6 +710,20 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("restores hermes from provider history when no settings file exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* recordProviderUsage("hermes");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
|
||||
assert.isTrue(settings.providers.hermes.enabled);
|
||||
assert.isFalse(settings.providers.grok.enabled);
|
||||
assert.isFalse(settings.providers.opencode.enabled);
|
||||
assert.isFalse(settings.providers.cursor.enabled);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves provider history when the settings file is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
@@ -771,6 +790,27 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("falls back to the Hermes session model when only Hermes is enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
|
||||
const settings = yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: { enabled: false },
|
||||
claudeAgent: { enabled: false },
|
||||
hermes: { enabled: true },
|
||||
},
|
||||
});
|
||||
|
||||
// "default" is Hermes's product slug, not an ACP model id: the adapter
|
||||
// skips session/set_model for it and keeps Hermes's configured model.
|
||||
// Without a DEFAULT_MODEL_BY_PROVIDER entry the fallback would hand
|
||||
// Hermes the Codex text-generation slug, which Hermes rejects.
|
||||
assert.deepEqual(settings.textGenerationModelSelection.instanceId, "hermes");
|
||||
assert.deepEqual(settings.textGenerationModelSelection.model, "default");
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("persists explicit disables after a provider has been used", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
@@ -1043,6 +1083,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
hermes: {
|
||||
enabled: false,
|
||||
},
|
||||
opencode: {
|
||||
enabled: false,
|
||||
serverUrl: "http://127.0.0.1:4096",
|
||||
|
||||
@@ -263,6 +263,7 @@ const PersistedOptionalProviderSettings = Schema.Struct({
|
||||
Schema.Struct({
|
||||
cursor: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
grok: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
hermes: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
opencode: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
}),
|
||||
),
|
||||
@@ -291,6 +292,7 @@ function restoreUsedProviders(
|
||||
instance.enabled === undefined &&
|
||||
(instance.driver === "cursor" ||
|
||||
instance.driver === "grok" ||
|
||||
instance.driver === "hermes" ||
|
||||
instance.driver === "opencode") &&
|
||||
usedProviderInstances.has(instanceId)
|
||||
? { ...instance, enabled: true }
|
||||
@@ -310,6 +312,10 @@ function restoreUsedProviders(
|
||||
...settings.providers.grok,
|
||||
enabled: persisted.providers?.grok?.enabled ?? usedProviders.has("grok"),
|
||||
},
|
||||
hermes: {
|
||||
...settings.providers.hermes,
|
||||
enabled: persisted.providers?.hermes?.enabled ?? usedProviders.has("hermes"),
|
||||
},
|
||||
opencode: {
|
||||
...settings.providers.opencode,
|
||||
enabled: persisted.providers?.opencode?.enabled ?? usedProviders.has("opencode"),
|
||||
@@ -367,6 +373,7 @@ const PERSISTED_SERVER_SETTINGS_DEFAULTS = {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
cursor: { ...DEFAULT_SERVER_SETTINGS.providers.cursor, enabled: undefined },
|
||||
grok: { ...DEFAULT_SERVER_SETTINGS.providers.grok, enabled: undefined },
|
||||
hermes: { ...DEFAULT_SERVER_SETTINGS.providers.hermes, enabled: undefined },
|
||||
opencode: { ...DEFAULT_SERVER_SETTINGS.providers.opencode, enabled: undefined },
|
||||
},
|
||||
};
|
||||
@@ -592,13 +599,13 @@ const make = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId"
|
||||
FROM projection_thread_sessions
|
||||
WHERE provider_name IN ('cursor', 'grok', 'opencode')
|
||||
WHERE provider_name IN ('cursor', 'grok', 'hermes', 'opencode')
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId"
|
||||
FROM provider_session_runtime
|
||||
WHERE provider_name IN ('cursor', 'grok', 'opencode')
|
||||
WHERE provider_name IN ('cursor', 'grok', 'hermes', 'opencode')
|
||||
`.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - the suite builds a real on-disk ACP agent wrapper with Node fs/path/url.
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeURL from "node:url";
|
||||
import * as NodeFS from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import { HermesSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import { makeHermesTextGeneration } from "./HermesTextGeneration.ts";
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
const HermesTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-hermes-text-generation-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
|
||||
const binDir = NodePath.join(dir, "bin");
|
||||
const agentPath = NodePath.join(binDir, "agent");
|
||||
NodeFS.mkdirSync(binDir, { recursive: true });
|
||||
NodeFS.writeFileSync(
|
||||
agentPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||
'if [ "$1" != "acp" ]; then',
|
||||
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||
" exit 11",
|
||||
"fi",
|
||||
`exec node ${JSON.stringify(mockAgentPath)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
NodeFS.chmodSync(agentPath, 0o755);
|
||||
return agentPath;
|
||||
}
|
||||
|
||||
function withFakeAcpAgent<A, E, R>(
|
||||
env: Record<string, string>,
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-acp-"));
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||
const config = decodeHermesSettings({ binaryPath: agentPath });
|
||||
const textGeneration = yield* makeHermesTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
|
||||
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = (yield* Clock.currentTimeMillis) + 5_000;
|
||||
for (;;) {
|
||||
const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8")));
|
||||
if (Exit.isSuccess(result)) {
|
||||
return result.value;
|
||||
}
|
||||
{
|
||||
if ((yield* Clock.currentTimeMillis) >= deadline) {
|
||||
return yield* Effect.die(result.cause);
|
||||
}
|
||||
}
|
||||
yield* Effect.sleep(25);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(HermesTextGenerationTestLayer)("HermesTextGeneration", (it) => {
|
||||
it.effect("forwards the requested model id to the ACP session verbatim", () => {
|
||||
const requestLogDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-log-"),
|
||||
);
|
||||
const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Add generated commit message",
|
||||
body: "- verify hermes acp model selection path",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-text-generation",
|
||||
stagedSummary: "M apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/HermesTextGeneration.ts b/apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
// The shared acp-mock-agent only allowlists grok-* ids for
|
||||
// session/set_model, so Hermes tests reuse them.
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("hermes"),
|
||||
"grok-mock-alt",
|
||||
),
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add generated commit message");
|
||||
expect(generated.body).toBe("- verify hermes acp model selection path");
|
||||
|
||||
const requests = NodeFS.readFileSync(requestLogPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map(
|
||||
(line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> },
|
||||
);
|
||||
|
||||
expect(
|
||||
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||
).toMatchObject({
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_model" &&
|
||||
request.params?.modelId === "grok-mock-alt",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Staged patch:"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
NodeFS.rmSync(requestLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts json objects with extra assistant text around them", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-noisy-json",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
|
||||
expect(generated.body).toBe("");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through Hermes ACP text generation", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
title: '"Trim reconnect spinner status after resume."',
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix the reconnect spinner after a resumed session.",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process after text generation completes", () => {
|
||||
const exitLogDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-exit-log-"),
|
||||
);
|
||||
const exitLogPath = NodePath.join(exitLogDir, "exit.log");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Close runtime after generation",
|
||||
body: "",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-runtime-close",
|
||||
stagedSummary: "M apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/HermesTextGeneration.ts b/apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Close runtime after generation");
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("exit:0");
|
||||
|
||||
NodeFS.rmSync(exitLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { type HermesSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { extractJsonObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
applyHermesAcpModelSelection,
|
||||
currentHermesModelIdFromSessionSetup,
|
||||
makeHermesAcpRuntime,
|
||||
} from "../provider/acp/HermesAcpSupport.ts";
|
||||
|
||||
const HERMES_TIMEOUT_MS = 180_000;
|
||||
|
||||
const isTextGenerationError = Schema.is(TextGenerationError);
|
||||
|
||||
/**
|
||||
* Build a Hermes text-generation closure bound to a specific `HermesSettings`
|
||||
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
|
||||
*/
|
||||
export const makeHermesTextGeneration = Effect.fn("makeHermesTextGeneration")(function* (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
|
||||
const runHermesJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const outputRef = yield* Ref.make("");
|
||||
const runtime = yield* makeHermesAcpRuntime({
|
||||
hermesSettings,
|
||||
environment: resolvedEnvironment,
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "agent_message_chunk") {
|
||||
return Effect.void;
|
||||
}
|
||||
const content = update.content;
|
||||
if (content.type !== "text") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.update(outputRef, (current) => current + content.text);
|
||||
});
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
const started = yield* runtime.start();
|
||||
yield* Effect.ignore(runtime.setMode("ask"));
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: currentHermesModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
model: modelSelection.model,
|
||||
mapError: ({ cause }) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to set Hermes ACP model for text generation.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: prompt }],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeoutOption(HERMES_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes Agent request timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes ACP request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const rawResult = (yield* Ref.get(outputRef)).trim();
|
||||
if (!rawResult) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
promptResult.stopReason === "cancelled"
|
||||
? "Hermes ACP request was cancelled."
|
||||
: "Hermes Agent returned empty output.",
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes ACP text generation failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
|
||||
Effect.fn("HermesTextGeneration.generateCommitMessage")(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
|
||||
Effect.fn("HermesTextGeneration.generatePrContent")(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
|
||||
Effect.fn("HermesTextGeneration.generateBranchName")(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
|
||||
Effect.fn("HermesTextGeneration.generateThreadTitle")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
previousTitle: input.previousTitle,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -709,6 +709,25 @@ export const AntigravityIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const HermesIcon: Icon = (props) => (
|
||||
<svg
|
||||
{...props}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 3v18" />
|
||||
<path d="M8.5 5.5C6 3.5 3.5 4 2 6c2.8-.2 4.8.7 6 2.5" />
|
||||
<path d="M15.5 5.5C18 3.5 20.5 4 22 6c-2.8-.2-4.8.7-6 2.5" />
|
||||
<path d="M8 9.5c0 2 1.7 2.5 4 3.5 2.3 1 4 1.5 4 3.5S14.3 19 12 20" />
|
||||
<path d="M16 9.5c0 2-1.7 2.5-4 3.5-2.3 1-4 1.5-4 3.5S9.7 19 12 20" />
|
||||
<path d="M10 3h4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const OpenCodeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clipPath="url(#opencode__clip0_1311_94969)">
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ClaudeAI,
|
||||
CursorIcon,
|
||||
GrokIcon,
|
||||
HermesIcon,
|
||||
Icon,
|
||||
OpenAI,
|
||||
OpenCodeIcon,
|
||||
@@ -15,6 +16,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,
|
||||
[ProviderDriverKind.make("antigravity")]: AntigravityIcon,
|
||||
};
|
||||
|
||||
|
||||
@@ -70,6 +70,13 @@ describe("ProviderSettingsForm helpers", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers Hermes with its ACP binary setting", () => {
|
||||
const hermes = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("hermes")];
|
||||
expect(hermes).toBeDefined();
|
||||
expect(hermes?.badgeLabel).toBe("Experimental");
|
||||
expect(deriveProviderSettingsFields(hermes!).map((field) => field.key)).toEqual(["binaryPath"]);
|
||||
});
|
||||
|
||||
it("preserves unknown config keys while omitting empty configurable fields", () => {
|
||||
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
|
||||
expect(opencode).toBeDefined();
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CodexSettings,
|
||||
CursorSettings,
|
||||
GrokSettings,
|
||||
HermesSettings,
|
||||
OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
ClaudeAI,
|
||||
CursorIcon,
|
||||
GrokIcon,
|
||||
HermesIcon,
|
||||
type Icon,
|
||||
OpenAI,
|
||||
OpenCodeIcon,
|
||||
@@ -70,6 +72,13 @@ const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] = [
|
||||
badgeLabel: "Early Access",
|
||||
settingsSchema: GrokSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("hermes"),
|
||||
label: "Hermes",
|
||||
icon: HermesIcon,
|
||||
badgeLabel: "Experimental",
|
||||
settingsSchema: HermesSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("opencode"),
|
||||
label: "OpenCode",
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@
|
||||
- [Remote access](./user/remote-access.md)
|
||||
- [Running in the background](./user/background-service.md)
|
||||
- [Updating T3 Code](./user/updating.md)
|
||||
- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md)
|
||||
- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [Hermes](./user/providers-hermes.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+11
-8
@@ -73,19 +73,22 @@ and enable the provider you want. Installation, login, and configuration belong
|
||||
to that environment's machine, even when you connect from a phone or another
|
||||
computer.
|
||||
|
||||
| Provider | Install and authenticate |
|
||||
| ----------- | -------------------------------------------------------------------------------------------- |
|
||||
| Codex | Install [Codex CLI](https://developers.openai.com/codex/cli), then run `codex login`. |
|
||||
| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. |
|
||||
| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. |
|
||||
| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. |
|
||||
| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. |
|
||||
| Antigravity | Install and sign in with Google from T3 Code's provider settings. |
|
||||
| Provider | Install and authenticate |
|
||||
| ----------- | ---------------------------------------------------------------------------------------------- |
|
||||
| Codex | Install [Codex CLI](https://developers.openai.com/codex/cli), then run `codex login`. |
|
||||
| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. |
|
||||
| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. |
|
||||
| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. |
|
||||
| Hermes | Install [Hermes Agent](https://github.com/NousResearch/hermes-agent), then run `hermes setup`. |
|
||||
| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. |
|
||||
| Antigravity | Install and sign in with Google from T3 Code's provider settings. |
|
||||
|
||||
Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its
|
||||
**Binary path** in provider settings, especially when using a version manager.
|
||||
Cursor's executable is `cursor-agent`, although its login command is
|
||||
`agent login`. Antigravity can use its managed runtime without a `PATH` entry.
|
||||
Hermes is experimental — its provider card shows an **Experimental** badge; see
|
||||
[Hermes](./providers-hermes.md) for details.
|
||||
|
||||
When a provider CLI is behind its latest release, its provider card shows the
|
||||
available version. **Update now** appears only when T3 Code can tell which
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Hermes
|
||||
|
||||
[Hermes Agent](https://github.com/NousResearch/hermes-agent) is a coding agent CLI. T3 Code can
|
||||
drive it like any other provider, giving it the same chat, tool-approval, and checkpoint
|
||||
experience as Codex, Claude, Cursor, Grok Build, and OpenCode.
|
||||
|
||||
Hermes support is experimental. The provider card in **Settings** shows an **Experimental** badge.
|
||||
|
||||
## Requirements
|
||||
|
||||
Hermes Agent must be installed and configured on the machine running the T3 Code server, not on
|
||||
the device you browse from:
|
||||
|
||||
```bash
|
||||
hermes setup
|
||||
```
|
||||
|
||||
T3 Code spawns `hermes acp` and expects Hermes to already know which model providers to use. It
|
||||
does not configure Hermes on your behalf.
|
||||
|
||||
## Enable Hermes
|
||||
|
||||
Hermes is off by default. Turn it on in **Settings** → **Providers** → **Hermes**.
|
||||
|
||||
The only setting is **Binary path**, which defaults to `hermes`. Set it when a version manager or
|
||||
a non-standard install location keeps the CLI off the `PATH` of the shell that started T3 Code.
|
||||
|
||||
To use more than one Hermes installation or profile on the same environment, choose **Add provider
|
||||
instance**, select **Hermes**, and give the instance a name. Each instance can use its own binary
|
||||
path and environment variables; set `HERMES_HOME` there when the instances should use separate
|
||||
Hermes profiles.
|
||||
|
||||
## Models
|
||||
|
||||
Hermes has no model list of its own in T3 Code. T3 Code asks Hermes for the catalog it advertises
|
||||
when a session starts — whatever providers you configured through `hermes setup` or `hermes
|
||||
model`. Pick a model from that list in the model picker for each thread, the same as with any
|
||||
other provider.
|
||||
|
||||
## What works
|
||||
|
||||
- Chat, including tool calls and file edits
|
||||
- Tool approvals through T3 Code's normal permission prompts
|
||||
- Resuming an existing thread
|
||||
- Generated thread titles, commit messages, PR titles and descriptions, and branch names
|
||||
|
||||
## Limits
|
||||
|
||||
- Experimental: expect rougher edges than the other providers.
|
||||
- Local binary only. T3 Code spawns `hermes acp` as a subprocess; it does not support a remote
|
||||
Hermes endpoint.
|
||||
- Hermes Agent must be installed and configured on the machine running the T3 Code server. A
|
||||
client connecting from a phone or another desktop does not need it installed locally.
|
||||
@@ -147,6 +147,7 @@ const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const HERMES_DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-6-astra";
|
||||
@@ -172,6 +173,9 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
[CURSOR_DRIVER_KIND]: "auto",
|
||||
// Product slug, not an ACP model id. The Grok adapter treats it as "the session's current model".
|
||||
[GROK_DRIVER_KIND]: "grok-build",
|
||||
// Product slug, not an ACP model id. The Hermes adapter treats it as "keep the
|
||||
// model Hermes is configured with" and skips session/set_model for it.
|
||||
[HERMES_DRIVER_KIND]: "default",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
[ProviderDriverKind.make("antigravity")]: ANTIGRAVITY_DEFAULT_MODEL,
|
||||
};
|
||||
@@ -184,6 +188,7 @@ export const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
[ProviderDriverKind.make("antigravity")]: ANTIGRAVITY_DEFAULT_MODEL,
|
||||
[CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",
|
||||
[CURSOR_DRIVER_KIND]: "composer-2",
|
||||
[HERMES_DRIVER_KIND]: "default",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
};
|
||||
|
||||
@@ -221,5 +226,6 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
|
||||
[CLAUDE_DRIVER_KIND]: "Claude",
|
||||
[CURSOR_DRIVER_KIND]: "Cursor",
|
||||
[GROK_DRIVER_KIND]: "Grok",
|
||||
[HERMES_DRIVER_KIND]: "Hermes",
|
||||
[OPENCODE_DRIVER_KIND]: "OpenCode",
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ClientSettingsPatch,
|
||||
ClaudeSettings,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
HermesSettings,
|
||||
resolveProviderInstanceEnabled,
|
||||
ServerSettings,
|
||||
ServerSettingsPatch,
|
||||
@@ -19,6 +20,7 @@ const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
|
||||
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
|
||||
const decodeHermesSettings = Schema.decodeUnknownSync(HermesSettings);
|
||||
|
||||
describe("ServerSettings default permissions", () => {
|
||||
it("keeps full access for settings saved before a default was configured", () => {
|
||||
@@ -665,6 +667,7 @@ describe("provider enabled defaults", () => {
|
||||
expect(decoded.providers.claudeAgent.enabled).toBe(true);
|
||||
expect(decoded.providers.cursor.enabled).toBe(false);
|
||||
expect(decoded.providers.grok.enabled).toBe(false);
|
||||
expect(decoded.providers.hermes.enabled).toBe(false);
|
||||
expect(decoded.providers.opencode.enabled).toBe(false);
|
||||
});
|
||||
|
||||
@@ -840,6 +843,20 @@ describe("ServerSettingsPatch string normalization", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("HermesSettings", () => {
|
||||
it("decodes defaults", () => {
|
||||
const decoded = decodeHermesSettings({});
|
||||
expect(decoded.enabled).toBe(false);
|
||||
expect(decoded.binaryPath).toBe("hermes");
|
||||
expect(decoded.customModels).toEqual([]);
|
||||
});
|
||||
|
||||
it("is reachable via ServerSettings defaults", () => {
|
||||
const settings = decodeServerSettings({});
|
||||
expect(settings.providers.hermes.binaryPath).toBe("hermes");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettings environment icon", () => {
|
||||
it("defaults to null", () => {
|
||||
expect(decodeServerSettings({}).environmentIcon).toBeNull();
|
||||
|
||||
@@ -813,6 +813,32 @@ export const AntigravitySettings = makeProviderSettingsSchema(
|
||||
);
|
||||
export type AntigravitySettings = typeof AntigravitySettings.Type;
|
||||
|
||||
export const HermesSettings = makeProviderSettingsSchema(
|
||||
{
|
||||
// Off by default (like Cursor, Grok, and OpenCode): the binding is not
|
||||
// yet stable enough to probe on every install. Users opt in from Settings.
|
||||
enabled: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(false)),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
binaryPath: makeBinaryPathSetting("hermes").pipe(
|
||||
Schema.annotateKey({
|
||||
title: "Binary path",
|
||||
description: "Path to the Hermes Agent binary.",
|
||||
providerSettingsForm: { placeholder: "hermes", clearWhenEmpty: "omit" },
|
||||
}),
|
||||
),
|
||||
customModels: Schema.Array(CustomModelSetting).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed([])),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
},
|
||||
{
|
||||
order: ["binaryPath"],
|
||||
},
|
||||
);
|
||||
export type HermesSettings = typeof HermesSettings.Type;
|
||||
|
||||
export const OpenCodeSettings = makeProviderSettingsSchema(
|
||||
{
|
||||
// Off by default (like Cursor and Grok): the binding is not yet stable
|
||||
@@ -1160,6 +1186,7 @@ export const ServerSettings = Schema.Struct({
|
||||
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
hermes: HermesSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
antigravity: AntigravitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
@@ -1327,6 +1354,12 @@ const AntigravitySettingsPatch = Schema.Struct({
|
||||
customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
|
||||
});
|
||||
|
||||
const HermesSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
binaryPath: Schema.optionalKey(TrimmedString),
|
||||
customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
|
||||
});
|
||||
|
||||
const OpenCodeSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
binaryPath: Schema.optionalKey(TrimmedString),
|
||||
@@ -1407,6 +1440,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
|
||||
cursor: Schema.optionalKey(CursorSettingsPatch),
|
||||
grok: Schema.optionalKey(GrokSettingsPatch),
|
||||
hermes: Schema.optionalKey(HermesSettingsPatch),
|
||||
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
|
||||
antigravity: Schema.optionalKey(AntigravitySettingsPatch),
|
||||
}),
|
||||
|
||||
Reference in new issue
Block a user