mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
fix(cli): let agent_spawn take an exact model id (#3215)
agent_spawn's input schema limited `model` to five aliases, so a client that validates against the schema could not pass an exact model id such as claude-opus-5-5 or openrouter/anthropic/claude-sonnet-5.5, although the handler already passes non-alias strings through as modelId (#2962). The enum is now a bounded string (1-256 chars) with an anchored pattern: letters, digits and . _ : / @ + -, starting with a letter or digit. The handler applies the same check to `model` and to `config.model` (the `agent spawn -m` path, which the schema never sees), so whitespace and shell metacharacters are refused before the agent is stored. Aliases route as before; exact ids are reported back as modelId. Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
1 parent
29be054e85
commit
1b2deae0ee
2 files changed
+220
-5
No files matched your search
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Regression guard for ruvnet/ruflo#3215 — agent_spawn's input schema limited
|
||||
* `model` to an enum of five aliases, so an MCP client that validates against
|
||||
* the schema could not pass an exact model id (`claude-opus-5-5`,
|
||||
* `openrouter/anthropic/claude-sonnet-5.5`) even though the handler already
|
||||
* routed non-alias strings through as `modelId` (#2962). The enum is now a
|
||||
* bounded string with a safe-character pattern, and the handler applies the
|
||||
* same check, including to `config.model` (the `agent spawn -m` path).
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Ajv from 'ajv';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { validateSchema } from '@claude-flow/mcp/schema-validator';
|
||||
import { agentTools } from '../src/mcp-tools/agent-tools.js';
|
||||
|
||||
const tool = agentTools.find(t => t.name === 'agent_spawn')!;
|
||||
const spawn = (input: Record<string, unknown>) =>
|
||||
tool.handler(input) as Promise<Record<string, any>>;
|
||||
|
||||
const ALIASES = ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'];
|
||||
const EXACT_IDS = [
|
||||
'claude-opus-5-5',
|
||||
'gpt-6-astra',
|
||||
'openrouter/anthropic/claude-sonnet-5.5',
|
||||
'openrouter/x/y',
|
||||
'qwen3.6:27b',
|
||||
'anthropic/claude-opus-4@20260101',
|
||||
'model+variant',
|
||||
];
|
||||
const BAD_IDS: Array<[string, string]> = [
|
||||
['empty', ''],
|
||||
['over 256 chars', 'a'.repeat(257)],
|
||||
['inner space', 'claude opus'],
|
||||
['leading space', ' claude-opus-5-5'],
|
||||
['trailing newline', 'claude-opus-5-5\n'],
|
||||
['tab', 'claude\topus'],
|
||||
['command substitution', '$(id)'],
|
||||
['backticks', '`id`'],
|
||||
['semicolon', 'a;rm -rf x'],
|
||||
['pipe', 'a|b'],
|
||||
['ampersand', 'a&&b'],
|
||||
['redirect', 'a>b'],
|
||||
['quote', "a'b"],
|
||||
['leading dash (flag-like)', '-leading'],
|
||||
['leading slash', '/etc/passwd'],
|
||||
['leading dot', '../x'],
|
||||
];
|
||||
|
||||
function storedAgent(dir: string, id: string): Record<string, unknown> {
|
||||
return JSON.parse(readFileSync(join(dir, '.claude-flow', 'agents', 'store.json'), 'utf8')).agents[id];
|
||||
}
|
||||
|
||||
describe('#3215 — agent_spawn model schema', () => {
|
||||
const ajvValidate = new Ajv().compile(tool.inputSchema);
|
||||
const ok = (model: unknown) => ajvValidate({ agentType: 'coder', model });
|
||||
const mcpOk = (model: unknown) =>
|
||||
validateSchema({ agentType: 'coder', model }, tool.inputSchema as any).valid;
|
||||
|
||||
it('is a bounded string, not an enum', () => {
|
||||
const model = (tool.inputSchema.properties as Record<string, any>).model;
|
||||
expect(model.type).toBe('string');
|
||||
expect(model.enum).toBeUndefined();
|
||||
expect(model.minLength).toBe(1);
|
||||
expect(model.maxLength).toBe(256);
|
||||
expect(typeof model.pattern).toBe('string');
|
||||
});
|
||||
|
||||
it('documents the aliases and the exact-id pass-through', () => {
|
||||
const d: string = (tool.inputSchema.properties as Record<string, any>).model.description;
|
||||
for (const a of ALIASES) expect(d).toContain(a);
|
||||
expect(d).toMatch(/exact model id/i);
|
||||
});
|
||||
|
||||
it.each(ALIASES)('ajv accepts alias %s', a => expect(ok(a)).toBe(true));
|
||||
it.each(EXACT_IDS)('ajv accepts exact id %s', id => expect(ok(id)).toBe(true));
|
||||
it('ajv accepts exactly 256 chars', () => expect(ok('a'.repeat(256))).toBe(true));
|
||||
it.each(BAD_IDS)('ajv rejects %s', (_label, id) => expect(ok(id)).toBe(false));
|
||||
it('ajv rejects a non-string model', () => expect(ok(42)).toBe(false));
|
||||
|
||||
// The @claude-flow/mcp HTTP/stdio server validates with its own validator,
|
||||
// which compiles `pattern` with `new RegExp(pattern)` (no `u` flag).
|
||||
it.each([...ALIASES, ...EXACT_IDS])('mcp validator accepts %s', id => expect(mcpOk(id)).toBe(true));
|
||||
it.each(BAD_IDS)('mcp validator rejects %s', (_label, id) => expect(mcpOk(id)).toBe(false));
|
||||
});
|
||||
|
||||
describe('#3215 — agent_spawn model handler', () => {
|
||||
let dir: string;
|
||||
let prevCwd: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'ruflo-3215-'));
|
||||
prevCwd = process.env.CLAUDE_FLOW_CWD;
|
||||
process.env.CLAUDE_FLOW_CWD = dir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;
|
||||
else process.env.CLAUDE_FLOW_CWD = prevCwd;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each(ALIASES)('alias %s routes as a tier with no modelId', async alias => {
|
||||
const r = await spawn({ agentType: 'coder', model: alias });
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.model).toBe(alias);
|
||||
expect(r.modelRoutedBy).toBe('explicit');
|
||||
expect(r).not.toHaveProperty('modelId');
|
||||
expect(storedAgent(dir, r.agentId)).not.toHaveProperty('modelId');
|
||||
});
|
||||
|
||||
it.each(['claude-opus-5-5', 'openrouter/x/y', 'openrouter/anthropic/claude-sonnet-5.5'])(
|
||||
'exact id %s round-trips as modelId',
|
||||
async id => {
|
||||
const r = await spawn({ agentType: 'coder', model: id });
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.modelId).toBe(id);
|
||||
expect(r.modelRoutedBy).toBe('explicit');
|
||||
const stored = storedAgent(dir, r.agentId);
|
||||
expect(stored.modelId).toBe(id);
|
||||
expect((stored.config as Record<string, unknown>).model).toBe(id);
|
||||
},
|
||||
);
|
||||
|
||||
it('exact id sent in config.model (agent spawn -m) round-trips as modelId', async () => {
|
||||
const r = await spawn({ agentType: 'coder', config: { provider: 'anthropic', model: 'gpt-6-astra' } });
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.modelId).toBe('gpt-6-astra');
|
||||
});
|
||||
|
||||
it.each(BAD_IDS)('rejects top-level model: %s', async (_label, id) => {
|
||||
const r = await spawn({ agentType: 'coder', model: id });
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error).toMatch(/Input validation failed: model/);
|
||||
});
|
||||
|
||||
it.each(BAD_IDS.filter(([, id]) => id !== ''))('rejects config.model: %s', async (_label, id) => {
|
||||
const r = await spawn({ agentType: 'coder', config: { model: id } });
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error).toMatch(/Input validation failed: config\.model/);
|
||||
});
|
||||
|
||||
it('rejects a non-string model', async () => {
|
||||
const r = await spawn({ agentType: 'coder', config: { model: { evil: true } } });
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error).toMatch(/config\.model must be a non-empty string/);
|
||||
});
|
||||
|
||||
it('an empty or absent config.model still means no explicit model', async () => {
|
||||
const a = await spawn({ agentType: 'coder', config: { model: '' } });
|
||||
expect(a.success).toBe(true);
|
||||
expect(a.modelRoutedBy).not.toBe('explicit');
|
||||
const b = await spawn({ agentType: 'coder', config: { model: undefined } });
|
||||
expect(b.success).toBe(true);
|
||||
expect(b.modelRoutedBy).not.toBe('explicit');
|
||||
});
|
||||
|
||||
it('a null top-level model is treated as absent', async () => {
|
||||
const r = await spawn({ agentType: 'coder', model: null });
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.modelRoutedBy).not.toBe('explicit');
|
||||
});
|
||||
|
||||
it('a rejected model does not register an agent', async () => {
|
||||
const r = await spawn({ agentType: 'coder', agentId: 'bad-model-1', model: '$(id)' });
|
||||
expect(r.success).toBe(false);
|
||||
let stored: unknown;
|
||||
try { stored = storedAgent(dir, 'bad-model-1'); } catch { stored = undefined; }
|
||||
expect(stored).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,37 @@ const HIVE_AGENT_FILE = 'agents.json';
|
||||
// Model types matching Claude Agent SDK
|
||||
type ClaudeModel = 'haiku' | 'sonnet' | 'opus' | 'opus-4.7' | 'inherit';
|
||||
|
||||
/** Model aliases that resolve to a tier label rather than an exact model id. */
|
||||
const MODEL_ALIASES: readonly ClaudeModel[] = ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'];
|
||||
|
||||
/**
|
||||
* #3215 — agent_spawn's `model` accepts an alias or an exact provider model id
|
||||
* (`claude-opus-5-5`, `gpt-6-astra`, `openrouter/anthropic/claude-sonnet-5.5`,
|
||||
* `qwen3.6:27b`). One pattern is shared by the input schema and the handler so
|
||||
* the two cannot drift. It is anchored, starts with an alphanumeric (so a value
|
||||
* cannot read as a CLI flag), and allows only `._:/@+-` besides alphanumerics:
|
||||
* no whitespace and no shell metacharacters. The character class has no
|
||||
* escapes, so it compiles the same under ajv's `u` flag and under the plain
|
||||
* `new RegExp(pattern)` that @claude-flow/mcp's schema validator uses.
|
||||
*/
|
||||
export const MODEL_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$';
|
||||
export const MODEL_ID_MAX_LENGTH = 256;
|
||||
const MODEL_ID_RE = new RegExp(MODEL_ID_PATTERN);
|
||||
|
||||
/** Returns an error message for an invalid model value, or null when it is valid. */
|
||||
export function modelIdError(value: unknown, label = 'model'): string | null {
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
return `${label} must be a non-empty string`;
|
||||
}
|
||||
if (value.length > MODEL_ID_MAX_LENGTH) {
|
||||
return `${label} exceeds ${MODEL_ID_MAX_LENGTH} characters`;
|
||||
}
|
||||
if (!MODEL_ID_RE.test(value)) {
|
||||
return `${label} contains invalid characters (must start with a letter or digit; allowed: letters, digits, . _ : / @ + -)`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface AgentRecord {
|
||||
agentId: string;
|
||||
agentType: string;
|
||||
@@ -229,7 +260,7 @@ async function determineAgentModel(
|
||||
// 1. Explicit model in config
|
||||
if (config.model) {
|
||||
const explicitModel = config.model as string;
|
||||
if (['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'].includes(explicitModel)) {
|
||||
if ((MODEL_ALIASES as readonly string[]).includes(explicitModel)) {
|
||||
return { model: explicitModel as ClaudeModel, routedBy: 'explicit' };
|
||||
}
|
||||
// #2962 — a non-alias model string (e.g. an Ollama tag like
|
||||
@@ -340,8 +371,10 @@ export const agentTools: MCPTool[] = [
|
||||
domain: { type: 'string', description: 'Agent domain' },
|
||||
model: {
|
||||
type: 'string',
|
||||
enum: ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'],
|
||||
description: 'Claude model alias (haiku=fast/cheap, sonnet=balanced, opus=current Opus 4.8, opus-4.7=prior Opus pin)'
|
||||
minLength: 1,
|
||||
maxLength: MODEL_ID_MAX_LENGTH,
|
||||
pattern: MODEL_ID_PATTERN,
|
||||
description: 'Model alias or exact model id. Aliases: haiku=fast/cheap, sonnet=balanced, opus=current Opus 4.8, opus-4.7=prior Opus pin, inherit=the default model. Any other value is passed through unchanged as an exact model id (e.g. claude-opus-5-5, gpt-6-astra, openrouter/anthropic/claude-sonnet-5.5) and reported back as modelId. Letters, digits and . _ : / @ + - only, starting with a letter or digit.'
|
||||
},
|
||||
task: { type: 'string', description: 'Task description for intelligent model routing' },
|
||||
memoryBase: { type: 'string', description: 'Opt-in: base .rvf memory file to fork a per-agent Copy-On-Write branch from (agenticow). When set, the agent gets an isolated ~162-byte COW branch instead of a full copy — promote on success, discard on terminate. Requires the optional `agenticow` dep; degrades to a no-op when absent or when CLAUDE_FLOW_NO_COW_MEMORY=1.' },
|
||||
@@ -384,9 +417,19 @@ export const agentTools: MCPTool[] = [
|
||||
}
|
||||
const config = (input.config as Record<string, unknown>) || {};
|
||||
|
||||
// Add explicit model to config if provided
|
||||
if (input.model) {
|
||||
// #3215 — validate an explicit model before it is stored or routed. The
|
||||
// top-level field is checked even when empty (the schema rejects ''; null
|
||||
// is treated as absent), and config.model is checked too: `agent spawn -m`
|
||||
// sends the model there, where the input schema never sees it. A falsy
|
||||
// config.model keeps its old meaning (no explicit model), matching
|
||||
// determineAgentModel's check.
|
||||
if (input.model !== undefined && input.model !== null) {
|
||||
const err = modelIdError(input.model);
|
||||
if (err) return { success: false, error: `Input validation failed: ${err}` };
|
||||
config.model = input.model;
|
||||
} else if (config.model) {
|
||||
const err = modelIdError(config.model, 'config.model');
|
||||
if (err) return { success: false, error: `Input validation failed: ${err}` };
|
||||
}
|
||||
|
||||
// Get task from either top-level or config (CLI passes it in config.task)
|
||||
|
||||
Reference in new issue
Block a user