@devries-cameron20 / t3code-1 / commits / 78c6de4dba
Fork 0

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

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

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Oct 20, 2026 at 02:04 UTC 78c6de4dbac742a34a24d34074f93d60f2080cf0
8 files changed +201 -84
apps/server/scripts/acp-replay-agent.ts
+23 -25
@@ -138,11 +138,6 @@ function stopWithFailure(detail: string, actual?: unknown): void {
138 process.stdin.pause();
139 }
140
141 -function advance(): void {
142 - cursor += 1;
143 - writeStatus();
144 -}
145 -
141 function send(message: JsonRpcMessage): void {
142 process.stdout.write(`${JSON.stringify(message)}\n`);
143 }
@@ -182,56 +177,57 @@ function materializeInbound(value: unknown): unknown {
177 );
178 }
179
185 -function emitInbound(recorded: LogicalFrame): void {
180 +function inboundMessage(recorded: LogicalFrame): JsonRpcMessage | undefined {
181 const frame = materializeInbound(recorded) as LogicalFrame;
182 switch (frame.kind) {
183 case "notification":
189 - send({
184 + return {
185 jsonrpc: "2.0",
186 method: frame.method,
187 ...(frame.params === undefined ? {} : { params: frame.params }),
193 - });
194 - return;
188 + };
189 case "request": {
190 const id = nextAgentRequestId;
191 nextAgentRequestId += 1;
192 pendingAgentRequestMethods.set(String(id), frame.method);
199 - send({
193 + return {
194 jsonrpc: "2.0",
195 id,
196 method: frame.method,
197 ...(frame.params === undefined ? {} : { params: frame.params }),
198 headers: [],
205 - });
206 - return;
199 + };
200 }
201 case "response": {
202 const id = pendingClientRequestId(frame.method);
203 if (id === undefined) {
204 stopWithFailure(`No pending client request for ${frame.method}`, frame);
212 - return;
205 + return undefined;
206 }
207 pendingClientRequestIds.delete(frame.method);
215 - send({
208 + return {
209 jsonrpc: "2.0",
210 id,
211 ...(frame.result === undefined ? {} : { result: frame.result }),
212 ...(frame.error === undefined ? {} : { error: frame.error }),
220 - });
213 + };
214 }
215 }
216 }
217
218 +// T3 may kill the agent after its last reply. Record the batch, including trailing
219 +// runtime exits, before publishing any frames.
220 function flushInbound(): void {
221 + const messages: Array<JsonRpcMessage> = [];
222 while (!stopped) {
223 const entry = transcript.entries[cursor];
228 - if (entry === undefined || entry.type === "expect_outbound") return;
224 + if (entry === undefined || entry.type === "expect_outbound") break;
225 if (entry.type === "runtime_exit") {
226 if (entry.status !== "success" && entry.status !== "cancelled") {
227 stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
232 - return;
228 + break;
229 }
234 - advance();
230 + cursor += 1;
231 continue;
232 }
233 const frame = entry.frame as LogicalFrame;
@@ -242,12 +238,15 @@ function flushInbound(): void {
238 typeof frame.method !== "string"
239 ) {
240 stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
245 - return;
241 + break;
242 }
247 - emitInbound(frame);
248 - if (stopped) return;
249 - advance();
243 + const message = inboundMessage(frame);
244 + if (message === undefined) break;
245 + messages.push(message);
246 + cursor += 1;
247 }
248 + if (!stopped) writeStatus();
249 + messages.forEach(send);
250 }
251
252 function handleMessage(message: JsonRpcMessage): void {
@@ -259,6 +258,7 @@ function handleMessage(message: JsonRpcMessage): void {
258 }
259 const entry = transcript.entries[cursor];
260 if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
261 + stopWithFailure("Unexpected outbound ACP frame", actual);
262 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
263 send({
264 jsonrpc: "2.0",
@@ -266,7 +266,6 @@ function handleMessage(message: JsonRpcMessage): void {
266 error: { code: -32603, message: "ACP replay frame mismatch" },
267 });
268 }
269 - stopWithFailure("Unexpected outbound ACP frame", actual);
269 return;
270 }
271 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
@@ -274,11 +273,10 @@ function handleMessage(message: JsonRpcMessage): void {
273 } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
274 pendingAgentRequestMethods.delete(String(message.id));
275 }
277 - advance();
276 + cursor += 1;
277 flushInbound();
278 }
279
281 -writeStatus();
280 flushInbound();
281
282 const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+130 -14
@@ -2,8 +2,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
4 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
5 +import * as Cause from "effect/Cause";
6 import * as Deferred from "effect/Deferred";
7 import * as Effect from "effect/Effect";
8 +import * as Exit from "effect/Exit";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
@@ -39,6 +41,7 @@ import {
41 ACP_REGISTRY_PROVIDER,
42 makeAcpRegistryAdapterV2,
43 acpRegistryPromptFailure,
44 + acpRegistryProbeResult,
45 } from "@t3tools/provider-acp-registry/testing";
46
47 const registryUrl = "https://registry.test/registry.json";
@@ -140,7 +143,7 @@ describe("AcpRegistryAdapterV2", () => {
143 });
144 });
145
143 - describe("the agent's own mode picker", () => {
146 + describe("applying a stored selection to a scripted agent", () => {
147 type Frame = Record<string, unknown>;
148 const outbound = (method: string, params: unknown = "<any>"): Frame => ({
149 type: "expect_outbound",
@@ -150,6 +153,8 @@ describe("AcpRegistryAdapterV2", () => {
153 type: "emit_inbound",
154 frame: { kind: "response", method, result },
155 });
156 + const assertOpened = (opened: Exit.Exit<void, unknown>) =>
157 + assert.isTrue(Exit.isSuccess(opened));
158 const permissionModeOption = (currentValue: string) => ({
159 id: "permission-mode",
160 name: "Permission mode",
@@ -159,10 +164,11 @@ describe("AcpRegistryAdapterV2", () => {
164 options: ["ask", "auto"].map((value) => ({ value, name: value })),
165 });
166
162 - const openWithStoredModePick = Effect.fn("openWithStoredModePick")(function* (input: {
167 + const openWithStoredSelection = Effect.fn("openWithStoredSelection")(function* (input: {
168 readonly setup: unknown;
164 - readonly modeFrames: ReadonlyArray<Frame>;
165 - readonly storedModePick: string;
169 + readonly selectionFrames: ReadonlyArray<Frame>;
170 + readonly model?: string;
171 + readonly storedModePick?: string;
172 }) {
173 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
174 const fileSystem = yield* FileSystem.FileSystem;
@@ -186,7 +192,7 @@ describe("AcpRegistryAdapterV2", () => {
192 }),
193 outbound("session/new"),
194 answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }),
189 - ...input.modeFrames,
195 + ...input.selectionFrames,
196 ] as never,
197 },
198 ACP_REGISTRY_PROVIDER,
@@ -210,14 +216,16 @@ describe("AcpRegistryAdapterV2", () => {
216 fileSystem,
217 }),
218 }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
213 - yield* adapter
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,
219 - model: "default",
220 - options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }],
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",
@@ -225,30 +233,31 @@ describe("AcpRegistryAdapterV2", () => {
233 cwd: replayDir,
234 }),
235 })
228 - .pipe(Effect.scoped);
236 + .pipe(Effect.asVoid, Effect.scoped, Effect.exit);
237 yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
238 + return opened;
239 });
240
241 it.effect("switches an agent that only advertises modes with session/set_mode", () =>
233 - openWithStoredModePick({
242 + openWithStoredSelection({
243 setup: {
244 modes: {
245 currentModeId: "default",
246 availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })),
247 },
248 },
240 - modeFrames: [
249 + selectionFrames: [
250 outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }),
251 answer("session/set_mode", {}),
252 ],
253 storedModePick: "autoEdit",
245 - }).pipe(Effect.provide(layerTest), Effect.scoped),
254 + }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
255 );
256
257 it.effect("switches a mode config option under its own id", () =>
249 - openWithStoredModePick({
258 + openWithStoredSelection({
259 setup: { configOptions: [permissionModeOption("ask")] },
251 - modeFrames: [
260 + selectionFrames: [
261 outbound("session/set_config_option", {
262 sessionId: "agent-session",
263 configId: "permission-mode",
@@ -257,6 +266,113 @@ describe("AcpRegistryAdapterV2", () => {
266 answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
267 ],
268 storedModePick: "auto",
269 + }).pipe(Effect.map(assertOpened), Effect.provide(layerTest), Effect.scoped),
270 + );
271 +
272 + const modelOptions = [
273 + { id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false },
274 + {
275 + id: " ",
276 + name: "Unnamed",
277 + category: "model",
278 + type: "select",
279 + currentValue: "unaddressable",
280 + options: [{ value: "unaddressable", name: "Unaddressable" }],
281 + },
282 + {
283 + id: "provider",
284 + name: "Provider",
285 + category: "model",
286 + type: "select",
287 + currentValue: "gateway",
288 + options: [
289 + {
290 + group: "hosted",
291 + name: "Hosted",
292 + options: [
293 + { value: "gateway", name: "Gateway" },
294 + { value: "codex", name: "Codex" },
295 + ],
296 + },
297 + ],
298 + },
299 + {
300 + id: "model",
301 + name: "Model",
302 + category: "model",
303 + type: "select",
304 + currentValue: "later-model",
305 + options: [{ value: "later-model", name: "Later model" }],
306 + },
307 + ] as const;
308 +
309 + it.effect("opens a model from the catalog by writing the first usable model select", () =>
310 + Effect.gen(function* () {
311 + const setup = { sessionId: "agent-session", configOptions: modelOptions };
312 + const catalog = acpRegistryProbeResult(ProviderInstanceId.make("acp-registry-mode-pick"), {
313 + sessionId: setup.sessionId,
314 + initializeResult: { protocolVersion: 1 },
315 + sessionSetupResult: {
316 + ...setup,
317 + // The catalog uses the normalized groupId; ACP v1 sends group on the wire.
318 + configOptions: modelOptions.map((option) =>
319 + option.id === "provider"
320 + ? {
321 + ...option,
322 + options: [{ ...option.options[0], groupId: option.options[0].group }],
323 + }
324 + : option,
325 + ),
326 + },
327 + modelConfigId: "provider",
328 + });
329 + assert.deepEqual(catalog.models, [
330 + { id: "gateway", name: "Gateway", description: null },
331 + { id: "codex", name: "Codex", description: null },
332 + ]);
333 + assert.equal(catalog.currentModelId, "gateway");
334 + const model = catalog.models[1]?.id;
335 + assert.isDefined(model);
336 + const opened = yield* openWithStoredSelection({
337 + setup,
338 + selectionFrames: [
339 + outbound("session/set_config_option", {
340 + sessionId: "agent-session",
341 + configId: "provider",
342 + value: "codex",
343 + }),
344 + answer("session/set_config_option", {
345 + configOptions: modelOptions.map((option) =>
346 + option.id === "provider" ? { ...option, currentValue: "codex" } : option,
347 + ),
348 + }),
349 + ],
350 + model,
351 + });
352 + assertOpened(opened);
353 + }).pipe(Effect.provide(layerTest), Effect.scoped),
354 + );
355 +
356 + it.effect("rejects a later-option model before writing any configuration", () =>
357 + Effect.gen(function* () {
358 + const opened = yield* openWithStoredSelection({
359 + 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 + },
375 + });
376 }).pipe(Effect.provide(layerTest), Effect.scoped),
377 );
378 });
packages/provider-acp-registry/src/server/probe.ts
+15 -22
@@ -25,8 +25,14 @@ import type * as EffectAcpSchema from "effect-acp/compat";
25
26 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
27 import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
28 -import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
29 -import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
28 +import {
29 + findModelConfigOption,
30 + parseSessionModeState,
31 +} from "@t3tools/provider-acp/server/runtimeModel";
32 +import {
33 + acpProviderOptionDescriptors,
34 + flattenSelectChoices,
35 +} from "@t3tools/provider-acp/server/sessionConfig";
36 import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
37 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
38
@@ -53,23 +59,12 @@ export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
59 return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
60 }
61
56 -function modelConfigOptions(
57 - configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
58 -): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
59 - return (configOptions ?? []).flatMap((option) => {
60 - if (option.category !== "model" || option.type !== "select") return [];
61 - return option.options.flatMap((candidate) =>
62 - "value" in candidate ? [candidate] : candidate.options,
63 - );
64 - });
65 -}
66 -
62 function normalizeModels(
68 - configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
63 + modelChoices: ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption>,
64 ): ReadonlyArray<AcpRegistryProbeModel> {
65 // Model discovery is the model config option's base models; ACP has no
66 // other portable model inventory.
72 - const candidates = modelConfigOptions(configOptions).map((model) => ({
67 + const candidates = modelChoices.map((model) => ({
68 id: model.value,
69 name: model.name,
70 description: model.description ?? null,
@@ -174,14 +169,12 @@ export function normalizeAcpRegistryLiveConfiguration(
169 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
170 modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
171 ): AcpRegistryLiveConfiguration {
177 - const modelOption = configOptions.find(
178 - (option) => option.category === "model" && option.type === "select",
179 - );
172 + const modelOption = findModelConfigOption(configOptions);
173 const boundedCurrentModelId =
181 - modelOption?.type === "select"
182 - ? (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null)
183 - : null;
184 - const models = normalizeModels(configOptions);
174 + modelOption === undefined
175 + ? null
176 + : (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null);
177 + const models = normalizeModels(flattenSelectChoices(modelOption?.options ?? []));
178 return {
179 models,
180 currentModelId: models.some((model) => model.id === boundedCurrentModelId)
packages/provider-acp/src/server/AcpSessionRuntime.ts
+7 -2
@@ -36,6 +36,7 @@ import {
36 collectSessionConfigOptionValues,
37 decideToolCallUpdateEmission,
38 extractModelConfigId,
39 + findModelConfigOption,
40 findSessionConfigOption,
41 mergeToolCallState,
42 toolCallProgressLength,
@@ -1818,7 +1819,8 @@ export const make = (
1819 value: string | boolean,
1820 ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
1821 Effect.gen(function* () {
1821 - const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
1822 + const configOptions = yield* Ref.get(configOptionsRef);
1823 + const configOption = findSessionConfigOption(configOptions, configId);
1824 if (!configOption) {
1825 return;
1826 }
@@ -1851,7 +1853,10 @@ export const make = (
1853 if (allowedValues.includes(value)) {
1854 return;
1855 }
1854 - if (configOption.category === "model" && options.customModels?.includes(value)) {
1856 + if (
1857 + configOption === findModelConfigOption(configOptions) &&
1858 + options.customModels?.includes(value)
1859 + ) {
1860 return;
1861 }
1862 return yield* new EffectAcpErrors.AcpRequestError({
packages/provider-acp/src/server/adapter.ts
+3 -7
@@ -67,6 +67,7 @@ import {
67 acpContentBlockDisplayText,
68 embeddedTerminalIdsFromSessionUpdate,
69 extractMcpToolCallIdentity,
70 + findModelConfigOption,
71 mergeToolCallState,
72 parsePermissionRequest,
73 parseSessionUpdateEvent,
@@ -515,8 +516,7 @@ function negotiatedCapabilities(
516 const agent = started.initializeResult.agentCapabilities ?? {};
517 const session = agent.sessionCapabilities;
518 const setup = started.sessionSetupResult;
518 - const hasModelConfig =
519 - setup.configOptions?.some((option) => option.category === "model") === true;
519 + const hasModelConfig = findModelConfigOption(setup.configOptions) !== undefined;
520 const canLoad = agent.loadSession === true;
521 const canFork = session?.fork != null;
522 return {
@@ -5902,11 +5902,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5902 requestedModel !== "auto" &&
5903 requestedModel !== "default"
5904 ) {
5905 - const hasModelConfig =
5906 - startResult.sessionSetupResult.configOptions?.some(
5907 - (option) => option.category === "model",
5908 - ) === true;
5909 - if (hasModelConfig) {
5905 + if (findModelConfigOption(startResult.sessionSetupResult.configOptions) !== undefined) {
5906 yield* runtime.setModel(requestedModel);
5907 }
5908 }
packages/provider-acp/src/server/runtimeModel.ts
+16 -8
@@ -398,15 +398,23 @@ type AcpToolCallUpdate = Extract<
398 { readonly sessionUpdate: "tool_call" | "tool_call_update" }
399 >;
400
401 +type AcpSelectConfigOption = Extract<
402 + EffectAcpSchema.SessionConfigOption,
403 + { readonly type: "select" }
404 +>;
405 +
406 +// ACP resolves options in the same category by array order.
407 +export function findModelConfigOption(
408 + configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
409 +): AcpSelectConfigOption | undefined {
410 + return configOptions?.find(
411 + (option): option is AcpSelectConfigOption =>
412 + option.category === "model" && option.type === "select" && option.id.trim().length > 0,
413 + );
414 +}
415 +
416 export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
402 - const configOptions = sessionResponse.configOptions;
403 - if (!configOptions) return undefined;
404 - for (const opt of configOptions) {
405 - if (opt.category === "model" && opt.id.trim().length > 0) {
406 - return opt.id.trim();
407 - }
408 - }
409 - return undefined;
417 + return findModelConfigOption(sessionResponse.configOptions)?.id.trim();
418 }
419
420 export function findSessionConfigOption(
packages/provider-acp/src/server/sessionConfig.ts
+1 -1
@@ -26,7 +26,7 @@ const boundedOpaqueValue = (value: string, maximumLength: number): string | unde
26 const choiceId = (value: string): string | undefined =>
27 value === "" ? ACP_EMPTY_OPTION_VALUE : boundedOpaqueValue(value, MAX_TEXT_LENGTH);
28
29 -function flattenSelectChoices(
29 +export function flattenSelectChoices(
30 options: EffectAcpSchema.SessionConfigSelectOptions,
31 ): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
32 return options.flatMap((candidate) => ("value" in candidate ? [candidate] : candidate.options));
packages/provider-grok/src/server/adapter.ts
+6 -5
@@ -56,7 +56,10 @@ import {
56 } from "./xaiAcpExtension.ts";
57 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
58 import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
59 -import { sessionModelStateFromInitialize } from "@t3tools/provider-acp/server/runtimeModel";
59 +import {
60 + findModelConfigOption,
61 + sessionModelStateFromInitialize,
62 +} from "@t3tools/provider-acp/server/runtimeModel";
63 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
64 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
65 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -265,16 +268,14 @@ export function makeGrokAcpAdapterFlavor(
268 Effect.gen(function* () {
269 const legacy = startResult.initializeResult.protocolVersion === 1;
270 const options = legacy ? [] : yield* runtime.getConfigOptions;
268 - const configuredModel = options.find((option) => option.category === "model")?.currentValue;
271 + const configuredModel = findModelConfigOption(options)?.currentValue;
272 return yield* applyGrokAcpModelSelection({
273 runtime: legacy
274 ? runtime
275 : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
276 currentModelId: legacy
277 ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)
275 - : typeof configuredModel === "string"
276 - ? configuredModel
277 - : undefined,
278 + : configuredModel,
279 requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),
280 mapError: (cause) => cause,
281 });