Compare commits
3 Commits
a8a337e7b3
...
6e42970004
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e42970004 | |||
| 319c6ac872 | |||
| 9fd1804b12 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -2,3 +2,4 @@ node_modules
|
|||||||
dist
|
dist
|
||||||
*.log
|
*.log
|
||||||
dump/
|
dump/
|
||||||
|
.opencode2/
|
||||||
|
|||||||
221
AGENTS.md
221
AGENTS.md
@ -4,33 +4,38 @@ Instructions for LLM coding agents working in this repository.
|
|||||||
|
|
||||||
## Project overview
|
## Project overview
|
||||||
|
|
||||||
`opencode-commandcode-provider` is a native AI SDK provider that connects opencode to the
|
`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`
|
CommandCode `/alpha/generate` API. It implements `LanguageModelV3` from `@ai-sdk/provider@3.0.8`
|
||||||
and is loaded by opencode from `dist/index.js` via a `file://` npm spec.
|
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`.
|
- Language/tooling: TypeScript, ESM, `tsc`.
|
||||||
- Runtime target: opencode's provider loader, `@ai-sdk/provider@3.0.8` (V3 specification).
|
- Runtime target: opencode 2's `aisdk:` provider bridge, `@ai-sdk/provider@3.0.8` (V3 specification).
|
||||||
- No runtime dependencies. `@ai-sdk/provider` is imported with `import type` only; the built
|
- No runtime dependencies. `@ai-sdk/provider`, `@opencode/plugin`, `solid-js`, `@opencode/theme`,
|
||||||
output has no imports of its own.
|
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
|
## Commands
|
||||||
|
|
||||||
Run from the repository root.
|
Run from the repository root.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
npm install # dev deps: typescript, @types/node, @ai-sdk/provider
|
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 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 build # tsc -> dist/ (provider only; the TUI plugin is loaded from source)
|
||||||
npm run smoke # live request against CommandCode (needs a key)
|
npm run smoke # live request against CommandCode (needs a key)
|
||||||
npm run quota # live 5-hour/weekly/monthly quota (needs a key)
|
npm run quota # live 5-hour/weekly/monthly quota (needs a key)
|
||||||
npm run sync-models # regenerate provider.commandcode-go.models from the live catalog
|
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`
|
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).
|
is the interactive model picker (needs `dist/` first; needs a TTY; writes the global opencode config).
|
||||||
|
|
||||||
After any change under `src/`, run `npm run typecheck`, then `npm run build`, then `npm run smoke`.
|
After any change under `src/` or `plugin/`, run `npm run typecheck`, then `npm run build`, then
|
||||||
A change is not done until it typechecks and the smoke test passes.
|
`npm run smoke`. A change is not done until it typechecks and the smoke test passes.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
@ -44,21 +49,21 @@ src/redact.ts Credential scrubbing for error surfaces.
|
|||||||
src/log.ts Opt-in tracing (toggle file) to a log file.
|
src/log.ts Opt-in tracing (toggle file) to a log file.
|
||||||
src/toggles.ts Shared toggle file (~/.config/opencode/commandcode-toggles.json).
|
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/quota.ts Live 5-hour/weekly/monthly quota from the CommandCode alpha billing API.
|
||||||
src/tui.tsx opencode TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar.
|
|
||||||
src/tui-shims.d.ts Ambient types for the opencode-provided solid-js/@opentui/solid runtime.
|
|
||||||
tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles/log) against the shim (no dependencies).
|
|
||||||
src/constants.ts Defaults, paths, headers, static config block.
|
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/smoke.mjs Live end-to-end check.
|
||||||
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
|
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
|
||||||
scripts/sync-models.mjs Catalog -> provider.commandcode-go.models generator (with vision probing).
|
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.
|
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture / data flow
|
## Architecture / data flow
|
||||||
|
|
||||||
```
|
```
|
||||||
opencode
|
opencode 2 (aisdk: bridge)
|
||||||
└─ provider.languageModel(id).doStream(options)
|
└─ createCommandCode({name, ...settings}).languageModel(id).doStream(options)
|
||||||
├─ transform(options, id) ──► JSON envelope
|
├─ transform(options, id) ──► JSON envelope
|
||||||
├─ fetch POST {baseURL}/alpha/generate (retry 429/5xx)
|
├─ fetch POST {baseURL}/alpha/generate (retry 429/5xx)
|
||||||
├─ iterateEvents(response.body) (NDJSON lines)
|
├─ iterateEvents(response.body) (NDJSON lines)
|
||||||
@ -72,7 +77,8 @@ opencode
|
|||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
- ESM only. Imports of local files **must** end in `.js` (NodeNext resolution), e.g.
|
- ESM only. Imports of local files **must** end in `.js` (NodeNext resolution), e.g.
|
||||||
`import { transform } from "./transform.js";`.
|
`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`.
|
- `strict` TypeScript is on, including `noUncheckedIndexedAccess` and `verbatimModuleSyntax`.
|
||||||
Type-only imports must use `import type`.
|
Type-only imports must use `import type`.
|
||||||
- Do **not** add comments unless they explain a non-obvious decision. Existing comments document
|
- Do **not** add comments unless they explain a non-obvious decision. Existing comments document
|
||||||
@ -80,17 +86,21 @@ opencode
|
|||||||
- Keep the `transform.ts` envelope stable. If you change it, document the upstream behavior that
|
- Keep the `transform.ts` envelope stable. If you change it, document the upstream behavior that
|
||||||
motivated the change.
|
motivated the change.
|
||||||
- Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named
|
- Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named
|
||||||
and the default export.
|
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
|
- 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` directly.
|
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
|
## Invariants and gotchas
|
||||||
|
|
||||||
These are load-bearing. Breaking one causes silent failures in opencode.
|
These are load-bearing. Breaking one causes silent failures in opencode.
|
||||||
|
|
||||||
1. **Exactly one `create*` export reachable from the entrypoint.** opencode loads a custom npm
|
1. **Exactly one `create*` export reachable from the entrypoint.** opencode 2's
|
||||||
provider by importing it, choosing the first export whose name starts with `create`, and calling
|
`opencode.provider.dynamic` plugin loads an `aisdk:` package, chooses the first export whose
|
||||||
it as `fn({ name: providerID, ...options })`. The result must expose `languageModel(id)`.
|
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
|
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
|
"Proxy use detected. This endpoint only serves CLI." Non-streaming clients are served by
|
||||||
buffering the V3 stream in `doGenerate`.
|
buffering the V3 stream in `doGenerate`.
|
||||||
@ -103,7 +113,9 @@ These are load-bearing. Breaking one causes silent failures in opencode.
|
|||||||
be omitted from the envelope; upstream rejects the whole request otherwise.
|
be omitted from the envelope; upstream rejects the whole request otherwise.
|
||||||
6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and
|
6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and
|
||||||
`outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`.
|
`outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`.
|
||||||
`inputTokens.total` is input-only; `totalTokens` is input+output.
|
`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.
|
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
|
8. **Redact before surfacing errors.** Any upstream error text passed to the client must go through
|
||||||
`redact()`.
|
`redact()`.
|
||||||
@ -115,56 +127,53 @@ These are load-bearing. Breaking one causes silent failures in opencode.
|
|||||||
(`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata`
|
(`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata`
|
||||||
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
|
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
|
||||||
only. Capture both into `providerMetadata` keyed by the resolved provider id
|
only. Capture both into `providerMetadata` keyed by the resolved provider id
|
||||||
(`options.name`; `commandcode-go` under opencode and as the factory default) on the
|
(`options.name`; `commandcode-go` — opencode 2 passes `canonical ?? providerID` as `name`,
|
||||||
terminal V3 `finish` part (and `doGenerate` result), and stash into `usage.raw`. A reported
|
and a config provider has no canonical unless one is configured) on the terminal V3 `finish`
|
||||||
`0` is meaningful; only `undefined` means absent. The built-in sidebar still shows `$0.00`
|
part (and `doGenerate` result), and stash into `usage.raw`. A reported `0` is meaningful; only
|
||||||
until the fork consumes this field (anomalyco/opencode#43818); `/cc-usage` is the accurate
|
`undefined` means absent. opencode 2 records provider-reported session costs
|
||||||
dollar source meanwhile.
|
(`session.usage.updated` → `SessionInfo.cost`), and the sidebar shows a `spent` line from
|
||||||
11. **`file://` npm specs bypass install.** opencode imports `dist/index.js` directly, so the repo
|
`data.session.cost(sessionID)`; `/cc-usage` remains the CommandCode dollar source.
|
||||||
must be rebuilt for opencode to see source changes.
|
11. **`aisdk:file://` specs bypass install.** opencode 2 imports the file directly (its
|
||||||
12. **`/models` is config-driven, not provider-driven.** opencode builds the model list from
|
`loadSDKFactory` special-cases `file://`), so the repo must be rebuilt for opencode to see
|
||||||
`provider.commandcode-go.models` in `opencode.json` and never asks a custom `file://` provider to
|
source changes. The `aisdk:` prefix is required — a bare `file://` provider package must
|
||||||
discover models (only internal providers can register `discoverModels`). Refresh the map with
|
export the native `model(modelID, settings)`, which this package deliberately does not.
|
||||||
`npm run sync-models`; do not expect a discovery hook in `src/` to populate it.
|
The background service keeps the previously imported module alive, so after rebuilding run
|
||||||
13. **The TUI plugin lives outside the provider entrypoint.** `src/tui.tsx` is loaded from
|
`opencode service restart` (or verify with `opencode run --standalone`) or the old code
|
||||||
**source** (not `dist/`) via a `tui.json` `plugin` entry that must be a **direct `file://` URL
|
serves every request.
|
||||||
to `src/tui.tsx`** (global `~/.config/opencode/tui.json` or project `.opencode/tui.json`),
|
12. **`/models` is config-driven, not provider-driven.** opencode 2 builds the model list from
|
||||||
wired by hand: `opencode plugin <path>` cannot install a bare `.tsx` (it needs a `package.json`
|
`providers.commandcode-go.models` in `opencode.json` and never asks a custom `aisdk:` provider
|
||||||
manifest next to the target), and the spec must never point at the **repo root** — a directory
|
to discover models. Refresh the map with `npm run sync-models`; do not expect a discovery hook
|
||||||
spec is also picked up as a server plugin via `package.json` `main` → `dist/index.js` (the
|
in `src/` to populate it. Model entries use the opencode 2 shape: `name`, `limit`,
|
||||||
provider, not a plugin). Do not re-add a `./tui` export for this; it is deliberately removed.
|
`capabilities.{tools,input,output}`, `variants` as an array of `{ id, settings }`. The pre-2
|
||||||
opencode compiles the `.tsx` at load with
|
model fields (`reasoning`, `attachment`, `modalities`) are accepted but ignored with a warning.
|
||||||
its Bun/Solid transform and maps `solid-js` / `@opentui/solid` to its internal modules, so the
|
13. **The TUI plugin is an opencode 2 TUI-only plugin directory.** `plugin/tui.tsx` is loaded from
|
||||||
package stays dependency-free — do not add a build step or real imports of those packages.
|
**source** (not `dist/`) by registering the **directory** in the terminal client config
|
||||||
`src/tui-shims.d.ts` is the only local stand-in for types; keep it in sync with what the file
|
`~/.config/opencode/cli.json`: `{ "plugins": ["file:///abs/path/plugin"] }` (a plain absolute
|
||||||
actually imports. Verified on opencode 1.18.31: the module's **default export must be
|
path also works). The directory uses opencode 2's file-name convention and intentionally has
|
||||||
`{ id, tui }`** (a bare `tui` named export is imported but never invoked), `id` is required,
|
no `package.json`: `tui.tsx` at its root is the TUI part and there is no server part. Do not
|
||||||
and `tui` is `async (api) => {}`. Commands register via
|
register the **repo root** — its `package.json` has `name` + `exports`, so opencode would load
|
||||||
`api.keymap.registerLayer({ commands })` with `{ name, run, title, desc, category,
|
`.` (`dist/index.js`, the provider) as a server plugin. TUI-only packages belong in `cli.json`,
|
||||||
namespace: "palette", slashName }`. The sidebar panel registers via
|
not in `opencode.json` `plugins`. opencode compiles the `.tsx` with its Bun/Solid transform
|
||||||
`api.slots.register({ order, slots: { sidebar_content } })`; `order: 90` keeps it above the
|
(`@opentui/solid` runtime support) and maps `solid-js` and `@opencode/plugin/tui` to its
|
||||||
built-in panels (100 context, 200 mcp, 300 lsp, 400 todo, 500 files). The slot renderer
|
internal modules. Verified on opencode 2.2.5: the module default-exports
|
||||||
returns Solid JSX and is reactive; it relies on `api.theme` and `api.lifecycle.onDispose`.
|
`Plugin.define({ id, setup(context) })` from `@opencode/plugin/tui`; `setup` registers
|
||||||
Solid reactivity gotcha: **read `createSignal` getters inside the returned JSX, never hoist
|
everything and returns a cleanup function (there is no `lifecycle.onDispose`). Commands
|
||||||
`signal()` into a `const` above the `return` in the slot component.** A hoisted read subscribes
|
register via `context.keymap.layer(() => ({ mode: "global", commands: [...] }))` with
|
||||||
once under a non-tracking owner and the panel freezes after first paint (fetch succeeds, Solid
|
`{ id, title, description, group, palette: true, slash: { name }, run }`. The sidebar panel
|
||||||
never re-renders). The slot handler itself re-runs on session change, which masks the bug —
|
registers via `context.ui.slot({ append: "sidebar.content", render })`; the slot render
|
||||||
it looks "fixed" after `/session` but stays stale on fresh launch. The built-in
|
receives `{ sessionID }` reactively and relies on `context.theme` (tokens:
|
||||||
`internal:sidebar-context` plugin reads its memos inside JSX for the same reason.
|
`theme.text.base`, `theme.text.muted`, `theme.text.feedback.{error,warning,success}.base`).
|
||||||
Session token accounting is available to the panel via the same reactive store the
|
Solid reactivity gotcha: **read signals and store getters inside the returned JSX/memos, never
|
||||||
built-in context panel uses, `api.state.session.messages(sessionID)`: each assistant
|
hoist a `.value` read into a plain `const` above the `return`** — a hoisted read subscribes
|
||||||
info's `tokens.cache.read`/`write` come from the provider's V3
|
once under a non-tracking owner and the panel freezes after first paint. Session token
|
||||||
`inputTokens.cacheRead`/`cacheWrite`, and `tokens.input` is non-cached — so total
|
accounting: `context.data.session.get(sessionID).tokens` is the server-summed per-step deltas
|
||||||
prompt tokens are `input+cache.read+cache.write` and output includes `reasoning`.
|
(`input` non-cached, `output` includes `reasoning`; total prompt = input+cache.read+cache.write)
|
||||||
Sub-agents (`task` tool) run in child sessions (`session.parent_id`) and are **not** in
|
and `context.data.session.family(sessionID)` lists descendant sub-agent sessions — sum each
|
||||||
the current session's message list, so the panel separately walks descendants with
|
member's `get(id).tokens` (bounded), never the parent's list. `context.data.session.cost(id)`
|
||||||
`api.client.session.children({ sessionID })` (the V1 plugin API exposes the SDK client as
|
is the recorded session cost.
|
||||||
`api.client`) and sums each child's tokens — preferring the v2 session store's aggregate
|
14. **Slash commands and `Ctrl+P` share one registry.** A V2 keymap command with both
|
||||||
`api.state.session.get(id).tokens`, falling back to `api.client.session.messages`. Do not
|
`palette: true` and `slash: { name }` appears in both menus; there is no slash-only entry.
|
||||||
assume the parent's tokens include children, and keep the walk bounded (depth/breadth).
|
Do not add `bind` to these commands — they are meant to be invoked, not keybound.
|
||||||
14. **Slash commands and `Ctrl+P` share one registry.** In opencode 1.x the slash menu queries
|
|
||||||
the same `namespace: "palette"` commands the palette lists (both filter out `hidden: true`).
|
|
||||||
A slash-only entry is not expressible; registering `/cc-*` also adds them to `Ctrl+P`.
|
|
||||||
15. **Toggles are resolved per request, never at load.** `zdr` and `debug` are read in
|
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
|
`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` >
|
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` >
|
||||||
@ -174,9 +183,13 @@ These are load-bearing. Breaking one causes silent failures in opencode.
|
|||||||
`/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `resetAt` has shipped
|
`/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `resetAt` has shipped
|
||||||
as both seconds and epoch ms — normalize
|
as both seconds and epoch ms — normalize
|
||||||
(>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any
|
(>= 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 `api.state` (provider
|
plan; never hardcode a plan→cap table. The TUI resolves the key from
|
||||||
entry, then `config.provider.commandcode-go.options`, then `COMMANDCODE_API_KEY`), expanding
|
`context.data.location.provider.list()` (the `commandcode-go` entry's `settings.apiKey`, then
|
||||||
`{env:VAR}` itself, and must never log the key — quota errors go through `redact()`.
|
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
|
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.
|
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",
|
`{"type":"server_error","message":"Invalid error response format: Gateway request failed",
|
||||||
@ -186,24 +199,47 @@ These are load-bearing. Breaking one causes silent failures in opencode.
|
|||||||
retried (retrying mid-stream would duplicate output). Non-retryable in-stream errors (400s)
|
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.
|
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
|
18. **The provider id is `commandcode-go` (`PROVIDER_ID` in `constants.ts`) and must never be
|
||||||
`commandcode`.** opencode 1.18+ ships a models.dev catalog entry for `commandcode`
|
`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
|
(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 `api.url` from the catalog
|
provider whose id matches a catalog id, opencode sets each model's endpoint from the catalog
|
||||||
entry and `resolveSDK` forwards it as `options.baseURL` into the factory
|
entry, so a `commandcode`-id provider posts to `/provider/v1/alpha/generate` and gets
|
||||||
(`packages/opencode/src/provider/provider.ts`, models-dev merge + `options["baseURL"] =
|
`404 not a registered API route`. `commandcode-go` is absent from the catalog (unlike
|
||||||
model.api.url`), so a `commandcode`-id provider posts to `/provider/v1/alpha/generate` and
|
|
||||||
gets `404 not a registered API route`. A non-catalog id has `api.url === ""` → no injected
|
|
||||||
baseURL → `DEFAULT_BASE_URL` applies; `commandcode-go` is absent from the catalog (unlike
|
|
||||||
`commandcode` and `opencode-go`), so it is safe. The official catalog provider is neutralized
|
`commandcode` and `opencode-go`), so it is safe. The official catalog provider is neutralized
|
||||||
with `"disabled_providers": ["commandcode"]`; `disabled_providers` filters the final merged
|
with `"disabled_providers": ["commandcode"]` (opencode 2 normalizes it into deny policies);
|
||||||
provider map, so it would also kill a config provider sharing the id — never re-register
|
the filter applies to the final merged provider map, so it would also kill a config provider
|
||||||
under `commandcode`. `PROVIDER_ID` lives in `src/constants.ts`; scripts import it from
|
sharing the id — never re-register under `commandcode`. `PROVIDER_ID` lives in
|
||||||
`dist/constants.js`; `providerOptions` is read only under `commandcode-go`.
|
`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
|
## Change workflow
|
||||||
|
|
||||||
1. Identify the upstream behavior and the `src/` module that implements it.
|
1. Identify the upstream behavior and the `src/` (or `plugin/`) module that implements it.
|
||||||
2. Make the smallest change in the matching `src/` file.
|
2. Make the smallest change in the matching file.
|
||||||
3. `npm run typecheck` — fix all errors.
|
3. `npm run typecheck` — fix all errors.
|
||||||
4. `npm run build`.
|
4. `npm run build`.
|
||||||
5. `npm run smoke` — verify text and, when relevant, tool calls.
|
5. `npm run smoke` — verify text and, when relevant, tool calls.
|
||||||
@ -227,16 +263,19 @@ Quota changes additionally need a live check (needs a key):
|
|||||||
npm run quota
|
npm run quota
|
||||||
```
|
```
|
||||||
|
|
||||||
Inside opencode (restart it first if config changed):
|
Inside opencode 2 (restart it first if config changed):
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
opencode models commandcode-go
|
opencode models commandcode-go
|
||||||
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp
|
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 "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
|
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`.
|
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 / Don't
|
||||||
|
|
||||||
@ -246,4 +285,6 @@ replayed). Run it after touching `transform.ts` or the tool-call mapping in `mod
|
|||||||
- **Don't** commit real API keys, `dist/`, `node_modules/`, `dump/`, or logs (all gitignored).
|
- **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** 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** 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.
|
- **Don't** commit unless the user explicitly asks.
|
||||||
|
|||||||
251
README.md
251
README.md
@ -1,33 +1,35 @@
|
|||||||
# opencode-commandcode-provider
|
# opencode-commandcode-provider
|
||||||
|
|
||||||
A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode](https://opencode.ai)
|
A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode 2](https://opencode.ai)
|
||||||
to the **CommandCode** `/alpha/generate` API.
|
to the **CommandCode** `/alpha/generate` API.
|
||||||
|
|
||||||
This package implements the `LanguageModelV3` interface directly, so opencode talks to
|
This package implements the `LanguageModelV3` interface directly, so opencode talks to
|
||||||
CommandCode with no local proxy in the middle.
|
CommandCode with no local proxy in the middle. opencode loads it through its `aisdk:`
|
||||||
|
bridge, which imports the package, picks up the `create*` factory, and wraps the V3 model
|
||||||
|
in its native route system.
|
||||||
|
|
||||||
```
|
```
|
||||||
opencode ──► @ai-sdk/provider (LanguageModelV3)
|
opencode 2 ──► aisdk: bridge (LanguageModelV3)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
opencode-commandcode-provider
|
opencode-commandcode-provider
|
||||||
transform → POST /alpha/generate
|
transform → POST /alpha/generate
|
||||||
NDJSON events → V3 stream parts
|
NDJSON events → V3 stream parts
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
api.commandcode.ai
|
api.commandcode.ai
|
||||||
```
|
```
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- **Node.js >= 18** (uses global `fetch`, `ReadableStream`, `TextDecoder`, `structuredClone`).
|
- **Node.js >= 18** (uses global `fetch`, `ReadableStream`, `TextDecoder`, `structuredClone`).
|
||||||
- **opencode >= 1.17** that ships `@ai-sdk/provider@3.0.8` (verified against opencode 1.18.35).
|
- **opencode 2** (verified against 2.2.5, which still ships `@ai-sdk/provider@3.0.8`).
|
||||||
- A CommandCode account and API key with access to the `/alpha/generate` endpoint.
|
- A CommandCode account and API key with access to the `/alpha/generate` endpoint.
|
||||||
|
|
||||||
## Install and wire into opencode
|
## Install and wire into opencode
|
||||||
|
|
||||||
The provider is consumed directly from its build output via a `file://` spec. This bypasses
|
The provider is consumed directly from its build output via an `aisdk:file://` spec. This
|
||||||
npm install and is the intended development workflow.
|
bypasses npm install and is the intended development workflow.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# 1. build the provider
|
# 1. build the provider
|
||||||
@ -40,19 +42,18 @@ npm run build
|
|||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"disabled_providers": ["commandcode"],
|
"disabled_providers": ["commandcode"],
|
||||||
"provider": {
|
"providers": {
|
||||||
"commandcode-go": {
|
"commandcode-go": {
|
||||||
"name": "Command Code",
|
"name": "Command Code",
|
||||||
"npm": "file:///C:/dev/opencode-commandcode-provider/dist/index.js",
|
"package": "aisdk:file:///C:/dev/opencode-commandcode-provider/dist/index.js",
|
||||||
"options": {
|
"settings": {
|
||||||
"apiKey": "{env:COMMANDCODE_API_KEY}"
|
"apiKey": "{env:COMMANDCODE_API_KEY}"
|
||||||
},
|
},
|
||||||
"models": {
|
"models": {
|
||||||
"deepseek/deepseek-v4.1-flash": {
|
"deepseek/deepseek-v4.1-flash": {
|
||||||
"name": "DeepSeek V4.1 Flash",
|
"name": "DeepSeek V4.1 Flash",
|
||||||
"limit": { "context": 1048576, "output": 256000 },
|
"limit": { "context": 1048576, "output": 256000 },
|
||||||
"attachment": true,
|
"capabilities": { "tools": true, "input": ["text", "image"], "output": ["text"] }
|
||||||
"modalities": { "input": ["text", "image"], "output": ["text"] }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -60,13 +61,17 @@ npm run build
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> The `aisdk:` prefix is required. A bare `file://` package is loaded as an opencode 2
|
||||||
|
> *native* provider and must export `model(modelID, settings)`; this package exports the AI
|
||||||
|
> SDK `create*` factory instead, which only the `aisdk:` bridge understands.
|
||||||
|
|
||||||
> The provider id is **`commandcode-go`**, deliberately not `commandcode`. opencode's models.dev
|
> The provider id is **`commandcode-go`**, deliberately not `commandcode`. opencode's models.dev
|
||||||
> catalog defines an official `commandcode` provider (OpenAI-compatible,
|
> catalog defines an official `commandcode` provider (OpenAI-compatible,
|
||||||
> `api.commandcode.ai/provider/v1`); opencode merges any config-defined provider with the catalog
|
> `api.commandcode.ai/provider/v1`); opencode merges any config-defined provider with the catalog
|
||||||
> entry of the same id and forwards the catalog `api` URL as `options.baseURL`, which breaks this
|
> entry of the same id and forwards the catalog `api` URL as `baseURL`, which breaks this
|
||||||
> provider's `/alpha/generate` path with a `404 not a registered API route`. Using a non-catalog id
|
> provider's `/alpha/generate` path with a `404 not a registered API route`. Using a non-catalog id
|
||||||
> avoids the merge; list the official provider under `disabled_providers` so it stays out of the
|
> avoids the merge; list the official provider under `disabled_providers` so it stays out of the
|
||||||
> model picker.
|
> model picker (the field is still accepted and normalized into policies in opencode 2).
|
||||||
|
|
||||||
Then set the key and restart opencode:
|
Then set the key and restart opencode:
|
||||||
|
|
||||||
@ -75,17 +80,18 @@ $env:COMMANDCODE_API_KEY = "user_..."
|
|||||||
opencode models commandcode-go
|
opencode models commandcode-go
|
||||||
```
|
```
|
||||||
|
|
||||||
> opencode loads configuration **once at startup**. After changing `opencode.json`, a plugin, or
|
> opencode loads configuration **once at startup**. After changing `opencode.json` or `cli.json`,
|
||||||
> a rebuilt provider, quit and relaunch opencode for the change to take effect.
|
> quit and relaunch opencode for the change to take effect. A rebuilt provider is re-imported the
|
||||||
|
> same way.
|
||||||
|
|
||||||
The `models` map is required — opencode silently drops a custom provider whose model list is
|
The `models` map is required — opencode silently drops a custom provider whose model list is
|
||||||
empty. The provider itself only needs `languageModel(id)`, which it implements for any id passed
|
empty. The provider itself only needs `languageModel(id)`, which it implements for any id passed
|
||||||
to it, but opencode builds `/models` and the TUI picker from this map and never asks a custom
|
to it, but opencode builds `/models` and the TUI picker from this map and never asks a custom
|
||||||
`file://` provider to discover models. Use the sync script below to fill it in.
|
`aisdk:file://` provider to discover models. Use the sync script below to fill it in.
|
||||||
|
|
||||||
## Listing all CommandCode models
|
## Listing all CommandCode models
|
||||||
|
|
||||||
opencode reads the model list from `provider.commandcode-go.models`; a custom provider cannot
|
opencode reads the model list from `providers.commandcode-go.models`; a custom provider cannot
|
||||||
register dynamic discovery. `scripts/sync-models.mjs` fetches the live catalog from
|
register dynamic discovery. `scripts/sync-models.mjs` fetches the live catalog from
|
||||||
`GET /provider/v1/models` and opens an interactive checkbox picker (nothing pre-checked).
|
`GET /provider/v1/models` and opens an interactive checkbox picker (nothing pre-checked).
|
||||||
Only the selected models are vision-probed and written into your global opencode config —
|
Only the selected models are vision-probed and written into your global opencode config —
|
||||||
@ -103,7 +109,7 @@ without writing. Each row shows the model id and name plus a second line with it
|
|||||||
interactive terminal.
|
interactive terminal.
|
||||||
|
|
||||||
Before anything else the script requires a CommandCode API key (from
|
Before anything else the script requires a CommandCode API key (from
|
||||||
`provider.commandcode-go.options.apiKey` or `COMMANDCODE_API_KEY`). If neither is present — including
|
`providers.commandcode-go.settings.apiKey` or `COMMANDCODE_API_KEY`). If neither is present — including
|
||||||
when `opencode.json` does not exist yet — it exits and points you at the CommandCode Console
|
when `opencode.json` does not exist yet — it exits and points you at the CommandCode Console
|
||||||
(<https://commandcode.ai/studio/provider>) to generate one. It never writes without a key.
|
(<https://commandcode.ai/studio/provider>) to generate one. It never writes without a key.
|
||||||
|
|
||||||
@ -113,29 +119,39 @@ Then restart opencode and confirm:
|
|||||||
opencode models commandcode-go
|
opencode models commandcode-go
|
||||||
```
|
```
|
||||||
|
|
||||||
Mapping and behaviour:
|
Mapping and behaviour (opencode 2 native shape):
|
||||||
|
|
||||||
- Every catalog entry gets `limit.context` from its `context_length`, `limit.output` from
|
- Every catalog entry gets `limit.context` from its `context_length`, `limit.output` from
|
||||||
`DEFAULT_MAX_TOKENS`, and **`reasoning: true`**.
|
`DEFAULT_MAX_TOKENS`, and `capabilities.tools: true`.
|
||||||
- Vision (`attachment` + `modalities.input` with `image`) is **probed** per model: a 64×64 image
|
- Vision (`capabilities.input` with `image`) is **probed** per model: a 64×64 image
|
||||||
is sent and the reply is inspected. Models that answer a color are marked vision; models that
|
is sent and the reply is inspected. Models that answer a color are marked vision; models that
|
||||||
reply `NO_IMAGE` (retried once) or reject the image are not. Probes that cannot run — plan-gated,
|
reply `NO_IMAGE` (retried once) or reject the image are not. Probes that cannot run — plan-gated,
|
||||||
temporarily unavailable — fall back to a family heuristic (`claude`, `gpt-5`, `gemini`, `grok`,
|
temporarily unavailable — fall back to a family heuristic (`claude`, `gpt-5`, `gemini`, `grok`,
|
||||||
`qwen…vl`, …). Probing is best-effort: upstream is nondeterministic and a re-run may flip a
|
`qwen…vl`, …). Probing is best-effort: upstream is nondeterministic and a re-run may flip a
|
||||||
borderline model.
|
borderline model.
|
||||||
- Generated fields (`name`, `limit`, `reasoning`, `attachment`, `modalities`) overwrite existing
|
- Reasoning effort (`variants`) is **probed** per model: a tiny request is sent for each candidate
|
||||||
values. Other fields (`variants`, `options`, `cost`, …) on selected ids are preserved.
|
tier (`low`, `medium`, `high`, `xhigh`, `max`) carrying `reasoningEffort`, and a tier counts as
|
||||||
Unselected ids are removed from the map.
|
supported when the request completes (an unsupported tier fails the request, which is the
|
||||||
|
signal). Verified tiers are written as opencode 2 variants —
|
||||||
The API key is read from `COMMANDCODE_API_KEY`, then `provider.commandcode-go.options.apiKey` in the
|
`[{ "id": "high", "settings": { "reasoningEffort": "high" } }]` — so the `#high` model suffix
|
||||||
global config (`baseURL`/`ccVersion` are read from there too).
|
and `/variants` switcher work. If every tier is rejected, a no-effort baseline probe
|
||||||
|
decides: a reachable model gets no variants at all; an unreachable or plan-gated model falls
|
||||||
|
back to a static guess (`low`/`medium`/`high`, plus `max` for `deepseek-v4`). Probing is skipped
|
||||||
|
for ids that already carry user-defined variants — those are preserved as-is.
|
||||||
|
- Generated fields (`name`, `limit`, `capabilities`) overwrite existing values. `variants` are
|
||||||
|
written only when the entry has none; other fields (`settings`, `cost`, …) on selected ids are
|
||||||
|
preserved. Unselected ids are removed from the map.
|
||||||
|
|
||||||
|
The API key is read from `COMMANDCODE_API_KEY`, then `providers.commandcode-go.settings.apiKey` in the
|
||||||
|
global config (`baseURL`/`ccVersion` are read from there too; the pre-2 `provider.<id>.options`
|
||||||
|
shape is still accepted when reading).
|
||||||
|
|
||||||
## Configuration options
|
## Configuration options
|
||||||
|
|
||||||
`provider.commandcode-go.options` is forwarded to `createCommandCode(options)`.
|
`providers.commandcode-go.settings` is forwarded to `createCommandCode(options)`. Per-model and
|
||||||
|
per-variant `settings` merge over it (provider ← model ← variant).
|
||||||
|
|
||||||
| Option | Type | Default | Description |
|
| Setting | Type | Default | Description |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `apiKey` | `string` | — | CommandCode API key. A bare token or `Bearer <token>` both work. |
|
| `apiKey` | `string` | — | CommandCode API key. A bare token or `Bearer <token>` both work. |
|
||||||
| `headers` | `Record<string,string>` | `{}` | Extra request headers, merged over the built-in ones. An `Authorization` header is accepted as an alternative auth source. |
|
| `headers` | `Record<string,string>` | `{}` | Extra request headers, merged over the built-in ones. An `Authorization` header is accepted as an alternative auth source. |
|
||||||
@ -143,16 +159,21 @@ global config (`baseURL`/`ccVersion` are read from there too).
|
|||||||
| `ccVersion` | `string` | `1.84.0` | Value of the `x-command-code-version` header. |
|
| `ccVersion` | `string` | `1.84.0` | Value of the `x-command-code-version` header. |
|
||||||
| `maxRetries` | `number` | `2` | Retry attempts for retryable failures (429/5xx/network). |
|
| `maxRetries` | `number` | `2` | Retry attempts for retryable failures (429/5xx/network). |
|
||||||
| `retryMaxDelaySeconds` | `number` | `60` | Longest wait honoured from `Retry-After`; longer values are not retried. |
|
| `retryMaxDelaySeconds` | `number` | `60` | Longest wait honoured from `Retry-After`; longer values are not retried. |
|
||||||
|
| `reasoningEffort` | `string` | — | Provider-level default reasoning effort, sent as `params.reasoning_effort` (`reasoning_effort` is an accepted alias). Model/variant settings override it — see [Reasoning effort](#reasoning-effort). |
|
||||||
| `name` | `string` | `commandcode-go` | Provider id reported to the AI SDK. opencode sets this automatically. |
|
| `name` | `string` | `commandcode-go` | Provider id reported to the AI SDK. opencode sets this automatically. |
|
||||||
|
|
||||||
**Auth precedence:** `options.apiKey` wins; otherwise the value of an `Authorization` header in
|
opencode's own provider fields (`headers`, `body`) are separate overlays in opencode 2 and reach
|
||||||
`options.headers` (with a leading `Bearer ` stripped). If neither is present, requests are sent
|
the factory merged in. Timeouts (`timeout`, `headerTimeout`, `chunkTimeout`) and `encoding` are
|
||||||
unauthenticated and CommandCode will reject them.
|
read by opencode itself and are not forwarded to the provider.
|
||||||
|
|
||||||
|
**Auth precedence:** `settings.apiKey` wins; otherwise the value of an `Authorization` header in
|
||||||
|
the provider's `headers` overlay (with a leading `Bearer ` stripped). If neither is present,
|
||||||
|
requests are sent unauthenticated and CommandCode will reject them.
|
||||||
|
|
||||||
## Environment variables
|
## Environment variables
|
||||||
|
|
||||||
All environment variables read by the provider, its scripts, and its TUI plugin. String values in
|
All environment variables read by the provider, its scripts, and its TUI plugin. String values in
|
||||||
`options` also accept `{env:NAME}`, which opencode/the TUI expand generically (not a fixed set).
|
`settings` also accept `{env:NAME}`, which opencode/the TUI expand generically (not a fixed set).
|
||||||
|
|
||||||
CommandCode-specific:
|
CommandCode-specific:
|
||||||
|
|
||||||
@ -191,7 +212,7 @@ does not require restarting opencode.
|
|||||||
Precedence, highest first:
|
Precedence, highest first:
|
||||||
|
|
||||||
1. `providerOptions.commandcode-go.zdr` (`true`/`false`), e.g. a model variant or agent option.
|
1. `providerOptions.commandcode-go.zdr` (`true`/`false`), e.g. a model variant or agent option.
|
||||||
2. An explicit `x-cmd-zdr` header in `opencode.json` `options.headers` or the call's `headers`.
|
2. An explicit `x-cmd-zdr` header in the provider's `headers` overlay or the call's `headers`.
|
||||||
3. The toggle file (`zdr` key — see [Runtime toggles](#runtime-toggles)).
|
3. The toggle file (`zdr` key — see [Runtime toggles](#runtime-toggles)).
|
||||||
|
|
||||||
With tracing enabled, the trace logs a `zdr on|off` line per request so the toggle state is
|
With tracing enabled, the trace logs a `zdr on|off` line per request so the toggle state is
|
||||||
@ -204,50 +225,42 @@ reads on every request, so both settings change without restarting opencode. `/c
|
|||||||
the current state. The file is `~/.config/opencode/commandcode-toggles.json` (overridable with
|
the current state. The file is `~/.config/opencode/commandcode-toggles.json` (overridable with
|
||||||
`COMMANDCODE_TOGGLES_FILE` — see [Environment variables](#environment-variables)).
|
`COMMANDCODE_TOGGLES_FILE` — see [Environment variables](#environment-variables)).
|
||||||
|
|
||||||
These commands come from a small TUI plugin shipped in this package (`src/tui.tsx`). It is loaded
|
These commands come from a small TUI plugin shipped in this package (`plugin/tui.tsx`). It is an
|
||||||
from **source** — opencode compiles the TSX and provides the Solid runtime itself — so there is no
|
opencode 2 TUI-only plugin (`Plugin.define` from `@opencode/plugin/tui`), loaded from **source** —
|
||||||
build step and no runtime dependency for it. Register it once by adding the plugin file's absolute
|
opencode compiles the TSX and provides the Solid runtime itself — so there is no build step and no
|
||||||
`file://` URL to the `plugin` list in `tui.json` (global `~/.config/opencode/tui.json`, or
|
runtime dependency for it. Register it once by adding the plugin directory to the `plugins` list
|
||||||
project-local `.opencode/tui.json`):
|
in the terminal client config, `~/.config/opencode/cli.json`:
|
||||||
|
|
||||||
```jsonc
|
```jsonc
|
||||||
// tui.json
|
// ~/.config/opencode/cli.json
|
||||||
{
|
{
|
||||||
"plugin": ["file:///C:/dev/opencode-commandcode-provider/src/tui.tsx"]
|
"plugins": ["file:///C:/dev/opencode-commandcode-provider/plugin"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Use an absolute path with forward slashes (`file:///C:/...` on Windows, `file:///home/...` on
|
Use an absolute path with forward slashes (`file:///C:/...` on Windows, `file:///home/...` on
|
||||||
Linux/macOS). Two rules for the entry:
|
Linux/macOS); a plain absolute path works too. The directory uses opencode 2's file-name
|
||||||
|
convention (no `package.json` inside): `plugin/tui.tsx` is the TUI part, and there is no server
|
||||||
- It must point at **`src/tui.tsx` itself**. `opencode plugin <module>` cannot install this form:
|
part. A TUI-only package belongs in `cli.json`, not in `opencode.json` `plugins`.
|
||||||
the CLI requires a `package.json` manifest next to the target, so a bare `.tsx` must be wired in
|
|
||||||
by hand as above.
|
|
||||||
- Never point `plugin` at the **repo root**. A directory spec makes opencode also treat the package
|
|
||||||
as a server plugin (via `package.json` `main` → `dist/index.js`), which is the AI SDK provider,
|
|
||||||
not a plugin — it loads as dead weight into every session.
|
|
||||||
|
|
||||||
Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also
|
Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also
|
||||||
renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, combined main + sub-agent
|
renders a **CommandCode panel in the session sidebar** (`sidebar.content` slot): `zdr` / `debug`,
|
||||||
token totals (`in` / `out` / cache `hit`), plus live quota, above the built-in panels) that updates
|
combined main + sub-agent token totals (`in` / `out` / cache `hit`, plus `$` spent when the
|
||||||
live as you toggle. `in` and `out` show the combined main-agent and descendant total with the
|
session reports cost), and live quota. The slash commands and the `Ctrl+P` palette share one
|
||||||
sub-agent-only contribution in parentheses (omitted when there are no sub-agents); `hit` is the
|
registry, so these entries appear in both. If you run opencode against a remote server, register
|
||||||
cache-read percentage weighted across both. Note that in opencode 1.x the slash menu and the
|
the plugin in the terminal's own `cli.json`; the provider-side toggle file must live on the
|
||||||
`Ctrl+P` palette read the same command registry, so these entries appear in both. If you run opencode
|
server host — use the env vars or `providerOptions` there.
|
||||||
against a remote server, the TUI-side file is not visible to the provider on the server host — use
|
|
||||||
the env vars or `providerOptions` there.
|
|
||||||
|
|
||||||
Sub-agent tokens are included in the same totals: `task`-tool subagents run in child sessions
|
Sub-agent tokens are included in the same totals: `task`-tool subagents run in child sessions, so
|
||||||
(`session.parent_id`), so their usage is not in the current session's message list. The panel walks
|
their usage is not in the current session's store. The panel reads opencode's reactive family
|
||||||
descendants with the SDK's `session.children` endpoint (bounded depth/breadth), reads each child's
|
index (`data.session.family`) and sums each descendant session's aggregate tokens (bounded to 50
|
||||||
aggregate tokens from the session store or falls back to summing its assistant messages, and adds
|
sessions), adding them to the combined `in` / `out` / `hit`. The parenthetical delta in `in` and
|
||||||
them to the combined `in` / `out` / `hit`. The parenthetical delta in `in` and `out` is sub-agent
|
`out` is sub-agent usage alone; it is omitted when no descendant sessions were found.
|
||||||
usage alone; it is omitted when no descendant sessions were found.
|
|
||||||
|
|
||||||
## Quota tracking
|
## Quota tracking
|
||||||
|
|
||||||
`/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the
|
`/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the
|
||||||
account behind `provider.commandcode-go.options.apiKey`. The numbers come live from the same alpha
|
account behind `providers.commandcode-go.settings.apiKey`. The numbers come live from the same alpha
|
||||||
billing endpoints the `cmd` CLI `/usage` command uses:
|
billing endpoints the `cmd` CLI `/usage` command uses:
|
||||||
|
|
||||||
| Endpoint | Used for |
|
| Endpoint | Used for |
|
||||||
@ -263,14 +276,13 @@ plan (including org and pay-as-you-go) without a maintained price table. Free an
|
|||||||
accounts can return no `windowLimits`; those rows stay hidden and the missing section is reported
|
accounts can return no `windowLimits`; those rows stay hidden and the missing section is reported
|
||||||
instead of being shown as zero.
|
instead of being shown as zero.
|
||||||
|
|
||||||
The sidebar refreshes after each completed turn (`session.idle`, plus `session.status`,
|
The sidebar refreshes after each completed turn (`session.usage.updated`, `session.execution.succeeded`,
|
||||||
`session.updated`, and `message.updated` as fallbacks since `session.idle` is a server-plugin
|
`session.execution.failed`, `session.idle` and `session.status` — all debounced) and when the
|
||||||
event that may never reach the TUI bus — all debounced) and when the active session changes,
|
active session changes, but never more than once every 2 minutes; every 5 minutes as a fallback
|
||||||
but never more than once every 2 minutes; every 5 minutes as a fallback
|
|
||||||
(`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see
|
(`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see
|
||||||
[Environment variables](#environment-variables)) and the
|
[Environment variables](#environment-variables)) and the
|
||||||
countdown ticks every 30 seconds. The token totals (including the sub-agent delta) are refreshed on
|
countdown ticks every 30 seconds. Token totals and the `spent` line read opencode's reactive
|
||||||
the same triggers (they are independent of quota rate-limiting). Key resolution and fetch failures
|
session store, so they update live without polling. Key resolution and fetch failures
|
||||||
are redacted and shown inline; the panel never stays on `loading…` and never blocks the provider.
|
are redacted and shown inline; the panel never stays on `loading…` and never blocks the provider.
|
||||||
Extra trace lines (`tui-quota`) are appended to the debug log only when debug tracing is on.
|
Extra trace lines (`tui-quota`) are appended to the debug log only when debug tracing is on.
|
||||||
|
|
||||||
@ -298,14 +310,14 @@ The API key is never logged; quota errors pass through `redact()` like every oth
|
|||||||
| Tool results | Yes — paired results are replayed; unpaired ids are dropped |
|
| Tool results | Yes — paired results are replayed; unpaired ids are dropped |
|
||||||
| Multiple images (vision) | Yes — `data:` URIs, raw base64, `Uint8Array`, and remote URLs |
|
| Multiple images (vision) | Yes — `data:` URIs, raw base64, `Uint8Array`, and remote URLs |
|
||||||
| Token usage | Yes — input/output totals, cache read, reasoning tokens |
|
| Token usage | Yes — input/output totals, cache read, reasoning tokens |
|
||||||
| Provider-reported cost | Yes — per-request USD from `finish-step`/`provider-metadata` is forwarded as `providerMetadata.commandcode-go.cost` (plus `marketCost`); also stashed in `usage.raw`. The built-in sidebar still shows `$0.00` until opencode itself consumes this field (upstream `anomalyco/opencode#43818`); `/cc-usage` remains the accurate dollar source |
|
| Provider-reported cost | Yes — per-request USD from `finish-step`/`provider-metadata` is forwarded as `providerMetadata.commandcode-go.cost` (plus `marketCost`); also stashed in `usage.raw`. opencode 2 records provider-reported session costs, and the sidebar shows the recorded session `spent` line when it is non-zero |
|
||||||
| Finish reasons | Yes — unified (`stop`, `length`, `tool-calls`, `content-filter`, `error`, `other`) plus raw |
|
| Finish reasons | Yes — unified (`stop`, `length`, `tool-calls`, `content-filter`, `error`, `other`) plus raw |
|
||||||
| Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties |
|
| Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties |
|
||||||
| `reasoning_effort` | Yes — via `providerOptions.commandcode-go` |
|
| `reasoning_effort` | Yes — provider default via `settings.reasoningEffort`; per request via variant settings or `providerOptions.commandcode-go.reasoningEffort`; switchable per message through `#variant` / `/variants` (variants generated by `sync-models`) |
|
||||||
| Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) |
|
| Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) |
|
||||||
| Credential redaction | Yes — error bodies are scrubbed before surfacing |
|
| Credential redaction | Yes — error bodies are scrubbed before surfacing |
|
||||||
| Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart |
|
| Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart |
|
||||||
| Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug`, combined main + sub-agent token totals (`in`/`out` with a sub-agent-only delta, plus cache `hit`), and live quota |
|
| Sidebar status panel | Yes — a `sidebar.content` panel shows `zdr`/`debug`, combined main + sub-agent token totals (`in`/`out` with a sub-agent-only delta, plus cache `hit` and `$` spent), and live quota |
|
||||||
| Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` |
|
| Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` |
|
||||||
|
|
||||||
### `tool_choice` handling
|
### `tool_choice` handling
|
||||||
@ -320,19 +332,56 @@ values accordingly:
|
|||||||
|
|
||||||
### Reasoning effort
|
### Reasoning effort
|
||||||
|
|
||||||
Set the per-request reasoning effort through provider options:
|
The effort reaches CommandCode as `params.reasoning_effort`. Config layers, most specific wins:
|
||||||
|
|
||||||
|
| Layer | opencode.json location | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Selected variant | `providers.<id>.models.<model>.variants[]` entry | Switched per message via `#variant` refs, `/variants`, or `opencode run --model commandcode-go/<model>#high` — no restart needed |
|
||||||
|
| Model default | `providers.<id>.models.<model>.settings.reasoningEffort` | Every request for that model |
|
||||||
|
| Provider default | `providers.<id>.settings.reasoningEffort` | Fallback when nothing more specific is set |
|
||||||
|
|
||||||
```jsonc
|
```jsonc
|
||||||
// opencode model options / variant
|
// opencode.json
|
||||||
"options": { "providerOptions": { "commandcode-go": { "reasoningEffort": "high" } } }
|
{
|
||||||
|
"providers": {
|
||||||
|
"commandcode-go": {
|
||||||
|
"settings": { "reasoningEffort": "medium" },
|
||||||
|
"models": {
|
||||||
|
"deepseek/deepseek-v4.1-flash": {
|
||||||
|
"settings": { "reasoningEffort": "low" },
|
||||||
|
"variants": [
|
||||||
|
{ "id": "low", "settings": { "reasoningEffort": "low" } },
|
||||||
|
{ "id": "high", "settings": { "reasoningEffort": "high" } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Both `reasoning_effort` and `reasoningEffort` keys are recognised and forwarded as
|
Notes:
|
||||||
`params.reasoning_effort`.
|
|
||||||
|
- `reasoning_effort` is accepted as a key alias at every layer (request options and the
|
||||||
|
provider default).
|
||||||
|
- Variant `settings` (and model/provider `settings`) are merged into the options the `aisdk:`
|
||||||
|
bridge passes to `createCommandCode`; the selected variant wins because opencode instantiates
|
||||||
|
the SDK per merged settings.
|
||||||
|
- Request-level `providerOptions.commandcode-go.reasoningEffort` still overrides everything —
|
||||||
|
opencode keys request options by the provider id for custom `aisdk:` packages.
|
||||||
|
- Values are forwarded **unvalidated**: an effort the upstream model does not support fails the
|
||||||
|
request. Run `npm run sync-models` to probe which tiers each model actually accepts and write
|
||||||
|
the verified ones as variants.
|
||||||
|
- Variants must exist in config for `/variants` to appear — opencode ships no built-in variants
|
||||||
|
for custom `aisdk:` providers, and a custom provider cannot register variants itself
|
||||||
|
(see [Listing all CommandCode models](#listing-all-commandcode-models)).
|
||||||
|
- Config edits need a restart; selecting a different variant does not (it is resolved per
|
||||||
|
message). With `/cc-debug` enabled, each request logs an `effort=<value|default>` line.
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
|
|
||||||
```
|
```
|
||||||
|
dist/index.js Built entrypoint opencode imports (create* factory, LanguageModelV3).
|
||||||
src/index.ts Public exports: createCommandCode + default.
|
src/index.ts Public exports: createCommandCode + default.
|
||||||
src/model.ts CommandCodeLanguageModel (LanguageModelV3): HTTP, retries, stream/generate.
|
src/model.ts CommandCodeLanguageModel (LanguageModelV3): HTTP, retries, stream/generate.
|
||||||
src/transform.ts LanguageModelV3CallOptions -> /alpha/generate envelope (JSON string).
|
src/transform.ts LanguageModelV3CallOptions -> /alpha/generate envelope (JSON string).
|
||||||
@ -342,17 +391,18 @@ src/redact.ts Credential scrubbing for error surfaces.
|
|||||||
src/log.ts Opt-in tracing (toggle file) to a log file.
|
src/log.ts Opt-in tracing (toggle file) to a log file.
|
||||||
src/toggles.ts Shared toggle file read by the provider and written by the TUI plugin.
|
src/toggles.ts Shared toggle file read by the provider and written by the TUI plugin.
|
||||||
src/quota.ts Live 5-hour/weekly/monthly quota from the alpha billing endpoints.
|
src/quota.ts Live 5-hour/weekly/monthly quota from the alpha billing endpoints.
|
||||||
src/tui.tsx opencode TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar panel.
|
|
||||||
src/constants.ts Defaults, header names, static config block.
|
src/constants.ts Defaults, header names, static config block.
|
||||||
|
plugin/tui.tsx opencode 2 TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar panel.
|
||||||
scripts/smoke.mjs Live end-to-end check against api.commandcode.ai.
|
scripts/smoke.mjs Live end-to-end check against api.commandcode.ai.
|
||||||
scripts/quota.mjs Print the live quota headlessly.
|
scripts/quota.mjs Print the live quota headlessly.
|
||||||
scripts/sync-models.mjs Pick models interactively and write provider.commandcode-go.models.
|
scripts/sync-models.mjs Pick models interactively and write providers.commandcode-go.models.
|
||||||
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
||||||
```
|
```
|
||||||
|
|
||||||
### Request lifecycle
|
### Request lifecycle
|
||||||
|
|
||||||
1. opencode calls `provider.languageModel(id)`, then `model.doStream(options)`.
|
1. opencode's `aisdk:` bridge imports `dist/index.js`, calls `createCommandCode({ name, ...settings })`,
|
||||||
|
then `sdk.languageModel(id)` and `model.doStream(options)`.
|
||||||
2. `transform()` converts the AI SDK prompt into the CommandCode envelope:
|
2. `transform()` converts the AI SDK prompt into the CommandCode envelope:
|
||||||
- `system` text is joined into `params.system`.
|
- `system` text is joined into `params.system`.
|
||||||
- user/assistant/tool messages become `params.messages` content parts.
|
- user/assistant/tool messages become `params.messages` content parts.
|
||||||
@ -371,16 +421,20 @@ scripts/opencode-config.mjs Shared opencode config/key lookup for the dev script
|
|||||||
## Development
|
## Development
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
npm install # installs typescript, @types/node, @ai-sdk/provider
|
npm install # installs typescript, @types/node, @ai-sdk/provider, @opencode/plugin, solid-js
|
||||||
npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plugin)
|
npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plugin)
|
||||||
npm run build # tsc -> dist/ (provider only; the TUI plugin loads from source)
|
npm run build # tsc -> dist/ (provider only; the TUI plugin loads from source)
|
||||||
npm run smoke # live request against CommandCode
|
npm run smoke # live request against CommandCode
|
||||||
npm run quota # live 5-hour/weekly/monthly quota
|
npm run quota # live 5-hour/weekly/monthly quota
|
||||||
npm run sync-models # regenerate provider.commandcode-go.models from the catalog
|
npm run sync-models # regenerate providers.commandcode-go.models from the catalog
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`@opencode/plugin`, `solid-js`, `@opencode/theme`, and `@opentui/*` are **type-only** dev
|
||||||
|
dependencies for `plugin/tui.tsx`; opencode resolves those imports from its own runtime when it
|
||||||
|
loads the plugin, so the built provider keeps zero runtime dependencies.
|
||||||
|
|
||||||
`scripts/smoke.mjs` reads the key from `COMMANDCODE_API_KEY`, falling back to
|
`scripts/smoke.mjs` reads the key from `COMMANDCODE_API_KEY`, falling back to
|
||||||
`provider.commandcode-go.options.apiKey` in `~/.config/opencode/opencode.json`. It exercises both
|
`providers.commandcode-go.settings.apiKey` in `~/.config/opencode/opencode.json`. It exercises both
|
||||||
`doGenerate` and `doStream` and prints content, finish reason, and usage.
|
`doGenerate` and `doStream` and prints content, finish reason, and usage.
|
||||||
|
|
||||||
To smoke-test a specific model:
|
To smoke-test a specific model:
|
||||||
@ -395,21 +449,26 @@ node scripts/smoke.mjs deepseek/deepseek-v4.1-flash
|
|||||||
opencode models commandcode-go
|
opencode models commandcode-go
|
||||||
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4.1-flash
|
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4.1-flash
|
||||||
opencode run "Use the glob tool to list *.mjs and report the filenames." -m commandcode-go/deepseek/deepseek-v4.1-flash
|
opencode run "Use the glob tool to list *.mjs and report the filenames." -m commandcode-go/deepseek/deepseek-v4.1-flash
|
||||||
|
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4.1-flash#high
|
||||||
```
|
```
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
| Symptom | Likely cause / fix |
|
| Symptom | Likely cause / fix |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `Provider not found: commandcode-go` | Provider was dropped because `models` is empty, or the `npm` path is wrong. Confirm `dist/index.js` exists (`npm run build`) and that the `file://` path is absolute. |
|
| `Provider not found: commandcode-go` | Provider was dropped because `models` is empty, or the `package` path is wrong. Confirm `dist/index.js` exists (`npm run build`) and that the `aisdk:file://` path is absolute. |
|
||||||
| Models appear but every call fails auth | `options.apiKey` missing/expired, or `{env:COMMANDCODE_API_KEY}` not set in the environment opencode was launched with. |
|
| `Provider package … does not export model(modelID, settings)` | The `aisdk:` prefix is missing from `package`. A bare `file://` spec is loaded as a native opencode 2 provider and needs a different export shape. |
|
||||||
|
| Models appear but every call fails auth | `settings.apiKey` missing/expired, or `{env:COMMANDCODE_API_KEY}` not set in the environment opencode was launched with. |
|
||||||
| `stream ended ... no finish` / truncated output | Upstream closed the connection early. The provider emits a synthetic `finish`, but the response is incomplete; retry the turn. |
|
| `stream ended ... no finish` / truncated output | Upstream closed the connection early. The provider emits a synthetic `finish`, but the response is incomplete; retry the turn. |
|
||||||
| Images are ignored by the model | The selected model is not vision-capable. Mark it with `"attachment": true` and `modalities.input: ["text","image"]` in `models`, and pick a vision model id. |
|
| Images are ignored by the model | The selected model is not vision-capable. Set `capabilities.input: ["text","image"]` in `models`, and pick a vision model id. |
|
||||||
| Upstream 400 about tool calls | A `tool-call` or `tool-result` without a matching pair slipped through. Pairing is enforced in `src/transform.ts`; report a repro if it still occurs. |
|
| Upstream 400 about tool calls | A `tool-call` or `tool-result` without a matching pair slipped through. Pairing is enforced in `src/transform.ts`; report a repro if it still occurs. |
|
||||||
| Need to see what the provider sends/receives | Flip `/cc-debug` and read the appended log file (see [Debug tracing](#debug-tracing)). |
|
| Need to see what the provider sends/receives | Flip `/cc-debug` and read the appended log file (see [Debug tracing](#debug-tracing)). |
|
||||||
| `tool_choice` seemingly ignored | Expected for `required`; upstream cannot force a call. `none` and named-tool are emulated via the tool list. |
|
| `tool_choice` seemingly ignored | Expected for `required`; upstream cannot force a call. `none` and named-tool are emulated via the tool list. |
|
||||||
| Config change had no effect | opencode reads config once at startup. Restart it. |
|
| Config change had no effect | opencode reads config once at startup. Restart it. |
|
||||||
| `/cc-*` commands and the sidebar panel are missing | TUI plugin not registered: add a direct `file://` URL to `src/tui.tsx` in `tui.json` (see [Runtime toggles](#runtime-toggles)). A repo-root or `src/tui.tsx`-less entry does not load. |
|
| `/variants` missing or only shows "Default" | The model has no `variants` in config. Run `npm run sync-models` (probes tiers live) or add `variants` manually, then restart opencode. |
|
||||||
|
| Reasoning-effort change has no effect | Check the selected variant and the config key spelling (`reasoningEffort`), then look for the `effort=` line in the debug log. Config edits need a restart; variant switches do not. An effort the upstream model rejects fails the request by design. |
|
||||||
|
| `/cc-*` commands and the sidebar panel are missing | TUI plugin not registered: add the `plugin/` directory to `plugins` in `~/.config/opencode/cli.json` (see [Runtime toggles](#runtime-toggles)). A bare `.tsx` file path or the repo root (whose `package.json` exports the provider as `.`) does not load as a TUI-only plugin. |
|
||||||
|
| Config warnings about `attachment`/`modalities`/`reasoning` fields | Those are pre-2 model fields that opencode 2 ignores. Rewrite model entries with `capabilities` (the sync script writes the native shape). |
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
|
|||||||
5264
package-lock.json
generated
5264
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -13,8 +13,7 @@
|
|||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"src/tui.tsx",
|
"plugin/tui.tsx",
|
||||||
"src/tui-shims.d.ts",
|
|
||||||
"src/toggles.ts",
|
"src/toggles.ts",
|
||||||
"src/quota.ts",
|
"src/quota.ts",
|
||||||
"src/log.ts",
|
"src/log.ts",
|
||||||
@ -30,7 +29,12 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ai-sdk/provider": "3.0.8",
|
"@ai-sdk/provider": "3.0.8",
|
||||||
|
"@opencode/plugin": "^2.2.5",
|
||||||
|
"@opencode/theme": "^2.2.5",
|
||||||
|
"@opentui/core": "^0.8.0",
|
||||||
|
"@opentui/solid": "^0.8.0",
|
||||||
"@types/node": "22.10.2",
|
"@types/node": "22.10.2",
|
||||||
|
"solid-js": "^1.9.17",
|
||||||
"typescript": "5.8.2"
|
"typescript": "5.8.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
466
plugin/tui.tsx
Normal file
466
plugin/tui.tsx
Normal file
@ -0,0 +1,466 @@
|
|||||||
|
// opencode 2 TUI plugin exposing /cc-zdr, /cc-debug, /cc-status and /cc-usage, plus a sidebar
|
||||||
|
// panel showing the current toggle state and live CommandCode quota. It flips the shared toggle
|
||||||
|
// file (see ../src/toggles.ts) that the provider reads on every request, so a change takes
|
||||||
|
// effect without restarting opencode, and reads the alpha billing endpoints (see
|
||||||
|
// ../src/quota.ts) with the provider's API key for the 5-hour, weekly and monthly meters.
|
||||||
|
//
|
||||||
|
// This is an opencode 2 plugin (`Plugin.define` from `@opencode/plugin/tui`). opencode loads
|
||||||
|
// the `tui` part from a plugin directory registered in `cli.json` (`"plugins": ["<abs>/plugin"]`),
|
||||||
|
// compiles this file with its Bun/Solid transform, and maps `solid-js`,
|
||||||
|
// `@opencode/plugin/tui` and the JSX runtime to its internal modules; that keeps this package
|
||||||
|
// free of runtime dependencies. `../src/*.js` imports resolve to the sibling TS sources.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { createEffect, createMemo, createSignal } from "solid-js";
|
||||||
|
|
||||||
|
import { Plugin } from "@opencode/plugin/tui";
|
||||||
|
|
||||||
|
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult } from "../src/quota.js";
|
||||||
|
import { PROVIDER_ID } from "../src/constants.js";
|
||||||
|
import { debugWhen } from "../src/log.js";
|
||||||
|
import { redact } from "../src/redact.js";
|
||||||
|
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "../src/toggles.js";
|
||||||
|
|
||||||
|
const CATEGORY = "CommandCode";
|
||||||
|
const DEFAULT_QUOTA_INTERVAL_MS = 300_000;
|
||||||
|
const MIN_REFRESH_INTERVAL_MS = 120_000;
|
||||||
|
// Sub-agent (child session) accounting cap. The sidebar reads the host's reactive family
|
||||||
|
// index (`data.session.family`), so the cap only bounds how much of a runaway task tree
|
||||||
|
// is summed.
|
||||||
|
const FAMILY_MAX_SESSIONS = 50;
|
||||||
|
// Server events that mark progress or the end of a turn. All event-driven refreshes are
|
||||||
|
// floored to MIN_REFRESH_INTERVAL_MS (hard skip).
|
||||||
|
const QUOTA_TRIGGER_EVENTS = [
|
||||||
|
"session.usage.updated",
|
||||||
|
"session.execution.succeeded",
|
||||||
|
"session.execution.failed",
|
||||||
|
"session.idle",
|
||||||
|
"session.status",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
type TokenUsageView = {
|
||||||
|
input?: number;
|
||||||
|
output?: number;
|
||||||
|
reasoning?: number;
|
||||||
|
cache?: { read?: number; write?: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
type TokenTotals = { input: number; output: number; read: number; seen: number };
|
||||||
|
|
||||||
|
type CacheSummary = { input: number; output: number; hit: number | undefined; read: number };
|
||||||
|
|
||||||
|
function safeEnv(name: string): string | undefined {
|
||||||
|
try {
|
||||||
|
return typeof process === "undefined" ? undefined : process.env?.[name];
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
|
||||||
|
function trace(...args: unknown[]): void {
|
||||||
|
debugWhen(debugEnabled(), "tui-quota", ...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
function state(value: boolean | undefined): string {
|
||||||
|
return value === true ? "on" : "off";
|
||||||
|
}
|
||||||
|
|
||||||
|
function summary(toggles: Toggles = readToggles()): string {
|
||||||
|
return `zdr=${state(toggles.zdr)}, debug=${state(toggles.debug)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Expands an `{env:NAME}` config reference; other templates are treated as unset. */
|
||||||
|
function resolveRef(value: unknown): string | undefined {
|
||||||
|
if (typeof value !== "string" || value.length === 0) return undefined;
|
||||||
|
const trimmed = value.trim();
|
||||||
|
const template = /^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(trimmed);
|
||||||
|
if (template) return template[1] ? safeEnv(template[1]) : undefined;
|
||||||
|
if (/^\{.*\}$/.test(trimmed)) return undefined;
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addTokens(totals: TokenTotals, tokens: TokenUsageView | undefined): void {
|
||||||
|
if (!tokens) return;
|
||||||
|
const cacheRead = tokens.cache?.read ?? 0;
|
||||||
|
totals.input += (tokens.input ?? 0) + cacheRead + (tokens.cache?.write ?? 0);
|
||||||
|
totals.output += (tokens.output ?? 0) + (tokens.reasoning ?? 0);
|
||||||
|
totals.read += cacheRead;
|
||||||
|
totals.seen++;
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
|
||||||
|
if (totals.seen === 0) return undefined;
|
||||||
|
return {
|
||||||
|
input: totals.input,
|
||||||
|
output: totals.output,
|
||||||
|
hit: totals.input > 0 ? (totals.read / totals.input) * 100 : undefined,
|
||||||
|
read: totals.read,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// The location provider collection is not synced by the host; fetch it once so the
|
||||||
|
// configured `settings.apiKey` / `headers.Authorization` / `baseURL` can be read. Falls
|
||||||
|
// back to the global opencode.json for setups where the client omits credential settings.
|
||||||
|
let providerInfo: { settings?: Record<string, unknown>; headers?: Record<string, unknown> } | undefined;
|
||||||
|
let providerInfoResolved = false;
|
||||||
|
|
||||||
|
async function ensureProviderInfo(context: Plugin.Context): Promise<void> {
|
||||||
|
if (providerInfoResolved) return;
|
||||||
|
providerInfoResolved = true;
|
||||||
|
try {
|
||||||
|
const location = context.location ?? context.data.location.default();
|
||||||
|
await context.data.location.provider.sync(location);
|
||||||
|
const provider = context.data.location.provider.list(location)?.find((entry) => entry?.id === PROVIDER_ID);
|
||||||
|
providerInfo = {
|
||||||
|
settings: provider?.settings as Record<string, unknown> | undefined,
|
||||||
|
headers: provider?.headers as Record<string, unknown> | undefined,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
trace("provider-sync-error", redact(error instanceof Error ? error.message : String(error)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function configFromFile(): Record<string, unknown> | undefined {
|
||||||
|
try {
|
||||||
|
const configHome = safeEnv("XDG_CONFIG_HOME") ?? join(homedir(), ".config");
|
||||||
|
const parsed = JSON.parse(readFileSync(join(configHome, "opencode", "opencode.json"), "utf8")) as Record<
|
||||||
|
string,
|
||||||
|
unknown
|
||||||
|
>;
|
||||||
|
const providers = parsed["providers"] as Record<string, unknown> | undefined;
|
||||||
|
const legacy = parsed["provider"] as Record<string, unknown> | undefined;
|
||||||
|
const entry = (providers?.[PROVIDER_ID] ?? legacy?.[PROVIDER_ID]) as Record<string, unknown> | undefined;
|
||||||
|
if (!entry) return undefined;
|
||||||
|
return {
|
||||||
|
...((entry["settings"] as Record<string, unknown> | undefined) ??
|
||||||
|
(entry["options"] as Record<string, unknown> | undefined)),
|
||||||
|
headers: entry["headers"] ?? (entry["options"] as Record<string, unknown> | undefined)?.["headers"],
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveApiKeySource(): { key?: string; source: string } {
|
||||||
|
const file = configFromFile();
|
||||||
|
const named: Array<[string, unknown]> = [
|
||||||
|
["provider.settings.apiKey", providerInfo?.settings?.["apiKey"]],
|
||||||
|
["provider.headers.Authorization", providerInfo?.headers?.["Authorization"] ?? providerInfo?.headers?.["authorization"]],
|
||||||
|
["config.settings.apiKey", file?.["apiKey"]],
|
||||||
|
["config.headers.Authorization", file?.["headers"] && (file["headers"] as Record<string, unknown>)["Authorization"]],
|
||||||
|
["COMMANDCODE_API_KEY", safeEnv("COMMANDCODE_API_KEY")],
|
||||||
|
];
|
||||||
|
for (const [source, candidate] of named) {
|
||||||
|
const value = resolveRef(candidate);
|
||||||
|
if (value) return { key: value.replace(/^Bearer\s+/i, ""), source };
|
||||||
|
}
|
||||||
|
return { source: "none" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBaseURL(): string | undefined {
|
||||||
|
return resolveRef(providerInfo?.settings?.["baseURL"] ?? configFromFile()?.["baseURL"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Plugin.define({
|
||||||
|
id: "commandcode-toggles",
|
||||||
|
setup(context) {
|
||||||
|
const [toggles, setToggles] = createSignal(readToggles());
|
||||||
|
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
|
||||||
|
const [now, setNow] = createSignal(Date.now());
|
||||||
|
const [updatedAt, setUpdatedAt] = createSignal(0);
|
||||||
|
|
||||||
|
let inflight = false;
|
||||||
|
let pending = false;
|
||||||
|
let lastRefreshAt = 0;
|
||||||
|
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
const refreshQuota = async (): Promise<void> => {
|
||||||
|
if (inflight) {
|
||||||
|
pending = true;
|
||||||
|
trace("coalesced", "inflight");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const since = Date.now() - lastRefreshAt;
|
||||||
|
if (lastRefreshAt > 0 && since < MIN_REFRESH_INTERVAL_MS) {
|
||||||
|
trace("rate-limited", `remainingMs=${MIN_REFRESH_INTERVAL_MS - since}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
inflight = true;
|
||||||
|
try {
|
||||||
|
await ensureProviderInfo(context);
|
||||||
|
const { key: apiKey, source } = resolveApiKeySource();
|
||||||
|
if (!apiKey) {
|
||||||
|
setQuota({ ok: false, error: { kind: "config", message: "No API key found" } });
|
||||||
|
setNow(Date.now());
|
||||||
|
trace("no-key", `source=${source}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
trace("fetch-start", `source=${source}`);
|
||||||
|
const result = await fetchQuota({ apiKey, baseURL: resolveBaseURL() });
|
||||||
|
setQuota(result);
|
||||||
|
if (result.ok) {
|
||||||
|
trace(
|
||||||
|
"fetch-ok",
|
||||||
|
`windows=${result.quota.windows.map((w) => `${w.id}:${w.used}/${w.cap}`).join(",")}`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
trace("fetch-error", `kind=${result.error.kind}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Key resolution, provider list access, and fetch can all throw; surface it
|
||||||
|
// instead of wedging the panel on `loading…`.
|
||||||
|
const message = redact(error instanceof Error ? error.message : String(error));
|
||||||
|
setQuota({ ok: false, error: { kind: "network", message } });
|
||||||
|
trace("fetch-throw", message);
|
||||||
|
} finally {
|
||||||
|
inflight = false;
|
||||||
|
lastRefreshAt = Date.now();
|
||||||
|
setNow(Date.now());
|
||||||
|
setUpdatedAt(Date.now());
|
||||||
|
if (pending) {
|
||||||
|
pending = false;
|
||||||
|
trace("flush-pending");
|
||||||
|
void refreshQuota();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const scheduleQuotaRefresh = (reason: string, delayMs = 800): void => {
|
||||||
|
trace("scheduled", `reason=${reason}`, `delayMs=${delayMs}`);
|
||||||
|
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
||||||
|
debounceTimer = setTimeout(() => {
|
||||||
|
debounceTimer = undefined;
|
||||||
|
void refreshQuota();
|
||||||
|
}, delayMs);
|
||||||
|
};
|
||||||
|
|
||||||
|
const flip = (name: ToggleName): void => {
|
||||||
|
const next = toggle(name);
|
||||||
|
setToggles(next);
|
||||||
|
context.ui.toast.show({
|
||||||
|
title: CATEGORY,
|
||||||
|
message: `${name} ${state(next[name])} (${summary(next)})`,
|
||||||
|
variant: next[name] === true ? "success" : "info",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const SidebarPanel = (props: { sessionID: string | undefined }) => {
|
||||||
|
// Session-cumulative token accounting from the reactive session store. The server
|
||||||
|
// sums per-step deltas into `SessionInfo.tokens` (`input` is non-cached, so total
|
||||||
|
// prompt tokens are input+cache.read+cache.write; output includes reasoning), which
|
||||||
|
// matches the provider's V3 usage shape. Family members (sub-agent sessions) come
|
||||||
|
// from the host's family index and are summed the same way.
|
||||||
|
const main = createMemo(() => {
|
||||||
|
const id = props.sessionID;
|
||||||
|
if (!id) return undefined;
|
||||||
|
const info = context.data.session.get(id);
|
||||||
|
if (!info) return undefined;
|
||||||
|
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
||||||
|
addTokens(totals, info.tokens as TokenUsageView | undefined);
|
||||||
|
return summarizeTotals(totals);
|
||||||
|
});
|
||||||
|
const family = createMemo(() => {
|
||||||
|
const id = props.sessionID;
|
||||||
|
if (!id) return undefined;
|
||||||
|
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
||||||
|
const members = context.data.session.family(id);
|
||||||
|
for (const member of members.slice(0, FAMILY_MAX_SESSIONS)) {
|
||||||
|
addTokens(totals, context.data.session.get(member)?.tokens as TokenUsageView | undefined);
|
||||||
|
}
|
||||||
|
return summarizeTotals(totals);
|
||||||
|
});
|
||||||
|
const spent = createMemo(() => {
|
||||||
|
const id = props.sessionID;
|
||||||
|
if (!id) return 0;
|
||||||
|
return context.data.session.cost(id);
|
||||||
|
});
|
||||||
|
const view = createMemo(() => {
|
||||||
|
const sub = family();
|
||||||
|
const input = (main()?.input ?? 0) + (sub?.input ?? 0);
|
||||||
|
const output = (main()?.output ?? 0) + (sub?.output ?? 0);
|
||||||
|
const read = (main()?.read ?? 0) + (sub?.read ?? 0);
|
||||||
|
return {
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
subInput: sub?.input ?? 0,
|
||||||
|
subOutput: sub?.output ?? 0,
|
||||||
|
hasSub: sub !== undefined,
|
||||||
|
hit: input > 0 ? (read / input) * 100 : undefined,
|
||||||
|
empty: main() === undefined && sub === undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Session changes refresh the quota meters (rate-limited inside refreshQuota).
|
||||||
|
createEffect(() => {
|
||||||
|
if (props.sessionID) scheduleQuotaRefresh("session-change");
|
||||||
|
});
|
||||||
|
|
||||||
|
const theme = context.theme;
|
||||||
|
const errorColor = theme.text.feedback.error.base;
|
||||||
|
const warningColor = theme.text.feedback.warning.base;
|
||||||
|
const successColor = theme.text.feedback.success.base;
|
||||||
|
// Reads toggles()/quota()/view()/now() inside the JSX so Solid tracks the signals.
|
||||||
|
// Hoisting them into a `const` above the return would subscribe once under a
|
||||||
|
// non-tracking owner and freeze the panel after first paint.
|
||||||
|
return (
|
||||||
|
<box flexDirection="column" gap={0}>
|
||||||
|
<text fg={theme.text.base}>
|
||||||
|
<b>CommandCode</b>
|
||||||
|
</text>
|
||||||
|
<text fg={theme.text.muted}>
|
||||||
|
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
|
||||||
|
</text>
|
||||||
|
<text fg={theme.text.muted}>
|
||||||
|
{view().empty
|
||||||
|
? "in: --"
|
||||||
|
: `in: ${view().input.toLocaleString()}${view().hasSub ? ` (+${view().subInput.toLocaleString()})` : ""}`}
|
||||||
|
</text>
|
||||||
|
<text fg={theme.text.muted}>
|
||||||
|
{view().empty
|
||||||
|
? "out: --"
|
||||||
|
: `out: ${view().output.toLocaleString()}${view().hasSub ? ` (+${view().subOutput.toLocaleString()})` : ""}`}
|
||||||
|
</text>
|
||||||
|
<text fg={theme.text.muted}>
|
||||||
|
{view().empty || view().hit === undefined ? "hit: --" : `hit: ${view().hit?.toFixed(1)}%`}
|
||||||
|
</text>
|
||||||
|
{view().empty || spent() <= 0 ? null : <text fg={theme.text.muted}>spent: ${spent().toFixed(2)}</text>}
|
||||||
|
{(quota()?.ok === true
|
||||||
|
? (quota() as Extract<QuotaResult, { ok: true }>).quota.windows
|
||||||
|
: []
|
||||||
|
).map((w) => {
|
||||||
|
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
|
||||||
|
const reset = formatReset(w.resetAtMs, now());
|
||||||
|
const amount =
|
||||||
|
w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
|
||||||
|
return (
|
||||||
|
<text
|
||||||
|
fg={
|
||||||
|
w.exceeded || percent(w.used, w.cap) >= 100
|
||||||
|
? errorColor
|
||||||
|
: percent(w.used, w.cap) >= 80
|
||||||
|
? warningColor
|
||||||
|
: successColor
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{`${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${reset ? ` · ${reset}` : ""}`}
|
||||||
|
</text>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{quota()?.ok === false ? (
|
||||||
|
<text fg={errorColor}>quota: {(quota() as Extract<QuotaResult, { ok: false }>).error.message}</text>
|
||||||
|
) : quota() === null ? (
|
||||||
|
<text fg={theme.text.muted}>quota: loading…</text>
|
||||||
|
) : null}
|
||||||
|
<text fg={theme.text.muted}>
|
||||||
|
updated @ {updatedAt() > 0 ? new Date(updatedAt()).toTimeString().slice(0, 8) : "--:--:--"}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
context.ui.slot({
|
||||||
|
append: "sidebar.content",
|
||||||
|
render: (input) => <SidebarPanel sessionID={input.sessionID} />,
|
||||||
|
});
|
||||||
|
|
||||||
|
context.keymap.layer(() => ({
|
||||||
|
mode: "global",
|
||||||
|
commands: [
|
||||||
|
{
|
||||||
|
id: "commandcode-toggles.zdr",
|
||||||
|
title: "CommandCode: toggle ZDR header",
|
||||||
|
description: "Send the x-cmd-zdr header on requests",
|
||||||
|
group: CATEGORY,
|
||||||
|
palette: true,
|
||||||
|
slash: { name: "cc-zdr" },
|
||||||
|
run: () => flip("zdr"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "commandcode-toggles.debug",
|
||||||
|
title: "CommandCode: toggle debug tracing",
|
||||||
|
description: "Write a redacted request and stream trace to a log file",
|
||||||
|
group: CATEGORY,
|
||||||
|
palette: true,
|
||||||
|
slash: { name: "cc-debug" },
|
||||||
|
run: () => flip("debug"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "commandcode-toggles.status",
|
||||||
|
title: "CommandCode: show toggle status",
|
||||||
|
description: "Show the current zdr and debug state",
|
||||||
|
group: CATEGORY,
|
||||||
|
palette: true,
|
||||||
|
slash: { name: "cc-status" },
|
||||||
|
run: () => context.ui.toast.show({ title: CATEGORY, message: summary(), variant: "info" }),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "commandcode-toggles.usage",
|
||||||
|
title: "CommandCode: show usage and quota",
|
||||||
|
description: "Show the 5-hour, weekly and monthly quota from the CommandCode API",
|
||||||
|
group: CATEGORY,
|
||||||
|
palette: true,
|
||||||
|
slash: { name: "cc-usage" },
|
||||||
|
run: async () => {
|
||||||
|
await ensureProviderInfo(context);
|
||||||
|
const { key: apiKey } = resolveApiKeySource();
|
||||||
|
if (!apiKey) {
|
||||||
|
context.ui.toast.show({
|
||||||
|
title: CATEGORY,
|
||||||
|
message: `No API key found. Set providers.${PROVIDER_ID}.settings.apiKey or COMMANDCODE_API_KEY.`,
|
||||||
|
variant: "warning",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let result: QuotaResult;
|
||||||
|
try {
|
||||||
|
result = await fetchQuota({ apiKey, baseURL: resolveBaseURL() });
|
||||||
|
} catch (error) {
|
||||||
|
const message = redact(error instanceof Error ? error.message : String(error));
|
||||||
|
setQuota({ ok: false, error: { kind: "network", message } });
|
||||||
|
trace("usage-throw", message);
|
||||||
|
context.ui.toast.show({ title: CATEGORY, message, variant: "error" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!result.ok) {
|
||||||
|
setQuota(result);
|
||||||
|
context.ui.toast.show({ title: CATEGORY, message: result.error.message, variant: "error" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setQuota(result);
|
||||||
|
setNow(Date.now());
|
||||||
|
setUpdatedAt(Date.now());
|
||||||
|
context.ui.toast.show({
|
||||||
|
title: CATEGORY,
|
||||||
|
message: formatQuota(result.quota),
|
||||||
|
variant: "info",
|
||||||
|
duration: 15000,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
|
||||||
|
void refreshQuota();
|
||||||
|
const toggleTimer = setInterval(() => setToggles(readToggles()), 1500);
|
||||||
|
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
|
||||||
|
const configIntervalMs = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
|
||||||
|
const quotaTimer = setInterval(() => {
|
||||||
|
void refreshQuota();
|
||||||
|
}, Number.isFinite(configIntervalMs) && configIntervalMs > 0 ? configIntervalMs : DEFAULT_QUOTA_INTERVAL_MS);
|
||||||
|
const unsubEvents = QUOTA_TRIGGER_EVENTS.map((type) =>
|
||||||
|
context.data.on(type, () => scheduleQuotaRefresh(type)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
for (const unsub of unsubEvents) unsub();
|
||||||
|
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
||||||
|
clearInterval(toggleTimer);
|
||||||
|
clearInterval(clockTimer);
|
||||||
|
clearInterval(quotaTimer);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
@ -16,14 +16,25 @@ export function readConfig(path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** COMMANDCODE_API_KEY, then provider options apiKey, then a configured Authorization header. */
|
/** COMMANDCODE_API_KEY, then provider settings apiKey, then a configured Authorization header.
|
||||||
|
* Reads the opencode 2 shape (`providers.<id>.settings`) and the pre-2
|
||||||
|
* `provider.<id>.options` shape for older files. `{env:...}` templates resolve through the
|
||||||
|
* environment or count as absent. */
|
||||||
export function resolveKey(config, env) {
|
export function resolveKey(config, env) {
|
||||||
const fromEnv = env.COMMANDCODE_API_KEY;
|
const fromEnv = env.COMMANDCODE_API_KEY;
|
||||||
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
|
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
|
||||||
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
|
const candidates = [
|
||||||
const fromConfig = options.apiKey;
|
config?.providers?.[PROVIDER_ID]?.settings,
|
||||||
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
|
config?.provider?.[PROVIDER_ID]?.options,
|
||||||
const auth = options.headers?.Authorization ?? options.headers?.authorization;
|
];
|
||||||
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
|
for (const options of candidates) {
|
||||||
|
if (!options || typeof options !== "object") continue;
|
||||||
|
const apiKey = options.apiKey;
|
||||||
|
if (typeof apiKey === "string" && apiKey.trim() && !/^\{.*\}$/.test(apiKey.trim())) {
|
||||||
|
return apiKey.trim();
|
||||||
|
}
|
||||||
|
const auth = options.headers?.Authorization ?? options.headers?.authorization;
|
||||||
|
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
|
||||||
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -62,12 +62,15 @@ try {
|
|||||||
const apiKey = resolveKey(config, process.env);
|
const apiKey = resolveKey(config, process.env);
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
console.error(
|
console.error(
|
||||||
`No CommandCode API key found. Set COMMANDCODE_API_KEY or provider.${PROVIDER_ID}.options.apiKey in ${opts.config}.`,
|
`No CommandCode API key found. Set COMMANDCODE_API_KEY or providers.${PROVIDER_ID}.settings.apiKey in ${opts.config}.`,
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseURL = opts.baseURL ?? config?.provider?.[PROVIDER_ID]?.options?.baseURL;
|
const baseURL =
|
||||||
|
opts.baseURL ??
|
||||||
|
config?.providers?.[PROVIDER_ID]?.settings?.baseURL ??
|
||||||
|
config?.provider?.[PROVIDER_ID]?.options?.baseURL;
|
||||||
const result = await fetchQuota({ apiKey, baseURL: typeof baseURL === "string" ? baseURL : undefined });
|
const result = await fetchQuota({ apiKey, baseURL: typeof baseURL === "string" ? baseURL : undefined });
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
console.error(result.error.message);
|
console.error(result.error.message);
|
||||||
|
|||||||
@ -1,23 +1,22 @@
|
|||||||
// Live smoke test for the CommandCode provider. Run: node scripts/smoke.mjs [modelId]
|
// Live smoke test for the CommandCode provider. Run: node scripts/smoke.mjs [modelId]
|
||||||
import { readFileSync } from "node:fs";
|
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { createCommandCode } from "../dist/index.js";
|
import { createCommandCode } from "../dist/index.js";
|
||||||
import { PROVIDER_ID } from "../dist/constants.js";
|
import { PROVIDER_ID } from "../dist/constants.js";
|
||||||
|
import { readConfig, resolveKey } from "./opencode-config.mjs";
|
||||||
|
|
||||||
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
|
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
|
||||||
let key = process.env.COMMANDCODE_API_KEY;
|
let key = process.env.COMMANDCODE_API_KEY;
|
||||||
if (!key) {
|
if (!key) {
|
||||||
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
|
||||||
try {
|
try {
|
||||||
const cfg = JSON.parse(readFileSync(configPath, "utf8"));
|
const cfg = readConfig(join(homedir(), ".config", "opencode", "opencode.json")).data;
|
||||||
key = cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
|
key = resolveKey(cfg, {});
|
||||||
} catch {
|
} catch {
|
||||||
key = undefined;
|
key = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!key) {
|
if (!key) {
|
||||||
console.error(`No API key: set COMMANDCODE_API_KEY or configure provider.${PROVIDER_ID}.options.apiKey`);
|
console.error(`No API key: set COMMANDCODE_API_KEY or configure providers.${PROVIDER_ID}.settings.apiKey`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,10 +1,12 @@
|
|||||||
// Interactive model picker for opencode `provider.commandcode-go.models`.
|
// Interactive model picker for opencode 2 `providers.commandcode-go.models`.
|
||||||
//
|
//
|
||||||
// opencode builds `/models` from the configured model map; a custom `file://` provider is only
|
// opencode builds `/models` from the configured model map; a custom `aisdk:file://` provider is
|
||||||
// ever asked for `languageModel(id)`, never queried for discovery. So the catalog has to be baked
|
// only ever asked for `languageModel(id)`, never queried for discovery. So the catalog has to be
|
||||||
// into opencode.json. This script fetches the live catalog, lets the user pick which models to
|
// baked into opencode.json. This script fetches the live catalog, lets the user pick which models
|
||||||
// enable with a builtins-only checkbox UI, probes the selection for vision support, and writes
|
// to enable with a builtins-only checkbox UI, probes the selection for vision support and for the
|
||||||
// the result into the global opencode config. Deselecting a model removes it from the config.
|
// reasoning_effort tiers upstream accepts, and writes the result into the global opencode config
|
||||||
|
// (opencode 2 native shape: `providers`, `capabilities`, `variants` arrays). Deselecting a model
|
||||||
|
// removes it from the config.
|
||||||
//
|
//
|
||||||
// Run: node scripts/sync-models.mjs (build first: npm run build)
|
// Run: node scripts/sync-models.mjs (build first: npm run build)
|
||||||
import { mkdirSync, realpathSync, writeFileSync, renameSync } from "node:fs";
|
import { mkdirSync, realpathSync, writeFileSync, renameSync } from "node:fs";
|
||||||
@ -37,6 +39,74 @@ const NO_IMAGE =
|
|||||||
// so this is only a best guess for ids that look like known vision families.
|
// so this is only a best guess for ids that look like known vision families.
|
||||||
const VISION_HEURISTIC = /claude|gpt-5|gemini|grok|qwen.*vl|vision|(?:^|[^a-z])vl(?:[^a-z]|$)|omni|multimodal/i;
|
const VISION_HEURISTIC = /claude|gpt-5|gemini|grok|qwen.*vl|vision|(?:^|[^a-z])vl(?:[^a-z]|$)|omni|multimodal/i;
|
||||||
|
|
||||||
|
// Candidate reasoning_effort tiers probed live per model. A tier counts as supported when a
|
||||||
|
// tiny request carrying it completes; upstream rejects unsupported values for the whole
|
||||||
|
// request, which is exactly the signal. A timeout is inconclusive, not a rejection — a slow
|
||||||
|
// thinking model must not lose its tier.
|
||||||
|
const EFFORT_CANDIDATES = ["low", "medium", "high", "xhigh", "max"];
|
||||||
|
|
||||||
|
// Static guess when live probing cannot classify a model (unreachable or plan-gated),
|
||||||
|
// mirroring the vision-heuristic fallback: common tiers, plus DeepSeek V4's extra "max".
|
||||||
|
function fallbackEfforts(id) {
|
||||||
|
const tiers = ["low", "medium", "high"];
|
||||||
|
if (/deepseek-v4/i.test(id)) tiers.push("max");
|
||||||
|
return tiers;
|
||||||
|
}
|
||||||
|
|
||||||
|
// User-curated variants are honored (and never overwritten) only when the entry carries at
|
||||||
|
// least one. opencode 2 spells variants as an array of `{ id, settings }`; the pre-2 object
|
||||||
|
// map is still accepted when reading older files.
|
||||||
|
function variantIds(value) {
|
||||||
|
if (Array.isArray(value)) return value.map((v) => v?.id).filter((id) => typeof id === "string");
|
||||||
|
if (value && typeof value === "object") return Object.keys(value);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasVariants(value) {
|
||||||
|
return variantIds(value).length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeEffort(provider, id, effort) {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(new Error("probe timeout")), 30000);
|
||||||
|
try {
|
||||||
|
await provider.languageModel(id).doGenerate({
|
||||||
|
prompt: [{ role: "user", content: [{ type: "text", text: "Reply with exactly: ok" }] }],
|
||||||
|
maxOutputTokens: 256,
|
||||||
|
temperature: 0,
|
||||||
|
...(effort === undefined ? {} : { providerOptions: { [PROVIDER_ID]: { reasoningEffort: effort } } }),
|
||||||
|
abortSignal: controller.signal,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
return /probe timeout|abort/i.test(message) ? undefined : false;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolves the tiers to write as variants: the probed-and-verified tiers when at least one
|
||||||
|
// request succeeded, the static fallback when probing could not classify, or none when the
|
||||||
|
// model is reachable but rejects every candidate effort (variants stay unset so /variants
|
||||||
|
// does not offer tiers that always fail).
|
||||||
|
async function probeEfforts(provider, id) {
|
||||||
|
const verified = [];
|
||||||
|
let inconclusive = false;
|
||||||
|
for (const effort of EFFORT_CANDIDATES) {
|
||||||
|
const ok = await probeEffort(provider, id, effort);
|
||||||
|
if (ok === true) verified.push(effort);
|
||||||
|
else if (ok === undefined) inconclusive = true;
|
||||||
|
}
|
||||||
|
if (verified.length > 0) return { tiers: verified, source: "probed" };
|
||||||
|
if (inconclusive) return { tiers: fallbackEfforts(id), source: "fallback" };
|
||||||
|
// Every candidate hard-rejected. A no-effort baseline separates "model rejects all
|
||||||
|
// efforts" from "model is unreachable or plan-gated" (where the fallback is the best guess).
|
||||||
|
const baseline = await probeEffort(provider, id, undefined);
|
||||||
|
if (baseline === true) return { tiers: [], source: "none" };
|
||||||
|
return { tiers: fallbackEfforts(id), source: "fallback" };
|
||||||
|
}
|
||||||
|
|
||||||
async function probeVision(provider, id) {
|
async function probeVision(provider, id) {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timer = setTimeout(() => controller.abort(new Error("probe timeout")), 30000);
|
const timer = setTimeout(() => controller.abort(new Error("probe timeout")), 30000);
|
||||||
@ -302,8 +372,8 @@ async function main() {
|
|||||||
`${where}\n` +
|
`${where}\n` +
|
||||||
`Generate an API key in the CommandCode Console: ${CONSOLE_URL}\n` +
|
`Generate an API key in the CommandCode Console: ${CONSOLE_URL}\n` +
|
||||||
(exists
|
(exists
|
||||||
? `Add it as provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`
|
? `Add it as providers.${PROVIDER_ID}.settings.apiKey, or export COMMANDCODE_API_KEY.`
|
||||||
: `Create that file with provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`) +
|
: `Create that file with providers.${PROVIDER_ID}.settings.apiKey, or export COMMANDCODE_API_KEY.`) +
|
||||||
`\nNothing was written.`,
|
`\nNothing was written.`,
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@ -314,8 +384,11 @@ async function main() {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseURL = (config?.provider?.[PROVIDER_ID]?.options?.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
// opencode 2 native provider shape; fall back to the pre-2 `provider.<id>.options` for older files.
|
||||||
const ccVersion = config?.provider?.[PROVIDER_ID]?.options?.ccVersion ?? DEFAULT_CC_VERSION;
|
const providerEntry = config?.providers?.[PROVIDER_ID] ?? config?.provider?.[PROVIDER_ID] ?? {};
|
||||||
|
const providerSettings = providerEntry.settings ?? providerEntry.options ?? {};
|
||||||
|
const baseURL = (providerSettings.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
||||||
|
const ccVersion = providerSettings.ccVersion ?? DEFAULT_CC_VERSION;
|
||||||
|
|
||||||
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
|
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
|
||||||
let catalog;
|
let catalog;
|
||||||
@ -343,7 +416,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
console.log(`Catalog: ${catalog.length} models`);
|
console.log(`Catalog: ${catalog.length} models`);
|
||||||
|
|
||||||
const existing = config?.provider?.[PROVIDER_ID]?.models ?? {};
|
const existing = config?.providers?.[PROVIDER_ID]?.models ?? config?.provider?.[PROVIDER_ID]?.models ?? {};
|
||||||
const existingIds = new Set(Object.keys(existing));
|
const existingIds = new Set(Object.keys(existing));
|
||||||
|
|
||||||
const picked = await pickModels(catalog, existingIds);
|
const picked = await pickModels(catalog, existingIds);
|
||||||
@ -357,7 +430,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const selected = picked.map((index) => catalog[index]).filter(Boolean);
|
const selected = picked.map((index) => catalog[index]).filter(Boolean);
|
||||||
console.log(`Probing vision (${selected.length} models, concurrency ${CONCURRENCY})...`);
|
console.log(`Probing vision + reasoning efforts (${selected.length} models, concurrency ${CONCURRENCY})...`);
|
||||||
const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key, baseURL, ccVersion, maxRetries: 1 });
|
const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key, baseURL, ccVersion, maxRetries: 1 });
|
||||||
const probeResults = new Array(selected.length);
|
const probeResults = new Array(selected.length);
|
||||||
let probeCursor = 0;
|
let probeCursor = 0;
|
||||||
@ -369,11 +442,26 @@ async function main() {
|
|||||||
// Some models intermittently deny seeing an image on the first try. Retry an explicit
|
// Some models intermittently deny seeing an image on the first try. Retry an explicit
|
||||||
// "no image" once so a flaky denial does not mislabel a vision model; inconclusive
|
// "no image" once so a flaky denial does not mislabel a vision model; inconclusive
|
||||||
// results skip the retry.
|
// results skip the retry.
|
||||||
let outcome = await probeVision(provider, model.id);
|
let vision = await probeVision(provider, model.id);
|
||||||
if (outcome.vision === false) outcome = await probeVision(provider, model.id);
|
if (vision.vision === false) vision = await probeVision(provider, model.id);
|
||||||
const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown";
|
const tag = vision.vision === true ? "vision" : vision.vision === false ? "no-vision" : "unknown";
|
||||||
console.log(` [${index + 1}/${selected.length}] ${model.id}: ${tag} (${outcome.reason})`);
|
console.log(` [${index + 1}/${selected.length}] ${model.id}: ${tag} (${vision.reason})`);
|
||||||
probeResults[index] = outcome;
|
// Reasoning-effort probe. Skipped when the user already curated variants for this id
|
||||||
|
// (kept as-is, nothing probed or overwritten), or when the vision probe showed the
|
||||||
|
// model is not reachable at all — the effort probes would only burn failing requests
|
||||||
|
// on the same failure, so the static fallback covers it.
|
||||||
|
const userVariants = existing[model.id]?.variants;
|
||||||
|
let efforts;
|
||||||
|
if (hasVariants(userVariants)) {
|
||||||
|
efforts = { tiers: variantIds(userVariants), source: "kept" };
|
||||||
|
} else if (vision.vision === undefined && !/^empty\b/.test(vision.reason)) {
|
||||||
|
efforts = { tiers: fallbackEfforts(model.id), source: "fallback" };
|
||||||
|
} else {
|
||||||
|
efforts = await probeEfforts(provider, model.id);
|
||||||
|
}
|
||||||
|
const effortTag = `${efforts.tiers.join(",") || "none"}${efforts.source === "probed" ? "" : ` (${efforts.source})`}`;
|
||||||
|
console.log(` [${index + 1}/${selected.length}] ${model.id}: efforts=${effortTag}`);
|
||||||
|
probeResults[index] = { vision, efforts };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
await Promise.all(probeRunners);
|
await Promise.all(probeRunners);
|
||||||
@ -381,9 +469,19 @@ async function main() {
|
|||||||
// Deselect = remove: the final map holds exactly the picked ids. Extra user fields on
|
// Deselect = remove: the final map holds exactly the picked ids. Extra user fields on
|
||||||
// picked ids are preserved; unpicked ids are dropped.
|
// picked ids are preserved; unpicked ids are dropped.
|
||||||
const merged = {};
|
const merged = {};
|
||||||
const stats = { probed: 0, vision: 0, noVision: 0, unknown: 0, heuristic: 0 };
|
const stats = {
|
||||||
|
probed: 0,
|
||||||
|
vision: 0,
|
||||||
|
noVision: 0,
|
||||||
|
unknown: 0,
|
||||||
|
heuristic: 0,
|
||||||
|
effortsProbed: 0,
|
||||||
|
effortsFallback: 0,
|
||||||
|
effortsNone: 0,
|
||||||
|
effortsKept: 0,
|
||||||
|
};
|
||||||
selected.forEach((model, index) => {
|
selected.forEach((model, index) => {
|
||||||
const outcome = probeResults[index];
|
const outcome = probeResults[index]?.vision;
|
||||||
let vision;
|
let vision;
|
||||||
if (outcome && outcome.vision !== undefined) {
|
if (outcome && outcome.vision !== undefined) {
|
||||||
vision = outcome.vision;
|
vision = outcome.vision;
|
||||||
@ -398,21 +496,36 @@ async function main() {
|
|||||||
const entry = {
|
const entry = {
|
||||||
name: typeof model.name === "string" && model.name ? model.name : model.id,
|
name: typeof model.name === "string" && model.name ? model.name : model.id,
|
||||||
limit: { context: Number(model.context_length) || 0, output: DEFAULT_MAX_TOKENS },
|
limit: { context: Number(model.context_length) || 0, output: DEFAULT_MAX_TOKENS },
|
||||||
reasoning: true,
|
capabilities: {
|
||||||
attachment: vision,
|
tools: true,
|
||||||
modalities: {
|
|
||||||
input: vision ? ["text", "image"] : ["text"],
|
input: vision ? ["text", "image"] : ["text"],
|
||||||
output: ["text"],
|
output: ["text"],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
merged[model.id] = { ...(existing[model.id] ?? {}), ...entry };
|
merged[model.id] = { ...(existing[model.id] ?? {}), ...entry };
|
||||||
|
// Variants are what opencode's /variants switcher (and `model#variant` refs) list; a custom
|
||||||
|
// provider cannot register them itself. opencode 2 spells them as an array with an `id` and
|
||||||
|
// package `settings`. Never overwrite user-curated variants.
|
||||||
|
const efforts = probeResults[index]?.efforts;
|
||||||
|
if (efforts) {
|
||||||
|
if (efforts.tiers.length > 0 && !hasVariants(merged[model.id].variants)) {
|
||||||
|
merged[model.id].variants = efforts.tiers.map((tier) => ({
|
||||||
|
id: tier,
|
||||||
|
settings: { reasoningEffort: tier },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if (efforts.source === "probed") stats.effortsProbed++;
|
||||||
|
else if (efforts.source === "fallback") stats.effortsFallback++;
|
||||||
|
else if (efforts.source === "none") stats.effortsNone++;
|
||||||
|
else stats.effortsKept++;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const removed = [...existingIds].filter((id) => !(id in merged)).length;
|
const removed = [...existingIds].filter((id) => !(id in merged)).length;
|
||||||
|
|
||||||
config.provider ??= {};
|
config.providers ??= {};
|
||||||
config.provider[PROVIDER_ID] ??= {};
|
config.providers[PROVIDER_ID] ??= {};
|
||||||
config.provider[PROVIDER_ID].models = merged;
|
config.providers[PROVIDER_ID].models = merged;
|
||||||
|
|
||||||
const indentMatch = /\n([ \t]+)\S/.exec(text);
|
const indentMatch = /\n([ \t]+)\S/.exec(text);
|
||||||
const indent = !indentMatch ? 2 : indentMatch[1].startsWith("\t") ? "\t" : indentMatch[1].length;
|
const indent = !indentMatch ? 2 : indentMatch[1].startsWith("\t") ? "\t" : indentMatch[1].length;
|
||||||
@ -435,6 +548,8 @@ async function main() {
|
|||||||
` selected=${selected.length} removed=${removed}\n` +
|
` selected=${selected.length} removed=${removed}\n` +
|
||||||
` probed=${stats.probed} vision=${stats.vision} no-vision=${stats.noVision} ` +
|
` probed=${stats.probed} vision=${stats.vision} no-vision=${stats.noVision} ` +
|
||||||
`unknown=${stats.unknown} heuristic-vision=${stats.heuristic}\n` +
|
`unknown=${stats.unknown} heuristic-vision=${stats.heuristic}\n` +
|
||||||
|
` efforts: probed=${stats.effortsProbed} fallback=${stats.effortsFallback} ` +
|
||||||
|
`none=${stats.effortsNone} kept=${stats.effortsKept}\n` +
|
||||||
`Restart opencode, then run: opencode models ${PROVIDER_ID}`,
|
`Restart opencode, then run: opencode models ${PROVIDER_ID}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
66
src/model.ts
66
src/model.ts
@ -23,7 +23,7 @@ import { iterateEvents } from "./events.js";
|
|||||||
import { debugWhen, isDebugEnabled } from "./log.js";
|
import { debugWhen, isDebugEnabled } from "./log.js";
|
||||||
import { redact } from "./redact.js";
|
import { redact } from "./redact.js";
|
||||||
import { zdrEnabled } from "./toggles.js";
|
import { zdrEnabled } from "./toggles.js";
|
||||||
import { transform } from "./transform.js";
|
import { resolveReasoningEffort, transform } from "./transform.js";
|
||||||
import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js";
|
import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js";
|
||||||
|
|
||||||
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
|
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
|
||||||
@ -43,6 +43,10 @@ export type CommandCodeOptions = {
|
|||||||
ccVersion?: string;
|
ccVersion?: string;
|
||||||
maxRetries?: number;
|
maxRetries?: number;
|
||||||
retryMaxDelaySeconds?: number;
|
retryMaxDelaySeconds?: number;
|
||||||
|
/** Provider-level default reasoning effort; per-request providerOptions (incl. a selected variant) override it. */
|
||||||
|
reasoningEffort?: string;
|
||||||
|
/** Alias for `reasoningEffort`, mirroring the request-level key spelling. */
|
||||||
|
reasoning_effort?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ResolvedOptions = {
|
type ResolvedOptions = {
|
||||||
@ -53,6 +57,7 @@ type ResolvedOptions = {
|
|||||||
ccVersion: string;
|
ccVersion: string;
|
||||||
maxRetries: number;
|
maxRetries: number;
|
||||||
retryMaxDelay: number;
|
retryMaxDelay: number;
|
||||||
|
reasoningEffort?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function headerValue(headers: Record<string, string | undefined>, key: string): string | undefined {
|
function headerValue(headers: Record<string, string | undefined>, key: string): string | undefined {
|
||||||
@ -289,8 +294,18 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
|
|
||||||
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
|
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
|
||||||
const dbg = resolveDebug(options);
|
const dbg = resolveDebug(options);
|
||||||
const body = transform(options, this.modelId);
|
const body = transform(options, this.modelId, {
|
||||||
debugWhen(dbg, "doStream", `model=${this.modelId}`, `bodyBytes=${Buffer.byteLength(body, "utf8")}`);
|
providerId: this.opts.providerId,
|
||||||
|
reasoningEffort: this.opts.reasoningEffort,
|
||||||
|
});
|
||||||
|
const effort = resolveReasoningEffort(options, this.opts.providerId, this.opts.reasoningEffort);
|
||||||
|
debugWhen(
|
||||||
|
dbg,
|
||||||
|
"doStream",
|
||||||
|
`model=${this.modelId}`,
|
||||||
|
`effort=${effort === undefined ? "default" : String(effort)}`,
|
||||||
|
`bodyBytes=${Buffer.byteLength(body, "utf8")}`,
|
||||||
|
);
|
||||||
const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg);
|
const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg);
|
||||||
if (!response.ok || !response.body) {
|
if (!response.ok || !response.body) {
|
||||||
let responseBody = "";
|
let responseBody = "";
|
||||||
@ -414,6 +429,10 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
let textOpen = false;
|
let textOpen = false;
|
||||||
let reasoningOpen = false;
|
let reasoningOpen = false;
|
||||||
let toolId: string | null = null;
|
let toolId: string | null = null;
|
||||||
|
// Upstream follows the streamed input (start → deltas → end) with a complete `tool-call`
|
||||||
|
// for the same id; opencode 2 dies on a second `tool-input-start` for one id
|
||||||
|
// ("Duplicate tool input start"), so only the first start for an id is ever emitted.
|
||||||
|
const startedTools = new Set<string>();
|
||||||
let hadToolCalls = false;
|
let hadToolCalls = false;
|
||||||
let usage: LanguageModelV3Usage | undefined;
|
let usage: LanguageModelV3Usage | undefined;
|
||||||
let finishReason: LanguageModelV3FinishReason | undefined;
|
let finishReason: LanguageModelV3FinishReason | undefined;
|
||||||
@ -463,25 +482,37 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
yield { type: "reasoning-end", id: reasoningId };
|
yield { type: "reasoning-end", id: reasoningId };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "tool-input-start":
|
case "tool-input-start": {
|
||||||
hadToolCalls = true;
|
hadToolCalls = true;
|
||||||
toolId = evt.id ?? null;
|
const id = String(evt.id ?? "");
|
||||||
yield { type: "tool-input-start", id: String(evt.id ?? ""), toolName: String(evt.toolName ?? "unknown") };
|
toolId = id || null;
|
||||||
break;
|
if (id && !startedTools.has(id)) {
|
||||||
case "tool-input-delta":
|
startedTools.add(id);
|
||||||
if (toolId) yield { type: "tool-input-delta", id: toolId, delta: evt.delta ?? "" };
|
yield { type: "tool-input-start", id, toolName: String(evt.toolName ?? "unknown") };
|
||||||
break;
|
|
||||||
case "tool-input-end":
|
|
||||||
if (toolId) {
|
|
||||||
yield { type: "tool-input-end", id: toolId };
|
|
||||||
toolId = null;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
case "tool-input-delta": {
|
||||||
|
const deltaId = typeof evt.id === "string" && evt.id ? evt.id : toolId;
|
||||||
|
if (deltaId) yield { type: "tool-input-delta", id: deltaId, delta: evt.delta ?? "" };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "tool-input-end": {
|
||||||
|
const endId: string | null = typeof evt.id === "string" && evt.id ? evt.id : toolId;
|
||||||
|
if (endId) {
|
||||||
|
yield { type: "tool-input-end", id: endId };
|
||||||
|
if (toolId === endId) toolId = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "tool-call": {
|
case "tool-call": {
|
||||||
hadToolCalls = true;
|
hadToolCalls = true;
|
||||||
const id = evt.toolCallId ?? toolId;
|
const id = typeof evt.toolCallId === "string" && evt.toolCallId ? evt.toolCallId : toolId;
|
||||||
const name = evt.toolName ?? evt.name ?? "unknown";
|
const name = String(evt.toolName ?? evt.name ?? "unknown");
|
||||||
if (!toolId && id) yield { type: "tool-input-start", id, toolName: name };
|
if (id && !startedTools.has(id)) {
|
||||||
|
startedTools.add(id);
|
||||||
|
yield { type: "tool-input-start", id, toolName: name };
|
||||||
|
}
|
||||||
if (id) {
|
if (id) {
|
||||||
const input = typeof evt.input === "string" ? evt.input : JSON.stringify(evt.input ?? {});
|
const input = typeof evt.input === "string" ? evt.input : JSON.stringify(evt.input ?? {});
|
||||||
yield { type: "tool-call", toolCallId: id, toolName: name, input };
|
yield { type: "tool-call", toolCallId: id, toolName: name, input };
|
||||||
@ -570,6 +601,7 @@ export function createCommandCode(options: CommandCodeOptions = {}): {
|
|||||||
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
|
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
|
||||||
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
|
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
|
||||||
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
|
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
|
||||||
|
reasoningEffort: options.reasoningEffort ?? options.reasoning_effort,
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
languageModel(modelId: string) {
|
languageModel(modelId: string) {
|
||||||
|
|||||||
@ -16,8 +16,27 @@ function stringify(value: unknown): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the reasoning effort for a request: per-request `providerOptions[providerId]`
|
||||||
|
* (model/agent options and the selected variant, merged by opencode) win over the
|
||||||
|
* provider-level default. Both key spellings are accepted; the value is forwarded
|
||||||
|
* unvalidated — an effort upstream does not support fails the request.
|
||||||
|
*/
|
||||||
|
export function resolveReasoningEffort(
|
||||||
|
options: LanguageModelV3CallOptions,
|
||||||
|
providerId: string = PROVIDER_ID,
|
||||||
|
fallback?: unknown,
|
||||||
|
): unknown {
|
||||||
|
const scoped = options.providerOptions?.[providerId] as Record<string, unknown> | undefined;
|
||||||
|
return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"] ?? fallback;
|
||||||
|
}
|
||||||
|
|
||||||
/** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */
|
/** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */
|
||||||
export function transform(options: LanguageModelV3CallOptions, modelId: string): string {
|
export function transform(
|
||||||
|
options: LanguageModelV3CallOptions,
|
||||||
|
modelId: string,
|
||||||
|
defaults: { providerId?: string; reasoningEffort?: unknown } = {},
|
||||||
|
): string {
|
||||||
const systemParts: string[] = [];
|
const systemParts: string[] = [];
|
||||||
const messages: Array<Record<string, unknown>> = [];
|
const messages: Array<Record<string, unknown>> = [];
|
||||||
|
|
||||||
@ -215,8 +234,7 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
|
|||||||
if (options.seed !== undefined) params["seed"] = options.seed;
|
if (options.seed !== undefined) params["seed"] = options.seed;
|
||||||
if (options.presencePenalty !== undefined) params["presence_penalty"] = options.presencePenalty;
|
if (options.presencePenalty !== undefined) params["presence_penalty"] = options.presencePenalty;
|
||||||
if (options.frequencyPenalty !== undefined) params["frequency_penalty"] = options.frequencyPenalty;
|
if (options.frequencyPenalty !== undefined) params["frequency_penalty"] = options.frequencyPenalty;
|
||||||
const scoped = options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
|
const effort = resolveReasoningEffort(options, defaults.providerId ?? PROVIDER_ID, defaults.reasoningEffort);
|
||||||
const effort = scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
|
|
||||||
if (effort !== undefined) params["reasoning_effort"] = effort;
|
if (effort !== undefined) params["reasoning_effort"] = effort;
|
||||||
|
|
||||||
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
|
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
|
||||||
|
|||||||
20
src/tui-shims.d.ts
vendored
20
src/tui-shims.d.ts
vendored
@ -1,20 +0,0 @@
|
|||||||
// Ambient shims for the symbols the TUI plugin imports from opencode's bundled runtime.
|
|
||||||
// opencode resolves `solid-js` and `@opentui/solid` to its own internal modules when it
|
|
||||||
// loads the `.tsx` plugin, so this package declares just enough surface for `tsc` without
|
|
||||||
// taking a dependency. The JSX namespace is intentionally permissive: only a handful of
|
|
||||||
// intrinsic elements are used and their props come from opencode's theme at runtime.
|
|
||||||
|
|
||||||
declare module "solid-js" {
|
|
||||||
export function createSignal<Value>(value: Value): [get: () => Value, set: (value: Value) => void];
|
|
||||||
export function createMemo<Value>(fn: () => Value): () => Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
declare namespace JSX {
|
|
||||||
type Element = unknown;
|
|
||||||
interface ElementChildrenAttribute {
|
|
||||||
children: {};
|
|
||||||
}
|
|
||||||
interface IntrinsicElements {
|
|
||||||
[name: string]: any;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
599
src/tui.tsx
599
src/tui.tsx
@ -1,599 +0,0 @@
|
|||||||
// opencode TUI plugin exposing /cc-zdr, /cc-debug, /cc-status and /cc-usage, plus a sidebar
|
|
||||||
// panel showing the current toggle state and live CommandCode quota. It flips the shared toggle
|
|
||||||
// file (see ./toggles.ts) that the provider reads on every request, so a change takes effect
|
|
||||||
// without restarting opencode, and reads the alpha billing endpoints (see ./quota.ts) with the
|
|
||||||
// provider's API key for the 5-hour, weekly and monthly meters.
|
|
||||||
//
|
|
||||||
// opencode loads this module's default export (`{ id, tui }`) from a `tui.json` plugin
|
|
||||||
// entry. It is loaded from source (not dist) so opencode's Bun/Solid transform compiles
|
|
||||||
// the JSX and maps `solid-js` / `@opentui/solid` to its internal modules; that keeps this
|
|
||||||
// package free of runtime and build dependencies. The ambient types in ./tui-shims.d.ts
|
|
||||||
// back the JSX and `createSignal` references for `tsc -p tsconfig.tui.json`.
|
|
||||||
//
|
|
||||||
// Note: in this opencode version slash commands and the Ctrl+P palette read the same
|
|
||||||
// `namespace: "palette"` command list, so these entries appear in both; `hidden: true`
|
|
||||||
// would remove them from both.
|
|
||||||
|
|
||||||
import { createMemo, createSignal } from "solid-js";
|
|
||||||
|
|
||||||
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult } from "./quota.js";
|
|
||||||
import { PROVIDER_ID } from "./constants.js";
|
|
||||||
import { debugWhen } from "./log.js";
|
|
||||||
import { redact } from "./redact.js";
|
|
||||||
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "./toggles.js";
|
|
||||||
|
|
||||||
type ToastVariant = "info" | "success" | "warning" | "error";
|
|
||||||
|
|
||||||
type TuiCommand = {
|
|
||||||
name: string;
|
|
||||||
title?: string;
|
|
||||||
desc?: string;
|
|
||||||
category?: string;
|
|
||||||
namespace?: string;
|
|
||||||
slashName?: string;
|
|
||||||
slashAliases?: string[];
|
|
||||||
suggested?: boolean;
|
|
||||||
hidden?: boolean;
|
|
||||||
enabled?: boolean | (() => boolean);
|
|
||||||
run: () => void | Promise<void>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiTheme = {
|
|
||||||
current: { text: unknown; textMuted: unknown; success: unknown; warning: unknown; error: unknown };
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiSlotHandler = (ctx: { theme: TuiTheme }, props: { session_id: string }) => unknown;
|
|
||||||
|
|
||||||
type TuiSlotPlugin = { order?: number; slots: Record<string, TuiSlotHandler> };
|
|
||||||
|
|
||||||
type TuiProvider = { id?: string; key?: string; options?: Record<string, unknown> };
|
|
||||||
|
|
||||||
type TuiProviderConfig = { options?: Record<string, unknown> };
|
|
||||||
|
|
||||||
type TuiSessionTokens = {
|
|
||||||
input?: number;
|
|
||||||
output?: number;
|
|
||||||
reasoning?: number;
|
|
||||||
cache?: { read?: number; write?: number };
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiMessageInfo = {
|
|
||||||
role?: string;
|
|
||||||
providerID?: string;
|
|
||||||
modelID?: string;
|
|
||||||
tokens?: TuiSessionTokens;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiSessionInfo = {
|
|
||||||
id: string;
|
|
||||||
parentID?: string;
|
|
||||||
tokens?: TuiSessionTokens;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiClient = {
|
|
||||||
session: {
|
|
||||||
children(input: { sessionID: string }): Promise<{ data?: ReadonlyArray<TuiSessionInfo> }>;
|
|
||||||
messages(input: { sessionID: string; limit?: number }): Promise<{ data?: ReadonlyArray<{ info?: TuiMessageInfo }> }>;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiState = {
|
|
||||||
config?: { provider?: Record<string, TuiProviderConfig | undefined> };
|
|
||||||
provider?: ReadonlyArray<TuiProvider>;
|
|
||||||
session?: {
|
|
||||||
messages(sessionID: string): ReadonlyArray<TuiMessageInfo>;
|
|
||||||
get?(sessionID: string): TuiSessionInfo | undefined;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type TuiApi = {
|
|
||||||
keymap: { registerLayer(layer: { commands?: readonly TuiCommand[] }): () => void };
|
|
||||||
ui: { toast(input: { title?: string; message: string; variant?: ToastVariant; duration?: number }): void };
|
|
||||||
slots: { register(plugin: TuiSlotPlugin): string };
|
|
||||||
event: { on(type: string, handler: (event?: { type?: string }) => void): () => void };
|
|
||||||
theme: TuiTheme;
|
|
||||||
state: TuiState;
|
|
||||||
client?: TuiClient;
|
|
||||||
lifecycle: { onDispose(fn: () => void): () => void };
|
|
||||||
};
|
|
||||||
|
|
||||||
const ID = "commandcode-toggles";
|
|
||||||
const CATEGORY = "CommandCode";
|
|
||||||
const SIDEBAR_ORDER = 90;
|
|
||||||
const DEFAULT_QUOTA_INTERVAL_MS = 300_000;
|
|
||||||
const MIN_REFRESH_INTERVAL_MS = 120_000;
|
|
||||||
// Sub-agent (child session) accounting limits: the sidebar walks descendants via the SDK's
|
|
||||||
// session.children endpoint, so cap the breadth/depth and per-session message fetch to keep it
|
|
||||||
// cheap even for runaway task trees.
|
|
||||||
const FAMILY_MAX_DEPTH = 4;
|
|
||||||
const FAMILY_MAX_SESSIONS = 50;
|
|
||||||
const FAMILY_MESSAGE_LIMIT = 100;
|
|
||||||
// Extra TUI-bus signals that mark the end of a turn. `session.idle` is a server
|
|
||||||
// plugin event and may never fire here; these keep the panel fresh regardless.
|
|
||||||
// All event-driven refreshes are floored to MIN_REFRESH_INTERVAL_MS (hard skip).
|
|
||||||
const QUOTA_TRIGGER_EVENTS = ["session.idle", "session.status", "session.updated", "message.updated"] as const;
|
|
||||||
|
|
||||||
function safeEnv(name: string): string | undefined {
|
|
||||||
try {
|
|
||||||
return typeof process === "undefined" ? undefined : process.env?.[name];
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
|
|
||||||
function trace(...args: unknown[]): void {
|
|
||||||
debugWhen(debugEnabled(), "tui-quota", ...args);
|
|
||||||
}
|
|
||||||
|
|
||||||
function state(value: boolean | undefined): string {
|
|
||||||
return value === true ? "on" : "off";
|
|
||||||
}
|
|
||||||
|
|
||||||
function summary(toggles: Toggles = readToggles()): string {
|
|
||||||
return `zdr=${state(toggles.zdr)}, debug=${state(toggles.debug)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Expands an `{env:NAME}` config reference; other templates are treated as unset. */
|
|
||||||
function resolveRef(value: unknown): string | undefined {
|
|
||||||
if (typeof value !== "string" || value.length === 0) return undefined;
|
|
||||||
const trimmed = value.trim();
|
|
||||||
const template = /^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(trimmed);
|
|
||||||
if (template) return template[1] ? safeEnv(template[1]) : undefined;
|
|
||||||
if (/^\{.*\}$/.test(trimmed)) return undefined;
|
|
||||||
return trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
function commandCodeOptions(api: TuiApi): Record<string, unknown> | undefined {
|
|
||||||
try {
|
|
||||||
return api.state?.config?.provider?.[PROVIDER_ID]?.options;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
|
|
||||||
let providers: readonly TuiProvider[] = [];
|
|
||||||
try {
|
|
||||||
const list = api.state?.provider;
|
|
||||||
if (Array.isArray(list)) providers = list as TuiProvider[];
|
|
||||||
// Tolerate a non-array provider state shape instead of throwing.
|
|
||||||
else if (list && typeof list === "object") providers = Object.values(list) as TuiProvider[];
|
|
||||||
} catch {
|
|
||||||
/* fall through */
|
|
||||||
}
|
|
||||||
const provider = providers.find((entry) => entry?.id === PROVIDER_ID);
|
|
||||||
const options = commandCodeOptions(api);
|
|
||||||
const headers = options?.["headers"] as Record<string, unknown> | undefined;
|
|
||||||
const named: Array<[string, unknown]> = [
|
|
||||||
["provider.key", provider?.key],
|
|
||||||
["provider.options.apiKey", provider?.options?.["apiKey"]],
|
|
||||||
["headers.Authorization", headers?.["Authorization"] ?? headers?.["authorization"]],
|
|
||||||
["options.apiKey", options?.["apiKey"]],
|
|
||||||
["COMMANDCODE_API_KEY", safeEnv("COMMANDCODE_API_KEY")],
|
|
||||||
];
|
|
||||||
for (const [source, candidate] of named) {
|
|
||||||
const value = resolveRef(candidate);
|
|
||||||
if (value) return { key: value.replace(/^Bearer\s+/i, ""), source };
|
|
||||||
}
|
|
||||||
return { source: "none" };
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveBaseURL(api: TuiApi): string | undefined {
|
|
||||||
return resolveRef(commandCodeOptions(api)?.["baseURL"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
type CacheSummary = { input: number; output: number; hit: number | undefined; read: number };
|
|
||||||
|
|
||||||
type TokenTotals = { input: number; output: number; read: number; seen: number };
|
|
||||||
|
|
||||||
function addMessageTokens(totals: TokenTotals, tokens: TuiSessionTokens | undefined): void {
|
|
||||||
if (!tokens) return;
|
|
||||||
const cacheRead = tokens.cache?.read ?? 0;
|
|
||||||
totals.input += (tokens.input ?? 0) + cacheRead + (tokens.cache?.write ?? 0);
|
|
||||||
totals.output += (tokens.output ?? 0) + (tokens.reasoning ?? 0);
|
|
||||||
totals.read += cacheRead;
|
|
||||||
totals.seen++;
|
|
||||||
}
|
|
||||||
|
|
||||||
function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
|
|
||||||
if (totals.seen === 0) return undefined;
|
|
||||||
return {
|
|
||||||
input: totals.input,
|
|
||||||
output: totals.output,
|
|
||||||
hit: totals.input > 0 ? (totals.read / totals.input) * 100 : undefined,
|
|
||||||
read: totals.read,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Walk every descendant sub-agent session (task tool children can nest) via the SDK
|
|
||||||
* `session.children` endpoint and sum their token usage. Never throws into the render path.
|
|
||||||
*/
|
|
||||||
async function collectFamily(api: TuiApi, rootID: string): Promise<CacheSummary | undefined> {
|
|
||||||
const client = api.client;
|
|
||||||
if (!client?.session?.children) return undefined;
|
|
||||||
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
|
||||||
const visited = new Set<string>([rootID]);
|
|
||||||
let frontier: string[] = [rootID];
|
|
||||||
let counted = 0;
|
|
||||||
for (let depth = 0; depth < FAMILY_MAX_DEPTH && frontier.length > 0 && counted < FAMILY_MAX_SESSIONS; depth++) {
|
|
||||||
const next: string[] = [];
|
|
||||||
for (const id of frontier) {
|
|
||||||
let children: ReadonlyArray<TuiSessionInfo>;
|
|
||||||
try {
|
|
||||||
const response = await client.session.children({ sessionID: id });
|
|
||||||
children = Array.isArray(response?.data) ? response.data : [];
|
|
||||||
} catch (error) {
|
|
||||||
trace("family-children-error", redact(error instanceof Error ? error.message : String(error)));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (const child of children) {
|
|
||||||
if (!child?.id || visited.has(child.id) || counted >= FAMILY_MAX_SESSIONS) continue;
|
|
||||||
visited.add(child.id);
|
|
||||||
next.push(child.id);
|
|
||||||
counted++;
|
|
||||||
// Prefer the child's aggregate tokens (the v2 store exposes them) and fall back to
|
|
||||||
// summing its assistant messages; mirrors the parent accounting so the math matches.
|
|
||||||
let aggregate = child.tokens;
|
|
||||||
try {
|
|
||||||
aggregate = api.state?.session?.get?.(child.id)?.tokens ?? child.tokens;
|
|
||||||
} catch {
|
|
||||||
/* fall back to the child entry's tokens */
|
|
||||||
}
|
|
||||||
if (aggregate) {
|
|
||||||
addMessageTokens(totals, aggregate);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!client.session?.messages) continue;
|
|
||||||
try {
|
|
||||||
const response = await client.session.messages({ sessionID: child.id, limit: FAMILY_MESSAGE_LIMIT });
|
|
||||||
for (const entry of response?.data ?? []) {
|
|
||||||
if (entry?.info?.role !== "assistant") continue;
|
|
||||||
addMessageTokens(totals, entry.info.tokens);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
trace("family-messages-error", redact(error instanceof Error ? error.message : String(error)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
frontier = next;
|
|
||||||
}
|
|
||||||
trace("family-collected", `root=${rootID}`, `sessions=${counted}`, `seen=${totals.seen}`);
|
|
||||||
return summarizeTotals(totals);
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokenView = {
|
|
||||||
input: number;
|
|
||||||
output: number;
|
|
||||||
subInput: number;
|
|
||||||
subOutput: number;
|
|
||||||
hasSub: boolean;
|
|
||||||
hit: number | undefined;
|
|
||||||
empty: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const tui = async (api: TuiApi): Promise<void> => {
|
|
||||||
const [toggles, setToggles] = createSignal(readToggles());
|
|
||||||
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
|
|
||||||
const [now, setNow] = createSignal(Date.now());
|
|
||||||
const [updatedAt, setUpdatedAt] = createSignal(0);
|
|
||||||
const [sessionId, setSessionId] = createSignal<string | undefined>(undefined);
|
|
||||||
const [family, setFamily] = createSignal<CacheSummary | undefined>(undefined);
|
|
||||||
|
|
||||||
let inflight = false;
|
|
||||||
let pending = false;
|
|
||||||
let lastRefreshAt = 0;
|
|
||||||
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
||||||
let lastSessionId: string | undefined;
|
|
||||||
let familyRequestId = 0;
|
|
||||||
let familyTimer: ReturnType<typeof setTimeout> | undefined;
|
|
||||||
|
|
||||||
const refreshQuota = async (): Promise<void> => {
|
|
||||||
if (inflight) {
|
|
||||||
pending = true;
|
|
||||||
trace("coalesced", "inflight");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const since = Date.now() - lastRefreshAt;
|
|
||||||
if (lastRefreshAt > 0 && since < MIN_REFRESH_INTERVAL_MS) {
|
|
||||||
trace("rate-limited", `remainingMs=${MIN_REFRESH_INTERVAL_MS - since}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
inflight = true;
|
|
||||||
try {
|
|
||||||
const { key: apiKey, source } = resolveApiKeySource(api);
|
|
||||||
if (!apiKey) {
|
|
||||||
setQuota({ ok: false, error: { kind: "config", message: "No API key found" } });
|
|
||||||
setNow(Date.now());
|
|
||||||
trace("no-key", `source=${source}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
trace("fetch-start", `source=${source}`);
|
|
||||||
const result = await fetchQuota({ apiKey, baseURL: resolveBaseURL(api) });
|
|
||||||
setQuota(result);
|
|
||||||
if (result.ok) {
|
|
||||||
trace(
|
|
||||||
"fetch-ok",
|
|
||||||
`windows=${result.quota.windows.map((w) => `${w.id}:${w.used}/${w.cap}`).join(",")}`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
trace("fetch-error", `kind=${result.error.kind}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Key resolution, state access, and fetch can all throw (e.g. unsynced
|
|
||||||
// api.state); surface it instead of wedging the panel on `loading…`.
|
|
||||||
const message = redact(error instanceof Error ? error.message : String(error));
|
|
||||||
setQuota({ ok: false, error: { kind: "network", message } });
|
|
||||||
trace("fetch-throw", message);
|
|
||||||
} finally {
|
|
||||||
inflight = false;
|
|
||||||
lastRefreshAt = Date.now();
|
|
||||||
setNow(Date.now());
|
|
||||||
setUpdatedAt(Date.now());
|
|
||||||
if (pending) {
|
|
||||||
pending = false;
|
|
||||||
trace("flush-pending");
|
|
||||||
void refreshQuota();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const scheduleQuotaRefresh = (reason: string, delayMs = 800): void => {
|
|
||||||
trace("scheduled", `reason=${reason}`, `delayMs=${delayMs}`);
|
|
||||||
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
|
||||||
debounceTimer = setTimeout(() => {
|
|
||||||
debounceTimer = undefined;
|
|
||||||
void refreshQuota();
|
|
||||||
}, delayMs);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Stale responses are dropped via a monotonic request id rather than an inflight lock, so a
|
|
||||||
// session switch during a slow walk can never leave the panel showing the previous session.
|
|
||||||
const refreshFamily = async (sessionID: string | undefined): Promise<void> => {
|
|
||||||
const requestId = ++familyRequestId;
|
|
||||||
if (sessionID === undefined) {
|
|
||||||
setFamily(undefined);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const result = await collectFamily(api, sessionID);
|
|
||||||
if (requestId === familyRequestId) setFamily(result);
|
|
||||||
} catch (error) {
|
|
||||||
if (requestId === familyRequestId) setFamily(undefined);
|
|
||||||
trace("family-throw", redact(error instanceof Error ? error.message : String(error)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const scheduleFamilyRefresh = (sessionID: string | undefined, delayMs = 800): void => {
|
|
||||||
if (familyTimer !== undefined) clearTimeout(familyTimer);
|
|
||||||
familyTimer = setTimeout(() => {
|
|
||||||
familyTimer = undefined;
|
|
||||||
void refreshFamily(sessionID);
|
|
||||||
}, delayMs);
|
|
||||||
};
|
|
||||||
|
|
||||||
const flip = (name: ToggleName): void => {
|
|
||||||
const next = toggle(name);
|
|
||||||
setToggles(next);
|
|
||||||
api.ui.toast({
|
|
||||||
title: CATEGORY,
|
|
||||||
message: `${name} ${state(next[name])} (${summary(next)})`,
|
|
||||||
variant: next[name] === true ? "success" : "info",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Session-cumulative token accounting from the reactive session store opencode's built-in
|
|
||||||
* context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
|
|
||||||
* input+cache.read+cache.write; output includes reasoning. `hit` is cacheRead/total-input.
|
|
||||||
* A memo over the sessionId()/family() signals so the panel walks messages once per change.
|
|
||||||
*/
|
|
||||||
const view = createMemo((): TokenView => {
|
|
||||||
const sessionID = sessionId();
|
|
||||||
let main: CacheSummary | undefined;
|
|
||||||
if (sessionID) {
|
|
||||||
let messages: ReadonlyArray<TuiMessageInfo> | undefined;
|
|
||||||
try {
|
|
||||||
const list = api.state?.session?.messages(sessionID);
|
|
||||||
if (Array.isArray(list)) messages = list;
|
|
||||||
} catch {
|
|
||||||
messages = undefined;
|
|
||||||
}
|
|
||||||
if (messages) {
|
|
||||||
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
|
||||||
for (const message of messages) {
|
|
||||||
if (message?.role !== "assistant") continue;
|
|
||||||
addMessageTokens(totals, message.tokens);
|
|
||||||
}
|
|
||||||
main = summarizeTotals(totals);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const sub = family();
|
|
||||||
const input = (main?.input ?? 0) + (sub?.input ?? 0);
|
|
||||||
const output = (main?.output ?? 0) + (sub?.output ?? 0);
|
|
||||||
const read = (main?.read ?? 0) + (sub?.read ?? 0);
|
|
||||||
return {
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
subInput: sub?.input ?? 0,
|
|
||||||
subOutput: sub?.output ?? 0,
|
|
||||||
hasSub: sub !== undefined,
|
|
||||||
hit: input > 0 ? (read / input) * 100 : undefined,
|
|
||||||
empty: main === undefined && sub === undefined,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const errorOf = (result: QuotaResult | null): string | undefined =>
|
|
||||||
result?.ok === false ? result.error.message : undefined;
|
|
||||||
|
|
||||||
api.slots.register({
|
|
||||||
order: SIDEBAR_ORDER,
|
|
||||||
slots: {
|
|
||||||
sidebar_content(_ctx, props?: { session_id?: string }) {
|
|
||||||
const id = props?.session_id;
|
|
||||||
if (id !== undefined && id !== lastSessionId) {
|
|
||||||
lastSessionId = id;
|
|
||||||
scheduleQuotaRefresh("session-change");
|
|
||||||
scheduleFamilyRefresh(id);
|
|
||||||
}
|
|
||||||
if (id !== undefined) setSessionId(id);
|
|
||||||
const theme = api.theme;
|
|
||||||
// Reads toggles()/quota()/view()/now() inside the JSX so Solid tracks the signals.
|
|
||||||
// Hoisting them into a `const` above the return would subscribe once under a
|
|
||||||
// non-tracking owner (the slot re-invokes the handler on session change, which is
|
|
||||||
// why /session "fixed" it) and freeze the panel after first paint.
|
|
||||||
return (
|
|
||||||
<box flexDirection="column" gap={0}>
|
|
||||||
<text fg={theme.current.text}>
|
|
||||||
<b>CommandCode</b>
|
|
||||||
</text>
|
|
||||||
<text fg={theme.current.textMuted}>
|
|
||||||
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
|
|
||||||
</text>
|
|
||||||
<text fg={theme.current.textMuted}>
|
|
||||||
{view().empty
|
|
||||||
? "in: --"
|
|
||||||
: `in: ${view().input.toLocaleString()}${view().hasSub ? ` (+${view().subInput.toLocaleString()})` : ""}`}
|
|
||||||
</text>
|
|
||||||
<text fg={theme.current.textMuted}>
|
|
||||||
{view().empty
|
|
||||||
? "out: --"
|
|
||||||
: `out: ${view().output.toLocaleString()}${view().hasSub ? ` (+${view().subOutput.toLocaleString()})` : ""}`}
|
|
||||||
</text>
|
|
||||||
<text fg={theme.current.textMuted}>
|
|
||||||
{view().empty || view().hit === undefined ? "hit: --" : `hit: ${view().hit?.toFixed(1)}%`}
|
|
||||||
</text>
|
|
||||||
{(quota()?.ok === true
|
|
||||||
? (quota() as Extract<QuotaResult, { ok: true }>).quota.windows
|
|
||||||
: []
|
|
||||||
).map((w) => {
|
|
||||||
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
|
|
||||||
const reset = formatReset(w.resetAtMs, now());
|
|
||||||
const amount =
|
|
||||||
w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
|
|
||||||
return (
|
|
||||||
<text
|
|
||||||
fg={
|
|
||||||
w.exceeded || percent(w.used, w.cap) >= 100
|
|
||||||
? theme.current.error
|
|
||||||
: percent(w.used, w.cap) >= 80
|
|
||||||
? theme.current.warning
|
|
||||||
: theme.current.success
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{`${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${reset ? ` · ${reset}` : ""}`}
|
|
||||||
</text>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{errorOf(quota()) !== undefined ? (
|
|
||||||
<text fg={theme.current.error}>quota: {errorOf(quota())}</text>
|
|
||||||
) : quota() === null ? (
|
|
||||||
<text fg={theme.current.textMuted}>quota: loading…</text>
|
|
||||||
) : null}
|
|
||||||
<text fg={theme.current.textMuted}>
|
|
||||||
updated @ {updatedAt() > 0 ? new Date(updatedAt()).toTimeString().slice(0, 8) : "--:--:--"}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
api.keymap.registerLayer({
|
|
||||||
commands: [
|
|
||||||
{
|
|
||||||
name: `${ID}.zdr`,
|
|
||||||
title: "CommandCode: toggle ZDR header",
|
|
||||||
desc: "Send the x-cmd-zdr header on requests",
|
|
||||||
category: CATEGORY,
|
|
||||||
namespace: "palette",
|
|
||||||
slashName: "cc-zdr",
|
|
||||||
run: () => flip("zdr"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: `${ID}.debug`,
|
|
||||||
title: "CommandCode: toggle debug tracing",
|
|
||||||
desc: "Write a redacted request and stream trace to a log file",
|
|
||||||
category: CATEGORY,
|
|
||||||
namespace: "palette",
|
|
||||||
slashName: "cc-debug",
|
|
||||||
run: () => flip("debug"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: `${ID}.status`,
|
|
||||||
title: "CommandCode: show toggle status",
|
|
||||||
desc: "Show the current zdr and debug state",
|
|
||||||
category: CATEGORY,
|
|
||||||
namespace: "palette",
|
|
||||||
slashName: "cc-status",
|
|
||||||
run: () => api.ui.toast({ title: CATEGORY, message: summary(), variant: "info" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: `${ID}.usage`,
|
|
||||||
title: "CommandCode: show usage and quota",
|
|
||||||
desc: "Show the 5-hour, weekly and monthly quota from the CommandCode API",
|
|
||||||
category: CATEGORY,
|
|
||||||
namespace: "palette",
|
|
||||||
slashName: "cc-usage",
|
|
||||||
run: async () => {
|
|
||||||
const { key: apiKey } = resolveApiKeySource(api);
|
|
||||||
if (!apiKey) {
|
|
||||||
api.ui.toast({
|
|
||||||
title: CATEGORY,
|
|
||||||
message: `No API key found. Set provider.${PROVIDER_ID}.options.apiKey or COMMANDCODE_API_KEY.`,
|
|
||||||
variant: "warning",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let result: QuotaResult;
|
|
||||||
try {
|
|
||||||
result = await fetchQuota({ apiKey, baseURL: resolveBaseURL(api) });
|
|
||||||
} catch (error) {
|
|
||||||
const message = redact(error instanceof Error ? error.message : String(error));
|
|
||||||
setQuota({ ok: false, error: { kind: "network", message } });
|
|
||||||
trace("usage-throw", message);
|
|
||||||
api.ui.toast({ title: CATEGORY, message, variant: "error" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!result.ok) {
|
|
||||||
setQuota(result);
|
|
||||||
api.ui.toast({ title: CATEGORY, message: result.error.message, variant: "error" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setQuota(result);
|
|
||||||
setNow(Date.now());
|
|
||||||
setUpdatedAt(Date.now());
|
|
||||||
api.ui.toast({ title: CATEGORY, message: formatQuota(result.quota), variant: "info", duration: 15000 });
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
void refreshQuota();
|
|
||||||
const toggleTimer = setInterval(() => setToggles(readToggles()), 1500);
|
|
||||||
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
|
|
||||||
const configIntervalMs = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
|
|
||||||
const quotaTimer = setInterval(() => {
|
|
||||||
void refreshQuota();
|
|
||||||
void refreshFamily(sessionId());
|
|
||||||
}, Number.isFinite(configIntervalMs) && configIntervalMs > 0 ? configIntervalMs : DEFAULT_QUOTA_INTERVAL_MS);
|
|
||||||
const unsubs = QUOTA_TRIGGER_EVENTS.map((type) =>
|
|
||||||
api.event.on(type, (event) => {
|
|
||||||
scheduleQuotaRefresh(event?.type ?? type);
|
|
||||||
scheduleFamilyRefresh(sessionId());
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
api.lifecycle.onDispose(() => {
|
|
||||||
for (const unsub of unsubs) unsub();
|
|
||||||
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
|
||||||
if (familyTimer !== undefined) clearTimeout(familyTimer);
|
|
||||||
clearInterval(toggleTimer);
|
|
||||||
clearInterval(clockTimer);
|
|
||||||
clearInterval(quotaTimer);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const id = ID;
|
|
||||||
|
|
||||||
export default { id: ID, tui };
|
|
||||||
@ -14,7 +14,8 @@
|
|||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"jsx": "preserve",
|
"jsx": "preserve",
|
||||||
|
"jsxImportSource": "@opentui/solid",
|
||||||
"noEmit": true
|
"noEmit": true
|
||||||
},
|
},
|
||||||
"include": ["src/tui.tsx", "src/tui-shims.d.ts", "src/quota.ts", "src/toggles.ts", "src/log.ts", "src/redact.ts", "src/constants.ts"]
|
"include": ["plugin/tui.tsx", "src/quota.ts", "src/toggles.ts", "src/log.ts", "src/redact.ts", "src/constants.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user