Compare commits

...
Author SHA1 Message Date
Mohamed Boudra dc72e6e5a2 test(app): assert the exact plugin toggle name 2026-11-18 19:03:32 +01:00
Mohamed Boudra 872b791aaa fix(app): preserve plugin toggle labels 2026-11-18 19:03:05 +01:00
Mohamed Boudra b242b99340 fix(claude): keep Ultra Code enabled when reopening older sessions 2026-11-18 18:39:13 +01:00
Mohamed Boudra 3a291393ca fix(app): share the draft effort action across controls
Keep the schedule effort picker able to select Ultra Code while schedules use a single effort field.
2026-11-18 18:27:22 +01:00
Mohamed Boudra f12f9ff9f6 fix(claude): let the host translate legacy Ultracode settings
Retain the legacy effort through older hosts. Promote the resolved setting on effort changes only when the current host exposes a toggle, and persist it with the effort choice.
2026-11-18 18:11:21 +01:00
Mohamed Boudra dac365aaac fix(claude): retain Ultracode when a legacy draft changes effort
Keep migrated model options in the draft model. Preserve the combined Extra high behavior for older Claude Code versions.
2026-11-18 17:57:51 +01:00
Mohamed Boudra 59eb9c0057 fix(claude): preserve model-specific Ultracode preferences
Read the legacy setting for the selected model and leave schedules editable through their existing effort control. Keep the state in the default toolbar tooltip.
2026-11-18 17:44:47 +01:00
Mohamed Boudra 4fc3631080 fix(claude): carry saved Ultra Code choices into the toggle
Convert saved settings before consumers validate effort. Keep provider-supplied toolbar tooltips so availability notices remain visible.
2026-11-18 17:31:11 +01:00
Mohamed Boudra ae61c08ac6 test(app): cover visible toggle state in the composer 2026-11-18 17:14:02 +01:00
Mohamed Boudraandfivetaku 6444c021ea feat(claude): give Ultracode its own toggle
Keep workflow orchestration enabled across live effort changes. Preserve the combined effort choice for older Claude Code versions and legacy sessions.

Co-authored-by: fivetaku <zipsanyang.ai@gmail.com>
2026-11-18 17:10:14 +01:00
29 changed files with 584 additions and 101 deletions
+2 -2
View File
@@ -50,8 +50,8 @@ or without a control.
reject. A key the running session cannot apply (one the provider reads only when it opens) is
rejected too, so a stored option always describes what runs. Claude reads most options when it
starts its query, and replacing a started query would end its background work, so after the
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
first prompt only Fast and Ultracode can change. Codex fixes its approval policy and sandbox
when the thread starts, so it applies only `service_tier` and `plan_mode` live. A session with no
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
it ended up with when they differ from the request. The daemon stores the patch and that
result in one step after the call resolves. Throwing rejects the whole patch and none of it is
@@ -30,6 +30,25 @@ function answer(
}
describe("draft options model", () => {
it("retains an Ultracode option only after the current host advertises it", () => {
const model = openDraftOptions({ provider: "claude" });
const legacy = { provider: "claude", cwd: "/repo", thinkingOptionId: "ultracode" };
model.applyResolved(answer("claude", "old-host", {}, []));
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(draftControlsRequest(model.getState(), legacy)).toEqual(legacy);
model.applyResolved(
answer("claude", "new-host", { ultracode: true }, [
{ type: "toggle", key: "ultracode", label: "Ultracode" },
]),
);
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(model.retainResolvedOption("ultracode", "new-host")).toEqual({ ultracode: true });
expect(
draftControlsRequest(model.getState(), { ...legacy, thinkingOptionId: "high" }),
).toMatchObject({ thinkingOptionId: "high", providerOptions: { ultracode: true } });
});
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
@@ -47,6 +47,7 @@ export interface DraftOptionsModel {
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
setRemembered: (remembered: ProviderOptions) => void;
setOption: (key: string, value: unknown) => void;
retainResolvedOption: (key: string, requestKey: string) => ProviderOptions | undefined;
applyResolved: (resolved: ResolvedDraftOptions) => void;
}
@@ -112,6 +113,17 @@ export function openDraftOptions(input: {
: { ...current, edits: { ...current.edits, [key]: value } },
);
},
retainResolvedOption: (key, requestKey) => {
const resolved = state.resolved;
if (resolved?.requestKey !== requestKey || key in state.edits) return undefined;
const value = resolved.options[key];
if (value === undefined || !resolved.controls.some((control) => control.key === key)) {
return undefined;
}
const patch = { [key]: value };
publish((current) => ({ ...current, edits: { ...current.edits, ...patch } }));
return patch;
},
applyResolved: (resolved) =>
publish((current) => ({
...current,
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
expect(trigger.textContent).not.toContain("Large");
});
it("flips a toggle on press in the toolbar", () => {
it("keeps the toolbar toggle name and flips it on press", () => {
const onChange = vi.fn();
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
fireEvent.click(screen.getByRole("button", { name: "Context" }));
fireEvent.click(screen.getByRole("button", { name: /^Context$/ }));
expect(onChange).toHaveBeenCalledWith(false);
});
@@ -94,6 +94,12 @@ describe("ComposerControls", () => {
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
});
it("keeps the provider's tooltip for a toolbar toggle", () => {
const tooltip = "Fast is enabled but does not apply to this model.";
renderControls([{ ...base, type: "toggle", value: true, tooltip, onChange: () => undefined }]);
expect(screen.getByRole("button", { name: tooltip })).toBeDefined();
});
it("gives a sheet row's value the row's width, so a short value is not truncated", () => {
const toast = createToast();
render(
@@ -157,6 +163,8 @@ describe("ComposerControls", () => {
});
const FAST_ON = { fast_mode: true };
const ULTRACODE_ON = { ultracode: true };
const ignoreOption = () => undefined;
describe("provider option controls", () => {
const fastMode: AgentOptionControl = {
@@ -173,7 +181,11 @@ describe("provider option controls", () => {
onSetOption: (key: string, value: unknown) => void;
}) {
const optionControls = React.useMemo(
() => ({ controls: [fastMode], options, onSetOption }),
() => ({
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
options,
onSetOption,
}),
[onSetOption, options],
);
const items = useAgentControlItems({
@@ -197,4 +209,9 @@ describe("provider option controls", () => {
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
expect(writes).toEqual([["fast_mode", false]]);
});
it("announces the state of a provider toggle with no custom tooltip", () => {
render(<OptionControls options={ULTRACODE_ON} onSetOption={ignoreOption} />);
expect(screen.getByRole("button", { name: "Ultracode: On" })).toBeDefined();
});
});
@@ -28,7 +28,7 @@ interface ComposerControlBase {
title: string;
icon: AgentControlIcon;
/** Tints the icon; muted when absent. */
highlight?: "blue" | "green" | "yellow";
highlight?: "blue" | "green" | "purple" | "yellow";
/** Defaults to the title, or to "title: choice" on an icon-only select. */
tooltip?: string;
/** Defaults to the tooltip. */
@@ -393,6 +393,7 @@ function ComposerControlSlot({
const styles = StyleSheet.create((theme) => ({
fieldIcon: { color: theme.colors.foregroundMuted },
blue: { color: theme.colors.palette.blue[400] },
purple: { color: theme.colors.palette.purple[500] },
green: { color: theme.colors.palette.green[400] },
yellow: { color: theme.colors.palette.yellow[400] },
tooltipText: {
@@ -33,6 +33,8 @@ function getFeatureHighlight(
function toFeatureItem(
control: AgentOptionControl,
optionControls: ComposerOptionControls,
surface: ComposerControlSurface,
t: TFunction,
): ComposerControlItem {
const { options, onSetOption } = optionControls;
const base = {
@@ -43,11 +45,15 @@ function toFeatureItem(
testID: `agent-feature-${control.key}`,
};
if (control.type === "toggle") {
const enabled = readToggleOption(control, options);
const stateLabel = enabled ? t("agentControls.features.on") : t("agentControls.features.off");
return {
...base,
type: "toggle",
tooltip: getControlTooltip(control),
value: readToggleOption(control, options),
tooltip:
control.tooltip ??
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
value: enabled,
onChange: (value) => onSetOption(control.key, value),
};
}
@@ -92,9 +98,11 @@ export function useAgentControlItems({
const features = useMemo(
() =>
optionControls
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
? optionControls.controls.map((control) =>
toFeatureItem(control, optionControls, surface, t),
)
: [],
[optionControls],
[optionControls, surface, t],
);
return { thinking: thinkingItem, features };
}
@@ -1316,8 +1316,7 @@ export function DraftAgentControls({
return toThinkingControlOptions(thinkingOptions);
}, [thinkingOptions]);
const effectiveSelectedThinkingOption =
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
const modelOptions = useMemo<AgentControlOption[]>(
() =>
@@ -20,6 +20,7 @@ describe("feature metadata helpers", () => {
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
expect(getFeatureHighlightColor("ultracode")).toBe("purple");
expect(getFeatureHighlightColor("other")).toBe("default");
});
});
@@ -8,7 +8,7 @@ import {
} from "@/agent-controls/policy";
export type ExplainedAgentControl = "mode" | "model" | "thinking";
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
export type FeatureHighlightColor = "blue" | "default" | "green" | "purple" | "yellow";
export type AgentControlHintKey =
| "agentControls.hints.thinking"
| "agentControls.hints.model"
@@ -48,6 +48,8 @@ export function getFeatureHighlightColor(featureId: string): FeatureHighlightCol
return "yellow";
case "auto_accept":
return "green";
case "ultracode":
return "purple";
case PLAN_MODE_FEATURE_ID:
return "blue";
default:
+20 -2
View File
@@ -22,6 +22,7 @@ import {
resolveEffectiveComposerThinkingOptionId,
type ProviderSelectionState,
} from "@/provider-selection/provider-selection";
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { useShallow } from "zustand/shallow";
@@ -293,6 +294,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
options: draftOptions,
shownOptions: draftShownOptions,
setOption: setDraftOption,
retainLegacyUltracode,
applyProfile: applyProfileOptions,
} = useDraftProviderOptions({
serverId: formState.selectedServerId,
@@ -312,6 +314,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
},
[applyProfileOptions, formState],
);
const setDraftThinking = useCallback(
(thinkingOptionId: string) =>
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
[formState, retainLegacyUltracode],
);
const commandDraft = useMemo(
() =>
@@ -330,8 +337,18 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
return null;
}
return {
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const draftForm = {
...formState,
selectedThinkingOptionId:
findThinkingOptionReplacement(
formState.availableThinkingOptions,
formState.selectedThinkingOptionId,
) ?? formState.selectedThinkingOptionId,
setThinkingOptionFromUser: setDraftThinking,
};
return {
...draftForm,
workingDir,
effectiveModeId,
effectiveModelId,
@@ -339,7 +356,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
providerOptions: draftOptions,
metadata,
agentControls: buildDraftAgentControls({
formState,
formState: draftForm,
optionControls: draftOptionControls,
options: draftShownOptions,
onSetOption: setDraftOption,
@@ -360,6 +377,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
draftOptions,
draftShownOptions,
setDraftOption,
setDraftThinking,
applyDraftAgentProfile,
formState,
metadata,
@@ -4,6 +4,7 @@ import type {
AgentMode,
AgentModelDefinition,
AgentProvider,
ProviderOptions,
ProviderSnapshotEntry,
} from "@getpaseo/protocol/agent-types";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
@@ -58,7 +59,7 @@ export interface UseAgentFormStateResult {
selectedModel: string;
setModelFromUser: (modelId: string) => void;
selectedThinkingOptionId: string;
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
workingDir: string;
providerDefinitions: AgentProviderDefinition[];
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
@@ -419,7 +420,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
);
const setThinkingOptionFromUser = useCallback(
(thinkingOptionId: string) => {
(thinkingOptionId: string, retainedOptions?: ProviderOptions) => {
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
const { provider, model: modelId } = formStore.getState().form;
if (provider && modelId) {
@@ -431,6 +432,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
thinkingByModel: {
[modelId]: thinkingOptionId,
},
options: retainedOptions,
},
}),
);
@@ -69,6 +69,14 @@ export function useDraftProviderOptions(input: {
[draftConfig, serverId],
);
const requestKey = JSON.stringify(queryKey);
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const retainLegacyUltracode = useCallback(
() =>
thinkingOptionId === "ultracode"
? model.retainResolvedOption("ultracode", requestKey)
: undefined,
[model, requestKey, thinkingOptionId],
);
const { data } = useFetchQuery({
queryKey,
@@ -129,6 +137,7 @@ export function useDraftProviderOptions(input: {
options: ownOptions,
shownOptions,
setOption,
retainLegacyUltracode,
applyProfile: model.applyProfile,
};
}
@@ -167,6 +167,14 @@ function resolvePreferredThinkingOptionId(input: {
return "";
}
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
export function findThinkingOptionReplacement(
options: NonNullable<AgentModelDefinition["thinkingOptions"]>,
legacyId: string,
): string | undefined {
return options.find((option) => option.metadata?.replacesThinkingOptionId === legacyId)?.id;
}
export function resolveThinkingOptionId(args: {
availableModels: AgentModelDefinition[] | null;
modelId: string;
@@ -183,6 +191,9 @@ export function resolveThinkingOptionId(args: {
) {
return normalizedThinkingOptionId;
}
if (findThinkingOptionReplacement(thinkingOptions, normalizedThinkingOptionId)) {
return normalizedThinkingOptionId;
}
return effectiveModel?.defaultThinkingOptionId ?? thinkingOptions[0]?.id ?? "";
}
@@ -96,6 +96,7 @@ function scheduleOnHost(input: {
serverName: string;
cwd: string;
model: string;
provider?: string;
thinkingOptionId?: string | null;
cadence?: ScheduleSummary["cadence"];
}): TestSchedule {
@@ -109,7 +110,7 @@ function scheduleOnHost(input: {
target: {
type: "new-agent",
config: {
provider: "mock",
provider: input.provider ?? "mock",
cwd: input.cwd,
model: input.model,
modeId: "load-test",
@@ -186,6 +187,56 @@ function applyPreferences(form: ReturnType<typeof open>, preferences: FormPrefer
}
describe("schedule form model", () => {
it("keeps Ultra Code available in the schedule effort picker", () => {
const model = "claude-opus-4-8";
const form = open({
mode: "edit",
schedule: scheduleOnHost({
serverId: "host-a",
serverName: "Host A",
cwd: "/repo/a",
provider: "claude",
model,
thinkingOptionId: "ultracode",
}),
defaults: { serverId: null, projectTargets: PROJECT_TARGETS, preferences: {} },
});
form.applyProviderSnapshot("host-a", {
...providerSnapshot([]),
entries: [
{
provider: "claude",
status: "ready",
enabled: true,
models: [
{
provider: "claude",
id: model,
label: "Opus 4.8",
thinkingOptions: [
{ id: "high", label: "High" },
{
id: "xhigh",
label: "Extra high",
metadata: { replacesThinkingOptionId: "ultracode" },
},
],
},
],
},
],
});
expect(form.getState().selectedThinkingOptionId).toBe("ultracode");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
form.setThinking("high");
expect(form.getState().selectedThinkingOptionId).toBe("high");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
});
it("opens edit from the schedule host snapshot and completes that host resolution", () => {
const previous = open({
mode: "edit",
@@ -14,6 +14,7 @@ import {
import { filterSelectableModels, findModelByReference } from "@/provider-selection/model-catalog";
import {
buildProviderDefinitionMapForStatuses,
findThinkingOptionReplacement,
INITIAL_USER_MODIFIED,
RESOLVABLE_PROVIDER_STATUSES,
resolveDefaultModelId,
@@ -273,7 +274,14 @@ function resolveThinkingOptions(
modelId: string,
): NonNullable<AgentModelDefinition["thinkingOptions"]> {
const model = resolveEffectiveModel(resolveAvailableModels(entries, provider), modelId);
return model?.thinkingOptions ?? [];
const options = model?.thinkingOptions ?? [];
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18
// once schedules edit the Ultracode option independently.
// Schedules still use a single effort field.
return findThinkingOptionReplacement(options, "ultracode") &&
!options.some((option) => option.id === "ultracode")
? [...options, { id: "ultracode", label: "Ultra Code" }]
: options;
}
function resolveModelDisplay(input: {
@@ -92,7 +92,11 @@ const pinnedTheme = {
const testTheme = {
...lightTheme,
...pinnedTheme,
colors: { ...lightTheme.colors, ...pinnedTheme.colors },
colors: {
...lightTheme.colors,
...pinnedTheme.colors,
palette: { ...lightTheme.colors.palette, ...pinnedTheme.colors.palette },
},
};
type StyleFactory<T> = (theme: typeof testTheme) => T;
@@ -69,6 +69,7 @@ import {
applyProviderOptionsPatch,
exposeFeatureValuesToHook,
convertLegacyOptions,
convertLegacyClaudeUltracode,
MalformedLegacyOptionError,
resolveAdapter,
foldHookFeatureValues,
@@ -6194,7 +6195,15 @@ export class AgentManager {
private withConvertedOptions(config: AgentSessionConfig): AgentSessionConfig {
const providerOptions = this.convertLegacyOptions(config.provider, config.providerOptions);
return providerOptions === config.providerOptions ? config : { ...config, providerOptions };
return this.convertLegacySessionConfig(
providerOptions === config.providerOptions ? config : { ...config, providerOptions },
);
}
convertLegacySessionConfig<T extends Parameters<typeof convertLegacyClaudeUltracode>[0]>(
config: T,
): T {
return convertLegacyClaudeUltracode(config, this.adapterOf(config.provider));
}
private async prepareSessionConfig(
@@ -1,6 +1,19 @@
import { isDeepStrictEqual } from "node:util";
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18
// once schedules stop writing the legacy effort and existing records have migrated.
export function convertLegacyClaudeUltracode<
T extends { provider: string; thinkingOptionId?: string; providerOptions?: ProviderOptions },
>(config: T, adapter = config.provider): T {
if (adapter !== "claude" || config.thinkingOptionId !== "ultracode") return config;
return {
...config,
thinkingOptionId: "xhigh",
providerOptions: { ultracode: true, ...config.providerOptions },
};
}
/**
* A patch over an agent's own options: top-level keys replace, `null` removes the key so the
* `config.json` default (or the provider's own default) applies again.
@@ -1548,7 +1548,7 @@ describe("model merging", () => {
models
.find((model) => model.id === "claude-sonnet-5")
?.thinkingOptions?.map((option) => option.id),
).toEqual(["off", "low", "medium", "high", "xhigh", "max", "ultracode"]);
).toEqual(["off", "low", "medium", "high", "xhigh", "max"]);
expect(models.find((model) => model.id === "claude-opus-5")?.thinkingOptions).toEqual([]);
expect(models.find((model) => model.id === "custom-explicit")).toMatchObject({
thinkingOptions: [{ id: "bespoke", label: "Bespoke", isDefault: true }],
@@ -26,6 +26,7 @@ import {
resolveSnapshotCwd,
} from "./provider-snapshot-manager.js";
import { OpenCodeAgentClient } from "./providers/opencode-agent.js";
import { getClaudeModels } from "./providers/claude/models.js";
const TEST_CAPABILITIES = {
supportsStreaming: false,
@@ -311,6 +312,29 @@ describe("ProviderSnapshotManager public surface", () => {
}
});
test("accepts a legacy Ultra Code choice on a model with an independent effort catalog", async () => {
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
extraClients: {
claude: createExtraClient("claude", {
isAvailable: async () => true,
fetchCatalog: async () => ({ models: getClaudeModels("2.1.284"), modes: [] }),
}),
},
});
try {
await expect(
manager.validateAgentConfiguration({
provider: "claude",
model: "claude-opus-4-8",
thinkingOptionId: "ultracode",
}),
).resolves.toEqual([]);
} finally {
manager.destroy();
}
});
test("reports an unavailable Hub agent provider at the authored provider field", async () => {
const manager = new ProviderSnapshotManager({ logger: createTestLogger() });
try {
@@ -51,6 +51,7 @@ import {
} from "./agent-configuration-validator.js";
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { PluginAgentClientRegistry } from "./plugin-provider.js";
import { convertLegacyClaudeUltracode, resolveAdapter } from "./option-controls.js";
const DEFAULT_REFRESH_TIMEOUT_MS = 120_000;
const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647;
@@ -516,7 +517,13 @@ export class ProviderSnapshotManager {
}
return validateAgentConfigurationAgainstProvider({
input,
input: convertLegacyClaudeUltracode(
input,
resolveAdapter({
provider: input.provider,
extendsOf: (id) => this.generation.definitions[id]?.derivedFromProviderId,
}),
),
provider,
});
}
@@ -2,6 +2,7 @@ import { expect, test } from "vitest";
import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import { convertLegacyClaudeUltracode } from "../../option-controls.js";
import { ClaudeAgentClient } from "./agent.js";
import type { ClaudeQueryInput } from "./query.js";
@@ -18,6 +19,7 @@ function deferred<T>() {
class ForegroundQuery {
readonly work = deferred<void>();
readonly closed = deferred<void>();
readonly flagSettings: Parameters<Query["applyFlagSettings"]>[0][] = [];
private stopped = false;
private readonly output: AsyncGenerator<SDKMessage>;
@@ -72,6 +74,9 @@ class ForegroundQuery {
}
async setPermissionMode() {}
async setModel() {}
async applyFlagSettings(settings: Parameters<Query["applyFlagSettings"]>[0]) {
this.flagSettings.push(settings);
}
async supportedCommands() {
return [];
}
@@ -156,3 +161,122 @@ test.each(["mode", "model", "commands"] as const)(
}
},
);
test("Ultracode toggles at Medium and stays enabled when effort changes live", async () => {
const queries: ForegroundQuery[] = [];
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.284",
queryFactory: (input) => {
const query = new ForegroundQuery(input);
queries.push(query);
launchOptions.push(input.options);
return query as unknown as Query;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: "medium",
providerOptions: { ultracode: false },
});
try {
expect(session.controls).toContainEqual(
expect.objectContaining({ key: "ultracode", type: "toggle" }),
);
await session.startTurn("Start at Medium");
expect(launchOptions[0]).toMatchObject({ effort: "medium", settings: { ultracode: false } });
await session.applyOptions?.({ ultracode: true });
await session.setThinkingOption?.("high");
await session.applyOptions?.({ ultracode: false });
expect(queries).toHaveLength(1);
expect(queries[0].flagSettings).toEqual([
{ fastMode: false, ultracode: false },
{ ultracode: true },
{ effortLevel: "high", ultracode: true },
{ ultracode: false },
]);
} finally {
await session.close();
}
});
test.each([
["xhigh", true],
["high", false],
] as const)("older Claude Code launches %s with Ultracode set to %s", async (effort, enabled) => {
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.283",
queryFactory: (input) => {
launchOptions.push(input.options);
return new ForegroundQuery(input) as unknown as Query;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: effort,
providerOptions: { ultracode: true },
});
try {
expect(session.controls?.some((control) => control.key === "ultracode")).toBe(false);
await session.startTurn("Start the agent");
expect(launchOptions[0]).toMatchObject({ effort, settings: { ultracode: enabled } });
} finally {
await session.close();
}
});
test("reopens an older Claude Code agent with Ultracode after choosing Ultra Code again", async () => {
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.283",
queryFactory: (input) => {
launchOptions.push(input.options);
return new ForegroundQuery(input) as unknown as Query;
},
});
const config = {
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: "xhigh",
providerOptions: { ultracode: true },
};
const session = await client.createSession(config);
let savedOptions = config.providerOptions;
session.subscribe((event) => {
if (event.type === "options_changed" && typeof event.patch.ultracode === "boolean") {
savedOptions = { ultracode: event.patch.ultracode };
}
});
try {
await session.setThinkingOption?.("high");
expect(savedOptions.ultracode).toBe(false);
await session.setThinkingOption?.("ultracode");
} finally {
await session.close();
}
const reopened = await client.createSession(
convertLegacyClaudeUltracode({
...config,
thinkingOptionId: "ultracode",
providerOptions: savedOptions,
}),
);
try {
await reopened.startTurn("Start the agent");
expect(launchOptions[0]).toMatchObject({ effort: "xhigh", settings: { ultracode: true } });
} finally {
await reopened.close();
}
});
@@ -543,21 +543,20 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
return models.find((model) => model.id === modelId)?.thinkingOptions?.map(({ id }) => id);
};
expect(getThinkingIds("claude-opus-5")).toContain("ultracode");
expect(getThinkingIds("claude-opus-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-mythos-5-1")).toEqual([
"low",
"medium",
"high",
"xhigh",
"max",
"ultracode",
]);
expect(getThinkingIds("claude-fable-5-1")).toContain("ultracode");
expect(getThinkingIds("claude-fable-5")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8[1m]")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8")).toContain("ultracode");
expect(getThinkingIds("claude-fable-5-1")).not.toContain("ultracode");
expect(getThinkingIds("claude-fable-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8[1m]")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8")).not.toContain("ultracode");
expect(getThinkingIds("claude-sonnet-5")).toContain("xhigh");
expect(getThinkingIds("claude-sonnet-5")).toContain("ultracode");
expect(getThinkingIds("claude-sonnet-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-haiku-5-5")).toEqual([
"off",
"low",
@@ -565,12 +564,11 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
"high",
"xhigh",
"max",
"ultracode",
]);
expect(getThinkingIds("claude-sonnet-5-5")).toContain("xhigh");
expect(getThinkingIds("claude-sonnet-5-5")).not.toContain("off");
expect(getThinkingIds("claude-opus-4-7[1m]")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7[1m]")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).not.toContain("ultracode");
expect(getThinkingIds("claude-sonnet-4-6")).not.toContain("ultracode");
} finally {
await fs.rm(emptyConfigDir, { recursive: true, force: true });
@@ -1181,8 +1179,8 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test("lists fast mode only for supported Opus models", async () => {
const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" });
test("lists Claude controls by model capability", async () => {
const client = new ClaudeAgentClient({ logger, resolveVersion: async () => "2.1.284" });
await expect(
client.listControls({
@@ -1191,7 +1189,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1202,7 +1203,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8[1m]",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1213,7 +1217,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8-20260101",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1224,7 +1231,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-5",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1234,7 +1244,10 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "openrouter/anthropic/claude-opus-4-8",
}),
).resolves.toEqual({ controls: [], options: {} });
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
await expect(
client.listControls({
@@ -1242,7 +1255,10 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "claude-sonnet-5",
}),
).resolves.toEqual({ controls: [], options: {} });
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
await expect(
client.listControls({
@@ -50,8 +50,10 @@ import {
import {
CLAUDE_DISABLED_THINKING_OPTION_ID,
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
resolveClaudeDisabledThinkingForModel,
supportsIndependentClaudeUltracode,
} from "./model-manifest.js";
import { expandTilde } from "../../../../utils/path.js";
import { parsePartialJsonObject } from "./partial-json.js";
@@ -496,6 +498,7 @@ interface ClaudeAgentSessionOptions {
logger: Logger;
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
rewindSdk?: ClaudeRewindSdk;
}
@@ -1618,6 +1621,7 @@ export class ClaudeAgentClient implements AgentClient {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
private version: Promise<string | undefined> | undefined;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
(candidate: ClaudeSessionCandidate, signal) => this.readImportDescriptor(candidate, signal),
@@ -1661,6 +1665,7 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
}
@@ -1690,6 +1695,7 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1714,6 +1720,7 @@ export class ClaudeAgentClient implements AgentClient {
} catch (error) {
this.logger.warn({ err: error }, "Failed to resolve Claude Code version for model catalog");
}
this.version = Promise.resolve(claudeCodeVersion);
const env = this.buildProviderEnv();
let discoveredModelIds = new Set<string>();
try {
@@ -1770,11 +1777,19 @@ export class ClaudeAgentClient implements AgentClient {
async listControls(config: AgentSessionConfig): Promise<AgentDraftControls> {
return {
controls: buildClaudeControls(this.assertConfig(config).model),
controls: buildClaudeControls(
this.assertConfig(config).model,
await this.supportsIndependentUltracode(),
),
options: config.providerOptions ?? {},
};
}
private async supportsIndependentUltracode(): Promise<boolean> {
this.version ??= this.resolveVersion().catch(() => undefined);
return supportsIndependentClaudeUltracode(await this.version);
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
@@ -2307,6 +2322,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly logger: Logger;
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2444,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession {
this.logger = options.logger.child({ agentId: this.agentId });
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -2481,6 +2498,16 @@ class ClaudeAgentSession implements AgentSession {
this.config.providerOptions = { ...config.providerOptions, fast_mode: false };
this.openOptionsPatch = { fast_mode: false };
}
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
// Direct adapter callers can still pass the combined choice.
if (
this.independentUltracode &&
config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
config.providerOptions.ultracode === undefined
) {
this.config.providerOptions = { ...config.providerOptions, ultracode: true };
this.openOptionsPatch.ultracode = true;
}
}
get id(): string | null {
@@ -2488,18 +2515,28 @@ class ClaudeAgentSession implements AgentSession {
}
get controls(): AgentOptionControl[] {
return buildClaudeControls(this.config.model);
return buildClaudeControls(this.config.model, this.independentUltracode);
}
async getRuntimeInfo(): Promise<AgentRuntimeInfo> {
if (this.cachedRuntimeInfo) {
return { ...this.cachedRuntimeInfo };
}
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
const info: AgentRuntimeInfo = {
provider: "claude",
sessionId: this.claudeSessionId,
model: this.lastOptionsModel ?? this.config.model ?? null,
modeId: this.currentMode ?? null,
...(this.independentUltracode &&
this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? { thinkingOptionId: "xhigh" }
: {}),
...(!this.independentUltracode &&
this.config.thinkingOptionId === "xhigh" &&
this.config.providerOptions.ultracode === true
? { thinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID }
: {}),
...(this.lastRuntimeModel
? {
extra: {
@@ -2522,12 +2559,7 @@ class ClaudeAgentSession implements AgentSession {
reduceFinalText: appendOrReplaceGrowingAssistantMessage,
});
this.cachedRuntimeInfo = {
provider: "claude",
sessionId: this.claudeSessionId,
model: this.lastOptionsModel,
modeId: this.currentMode ?? null,
};
this.cachedRuntimeInfo = null;
if (!this.claudeSessionId) {
throw new Error("Session ID not set after run completed");
@@ -2816,9 +2848,14 @@ class ClaudeAgentSession implements AgentSession {
const normalizedModelId =
typeof modelId === "string" && modelId.trim().length > 0 ? modelId.trim() : null;
const activeQuery = await this.ensureQuery();
const previousUltracode = this.resolveUltracodeSetting();
await activeQuery.setModel(normalizedModelId ?? undefined);
this.config.model = normalizedModelId ?? undefined;
this.reconcileThinkingOptionForModel(normalizedModelId);
const ultracode = this.resolveUltracodeSetting();
if (previousUltracode !== ultracode && this.config.providerOptions.ultracode !== undefined) {
await activeQuery.applyFlagSettings({ ultracode: ultracode ?? false });
}
if (this.config.providerOptions.fast_mode) {
const supported = claudeModelSupportsFastMode(this.config.model);
await activeQuery.applyFlagSettings({ fastMode: supported });
@@ -2877,9 +2914,26 @@ class ClaudeAgentSession implements AgentSession {
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
assertClaudeThinkingOptionSupported(this.config.model, normalizedThinkingOptionId);
this.config.thinkingOptionId = normalizedThinkingOptionId;
if (
normalizedThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
this.config.providerOptions.ultracode !== true
) {
this.config.providerOptions = { ...this.config.providerOptions, ultracode: true };
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: true } });
}
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
this.cachedRuntimeInfo = null;
if (
!this.independentUltracode &&
normalizedThinkingOptionId !== CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
this.config.providerOptions.ultracode === true
) {
this.config.providerOptions = { ...this.config.providerOptions, ultracode: false };
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: false } });
this.queryRestartNeeded = true;
}
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
@@ -2896,12 +2950,20 @@ class ClaudeAgentSession implements AgentSession {
previousThinkingOptionId: string | undefined,
): Promise<boolean> {
const effort = this.config.thinkingOptionId;
const previousEffort =
this.independentUltracode && previousThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? "xhigh"
: previousThinkingOptionId;
if (!this.query || this.queryRestartNeeded) return false;
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
if (!isClaudeThinkingEffort(previousEffort) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
await this.query.applyFlagSettings({ effortLevel: effort });
const ultracode = this.resolveUltracodeSetting();
await this.query.applyFlagSettings({
effortLevel: effort,
...(ultracode === undefined ? {} : { ultracode }),
});
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
@@ -2910,14 +2972,13 @@ class ClaudeAgentSession implements AgentSession {
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Every option but Fast is read when the query is built, and replacing a started query would
// end its background work, so once it exists only Fast can change.
// Replacing a started query ends background work, so only flag settings can change live.
if (this.query || this.queryStarting) {
assertChangesAreLive({
provider: "claude",
patch: options,
current: this.config.providerOptions,
live: ["fast_mode"],
live: ["fast_mode", "ultracode"],
});
}
const providerOptions =
@@ -2933,14 +2994,34 @@ class ClaudeAgentSession implements AgentSession {
}
const fastModeChanged =
(providerOptions.fast_mode === true) !== (this.config.providerOptions.fast_mode === true);
if (fastModeChanged) {
await this.query?.applyFlagSettings({ fastMode: providerOptions.fast_mode === true });
const ultracodeChanged = providerOptions.ultracode !== this.config.providerOptions.ultracode;
if (ultracodeChanged) this.assertUltracodeChangeSupported(providerOptions.ultracode);
if (fastModeChanged || ultracodeChanged) {
await this.query?.applyFlagSettings({
...(fastModeChanged ? { fastMode: providerOptions.fast_mode === true } : {}),
...(ultracodeChanged ? { ultracode: providerOptions.ultracode ?? false } : {}),
});
this.cachedRuntimeInfo = null;
}
// Held until the runtime accepts, so a rejected change is retried instead of skipped.
this.config.providerOptions = providerOptions;
}
private assertUltracodeChangeSupported(value: boolean | undefined): void {
if (!this.independentUltracode) {
throw new Error("The Ultracode toggle requires Claude Code 2.1.284 or later");
}
if (this.query && value === undefined) {
// The SDK treats null as Off, so a running process cannot restore inherited settings.
throw new Error("Close the agent to reset Ultracode to Claude's default");
}
if (value === true && !claudeManifestModelSupportsUltracode(this.config.model)) {
throw new Error(
`Claude Ultracode is not available for model '${this.config.model ?? "default"}'`,
);
}
}
getPendingPermissions(): AgentPermissionRequest[] {
return Array.from(this.pendingPermissions.values()).map((entry) => entry.request);
}
@@ -3670,8 +3751,12 @@ class ClaudeAgentSession implements AgentSession {
);
this.queryStarting = false;
const fastMode = this.resolveFastModeSetting();
if (fastMode !== null) {
await this.query.applyFlagSettings({ fastMode });
const ultracode = this.independentUltracode ? this.resolveUltracodeSetting() : undefined;
if (fastMode !== null || ultracode !== undefined) {
await this.query.applyFlagSettings({
...(fastMode === null ? {} : { fastMode }),
...(ultracode === undefined ? {} : { ultracode }),
});
}
// Do not kick off background control-plane queries here. Methods like
// supportedCommands()/setPermissionMode() may execute immediately after
@@ -3729,7 +3814,6 @@ class ClaudeAgentSession implements AgentSession {
private resolveThinkingConfig(): {
thinking: ClaudeOptions["thinking"];
effort: ClaudeOptions["effort"];
ultracode: boolean;
} {
const thinkingOptionId =
this.config.thinkingOptionId && this.config.thinkingOptionId !== "default"
@@ -3737,23 +3821,21 @@ class ClaudeAgentSession implements AgentSession {
: undefined;
assertClaudeThinkingOptionSupported(this.config.model, thinkingOptionId);
if (thinkingOptionId === CLAUDE_DISABLED_THINKING_OPTION_ID) {
return { thinking: { type: "disabled" }, effort: undefined, ultracode: false };
return { thinking: { type: "disabled" }, effort: undefined };
}
if (thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) {
return {
thinking: { type: "adaptive", display: "summarized" },
effort: "xhigh",
ultracode: true,
};
}
if (thinkingOptionId && isClaudeThinkingEffort(thinkingOptionId)) {
return {
thinking: { type: "adaptive", display: "summarized" },
effort: thinkingOptionId,
ultracode: false,
};
}
return { thinking: undefined, effort: undefined, ultracode: false };
return { thinking: undefined, effort: undefined };
}
private buildAppendedSystemPrompt(): string {
@@ -3790,12 +3872,15 @@ class ClaudeAgentSession implements AgentSession {
}
private async buildOptions(permissionMode: PermissionMode): Promise<ClaudeOptions> {
const { thinking, effort, ultracode } = this.resolveThinkingConfig();
const { thinking, effort } = this.resolveThinkingConfig();
const appendedSystemPrompt = this.buildAppendedSystemPrompt();
// `fast_mode` is a composer control the provider applies through flag settings.
const { fast_mode: _fastMode, ...sdkProviderOptions } = this.config.providerOptions;
const {
fast_mode: _fastMode,
ultracode: _ultracode,
...sdkProviderOptions
} = this.config.providerOptions;
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode });
const settingsOptions = await this.buildSettingsOptions(providerOptions);
const sdkEnv = this.harnessEnvironment;
assertClaudeModeCanRun(permissionMode, sdkEnv);
@@ -3882,18 +3967,18 @@ class ClaudeAgentSession implements AgentSession {
private async buildSettingsOptions(
providerOptions: ClaudeProviderOptions,
input: { ultracode: boolean },
): Promise<Pick<ClaudeOptions, "settings" | "extraArgs"> | Record<string, never>> {
const fastMode = this.resolveFastModeSetting();
const ultracode = this.resolveUltracodeSetting();
// Internal agents do daemon work such as naming a branch, so the user's and
// project's hooks must not run for them.
const disableAllHooks = this.config.internal === true;
if (fastMode === null && !input.ultracode && !disableAllHooks) {
if (fastMode === null && ultracode === undefined && !disableAllHooks) {
return {};
}
const updates = {
...(fastMode === null ? {} : { fastMode }),
...(input.ultracode ? { ultracode: true } : {}),
...(ultracode === undefined ? {} : { ultracode }),
...(disableAllHooks ? { disableAllHooks: true } : {}),
};
// The SDK replaces extraArgs.settings with Options.settings, so a user's
@@ -3909,6 +3994,18 @@ class ClaudeAgentSession implements AgentSession {
};
}
private resolveUltracodeSetting(): boolean | undefined {
const ultracode = this.config.providerOptions.ultracode;
if (!this.independentUltracode) {
return this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? true
: ultracode && this.config.thinkingOptionId === "xhigh";
}
if (ultracode === undefined) return undefined;
if (this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) return ultracode;
return ultracode && claudeManifestModelSupportsUltracode(this.config.model);
}
private resolveFastModeSetting(): boolean | null {
if (!claudeModelSupportsFastMode(this.config.model)) {
return null;
@@ -1,5 +1,8 @@
import type { AgentOptionControl, AgentOptionToggleControl } from "../../agent-sdk-types.js";
import { claudeManifestModelSupportsFastMode } from "./model-manifest.js";
import {
claudeManifestModelSupportsFastMode,
claudeManifestModelSupportsUltracode,
} from "./model-manifest.js";
export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
type: "toggle",
@@ -10,10 +13,26 @@ export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
icon: "zap",
};
const CLAUDE_ULTRACODE_CONTROL: AgentOptionToggleControl = {
type: "toggle",
key: "ultracode",
label: "Ultracode",
description: "Let Claude plan workflows for substantive tasks",
icon: "Workflow",
};
export function claudeModelSupportsFastMode(modelId: string | null | undefined): boolean {
return claudeManifestModelSupportsFastMode(modelId);
}
export function buildClaudeControls(modelId: string | null | undefined): AgentOptionControl[] {
return claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : [];
export function buildClaudeControls(
modelId: string | null | undefined,
independentUltracode: boolean,
): AgentOptionControl[] {
return [
...(claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : []),
...(independentUltracode && claudeManifestModelSupportsUltracode(modelId)
? [{ ...CLAUDE_ULTRACODE_CONTROL }]
: []),
];
}
@@ -226,25 +226,27 @@ function buildThinkingOptions(
effortLevels: readonly ClaudeEffortLevel[] | undefined,
supportsThinkingDisabled: boolean,
defaultThinkingOptionId: ClaudeEffortLevel,
independentUltracode: boolean,
): AgentSelectOption[] | undefined {
if (!effortLevels) {
return undefined;
}
const options: AgentSelectOption[] = [
return [
...(supportsThinkingDisabled ? [{ id: CLAUDE_DISABLED_THINKING_OPTION_ID, label: "Off" }] : []),
...effortLevels.map((id) => ({
id,
label: CLAUDE_EFFORT_LABELS[id],
...(id === defaultThinkingOptionId ? { isDefault: true } : {}),
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
...(independentUltracode && id === "xhigh"
? { metadata: { replacesThinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID } }
: {}),
})),
...(!independentUltracode && effortLevels.includes("xhigh")
? [{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" }]
: []),
];
if (effortLevels.includes("xhigh")) {
options.push({ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" });
}
return options;
}
export function getClaudeManifestModels(
@@ -270,6 +272,7 @@ export function getClaudeManifestModels(
model.effortLevels,
model.supportsThinkingDisabled === true,
getDefaultThinkingOptionId(model),
supportsIndependentClaudeUltracode(claudeCodeVersion),
);
const definition: AgentModelDefinition = {
provider: "claude",
@@ -340,6 +343,10 @@ export function parseClaudeCodeVersion(value: string): [number, number, number]
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
}
export function supportsIndependentClaudeUltracode(version: string | undefined): boolean {
return version === undefined || compareVersions(version, "2.1.284") >= 0;
}
export interface ClaudeDisabledThinkingResolution {
supported: boolean;
fallbackThinkingOptionId: string | undefined;
@@ -381,6 +388,14 @@ export function claudeManifestModelSupportsFastMode(modelId: string | null | und
);
}
export function claudeManifestModelSupportsUltracode(modelId: string | null | undefined): boolean {
const normalized = normalizeClaudeRuntimeModelId(modelId);
const model: ClaudeModelManifestEntry | undefined = CLAUDE_MODEL_MANIFEST.find(
(candidate) => candidate.id === normalized,
);
return model?.effortLevels?.includes("xhigh") === true;
}
/**
* Normalize first-party Claude model IDs for manifest capability checks. Provider-prefixed
* runtime IDs intentionally use normalizeClaudeRuntimeModelId instead.
@@ -8,7 +8,6 @@ import { createTestLogger } from "../../../../test-utils/test-logger.js";
import { ClaudeAgentClient } from "./agent.js";
import {
CLAUDE_DISABLED_THINKING_OPTION_ID,
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
claudeManifestModelSupportsFastMode,
normalizeClaudeManifestModelId,
parseClaudeCodeVersion,
@@ -190,7 +189,6 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(models.get("claude-sonnet-5")?.thinkingOptions?.map((option) => option.id)).toEqual([
CLAUDE_DISABLED_THINKING_OPTION_ID,
@@ -199,14 +197,7 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(
models
.get("claude-sonnet-5")
?.thinkingOptions?.find((option) => option.id === CLAUDE_ULTRACODE_THINKING_OPTION_ID)
?.label,
).toBe("Ultra Code");
expect(models.get("claude-sonnet-5")?.defaultThinkingOptionId).toBe("high");
expect(models.get("claude-sonnet-5[1m]")?.thinkingOptions).toEqual(
models.get("claude-sonnet-5")?.thinkingOptions,
@@ -219,7 +210,6 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(models.get("claude-sonnet-4-6")?.thinkingOptions?.map((option) => option.id)).toEqual([
CLAUDE_DISABLED_THINKING_OPTION_ID,
@@ -420,9 +410,12 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{ id: "xhigh", label: "Extra High" },
{
id: "xhigh",
label: "Extra High",
metadata: { replacesThinkingOptionId: "ultracode" },
},
{ id: "max", label: "Max" },
{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" },
];
const configDir = await createClaudeConfigDir({
model: "us.anthropic.claude-opus-4-7[1m]",
@@ -845,7 +838,6 @@ describe("Claude Fable 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-fable-5-2")).toBe(true);
});
@@ -887,7 +879,6 @@ describe("Claude Opus 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(opus55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -922,7 +913,6 @@ describe("Claude Sonnet 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(sonnet55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -959,7 +949,6 @@ describe("Claude Haiku 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(haiku55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -1016,7 +1005,6 @@ describe("Claude Mythos 5.1 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(
models[0].thinkingOptions?.filter((option) => option.isDefault).map((option) => option.id),
@@ -1088,7 +1076,6 @@ describe("Claude Mythos 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-mythos-5-2")).toBe(true);
});
@@ -45,8 +45,9 @@ const SandboxFilesystemSchema = z
// Claude Agent SDK Options, maintained against @anthropic-ai/claude-agent-sdk 0.3.246.
export const ClaudeProviderOptionsSchema = z
.object({
/** Composer control, not a Claude SDK option: the provider reads it and keeps it out of the SDK options. */
/** Composer controls applied through Claude flag settings. */
fast_mode: z.boolean().optional(),
ultracode: z.boolean().optional(),
allowedTools: z.array(z.string()).optional(),
disallowedTools: z.array(z.string()).optional(),
additionalDirectories: z.array(z.string()).optional(),
@@ -6,6 +6,7 @@ import {
} from "./persisted-config.js";
import { ProviderOverrideSchema } from "./agent/provider-launch-config.js";
import {
convertLegacyClaudeUltracode,
convertLegacyOptions,
foldProfileFeatureValues,
resolveAdapter,
@@ -194,13 +195,21 @@ function foldConfigProfiles<T extends { agentProfiles?: AgentProfile[] }>(input:
options,
});
const identity = (_provider: string, options: Record<string, unknown> | undefined) => options;
const foldWith = (profile: AgentProfile, convertWith: typeof convert) =>
foldProfileFeatureValues({
const foldWith = (profile: AgentProfile, convertWith: typeof convert) => {
const folded = foldProfileFeatureValues<
Pick<AgentProfile, "provider" | "options" | "featureValues">
>({
profile,
stored: held.find((candidate) => candidate.id === profile.id),
source,
convert: convertWith,
});
const { providerOptions, ...converted } = convertLegacyClaudeUltracode(
{ ...folded, thinkingOptionId: profile.thinkingOptionId, providerOptions: folded.options },
resolveAdapter({ provider: profile.provider, extendsOf: (id) => providers?.[id]?.extends }),
);
return { ...converted, options: providerOptions };
};
return {
...config,
agentProfiles: config.agentProfiles.map((profile) => {