Skip to content

nanocoai/nanoclaw / .claude/skills/add-opencode

add-opencode

Verified

Use OpenCode as an agent provider. OpenRouter, OpenAI, Google, DeepSeek, etc. via OpenCode config — not the Anthropic Agent SDK. Per group via `ncl groups config update --provider opencode`; host passes OPENCODE_* and XDG mount when spawning containers.

FileKindSize
ARCHITECTURE.mdmarkdown8.0 KB
REMOVE.mdmarkdown3.4 KB
SKILL.mdskill md19.8 KB
apply-fixtures.jsonconfig303 B
payload/container/agent-runner/src/provider-contracts/opencode.tsscript866 B
payload/container/agent-runner/src/providers/mcp-to-opencode.test.tsscript2.7 KB
payload/container/agent-runner/src/providers/mcp-to-opencode.tsscript1.6 KB
payload/container/agent-runner/src/providers/opencode-auth.test.tsscript3.1 KB
payload/container/agent-runner/src/providers/opencode-auth.tsscript1.7 KB
payload/container/agent-runner/src/providers/opencode-config.tsscript10.0 KB
payload/container/agent-runner/src/providers/opencode-memory.tsscript4.4 KB
payload/container/agent-runner/src/providers/opencode-registration.test.tsscript625 B
payload/container/agent-runner/src/providers/opencode-turn.tsscript14.1 KB
payload/container/agent-runner/src/providers/opencode.config.test.tsscript16.2 KB
payload/container/agent-runner/src/providers/opencode.conformance.test.tsscript253 B
payload/container/agent-runner/src/providers/opencode.empty-resume.test.tsscript14.7 KB
payload/container/agent-runner/src/providers/opencode.factory.test.tsscript331 B
payload/container/agent-runner/src/providers/opencode.memory.test.tsscript6.9 KB
payload/container/agent-runner/src/providers/opencode.native.test.tsscript17.6 KB
payload/container/agent-runner/src/providers/opencode.question.test.tsscript7.6 KB
payload/container/agent-runner/src/providers/opencode.shared-runtime.test.tsscript30.9 KB
payload/container/agent-runner/src/providers/opencode.sse-cleanup.test.tsscript6.4 KB
payload/container/agent-runner/src/providers/opencode.tsscript24.9 KB
payload/scripts/opencode-auth-config.test.tsscript27.1 KB
payload/scripts/opencode-auth.test.tsscript19.7 KB
payload/scripts/opencode-auth.tsscript21.4 KB
payload/scripts/opencode-gateway.test.tsscript7.1 KB
payload/scripts/opencode-host.test.tsscript13.4 KB
payload/scripts/opencode-host.tsscript8.9 KB
payload/scripts/opencode-model-config.tsscript8.6 KB
payload/scripts/opencode-models.test.tsscript10.6 KB
payload/scripts/opencode-models.tsscript4.0 KB
payload/scripts/opencode-vault.test.tsscript3.3 KB
payload/scripts/opencode-vault.tsscript2.7 KB
payload/scripts/tsconfig.opencode-auth.jsonconfig171 B
payload/setup/providers/opencode.test.tsscript1.2 KB
payload/setup/providers/opencode.tsscript806 B
payload/src/provider-contracts/opencode.tsscript2.9 KB
payload/src/providers/opencode-auth-stub.tsscript909 B
payload/src/providers/opencode-registration.test.tsscript8.5 KB
payload/src/providers/opencode.tsscript2.7 KB

payload/scripts/opencode-host.test.ts

View on GitHub
import fs from 'fs';
import os from 'os';
import path from 'path';
import { EventEmitter } from 'events';

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const edge = vi.hoisted(() => ({
  confirm: vi.fn(),
  spawn: vi.fn(),
  spawnSync: vi.fn(),
  nativeHome: '',
  exitCode: 0,
  postinstallExitCode: 0,
  warn: vi.fn(),
}));
vi.mock('@clack/prompts', () => ({
  confirm: edge.confirm,
  isCancel: (v: unknown) => typeof v === 'symbol',
  log: { info: vi.fn(), warn: edge.warn },
  note: vi.fn(),
}));
vi.mock('child_process', () => ({ spawn: edge.spawn, spawnSync: edge.spawnSync }));
vi.mock('os', async (original) => ({
  default: { ...(await original<typeof import('os')>()).default, homedir: () => edge.nativeHome },
}));

import {
  findHostOpenCode,
  hostOpenCode,
  offerOpenCodeFailureAssist,
  runHostOpenCode,
  OPENCODE_HOST_INSTALL_VERSION,
} from './opencode-host.js';

let root: string;
function touch(file: string, content = ''): void {
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, content);
}
beforeEach(() => {
  root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-host-test-'));
  edge.nativeHome = path.join(root, 'native-home');
  edge.exitCode = 0;
  edge.postinstallExitCode = 0;
  vi.stubEnv('PATH', path.join(root, 'bin'));
  vi.clearAllMocks();
  edge.confirm.mockResolvedValue(true);
  edge.spawnSync.mockImplementation((_binary: string, args: string[]) => ({
    status: 0,
    stdout: args[0] === '--help' ? '      --prompt        prompt to use [string]' : OPENCODE_HOST_INSTALL_VERSION,
  }));
  edge.spawn.mockImplementation((binary: string, args: string[]) => {
    if (binary === 'npm' && edge.exitCode === 0) {
      touch(path.join(args[args.indexOf('--prefix') + 1], 'node_modules/.bin/opencode'));
    }
    const child = new EventEmitter();
    queueMicrotask(() => child.emit('close', binary === process.execPath ? edge.postinstallExitCode : edge.exitCode));
    return child;
  });
});
afterEach(() => {
  vi.unstubAllEnvs();
  fs.rmSync(root, { recursive: true, force: true });
});

describe('native host OpenCode lifecycle', () => {
  it('imports without running a CLI, authenticating, or changing configuration', async () => {
    vi.resetModules();
    await import('./opencode-host.js');
    expect(edge.spawn).not.toHaveBeenCalled();
    expect(edge.spawnSync).not.toHaveBeenCalled();
    expect(edge.confirm).not.toHaveBeenCalled();
  });

  it('preserves an existing native installation and configuration', async () => {
    const binary = path.join(root, 'bin/opencode');
    const config = path.join(edge.nativeHome, '.config/opencode/opencode.json');
    touch(binary, 'existing binary');
    touch(config, '{"model":"user/chosen-model"}');
    edge.spawnSync.mockImplementation((_binary: string, args: string[]) => ({
      status: 0,
      stdout: args[0] === '--help' ? '      --prompt        prompt to use [string]' : '1.18.26',
    }));
    expect(await hostOpenCode.prepare(root)).toBe('available');
    expect(findHostOpenCode(root)).toEqual({ binary, version: '1.18.26' });
    expect(fs.readFileSync(binary, 'utf8')).toBe('existing binary');
    expect(fs.readFileSync(config, 'utf8')).toBe('{"model":"user/chosen-model"}');
    expect(edge.spawn).not.toHaveBeenCalled();
    expect(edge.confirm).not.toHaveBeenCalled();
  });

  it('rejects an old CLI and one without the maintenance prompt option', () => {
    touch(path.join(root, 'bin/opencode'));
    edge.spawnSync.mockReturnValue({ status: 0, stdout: '1.18.24' });
    expect(findHostOpenCode(root)).toBeUndefined();
    edge.spawnSync.mockImplementation((_binary: string, args: string[]) => ({
      status: 0,
      stdout: args[0] === '--help' ? 'Usage: opencode [project]' : '1.18.25',
    }));
    expect(findHostOpenCode(root)).toBeUndefined();
  });

  it('accepts successful stderr-only help after installation and for later launches', async () => {
    edge.spawnSync.mockImplementation((_binary: string, args: string[]) => ({
      status: 0,
      stdout: args[0] === '--help' ? '' : OPENCODE_HOST_INSTALL_VERSION,
      stderr: args[0] === '--help' ? '      --prompt        prompt to use [string]' : '',
    }));
    expect(await hostOpenCode.prepare(root)).toBe('available');
    const binary = path.join(root, 'data/host-harness/opencode/node_modules/.bin/opencode');
    expect(findHostOpenCode(root)).toEqual({ binary, version: OPENCODE_HOST_INSTALL_VERSION });
    expect(await hostOpenCode.launch(root)).toBe('exited');
    expect(edge.spawn).toHaveBeenLastCalledWith(binary, [], {
      cwd: root,
      stdio: 'inherit',
      env: expect.objectContaining({ OPENCODE_PERMISSION: JSON.stringify({ edit: 'ask', bash: 'ask' }) }),
    });
  });

  it('rejects failed help commands even when stderr names the maintenance option', () => {
    touch(path.join(root, 'bin/opencode'));
    edge.spawnSync.mockImplementation((_binary: string, args: string[]) => ({
      status: args[0] === '--help' ? 1 : 0,
      stdout: args[0] === '--help' ? '' : OPENCODE_HOST_INSTALL_VERSION,
      stderr: args[0] === '--help' ? '      --prompt        prompt to use [string]' : '',
    }));
    expect(findHostOpenCode(root)).toBeUndefined();
  });

  it('prefers a newer compatible native installation over the managed copy', () => {
    const native = path.join(root, 'bin/opencode');
    const managed = path.join(root, 'data/host-harness/opencode/node_modules/.bin/opencode');
    touch(native);
    touch(managed);
    edge.spawnSync.mockImplementation((binary: string, args: string[]) => ({
      status: 0,
      stdout:
        args[0] === '--help'
          ? '      --prompt        prompt to use [string]'
          : binary === native
            ? '1.19.0'
            : '1.18.25',
    }));
    expect(findHostOpenCode(root)).toEqual({ binary: native, version: '1.19.0' });
  });

  it('installs the exact CLI and runs only its native linker inside this checkout', async () => {
    expect(await hostOpenCode.prepare(root)).toBe('available');
    const [binary, args, options] = edge.spawn.mock.calls[0];
    expect(binary).toBe('npm');
    expect(args).toEqual([
      'install',
      '--prefix',
      path.join(root, 'data/host-harness/opencode'),
      '--no-save',
      '--package-lock=false',
      '--ignore-scripts',
      '--no-audit',
      '--no-fund',
      `opencode-ai@${OPENCODE_HOST_INSTALL_VERSION}`,
    ]);
    expect(options).toEqual({ cwd: root, stdio: 'inherit' });
    expect(edge.spawn.mock.calls[1]).toEqual([
      process.execPath,
      [path.join(root, 'data/host-harness/opencode/node_modules/opencode-ai/postinstall.mjs')],
      { cwd: root, stdio: 'inherit' },
    ]);
    expect(edge.spawn).toHaveBeenCalledTimes(2);
    expect(fs.existsSync(path.join(root, 'package.json'))).toBe(false);
  });

  it('distinguishes declined installation, cancellation, and installer failure', async () => {
    edge.confirm.mockResolvedValueOnce(false);
    expect(await hostOpenCode.prepare(root)).toBe('declined');
    edge.confirm.mockResolvedValueOnce(Symbol('cancel'));
    expect(await hostOpenCode.prepare(root)).toBe('cancelled');
    expect(edge.spawn).not.toHaveBeenCalled();
    edge.exitCode = 1;
    expect(await hostOpenCode.prepare(root)).toBe('unavailable');
    expect(edge.spawn).toHaveBeenCalledTimes(1);
  });

  it('rejects native-linker failures and a nonmatching installed CLI version', async () => {
    edge.postinstallExitCode = 1;
    expect(await hostOpenCode.prepare(root)).toBe('unavailable');
    edge.postinstallExitCode = 0;
    edge.spawnSync.mockReturnValueOnce({ status: 1, stdout: '' }).mockReturnValue({ status: 0, stdout: '1.18.24' });
    expect(await hostOpenCode.prepare(root)).toBe('unavailable');
  });

  it('uses the current checkout, a restrictive permission override, and only a context file reference in argv', async () => {
    touch(path.join(root, 'bin/opencode'));
    const context = path.join(root, 'context with spaces.md');
    touch(context, 'PRIVATE FAILURE DETAIL');
    expect(await hostOpenCode.launch(root, context)).toBe('exited');
    const [, args, options] = edge.spawn.mock.calls[0];
    expect(args).toEqual(['--prompt', `Read ${JSON.stringify(context)} and follow the maintenance request inside it.`]);
    expect(JSON.stringify(args)).not.toContain('PRIVATE FAILURE DETAIL');
    expect(args).not.toContain('--auto');
    expect(options.cwd).toBe(root);
    expect(options.stdio).toBe('inherit');
    expect(options.env.PATH).toBe(process.env.PATH);
    // OPENCODE_PERMISSION merges after the global and project config, so it
    // wins over an operator's top-level allow-all.
    expect(JSON.parse(options.env.OPENCODE_PERMISSION)).toEqual({ edit: 'ask', bash: 'ask' });
  });

  it('keeps native configuration free of the maintenance override', async () => {
    touch(path.join(root, 'bin/opencode'));
    await hostOpenCode.configure(root);
    expect(edge.spawn.mock.calls[0][2]).toEqual({ cwd: root, stdio: 'inherit' });
  });

  it('allows native configuration without consulting Docker or OneCLI', async () => {
    touch(path.join(root, 'bin/opencode'));
    expect(await hostOpenCode.configure(root)).toBe('exited');
    expect(edge.spawn.mock.calls[0][1]).toEqual([]);
    edge.exitCode = 1;
    expect(await hostOpenCode.launch(root)).toBe('failed');
  });
});

describe('existing setup failure-assist hook', () => {
  const context = { stepName: 'auth', msg: 'PRIVATE FAILURE DETAIL', hint: 'Authentication callback failed' };
  it('registers and invokes the installed provider hook with private temporary context', async () => {
    await import('../setup/providers/index.js');
    const { getSetupProvider } = await import('../setup/providers/registry.js');
    touch(path.join(root, 'bin/opencode'));
    let contextFile = '';
    edge.spawn.mockImplementation((_binary: string, args: string[]) => {
      contextFile = JSON.parse(args[1].slice('Read '.length).split(' and follow')[0]);
      expect(fs.readFileSync(contextFile, 'utf8')).toContain('PRIVATE FAILURE DETAIL');
      expect(fs.readFileSync(contextFile, 'utf8')).toContain('Authentication callback failed');
      expect(fs.statSync(contextFile).mode & 0o777).toBe(0o600);
      expect(fs.statSync(path.dirname(contextFile)).mode & 0o777).toBe(0o700);
      expect(JSON.stringify(args)).not.toContain('PRIVATE FAILURE DETAIL');
      const child = new EventEmitter();
      queueMicrotask(() => child.emit('close', 0));
      return child;
    });
    expect(await getSetupProvider('opencode')!.offerFailureAssist!(context, root)).toBe('launched');
    expect(fs.existsSync(path.dirname(contextFile))).toBe(false);
  });
  it('preserves decline and unavailable outcomes for the shared dispatcher', async () => {
    edge.confirm.mockResolvedValueOnce(false);
    expect(await offerOpenCodeFailureAssist(context, root)).toBe('declined');
    expect(edge.spawn).not.toHaveBeenCalled();
    touch(path.join(root, 'bin/opencode'));
    edge.spawn.mockImplementation(() => {
      const child = new EventEmitter();
      queueMicrotask(() => child.emit('error', new Error('spawn failed')));
      return child;
    });
    expect(await offerOpenCodeFailureAssist(context, root)).toBe('unavailable');
  });
  it('allows guarded fallback when help was accepted but installing OpenCode was declined', async () => {
    edge.confirm.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
    expect(await offerOpenCodeFailureAssist(context, root)).toBe('unavailable');
    expect(edge.spawn).not.toHaveBeenCalled();
  });
  it('preserves cancellation at the installation prompt', async () => {
    edge.confirm.mockResolvedValueOnce(true).mockResolvedValueOnce(Symbol('cancel'));
    expect(await offerOpenCodeFailureAssist(context, root)).toBe('declined');
    expect(edge.spawn).not.toHaveBeenCalled();
  });
  it('does not launch a second assistant after OpenCode runs but exits unsuccessfully', async () => {
    touch(path.join(root, 'bin/opencode'));
    edge.exitCode = 1;
    expect(await offerOpenCodeFailureAssist(context, root)).toBe('launched');
    expect(edge.warn).toHaveBeenCalledWith(expect.stringContaining('exited unsuccessfully'));
  });
  it('routes standalone update work to the existing update skill', async () => {
    touch(path.join(root, 'bin/opencode'));
    edge.spawn.mockImplementation((_binary: string, args: string[]) => {
      const file = JSON.parse(args[1].slice('Read '.length).split(' and follow')[0]);
      expect(fs.readFileSync(file, 'utf8')).toContain('.claude/skills/update-nanoclaw/SKILL.md');
      const child = new EventEmitter();
      queueMicrotask(() => child.emit('close', 0));
      return child;
    });
    await runHostOpenCode(['--update'], root);
  });
  it('asks before every edit and command in debug and update sessions', async () => {
    touch(path.join(root, 'bin/opencode'));
    const permissions: Record<string, string>[] = [];
    edge.spawn.mockImplementation((_binary: string, _args: string[], options: { env: Record<string, string> }) => {
      permissions.push(JSON.parse(options.env.OPENCODE_PERMISSION));
      const child = new EventEmitter();
      queueMicrotask(() => child.emit('close', 0));
      return child;
    });
    await runHostOpenCode(['--update'], root);
    await runHostOpenCode(['--debug'], root);
    expect(permissions).toHaveLength(2);
    for (const permission of permissions) expect(permission).toEqual({ edit: 'ask', bash: 'ask' });
  });
});

it('reports standalone installation failure instead of a successful command exit', async () => {
  edge.exitCode = 1;
  await expect(runHostOpenCode(['--configure'], root)).rejects.toThrow('unavailable');
});
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 321kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 321kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 321kUpdated Claude CodeCodexVerifiedInstall