codiedev 0.9.55 → 0.9.57

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/dist/codie.js CHANGED
@@ -51,9 +51,14 @@ const child_process_1 = require("child_process");
51
51
  const url_1 = require("url");
52
52
  const configDir_1 = require("./configDir");
53
53
  const codieLauncher_1 = require("./codieLauncher");
54
+ const codieBrandInstall_1 = require("./codieBrandInstall");
55
+ const codieUsage_1 = require("./codieUsage");
54
56
  const codieRuntime_1 = require("./codieRuntime");
55
57
  const codieRuntimeInstall_1 = require("./codieRuntimeInstall");
56
58
  const upgradeNudge_1 = require("./upgradeNudge");
59
+ // How long to let the gateway finish booking the last request before asking
60
+ // what the session cost.
61
+ const USAGE_SETTLE_MS = 1200;
57
62
  function git(args) {
58
63
  const result = (0, child_process_1.spawnSync)("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
59
64
  return result.status === 0 ? result.stdout.trim() : "";
@@ -96,32 +101,6 @@ function assetPath(name) {
96
101
  // dist/codie.js → ../assets/<name>; src/codie.ts → ../assets/<name>.
97
102
  return path.join(__dirname, "..", "assets", name);
98
103
  }
99
- // Stage the home-screen branding plugin. TUI plugins only load from tui.json
100
- // in the OpenCode config dir, so the packaged file is copied next to the
101
- // capture plugin and referenced with a relative spec. Best-effort: any
102
- // failure (e.g. a hand-edited tui.json with comments) leaves the stock logo.
103
- function installBrandPlugin() {
104
- try {
105
- // OpenCode resolves its config dir per the XDG spec, so a customized
106
- // XDG_CONFIG_HOME must be honored or tui.json lands where it never reads.
107
- const configDir = path.join(process.env.XDG_CONFIG_HOME?.trim() || path.join(os.homedir(), ".config"), "opencode");
108
- const pluginDir = path.join(configDir, "plugins");
109
- fs.mkdirSync(pluginDir, { recursive: true });
110
- const source = fs.readFileSync(assetPath("tui-brand-plugin.tsx"), "utf8");
111
- const destination = path.join(pluginDir, "codiedev-brand.tsx");
112
- if (!fs.existsSync(destination) || fs.readFileSync(destination, "utf8") !== source) {
113
- fs.writeFileSync(destination, source);
114
- }
115
- const tuiConfigPath = path.join(configDir, "tui.json");
116
- const existing = fs.existsSync(tuiConfigPath) ? JSON.parse(fs.readFileSync(tuiConfigPath, "utf8")) : {};
117
- const { config, changed } = (0, codieLauncher_1.withBrandPlugin)(existing);
118
- if (changed)
119
- fs.writeFileSync(tuiConfigPath, `${JSON.stringify(config, null, 2)}\n`);
120
- }
121
- catch (error) {
122
- console.error(`codie: continuing without Codiedev branding (${error instanceof Error ? error.message : error})`);
123
- }
124
- }
125
104
  // Remove the engine's boot/exit banner wordmark in place (see
126
105
  // patchBrandWordmark). Best-effort like the TUI plugin: any failure rolls the
127
106
  // bytes back and the stock banner keeps working. Runs once per install; an
@@ -214,7 +193,7 @@ async function main() {
214
193
  });
215
194
  const metadataPlugin = (0, url_1.pathToFileURL)(assetPath("opencode-plugin.mjs")).href;
216
195
  const capturePlugin = (0, codieLauncher_1.resolveCapturePlugin)({ homeDir: os.homedir(), existsSync: fs.existsSync });
217
- installBrandPlugin();
196
+ (0, codieBrandInstall_1.installTuiPlugin)();
218
197
  installBrandWordmark(runtime);
219
198
  const config = (0, codieLauncher_1.buildCodieConfig)({
220
199
  existing: existingInlineConfig(),
@@ -232,6 +211,33 @@ async function main() {
232
211
  OPENCODE_CONFIG_CONTENT: JSON.stringify(config),
233
212
  };
234
213
  const runtimeArgs = (0, codieLauncher_1.withCodieWorkingDirectory)(parsed.args, process.cwd());
214
+ const nonInteractiveRun = runtimeArgs[0] === "run";
215
+ if (nonInteractiveRun) {
216
+ // The TUI paints its own live status line from the same endpoint. A
217
+ // non-interactive run has no TUI, so the budget arrives as two printed
218
+ // lines instead — and only for a human at a terminal, so a scripted run
219
+ // is neither slowed nor polluted.
220
+ const reportCost = Boolean(process.stderr.isTTY);
221
+ const startedAt = Date.now();
222
+ if (reportCost) {
223
+ const line = (0, codieUsage_1.formatUsageLine)(await (0, codieUsage_1.fetchCodieUsage)({ baseUrl: gatewayUrl, key }));
224
+ if (line)
225
+ console.error(line);
226
+ }
227
+ const result = (0, child_process_1.spawnSync)(runtime, runtimeArgs, { stdio: "inherit", env });
228
+ if (result.error)
229
+ throw result.error;
230
+ process.exitCode = result.status === null ? 1 : result.status;
231
+ if (reportCost) {
232
+ // The gateway books a request's cost after it has answered, so a poll
233
+ // fired the instant the run closes can miss the last one.
234
+ await new Promise((resolve) => setTimeout(resolve, USAGE_SETTLE_MS));
235
+ const cost = (0, codieUsage_1.formatSessionCostLine)(await (0, codieUsage_1.fetchCodieUsage)({ baseUrl: gatewayUrl, key, sinceMs: startedAt }));
236
+ if (cost)
237
+ console.error(cost);
238
+ }
239
+ return;
240
+ }
235
241
  const result = (0, child_process_1.spawnSync)(runtime, runtimeArgs, { stdio: "inherit", env });
236
242
  if (result.error)
237
243
  throw result.error;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The usage module this install should load. The shipped package has the
3
+ * compiled file; a source checkout (and the test run) has the TypeScript one.
4
+ * Naming a path that does not exist would cost the status line silently, so a
5
+ * miss raises instead and the caller falls back to the plain plugin.
6
+ */
7
+ export declare function usageModulePath(): string;
8
+ /** The engine resolves its config dir per the XDG spec, so a customized
9
+ * XDG_CONFIG_HOME must be honored or tui.json lands where it never reads. */
10
+ export declare function openCodeConfigDir(): string;
11
+ export declare function installTuiPlugin(): void;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ // Stages the Codiedev TUI plugin into the engine's config directory.
3
+ //
4
+ // TUI plugins load only from tui.json in the OpenCode config dir, so the
5
+ // packaged template is copied there and referenced by a relative spec. The
6
+ // copy also carries the status line, which needs an absolute path back into
7
+ // this package — the plugin sits outside it and cannot reach it any other way.
8
+ //
9
+ // Every step is best-effort: a developer who cannot write this directory still
10
+ // gets a working harness, just the stock logo and no status line.
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.usageModulePath = usageModulePath;
46
+ exports.openCodeConfigDir = openCodeConfigDir;
47
+ exports.installTuiPlugin = installTuiPlugin;
48
+ const fs = __importStar(require("fs"));
49
+ const os = __importStar(require("os"));
50
+ const path = __importStar(require("path"));
51
+ const codieLauncher_1 = require("./codieLauncher");
52
+ function assetPath(name) {
53
+ // dist/codieBrandInstall.js → ../assets/<name>; src/… → ../assets/<name>.
54
+ return path.join(__dirname, "..", "assets", name);
55
+ }
56
+ /**
57
+ * The usage module this install should load. The shipped package has the
58
+ * compiled file; a source checkout (and the test run) has the TypeScript one.
59
+ * Naming a path that does not exist would cost the status line silently, so a
60
+ * miss raises instead and the caller falls back to the plain plugin.
61
+ */
62
+ function usageModulePath() {
63
+ const candidates = [
64
+ path.join(__dirname, "codieUsage.js"),
65
+ path.join(__dirname, "codieUsage.ts"),
66
+ ];
67
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
68
+ if (!found)
69
+ throw new Error("this install has no Codiedev usage module");
70
+ return found;
71
+ }
72
+ /** The engine resolves its config dir per the XDG spec, so a customized
73
+ * XDG_CONFIG_HOME must be honored or tui.json lands where it never reads. */
74
+ function openCodeConfigDir() {
75
+ return path.join(process.env.XDG_CONFIG_HOME?.trim() || path.join(os.homedir(), ".config"), "opencode");
76
+ }
77
+ function installTuiPlugin() {
78
+ try {
79
+ const configDir = openCodeConfigDir();
80
+ const pluginDir = path.join(configDir, "plugins");
81
+ fs.mkdirSync(pluginDir, { recursive: true });
82
+ const source = (0, codieLauncher_1.stageUsageModule)(fs.readFileSync(assetPath("tui-brand-plugin.tsx"), "utf8"), usageModulePath());
83
+ const destination = path.join(pluginDir, path.basename(codieLauncher_1.BRAND_PLUGIN_SPEC));
84
+ if (!fs.existsSync(destination) || fs.readFileSync(destination, "utf8") !== source) {
85
+ fs.writeFileSync(destination, source);
86
+ }
87
+ const tuiConfigPath = path.join(configDir, "tui.json");
88
+ const existing = fs.existsSync(tuiConfigPath)
89
+ ? JSON.parse(fs.readFileSync(tuiConfigPath, "utf8"))
90
+ : {};
91
+ const { config, changed } = (0, codieLauncher_1.withBrandPlugin)(existing);
92
+ if (changed)
93
+ fs.writeFileSync(tuiConfigPath, `${JSON.stringify(config, null, 2)}\n`);
94
+ }
95
+ catch (error) {
96
+ console.error(`codie: continuing without Codiedev branding (${error instanceof Error ? error.message : error})`);
97
+ }
98
+ }
@@ -1,7 +1,30 @@
1
+ export interface ModelCost {
2
+ /** Dollars per million prompt tokens. */
3
+ input: number;
4
+ /** Dollars per million completion tokens. */
5
+ output: number;
6
+ }
7
+ export interface ModelLimit {
8
+ /** Maximum prompt tokens the model accepts. */
9
+ context: number;
10
+ /** Maximum completion tokens the model emits. */
11
+ output: number;
12
+ }
1
13
  export interface CatalogModel {
2
14
  id: string;
3
15
  name?: string;
16
+ cost?: ModelCost;
17
+ limit?: ModelLimit;
4
18
  }
19
+ /** A rate card is usable only when both sides are real, finite and not
20
+ * negative. Half a card prices a session wrong in a way nobody can see, so a
21
+ * partial one is dropped and the model stays unpriced. */
22
+ export declare function usableModelCost(value: unknown): ModelCost | undefined;
23
+ /** A context/output window is usable only when both sides are real, finite and
24
+ * positive. A partial window makes the engine's "% of context used" read wrong
25
+ * in a way nobody can see, so a partial one is dropped and the model keeps the
26
+ * engine's default. */
27
+ export declare function usableModelLimit(value: unknown): ModelLimit | undefined;
5
28
  /**
6
29
  * Pin non-interactive runs to the directory where `codie` was launched.
7
30
  * OpenCode can reuse a previously-known project instance; without an explicit
@@ -17,6 +40,16 @@ export declare function buildCodieConfig({ existing, catalog, env, plugin, plugi
17
40
  plugin?: string;
18
41
  plugins?: string[];
19
42
  }): Record<string, any>;
43
+ export declare const USAGE_MODULE_PLACEHOLDER = "__CODIEDEV_USAGE_MODULE__";
44
+ /**
45
+ * Point the staged TUI plugin at this install's usage module.
46
+ *
47
+ * The plugin is copied into the engine's own config directory, so it cannot
48
+ * reach the package by a relative path — the absolute path is baked in at
49
+ * stage time. It goes in as a JSON literal so a Windows path keeps its
50
+ * backslashes instead of turning into escape sequences.
51
+ */
52
+ export declare function stageUsageModule(source: string, modulePath: string): string;
20
53
  export declare const BRAND_PLUGIN_SPEC = "./plugins/codiedev-brand.tsx";
21
54
  export declare function withBrandPlugin(existing: Record<string, any> | undefined): {
22
55
  config: Record<string, any>;
@@ -42,10 +42,13 @@ var __importStar = (this && this.__importStar) || (function () {
42
42
  };
43
43
  })();
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.HIDDEN_WORDMARK = exports.CODIEDEV_WORDMARK = exports.LEGACY_CODIEDEV_WORDMARK = exports.STOCK_WORDMARK = exports.BRAND_PLUGIN_SPEC = void 0;
45
+ exports.HIDDEN_WORDMARK = exports.CODIEDEV_WORDMARK = exports.LEGACY_CODIEDEV_WORDMARK = exports.STOCK_WORDMARK = exports.BRAND_PLUGIN_SPEC = exports.USAGE_MODULE_PLACEHOLDER = void 0;
46
+ exports.usableModelCost = usableModelCost;
47
+ exports.usableModelLimit = usableModelLimit;
46
48
  exports.withCodieWorkingDirectory = withCodieWorkingDirectory;
47
49
  exports.bareModel = bareModel;
48
50
  exports.buildCodieConfig = buildCodieConfig;
51
+ exports.stageUsageModule = stageUsageModule;
49
52
  exports.withBrandPlugin = withBrandPlugin;
50
53
  exports.patchBrandWordmark = patchBrandWordmark;
51
54
  exports.resolveCapturePlugin = resolveCapturePlugin;
@@ -62,6 +65,37 @@ const DEFAULT_NAMES = {
62
65
  "z-ai/glm-5.2": "GLM 5.2 · Fireworks ZDR",
63
66
  "moonshotai/kimi-k2.7-code": "Kimi K2.7 Code · Fireworks ZDR",
64
67
  };
68
+ /** A rate card is usable only when both sides are real, finite and not
69
+ * negative. Half a card prices a session wrong in a way nobody can see, so a
70
+ * partial one is dropped and the model stays unpriced. */
71
+ function usableModelCost(value) {
72
+ if (!value || typeof value !== "object")
73
+ return undefined;
74
+ const { input, output } = value;
75
+ if (typeof input !== "number" || typeof output !== "number")
76
+ return undefined;
77
+ if (!Number.isFinite(input) || !Number.isFinite(output))
78
+ return undefined;
79
+ if (input < 0 || output < 0)
80
+ return undefined;
81
+ return { input, output };
82
+ }
83
+ /** A context/output window is usable only when both sides are real, finite and
84
+ * positive. A partial window makes the engine's "% of context used" read wrong
85
+ * in a way nobody can see, so a partial one is dropped and the model keeps the
86
+ * engine's default. */
87
+ function usableModelLimit(value) {
88
+ if (!value || typeof value !== "object")
89
+ return undefined;
90
+ const { context, output } = value;
91
+ if (typeof context !== "number" || typeof output !== "number")
92
+ return undefined;
93
+ if (!Number.isFinite(context) || !Number.isFinite(output))
94
+ return undefined;
95
+ if (context <= 0 || output <= 0)
96
+ return undefined;
97
+ return { context, output };
98
+ }
65
99
  /**
66
100
  * Pin non-interactive runs to the directory where `codie` was launched.
67
101
  * OpenCode can reuse a previously-known project instance; without an explicit
@@ -121,10 +155,23 @@ function buildCodieConfig({ existing = {}, catalog, env = {}, plugin, plugins =
121
155
  const planModel = governedModel(requestedPlan, approved, fast, "Plan agent");
122
156
  const existingPlugins = Array.isArray(existing.plugin) ? existing.plugin : [];
123
157
  const requiredPlugins = [...plugins, plugin].filter(Boolean);
124
- const models = Object.fromEntries(catalog.map((model) => [
125
- bareModel(model.id),
126
- { name: model.name || DEFAULT_NAMES[bareModel(model.id)] || bareModel(model.id) },
127
- ]));
158
+ const models = Object.fromEntries(catalog.map((model) => {
159
+ // The engine prices a session from this rate card. Without it every
160
+ // model reads $0.00, which is how the harness came to show no spend at
161
+ // all. The gateway publishes prompt and completion prices only, so
162
+ // cached tokens are priced at zero here and the engine's session figure
163
+ // stays an estimate — the budget line from /me/usage is the true spend.
164
+ const cost = usableModelCost(model.cost);
165
+ const limit = usableModelLimit(model.limit);
166
+ return [
167
+ bareModel(model.id),
168
+ {
169
+ name: model.name || DEFAULT_NAMES[bareModel(model.id)] || bareModel(model.id),
170
+ ...(cost ? { cost: { ...cost, cache: { read: 0, write: 0 } } } : {}),
171
+ ...(limit ? { limit } : {}),
172
+ },
173
+ ];
174
+ }));
128
175
  return {
129
176
  ...existing,
130
177
  model: governedModel(primary, approved, first, "Primary agent"),
@@ -152,6 +199,21 @@ function buildCodieConfig({ existing = {}, catalog, env = {}, plugin, plugins =
152
199
  plugin: [...existingPlugins.filter((item) => !requiredPlugins.includes(item)), ...requiredPlugins],
153
200
  };
154
201
  }
202
+ exports.USAGE_MODULE_PLACEHOLDER = "__CODIEDEV_USAGE_MODULE__";
203
+ /**
204
+ * Point the staged TUI plugin at this install's usage module.
205
+ *
206
+ * The plugin is copied into the engine's own config directory, so it cannot
207
+ * reach the package by a relative path — the absolute path is baked in at
208
+ * stage time. It goes in as a JSON literal so a Windows path keeps its
209
+ * backslashes instead of turning into escape sequences.
210
+ */
211
+ function stageUsageModule(source, modulePath) {
212
+ if (!source.includes(exports.USAGE_MODULE_PLACEHOLDER)) {
213
+ throw new Error(`plugin template is missing the ${exports.USAGE_MODULE_PLACEHOLDER} placeholder`);
214
+ }
215
+ return source.split(exports.USAGE_MODULE_PLACEHOLDER).join(JSON.stringify(modulePath));
216
+ }
155
217
  exports.BRAND_PLUGIN_SPEC = "./plugins/codiedev-brand.tsx";
156
218
  // Pure merge for ~/.config/opencode/tui.json: TUI plugins load from tui.json,
157
219
  // not the opencode.json we inject via OPENCODE_CONFIG_CONTENT.
@@ -310,10 +372,16 @@ async function fetchApprovedCatalog({ baseUrl, key, fetchImpl = fetch, }) {
310
372
  if (!Array.isArray(payload?.data) || payload.data.length === 0) {
311
373
  throw new Error("model catalog is empty");
312
374
  }
313
- return payload.data.map((model) => ({
314
- id: bareModel(model.id),
315
- name: typeof model.name === "string" && model.name ? model.name : DEFAULT_NAMES[bareModel(model.id)],
316
- }));
375
+ return payload.data.map((model) => {
376
+ const cost = usableModelCost(model.cost);
377
+ const limit = usableModelLimit(model.limit);
378
+ return {
379
+ id: bareModel(model.id),
380
+ name: typeof model.name === "string" && model.name ? model.name : DEFAULT_NAMES[bareModel(model.id)],
381
+ ...(cost ? { cost } : {}),
382
+ ...(limit ? { limit } : {}),
383
+ };
384
+ });
317
385
  }
318
386
  finally {
319
387
  clearTimeout(timeout);
@@ -0,0 +1,57 @@
1
+ export interface CodieUsageBudget {
2
+ companyBudgetUsd: number | null;
3
+ companySpentUsd: number;
4
+ companyHeldUsd: number;
5
+ userBudgetUsd: number | null;
6
+ userSpentUsd: number;
7
+ userHeldUsd: number;
8
+ keyBudgetUsd: number | null;
9
+ keySpentUsd: number;
10
+ keyHeldUsd: number | null;
11
+ }
12
+ export interface CodieUsageInFlight {
13
+ /** Reservations open inside the gateway's hold TTL: real work running now. */
14
+ requests: number;
15
+ heldUsd: number;
16
+ /** Reservations past the TTL, waiting for the sweep. They hold budget
17
+ * without doing work, so they are never counted as live work. */
18
+ staleRequests: number;
19
+ staleHeldUsd: number;
20
+ }
21
+ export interface CodieUsage {
22
+ enabled: boolean;
23
+ user: {
24
+ name: string;
25
+ email: string;
26
+ role: string;
27
+ } | null;
28
+ budget: CodieUsageBudget;
29
+ inFlight: CodieUsageInFlight;
30
+ since?: {
31
+ costUsd: number;
32
+ promptTokens: number;
33
+ completionTokens: number;
34
+ requests: number;
35
+ };
36
+ }
37
+ /**
38
+ * One line: who is spending, how much, against what, and what is running.
39
+ * Returns "" when there is nothing honest to say.
40
+ */
41
+ export declare function formatUsageLine(usage: CodieUsage | null | undefined): string;
42
+ /**
43
+ * What this session just cost. Returns "" when the session billed nothing,
44
+ * because a developer who spent nothing does not need to be told a number.
45
+ */
46
+ export declare function formatSessionCostLine(usage: CodieUsage | null | undefined): string;
47
+ /**
48
+ * Read the developer's budget snapshot. Returns null on any refusal, network
49
+ * failure, timeout, or malformed answer — a status poll is never worth an
50
+ * error in front of a developer who asked for none.
51
+ */
52
+ export declare function fetchCodieUsage({ baseUrl, key, sinceMs, fetchImpl, }: {
53
+ baseUrl?: string;
54
+ key: string;
55
+ sinceMs?: number;
56
+ fetchImpl?: typeof fetch;
57
+ }): Promise<CodieUsage | null>;
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ // The Codie harness status line.
3
+ //
4
+ // The gateway already knows what a developer has spent, what caps them, and
5
+ // what they have in flight. Nothing ever asked it. This module asks, and turns
6
+ // the answer into one line the harness can paint next to the prompt.
7
+ //
8
+ // Every failure here is silent by design: a status poll must never interrupt,
9
+ // delay, or break a coding session. No snapshot means no line.
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.formatUsageLine = formatUsageLine;
12
+ exports.formatSessionCostLine = formatSessionCostLine;
13
+ exports.fetchCodieUsage = fetchCodieUsage;
14
+ const USAGE_TIMEOUT_MS = 4000;
15
+ function cleanBaseUrl(value) {
16
+ return String(value || "https://gateway.codiedev.com/api/v1").replace(/\/+$/, "");
17
+ }
18
+ function money(value) {
19
+ return `$${value.toFixed(2)}`;
20
+ }
21
+ /** Budgets are set in whole dollars far more often than not, so $150 reads
22
+ * better than $150.00 next to a spend figure that does need its cents. */
23
+ function budgetMoney(value) {
24
+ return Number.isInteger(value) ? `$${value}` : money(value);
25
+ }
26
+ function percent(spent, budget) {
27
+ if (!(budget > 0))
28
+ return null;
29
+ const share = (spent / budget) * 100;
30
+ // A first request against a large budget rounds to 0%, which reads as
31
+ // "nothing spent". Say "under one percent" instead.
32
+ if (share > 0 && share < 1)
33
+ return "<1%";
34
+ return `${Math.round(share)}%`;
35
+ }
36
+ /**
37
+ * One line: who is spending, how much, against what, and what is running.
38
+ * Returns "" when there is nothing honest to say.
39
+ */
40
+ function formatUsageLine(usage) {
41
+ if (!usage || !usage.enabled)
42
+ return "";
43
+ const { budget, inFlight } = usage;
44
+ const segments = [];
45
+ if (usage.user?.name)
46
+ segments.push(usage.user.name);
47
+ // The developer's own month-to-date spend is always the headline. Only the
48
+ // budget that actually caps them earns a percentage next to it.
49
+ if (typeof budget.userBudgetUsd === "number") {
50
+ segments.push(`${money(budget.userSpentUsd)} / ${budgetMoney(budget.userBudgetUsd)}`);
51
+ const share = percent(budget.userSpentUsd, budget.userBudgetUsd);
52
+ if (share)
53
+ segments.push(share);
54
+ }
55
+ else {
56
+ segments.push(money(budget.userSpentUsd));
57
+ if (typeof budget.companyBudgetUsd === "number") {
58
+ const share = percent(budget.companySpentUsd, budget.companyBudgetUsd);
59
+ // Labelled, because a team percentage beside a personal dollar figure
60
+ // otherwise reads as the developer's own share.
61
+ if (share)
62
+ segments.push(`team ${share}`);
63
+ }
64
+ }
65
+ if (inFlight.requests > 0)
66
+ segments.push(`${inFlight.requests} in flight`);
67
+ // Stale holds cap a budget while doing no work. Naming them is the
68
+ // difference between "I am blocked" and "I am blocked by nothing".
69
+ if (inFlight.staleHeldUsd > 0)
70
+ segments.push(`${money(inFlight.staleHeldUsd)} held stale`);
71
+ return segments.join(" · ");
72
+ }
73
+ function tokens(total) {
74
+ // Rounded by arithmetic, not toFixed: 2.55 is not exactly representable, so
75
+ // toFixed(1) rounds it down and the same count can read two ways.
76
+ if (total >= 1_000_000)
77
+ return `${Math.round(total / 100_000) / 10}M`;
78
+ if (total >= 1_000)
79
+ return `${Math.round(total / 1_000)}k`;
80
+ return String(total);
81
+ }
82
+ /**
83
+ * What this session just cost. Returns "" when the session billed nothing,
84
+ * because a developer who spent nothing does not need to be told a number.
85
+ */
86
+ function formatSessionCostLine(usage) {
87
+ const since = readSince(usage?.since);
88
+ if (!since || since.requests <= 0)
89
+ return "";
90
+ // A real charge that rounds to $0.00 reads as free. Say it is under a cent
91
+ // instead — the month-to-date figure is where it really lands.
92
+ const cost = since.costUsd > 0 && since.costUsd < 0.005 ? "<$0.01" : money(since.costUsd);
93
+ const requests = `${since.requests} ${since.requests === 1 ? "request" : "requests"}`;
94
+ return `This session: ${cost} · ${requests} · ${tokens(since.promptTokens + since.completionTokens)} tokens`;
95
+ }
96
+ /**
97
+ * A usage window is reported only when every field of it is a real number.
98
+ * A partial block is worse than none: it reads as a cheap session, and the
99
+ * arithmetic on a missing field throws out of a call site whose whole
100
+ * contract is that it cannot break the run that just finished.
101
+ */
102
+ function readSince(value) {
103
+ if (!value || typeof value !== "object" || Array.isArray(value))
104
+ return undefined;
105
+ const { costUsd, promptTokens, completionTokens, requests } = value;
106
+ const finite = (candidate) => typeof candidate === "number" && Number.isFinite(candidate);
107
+ if (!finite(costUsd) || !finite(promptTokens) || !finite(completionTokens) || !finite(requests)) {
108
+ return undefined;
109
+ }
110
+ return { costUsd, promptTokens, completionTokens, requests };
111
+ }
112
+ function readNumber(value, fallback = 0) {
113
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
114
+ }
115
+ function readBudgetCap(value) {
116
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
117
+ }
118
+ function readUser(value) {
119
+ if (!value || typeof value !== "object")
120
+ return null;
121
+ const { name, email, role } = value;
122
+ if (typeof name !== "string" || !name)
123
+ return null;
124
+ return {
125
+ name,
126
+ email: typeof email === "string" ? email : "",
127
+ role: typeof role === "string" ? role : "",
128
+ };
129
+ }
130
+ /**
131
+ * Read the developer's budget snapshot. Returns null on any refusal, network
132
+ * failure, timeout, or malformed answer — a status poll is never worth an
133
+ * error in front of a developer who asked for none.
134
+ */
135
+ async function fetchCodieUsage({ baseUrl, key, sinceMs, fetchImpl = fetch, }) {
136
+ const controller = new AbortController();
137
+ const timeout = setTimeout(() => controller.abort(), USAGE_TIMEOUT_MS);
138
+ try {
139
+ const query = typeof sinceMs === "number" && sinceMs > 0 ? `?since=${sinceMs}` : "";
140
+ const response = await fetchImpl(`${cleanBaseUrl(baseUrl)}/me/usage${query}`, {
141
+ headers: { Authorization: `Bearer ${key}` },
142
+ signal: controller.signal,
143
+ });
144
+ if (!response.ok)
145
+ return null;
146
+ const payload = (await response.json());
147
+ const budget = payload?.budget;
148
+ if (!budget || typeof budget !== "object")
149
+ return null;
150
+ const raw = budget;
151
+ const flight = (payload?.inFlight ?? {});
152
+ return {
153
+ enabled: payload?.enabled === true,
154
+ user: readUser(payload?.user),
155
+ budget: {
156
+ companyBudgetUsd: readBudgetCap(raw.companyBudgetUsd),
157
+ companySpentUsd: readNumber(raw.companySpentUsd),
158
+ companyHeldUsd: readNumber(raw.companyHeldUsd),
159
+ userBudgetUsd: readBudgetCap(raw.userBudgetUsd),
160
+ userSpentUsd: readNumber(raw.userSpentUsd),
161
+ userHeldUsd: readNumber(raw.userHeldUsd),
162
+ keyBudgetUsd: readBudgetCap(raw.keyBudgetUsd),
163
+ keySpentUsd: readNumber(raw.keySpentUsd),
164
+ keyHeldUsd: typeof raw.keyHeldUsd === "number" ? raw.keyHeldUsd : null,
165
+ },
166
+ inFlight: {
167
+ requests: readNumber(flight.requests),
168
+ heldUsd: readNumber(flight.heldUsd),
169
+ staleRequests: readNumber(flight.staleRequests),
170
+ staleHeldUsd: readNumber(flight.staleHeldUsd),
171
+ },
172
+ ...(() => {
173
+ const since = readSince(payload?.since);
174
+ return since ? { since } : {};
175
+ })(),
176
+ };
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ finally {
182
+ clearTimeout(timeout);
183
+ }
184
+ }