refactor function usage: inline single-use helpers, dedupe script config lookup

This commit is contained in:
nhat.nguyenhong 2026-10-18 12:37:18 +07:00
parent 2532df4963
commit 1c74e81355
16 changed files with 557 additions and 729 deletions

View File

@ -46,11 +46,12 @@ src/toggles.ts Shared toggle file (~/.config/opencode/commandcode-toggles.jso
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) against the shim (no dependencies).
src/constants.ts Defaults, paths, headers, passthrough params, static config block.
tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles/log) against the shim (no dependencies).
src/constants.ts Defaults, paths, headers, static config block.
scripts/smoke.mjs Live end-to-end check.
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
scripts/sync-models.mjs Catalog -> provider.commandcode-go.models generator (with vision probing).
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
```
## Architecture / data flow

View File

@ -343,10 +343,11 @@ 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/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, passthrough params, static config block.
src/constants.ts Defaults, header names, static config block.
scripts/smoke.mjs Live end-to-end check against api.commandcode.ai.
scripts/quota.mjs Print the live quota headlessly.
scripts/sync-models.mjs Pick models interactively and write provider.commandcode-go.models.
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
```
### Request lifecycle

View File

@ -17,6 +17,7 @@
"src/tui-shims.d.ts",
"src/toggles.ts",
"src/quota.ts",
"src/log.ts",
"src/redact.ts",
"src/constants.ts"
],

View File

@ -0,0 +1,29 @@
// Shared by quota.mjs and sync-models.mjs: locate the opencode config and the CommandCode
// API key the same way the provider does.
import { readFileSync } from "node:fs";
import { PROVIDER_ID } from "../dist/constants.js";
/** Parse an opencode.json; a missing file is `{ text: "", data: {}, exists: false }`. */
export function readConfig(path) {
try {
const text = readFileSync(path, "utf8");
return { text, data: JSON.parse(text), exists: true };
} catch (error) {
// A fresh install has no opencode.json yet; treat it as empty. Bad JSON or unreadable
// files still throw.
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
throw error;
}
}
/** COMMANDCODE_API_KEY, then provider options apiKey, then a configured Authorization header. */
export function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}

View File

@ -3,18 +3,19 @@
// the headless check and does not need opencode running.
//
// Run: node scripts/quota.mjs [--config <path>] [--base-url <url>] [--json] (build first: npm run build)
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { fetchQuota, formatQuota } from "../dist/quota.js";
import { PROVIDER_ID } from "../dist/constants.js";
import { readConfig, resolveKey } from "./opencode-config.mjs";
function parseArgs(argv) {
const opts = {
config: join(homedir(), ".config", "opencode", "opencode.json"),
baseURL: undefined,
json: false,
};
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const value = () => {
@ -50,30 +51,14 @@ function parseArgs(argv) {
throw new Error(`Unknown argument: ${arg}`);
}
}
return opts;
}
function readConfig(path) {
let config = {};
try {
return JSON.parse(readFileSync(path, "utf8"));
config = readConfig(opts.config).data;
} catch {
return {};
}
config = {};
}
function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}
const opts = parseArgs(process.argv.slice(2));
const config = readConfig(opts.config);
const apiKey = resolveKey(config, process.env);
if (!apiKey) {
console.error(

View File

@ -5,19 +5,17 @@ import { join } from "node:path";
import { createCommandCode } from "../dist/index.js";
import { PROVIDER_ID } from "../dist/constants.js";
function apiKey() {
if (process.env.COMMANDCODE_API_KEY) return process.env.COMMANDCODE_API_KEY;
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
let key = process.env.COMMANDCODE_API_KEY;
if (!key) {
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
try {
const cfg = JSON.parse(readFileSync(configPath, "utf8"));
return cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
key = cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
} catch {
return undefined;
key = undefined;
}
}
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
const key = apiKey();
if (!key) {
console.error(`No API key: set COMMANDCODE_API_KEY or configure provider.${PROVIDER_ID}.options.apiKey`);
process.exit(1);

View File

@ -7,13 +7,14 @@
// the result into the global opencode config. Deselecting a model removes it from the config.
//
// Run: node scripts/sync-models.mjs (build first: npm run build)
import { mkdirSync, readFileSync, realpathSync, writeFileSync, renameSync } from "node:fs";
import { mkdirSync, realpathSync, writeFileSync, renameSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import readline from "node:readline";
import { createCommandCode } from "../dist/index.js";
import { redact } from "../dist/redact.js";
import { DEFAULT_BASE_URL, DEFAULT_CC_VERSION, DEFAULT_MAX_TOKENS, MODELS_PATH, PROVIDER_ID } from "../dist/constants.js";
import { readConfig, resolveKey } from "./opencode-config.mjs";
const CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json");
const CONSOLE_URL = "https://commandcode.ai/studio/provider";
@ -36,53 +37,6 @@ const NO_IMAGE =
// 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;
function readConfig(path) {
try {
const text = readFileSync(path, "utf8");
return { text, data: JSON.parse(text), exists: true };
} catch (error) {
// A fresh install has no opencode.json yet; treat it as empty so the console
// guidance / env-key path can still run. Bad JSON or unreadable files still throw.
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
throw error;
}
}
function detectIndent(text) {
const match = /\n([ \t]+)\S/.exec(text);
if (!match) return 2;
const indent = match[1];
if (indent.startsWith("\t")) return "\t";
return indent.length;
}
function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv) return fromEnv.trim();
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}
async function fetchCatalog(baseURL, apiKey, ccVersion) {
const response = await fetch(`${baseURL}${MODELS_PATH}`, {
headers: {
Authorization: /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`,
"x-command-code-version": ccVersion,
},
});
const body = await response.text();
if (!response.ok) {
throw new Error(`catalog ${response.status}: ${redact(body.slice(0, 500)) || response.statusText}`);
}
const parsed = JSON.parse(body);
const data = Array.isArray(parsed?.data) ? parsed.data : [];
return data.filter((m) => m && typeof m.id === "string" && m.id.length > 0);
}
async function probeVision(provider, id) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error("probe timeout")), 30000);
@ -122,68 +76,6 @@ async function probeVision(provider, id) {
}
}
// 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 results skip the retry.
async function probeVisionConfirmed(provider, id) {
let outcome = await probeVision(provider, id);
if (outcome.vision === false) outcome = await probeVision(provider, id);
return outcome;
}
async function mapPool(items, concurrency, worker) {
const results = new Array(items.length);
let cursor = 0;
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (true) {
const index = cursor++;
if (index >= items.length) return;
results[index] = await worker(items[index], index);
}
});
await Promise.all(runners);
return results;
}
function modelEntry(catalogModel, vision) {
const id = catalogModel.id;
const context = Number(catalogModel.context_length) || 0;
const entry = {
name: typeof catalogModel.name === "string" && catalogModel.name ? catalogModel.name : id,
limit: { context, output: DEFAULT_MAX_TOKENS },
reasoning: true,
attachment: vision,
modalities: {
input: vision ? ["text", "image"] : ["text"],
output: ["text"],
},
};
return entry;
}
function writeAtomic(path, contents) {
// Write next to the real file: renaming over a symlink would replace the link itself.
try {
path = realpathSync(path);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, contents);
renameSync(tmp, path);
}
// The catalog carries no pricing fields (id/name/context_length/supported_endpoints only),
// so the picker shows context with any opportunistically present pricing keys omitted.
function formatContext(value) {
const n = Number(value);
if (!Number.isFinite(n) || n <= 0) return "unknown";
if (n >= 1_000_000 && n % 1_000_000 === 0) return `${n / 1_000_000}M (${n})`;
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M (${n})`;
if (n >= 1000 && n % 1000 === 0) return `${n / 1000}k (${n})`;
if (n >= 1000) return `${(n / 1000).toFixed(0)}k (${n})`;
return `${n}`;
}
// Builtins-only checkbox picker (no dependencies, so the package stays runtime-dependency-free).
// Nothing is pre-checked; deselected ids are dropped by the caller. Resolves to the selected
// catalog indices, or null when the user aborts (Esc on empty filter / Ctrl-C).
@ -253,7 +145,22 @@ function pickModels(catalog, existingIds) {
// Selected rows render green (both lines); the cursor row renders bold on top.
const code = selected ? (active ? "1;32" : "32") : active ? "1" : undefined;
line(`${active ? "\u203a" : " "} [${mark}] ${model.id} \u2014 ${model.name ?? model.id}${current}`, code);
line(` ctx ${formatContext(model.context_length)}`, code);
// The catalog carries no pricing fields (id/name/context_length only), so only context
// is shown; opportunistically present extra keys are omitted.
const ctx = Number(model.context_length);
const ctxText =
!Number.isFinite(ctx) || ctx <= 0
? "unknown"
: ctx >= 1_000_000 && ctx % 1_000_000 === 0
? `${ctx / 1_000_000}M (${ctx})`
: ctx >= 1_000_000
? `${(ctx / 1_000_000).toFixed(1)}M (${ctx})`
: ctx >= 1000 && ctx % 1000 === 0
? `${ctx / 1000}k (${ctx})`
: ctx >= 1000
? `${(ctx / 1000).toFixed(0)}k (${ctx})`
: `${ctx}`;
line(` ctx ${ctxText}`, code);
});
line("");
line("\u2191/\u2193 navigate · space toggle · ctrl-a all · ctrl-u none · esc back/abort · enter confirm");
@ -413,7 +320,19 @@ async function main() {
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
let catalog;
try {
catalog = await fetchCatalog(baseURL, key, ccVersion);
const response = await fetch(`${baseURL}${MODELS_PATH}`, {
headers: {
Authorization: /^Bearer\s/i.test(key) ? key : `Bearer ${key}`,
"x-command-code-version": ccVersion,
},
});
const body = await response.text();
if (!response.ok) {
throw new Error(`catalog ${response.status}: ${redact(body.slice(0, 500)) || response.statusText}`);
}
const parsed = JSON.parse(body);
const data = Array.isArray(parsed?.data) ? parsed.data : [];
catalog = data.filter((m) => m && typeof m.id === "string" && m.id.length > 0);
} catch (error) {
console.error(`Failed to fetch catalog: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
@ -440,12 +359,24 @@ async function main() {
const selected = picked.map((index) => catalog[index]).filter(Boolean);
console.log(`Probing vision (${selected.length} models, concurrency ${CONCURRENCY})...`);
const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key, baseURL, ccVersion, maxRetries: 1 });
const probeResults = await mapPool(selected, CONCURRENCY, async (model, index) => {
const outcome = await probeVisionConfirmed(provider, model.id);
const probeResults = new Array(selected.length);
let probeCursor = 0;
const probeRunners = Array.from({ length: Math.min(CONCURRENCY, selected.length) }, async () => {
while (true) {
const index = probeCursor++;
if (index >= selected.length) return;
const model = selected[index];
// 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
// results skip the retry.
let outcome = await probeVision(provider, model.id);
if (outcome.vision === false) outcome = await probeVision(provider, model.id);
const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown";
console.log(` [${index + 1}/${selected.length}] ${model.id}: ${tag} (${outcome.reason})`);
return outcome;
probeResults[index] = outcome;
}
});
await Promise.all(probeRunners);
// Deselect = remove: the final map holds exactly the picked ids. Extra user fields on
// picked ids are preserved; unpicked ids are dropped.
@ -464,7 +395,17 @@ async function main() {
stats.unknown++;
if (vision) stats.heuristic++;
}
merged[model.id] = { ...(existing[model.id] ?? {}), ...modelEntry(model, vision) };
const entry = {
name: typeof model.name === "string" && model.name ? model.name : model.id,
limit: { context: Number(model.context_length) || 0, output: DEFAULT_MAX_TOKENS },
reasoning: true,
attachment: vision,
modalities: {
input: vision ? ["text", "image"] : ["text"],
output: ["text"],
},
};
merged[model.id] = { ...(existing[model.id] ?? {}), ...entry };
});
const removed = [...existingIds].filter((id) => !(id in merged)).length;
@ -473,11 +414,21 @@ async function main() {
config.provider[PROVIDER_ID] ??= {};
config.provider[PROVIDER_ID].models = merged;
const indent = detectIndent(text);
const indentMatch = /\n([ \t]+)\S/.exec(text);
const indent = !indentMatch ? 2 : indentMatch[1].startsWith("\t") ? "\t" : indentMatch[1].length;
const trailing = text === "" || text.endsWith("\n") ? "\n" : "";
// The config directory may not exist yet on a fresh install; create it before the atomic write.
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
writeAtomic(CONFIG_PATH, `${JSON.stringify(config, null, indent)}${trailing}`);
// Write next to the real file: renaming over a symlink would replace the link itself.
let target = CONFIG_PATH;
try {
target = realpathSync(target);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const tmp = `${target}.${process.pid}.tmp`;
writeFileSync(tmp, `${JSON.stringify(config, null, indent)}${trailing}`);
renameSync(tmp, target);
console.log(
`Wrote ${Object.keys(merged).length} models to ${CONFIG_PATH}\n` +

View File

@ -18,18 +18,6 @@ export const DEFAULT_MAX_RETRIES = 2;
export const BASE_RETRY_DELAY = 0.5;
export const DEFAULT_RETRY_MAX_DELAY = 60;
// Sampling knobs CommandCode accepts. Forwarded verbatim.
export const PASSTHROUGH_PARAMS = [
"temperature",
"top_p",
"top_k",
"stop",
"seed",
"presence_penalty",
"frequency_penalty",
"reasoning_effort",
] as const;
export const STATIC_CONFIG = {
workingDir: "",
date: "",

View File

@ -10,22 +10,29 @@ import { debugEnabled } from "./toggles.js";
const FILE = join(tmpdir(), "commandcode-debug.log");
function serialize(value: unknown): string {
/** Effective default tracing state (toggle file). Re-read on every call. */
export function isDebugEnabled(): boolean {
return debugEnabled();
}
/** Trace with a per-request override, so providerOptions/history state is not global. */
export function debugWhen(enabled: boolean, scope: string, ...args: unknown[]): void {
if (!enabled) return;
const parts = args.map((value) => {
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function emit(scope: string, args: unknown[]): void {
const parts = args.map(serialize);
});
const line = `[commandcode] ${new Date().toISOString()} [${scope}] ${parts.join(" ")}`;
try {
appendFileSync(FILE, redact(line) + "\n", "utf8");
} catch {
// Never let tracing break the request path.
// Never let tracing break the request path, or corrupt an interactive terminal
// (the TUI plugin shares this writer and its stderr may be the rendered screen).
if (!process.stderr.isTTY) {
try {
process.stderr.write(redact(line) + "\n");
} catch {
@ -33,20 +40,4 @@ function emit(scope: string, args: unknown[]): void {
}
}
}
/** Effective default tracing state (toggle file). Re-read on every call. */
export function isDebugEnabled(): boolean {
return debugEnabled();
}
/** Write a trace line (appended) if tracing is enabled. Values are redacted before write. */
export function debug(scope: string, ...args: unknown[]): void {
if (!debugEnabled()) return;
emit(scope, args);
}
/** Trace with a per-request override, so providerOptions/history state is not global. */
export function debugWhen(enabled: boolean, scope: string, ...args: unknown[]): void {
if (!enabled) return;
emit(scope, args);
}

View File

@ -26,28 +26,10 @@ import { zdrEnabled } from "./toggles.js";
import { transform } from "./transform.js";
import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js";
// x-cmd-zdr breaks some models; off by default.
// Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely.
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
return options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
}
function truthyHeader(value: string): boolean {
return !/^(0|false|no|off)$/i.test(value);
}
function resolveZdr(
options: LanguageModelV3CallOptions,
providerHeaders: Record<string, string>,
): string | undefined {
const scoped = providerScoped(options)?.["zdr"];
if (typeof scoped === "boolean") return scoped ? "1" : "0";
const header = headerValue({ ...providerHeaders, ...(options.headers ?? {}) }, "x-cmd-zdr");
if (header !== undefined) return truthyHeader(header) ? "1" : "0";
return zdrEnabled() ? "1" : undefined;
}
function resolveDebug(options: LanguageModelV3CallOptions): boolean {
const scoped = providerScoped(options)?.["debug"];
return typeof scoped === "boolean" ? scoped : isDebugEnabled();
@ -79,26 +61,6 @@ function headerValue(headers: Record<string, string | undefined>, key: string):
return undefined;
}
function bearer(token: string | undefined): string | undefined {
if (!token) return undefined;
return /^Bearer\s/i.test(token) ? token : `Bearer ${token}`;
}
function resolve(options: CommandCodeOptions): ResolvedOptions {
const headers = { ...(options.headers ?? {}) };
const fromHeader = headerValue(headers, "authorization");
const apiKey = options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, "");
return {
providerId: options.name ?? PROVIDER_ID,
apiKey,
headers,
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
};
}
function zeroUsage(): LanguageModelV3Usage {
return {
inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
@ -114,23 +76,6 @@ function isRetryable(status: number): boolean {
// CommandCode's gateway marks these with `statusCode`/`isRetryable`; retry before content.
type StreamErrorInfo = { message: string; statusCode?: number; isRetryable?: boolean };
function streamErrorInfo(evt: Record<string, any>): StreamErrorInfo | null {
if (evt?.["type"] !== "error") return null;
const err = evt["error"];
if (err === null || typeof err !== "object") return { message: String(err) };
const record = err as Record<string, unknown>;
const message = typeof record["message"] === "string" ? record["message"] : JSON.stringify(err);
return {
message,
...(typeof record["statusCode"] === "number" ? { statusCode: record["statusCode"] } : {}),
...(typeof record["isRetryable"] === "boolean" ? { isRetryable: record["isRetryable"] } : {}),
};
}
function isRetryableStreamError(info: StreamErrorInfo): boolean {
return info.isRetryable === true || (info.statusCode !== undefined && isRetryable(info.statusCode));
}
// Only `start`/`start-step` are safe to buffer while looking for an immediate stream error;
// once real output appears a retry would duplicate the response.
const STREAM_PREAMBLE = new Set(["start", "start-step"]);
@ -165,31 +110,6 @@ function retryDelay(attempt: number, retryAfter: string | null, maxDelay: number
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function toReadableStream<T>(iterator: AsyncGenerator<T>): ReadableStream<T> {
return new ReadableStream<T>({
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await iterator.return?.(reason as never);
},
});
}
function headerObject(headers: Headers): Record<string, string> {
const out: Record<string, string> = {};
headers.forEach((value, key) => {
out[key] = value;
});
return out;
}
class CommandCodeLanguageModel implements LanguageModelV3 {
readonly specificationVersion = "v3" as const;
readonly provider: string;
@ -205,11 +125,23 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
supportedUrls: Record<string, RegExp[]> = {};
private requestHeaders(
extra: Record<string, string | undefined> | undefined,
zdr: string | undefined,
private async fetchWithRetry(
body: string,
options: LanguageModelV3CallOptions,
dbg: boolean,
): Record<string, string> {
): Promise<OpenedStream> {
// x-cmd-zdr breaks some models; off by default.
// Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely.
const scopedZdr = providerScoped(options)?.["zdr"];
let zdr: string | undefined;
if (typeof scopedZdr === "boolean") zdr = scopedZdr ? "1" : "0";
else {
const header = headerValue({ ...this.opts.headers, ...(options.headers ?? {}) }, "x-cmd-zdr");
if (header !== undefined) zdr = /^(0|false|no|off)$/i.test(header) ? "0" : "1";
else if (zdrEnabled()) zdr = "1";
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
"x-command-code-version": this.opts.ccVersion,
@ -221,18 +153,10 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
};
if (zdr !== undefined) headers["x-cmd-zdr"] = zdr;
debugWhen(dbg, "fetch", "zdr", zdr === "1" ? "on" : "off");
const auth = bearer(this.opts.apiKey);
if (auth) headers["Authorization"] = auth;
for (const [k, v] of Object.entries(extra ?? {})) if (v !== undefined) headers[k] = v;
return headers;
}
const apiKey = this.opts.apiKey;
if (apiKey) headers["Authorization"] = /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`;
for (const [k, v] of Object.entries(options.headers ?? {})) if (v !== undefined) headers[k] = v;
private async fetchWithRetry(
body: string,
options: LanguageModelV3CallOptions,
dbg: boolean,
): Promise<OpenedStream> {
const headers = this.requestHeaders(options.headers, resolveZdr(options, this.opts.headers), dbg);
let lastError: unknown;
const url = `${this.opts.baseURL}${GENERATE_PATH}`;
@ -307,9 +231,21 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
if (next.done) break;
const evt = next.value;
prefix.push(evt);
const info = streamErrorInfo(evt);
if (info) {
if (isRetryableStreamError(info) && attempt < this.opts.maxRetries) streamRetry = info;
if (evt?.["type"] === "error") {
const err = evt["error"];
let info: StreamErrorInfo;
if (err === null || typeof err !== "object") {
info = { message: String(err) };
} else {
const record = err as Record<string, unknown>;
info = {
message: typeof record["message"] === "string" ? record["message"] : JSON.stringify(err),
...(typeof record["statusCode"] === "number" ? { statusCode: record["statusCode"] } : {}),
...(typeof record["isRetryable"] === "boolean" ? { isRetryable: record["isRetryable"] } : {}),
};
}
const retryable = info.isRetryable === true || (info.statusCode !== undefined && isRetryable(info.statusCode));
if (retryable && attempt < this.opts.maxRetries) streamRetry = info;
break;
}
if (!STREAM_PREAMBLE.has(evt["type"])) break;
@ -351,16 +287,21 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
throw lastError instanceof Error ? lastError : new Error("Upstream unreachable");
}
private async errorFrom(response: Response, dbg: boolean): Promise<Error> {
let body = "";
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
const dbg = resolveDebug(options);
const body = transform(options, this.modelId);
debugWhen(dbg, "doStream", `model=${this.modelId}`, `bodyBytes=${Buffer.byteLength(body, "utf8")}`);
const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg);
if (!response.ok || !response.body) {
let responseBody = "";
try {
body = await response.text();
responseBody = await response.text();
} catch {
/* ignore */
}
let message = body;
let message = responseBody;
try {
const parsed = JSON.parse(body);
const parsed = JSON.parse(responseBody);
const err = parsed?.error;
if (typeof err === "string") message = err;
else if (err && typeof err === "object" && typeof err.message === "string") message = err.message;
@ -369,22 +310,29 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
}
const surfaced = redact(message.slice(0, 2000) || `Upstream returned ${response.status}`);
debugWhen(dbg, "error", `status=${response.status}`, `body=${surfaced}`);
return new Error(surfaced);
throw new Error(surfaced);
}
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
const dbg = resolveDebug(options);
const body = transform(options, this.modelId);
debugWhen(dbg, "doStream", `model=${this.modelId}`, `bodyBytes=${Buffer.byteLength(body, "utf8")}`);
const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg);
if (!response.ok || !response.body) throw await this.errorFrom(response, dbg);
debugWhen(dbg, "doStream", "ok", `status=${response.status}`);
const stream = toReadableStream(this.streamParts(prefix, events, dbg));
const iterator = this.streamParts(prefix, events, dbg);
const stream = new ReadableStream<LanguageModelV3StreamPart>({
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await iterator.return?.(reason as never);
},
});
return {
stream,
request: { body: JSON.parse(body) as unknown },
response: { headers: headerObject(response.headers) },
response: { headers: Object.fromEntries(response.headers) },
};
}
@ -612,7 +560,17 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
export function createCommandCode(options: CommandCodeOptions = {}): {
languageModel(modelId: string): LanguageModelV3;
} {
const resolved = resolve(options);
const headers = { ...(options.headers ?? {}) };
const fromHeader = headerValue(headers, "authorization");
const resolved: ResolvedOptions = {
providerId: options.name ?? PROVIDER_ID,
apiKey: options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, ""),
headers,
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
};
return {
languageModel(modelId: string) {
return new CommandCodeLanguageModel(modelId, resolved);

View File

@ -370,46 +370,41 @@ export function formatReset(resetAtMs: number | null, now: number = Date.now()):
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
}
function formatTokens(tokens: number): string {
if (tokens >= 1_000_000_000) return `${(tokens / 1_000_000_000).toFixed(1)}B`;
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
return String(tokens);
/** Human-readable multi-line quota summary for the `/cc-usage` command and CLI. */
export function formatQuota(quota: Quota, now: number = Date.now()): string {
const lines: string[] = [];
lines.push(quota.account.keyName ?? quota.account.login);
if (quota.plan) {
const plan = quota.plan;
const name = plan.id.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
const status = plan.status ? ` · ${plan.status}` : "";
const end = periodEndMs(plan);
if (end === null) {
lines.push(`Plan: ${name}${status}`);
} else {
const days = Math.ceil((end - now) / 86_400_000);
const date = new Date(end).toISOString().slice(0, 10);
const when = days > 0 ? `renews ${date} (${days}d)` : days === 0 ? `renews ${date} (today)` : `renewed ${date}`;
lines.push(`Plan: ${name}${status} · ${when}`);
}
}
function formatWindowLine(w: QuotaWindow, now: number): string {
if (quota.windows.length > 0) {
lines.push("");
for (const w of quota.windows) {
const pct = Math.min(percent(w.used, w.cap), 999);
const reset = formatReset(w.resetAtMs, now);
const amount =
w.id === "monthly"
? `$${w.used.toFixed(2)} / $${w.cap.toFixed(2)}`
: `${w.used.toFixed(2)} / ${w.cap.toFixed(2)} credits`;
return `${w.label.padEnd(8)} ${quotaBar(w.used, w.cap)} ${String(pct).padStart(3)}% ${amount}${
lines.push(
`${w.label.padEnd(8)} ${quotaBar(w.used, w.cap)} ${String(pct).padStart(3)}% ${amount}${
reset ? ` (resets in ${reset})` : ""
}`;
}`,
);
}
function planLine(plan: QuotaPlan, now: number): string {
const name = plan.id.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
const status = plan.status ? ` · ${plan.status}` : "";
const end = periodEndMs(plan);
if (end === null) return `Plan: ${name}${status}`;
const remaining = end - now;
const days = Math.ceil(remaining / 86_400_000);
const date = new Date(end).toISOString().slice(0, 10);
const when = days > 0 ? `renews ${date} (${days}d)` : days === 0 ? `renews ${date} (today)` : `renewed ${date}`;
return `Plan: ${name}${status} · ${when}`;
}
/** Human-readable multi-line quota summary for the `/cc-usage` command and CLI. */
export function formatQuota(quota: Quota, now: number = Date.now()): string {
const lines: string[] = [];
lines.push(quota.account.keyName ?? quota.account.login);
if (quota.plan) lines.push(planLine(quota.plan, now));
if (quota.windows.length > 0) {
lines.push("");
for (const w of quota.windows) lines.push(formatWindowLine(w, now));
}
if (quota.credits) {
@ -420,7 +415,19 @@ export function formatQuota(quota: Quota, now: number = Date.now()): string {
if (quota.summary) {
const period = quota.plan?.currentPeriodStart ? "this billing period" : "total";
const tokens = quota.summary.totalTokens === undefined ? "" : ` · ${formatTokens(quota.summary.totalTokens)} tokens`;
const totalTokens = quota.summary.totalTokens;
let tokens = "";
if (totalTokens !== undefined) {
const amount =
totalTokens >= 1_000_000_000
? `${(totalTokens / 1_000_000_000).toFixed(1)}B`
: totalTokens >= 1_000_000
? `${(totalTokens / 1_000_000).toFixed(1)}M`
: totalTokens >= 1_000
? `${(totalTokens / 1_000).toFixed(1)}k`
: String(totalTokens);
tokens = ` · ${amount} tokens`;
}
lines.push(
`Usage: ${quota.summary.totalCount.toLocaleString("en-US")} requests · $${quota.summary.totalCost.toFixed(2)} (${period})${tokens}`,
);

View File

@ -30,8 +30,9 @@ export function readToggles(): Toggles {
}
}
export function writeToggles(patch: Toggles): Toggles {
const merged = { ...readToggles(), ...patch };
export function toggle(name: ToggleName): Toggles {
const current = readToggles();
const merged = { ...current, [name]: current[name] !== true };
const path = togglesPath();
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.tmp`;
@ -40,11 +41,6 @@ export function writeToggles(patch: Toggles): Toggles {
return merged;
}
export function toggle(name: ToggleName): Toggles {
const current = readToggles();
return writeToggles({ [name]: current[name] !== true });
}
/** Toggle state from the shared flag file; an absent key means off. */
export function zdrEnabled(): boolean {
return readToggles().zdr === true;

View File

@ -1,55 +1,12 @@
import type {
LanguageModelV3CallOptions,
LanguageModelV3FunctionTool,
LanguageModelV3ToolResultOutput,
LanguageModelV3ToolResultPart,
} from "@ai-sdk/provider";
import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, PROVIDER_ID, STATIC_CONFIG } from "./constants.js";
import { DEFAULT_MAX_TOKENS, PROVIDER_ID, STATIC_CONFIG } from "./constants.js";
type ContentPart = Record<string, unknown>;
function environmentInfo(): string {
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
const ver = typeof process !== "undefined" && process.version ? process.version : "";
return `${plat}${ver ? `, Node ${ver}` : ""}`;
}
function today(): string {
return new Date().toISOString().slice(0, 10);
}
/** tool_call_id -> tool name, so tool results can be attributed. */
function collectToolNames(prompt: LanguageModelV3CallOptions["prompt"]): Map<string, string> {
const names = new Map<string, string>();
for (const message of prompt) {
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) {
names.set(part.toolCallId, part.toolName);
}
}
}
return names;
}
/** Tool ids that have both a call and a result. Unmatched ids make upstream reject the request. */
function pairedToolCallIds(prompt: LanguageModelV3CallOptions["prompt"]): Set<string> {
const calls = new Set<string>();
const results = new Set<string>();
for (const message of prompt) {
if (message.role === "assistant") {
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) calls.add(part.toolCallId);
}
} else if (message.role === "tool") {
for (const part of message.content) {
if (part.type === "tool-result" && part.toolCallId) results.add(part.toolCallId);
}
}
}
return new Set([...calls].filter((id) => results.has(id)));
}
function stringify(value: unknown): string {
if (typeof value === "string") return value;
try {
@ -59,107 +16,35 @@ function stringify(value: unknown): string {
}
}
function toolResultOutput(output: LanguageModelV3ToolResultOutput): ContentPart {
switch (output.type) {
case "text":
case "error-text":
return { type: "text", value: output.value };
case "json":
case "error-json":
return { type: "text", value: stringify(output.value) };
case "execution-denied":
return { type: "text", value: output.reason ?? "Execution denied" };
case "content": {
const parts: ContentPart[] = [];
for (const item of output.value) {
if (item.type === "text") {
parts.push({ type: "text", text: item.text });
} else if (item.type === "image-data") {
parts.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else if (item.type === "image-url" || item.type === "file-url") {
parts.push({ type: "image", image: item.url });
} else if (item.type === "file-data") {
parts.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else {
parts.push({ type: "text", text: stringify(item) });
}
}
return { type: "text", value: stringify(parts) };
}
default:
return { type: "text", value: stringify(output) };
}
}
/** AI SDK file part -> CommandCode image part. */
function imagePart(data: unknown, mediaType: string): ContentPart | null {
if (data instanceof URL) return { type: "image", image: data.toString() };
if (typeof data === "string") {
if (/^data:[^;,]+;base64,/.test(data)) return { type: "image", image: data, mimeType: mediaType };
if (/^https?:\/\//i.test(data)) return { type: "image", image: data };
return { type: "image", image: `data:${mediaType};base64,${data}`, mimeType: mediaType };
}
if (data instanceof Uint8Array) {
return { type: "image", image: `data:${mediaType};base64,${Buffer.from(data).toString("base64")}`, mimeType: mediaType };
}
return null;
}
function mapTools(tools: LanguageModelV3CallOptions["tools"]): Array<Record<string, unknown>> {
const out: Array<Record<string, unknown>> = [];
for (const tool of tools ?? []) {
if (tool.type !== "function") continue;
const fn = tool as LanguageModelV3FunctionTool;
out.push({
type: "function",
name: fn.name,
description: fn.description ?? "",
input_schema: fn.inputSchema ?? { type: "object", properties: {} },
});
}
return out;
}
/**
* OpenAI/upstream `tool_choice` -> (tools, params.tool_choice).
*
* Upstream accepts exactly one value, `{"type":"auto"}`. `none` is emulated by sending no
* tools; a named tool by sending only that tool; `required` is not expressible.
*/
function applyToolChoice(
tools: Array<Record<string, unknown>>,
toolChoice: LanguageModelV3CallOptions["toolChoice"],
): { tools: Array<Record<string, unknown>>; toolChoice: Record<string, unknown> | null } {
if (!toolChoice) return { tools, toolChoice: null };
if (toolChoice.type === "auto") return { tools, toolChoice: { type: "auto" } };
if (toolChoice.type === "none") return { tools: [], toolChoice: null };
if (toolChoice.type === "required") return { tools, toolChoice: null };
if (toolChoice.type === "tool") {
const picked = tools.filter((t) => t.name === toolChoice.toolName);
return { tools: picked.length ? picked : tools, toolChoice: null };
}
return { tools, toolChoice: null };
}
function reasoningEffort(options: LanguageModelV3CallOptions): unknown {
const scoped = options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
}
/** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */
export function transform(options: LanguageModelV3CallOptions, modelId: string): string {
const systemParts: string[] = [];
const messages: Array<Record<string, unknown>> = [];
const paired = pairedToolCallIds(options.prompt);
const toolNames = collectToolNames(options.prompt);
// Tool ids that have both a call and a result. Unmatched ids make upstream reject the request.
const calls = new Set<string>();
const results = new Set<string>();
for (const message of options.prompt) {
if (message.role === "assistant") {
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) calls.add(part.toolCallId);
}
} else if (message.role === "tool") {
for (const part of message.content) {
if (part.type === "tool-result" && part.toolCallId) results.add(part.toolCallId);
}
}
}
const paired = new Set([...calls].filter((id) => results.has(id)));
// tool_call_id -> tool name, so tool results can be attributed.
const toolNames = new Map<string, string>();
for (const message of options.prompt) {
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) toolNames.set(part.toolCallId, part.toolName);
}
}
for (const message of options.prompt) {
if (message.role === "system") {
@ -171,6 +56,49 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
for (const part of message.content) {
if (part.type !== "tool-result") continue;
if (!paired.has(part.toolCallId)) continue;
const output = (part as LanguageModelV3ToolResultPart).output;
let rendered: ContentPart;
switch (output.type) {
case "text":
case "error-text":
rendered = { type: "text", value: output.value };
break;
case "json":
case "error-json":
rendered = { type: "text", value: stringify(output.value) };
break;
case "execution-denied":
rendered = { type: "text", value: output.reason ?? "Execution denied" };
break;
case "content": {
const items: ContentPart[] = [];
for (const item of output.value) {
if (item.type === "text") {
items.push({ type: "text", text: item.text });
} else if (item.type === "image-data") {
items.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else if (item.type === "image-url" || item.type === "file-url") {
items.push({ type: "image", image: item.url });
} else if (item.type === "file-data") {
items.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else {
items.push({ type: "text", text: stringify(item) });
}
}
rendered = { type: "text", value: stringify(items) };
break;
}
default:
rendered = { type: "text", value: stringify(output) };
}
messages.push({
role: "tool",
content: [
@ -178,7 +106,7 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
type: "tool-result",
toolCallId: part.toolCallId,
toolName: part.toolName ?? toolNames.get(part.toolCallId) ?? "unknown",
output: toolResultOutput((part as LanguageModelV3ToolResultPart).output),
output: rendered,
},
],
});
@ -220,9 +148,23 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
if (part.type === "text") {
parts.push({ type: "text", text: part.text });
} else if (part.type === "file") {
if (part.mediaType?.startsWith("image/")) {
const img = imagePart((part as { data?: unknown }).data, part.mediaType);
if (img) parts.push(img);
const mediaType = part.mediaType;
if (mediaType?.startsWith("image/")) {
// AI SDK file part -> CommandCode image part.
const data = (part as { data?: unknown }).data;
if (data instanceof URL) {
parts.push({ type: "image", image: data.toString() });
} else if (typeof data === "string") {
if (/^data:[^;,]+;base64,/.test(data)) parts.push({ type: "image", image: data, mimeType: mediaType });
else if (/^https?:\/\//i.test(data)) parts.push({ type: "image", image: data });
else parts.push({ type: "image", image: `data:${mediaType};base64,${data}`, mimeType: mediaType });
} else if (data instanceof Uint8Array) {
parts.push({
type: "image",
image: `data:${mediaType};base64,${Buffer.from(data).toString("base64")}`,
mimeType: mediaType,
});
}
} else {
parts.push({ type: "text", text: `[file: ${part.filename ?? part.mediaType}]` });
}
@ -231,8 +173,30 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
messages.push({ role: "user", content: parts });
}
const mapped = mapTools(options.tools);
const { tools, toolChoice } = applyToolChoice(mapped, options.toolChoice);
const tools: Array<Record<string, unknown>> = [];
for (const tool of options.tools ?? []) {
if (tool.type !== "function") continue;
const fn = tool as LanguageModelV3FunctionTool;
tools.push({
type: "function",
name: fn.name,
description: fn.description ?? "",
input_schema: fn.inputSchema ?? { type: "object", properties: {} },
});
}
// Upstream accepts exactly one `tool_choice` value, `{"type":"auto"}`. `none` is emulated
// by sending no tools; a named tool by sending only that tool; `required` is not expressible.
let toolChoice: Record<string, unknown> | null = null;
if (options.toolChoice) {
const choice = options.toolChoice;
if (choice.type === "auto") toolChoice = { type: "auto" };
else if (choice.type === "none") tools.length = 0;
else if (choice.type === "tool") {
const picked = tools.filter((t) => t.name === choice.toolName);
if (picked.length) tools.splice(0, tools.length, ...picked);
}
}
const params: Record<string, unknown> = { model: modelId };
const systemText = systemParts.filter(Boolean).join("\n\n");
@ -251,10 +215,17 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
if (options.seed !== undefined) params["seed"] = options.seed;
if (options.presencePenalty !== undefined) params["presence_penalty"] = options.presencePenalty;
if (options.frequencyPenalty !== undefined) params["frequency_penalty"] = options.frequencyPenalty;
const effort = reasoningEffort(options);
const scoped = options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
const effort = scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
if (effort !== undefined) params["reasoning_effort"] = effort;
const config = { ...STATIC_CONFIG, date: today(), environment: environmentInfo() };
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
const ver = typeof process !== "undefined" && process.version ? process.version : "";
const config = {
...STATIC_CONFIG,
date: new Date().toISOString().slice(0, 10),
environment: `${plat}${ver ? `, Node ${ver}` : ""}`,
};
return JSON.stringify({
config,
@ -265,5 +236,3 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
params,
});
}
export { PASSTHROUGH_PARAMS };

1
src/tui-shims.d.ts vendored
View File

@ -6,6 +6,7 @@
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 {

View File

@ -14,13 +14,11 @@
// `namespace: "palette"` command list, so these entries appear in both; `hidden: true`
// would remove them from both.
import { appendFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSignal } from "solid-js";
import { createMemo, createSignal } from "solid-js";
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult, type QuotaWindow } from "./quota.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";
@ -125,23 +123,7 @@ function safeEnv(name: string): string | undefined {
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
function trace(...args: unknown[]): void {
if (!debugEnabled()) return;
const file = join(tmpdir(), "commandcode-debug.log");
const parts = args.map((value) => (typeof value === "string" ? value : safeJson(value)));
const line = `[commandcode] ${new Date().toISOString()} [tui-quota] ${parts.join(" ")}`;
try {
appendFileSync(file, redact(line) + "\n", "utf8");
} catch {
// Never let tracing break the panel.
}
}
function safeJson(value: unknown): string {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
debugWhen(debugEnabled(), "tui-quota", ...args);
}
function state(value: boolean | undefined): string {
@ -170,20 +152,17 @@ function commandCodeOptions(api: TuiApi): Record<string, unknown> | undefined {
}
}
function providersOf(api: TuiApi): TuiProvider[] {
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
let providers: readonly TuiProvider[] = [];
try {
const list = api.state?.provider;
if (Array.isArray(list)) return list as TuiProvider[];
if (Array.isArray(list)) providers = list as TuiProvider[];
// Tolerate a non-array provider state shape instead of throwing.
if (list && typeof list === "object") return Object.values(list) as TuiProvider[];
else if (list && typeof list === "object") providers = Object.values(list) as TuiProvider[];
} catch {
/* fall through */
}
return [];
}
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
const provider = providersOf(api).find((entry) => entry?.id === PROVIDER_ID);
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]> = [
@ -227,61 +206,6 @@ function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
};
}
/**
* 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.
*/
function sessionCacheSummary(api: TuiApi, sessionID: string | undefined): CacheSummary | undefined {
if (!sessionID) return undefined;
let messages: ReadonlyArray<TuiMessageInfo>;
try {
const list = api.state?.session?.messages(sessionID);
if (!Array.isArray(list)) return undefined;
messages = list;
} catch {
return undefined;
}
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);
}
return summarizeTotals(totals);
}
function safeSessionGet(api: TuiApi, sessionID: string): TuiSessionInfo | undefined {
try {
return api.state?.session?.get?.(sessionID);
} catch {
return undefined;
}
}
/**
* Prefer the child session's aggregate tokens (the v2 store exposes them), and fall back to
* summing its assistant messages when the aggregate is absent. Mirrors sessionCacheSummary so
* parent and descendant numbers use the same math.
*/
async function addChildTokens(api: TuiApi, child: TuiSessionInfo, totals: TokenTotals): Promise<void> {
const aggregate = safeSessionGet(api, child.id)?.tokens ?? child.tokens;
if (aggregate) {
addMessageTokens(totals, aggregate);
return;
}
const client = api.client;
if (!client?.session?.messages) return;
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)));
}
}
/**
* 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.
@ -309,7 +233,28 @@ async function collectFamily(api: TuiApi, rootID: string): Promise<CacheSummary
visited.add(child.id);
next.push(child.id);
counted++;
await addChildTokens(api, child, totals);
// 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;
@ -328,56 +273,6 @@ type TokenView = {
empty: boolean;
};
function combineTokens(main: CacheSummary | undefined, sub: CacheSummary | undefined): TokenView {
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,
};
}
function formatIn(view: TokenView): string {
if (view.empty) return "in: --";
const delta = view.hasSub ? ` (+${view.subInput.toLocaleString()})` : "";
return `in: ${view.input.toLocaleString()}${delta}`;
}
function formatOut(view: TokenView): string {
if (view.empty) return "out: --";
const delta = view.hasSub ? ` (+${view.subOutput.toLocaleString()})` : "";
return `out: ${view.output.toLocaleString()}${delta}`;
}
function formatHit(view: TokenView): string {
if (view.empty || view.hit === undefined) return "hit: --";
return `hit: ${view.hit.toFixed(1)}%`;
}
function quotaIntervalMs(): number {
const raw = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_QUOTA_INTERVAL_MS;
}
function formatClock(ms: number): string {
if (!(ms > 0)) return "--:--:--";
return new Date(ms).toTimeString().slice(0, 8);
}
function shortWindow(w: QuotaWindow, nowMs: number): string {
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
const reset = formatReset(w.resetAtMs, nowMs);
const tail = reset ? ` · ${reset}` : "";
const amount = w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
return `${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${tail}`;
}
export const tui = async (api: TuiApi): Promise<void> => {
const [toggles, setToggles] = createSignal(readToggles());
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
@ -394,8 +289,6 @@ export const tui = async (api: TuiApi): Promise<void> => {
let familyRequestId = 0;
let familyTimer: ReturnType<typeof setTimeout> | undefined;
const refresh = (): void => setToggles(readToggles());
const refreshQuota = async (): Promise<void> => {
if (inflight) {
pending = true;
@ -490,49 +383,50 @@ export const tui = async (api: TuiApi): Promise<void> => {
});
};
function tone(w: QuotaWindow, theme: TuiTheme): unknown {
if (w.exceeded || percent(w.used, w.cap) >= 100) return theme.current.error;
if (percent(w.used, w.cap) >= 80) return theme.current.warning;
return theme.current.success;
/**
* 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;
}
// Reads quota()/now() inside the JSX so Solid tracks the signals. Hoisting
// `quota()` 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.
const windowsOf = (result: QuotaResult | null): QuotaWindow[] =>
result?.ok === true ? result.quota.windows : [];
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;
const Status = () => {
const theme = api.theme;
const view = () => combineTokens(sessionCacheSummary(api, sessionId()), family());
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}>{formatIn(view())}</text>
<text fg={theme.current.textMuted}>{formatOut(view())}</text>
<text fg={theme.current.textMuted}>{formatHit(view())}</text>
{windowsOf(quota()).map((w) => (
<text fg={tone(w, theme)}>{shortWindow(w, now())}</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 @ {formatClock(updatedAt())}</text>
</box>
);
};
api.slots.register({
order: SIDEBAR_ORDER,
slots: {
@ -544,7 +438,64 @@ export const tui = async (api: TuiApi): Promise<void> => {
scheduleFamilyRefresh(id);
}
if (id !== undefined) setSessionId(id);
return <Status />;
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>
);
},
},
});
@ -620,12 +571,13 @@ export const tui = async (api: TuiApi): Promise<void> => {
});
void refreshQuota();
const toggleTimer = setInterval(refresh, 1500);
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());
}, quotaIntervalMs());
}, 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);

View File

@ -16,5 +16,5 @@
"jsx": "preserve",
"noEmit": true
},
"include": ["src/tui.tsx", "src/tui-shims.d.ts", "src/quota.ts", "src/toggles.ts", "src/redact.ts", "src/constants.ts"]
"include": ["src/tui.tsx", "src/tui-shims.d.ts", "src/quota.ts", "src/toggles.ts", "src/log.ts", "src/redact.ts", "src/constants.ts"]
}