Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* CLI→MCP gap-closure wave [OV6] — per-subcommand thin-client routing for the
* commands whose reads/writes gained MCP ops: takes (list/search/scorecard/
* calibration + the write verbs), search (modes/stats/tune, read-only forms),
* jobs stats, cache stats, quarantine list, wakeshift watch (watch_job /
* watch_write_request / watch_cron) and wakeshift accept-terms
* (accept_wakeshift_terms). The salience/anomalies/
* graph-query precedent, engine-free: each routable subcommand maps onto its
* op over callRemoteTool; everything else returns false so the caller falls
* through to refuseThinClient's pinpoint hint.
*
* Config-MUTATING forms stay host-side by design: `search modes --reset` and
* `search tune --apply` (CDX-21), plus `search modes --source <mode>` (the
* reset dry-run — previews what a reset would change on the host), `cache
* clear|prune`, `quarantine scan|clear`, `takes extract|revisit`.
*/
import type { GBrainConfig } from '../core/config.ts';
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
function flagValue(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
return i === -1 ? undefined : args[i + 1];
}
function num(v: string | undefined): number | undefined {
if (v === undefined) return undefined;
const n = parseFloat(v);
return Number.isFinite(n) ? n : undefined;
}
async function call(cfg: GBrainConfig, tool: string, args: Record<string, unknown>): Promise<unknown> {
return unpackToolResult(await callRemoteTool(cfg, tool, args));
}
function printJson(result: unknown): void {
console.log(JSON.stringify(result, null, 2));
}
/**
* Recognized-but-malformed routable subcommand: print the SAME usage string
* the host CLI prints (copied verbatim from src/commands/takes.ts) and exit 1.
* Returning false here instead would fall through to the host-bound refusal
* hint, which misleads (the subcommand IS routable — the args are just wrong).
*/
function usageExit(...lines: string[]): never {
for (const line of lines) console.error(line);
process.exit(1);
}
/**
* Route a thin-client invocation to its MCP op. Returns true when handled
* (output printed); false ONLY when the subcommand is genuinely host-bound
* and the caller should refuse with the hint. Routable subcommands with
* invalid required args report a nonzero CLI verdict instead of returning
* false. Take writes share the durable mutation parser, timeout and typed
* receipt renderer; other remote op errors propagate to the dispatcher.
*/
export async function routeThinClientCommand(
cfg: GBrainConfig,
command: string,
args: string[],
): Promise<boolean> {
const sub = args[0];
const rest = args.slice(1);
// #8543: bare `serve` (or gbrain's own registration flags) is the stdio bridge to the remote brain; every other serve
// form refuses here with a fix that keeps its flags, so the caller's generic refusal never renders `Fix: gbrain serve`.
if (command === 'serve' && !args.includes('--help') && !args.includes('-h')) {
const { parseBridgeServeArgs, serveThinClientRefusal } = await import('../mcp/remote-bridge-args.ts');
const { exitCliError, usageError } = await import('../cli/cli-error.ts');
const { getCliOptions } = await import('../core/cli-options.ts');
if (getCliOptions().brain) exitCliError(usageError('--brain is not supported on a thin-client install: the remote server is a single brain.', 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), 'serve');
const parsed = (() => { try { return parseBridgeServeArgs(args); } catch (error) { return exitCliError(error, 'serve'); } })();
if (!parsed.bridge) return exitCliError(serveThinClientRefusal(parsed.refused, cfg.remote_mcp?.mcp_url ?? ''), 'serve');
const { startRemoteStdioBridge } = await import('../mcp/remote-bridge.ts');
const timeoutMs = getCliOptions().timeoutMs;
await startRemoteStdioBridge(cfg, { surface: parsed.surface, advertise: parsed.advertise, sourceGuard: parsed.sourceGuard, ...(timeoutMs ? { timeoutMs } : {}) });
return true;
}
if (command === 'sources' && sub === 'shared-skills') {
if (rest.includes('--help') || rest.includes('-h')) {
console.log((await import('./sources-shared-skills.ts')).SOURCES_SHARED_SKILLS_HELP);
return true;
}
const [id, action] = rest.filter(arg => !arg.startsWith('-'));
if (!id || !/^[a-z0-9-]{1,32}$/.test(id)) return false;
const { sharedSkillsRemoteRefusal } = await import('../core/shared-skills/source-opt-out.ts');
const { exitCliError } = await import('../cli/cli-error.ts');
exitCliError(sharedSkillsRemoteRefusal(id, action === 'on' || action === 'off' ? action : 'status'), 'sources');
}
if (command === 'beliefs' && sub === 'changes' && !rest.includes('--help') && !rest.includes('-h')) {
if (rest.includes('--source') || rest.some(a => a.startsWith('--source='))) return false; // the remote token names the source
const { beliefsChangesArgs } = await import('./beliefs.ts');
const { renderBeliefChanges } = await import('../core/belief/changes.ts');
const { opError, OperationError } = await import('../core/ops/contract.ts');
const { writeCliError } = await import('../cli/cli-error.ts');
const { jsonRequested, setCliExitVerdict } = await import('../core/cli-force-exit.ts');
try {
const { entities, since } = beliefsChangesArgs(args);
const result = await call(cfg, 'delta', { since, beliefs: true, ...(entities.length ? { entities: entities.join(',') } : {}) }) as { beliefs?: import('../core/belief/changes.ts').BeliefChanges };
if (!result?.beliefs) throw opError('unavailable', 'The remote brain\'s delta does not return belief changes: the brain host runs a gbrain older than the belief ledger weekly diff.', 'Upgrade gbrain on the brain host (gbrain upgrade there).');
if (jsonRequested(args)) printJson(result.beliefs);
else console.log(renderBeliefChanges(result.beliefs));
} catch (error) {
if (!(error instanceof OperationError)) throw error;
setCliExitVerdict(writeCliError(error, 'beliefs', { json: jsonRequested(args) }));
}
return true;
}
if (command === 'config') {
const { tryRunConfigThinClient } = await import('./config.ts');
return tryRunConfigThinClient(args);
}
if (command === 'takes') {
switch (sub) {
case 'list': {
const slug = rest[0] && !rest[0].startsWith('-') ? rest[0] : undefined;
printJson(await call(cfg, 'takes_list', {
...(slug ? { page_slug: slug } : {}),
...(flagValue(rest, '--who') ? { holder: flagValue(rest, '--who') } : {}),
...(flagValue(rest, '--kind') ? { kind: flagValue(rest, '--kind') } : {}),
}));
return true;
}
case 'search': {
if (!rest[0]) {
usageExit('Usage: gbrain takes search "<query>" [--who h] [--json]');
}
printJson(await call(cfg, 'takes_search', { query: rest[0], ...(num(flagValue(rest, '--limit')) !== undefined ? { limit: num(flagValue(rest, '--limit')) } : {}) }));
return true;
}
case 'scorecard': {
if (rest.includes('--group-by') || rest.includes('--min-n')) return false; // W7: private journal groups, host-bound
const holder = rest[0] && !rest[0].startsWith('--') ? rest[0] : flagValue(rest, '--holder');
printJson(await call(cfg, 'takes_scorecard', { ...(holder ? { holder } : {}) }));
return true;
}
case 'calibration': {
printJson(await call(cfg, 'takes_calibration', { ...(flagValue(rest, '--holder') ? { holder: flagValue(rest, '--holder') } : {}) }));
return true;
}
case 'add':
case 'update':
case 'resolve':
case 'supersede': {
const { runTakesMutation } = await import('./takes-mutation.ts');
await runTakesMutation(async () => { throw new Error('Remote takes cannot open a local engine.'); }, args, cfg);
return true;
}
default:
return false; // extract / revisit / unknown — host-bound, refuse with hint
}
}
if (command === 'search') {
if (sub === 'modes' && !rest.includes('--reset') && !rest.includes('--source') && !rest.includes('--mode')) {
printJson(await call(cfg, 'search_modes', {}));
return true;
}
if (sub === 'stats') {
printJson(await call(cfg, 'search_stats', { ...(num(flagValue(rest, '--days')) !== undefined ? { days: num(flagValue(rest, '--days')) } : {}) }));
return true;
}
if (sub === 'tune' && !rest.includes('--apply')) {
printJson(await call(cfg, 'search_tune', {}));
return true;
}
return false; // modes --reset / modes --mode|--source (the reset dry-run) / tune --apply / diagnose — host-side config or live probe
}
if (command === 'wakeshift' && (sub === 'watch' || sub === 'accept-terms')) {
const { runWakeshiftWatchRemote } = await import('./wakeshift-watch.ts');
await runWakeshiftWatchRemote(cfg, sub === 'watch' ? rest : ['accept-terms', ...rest]);
return true;
}
if (command === 'jobs' && sub === 'stats') {
printJson(await call(cfg, 'get_job_stats', { ...(flagValue(rest, '--queue') ? { queue: flagValue(rest, '--queue') } : {}) }));
return true;
}
if (command === 'cache' && sub === 'stats') {
printJson(await call(cfg, 'cache_stats', {}));
return true;
}
if (command === 'quarantine' && sub === 'list') {
printJson(await call(cfg, 'quarantine_list', { ...(rest.includes('--include-flagged') ? { include_flagged: true } : {}) }));
return true;
}
return false;
}