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-gateway.test.ts

View on GitHub
// OpenCode reaches credentials only through the selected gateway's
// credential store. This test installs a gateway that exists nowhere else —
// a fixture skill with its own `gateway.json` — and drives the real setup
// entry points through the real `getCredentialStore()` resolution. If OpenCode
// carried a gateway-specific branch, the fixture gateway could not satisfy it.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const fixture = vi.hoisted(() => ({
  backend: 'openrouter',
  key: 'fixture-key',
  passwords: 0,
  writes: [] as Array<[string, string | null]>,
}));
vi.mock('../setup/lib/bright-select.js', () => ({
  brightSelect: async ({ message }: { message: string }) =>
    message.includes('backend') ? fixture.backend : message.includes('ChatGPT') ? 'device' : 'openrouter/fixture',
}));
vi.mock('@clack/prompts', () => ({
  isCancel: (value: unknown) => typeof value === 'symbol',
  cancel: () => {
    throw new Error('cancelled');
  },
  text: async () => 'openrouter/fixture',
  confirm: async () => false,
  password: async () => {
    fixture.passwords++;
    return fixture.key;
  },
  log: { success: vi.fn(), info: vi.fn(), warn: vi.fn(), step: vi.fn() },
}));
vi.mock('../setup/logs.js', () => ({ userInput: vi.fn(), step: vi.fn() }));
vi.mock('../setup/set-env.js', () => ({
  upsertEnvVar: (key: string, value: string) => fixture.writes.push([key, value]),
  removeEnvVar: (key: string) => fixture.writes.push([key, null]),
}));
vi.mock('child_process', async (original) => ({
  ...(await original<typeof import('child_process')>()),
  execFileSync: () => {
    throw new Error('catalog unavailable');
  },
}));
import { runOpenCodeChatGptAuth, runOpenCodeSetupAuth } from './opencode-auth.js';

type Call = [string, ...unknown[]];
declare global {
  // eslint-disable-next-line no-var
  var __opencodeGatewayFixture: { calls: Call[]; found: { reusable: boolean } | null; withConnection: boolean };
}

const cwd = process.cwd();
const roots: string[] = [];
function installFixtureGateway(): string {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-fixture-gateway-'));
  roots.push(root);
  const skill = path.join(root, '.claude/skills/add-fixture');
  fs.mkdirSync(path.join(skill, 'scripts'), { recursive: true });
  fs.writeFileSync(
    path.join(skill, 'gateway.json'),
    JSON.stringify({ kind: 'fixture', label: 'Fixture', description: 'test gateway', default: true }),
  );
  fs.writeFileSync(path.join(skill, 'SKILL.md'), '# fixture\n');
  fs.writeFileSync(
    path.join(skill, 'scripts/credential-store.ts'),
    `
    const state = globalThis.__opencodeGatewayFixture;
    export function createCredentialStore() {
      return {
        has: async () => false,
        save: async () => {},
        modelEndpoint: (url) => ({ configure: async () => { state.calls.push(['endpoint', url]); } }),
        ...(state.withConnection
          ? {
              connection: (target) => ({
                find: async (options) => { state.calls.push(['find', target, Boolean(options)]); return state.found; },
                save: async (value) => { state.calls.push(['save', value]); },
                keep: async () => { state.calls.push(['keep']); },
              }),
            }
          : {}),
      };
    }`,
  );
  return root;
}

beforeEach(() => {
  globalThis.__opencodeGatewayFixture = { calls: [], found: null, withConnection: true };
  Object.assign(fixture, { backend: 'openrouter', key: 'fixture-key', passwords: 0, writes: [] });
  for (const key of [
    'OPENCODE_PROVIDER',
    'OPENCODE_MODEL',
    'OPENCODE_SMALL_MODEL',
    'OPENCODE_BASE_URL',
    'OPENCODE_AUTH_MODE',
  ])
    vi.stubEnv(key, undefined);
  vi.stubEnv('NANOCLAW_GATEWAY_PROVIDER', 'fixture');
  process.chdir(installFixtureGateway());
});
afterEach(() => {
  process.chdir(cwd);
  vi.unstubAllEnvs();
  for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
});
const calls = () => globalThis.__opencodeGatewayFixture.calls;

describe('OpenCode through a gateway it has never heard of', () => {
  it('describes an API key with only provider-owned facts and saves before writing defaults', async () => {
    await runOpenCodeSetupAuth();
    expect(calls().map(([name]) => name)).toEqual(['find', 'save', 'endpoint']);
    expect(calls()[0][1]).toEqual({
      name: 'OpenCode openrouter',
      kind: 'api-key',
      host: 'openrouter.ai',
      proxyValue: 'nc-opencode-token-v1',
      provider: 'opencode',
      injection: { headerName: 'Authorization', valueFormat: 'Bearer {value}' },
    });
    expect(calls()[0][2]).toBe(true);
    expect(calls()[1]).toEqual(['save', 'fixture-key']);
    expect(calls()[2]).toEqual(['endpoint', 'https://openrouter.ai']);
    expect(fixture.writes).toContainEqual(['OPENCODE_PROVIDER', 'openrouter']);
  });

  it('keeps a reusable credential on a blank answer without asking the gateway for an id', async () => {
    globalThis.__opencodeGatewayFixture.found = { reusable: true };
    fixture.key = '';
    await runOpenCodeSetupAuth();
    expect(calls().map(([name]) => name)).toEqual(['find', 'keep', 'endpoint']);
    expect(fixture.writes).toContainEqual(['OPENCODE_PROVIDER', 'openrouter']);
  });

  it('demands a value when the gateway reports the stored credential cannot be kept', async () => {
    globalThis.__opencodeGatewayFixture.found = { reusable: false };
    fixture.key = '';
    await expect(runOpenCodeSetupAuth()).rejects.toThrow('API key is required');
    expect(calls().map(([name]) => name)).toEqual(['find']);
    expect(fixture.writes).toEqual([]);
  });

  it('hands ChatGPT sign-in to the gateway as the named profile and reuses a live login', async () => {
    const signIn = vi.fn(async (_method: string, _root: string, vault: { save: (v: unknown) => Promise<void> }) => {
      await vault.save({ profile: 'chatgpt', accessToken: 'a', refreshToken: 'r', accountId: 'acct' });
    });
    await runOpenCodeChatGptAuth('device', { signIn });
    expect(calls()[0][1]).toEqual({
      name: 'OpenCode ChatGPT',
      kind: 'oauth',
      host: 'chatgpt.com',
      proxyValue: 'nc-opencode-token-v1',
      provider: 'opencode',
      oauth: { profile: 'chatgpt', clientId: expect.any(String), tokenEndpoint: 'https://auth.openai.com/oauth/token' },
    });
    expect(calls()[1]).toEqual([
      'save',
      { profile: 'chatgpt', accessToken: 'a', refreshToken: 'r', accountId: 'acct' },
    ]);
    globalThis.__opencodeGatewayFixture.calls = [];
    globalThis.__opencodeGatewayFixture.found = { reusable: true };
    await runOpenCodeChatGptAuth('device', { signIn });
    expect(calls().map(([name]) => name)).toEqual(['find', 'keep']);
    expect(signIn).toHaveBeenCalledTimes(1);
  });

  it('fails before any prompt or default when the selected gateway offers no connections', async () => {
    globalThis.__opencodeGatewayFixture.withConnection = false;
    await expect(runOpenCodeSetupAuth()).rejects.toThrow('does not support provider credential connections');
    expect(fixture.passwords).toBe(0);
    expect(fixture.writes).toEqual([]);
  });
});
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