Skip to content

Commit 5635eda

Browse files
jhste102labclaude
andcommitted
fix(claude): preserve generated subagent effort
Add a validated claudeCode.subagentEffort setting and render it into generated ocx agent frontmatter. Claude Code 2.1.220 collapses xhigh and max custom-agent effort to a legacy thinking budget, so carry the exact value through an owned system directive and restore it at the routed inbound boundary. Invalid persisted values degrade without discarding unrelated provider or account configuration. Co-Authored-By: Claude <[email protected]>
1 parent 693347d commit 5635eda

11 files changed

Lines changed: 220 additions & 26 deletions

File tree

‎docs-site/src/content/docs/reference/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ body-occupancy guard):
206206
| `claudeCode.bodyMaxBytes?` | `number` | `67108864` | Native passthrough cumulative body byte cap (streamed SSE and buffered non-stream). Exactly `0` disables. |
207207
| `claudeCode.authMode?` | `"proxy" \| "subscription"` | unset (auto) | How `ANTHROPIC_AUTH_TOKEN` is handled at launch. Unset means auto: opencodex detects Claude auth on every launch and picks subscription when it finds any, proxy when it finds none, and subscription with a warning when it cannot tell. An explicit value is never overridden by detection. See [Claude Code](/guides/claude-code/#auth-mode). |
208208
| `claudeCode.authModeMigratedAt?` | `string` | unset | Internal one-time marker. Written once when an upgrade pins a pre-`auto` config to `subscription`, so a deliberate subscriber is not silently moved onto the proxy. Do not set by hand. |
209+
| `claudeCode.subagentEffort?` | `"low" \| "medium" \| "high" \| "xhigh" \| "max"` | unset (inherit) | Effort written to every generated `~/.claude/agents/ocx-*.md` definition. Unset lets each subagent inherit the parent Claude Code session effort. This controls Claude Code custom-agent frontmatter; it is separate from Codex `injectionEffort` guidance and proxy-side effort caps. Regenerate the definitions by starting through `ocx claude` after changing it. |
209210

210211
### Managed record shapes
211212

‎docs-site/src/content/docs/ru/reference/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ body-occupancy):
120120
| --- | --- | --- | --- |
121121
| `claudeCode.bodyStallSec?` | `number` | `90` | Бюджет неактивности тела нативного passthrough в секундах — тишина по сырым байтам от вышестоящей стороны, пока ожидается чтение, а не общая длительность. Минимум 1. Ровно `0` отключает. |
122122
| `claudeCode.bodyMaxBytes?` | `number` | `67108864` | Ограничение суммарного размера тела нативного passthrough в байтах (потоковый SSE и буферизованный непотоковый ответ). Ровно `0` отключает. |
123+
| `claudeCode.subagentEffort?` | `"low" \| "medium" \| "high" \| "xhigh" \| "max"` | не задано (наследуется) | Уровень effort, записываемый во все сгенерированные определения `~/.claude/agents/ocx-*.md`. Если значение не задано, subagent наследует effort родительской сессии Claude Code. Это поле управляет frontmatter пользовательского агента Claude Code и не связано с Codex `injectionEffort` или ограничениями effort на стороне proxy. После изменения запустите через `ocx claude`, чтобы пересоздать определения. |
123124

124125
### Управляемые формы записей
125126

‎src/claude/agents-inject.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export interface ClaudeAgentDef {
2727
name: string;
2828
model: string;
2929
description: string;
30+
effort?: NonNullable<OcxConfig["claudeCode"]>["subagentEffort"];
3031
blockedSkills: readonly string[];
3132
}
3233

@@ -99,6 +100,7 @@ export function buildClaudeAgentDefs(config: OcxConfig, windows: Record<string,
99100
name: `${OWNED_PREFIX}${unique}`,
100101
model,
101102
description,
103+
effort: config.claudeCode?.subagentEffort,
102104
blockedSkills: blockedSkillsFor(model),
103105
});
104106
};
@@ -124,6 +126,7 @@ export function buildClaudeAgentDefs(config: OcxConfig, windows: Record<string,
124126
name: `${OWNED_PREFIX}self`,
125127
model: marked,
126128
description: `Self-clone: delegate to your default main model (${marked}), synced from the /model picker at launch. ${NO_MODEL_ARG}`,
129+
effort: config.claudeCode?.subagentEffort,
127130
blockedSkills: blockedSkillsFor(marked),
128131
});
129132
}
@@ -149,6 +152,7 @@ function renderAgentDef(def: ClaudeAgentDef): string {
149152
`name: ${JSON.stringify(def.name)}`,
150153
`description: ${JSON.stringify(def.description)}`,
151154
`model: ${JSON.stringify(def.model)}`,
155+
...(def.effort ? [`effort: ${JSON.stringify(def.effort)}`] : []),
152156
"---",
153157
"",
154158
`<!-- ${GENERATED_MARKER} -->`,
@@ -157,6 +161,7 @@ function renderAgentDef(def: ClaudeAgentDef): string {
157161
// BODY rides the subagent's system prompt verbatim. The proxy detects this
158162
// directive and overrides the request model before routing/passthrough.
159163
`<!-- ocx-route: ${def.model} -->`,
164+
...(def.effort ? [`<!-- ocx-effort: ${def.effort} -->`] : []),
160165
"",
161166
`You are a delegated worker running on \`${def.model}\` through the local opencodex proxy.`,
162167
`IDENTITY: your ACTUAL underlying model is \`${def.model}\` — the opencodex proxy routes this`,

‎src/claude/inbound.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -147,23 +147,40 @@ export function effectiveBlockedSkillNames(cc?: Pick<OcxClaudeCodeConfig, "block
147147
* FIRST directive wins; the scan is bounded to the system field.
148148
*/
149149
const OCX_ROUTE_RE = /<!--\s*ocx-route:\s*([^\s]+)\s*-->/;
150+
const OCX_EFFORT_RE = /<!--\s*ocx-effort:\s*(low|medium|high|xhigh|max)\s*-->/;
150151

151-
export function extractOcxRouteDirective(body: unknown): string | null {
152+
function systemText(body: unknown): string | null {
152153
if (!isRec(body)) return null;
153154
const system = body.system;
154-
let text: string | undefined;
155-
if (typeof system === "string") text = system;
156-
else if (Array.isArray(system)) {
157-
text = system
158-
.filter((b): b is Rec => isRec(b) && b.type === "text" && typeof b.text === "string")
159-
.map(b => b.text as string)
160-
.join("\n");
161-
}
155+
if (typeof system === "string") return system || null;
156+
if (!Array.isArray(system)) return null;
157+
const text = system
158+
.filter((b): b is Rec => isRec(b) && b.type === "text" && typeof b.text === "string")
159+
.map(b => b.text as string)
160+
.join("\n");
161+
return text || null;
162+
}
163+
164+
export function extractOcxRouteDirective(body: unknown): string | null {
165+
const text = systemText(body);
162166
if (!text) return null;
163167
const match = OCX_ROUTE_RE.exec(text);
164168
return match ? match[1]! : null;
165169
}
166170

171+
/**
172+
* Claude Code 2.1.220 collapses custom-agent frontmatter `effort: max` and
173+
* `effort: xhigh` into the legacy `thinking.budget_tokens` shape. Preserve the
174+
* exact generated-agent setting through the same trusted system-body channel as
175+
* ocx-route so the inbound translator can restore `output_config.effort`.
176+
*/
177+
export function extractOcxEffortDirective(body: unknown): NonNullable<OcxClaudeCodeConfig["subagentEffort"]> | null {
178+
const text = systemText(body);
179+
if (!text) return null;
180+
const match = OCX_EFFORT_RE.exec(text);
181+
return match ? match[1] as NonNullable<OcxClaudeCodeConfig["subagentEffort"]> : null;
182+
}
183+
167184
/** Injected-skill payloads below this size are never stubbed (not worth it). */
168185
const SKILL_ELISION_MIN_CHARS = 10_000;
169186
const SKILL_TEXT_MARKER = "Base directory for this skill: ";

‎src/config.ts‎

Lines changed: 59 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
MODEL_ADAPTER_OVERRIDE_ALLOWED,
2121
OPENAI_PROVIDER_TIER_VERSION,
2222
REASONING_SUMMARY_DELIVERY_VALUES,
23+
type OcxClaudeCodeConfig,
2324
type OcxConfig,
2425
type OcxProviderConfig,
2526
} from "./types";
@@ -699,15 +700,18 @@ const configSchema = z.object({
699700
const claudeCode = (config as { claudeCode?: unknown }).claudeCode;
700701
if (claudeCode !== undefined && (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode))) {
701702
ctx.addIssue({ code: "custom", path: ["claudeCode"], message: "claudeCode must be an object" });
702-
} else if (claudeCode && "desktopProfile" in claudeCode && (claudeCode as { desktopProfile?: unknown }).desktopProfile !== undefined) {
703-
try {
704-
parseDesktopProfile((claudeCode as { desktopProfile?: unknown }).desktopProfile);
705-
} catch (error) {
706-
ctx.addIssue({
707-
code: "custom",
708-
path: ["claudeCode", "desktopProfile"],
709-
message: error instanceof Error ? error.message : String(error),
710-
});
703+
} else if (claudeCode) {
704+
const claude = claudeCode as { desktopProfile?: unknown };
705+
if (claude.desktopProfile !== undefined) {
706+
try {
707+
parseDesktopProfile(claude.desktopProfile);
708+
} catch (error) {
709+
ctx.addIssue({
710+
code: "custom",
711+
path: ["claudeCode", "desktopProfile"],
712+
message: error instanceof Error ? error.message : String(error),
713+
});
714+
}
711715
}
712716
}
713717

@@ -1007,6 +1011,34 @@ function warnDegradedHostname(rawParsed: unknown, validated: OcxConfig): void {
10071011
}
10081012
}
10091013

1014+
const CLAUDE_SUBAGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
1015+
1016+
function isClaudeSubagentEffort(value: unknown): value is NonNullable<OcxClaudeCodeConfig["subagentEffort"]> {
1017+
return typeof value === "string" && CLAUDE_SUBAGENT_EFFORTS.includes(value as typeof CLAUDE_SUBAGENT_EFFORTS[number]);
1018+
}
1019+
1020+
function rawClaudeSubagentEffort(rawParsed: unknown): unknown {
1021+
const raw = rawConfigRecord(rawParsed);
1022+
const claudeCode = raw?.claudeCode;
1023+
if (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode)) return undefined;
1024+
return (claudeCode as Record<string, unknown>).subagentEffort;
1025+
}
1026+
1027+
function normalizeClaudeSubagentEffort(config: OcxConfig, rawParsed: unknown): OcxConfig {
1028+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
1029+
if (rawEffort === undefined || isClaudeSubagentEffort(rawEffort)) return config;
1030+
const normalized = { ...config, claudeCode: { ...config.claudeCode } };
1031+
delete normalized.claudeCode!.subagentEffort;
1032+
return normalized;
1033+
}
1034+
1035+
function warnDegradedClaudeSubagentEffort(rawParsed: unknown): void {
1036+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
1037+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
1038+
console.warn(`⚠️ config.json claudeCode.subagentEffort ${JSON.stringify(rawEffort)} is invalid (expected ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}) — ignoring it. Other settings were preserved.`);
1039+
}
1040+
}
1041+
10101042
type NativeSubagentPersistedField = "injectionModel" | "injectionEffort" | "syncCodexSubagentDefaults";
10111043

10121044
function rawConfigRecord(rawParsed: unknown): Record<string, unknown> | null {
@@ -1082,8 +1114,9 @@ export function loadConfig(): OcxConfig {
10821114
const config = result.data as OcxConfig;
10831115
warnDegradedStreamMode(parsed, config);
10841116
warnDegradedHostname(parsed, config);
1117+
warnDegradedClaudeSubagentEffort(parsed);
10851118
warnDegradedNativeSubagentConfig(parsed, config);
1086-
return normalizeNativeSubagentSync(config, parsed);
1119+
return normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed);
10871120
}
10881121
// Schema validation failed — merge defaults into the raw object instead of
10891122
// discarding it entirely, so pool accounts and providers survive a missing
@@ -1099,8 +1132,9 @@ export function loadConfig(): OcxConfig {
10991132
warnConfigRepaired(configPath, result.error);
11001133
const config = retryResult.data as OcxConfig;
11011134
warnDegradedHostname(parsed, config);
1135+
warnDegradedClaudeSubagentEffort(parsed);
11021136
warnDegradedNativeSubagentConfig(parsed, config);
1103-
return normalizeNativeSubagentSync(config, parsed);
1137+
return normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed);
11041138
}
11051139
// Merge couldn't fix it — truly broken config
11061140
warnAndBackupInvalidConfig(configPath, result.error);
@@ -1131,12 +1165,16 @@ function configPlaceholderWarnings(config: OcxConfig): string[] {
11311165
}
11321166

11331167
function validFileConfigDiagnostics(config: OcxConfig, rawParsed: unknown): ConfigDiagnostics {
1134-
// An unsafe hand-edited opt-in is disabled in memory instead of rejecting
1168+
// Unsafe hand-edited optional values are disabled in memory instead of rejecting
11351169
// the entire config, which would hide unrelated providers/accounts. The next
11361170
// ordinary save persists the normalized absence.
11371171
const syncDisabledReason = nativeSubagentSyncDisabledReason(config, rawParsed);
1138-
const normalized = normalizeNativeSubagentSync(config, rawParsed);
1172+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
1173+
const normalized = normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, rawParsed), rawParsed);
11391174
const warnings = configPlaceholderWarnings(normalized);
1175+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
1176+
warnings.push(`claudeCode.subagentEffort ignored: expected one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`);
1177+
}
11401178
warnings.push(...malformedNativeSubagentFields(rawParsed).map(malformedNativeSubagentFieldWarning));
11411179
if (syncDisabledReason) {
11421180
warnings.push(`syncCodexSubagentDefaults ignored: ${syncDisabledReason}`);
@@ -1190,10 +1228,16 @@ function blankHostnameError(value: unknown): string | null {
11901228
return null;
11911229
}
11921230

1231+
function claudeSubagentEffortError(value: unknown): string | null {
1232+
const effort = rawClaudeSubagentEffort(value);
1233+
if (effort === undefined || isClaudeSubagentEffort(effort)) return null;
1234+
return `schema_invalid: claudeCode.subagentEffort: must be one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`;
1235+
}
1236+
11931237
/** Validate an in-memory config candidate without touching disk. Used by headless CLI import/set. */
11941238
export function validateConfigCandidate(value: unknown): { ok: true; config: OcxConfig } | { ok: false; error: string } {
1195-
const hostnameError = blankHostnameError(value);
1196-
if (hostnameError) return { ok: false, error: hostnameError };
1239+
const boundaryError = blankHostnameError(value) ?? claudeSubagentEffortError(value);
1240+
if (boundaryError) return { ok: false, error: boundaryError };
11971241
const result = configSchema.safeParse(value);
11981242
if (result.success) return { ok: true, config: result.data as OcxConfig };
11991243
return { ok: false, error: schemaDiagnosticsError(result.error) };

‎src/server/claude-messages.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import { FORWARD_HEADERS } from "../adapters/openai-responses";
1010
import { enforceAnthropicImageLimits } from "../adapters/anthropic-image-guard";
1111
import { normalizeAnthropicImages } from "../adapters/anthropic-image-normalize";
12-
import { AnthropicRequestError, anthropicToResponsesTranslation, extractOcxRouteDirective, resolveInboundModel, type ClaudeCacheKeySource } from "../claude/inbound";
12+
import { AnthropicRequestError, anthropicToResponsesTranslation, extractOcxEffortDirective, extractOcxRouteDirective, resolveInboundModel, type ClaudeCacheKeySource } from "../claude/inbound";
1313
import { resolveDesktop3pAlias } from "../claude/desktop-3p";
1414
import { recordDesktopRequest } from "../claude/desktop-health";
1515
import { stripOneMillionMarker } from "../claude/context-windows";
@@ -539,6 +539,11 @@ export async function handleClaudeMessages(
539539
const routeOverride = extractOcxRouteDirective(anthropicBody);
540540
if (routeOverride && typeof anthropicBody.model === "string") {
541541
anthropicBody.model = stripOneMillionMarker(routeOverride);
542+
const effortOverride = extractOcxEffortDirective(anthropicBody);
543+
if (effortOverride) {
544+
anthropicBody.output_config = { effort: effortOverride };
545+
delete anthropicBody.thinking;
546+
}
542547
}
543548
}
544549
// Debug capture (opt-in allowlist scalars) BEFORE the passthrough branch so

‎src/types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,11 @@ export interface OcxClaudeCodeConfig {
442442
* free. Only ocx-*.md files are owned/pruned. Default: enabled.
443443
*/
444444
injectAgents?: boolean;
445+
/**
446+
* Optional Claude Code effort pinned in every generated ocx-* subagent
447+
* definition. Unset inherits the parent session effort.
448+
*/
449+
subagentEffort?: "low" | "medium" | "high" | "xhigh" | "max";
445450
/** Claude-originated web-search override. Unset fields inherit the global sidecar settings. */
446451
webSearchSidecar?: { backend?: "openai" | "anthropic"; model?: string };
447452
/** Claude-originated vision override. Unset fields inherit the global sidecar settings. */

‎tests/claude-agents-inject.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,44 @@ describe("buildClaudeAgentDefs (devlog 070 + audit 071)", () => {
7777
}
7878
expect(fields.name).toBe(def!.name);
7979
expect(fields.model).toBe(def!.model);
80+
expect(fields.effort).toBeUndefined();
8081
expect(typeof fields.description).toBe("string");
8182
expect(body).toContain("generated-by: opencodex");
8283
expect(body).toContain(`ocx-route: ${def!.model}`);
8384
expect(body).toContain("IDENTITY: your ACTUAL underlying model");
8485
});
8586

87+
test("configured Claude Code subagent effort is rendered for roster and self definitions", () => {
88+
const levels = ["low", "medium", "high", "xhigh", "max"] as const;
89+
for (const effort of levels) {
90+
const dir = tempDir();
91+
writeFileSync(join(dir, "settings.json"), JSON.stringify({ model: "claude-ocx-native--gpt-5.6-sol" }));
92+
const defs = buildClaudeAgentDefs(cfg({
93+
subagentModels: ["gpt-5.6-sol"],
94+
claudeCode: { subagentEffort: effort },
95+
}), {}, dir);
96+
expect(defs).toHaveLength(2);
97+
expect(defs.every(def => def.effort === effort)).toBe(true);
98+
syncClaudeAgentDefs(defs, dir);
99+
for (const def of defs) {
100+
const body = readFileSync(join(dir, "agents", def.file), "utf8");
101+
expect(body.match(new RegExp(`^effort: ${JSON.stringify(effort)}$`, "gm"))).toHaveLength(1);
102+
expect(body).toContain(`<!-- ocx-effort: ${effort} -->`);
103+
}
104+
}
105+
});
106+
107+
test("regeneration removes a previously configured effort when the option is cleared", () => {
108+
const dir = tempDir();
109+
const configured = cfg({ subagentModels: ["gpt-5.6-sol"], claudeCode: { subagentEffort: "max" } });
110+
injectClaudeAgentDefs(configured, {}, dir);
111+
const target = join(dir, "agents", "ocx-gpt-5-6-sol.md");
112+
expect(readFileSync(target, "utf8")).toContain('effort: "max"');
113+
114+
injectClaudeAgentDefs(cfg({ subagentModels: ["gpt-5.6-sol"] }), {}, dir);
115+
expect(readFileSync(target, "utf8")).not.toContain("effort:");
116+
});
117+
86118
test("generated routed agents refuse the default blocked skill before its bundle expands", () => {
87119
const dir = tempDir();
88120
writeFileSync(join(dir, "settings.json"), JSON.stringify({ model: "claude-ocx-native--gpt-5.6-sol" }));

‎tests/claude-inbound.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test";
2-
import { AnthropicRequestError, anthropicToResponsesBody, anthropicToResponsesTranslation, effortForThinkingBudget, resolveInboundModel } from "../src/claude/inbound";
2+
import { AnthropicRequestError, anthropicToResponsesBody, anthropicToResponsesTranslation, effortForThinkingBudget, extractOcxEffortDirective, resolveInboundModel } from "../src/claude/inbound";
33
import { parseRequest } from "../src/responses/parser";
44
import { responsesRequestSchema } from "../src/responses/schema";
55

@@ -382,10 +382,19 @@ describe("ocx-route directive (devlog 072)", () => {
382382
})).toBe("gemini/gemini-3-pro");
383383
});
384384

385+
test("extracts only supported generated-agent effort values", () => {
386+
expect(extractOcxEffortDirective({ system: "<!-- ocx-effort: max -->" })).toBe("max");
387+
expect(extractOcxEffortDirective({
388+
system: [{ type: "text", text: "<!-- ocx-effort: xhigh -->" }],
389+
})).toBe("xhigh");
390+
expect(extractOcxEffortDirective({ system: "<!-- ocx-effort: ultra -->" })).toBeNull();
391+
});
392+
385393
test("absent or malformed directives return null", () => {
386394
expect(extractOcxRouteDirective({ system: "no directive here" })).toBeNull();
387395
expect(extractOcxRouteDirective({ system: [{ type: "text", text: "<!-- ocx-route: -->" }] })).toBeNull();
388396
expect(extractOcxRouteDirective({})).toBeNull();
389397
expect(extractOcxRouteDirective(null)).toBeNull();
398+
expect(extractOcxEffortDirective(null)).toBeNull();
390399
});
391400
});

0 commit comments

Comments
 (0)