Skip to content
TypeScript

fix(acp): explain rejected model selections (#19699)

Wout Stiens04ab2fca4bcb
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 8cdcbaff204..85048cfbebc 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -47,7 +47,10 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
-import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
+import {
+ knownProviderFailureMessage,
+ makeProviderFailure,
+} from "@t3tools/provider-core/server/failure";
import * as RunExecutionService from "./RunExecutionService.ts";
import * as RuntimePolicy from "./RuntimePolicy.ts";
import {
@@ -569,11 +572,12 @@ export const layer: Layer.Layer<
failure: makeProviderFailure({
cause: failed.error,
message:
- nestedCause instanceof Error
+ knownProviderFailureMessage(failed.error) ??
+ (nestedCause instanceof Error
? nestedCause.message
: typeof nestedCause === "string"
? nestedCause
- : failed.error.message,
+ : failed.error.message),
class: "provider_error",
}),
},
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
index 2573e896690..c62e6e8e5b3 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
@@ -1,13 +1,23 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
-import type {
- OrchestrationV2DomainEvent,
- ProviderReplayEntry,
- ProviderReplayTranscript,
+import {
+ ProviderDriverKind,
+ ProviderInstanceId,
+ type OrchestrationV2DomainEvent,
+ type ProviderReplayEntry,
+ type ProviderReplayTranscript,
} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Path from "effect/Path";
+import * as Stream from "effect/Stream";
+import { TestClock } from "effect/testing";
+
+import * as EffectWorker from "../EffectWorker.ts";
+import * as Orchestrator from "../Orchestrator.ts";
import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
@@ -31,12 +41,14 @@ import { messageRestartInput } from "./fixtures/message_steering/input.ts";
import {
assertProviderNativeSubagentRootTurns,
materializeFixtureInput,
+ SIMPLE_PROMPT,
projectionFor,
type OrchestratorFixtureInput,
type ProviderOrchestratorReplayVariant,
} from "./fixtures/shared.ts";
import {
runOrchestratorV2ProviderReplayScenario,
+ layerProviderReplay,
type OrchestratorV2ProviderReplayHarness,
} from "./ProviderReplayHarness.ts";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
@@ -232,6 +244,185 @@ function runFixtureProviderWithRegisteredHarness(input: {
}
describe("orchestrator replay fixtures", () => {
+ it.effect.each([
+ { name: "open", firstTurn: false, code: -32602 },
+ { name: "switch", firstTurn: true, code: -32602 },
+ { name: "authentication", firstTurn: false, code: -32000 },
+ ])("preserves the ACP model-write $name failure through orchestration", (testCase) =>
+ Effect.gen(function* () {
+ const name = `acp_model_write_${testCase.name}`;
+ const sessionId = "grok-replay-session-1";
+ const rejectedModel = "replay-model-b";
+ const modelSelection = {
+ instanceId: ProviderInstanceId.make("acpRegistry"),
+ model: rejectedModel,
+ };
+ const recorded = yield* readTranscript(
+ new URL("./fixtures/simple/registry_transcript.ndjson", import.meta.url),
+ );
+ const sessionIndex = recorded.entries.findIndex(
+ (entry) => "label" in entry && entry.label === "session.created",
+ );
+ assert.isAtLeast(sessionIndex, 0);
+ const transcript = {
+ ...recorded,
+ scenario: name,
+ entries: [
+ ...recorded.entries.slice(0, sessionIndex),
+ {
+ type: "emit_inbound",
+ label: "session.created",
+ frame: {
+ kind: "response",
+ method: "session/new",
+ result: {
+ sessionId,
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ category: "model",
+ type: "select",
+ currentValue: "replay-model-a",
+ options: [
+ { value: "replay-model-a", name: "Model A" },
+ { value: rejectedModel, name: "Model B" },
+ ],
+ },
+ ],
+ },
+ },
+ },
+ ...(testCase.firstTurn
+ ? recorded.entries
+ .slice(sessionIndex + 1)
+ .filter((entry) => entry.type !== "runtime_exit")
+ : []),
+ {
+ type: "expect_outbound",
+ label: "session.set_model",
+ frame: {
+ kind: "request",
+ method: "session/set_config_option",
+ params: { sessionId, configId: "model", value: rejectedModel },
+ },
+ },
+ {
+ type: "emit_inbound",
+ label: "session.set_model.rejected",
+ frame: {
+ kind: "response",
+ method: "session/set_config_option",
+ error: {
+ code: testCase.code,
+ message: testCase.code === -32602 ? "Invalid provider" : "Authentication required",
+ },
+ },
+ },
+ ],
+ } satisfies ProviderReplayTranscript;
+ const materialized = yield* materializeFixtureInput({
+ scenario: name,
+ fixtureInput: {
+ steps: Array.from({ length: testCase.firstTurn ? 2 : 1 }, () => ({
+ type: "message" as const,
+ text: SIMPLE_PROMPT,
+ })),
+ },
+ driver: ProviderDriverKind.make("acpRegistry"),
+ modelSelection: {
+ ...modelSelection,
+ model: testCase.firstTurn ? "replay-model-a" : rejectedModel,
+ },
+ });
+ const scenario = {
+ ...materialized,
+ name,
+ transcript: yield* AcpRegistryOrchestratorReplayHarness.decodeTranscript(
+ materializeReplayTranscriptRuntimeInstructions(transcript, {
+ driver: ProviderDriverKind.make("acpRegistry"),
+ model: "replay-model-a",
+ }),
+ ),
+ runtimePolicyOverride: { cwd: yield* checkpointWorkspace(name) },
+ };
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ if (testCase.firstTurn) yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);
+ for (const [index, command] of materialized.commands.entries()) {
+ const isFirstTurn =
+ testCase.firstTurn && command.type === "message.dispatch" && index === 1;
+ yield* orchestrator.dispatch(
+ command.type === "message.dispatch" && !isFirstTurn
+ ? { ...command, modelSelection }
+ : command,
+ );
+ if (isFirstTurn) {
+ // Wait for the committed terminal event before switching models.
+ yield* orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) => event.type === "run.updated" && event.payload.status === "completed",
+ ),
+ Stream.runHead,
+ );
+ }
+ }
+ if (testCase.firstTurn) {
+ yield* orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) => event.type === "run.updated" && event.payload.status === "failed",
+ ),
+ Stream.runHead,
+ );
+ } else {
+ // Failed opens retry on the outbox schedule. Advance to each recorded
+ // deadline, draining effects instead of polling the projection.
+ for (let attempt = 0; attempt < 10; attempt++) {
+ yield* worker.drain();
+ const next = yield* worker.nextClaimableAt;
+ if (Option.isNone(next)) break;
+ const now = yield* DateTime.now;
+ yield* TestClock.adjust(
+ Math.max(0, DateTime.toEpochMillis(next.value) - DateTime.toEpochMillis(now)),
+ );
+ }
+ }
+ const projection = yield* orchestrator.getThreadProjection(
+ materialized.projectionThreadIds[0]!,
+ );
+ assert.deepEqual(
+ projection.runs.map((run) => run.status),
+ testCase.firstTurn ? ["completed", "failed"] : ["failed"],
+ );
+ const errors = projection.turnItems.filter((item) => item.type === "error");
+ assert.lengthOf(errors, 1);
+ assert.equal(errors[0]?.failure.class, "provider_error");
+ if (testCase.code === -32602) {
+ assert.equal(
+ errors[0]?.failure.message,
+ 'The agent did not accept the model "replay-model-b". Choose another model for this provider, then retry.',
+ );
+ } else {
+ assert.match(
+ errors[0]?.failure.message ?? "",
+ /^Failed to open acpRegistry provider session \S+\.$/u,
+ );
+ }
+ }).pipe(
+ Effect.provide(
+ layerProviderReplay(scenario, AcpRegistryOrchestratorReplayHarness, {
+ runEffectWorker: false,
+ }),
+ ),
+ );
+ }).pipe(
+ Effect.scoped,
+ provideDeterministicTestRuntime,
+ Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer)),
+ ),
+ );
+
it.effect.each(
ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
fixture.providers.map(
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 21ecde2ef4f..443d0906e19 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -51,6 +51,7 @@ import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
+import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
@@ -204,6 +205,24 @@ export interface AcpAdapterV2ExtensionContext {
readonly lastProposedPlanMarkdown: Effect.Effect<string | undefined>;
}
+/**
+ * Raised when an agent does not accept the session's model selection: the
+ * session's model option does not offer it, or the agent answers the write
+ * with invalid params. `makeProviderFailure` shows its message to the user;
+ * the agent's reply stays on `cause`.
+ */
+class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>()(
+ "AcpModelSelectionError",
+ {
+ model: Schema.String,
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ return `The agent did not accept the model "${this.model}". Choose another model for this provider, then retry.`;
+ }
+}
+
export interface AcpAdapterV2Flavor {
readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
readonly driver: ProviderDriverKind;
@@ -6610,13 +6629,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
) {
yield* Ref.set(activeSelection, null);
const requestedModel = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model;
+ // Invalid params is the agent refusing the value, and the runtime
+ // raises the same code when the session's model option does not offer
+ // it. Other failures, such as sign-in or a lost connection, keep their
+ // own error.
+ const rejectedModel = (error: EffectAcpErrors.AcpError) =>
+ error._tag === "AcpRequestError" && error.code === -32602
+ ? new AcpModelSelectionError({ model: modelSelection.model, cause: error })
+ : error;
let appliedModel: string | undefined;
if (flavor.applyModelSelection !== undefined) {
- appliedModel = yield* flavor.applyModelSelection({
- runtime,
- startResult,
- modelSelection,
- });
+ appliedModel = yield* flavor
+ .applyModelSelection({
+ runtime,
+ startResult,
+ modelSelection,
+ })
+ .pipe(Effect.mapError(rejectedModel));
} else if (requestedModel.length > 0) {
// Stored catalog choices can expire; explicitly configured custom IDs
// are validated by the agent instead.
@@ -6632,7 +6661,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
: entry.options.some((choice) => choice.value === requestedModel),
)
) {
- yield* runtime.setConfigOption(modelOption.id, requestedModel);
+ yield* runtime
+ .setConfigOption(modelOption.id, requestedModel)
+ .pipe(Effect.mapError(rejectedModel));
appliedModel = requestedModel;
}
} else if (
@@ -6641,7 +6672,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
modelState.availableModels.some((model) => model.modelId === requestedModel))
) {
if (modelState.currentModelId !== requestedModel) {
- yield* runtime.setSessionModel(requestedModel);
+ yield* runtime.setSessionModel(requestedModel).pipe(Effect.mapError(rejectedModel));
}
appliedModel = requestedModel;
}
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts
index 68f9ef675e4..a20aa4a4fe6 100644
--- a/packages/provider-core/src/server/failure.ts
+++ b/packages/provider-core/src/server/failure.ts
@@ -57,10 +57,24 @@ const PROVIDER_FAILURE_REASONS: Record<ProviderAdapterFailureReason, string> = {
attachment_unreadable: "an attachment could not be read",
};
-function causeMessage(cause: unknown): string | undefined {
+/**
+ * Walks a cause chain for curated text without reading arbitrary provider
+ * defect text. `known` is the message of a domain error T3 raised itself;
+ * `category` is the generic message of the innermost provider wrapper seen.
+ */
+function curatedCauseMessages(cause: unknown): {
+ readonly known: string | undefined;
+ readonly category: string | undefined;
+} {
const seen = new Set<unknown>();
let category: (typeof PROVIDER_FAILURE_CATEGORIES)[string];
let reason: string | undefined;
+ const categoryMessage = () => {
+ if (category === undefined) return undefined;
+ return reason
+ ? `${category.summary}: ${reason}. ${category.guidance}`
+ : `${category.summary}. ${category.guidance}`;
+ };
for (let depth = 0; depth < 16 && cause != null && !seen.has(cause); depth++) {
seen.add(cause);
try {
@@ -72,14 +86,19 @@ function causeMessage(cause: unknown): string | undefined {
const tag = (cause as Record<string, unknown>)._tag;
switch (tag) {
case "ContextHandoffBudgetError":
- return new ContextHandoffBudgetError().message;
+ return { known: new ContextHandoffBudgetError().message, category: categoryMessage() };
+ case "AcpModelSelectionError":
case "ClaudeBackgroundWorkBlocksQueryReplacementError":
case "ClaudeAppendSystemPromptFileError":
case "ClaudeAppendSystemPromptMissingValueError":
case "CursorModelUnavailableError":
- return stringField(cause, "message");
+ return { known: stringField(cause, "message"), category: categoryMessage() };
case "ContextHandoffDeliveryUncertainError":
- return "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.";
+ return {
+ known:
+ "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.",
+ category: categoryMessage(),
+ };
case "ProviderAdapterProtocolError": {
const typedReason = (cause as Record<string, unknown>).reason;
if (
@@ -101,10 +120,16 @@ function causeMessage(cause: unknown): string | undefined {
break;
}
}
- if (category === undefined) return undefined;
- return reason
- ? `${category.summary}: ${reason}. ${category.guidance}`
- : `${category.summary}. ${category.guidance}`;
+ return { known: undefined, category: categoryMessage() };
+}
+
+/**
+ * The curated message of a domain error in a failure's cause chain, if any.
+ * Callers that pass their own `message` to `makeProviderFailure` check it
+ * first, so a known reason is not hidden behind a wrapper's text.
+ */
+export function knownProviderFailureMessage(cause: unknown): string | undefined {
+ return curatedCauseMessages(cause).known;
}
function stringField(value: unknown, key: "message" | "code"): string | undefined {
@@ -183,7 +208,9 @@ export function makeProviderFailure(input: {
readonly retryable?: boolean | null;
readonly resetAt?: string | null;
}): OrchestrationV2ProviderFailure {
- const rawMessage = input.message ?? causeMessage(input.cause) ?? DEFAULT_PROVIDER_FAILURE_MESSAGE;
+ const curated = curatedCauseMessages(input.cause);
+ const rawMessage =
+ input.message ?? curated.known ?? curated.category ?? DEFAULT_PROVIDER_FAILURE_MESSAGE;
const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
const code =