pal-code 0.0.19 → 0.0.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.19",
3
+ "version": "0.0.20",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -65,7 +65,7 @@
65
65
  "gemini"
66
66
  ],
67
67
  "dependencies": {
68
- "@pal-code/core": "0.0.19",
68
+ "@pal-code/core": "0.0.20",
69
69
  "@earendil-works/pi-tui": "^0.85.1",
70
70
  "get-east-asian-width": "1.6.0",
71
71
  "marked": "^18.1.3"
@@ -8,6 +8,8 @@ import type {Container, TUI} from '@earendil-works/pi-tui';
8
8
 
9
9
  import {RunView} from './components/run-view.js';
10
10
  import {state} from './state.js';
11
+ import {c} from './theme.js';
12
+ import {Text} from './tui/components/text.js';
11
13
  import {checkToolPermission} from './utils/permissions.js';
12
14
 
13
15
  export function createTuiAgentUi(tui: TUI, container: Container): AgentUi {
@@ -45,6 +47,14 @@ export function createTuiAgentUi(tui: TUI, container: Container): AgentUi {
45
47
  extensions(extensions) {
46
48
  state.extensions = extensions;
47
49
  },
50
+ advisories(lines) {
51
+ // Rendered into the transcript rather than a run block: this fires before
52
+ // any turn exists, so `notice()` would be dropped.
53
+ for (const line of lines) {
54
+ container.addChild(new Text(`${c.yellow} ${line}${c.reset}`, 1, 0));
55
+ }
56
+ tui.requestRender();
57
+ },
48
58
  mcpServers(servers) {
49
59
  state.mcpServers = servers;
50
60
  },
@@ -57,7 +57,12 @@ import {
57
57
  saveUpdateCache,
58
58
  } from './commands/update-check.js';
59
59
  import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
60
- import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
60
+ import {
61
+ loadCostManifest,
62
+ isPricedModel,
63
+ registerModelPricing,
64
+ resolveTurnCost,
65
+ } from './utils/cost.js';
61
66
  import {
62
67
  buildOsc22Pointer,
63
68
  buildOsc52Sequence,
@@ -123,7 +128,7 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
123
128
  // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
124
129
 
125
130
  // Version synced from version.json via `node scripts/sync-version.js`.
126
- const VERSION = '0.0.19';
131
+ const VERSION = '0.0.20';
127
132
 
128
133
  // ── Canvas sync (OSC 10/11) ──
129
134
  // Raw reply payloads captured after a successful startup query + set, or null
@@ -276,8 +281,34 @@ async function main() {
276
281
  });
277
282
  }
278
283
 
284
+ /**
285
+ * Teach the cost table what this provider charges.
286
+ *
287
+ * Gateways price their own catalogue, and that catalogue is keyed by gateway
288
+ * model id — which the LiteLLM manifest does not know (`deepseek-v4.1-flash`
289
+ * vs `azure_ai/deepseek-v4.1-flash`). Without this, a paid gateway model
290
+ * matched nothing and every turn displayed `$0.00`. Fire-and-forget and
291
+ * once per provider: a failure just leaves the fallback table in place.
292
+ */
293
+ const pricingSynced = new Set<string>();
294
+ function syncModelPricing(provider: Provider): void {
295
+ const id = provider.id;
296
+ if (pricingSynced.has(id)) return;
297
+ pricingSynced.add(id);
298
+ void provider
299
+ .models()
300
+ .then((models) => {
301
+ registerModelPricing(models, id);
302
+ refreshSidebar();
303
+ })
304
+ .catch(() => {
305
+ // offline or unauthenticated — the hardcoded/manifest table still applies
306
+ });
307
+ }
308
+
279
309
  const providerRef = {current: createProvider(config.model)};
280
310
  await providerRef.current.init();
311
+ syncModelPricing(providerRef.current);
281
312
 
282
313
  // ── Session store (deferred — bun:sqlite breaks pi-tui stdin) ──
283
314
  let store: SessionStoreType | null = null;
@@ -863,7 +894,9 @@ async function main() {
863
894
  contextPct,
864
895
  ctxTokens,
865
896
  contextLimit: config.contextLimit,
866
- priced: isPricedModel(config.model),
897
+ // A turn whose cost the provider actually reported is priced by
898
+ // definition, even if our table doesn't know the model.
899
+ priced: isPricedModel(config.model) || state.sessionTokenomics.cost > 0,
867
900
  });
868
901
  tui.requestRender();
869
902
  }
@@ -907,6 +940,7 @@ async function main() {
907
940
  }
908
941
  providerRef.current = createProvider(config.model);
909
942
  providerRef.current.init();
943
+ syncModelPricing(providerRef.current);
910
944
  updateStatusLine();
911
945
  };
912
946
 
@@ -1712,6 +1746,7 @@ async function main() {
1712
1746
  providerRef,
1713
1747
  createProvider,
1714
1748
  allKeys,
1749
+ syncModelPricing,
1715
1750
  );
1716
1751
  return;
1717
1752
  }
@@ -1722,6 +1757,7 @@ async function main() {
1722
1757
  saveSetting('model', newName);
1723
1758
  providerRef.current = createProvider(newName);
1724
1759
  providerRef.current.init();
1760
+ syncModelPricing(providerRef.current);
1725
1761
  messagesContainer.addChild(
1726
1762
  new Text(`${c.green} Model set to: ${config.model}${c.reset}`, 1, 0),
1727
1763
  );
@@ -2129,7 +2165,10 @@ async function main() {
2129
2165
  tok.inputTokens += result.inputTokens;
2130
2166
  tok.cachedTokens += result.cachedTokens;
2131
2167
  tok.outputTokens += result.outputTokens;
2132
- const turnCost = estimateCost(
2168
+ // Prefer the provider's own billed figure: it is authoritative and
2169
+ // already reflects cache discounts and account-level pricing.
2170
+ const turnCost = resolveTurnCost(
2171
+ result.reportedCost,
2133
2172
  result.model,
2134
2173
  result.inputTokens,
2135
2174
  result.outputTokens,
@@ -48,6 +48,8 @@ export function showModelSelector(
48
48
  providerRef: {current: Provider},
49
49
  createProviderFn: (model: string) => Provider,
50
50
  allKeys: ProviderKeys,
51
+ /** Called with the freshly built provider so callers can refresh pricing. */
52
+ onProviderChange?: (provider: Provider) => void,
51
53
  ): void {
52
54
  showSelectOverlay(
53
55
  {
@@ -61,6 +63,7 @@ export function showModelSelector(
61
63
  saveSetting('model', item.value);
62
64
  providerRef.current = createProviderFn(item.value);
63
65
  providerRef.current.init();
66
+ onProviderChange?.(providerRef.current);
64
67
  state.refreshStatusLine();
65
68
  },
66
69
  },
@@ -1,93 +1,18 @@
1
1
  /**
2
- * Cost estimation and display formatting.
2
+ * Cost *display* helpers for the terminal UI.
3
3
  *
4
- * Pricing starts from a small hardcoded table, then merges LiteLLM's public
5
- * manifest when it can be fetched. Unknown models deliberately price at $0
6
- * rather than guessing — see `estimateCost`.
4
+ * Pricing and cost resolution live in `@pal-code/core` so the CLI and the UI
5
+ * server cannot drift apart — this module only formats the numbers.
7
6
  */
8
7
 
9
- const MODEL_PRICING: Record<string, {input: number; output: number}> = {
10
- 'anthropic/claude-sonnet-4': {input: 3, output: 15},
11
- 'anthropic/claude-3.5-sonnet': {input: 3, output: 15},
12
- 'openai/gpt-4o': {input: 2.5, output: 10},
13
- 'openai/gpt-4o-mini': {input: 0.15, output: 0.6},
14
- };
15
-
16
- const COST_MANIFEST_URL =
17
- 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
18
-
19
- /** Mutable pricing — hardcoded, upgraded by loadCostManifest() when the fetch succeeds. */
20
- let costManifest: Record<string, {input: number; output: number}> = {...MODEL_PRICING};
21
-
22
- /** True once the remote manifest has been merged in. */
23
- let manifestLoaded = false;
24
-
25
- export function isCostManifestLoaded(): boolean {
26
- return manifestLoaded;
27
- }
28
-
29
- export async function loadCostManifest(): Promise<Record<string, {input: number; output: number}>> {
30
- try {
31
- const res = await fetch(COST_MANIFEST_URL, {signal: AbortSignal.timeout(5000)});
32
- if (!res.ok) return MODEL_PRICING;
33
- const data = (await res.json()) as Record<
34
- string,
35
- {input_cost_per_token?: number; output_cost_per_token?: number}
36
- >;
37
- const manifest: Record<string, {input: number; output: number}> = {};
38
- for (const [model, info] of Object.entries(data)) {
39
- if (info && typeof info === 'object' && 'input_cost_per_token' in info) {
40
- manifest[model] = {
41
- input: (info.input_cost_per_token ?? 0) * 1_000_000,
42
- output: (info.output_cost_per_token ?? 0) * 1_000_000,
43
- };
44
- }
45
- }
46
- costManifest = {...MODEL_PRICING, ...manifest};
47
- manifestLoaded = true;
48
- return costManifest;
49
- } catch {
50
- return MODEL_PRICING; // offline / rate-limited — keep the hardcoded table
51
- }
52
- }
53
-
54
- /** Cached input tokens are billed at roughly 10% of the normal input rate. */
55
- const CACHE_DISCOUNT = 0.1;
56
-
57
- /**
58
- * Cost in USD for one turn.
59
- *
60
- * Tries the full `provider/model` spec, then the bare model name, because
61
- * manifests key differently. Returns 0 for unknown models and for `*free*`
62
- * variants — under-reporting beats inventing a number.
63
- */
64
- /**
65
- * True when we have a price for this model. Unknown models price at $0, so the
66
- * UI uses this to label the figure as an estimate rather than a real cost.
67
- */
68
- export function isPricedModel(model: string): boolean {
69
- if (model.includes(':free') || model.includes('-free')) return true;
70
- const bare = model.includes('/') ? model.split('/').slice(1).join('/') : model;
71
- return Boolean(costManifest[model] ?? costManifest[bare]);
72
- }
73
-
74
- export function estimateCost(
75
- model: string,
76
- inputTokens: number,
77
- outputTokens: number,
78
- cachedTokens = 0,
79
- ): number {
80
- if (model.includes(':free') || model.includes('-free')) return 0;
81
- const bare = model.includes('/') ? model.split('/').slice(1).join('/') : model;
82
- const pricing = costManifest[model] ?? costManifest[bare];
83
- if (!pricing) return 0;
84
- const uncachedInput = Math.max(0, inputTokens - cachedTokens);
85
- return (
86
- (uncachedInput / 1_000_000) * pricing.input +
87
- (cachedTokens / 1_000_000) * pricing.input * CACHE_DISCOUNT +
88
- (outputTokens / 1_000_000) * pricing.output
89
- );
90
- }
8
+ export {
9
+ estimateCost,
10
+ isCostManifestLoaded,
11
+ isPricedModel,
12
+ loadCostManifest,
13
+ registerModelPricing,
14
+ resolveTurnCost,
15
+ } from '@pal-code/core';
91
16
 
92
17
  export function formatTokens(n: number): string {
93
18
  if (n >= 10_000_000) return `${Math.round(n / 1_000_000)}M`;
@@ -97,6 +22,12 @@ export function formatTokens(n: number): string {
97
22
  return String(n);
98
23
  }
99
24
 
25
+ /**
26
+ * `$0.00` for zero, `<$0.01` for a real-but-tiny figure.
27
+ *
28
+ * The distinction matters: a session that genuinely cost $0.004 should not read
29
+ * as free, which is exactly the confusion this whole change exists to fix.
30
+ */
100
31
  export function formatCost(cost: number): string {
101
32
  if (cost === 0) return '$0.00';
102
33
  if (cost < 0.01) return '<$0.01';