Skip to content
TypeScript

fix(acp): discover and select models from session model state (#19519)

Wout Stiens9cbc2c0049a7
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index ce997f64828..92bb99e4de1 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -15,16 +15,11 @@ import { assert, describe, it } from "@effect/vitest";
import {
CheckpointId,
EnvironmentId,
- MessageId,
type ModelSelection,
- NodeId,
- ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
- RunAttemptId,
- RunId,
ThreadId,
type OrchestrationV2ProviderThread,
type ProviderOptionDescriptor,
@@ -73,6 +68,7 @@ import {
} from "@t3tools/provider-grok/testing";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
+import { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
AcpProviderCapabilitiesV2,
@@ -540,69 +536,6 @@ const pollProtocolMethods = (events: Queue.Queue<EffectAcpProtocol.AcpProtocolLo
return methods;
});
-function makeTurnInput(input: {
- readonly threadId: ThreadId;
- readonly providerThread: OrchestrationV2ProviderThread;
- readonly instanceId: ProviderInstanceId;
- readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
- readonly now: DateTime.Utc;
- readonly ordinal?: number;
- readonly modelSelection?: ModelSelection;
- readonly messageCreatedBy?: "user" | "agent";
- readonly messageCreationSource?: "web" | "mobile" | "mcp" | "provider" | "server";
- readonly messageText?: string;
-}): ProviderAdapter.ProviderAdapterV2TurnInput {
- const ordinal = input.ordinal ?? 1;
- const suffix = `${input.threadId}:${ordinal}`;
- const modelSelection =
- input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const);
- return {
- appThread: {
- createdBy: "user",
- creationSource: "web",
- id: input.threadId,
- projectId: ProjectId.make(`project:${input.threadId}`),
- title: "ACP adapter test",
- providerInstanceId: input.instanceId,
- modelSelection,
- runtimeMode: "approval-required",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- activeProviderThreadId: input.providerThread.id,
- lineage: {
- parentThreadId: null,
- relationshipToParent: null,
- rootThreadId: input.threadId,
- },
- forkedFrom: null,
- createdAt: input.now,
- updatedAt: input.now,
- archivedAt: null,
- settledOverride: null,
- settledAt: null,
- lastVisitedAt: null,
- deletedAt: null,
- },
- threadId: input.threadId,
- runId: RunId.make(`run:${suffix}`),
- runOrdinal: ordinal,
- providerTurnOrdinal: ordinal,
- attemptId: RunAttemptId.make(`attempt:${suffix}`),
- rootNodeId: NodeId.make(`node:${suffix}`),
- providerThread: input.providerThread,
- message: {
- createdBy: input.messageCreatedBy ?? "user",
- creationSource: input.messageCreationSource ?? "web",
- messageId: MessageId.make(`message:${suffix}`),
- text: input.messageText ?? "test prompt",
- attachments: [],
- },
- modelSelection,
- runtimePolicy: input.runtimePolicy,
- };
-}
-
describe("AcpAdapterV2", () => {
it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
"projects Mistral retry notices and their %s outcome",
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts
index 421cc959245..6f8333dd27f 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts
@@ -1,8 +1,19 @@
import {
+ MessageId,
+ type ModelSelection,
+ NodeId,
+ ProjectId,
+ type ProviderInstanceId,
+ RunAttemptId,
+ RunId,
+ type OrchestrationV2ProviderThread,
+ type ThreadId,
ProviderDriverKind,
ProviderReplayEntry,
type ProviderReplayTranscript,
} from "@t3tools/contracts";
+import type * as DateTime from "effect/DateTime";
+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
@@ -181,6 +192,7 @@ export function makeAcpReplayRuntime(input: {
readonly scriptPath: string;
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly fileSystem: FileSystem.FileSystem;
+ readonly customModels?: AcpSessionRuntime.AcpSessionRuntimeOptions["customModels"];
readonly cancelMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelMeta"];
readonly initializeMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["initializeMeta"];
readonly replayGate?: ProviderReplayGate;
@@ -222,6 +234,7 @@ export function makeAcpReplayRuntime(input: {
},
},
authMethodId: "replay",
+ ...(input.customModels === undefined ? {} : { customModels: input.customModels }),
...(input.cancelMeta === undefined ? {} : { cancelMeta: input.cancelMeta }),
...(input.initializeMeta === undefined ? {} : { initializeMeta: input.initializeMeta }),
...(input.replayGate === undefined
@@ -238,3 +251,66 @@ export function makeAcpReplayRuntime(input: {
);
});
}
+
+export function makeTurnInput(input: {
+ readonly threadId: ThreadId;
+ readonly providerThread: OrchestrationV2ProviderThread;
+ readonly instanceId: ProviderInstanceId;
+ readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
+ readonly now: DateTime.Utc;
+ readonly ordinal?: number;
+ readonly modelSelection?: ModelSelection;
+ readonly messageCreatedBy?: "user" | "agent";
+ readonly messageCreationSource?: "web" | "mobile" | "mcp" | "provider" | "server";
+ readonly messageText?: string;
+}): ProviderAdapter.ProviderAdapterV2TurnInput {
+ const ordinal = input.ordinal ?? 1;
+ const suffix = `${input.threadId}:${ordinal}`;
+ const modelSelection =
+ input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const);
+ return {
+ appThread: {
+ createdBy: "user",
+ creationSource: "web",
+ id: input.threadId,
+ projectId: ProjectId.make(`project:${input.threadId}`),
+ title: "ACP adapter test",
+ providerInstanceId: input.instanceId,
+ modelSelection,
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: input.providerThread.id,
+ lineage: {
+ parentThreadId: null,
+ relationshipToParent: null,
+ rootThreadId: input.threadId,
+ },
+ forkedFrom: null,
+ createdAt: input.now,
+ updatedAt: input.now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ threadId: input.threadId,
+ runId: RunId.make(`run:${suffix}`),
+ runOrdinal: ordinal,
+ providerTurnOrdinal: ordinal,
+ attemptId: RunAttemptId.make(`attempt:${suffix}`),
+ rootNodeId: NodeId.make(`node:${suffix}`),
+ providerThread: input.providerThread,
+ message: {
+ createdBy: input.messageCreatedBy ?? "user",
+ creationSource: input.messageCreationSource ?? "web",
+ messageId: MessageId.make(`message:${suffix}`),
+ text: input.messageText ?? "test prompt",
+ attachments: [],
+ },
+ modelSelection,
+ runtimePolicy: input.runtimePolicy,
+ };
+}
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
index 6b27625e1e6..fb931519d9e 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
@@ -1,11 +1,16 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
-import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
+import {
+ type ModelSelection,
+ ProviderInstanceId,
+ ProviderSessionId,
+ ThreadId,
+} from "@t3tools/contracts";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
-import * as Cause from "effect/Cause";
+import * as DateTime from "effect/DateTime";
+import * as Stream from "effect/Stream";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
-import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -33,6 +38,7 @@ import {
decodeAcpReplayTranscript,
makeAcpReplayCompletenessAssertion,
makeAcpReplayRuntime,
+ makeTurnInput,
} from "./AcpAdapterV2.testkit.ts";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts";
@@ -143,7 +149,7 @@ describe("AcpRegistryAdapterV2", () => {
});
});
- describe("applying a stored selection to a scripted agent", () => {
+ describe("the agent's own pickers", () => {
type Frame = Record<string, unknown>;
const outbound = (method: string, params: unknown = "<any>"): Frame => ({
type: "expect_outbound",
@@ -153,8 +159,6 @@ describe("AcpRegistryAdapterV2", () => {
type: "emit_inbound",
frame: { kind: "response", method, result },
});
- const assertOpened = (opened: Exit.Exit<void, unknown>) =>
- assert.isTrue(Exit.isSuccess(opened));
const permissionModeOption = (currentValue: string) => ({
id: "permission-mode",
name: "Permission mode",
@@ -164,17 +168,19 @@ describe("AcpRegistryAdapterV2", () => {
options: ["ask", "auto"].map((value) => ({ value, name: value })),
});
- const openWithStoredSelection = Effect.fn("openWithStoredSelection")(function* (input: {
+ const openWithStoredPicks = Effect.fn("openWithStoredPicks")(function* (input: {
readonly setup: unknown;
- readonly selectionFrames: ReadonlyArray<Frame>;
- readonly model?: string;
+ readonly pickFrames: ReadonlyArray<Frame>;
+ readonly customModels?: ReadonlyArray<string>;
+ readonly storedModel?: string;
readonly storedModePick?: string;
+ readonly turnModels?: ReadonlyArray<string>;
}) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const replayDir = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-acp-registry-mode-pick-",
+ prefix: "t3-acp-registry-stored-picks-",
});
const statusPath = path.join(replayDir, "status.json");
const transcript = yield* decodeAcpReplayTranscript(
@@ -182,7 +188,7 @@ describe("AcpRegistryAdapterV2", () => {
provider: ACP_REGISTRY_PROVIDER,
protocol: "acp.ndjson-jsonrpc",
version: "1",
- scenario: "stored-mode-pick",
+ scenario: "stored-picks",
entries: [
outbound("initialize"),
answer("initialize", {
@@ -192,21 +198,24 @@ describe("AcpRegistryAdapterV2", () => {
}),
outbound("session/new"),
answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }),
- ...input.selectionFrames,
+ ...input.pickFrames,
] as never,
},
ACP_REGISTRY_PROVIDER,
);
- const instanceId = ProviderInstanceId.make("acp-registry-mode-pick");
+ const instanceId = ProviderInstanceId.make("acp-registry-stored-picks");
+ let published: AcpRegistryLiveConfiguration | undefined;
const adapter = yield* makeAcpRegistryAdapterV2({
selfInvocation: yield* resolveSelfInvocation(),
instanceId,
settings: yield* decodeAcpRegistryAdapterSettings({
agentId: "fixture-agent",
authMethodId: "test",
+ customModels: input.customModels ?? [],
}),
environment: {},
makeRuntime: makeAcpReplayRuntime({
+ customModels: input.customModels,
transcript,
statusPath,
scriptPath: yield* path.fromFileUrl(
@@ -215,49 +224,107 @@ describe("AcpRegistryAdapterV2", () => {
childProcessSpawner,
fileSystem,
}),
- }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
- const opened = yield* adapter
- .openSession({
- threadId: ThreadId.make("thread-acp-registry-mode-pick"),
- providerSessionId: ProviderSessionId.make("provider-session-mode-pick"),
- modelSelection: {
- instanceId,
- model: input.model ?? "default",
- ...(input.storedModePick === undefined
- ? {}
- : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
- },
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
- interactionMode: "default",
- cwd: replayDir,
- }),
- })
- .pipe(Effect.asVoid, Effect.scoped, Effect.exit);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ layerInjectedRuntimeCatalog,
+ Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({
+ withForegroundStartup: (_startupKey, effect) => effect,
+ publishLiveConfiguration: (_instanceId, configuration) =>
+ Effect.sync(() => {
+ published = configuration;
+ }),
+ }),
+ ),
+ ),
+ );
+ const threadId = ThreadId.make("thread-acp-registry-stored-picks");
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: replayDir,
+ });
+ const stored: ModelSelection = {
+ instanceId,
+ model: input.storedModel ?? "default",
+ ...(input.storedModePick === undefined
+ ? {}
+ : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
+ };
+ const configurations: Array<AcpRegistryLiveConfiguration | undefined> = [];
+ yield* Effect.gen(function* () {
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-stored-picks"),
+ modelSelection: stored,
+ runtimePolicy,
+ });
+ configurations.push(published);
+ if (input.turnModels === undefined) return;
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection: stored,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ let current = stored;
+ for (const [index, model] of input.turnModels.entries()) {
+ const target: ModelSelection = { instanceId, model };
+ const plan = yield* adapter.planSelectionTransition({
+ current,
+ target,
+ sessionCapabilities: runtime.providerSession.capabilities,
+ });
+ assert.equal(plan.type, "apply_on_next_turn");
+ yield* runtime.startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now,
+ ordinal: index + 1,
+ modelSelection: target,
+ }),
+ );
+ yield* runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runForEach((event) =>
+ Effect.sync(() => {
+ if (event.type === "turn.terminal") {
+ assert.equal(event.status, "completed", event.failure?.message);
+ }
+ }),
+ ),
+ );
+ configurations.push(published);
+ current = target;
+ }
+ }).pipe(Effect.scoped);
yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
- return opened;
+ return { configurations };
});
it.effect("switches an agent that only advertises modes with session/set_mode", () =>
- openWithStoredSelection({
+ openWithStoredPicks({
setup: {
modes: {
currentModeId: "default",
availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })),
},
},
- selectionFrames: [
+ pickFrames: [
outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }),
answer("session/set_mode", {}),
],
storedModePick: "autoEdit",
- }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
);
it.effect("switches a mode config option under its own id", () =>
- openWithStoredSelection({
+ openWithStoredPicks({
setup: { configOptions: [permissionModeOption("ask")] },
- selectionFrames: [
+ pickFrames: [
outbound("session/set_config_option", {
sessionId: "agent-session",
configId: "permission-mode",
@@ -266,9 +333,195 @@ describe("AcpRegistryAdapterV2", () => {
answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
],
storedModePick: "auto",
- }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ const modelOption = (id: string, currentValue: string, grouped = false) => ({
+ id,
+ name: "Model",
+ category: "model",
+ type: "select",
+ currentValue,
+ options: grouped
+ ? [{ group: "models", name: "Models", options: [{ value: "default", name: "Default" }] }]
+ : [{ value: "auto", name: "Auto" }],
+ });
+ const configOptionUpdate = (configOptions: ReadonlyArray<unknown>): Frame => ({
+ type: "emit_inbound",
+ frame: {
+ kind: "notification",
+ method: "session/update",
+ params: {
+ sessionId: "agent-session",
+ update: { sessionUpdate: "config_option_update", configOptions },
+ },
+ },
+ });
+ const prompt = (...updates: ReadonlyArray<Frame>): ReadonlyArray<Frame> => [
+ outbound("session/prompt"),
+ ...updates,
+ answer("session/prompt", { stopReason: "end_turn" }),
+ ];
+ const setModel = (modelId: string): ReadonlyArray<Frame> => [
+ outbound("session/set_model", { sessionId: "agent-session", modelId }),
+ answer("session/set_model", {}),
+ ];
+
+ it.effect(
+ "discovers session models and switches through live model configuration changes",
+ () =>
+ Effect.gen(function* () {
+ const flatOption = (current: string) => modelOption("live-model", current);
+ const groupedOption = (current: string) =>
+ modelOption("replacement-model", current, true);
+ const { configurations } = yield* openWithStoredPicks({
+ setup: {
+ models: {
+ currentModelId: "hermes",
+ availableModels: ["hermes", "auto", "default"].map((modelId) => ({
+ modelId,
+ name: modelId,
+ })),
+ },
+ },
+ customModels: ["custom-model"],
+ storedModel: "default",
+ turnModels: [
+ "hermes",
+ "custom-model",
+ "auto",
+ "default",
+ "hermes",
+ "custom-model",
+ "auto",
+ "custom-model",
+ "default",
+ "hermes",
+ ],
+ pickFrames: [
+ ...setModel("default"),
+ ...setModel("hermes"),
+ ...prompt(),
+ ...setModel("custom-model"),
+ ...prompt(),
+ ...setModel("auto"),
+ ...prompt(),
+ ...setModel("default"),
+ ...prompt(),
+ ...setModel("hermes"),
+ ...prompt(configOptionUpdate([flatOption("hermes")])),
+ outbound("session/set_config_option", {
+ sessionId: "agent-session",
+ configId: "live-model",
+ value: "custom-model",
+ }),
+ answer("session/set_config_option", { configOptions: [flatOption("custom-model")] }),
+ ...prompt(),
+ outbound("session/set_config_option", {
+ sessionId: "agent-session",
+ configId: "live-model",
+ value: "auto",
+ }),
+ answer("session/set_config_option", { configOptions: [flatOption("auto")] }),
+ ...prompt(configOptionUpdate([groupedOption("auto")])),
+ outbound("session/set_config_option", {
+ sessionId: "agent-session",
+ configId: "replacement-model",
+ value: "custom-model",
+ }),
+ answer("session/set_config_option", {
+ configOptions: [groupedOption("custom-model")],
+ }),
+ ...prompt(),
+ outbound("session/set_config_option", {
+ sessionId: "agent-session",
+ configId: "replacement-model",
+ value: "default",
+ }),
+ answer("session/set_config_option", { configOptions: [groupedOption("default")] }),
+ ...prompt(configOptionUpdate([])),
+ ...setModel("hermes"),
+ ...prompt(),
+ ],
+ });
+ assert.deepEqual(
+ configurations.map((configuration) => ({
+ models: configuration?.models.map((model) => model.id),
+ current: configuration?.currentModelId,
+ })),
+ [
+ { models: ["hermes", "auto", "default"], current: "default" },
+ { models: ["hermes", "auto", "default"], current: "hermes" },
+ { models: ["hermes", "auto", "default"], current: null },
+ { models: ["hermes", "auto", "default"], current: "auto" },
+ { models: ["hermes", "auto", "default"], current: "default" },
+ { models: ["auto"], current: null },
+ { models: ["auto"], current: null },
+ { models: ["default"], current: null },
+ { models: ["default"], current: null },
+ { models: ["hermes", "auto", "default"], current: "default" },
+ { models: ["hermes", "auto", "default"], current: "hermes" },
+ ],
+ );
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
+ it.effect("leaves unadvertised model IDs alone in both model selection protocols", () =>
+ Effect.gen(function* () {
+ const { configurations } = yield* openWithStoredPicks({
+ setup: {
+ models: {
+ currentModelId: "hermes",
+ availableModels: ["hermes", "other"].map((modelId) => ({ modelId, name: modelId })),
+ },
+ },
+ storedModel: "default",
+ turnModels: [
+ "auto",
+ "removed-model",
+ "other",
+ "default",
+ "auto",
+ "hermes",
+ "removed-model",
+ ],
+ pickFrames: [
+ ...prompt(),
+ ...prompt(),
+ ...setModel("other"),
+ ...prompt(
+ configOptionUpdate([
+ {
+ ...modelOption("live-model", "other"),
+ options: [{ value: "other", name: "Other" }],
+ },
+ ]),
+ ),
+ ...prompt(),
+ ...prompt(),
+ ...prompt(
+ configOptionUpdate([
+ {
+ ...modelOption("replacement-model", "other", true),
+ options: [
+ {
+ group: "models",
+ name: "Models",
+ options: [{ value: "other", name: "Other" }],
+ },
+ ],
+ },
+ ]),
+ ),
+ ...prompt(),
+ ],
+ });
+ assert.deepEqual(
+ configurations.map((configuration) => configuration?.currentModelId),
+ ["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"],
+ );
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
const modelOptions = [
{ id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false },
{
@@ -333,9 +586,9 @@ describe("AcpRegistryAdapterV2", () => {
assert.equal(catalog.currentModelId, "gateway");
const model = catalog.models[1]?.id;
assert.isDefined(model);
- const opened = yield* openWithStoredSelection({
+ const opened = yield* openWithStoredPicks({
setup,
- selectionFrames: [
+ pickFrames: [
outbound("session/set_config_option", {
sessionId: "agent-session",
configId: "provider",
@@ -347,32 +600,20 @@ describe("AcpRegistryAdapterV2", () => {
),
}),
],
- model,
+ storedModel: model,
});
- assertOpened(opened);
+ assert.equal(opened.configurations.at(-1)?.currentModelId, "codex");
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.effect("rejects a later-option model before writing any configuration", () =>
+ it.effect("ignores a later-option model without writing configuration", () =>
Effect.gen(function* () {
- const opened = yield* openWithStoredSelection({
+ const { configurations } = yield* openWithStoredPicks({
setup: { configOptions: modelOptions },
- selectionFrames: [],
- model: "later-model",
- });
- assert.isTrue(Exit.isFailure(opened));
- const failure = Exit.isFailure(opened) ? Cause.squash(opened.cause) : undefined;
- assert.instanceOf(failure, ProviderAdapter.ProviderAdapterOpenSessionError);
- const rejection = failure instanceof Error ? failure.cause : undefined;
- assert.instanceOf(rejection, EffectAcpErrors.AcpRequestError);
- assert.deepInclude(rejection, {
- code: -32602,
- data: {
- configId: "provider",
- allowedValues: ["gateway", "codex"],
- receivedValue: "later-model",
- },
+ pickFrames: [],
+ storedModel: "later-model",
});
+ assert.equal(configurations[0]?.currentModelId, "gateway");
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
});
diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts
index 7b69ca58baa..6c8cb5aebf8 100644
--- a/apps/server/src/provider/AcpRegistryProbe.test.ts
+++ b/apps/server/src/provider/AcpRegistryProbe.test.ts
@@ -292,32 +292,42 @@ describe("ACP Registry probe", () => {
]);
});
- it("omits a current model that falls outside the bounded model catalog", () => {
- const result = acpRegistryProbeResult(instanceId, {
- sessionId: "probe-session",
- initializeResult: { protocolVersion: 1 },
- sessionSetupResult: {
+ it.each(["config option", "session model state"] as const)(
+ "retains the current model beyond the catalog cap from %s",
+ (source) => {
+ const models = Array.from({ length: 257 }, (_, index) => ({
+ modelId: `model-${index}`,
+ name: `Model ${index}`,
+ }));
+ const result = acpRegistryProbeResult(instanceId, {
sessionId: "probe-session",
- configOptions: [
- {
- id: "model",
- name: "Model",
- category: "model",
- type: "select",
- currentValue: "model-256",
- options: Array.from({ length: 257 }, (_, index) => ({
- value: `model-${index}`,
- name: `Model ${index}`,
- })),
- },
- ],
- },
- modelConfigId: "model",
- } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
-
- expect(result.models).toHaveLength(256);
- expect(result.currentModelId).toBeNull();
- });
+ initializeResult: { protocolVersion: 1 },
+ sessionSetupResult: {
+ sessionId: "probe-session",
+ ...(source === "config option"
+ ? {
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ category: "model",
+ type: "select",
+ currentValue: "model-256",
+ options: models.map(({ modelId, name }) => ({ value: modelId, name })),
+ },
+ ],
+ }
+ : { models: { currentModelId: "model-256", availableModels: models } }),
+ },
+ modelConfigId: source === "config option" ? "model" : undefined,
+ } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
+
+ expect(result.models).toHaveLength(256);
+ expect(result.models[0]?.id).toBe("model-0");
+ expect(result.models.at(-1)?.id).toBe("model-256");
+ expect(result.currentModelId).toBe("model-256");
+ },
+ );
it("bounds and de-duplicates advertised commands", () => {
const commands = normalizeAcpRegistryCommands([
diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts
index 63157b16462..6de4e773ee1 100644
--- a/packages/provider-acp-registry/src/server/adapter.ts
+++ b/packages/provider-acp-registry/src/server/adapter.ts
@@ -187,6 +187,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
const flavor: AcpAdapterV2Flavor = {
driver: ACP_REGISTRY_PROVIDER,
capabilities: AcpProviderCapabilitiesV2,
+ customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
...(registryAgentId === "mistral-vibe"
? { registerExtensions: registerMistralVibeAcpExtensions }
@@ -219,10 +220,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
options.instanceId,
normalizeAcpRegistryCommands(commands),
),
- onSessionConfigurationUpdate: (configOptions, modeState) =>
+ onSessionConfigurationUpdate: (configOptions, modeState, modelState) =>
runtimeCoordinator.publishLiveConfiguration(
options.instanceId,
- normalizeAcpRegistryLiveConfiguration(configOptions, modeState),
+ normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState),
),
onUrlElicitation: ({ elicitationId, url, message }) => {
const normalizedUrl = normalizeAcpRegistryWebUrl(url);
diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts
index 52bf5f505fc..ba50b57461f 100644
--- a/packages/provider-acp-registry/src/server/probe.ts
+++ b/packages/provider-acp-registry/src/server/probe.ts
@@ -59,31 +59,36 @@ export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
}
+function normalizedModel(id: string, candidate: AcpRegistryProbeModel): AcpRegistryProbeModel {
+ return {
+ id,
+ name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
+ description:
+ candidate.description === null
+ ? null
+ : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
+ };
+}
+
function normalizeModels(
- modelChoices: ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption>,
+ candidates: ReadonlyArray<AcpRegistryProbeModel>,
+ currentModelId: string | null,
): ReadonlyArray<AcpRegistryProbeModel> {
- // Model discovery is the model config option's base models; ACP has no
- // other portable model inventory.
- const candidates = modelChoices.map((model) => ({
- id: model.value,
- name: model.name,
- description: model.description ?? null,
- }));
const seen = new Set<string>();
const models: Array<AcpRegistryProbeModel> = [];
for (const candidate of candidates) {
+ if (models.length === MAX_MODELS) break;
const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH);
if (id === undefined || seen.has(id)) continue;
seen.add(id);
- models.push({
- id,
- name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
- description:
- candidate.description === null
- ? null
- : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
- });
- if (models.length === MAX_MODELS) break;
+ models.push(normalizedModel(id, candidate));
+ }
+ // Keep the running model visible even when its advertised position exceeds the cap.
+ if (currentModelId !== null && models.length === MAX_MODELS && !seen.has(currentModelId)) {
+ const current = candidates.find((candidate) => candidate.id === currentModelId);
+ if (current !== undefined) {
+ models[MAX_MODELS - 1] = normalizedModel(currentModelId, current);
+ }
}
return models;
}
@@ -168,13 +173,28 @@ export interface AcpRegistryLiveConfiguration {
export function normalizeAcpRegistryLiveConfiguration(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
+ modelState?: EffectAcpSchema.SessionModelState | null,
): AcpRegistryLiveConfiguration {
const modelOption = findModelConfigOption(configOptions);
- const boundedCurrentModelId =
+ const currentModelId =
+ modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId;
+ const candidates =
modelOption === undefined
+ ? (modelState?.availableModels ?? []).map((model) => ({
+ id: model.modelId,
+ name: model.name,
+ description: model.description ?? null,
+ }))
+ : flattenSelectChoices(modelOption.options).map((model) => ({
+ id: model.value,
+ name: model.name,
+ description: model.description ?? null,
+ }));
+ const boundedCurrentModelId =
+ currentModelId === undefined
? null
- : (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null);
- const models = normalizeModels(flattenSelectChoices(modelOption?.options ?? []));
+ : (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null);
+ const models = normalizeModels(candidates, boundedCurrentModelId);
return {
models,
currentModelId: models.some((model) => model.id === boundedCurrentModelId)
@@ -236,6 +256,7 @@ export function acpRegistryProbeResult(
const liveConfiguration = normalizeAcpRegistryLiveConfiguration(
started.sessionSetupResult.configOptions ?? [],
parseSessionModeState(started.sessionSetupResult),
+ started.sessionSetupResult.models,
);
return AcpRegistryProbeResult.make({
instanceId,
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 5d7ea0b7d28..5aaac47c943 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -217,6 +217,7 @@ export interface AcpAdapterV2Flavor {
readonly onSessionConfigurationUpdate?: (
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
modeState: AcpSessionModeState | undefined,
+ modelState: EffectAcpSchema.SessionModelState | null | undefined,
) => Effect.Effect<void>;
readonly onUrlElicitation?: (input: {
readonly elicitationId: string;
@@ -231,6 +232,7 @@ export interface AcpAdapterV2Flavor {
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
>;
+ readonly customModels?: ReadonlyArray<string>;
readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
readonly getModelContextWindow?: (
selection: ModelSelection,
@@ -516,14 +518,15 @@ function negotiatedCapabilities(
const agent = started.initializeResult.agentCapabilities ?? {};
const session = agent.sessionCapabilities;
const setup = started.sessionSetupResult;
- const hasModelConfig = findModelConfigOption(setup.configOptions) !== undefined;
+ const canSwitchModel =
+ findModelConfigOption(setup.configOptions) !== undefined || setup.models != null;
const canLoad = agent.loadSession === true;
const canFork = session?.fork != null;
return {
...base,
sessions: {
...base.sessions,
- supportsModelSwitchInSession: hasModelConfig,
+ supportsModelSwitchInSession: canSwitchModel,
},
threads: {
...base.threads,
@@ -5129,6 +5132,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
flavor.onSessionConfigurationUpdate?.(
yield* runtime.getConfigOptions,
yield* runtime.getModeState,
+ (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
) ?? Effect.void
);
}
@@ -5904,13 +5908,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
startResult,
modelSelection,
});
- } else if (
- requestedModel.length > 0 &&
- requestedModel !== "auto" &&
- requestedModel !== "default"
- ) {
- if (findModelConfigOption(startResult.sessionSetupResult.configOptions) !== undefined) {
- yield* runtime.setModel(requestedModel);
+ } else if (requestedModel.length > 0) {
+ // Stored catalog choices can expire; explicitly configured custom IDs
+ // are validated by the agent instead.
+ const isCustomModel = flavor.customModels?.includes(requestedModel) === true;
+ const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
+ const modelState = startResult.sessionSetupResult.models;
+ if (modelOption?.type === "select") {
+ if (
+ isCustomModel ||
+ modelOption.options.some((entry) =>
+ "value" in entry
+ ? entry.value === requestedModel
+ : entry.options.some((choice) => choice.value === requestedModel),
+ )
+ ) {
+ yield* runtime.setConfigOption(modelOption.id, requestedModel);
+ appliedModel = requestedModel;
+ }
+ } else if (
+ modelState != null &&
+ (isCustomModel ||
+ modelState.availableModels.some((model) => model.modelId === requestedModel))
+ ) {
+ if (modelState.currentModelId !== requestedModel) {
+ yield* runtime.setSessionModel(requestedModel);
+ }
+ appliedModel = requestedModel;
}
}
if (appliedModel !== undefined) {
@@ -6078,6 +6102,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
flavor.onSessionConfigurationUpdate?.(
yield* runtime.getConfigOptions,
yield* runtime.getModeState,
+ (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
) ?? Effect.void
);
});