291 lines
19 KiB
Markdown
291 lines
19 KiB
Markdown
# AGENTS.md
|
|
|
|
Instructions for LLM coding agents working in this repository.
|
|
|
|
## Project overview
|
|
|
|
`opencode-commandcode-provider` is a native AI SDK provider that connects opencode 2 to the
|
|
CommandCode `/alpha/generate` API. It implements `LanguageModelV3` from `@ai-sdk/provider@3.0.8`
|
|
and is loaded by opencode 2 from `dist/index.js` through its `aisdk:` bridge (config
|
|
`package: "aisdk:file://…/dist/index.js"`): opencode imports the file, picks the first `create*`
|
|
export, calls it with `{ name: providerID, ...settings, headers, body, fetch }`, and then calls
|
|
`sdk.languageModel(id)`. The same `@ai-sdk/provider` version ships inside opencode 2, so the V3
|
|
implementation is shared verbatim.
|
|
|
|
- Language/tooling: TypeScript, ESM, `tsc`.
|
|
- Runtime target: opencode 2's `aisdk:` provider bridge, `@ai-sdk/provider@3.0.8` (V3 specification).
|
|
- No runtime dependencies. `@ai-sdk/provider`, `@opencode/plugin`, `solid-js`, `@opencode/theme`,
|
|
and `@opentui/*` are type-only dev dependencies; opencode resolves the plugin's imports from its
|
|
own runtime at load, and the built output has no imports of its own.
|
|
|
|
## Commands
|
|
|
|
Run from the repository root.
|
|
|
|
```powershell
|
|
npm install # dev deps: typescript, @types/node, @ai-sdk/provider, @opencode/plugin, solid-js, @opencode/theme, @opentui/*
|
|
npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plugin)
|
|
npm run build # tsc -> dist/ (provider only; the TUI plugin is loaded from source)
|
|
npm run smoke # live request against CommandCode (needs a key)
|
|
npm run quota # live 5-hour/weekly/monthly quota (needs a key)
|
|
npm run sync-models # regenerate providers.commandcode-go.models (models + reasoning-effort variants)
|
|
```
|
|
|
|
There is no unit-test suite. `scripts/smoke.mjs` is the end-to-end check. `scripts/sync-models.mjs`
|
|
is the interactive model picker (needs `dist/` first; needs a TTY; writes the global opencode config).
|
|
|
|
After any change under `src/` or `plugin/`, run `npm run typecheck`, then `npm run build`, then
|
|
`npm run smoke`. A change is not done until it typechecks and the smoke test passes.
|
|
|
|
## Layout
|
|
|
|
```
|
|
src/index.ts Public exports: createCommandCode (named) and default.
|
|
src/model.ts CommandCodeLanguageModel: HTTP, retries, doStream/doGenerate, event->part mapping.
|
|
src/transform.ts LanguageModelV3CallOptions -> /alpha/generate envelope (returns a JSON string).
|
|
src/events.ts Async iterator over the NDJSON/SSE response body.
|
|
src/usage.ts finish event -> LanguageModelV3Usage; finish-reason unification.
|
|
src/redact.ts Credential scrubbing for error surfaces.
|
|
src/log.ts Opt-in tracing (toggle file) to a log file.
|
|
src/toggles.ts Shared toggle file (~/.config/opencode/commandcode-toggles.json).
|
|
src/quota.ts Live 5-hour/weekly/monthly quota from the CommandCode alpha billing API.
|
|
src/constants.ts Defaults, paths, headers, static config block.
|
|
plugin/tui.tsx opencode 2 TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar.
|
|
tsconfig.tui.json Typechecks plugin/tui.tsx (+ quota/toggles/log/redact/constants) with
|
|
jsxImportSource @opentui/solid (no build step for the plugin).
|
|
scripts/smoke.mjs Live end-to-end check.
|
|
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
|
|
scripts/sync-models.mjs Catalog -> providers.commandcode-go.models generator (vision + effort probing).
|
|
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
|
```
|
|
|
|
## Architecture / data flow
|
|
|
|
```
|
|
opencode 2 (aisdk: bridge)
|
|
└─ createCommandCode({name, ...settings}).languageModel(id).doStream(options)
|
|
├─ transform(options, id) ──► JSON envelope
|
|
├─ fetch POST {baseURL}/alpha/generate (retry 429/5xx)
|
|
├─ iterateEvents(response.body) (NDJSON lines)
|
|
└─ map each event ──► LanguageModelV3StreamPart*
|
|
... always ending with a `finish` part
|
|
```
|
|
|
|
`doGenerate` calls `doStream` and drains the resulting stream into a
|
|
`LanguageModelV3GenerateResult`.
|
|
|
|
## Conventions
|
|
|
|
- ESM only. Imports of local files **must** end in `.js` (NodeNext resolution), e.g.
|
|
`import { transform } from "./transform.js";`. The TUI plugin imports shared modules as
|
|
`../src/*.js` — opencode's Bun transform resolves those to the TS sources.
|
|
- `strict` TypeScript is on, including `noUncheckedIndexedAccess` and `verbatimModuleSyntax`.
|
|
Type-only imports must use `import type`.
|
|
- Do **not** add comments unless they explain a non-obvious decision. Existing comments document
|
|
upstream quirks and are intentional; match that spirit, not volume.
|
|
- Keep the `transform.ts` envelope stable. If you change it, document the upstream behavior that
|
|
motivated the change.
|
|
- Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named
|
|
and the default export; the `aisdk:` bridge picks the first export whose name starts with
|
|
`create`, so nothing else in `dist/index.js` may export such a name.
|
|
- The package must stay runtime-dependency-free. Do not add a runtime `import` of a package that
|
|
would need `node_modules` at load time; opencode imports `dist/index.js` and `plugin/tui.tsx`
|
|
directly and resolves their third-party imports itself.
|
|
|
|
## Invariants and gotchas
|
|
|
|
These are load-bearing. Breaking one causes silent failures in opencode.
|
|
|
|
1. **Exactly one `create*` export reachable from the entrypoint.** opencode 2's
|
|
`opencode.provider.dynamic` plugin loads an `aisdk:` package, chooses the first export whose
|
|
name starts with `create`, and calls it as `fn({ name: providerID, ...settings, headers, body,
|
|
fetch })`. The result must expose `languageModel(id)`. A bare `file://` package instead needs a
|
|
native `model(modelID, settings)` export — never switch to that shape here.
|
|
2. **`params.stream` is always `true`.** Sending `stream: false` makes upstream answer
|
|
"Proxy use detected. This endpoint only serves CLI." Non-streaming clients are served by
|
|
buffering the V3 stream in `doGenerate`.
|
|
3. **`tool-call` stream parts carry `input` as a stringified JSON string**, not an object
|
|
(`LanguageModelV3ToolCall.input: string`). Serialize with `JSON.stringify`. Passing an object
|
|
breaks opencode's tool execution with errors like `K.input.trim is not a function`.
|
|
4. **Always emit a terminal `finish` part.** If upstream ends without a `finish` event, synthesize
|
|
one from the accumulated state. A missing finish surfaces as a truncated-response error.
|
|
5. **Drop unpaired tool ids.** Any `tool-call` without a matching `tool-result` (or vice versa) must
|
|
be omitted from the envelope; upstream rejects the whole request otherwise.
|
|
6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and
|
|
`outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`.
|
|
`inputTokens.total` is input-only; `totalTokens` is input+output. opencode 2 folds these into
|
|
its `TokenUsage` (`input` non-cached + `cache.read`/`cache.write`, `reasoning` inside output)
|
|
and sums per-step deltas into `SessionInfo.tokens`.
|
|
7. **`supportedUrls` is `{}` and stays empty.** CommandCode URLs are not fetched by the SDK.
|
|
8. **Redact before surfacing errors.** Any upstream error text passed to the client must go through
|
|
`redact()`.
|
|
9. **Replay assistant reasoning as a `{type:"reasoning"}` content part.** DeepSeek thinking mode
|
|
rejects any request carrying `tools` whose prior assistant turns omit their reasoning. In
|
|
`transform.ts`, forward each assistant `reasoning` part as `{type:"reasoning", text, signature?}`;
|
|
do not drop it and do not fabricate empty reasoning.
|
|
10. **Upstream cost never appears on `finish`.** Per-request USD arrives on `finish-step`
|
|
(`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata`
|
|
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
|
|
only. Capture both into `providerMetadata` keyed by the resolved provider id
|
|
(`options.name`; `commandcode-go` — opencode 2 passes `canonical ?? providerID` as `name`,
|
|
and a config provider has no canonical unless one is configured) on the terminal V3 `finish`
|
|
part (and `doGenerate` result), and stash into `usage.raw`. A reported `0` is meaningful; only
|
|
`undefined` means absent. opencode 2 records provider-reported session costs
|
|
(`session.usage.updated` → `SessionInfo.cost`), and the sidebar shows a `spent` line from
|
|
`data.session.cost(sessionID)`; `/cc-usage` remains the CommandCode dollar source.
|
|
11. **`aisdk:file://` specs bypass install.** opencode 2 imports the file directly (its
|
|
`loadSDKFactory` special-cases `file://`), so the repo must be rebuilt for opencode to see
|
|
source changes. The `aisdk:` prefix is required — a bare `file://` provider package must
|
|
export the native `model(modelID, settings)`, which this package deliberately does not.
|
|
The background service keeps the previously imported module alive, so after rebuilding run
|
|
`opencode service restart` (or verify with `opencode run --standalone`) or the old code
|
|
serves every request.
|
|
12. **`/models` is config-driven, not provider-driven.** opencode 2 builds the model list from
|
|
`providers.commandcode-go.models` in `opencode.json` and never asks a custom `aisdk:` provider
|
|
to discover models. Refresh the map with `npm run sync-models`; do not expect a discovery hook
|
|
in `src/` to populate it. Model entries use the opencode 2 shape: `name`, `limit`,
|
|
`capabilities.{tools,input,output}`, `variants` as an array of `{ id, settings }`. The pre-2
|
|
model fields (`reasoning`, `attachment`, `modalities`) are accepted but ignored with a warning.
|
|
13. **The TUI plugin is an opencode 2 TUI-only plugin directory.** `plugin/tui.tsx` is loaded from
|
|
**source** (not `dist/`) by registering the **directory** in the terminal client config
|
|
`~/.config/opencode/cli.json`: `{ "plugins": ["file:///abs/path/plugin"] }` (a plain absolute
|
|
path also works). The directory uses opencode 2's file-name convention and intentionally has
|
|
no `package.json`: `tui.tsx` at its root is the TUI part and there is no server part. Do not
|
|
register the **repo root** — its `package.json` has `name` + `exports`, so opencode would load
|
|
`.` (`dist/index.js`, the provider) as a server plugin. TUI-only packages belong in `cli.json`,
|
|
not in `opencode.json` `plugins`. opencode compiles the `.tsx` with its Bun/Solid transform
|
|
(`@opentui/solid` runtime support) and maps `solid-js` and `@opencode/plugin/tui` to its
|
|
internal modules. Verified on opencode 2.2.5: the module default-exports
|
|
`Plugin.define({ id, setup(context) })` from `@opencode/plugin/tui`; `setup` registers
|
|
everything and returns a cleanup function (there is no `lifecycle.onDispose`). Commands
|
|
register via `context.keymap.layer(() => ({ mode: "global", commands: [...] }))` with
|
|
`{ id, title, description, group, palette: true, slash: { name }, run }`. The sidebar panel
|
|
registers via `context.ui.slot({ append: "sidebar.content", render })`; the slot render
|
|
receives `{ sessionID }` reactively and relies on `context.theme` (tokens:
|
|
`theme.text.base`, `theme.text.muted`, `theme.text.feedback.{error,warning,success}.base`).
|
|
Solid reactivity gotcha: **read signals and store getters inside the returned JSX/memos, never
|
|
hoist a `.value` read into a plain `const` above the `return`** — a hoisted read subscribes
|
|
once under a non-tracking owner and the panel freezes after first paint. Session token
|
|
accounting: `context.data.session.get(sessionID).tokens` is the server-summed per-step deltas
|
|
(`input` non-cached, `output` includes `reasoning`; total prompt = input+cache.read+cache.write)
|
|
and `context.data.session.family(sessionID)` lists descendant sub-agent sessions — sum each
|
|
member's `get(id).tokens` (bounded), never the parent's list. `context.data.session.cost(id)`
|
|
is the recorded session cost.
|
|
14. **Slash commands and `Ctrl+P` share one registry.** A V2 keymap command with both
|
|
`palette: true` and `slash: { name }` appears in both menus; there is no slash-only entry.
|
|
Do not add `bind` to these commands — they are meant to be invoked, not keybound.
|
|
15. **Toggles are resolved per request, never at load.** `zdr` and `debug` are read in
|
|
`model.ts`/`log.ts` on every call from the toggle file, so `/cc-*` changes take effect
|
|
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` >
|
|
`x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts.
|
|
16. **Quota is live from the alpha billing API.** `src/quota.ts` reads
|
|
`/alpha/whoami`, `/alpha/billing/credits`, `/alpha/billing/subscriptions`, and
|
|
`/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `resetAt` has shipped
|
|
as both seconds and epoch ms — normalize
|
|
(>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any
|
|
plan; never hardcode a plan→cap table. The TUI resolves the key from
|
|
`context.data.location.provider.list()` (the `commandcode-go` entry's `settings.apiKey`, then
|
|
its `headers.Authorization`), then the global `opencode.json` (`providers.<id>.settings`, then
|
|
the pre-2 `provider.<id>.options`), then `COMMANDCODE_API_KEY`, expanding `{env:VAR}` itself,
|
|
and must never log the key — quota errors go through `redact()`. The provider collection is
|
|
not synced by the host: call `context.data.location.provider.sync(location)` once before
|
|
reading it, or the list is empty.
|
|
17. **Retryable upstream failures can arrive inside an HTTP 200 stream.** CommandCode's gateway
|
|
answers `200` and then emits an SSE `error` event carrying `statusCode`/`isRetryable` (e.g.
|
|
`{"type":"server_error","message":"Invalid error response format: Gateway request failed",
|
|
"statusCode":520,"isRetryable":true}`). `fetchWithRetry` buffers only the `start`/`start-step`
|
|
preamble and, if the first real event is such a retryable error and attempts remain, cancels the
|
|
body and retries with backoff. Once any content event is seen the error is surfaced, not
|
|
retried (retrying mid-stream would duplicate output). Non-retryable in-stream errors (400s)
|
|
surface immediately. Keep the preamble set in sync if upstream adds new pre-content events.
|
|
18. **The provider id is `commandcode-go` (`PROVIDER_ID` in `constants.ts`) and must never be
|
|
`commandcode`.** opencode 2 still ships a models.dev catalog entry for `commandcode`
|
|
(OpenAI-compatible, `api: https://api.commandcode.ai/provider/v1`). For a config-defined
|
|
provider whose id matches a catalog id, opencode sets each model's endpoint from the catalog
|
|
entry, so a `commandcode`-id provider posts to `/provider/v1/alpha/generate` and gets
|
|
`404 not a registered API route`. `commandcode-go` is absent from the catalog (unlike
|
|
`commandcode` and `opencode-go`), so it is safe. The official catalog provider is neutralized
|
|
with `"disabled_providers": ["commandcode"]` (opencode 2 normalizes it into deny policies);
|
|
the filter applies to the final merged provider map, so it would also kill a config provider
|
|
sharing the id — never re-register under `commandcode`. `PROVIDER_ID` lives in
|
|
`src/constants.ts`; scripts import it from `dist/constants.js`; `providerOptions` is read
|
|
only under `commandcode-go`.
|
|
19. **Reasoning effort: settings beat the provider default; request options beat both.** opencode 2
|
|
merges `providers.<id>.settings` ← `models.<id>.settings` ← the selected variant's `settings`
|
|
and passes the result into the `createCommandCode` factory call (the `aisdk:` bridge spreads
|
|
the merged settings into the factory options and caches one SDK instance per merged settings
|
|
key). `transform.ts` reads both `reasoningEffort` and `reasoning_effort`
|
|
(`resolveReasoningEffort`) from the factory options and forwards `params.reasoning_effort`
|
|
**unvalidated** — an effort the upstream model does not support fails the whole request, which
|
|
is intentional and also the signal `sync-models` probes with. Request-level
|
|
`providerOptions.commandcode-go.reasoningEffort` (opencode keys request options by the
|
|
provider id for custom `aisdk:` packages) still overrides the settings chain. The resolved
|
|
value is logged as `effort=` in the debug trace.
|
|
20. **Variants are config-only.** opencode 2's variant switcher lists what
|
|
`providers.commandcode-go.models.<id>.variants` contains; custom `aisdk:` providers are only
|
|
ever asked for `languageModel(id)`, so there is no provider-side variant registration hook.
|
|
V2 spells variants as an array: `[{ "id": "high", "settings": { "reasoningEffort": "high" } }]`,
|
|
selected as `commandcode-go/<model>#high`. `scripts/sync-models.mjs` probes
|
|
`low/medium/high/xhigh/max` per model (tier accepted = tiny request completes) and writes the
|
|
verified tiers, never overwriting user-defined variants; unreachable models get a static
|
|
fallback set, reachable-but-effort-less models get none.
|
|
21. **Never emit a second `tool-input-start` for one id.** CommandCode streams a tool call as
|
|
`tool-input-start` → deltas → `tool-input-end`, then a complete `tool-call` with the same id.
|
|
opencode 2's session runner dies with `Duplicate tool input start: <id>` when a V3 stream
|
|
opens the same tool id twice (opencode 1.x tolerated the duplicate, which is why
|
|
`streamParts` tracks `startedTools`). A bare `tool-call` without a preamble still gets a
|
|
synthetic `tool-input-start`.
|
|
|
|
## Change workflow
|
|
|
|
1. Identify the upstream behavior and the `src/` (or `plugin/`) module that implements it.
|
|
2. Make the smallest change in the matching file.
|
|
3. `npm run typecheck` — fix all errors.
|
|
4. `npm run build`.
|
|
5. `npm run smoke` — verify text and, when relevant, tool calls.
|
|
6. If the change affects the opencode integration, verify with `opencode run` (see below).
|
|
7. Update `README.md` if options, features, or behavior changed. Keep `AGENTS.md` invariants
|
|
current if you discover a new one.
|
|
|
|
Do not edit `dist/` by hand; it is generated.
|
|
|
|
## Verification
|
|
|
|
Automated:
|
|
|
|
```powershell
|
|
npm run typecheck; npm run build; npm run smoke
|
|
```
|
|
|
|
Quota changes additionally need a live check (needs a key):
|
|
|
|
```powershell
|
|
npm run quota
|
|
```
|
|
|
|
Inside opencode 2 (restart it first if config changed):
|
|
|
|
```powershell
|
|
opencode models commandcode-go
|
|
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp
|
|
opencode run "Use the glob tool to list *.mjs in this directory and report the filenames." -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp
|
|
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp#high
|
|
```
|
|
|
|
The third command confirms the full tool-call round trip (tool-call emitted, executed, result
|
|
replayed). Run it after touching `transform.ts` or the tool-call mapping in `model.ts`. The last
|
|
one confirms variant settings reach the factory. For the TUI plugin, launch the opencode TUI and
|
|
check the sidebar panel plus `/cc-status` and `/cc-usage`.
|
|
|
|
## Do / Don't
|
|
|
|
- **Do** keep the wire envelope stable; document intentional changes.
|
|
- **Do** run typecheck, build, and smoke after every source change.
|
|
- **Do** prefer `{env:COMMANDCODE_API_KEY}` in docs and examples.
|
|
- **Don't** commit real API keys, `dist/`, `node_modules/`, `dump/`, or logs (all gitignored).
|
|
- **Don't** add runtime dependencies or make `dist` require `node_modules`.
|
|
- **Don't** force `stream:false`, send object `tool-call.input`, or omit the `finish` part.
|
|
- **Don't** register the repo root as a plugin, add a `package.json` to `plugin/`, or load the
|
|
TUI plugin from `opencode.json` `plugins`.
|
|
- **Don't** commit unless the user explicitly asks.
|