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
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "precost-marketplace",
|
|
3
|
+
"description": "Cost range preview and approval gate for Claude Code prompts.",
|
|
4
|
+
"owner": { "name": "glauberportella" },
|
|
5
|
+
"plugins": [
|
|
6
|
+
{ "name": "precost", "source": "./", "description": "Cost preview and approval before each prompt (an estimate, not a spending cap)." }
|
|
7
|
+
]
|
|
8
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "precost",
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "Cost range estimate before each prompt and explicit approval above a USD limit. An estimate, not a spending cap.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "glauberportella"
|
|
7
|
+
},
|
|
8
|
+
"homepage": "https://github.com/glauberportella/opencode-precost",
|
|
9
|
+
"repository": "https://github.com/glauberportella/opencode-precost",
|
|
10
|
+
"keywords": [
|
|
11
|
+
"cost",
|
|
12
|
+
"budget",
|
|
13
|
+
"estimate",
|
|
14
|
+
"hooks"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT"
|
|
17
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Glauber Portella
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-precost
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**English** | [Português (Brasil)](README.pt-BR.md)
|
|
4
|
+
|
|
5
|
+
Shows an **estimated** cost range *before* a task runs in a coding agent (OpenCode and Claude Code). Optionally asks for explicit approval when the high end of the range goes above a limit you set. No paid calls, no network access at run time.
|
|
6
|
+
|
|
7
|
+
> Status: version 0.3.2, early release. The packaged install is checked in CI on Linux x64, macOS arm64 and Windows x64, with fake servers and no paid calls. macOS Intel is not covered (see docs/INSTALLATION.md). Read "Limits" before relying on it.
|
|
8
|
+
|
|
9
|
+
## What it does
|
|
10
|
+
|
|
11
|
+
- `precost estimate <task>` prints a per-model range (three fixed scenarios, or percentiles from your own session history). The high end is a P75 / large scenario, **not a cap**.
|
|
12
|
+
- A gate runs before your prompt reaches the model. With `limitUsd` set, a prompt whose high estimate is above the limit is blocked until you type `precost approve CODE`. The approval is bound to the prompt, model, session, price table, limit and estimated ceiling. It lasts 10 minutes (default) and works once.
|
|
13
|
+
- Fails closed when a limit is set: unreadable config, unknown model, model without a price, unreadable context file, or an internal error all block instead of letting the prompt through. Without `limitUsd` the tool only informs ("NO GATE").
|
|
14
|
+
|
|
15
|
+
## Pictures
|
|
16
|
+
|
|
17
|
+
All images are **renderings of terminal output text, not UI screenshots**. Where a model appears it is a **simulated** local server (no cost, no credentials). Everything shown was run on **Linux**; nothing here is macOS or Windows validation (see "Platforms").
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+

|
|
21
|
+

|
|
22
|
+

|
|
23
|
+

|
|
24
|
+
|
|
25
|
+
Image 05 illustrates the block (a model with no price in the table) as a partial crop rebuilt from the real TUI. It is not a full screenshot and not proof of the approval flow in OpenCode.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
Details, prerequisites and the validation matrix: [docs/INSTALLATION.md](docs/INSTALLATION.md).
|
|
30
|
+
|
|
31
|
+
- **Claude Code (plugin):** `claude --plugin-dir /path/to/opencode-precost` to try it locally. Marketplace install (`/plugin marketplace add <repo>`, `/plugin install precost@precost-marketplace`) will work only after the repository is public. Not published to any marketplace yet.
|
|
32
|
+
- **Claude Code (manual):** copy `adapters/claude-code/settings.example.json` into your Claude settings and fix the path. Keep `"onFailure": "block"`: without it a crashing, missing or hanging hook lets the prompt reach the model.
|
|
33
|
+
- **OpenCode (1.19.6 only):** `npm i opencode-precost @opencode-ai/plugin@1.19.6` (the package is not on npm yet; use `npm pack` from a clone) and create `.opencode/plugins/precost.js`:
|
|
34
|
+
```js
|
|
35
|
+
import { PrecostPlugin } from 'opencode-precost';
|
|
36
|
+
export const P = async (input) => PrecostPlugin(input, { limitUsd: 5 });
|
|
37
|
+
```
|
|
38
|
+
Loading the plugin only through `opencode.json` was not verified.
|
|
39
|
+
- **Config** (`~/.config/precost/config.json`, Windows `%APPDATA%\precost\config.json`): `{"model":"claude-sonnet-5.5","limitUsd":5}`.
|
|
40
|
+
- **Check the install:** `node bin/precost.js doctor`. It cannot prove the client loaded the hook in your session. In a real session type `precost last` first: if a model answers, the hook is not loaded.
|
|
41
|
+
|
|
42
|
+
## Commands
|
|
43
|
+
|
|
44
|
+
Typed in the prompt (they never reach the model): `precost estimate <task>`, `precost last`, `precost approve CODE`, `precost revoke CODE|all`.
|
|
45
|
+
In a terminal: `node bin/precost.js estimate "task" --model claude-sonnet-5.5`.
|
|
46
|
+
|
|
47
|
+
### Update the reference price table
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
precost prices # table in use, date, age (warns after 30 days)
|
|
51
|
+
precost update-prices --from FILE_OR_URL # validates and shows the diff; nothing is written (URL must be https)
|
|
52
|
+
precost update-prices --from FILE_OR_URL --yes # writes ~/.config/precost/prices.json (Windows: %APPDATA%\precost\prices.json)
|
|
53
|
+
precost update-prices # default source: data/prices.json on main of the project repo (works only once the repo is public; until then HTTP 404, exit 1, nothing changes)
|
|
54
|
+
precost update-prices --reset # back to the bundled table
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
It rejects an invalid table, one older than the current one, or one with a removal or a change above 5x (use `--force` only after checking the source). It runs only from the CLI, never inside the hook or plugin. A user table is used only if it is not older than the bundled one. Changing the table invalidates pending approvals. There is **no automatic reading of official pricing pages**. The default source is the table published on `main` of the project repository, which exists only once the repository is public (until then HTTP 404 and nothing changes); `--from` or `PRECOST_PRICES_SOURCE` give another source (file or https URL). Today the bundled `data/prices.json` is the reference; the official pages cited per model remain the source of truth. Always check them.
|
|
58
|
+
|
|
59
|
+
## Platforms
|
|
60
|
+
|
|
61
|
+
What was actually executed is in the matrix in [docs/INSTALLATION.md](docs/INSTALLATION.md#validation-matrix). Linux is not validation of macOS or Windows. The code uses per-platform paths (`src/paths.js`) and the Claude Code hook uses `node` + `args` (no shell). `npm run e2e:native` (Node, no bash) runs the real clients against fake local servers on Linux, macOS and Windows; results per system are in the matrix. Official client support on Windows: Claude Code runs natively on Windows 10 1809+ (Git for Windows recommended); OpenCode runs on Windows but its docs recommend WSL.
|
|
62
|
+
|
|
63
|
+
## Test it
|
|
64
|
+
|
|
65
|
+
```
|
|
66
|
+
npm ci # installs the dev dependency @opencode-ai/plugin@1.19.6 (needed by the OpenCode adapter test)
|
|
67
|
+
npm test # 71 unit tests (English and Portuguese output)
|
|
68
|
+
npm run e2e:native # real Claude Code 2.1.332 and OpenCode 1.19.6 vs fake servers: block, approve, single use, fail closed
|
|
69
|
+
npm run e2e:claude-plugin # Claude Code plugin cycle (bash, Linux/macOS)
|
|
70
|
+
npm run e2e:claude-plugin-failure # hook crash / missing node / timeout never reach the model (bash)
|
|
71
|
+
npm run e2e:opencode # OpenCode 1.19.6 block/approve/single-use cycle (bash)
|
|
72
|
+
```
|
|
73
|
+
End-to-end scripts download pinned client versions through `npx` and call only local fake servers. No paid model is called.
|
|
74
|
+
|
|
75
|
+
## Limits
|
|
76
|
+
|
|
77
|
+
- It is an estimate: tokens are chars/4 (x1.3 for observed Claude 4.7+ tokens) plus an assumed system prompt (8k OpenCode, 13k Claude Code). It is not a known cost.
|
|
78
|
+
- The high end is not a cap. The gate acts before the prompt; it does not limit spend during a task or inside long loops.
|
|
79
|
+
- Claude Code does not tell the hook which model is active (observed in 2.1.332). An unproven model uses the worst case in the supported catalog, labeled as such.
|
|
80
|
+
- OpenCode has no automatic preview before the model; this plugin computes it inside `chat.message`. Blocking by throwing is undocumented behavior, so the plugin is pinned to OpenCode 1.19.6 and fails closed on other versions (unless `allowUnverifiedVersion` is set).
|
|
81
|
+
- Approval is a local file of the same user. It protects against accidental spend, not against an agent with a shell.
|
|
82
|
+
- The gate only works while the plugin or hook is loaded.
|
|
83
|
+
- Prices: Gemini from cloud.google.com/vertex-ai/generative-ai/pricing and Claude from platform.claude.com/docs/en/about-claude/pricing, read on 2026-11-25. Not modeled: batch, priority, fast mode, data residency. Carbon/Argon raw price is inferred.
|
|
84
|
+
- Token semantics were checked against real events and transcripts from OpenCode and Claude Code with **fake** providers. No comparison with a real invoice has been done.
|
|
85
|
+
|
|
86
|
+
More detail: [docs/CAPABILITIES.md](docs/CAPABILITIES.md).
|
|
87
|
+
|
|
88
|
+
## Language
|
|
89
|
+
|
|
90
|
+
The documentation is available in English (main) and Portuguese (Brasil). The messages printed by the tool (CLI, Claude Code hook, OpenCode plugin) are in English by default. For Portuguese, set `"lang": "pt"` in the config file (or the `lang` option of the OpenCode plugin), or set the environment variable `PRECOST_LANG=pt`. The config value wins over the environment variable. Only the text changes: commands (`precost approve CODE`, `precost revoke CODE`, `precost last`, `precost estimate ...`), approval codes, config keys and the gate's behavior are the same in both languages, and the tests check both.
|
|
91
|
+
|
|
92
|
+
The notes in the price table (`data/prices.json`) are in English. Code comments in `src/` and `adapters/` and the messages of the test and e2e scripts are still partly Portuguese.
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
MIT. See [LICENSE](LICENSE). Copyright (c) 2026 Glauber Portella.
|
package/README.pt-BR.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# opencode-precost (prototipo)
|
|
2
|
+
|
|
3
|
+
[English](README.md) | **Português (Brasil)**
|
|
4
|
+
|
|
5
|
+
Mostra uma ESTIMATIVA de faixa de custo ANTES de executar uma tarefa em agentes de codigo (OpenCode e Claude Code), e opcionalmente pede aprovacao explicita quando a faixa alta passa de um limite. Privado, sem chamadas pagas. Versao de desenvolvimento 0.3.0 (branch dev/0.3.0), com limites: ver `docs/INSTALACAO.pt-BR.md`, "Limites" e `docs/CAPACIDADES.md`.
|
|
6
|
+
|
|
7
|
+
## Imagens (execucao real, Linux)
|
|
8
|
+
Renderizacoes do texto de saida do terminal (nao sao screenshots de interface), geradas a partir de saidas reais; as legendas nas imagens estao em ingles e as mensagens da ferramenta ainda estao em portugues. Onde ha modelo, ele e um servidor SIMULADO local (sem custo, sem credencial). Nada abaixo foi executado em macOS ou Windows.
|
|
9
|
+
|
|
10
|
+

|
|
11
|
+

|
|
12
|
+

|
|
13
|
+

|
|
14
|
+

|
|
15
|
+
|
|
16
|
+
_Imagem 05: ilustracao do bloqueio (modelo sem preco na tabela) em recorte parcial reconstruido da TUI real; nao e screenshot integral nem prova visual do fluxo de aprovacao no OpenCode._
|
|
17
|
+
|
|
18
|
+
## Atualizar a tabela de precos
|
|
19
|
+
```
|
|
20
|
+
precost prices # tabela em uso, data e idade (aviso se > 30 dias)
|
|
21
|
+
precost update-prices --from ARQUIVO_OU_URL # valida e mostra o diff (nada e gravado). URL: https obrigatorio
|
|
22
|
+
precost update-prices --from ARQUIVO_OU_URL --yes # grava em ~/.config/precost/prices.json (Windows: %APPDATA%\precost\prices.json)
|
|
23
|
+
precost update-prices # fonte padrao: data/prices.json no main do repo do projeto (so funciona depois que o repo for publico; ate la HTTP 404, exit 1, nada muda)
|
|
24
|
+
precost update-prices --reset # volta para a tabela embutida
|
|
25
|
+
```
|
|
26
|
+
Recusa tabela invalida, mais antiga que a atual, ou com remocao/variacao acima de 5x (use `--force` so depois de conferir a fonte). Roda so na CLI, nunca dentro do hook/plugin. Usa-se a tabela do usuario so se nao for mais antiga que a embutida. Trocar a tabela invalida aprovacoes pendentes. Nao ha leitura automatica das paginas oficiais de preco. A fonte padrao e a tabela publicada no `main` do repositorio do projeto, que so existe depois que o repo for publico (ate la HTTP 404 e nada muda); `--from` ou `PRECOST_PRICES_SOURCE` indicam outra fonte (arquivo ou https). Hoje a tabela embutida (`data/prices.json`) e a fonte de referencia; as paginas oficiais citadas em cada modelo continuam sendo a verdade. Confira sempre.
|
|
27
|
+
|
|
28
|
+
## Plataformas
|
|
29
|
+
Matriz do que foi realmente executado (CI real do GitHub + execucao local): ver `docs/INSTALACAO.pt-BR.md`, "Matriz de validacao". Linux nao e validacao de macOS/Windows. O codigo usa caminhos por plataforma (`src/paths.js`; Windows: `%APPDATA%`) e o hook do Claude Code usa `node` + `args` (sem shell). O harness `npm run e2e:native` (Node, sem bash) roda os clientes reais contra servidores falsos em Linux, macOS e Windows.
|
|
30
|
+
|
|
31
|
+
## Claude Code como plugin
|
|
32
|
+
`claude plugin marketplace add glauberportella/opencode-precost` e `claude plugin install precost@precost-marketplace` (apos o repositorio estar publico). Local: `claude --plugin-dir .`. Testado em Linux com Claude Code 2.1.332 real e servidor falso (`npm run e2e:claude-plugin`). `onFailure:"block"` no hook do plugin; falha do hook no plugin testada em Linux (`npm run e2e:claude-plugin-failure`).
|
|
33
|
+
|
|
34
|
+
## Instalar e testar (reproduzivel)
|
|
35
|
+
```
|
|
36
|
+
npm ci # usa package-lock.json; instala a dependencia de dev @opencode-ai/plugin@1.19.6 (necessaria para o teste do adaptador OpenCode)
|
|
37
|
+
npm test # 71 testes (saida em ingles e em portugues); sem npm ci o teste do adaptador OpenCode falha por dependencia ausente
|
|
38
|
+
node bin/precost.js doctor # verifica instalacao local (limite: nao prova que o cliente carregou o hook)
|
|
39
|
+
npm run e2e:opencode # OpenCode 1.19.6 real, sem modelo: ciclo bloqueio/approve/uso unico (npx opencode-ai@1.19.6)
|
|
40
|
+
npm run e2e:opencode-ledger # OpenCode 1.19.6 real + provedor FALSO local: evento real do assistente, semantica de tokens/custo
|
|
41
|
+
npm run e2e:claude-tui # TUI INTERATIVA real do Claude Code (pty) + servidor falso: bloqueio visivel, 0 chamadas ao modelo
|
|
42
|
+
npm run e2e:claude-failure # falha do hook (crash, node ausente, timeout) no settings.example.json real: nada chega ao modelo (onFailure:block)
|
|
43
|
+
npm run e2e:opencode-tui # TUI real do OpenCode 1.19.6 (pty): bloqueio visivel, plugin carregado, sem provedor pago
|
|
44
|
+
npm run e2e:claude # Claude Code 2.1.332 REAL + servidor Anthropic FALSO local: hook, bloqueio sem chamar modelo, approve, uso unico, modelo via transcript (npx @anthropic-ai/claude-code@2.1.332)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Primeiro uso real guiado (escopo)
|
|
48
|
+
1. Previa pelo terminal, o canal acessivel e verificado: `node bin/precost.js estimate "tarefa..." --model gemini-3.5-flash` (ou `--task`, `--file`). Tambem `node bin/precost.js last` mostra o ultimo bloqueio.
|
|
49
|
+
2. Modelos com preco conhecido na tabela (`data/prices.json`): Gemini 3.x/4 e Claude 4.5 a 5.5. Modelo fora da tabela com limite configurado = bloqueia e pede aprovacao.
|
|
50
|
+
3. Claude Code NAO informa o modelo ao hook (observado na 2.1.332). So `PRECOST_MODEL` e aceito como modelo efetivo sem pior caso: e uma DECLARACAO do operador, NAO uma prova tecnica (ela nao forca o Claude a usar esse modelo; use-a junto com `claude --model` igual). Rastreador, ultima resposta do transcript e `--model` do processo sao OBSERVADOS: nao garantem o modelo do proximo prompt (apos `/model`). `ANTHROPIC_MODEL`, settings do Claude e `config.model` sao DECLARADOS. Fora do caso comprovado, o gate usa o PIOR CASO do catalogo suportado (rotulado, nao e preco comprovado nem teto: modelo fora do catalogo nao e coberto) e a aprovacao fica presa a esse estado. `trustConfiguredModel:true` no config aceita um modelo observado/declarado consistente como efetivo (decisao do usuario), exceto quando o transcript registra um `/model` depois da ultima resposta (troca pendente: volta ao pior caso). Exemplo de config: `{"model":"claude-sonnet-5.5","limitUsd":5}`. Historico: com 5+ sessoes do mesmo modelo na pasta de transcripts do projeto, a previa usa o consumo real.
|
|
51
|
+
Instalacao: copie `adapters/claude-code/settings.example.json` ajustando o caminho. O `onFailure:"block"` do UserPromptSubmit e obrigatorio para o gate: sem ele (ou com `continue`) crash, node ausente ou timeout do hook deixam o prompt chegar ao modelo (reproduzido; `npm run e2e:claude-failure`). Sem limite configurado o hook e so informativo.
|
|
52
|
+
4. OpenCode: `.opencode/plugins/precost.js` reexportando `adapters/opencode/index.js`, opcoes `limitUsd`, `models`, `ttlMin`. So OpenCode 1.19.6 (outra versao bloqueia, salvo `allowUnverifiedVersion`).
|
|
53
|
+
5. Comandos digitados no prompt (nao chegam ao modelo): `precost estimate <tarefa>`, `precost last`, `precost approve CODIGO`, `precost revoke CODIGO|all`. No Claude Code 2.1.332 em modo `claude -p` o texto aparece na saida ("UserPromptSubmit operation blocked by hook: ..."), verificado com Claude Code real; a TUI interativa tambem foi verificada (`npm run e2e:claude-tui`). No OpenCode o cliente recebe erro generico; na TUI real do OpenCode 1.19.6 o texto de bloqueio aparece numa caixa de erro (`npm run e2e:opencode-tui`, captura em docs/evidence/opencode-tui-pty-capture.txt); ciclo approve/reenvio/uso unico testado na TUI com provedor falso local. Trate o terminal como canal confiavel e os comandos no prompt como conveniencia nao comprovada no OpenCode.
|
|
54
|
+
|
|
55
|
+
## Limites (resumo; detalhes em docs/CAPACIDADES.md)
|
|
56
|
+
- E estimativa: tokens = chars/4 (x1.3 nos observados para Claude 4.7+) + 8k de sistema (premissa). Nao e custo conhecido.
|
|
57
|
+
- Faixa alta = P75/cenario grande, nao teto. O gate age antes do prompt; nao limita gasto durante a tarefa nem laços longos.
|
|
58
|
+
- OpenCode nao tem previa automatica antes do modelo; este plugin calcula dentro de `chat.message`. O bloqueio por throw e comportamento nao documentado (versao fixada, falha fechada).
|
|
59
|
+
- Gate contra gasto acidental, nao contra agente com shell no mesmo usuario (estado e arquivo local).
|
|
60
|
+
- Precos: Gemini via cloud.google.com/vertex-ai/generative-ai/pricing, Claude via platform.claude.com/docs/en/about-claude/pricing, lidos em 25/nov/2026. Carbon/Argon: bruto inferido. Nao modelados: Batch, Priority, Fast mode, residencia de dados.
|
|
61
|
+
- Historico: so sessoes do mesmo modelo e projeto, minimo 5. Semantica dos tokens validada com eventos/transcripts reais de OpenCode e Claude Code contra provedores FALSOS (sem fatura real): `input` exclui o cache. Comparacao com fatura real ainda nao feita.
|
|
62
|
+
- Premissa de sistema: 8k tokens no OpenCode e 13k no Claude Code, a partir do tamanho medido do corpo da requisicao (32,6 KB e 48,9 KB para um prompt de 3 a 9 caracteres) convertido por chars/4; nao e contagem de tokens do provedor.
|
|
63
|
+
|
|
64
|
+
## Licenca
|
|
65
|
+
|
|
66
|
+
MIT. Veja [LICENSE](LICENSE). Copyright (c) 2026 Glauber Portella.
|
|
67
|
+
|
|
68
|
+
## Idioma das mensagens
|
|
69
|
+
|
|
70
|
+
As mensagens da propria ferramenta (CLI, hook do Claude Code, plugin do OpenCode) saem em **ingles por padrao**. Para portugues, coloque `"lang": "pt"` no config (ou a opcao `lang` do plugin OpenCode), ou defina `PRECOST_LANG=pt`. O valor do config vence a variavel de ambiente. So o texto muda: comandos (`precost approve CODIGO`, `precost revoke`, `precost last`, `precost estimate`), codigos de aprovacao, chaves do config e o comportamento do gate sao os mesmos nos dois idiomas, e os testes cobrem os dois. As imagens da documentacao mostram a saida real em ingles.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"SessionStart": [
|
|
4
|
+
{
|
|
5
|
+
"hooks": [
|
|
6
|
+
{
|
|
7
|
+
"type": "command",
|
|
8
|
+
"command": "node /CAMINHO/opencode-precost/adapters/claude-code/track-model.js"
|
|
9
|
+
}
|
|
10
|
+
]
|
|
11
|
+
}
|
|
12
|
+
],
|
|
13
|
+
"PostModelSwitch": [
|
|
14
|
+
{
|
|
15
|
+
"hooks": [
|
|
16
|
+
{
|
|
17
|
+
"type": "command",
|
|
18
|
+
"command": "node /CAMINHO/opencode-precost/adapters/claude-code/track-model.js"
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"UserPromptSubmit": [
|
|
24
|
+
{
|
|
25
|
+
"hooks": [
|
|
26
|
+
{
|
|
27
|
+
"type": "command",
|
|
28
|
+
"command": "node /CAMINHO/opencode-precost/adapters/claude-code/userpromptsubmit.js",
|
|
29
|
+
"timeout": 20,
|
|
30
|
+
"onFailure": "block"
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
"permissions": {
|
|
37
|
+
"deny": [
|
|
38
|
+
"Read(~/.cache/precost/**)",
|
|
39
|
+
"Edit(~/.cache/precost/**)",
|
|
40
|
+
"Write(~/.cache/precost/**)"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"_comment": "permissions.deny: reduz a chance do modelo ler/escrever o estado de aprovacao via ferramentas de arquivo; NAO testado em Claude Code real e NAO impede Bash (ver docs/CAPACIDADES.md, limite de seguranca)."
|
|
44
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Hooks SessionStart (campo model, opcional) e PostModelSwitch (to_model). Guarda o modelo por sessao.
|
|
3
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
4
|
+
import { stateDir, safeId } from '../../src/paths.js';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
let ev = {};
|
|
7
|
+
try { ev = JSON.parse(readFileSync(0, 'utf8')); } catch { process.exit(0); }
|
|
8
|
+
const model = ev.hook_event_name === 'PostModelSwitch' ? ev.to_model : ev.model;
|
|
9
|
+
if (!model || !ev.session_id) process.exit(0);
|
|
10
|
+
const dir = stateDir();
|
|
11
|
+
mkdirSync(dir, { recursive: true });
|
|
12
|
+
writeFileSync(join(dir, `model-${safeId(ev.session_id)}.json`), JSON.stringify({ model, at: Date.now() }));
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Hook UserPromptSubmit (contrato lido em https://code.claude.com/docs/en/hooks.md, secoes UserPromptSubmit e JSON output).
|
|
3
|
+
// Bloqueio: JSON {"decision":"block","reason":...} com exit 0. suppressOriginalPrompt evita repetir o prompt na mensagem.
|
|
4
|
+
// ATENCAO: este evento tambem dispara em prompts automaticos (tarefas agendadas, subagente em segundo plano, mensagem de outra sessao).
|
|
5
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
6
|
+
import { stateDir as stateDirOf, safeId, configPath as configPathOf } from '../../src/paths.js';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { tr, setLang } from '../../src/i18n.js';
|
|
9
|
+
|
|
10
|
+
const block = (text) => { process.stdout.write(JSON.stringify({ decision: 'block', reason: text, hookSpecificOutput: { hookEventName: 'UserPromptSubmit', suppressOriginalPrompt: true } })); process.exit(0); };
|
|
11
|
+
const stateDir = stateDirOf();
|
|
12
|
+
const cfgPath = configPathOf();
|
|
13
|
+
|
|
14
|
+
// Config: ausente = so informativo (e diz isso); presente mas ilegivel/invalida = FALHA FECHADA (bloqueia).
|
|
15
|
+
let config = {}, hasCfg = false;
|
|
16
|
+
if (existsSync(cfgPath)) {
|
|
17
|
+
hasCfg = true;
|
|
18
|
+
try { config = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch (e) { block(tr(`precost: config ${cfgPath} unreadable (${e.message}). Blocked for safety until fixed.`, `precost: config ${cfgPath} ilegivel (${e.message}). Bloqueado por seguranca ate corrigir.`)); }
|
|
19
|
+
}
|
|
20
|
+
setLang(config.lang);
|
|
21
|
+
const gatedCfg = hasCfg && config.limitUsd !== undefined && config.limitUsd !== null;
|
|
22
|
+
const failure = (why) => (gatedCfg ? block(tr(`precost: ${why}. Blocked for safety (fail closed); nothing was sent to the model.`, `precost: ${why}. Bloqueado por seguranca (falha fechada); nada foi enviado ao modelo.`)) : (process.stdout.write(JSON.stringify({ systemMessage: tr(`precost: ${why}; no preview and no gate for this prompt.`, `precost: ${why}; sem previa nem gate neste prompt.`) })), process.exit(0)));
|
|
23
|
+
|
|
24
|
+
let ev;
|
|
25
|
+
try { ev = JSON.parse(readFileSync(0, 'utf8')); } catch (e) { failure(tr('hook input unreadable', 'entrada do hook ilegivel')); }
|
|
26
|
+
|
|
27
|
+
// Modelo ativo: o evento NAO traz (observado na 2.1.332). Ver src/claude-model.js para fontes comprovadas e nao comprovadas.
|
|
28
|
+
let model, modelSource, proven = false, observed = false, declared = [];
|
|
29
|
+
if (process.env.PRECOST_MODEL) { model = process.env.PRECOST_MODEL; modelSource = tr('env PRECOST_MODEL (operator declaration, NOT verified against the request: it does not force the Claude model; if Claude uses another, the approved price is the declared model\'s)', 'env PRECOST_MODEL (declaracao do operador, NAO verificada contra o request: nao forca o modelo do Claude; se ele usar outro, o preco aprovado e o do modelo declarado)'); proven = true; }
|
|
30
|
+
if (!model) { try { model = JSON.parse(readFileSync(join(stateDir, `model-${safeId(ev.session_id)}.json`), 'utf8')).model; if (model) { modelSource = tr('tracker (SessionStart/PostModelSwitch; observed, may be stale)', 'rastreador (SessionStart/PostModelSwitch; observado, pode estar defasado)'); observed = true; } } catch { /* nao rastreado */ } }
|
|
31
|
+
if (!model && ev.transcript_path) { const { lastModel } = await import('../../src/claude-transcript.js'); model = lastModel(ev.transcript_path) ?? undefined; if (model) { modelSource = tr('transcript (last response; observed, does not guarantee the next one after a model switch)', 'transcript (ultima resposta; observado, nao garante a proxima apos troca de modelo)'); observed = true; } }
|
|
32
|
+
if (!model) { const { modelFromProcessChain } = await import('../../src/claude-model.js'); model = modelFromProcessChain() ?? undefined; if (model) { modelSource = tr('--model flag of the claude process (observed at start; /model may have changed it)', 'flag --model do processo claude (observado no inicio; /model pode ter trocado)'); observed = true; } }
|
|
33
|
+
if (!model) {
|
|
34
|
+
const { declaredModels } = await import('../../src/claude-model.js');
|
|
35
|
+
declared = declaredModels({ cwd: ev.cwd, config });
|
|
36
|
+
if (declared.length) { model = declared[0].model; modelSource = declared[0].source; const distinct = new Set(declared.map((x) => x.model)); proven = config.trustConfiguredModel === true && distinct.size === 1; if (distinct.size > 1) modelSource += tr(` (CONFLICT between ${[...distinct].join(', ')})`, ` (CONFLITO entre ${[...distinct].join(', ')})`); }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// So PRECOST_MODEL e aceito sem pior caso, como DECLARACAO do operador (nao e prova tecnica do modelo efetivo). Fonte observada (tracker/transcript/flag) e a melhor evidencia, mas NAO garante o modelo da proxima resposta (troca de modelo): so conta como comprovada com trustConfiguredModel:true e sem conflito com fontes declaradas.
|
|
40
|
+
if (observed) {
|
|
41
|
+
const { declaredModels } = await import('../../src/claude-model.js');
|
|
42
|
+
declared = declaredModels({ cwd: ev.cwd, config }).filter((x) => x.model !== model);
|
|
43
|
+
if (declared.length) modelSource += tr(` (CONFLICT with ${[...new Set(declared.map((x) => x.model))].join(', ')})`, ` (CONFLITO com ${[...new Set(declared.map((x) => x.model))].join(', ')})`);
|
|
44
|
+
proven = config.trustConfiguredModel === true && declared.length === 0;
|
|
45
|
+
if (ev.transcript_path) { const { pendingModelSwitch } = await import('../../src/claude-transcript.js'); const sw = pendingModelSwitch(ev.transcript_path); if (sw) { proven = false; modelSource += tr(` (MODEL SWITCH /model${sw.args ? ' ' + sw.args : ''} recorded in the transcript after the last response: the current model may be different)`, ` (TROCA DE MODELO /model${sw.args ? ' ' + sw.args : ''} registrada no transcript depois da ultima resposta: o modelo atual pode ser outro)`); if (sw.args) declared.push({ model: sw.args, source: tr('/model from the transcript', '/model do transcript') }); } }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let d;
|
|
49
|
+
try {
|
|
50
|
+
const { decide } = await import('../../src/gate.js'); // import dinamico: falha de carga vira falha FECHADA (com limite), nao saida nao-bloqueante
|
|
51
|
+
const { filesFromPrompt } = await import('../../src/context.js');
|
|
52
|
+
const root = ev.cwd ?? process.cwd();
|
|
53
|
+
const { dirname } = await import('node:path'); const { loadPrices } = await import('../../src/pricing.js');
|
|
54
|
+
let history; // historico REAL do projeto e do modelo ativo (transcripts), so se houver 5+ sessoes
|
|
55
|
+
if (model && ev.transcript_path) { const { historyFromDir } = await import('../../src/claude-transcript.js'); const h = historyFromDir(dirname(ev.transcript_path), { model, prices: loadPrices(config.prices), excludeSession: ev.session_id }); if (h.length) history = { [model]: h }; }
|
|
56
|
+
const prices0 = loadPrices(config.prices);
|
|
57
|
+
const candidates = !proven && model ? [...new Set([model, ...declared.map((x) => x.model), ...(/^claude/i.test(model) ? Object.keys(prices0.models).filter((k) => k.startsWith('claude-')) : [])])] : [];
|
|
58
|
+
d = decide({ prompt: ev.prompt ?? '', model, session: ev.session_id, config: { systemTokens: 13000, ...config }, stateDir, history, files: filesFromPrompt(ev.prompt ?? '', root), modelProof: model ? { proven, source: modelSource, candidates } : undefined });
|
|
59
|
+
if (modelSource && d.text) d.text += tr(`\nActive model comes from: ${modelSource}.`, `\nModelo ativo vem de: ${modelSource}.`);
|
|
60
|
+
} catch (e) { failure(tr(`internal error (${e.message})`, `erro interno (${e.message})`)); }
|
|
61
|
+
if (d.action === 'block') block(d.text);
|
|
62
|
+
else process.stdout.write(JSON.stringify({ systemMessage: d.text }));
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Plugin OpenCode (API V1, pacote @opencode-ai/plugin 1.19.x). Cobertura real em docs/CAPACIDADES.md.
|
|
2
|
+
// - tool precost_estimate: previa sob demanda (o modelo ou o usuario chama).
|
|
3
|
+
// - event message.updated: registra tokens/custo reais por sessao (base do historico e do limite).
|
|
4
|
+
// - tool.execute.before: com sessionLimitUsd, LANCA erro quando o gasto real da sessao passa do limite (bloqueio real de ferramenta).
|
|
5
|
+
// - chat.message: com limitUsd, bloqueia o prompt (throw) e exige 'precost approve CODIGO'; sem limitUsd so registra a previa.
|
|
6
|
+
import { tool } from '@opencode-ai/plugin';
|
|
7
|
+
import { ledgerPath, stateDir } from '../../src/paths.js';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { loadPrices } from '../../src/pricing.js';
|
|
10
|
+
import { estimate } from '../../src/estimate.js';
|
|
11
|
+
import { format } from '../../src/format.js';
|
|
12
|
+
import { SessionLedger } from '../../src/history.js';
|
|
13
|
+
import { decide, validateConfig, isCommand } from '../../src/gate.js';
|
|
14
|
+
import { filesFromParts } from '../../src/context.js';
|
|
15
|
+
import { tr, setLang } from '../../src/i18n.js';
|
|
16
|
+
|
|
17
|
+
export const PINNED_OPENCODE = '1.19.6';
|
|
18
|
+
|
|
19
|
+
export const PrecostPlugin = async (input = {}, options = {}) => {
|
|
20
|
+
const client = input.client;
|
|
21
|
+
setLang(options.lang);
|
|
22
|
+
const prices = loadPrices(options.prices);
|
|
23
|
+
const models = options.models ?? Object.keys(prices.models);
|
|
24
|
+
const ledger = new SessionLedger(options.historyPath ?? ledgerPath());
|
|
25
|
+
const histFor = (modelID) => ledger.list().filter((s) => s.turns > 0 && s.model && s.model === modelID && s.project === input.directory).map((s) => ({ input: s.input, output: s.output, cache_read: s.cache_read, cache_write: s.cache_write, turns: s.turns, peakCtx: s.peakCtx }));
|
|
26
|
+
const histMap = (ms) => Object.fromEntries(ms.map((m) => [m, histFor(m)]));
|
|
27
|
+
const run = (task) => {
|
|
28
|
+
const hist = histMap(models);
|
|
29
|
+
return format(estimate({ task, models, prices, history: hist, cacheHit: options.cacheHit ?? 0 }));
|
|
30
|
+
};
|
|
31
|
+
let cachedVersion;
|
|
32
|
+
const version = async () => {
|
|
33
|
+
if (options.version !== undefined) return options.version;
|
|
34
|
+
if (cachedVersion) return cachedVersion;
|
|
35
|
+
try { const r = await fetch(new URL('/global/health', input.serverUrl)); cachedVersion = (await r.json()).version; } catch { /* nao identificada */ }
|
|
36
|
+
if (!cachedVersion) { // TUI: serverUrl e fantasma (localhost:4096 sem servidor). Fallback: perguntar ao proprio binario em execucao; se nao for o opencode, a saida nao casa e o gate falha FECHADO.
|
|
37
|
+
try { const { execFileSync } = await import('node:child_process'); const o = execFileSync(process.execPath, ['--version'], { timeout: 5000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); if (/^\d+\.\d+\.\d+/.test(o)) cachedVersion = o; } catch { /* nao identificada */ }
|
|
38
|
+
}
|
|
39
|
+
return cachedVersion;
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
tool: {
|
|
43
|
+
precost_estimate: tool({
|
|
44
|
+
description: 'Estimates the cost range (USD) of a task before running it. Separates known context from the estimated range.',
|
|
45
|
+
args: { task: tool.schema.string().describe('description of the task to estimate') },
|
|
46
|
+
async execute(args) { return run(args.task); },
|
|
47
|
+
}),
|
|
48
|
+
},
|
|
49
|
+
event: async ({ event }) => {
|
|
50
|
+
if (event.type !== 'message.updated') return;
|
|
51
|
+
const m = event.properties.info;
|
|
52
|
+
if (m.role === 'assistant' && m.time?.completed) ledger.record({ id: m.id, sessionID: m.sessionID, cost: m.cost, tokens: m.tokens, model: m.modelID, project: input.directory });
|
|
53
|
+
},
|
|
54
|
+
// Verificado em opencode 1.19.6 (docs/evidence-*): lancar aqui impede o prompt de entrar na sessao e de chegar ao modelo.
|
|
55
|
+
// Efeito NAO documentado: por isso a versao e fixada (PINNED_OPENCODE) e verificada em runtime; versao diferente = FALHA FECHADA,
|
|
56
|
+
// salvo options.allowUnverifiedVersion. O cliente recebe so erro generico; o texto tambem vai para toast (melhor esforco),
|
|
57
|
+
// options.log e <stateDir>/last-block.txt (comando: precost last).
|
|
58
|
+
'chat.message': async (inp, output) => {
|
|
59
|
+
const gated = options.limitUsd !== undefined && options.limitUsd !== null;
|
|
60
|
+
const text = (output.parts ?? []).filter((p) => p.type === 'text').map((p) => p.text).join('\n');
|
|
61
|
+
const deny = async (msg) => { try { await client?.tui?.showToast?.({ body: { message: msg.slice(0, 600), variant: 'warning' } }); } catch { /* sem TUI */ } const err = new Error(msg); err.precostDeny = true; throw err; };
|
|
62
|
+
try {
|
|
63
|
+
const root0 = input.directory ?? process.cwd();
|
|
64
|
+
if (isCommand(text)) { // comandos do usuario: SEMPRE interceptados (nunca chegam ao modelo), com ou sem limite
|
|
65
|
+
const c = decide({ prompt: text, model: inp.model?.modelID, session: inp.sessionID, config: { limitUsd: options.limitUsd, ttlMin: options.ttlMin, cacheHit: options.cacheHit, prices: options.prices, compare: options.compare, lang: options.lang }, stateDir: options.stateDir ?? stateDir(), history: histMap([inp.model?.modelID, ...(options.compare ?? [])].filter(Boolean)) });
|
|
66
|
+
return await deny(c.text);
|
|
67
|
+
}
|
|
68
|
+
if (!gated) { if (text && options.log) options.log(run(text)); return; }
|
|
69
|
+
const bad = validateConfig(options);
|
|
70
|
+
if (bad) return await deny(tr(`precost: invalid configuration (${bad}). Blocked (fail closed).`, `precost: configuracao invalida (${bad}). Bloqueado (falha fechada).`));
|
|
71
|
+
if (!options.allowUnverifiedVersion) {
|
|
72
|
+
const v = await version(inp);
|
|
73
|
+
if (v !== PINNED_OPENCODE) return await deny(tr(`precost: OpenCode version ${v ?? 'not identified'} differs from the verified one (${PINNED_OPENCODE}); blocking by throw is undocumented behavior. Blocked (fail closed). Validate with npm run e2e:opencode and set allowUnverifiedVersion:true at your own risk.`, `precost: versao do OpenCode ${v ?? 'nao identificada'} difere da verificada (${PINNED_OPENCODE}); o bloqueio por throw e comportamento nao documentado. Bloqueado (falha fechada). Valide com npm run e2e:opencode e use allowUnverifiedVersion:true por sua conta.`));
|
|
74
|
+
}
|
|
75
|
+
const root = root0;
|
|
76
|
+
const fileParts = filesFromParts(output.parts, root);
|
|
77
|
+
if (!text && fileParts.length === 0) return; // sem texto e sem arquivo: nada a avaliar
|
|
78
|
+
|
|
79
|
+
const d = decide({ prompt: text ?? '', model: inp.model?.modelID, session: inp.sessionID, files: fileParts, config: { limitUsd: options.limitUsd, ttlMin: options.ttlMin, cacheHit: options.cacheHit, prices: options.prices, compare: options.compare, lang: options.lang }, stateDir: options.stateDir ?? stateDir(), history: histMap([inp.model?.modelID, ...(options.compare ?? [])].filter(Boolean)) });
|
|
80
|
+
if (options.log) options.log(d.text);
|
|
81
|
+
if (d.action === 'allow') return;
|
|
82
|
+
return await deny(d.text);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
if (e?.precostDeny) throw e;
|
|
85
|
+
return await deny(tr(`precost: internal error (${e?.message}); blocked for safety (fail closed).`, `precost: erro interno (${e?.message}); bloqueado por seguranca (falha fechada).`));
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
'tool.execute.before': async (input) => {
|
|
89
|
+
if (options.sessionLimitUsd === undefined) return;
|
|
90
|
+
if (typeof options.sessionLimitUsd !== 'number' || !Number.isFinite(options.sessionLimitUsd)) throw new Error(tr('precost: invalid sessionLimitUsd; blocked (fail closed).', 'precost: sessionLimitUsd invalido; bloqueado (falha fechada).'));
|
|
91
|
+
const s = ledger.spent(input.sessionID);
|
|
92
|
+
if (s > options.sessionLimitUsd) throw new Error(tr(`precost: session spend US$${s.toFixed(2)} passed the US$${options.sessionLimitUsd} limit. Raise the limit or start a new session.`, `precost: gasto da sessao US$${s.toFixed(2)} passou do limite US$${options.sessionLimitUsd}. Aumente o limite ou inicie nova sessao.`));
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
export default { id: 'opencode-precost', server: PrecostPlugin };
|
package/bin/precost.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import { stateDir, configPath } from '../src/paths.js';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { loadPrices } from '../src/pricing.js';
|
|
7
|
+
import { estimate } from '../src/estimate.js';
|
|
8
|
+
import { format } from '../src/format.js';
|
|
9
|
+
import { tr, setLang } from '../src/i18n.js';
|
|
10
|
+
|
|
11
|
+
try { setLang(JSON.parse(readFileSync(configPath(), 'utf8')).lang); } catch { setLang(undefined); }
|
|
12
|
+
|
|
13
|
+
if (process.argv[2] === 'doctor') {
|
|
14
|
+
const { doctor } = await import('../src/doctor.js'); const a = process.argv.slice(3); const cs = []; let project = process.cwd();
|
|
15
|
+
for (let i = 0; i < a.length; i++) { if (a[i] === '--claude-settings') cs.push(a[++i]); else if (a[i] === '--project') project = a[++i]; }
|
|
16
|
+
const { levelLabel } = await import('../src/doctor.js'); const res = doctor({ project, claudeSettings: cs }); for (const r of res) console.log(`[${levelLabel(r.level)}] ${r.msg}`);
|
|
17
|
+
process.exit(res.some((r) => r.level === 'FAIL') ? 1 : 0);
|
|
18
|
+
}
|
|
19
|
+
if (process.argv[2] === 'prices' || process.argv[2] === 'update-prices') { const { runPricesCli } = await import('../src/prices-cli.js'); process.exit(await runPricesCli(process.argv[2], process.argv.slice(3))); }
|
|
20
|
+
if (process.argv[2] === 'last') { // ultima mensagem de bloqueio (UX quando o cliente so mostra erro generico)
|
|
21
|
+
try { console.log((() => { const d = stateDir(); const fs = readdirSync(d).filter((f) => /^last-block-/.test(f)).map((f) => [f, statSync(join(d, f)).mtimeMs]).sort((a, b) => b[1] - a[1]); return fs.length ? tr('(latest block of any session: ', '(ultimo bloqueio de qualquer sessao: ') + fs[0][0] + ')\n' + readFileSync(join(d, fs[0][0]), 'utf8') : (() => { throw 0; })(); })()); } catch { console.log(tr('precost: no block recorded.', 'precost: sem bloqueio registrado.')); }
|
|
22
|
+
process.exit(0);
|
|
23
|
+
}
|
|
24
|
+
if (process.argv[2] === 'estimate' && process.argv[3] && !process.argv[3].startsWith('--')) { // precost estimate "tarefa" [--model m]: usa model do config se existir
|
|
25
|
+
let cfg = {}; try { cfg = JSON.parse(readFileSync(configPath(), 'utf8')); } catch { /* sem config */ }
|
|
26
|
+
const rest = process.argv.slice(4);
|
|
27
|
+
process.argv.splice(2, 2, '--task', process.argv[3], ...(rest.includes('--model') || !cfg.model ? [] : ['--model', cfg.model]));
|
|
28
|
+
}
|
|
29
|
+
const { values } = parseArgs({ options: {
|
|
30
|
+
task: { type: 'string' }, 'task-file': { type: 'string' }, file: { type: 'string', multiple: true },
|
|
31
|
+
model: { type: 'string', multiple: true }, prices: { type: 'string' }, history: { type: 'string' },
|
|
32
|
+
'cache-hit': { type: 'string' }, json: { type: 'boolean' }, date: { type: 'string' },
|
|
33
|
+
} });
|
|
34
|
+
const task = values.task ?? (values['task-file'] ? readFileSync(values['task-file'], 'utf8') : '');
|
|
35
|
+
if (!task) { console.error(tr('usage: precost --task "..." [--file f]... [--model m]... [--history h.json] [--cache-hit 0.5] [--json]', 'uso: precost --task "..." [--file f]... [--model m]... [--history h.json] [--cache-hit 0.5] [--json]')); process.exit(2); }
|
|
36
|
+
const prices = loadPrices(values.prices);
|
|
37
|
+
const models = values.model ?? Object.keys(prices.models);
|
|
38
|
+
const history = values.history ? JSON.parse(readFileSync(values.history, 'utf8')) : undefined;
|
|
39
|
+
if (Array.isArray(history) && models.length > 1) { console.error(tr('precost: --history as a list applies to ONE model; to compare several use a {"model": [sessions]} map (each row uses only its own history).', 'precost: --history como lista vale para UM modelo; para comparar varios use um mapa {"modelo": [sessoes]} (cada linha usa so o seu historico).')); process.exit(2); }
|
|
40
|
+
const res = estimate({ task, fileTexts: (values.file ?? []).map((f) => readFileSync(f, 'utf8')), models, prices, history, cacheHit: Number(values['cache-hit'] ?? 0), date: values.date });
|
|
41
|
+
console.log(values.json ? JSON.stringify(res, null, 2) : format(res));
|