Skip to content

Commit 85f7742

Browse files
agents-squads[bot]Jorge Vidaurreclaude
authored
feat(providers): opencode adapter — init menu, providers table, error detection, docs (#1143)
* feat(providers): opencode adapter — LLM_CLIS entry, session detection, board rows (partial #978) Salvaged from a lane run: opencode LLM_CLIS entry (headless 'opencode run --auto'), sessions.ts detection pattern, and board integration reading ~/.local/share/opencode/opencode.db (deriveOpenCodeRows — real cost, not notional; deduped against ledger rows like claude-harness rows). Hardened the sqlite query: directory path is SQL-escaped and the whole statement shell-quoted via JSON.stringify — a path with a quote no longer breaks the command. Remaining #978 scope (init provider menu, providers table row, fatal-error patterns, docs) lands on this branch next. Refs #978 Co-Authored-By: Claude <[email protected]> * feat(providers): opencode init menu entry + headless priority (#978) Add opencode to setup-checks PROVIDERS (mirroring aider's shape) and the init Provider union, so `squads init` can select/scaffold it. Appended to CLI_PROVIDER_PRIORITY after aider — same lowest-priority tier, only auto-picked headless when no higher-priority CLI is found. * test(providers): cover opencode LLM_CLIS registry entry (#978) `squads providers` renders getAllCLIStatus(), which already maps over LLM_CLIS.opencode — no source change needed. Add a direct assertion so its identity/buildArgs/scope (no streamJson, no parseUsage) can't silently regress. * fix(providers): detect opencode's Vercel AI SDK fatal errors (#978) OpenCode is built on the Vercel AI SDK; real-world failures surface as AI_APICallError / AI_LoadAPIKeyError etc. (anomalyco/opencode#2245, #1061, #1631, #2944) rather than a non-zero exit, so add them to PROVIDER_FATAL alongside the existing litellm/aider signature. * docs(providers): document opencode as a file-based executor (#978) Add opencode to the provider table and the file-based-executors section in docs/providers.md, and mention it alongside claude/gemini/ aider in the README's CLI-orchestration blurb. --------- Co-authored-by: Jorge Vidaurre <[email protected]> Co-authored-by: Claude <[email protected]>
1 parent 0cffa85 commit 85f7742

11 files changed

Lines changed: 200 additions & 15 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ team — tuned by role so scanners stay lightweight and leads get the full
7171
picture. Agents that know what's been done don't duplicate work; agents
7272
that see their own feedback stop producing noise.
7373

74-
Squads shells out to native AI CLIs (`claude`, `gemini`, `aider`, …), so
74+
Squads shells out to native AI CLIs (`claude`, `gemini`, `aider`, `opencode`, …), so
7575
mixed-model teams work out of the box: a cheap model scans, a deep
7676
reasoning model builds, a mid-tier model verifies.
7777

‎docs/providers.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ context, and tool use independently — Squads just orchestrates.
1515
| Anthropic | `claude` | Stable — primary provider |
1616
| Google | `gemini` | Stable |
1717
| DeepSeek | `aider` (delegation) | New in 0.8.0 — file-based roles |
18+
| OpenCode | `opencode` (native) | New — file-based executor |
1819
| OpenAI | `codex` | Experimental |
1920
| Mistral | `vibe` | Experimental |
2021
| xAI | `grok` | Experimental |
@@ -47,12 +48,13 @@ Precedence: agent frontmatter → `--provider` flag → squad
4748

4849
## File-based executors
4950

50-
Some providers (DeepSeek via `aider`) run as *file-based executors*: they
51-
read and edit files and commit the result, but don't run shell commands
52-
or browse the web. They're a fit for validators, formatters, and
53-
summarizers — agents whose job is read files → write files. Squads
54-
harvests their output from the isolated execution worktree, so completed
55-
work is never lost even if the run ends abnormally.
51+
Some providers (DeepSeek via `aider`, and `opencode` directly) run as
52+
*file-based executors*: they read and edit files and commit the result,
53+
but don't run shell commands or browse the web. They're a fit for
54+
validators, formatters, and summarizers — agents whose job is read files
55+
→ write files. Squads harvests their output from the isolated execution
56+
worktree, so completed work is never lost even if the run ends
57+
abnormally.
5658

5759
Every provider run is recorded in observability (`squads exec list`,
5860
`squads usage`) with real token and cost figures parsed from the

‎src/commands/board.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* (#1129) before rendering — otherwise the same run double-counts.
1414
*
1515
* Row provenance: every EXECUTIONS row (and --json `executions` entry)
16-
* carries `source: 'ledger' | 'claude-code'`. Claude-harness rows always
16+
* carries `source: 'ledger' | 'claude-code' | 'opencode'`. Claude-harness rows always
1717
* show provider `claude-code` (the EXECUTOR, not the underlying model) and
1818
* `cost_estimated: true` — their cost is a notional list-price token proxy,
1919
* flagged with a `~` in the COST column, never presented as a real bill.
@@ -30,7 +30,7 @@
3030

3131
import { execSync } from 'child_process';
3232
import { queryExecutions, type ObservabilityRecord } from '../lib/observability.js';
33-
import { deriveClaudeHarnessRows } from '../lib/claude-sessions.js';
33+
import { deriveClaudeHarnessRows, deriveOpenCodeRows } from '../lib/claude-sessions.js';
3434
import { listDetachedRuns } from '../lib/runs-inventory.js';
3535
import { formatDuration } from '../lib/executions.js';
3636
import {
@@ -299,9 +299,12 @@ export async function boardCommand(options: BoardOptions = {}): Promise<void> {
299299
// there's no ledger row — derive them from ~/.claude/projects transcripts
300300
// instead. Degrades to [] on any read failure (never breaks the board).
301301
let harnessRecords: ObservabilityRecord[] = [];
302+
let opencodeRecords: ObservabilityRecord[] = [];
302303
try {
303304
const { getProjectRoot } = await import('../lib/run-utils.js');
304-
harnessRecords = await deriveClaudeHarnessRows(bounds, { projectRoot: getProjectRoot() });
305+
const root = getProjectRoot();
306+
harnessRecords = await deriveClaudeHarnessRows(bounds, { projectRoot: root });
307+
opencodeRecords = await deriveOpenCodeRows(bounds, { projectRoot: root });
305308
} catch { /* transcript reads never break the board */ }
306309

307310
// #1129: a dispatched lane run is BOTH a ledger execution and a
@@ -315,8 +318,11 @@ export async function boardCommand(options: BoardOptions = {}): Promise<void> {
315318
const dedupedHarnessRecords = harnessRecords.filter(
316319
(r) => !r.session_id || !ledgerSessionIds.has(r.session_id),
317320
);
321+
const dedupedOpenCodeRecords = opencodeRecords.filter(
322+
(r) => !r.session_id || !ledgerSessionIds.has(r.session_id),
323+
);
318324

319-
const dayRecords = [...ledgerRecords, ...dedupedHarnessRecords]
325+
const dayRecords = [...ledgerRecords, ...dedupedHarnessRecords, ...dedupedOpenCodeRecords]
320326
.sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime())
321327
.map(repriceIfNeeded); // #1118: reprice GLM runs when env rates now set
322328
const tiles = buildTiles(dayRecords);

‎src/commands/init.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export interface InitOptions {
4343
pack?: string[];
4444
}
4545

46-
type Provider = 'claude' | 'gemini' | 'openai' | 'ollama' | 'cursor' | 'aider' | 'none';
46+
type Provider = 'claude' | 'gemini' | 'openai' | 'ollama' | 'cursor' | 'aider' | 'opencode' | 'none';
4747

4848
type UseCase = 'engineering' | 'marketing' | 'growth' | 'operations' | 'full-company' | 'custom';
4949

@@ -328,7 +328,7 @@ async function prompt(question: string, defaultValue = ''): Promise<string> {
328328

329329
// CLI-based providers, in preference order — used to auto-pick a provider
330330
// headless when the caller didn't force one (#977).
331-
const CLI_PROVIDER_PRIORITY: Provider[] = ['claude', 'gemini', 'ollama', 'aider'];
331+
const CLI_PROVIDER_PRIORITY: Provider[] = ['claude', 'gemini', 'ollama', 'aider', 'opencode'];
332332

333333
/**
334334
* Headless (non-interactive, no --provider) provider resolution.

‎src/lib/claude-sessions.ts‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { existsSync, readdirSync, statSync, createReadStream } from 'fs';
2525
import { join } from 'path';
2626
import { homedir } from 'os';
2727
import { createInterface } from 'readline';
28+
import { execSync } from 'child_process';
2829
import { deriveCostFromTokens, type ObservabilityRecord } from './observability.js';
2930
import { findSquadsDir, listSquads } from './squad-parser.js';
3031

@@ -458,3 +459,129 @@ export async function deriveClaudeHarnessRows(
458459

459460
return rows;
460461
}
462+
463+
// ── OpenCode session reader ───────────────────────────────────────────
464+
465+
function getOpenCodeDbPath(): string {
466+
const dataDir = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
467+
return join(dataDir, 'opencode', 'opencode.db');
468+
}
469+
470+
function parseOpenCodeModel(raw: string): string {
471+
if (!raw) return '';
472+
try {
473+
const m = JSON.parse(raw) as Record<string, unknown>;
474+
return typeof m.id === 'string' ? m.id : '';
475+
} catch {
476+
return '';
477+
}
478+
}
479+
480+
function parseOpenCodeProvider(raw: string): string {
481+
if (!raw) return '';
482+
try {
483+
const m = JSON.parse(raw) as Record<string, unknown>;
484+
return typeof m.providerID === 'string' ? m.providerID : '';
485+
} catch {
486+
return '';
487+
}
488+
}
489+
490+
/**
491+
* Derive execution rows from the opencode SQLite database — the opencode
492+
* equivalent of `deriveClaudeHarnessRows`. opencode stores every session in
493+
* `~/.local/share/opencode/opencode.db` with token counts and cost already
494+
* aggregated per session, so we don't need to stream message-by-message.
495+
*
496+
* Cost is real (opencode tracks actual provider cost), not a notional
497+
* estimate — we still mark `cost_estimated: false` to distinguish from
498+
* Claude Code's list-price proxy.
499+
*/
500+
export async function deriveOpenCodeRows(
501+
bounds: { start: number; end: number },
502+
opts: { projectRoot?: string } = {},
503+
): Promise<ObservabilityRecord[]> {
504+
const dbPath = getOpenCodeDbPath();
505+
if (!existsSync(dbPath)) return [];
506+
507+
const root = opts.projectRoot || process.cwd();
508+
509+
const knownSquads: string[] = [];
510+
try {
511+
const squadsDir = findSquadsDir();
512+
if (squadsDir) knownSquads.push(...listSquads(squadsDir));
513+
} catch { /* attribution degrades to raw slugs */ }
514+
515+
let raw: string;
516+
try {
517+
// SQL-escape the directory (double any single quote) — a path like
518+
// .../jorge's-repo would otherwise terminate the SQL string literal.
519+
const dir = root.replace(/'/g, "''");
520+
const sql =
521+
`SELECT id, directory, time_created, time_updated, cost, ` +
522+
`tokens_input, tokens_output, tokens_cache_read, ` +
523+
`tokens_cache_write, tokens_reasoning, model, agent FROM session ` +
524+
`WHERE directory = '${dir}' ` +
525+
`AND time_updated >= ${bounds.start} AND time_created < ${bounds.end} ` +
526+
`ORDER BY time_created ASC`;
527+
raw = execSync(`sqlite3 -json "${dbPath.replace(/"/g, '\\"')}" ${JSON.stringify(sql)}`, {
528+
encoding: 'utf8',
529+
stdio: ['pipe', 'pipe', 'pipe'],
530+
timeout: 5000,
531+
}).trim();
532+
} catch {
533+
return [];
534+
}
535+
536+
if (!raw) return [];
537+
538+
let rows: Array<Record<string, unknown>>;
539+
try {
540+
rows = JSON.parse(raw) as Array<Record<string, unknown>>;
541+
if (!Array.isArray(rows)) return [];
542+
} catch {
543+
return [];
544+
}
545+
546+
return rows.map((r) => {
547+
const directory = String(r.directory || '');
548+
const modelJson = String(r.model || '');
549+
const provider = parseOpenCodeProvider(modelJson);
550+
const modelId = parseOpenCodeModel(modelJson);
551+
const id = String(r.id || '');
552+
const agent = String(r.agent || '');
553+
const cost = Number(r.cost) || 0;
554+
const inputTokens = Number(r.tokens_input) || 0;
555+
const outputTokens = Number(r.tokens_output) || 0;
556+
const cacheRead = Number(r.tokens_cache_read) || 0;
557+
const cacheWrite = Number(r.tokens_cache_write) || 0;
558+
const created = Number(r.time_created);
559+
const updated = Number(r.time_updated);
560+
561+
const dirSegments = directory.split('/').filter(Boolean);
562+
const lastSeg = dirSegments[dirSegments.length - 1] || 'session';
563+
const squad = knownSquads.includes(lastSeg) ? lastSeg : 'interactive';
564+
const agentTag = agent || 'opencode';
565+
566+
return {
567+
ts: new Date(created).toISOString(),
568+
id: `opencode:${id}`,
569+
squad,
570+
agent: squad === 'interactive' ? lastSeg : agentTag,
571+
provider: provider || 'opencode',
572+
model: modelId || 'unknown',
573+
session_id: id,
574+
trigger: 'manual' as const,
575+
status: 'completed' as const,
576+
duration_ms: Math.max(0, updated - created),
577+
input_tokens: inputTokens,
578+
output_tokens: outputTokens,
579+
cache_read_tokens: cacheRead,
580+
cache_write_tokens: cacheWrite,
581+
cost_usd: cost,
582+
context_tokens: 0,
583+
source: 'opencode' as ObservabilityRecord['source'],
584+
cost_estimated: false,
585+
};
586+
});
587+
}

‎src/lib/llm-clis.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ const PROVIDER_FATAL = [
136136
/insufficient balance|please recharge|insufficient_quota|exceeded your current quota/i,
137137
/The supported API model names are/,
138138
/invalid api key|incorrect api key/i,
139+
/AI_\w*Error/, // opencode (Vercel AI SDK) — AI_APICallError, AI_LoadAPIKeyError, etc. (#978)
139140
];
140141

141142
/** Returns the matched failure line for logging, or null when output looks healthy. */
@@ -292,6 +293,19 @@ export const LLM_CLIS: Record<string, CLIConfig> = {
292293
parseUsage: parseAiderUsage,
293294
},
294295

296+
opencode: {
297+
provider: 'opencode',
298+
displayName: 'OpenCode',
299+
command: 'opencode',
300+
install: 'curl -fsSL https://opencode.ai/install.sh | bash',
301+
buildArgs: (prompt, opts) => {
302+
const args = ['run', '--auto', prompt];
303+
if (opts?.model) args.push('--model', opts.model);
304+
if (opts?.cwd) args.push('--dir', opts.cwd);
305+
return args;
306+
},
307+
},
308+
295309
ollama: {
296310
provider: 'ollama',
297311
displayName: 'Ollama (Local)',

‎src/lib/observability.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export interface ObservabilityRecord {
6767
// merged in from ~/.claude/projects transcripts at render time. Absent on
6868
// rows written by this module (always a squads-cli dispatch) — callers that
6969
// merge sources tag ledger rows 'ledger' explicitly.
70-
source?: 'ledger' | 'claude-code';
70+
source?: 'ledger' | 'claude-code' | 'opencode';
7171
// True when cost_usd is a notional list-price estimate derived from raw
7272
// token counts (no billing signal), not what execution-log.ts recorded.
7373
cost_estimated?: boolean;

‎src/lib/sessions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ const AI_TOOL_PATTERNS: { pattern: RegExp; name: string }[] = [
6969
{ pattern: /^copilot$/i, name: 'copilot' },
7070
{ pattern: /^cody$/i, name: 'cody' },
7171
{ pattern: /^continue$/i, name: 'continue' },
72+
{ pattern: /^opencode$/, name: 'opencode' },
7273
];
7374

7475
// Session is stale after 5 minutes without heartbeat

‎src/lib/setup-checks.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,14 @@ export const PROVIDERS: Record<string, ProviderInfo> = {
8080
requiresSubscription: false,
8181
requiresApiKey: true,
8282
},
83+
opencode: {
84+
id: 'opencode',
85+
name: 'OpenCode',
86+
cliCheck: 'opencode',
87+
installCmd: 'curl -fsSL https://opencode.ai/install.sh | bash',
88+
requiresSubscription: false,
89+
requiresApiKey: true,
90+
},
8391
none: {
8492
id: 'none',
8593
name: 'Planning Only (no agent execution)',

‎test/llm-usage.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,31 @@ describe('glm lane (#926 — z.ai Anthropic-compatible endpoint via claude CLI)'
110110
});
111111
});
112112

113+
describe('opencode lane (#978 — headless `opencode run`, aider-tier file executor)', () => {
114+
it('is registered in LLM_CLIS with the right identity', () => {
115+
expect(LLM_CLIS.opencode.provider).toBe('opencode');
116+
expect(LLM_CLIS.opencode.displayName).toBe('OpenCode');
117+
expect(LLM_CLIS.opencode.command).toBe('opencode');
118+
});
119+
120+
it('builds a headless run with --auto and the prompt', () => {
121+
const args = LLM_CLIS.opencode.buildArgs('do the thing');
122+
expect(args).toEqual(['run', '--auto', 'do the thing']);
123+
});
124+
125+
it('appends --model and --dir only when provided', () => {
126+
const args = LLM_CLIS.opencode.buildArgs('hi', { model: 'claude-sonnet-4-5', cwd: '/repo' });
127+
expect(args).toEqual(['run', '--auto', 'hi', '--model', 'claude-sonnet-4-5', '--dir', '/repo']);
128+
});
129+
130+
// Scope guard (#978): opencode is a plain one-shot file-editing executor,
131+
// same tier as aider — not a conversational tool-use harness like claude/glm.
132+
it('stays a plain one-shot executor: no streamJson, no parseUsage', () => {
133+
expect(LLM_CLIS.opencode.streamJson).toBeUndefined();
134+
expect(LLM_CLIS.opencode.parseUsage).toBeUndefined();
135+
});
136+
});
137+
113138
describe('detectProviderFatalError (#936 — exit-0 API failures must fail loud)', () => {
114139
it('catches the real failure classes seen in production', async () => {
115140
const { detectProviderFatalError } = await import('../src/lib/llm-clis.js');
@@ -118,6 +143,8 @@ describe('detectProviderFatalError (#936 — exit-0 API failures must fail loud)
118143
expect(detectProviderFatalError('[1113][Insufficient balance or no resource package. Please recharge.]')).toBeTruthy();
119144
expect(detectProviderFatalError('You exceeded your current quota, please check your plan')).toBeTruthy();
120145
expect(detectProviderFatalError('Error: invalid api key provided')).toBeTruthy();
146+
expect(detectProviderFatalError('AI_APICallError: Incorrect API key provided')).toBeTruthy();
147+
expect(detectProviderFatalError('AI_APICallError: No auth credentials found')).toBeTruthy();
121148
});
122149
it('stays quiet on healthy output', async () => {
123150
const { detectProviderFatalError } = await import('../src/lib/llm-clis.js');

0 commit comments

Comments
 (0)