opencode-precost 0.0.0-stage → 0.3.2

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/src/gate.js ADDED
@@ -0,0 +1,128 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { estimate, range } from './estimate.js';
5
+ import { format } from './format.js';
6
+ import { loadPrices } from './pricing.js';
7
+ import { contextHash } from './context.js';
8
+ import { tr, setLang } from './i18n.js';
9
+
10
+ // Aprovacao explicita e vinculada. Reenviar o mesmo prompt NUNCA aprova.
11
+ // Fluxo: (1) prompt que nao cabe no limite (ou nao pode ser avaliado) -> bloqueia, cria pendencia com CODIGO aleatorio;
12
+ // (2) o usuario digita "precost approve CODIGO" -> aprovacao vinculada a prompt, modelo, sessao, tabela de precos,
13
+ // limite, faixa alta estimada e arquivos de contexto (hash do conteudo); vale por ttl, uso unico;
14
+ // (3) reenviar o prompt original consome a aprovacao se o vinculo ainda bate.
15
+ // Revogar: "precost revoke CODIGO" ou "precost revoke all": remove pendencias E aprovacoes ja concedidas.
16
+ // LIMITE DE SEGURANCA (declarado): o estado fica em arquivos do mesmo usuario. Um agente com shell/escrita nesse usuario pode
17
+ // forjar aprovacao. O gate protege contra gasto acidental e prompts grandes, NAO contra um agente que queira se autoaprovar.
18
+ const APPROVE = /^\s*precost\s+approve\s+([0-9a-f]{8})\s*$/i;
19
+ const PREVIEW = /^\s*precost\s+(?:estimate|preview)\s+([\s\S]+)$/i;
20
+ const LAST = /^\s*precost\s+last\s*$/i;
21
+ const REVOKE = /^\s*precost\s+revoke\s+([0-9a-f]{8}|all)\s*$/i;
22
+
23
+ export const isCommand = (p) => LAST.test(p) || PREVIEW.test(p) || REVOKE.test(p) || APPROVE.test(p);
24
+ const lastFile = (session) => `last-block-${createHash('sha256').update(String(session ?? 'global')).digest('hex').slice(0, 12)}.txt`;
25
+
26
+ export function bindingHash({ prompt, model, session, pricesHash, limit, maxUsd, ctx = '' }) {
27
+ const max = Number.isFinite(maxUsd) ? Math.round(maxUsd * 1e6) : 'sem-limite-conhecido';
28
+ return createHash('sha256').update(JSON.stringify([prompt, model ?? null, session ?? null, pricesHash, limit, max, ctx])).digest('hex');
29
+ }
30
+ const rd = (f) => { try { return JSON.parse(readFileSync(f, 'utf8')); } catch { return null; } };
31
+ const alive = (r, now) => r && now <= r.expiresAt;
32
+ const blockCfg = (why) => ({ action: 'block', command: 'config', text: tr(`precost: invalid configuration (${why}). Blocked for safety (fail closed) until the configuration is fixed. Nothing was sent to the model.`, `precost: configuracao invalida (${why}). Bloqueado por seguranca (falha fechada) ate corrigir a configuracao. Nada foi enviado ao modelo.`) });
33
+
34
+ export function validateConfig(config = {}) {
35
+ if (config.limitUsd !== undefined && config.limitUsd !== null && !(typeof config.limitUsd === 'number' && Number.isFinite(config.limitUsd) && config.limitUsd >= 0)) return tr(`limitUsd must be a number >= 0, got ${JSON.stringify(config.limitUsd)}`, `limitUsd deve ser numero >= 0, recebido ${JSON.stringify(config.limitUsd)}`);
36
+ if (config.ttlMin !== undefined && !(typeof config.ttlMin === 'number' && Number.isFinite(config.ttlMin) && config.ttlMin > 0)) return tr(`ttlMin must be a number > 0, got ${JSON.stringify(config.ttlMin)}`, `ttlMin deve ser numero > 0, recebido ${JSON.stringify(config.ttlMin)}`);
37
+ if (config.systemTokens !== undefined && !(typeof config.systemTokens === 'number' && Number.isFinite(config.systemTokens) && config.systemTokens >= 0)) return tr('systemTokens must be a number >= 0', 'systemTokens deve ser numero >= 0');
38
+ if (config.trustConfiguredModel !== undefined && typeof config.trustConfiguredModel !== 'boolean') return tr('trustConfiguredModel must be true or false', 'trustConfiguredModel deve ser true ou false');
39
+ if (config.cacheHit !== undefined && !(typeof config.cacheHit === 'number' && config.cacheHit >= 0 && config.cacheHit <= 1)) return tr('cacheHit must be between 0 and 1', 'cacheHit deve estar entre 0 e 1');
40
+ return null;
41
+ }
42
+
43
+ export function decide({ prompt, model, session, config = {}, stateDir, now = Date.now(), history, files = [], modelProof }) {
44
+ setLang(config.lang);
45
+ mkdirSync(stateDir, { recursive: true });
46
+ const bad = validateConfig(config);
47
+ if (bad) return blockCfg(bad);
48
+ const ttl = (config.ttlMin ?? 10) * 60_000;
49
+ if (Array.isArray(history) && new Set([model, ...(config.compare ?? []), ...(modelProof?.candidates ?? [])].filter(Boolean)).size > 1) return blockCfg(tr('history as a single list with several models: use a {model: list} map; mixing histories across models is not allowed', 'historico em lista unica com varios modelos: use mapa {modelo: lista}; misturar historicos entre modelos nao e permitido'));
50
+
51
+ let m;
52
+ if (LAST.test(prompt)) {
53
+ let t = tr('precost: no block recorded in this session.', 'precost: sem bloqueio registrado nesta sessao.'); try { t = readFileSync(join(stateDir, lastFile(session)), 'utf8'); } catch { /* nenhum */ }
54
+ return { action: 'block', text: t, command: 'last' };
55
+ }
56
+ if ((m = PREVIEW.exec(prompt))) { // previa sob demanda: digitada pelo usuario, nunca chega ao modelo, sem gasto
57
+ let prices0; try { prices0 = loadPrices(config.prices); } catch (e) { return blockCfg(tr(`price table unreadable: ${e.message}`, `tabela de precos ilegivel: ${e.message}`)); }
58
+ const r0 = estimate({ systemTokens: config.systemTokens, task: m[1], models: [model, ...(config.compare ?? [])].filter(Boolean).length ? [model, ...(config.compare ?? [])].filter(Boolean) : Object.keys(prices0.models), prices: prices0, history, cacheHit: config.cacheHit ?? 0 });
59
+ return { action: 'block', command: 'preview', text: format(r0, { title: tr(`On-demand preview (ESTIMATE; active model: ${model ?? 'unknown'}). Nothing was sent to the model.`, `Previa sob demanda (ESTIMATIVA; modelo ativo: ${model ?? 'desconhecido'}). Nada foi enviado ao modelo.`) }) };
60
+ }
61
+ if ((m = REVOKE.exec(prompt))) {
62
+ const want = m[1].toLowerCase();
63
+ let n = 0;
64
+ for (const f of readdirSync(stateDir)) {
65
+ if (!/^(pending|approved)-.*\.json$/.test(f)) continue;
66
+ const r = rd(join(stateDir, f));
67
+ if (want === 'all' || !r || r.code === want) { unlinkSync(join(stateDir, f)); n++; }
68
+ }
69
+ return { action: 'block', text: tr(`precost: ${n} pending item(s)/approval(s) revoked.`, `precost: ${n} pendencia(s)/aprovacao(oes) revogada(s).`), command: 'revoke', revoked: n };
70
+ }
71
+ if ((m = APPROVE.exec(prompt))) {
72
+ const code = m[1].toLowerCase();
73
+ const pf = join(stateDir, `pending-${code}.json`);
74
+ const p = existsSync(pf) ? rd(pf) : null;
75
+ if (!p) return { action: 'block', text: tr('precost: unknown, expired or already used code. Nothing was approved.', 'precost: codigo desconhecido, expirado ou ja usado. Nada foi aprovado.'), command: 'approve' };
76
+ if (!alive(p, now)) { unlinkSync(pf); return { action: 'block', text: tr('precost: code expired. Nothing was approved; resend the prompt to get a new one.', 'precost: codigo expirado. Nada foi aprovado; reenvie o prompt para gerar outro.'), command: 'approve' }; }
77
+ if (p.session !== (session ?? null)) return { action: 'block', text: tr('precost: code belongs to another session. Nothing was approved.', 'precost: codigo pertence a outra sessao. Nada foi aprovado.'), command: 'approve' };
78
+ writeFileSync(join(stateDir, `approved-${code}.json`), JSON.stringify({ binding: p.binding, code, expiresAt: now + ttl }));
79
+ unlinkSync(pf);
80
+ return { action: 'block', text: tr(`precost: approved for ${config.ttlMin ?? 10} min, single use. Now resend the original prompt unchanged. To undo: precost revoke ${code}`, `precost: aprovado por ${config.ttlMin ?? 10} min, uso unico. Agora reenvie o prompt original sem alteracao. Para desfazer: precost revoke ${code}`), command: 'approve' };
81
+ }
82
+
83
+ let prices;
84
+ try { prices = loadPrices(config.prices); } catch (e) { return blockCfg(tr(`price table unreadable: ${e.message}`, `tabela de precos ilegivel: ${e.message}`)); }
85
+ const limit = config.limitUsd;
86
+ const gated = typeof limit === 'number';
87
+ const unproven = modelProof && modelProof.proven === false && modelProof.candidates?.length > 1;
88
+ const models = [...new Set([model, ...(unproven ? modelProof.candidates : []), ...(config.compare ?? [])].filter(Boolean))];
89
+ const res = estimate({ systemTokens: config.systemTokens, task: prompt, fileTexts: files.filter((f) => f.text !== undefined).map((f) => f.text), models: models.length ? models : Object.keys(prices.models), prices, history, cacheHit: config.cacheHit ?? 0 });
90
+ const active = model ? res.rows.find((r) => r.model === model && !r.error) : null;
91
+ const skipped = files.filter((f) => f.skipped);
92
+ let text = format(res, { title: tr(`Cost preview (ESTIMATE; active model: ${model ?? 'unknown'})`, `Previa de custo (ESTIMATIVA; modelo ativo: ${model ?? 'desconhecido'})`) });
93
+ if (files.length) text += tr('\nContext files: ', '\nArquivos de contexto: ') + `${files.map((f) => f.skipped ? `${f.path} (${tr('NOT counted', 'NAO contado')}: ${f.skipped})` : `${f.path} (${f.bytes} bytes)`).join(', ')}.`;
94
+ if (!gated) return { action: 'allow', text: text + tr('\nNO GATE: limitUsd is not configured; informational only.', '\nSEM GATE: limitUsd nao configurado; apenas informativo.'), res, ungated: true };
95
+
96
+ // O gate decide se precisa de aprovacao: faixa alta acima do limite, modelo sem preco, ou custo so com limite inferior.
97
+ let reason = null, maxUsd = null, bindModel = model;
98
+ if (!active) reason = tr(`active model ${model ? `"${model}" has no price in the table` : 'unknown'}: cost cannot be evaluated`, `modelo ativo ${model ? `"${model}" sem preco na tabela` : 'desconhecido'}: custo nao pode ser avaliado`);
99
+ else {
100
+ maxUsd = range(active).max;
101
+ if (active.lowerBound) { reason = tr('context above the threshold with no known rate: the value shown is only a lower bound', 'contexto acima do limiar sem taxa conhecida: o valor mostrado e so limite inferior'); maxUsd = Infinity; }
102
+ if (unproven) { // modelo efetivo nao comprovado: o gate usa o PIOR CASO entre os candidatos e diz isso
103
+ const rows = res.rows.filter((r) => modelProof.candidates.includes(r.model) && !r.error);
104
+ const worst = rows.map((r) => ({ r, v: r.lowerBound ? Infinity : range(r).max })).sort((a, b) => b.v - a.v)[0];
105
+ const mine = maxUsd;
106
+ maxUsd = worst.v; bindModel = `${model}|nao-comprovado:${modelProof.source}|pior:${worst.r.model}`;
107
+ text += tr(`\nMODEL NOT PROVEN (source: ${modelProof.source}). The gate uses the WORST CASE of the supported CATALOG (a model outside the catalog is not covered and closes the gate) among ${rows.length} candidate models: ${worst.r.model} ${Number.isFinite(worst.v) ? 'US$' + worst.v.toFixed(2) : 'no known upper bound'}; with ${model} the high range would be ${Number.isFinite(mine) ? 'US$' + mine.toFixed(2) : 'undefined'}. To use the declared model's price, state the model (PRECOST_MODEL or claude --model) or set trustConfiguredModel:true in the config.`, `\nMODELO NAO COMPROVADO (fonte: ${modelProof.source}). O gate usa o PIOR CASO do CATALOGO suportado (modelo fora do catalogo nao e coberto e fecha o gate) entre ${rows.length} modelos candidatos: ${worst.r.model} ${Number.isFinite(worst.v) ? 'US$' + worst.v.toFixed(2) : 'sem limite superior conhecido'}; com ${model} a faixa alta seria ${Number.isFinite(mine) ? 'US$' + mine.toFixed(2) : 'indefinida'}. Para usar o preco do modelo declarado, informe o modelo (PRECOST_MODEL ou claude --model) ou declare trustConfiguredModel:true no config.`);
108
+ if (maxUsd > limit) reason = tr(`effective model not proven and the worst case (${worst.r.model}) exceeds the US$${limit} limit`, `modelo efetivo nao comprovado e o pior caso (${worst.r.model}) passa do limite US$${limit}`);
109
+ } else if (!active.lowerBound && maxUsd > limit) reason = tr(`estimated high range US$${maxUsd.toFixed(2)} above the US$${limit} limit (high range = P75 / large scenario, NOT a spending cap)`, `faixa alta estimada US$${maxUsd.toFixed(2)} acima do limite US$${limit} (faixa alta = P75/cenario grande, NAO e teto de gasto)`);
110
+ }
111
+ if (!reason && skipped.length === 0) return { action: 'allow', text, res };
112
+ if (!reason) reason = tr(`context files not counted (${skipped.map((f) => f.path).join(', ')}): cost may be underestimated`, `arquivos de contexto nao contados (${skipped.map((f) => f.path).join(', ')}): custo pode estar subestimado`);
113
+
114
+ const binding = bindingHash({ prompt, model: bindModel, session, pricesHash: prices._hash, limit, maxUsd, ctx: contextHash(files) });
115
+ for (const f of readdirSync(stateDir)) {
116
+ if (!/^approved-[0-9a-f]{8}\.json$/.test(f)) continue;
117
+ const a = rd(join(stateDir, f));
118
+ if (a && a.binding === binding) {
119
+ unlinkSync(join(stateDir, f)); // uso unico, mesmo expirado
120
+ if (alive(a, now)) return { action: 'allow', text: text + tr(`\n(approval ${a.code} consumed)`, `\n(aprovacao ${a.code} consumida)`), res, approved: true };
121
+ }
122
+ }
123
+ const code = randomBytes(4).toString('hex');
124
+ writeFileSync(join(stateDir, `pending-${code}.json`), JSON.stringify({ binding, code, session: session ?? null, expiresAt: now + ttl }));
125
+ const out = text + tr(`\n\nBLOCKED: ${reason}. Resending the prompt does NOT approve it. To approve this prompt, on this model, with these prices and these files, type exactly: precost approve ${code} (valid ${config.ttlMin ?? 10} min, single use; undo with precost revoke ${code}). Then resend the prompt unchanged. This does not cap spending during the task.`, `\n\nBLOQUEADO: ${reason}. Reenviar o prompt NAO aprova. Para aprovar este prompt, neste modelo, com estes precos e estes arquivos, digite exatamente: precost approve ${code} (vale ${config.ttlMin ?? 10} min, uso unico; desfaz com precost revoke ${code}). Depois reenvie o prompt sem alteracao. Isto nao limita o gasto durante a tarefa.`);
126
+ writeFileSync(join(stateDir, lastFile(session)), out);
127
+ return { action: 'block', code, text: out, res };
128
+ }
package/src/history.js ADDED
@@ -0,0 +1,39 @@
1
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+
4
+ // Acumula tokens reais por sessao a partir de mensagens do assistente concluidas.
5
+ // Dedup por id de mensagem (o evento message.updated dispara varias vezes por mensagem).
6
+ export class SessionLedger {
7
+ constructor(path) { this.path = path; this.msgs = new Map(); this.sessions = new Map(); this.load(); }
8
+ load() {
9
+ if (!this.path) return;
10
+ try {
11
+ const j = JSON.parse(readFileSync(this.path, 'utf8'));
12
+ for (const s of Array.isArray(j) ? j : j.sessions) this.sessions.set(s.session, s);
13
+ for (const [id, m] of Object.entries(Array.isArray(j) ? {} : j.msgs ?? {})) this.msgs.set(id, m);
14
+ } catch { /* arquivo novo */ }
15
+ }
16
+ record({ id, sessionID, cost, tokens, model, project }) {
17
+ if (this.msgs.has(id)) { // substitui valor anterior da mesma mensagem
18
+ const old = this.msgs.get(id);
19
+ this.apply(old.sessionID ?? sessionID, old, -1);
20
+ }
21
+ const m = { model: model ?? null, project: project ?? null, ctx: (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0), cost: cost ?? 0, input: tokens.input, output: tokens.output + (tokens.reasoning ?? 0), cache_read: tokens.cache?.read ?? 0, cache_write: tokens.cache?.write ?? 0 };
22
+ this.msgs.set(id, { ...m, sessionID });
23
+ this.apply(sessionID, m, 1);
24
+ this.save();
25
+ }
26
+ apply(sessionID, m, sign) {
27
+ const s = this.sessions.get(sessionID) ?? { session: sessionID, turns: 0, input: 0, output: 0, cache_read: 0, cache_write: 0, cost: 0 };
28
+ s.turns += sign; s.input += sign * m.input; s.output += sign * m.output; s.cache_read += sign * m.cache_read; s.cache_write += sign * m.cache_write; s.cost += sign * m.cost;
29
+ this.sessions.set(sessionID, s);
30
+ }
31
+ spent(sessionID) { return this.sessions.get(sessionID)?.cost ?? 0; }
32
+ // peakCtx = maior contexto REAL (entrada+cache) de uma chamada da sessao, a partir das mensagens registradas.
33
+ list() {
34
+ const peak = new Map(), meta = new Map();
35
+ for (const m of this.msgs.values()) { peak.set(m.sessionID, Math.max(peak.get(m.sessionID) ?? 0, m.ctx ?? 0)); const x = meta.get(m.sessionID) ?? { models: new Set(), projects: new Set() }; x.models.add(m.model); x.projects.add(m.project); meta.set(m.sessionID, x); }
36
+ return [...this.sessions.values()].map((s) => { const x = meta.get(s.session); const one = (set) => (set && set.size === 1 ? [...set][0] : null); return { ...s, ...(peak.get(s.session) > 0 ? { peakCtx: peak.get(s.session) } : {}), model: one(x?.models), project: one(x?.projects) }; });
37
+ }
38
+ save() { if (!this.path) return; mkdirSync(dirname(this.path), { recursive: true }); writeFileSync(this.path, JSON.stringify({ sessions: this.list(), msgs: Object.fromEntries(this.msgs) }, null, 1)); }
39
+ }
package/src/i18n.js ADDED
@@ -0,0 +1,11 @@
1
+ // Idioma das mensagens impressas pela ferramenta. Padrao: ingles. Escolha: config.lang ("en" | "pt"), senao PRECOST_LANG, senao "en".
2
+ // Somente o TEXTO muda. Comandos (precost approve CODE ...), codigos, chaves de config e o comportamento do gate nao dependem do idioma.
3
+ let current = null;
4
+ export const resolveLang = (v) => {
5
+ const x = String(v ?? process.env.PRECOST_LANG ?? 'en').toLowerCase();
6
+ return x.startsWith('pt') ? 'pt' : 'en';
7
+ };
8
+ export const setLang = (v) => { current = resolveLang(v); return current; };
9
+ export const lang = () => current ?? resolveLang();
10
+ // tr(en, pt): as duas versoes sao montadas no ponto de uso; so uma e devolvida.
11
+ export const tr = (en, pt) => (lang() === 'pt' ? pt : en);
package/src/paths.js ADDED
@@ -0,0 +1,22 @@
1
+ // Diretorios por plataforma. Linux/macOS mantem os caminhos da v0.2.0; Windows usa APPDATA/LOCALAPPDATA.
2
+ // Variaveis PRECOST_STATE / PRECOST_CONFIG continuam mandando em todas as plataformas.
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ const isWin = (platform) => platform === 'win32';
7
+ const roaming = (env) => env.APPDATA ?? join(homedir(), 'AppData', 'Roaming');
8
+ const local = (env) => env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local');
9
+
10
+ export const stateDir = (env = process.env, platform = process.platform) =>
11
+ env.PRECOST_STATE ?? (isWin(platform) ? join(local(env), 'precost', 'state') : join(homedir(), '.cache', 'precost'));
12
+ export const configPath = (env = process.env, platform = process.platform) =>
13
+ env.PRECOST_CONFIG ?? (isWin(platform) ? join(roaming(env), 'precost', 'config.json') : join(homedir(), '.config', 'precost', 'config.json'));
14
+ export const ledgerPath = (env = process.env, platform = process.platform) =>
15
+ isWin(platform) ? join(local(env), 'precost', 'sessions.json') : join(homedir(), '.local', 'share', 'precost', 'sessions.json');
16
+ // Tabela de precos atualizada pelo usuario (precost update-prices). Fica ao lado da config.
17
+ export const userPricesPath = (env = process.env, platform = process.platform) =>
18
+ env.PRECOST_PRICES ?? join(configPath(env, platform), '..', 'prices.json');
19
+ // Id de sessao vira nome de arquivo: troca o que Windows/macOS nao aceitam em nomes.
20
+ export const safeId = (id) => String(id).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120);
21
+ export const claudeConfigDir = (env = process.env) => env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
22
+ export const opencodeConfigDir = (env = process.env) => join(env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'opencode');
@@ -0,0 +1,42 @@
1
+ import { loadPrices } from './pricing.js';
2
+ import { tr, setLang } from './i18n.js';
3
+ import { userPricesPath } from './paths.js';
4
+ import { STALE_DAYS, DEFAULT_PRICES_SOURCE, validatePrices, tableDate, ageDays, diffPrices, fetchSource, writeUserPrices, resetUserPrices } from './prices-update.js';
5
+
6
+ const usage = () => tr(`usage:
7
+ precost prices show which table is in use, its date and age
8
+ precost update-prices [--from HTTPS_URL|FILE] [--yes] [--force] (default: the table published in the project repository; or PRECOST_PRICES_SOURCE)
9
+ without --yes: only shows the diff (nothing is written). --force: accept removals and changes > 5x.
10
+ precost update-prices --reset remove the user table (back to the bundled one)`, `uso:
11
+ precost prices mostra qual tabela esta em uso, data e idade
12
+ precost update-prices [--from URL_HTTPS|ARQUIVO] [--yes] [--force] (padrao: a tabela publicada no repositorio do projeto; ou PRECOST_PRICES_SOURCE)
13
+ sem --yes: so mostra o diff (nada e gravado). --force: aceita remocoes e variacoes > 5x.
14
+ precost update-prices --reset remove a tabela do usuario (volta para a embutida)`);
15
+
16
+ export async function runPricesCli(cmd, args, { out = console.log, err = console.error } = {}) {
17
+ const o = { from: null, yes: false, force: false, reset: false };
18
+ for (let i = 0; i < args.length; i++) { const a = args[i]; if (a === '--from') o.from = args[++i]; else if (a === '--yes') o.yes = true; else if (a === '--force') o.force = true; else if (a === '--reset') o.reset = true; else { err(usage()); return 2; } }
19
+ setLang(undefined);
20
+ let cur; try { cur = loadPrices(); } catch (e) { err(tr(`precost: current table unreadable: ${e.message}`, `precost: tabela atual ilegivel: ${e.message}`)); return 1; }
21
+ const ag = ageDays(cur);
22
+ if (cmd === 'prices') {
23
+ out(tr(`table in use: ${cur._source.kind} (${cur._source.path})\ndate: ${tableDate(cur)}${ag === null ? '' : ` (${ag} days)`}; ${Object.keys(cur.models).length} models; hash ${cur._hash}`, `tabela em uso: ${cur._source.kind} (${cur._source.path})\ndata: ${tableDate(cur)}${ag === null ? '' : ` (${ag} dias)`}; ${Object.keys(cur.models).length} modelos; hash ${cur._hash}`));
24
+ if (ag !== null && ag > STALE_DAYS) out(tr(`WARNING: older than ${STALE_DAYS} days. Run \`precost update-prices\`. Prices change; the estimate may be outdated.`, `AVISO: mais de ${STALE_DAYS} dias. Rode \`precost update-prices\`. Precos mudam; a estimativa pode estar defasada.`));
25
+ return 0;
26
+ }
27
+ if (o.reset) { out(resetUserPrices(userPricesPath()) ? tr('user table removed; the bundled one applies again.', 'tabela do usuario removida; volta a valer a embutida.') : tr('there was no user table.', 'nao havia tabela do usuario.')); return 0; }
28
+ const source = o.from || process.env.PRECOST_PRICES_SOURCE || DEFAULT_PRICES_SOURCE;
29
+ let got; try { got = await fetchSource(source); } catch (e) { err(tr(`precost: could not get ${source}: ${e.message}. Current table kept.`, `precost: nao consegui obter ${source}: ${e.message}. Tabela atual mantida.`)); return 1; }
30
+ const bad = validatePrices(got.table); if (bad) { err(tr(`precost: table rejected (${bad}). Current table kept.`, `precost: tabela recusada (${bad}). Tabela atual mantida.`)); return 1; }
31
+ const nd = tableDate(got.table), cd = tableDate(cur);
32
+ if (cd && nd && nd < cd && !o.force) { err(tr(`precost: new table (${nd}) is older than the current one (${cd}). Use --force if intended.`, `precost: tabela nova (${nd}) e mais antiga que a atual (${cd}). Use --force se for proposital.`)); return 1; }
33
+ const d = diffPrices(cur, got.table);
34
+ out(tr(`source: ${source}\ncurrent: ${cd} (${cur._source.kind}) -> new: ${nd}; ${d.changes.length} change(s)`, `fonte: ${source}\natual: ${cd} (${cur._source.kind}) -> nova: ${nd}; ${d.changes.length} alteracao(oes)`));
35
+ for (const c of d.changes) out(c.kind === 'preco' ? ` ${c.id}.${c.field}: ${c.from ?? tr('unknown', 'desconhecido')} -> ${c.to ?? tr('unknown', 'desconhecido')}` : ` ${c.id}: ${tr({ removido: 'removed', novo: 'new' }[c.kind] ?? c.kind, c.kind)}`);
36
+ if ((d.big.length || d.removed) && !o.force) { err(tr(`precost: suspicious changes (${d.removed} removed${d.big.length ? '; change > 5x: ' + d.big.join('; ') : ''}). Check the source and use --force.`, `precost: mudancas suspeitas (${d.removed} removido(s)${d.big.length ? '; variacao > 5x: ' + d.big.join('; ') : ''}). Confira a fonte e use --force.`)); return 1; }
37
+ if (!d.changes.length && nd === cd) { out(tr('already up to date.', 'ja esta atualizada.')); return 0; }
38
+ if (!o.yes) { out(tr('nothing written. To apply: precost update-prices --yes', 'nada gravado. Para aplicar: precost update-prices --yes') + (o.from ? ` --from ${o.from}` : '')); return 0; }
39
+ writeUserPrices(userPricesPath(), got.raw);
40
+ out(tr(`written to ${userPricesPath()}. Pending approvals become invalid (the table is part of the binding). An estimate is still an estimate; check the official source.`, `gravado em ${userPricesPath()}. Aprovacoes pendentes ficam invalidas (a tabela entra no vinculo). Estimativa continua sendo estimativa; confira a fonte oficial.`));
41
+ return 0;
42
+ }
@@ -0,0 +1,70 @@
1
+ // Atualizacao da tabela de precos de referencia: valida, mostra o diff e so grava com --yes.
2
+ // NUNCA roda dentro do hook/plugin (so na CLI). O gate le o arquivo local; falha de rede nao afeta bloqueio.
3
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync } from 'node:fs';
4
+ import { dirname } from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+ import { tr } from './i18n.js';
7
+
8
+ // Sem fonte padrao embutida: uma URL que ainda nao existe falharia em campo. Informe --from ou PRECOST_PRICES_SOURCE.
9
+ export const STALE_DAYS = 30;
10
+ // Default source: the table published on the main branch of the project repository (see docs/PRICES.md).
11
+ // It only works once the repository is public; until then the command fails with a clear message and keeps the current table.
12
+ export const DEFAULT_PRICES_SOURCE = 'https://raw.githubusercontent.com/glauberportella/opencode-precost/main/data/prices.json';
13
+ const NUM_FIELDS = ['input', 'output', 'cache_read', 'cache_write_5m', 'cache_write', 'tokenizer_multiplier'];
14
+
15
+ export function validatePrices(t) {
16
+ if (!t || typeof t !== 'object' || Array.isArray(t)) return tr('table is not a JSON object', 'tabela nao e um objeto JSON');
17
+ if (t.currency !== 'USD') return tr('currency must be "USD"', 'currency deve ser "USD"');
18
+ if (!t.models || typeof t.models !== 'object' || !Object.keys(t.models).length) return tr('models missing or empty', 'models ausente ou vazio');
19
+ for (const [id, m] of Object.entries(t.models)) {
20
+ if (!m || typeof m !== 'object') return tr(`${id}: invalid entry`, `${id}: entrada invalida`);
21
+ for (const f of ['input', 'output']) if (!(typeof m[f] === 'number' && Number.isFinite(m[f]) && m[f] >= 0)) return tr(`${id}: ${f} must be a number >= 0`, `${id}: ${f} deve ser numero >= 0`);
22
+ for (const f of NUM_FIELDS) if (m[f] !== undefined && !(typeof m[f] === 'number' && Number.isFinite(m[f]) && m[f] >= 0)) return tr(`${id}: ${f} must be a number >= 0 (missing field = unknown)`, `${id}: ${f} deve ser numero >= 0 (campo ausente = desconhecido)`);
23
+ if (typeof m.source !== 'string' || !/^https:\/\//.test(m.source)) return tr(`${id}: source (https) is required`, `${id}: source (https) obrigatorio`);
24
+ if (typeof m.read !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(m.read)) return tr(`${id}: read (date yyyy-mm-dd) is required`, `${id}: read (data yyyy-mm-dd) obrigatorio`);
25
+ }
26
+ return null;
27
+ }
28
+
29
+ // Data da tabela = leitura mais recente entre os modelos (yyyy-mm-dd).
30
+ export const tableDate = (t) => Object.values(t.models ?? {}).map((m) => String(m.read ?? '').slice(0, 10)).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)).sort().pop() ?? null;
31
+ export const ageDays = (t, now = Date.now()) => { const d = tableDate(t); return d ? Math.max(0, Math.floor((now - Date.parse(d + 'T00:00:00Z')) / 864e5)) : null; };
32
+
33
+ const CMP = ['input', 'output', 'cache_read', 'cache_write_5m', 'cache_write'];
34
+ export function diffPrices(oldT, newT) {
35
+ const changes = [], big = [];
36
+ for (const id of Object.keys(oldT.models)) if (!newT.models[id]) changes.push({ id, kind: 'removido' });
37
+ for (const [id, m] of Object.entries(newT.models)) {
38
+ const o = oldT.models[id];
39
+ if (!o) { changes.push({ id, kind: 'novo' }); continue; }
40
+ for (const f of CMP) {
41
+ if (o[f] === m[f]) continue;
42
+ changes.push({ id, kind: 'preco', field: f, from: o[f] ?? null, to: m[f] ?? null });
43
+ if (typeof o[f] === 'number' && typeof m[f] === 'number' && o[f] > 0 && (m[f] / o[f] > 5 || m[f] / o[f] < 0.2)) big.push(`${id}.${f}: ${o[f]} -> ${m[f]}`);
44
+ }
45
+ }
46
+ const removed = changes.filter((c) => c.kind === 'removido').length;
47
+ return { changes, big, removed };
48
+ }
49
+
50
+ export async function fetchSource(source, { fetchImpl = globalThis.fetch, timeoutMs = 15000, maxBytes = 1_000_000 } = {}) {
51
+ let raw;
52
+ if (/^https?:\/\//i.test(source)) {
53
+ const u = new URL(source);
54
+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
55
+ if (u.protocol !== 'https:' && !loopback) throw new Error(tr('remote source must be https', 'fonte remota precisa ser https'));
56
+ const r = await fetchImpl(source, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
57
+ if (!r.ok) throw new Error(tr(`HTTP ${r.status} while downloading ${source}`, `HTTP ${r.status} ao baixar ${source}`));
58
+ raw = await r.text();
59
+ } else raw = readFileSync(source, 'utf8');
60
+ if (Buffer.byteLength(raw) > maxBytes) throw new Error(tr('table too large (> 1 MB)', 'tabela grande demais (> 1 MB)'));
61
+ let t; try { t = JSON.parse(raw); } catch { throw new Error(tr('source is not valid JSON', 'fonte nao e JSON valido')); }
62
+ return { raw, table: t };
63
+ }
64
+
65
+ export function writeUserPrices(path, raw) {
66
+ mkdirSync(dirname(path), { recursive: true });
67
+ const tmp = `${path}.${process.pid}.tmp`; writeFileSync(tmp, raw); renameSync(tmp, path);
68
+ }
69
+ export function resetUserPrices(path) { if (existsSync(path)) { unlinkSync(path); return true; } return false; }
70
+ export const hashOf = (raw) => createHash('sha256').update(raw).digest('hex').slice(0, 16);
package/src/pricing.js ADDED
@@ -0,0 +1,84 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { userPricesPath } from './paths.js';
6
+ import { validatePrices, tableDate } from './prices-update.js';
7
+ import { tr } from './i18n.js';
8
+ const BUNDLED = fileURLToPath(new URL('../data/prices.json', import.meta.url));
9
+
10
+ // Sem caminho explicito: usa a tabela do usuario (precost update-prices) se for valida e NAO mais antiga que a embutida;
11
+ // caso contrario a embutida. Caminho explicito (config.prices / --prices) manda e falha se ilegivel.
12
+ function pick(path) {
13
+ if (path) return { p: path, source: 'explicit' };
14
+ try {
15
+ const up = userPricesPath(); const raw = readFileSync(up, 'utf8'); const t = JSON.parse(raw);
16
+ if (!validatePrices(t)) { const b = JSON.parse(readFileSync(BUNDLED, 'utf8')); if ((tableDate(t) ?? '') >= (tableDate(b) ?? '')) return { p: up, source: 'user', raw }; }
17
+ } catch { /* sem tabela do usuario ou invalida: embutida */ }
18
+ return { p: BUNDLED, source: 'bundled' };
19
+ }
20
+ export function loadPrices(path) {
21
+ const { p, source } = pick(path);
22
+ const raw = readFileSync(p, 'utf8');
23
+ const prices = JSON.parse(raw);
24
+ prices._source = { kind: source, path: p };
25
+ prices._hash = createHash('sha256').update(raw).digest('hex').slice(0, 16); // entra no vinculo da aprovacao
26
+ return prices;
27
+ }
28
+
29
+ // Preco vigente numa data (yyyy-mm-dd). Campo ausente continua ausente.
30
+ // Normaliza ids de modelo ("anthropic/claude-sonnet-5-5-20261001[1m]" -> "claude-sonnet-5.5"). Desconhecido continua desconhecido.
31
+ export function resolveModel(prices, id) {
32
+ if (!id) return null;
33
+ if (prices.models[id]) return id;
34
+ const n = String(id).toLowerCase().replace(/^[a-z-]+\//, '').replace(/\[.*\]$/, '').replace(/-\d{8}$/, '').replace(/(\d)-(\d)/g, '$1.$2');
35
+ return prices.models[n] ? n : null;
36
+ }
37
+ export function priceAt(prices, model, date = new Date().toISOString().slice(0, 10)) {
38
+ const key = resolveModel(prices, model);
39
+ const m = key && prices.models[key];
40
+ if (!m) return null;
41
+ let cur = { ...m };
42
+ for (const ch of (m.changes ?? []).slice().sort((a, b) => a.from.localeCompare(b.from))) {
43
+ if (date >= ch.from) cur = { ...cur, ...ch };
44
+ }
45
+ return cur;
46
+ }
47
+
48
+ const has = (v) => typeof v === 'number';
49
+
50
+ // Custo de uma lista de chamadas [{ctx, cachedIn, out}] (ctx = tokens de entrada da chamada).
51
+ // Acima do limiar, todos os tokens da chamada usam a taxa longa (se a tabela a tiver).
52
+ export function costCalls(price, calls, defaultThreshold = 200000) {
53
+ const threshold = price.long_context_threshold ?? defaultThreshold;
54
+ let usd = 0, cacheKnown = true, longUnknown = false;
55
+ for (const c of calls) {
56
+ const tier = typeof price.long_context === 'object' && price.long_context;
57
+ const long = c.ctx > threshold && tier;
58
+ if (c.ctx > threshold && price.long_context === 'unknown') longUnknown = true;
59
+ const r = long ? { ...price, ...price.long_context } : price;
60
+ const cachedRate = has(r.cache_read) ? r.cache_read : r.input;
61
+ if (c.cachedIn > 0 && !has(r.cache_read)) cacheKnown = false;
62
+ const freshRate = r.cache_write_5m ?? r.input; // conservador: entrada nova como cache write quando o preco existe
63
+ usd += ((c.ctx - c.cachedIn) * freshRate + c.cachedIn * cachedRate + c.out * r.output) / 1e6;
64
+ }
65
+ return { usd, cacheKnown, longUnknown };
66
+ }
67
+
68
+ // Custo de totais agregados (historico real): nao ha ctx por chamada, entao so a taxa base.
69
+ export function costTotals(price, { freshIn, cachedIn = 0, out, peak, cacheWrite = 0 }, defaultThreshold = 200000) {
70
+ const threshold = price.long_context_threshold ?? defaultThreshold;
71
+ const cacheKnown = has(price.cache_read) || cachedIn === 0;
72
+ const cachedRate = has(price.cache_read) ? price.cache_read : price.input;
73
+ // O limiar e POR CHAMADA e o total agregado nao diz o contexto de cada chamada. Media por chamada nao prova ausencia de picos.
74
+ // So com pico REAL registrado (peak) da pra afirmar: pico acima do limiar = limite inferior; abaixo = sem faixa longa.
75
+ // Pico desconhecido = incerteza: limite inferior (exige aprovacao no gate).
76
+ let longUnknown = false;
77
+ if (typeof price.long_context === 'object' || price.long_context === 'unknown') {
78
+ if (typeof peak !== 'number') longUnknown = true;
79
+ else if (peak > threshold) longUnknown = true;
80
+ else longUnknown = tr(`recorded real peak ${peak} tokens/call, below the ${threshold} threshold: the long-context tier does not apply to the history`, `pico real registrado ${peak} tokens/chamada, abaixo do limiar ${threshold}: faixa longa nao se aplica ao historico`);
81
+ }
82
+ const w = price.cache_write_5m ?? price.input;
83
+ return { usd: (freshIn * (price.cache_write_5m ?? price.input) + cacheWrite * w + cachedIn * cachedRate + out * price.output) / 1e6, cacheKnown, longUnknown };
84
+ }
package/src/tokens.js ADDED
@@ -0,0 +1,8 @@
1
+ // Contagem aproximada: caracteres / 4. E uma estimativa, nao o tokenizer do provedor.
2
+ // Troque por um contador real passando `counter` para estimate().
3
+ export function approxTokens(text) {
4
+ if (!text) return 0;
5
+ return Math.ceil(text.length / 4);
6
+ }
7
+ import { tr } from './i18n.js';
8
+ export const tokenMethod = () => tr('chars/4 (approximate; the provider tokenizer may differ)', 'chars/4 (aproximado; tokenizer do provedor pode diferir)');