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/.claude-plugin/marketplace.json +8 -0
- package/.claude-plugin/plugin.json +17 -0
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/README.pt-BR.md +70 -0
- package/adapters/claude-code/settings.example.json +44 -0
- package/adapters/claude-code/track-model.js +12 -0
- package/adapters/claude-code/userpromptsubmit.js +62 -0
- package/adapters/opencode/index.js +96 -0
- package/bin/precost.js +41 -0
- package/data/prices.json +241 -0
- package/docs/CAPABILITIES.md +54 -0
- package/docs/CAPACIDADES.md +89 -0
- package/docs/DISTRIBUTION.md +41 -0
- package/docs/INSTALACAO.pt-BR.md +78 -0
- package/docs/INSTALLATION.md +92 -0
- package/docs/PRICES.md +29 -0
- package/docs/PRIMEIRO-USO.md +33 -0
- package/docs/img/01-preview-and-block.png +0 -0
- package/docs/img/02-single-use-approval.png +0 -0
- package/docs/img/03-estimate-cli.png +0 -0
- package/docs/img/04-update-prices.png +0 -0
- package/docs/img/05-opencode-tui.png +0 -0
- package/hooks/hooks.json +13 -0
- package/package.json +56 -4
- package/src/claude-model.js +37 -0
- package/src/claude-transcript.js +60 -0
- package/src/context.js +45 -0
- package/src/doctor.js +57 -0
- package/src/estimate.js +104 -0
- package/src/format.js +22 -0
- package/src/gate.js +128 -0
- package/src/history.js +39 -0
- package/src/i18n.js +11 -0
- package/src/paths.js +22 -0
- package/src/prices-cli.js +42 -0
- package/src/prices-update.js +70 -0
- package/src/pricing.js +84 -0
- package/src/tokens.js +8 -0
package/docs/PRICES.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Price table: how it is published and updated
|
|
2
|
+
|
|
3
|
+
`precost` ships a bundled table (`data/prices.json`). Prices change, so the estimate is only as good as the table date.
|
|
4
|
+
`precost prices` shows the table in use, its date and age. After 30 days it prints a warning.
|
|
5
|
+
|
|
6
|
+
## For users
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
precost update-prices # shows the diff against the table in use; writes nothing
|
|
10
|
+
precost update-prices --yes # applies it (stored next to the config; pending approvals become invalid)
|
|
11
|
+
precost update-prices --reset # back to the bundled table
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
- Default source: `https://raw.githubusercontent.com/glauberportella/opencode-precost/main/data/prices.json`
|
|
15
|
+
(the table on `main` of the project repository). It works only after the repository is public. Before that the command
|
|
16
|
+
fails with an HTTP error, keeps the current table, and exit code is 1.
|
|
17
|
+
- Other source: `--from HTTPS_URL|FILE` or `PRECOST_PRICES_SOURCE`. Remote sources must be https.
|
|
18
|
+
- Safety checks before anything is written: valid JSON under 1 MB, every model has an https `source`, a table older than
|
|
19
|
+
the current one is refused (`--force` overrides), and removed models or changes above 5x need `--force`.
|
|
20
|
+
- A newer table is only used if valid; an invalid one never replaces the current one.
|
|
21
|
+
|
|
22
|
+
## For the maintainer
|
|
23
|
+
|
|
24
|
+
1. Check each model price in the vendor's official pricing page. Put that page in the model's `source` and the check date in `read`.
|
|
25
|
+
2. Edit `data/prices.json`, run `npm test`, commit to `dev/*`, merge to `main`. The raw URL above serves `main`, so merging is publishing.
|
|
26
|
+
3. Check with `precost update-prices --from data/prices.json` (diff only) before merging.
|
|
27
|
+
4. Do this at least every 30 days. Older tables warn every user.
|
|
28
|
+
|
|
29
|
+
The table is an estimate input, not an official price list. The project does not guarantee that prices are current.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Primeiro uso guiado (sem gasto, Linux)
|
|
2
|
+
|
|
3
|
+
> Instalação, `doctor` e escopo atual: ver `docs/INSTALACAO.pt-BR.md`. Este arquivo é o guia inicial da CLI; trechos marcados como simulados ou não verificados foram superados por `docs/CAPACIDADES.md` (Atualizações 6 a 8).
|
|
4
|
+
|
|
5
|
+
Recorte de prova de conceito local. Nada aqui chama modelo pago. Saidas reais capturadas em `docs/exemplos/` (rodadas em 25/nov/2026, Node 22).
|
|
6
|
+
|
|
7
|
+
## Passos minimos
|
|
8
|
+
```
|
|
9
|
+
git clone git@github.com:glauberportella/opencode-precost.git && cd opencode-precost
|
|
10
|
+
node --version # precisa de Node >= 20
|
|
11
|
+
node bin/precost.js estimate "Adicionar paginacao na listagem de pedidos e escrever testes" \
|
|
12
|
+
--model gemini-3.5-flash --model claude-sonnet-5.5 --model gemini-4-neon
|
|
13
|
+
```
|
|
14
|
+
Sem dependencias para a CLI. Para rodar os testes: `npm ci && npm test` (54 testes). Para o teste real no OpenCode 1.19.6 sem modelo pago: `npm run e2e:opencode`.
|
|
15
|
+
|
|
16
|
+
## O que a saida mostra (docs/exemplos/compare.txt)
|
|
17
|
+
- OBSERVADO: so caracteres. CONTEXTO INICIAL ESTIMADO: chars/4 + 8k de sistema (premissa).
|
|
18
|
+
- Uma faixa por modelo (tres cenarios fixos, nao medidos). O valor alto e P75/cenario grande, nao e teto.
|
|
19
|
+
- Claude: tokens observados x1,3 e entrada nova cobrada como cache write (conservador). gemini-4-neon: sem faixa >200K na tabela, entao "AO MENOS" (limite inferior).
|
|
20
|
+
- Comparar com historico por modelo: `--history docs/exemplos/historico-por-modelo.json` (arquivo SINTETICO de exemplo, mapa modelo -> sessoes). Cada linha usa so o seu historico (docs/exemplos/compare-historico-por-linha.txt).
|
|
21
|
+
|
|
22
|
+
## Gate com aprovacao (simulado, sem Claude Code real)
|
|
23
|
+
`docs/exemplos/bloqueio-hook.txt` e `ciclo-aprovacao-hook-simulado.txt`: bloqueio, `precost approve CODIGO`, reenvio permitido uma vez, reenvio seguinte bloqueado. Configuracao: `~/.config/precost/config.json` com `{"model":"claude-sonnet-5.5","limitUsd":5}` e o hook de `adapters/claude-code/settings.example.json`.
|
|
24
|
+
|
|
25
|
+
## Limites atuais
|
|
26
|
+
Estimativa, nao custo. Gate age antes do prompt, nao limita o gasto da tarefa. OpenCode so 1.19.6 (bloqueio por throw nao documentado). Claude Code real testado so em `-p` e contra servidor falso; modo interativo e toast/TUI do OpenCode nao verificados. Estado de aprovacao em arquivo do mesmo usuario. Carbon/Argon: preco bruto inferido. Historico real nao validado.
|
|
27
|
+
|
|
28
|
+
## Proximos passos concretos
|
|
29
|
+
1. Rodar uma vez no Claude Code real (usuario aceita) e registrar se o motivo do bloqueio aparece e se SessionStart traz o modelo.
|
|
30
|
+
2. Rodar uma sessao curta real no OpenCode (gasto pequeno, com aprovacao dele) para observar `message.updated` com custo/tokens e validar o historico e o ledger.
|
|
31
|
+
3. Validar o preco bruto de Carbon/Argon na fatura/console.
|
|
32
|
+
4. Comando nativo `/precost` e evidencia de TUI.
|
|
33
|
+
5. Ajustar faixa por tamanho de tarefa com historico real.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/hooks/hooks.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"SessionStart": [
|
|
4
|
+
{ "hooks": [ { "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/adapters/claude-code/track-model.js"] } ] }
|
|
5
|
+
],
|
|
6
|
+
"PostModelSwitch": [
|
|
7
|
+
{ "hooks": [ { "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/adapters/claude-code/track-model.js"] } ] }
|
|
8
|
+
],
|
|
9
|
+
"UserPromptSubmit": [
|
|
10
|
+
{ "hooks": [ { "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/adapters/claude-code/userpromptsubmit.js"], "timeout": 20, "onFailure": "block" } ] }
|
|
11
|
+
]
|
|
12
|
+
}
|
|
13
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-precost",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "Cost range preview and approval gate before a task runs in coding agents (OpenCode, Claude Code). An estimate, not a spending cap.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"precost": "bin/precost.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test",
|
|
11
|
+
"e2e:opencode": "bash scripts/opencode-gate-e2e.sh",
|
|
12
|
+
"e2e:claude": "bash scripts/claude-code-e2e.sh",
|
|
13
|
+
"e2e:claude-failure": "bash scripts/claude-failure-e2e.sh",
|
|
14
|
+
"e2e:opencode-tui": "python3 scripts/opencode-tui-e2e.py",
|
|
15
|
+
"e2e:claude-tui": "python3 scripts/claude-tui-e2e.py",
|
|
16
|
+
"e2e:opencode-ledger": "bash scripts/opencode-ledger-e2e.sh",
|
|
17
|
+
"e2e:claude-plugin": "bash scripts/claude-plugin-e2e.sh",
|
|
18
|
+
"e2e:claude-plugin-failure": "bash scripts/claude-plugin-failure-e2e.sh",
|
|
19
|
+
"e2e:native": "node scripts/e2e-native.mjs",
|
|
20
|
+
"e2e:packaged": "node scripts/packaged-e2e.mjs"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
},
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"main": "adapters/opencode/index.js",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./adapters/opencode/index.js",
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"adapters",
|
|
33
|
+
"bin",
|
|
34
|
+
"src",
|
|
35
|
+
"data",
|
|
36
|
+
"docs/*.md",
|
|
37
|
+
"docs/img",
|
|
38
|
+
"hooks",
|
|
39
|
+
".claude-plugin",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"keywords": [
|
|
44
|
+
"opencode",
|
|
45
|
+
"opencode-plugin",
|
|
46
|
+
"claude-code",
|
|
47
|
+
"cost",
|
|
48
|
+
"budget",
|
|
49
|
+
"estimate"
|
|
50
|
+
],
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/glauberportella/opencode-precost.git"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@opencode-ai/plugin": "1.19.6"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { claudeConfigDir } from './paths.js';
|
|
4
|
+
import { tr } from './i18n.js';
|
|
5
|
+
|
|
6
|
+
// Modelo ativo do Claude Code. O evento do hook NAO traz modelo (observado na 2.1.332), entao a resolucao vem de fontes indiretas.
|
|
7
|
+
// Nenhuma e prova tecnica do modelo do PROXIMO prompt. PRECOST_MODEL e declaracao do operador (aceita sem pior caso; nao forca o request).
|
|
8
|
+
// OBSERVADAS (rastreador, ultima resposta no transcript, flag --model do processo, Linux /proc): so valem com trustConfiguredModel:true e sem /model pendente.
|
|
9
|
+
// DECLARADAS (ANTHROPIC_MODEL, "model" nos settings do Claude, config.model): idem. Sem isso o gate usa o pior caso do catalogo suportado.
|
|
10
|
+
const rj = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
|
|
11
|
+
|
|
12
|
+
export function modelFromProcessChain(startPid = process.ppid, depth = 8) {
|
|
13
|
+
let pid = startPid;
|
|
14
|
+
for (let i = 0; i < depth && pid > 1; i++) {
|
|
15
|
+
try {
|
|
16
|
+
const args = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0');
|
|
17
|
+
const k = args.findIndex((a) => a === '--model' || a.startsWith('--model='));
|
|
18
|
+
if (k >= 0 && /claude/i.test(args.join(' '))) return args[k].includes('=') ? args[k].split('=')[1] : args[k + 1];
|
|
19
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
20
|
+
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
|
21
|
+
} catch { return null; }
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function declaredModels({ cwd, env = process.env, config = {} }) {
|
|
27
|
+
const out = [];
|
|
28
|
+
if (env.ANTHROPIC_MODEL) out.push({ model: env.ANTHROPIC_MODEL, source: 'ANTHROPIC_MODEL' });
|
|
29
|
+
const dirs = [claudeConfigDir(env)];
|
|
30
|
+
for (const f of [join(dirs[0], 'settings.json'), cwd && join(cwd, '.claude', 'settings.json'), cwd && join(cwd, '.claude', 'settings.local.json')].filter(Boolean)) {
|
|
31
|
+
const s = rj(f); if (!s) continue;
|
|
32
|
+
if (s.model) out.push({ model: s.model, source: tr(`Claude settings (${f})`, `settings do Claude (${f})`) });
|
|
33
|
+
if (s.env?.ANTHROPIC_MODEL) out.push({ model: s.env.ANTHROPIC_MODEL, source: tr(`Claude settings env (${f})`, `settings do Claude env (${f})`) });
|
|
34
|
+
}
|
|
35
|
+
if (config.model) out.push({ model: config.model, source: tr('precost config.model', 'config.model do precost') });
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { resolveModel } from './pricing.js';
|
|
4
|
+
|
|
5
|
+
// Transcripts do Claude Code (JSONL; formato OBSERVADO na v2.1.332): linhas type "assistant" com message.{id,model,usage}.
|
|
6
|
+
// usage.input_tokens exclui cache; cache_read_input_tokens e cache_creation_input_tokens sao separados.
|
|
7
|
+
const MAX_TAIL = 4_000_000, MAX_FILE = 80_000_000, MAX_FILES = 300;
|
|
8
|
+
const lines = (text) => text.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
9
|
+
|
|
10
|
+
// Modelo da ultima resposta do assistente na sessao (ignora sinteticos). Sem resposta ainda: null.
|
|
11
|
+
export function lastModel(transcriptPath) {
|
|
12
|
+
try {
|
|
13
|
+
const size = statSync(transcriptPath).size, n = Math.min(size, MAX_TAIL);
|
|
14
|
+
const fd = openSync(transcriptPath, 'r'); const buf = Buffer.alloc(n); readSync(fd, buf, 0, n, size - n); closeSync(fd);
|
|
15
|
+
const ls = lines(buf.toString('utf8')).filter((j) => j.type === 'assistant' && j.message?.model && !String(j.message.model).startsWith('<'));
|
|
16
|
+
return ls.length ? ls[ls.length - 1].message.model : null;
|
|
17
|
+
} catch { return null; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Troca de modelo (/model) registrada no transcript DEPOIS da ultima resposta do assistente (ou sem nenhuma resposta): o modelo da ultima resposta
|
|
21
|
+
// nao vale mais para o proximo prompt. Observado no Claude Code 2.1.332: /model grava uma entrada com <command-name>/model</command-name> e <command-args>.
|
|
22
|
+
export function pendingModelSwitch(transcriptPath) {
|
|
23
|
+
try {
|
|
24
|
+
const size = statSync(transcriptPath).size, n = Math.min(size, MAX_TAIL);
|
|
25
|
+
const fd = openSync(transcriptPath, 'r'); const buf = Buffer.alloc(n); readSync(fd, buf, 0, n, size - n); closeSync(fd);
|
|
26
|
+
const all = lines(buf.toString('utf8')); let lastA = -1;
|
|
27
|
+
all.forEach((j, i) => { if (j.type === 'assistant' && j.message?.model && !String(j.message.model).startsWith('<')) lastA = i; });
|
|
28
|
+
for (let i = lastA + 1; i < all.length; i++) {
|
|
29
|
+
const c = all[i]?.message?.content; const t = typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x?.text ?? '').join('') : '';
|
|
30
|
+
if (t.includes('<command-name>/model</command-name>')) { const a = /<command-args>([^<]*)<\/command-args>/.exec(t); return { args: (a?.[1] ?? '').trim() }; }
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
} catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Historico real do projeto (mesma pasta de transcripts) para UM modelo, excluindo a sessao atual.
|
|
37
|
+
export function historyFromDir(dir, { model, prices, excludeSession }) {
|
|
38
|
+
const want = resolveModel(prices, model);
|
|
39
|
+
if (!want) return [];
|
|
40
|
+
const out = [];
|
|
41
|
+
let files = [];
|
|
42
|
+
try { files = readdirSync(dir).filter((f) => f.endsWith('.jsonl')).map((f) => [f, statSync(join(dir, f))]).filter(([, s]) => s.size <= MAX_FILE).sort((a, b) => b[1].mtimeMs - a[1].mtimeMs).slice(0, MAX_FILES); } catch { return []; }
|
|
43
|
+
for (const [f] of files) {
|
|
44
|
+
if (excludeSession && f.startsWith(excludeSession)) continue;
|
|
45
|
+
const byId = new Map();
|
|
46
|
+
let ls; try { ls = lines(readFileSync(join(dir, f), 'utf8')); } catch { continue; }
|
|
47
|
+
for (const j of ls) {
|
|
48
|
+
const m = j.message;
|
|
49
|
+
if (j.type !== 'assistant' || !m?.usage || !m.id) continue;
|
|
50
|
+
if (resolveModel(prices, m.model) !== want) continue;
|
|
51
|
+
const u = m.usage, cur = byId.get(m.id) ?? { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
52
|
+
byId.set(m.id, { input: Math.max(cur.input, u.input_tokens ?? 0), output: Math.max(cur.output, u.output_tokens ?? 0), cache_read: Math.max(cur.cache_read, u.cache_read_input_tokens ?? 0), cache_write: Math.max(cur.cache_write, u.cache_creation_input_tokens ?? 0) });
|
|
53
|
+
}
|
|
54
|
+
if (!byId.size) continue;
|
|
55
|
+
const s = { input: 0, output: 0, cache_read: 0, cache_write: 0, turns: byId.size, peakCtx: 0 };
|
|
56
|
+
for (const m of byId.values()) { s.input += m.input; s.output += m.output; s.cache_read += m.cache_read; s.cache_write += m.cache_write; s.peakCtx = Math.max(s.peakCtx, m.input + m.cache_read + m.cache_write); }
|
|
57
|
+
out.push(s);
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
package/src/context.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { resolve, sep, basename } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { tr } from './i18n.js';
|
|
6
|
+
|
|
7
|
+
// Arquivos observados como parte do contexto de um prompt. So le dentro de `root`, sem seguir links para fora,
|
|
8
|
+
// ignora segredos obvios e arquivos grandes. O hash entra no vinculo da aprovacao: mudou o arquivo, a aprovacao cai.
|
|
9
|
+
const SECRET = /(^|\/)(\.env(\..*)?|.*\.(pem|key|p12|pfx)|id_(rsa|ed25519)|\.git\/.*|\.ssh\/.*)$/i;
|
|
10
|
+
const MAX = 1_000_000;
|
|
11
|
+
|
|
12
|
+
export function readContextFile(path, root) {
|
|
13
|
+
const sig = (p) => { try { const s = statSync(p); return `${s.size}:${Math.round(s.mtimeMs)}`; } catch { return 'sem-stat'; } };
|
|
14
|
+
try {
|
|
15
|
+
const rp = realpathSync(resolve(root, path)), rr = realpathSync(root);
|
|
16
|
+
if (rp !== rr && !rp.startsWith(rr + sep)) return { path, skipped: tr('outside the project', 'fora do projeto') };
|
|
17
|
+
if (SECRET.test(rp.slice(rr.length + 1)) || SECRET.test(basename(rp))) return { path, skipped: tr('possible secret, not read', 'possivel segredo, nao lido'), sha: 'stat:' + sig(rp) };
|
|
18
|
+
const st = statSync(rp);
|
|
19
|
+
if (!st.isFile()) return { path, skipped: tr('not a file', 'nao e arquivo') };
|
|
20
|
+
if (st.size > MAX) return { path, skipped: tr(`larger than ${MAX} bytes`, `maior que ${MAX} bytes`), bytes: st.size, sha: 'stat:' + sig(rp) };
|
|
21
|
+
const text = readFileSync(rp, 'utf8');
|
|
22
|
+
return { path, bytes: st.size, text, sha: createHash('sha256').update(text).digest('hex') };
|
|
23
|
+
} catch (e) { return { path, skipped: tr('unreadable', 'ilegivel'), unreadable: true }; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Claude Code: referencias @caminho no texto do prompt.
|
|
27
|
+
export function filesFromPrompt(prompt, root) {
|
|
28
|
+
const out = [], seen = new Set();
|
|
29
|
+
for (const m of prompt.matchAll(/(?:^|\s)@([\w./\-~]+)/g)) {
|
|
30
|
+
if (seen.has(m[1])) continue; seen.add(m[1]);
|
|
31
|
+
const r = readContextFile(m[1], root);
|
|
32
|
+
if (r.text !== undefined || !r.unreadable) out.push(r);
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
// OpenCode: partes type "file" (url file://...).
|
|
37
|
+
export function filesFromParts(parts, root) {
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const p of parts ?? []) {
|
|
40
|
+
if (p.type !== 'file' || !p.url?.startsWith('file:')) continue;
|
|
41
|
+
try { out.push(readContextFile(fileURLToPath(p.url), root)); } catch { out.push({ path: p.filename ?? p.url, skipped: tr('invalid url', 'url invalida') }); }
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
export const contextHash = (files) => createHash('sha256').update(JSON.stringify((files ?? []).map((f) => [f.path, f.sha ?? f.skipped ?? null]))).digest('hex');
|
package/src/doctor.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// precost doctor: verificacao LOCAL e SEM chamada ao modelo/provedor. Prova arquivos, config, execucao do hook neste node.
|
|
2
|
+
// NAO prova que o cliente (Claude Code/OpenCode) carregou o hook/plugin na sessao: o fail-closed so vale com hook/plugin carregado.
|
|
3
|
+
import { readFileSync, existsSync, mkdtempSync, writeFileSync, readdirSync } from 'node:fs';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { configPath, claudeConfigDir, opencodeConfigDir, userPricesPath } from './paths.js';
|
|
7
|
+
import { ageDays, tableDate, STALE_DAYS } from './prices-update.js';
|
|
8
|
+
import { join, resolve, dirname } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { validateConfig } from './gate.js';
|
|
11
|
+
import { loadPrices } from './pricing.js';
|
|
12
|
+
import { tr, setLang } from './i18n.js';
|
|
13
|
+
|
|
14
|
+
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
15
|
+
const rj = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
|
|
16
|
+
|
|
17
|
+
export const levelLabel = (l) => tr(l, { WARN: 'AVISO', FAIL: 'FALHA' }[l] ?? l);
|
|
18
|
+
export function doctor({ project = process.cwd(), claudeSettings = [], env = process.env } = {}) {
|
|
19
|
+
const out = []; const add = (level, msg) => out.push({ level, msg });
|
|
20
|
+
const cfgPath = configPath(env);
|
|
21
|
+
let cfg = {};
|
|
22
|
+
setLang(env.PRECOST_LANG);
|
|
23
|
+
if (!existsSync(cfgPath)) add('WARN', tr(`config missing (${cfgPath}): the hook only informs, it does NOT block (no limit).`, `config ausente (${cfgPath}): o hook so informa, NAO bloqueia (sem limite).`));
|
|
24
|
+
else { const c = rj(cfgPath); if (!c) add('FAIL', tr(`config unreadable: ${cfgPath} (the hook blocks everything until fixed).`, `config ilegivel: ${cfgPath} (o hook bloqueia tudo ate corrigir).`)); else { cfg = c; setLang(c.lang); const bad = validateConfig(c); if (bad) add('FAIL', tr(`invalid config: ${bad}`, `config invalida: ${bad}`)); else add(c.limitUsd == null ? 'WARN' : 'OK', c.limitUsd == null ? tr('config without limitUsd: informational only, no gate.', 'config sem limitUsd: so informativo, sem gate.') : tr(`valid config (limitUsd US$${c.limitUsd}).`, `config valida (limitUsd US$${c.limitUsd}).`)); } }
|
|
25
|
+
try { const p = loadPrices(cfg.prices); add('OK', tr(`price table loaded (${Object.keys(p.models).length} models; source: ${p._source.kind}, date ${tableDate(p)}).`, `tabela de precos carregada (${Object.keys(p.models).length} modelos; origem: ${p._source.kind}, data ${tableDate(p)}).`)); const ag = ageDays(p); if (ag !== null && ag > STALE_DAYS) add('WARN', tr(`price table is ${ag} days old: run \`precost update-prices\` (prices change; the estimate may be outdated).`, `tabela de precos com ${ag} dias: rode \`precost update-prices\` (precos mudam; estimativa pode estar defasada).`)); } catch (e) { add('FAIL', tr(`price table: ${e.message}`, `tabela de precos: ${e.message}`)); }
|
|
26
|
+
|
|
27
|
+
// Claude Code: o hook precisa estar em algum settings que o Claude le, com onFailure block.
|
|
28
|
+
const cc = [...claudeSettings, join(claudeConfigDir(env), 'settings.json'), join(project, '.claude', 'settings.json'), join(project, '.claude', 'settings.local.json')];
|
|
29
|
+
let ccFound = false;
|
|
30
|
+
for (const f of cc) {
|
|
31
|
+
const s = rj(f); if (!s?.hooks) continue;
|
|
32
|
+
const ups = (s.hooks.UserPromptSubmit ?? []).flatMap((g) => g.hooks ?? []).filter((h) => /userpromptsubmit\.js/.test(h.command ?? ''));
|
|
33
|
+
if (!ups.length) continue; ccFound = true;
|
|
34
|
+
for (const h of ups) {
|
|
35
|
+
const script = /(\S*userpromptsubmit\.js)/.exec(h.command)[1];
|
|
36
|
+
add(existsSync(script) ? 'OK' : 'FAIL', tr(`Claude Code: UserPromptSubmit in ${f} -> ${script}${existsSync(script) ? '' : ' (FILE DOES NOT EXIST: the hook fails)'}`, `Claude Code: UserPromptSubmit em ${f} -> ${script}${existsSync(script) ? '' : ' (ARQUIVO NAO EXISTE: o hook falha)'}`));
|
|
37
|
+
add(h.onFailure === 'block' ? 'OK' : 'FAIL', h.onFailure === 'block' ? tr('Claude Code: onFailure=block (crash/timeout/missing node do not let prompts through).', 'Claude Code: onFailure=block (crash/timeout/node ausente nao deixam passar).') : tr(`Claude Code: onFailure=${h.onFailure ?? 'missing'}: a crash, timeout or missing node lets the prompt reach the model (FAIL OPEN). Use "onFailure":"block".`, `Claude Code: onFailure=${h.onFailure ?? 'ausente'}: crash, timeout ou node ausente deixam o prompt chegar ao modelo (FALHA ABERTA). Use "onFailure":"block".`));
|
|
38
|
+
}
|
|
39
|
+
const trk = ['SessionStart', 'PostModelSwitch'].filter((e) => (s.hooks[e] ?? []).flatMap((g) => g.hooks ?? []).some((h) => /track-model\.js/.test(h.command ?? '')));
|
|
40
|
+
const miss = ['SessionStart', 'PostModelSwitch'].filter((e) => !trk.includes(e)).join(', ');
|
|
41
|
+
add(trk.length === 2 ? 'OK' : 'WARN', trk.length === 2 ? tr('Claude Code: SessionStart and PostModelSwitch trackers present.', 'Claude Code: rastreadores SessionStart e PostModelSwitch presentes.') : tr(`Claude Code: tracker missing for ${miss}: without it the model only comes from observed/declared sources (worst case unless trustConfiguredModel).`, `Claude Code: rastreador ausente em ${miss}: sem ele o modelo so vem de fontes observadas/declaradas (pior caso salvo trustConfiguredModel).`));
|
|
42
|
+
}
|
|
43
|
+
if (!ccFound) add('INFO', tr('Claude Code: precost UserPromptSubmit hook not found in the checked settings (fine if you do not use Claude Code, or pass --claude-settings PATH).', 'Claude Code: hook UserPromptSubmit do precost nao encontrado nos settings verificados (ok se voce nao usa Claude Code, ou passe --claude-settings CAMINHO).'));
|
|
44
|
+
|
|
45
|
+
// OpenCode: plugin local do projeto ou global.
|
|
46
|
+
const ocDirs = [join(project, '.opencode', 'plugins'), join(opencodeConfigDir(env), 'plugins')]; let ocFound = false;
|
|
47
|
+
for (const d of ocDirs) { try { for (const f of readdirSync(d)) { const t = readFileSync(join(d, f), 'utf8'); if (/adapters[\\/]opencode[\\/]index\.js/.test(t)) { ocFound = true; const m = /from\s+['"]([^'"]*adapters[\\/]opencode[\\/]index\.js)['"]/.exec(t); add(m && existsSync(m[1]) ? 'OK' : 'FAIL', tr(`OpenCode: plugin in ${join(d, f)}${m && existsSync(m[1]) ? '' : ' (import points to a missing file: the plugin does not load)'}`, `OpenCode: plugin em ${join(d, f)}${m && existsSync(m[1]) ? '' : ' (import aponta para arquivo inexistente: o plugin nao carrega)'}`)); } } } catch { /* sem pasta */ } }
|
|
48
|
+
if (!ocFound) add('INFO', tr('OpenCode: precost plugin not found in .opencode/plugins (project) or the global directory (fine if you do not use OpenCode).', 'OpenCode: plugin do precost nao encontrado em .opencode/plugins (projeto) nem no diretorio global (ok se voce nao usa OpenCode).'));
|
|
49
|
+
|
|
50
|
+
// Execucao real do hook neste node, com prompt grande e limite minimo, em estado temporario: deve BLOQUEAR sem chamar nada.
|
|
51
|
+
const tmp = mkdtempSync(join(tmpdir(), 'precost-doctor-')); writeFileSync(join(tmp, 'c.json'), JSON.stringify({ model: 'claude-sonnet-5.5', limitUsd: 0.01 }));
|
|
52
|
+
const r = spawnSync(process.execPath, [join(ROOT, 'adapters/claude-code/userpromptsubmit.js')], { input: JSON.stringify({ session_id: 'doctor', prompt: 'x'.repeat(4000), cwd: tmp }), env: { ...env, PRECOST_CONFIG: join(tmp, 'c.json'), PRECOST_STATE: join(tmp, 'st') }, encoding: 'utf8', timeout: 20000 });
|
|
53
|
+
let blocked = false; try { blocked = JSON.parse(r.stdout).decision === 'block'; } catch { /* nao JSON */ }
|
|
54
|
+
add(blocked ? 'OK' : 'FAIL', blocked ? tr(`hook runs on ${process.execPath} (node ${process.version}) and blocks a large prompt under a minimal limit (temporary state, no model call).`, `hook executa em ${process.execPath} (node ${process.version}) e bloqueia prompt grande com limite minimo (estado temporario, nenhuma chamada a modelo).`) : tr(`hook did NOT block in the local test (output: ${String(r.stdout || r.stderr).slice(0, 120)}).`, `hook NAO bloqueou no teste local (saida: ${String(r.stdout || r.stderr).slice(0, 120)}).`));
|
|
55
|
+
add('WARN', tr('LIMIT: the doctor proves files, config and local execution; it does NOT prove that the client loaded the hook/plugin IN THIS session. Fail closed only holds while the hook/plugin is loaded. If it is not loaded, large prompts pass with no preview and no gate. Load test without a paid provider: `npm run e2e:claude` / `e2e:opencode` (local fake server). In a real session, type `precost last` first: with the hook loaded the answer comes from precost without a model; if the model answers, the hook is NOT loaded (cost of one short prompt).', 'LIMITE: o doctor prova arquivos, config e execucao local; NAO prova que o cliente carregou o hook/plugin NESTA sessao. Fail-closed so vale com hook/plugin carregado. Se o plugin/hook nao carregar, prompts grandes passam sem previa nem gate. Teste de carga sem provedor pago: `npm run e2e:claude` / `e2e:opencode` (servidor falso local). Em sessao real, digite `precost last` primeiro: com o hook carregado a resposta vem do precost sem modelo; se o modelo responder, o hook NAO esta carregado (custo de um prompt curto).'));
|
|
56
|
+
return out;
|
|
57
|
+
}
|
package/src/estimate.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { approxTokens, tokenMethod } from './tokens.js';
|
|
2
|
+
import { tr } from './i18n.js';
|
|
3
|
+
import { priceAt, costCalls, costTotals } from './pricing.js';
|
|
4
|
+
|
|
5
|
+
// Premissas padrao (NAO medidas). Aparecem no resultado.
|
|
6
|
+
export const DEFAULT_SCENARIOS = {
|
|
7
|
+
pequena: { turns: 6, outPerTurn: 500, growthPerTurn: 2000 },
|
|
8
|
+
media: { turns: 18, outPerTurn: 900, growthPerTurn: 4000 },
|
|
9
|
+
grande: { turns: 45, outPerTurn: 1500, growthPerTurn: 8000 },
|
|
10
|
+
};
|
|
11
|
+
export const DEFAULT_SYSTEM_TOKENS = 8000; // premissa: prompt do sistema + ferramentas
|
|
12
|
+
|
|
13
|
+
export function quantile(sorted, q) {
|
|
14
|
+
if (!sorted.length) return null;
|
|
15
|
+
const pos = (sorted.length - 1) * q, lo = Math.floor(pos), hi = Math.ceil(pos);
|
|
16
|
+
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Lista de chamadas simuladas: chamada i le base + (i-1)*growth; a primeira sem cache.
|
|
20
|
+
export function simulateCalls({ base, turns, outPerTurn, growthPerTurn, cacheHit }) {
|
|
21
|
+
const calls = [];
|
|
22
|
+
for (let i = 1; i <= turns; i++) {
|
|
23
|
+
const ctx = Math.round(base + (i - 1) * growthPerTurn);
|
|
24
|
+
calls.push({ ctx, cachedIn: i === 1 ? 0 : Math.round(ctx * cacheHit), out: outPerTurn });
|
|
25
|
+
}
|
|
26
|
+
return calls;
|
|
27
|
+
}
|
|
28
|
+
export function totalsOf(calls) {
|
|
29
|
+
const t = calls.reduce((s, c) => ({ freshIn: s.freshIn + c.ctx - c.cachedIn, cachedIn: s.cachedIn + c.cachedIn, out: s.out + c.out }), { freshIn: 0, cachedIn: 0, out: 0 });
|
|
30
|
+
return { ...t, turns: calls.length };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function fromHistory(history) {
|
|
34
|
+
const col = (k) => history.map((h) => h[k] ?? 0).sort((a, b) => a - b);
|
|
35
|
+
const pick = (q) => ({ freshIn: Math.round(quantile(col('input'), q)), cachedIn: Math.round(quantile(col('cache_read'), q)), out: Math.round(quantile(col('output'), q)), cacheWrite: Math.round(quantile(col('cache_write'), q)), turns: Math.max(1, Math.round(quantile(col('turns'), q))), peak: history.every((h) => typeof h.peakCtx === 'number') ? Math.max(...history.map((h) => h.peakCtx)) : undefined /* MAIOR pico registrado, nao quantil */ });
|
|
36
|
+
return { low: pick(0.25), mid: pick(0.5), high: pick(0.75) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function estimate({ task = '', fileTexts = [], models, prices, history, cacheHit = 0, systemTokens = DEFAULT_SYSTEM_TOKENS, date, counter = approxTokens }) {
|
|
40
|
+
const promptChars = task.length, fileChars = fileTexts.reduce((s, t) => s + t.length, 0);
|
|
41
|
+
const promptTokens = counter(task), fileTokens = fileTexts.reduce((s, t) => s + counter(t), 0);
|
|
42
|
+
// OBSERVADO: so os caracteres lidos. Tokens e custo abaixo sao ESTIMATIVAS (chars/4 + premissa de sistema).
|
|
43
|
+
const initial = { observedChars: promptChars + fileChars, promptChars, fileChars, estTokens: promptTokens + fileTokens + systemTokens, estPromptTokens: promptTokens, estFileTokens: fileTokens, assumedSystemTokens: systemTokens };
|
|
44
|
+
const threshold = prices.long_context_threshold_tokens ?? 200000;
|
|
45
|
+
|
|
46
|
+
// Cenarios por modelo: o multiplicador de tokenizador (Claude 4.7+, ~30%) so afeta os tokens observados (prompt/arquivos), nao a premissa de sistema.
|
|
47
|
+
// history: lista (vale para todas as linhas) ou mapa {modelo: lista} (cada linha usa so o seu; sem mistura entre modelos comparados).
|
|
48
|
+
if (Array.isArray(history) && models.length > 1) throw new Error(tr('history as a single list with several models: use a {model: list} map', 'history em lista unica com varios modelos: use mapa {modelo: lista}'));
|
|
49
|
+
const histOf = (model) => (Array.isArray(history) ? history : history?.[model]);
|
|
50
|
+
const build = (mult, hist) => {
|
|
51
|
+
const pT = Math.round(promptTokens * mult), fT = Math.round(fileTokens * mult);
|
|
52
|
+
if (hist && hist.length >= 5) {
|
|
53
|
+
const sc = fromHistory(hist);
|
|
54
|
+
for (const s of Object.values(sc)) s.freshIn += pT + fT; // entrada observada desta tarefa somada uma vez
|
|
55
|
+
return sc;
|
|
56
|
+
}
|
|
57
|
+
const sc = {};
|
|
58
|
+
for (const [name, k] of Object.entries(DEFAULT_SCENARIOS)) sc[name] = simulateCalls({ base: pT + fT + systemTokens, ...k, cacheHit });
|
|
59
|
+
return sc;
|
|
60
|
+
};
|
|
61
|
+
const basisOf = (hist) => (hist && hist.length >= 5
|
|
62
|
+
? { kind: 'historico', sessions: hist.length, note: tr('P25/P50/P75 of earlier sessions of this model and project, plus this task\'s observed input added once; peak per call = LARGEST recorded; history does not scale with task size beyond that. Input/cache semantics of real events were NOT validated against a real model response', 'P25/P50/P75 de sessoes anteriores deste modelo e projeto, mais a entrada observada desta tarefa somada uma vez; pico por chamada = MAIOR registrado; o historico nao depende do tamanho da tarefa alem disso. Semantica input/cache dos eventos reais NAO validada contra resposta de modelo') }
|
|
63
|
+
: { kind: 'premissas', note: hist?.length ? tr(`history with ${hist.length} sessions (<5) ignored`, `historico com ${hist.length} sessoes (<5) ignorado`) : tr('no history: three scenarios with fixed assumptions, not measured', 'sem historico: tres cenarios com premissas fixas, nao medidas'), scenarios: DEFAULT_SCENARIOS, cacheHit });
|
|
64
|
+
|
|
65
|
+
const rows = models.map((model) => {
|
|
66
|
+
const price = priceAt(prices, model, date);
|
|
67
|
+
if (!price || typeof price.input !== 'number' || typeof price.output !== 'number') return { model, error: tr('no price in the table (n/a, not treated as zero)', 'sem preco na tabela (n/d, nao tratado como zero)') };
|
|
68
|
+
const scenarios = {}, notes = [];
|
|
69
|
+
let lowerBound = false;
|
|
70
|
+
const mult = price.tokenizer_multiplier ?? 1;
|
|
71
|
+
const hist = histOf(model);
|
|
72
|
+
const scen = build(mult, hist);
|
|
73
|
+
const base = Math.round(promptTokens * mult) + Math.round(fileTokens * mult) + systemTokens;
|
|
74
|
+
for (const [name, u] of Object.entries(scen)) {
|
|
75
|
+
const c = Array.isArray(u) ? costCalls(price, u, threshold) : costTotals(price, u, threshold);
|
|
76
|
+
scenarios[name] = { usd: c.usd, tokens: Array.isArray(u) ? totalsOf(u) : u };
|
|
77
|
+
if (c.longUnknown === true) lowerBound = true;
|
|
78
|
+
if (!c.cacheKnown) notes.push(tr('no cache price in the table: cached input billed at the full rate (upper bound)', 'sem preco de cache na tabela: entrada em cache cobrada a preco cheio (limite superior)'));
|
|
79
|
+
if (c.longUnknown) notes.push(typeof c.longUnknown === 'string' ? c.longUnknown : tr('context above the threshold: the table has no long-context rate (unknown)', 'contexto acima do limiar: tabela nao traz taxa longa (desconhecido)'));
|
|
80
|
+
}
|
|
81
|
+
if (mult !== 1) notes.push(tr(`observed tokens x${mult} (new tokenizer, ~30% more; assumption from the official note)`, `tokens observados x${mult} (tokenizador novo, ~30% a mais; premissa da nota oficial)`));
|
|
82
|
+
if (price.cache_write_5m) notes.push(tr(`conservative: all new input billed as 5-minute cache write (US$${price.cache_write_5m}/1M); real cache savings are not credited beyond reads`, `conservador: toda entrada nova cobrada como cache write 5min (US$${price.cache_write_5m}/1M); economia real do cache nao creditada alem da leitura`));
|
|
83
|
+
if (price.access_note) notes.push(tr(`access: ${price.access_note}`, `acesso: ${price.access_note}`));
|
|
84
|
+
if (price.cache_write) notes.push(tr(`cache write (US$${price.cache_write}/1M from ${price.cache_write_from}) not modeled`, `cache write (US$${price.cache_write}/1M a partir de ${price.cache_write_from}) nao modelado`));
|
|
85
|
+
const initialUsd = costCalls(price, [{ ctx: base, cachedIn: 0, out: 0 }], threshold).usd;
|
|
86
|
+
const promoActive = price.promo ? { ...price.promo } : null;
|
|
87
|
+
return { model, basis: basisOf(hist), lowerBound, promo: promoActive, price: { input: price.input, output: price.output, cache_read: price.cache_read ?? null }, initialContextEstUsd: initialUsd, scenarios, notes: [...new Set(notes)] };
|
|
88
|
+
});
|
|
89
|
+
const ok = rows.filter((r) => !r.error), kinds = new Set(ok.map((r) => r.basis.kind));
|
|
90
|
+
const basis = kinds.size === 1 ? ok[0].basis : kinds.size === 0 ? basisOf(undefined) : { kind: 'mista', note: tr('see each model\'s basis below (history only where there are 5+ sessions of that model and project)', 'ver a base de cada modelo abaixo (historico so onde ha 5+ sessoes do proprio modelo e projeto)') };
|
|
91
|
+
return { tokenMethod: tokenMethod(), initial, basis, rows, pricesHash: prices._hash ?? null };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Beneficio condicional da promocao (credito), SEPARADO da cobranca bruta. Nao e previsao da fatura.
|
|
95
|
+
export function promoBenefit(row) {
|
|
96
|
+
if (!row.promo?.credit_back_pct) return null;
|
|
97
|
+
const g = range(row);
|
|
98
|
+
const f = row.promo.credit_back_pct / 100;
|
|
99
|
+
return { until: row.promo.until, pct: row.promo.credit_back_pct, minUsd: g.min * f, maxUsd: g.max * f };
|
|
100
|
+
}
|
|
101
|
+
export function range(row) {
|
|
102
|
+
const v = Object.values(row.scenarios).map((s) => s.usd).sort((a, b) => a - b);
|
|
103
|
+
return { min: v[0], mid: v[Math.floor((v.length - 1) / 2)], max: v[v.length - 1] };
|
|
104
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { range, promoBenefit } from './estimate.js';
|
|
2
|
+
import { tr } from './i18n.js';
|
|
3
|
+
const usd = (n) => (n < 0.01 ? `US$${n.toFixed(4)}` : `US$${n.toFixed(2)}`);
|
|
4
|
+
|
|
5
|
+
export function format(result, { title = tr('Cost preview (ESTIMATE)', 'Previa de custo (ESTIMATIVA)') } = {}) {
|
|
6
|
+
const k = result.initial;
|
|
7
|
+
const L = [title];
|
|
8
|
+
L.push(tr(`OBSERVED: ${k.observedChars} characters (prompt ${k.promptChars} + files ${k.fileChars}).`, `OBSERVADO: ${k.observedChars} caracteres (prompt ${k.promptChars} + arquivos ${k.fileChars}).`));
|
|
9
|
+
L.push(tr(`ESTIMATED INITIAL CONTEXT: ~${k.estTokens} tokens = prompt ~${k.estPromptTokens} + files ~${k.estFileTokens} (${result.tokenMethod}) + ${k.assumedSystemTokens} system/tools (ASSUMPTION, not measured).`, `CONTEXTO INICIAL ESTIMADO: ~${k.estTokens} tokens = prompt ~${k.estPromptTokens} + arquivos ~${k.estFileTokens} (${result.tokenMethod}) + ${k.assumedSystemTokens} de sistema/ferramentas (PREMISSA, nao medida).`));
|
|
10
|
+
const kindLabel = (k) => tr({ historico: 'history', premissas: 'assumptions', mista: 'mixed' }[k] ?? k, k);
|
|
11
|
+
L.push(tr(`FULL TASK (basis: ${kindLabel(result.basis.kind)}): ${result.basis.note}.`, `TAREFA COMPLETA (base: ${result.basis.kind}): ${result.basis.note}.`));
|
|
12
|
+
for (const r of result.rows) {
|
|
13
|
+
if (r.error) { L.push(`- ${r.model}: ${r.error}`); continue; }
|
|
14
|
+
const g = range(r);
|
|
15
|
+
const mixed = result.basis.kind === 'mista';
|
|
16
|
+
L.push(tr(`- ${r.model}${mixed ? ` [basis: ${kindLabel(r.basis.kind)}]` : ''}: initial context ~${usd(r.initialContextEstUsd)} (estimated); task ${r.lowerBound ? 'AT LEAST ' : ''}${usd(g.min)} to ${usd(g.max)}${r.lowerBound ? ' (lower bound only, long-context rate unknown)' : ''} (mid ${usd(g.mid)}; the high value is P75 / large scenario, NOT a cap)`, `- ${r.model}${mixed ? ` [base: ${r.basis.kind}]` : ''}: contexto inicial ~${usd(r.initialContextEstUsd)} (estimado); tarefa ${r.lowerBound ? 'AO MENOS ' : ''}${usd(g.min)} a ${usd(g.max)}${r.lowerBound ? ' (so limite inferior, taxa de contexto longo desconhecida)' : ''} (meio ${usd(g.mid)}; o valor alto e P75/cenario grande, NAO e teto)`) + (r.notes.length ? ` [${r.notes.join('; ')}]` : ''));
|
|
17
|
+
const pb = promoBenefit(r);
|
|
18
|
+
if (pb) L.push(tr(` charge above = INFERRED GROSS (post-promotion list price; not validated against a primary billing source: conservative estimate, not an exact charge). Conditional benefit until ${pb.until}: ${pb.pct}% credits back on net spend (about ${usd(pb.minUsd)} to ${usd(pb.maxUsd)}), if it applies to the account. It is not an invoice discount; the gate uses the gross value.`, ` cobranca acima = BRUTA INFERIDA (preco de lista pos-promocao; sem validacao em fonte primaria de faturamento: estimativa conservadora, nao cobranca exata). Beneficio condicional ate ${pb.until}: ${pb.pct}% de creditos de volta sobre gasto liquido (ate ~${usd(pb.minUsd)} a ${usd(pb.maxUsd)}), se aplicavel a conta. Nao e desconto na fatura; o gate usa o valor bruto.`));
|
|
19
|
+
}
|
|
20
|
+
L.push(tr('Nothing here is a known cost or a guarantee: the agent still explores files, runs tests and may redo work.', 'Nada aqui e custo conhecido nem garantia: o agente ainda explora arquivos, roda testes e pode refazer trabalho.'));
|
|
21
|
+
return L.join('\n');
|
|
22
|
+
}
|