diff --git a/apps/server/src/provider/Drivers/HermesDriver.ts b/apps/server/src/provider/Drivers/HermesDriver.ts index 33877534e0..7aea7d12cf 100644 --- a/apps/server/src/provider/Drivers/HermesDriver.ts +++ b/apps/server/src/provider/Drivers/HermesDriver.ts @@ -11,7 +11,7 @@ * * @module provider/Drivers/HermesDriver */ -import { HermesSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; +import { HermesSettings, ProviderDriverKind } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -25,6 +25,7 @@ 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, @@ -38,7 +39,6 @@ import { type ProviderDriver, type ProviderInstance, } from "../ProviderDriver.ts"; -import type { ServerProviderDraft } from "../providerSnapshot.ts"; import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; import { makeManualOnlyProviderMaintenanceCapabilities, @@ -73,22 +73,6 @@ export type HermesDriverEnv = | ServerConfig | ServerSettingsService; -const withInstanceIdentity = - (input: { - readonly instanceId: ProviderInstance["instanceId"]; - readonly displayName: string | undefined; - readonly accentColor: string | undefined; - readonly continuationGroupKey: string; - }) => - (snapshot: ServerProviderDraft): ServerProvider => ({ - ...snapshot, - instanceId: input.instanceId, - driver: DRIVER_KIND, - ...(input.displayName ? { displayName: input.displayName } : {}), - ...(input.accentColor ? { accentColor: input.accentColor } : {}), - continuation: { groupKey: input.continuationGroupKey }, - }); - export const HermesDriver: ProviderDriver = { driverKind: DRIVER_KIND, metadata: { @@ -111,6 +95,7 @@ export const HermesDriver: ProviderDriver = { }); const stampIdentity = withInstanceIdentity({ instanceId, + driverKind: DRIVER_KIND, displayName, accentColor, continuationGroupKey: continuationIdentity.continuationKey, diff --git a/apps/server/src/provider/Layers/HermesAdapter.test.ts b/apps/server/src/provider/Layers/HermesAdapter.test.ts new file mode 100644 index 0000000000..8a759cd4cf --- /dev/null +++ b/apps/server/src/provider/Layers/HermesAdapter.test.ts @@ -0,0 +1,259 @@ +// @effect-diagnostics nodeBuiltinImport:off +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, +} 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) { + 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[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("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"); +}); + +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("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(); + 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("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(); + 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); + }), + ); +}); diff --git a/apps/server/src/provider/Layers/HermesAdapter.ts b/apps/server/src/provider/Layers/HermesAdapter.ts index 82ddc27c7e..f61405afd0 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.ts @@ -67,6 +67,7 @@ import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts"; import { applyHermesAcpModelSelection, currentHermesModelIdFromSessionSetup, + HERMES_DEFAULT_MODEL_SLUG, makeHermesAcpRuntime, } from "../acp/HermesAcpSupport.ts"; import { type HermesAdapterShape } from "../Services/HermesAdapter.ts"; @@ -212,7 +213,7 @@ function isPlanMode(mode: AcpSessionMode): boolean { return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined; } -function resolveRequestedModeId(input: { +export function resolveRequestedModeId(input: { readonly interactionMode: ProviderInteractionMode | undefined; readonly runtimeMode: RuntimeMode; readonly modeState: AcpSessionModeState | undefined; @@ -288,7 +289,7 @@ function applyRequestedSessionConfiguration(input: { }); } -function selectAutoApprovedPermissionOption( +export function selectAutoApprovedPermissionOption( request: EffectAcpSchema.RequestPermissionRequest, ): string | undefined { const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always"); @@ -644,13 +645,27 @@ export function makeHermesAdapter( }); const now = yield* nowIso; + // Track the session's real current model, not just the picker + // selection: after configuration the session is on the requested + // model when one switched, otherwise on the ACP setup's current + // model. The `default` product slug is not a real id, so it falls + // through to the discovered current. This baseline is what the + // per-turn skip-if-match guard compares against. + const startCurrentModelId = currentHermesModelIdFromSessionSetup( + started.sessionSetupResult, + ); + const requestedStartModel = hermesModelSelection?.model; + const effectiveStartModel = + requestedStartModel && requestedStartModel !== HERMES_DEFAULT_MODEL_SLUG + ? requestedStartModel + : startCurrentModelId; const session: ProviderSession = { provider: PROVIDER, providerInstanceId: boundInstanceId, status: "ready", runtimeMode: input.runtimeMode, cwd, - model: hermesModelSelection?.model, + model: effectiveStartModel, threadId: input.threadId, resumeCursor: { schemaVersion: HERMES_RESUME_VERSION, @@ -795,13 +810,24 @@ export function makeHermesAdapter( const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4); // Count this prompt immediately so a superseded in-flight prompt // resolving from here on does not settle the turn; the matching - // decrement is the `ensuring` below. + // decrement is the `ensuring` below. The active turn id must land in + // the same synchronous window: a concurrent sendTurn arriving during + // the awaited session configuration below reads it to merge into this + // turn instead of opening a duplicate. ctx.promptsInFlight += 1; + ctx.activeTurnId = turnId; return yield* Effect.gen(function* () { const turnModelSelection = input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; - const model = turnModelSelection?.model ?? ctx.session.model; + // The `default` product slug means "keep the configured model", so + // it resolves to the session's tracked model rather than being sent + // or stored as if it were a real ACP model id. + const requestedTurnModel = + turnModelSelection?.model && turnModelSelection.model !== HERMES_DEFAULT_MODEL_SLUG + ? turnModelSelection.model + : undefined; + const model = requestedTurnModel ?? ctx.session.model; yield* applyRequestedSessionConfiguration({ runtime: ctx.acp, runtimeMode: ctx.session.runtimeMode, @@ -811,7 +837,6 @@ export function makeHermesAdapter( mapError: ({ cause, method }) => mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), }); - ctx.activeTurnId = turnId; if (steeringTurnId === undefined) { ctx.lastPlanFingerprint = undefined; } diff --git a/apps/server/src/provider/Layers/HermesProvider.ts b/apps/server/src/provider/Layers/HermesProvider.ts index 2801bc4116..29be7cbacf 100644 --- a/apps/server/src/provider/Layers/HermesProvider.ts +++ b/apps/server/src/provider/Layers/HermesProvider.ts @@ -33,7 +33,7 @@ import { enrichProviderSnapshotWithVersionAdvisory, type ProviderMaintenanceCapabilities, } from "../providerMaintenance.ts"; -import { makeHermesAcpRuntime } from "../acp/HermesAcpSupport.ts"; +import { HERMES_DEFAULT_MODEL_SLUG, makeHermesAcpRuntime } from "../acp/HermesAcpSupport.ts"; const HERMES_PRESENTATION = { displayName: "Hermes", @@ -54,9 +54,10 @@ const HERMES_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [ const HERMES_BUILT_IN_MODELS: ReadonlyArray = [ { - slug: "default", + slug: HERMES_DEFAULT_MODEL_SLUG, name: "Hermes (configured default)", isCustom: false, + isDefault: true, capabilities: EMPTY_CAPABILITIES, }, ]; @@ -106,6 +107,11 @@ function buildHermesDiscoveredModelsFromSessionModelState( 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(); return modelState.availableModels.flatMap((model) => { const slug = model.modelId.trim(); @@ -118,6 +124,7 @@ function buildHermesDiscoveredModelsFromSessionModelState( slug, name: model.name.trim() || slug, isCustom: false, + ...(slug === currentModelId ? { isDefault: true } : {}), capabilities: EMPTY_CAPABILITIES, } satisfies ServerProviderModel, ]; diff --git a/apps/server/src/provider/acp/HermesAcpSupport.test.ts b/apps/server/src/provider/acp/HermesAcpSupport.test.ts index 58e1fa7234..ce2389933b 100644 --- a/apps/server/src/provider/acp/HermesAcpSupport.test.ts +++ b/apps/server/src/provider/acp/HermesAcpSupport.test.ts @@ -63,6 +63,28 @@ describe("applyHermesAcpModelSelection", () => { }), ); + it.effect("never sends the default product slug as an ACP model id", () => + Effect.gen(function* () { + const modelCalls: Array = []; + 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 = []; diff --git a/apps/server/src/provider/acp/HermesAcpSupport.ts b/apps/server/src/provider/acp/HermesAcpSupport.ts index 6c8d65cdfe..54087c99c6 100644 --- a/apps/server/src/provider/acp/HermesAcpSupport.ts +++ b/apps/server/src/provider/acp/HermesAcpSupport.ts @@ -12,6 +12,13 @@ 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; interface HermesAcpRuntimeInput extends Omit< @@ -82,10 +89,11 @@ export function currentHermesModelIdFromSessionSetup( * 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. - * A selection matching the session's current model sends nothing: the - * session is already there, and a redundant `session/set_model` risks a - * rejection for ids the agent reports as current but does not advertise - * as switchable. + * 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 @@ -99,7 +107,11 @@ export function applyHermesAcpModelSelection(input: { readonly mapError: (context: HermesAcpModelSelectionErrorContext) => E; }): Effect.Effect { const requestedModelId = input.model.trim(); - if (requestedModelId.length === 0 || requestedModelId === input.currentModelId) { + if ( + requestedModelId.length === 0 || + requestedModelId === HERMES_DEFAULT_MODEL_SLUG || + requestedModelId === input.currentModelId + ) { return Effect.void; } return input.runtime.setSessionModel(requestedModelId).pipe(