@gururea/opencode-commandcode-provider 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # opencode-commandcode
1
+ # @gururea/opencode-commandcode-provider
2
2
 
3
3
  An [opencode](https://opencode.ai) plugin that adds the [Command Code](https://commandcode.ai) provider to the interface and its authentication to the `/connect` dialog.
4
4
 
@@ -11,7 +11,7 @@ Add the plugin to your `opencode.json`:
11
11
  ```json
12
12
  {
13
13
  "$schema": "https://opencode.ai/config.json",
14
- "plugin": ["opencode-commandcode"]
14
+ "plugin": ["@gururea/opencode-commandcode-provider"]
15
15
  }
16
16
  ```
17
17
 
@@ -25,12 +25,17 @@ Restart opencode, then:
25
25
 
26
26
  ## What the plugin does
27
27
 
28
- - **Registers the provider.** The plugin injects a `commandcode` custom provider into the opencode config (`@ai-sdk/openai-compatible`, base URL `https://api.commandcode.ai/provider/v1`). The model catalog is fetched live from the Provider API at startup; if the endpoint is unreachable, a built-in fallback catalog is used so the provider still appears.
28
+ - **Registers the provider.** The plugin injects a `commandcode` custom provider into the opencode config (`@ai-sdk/openai-compatible`, base URL `https://api.commandcode.ai/provider/v1`).
29
+ - **Live model discovery with caching.** The catalog is fetched from the Provider API at every startup. A successful fetch is cached to disk (`~/.cache/opencode/commandcode-models.json`) so the next start is fast and works offline; if both the endpoint and the cache are unavailable, a built-in fallback catalog keeps the provider visible.
29
30
  - **Adds authentication.** The `/connect` dialog gets two methods via the plugin `auth` hook:
30
31
  - **Browser login:** opens `commandcode.ai/studio/auth/cli` and receives the API key through a local callback server (fall back to pasting the key if the transfer fails).
31
32
  - **API key:** the standard key-paste dialog.
33
+ - **`commandcode_quota` tool / `/commandcode-quota`.** Reports your account usage and quota: remaining and used credits, plan, billing-period usage (cost, requests, tokens), and the 5-hour and weekly usage windows.
34
+ - **`commandcode_status` tool / `/commandcode-status`.** Shows plugin diagnostics: catalog source (live/cache/fallback), model count, last fetch time, endpoint, zero-data-retention setting, and version.
32
35
  - Command Code API keys (`user_...`) do not expire, so they are stored once and reused.
33
36
 
37
+ > The `/commandcode-quota` and `/commandcode-status` **tools** are registered by the plugin. The corresponding **slash commands** are provided as `.opencode/command/*.md` files in the package, which you can copy into your project's `.opencode/command/` directory if your opencode setup does not auto-discover package commands.
38
+
34
39
  ## Environment variables
35
40
 
36
41
  | Variable | Purpose |
@@ -38,6 +43,8 @@ Restart opencode, then:
38
43
  | `COMMAND_CODE_API_KEY` / `COMMANDCODE_API_KEY` | API key used as a fallback when no auth is stored via `/connect` |
39
44
  | `COMMANDCODE_API_BASE` | Override the provider API base URL (default `https://api.commandcode.ai/provider/v1`) |
40
45
  | `COMMANDCODE_MODELS_URL` | Override the model catalog URL (default `<api base>/models`) |
46
+ | `COMMANDCODE_MODELS_CACHE` | Override the model cache path (default `~/.cache/opencode/commandcode-models.json`) |
47
+ | `COMMANDCODE_MODELS_TIMEOUT_MS` | Model catalog fetch timeout (default `10000` ms) |
41
48
  | `CMD_ZDR=1` / `COMMANDCODE_ZDR=1` | Send the `x-cmd-zdr: 1` zero-data-retention header |
42
49
 
43
50
  ## Scope
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Show Command Code account usage and quota (credits, plan, usage)
3
+ ---
4
+
5
+ Use the **commandcode_quota** tool to fetch and report the user's Command Code account usage and quota. Summarize the credits remaining and used, the plan, the billing-period usage (cost, requests, tokens), and the 5-hour and weekly usage windows. If no API key is configured, tell the user to run `/connect` and select Command Code.
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Show Command Code plugin diagnostics (catalog source, model count, endpoint)
3
+ ---
4
+
5
+ Use the **commandcode_status** tool to fetch and report the Command Code plugin diagnostics: the model catalog source (live/cache/fallback), model count, when the catalog was last fetched, the API endpoint, the zero-data-retention setting, and the plugin version.
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ // src/index.ts
2
+ import { homedir } from "os";
3
+ import { join } from "path";
4
+
1
5
  // src/auth.ts
2
6
  import { randomBytes } from "crypto";
3
7
 
@@ -233,10 +237,519 @@ function createAuthHook(options = {}) {
233
237
  };
234
238
  }
235
239
 
240
+ // src/quota-tool.ts
241
+ import { tool } from "@opencode-ai/plugin";
242
+
243
+ // src/api-key.ts
244
+ import { existsSync, readFileSync } from "fs";
245
+ var PROVIDER_ID = "commandcode";
246
+ function isRecord(value) {
247
+ return typeof value === "object" && value !== null && !Array.isArray(value);
248
+ }
249
+ function authKey(record) {
250
+ const type = record.type;
251
+ if (type === "api") return typeof record.key === "string" ? record.key : void 0;
252
+ if (type === "oauth") return typeof record.access === "string" ? record.access : void 0;
253
+ if (type === "wellknown") {
254
+ return typeof record.token === "string" ? record.token : typeof record.key === "string" ? record.key : void 0;
255
+ }
256
+ return void 0;
257
+ }
258
+ function credentialFromAuthJson(raw) {
259
+ try {
260
+ const parsed = JSON.parse(raw);
261
+ if (!isRecord(parsed)) return void 0;
262
+ const entry = parsed[PROVIDER_ID];
263
+ if (!isRecord(entry)) return void 0;
264
+ return authKey(entry);
265
+ } catch {
266
+ return void 0;
267
+ }
268
+ }
269
+ function defaultAuthPath() {
270
+ return `${process.env.HOME ?? ""}/.local/share/opencode/auth.json`;
271
+ }
272
+ function readCommandCodeKey(options = {}) {
273
+ const env = options.env ?? process.env;
274
+ if (env.COMMAND_CODE_API_KEY) return env.COMMAND_CODE_API_KEY;
275
+ if (env.COMMANDCODE_API_KEY) return env.COMMANDCODE_API_KEY;
276
+ const authContent = options.authContent ?? env.OPENCODE_AUTH_CONTENT;
277
+ if (authContent) {
278
+ const fromContent = credentialFromAuthJson(authContent);
279
+ if (fromContent) return fromContent;
280
+ }
281
+ const authPath = options.authPath ?? defaultAuthPath();
282
+ try {
283
+ if (!existsSync(authPath)) return void 0;
284
+ const raw = readFileSync(authPath, "utf-8");
285
+ return credentialFromAuthJson(raw);
286
+ } catch {
287
+ return void 0;
288
+ }
289
+ }
290
+
291
+ // src/redact.ts
292
+ function redactBearer(value) {
293
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [redacted]");
294
+ }
295
+ function redactCredentials(value) {
296
+ return value.replace(
297
+ /\b(?:api[-_ ]?key|apikey|access[-_ ]?token|refresh[-_ ]?token|token|secret|password|authorization)\s*[=:]\s*[^\s,;&)]+/gi,
298
+ (match) => {
299
+ const separatorIndex = match.search(/[=:]/);
300
+ return separatorIndex < 0 ? "[redacted]" : `${match.slice(0, separatorIndex + 1)}[redacted]`;
301
+ }
302
+ );
303
+ }
304
+ function redactUserTokens(value) {
305
+ return value.replace(/\b(?:user|cc)_[A-Za-z0-9_-]{8,}\b/gi, "[redacted]");
306
+ }
307
+ function redactQuerySecrets(value) {
308
+ return value.replace(
309
+ /([?&](?:api[-_ ]?key|apikey|access_token|refresh_token|token|secret|password)=)[^&#\s]+/gi,
310
+ "$1[redacted]"
311
+ );
312
+ }
313
+ function redactStandaloneSecrets(value) {
314
+ return value.replace(
315
+ /\b(?:sk|rk|ghp|github_pat|xox[baprs])[-_A-Za-z0-9]{16,}\b|\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
316
+ "[redacted]"
317
+ );
318
+ }
319
+ function redactCommandCodeErrorText(value) {
320
+ return redactStandaloneSecrets(
321
+ redactQuerySecrets(redactUserTokens(redactCredentials(redactBearer(value))))
322
+ );
323
+ }
324
+
325
+ // src/quota.ts
326
+ var DEFAULT_API_BASE = "https://api.commandcode.ai";
327
+ var QUOTA_TIMEOUT_MS = 15e3;
328
+ function isRecord2(value) {
329
+ return typeof value === "object" && value !== null && !Array.isArray(value);
330
+ }
331
+ function numberValue(value) {
332
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
333
+ }
334
+ function stringValue(value) {
335
+ return typeof value === "string" && value.length > 0 ? value : void 0;
336
+ }
337
+ function errorMessage(error) {
338
+ return error instanceof Error ? error.message : String(error);
339
+ }
340
+ function normalizeResetAt(value) {
341
+ let timestamp;
342
+ if (typeof value === "number" && Number.isFinite(value)) timestamp = value;
343
+ if (typeof value === "string" && value.length > 0) {
344
+ const trimmed = value.trim();
345
+ timestamp = /^\d+$/.test(trimmed) ? Number(trimmed) : Date.parse(trimmed);
346
+ }
347
+ if (timestamp === void 0 || !Number.isFinite(timestamp) || timestamp < 0) return null;
348
+ return timestamp >= 1e12 ? Math.round(timestamp / 1e3) : timestamp;
349
+ }
350
+ function windowLimitsFromCredits(value) {
351
+ if (!isRecord2(value)) return [];
352
+ const limits = [];
353
+ for (const [window, entry] of [
354
+ ["fiveHour", value.fiveHour],
355
+ ["weekly", value.weekly]
356
+ ]) {
357
+ if (!isRecord2(entry)) continue;
358
+ const used = numberValue(entry.used);
359
+ const cap = numberValue(entry.cap);
360
+ if (used === void 0 || cap === void 0 || used === 0 && cap === 0) continue;
361
+ limits.push({ window, used, cap, resetAt: normalizeResetAt(entry.resetAt) });
362
+ }
363
+ return limits;
364
+ }
365
+ function parseCredits(value) {
366
+ if (!isRecord2(value) || !isRecord2(value.credits)) return null;
367
+ const credits = value.credits;
368
+ const monthlyCredits = numberValue(credits.monthlyCredits);
369
+ const purchasedCredits = numberValue(credits.purchasedCredits);
370
+ const freeCredits = numberValue(credits.freeCredits);
371
+ if (monthlyCredits === void 0 && purchasedCredits === void 0 && freeCredits === void 0) {
372
+ return null;
373
+ }
374
+ const monthly = monthlyCredits ?? 0;
375
+ const purchased = purchasedCredits ?? 0;
376
+ const free = freeCredits ?? 0;
377
+ return {
378
+ monthlyCredits: monthly,
379
+ purchasedCredits: purchased,
380
+ freeCredits: free,
381
+ remainingCredits: monthly + purchased + free,
382
+ windowLimits: windowLimitsFromCredits(value.windowLimits)
383
+ };
384
+ }
385
+ function parseSubscription(value) {
386
+ if (!isRecord2(value) || !isRecord2(value.data)) return null;
387
+ const data = value.data;
388
+ const planId = stringValue(data.planId);
389
+ const status = stringValue(data.status);
390
+ const currentPeriodStart = stringValue(data.currentPeriodStart);
391
+ const currentPeriodEnd = stringValue(data.currentPeriodEnd);
392
+ if (!planId && !status && !currentPeriodStart && !currentPeriodEnd) return null;
393
+ return {
394
+ planId: planId ?? null,
395
+ status: status ?? null,
396
+ currentPeriodStart: currentPeriodStart ?? null,
397
+ currentPeriodEnd: currentPeriodEnd ?? null
398
+ };
399
+ }
400
+ function parseSummary(value) {
401
+ if (!isRecord2(value)) return null;
402
+ const totalCost = numberValue(value.totalCost);
403
+ const totalCount = numberValue(value.totalCount);
404
+ if (totalCost === void 0 || totalCount === void 0) return null;
405
+ const totalTokens = numberValue(value.totalTokens) ?? numberValue(value.tokens);
406
+ return { totalCost, totalCount, ...totalTokens === void 0 ? {} : { totalTokens } };
407
+ }
408
+ function parseWhoami(value) {
409
+ if (!isRecord2(value)) return null;
410
+ const org = isRecord2(value.org) ? value.org : void 0;
411
+ const user = isRecord2(value.user) ? value.user : void 0;
412
+ const login = (org ? stringValue(org.login) : void 0) ?? (user ? stringValue(user.userName) ?? stringValue(user.name) : void 0);
413
+ if (!login) return null;
414
+ const orgId = org ? stringValue(org.id) : void 0;
415
+ const keyName = user ? stringValue(user.keyName) ?? stringValue(user.displayName) : void 0;
416
+ return { login, orgId: orgId ?? null, ...keyName ? { keyName } : {} };
417
+ }
418
+ function buildUrl(path, params) {
419
+ const search = new URLSearchParams();
420
+ for (const [key, value] of Object.entries(params)) {
421
+ if (value) search.set(key, value);
422
+ }
423
+ const query = search.toString();
424
+ return `${path}${query ? `?${query}` : ""}`;
425
+ }
426
+ function isHttpError(value) {
427
+ return isRecord2(value) && value.__httpError === true && typeof value.message === "string" && typeof value.status === "number" && typeof value.body === "string";
428
+ }
429
+ function isQuotaError(value) {
430
+ return isRecord2(value) && value.__quotaError === true && (value.kind === "timeout" || value.kind === "network");
431
+ }
432
+ function isBlockingHttpError(error) {
433
+ return error.status === 401 || error.status === 403;
434
+ }
435
+ function httpFailure(error, context) {
436
+ const detail = error.body.trim().slice(0, 200);
437
+ return {
438
+ ok: false,
439
+ error: {
440
+ kind: "http",
441
+ message: redactCommandCodeErrorText(
442
+ `${context} request failed (${error.status}): ${detail || error.message}`
443
+ )
444
+ }
445
+ };
446
+ }
447
+ var QuotaTimeoutError = class extends Error {
448
+ };
449
+ async function fetchCommandCodeQuota(options) {
450
+ if (!options.apiKey) {
451
+ return { ok: false, error: { message: "No Command Code API key found", kind: "config" } };
452
+ }
453
+ const baseUrl = options.baseUrl ?? DEFAULT_API_BASE;
454
+ const fetchImpl = options.fetchImpl ?? fetch;
455
+ const timeoutMs = options.timeoutMs ?? QUOTA_TIMEOUT_MS;
456
+ const overallController = new AbortController();
457
+ const overallTimer = setTimeout(() => overallController.abort(), timeoutMs);
458
+ const headers = {
459
+ accept: "application/json",
460
+ Authorization: `Bearer ${options.apiKey}`,
461
+ ...options.extraHeaders
462
+ };
463
+ const request = async (path) => {
464
+ if (overallController.signal.aborted) throw new QuotaTimeoutError();
465
+ try {
466
+ const response = await fetchImpl(`${baseUrl}${path}`, {
467
+ method: "GET",
468
+ headers,
469
+ signal: overallController.signal
470
+ });
471
+ if (!response.ok) {
472
+ return {
473
+ __httpError: true,
474
+ message: response.status === 401 || response.status === 403 ? "Command Code rejected the API key" : response.statusText,
475
+ status: response.status,
476
+ body: await response.text().catch(() => "")
477
+ };
478
+ }
479
+ return await response.json();
480
+ } catch (error) {
481
+ if (overallController.signal.aborted) throw new QuotaTimeoutError();
482
+ throw error;
483
+ }
484
+ };
485
+ const safeRequest = async (path) => {
486
+ try {
487
+ return await request(path);
488
+ } catch (error) {
489
+ return {
490
+ __quotaError: true,
491
+ kind: error instanceof QuotaTimeoutError ? "timeout" : "network"
492
+ };
493
+ }
494
+ };
495
+ try {
496
+ const whoamiRaw = await request("/alpha/whoami");
497
+ if (isHttpError(whoamiRaw)) return httpFailure(whoamiRaw, "whoami");
498
+ const account = parseWhoami(whoamiRaw);
499
+ if (!account) {
500
+ return {
501
+ ok: false,
502
+ error: { kind: "http", message: "Command Code returned an unrecognized account response" }
503
+ };
504
+ }
505
+ const orgId = account.orgId ?? void 0;
506
+ const [creditsRaw, subscriptionRaw] = await Promise.all([
507
+ safeRequest(buildUrl("/alpha/billing/credits", { orgId })),
508
+ safeRequest(buildUrl("/alpha/billing/subscriptions", { orgId }))
509
+ ]);
510
+ if (isHttpError(creditsRaw) && isBlockingHttpError(creditsRaw)) {
511
+ return httpFailure(creditsRaw, "credits");
512
+ }
513
+ if (isHttpError(subscriptionRaw) && isBlockingHttpError(subscriptionRaw)) {
514
+ return httpFailure(subscriptionRaw, "subscription");
515
+ }
516
+ const unavailable = [];
517
+ const credits = isHttpError(creditsRaw) || isQuotaError(creditsRaw) ? null : parseCredits(creditsRaw);
518
+ if (!credits) unavailable.push("credits");
519
+ const subscription = isHttpError(subscriptionRaw) || isQuotaError(subscriptionRaw) ? null : parseSubscription(subscriptionRaw);
520
+ if (!subscription) unavailable.push("subscription");
521
+ const summaryRaw = await safeRequest(
522
+ buildUrl("/alpha/usage/summary", {
523
+ orgId,
524
+ since: subscription?.currentPeriodStart ?? void 0
525
+ })
526
+ );
527
+ if (isHttpError(summaryRaw) && isBlockingHttpError(summaryRaw)) {
528
+ return httpFailure(summaryRaw, "summary");
529
+ }
530
+ const summary = isHttpError(summaryRaw) || isQuotaError(summaryRaw) ? null : parseSummary(summaryRaw);
531
+ if (!summary) unavailable.push("usage");
532
+ if (!credits && !subscription && !summary) {
533
+ return {
534
+ ok: false,
535
+ error: {
536
+ kind: overallController.signal.aborted ? "timeout" : "http",
537
+ message: overallController.signal.aborted ? "Command Code quota request timed out" : "Command Code returned no recognized usage data for the account"
538
+ }
539
+ };
540
+ }
541
+ return {
542
+ ok: true,
543
+ quota: {
544
+ account,
545
+ credits,
546
+ subscription,
547
+ summary,
548
+ ...unavailable.length > 0 ? { unavailable } : {}
549
+ }
550
+ };
551
+ } catch (error) {
552
+ if (error instanceof QuotaTimeoutError || overallController.signal.aborted) {
553
+ return {
554
+ ok: false,
555
+ error: { message: "Command Code quota request timed out", kind: "timeout" }
556
+ };
557
+ }
558
+ return {
559
+ ok: false,
560
+ error: {
561
+ message: redactCommandCodeErrorText(
562
+ `Failed to fetch Command Code quota: ${errorMessage(error)}`
563
+ ),
564
+ kind: "network"
565
+ }
566
+ };
567
+ } finally {
568
+ clearTimeout(overallTimer);
569
+ }
570
+ }
571
+
572
+ // src/quota-format.ts
573
+ function formatWindowLimits(limits, now = Date.now) {
574
+ const labels = {
575
+ fiveHour: "5-hour",
576
+ weekly: "Weekly"
577
+ };
578
+ return limits.map((limit) => {
579
+ const used = limit.used.toFixed(2);
580
+ const cap = limit.cap.toFixed(2);
581
+ const percent = limit.cap > 0 ? Math.round(limit.used / limit.cap * 100) : 0;
582
+ const reset = limit.resetAt === null ? "" : ` (resets ${formatResetClock(limit.resetAt, now)})`;
583
+ return `${labels[limit.window]}: ${used} / ${cap} credits (${percent}% used)${reset}`;
584
+ });
585
+ }
586
+ function formatResetClock(resetAtSeconds, now) {
587
+ const date = new Date(resetAtSeconds * 1e3);
588
+ if (Number.isNaN(date.getTime())) return "unknown";
589
+ const diffMs = date.getTime() - now();
590
+ if (diffMs <= 0) return "soon";
591
+ const minutes = Math.ceil(diffMs / 6e4);
592
+ if (minutes < 60) return `in ${minutes}m`;
593
+ const hours = Math.floor(minutes / 60);
594
+ const remainingMinutes = minutes % 60;
595
+ if (hours < 24) {
596
+ return remainingMinutes > 0 ? `in ${hours}h ${remainingMinutes}m` : `in ${hours}h`;
597
+ }
598
+ const days = Math.floor(hours / 24);
599
+ return days === 1 ? "in 1 day" : `in ${days} days`;
600
+ }
601
+ function creditsDetail(credits) {
602
+ if (!credits) return void 0;
603
+ const parts = [
604
+ `monthly $${credits.monthlyCredits.toFixed(2)}`,
605
+ `purchased $${credits.purchasedCredits.toFixed(2)}`
606
+ ];
607
+ if (credits.freeCredits > 0) parts.push(`free $${credits.freeCredits.toFixed(2)}`);
608
+ return `Sources: ${parts.join(" / ")}`;
609
+ }
610
+ function subscriptionLine(subscription) {
611
+ const plan = (subscription.planId ?? "Unknown").replace(/[_-]+/g, " ").trim();
612
+ const status = subscription.status ? ` (${subscription.status})` : "";
613
+ return `Plan: ${plan}${status}`;
614
+ }
615
+ function formatTokens(tokens) {
616
+ if (tokens >= 1e9) return `${(tokens / 1e9).toFixed(1)}B`;
617
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1)}M`;
618
+ if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1)}k`;
619
+ return String(tokens);
620
+ }
621
+ function formatQuota(quota, now = Date.now) {
622
+ const lines = [];
623
+ const remaining = quota.credits?.remainingCredits ?? 0;
624
+ const spent = quota.summary?.totalCost ?? 0;
625
+ const pool = remaining + spent;
626
+ if (quota.credits || quota.summary) {
627
+ lines.push("Credits");
628
+ lines.push(` Remaining: $${remaining.toFixed(2)} of $${pool.toFixed(2)}`);
629
+ lines.push(` Used: $${spent.toFixed(2)}`);
630
+ lines.push(` ${pool > 0 ? Math.round(spent / pool * 100) : 0}% used`);
631
+ }
632
+ const detail = creditsDetail(quota.credits);
633
+ if (detail) lines.push(detail);
634
+ if (quota.subscription) lines.push(subscriptionLine(quota.subscription));
635
+ if (quota.summary) {
636
+ lines.push("");
637
+ lines.push(quota.subscription?.currentPeriodStart ? "Usage (billing period)" : "Usage");
638
+ lines.push(` Cost: $${quota.summary.totalCost.toFixed(2)}`);
639
+ lines.push(` Requests: ${quota.summary.totalCount.toLocaleString("en-US")}`);
640
+ if (quota.summary.totalTokens !== void 0) {
641
+ lines.push(` Tokens: ${formatTokens(quota.summary.totalTokens)}`);
642
+ }
643
+ }
644
+ lines.push("");
645
+ lines.push("Account");
646
+ lines.push(` ${quota.account.keyName ?? quota.account.login}`);
647
+ const limits = quota.credits?.windowLimits ?? [];
648
+ if (limits.length > 0) {
649
+ lines.push("");
650
+ lines.push("Usage windows:");
651
+ lines.push(...formatWindowLimits(limits, now).map((line) => ` ${line}`));
652
+ }
653
+ if ((quota.unavailable?.length ?? 0) > 0) {
654
+ lines.push("");
655
+ lines.push(`Unavailable: ${quota.unavailable?.join(", ")}`);
656
+ }
657
+ lines.push("");
658
+ lines.push("Full detail: https://commandcode.ai/usage");
659
+ return lines.join("\n");
660
+ }
661
+
662
+ // src/quota-tool.ts
663
+ function createQuotaTool({ apiBase, extraHeaders, client, readKey }) {
664
+ const resolveKey = readKey ?? readCommandCodeKey;
665
+ const showToast = (message, variant) => {
666
+ client.tui.showToast({ body: { message, variant } }).catch(() => {
667
+ });
668
+ };
669
+ return {
670
+ commandcode_quota: tool({
671
+ description: "Show the user's Command Code account usage and quota: remaining and used credits, plan, billing-period usage, and usage windows.",
672
+ args: {},
673
+ async execute() {
674
+ const apiKey = resolveKey();
675
+ if (!apiKey) {
676
+ showToast(
677
+ "Command Code quota needs an API key. Run /connect and select Command Code.",
678
+ "error"
679
+ );
680
+ return {
681
+ title: "Command Code quota",
682
+ output: "No Command Code API key found. Run /connect and authenticate first."
683
+ };
684
+ }
685
+ const result = await fetchCommandCodeQuota({
686
+ apiKey,
687
+ baseUrl: apiBase,
688
+ extraHeaders
689
+ });
690
+ if (!result.ok) {
691
+ showToast(result.error.message, "error");
692
+ return { title: "Command Code quota", output: result.error.message };
693
+ }
694
+ const output = formatQuota(result.quota);
695
+ showToast("Command Code quota loaded.", "success");
696
+ return { title: "Command Code quota", output };
697
+ }
698
+ })
699
+ };
700
+ }
701
+
702
+ // src/status-tool.ts
703
+ import { tool as tool2 } from "@opencode-ai/plugin";
704
+
705
+ // src/status.ts
706
+ function formatStatus(input) {
707
+ const lines = [
708
+ "Command Code plugin status",
709
+ ` Source: ${input.source}`,
710
+ ` Models: ${input.modelCount}`,
711
+ ` Fetched: ${input.fetchedAt === void 0 ? "n/a" : new Date(input.fetchedAt).toISOString()}`,
712
+ ` Endpoint: ${input.apiBase}`,
713
+ ` Zero-data-retention: ${input.zdr ? "on" : "off"}`,
714
+ ` Version: ${input.version}`
715
+ ];
716
+ return lines.join("\n");
717
+ }
718
+
719
+ // src/status-tool.ts
720
+ function createStatusTool({
721
+ apiBase,
722
+ zdr,
723
+ version,
724
+ modelsInfo
725
+ }) {
726
+ return {
727
+ commandcode_status: tool2({
728
+ description: "Show Command Code plugin diagnostics: the model catalog source (live/cache/fallback), model count, cache time, endpoint, and zero-data-retention setting.",
729
+ args: {},
730
+ async execute() {
731
+ const output = formatStatus({
732
+ source: modelsInfo.source,
733
+ modelCount: modelsInfo.modelCount,
734
+ fetchedAt: modelsInfo.fetchedAt,
735
+ apiBase,
736
+ zdr,
737
+ version
738
+ });
739
+ return { title: "Command Code status", output };
740
+ }
741
+ })
742
+ };
743
+ }
744
+
236
745
  // src/models.ts
746
+ import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
747
+ import { dirname } from "path";
237
748
  var DEFAULT_PROVIDER_API_BASE = "https://api.commandcode.ai/provider/v1";
238
749
  var DEFAULT_MODELS_URL = `${DEFAULT_PROVIDER_API_BASE}/models`;
239
750
  var DEFAULT_MODELS_TIMEOUT_MS = 1e4;
751
+ var DEFAULT_MODELS_TTL_MS = 24 * 60 * 60 * 1e3;
752
+ var MODEL_CACHE_VERSION = 1;
240
753
  var DEFAULT_MAX_OUTPUT_TOKENS = 65536;
241
754
  var ZERO_MODEL_COST = {
242
755
  input: 0,
@@ -327,10 +840,10 @@ var MODEL_COSTS = {
327
840
  function modelCost(id) {
328
841
  return MODEL_COSTS[id] ?? ZERO_MODEL_COST;
329
842
  }
330
- function isOpenAiCompatibleModel(id) {
331
- return !id.startsWith("claude-");
843
+ function isAnthropicModel(id) {
844
+ return id.startsWith("claude-");
332
845
  }
333
- function isRecord(value) {
846
+ function isRecord3(value) {
334
847
  return typeof value === "object" && value !== null && !Array.isArray(value);
335
848
  }
336
849
  function stringField(record, key) {
@@ -348,11 +861,11 @@ function positiveNumberField(record, key) {
348
861
  return value;
349
862
  }
350
863
  function commandCodeModelsFromApiResponse(value) {
351
- if (!isRecord(value)) throw new Error("Expected models response to be an object");
864
+ if (!isRecord3(value)) throw new Error("Expected models response to be an object");
352
865
  if (value.object !== "list") throw new Error("Expected models response object to be 'list'");
353
866
  if (!Array.isArray(value.data)) throw new Error("Expected models response data to be an array");
354
867
  const models = value.data.map((entry) => {
355
- if (!isRecord(entry)) throw new Error("Expected model entry to be an object");
868
+ if (!isRecord3(entry)) throw new Error("Expected model entry to be an object");
356
869
  return {
357
870
  id: stringField(entry, "id"),
358
871
  name: stringField(entry, "name"),
@@ -365,11 +878,11 @@ function commandCodeModelsFromApiResponse(value) {
365
878
  function outputLimitForModel(id, contextLength) {
366
879
  return Math.min(contextLength, DEFAULT_MAX_OUTPUT_TOKENS);
367
880
  }
368
- function toProviderModelMap(models) {
881
+ function toProviderModelMap(models, providerBaseUrl2 = DEFAULT_PROVIDER_API_BASE) {
369
882
  const map = {};
370
883
  for (const model of models) {
371
- if (!isOpenAiCompatibleModel(model.id)) continue;
372
884
  const cost = modelCost(model.id);
885
+ const anthropic = isAnthropicModel(model.id);
373
886
  map[model.id] = {
374
887
  name: model.name,
375
888
  limit: {
@@ -381,11 +894,15 @@ function toProviderModelMap(models) {
381
894
  output: cost.output,
382
895
  cache_read: cost.cacheRead,
383
896
  cache_write: cost.cacheWrite
384
- }
897
+ },
898
+ ...anthropic ? { reasoning: true, provider: { npm: "@ai-sdk/anthropic", api: providerBaseUrl2 } } : {}
385
899
  };
386
900
  }
387
901
  return map;
388
902
  }
903
+ function errorMessage2(error) {
904
+ return error instanceof Error ? error.message : String(error);
905
+ }
389
906
  async function runWithTimeout(operation, timeoutMs, externalSignal) {
390
907
  const controller = new AbortController();
391
908
  let timer;
@@ -432,10 +949,110 @@ async function fetchCommandCodeModels(options = {}) {
432
949
  );
433
950
  return commandCodeModelsFromApiResponse(body);
434
951
  }
952
+ function cacheIsFresh(cachedAt, now, ttlMs) {
953
+ return now - cachedAt < ttlMs;
954
+ }
955
+ function commandCodeModelsFromCache(value) {
956
+ if (!isRecord3(value)) throw new Error("Expected model cache to be an object");
957
+ if (value.version !== MODEL_CACHE_VERSION) {
958
+ throw new Error(`Expected model cache version ${MODEL_CACHE_VERSION}`);
959
+ }
960
+ if (!Array.isArray(value.models)) throw new Error("Expected cached models to be an array");
961
+ const models = value.models.map((entry) => {
962
+ if (!isRecord3(entry)) throw new Error("Expected cached model entry to be an object");
963
+ return {
964
+ id: stringField(entry, "id"),
965
+ name: stringField(entry, "name"),
966
+ contextLength: positiveNumberField(entry, "contextLength")
967
+ };
968
+ });
969
+ if (models.length === 0) throw new Error("Expected cached models to be non-empty");
970
+ return models;
971
+ }
972
+ async function readCommandCodeModelsCache(cachePath) {
973
+ const contents = await readFile(cachePath, "utf-8");
974
+ return commandCodeModelsFromCache(JSON.parse(contents));
975
+ }
976
+ async function writeCommandCodeModelsCache(cachePath, models, fetchedAt = Date.now()) {
977
+ await mkdir(dirname(cachePath), { recursive: true });
978
+ const temporaryPath = `${cachePath}.${process.pid}.tmp`;
979
+ try {
980
+ await writeFile(
981
+ temporaryPath,
982
+ `${JSON.stringify({ version: MODEL_CACHE_VERSION, fetchedAt, models }, null, 2)}
983
+ `,
984
+ { encoding: "utf-8", mode: 384 }
985
+ );
986
+ await rename(temporaryPath, cachePath);
987
+ } finally {
988
+ try {
989
+ await rm(temporaryPath, { force: true });
990
+ } catch {
991
+ }
992
+ }
993
+ }
994
+ async function loadCommandCodeModels(options) {
995
+ const cachePath = options.cachePath;
996
+ const ttlMs = options.ttlMs ?? DEFAULT_MODELS_TTL_MS;
997
+ const now = options.now ?? Date.now;
998
+ try {
999
+ const models = await fetchCommandCodeModels(options);
1000
+ const fetchedAt = now();
1001
+ try {
1002
+ await writeCommandCodeModelsCache(cachePath, models, fetchedAt);
1003
+ return { models, source: "live", fetchedAt };
1004
+ } catch (error) {
1005
+ return {
1006
+ models,
1007
+ source: "live",
1008
+ fetchedAt,
1009
+ warning: `Loaded the live Command Code model catalog but could not write the cache at ${cachePath}: ${errorMessage2(error)}`
1010
+ };
1011
+ }
1012
+ } catch (liveError) {
1013
+ if (options.signal?.aborted) throw liveError;
1014
+ try {
1015
+ const cachedAt = await cachedTimestamp(cachePath);
1016
+ const models = await readCommandCodeModelsCache(cachePath);
1017
+ const stale = cachedAt !== null && !cacheIsFresh(cachedAt, now(), ttlMs);
1018
+ return {
1019
+ models,
1020
+ source: "cache",
1021
+ fetchedAt: cachedAt ?? void 0,
1022
+ warning: stale ? `Could not refresh the Command Code model catalog (${errorMessage2(liveError)}). Using a stale cached catalog from ${cachePath}.` : `Could not refresh the Command Code model catalog (${errorMessage2(liveError)}). Using the cached catalog from ${cachePath}.`
1023
+ };
1024
+ } catch (cacheError) {
1025
+ const fallback = options.fallbackModels ?? [];
1026
+ return {
1027
+ models: fallback,
1028
+ source: "fallback",
1029
+ warning: `Could not refresh the Command Code model catalog (${errorMessage2(liveError)}) and no valid cached catalog is available at ${cachePath} (${errorMessage2(cacheError)}). Using the built-in fallback catalog.`
1030
+ };
1031
+ }
1032
+ }
1033
+ }
1034
+ async function cachedTimestamp(cachePath) {
1035
+ try {
1036
+ const contents = await readFile(cachePath, "utf-8");
1037
+ const parsed = JSON.parse(contents);
1038
+ if (!isRecord3(parsed)) return null;
1039
+ return typeof parsed.fetchedAt === "number" && Number.isFinite(parsed.fetchedAt) ? parsed.fetchedAt : null;
1040
+ } catch {
1041
+ return null;
1042
+ }
1043
+ }
435
1044
 
436
1045
  // src/index.ts
437
- var PROVIDER_ID = "commandcode";
1046
+ var PROVIDER_ID2 = "commandcode";
1047
+ var PLUGIN_VERSION = "0.2.0";
438
1048
  var FALLBACK_MODELS = [
1049
+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", contextLength: 1e6 },
1050
+ { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", contextLength: 1e6 },
1051
+ { id: "claude-fable-5", name: "Claude Fable 5", contextLength: 1e6 },
1052
+ { id: "claude-opus-5", name: "Claude Opus 5", contextLength: 1e6 },
1053
+ { id: "claude-opus-4-8", name: "Claude Opus 4.8", contextLength: 1e6 },
1054
+ { id: "claude-opus-4-7", name: "Claude Opus 4.7", contextLength: 1e6 },
1055
+ { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", contextLength: 2e5 },
439
1056
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", contextLength: 105e4 },
440
1057
  { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", contextLength: 105e4 },
441
1058
  { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", contextLength: 105e4 },
@@ -498,33 +1115,61 @@ function zeroDataRetentionHeaders() {
498
1115
  }
499
1116
  return void 0;
500
1117
  }
501
- async function loadProviderModels(modelsUrl, log) {
502
- try {
503
- const models = await fetchCommandCodeModels({ url: modelsUrl });
504
- return toProviderModelMap(models);
505
- } catch (error) {
506
- const fallback = toProviderModelMap(FALLBACK_MODELS);
507
- const message = error instanceof Error ? error.message : String(error);
508
- log(`Could not fetch the Command Code model catalog (${message}). Using the built-in fallback catalog.`);
509
- return fallback;
510
- }
511
- }
512
1118
  function providerBaseUrl() {
513
1119
  const configured = process.env.COMMANDCODE_API_BASE;
514
1120
  if (configured && configured.length > 0) return configured;
515
1121
  return DEFAULT_PROVIDER_API_BASE;
516
1122
  }
1123
+ function modelsCachePath() {
1124
+ const configured = process.env.COMMANDCODE_MODELS_CACHE;
1125
+ if (configured && configured.length > 0) return configured;
1126
+ return join(homedir(), ".cache", "opencode", "commandcode-models.json");
1127
+ }
1128
+ async function loadProviderModels(modelsUrl, cachePath, providerBaseUrl2, logWarn, logInfo) {
1129
+ const result = await loadCommandCodeModels({
1130
+ url: modelsUrl,
1131
+ cachePath,
1132
+ fallbackModels: FALLBACK_MODELS,
1133
+ timeoutMs: getModelsTimeoutMs()
1134
+ });
1135
+ if (result.warning) logWarn(result.warning);
1136
+ else logInfo(`Loaded ${result.models.length} Command Code models from ${result.source}`);
1137
+ return {
1138
+ modelMap: toProviderModelMap(result.models, providerBaseUrl2),
1139
+ modelsInfo: {
1140
+ source: result.source,
1141
+ modelCount: result.models.length,
1142
+ fetchedAt: result.fetchedAt
1143
+ }
1144
+ };
1145
+ }
1146
+ function getModelsTimeoutMs() {
1147
+ const raw = process.env.COMMANDCODE_MODELS_TIMEOUT_MS;
1148
+ if (!raw) return DEFAULT_MODELS_TIMEOUT_MS;
1149
+ const parsed = Number(raw);
1150
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_MODELS_TIMEOUT_MS;
1151
+ }
517
1152
  var CommandCodePlugin = async ({ client }) => {
518
1153
  const apiBase = providerBaseUrl();
519
1154
  const modelsUrl = process.env.COMMANDCODE_MODELS_URL ?? `${apiBase}/models`;
520
- const models = await loadProviderModels(modelsUrl, (message) => {
521
- client.app.log({ body: { service: "opencode-commandcode", level: "warn", message } }).catch(() => {
522
- });
523
- });
1155
+ const cachePath = modelsCachePath();
1156
+ const { modelMap: models, modelsInfo } = await loadProviderModels(
1157
+ modelsUrl,
1158
+ cachePath,
1159
+ apiBase,
1160
+ (message) => {
1161
+ client.app.log({ body: { service: "opencode-commandcode", level: "warn", message } }).catch(() => {
1162
+ });
1163
+ },
1164
+ (message) => {
1165
+ client.app.log({ body: { service: "opencode-commandcode", level: "info", message } }).catch(() => {
1166
+ });
1167
+ }
1168
+ );
524
1169
  return {
525
1170
  config: async (cfg) => {
526
1171
  cfg.provider ??= {};
527
- cfg.provider[PROVIDER_ID] = {
1172
+ cfg.provider[PROVIDER_ID2] = {
528
1173
  npm: "@ai-sdk/openai-compatible",
529
1174
  name: "Command Code",
530
1175
  env: ["COMMAND_CODE_API_KEY", "COMMANDCODE_API_KEY"],
@@ -534,8 +1179,25 @@ var CommandCodePlugin = async ({ client }) => {
534
1179
  },
535
1180
  models
536
1181
  };
1182
+ client.app.log({
1183
+ body: {
1184
+ service: "opencode-commandcode",
1185
+ level: "info",
1186
+ message: `Registered Command Code provider with ${Object.keys(models).length} models (source: ${modelsInfo.source})`
1187
+ }
1188
+ }).catch(() => {
1189
+ });
537
1190
  },
538
- auth: createAuthHook()
1191
+ auth: createAuthHook(),
1192
+ tool: {
1193
+ ...createQuotaTool({ apiBase, extraHeaders: zeroDataRetentionHeaders(), client }),
1194
+ ...createStatusTool({
1195
+ apiBase,
1196
+ zdr: zeroDataRetentionHeaders() !== void 0,
1197
+ version: PLUGIN_VERSION,
1198
+ modelsInfo
1199
+ })
1200
+ }
539
1201
  };
540
1202
  };
541
1203
  var index_default = CommandCodePlugin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gururea/opencode-commandcode-provider",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "OpenCode plugin that adds the Command Code (commandcode.ai) provider and its authentication to the interface.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -13,11 +13,12 @@
13
13
  },
14
14
  "files": [
15
15
  "dist",
16
+ "command",
16
17
  "README.md",
17
18
  "LICENSE"
18
19
  ],
19
20
  "scripts": {
20
- "build": "tsup src/index.ts --format esm --dts --clean --out-dir dist",
21
+ "build": "tsup src/index.ts --format esm --dts --clean --out-dir dist --external @opencode-ai/plugin --external zod",
21
22
  "test": "node --import tsx --test tests/*.test.ts",
22
23
  "typecheck": "tsc --noEmit",
23
24
  "prepare": "npm run build"