Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(ops): op-fix builders for filled, surface-correct op error fixes (agent contract B2/B6/B8)
garrytan1419a438b0cb
diff --git a/src/core/ops/op-fix.ts b/src/core/ops/op-fix.tsnew file mode 100644index 0000000000..e55b3ae6e5--- /dev/null+++ b/src/core/ops/op-fix.ts@@ -0,0 +1,120 @@+/**+ * Agent contract v1 (Lane B): small builders op handlers use to attach a+ * filled, surface-correct next step to an `OperationError`.+ *+ * Type-only import of agent-output: ops sit in the PGLite snapshot-schema+ * import closure, so this module builds plain `Action` objects and never pulls+ * the renderer's runtime graph in. `command`/`next` are computed at render+ * time (agent-output.ts), never here.+ */+import type { Action, Effect, McpCall, Transport } from '../agent-output.ts';+import type { RegistryCode } from '../error-registry.ts';+import { opError, type OperationContext, type OperationError, type ParamDef } from './contract.ts';++type TransportCtx = Pick<OperationContext, 'remote' | 'transport'>;++/** The caller's surface: the trusted local CLI, or an MCP transport. */+export function opTransport(ctx: TransportCtx): Transport {+ if (ctx.remote === false) return 'cli';+ return ctx.transport === 'http' ? 'http' : 'stdio';+}++/**+ * How the caller passes one parameter on its own surface: `--no-pull` /+ * `--limit 20` on the CLI, `no_pull: true` / `limit: 20` over MCP.+ */+export function paramUse(ctx: TransportCtx, param: string, value: unknown = true): string {+ if (opTransport(ctx) === 'cli') {+ const flag = `--${param.replace(/_/g, '-')}`;+ return value === true ? flag : `${flag} ${typeof value === 'string' ? value : JSON.stringify(value)}`;+ }+ return `${param}: ${JSON.stringify(value)}`;+}++/** A read-only diagnostic step the agent can run itself (`mcp` is dropped at render unless callable). */+export function readFix(why: string, step: { argv?: string[]; mcp?: McpCall }): Action {+ return {+ ...(step.argv ? { argv: step.argv } : {}),+ ...(step.mcp ? { mcp: step.mcp } : {}),+ consent: [], actor: 'agent', why, requires_exclusive: false,+ };+}++/**+ * B6: a step only the trusted CLI on the brain host can run. Over MCP the+ * agent cannot run it: the user (stdio: same machine) or the host admin+ * (http) does, and `user_message` is the relay text.+ */+export function hostFix(+ ctx: TransportCtx,+ argv: string[],+ why: string,+ opts: { consent?: Effect[]; requires_exclusive?: boolean; user_message?: string } = {},+): Action {+ const transport = opTransport(ctx);+ const actor = transport === 'cli' ? 'agent' : transport === 'http' ? 'host_admin' : 'user';+ const relay = transport === 'http'+ ? 'This needs the gbrain CLI on the machine that hosts this brain. Please ask whoever runs that server to run the command shown.'+ : 'This needs the gbrain CLI in a terminal on this machine. Please run the command shown.';+ return {+ argv, consent: opts.consent ?? [], actor, why,+ ...(transport === 'cli' && opts.user_message === undefined ? {} : { user_message: opts.user_message ?? relay }),+ requires_exclusive: opts.requires_exclusive ?? false,+ };+}++/** A refusal whose next step is a host-only command (B6): suggestion + filled fix in one call. */+export function hostOnlyError(+ ctx: TransportCtx,+ code: RegistryCode,+ message: string,+ argv: string[],+ why: string,+ opts: { consent?: Effect[]; requires_exclusive?: boolean; suggestion?: string; legacy_error?: string; reason?: string } = {},+): OperationError {+ const who = opTransport(ctx) === 'http' ? 'the brain host operator' : 'the user, in a terminal on the brain host';+ const suggestion = opts.suggestion ?? (opTransport(ctx) === 'cli'+ ? 'Run the command in fix.'+ : `Only the trusted local CLI can do this; ${who} runs the command in fix.`);+ return opError(code, message, suggestion, {+ fix: hostFix(ctx, argv, why, opts),+ ...(opts.legacy_error ? { legacy_error: opts.legacy_error } : {}),+ ...(opts.reason ? { reason: opts.reason } : {}),+ });+}++function exampleValue(def: ParamDef | undefined, choices: readonly string[] | undefined): unknown {+ if (choices?.length) return choices[0];+ if (def?.default !== undefined) return def.default;+ switch (def?.type) {+ case 'number': return 10;+ case 'boolean': return true;+ case 'array': return [];+ case 'object': return {};+ default: return 'value';+ }+}++/**+ * B2/B3: `invalid_params` naming the parameter on the caller's surface, its+ * valid choices (or type and description) and one example call. The caller's+ * raw value is never echoed (messages can be persisted to request logs).+ */+export function invalidParam(+ ctx: TransportCtx,+ tool: string,+ param: string,+ message: string,+ opts: { choices?: readonly string[]; example?: unknown; def?: ParamDef; legacy_error?: string } = {},+): OperationError {+ const example = opts.example ?? exampleValue(opts.def, opts.choices ?? opts.def?.enum);+ const choices = opts.choices ?? opts.def?.enum;+ const cli = opTransport(ctx) === 'cli';+ const name = cli ? `--${param.replace(/_/g, '-')}` : `\`${param}\``;+ const what = choices?.length+ ? `one of: ${choices.join(', ')}`+ : `a ${opts.def?.type ?? 'value'}${opts.def?.description ? ` (${opts.def.description.replace(/\.$/, '')})` : ''}`;+ const call = cli ? paramUse(ctx, param, example) : `${tool} {"${param}": ${JSON.stringify(example)}}`;+ return opError('invalid_params', message, `Pass ${name} as ${what}. Example: ${call}.`,+ opts.legacy_error ? { legacy_error: opts.legacy_error } : {});+}diff --git a/test/op-fix.test.ts b/test/op-fix.test.tsnew file mode 100644index 0000000000..cb78821ea5--- /dev/null+++ b/test/op-fix.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from 'bun:test';+import { hostFix, hostOnlyError, invalidParam, opTransport, paramUse, readFix } from '../src/core/ops/op-fix.ts';+import { renderAction, cliRenderContext, toAgentError } from '../src/core/agent-output.ts';++const cli = { remote: false } as const;+const stdio = { remote: true, transport: 'stdio' } as const;+const http = { remote: true, transport: 'http' } as const;+const mcpRender = (transport: 'stdio' | 'http', callable: string[] = []) => ({+ transport, isCallable: (t: string) => callable.includes(t), preapproved: () => false,+});++describe('op-fix builders', () => {+ test('opTransport maps the trust flag and transport', () => {+ expect(opTransport(cli)).toBe('cli');+ expect(opTransport(stdio)).toBe('stdio');+ expect(opTransport(http)).toBe('http');+ expect(opTransport({ remote: true })).toBe('stdio');+ });++ test('paramUse renders the caller surface (B8)', () => {+ expect(paramUse(cli, 'no_pull')).toBe('--no-pull');+ expect(paramUse(stdio, 'no_pull')).toBe('no_pull: true');+ expect(paramUse(cli, 'limit', 20)).toBe('--limit 20');+ expect(paramUse(http, 'source_id', 'docs')).toBe('source_id: "docs"');+ });++ test('hostFix: agent on the CLI, user on stdio, host_admin on http; relay text over MCP', () => {+ const argv = ['gbrain', 'migrate', 'embeddings', '--source', 'docs'];+ expect(hostFix(cli, argv, 'why')).toEqual({ argv, consent: [], actor: 'agent', why: 'why', requires_exclusive: false });+ expect(hostFix(stdio, argv, 'why').actor).toBe('user');+ expect(hostFix(http, argv, 'why')).toMatchObject({ actor: 'host_admin', user_message: expect.stringContaining('server') });+ const rendered = renderAction(hostFix(http, argv, 'why'), mcpRender('http'));+ expect(rendered).toMatchObject({ next: 'tell_user_to_run', command: 'gbrain migrate embeddings --source docs' });+ });++ test('hostOnlyError carries code, suggestion and a rendered fix', () => {+ const e = hostOnlyError(stdio, 'permission_denied', 'local-only', ['gbrain', 'doctor', '--json'], 'Doctor runs on the host.');+ expect(e.code).toBe('permission_denied');+ expect(e.suggestion).toContain('trusted local CLI');+ const env = toAgentError(e, { transport: 'stdio', op: 'x', render: mcpRender('stdio') });+ expect(env.fix).toMatchObject({ actor: 'user', next: 'tell_user_to_run', command: 'gbrain doctor --json' });+ });++ test('invalidParam lists choices and an example on each surface', () => {+ const mcp = invalidParam(stdio, 'find_orphans', 'mode', 'Invalid mode.', { choices: ['inbound', 'islanded'] });+ expect(mcp.code).toBe('invalid_params');+ expect(mcp.suggestion).toBe('Pass `mode` as one of: inbound, islanded. Example: find_orphans {"mode": "inbound"}.');+ const local = invalidParam(cli, 'find_orphans', 'mode', 'Invalid mode.', { choices: ['inbound', 'islanded'] });+ expect(local.suggestion).toBe('Pass --mode as one of: inbound, islanded. Example: --mode inbound.');+ const typed = invalidParam(stdio, 'list_pages', 'limit', 'bad', { def: { type: 'number', description: 'Max rows.' } });+ expect(typed.suggestion).toBe('Pass `limit` as a number (Max rows). Example: list_pages {"limit": 10}.');+ });++ test('invalidParam keeps a frozen legacy error value', () => {+ const e = invalidParam(stdio, 'get_job', 'id', 'bad', { legacy_error: 'invalid_params', def: { type: 'number' } });+ expect(e.code).toBe('invalid_params');+ });++ test('readFix is a no-consent agent step', () => {+ const f = readFix('Lists jobs.', { argv: ['gbrain', 'jobs', 'list'], mcp: { tool: 'list_jobs', arguments: {} } });+ expect(renderAction(f, cliRenderContext())).toMatchObject({ next: 'run', command: 'gbrain jobs list' });+ expect(renderAction(f, mcpRender('stdio', ['list_jobs']))).toMatchObject({ next: 'run', mcp: { tool: 'list_jobs' } });+ });+});