refactor function usage: inline single-use helpers, dedupe script config lookup
This commit is contained in:
parent
2532df4963
commit
1c74e81355
@ -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/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.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.
|
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).
|
tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles/log) against the shim (no dependencies).
|
||||||
src/constants.ts Defaults, paths, headers, passthrough params, static config block.
|
src/constants.ts Defaults, paths, headers, static config block.
|
||||||
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 -> provider.commandcode-go.models generator (with vision probing).
|
||||||
|
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture / data flow
|
## Architecture / data flow
|
||||||
|
|||||||
@ -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/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/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/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 provider.commandcode-go.models.
|
||||||
|
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
|
||||||
```
|
```
|
||||||
|
|
||||||
### Request lifecycle
|
### Request lifecycle
|
||||||
|
|||||||
@ -17,6 +17,7 @@
|
|||||||
"src/tui-shims.d.ts",
|
"src/tui-shims.d.ts",
|
||||||
"src/toggles.ts",
|
"src/toggles.ts",
|
||||||
"src/quota.ts",
|
"src/quota.ts",
|
||||||
|
"src/log.ts",
|
||||||
"src/redact.ts",
|
"src/redact.ts",
|
||||||
"src/constants.ts"
|
"src/constants.ts"
|
||||||
],
|
],
|
||||||
|
|||||||
29
scripts/opencode-config.mjs
Normal file
29
scripts/opencode-config.mjs
Normal 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;
|
||||||
|
}
|
||||||
@ -3,19 +3,20 @@
|
|||||||
// the headless check and does not need opencode running.
|
// 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)
|
// 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 { homedir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { fetchQuota, formatQuota } from "../dist/quota.js";
|
import { fetchQuota, formatQuota } from "../dist/quota.js";
|
||||||
import { PROVIDER_ID } from "../dist/constants.js";
|
import { PROVIDER_ID } from "../dist/constants.js";
|
||||||
|
import { readConfig, resolveKey } from "./opencode-config.mjs";
|
||||||
|
|
||||||
function parseArgs(argv) {
|
const opts = {
|
||||||
const opts = {
|
|
||||||
config: join(homedir(), ".config", "opencode", "opencode.json"),
|
config: join(homedir(), ".config", "opencode", "opencode.json"),
|
||||||
baseURL: undefined,
|
baseURL: undefined,
|
||||||
json: false,
|
json: false,
|
||||||
};
|
};
|
||||||
for (let i = 0; i < argv.length; i++) {
|
|
||||||
|
const argv = process.argv.slice(2);
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
const arg = argv[i];
|
const arg = argv[i];
|
||||||
const value = () => {
|
const value = () => {
|
||||||
const next = argv[++i];
|
const next = argv[++i];
|
||||||
@ -49,31 +50,15 @@ function parseArgs(argv) {
|
|||||||
default:
|
default:
|
||||||
throw new Error(`Unknown argument: ${arg}`);
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return opts;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function readConfig(path) {
|
let config = {};
|
||||||
try {
|
try {
|
||||||
return JSON.parse(readFileSync(path, "utf8"));
|
config = readConfig(opts.config).data;
|
||||||
} catch {
|
} 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);
|
const apiKey = resolveKey(config, process.env);
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
console.error(
|
console.error(
|
||||||
|
|||||||
@ -5,19 +5,17 @@ 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";
|
||||||
|
|
||||||
function apiKey() {
|
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
|
||||||
if (process.env.COMMANDCODE_API_KEY) return process.env.COMMANDCODE_API_KEY;
|
let key = process.env.COMMANDCODE_API_KEY;
|
||||||
|
if (!key) {
|
||||||
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
||||||
try {
|
try {
|
||||||
const cfg = JSON.parse(readFileSync(configPath, "utf8"));
|
const cfg = JSON.parse(readFileSync(configPath, "utf8"));
|
||||||
return cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
|
key = cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
key = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
|
|
||||||
const key = apiKey();
|
|
||||||
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 provider.${PROVIDER_ID}.options.apiKey`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
@ -7,13 +7,14 @@
|
|||||||
// the result into the global opencode config. Deselecting a model removes it from the config.
|
// 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)
|
// 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 { homedir } from "node:os";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
import readline from "node:readline";
|
import readline from "node:readline";
|
||||||
import { createCommandCode } from "../dist/index.js";
|
import { createCommandCode } from "../dist/index.js";
|
||||||
import { redact } from "../dist/redact.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 { 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 CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json");
|
||||||
const CONSOLE_URL = "https://commandcode.ai/studio/provider";
|
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.
|
// 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;
|
||||||
|
|
||||||
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) {
|
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);
|
||||||
@ -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).
|
// 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
|
// 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).
|
// 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.
|
// Selected rows render green (both lines); the cursor row renders bold on top.
|
||||||
const code = selected ? (active ? "1;32" : "32") : active ? "1" : undefined;
|
const code = selected ? (active ? "1;32" : "32") : active ? "1" : undefined;
|
||||||
line(`${active ? "\u203a" : " "} [${mark}] ${model.id} \u2014 ${model.name ?? model.id}${current}`, code);
|
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("");
|
||||||
line("\u2191/\u2193 navigate · space toggle · ctrl-a all · ctrl-u none · esc back/abort · enter confirm");
|
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}`);
|
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
|
||||||
let catalog;
|
let catalog;
|
||||||
try {
|
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) {
|
} catch (error) {
|
||||||
console.error(`Failed to fetch catalog: ${error instanceof Error ? error.message : String(error)}`);
|
console.error(`Failed to fetch catalog: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@ -440,12 +359,24 @@ 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 (${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 = await mapPool(selected, CONCURRENCY, async (model, index) => {
|
const probeResults = new Array(selected.length);
|
||||||
const outcome = await probeVisionConfirmed(provider, model.id);
|
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";
|
const tag = outcome.vision === true ? "vision" : outcome.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} (${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
|
// 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.
|
||||||
@ -464,7 +395,17 @@ async function main() {
|
|||||||
stats.unknown++;
|
stats.unknown++;
|
||||||
if (vision) stats.heuristic++;
|
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;
|
const removed = [...existingIds].filter((id) => !(id in merged)).length;
|
||||||
@ -473,11 +414,21 @@ async function main() {
|
|||||||
config.provider[PROVIDER_ID] ??= {};
|
config.provider[PROVIDER_ID] ??= {};
|
||||||
config.provider[PROVIDER_ID].models = merged;
|
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" : "";
|
const trailing = text === "" || text.endsWith("\n") ? "\n" : "";
|
||||||
// The config directory may not exist yet on a fresh install; create it before the atomic write.
|
// The config directory may not exist yet on a fresh install; create it before the atomic write.
|
||||||
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
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(
|
console.log(
|
||||||
`Wrote ${Object.keys(merged).length} models to ${CONFIG_PATH}\n` +
|
`Wrote ${Object.keys(merged).length} models to ${CONFIG_PATH}\n` +
|
||||||
|
|||||||
@ -18,18 +18,6 @@ export const DEFAULT_MAX_RETRIES = 2;
|
|||||||
export const BASE_RETRY_DELAY = 0.5;
|
export const BASE_RETRY_DELAY = 0.5;
|
||||||
export const DEFAULT_RETRY_MAX_DELAY = 60;
|
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 = {
|
export const STATIC_CONFIG = {
|
||||||
workingDir: "",
|
workingDir: "",
|
||||||
date: "",
|
date: "",
|
||||||
|
|||||||
37
src/log.ts
37
src/log.ts
@ -10,43 +10,34 @@ import { debugEnabled } from "./toggles.js";
|
|||||||
|
|
||||||
const FILE = join(tmpdir(), "commandcode-debug.log");
|
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;
|
if (typeof value === "string") return value;
|
||||||
try {
|
try {
|
||||||
return JSON.stringify(value);
|
return JSON.stringify(value);
|
||||||
} catch {
|
} catch {
|
||||||
return String(value);
|
return String(value);
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
|
|
||||||
function emit(scope: string, args: unknown[]): void {
|
|
||||||
const parts = args.map(serialize);
|
|
||||||
const line = `[commandcode] ${new Date().toISOString()} [${scope}] ${parts.join(" ")}`;
|
const line = `[commandcode] ${new Date().toISOString()} [${scope}] ${parts.join(" ")}`;
|
||||||
try {
|
try {
|
||||||
appendFileSync(FILE, redact(line) + "\n", "utf8");
|
appendFileSync(FILE, redact(line) + "\n", "utf8");
|
||||||
} catch {
|
} 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 {
|
try {
|
||||||
process.stderr.write(redact(line) + "\n");
|
process.stderr.write(redact(line) + "\n");
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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);
|
|
||||||
}
|
}
|
||||||
|
|||||||
186
src/model.ts
186
src/model.ts
@ -26,28 +26,10 @@ import { zdrEnabled } from "./toggles.js";
|
|||||||
import { transform } from "./transform.js";
|
import { 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";
|
||||||
|
|
||||||
// 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 {
|
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
|
||||||
return options.providerOptions?.[PROVIDER_ID] as 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 {
|
function resolveDebug(options: LanguageModelV3CallOptions): boolean {
|
||||||
const scoped = providerScoped(options)?.["debug"];
|
const scoped = providerScoped(options)?.["debug"];
|
||||||
return typeof scoped === "boolean" ? scoped : isDebugEnabled();
|
return typeof scoped === "boolean" ? scoped : isDebugEnabled();
|
||||||
@ -79,26 +61,6 @@ function headerValue(headers: Record<string, string | undefined>, key: string):
|
|||||||
return undefined;
|
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 {
|
function zeroUsage(): LanguageModelV3Usage {
|
||||||
return {
|
return {
|
||||||
inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
|
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.
|
// CommandCode's gateway marks these with `statusCode`/`isRetryable`; retry before content.
|
||||||
type StreamErrorInfo = { message: string; statusCode?: number; isRetryable?: boolean };
|
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;
|
// 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.
|
// once real output appears a retry would duplicate the response.
|
||||||
const STREAM_PREAMBLE = new Set(["start", "start-step"]);
|
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));
|
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 {
|
class CommandCodeLanguageModel implements LanguageModelV3 {
|
||||||
readonly specificationVersion = "v3" as const;
|
readonly specificationVersion = "v3" as const;
|
||||||
readonly provider: string;
|
readonly provider: string;
|
||||||
@ -205,11 +125,23 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
|
|
||||||
supportedUrls: Record<string, RegExp[]> = {};
|
supportedUrls: Record<string, RegExp[]> = {};
|
||||||
|
|
||||||
private requestHeaders(
|
private async fetchWithRetry(
|
||||||
extra: Record<string, string | undefined> | undefined,
|
body: string,
|
||||||
zdr: string | undefined,
|
options: LanguageModelV3CallOptions,
|
||||||
dbg: boolean,
|
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> = {
|
const headers: Record<string, string> = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"x-command-code-version": this.opts.ccVersion,
|
"x-command-code-version": this.opts.ccVersion,
|
||||||
@ -221,18 +153,10 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
};
|
};
|
||||||
if (zdr !== undefined) headers["x-cmd-zdr"] = zdr;
|
if (zdr !== undefined) headers["x-cmd-zdr"] = zdr;
|
||||||
debugWhen(dbg, "fetch", "zdr", zdr === "1" ? "on" : "off");
|
debugWhen(dbg, "fetch", "zdr", zdr === "1" ? "on" : "off");
|
||||||
const auth = bearer(this.opts.apiKey);
|
const apiKey = this.opts.apiKey;
|
||||||
if (auth) headers["Authorization"] = auth;
|
if (apiKey) headers["Authorization"] = /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`;
|
||||||
for (const [k, v] of Object.entries(extra ?? {})) if (v !== undefined) headers[k] = v;
|
for (const [k, v] of Object.entries(options.headers ?? {})) if (v !== undefined) headers[k] = v;
|
||||||
return headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
let lastError: unknown;
|
||||||
const url = `${this.opts.baseURL}${GENERATE_PATH}`;
|
const url = `${this.opts.baseURL}${GENERATE_PATH}`;
|
||||||
|
|
||||||
@ -307,9 +231,21 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
|
|||||||
if (next.done) break;
|
if (next.done) break;
|
||||||
const evt = next.value;
|
const evt = next.value;
|
||||||
prefix.push(evt);
|
prefix.push(evt);
|
||||||
const info = streamErrorInfo(evt);
|
if (evt?.["type"] === "error") {
|
||||||
if (info) {
|
const err = evt["error"];
|
||||||
if (isRetryableStreamError(info) && attempt < this.opts.maxRetries) streamRetry = info;
|
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;
|
break;
|
||||||
}
|
}
|
||||||
if (!STREAM_PREAMBLE.has(evt["type"])) 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");
|
throw lastError instanceof Error ? lastError : new Error("Upstream unreachable");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async errorFrom(response: Response, dbg: boolean): Promise<Error> {
|
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
|
||||||
let body = "";
|
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 {
|
try {
|
||||||
body = await response.text();
|
responseBody = await response.text();
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
let message = body;
|
let message = responseBody;
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(body);
|
const parsed = JSON.parse(responseBody);
|
||||||
const err = parsed?.error;
|
const err = parsed?.error;
|
||||||
if (typeof err === "string") message = err;
|
if (typeof err === "string") message = err;
|
||||||
else if (err && typeof err === "object" && typeof err.message === "string") message = err.message;
|
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}`);
|
const surfaced = redact(message.slice(0, 2000) || `Upstream returned ${response.status}`);
|
||||||
debugWhen(dbg, "error", `status=${response.status}`, `body=${surfaced}`);
|
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}`);
|
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 {
|
return {
|
||||||
stream,
|
stream,
|
||||||
request: { body: JSON.parse(body) as unknown },
|
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 = {}): {
|
export function createCommandCode(options: CommandCodeOptions = {}): {
|
||||||
languageModel(modelId: string): LanguageModelV3;
|
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 {
|
return {
|
||||||
languageModel(modelId: string) {
|
languageModel(modelId: string) {
|
||||||
return new CommandCodeLanguageModel(modelId, resolved);
|
return new CommandCodeLanguageModel(modelId, resolved);
|
||||||
|
|||||||
73
src/quota.ts
73
src/quota.ts
@ -370,46 +370,41 @@ export function formatReset(resetAtMs: number | null, now: number = Date.now()):
|
|||||||
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
|
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatTokens(tokens: number): string {
|
/** Human-readable multi-line quota summary for the `/cc-usage` command and CLI. */
|
||||||
if (tokens >= 1_000_000_000) return `${(tokens / 1_000_000_000).toFixed(1)}B`;
|
export function formatQuota(quota: Quota, now: number = Date.now()): string {
|
||||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
const lines: string[] = [];
|
||||||
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
|
lines.push(quota.account.keyName ?? quota.account.login);
|
||||||
return String(tokens);
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatWindowLine(w: QuotaWindow, now: number): string {
|
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}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quota.windows.length > 0) {
|
||||||
|
lines.push("");
|
||||||
|
for (const w of quota.windows) {
|
||||||
const pct = Math.min(percent(w.used, w.cap), 999);
|
const pct = Math.min(percent(w.used, w.cap), 999);
|
||||||
const reset = formatReset(w.resetAtMs, now);
|
const reset = formatReset(w.resetAtMs, now);
|
||||||
const amount =
|
const amount =
|
||||||
w.id === "monthly"
|
w.id === "monthly"
|
||||||
? `$${w.used.toFixed(2)} / $${w.cap.toFixed(2)}`
|
? `$${w.used.toFixed(2)} / $${w.cap.toFixed(2)}`
|
||||||
: `${w.used.toFixed(2)} / ${w.cap.toFixed(2)} credits`;
|
: `${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})` : ""
|
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) {
|
if (quota.credits) {
|
||||||
@ -420,7 +415,19 @@ export function formatQuota(quota: Quota, now: number = Date.now()): string {
|
|||||||
|
|
||||||
if (quota.summary) {
|
if (quota.summary) {
|
||||||
const period = quota.plan?.currentPeriodStart ? "this billing period" : "total";
|
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(
|
lines.push(
|
||||||
`Usage: ${quota.summary.totalCount.toLocaleString("en-US")} requests · $${quota.summary.totalCost.toFixed(2)} (${period})${tokens}`,
|
`Usage: ${quota.summary.totalCount.toLocaleString("en-US")} requests · $${quota.summary.totalCost.toFixed(2)} (${period})${tokens}`,
|
||||||
);
|
);
|
||||||
|
|||||||
@ -30,8 +30,9 @@ export function readToggles(): Toggles {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeToggles(patch: Toggles): Toggles {
|
export function toggle(name: ToggleName): Toggles {
|
||||||
const merged = { ...readToggles(), ...patch };
|
const current = readToggles();
|
||||||
|
const merged = { ...current, [name]: current[name] !== true };
|
||||||
const path = togglesPath();
|
const path = togglesPath();
|
||||||
mkdirSync(dirname(path), { recursive: true });
|
mkdirSync(dirname(path), { recursive: true });
|
||||||
const tmp = `${path}.${process.pid}.tmp`;
|
const tmp = `${path}.${process.pid}.tmp`;
|
||||||
@ -40,11 +41,6 @@ export function writeToggles(patch: Toggles): Toggles {
|
|||||||
return merged;
|
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. */
|
/** Toggle state from the shared flag file; an absent key means off. */
|
||||||
export function zdrEnabled(): boolean {
|
export function zdrEnabled(): boolean {
|
||||||
return readToggles().zdr === true;
|
return readToggles().zdr === true;
|
||||||
|
|||||||
271
src/transform.ts
271
src/transform.ts
@ -1,55 +1,12 @@
|
|||||||
import type {
|
import type {
|
||||||
LanguageModelV3CallOptions,
|
LanguageModelV3CallOptions,
|
||||||
LanguageModelV3FunctionTool,
|
LanguageModelV3FunctionTool,
|
||||||
LanguageModelV3ToolResultOutput,
|
|
||||||
LanguageModelV3ToolResultPart,
|
LanguageModelV3ToolResultPart,
|
||||||
} from "@ai-sdk/provider";
|
} 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>;
|
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 {
|
function stringify(value: unknown): string {
|
||||||
if (typeof value === "string") return value;
|
if (typeof value === "string") return value;
|
||||||
try {
|
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). */
|
/** 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): string {
|
||||||
const systemParts: string[] = [];
|
const systemParts: string[] = [];
|
||||||
const messages: Array<Record<string, unknown>> = [];
|
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) {
|
for (const message of options.prompt) {
|
||||||
if (message.role === "system") {
|
if (message.role === "system") {
|
||||||
@ -171,6 +56,49 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
|
|||||||
for (const part of message.content) {
|
for (const part of message.content) {
|
||||||
if (part.type !== "tool-result") continue;
|
if (part.type !== "tool-result") continue;
|
||||||
if (!paired.has(part.toolCallId)) 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({
|
messages.push({
|
||||||
role: "tool",
|
role: "tool",
|
||||||
content: [
|
content: [
|
||||||
@ -178,7 +106,7 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
|
|||||||
type: "tool-result",
|
type: "tool-result",
|
||||||
toolCallId: part.toolCallId,
|
toolCallId: part.toolCallId,
|
||||||
toolName: part.toolName ?? toolNames.get(part.toolCallId) ?? "unknown",
|
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") {
|
if (part.type === "text") {
|
||||||
parts.push({ type: "text", text: part.text });
|
parts.push({ type: "text", text: part.text });
|
||||||
} else if (part.type === "file") {
|
} else if (part.type === "file") {
|
||||||
if (part.mediaType?.startsWith("image/")) {
|
const mediaType = part.mediaType;
|
||||||
const img = imagePart((part as { data?: unknown }).data, part.mediaType);
|
if (mediaType?.startsWith("image/")) {
|
||||||
if (img) parts.push(img);
|
// 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 {
|
} else {
|
||||||
parts.push({ type: "text", text: `[file: ${part.filename ?? part.mediaType}]` });
|
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 });
|
messages.push({ role: "user", content: parts });
|
||||||
}
|
}
|
||||||
|
|
||||||
const mapped = mapTools(options.tools);
|
const tools: Array<Record<string, unknown>> = [];
|
||||||
const { tools, toolChoice } = applyToolChoice(mapped, options.toolChoice);
|
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 params: Record<string, unknown> = { model: modelId };
|
||||||
const systemText = systemParts.filter(Boolean).join("\n\n");
|
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.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 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;
|
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({
|
return JSON.stringify({
|
||||||
config,
|
config,
|
||||||
@ -265,5 +236,3 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
|
|||||||
params,
|
params,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export { PASSTHROUGH_PARAMS };
|
|
||||||
|
|||||||
1
src/tui-shims.d.ts
vendored
1
src/tui-shims.d.ts
vendored
@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
declare module "solid-js" {
|
declare module "solid-js" {
|
||||||
export function createSignal<Value>(value: Value): [get: () => Value, set: (value: Value) => void];
|
export function createSignal<Value>(value: Value): [get: () => Value, set: (value: Value) => void];
|
||||||
|
export function createMemo<Value>(fn: () => Value): () => Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare namespace JSX {
|
declare namespace JSX {
|
||||||
|
|||||||
310
src/tui.tsx
310
src/tui.tsx
@ -14,13 +14,11 @@
|
|||||||
// `namespace: "palette"` command list, so these entries appear in both; `hidden: true`
|
// `namespace: "palette"` command list, so these entries appear in both; `hidden: true`
|
||||||
// would remove them from both.
|
// would remove them from both.
|
||||||
|
|
||||||
import { appendFileSync } from "node:fs";
|
import { createMemo, createSignal } from "solid-js";
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { 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 { PROVIDER_ID } from "./constants.js";
|
||||||
|
import { debugWhen } from "./log.js";
|
||||||
import { redact } from "./redact.js";
|
import { redact } from "./redact.js";
|
||||||
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "./toggles.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. */
|
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
|
||||||
function trace(...args: unknown[]): void {
|
function trace(...args: unknown[]): void {
|
||||||
if (!debugEnabled()) return;
|
debugWhen(debugEnabled(), "tui-quota", ...args);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function state(value: boolean | undefined): string {
|
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 {
|
try {
|
||||||
const list = api.state?.provider;
|
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.
|
// 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 {
|
} catch {
|
||||||
/* fall through */
|
/* fall through */
|
||||||
}
|
}
|
||||||
return [];
|
const provider = providers.find((entry) => entry?.id === PROVIDER_ID);
|
||||||
}
|
|
||||||
|
|
||||||
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
|
|
||||||
const provider = providersOf(api).find((entry) => entry?.id === PROVIDER_ID);
|
|
||||||
const options = commandCodeOptions(api);
|
const options = commandCodeOptions(api);
|
||||||
const headers = options?.["headers"] as Record<string, unknown> | undefined;
|
const headers = options?.["headers"] as Record<string, unknown> | undefined;
|
||||||
const named: Array<[string, unknown]> = [
|
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
|
* 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.
|
* `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);
|
visited.add(child.id);
|
||||||
next.push(child.id);
|
next.push(child.id);
|
||||||
counted++;
|
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;
|
frontier = next;
|
||||||
@ -328,56 +273,6 @@ type TokenView = {
|
|||||||
empty: boolean;
|
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> => {
|
export const tui = async (api: TuiApi): Promise<void> => {
|
||||||
const [toggles, setToggles] = createSignal(readToggles());
|
const [toggles, setToggles] = createSignal(readToggles());
|
||||||
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
|
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
|
||||||
@ -394,8 +289,6 @@ export const tui = async (api: TuiApi): Promise<void> => {
|
|||||||
let familyRequestId = 0;
|
let familyRequestId = 0;
|
||||||
let familyTimer: ReturnType<typeof setTimeout> | undefined;
|
let familyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
const refresh = (): void => setToggles(readToggles());
|
|
||||||
|
|
||||||
const refreshQuota = async (): Promise<void> => {
|
const refreshQuota = async (): Promise<void> => {
|
||||||
if (inflight) {
|
if (inflight) {
|
||||||
pending = true;
|
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;
|
* Session-cumulative token accounting from the reactive session store opencode's built-in
|
||||||
if (percent(w.used, w.cap) >= 80) return theme.current.warning;
|
* context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
|
||||||
return theme.current.success;
|
* 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) {
|
||||||
// Reads quota()/now() inside the JSX so Solid tracks the signals. Hoisting
|
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
||||||
// `quota()` into a `const` above the return would subscribe once under a
|
for (const message of messages) {
|
||||||
// non-tracking owner (the slot re-invokes the handler on session change,
|
if (message?.role !== "assistant") continue;
|
||||||
// which is why /session "fixed" it) and freeze the panel after first paint.
|
addMessageTokens(totals, message.tokens);
|
||||||
const windowsOf = (result: QuotaResult | null): QuotaWindow[] =>
|
}
|
||||||
result?.ok === true ? result.quota.windows : [];
|
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 =>
|
const errorOf = (result: QuotaResult | null): string | undefined =>
|
||||||
result?.ok === false ? result.error.message : 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({
|
api.slots.register({
|
||||||
order: SIDEBAR_ORDER,
|
order: SIDEBAR_ORDER,
|
||||||
slots: {
|
slots: {
|
||||||
@ -544,7 +438,64 @@ export const tui = async (api: TuiApi): Promise<void> => {
|
|||||||
scheduleFamilyRefresh(id);
|
scheduleFamilyRefresh(id);
|
||||||
}
|
}
|
||||||
if (id !== undefined) setSessionId(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();
|
void refreshQuota();
|
||||||
const toggleTimer = setInterval(refresh, 1500);
|
const toggleTimer = setInterval(() => setToggles(readToggles()), 1500);
|
||||||
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
|
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
|
||||||
|
const configIntervalMs = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
|
||||||
const quotaTimer = setInterval(() => {
|
const quotaTimer = setInterval(() => {
|
||||||
void refreshQuota();
|
void refreshQuota();
|
||||||
void refreshFamily(sessionId());
|
void refreshFamily(sessionId());
|
||||||
}, quotaIntervalMs());
|
}, Number.isFinite(configIntervalMs) && configIntervalMs > 0 ? configIntervalMs : DEFAULT_QUOTA_INTERVAL_MS);
|
||||||
const unsubs = QUOTA_TRIGGER_EVENTS.map((type) =>
|
const unsubs = QUOTA_TRIGGER_EVENTS.map((type) =>
|
||||||
api.event.on(type, (event) => {
|
api.event.on(type, (event) => {
|
||||||
scheduleQuotaRefresh(event?.type ?? type);
|
scheduleQuotaRefresh(event?.type ?? type);
|
||||||
|
|||||||
@ -16,5 +16,5 @@
|
|||||||
"jsx": "preserve",
|
"jsx": "preserve",
|
||||||
"noEmit": true
|
"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"]
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user