@devries-cameron20 / t3code Mirror · read-only / commits / 9cbc2c0049
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Oct 20, 2026 at 05:37 UTC 9cbc2c0049a79d9864fc3dd097e49a01b1a82b6e
7 files changed +491 -184
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+1 -68
@@ -15,16 +15,11 @@ import { assert, describe, it } from "@effect/vitest";
15 import {
16 CheckpointId,
17 EnvironmentId,
18 - MessageId,
18 type ModelSelection,
20 - NodeId,
21 - ProjectId,
19 ProviderDriverKind,
20 ProviderInstanceId,
21 ProviderSessionId,
22 ProviderThreadId,
26 - RunAttemptId,
27 - RunId,
23 ThreadId,
24 type OrchestrationV2ProviderThread,
25 type ProviderOptionDescriptor,
@@ -73,6 +68,7 @@ import {
68 } from "@t3tools/provider-grok/testing";
69 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
70 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
71 +import { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
72 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
73 import {
74 AcpProviderCapabilitiesV2,
@@ -540,69 +536,6 @@ const pollProtocolMethods = (events: Queue.Queue<EffectAcpProtocol.AcpProtocolLo
536 return methods;
537 });
538
543 -function makeTurnInput(input: {
544 - readonly threadId: ThreadId;
545 - readonly providerThread: OrchestrationV2ProviderThread;
546 - readonly instanceId: ProviderInstanceId;
547 - readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
548 - readonly now: DateTime.Utc;
549 - readonly ordinal?: number;
550 - readonly modelSelection?: ModelSelection;
551 - readonly messageCreatedBy?: "user" | "agent";
552 - readonly messageCreationSource?: "web" | "mobile" | "mcp" | "provider" | "server";
553 - readonly messageText?: string;
554 -}): ProviderAdapter.ProviderAdapterV2TurnInput {
555 - const ordinal = input.ordinal ?? 1;
556 - const suffix = `${input.threadId}:${ordinal}`;
557 - const modelSelection =
558 - input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const);
559 - return {
560 - appThread: {
561 - createdBy: "user",
562 - creationSource: "web",
563 - id: input.threadId,
564 - projectId: ProjectId.make(`project:${input.threadId}`),
565 - title: "ACP adapter test",
566 - providerInstanceId: input.instanceId,
567 - modelSelection,
568 - runtimeMode: "approval-required",
569 - interactionMode: "default",
570 - branch: null,
571 - worktreePath: null,
572 - activeProviderThreadId: input.providerThread.id,
573 - lineage: {
574 - parentThreadId: null,
575 - relationshipToParent: null,
576 - rootThreadId: input.threadId,
577 - },
578 - forkedFrom: null,
579 - createdAt: input.now,
580 - updatedAt: input.now,
581 - archivedAt: null,
582 - settledOverride: null,
583 - settledAt: null,
584 - lastVisitedAt: null,
585 - deletedAt: null,
586 - },
587 - threadId: input.threadId,
588 - runId: RunId.make(`run:${suffix}`),
589 - runOrdinal: ordinal,
590 - providerTurnOrdinal: ordinal,
591 - attemptId: RunAttemptId.make(`attempt:${suffix}`),
592 - rootNodeId: NodeId.make(`node:${suffix}`),
593 - providerThread: input.providerThread,
594 - message: {
595 - createdBy: input.messageCreatedBy ?? "user",
596 - creationSource: input.messageCreationSource ?? "web",
597 - messageId: MessageId.make(`message:${suffix}`),
598 - text: input.messageText ?? "test prompt",
599 - attachments: [],
600 - },
601 - modelSelection,
602 - runtimePolicy: input.runtimePolicy,
603 - };
604 -}
605 -
539 describe("AcpAdapterV2", () => {
540 it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
541 "projects Mistral retry notices and their %s outcome",
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts
+76
@@ -1,8 +1,19 @@
1 import {
2 + MessageId,
3 + type ModelSelection,
4 + NodeId,
5 + ProjectId,
6 + type ProviderInstanceId,
7 + RunAttemptId,
8 + RunId,
9 + type OrchestrationV2ProviderThread,
10 + type ThreadId,
11 ProviderDriverKind,
12 ProviderReplayEntry,
13 type ProviderReplayTranscript,
14 } from "@t3tools/contracts";
15 +import type * as DateTime from "effect/DateTime";
16 +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
17 import * as Effect from "effect/Effect";
18 import * as Crypto from "effect/Crypto";
19 import * as FileSystem from "effect/FileSystem";
@@ -181,6 +192,7 @@ export function makeAcpReplayRuntime(input: {
192 readonly scriptPath: string;
193 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
194 readonly fileSystem: FileSystem.FileSystem;
195 + readonly customModels?: AcpSessionRuntime.AcpSessionRuntimeOptions["customModels"];
196 readonly cancelMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelMeta"];
197 readonly initializeMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["initializeMeta"];
198 readonly replayGate?: ProviderReplayGate;
@@ -222,6 +234,7 @@ export function makeAcpReplayRuntime(input: {
234 },
235 },
236 authMethodId: "replay",
237 + ...(input.customModels === undefined ? {} : { customModels: input.customModels }),
238 ...(input.cancelMeta === undefined ? {} : { cancelMeta: input.cancelMeta }),
239 ...(input.initializeMeta === undefined ? {} : { initializeMeta: input.initializeMeta }),
240 ...(input.replayGate === undefined
@@ -238,3 +251,66 @@ export function makeAcpReplayRuntime(input: {
251 );
252 });
253 }
254 +
255 +export function makeTurnInput(input: {
256 + readonly threadId: ThreadId;
257 + readonly providerThread: OrchestrationV2ProviderThread;
258 + readonly instanceId: ProviderInstanceId;
259 + readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
260 + readonly now: DateTime.Utc;
261 + readonly ordinal?: number;
262 + readonly modelSelection?: ModelSelection;
263 + readonly messageCreatedBy?: "user" | "agent";
264 + readonly messageCreationSource?: "web" | "mobile" | "mcp" | "provider" | "server";
265 + readonly messageText?: string;
266 +}): ProviderAdapter.ProviderAdapterV2TurnInput {
267 + const ordinal = input.ordinal ?? 1;
268 + const suffix = `${input.threadId}:${ordinal}`;
269 + const modelSelection =
270 + input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const);
271 + return {
272 + appThread: {
273 + createdBy: "user",
274 + creationSource: "web",
275 + id: input.threadId,
276 + projectId: ProjectId.make(`project:${input.threadId}`),
277 + title: "ACP adapter test",
278 + providerInstanceId: input.instanceId,
279 + modelSelection,
280 + runtimeMode: "approval-required",
281 + interactionMode: "default",
282 + branch: null,
283 + worktreePath: null,
284 + activeProviderThreadId: input.providerThread.id,
285 + lineage: {
286 + parentThreadId: null,
287 + relationshipToParent: null,
288 + rootThreadId: input.threadId,
289 + },
290 + forkedFrom: null,
291 + createdAt: input.now,
292 + updatedAt: input.now,
293 + archivedAt: null,
294 + settledOverride: null,
295 + settledAt: null,
296 + lastVisitedAt: null,
297 + deletedAt: null,
298 + },
299 + threadId: input.threadId,
300 + runId: RunId.make(`run:${suffix}`),
301 + runOrdinal: ordinal,
302 + providerTurnOrdinal: ordinal,
303 + attemptId: RunAttemptId.make(`attempt:${suffix}`),
304 + rootNodeId: NodeId.make(`node:${suffix}`),
305 + providerThread: input.providerThread,
306 + message: {
307 + createdBy: input.messageCreatedBy ?? "user",
308 + creationSource: input.messageCreationSource ?? "web",
309 + messageId: MessageId.make(`message:${suffix}`),
310 + text: input.messageText ?? "test prompt",
311 + attachments: [],
312 + },
313 + modelSelection,
314 + runtimePolicy: input.runtimePolicy,
315 + };
316 +}
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+301 -60
@@ -1,11 +1,16 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 -import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
3 +import {
4 + type ModelSelection,
5 + ProviderInstanceId,
6 + ProviderSessionId,
7 + ThreadId,
8 +} from "@t3tools/contracts";
9 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
5 -import * as Cause from "effect/Cause";
10 +import * as DateTime from "effect/DateTime";
11 +import * as Stream from "effect/Stream";
12 import * as Deferred from "effect/Deferred";
13 import * as Effect from "effect/Effect";
8 -import * as Exit from "effect/Exit";
14 import * as FileSystem from "effect/FileSystem";
15 import * as Layer from "effect/Layer";
16 import * as Option from "effect/Option";
@@ -33,6 +38,7 @@ import {
38 decodeAcpReplayTranscript,
39 makeAcpReplayCompletenessAssertion,
40 makeAcpReplayRuntime,
41 + makeTurnInput,
42 } from "./AcpAdapterV2.testkit.ts";
43 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44 import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts";
@@ -143,7 +149,7 @@ describe("AcpRegistryAdapterV2", () => {
149 });
150 });
151
146 - describe("applying a stored selection to a scripted agent", () => {
152 + describe("the agent's own pickers", () => {
153 type Frame = Record<string, unknown>;
154 const outbound = (method: string, params: unknown = "<any>"): Frame => ({
155 type: "expect_outbound",
@@ -153,8 +159,6 @@ describe("AcpRegistryAdapterV2", () => {
159 type: "emit_inbound",
160 frame: { kind: "response", method, result },
161 });
156 - const assertOpened = (opened: Exit.Exit<void, unknown>) =>
157 - assert.isTrue(Exit.isSuccess(opened));
162 const permissionModeOption = (currentValue: string) => ({
163 id: "permission-mode",
164 name: "Permission mode",
@@ -164,17 +168,19 @@ describe("AcpRegistryAdapterV2", () => {
168 options: ["ask", "auto"].map((value) => ({ value, name: value })),
169 });
170
167 - const openWithStoredSelection = Effect.fn("openWithStoredSelection")(function* (input: {
171 + const openWithStoredPicks = Effect.fn("openWithStoredPicks")(function* (input: {
172 readonly setup: unknown;
169 - readonly selectionFrames: ReadonlyArray<Frame>;
170 - readonly model?: string;
173 + readonly pickFrames: ReadonlyArray<Frame>;
174 + readonly customModels?: ReadonlyArray<string>;
175 + readonly storedModel?: string;
176 readonly storedModePick?: string;
177 + readonly turnModels?: ReadonlyArray<string>;
178 }) {
179 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
180 const fileSystem = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const replayDir = yield* fileSystem.makeTempDirectoryScoped({
177 - prefix: "t3-acp-registry-mode-pick-",
183 + prefix: "t3-acp-registry-stored-picks-",
184 });
185 const statusPath = path.join(replayDir, "status.json");
186 const transcript = yield* decodeAcpReplayTranscript(
@@ -182,7 +188,7 @@ describe("AcpRegistryAdapterV2", () => {
188 provider: ACP_REGISTRY_PROVIDER,
189 protocol: "acp.ndjson-jsonrpc",
190 version: "1",
185 - scenario: "stored-mode-pick",
191 + scenario: "stored-picks",
192 entries: [
193 outbound("initialize"),
194 answer("initialize", {
@@ -192,21 +198,24 @@ describe("AcpRegistryAdapterV2", () => {
198 }),
199 outbound("session/new"),
200 answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }),
195 - ...input.selectionFrames,
201 + ...input.pickFrames,
202 ] as never,
203 },
204 ACP_REGISTRY_PROVIDER,
205 );
200 - const instanceId = ProviderInstanceId.make("acp-registry-mode-pick");
206 + const instanceId = ProviderInstanceId.make("acp-registry-stored-picks");
207 + let published: AcpRegistryLiveConfiguration | undefined;
208 const adapter = yield* makeAcpRegistryAdapterV2({
209 selfInvocation: yield* resolveSelfInvocation(),
210 instanceId,
211 settings: yield* decodeAcpRegistryAdapterSettings({
212 agentId: "fixture-agent",
213 authMethodId: "test",
214 + customModels: input.customModels ?? [],
215 }),
216 environment: {},
217 makeRuntime: makeAcpReplayRuntime({
218 + customModels: input.customModels,
219 transcript,
220 statusPath,
221 scriptPath: yield* path.fromFileUrl(
@@ -215,49 +224,107 @@ describe("AcpRegistryAdapterV2", () => {
224 childProcessSpawner,
225 fileSystem,
226 }),
218 - }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
219 - const opened = yield* adapter
220 - .openSession({
221 - threadId: ThreadId.make("thread-acp-registry-mode-pick"),
222 - providerSessionId: ProviderSessionId.make("provider-session-mode-pick"),
223 - modelSelection: {
224 - instanceId,
225 - model: input.model ?? "default",
226 - ...(input.storedModePick === undefined
227 - ? {}
228 - : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
229 - },
230 - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
231 - runtimeMode: "approval-required",
232 - interactionMode: "default",
233 - cwd: replayDir,
234 - }),
235 - })
236 - .pipe(Effect.asVoid, Effect.scoped, Effect.exit);
227 + }).pipe(
228 + Effect.provide(
229 + Layer.mergeAll(
230 + layerInjectedRuntimeCatalog,
231 + Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({
232 + withForegroundStartup: (_startupKey, effect) => effect,
233 + publishLiveConfiguration: (_instanceId, configuration) =>
234 + Effect.sync(() => {
235 + published = configuration;
236 + }),
237 + }),
238 + ),
239 + ),
240 + );
241 + const threadId = ThreadId.make("thread-acp-registry-stored-picks");
242 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
243 + runtimeMode: "approval-required",
244 + interactionMode: "default",
245 + cwd: replayDir,
246 + });
247 + const stored: ModelSelection = {
248 + instanceId,
249 + model: input.storedModel ?? "default",
250 + ...(input.storedModePick === undefined
251 + ? {}
252 + : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
253 + };
254 + const configurations: Array<AcpRegistryLiveConfiguration | undefined> = [];
255 + yield* Effect.gen(function* () {
256 + const runtime = yield* adapter.openSession({
257 + threadId,
258 + providerSessionId: ProviderSessionId.make("provider-session-stored-picks"),
259 + modelSelection: stored,
260 + runtimePolicy,
261 + });
262 + configurations.push(published);
263 + if (input.turnModels === undefined) return;
264 + const providerThread = yield* runtime.ensureThread({
265 + threadId,
266 + modelSelection: stored,
267 + runtimePolicy,
268 + });
269 + const now = yield* DateTime.now;
270 + let current = stored;
271 + for (const [index, model] of input.turnModels.entries()) {
272 + const target: ModelSelection = { instanceId, model };
273 + const plan = yield* adapter.planSelectionTransition({
274 + current,
275 + target,
276 + sessionCapabilities: runtime.providerSession.capabilities,
277 + });
278 + assert.equal(plan.type, "apply_on_next_turn");
279 + yield* runtime.startTurn(
280 + makeTurnInput({
281 + threadId,
282 + providerThread,
283 + instanceId,
284 + runtimePolicy,
285 + now,
286 + ordinal: index + 1,
287 + modelSelection: target,
288 + }),
289 + );
290 + yield* runtime.events.pipe(
291 + Stream.takeUntil((event) => event.type === "turn.terminal"),
292 + Stream.runForEach((event) =>
293 + Effect.sync(() => {
294 + if (event.type === "turn.terminal") {
295 + assert.equal(event.status, "completed", event.failure?.message);
296 + }
297 + }),
298 + ),
299 + );
300 + configurations.push(published);
301 + current = target;
302 + }
303 + }).pipe(Effect.scoped);
304 yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
238 - return opened;
305 + return { configurations };
306 });
307
308 it.effect("switches an agent that only advertises modes with session/set_mode", () =>
242 - openWithStoredSelection({
309 + openWithStoredPicks({
310 setup: {
311 modes: {
312 currentModeId: "default",
313 availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })),
314 },
315 },
249 - selectionFrames: [
316 + pickFrames: [
317 outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }),
318 answer("session/set_mode", {}),
319 ],
320 storedModePick: "autoEdit",
254 - }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
321 + }).pipe(Effect.provide(layerTest), Effect.scoped),
322 );
323
324 it.effect("switches a mode config option under its own id", () =>
258 - openWithStoredSelection({
325 + openWithStoredPicks({
326 setup: { configOptions: [permissionModeOption("ask")] },
260 - selectionFrames: [
327 + pickFrames: [
328 outbound("session/set_config_option", {
329 sessionId: "agent-session",
330 configId: "permission-mode",
@@ -266,9 +333,195 @@ describe("AcpRegistryAdapterV2", () => {
333 answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
334 ],
335 storedModePick: "auto",
269 - }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
336 + }).pipe(Effect.provide(layerTest), Effect.scoped),
337 );
338
339 + const modelOption = (id: string, currentValue: string, grouped = false) => ({
340 + id,
341 + name: "Model",
342 + category: "model",
343 + type: "select",
344 + currentValue,
345 + options: grouped
346 + ? [{ group: "models", name: "Models", options: [{ value: "default", name: "Default" }] }]
347 + : [{ value: "auto", name: "Auto" }],
348 + });
349 + const configOptionUpdate = (configOptions: ReadonlyArray<unknown>): Frame => ({
350 + type: "emit_inbound",
351 + frame: {
352 + kind: "notification",
353 + method: "session/update",
354 + params: {
355 + sessionId: "agent-session",
356 + update: { sessionUpdate: "config_option_update", configOptions },
357 + },
358 + },
359 + });
360 + const prompt = (...updates: ReadonlyArray<Frame>): ReadonlyArray<Frame> => [
361 + outbound("session/prompt"),
362 + ...updates,
363 + answer("session/prompt", { stopReason: "end_turn" }),
364 + ];
365 + const setModel = (modelId: string): ReadonlyArray<Frame> => [
366 + outbound("session/set_model", { sessionId: "agent-session", modelId }),
367 + answer("session/set_model", {}),
368 + ];
369 +
370 + it.effect(
371 + "discovers session models and switches through live model configuration changes",
372 + () =>
373 + Effect.gen(function* () {
374 + const flatOption = (current: string) => modelOption("live-model", current);
375 + const groupedOption = (current: string) =>
376 + modelOption("replacement-model", current, true);
377 + const { configurations } = yield* openWithStoredPicks({
378 + setup: {
379 + models: {
380 + currentModelId: "hermes",
381 + availableModels: ["hermes", "auto", "default"].map((modelId) => ({
382 + modelId,
383 + name: modelId,
384 + })),
385 + },
386 + },
387 + customModels: ["custom-model"],
388 + storedModel: "default",
389 + turnModels: [
390 + "hermes",
391 + "custom-model",
392 + "auto",
393 + "default",
394 + "hermes",
395 + "custom-model",
396 + "auto",
397 + "custom-model",
398 + "default",
399 + "hermes",
400 + ],
401 + pickFrames: [
402 + ...setModel("default"),
403 + ...setModel("hermes"),
404 + ...prompt(),
405 + ...setModel("custom-model"),
406 + ...prompt(),
407 + ...setModel("auto"),
408 + ...prompt(),
409 + ...setModel("default"),
410 + ...prompt(),
411 + ...setModel("hermes"),
412 + ...prompt(configOptionUpdate([flatOption("hermes")])),
413 + outbound("session/set_config_option", {
414 + sessionId: "agent-session",
415 + configId: "live-model",
416 + value: "custom-model",
417 + }),
418 + answer("session/set_config_option", { configOptions: [flatOption("custom-model")] }),
419 + ...prompt(),
420 + outbound("session/set_config_option", {
421 + sessionId: "agent-session",
422 + configId: "live-model",
423 + value: "auto",
424 + }),
425 + answer("session/set_config_option", { configOptions: [flatOption("auto")] }),
426 + ...prompt(configOptionUpdate([groupedOption("auto")])),
427 + outbound("session/set_config_option", {
428 + sessionId: "agent-session",
429 + configId: "replacement-model",
430 + value: "custom-model",
431 + }),
432 + answer("session/set_config_option", {
433 + configOptions: [groupedOption("custom-model")],
434 + }),
435 + ...prompt(),
436 + outbound("session/set_config_option", {
437 + sessionId: "agent-session",
438 + configId: "replacement-model",
439 + value: "default",
440 + }),
441 + answer("session/set_config_option", { configOptions: [groupedOption("default")] }),
442 + ...prompt(configOptionUpdate([])),
443 + ...setModel("hermes"),
444 + ...prompt(),
445 + ],
446 + });
447 + assert.deepEqual(
448 + configurations.map((configuration) => ({
449 + models: configuration?.models.map((model) => model.id),
450 + current: configuration?.currentModelId,
451 + })),
452 + [
453 + { models: ["hermes", "auto", "default"], current: "default" },
454 + { models: ["hermes", "auto", "default"], current: "hermes" },
455 + { models: ["hermes", "auto", "default"], current: null },
456 + { models: ["hermes", "auto", "default"], current: "auto" },
457 + { models: ["hermes", "auto", "default"], current: "default" },
458 + { models: ["auto"], current: null },
459 + { models: ["auto"], current: null },
460 + { models: ["default"], current: null },
461 + { models: ["default"], current: null },
462 + { models: ["hermes", "auto", "default"], current: "default" },
463 + { models: ["hermes", "auto", "default"], current: "hermes" },
464 + ],
465 + );
466 + }).pipe(Effect.provide(layerTest), Effect.scoped),
467 + );
468 +
469 + it.effect("leaves unadvertised model IDs alone in both model selection protocols", () =>
470 + Effect.gen(function* () {
471 + const { configurations } = yield* openWithStoredPicks({
472 + setup: {
473 + models: {
474 + currentModelId: "hermes",
475 + availableModels: ["hermes", "other"].map((modelId) => ({ modelId, name: modelId })),
476 + },
477 + },
478 + storedModel: "default",
479 + turnModels: [
480 + "auto",
481 + "removed-model",
482 + "other",
483 + "default",
484 + "auto",
485 + "hermes",
486 + "removed-model",
487 + ],
488 + pickFrames: [
489 + ...prompt(),
490 + ...prompt(),
491 + ...setModel("other"),
492 + ...prompt(
493 + configOptionUpdate([
494 + {
495 + ...modelOption("live-model", "other"),
496 + options: [{ value: "other", name: "Other" }],
497 + },
498 + ]),
499 + ),
500 + ...prompt(),
501 + ...prompt(),
502 + ...prompt(
503 + configOptionUpdate([
504 + {
505 + ...modelOption("replacement-model", "other", true),
506 + options: [
507 + {
508 + group: "models",
509 + name: "Models",
510 + options: [{ value: "other", name: "Other" }],
511 + },
512 + ],
513 + },
514 + ]),
515 + ),
516 + ...prompt(),
517 + ],
518 + });
519 + assert.deepEqual(
520 + configurations.map((configuration) => configuration?.currentModelId),
521 + ["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"],
522 + );
523 + }).pipe(Effect.provide(layerTest), Effect.scoped),
524 + );
525 const modelOptions = [
526 { id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false },
527 {
@@ -333,9 +586,9 @@ describe("AcpRegistryAdapterV2", () => {
586 assert.equal(catalog.currentModelId, "gateway");
587 const model = catalog.models[1]?.id;
588 assert.isDefined(model);
336 - const opened = yield* openWithStoredSelection({
589 + const opened = yield* openWithStoredPicks({
590 setup,
338 - selectionFrames: [
591 + pickFrames: [
592 outbound("session/set_config_option", {
593 sessionId: "agent-session",
594 configId: "provider",
@@ -347,32 +600,20 @@ describe("AcpRegistryAdapterV2", () => {
600 ),
601 }),
602 ],
350 - model,
603 + storedModel: model,
604 });
352 - assertOpened(opened);
605 + assert.equal(opened.configurations.at(-1)?.currentModelId, "codex");
606 }).pipe(Effect.provide(layerTest), Effect.scoped),
607 );
608
356 - it.effect("rejects a later-option model before writing any configuration", () =>
609 + it.effect("ignores a later-option model without writing configuration", () =>
610 Effect.gen(function* () {
358 - const opened = yield* openWithStoredSelection({
611 + const { configurations } = yield* openWithStoredPicks({
612 setup: { configOptions: modelOptions },
360 - selectionFrames: [],
361 - model: "later-model",
362 - });
363 - assert.isTrue(Exit.isFailure(opened));
364 - const failure = Exit.isFailure(opened) ? Cause.squash(opened.cause) : undefined;
365 - assert.instanceOf(failure, ProviderAdapter.ProviderAdapterOpenSessionError);
366 - const rejection = failure instanceof Error ? failure.cause : undefined;
367 - assert.instanceOf(rejection, EffectAcpErrors.AcpRequestError);
368 - assert.deepInclude(rejection, {
369 - code: -32602,
370 - data: {
371 - configId: "provider",
372 - allowedValues: ["gateway", "codex"],
373 - receivedValue: "later-model",
374 - },
613 + pickFrames: [],
614 + storedModel: "later-model",
615 });
616 + assert.equal(configurations[0]?.currentModelId, "gateway");
617 }).pipe(Effect.provide(layerTest), Effect.scoped),
618 );
619 });
apps/server/src/provider/AcpRegistryProbe.test.ts
+35 -25
@@ -292,32 +292,42 @@ describe("ACP Registry probe", () => {
292 ]);
293 });
294
295 - it("omits a current model that falls outside the bounded model catalog", () => {
296 - const result = acpRegistryProbeResult(instanceId, {
297 - sessionId: "probe-session",
298 - initializeResult: { protocolVersion: 1 },
299 - sessionSetupResult: {
295 + it.each(["config option", "session model state"] as const)(
296 + "retains the current model beyond the catalog cap from %s",
297 + (source) => {
298 + const models = Array.from({ length: 257 }, (_, index) => ({
299 + modelId: `model-${index}`,
300 + name: `Model ${index}`,
301 + }));
302 + const result = acpRegistryProbeResult(instanceId, {
303 sessionId: "probe-session",
301 - configOptions: [
302 - {
303 - id: "model",
304 - name: "Model",
305 - category: "model",
306 - type: "select",
307 - currentValue: "model-256",
308 - options: Array.from({ length: 257 }, (_, index) => ({
309 - value: `model-${index}`,
310 - name: `Model ${index}`,
311 - })),
312 - },
313 - ],
314 - },
315 - modelConfigId: "model",
316 - } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
317 -
318 - expect(result.models).toHaveLength(256);
319 - expect(result.currentModelId).toBeNull();
320 - });
304 + initializeResult: { protocolVersion: 1 },
305 + sessionSetupResult: {
306 + sessionId: "probe-session",
307 + ...(source === "config option"
308 + ? {
309 + configOptions: [
310 + {
311 + id: "model",
312 + name: "Model",
313 + category: "model",
314 + type: "select",
315 + currentValue: "model-256",
316 + options: models.map(({ modelId, name }) => ({ value: modelId, name })),
317 + },
318 + ],
319 + }
320 + : { models: { currentModelId: "model-256", availableModels: models } }),
321 + },
322 + modelConfigId: source === "config option" ? "model" : undefined,
323 + } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
324 +
325 + expect(result.models).toHaveLength(256);
326 + expect(result.models[0]?.id).toBe("model-0");
327 + expect(result.models.at(-1)?.id).toBe("model-256");
328 + expect(result.currentModelId).toBe("model-256");
329 + },
330 + );
331
332 it("bounds and de-duplicates advertised commands", () => {
333 const commands = normalizeAcpRegistryCommands([
packages/provider-acp-registry/src/server/adapter.ts
+3 -2
@@ -187,6 +187,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
187 const flavor: AcpAdapterV2Flavor = {
188 driver: ACP_REGISTRY_PROVIDER,
189 capabilities: AcpProviderCapabilitiesV2,
190 + customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
191 promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
192 ...(registryAgentId === "mistral-vibe"
193 ? { registerExtensions: registerMistralVibeAcpExtensions }
@@ -219,10 +220,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
220 options.instanceId,
221 normalizeAcpRegistryCommands(commands),
222 ),
222 - onSessionConfigurationUpdate: (configOptions, modeState) =>
223 + onSessionConfigurationUpdate: (configOptions, modeState, modelState) =>
224 runtimeCoordinator.publishLiveConfiguration(
225 options.instanceId,
225 - normalizeAcpRegistryLiveConfiguration(configOptions, modeState),
226 + normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState),
227 ),
228 onUrlElicitation: ({ elicitationId, url, message }) => {
229 const normalizedUrl = normalizeAcpRegistryWebUrl(url);
packages/provider-acp-registry/src/server/probe.ts
+41 -20
@@ -59,31 +59,36 @@ export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
59 return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
60 }
61
62 +function normalizedModel(id: string, candidate: AcpRegistryProbeModel): AcpRegistryProbeModel {
63 + return {
64 + id,
65 + name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
66 + description:
67 + candidate.description === null
68 + ? null
69 + : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
70 + };
71 +}
72 +
73 function normalizeModels(
63 - modelChoices: ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption>,
74 + candidates: ReadonlyArray<AcpRegistryProbeModel>,
75 + currentModelId: string | null,
76 ): ReadonlyArray<AcpRegistryProbeModel> {
65 - // Model discovery is the model config option's base models; ACP has no
66 - // other portable model inventory.
67 - const candidates = modelChoices.map((model) => ({
68 - id: model.value,
69 - name: model.name,
70 - description: model.description ?? null,
71 - }));
77 const seen = new Set<string>();
78 const models: Array<AcpRegistryProbeModel> = [];
79 for (const candidate of candidates) {
80 + if (models.length === MAX_MODELS) break;
81 const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH);
82 if (id === undefined || seen.has(id)) continue;
83 seen.add(id);
78 - models.push({
79 - id,
80 - name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
81 - description:
82 - candidate.description === null
83 - ? null
84 - : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
85 - });
86 - if (models.length === MAX_MODELS) break;
84 + models.push(normalizedModel(id, candidate));
85 + }
86 + // Keep the running model visible even when its advertised position exceeds the cap.
87 + if (currentModelId !== null && models.length === MAX_MODELS && !seen.has(currentModelId)) {
88 + const current = candidates.find((candidate) => candidate.id === currentModelId);
89 + if (current !== undefined) {
90 + models[MAX_MODELS - 1] = normalizedModel(currentModelId, current);
91 + }
92 }
93 return models;
94 }
@@ -168,13 +173,28 @@ export interface AcpRegistryLiveConfiguration {
173 export function normalizeAcpRegistryLiveConfiguration(
174 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
175 modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
176 + modelState?: EffectAcpSchema.SessionModelState | null,
177 ): AcpRegistryLiveConfiguration {
178 const modelOption = findModelConfigOption(configOptions);
173 - const boundedCurrentModelId =
179 + const currentModelId =
180 + modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId;
181 + const candidates =
182 modelOption === undefined
183 + ? (modelState?.availableModels ?? []).map((model) => ({
184 + id: model.modelId,
185 + name: model.name,
186 + description: model.description ?? null,
187 + }))
188 + : flattenSelectChoices(modelOption.options).map((model) => ({
189 + id: model.value,
190 + name: model.name,
191 + description: model.description ?? null,
192 + }));
193 + const boundedCurrentModelId =
194 + currentModelId === undefined
195 ? null
176 - : (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null);
177 - const models = normalizeModels(flattenSelectChoices(modelOption?.options ?? []));
196 + : (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null);
197 + const models = normalizeModels(candidates, boundedCurrentModelId);
198 return {
199 models,
200 currentModelId: models.some((model) => model.id === boundedCurrentModelId)
@@ -236,6 +256,7 @@ export function acpRegistryProbeResult(
256 const liveConfiguration = normalizeAcpRegistryLiveConfiguration(
257 started.sessionSetupResult.configOptions ?? [],
258 parseSessionModeState(started.sessionSetupResult),
259 + started.sessionSetupResult.models,
260 );
261 return AcpRegistryProbeResult.make({
262 instanceId,
packages/provider-acp/src/server/adapter.ts
+34 -9
@@ -217,6 +217,7 @@ export interface AcpAdapterV2Flavor {
217 readonly onSessionConfigurationUpdate?: (
218 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
219 modeState: AcpSessionModeState | undefined,
220 + modelState: EffectAcpSchema.SessionModelState | null | undefined,
221 ) => Effect.Effect<void>;
222 readonly onUrlElicitation?: (input: {
223 readonly elicitationId: string;
@@ -231,6 +232,7 @@ export interface AcpAdapterV2Flavor {
232 EffectAcpErrors.AcpError,
233 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
234 >;
235 + readonly customModels?: ReadonlyArray<string>;
236 readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
237 readonly getModelContextWindow?: (
238 selection: ModelSelection,
@@ -516,14 +518,15 @@ function negotiatedCapabilities(
518 const agent = started.initializeResult.agentCapabilities ?? {};
519 const session = agent.sessionCapabilities;
520 const setup = started.sessionSetupResult;
519 - const hasModelConfig = findModelConfigOption(setup.configOptions) !== undefined;
521 + const canSwitchModel =
522 + findModelConfigOption(setup.configOptions) !== undefined || setup.models != null;
523 const canLoad = agent.loadSession === true;
524 const canFork = session?.fork != null;
525 return {
526 ...base,
527 sessions: {
528 ...base.sessions,
526 - supportsModelSwitchInSession: hasModelConfig,
529 + supportsModelSwitchInSession: canSwitchModel,
530 },
531 threads: {
532 ...base.threads,
@@ -5129,6 +5132,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5132 flavor.onSessionConfigurationUpdate?.(
5133 yield* runtime.getConfigOptions,
5134 yield* runtime.getModeState,
5135 + (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
5136 ) ?? Effect.void
5137 );
5138 }
@@ -5904,13 +5908,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5908 startResult,
5909 modelSelection,
5910 });
5907 - } else if (
5908 - requestedModel.length > 0 &&
5909 - requestedModel !== "auto" &&
5910 - requestedModel !== "default"
5911 - ) {
5912 - if (findModelConfigOption(startResult.sessionSetupResult.configOptions) !== undefined) {
5913 - yield* runtime.setModel(requestedModel);
5911 + } else if (requestedModel.length > 0) {
5912 + // Stored catalog choices can expire; explicitly configured custom IDs
5913 + // are validated by the agent instead.
5914 + const isCustomModel = flavor.customModels?.includes(requestedModel) === true;
5915 + const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
5916 + const modelState = startResult.sessionSetupResult.models;
5917 + if (modelOption?.type === "select") {
5918 + if (
5919 + isCustomModel ||
5920 + modelOption.options.some((entry) =>
5921 + "value" in entry
5922 + ? entry.value === requestedModel
5923 + : entry.options.some((choice) => choice.value === requestedModel),
5924 + )
5925 + ) {
5926 + yield* runtime.setConfigOption(modelOption.id, requestedModel);
5927 + appliedModel = requestedModel;
5928 + }
5929 + } else if (
5930 + modelState != null &&
5931 + (isCustomModel ||
5932 + modelState.availableModels.some((model) => model.modelId === requestedModel))
5933 + ) {
5934 + if (modelState.currentModelId !== requestedModel) {
5935 + yield* runtime.setSessionModel(requestedModel);
5936 + }
5937 + appliedModel = requestedModel;
5938 }
5939 }
5940 if (appliedModel !== undefined) {
@@ -6078,6 +6102,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6102 flavor.onSessionConfigurationUpdate?.(
6103 yield* runtime.getConfigOptions,
6104 yield* runtime.getModeState,
6105 + (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
6106 ) ?? Effect.void
6107 );
6108 });