Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
6.6 KB
Raw Blame
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { readCredentials, credentialReceipt, PlainBearerKeyFile, type HarnessCredentials } from '../core/harness/credentials.ts';
import { shellQuote } from '../core/mcp-registration.ts';
import { harnessAdapter } from '../core/harness/registry.ts';
import { installHarnessConnection, type inlineTokenReceipt } from '../core/harness/install.ts';
import { normalizeMcpUrl } from '../core/mcp-registration.ts';
import { validateHarnessArguments } from '../core/harness/arguments.ts';
import { readHarnessConnectionStatus } from '../core/harness/status.ts';
import { isSkillLoading, skillsOutcomeFailed, type SkillsBlockOutcome } from '../core/setup/skills-block.ts';
import { renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';

export async function runHarnessConnect(args: string[]): Promise<void> {
  if (args.includes('--help') || args.includes('-h')) {
    console.log('gbrain connect <endpoint> --harness <id> --credentials-file <private-file> [--install [--fresh-token] [--no-instructions] [--skill-loading off|spring [--gbrain-bin <path>]] | --remove] [--root <persistent-root>] [--name <name>] [--json]\ngbrain connect --harness <id> --status [--root <persistent-root>] [--name <name>] [--json]');
    return;
  }
  const value = (flag: string) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };
  // GBRA-585: a bearer key (setup's member-keys/<member>.key) installs through the --agent lane; name it instead of a parse error.
  const bearerForm = (key: string) => {
    const agent = value('--harness') ?? value('--agent') ?? 'claude-code';
    return `gbrain connect ${args[0] && !args[0].startsWith('--') ? args[0] : '<mcp-url>'} --agent ${['claude-code', 'codex', 'opencode', 'perplexity'].includes(agent) ? agent : 'generic'} ${key}--install`;
  };
  try {
    if (args.includes('--token')) {
      throw new Error(`--token is the bearer-token form; --harness takes a --credentials-file handoff from gbrain mcp grant. For a bearer key run: ${bearerForm('--token <key> ')} (or set GBRAIN_REMOTE_TOKEN instead of passing --token, which keeps the key out of shell history).`);
    }
    validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name', '--skill-loading', '--gbrain-bin'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token', '--no-instructions'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });
    if (args.includes('--status')) {
      const harness = value('--harness') ?? value('--agent');
      if (!harness) throw new Error('--harness is required for local status; no credentials or live connection are needed');
      console.log(JSON.stringify(readHarnessConnectionStatus({ harness, root: value('--root'), name: value('--name') }), null, args.includes('--json') ? undefined : 2));
      return;
    }
    const skillLoading = value('--skill-loading');
    if (skillLoading !== undefined && !isSkillLoading(skillLoading)) throw new Error(`Unknown --skill-loading '${skillLoading}'; pass off or spring`);
    const path = value('--credentials-file');
    if (!path) throw new Error('--credentials-file is required; create the private handoff with gbrain mcp grant on the brain host');
    let c: HarnessCredentials;
    try { c = readCredentials(path); } catch (error) {
      if (!(error instanceof PlainBearerKeyFile)) throw error;
      throw new Error(`${path} holds a plain bearer key (like the member keys gbrain setup writes under member-keys/ for a brain that serves several people), not a credential handoff from gbrain mcp grant. Install it with the bearer-token form: GBRAIN_REMOTE_TOKEN="$(cat ${shellQuote(path)})" ${bearerForm('')}`);
    }
    const harness = harnessAdapter(value('--harness') ?? value('--agent') ?? c.harness ?? 'generic');
    const endpoint = normalizeMcpUrl(args[0] ?? '');
    if (!endpoint.ok || endpoint.url !== c.mcp_url) throw new Error('Endpoint does not match the private credential handoff');
    const result = args.includes('--install') || args.includes('--remove')
      ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path, freshToken: args.includes('--fresh-token'), ...(args.includes('--no-instructions') ? { instructions: false } : {}), ...(skillLoading ? { skillLoading } : {}), ...(value('--gbrain-bin') ? { gbrainBin: value('--gbrain-bin') } : {}) })
      : { ...credentialReceipt(c), status: 'prepared', harness: harness.id, documentation: harness.guide, next_action: 'Run this command with --install inside the intended harness environment. Keep the credential file private.' };
    const exposure = args.includes('--remove') ? null : sharedTokenNotice({ kind: 'oauth_client', id: c.client_id }, { harness: harness.id });
    writeExposureNotice(exposure);
    console.log(JSON.stringify(exposure ? { ...result, warnings: renderedExposure(exposure) } : result, null, args.includes('--json') ? undefined : 2));
    const token = result as Partial<ReturnType<typeof inlineTokenReceipt>>;
    if (!args.includes('--json') && token.token_storage === 'inline' && token.if_exposed) {
      console.error(`The bearer token is stored inline in ${token.config_path}; this output never prints it. Renew it with: ${token.renew_command}`);
      console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);
      if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);
    }
    const skills = (result as { skills?: SkillsBlockOutcome }).skills;
    const turnHookError = (result as { turn_hook?: { error?: { message: string; fix: { argv?: string[] } } } }).turn_hook?.error;
    if (skillsOutcomeFailed(skills) || turnHookError) {
      if (skillsOutcomeFailed(skills)) console.error(`skills index: ${skills!.detail}${'remote_membership_pending' in result && result.remote_membership_pending ? ' (remote membership deactivation is also pending; exit 1 outranks its exit 2)' : ''}`);
      if (turnHookError) console.error(`turn_hook_not_loaded: the per-turn gbrain hook is not active: ${turnHookError.message}. Fix: ${turnHookError.fix.argv?.join(' ')}`);
      setCliExitVerdict(1);
    } else if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);
  } catch (error) {
    console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));
    setCliExitVerdict(1);
  }
}