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/container/agent-runner/src/providers/opencode.memory.test.ts

View on GitHub
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import fs from 'fs';
import os from 'os';
import path from 'path';

import { OpenCodeProvider } from './opencode.js';
import { buildOpenCodeConfig } from './opencode-config.js';
import {
  prepareOpenCodeMemory,
  openCodeInstructionsPath,
  runHookCommand,
  runMemorySessionHook,
  type OpenCodeMemorySessionHook,
} from './opencode-memory.js';

// The same registered renderer used by other providers supplies a turn-start
// snapshot. Native OpenCode rereads its output file during that turn.

const MARKER = '<<memory-block>>';

let dir: string;
let scriptSeq = 0;

function logPath(): string {
  return path.join(dir, 'stdin.log');
}

/** Payloads the hook command received, one per invocation, in order. */
function invocations(): string[] {
  if (!fs.existsSync(logPath())) return [];
  return fs
    .readFileSync(logPath(), 'utf-8')
    .split('\n')
    .filter((line) => line.length > 0);
}

/**
 * A stand-in for `bun /app/src/memory/hook.ts`: appends its stdin to the log,
 * prints `body` on stdout, exits with `exitCode`.
 */
function fakeHook(opts: { body?: string; exitCode?: number } = {}): OpenCodeMemorySessionHook {
  const body = opts.body ?? MARKER;
  const script = path.join(dir, `hook-${scriptSeq++}.sh`);
  fs.writeFileSync(
    script,
    [
      '#!/bin/sh',
      `cat >> "${logPath()}"`,
      `echo "" >> "${logPath()}"`,
      `cat <<'EOF'`,
      body,
      'EOF',
      `exit ${opts.exitCode ?? 0}`,
    ].join('\n') + '\n',
  );
  return { command: `sh ${script}`, legacyCommands: [], sources: ['startup', 'clear', 'compact'] };
}

beforeEach(() => {
  dir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-memory-'));
  scriptSeq = 0;
});
afterEach(() => {
  fs.rmSync(dir, { recursive: true, force: true });
});

describe('runMemorySessionHook', () => {
  it('feeds the hook the SessionStart lifecycle payload for the source it runs', async () => {
    const hook = fakeHook();
    expect(await runMemorySessionHook(hook, 'startup')).toBe(MARKER);
    expect(await runMemorySessionHook(hook, 'compact')).toBe(MARKER);
    expect(invocations()).toEqual([
      '{"hook_event_name":"SessionStart","source":"startup"}',
      '{"hook_event_name":"SessionStart","source":"compact"}',
    ]);
  });

  it('injects the command output verbatim — truncation belongs to the shared renderer', async () => {
    // Far past the shared renderer's 16k-per-file budget: whatever the command
    // decided to print is what gets injected, uncut, so the caps live in one
    // place instead of being re-implemented (and double-applied) here.
    const big = 'x'.repeat(40_000);
    const out = await runMemorySessionHook(fakeHook({ body: big }), 'startup');
    expect(out).toBe(big);
    expect(out).toHaveLength(40_000);
  });

  it('distinguishes renderer failure from successfully empty output', async () => {
    expect(await runMemorySessionHook(fakeHook({ exitCode: 3 }), 'startup')).toBeUndefined();
    expect(await runMemorySessionHook(fakeHook({ body: '' }), 'startup')).toBe('');
    expect(await runMemorySessionHook(undefined, 'startup')).toBeUndefined();
    expect(
      await runMemorySessionHook(
        { command: path.join(dir, 'does-not-exist.sh'), legacyCommands: [], sources: ['startup'] },
        'startup',
      ),
    ).toBeUndefined();
  });

  it('gives up at the deadline even when a background child keeps stdout open', async () => {
    // The async path must not wait for `close` behind a lingering grandchild
    // or a hook that ignores SIGTERM.
    const started = Date.now();
    const res = await runHookCommand('sleep 5 & echo partial; wait', '{}', 150);
    expect(Date.now() - started).toBeLessThan(2000);
    expect(res.error?.message).toBe('timed out after 150ms');
    expect(res.stdout).toBe('partial\n');
  });

  it('skips a source the registration does not declare', async () => {
    const hook = { ...fakeHook(), sources: ['startup'] as const };
    expect(await runMemorySessionHook(hook, 'compact')).toBeUndefined();
    expect(invocations()).toEqual([]);
  });
});

describe('rendered turn instructions', () => {
  it('writes rendered memory, core instructions and delivery wording into one private file', async () => {
    const file = path.join(dir, 'turn.md');
    await prepareOpenCodeMemory(fakeHook(), 'CORE', 'ROUTING', file);
    expect(fs.readFileSync(file, 'utf8')).toBe(`${MARKER}\n\nCORE\n\nROUTING`);
    expect(fs.statSync(file).mode & 0o777).toBe(0o600);
    expect(invocations()).toEqual(['{"hook_event_name":"SessionStart","source":"startup"}']);
  });

  it('refreshes the same file on each external turn, including a resumed session', async () => {
    const file = path.join(dir, 'turn.md');
    await prepareOpenCodeMemory(fakeHook(), 'OLD', 'OLD ROUTING', file);
    await prepareOpenCodeMemory(fakeHook({ body: 'FRESH' }), 'CURRENT', 'ROUTING', file);
    expect(fs.readFileSync(file, 'utf8')).toBe('FRESH\n\nCURRENT\n\nROUTING');
    expect(invocations()).toHaveLength(2);
  });

  it('keeps current instructions when rendering fails and does not resurrect stale memory', async () => {
    const file = path.join(dir, 'turn.md');
    await prepareOpenCodeMemory(fakeHook(), 'OLD', '', file);
    await prepareOpenCodeMemory(fakeHook({ exitCode: 1 }), 'CURRENT', 'ROUTING', file);
    expect(fs.readFileSync(file, 'utf8')).toBe('CURRENT\n\nROUTING');
    await prepareOpenCodeMemory(fakeHook({ body: '' }), 'NEW', '', file);
    expect(fs.readFileSync(file, 'utf8')).toBe('NEW');
  });
});

describe('OpenCodeProvider memory registration', () => {
  it('refuses to start a query when the shared hook was never registered', () => {
    expect(() => new OpenCodeProvider().query({ prompt: 'hi', cwd: '/workspace' })).toThrow(
      /memory session hook was not registered/i,
    );
  });

  it('does not run startup before the lazy query actually creates a session', () => {
    const provider = new OpenCodeProvider();
    provider.registerMemorySessionHook(fakeHook());
    provider.query({ prompt: 'hi', cwd: '/workspace' });
    provider.query({ prompt: 'hi again', cwd: '/workspace', continuation: 'ses_existing' });
    expect(invocations()).toEqual([]);
  });
});

describe('buildOpenCodeConfig instructions', () => {
  it('loads the rendered turn file, preserving the shared renderer caps on raw memory', () => {
    const config = buildOpenCodeConfig({});
    expect(config.instructions).toContain(openCodeInstructionsPath());
    expect(config).not.toHaveProperty('plugin');
    expect(config.instructions).not.toContain('/workspace/agent/memory/index.md');
    expect(config.instructions).not.toContain('/workspace/agent/memory/system/definition.md');
  });

  it('loads the composed group instructions from the agent directory', () => {
    const config = buildOpenCodeConfig({});
    expect(config.instructions).toContain('/workspace/agent/CLAUDE.md');
    expect(config.instructions).toContain('/workspace/agent/CLAUDE.local.md');
  });
});
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