Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/agent-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ import {
} from "./harness-session.js";
import {
resolveLaunchModelFlag,
resolveSpawnEffort,
resolveSpawnModelPolicy,
type CodexEffort,
type SpawnModelPolicy,
} from "./model-policy.js";
import {
Expand Down Expand Up @@ -151,6 +153,7 @@ type ProcessLiveness = "alive" | "gone" | "unknown";
export interface SpawnAgentParams {
repo: string;
model?: string;
effort?: string;
cli: CliType;
prompt: string;
boot_prompt_timeout_ms?: number;
Expand Down Expand Up @@ -754,7 +757,12 @@ export function buildLaunchCommand(
// registry-prefix registrations launch correctly. Honored for the launcher
// CLIs (claude/codex/cursor/gemini); ignored for kiro (raw cd+exec).
launcherName?: string,
opts?: { cwd?: string; envPrefix?: string; allowModelOverride?: boolean },
opts?: {
cwd?: string;
envPrefix?: string;
allowModelOverride?: boolean;
effort?: CodexEffort;
},
): string {
const safeRepo = sanitizeRepoName(repo);
const modelFlag = resolveLaunchModelFlag(cli, model, {
Expand All @@ -764,18 +772,20 @@ export function buildLaunchCommand(
const launcherModelArgs = formattedModelFlag
? ` -m ${formattedModelFlag}`
: "";
const claudeModelArgs = modelFlag === "sonnet" ? " -S" : launcherModelArgs;
const rawModelArgs = formattedModelFlag
? ` --model ${formattedModelFlag}`
: "";
const launcherWorktreeArg = opts?.cwd ? ` -w ${shellQuote(opts.cwd)}` : "";
const launcherEffortArg = opts?.effort ? ` -E ${opts.effort}` : "";
const rawCdPrefix = opts?.cwd ? `cd ${shellQuote(opts.cwd)} && ` : "";
const envPrefix = opts?.envPrefix ? `${opts.envPrefix} ` : "";
switch (cli) {
case "claude":
// repoGolem launcher handles env vars via ralph-registry
return `${envPrefix}${launcherName ?? `${safeRepo}Claude`} -s${launcherModelArgs}${launcherWorktreeArg}`;
return `${envPrefix}${launcherName ?? `${safeRepo}Claude`} -s${claudeModelArgs}${launcherWorktreeArg}`;
case "codex":
return `${envPrefix}${launcherName ?? `${safeRepo}Codex`} -s${launcherModelArgs}${launcherWorktreeArg}`;
return `${envPrefix}${launcherName ?? `${safeRepo}Codex`} -s${launcherModelArgs}${launcherEffortArg}${launcherWorktreeArg}`;
case "gemini":
// repoGolem launcher (e.g. golemsGemini -s) wires antigravity + MCP.
return `${envPrefix}${launcherName ?? `${safeRepo}Gemini`} -s${launcherModelArgs}${launcherWorktreeArg}`;
Expand Down Expand Up @@ -4673,6 +4683,7 @@ export class AgentEngine {
*/
async spawnAgent(params: SpawnAgentParams): Promise<SpawnAgentResult> {
const modelPolicy = resolveSpawnModelPolicy(params.cli, params.model);
const effort = resolveSpawnEffort(params.cli, params.effort);
const spawnParams: SpawnAgentParams = {
...params,
model: modelPolicy.effective_model,
Expand Down Expand Up @@ -4891,6 +4902,7 @@ export class AgentEngine {
cwd: spawnParams.cwd,
envPrefix: spawnParams.mcp_env,
allowModelOverride: modelPolicy.override_allowed,
effort: effort ?? undefined,
},
);
try {
Expand Down
92 changes: 88 additions & 4 deletions src/model-policy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { CliType } from "./agent-types.js";

export const MODEL_OVERRIDE_ENV = "REPOGOLEM_ALLOW_MODEL";
export const CODEX_EFFORT_VALUES = [
"medium",
"high",
"xhigh",
"ultra",
] as const;
export type CodexEffort = (typeof CODEX_EFFORT_VALUES)[number];

export interface CliModelPolicyContract {
defaultModel: string;
Expand Down Expand Up @@ -129,6 +136,47 @@ function ownModelAlias(cli: CliType, normalized: string): string | null {
return typeof alias === "string" && alias ? alias : null;
}

function modelAliasUsesUngatedLauncherPath(
cli: CliType,
alias: string,
): boolean {
if (cli === "claude") return alias === "sonnet";
return cli === "gemini" || cli === "kiro";
}

function acceptedModelNames(
cli: CliType,
allowModelOverride: boolean,
): string[] {
const contract = MODEL_POLICY_CONTRACT.cli[cli];
const aliases = Object.keys(contract.modelAliases).filter(
(alias) =>
allowModelOverride || modelAliasUsesUngatedLauncherPath(cli, alias),
);
return [...new Set([contract.defaultModel, ...aliases])];
}

export function resolveSpawnEffort(
cli: CliType,
effort?: string,
): CodexEffort | null {
const requested = effort?.trim();
if (!requested) return null;

if (!(CODEX_EFFORT_VALUES as readonly string[]).includes(requested)) {
throw new Error(
`Invalid Codex effort "${requested}". Accepted values: ${CODEX_EFFORT_VALUES.join(", ")}. No agent was spawned.`,
);
}
if (cli !== "codex") {
throw new Error(
`Codex effort "${requested}" cannot be used with cli "${cli}". Set cli to "codex" or omit effort. No agent was spawned.`,
);
}

return requested as CodexEffort;
}

export function resolveModelAlias(cli: CliType, model: string): string {
const trimmed = model.trim();
const normalized = normalizeModelKey(trimmed);
Expand All @@ -154,6 +202,13 @@ export function resolveLaunchModelFlag(
}

const alias = ownModelAlias(cli, normalizeModelKey(requested));
if (
cli === "claude" &&
alias !== "sonnet" &&
!opts?.allowModelOverride
) {
return null;
}
return alias ?? null;
}

Expand All @@ -170,6 +225,22 @@ export function resolveSpawnModelPolicy(
const requestedOrDefault = requestedWasOmitted ? defaultModel : requestedModel;
const resolvedRequested = resolveModelAlias(cli, requestedOrDefault);

// Cursor deliberately accepts arbitrary model strings behind its escape
// hatch. Every launcher-backed CLI, however, has a finite alias table. Do
// not let the older Codex coercion branch turn an unknown alias into an
// apparently successful default-model spawn.
if (
!requestedWasOmitted &&
cli !== "cursor" &&
!modelMatchesDefault(cli, requestedModel) &&
ownModelAlias(cli, normalizeModelKey(requestedModel)) === null
) {
const acceptedModels = acceptedModelNames(cli, overrideAllowed);
throw new Error(
`Unsupported model "${requestedModel}" for cli "${cli}": without a valid alias, the launcher would actually run "${defaultModel}". Accepted models: ${acceptedModels.join(", ")}. No agent was spawned.`,
);
}

if (
!requestedWasOmitted &&
!contract.allowModelOverrideByDefault &&
Expand All @@ -195,14 +266,27 @@ export function resolveSpawnModelPolicy(
};
}

const launcherModel = requestedWasOmitted
? null
: resolveLaunchModelFlag(cli, resolvedRequested, {
allowModelOverride: overrideAllowed,
});
if (
!requestedWasOmitted &&
!modelMatchesDefault(cli, resolvedRequested) &&
launcherModel === null
) {
const acceptedModels = acceptedModelNames(cli, overrideAllowed);
throw new Error(
`Unsupported model "${requestedModel}" for cli "${cli}": without a valid alias, the launcher would actually run "${defaultModel}". Accepted models: ${acceptedModels.join(", ")}. No agent was spawned.`,
Comment on lines +277 to +281

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the public opus spawn alias

When REPOGOLEM_ALLOW_MODEL is unset, callers that explicitly request Claude model: "opus" now reach this branch and fail, even though opus was accepted before this commit and the deployed Pages demo still presents successful spawn_agent(..., model="opus") calls in landing/index.html:1074 and landing/index.html:1538. This is especially disruptive for the legacy aggregate tools whose nested model remains required; normalize opus to the default Claude launch with no model flag rather than rejecting an established tool input.

AGENTS.md reference: AGENTS.md:L44-L47

Useful? React with 👍 / 👎.

);
Comment on lines +280 to +282

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preflight all models before aggregate mutations

When spawn_in_workspace contains an unsupported model, this new exception is reached only from engine.spawnAgent() after src/server.ts has created the workspace, and if the invalid entry follows a valid one, earlier agents have already been spawned. The catch path reports the failure but does not roll those mutations back, so the error's claim that no agent was spawned is false and the nominally atomic tool leaves a partial team; new_worktree_split similarly prepares a worktree before reaching this validation. Validate every requested model at each tool boundary before creating workspaces/worktrees or starting the spawn loop.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5c38c8f. new_worktree_split now validates the requested model before worktree preparation, and spawn_in_workspace validates every normalized agent model before workspace/surface mutation. Added regressions proving no worktree command, workspace creation, or split occurs on invalid input. Exact-head verification: 2,381/2,381 full tests, 63/63 pre-PR checks, build and typecheck green.

}

return {
cli,
requested_model: requestedModel,
effective_model: resolvedRequested,
launcher_model:
requestedWasOmitted || modelMatchesDefault(cli, resolvedRequested)
? null
: resolvedRequested,
launcher_model: launcherModel,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
coerced: false,
warnings: [],
override_env: MODEL_OVERRIDE_ENV,
Expand Down
18 changes: 18 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ import { assertMutationAllowed, parseReservedModeKey } from "./mode-policy.js";
import { extractPrefix, replaceTaskSuffix } from "./naming.js";
import { createStaleBuildWarner, RUNNING_VERSION } from "./version.js";
import { buildSpawnToolReturn, shapeSpawnResponse } from "./spawn-response.js";
import {
CODEX_EFFORT_VALUES,
resolveSpawnEffort,
resolveSpawnModelPolicy,
} from "./model-policy.js";
import { StateManager } from "./state-manager.js";
import { createDefaultCloseForensicsRunner } from "./close-forensics.js";
import {
Expand Down Expand Up @@ -9159,6 +9164,12 @@ export function createServer(opts?: CreateServerOptions): McpServer {
.describe(
"OPTIONAL — leave UNSET so the launcher pins the top-tier model. Only set this if you have a specific reason NOT to use the top model (e.g. a deliberately cheaper 'sonnet' pass, or a non-claude engine variant like 'codex'). Never pass 'opus' for claude — the top Claude model is already the default.",
),
effort: z
.enum(CODEX_EFFORT_VALUES)
.optional()
.describe(
"Optional Codex reasoning effort passed to the repoGolem launcher. Accepted values: medium, high, xhigh, ultra. The launcher defaults to xhigh when omitted; max is not accepted by the current launcher.",
),
cli: z
.enum(["claude", "codex", "gemini", "kiro", "cursor"])
.describe("CLI tool to launch"),
Expand Down Expand Up @@ -9264,6 +9275,8 @@ export function createServer(opts?: CreateServerOptions): McpServer {
selectedRoleField,
);
const effectiveRole = normalizedRole.role;
resolveSpawnModelPolicy(args.cli, args.model);
resolveSpawnEffort(args.cli, args.effort);
const bootPromptPath = getBootPromptPath(args.boot_prompt_path);
assertBootPromptMode(args.prompt, bootPromptPath);
assertSpawnPromptInputAllowed({
Expand Down Expand Up @@ -9353,6 +9366,7 @@ export function createServer(opts?: CreateServerOptions): McpServer {
result = await engine.spawnAgent({
repo: args.repo,
model: args.model,
effort: args.effort,
cli: args.cli,
prompt: spawnPrompt,
boot_prompt_pending:
Expand Down Expand Up @@ -9713,6 +9727,7 @@ export function createServer(opts?: CreateServerOptions): McpServer {
let result: Awaited<ReturnType<typeof engine.spawnAgent>> | undefined;
let mutationWorkspace: string | undefined;
try {
resolveSpawnModelPolicy(args.cli, args.model);
assertBootPromptMode(args.prompt, null);
assertSpawnPromptInputAllowed({
tool: "new_worktree_split",
Expand Down Expand Up @@ -10032,6 +10047,9 @@ export function createServer(opts?: CreateServerOptions): McpServer {
compatibilityWarning: normalizedRole.warning,
};
});
for (const agent of normalizedAgents) {
resolveSpawnModelPolicy(agent.cli, agent.model);
}
const compatibilityWarnings = normalizedAgents.flatMap((agent) =>
agent.compatibilityWarning ? [agent.compatibilityWarning] : [],
);
Expand Down
26 changes: 18 additions & 8 deletions tests/agent-engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ describe("AgentEngine", () => {
).mock.calls[0];
expect(surface).toBe("surface:new");
expect(opts).toEqual({ workspace: "ws:1" });
expect(launchCmd).toBe("brainlayerClaude -s -m sonnet");
expect(launchCmd).toBe("brainlayerClaude -s -S");
});

it("launches with the launcher name resolved by preflight", async () => {
Expand Down Expand Up @@ -4237,6 +4237,7 @@ describe("AgentEngine", () => {

it.each([
[
"codex",
"codex",
"019d9aa5-93c0-7a52-9c47-9be1f7625f3e",
`gpt-5.4
Expand All @@ -4245,25 +4246,28 @@ To continue this session, run codex resume 019d9aa5-93c0-7a52-9c47-9be1f7625f3e`
],
[
"claude",
"sonnet",
"5b9f4f35-2942-4c8b-b1af-d89d4e36c95d",
`Claude Code
Session ID: 5b9f4f35-2942-4c8b-b1af-d89d4e36c95d`,
],
[
"cursor",
"auto",
"9e26fe1a-2374-4b15-b9b2-646ac7a8c2ef",
`Cursor Agent
chatId: 9e26fe1a-2374-4b15-b9b2-646ac7a8c2ef`,
],
[
"gemini",
"pro",
"8c2f7f0c-00ee-4c6e-856d-cc7ae91f5274",
`Gemini CLI
Resumable session: 8c2f7f0c-00ee-4c6e-856d-cc7ae91f5274`,
],
] as const)(
"captures %s session ids from the boot banner within the first sweep",
async (cli, sessionId, banner) => {
async (cli, model, sessionId, banner) => {
liveSurfaces = [makeSpawnSurface()];
(mockClient.readScreen as ReturnType<typeof vi.fn>).mockResolvedValue({
surface: "surface:new",
Expand All @@ -4275,7 +4279,7 @@ Resumable session: 8c2f7f0c-00ee-4c6e-856d-cc7ae91f5274`,
engine.startSweep(1000);
const result = await engine.spawnAgent({
repo: "brainlayer",
model: "sonnet",
model,
cli,
prompt: "Fix gap F",
});
Expand Down Expand Up @@ -8788,7 +8792,6 @@ To continue this session, run codex resume ${sessionId}`,
await expect(
defaultEngine.spawnAgent({
repo: `missinglauncher${suffix}`,
model: "test",
cli,
prompt: "",
}),
Expand All @@ -8815,7 +8818,6 @@ To continue this session, run codex resume ${sessionId}`,
await expect(
defaultEngine.spawnAgent({
repo: "missinglauncher",
model: "test",
cli: "claude",
prompt: "",
cwd: "/tmp/cmux-worktree",
Expand Down Expand Up @@ -10580,9 +10582,17 @@ describe("buildLaunchCommand", () => {
);
});

it("passes an explicit Codex effort to the repoGolem launcher", () => {
expect(
buildLaunchCommand("codex", "brainlayer", undefined, undefined, {
effort: "medium",
}),
).toBe("brainlayerCodex -s -E medium");
});

it("adds safe model flags for recognized launcher model aliases", () => {
expect(buildLaunchCommand("claude", "brainlayer", "sonnet")).toBe(
"brainlayerClaude -s -m sonnet",
"brainlayerClaude -s -S",
);
expect(
buildLaunchCommand("codex", "brainlayer", "gpt-5.3-codex-spark"),
Expand Down Expand Up @@ -10683,7 +10693,7 @@ describe("buildLaunchCommand", () => {
buildLaunchCommand("claude", "golems", "sonnet", undefined, {
cwd: "/p/wt",
}),
).toBe("golemsClaude -s -m sonnet -w '/p/wt'");
).toBe("golemsClaude -s -S -w '/p/wt'");
expect(
buildLaunchCommand("kiro", "golems", undefined, undefined, {
cwd: "/p/wt",
Expand Down Expand Up @@ -10714,7 +10724,7 @@ describe("buildLaunchCommand", () => {
"sonnet",
"agenthtmlhostClaude",
),
).toBe("agenthtmlhostClaude -s -m sonnet");
).toBe("agenthtmlhostClaude -s -S");
});

it("honors an explicitly resolved launcher name for gemini", () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/agent-hierarchy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ describe("Agent Hierarchy", () => {
// Spawn a child (second newSplit call will also return surface:new — ok for test)
const child = await engine.spawnAgent({
repo: "voicelayer",
model: "haiku",
model: "sonnet",
cli: "claude",
prompt: "Sub task",
parent_agent_id: root.agent_id,
Expand Down
3 changes: 1 addition & 2 deletions tests/audit-fixes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ describe("spawn_agent MCP schema includes parent_agent_id and max_cost_per_agent
const childResult = await spawn.handler(
{
repo: "test",
model: "haiku",
model: "sonnet",
cli: "claude",
workspace: "workspace:1",
parent_agent_id: parentId,
Expand All @@ -372,7 +372,6 @@ describe("spawn_agent MCP schema includes parent_agent_id and max_cost_per_agent
const result = await spawn.handler(
{
repo: "test",
model: "opus",
cli: "claude",
workspace: "workspace:1",
max_cost_per_agent: 5.0,
Expand Down
Loading
Loading