Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(cli): D6 parseOpArgs honours a bare -- ; D4 typed op flag values from ParamDef

garrytan844d87d89aef
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 5e90315e82..61b6e5e6ea 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -285,6 +285,7 @@
"test/cli-input-plumbing-2822.test.ts": 1178,
"test/cli-multimodal-integration.test.ts": 291,
"test/cli-op-error-status-exit.test.ts": 6871,
+ "test/cli-op-typed-args.test.ts": 2000,
"test/cli-options.test.ts": 4937,
"test/cli-pipe-truncation.test.ts": 1339,
"test/cli-query-image.test.ts": 18,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index b90ed52af3..de0000914d 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -902,6 +902,7 @@
"unit:test/cli-input-plumbing-2822.test.ts": 3233,
"unit:test/cli-multimodal-integration.test.ts": 1203,
"unit:test/cli-op-error-status-exit.test.ts": 14252,
+ "unit:test/cli-op-typed-args.test.ts": 2000,
"unit:test/cli-options.test.ts": 4800,
"unit:test/cli-pipe-truncation.test.ts": 1602,
"unit:test/cli-query-image.test.ts": 496,
diff --git a/src/cli.ts b/src/cli.ts
index dfba8a3f6d..a985173640 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -39,6 +39,7 @@ import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExit
import { agentJsonGuardMode } from './cli/json-guard.ts';
import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeFatalCliError } from './cli/cli-error.ts';
import { opError } from './core/ops/contract.ts';
+import { opParamValue } from './cli/op-param-values.ts';
import { serializeMarkdown } from './core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
import { runCliPreflight } from './core/cli-preflight.ts';
@@ -993,9 +994,11 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
const positional = op.cliHints?.positional || [];
let posIdx = 0;
+ let endOfOptions = false; // D6: a bare `--` ends options (as in findUnknownOpFlag); later tokens are positionals
for (let i = 0; i < args.length; i++) {
const arg = args[i];
- if (arg.startsWith('--')) {
+ if (arg === '--' && !endOfOptions) { endOfOptions = true; continue; }
+ if (arg.startsWith('--') && !endOfOptions) {
// #2185: `--key=value` inline form. Pre-fix this parsed as junk key
// 'key=value' and consumed the NEXT token as its value, corrupting
// positional parsing. Recognized here so the strict-flag validator and
@@ -1013,9 +1016,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
const def = op.params[key];
if (def) {
const raw = arg.slice(eq + 1);
- params[key] = def.type === 'boolean' ? raw !== 'false'
- : def.type === 'number' ? Number(raw)
- : raw;
+ params[key] = def.type === 'boolean' ? raw !== 'false' : opParamValue(op, key, def, raw);
continue;
}
}
@@ -1062,8 +1063,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
// positionally, then --content clobbered it). Warn to stderr; when
// the discarded value names an existing file, point at capture --file.
const prevValue = params[key];
- params[key] = args[++i];
- if (paramDef?.type === 'number') params[key] = Number(params[key]);
+ params[key] = opParamValue(op, key, paramDef, args[++i]);
if (prevValue !== undefined && prevValue !== params[key]) {
let fileHint = '';
try {
@@ -1079,7 +1079,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
} else if (posIdx < positional.length) {
const key = positional[posIdx++];
const paramDef = op.params[key];
- params[key] = paramDef?.type === 'number' ? Number(arg) : arg;
+ params[key] = opParamValue(op, key, paramDef, arg, true);
}
}
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index e601b9de12..111bf8b309 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -272,7 +272,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// answered before any engine or queue is touched. Paired with the SELF_HELP_WITHOUT_ENGINE entry
// below so a brainless machine gets real help, and with the `--`-aware help scan in main() so
// `agent run -- --help` submits the literal prompt instead.
- { name: 'agent', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/agent.ts') },
+ { name: 'agent', phase: 'post-connect', thinClient: 'none', selfHelp: true, end_of_options: true, load: () => import('./commands/agent.ts') },
{ name: 'book-mirror', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/book-mirror.ts') },
// selfHelp: v0.37 fix wave (Lane D.4 + CDX2-12): sync's --no-embed flag was unreachable via help
// because the dispatcher's generic CLI-only short-circuit fired before runSync could print its own
diff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.ts
new file mode 100644
index 0000000000..2fd652bbb0
--- /dev/null
+++ b/src/cli/op-param-values.ts
@@ -0,0 +1,30 @@
+/**
+ * Agent contract v1 (D4): typed CLI values for shared operations, from the
+ * op's `ParamDef`. A number flag that is not a finite number, or a string
+ * flag outside its declared `enum`, is a usage error (`invalid_params`,
+ * exit 2) naming the flag and a valid example, instead of reaching the
+ * handler as NaN or an unknown choice. Mirrors the MCP side's
+ * `validateParams` (types + enums) for the CLI parser.
+ */
+import { inertText } from '../core/agent-output.ts';
+import type { Operation, ParamDef } from '../core/ops/contract.ts';
+import { usageError } from './cli-error.ts';
+
+/** Coerce one raw CLI token for `op.params[key]`; `positional` labels a positional slot instead of a flag. */
+export function opParamValue(op: Operation, key: string, def: ParamDef | undefined, raw: string, positional = false): unknown {
+ if (!def) return raw;
+ const name = positional ? `<${key}>` : `--${key.replace(/_/g, '-')}`;
+ const usage = `gbrain ${op.cliHints?.name ?? op.name}`;
+ if (def.type === 'number') {
+ const n = Number(raw);
+ if (raw.trim() !== '' && Number.isFinite(n)) return n;
+ const example = typeof def.default === 'number' ? def.default : 10;
+ throw usageError(`${name} must be a number; got '${inertText(raw, 40)}'.`,
+ `Pass a number, e.g. ${usage} ${positional ? example : `${name} ${example}`}.`);
+ }
+ if (def.type === 'string' && def.enum && !def.enum.includes(raw)) {
+ throw usageError(`${name} must be one of: ${def.enum.join(', ')}; got '${inertText(raw, 40)}'.`,
+ `Pass one of the declared values, e.g. ${usage} ${positional ? def.enum[0] : `${name} ${def.enum[0]}`}.`);
+ }
+ return raw;
+}
diff --git a/test/cli-op-typed-args.test.ts b/test/cli-op-typed-args.test.ts
new file mode 100644
index 0000000000..605c492ad0
--- /dev/null
+++ b/test/cli-op-typed-args.test.ts
@@ -0,0 +1,55 @@
+/**
+ * Agent contract v1 D4 (typed validation from ParamDef) and D6 (a bare `--`
+ * ends options in parseOpArgs, matching findUnknownOpFlag).
+ */
+import { describe, expect, test } from 'bun:test';
+import { parseOpArgs, findUnknownOpFlag } from '../src/cli.ts';
+import { operations, OperationError } from '../src/core/operations.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+function usageErrorOf(fn: () => unknown): OperationError {
+ try { fn(); } catch (e) { if (e instanceof OperationError) return e; throw e; }
+ throw new Error('expected a usage error');
+}
+
+describe('D6: bare -- ends options', () => {
+ test('a positional after -- that looks like a flag binds to the positional slot', () => {
+ expect(parseOpArgs(op('get_page'), ['--', '--yes'])).toEqual({ slug: '--yes' });
+ });
+ test('flags before -- still parse; nothing after -- is read as a flag', () => {
+ const p = parseOpArgs(op('search'), ['--limit', '3', '--', '--limit']);
+ expect(p).toEqual({ limit: 3, query: '--limit' });
+ expect(findUnknownOpFlag(op('search'), ['--', '--not-a-flag'])).toBeNull();
+ });
+});
+
+describe('D4: typed op flag values', () => {
+ test('a non-numeric number flag is invalid_params naming the flag and an example', () => {
+ const e = usageErrorOf(() => parseOpArgs(op('search'), ['x', '--limit', 'abc']));
+ expect(e.code).toBe('invalid_params');
+ expect(e.message).toContain('--limit must be a number');
+ expect(e.suggestion).toContain('--limit');
+ });
+ test('the inline = form is validated the same way', () => {
+ expect(usageErrorOf(() => parseOpArgs(op('search'), ['x', '--limit=NaN'])).code).toBe('invalid_params');
+ });
+ test('an enum value outside the declared set lists the choices', () => {
+ const e = usageErrorOf(() => parseOpArgs(op('search'), ['x', '--salience', 'loud']));
+ expect(e.message).toContain('off, on, strong');
+ });
+ test('valid values still parse', () => {
+ expect(parseOpArgs(op('search'), ['x', '--limit', '5', '--salience', 'on'])).toEqual({ query: 'x', limit: 5, salience: 'on' });
+ });
+ test('end to end: exit 2 with an invalid_params envelope, before any brain is opened', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-typed-args-'));
+ const r = await runCli(['search', 'needle', '--limit', 'abc', '--json'], { home, cwd: home });
+ expect(r.exitCode).toBe(2);
+ expect(JSON.parse(r.stdout)).toMatchObject({ code: 'invalid_params', contract_version: 1 });
+ expect(r.stdout + r.stderr).not.toContain('No brain configured');
+ });
+});