UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

282 lines (267 loc) • 13.1 kB
/** * Claude Code custom-agent definition injection (devlog 260712 070). * * The Agent tool's `model` argument is a hard 4-alias enum (2.1.207 binary), but an * agent DEFINITION's frontmatter `model:` is a free string ("Model alias this agent * uses. If omitted, inherits the parent's model"). So we sync the featured * subagent roster (config.subagentModels, <=5) plus the main model (when not * already covered) into ~/.claude/agents/ocx-*.md — one dispatchable * `subagent_type` per routed model, loaded at the next session start. * * Ownership contract: this module only creates/overwrites/deletes files matching * `ocx-*.md` inside the agents dir. User-authored agents are never touched. */ import { lstatSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import type { OcxConfig } from "../types"; import { renameAtomicFile } from "../lib/windows-atomic-replace"; import { assertNotRealClaudeConfigUnderTest } from "../lib/test-home-guard"; import { accountsAt200k, entryParts, SAFE_AGENT_MODEL_ID, withSubagentContextMarker } from "./subagent-model"; import { stripOneMillionMarker } from "./context-windows"; import { claudeConfigDir } from "./gateway-cache"; import { DEFAULT_SUBAGENT_MODELS } from "../config"; import { effectiveBlockedSkillNames, resolveInboundModel } from "./inbound"; import { AnthropicRequestError } from "./inbound-records"; import { siblingOfLivePort } from "../codex/sibling-start"; export interface ClaudeAgentDef { file: string; name: string; model: string; description: string; effort?: NonNullable<OcxConfig["claudeCode"]>["subagentEffort"]; blockedSkills: readonly string[]; } const OWNED_PREFIX = "ocx-"; /** Ownership proof (audit 071 #2): a file without this marker is NEVER touched. */ const GENERATED_MARKER = "generated-by: opencodex"; function sanitizeName(value: string): string { const cleaned = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); return cleaned.length > 0 ? cleaned : "model"; } /** * The user's default model as saved by the /model picker (settings.json `model`). * `model: "inherit"` in agent frontmatter is DISPROVEN on 2.1.207 (live: a * no-model ocx-self dispatch fell back to claude-fable-5 — devlog 072), so the * self-clone pins this value instead, refreshed at every launch-time sync. */ function pickerDefaultModel(configDir: string): string | null { try { const parsed = JSON.parse(readFileSync(join(configDir, "settings.json"), "utf8")) as Record<string, unknown>; return typeof parsed.model === "string" && parsed.model.trim() !== "" ? parsed.model.trim() : null; } catch { return null; } } export function buildClaudeAgentDefs( config: OcxConfig, windows: Record<string, number>, configDir = claudeConfigDir(), /** * The roster to generate defs from, overriding local `config.subagentModels` (#4236). * * A connected client's local roster is whatever it had before it joined the hub — on a fresh * client, the five native defaults — while the hub's featured roster is the list that * actually routes. Passing it in keeps this function pure and keeps the override visible at * the call site instead of hidden behind a config read. * * Undefined preserves today's behaviour exactly, including "unset means the defaults, an * explicit `[]` means none". */ rosterOverride?: readonly string[], ): ClaudeAgentDef[] { const blockedSkills = effectiveBlockedSkillNames(config.claudeCode); const blockedSkillsFor = (model: string): readonly string[] => { const unmarked = stripOneMillionMarker(model); try { const nativePassthrough = config.claudeCode?.nativePassthrough !== false && !unmarked.includes("/") && /^(claude|anthropic)(?:-|$)/i.test(unmarked) && resolveInboundModel(unmarked, config.claudeCode) === unmarked; return nativePassthrough ? [] : blockedSkills; } catch (error) { // A stale Desktop selector must not break the roster or acquire native exemptions. if (error instanceof AnthropicRequestError) return blockedSkills; throw error; } }; const defs: ClaudeAgentDef[] = []; const usedNames = new Set<string>(); const coveredModels = new Set<string>(); const push = (name: string, alias: string, description: string) => { // Generated defs mark [1m] on the authoritative window only — never the // main-session auto-context predicate (a 372K route marked [1m] would be // accounted at 1M with no compaction safety net in the subagent). const model = withSubagentContextMarker(alias, windows, accountsAt200k(config)); const bare = alias.toLowerCase(); if (coveredModels.has(bare)) return; coveredModels.add(bare); let unique = name; for (let i = 2; usedNames.has(unique); i++) unique = `${name}-${i}`; usedNames.add(unique); defs.push({ file: `${OWNED_PREFIX}${unique}.md`, name: `${OWNED_PREFIX}${unique}`, model, description, effort: config.claudeCode?.subagentEffort, blockedSkills: blockedSkillsFor(model), }); }; // Default roster applies only when the field is UNSET — an explicit [] is // respected (audit 071 #6: an upgraded config must not lose the default five). const roster = rosterOverride ?? (config.subagentModels === undefined ? DEFAULT_SUBAGENT_MODELS : config.subagentModels); for (const entry of roster.slice(0, 5)) { if (typeof entry !== "string" || !SAFE_AGENT_MODEL_ID.test(entry.trim())) continue; const { alias, id, provider } = entryParts(entry.trim(), config); push(sanitizeName(id), alias, `Delegate work to ${id} (${provider}) via opencodex routing. General-purpose worker/explorer on that model. ${NO_MODEL_ARG}`); } // Self-clone slot: pin the picker-saved default (settings.json), falling back to // config.claudeCode.model. `inherit` is NOT honored by 2.1.207 (live-disproven, // devlog 072); a session started with a divergent --model stays divergent until // the next launch sync — documented limit. No resolvable default -> no self def. const selfModel = pickerDefaultModel(configDir) ?? (config.claudeCode?.model?.trim() || null); if (selfModel) { const marked = withSubagentContextMarker(selfModel, windows, accountsAt200k(config)); defs.push({ file: `${OWNED_PREFIX}self.md`, name: `${OWNED_PREFIX}self`, model: marked, description: `Self-clone: delegate to your default main model (${marked}), synced from the /model picker at launch. ${NO_MODEL_ARG}`, effort: config.claudeCode?.subagentEffort, blockedSkills: blockedSkillsFor(marked), }); } return defs; } function skillNameLiteral(name: string): string { return JSON.stringify(name) .replaceAll("`", "\\u0060") .replaceAll("<", "\\u003c") .replaceAll(">", "\\u003e"); } function renderAgentDef(def: ClaudeAgentDef): string { const blockedSkillGuard = def.blockedSkills.length === 0 ? [] : [ "", `Do not invoke blocked Claude Code skills: ${def.blockedSkills.map(skillNameLiteral).join(", ")}.`, "Their document bundles are intentionally omitted for routed models; continue without loading them.", ]; // YAML frontmatter: model ids carry dots/brackets — always double-quote scalars. return [ "---", `name: ${JSON.stringify(def.name)}`, `description: ${JSON.stringify(def.description)}`, `model: ${JSON.stringify(def.model)}`, ...(def.effort ? [`effort: ${JSON.stringify(def.effort)}`] : []), "---", "", `<!-- ${GENERATED_MARKER} -->`, // Proxy routing directive (devlog 072): 2.1.207 does not honor custom gateway // ids in agent frontmatter (falls back to sonnet — live-proven), but the agent // BODY rides the subagent's system prompt verbatim. The proxy detects this // directive and overrides the request model before routing/passthrough. `<!-- ocx-route: ${def.model} -->`, ...(def.effort ? [`<!-- ocx-effort: ${def.effort} -->`] : []), "", `You are a delegated worker running on \`${def.model}\` through the local opencodex proxy.`, `IDENTITY: your ACTUAL underlying model is \`${def.model}\` — the opencodex proxy routes this`, "session there regardless of what model name the Claude Code harness displays or claims.", "If asked which model you are, answer with the id above; do not guess a Claude model name.", ...blockedSkillGuard, "", "Complete the dispatched task directly and report results concisely. This file is", "auto-generated by opencodex (`ocx claude`) from the featured subagent roster —", "manual edits will be overwritten; remove the model from the roster to drop it.", "", ].join("\n"); } /** True only for a REGULAR file we generated (marker present; symlinks never owned). */ function isOwnedFile(path: string): boolean { try { const st = lstatSync(path); if (!st.isFile()) return false; // symlink or dir: never touch (audit 071 #2) return readFileSync(path, "utf8").includes(GENERATED_MARKER); } catch { return false; } } /** * Sync owned agent files: write/overwrite current defs, prune stale ocx-*.md, * never touch anything else. Ownership requires the generated marker; writes are * atomic (tmp + rename). Best-effort — returns null on any failure. */ export function syncClaudeAgentDefs(defs: readonly ClaudeAgentDef[], configDir = claudeConfigDir()): string[] | null { // Outside the best-effort catch: under an armed test process a write or prune of the // real Claude agents directory must throw, never degrade to "returned null" (#6775). // Every path written is judged by where it resolves, including a pre-placed link named like // a definition or its temporary file. const agentsDir = join(configDir, "agents"); assertNotRealClaudeConfigUnderTest( configDir, agentsDir, ...defs.flatMap(def => [join(agentsDir, def.file), `${join(agentsDir, def.file)}.tmp-${process.pid}`]), ); try { const dir = join(configDir, "agents"); if (defs.length === 0) { try { lstatSync(dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; } } else { mkdirSync(dir, { recursive: true }); } const keep = new Set(defs.map(d => d.file)); for (const existing of readdirSync(dir)) { if (!existing.startsWith(OWNED_PREFIX) || !existing.endsWith(".md")) continue; if (!keep.has(existing) && isOwnedFile(join(dir, existing))) { try { unlinkSync(join(dir, existing)); } catch { /* best-effort prune */ } } } const written: string[] = []; for (const def of defs) { const target = join(dir, def.file); // A pre-existing ocx-* file WITHOUT our marker is user property: skip the def. try { lstatSync(target); if (!isOwnedFile(target)) continue; } catch { /* does not exist: ours to create */ } const tmp = `${target}.tmp-${process.pid}`; writeFileSync(tmp, renderAgentDef(def), { encoding: "utf8", mode: 0o644 }); renameAtomicFile(tmp, target, undefined, "claude-agents"); written.push(def.file); } return written; } catch { return null; } } /** Launch-time hook: gate + build + sync in one call (used by ocx claude and systemEnv). */ export function injectClaudeAgentDefs( config: OcxConfig, windows: Record<string, number>, configDir?: string, /** Hub-sourced roster on a connected client; see `buildClaudeAgentDefs`. */ rosterOverride?: readonly string[], ): string[] | null { // `~/.claude/agents` is shared with the live proxy a sibling instance runs beside, which owns // both its roster and its pruning (`src/codex/sibling-start.ts`). if (siblingOfLivePort() !== null) return null; if (config.claudeCode?.enabled === false || config.claudeCode?.injectAgents === false) { // Disabled: prune verified-owned files so stale definitions stop loading // in future sessions (audit 071 #3). The roster override is irrelevant here by // construction: there is nothing to build. return syncClaudeAgentDefs([], configDir); } return syncClaudeAgentDefs(buildClaudeAgentDefs(config, windows, configDir, rosterOverride), configDir); } /** * Dispatcher directive appended to every ocx-* description. The ocx-route body * directive makes the Agent tool's `model` argument INERT (the proxy overrides * the request model before routing — live-proven), so instead of asking the * dispatcher to omit it (which caused schema-anxiety loops), we hand it a fixed * placeholder: any value works; "haiku" is canonical because a haiku-labeled call * is visibly a placeholder in the Claude Code UI, while "sonnet" was * indistinguishable from a genuine Sonnet call (issue #252). */ const NO_MODEL_ARG = "NOTE: this agent's real model is pinned by the opencodex proxy — the `model` argument is ignored. Pass model: \"haiku\" as a placeholder (or omit it); routing is unaffected either way.";