Skip to content
TypeScript

fix(acp): keep model discovery and selection on the same option (#19567)

Wout Stiens78c6de4dbac7
diff --git a/apps/server/scripts/acp-replay-agent.ts b/apps/server/scripts/acp-replay-agent.ts
index 1d6730bec93..351cfa131e2 100644
--- a/apps/server/scripts/acp-replay-agent.ts
+++ b/apps/server/scripts/acp-replay-agent.ts
@@ -138,11 +138,6 @@ function stopWithFailure(detail: string, actual?: unknown): void {
process.stdin.pause();
}
-function advance(): void {
- cursor += 1;
- writeStatus();
-}
-
function send(message: JsonRpcMessage): void {
process.stdout.write(`${JSON.stringify(message)}\n`);
}
@@ -182,56 +177,57 @@ function materializeInbound(value: unknown): unknown {
);
}
-function emitInbound(recorded: LogicalFrame): void {
+function inboundMessage(recorded: LogicalFrame): JsonRpcMessage | undefined {
const frame = materializeInbound(recorded) as LogicalFrame;
switch (frame.kind) {
case "notification":
- send({
+ return {
jsonrpc: "2.0",
method: frame.method,
...(frame.params === undefined ? {} : { params: frame.params }),
- });
- return;
+ };
case "request": {
const id = nextAgentRequestId;
nextAgentRequestId += 1;
pendingAgentRequestMethods.set(String(id), frame.method);
- send({
+ return {
jsonrpc: "2.0",
id,
method: frame.method,
...(frame.params === undefined ? {} : { params: frame.params }),
headers: [],
- });
- return;
+ };
}
case "response": {
const id = pendingClientRequestId(frame.method);
if (id === undefined) {
stopWithFailure(`No pending client request for ${frame.method}`, frame);
- return;
+ return undefined;
}
pendingClientRequestIds.delete(frame.method);
- send({
+ return {
jsonrpc: "2.0",
id,
...(frame.result === undefined ? {} : { result: frame.result }),
...(frame.error === undefined ? {} : { error: frame.error }),
- });
+ };
}
}
}
+// T3 may kill the agent after its last reply. Record the batch, including trailing
+// runtime exits, before publishing any frames.
function flushInbound(): void {
+ const messages: Array<JsonRpcMessage> = [];
while (!stopped) {
const entry = transcript.entries[cursor];
- if (entry === undefined || entry.type === "expect_outbound") return;
+ if (entry === undefined || entry.type === "expect_outbound") break;
if (entry.type === "runtime_exit") {
if (entry.status !== "success" && entry.status !== "cancelled") {
stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
- return;
+ break;
}
- advance();
+ cursor += 1;
continue;
}
const frame = entry.frame as LogicalFrame;
@@ -242,12 +238,15 @@ function flushInbound(): void {
typeof frame.method !== "string"
) {
stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
- return;
+ break;
}
- emitInbound(frame);
- if (stopped) return;
- advance();
+ const message = inboundMessage(frame);
+ if (message === undefined) break;
+ messages.push(message);
+ cursor += 1;
}
+ if (!stopped) writeStatus();
+ messages.forEach(send);
}
function handleMessage(message: JsonRpcMessage): void {
@@ -259,6 +258,7 @@ function handleMessage(message: JsonRpcMessage): void {
}
const entry = transcript.entries[cursor];
if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
+ stopWithFailure("Unexpected outbound ACP frame", actual);
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
send({
jsonrpc: "2.0",
@@ -266,7 +266,6 @@ function handleMessage(message: JsonRpcMessage): void {
error: { code: -32603, message: "ACP replay frame mismatch" },
});
}
- stopWithFailure("Unexpected outbound ACP frame", actual);
return;
}
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
@@ -274,11 +273,10 @@ function handleMessage(message: JsonRpcMessage): void {
} else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
pendingAgentRequestMethods.delete(String(message.id));
}
- advance();
+ cursor += 1;
flushInbound();
}
-writeStatus();
flushInbound();
const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
index 565a3cac2f1..6b27625e1e6 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
@@ -2,8 +2,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
+import * as Cause from "effect/Cause";
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";
@@ -39,6 +41,7 @@ import {
ACP_REGISTRY_PROVIDER,
makeAcpRegistryAdapterV2,
acpRegistryPromptFailure,
+ acpRegistryProbeResult,
} from "@t3tools/provider-acp-registry/testing";
const registryUrl = "https://registry.test/registry.json";
@@ -140,7 +143,7 @@ describe("AcpRegistryAdapterV2", () => {
});
});
- describe("the agent's own mode picker", () => {
+ describe("applying a stored selection to a scripted agent", () => {
type Frame = Record<string, unknown>;
const outbound = (method: string, params: unknown = "<any>"): Frame => ({
type: "expect_outbound",
@@ -150,6 +153,8 @@ 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",
@@ -159,10 +164,11 @@ describe("AcpRegistryAdapterV2", () => {
options: ["ask", "auto"].map((value) => ({ value, name: value })),
});
- const openWithStoredModePick = Effect.fn("openWithStoredModePick")(function* (input: {
+ const openWithStoredSelection = Effect.fn("openWithStoredSelection")(function* (input: {
readonly setup: unknown;
- readonly modeFrames: ReadonlyArray<Frame>;
- readonly storedModePick: string;
+ readonly selectionFrames: ReadonlyArray<Frame>;
+ readonly model?: string;
+ readonly storedModePick?: string;
}) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
@@ -186,7 +192,7 @@ describe("AcpRegistryAdapterV2", () => {
}),
outbound("session/new"),
answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }),
- ...input.modeFrames,
+ ...input.selectionFrames,
] as never,
},
ACP_REGISTRY_PROVIDER,
@@ -210,14 +216,16 @@ describe("AcpRegistryAdapterV2", () => {
fileSystem,
}),
}).pipe(Effect.provide(layerInjectedRuntimeCatalog));
- yield* adapter
+ const opened = yield* adapter
.openSession({
threadId: ThreadId.make("thread-acp-registry-mode-pick"),
providerSessionId: ProviderSessionId.make("provider-session-mode-pick"),
modelSelection: {
instanceId,
- model: "default",
- options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }],
+ model: input.model ?? "default",
+ ...(input.storedModePick === undefined
+ ? {}
+ : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
},
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "approval-required",
@@ -225,30 +233,31 @@ describe("AcpRegistryAdapterV2", () => {
cwd: replayDir,
}),
})
- .pipe(Effect.scoped);
+ .pipe(Effect.asVoid, Effect.scoped, Effect.exit);
yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
+ return opened;
});
it.effect("switches an agent that only advertises modes with session/set_mode", () =>
- openWithStoredModePick({
+ openWithStoredSelection({
setup: {
modes: {
currentModeId: "default",
availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })),
},
},
- modeFrames: [
+ selectionFrames: [
outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }),
answer("session/set_mode", {}),
],
storedModePick: "autoEdit",
- }).pipe(Effect.provide(layerTest), Effect.scoped),
+ }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
);
it.effect("switches a mode config option under its own id", () =>
- openWithStoredModePick({
+ openWithStoredSelection({
setup: { configOptions: [permissionModeOption("ask")] },
- modeFrames: [
+ selectionFrames: [
outbound("session/set_config_option", {
sessionId: "agent-session",
configId: "permission-mode",
@@ -257,6 +266,113 @@ describe("AcpRegistryAdapterV2", () => {
answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
],
storedModePick: "auto",
+ }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
+ );
+
+ const modelOptions = [
+ { id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false },
+ {
+ id: " ",
+ name: "Unnamed",
+ category: "model",
+ type: "select",
+ currentValue: "unaddressable",
+ options: [{ value: "unaddressable", name: "Unaddressable" }],
+ },
+ {
+ id: "provider",
+ name: "Provider",
+ category: "model",
+ type: "select",
+ currentValue: "gateway",
+ options: [
+ {
+ group: "hosted",
+ name: "Hosted",
+ options: [
+ { value: "gateway", name: "Gateway" },
+ { value: "codex", name: "Codex" },
+ ],
+ },
+ ],
+ },
+ {
+ id: "model",
+ name: "Model",
+ category: "model",
+ type: "select",
+ currentValue: "later-model",
+ options: [{ value: "later-model", name: "Later model" }],
+ },
+ ] as const;
+
+ it.effect("opens a model from the catalog by writing the first usable model select", () =>
+ Effect.gen(function* () {
+ const setup = { sessionId: "agent-session", configOptions: modelOptions };
+ const catalog = acpRegistryProbeResult(ProviderInstanceId.make("acp-registry-mode-pick"), {
+ sessionId: setup.sessionId,
+ initializeResult: { protocolVersion: 1 },
+ sessionSetupResult: {
+ ...setup,
+ // The catalog uses the normalized groupId; ACP v1 sends group on the wire.
+ configOptions: modelOptions.map((option) =>
+ option.id === "provider"
+ ? {
+ ...option,
+ options: [{ ...option.options[0], groupId: option.options[0].group }],
+ }
+ : option,
+ ),
+ },
+ modelConfigId: "provider",
+ });
+ assert.deepEqual(catalog.models, [
+ { id: "gateway", name: "Gateway", description: null },
+ { id: "codex", name: "Codex", description: null },
+ ]);
+ assert.equal(catalog.currentModelId, "gateway");
+ const model = catalog.models[1]?.id;
+ assert.isDefined(model);
+ const opened = yield* openWithStoredSelection({
+ setup,
+ selectionFrames: [
+ outbound("session/set_config_option", {
+ sessionId: "agent-session",
+ configId: "provider",
+ value: "codex",
+ }),
+ answer("session/set_config_option", {
+ configOptions: modelOptions.map((option) =>
+ option.id === "provider" ? { ...option, currentValue: "codex" } : option,
+ ),
+ }),
+ ],
+ model,
+ });
+ assertOpened(opened);
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
+ it.effect("rejects a later-option model before writing any configuration", () =>
+ Effect.gen(function* () {
+ const opened = yield* openWithStoredSelection({
+ 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",
+ },
+ });
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
});
diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts
index f7ee9f802ec..52bf5f505fc 100644
--- a/packages/provider-acp-registry/src/server/probe.ts
+++ b/packages/provider-acp-registry/src/server/probe.ts
@@ -25,8 +25,14 @@ import type * as EffectAcpSchema from "effect-acp/compat";
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
-import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
-import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
+import {
+ findModelConfigOption,
+ parseSessionModeState,
+} from "@t3tools/provider-acp/server/runtimeModel";
+import {
+ acpProviderOptionDescriptors,
+ flattenSelectChoices,
+} from "@t3tools/provider-acp/server/sessionConfig";
import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
@@ -53,23 +59,12 @@ export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
}
-function modelConfigOptions(
- configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
-): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
- return (configOptions ?? []).flatMap((option) => {
- if (option.category !== "model" || option.type !== "select") return [];
- return option.options.flatMap((candidate) =>
- "value" in candidate ? [candidate] : candidate.options,
- );
- });
-}
-
function normalizeModels(
- configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
+ modelChoices: ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption>,
): ReadonlyArray<AcpRegistryProbeModel> {
// Model discovery is the model config option's base models; ACP has no
// other portable model inventory.
- const candidates = modelConfigOptions(configOptions).map((model) => ({
+ const candidates = modelChoices.map((model) => ({
id: model.value,
name: model.name,
description: model.description ?? null,
@@ -174,14 +169,12 @@ export function normalizeAcpRegistryLiveConfiguration(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
): AcpRegistryLiveConfiguration {
- const modelOption = configOptions.find(
- (option) => option.category === "model" && option.type === "select",
- );
+ const modelOption = findModelConfigOption(configOptions);
const boundedCurrentModelId =
- modelOption?.type === "select"
- ? (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null)
- : null;
- const models = normalizeModels(configOptions);
+ modelOption === undefined
+ ? null
+ : (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null);
+ const models = normalizeModels(flattenSelectChoices(modelOption?.options ?? []));
return {
models,
currentModelId: models.some((model) => model.id === boundedCurrentModelId)
diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts
index 8f40efd164f..424cb79b6b7 100644
--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts
+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts
@@ -36,6 +36,7 @@ import {
collectSessionConfigOptionValues,
decideToolCallUpdateEmission,
extractModelConfigId,
+ findModelConfigOption,
findSessionConfigOption,
mergeToolCallState,
toolCallProgressLength,
@@ -1818,7 +1819,8 @@ export const make = (
value: string | boolean,
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
Effect.gen(function* () {
- const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
+ const configOptions = yield* Ref.get(configOptionsRef);
+ const configOption = findSessionConfigOption(configOptions, configId);
if (!configOption) {
return;
}
@@ -1851,7 +1853,10 @@ export const make = (
if (allowedValues.includes(value)) {
return;
}
- if (configOption.category === "model" && options.customModels?.includes(value)) {
+ if (
+ configOption === findModelConfigOption(configOptions) &&
+ options.customModels?.includes(value)
+ ) {
return;
}
return yield* new EffectAcpErrors.AcpRequestError({
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 633775402f6..0a2b7fa3948 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -67,6 +67,7 @@ import {
acpContentBlockDisplayText,
embeddedTerminalIdsFromSessionUpdate,
extractMcpToolCallIdentity,
+ findModelConfigOption,
mergeToolCallState,
parsePermissionRequest,
parseSessionUpdateEvent,
@@ -515,8 +516,7 @@ function negotiatedCapabilities(
const agent = started.initializeResult.agentCapabilities ?? {};
const session = agent.sessionCapabilities;
const setup = started.sessionSetupResult;
- const hasModelConfig =
- setup.configOptions?.some((option) => option.category === "model") === true;
+ const hasModelConfig = findModelConfigOption(setup.configOptions) !== undefined;
const canLoad = agent.loadSession === true;
const canFork = session?.fork != null;
return {
@@ -5902,11 +5902,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
requestedModel !== "auto" &&
requestedModel !== "default"
) {
- const hasModelConfig =
- startResult.sessionSetupResult.configOptions?.some(
- (option) => option.category === "model",
- ) === true;
- if (hasModelConfig) {
+ if (findModelConfigOption(startResult.sessionSetupResult.configOptions) !== undefined) {
yield* runtime.setModel(requestedModel);
}
}
diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts
index b6f6f1423ce..a2a271e5b9b 100644
--- a/packages/provider-acp/src/server/runtimeModel.ts
+++ b/packages/provider-acp/src/server/runtimeModel.ts
@@ -398,15 +398,23 @@ type AcpToolCallUpdate = Extract<
{ readonly sessionUpdate: "tool_call" | "tool_call_update" }
>;
+type AcpSelectConfigOption = Extract<
+ EffectAcpSchema.SessionConfigOption,
+ { readonly type: "select" }
+>;
+
+// ACP resolves options in the same category by array order.
+export function findModelConfigOption(
+ configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
+): AcpSelectConfigOption | undefined {
+ return configOptions?.find(
+ (option): option is AcpSelectConfigOption =>
+ option.category === "model" && option.type === "select" && option.id.trim().length > 0,
+ );
+}
+
export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
- const configOptions = sessionResponse.configOptions;
- if (!configOptions) return undefined;
- for (const opt of configOptions) {
- if (opt.category === "model" && opt.id.trim().length > 0) {
- return opt.id.trim();
- }
- }
- return undefined;
+ return findModelConfigOption(sessionResponse.configOptions)?.id.trim();
}
export function findSessionConfigOption(
diff --git a/packages/provider-acp/src/server/sessionConfig.ts b/packages/provider-acp/src/server/sessionConfig.ts
index 54609cfbed0..0495d95be49 100644
--- a/packages/provider-acp/src/server/sessionConfig.ts
+++ b/packages/provider-acp/src/server/sessionConfig.ts
@@ -26,7 +26,7 @@ const boundedOpaqueValue = (value: string, maximumLength: number): string | unde
const choiceId = (value: string): string | undefined =>
value === "" ? ACP_EMPTY_OPTION_VALUE : boundedOpaqueValue(value, MAX_TEXT_LENGTH);
-function flattenSelectChoices(
+export function flattenSelectChoices(
options: EffectAcpSchema.SessionConfigSelectOptions,
): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
return options.flatMap((candidate) => ("value" in candidate ? [candidate] : candidate.options));
diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.ts
index 19f1d28c5e8..ea8c3b101c5 100644
--- a/packages/provider-grok/src/server/adapter.ts
+++ b/packages/provider-grok/src/server/adapter.ts
@@ -56,7 +56,10 @@ import {
} from "./xaiAcpExtension.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
-import { sessionModelStateFromInitialize } from "@t3tools/provider-acp/server/runtimeModel";
+import {
+ findModelConfigOption,
+ sessionModelStateFromInitialize,
+} from "@t3tools/provider-acp/server/runtimeModel";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -265,16 +268,14 @@ export function makeGrokAcpAdapterFlavor(
Effect.gen(function* () {
const legacy = startResult.initializeResult.protocolVersion === 1;
const options = legacy ? [] : yield* runtime.getConfigOptions;
- const configuredModel = options.find((option) => option.category === "model")?.currentValue;
+ const configuredModel = findModelConfigOption(options)?.currentValue;
return yield* applyGrokAcpModelSelection({
runtime: legacy
? runtime
: { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
currentModelId: legacy
? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)
- : typeof configuredModel === "string"
- ? configuredModel
- : undefined,
+ : configuredModel,
requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),
mapError: (cause) => cause,
});