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/data/prices.json
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "USD per 1M tokens, Standard/global, first-party API. Missing field = unknown (never zero). Gemini: tier above 200K; Gemini 4 has no known tier above 200K (unknown). Claude: 1M context at the standard price, except Haiku 5.5 (tier at 100K). Cache write not modeled (slightly underestimates). Batch, Priority, Fast mode and data residency (1.1x) not modeled. Promotion = conditional benefit, never part of the gross price. long_context: 'none' = page lists no tier above the threshold (single price); 'unknown' = table without that column (Gemini 4): cost above the threshold becomes a lower bound and requires approval.",
|
|
3
|
+
"currency": "USD",
|
|
4
|
+
"long_context_threshold_tokens": 200000,
|
|
5
|
+
"models": {
|
|
6
|
+
"gemini-3.1-flash-lite": {
|
|
7
|
+
"input": 0.25,
|
|
8
|
+
"output": 1.5,
|
|
9
|
+
"cache_read": 0.025,
|
|
10
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
11
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
12
|
+
"long_context": "none"
|
|
13
|
+
},
|
|
14
|
+
"gemini-3.5-flash-lite": {
|
|
15
|
+
"input": 0.3,
|
|
16
|
+
"output": 2.5,
|
|
17
|
+
"cache_read": 0.03,
|
|
18
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
19
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
20
|
+
"long_context": "none"
|
|
21
|
+
},
|
|
22
|
+
"gemini-3.5-flash": {
|
|
23
|
+
"input": 1.5,
|
|
24
|
+
"output": 9.0,
|
|
25
|
+
"cache_read": 0.15,
|
|
26
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
27
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
28
|
+
"long_context": "none"
|
|
29
|
+
},
|
|
30
|
+
"gemini-3.6-flash": {
|
|
31
|
+
"input": 0.75,
|
|
32
|
+
"output": 3.75,
|
|
33
|
+
"cache_read": 0.075,
|
|
34
|
+
"changes": [
|
|
35
|
+
{
|
|
36
|
+
"from": "2027-01-01",
|
|
37
|
+
"input": 1.5,
|
|
38
|
+
"output": 7.5,
|
|
39
|
+
"cache_read": 0.15,
|
|
40
|
+
"note": "introductory price until 2026-12-31"
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
44
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
45
|
+
"long_context": "none"
|
|
46
|
+
},
|
|
47
|
+
"gemini-3.7-flash": {
|
|
48
|
+
"input": 0.75,
|
|
49
|
+
"output": 3.75,
|
|
50
|
+
"cache_read": 0.075,
|
|
51
|
+
"changes": [
|
|
52
|
+
{
|
|
53
|
+
"from": "2027-01-01",
|
|
54
|
+
"input": 1.5,
|
|
55
|
+
"output": 7.5,
|
|
56
|
+
"cache_read": 0.15,
|
|
57
|
+
"note": "introductory price until 2026-12-31"
|
|
58
|
+
}
|
|
59
|
+
],
|
|
60
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
61
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
62
|
+
"long_context": "none"
|
|
63
|
+
},
|
|
64
|
+
"gemini-3.8-flash": {
|
|
65
|
+
"input": 0.75,
|
|
66
|
+
"output": 3.75,
|
|
67
|
+
"cache_read": 0.075,
|
|
68
|
+
"changes": [
|
|
69
|
+
{
|
|
70
|
+
"from": "2027-01-01",
|
|
71
|
+
"input": 1.5,
|
|
72
|
+
"output": 7.5,
|
|
73
|
+
"cache_read": 0.15,
|
|
74
|
+
"note": "introductory price until 2026-12-31"
|
|
75
|
+
}
|
|
76
|
+
],
|
|
77
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
78
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
79
|
+
"long_context": "none"
|
|
80
|
+
},
|
|
81
|
+
"gemini-3.1-pro-preview": {
|
|
82
|
+
"input": 2.0,
|
|
83
|
+
"output": 12.0,
|
|
84
|
+
"cache_read": 0.2,
|
|
85
|
+
"long_context": {
|
|
86
|
+
"input": 4.0,
|
|
87
|
+
"output": 18.0,
|
|
88
|
+
"cache_read": 0.4
|
|
89
|
+
},
|
|
90
|
+
"note": "above 200K input tokens in the request, ALL tokens use the long-context rate",
|
|
91
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
92
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)"
|
|
93
|
+
},
|
|
94
|
+
"gemini-4-hydrogen": {
|
|
95
|
+
"input": 1.5,
|
|
96
|
+
"output": 7.5,
|
|
97
|
+
"cache_read": 0.075,
|
|
98
|
+
"cache_write": 1.875,
|
|
99
|
+
"cache_write_from": "2027-01-12",
|
|
100
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
101
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
102
|
+
"long_context": "unknown"
|
|
103
|
+
},
|
|
104
|
+
"gemini-4-neon": {
|
|
105
|
+
"input": 3.0,
|
|
106
|
+
"output": 15.0,
|
|
107
|
+
"cache_read": 0.15,
|
|
108
|
+
"cache_write": 3.75,
|
|
109
|
+
"cache_write_from": "2027-01-12",
|
|
110
|
+
"access_note": "docs page mentions 'verified enterprise customers in select regions' (earlier analysis); real account access not verified",
|
|
111
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
112
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
113
|
+
"long_context": "unknown"
|
|
114
|
+
},
|
|
115
|
+
"gemini-4-carbon": {
|
|
116
|
+
"access_note": "same enterprise access notice as Neon (earlier analysis)",
|
|
117
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
118
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
119
|
+
"input": 4.0,
|
|
120
|
+
"output": 20.0,
|
|
121
|
+
"cache_read": 0.2,
|
|
122
|
+
"promo": {
|
|
123
|
+
"until": "2026-11-30",
|
|
124
|
+
"credit_back_pct": 50,
|
|
125
|
+
"conditional": true,
|
|
126
|
+
"note": "page: promotional price via 50% credits back on net spend. Gross bill treated as list price (4/20), value inferred from the post-promotion price and the footer; the credit is a conditional benefit, not an invoice discount"
|
|
127
|
+
},
|
|
128
|
+
"changes": [
|
|
129
|
+
{
|
|
130
|
+
"from": "2026-12-01",
|
|
131
|
+
"promo": null
|
|
132
|
+
}
|
|
133
|
+
],
|
|
134
|
+
"long_context": "unknown"
|
|
135
|
+
},
|
|
136
|
+
"gemini-4-argon": {
|
|
137
|
+
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
|
|
138
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Standard, Global)",
|
|
139
|
+
"input": 4.0,
|
|
140
|
+
"output": 20.0,
|
|
141
|
+
"cache_read": 0.2,
|
|
142
|
+
"promo": {
|
|
143
|
+
"until": "2026-11-30",
|
|
144
|
+
"credit_back_pct": 50,
|
|
145
|
+
"conditional": true,
|
|
146
|
+
"note": "page: promotional price via 50% credits back on net spend. Gross bill treated as list price (4/20), value inferred from the post-promotion price and the footer; the credit is a conditional benefit, not an invoice discount"
|
|
147
|
+
},
|
|
148
|
+
"changes": [
|
|
149
|
+
{
|
|
150
|
+
"from": "2026-12-01",
|
|
151
|
+
"promo": null
|
|
152
|
+
}
|
|
153
|
+
],
|
|
154
|
+
"long_context": "unknown"
|
|
155
|
+
},
|
|
156
|
+
"claude-fable-5.2": {
|
|
157
|
+
"input": 8,
|
|
158
|
+
"output": 40,
|
|
159
|
+
"cache_read": 0.2,
|
|
160
|
+
"cache_write_5m": 10,
|
|
161
|
+
"cache_write_1h": 16,
|
|
162
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
163
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
164
|
+
"tokenizer_note": "new tokenizer (4.7+): ~30% more tokens for the same text; chars/4 underestimates",
|
|
165
|
+
"long_context": "none",
|
|
166
|
+
"tokenizer_multiplier": 1.3
|
|
167
|
+
},
|
|
168
|
+
"claude-opus-5.5": {
|
|
169
|
+
"input": 4,
|
|
170
|
+
"output": 20,
|
|
171
|
+
"cache_read": 0.2,
|
|
172
|
+
"cache_write_5m": 5,
|
|
173
|
+
"cache_write_1h": 8,
|
|
174
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
175
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
176
|
+
"tokenizer_note": "new tokenizer (4.7+): ~30% more tokens for the same text; chars/4 underestimates",
|
|
177
|
+
"long_context": "none",
|
|
178
|
+
"tokenizer_multiplier": 1.3
|
|
179
|
+
},
|
|
180
|
+
"claude-sonnet-5.5": {
|
|
181
|
+
"input": 2,
|
|
182
|
+
"output": 10,
|
|
183
|
+
"cache_read": 0.1,
|
|
184
|
+
"cache_write_5m": 2.5,
|
|
185
|
+
"cache_write_1h": 4,
|
|
186
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
187
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
188
|
+
"tokenizer_note": "new tokenizer (4.7+): ~30% more tokens for the same text; chars/4 underestimates",
|
|
189
|
+
"long_context": "none",
|
|
190
|
+
"tokenizer_multiplier": 1.3
|
|
191
|
+
},
|
|
192
|
+
"claude-haiku-5.5": {
|
|
193
|
+
"input": 0.1,
|
|
194
|
+
"output": 0.5,
|
|
195
|
+
"cache_read": 0.01,
|
|
196
|
+
"cache_write_5m": 0.125,
|
|
197
|
+
"cache_write_1h": 0.2,
|
|
198
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
199
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
200
|
+
"long_context_threshold": 100000,
|
|
201
|
+
"long_context": {
|
|
202
|
+
"input": 0.5,
|
|
203
|
+
"output": 2.5,
|
|
204
|
+
"cache_read": 0.05,
|
|
205
|
+
"cache_write_5m": 0.625
|
|
206
|
+
},
|
|
207
|
+
"tokenizer_note": "new tokenizer (4.7+): ~30% more tokens for the same text; chars/4 underestimates",
|
|
208
|
+
"tokenizer_multiplier": 1.3
|
|
209
|
+
},
|
|
210
|
+
"claude-sonnet-4.6": {
|
|
211
|
+
"input": 3,
|
|
212
|
+
"output": 15,
|
|
213
|
+
"cache_read": 0.3,
|
|
214
|
+
"cache_write_5m": 3.75,
|
|
215
|
+
"cache_write_1h": 6,
|
|
216
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
217
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
218
|
+
"long_context": "none"
|
|
219
|
+
},
|
|
220
|
+
"claude-opus-4.5": {
|
|
221
|
+
"input": 5,
|
|
222
|
+
"output": 25,
|
|
223
|
+
"cache_read": 0.5,
|
|
224
|
+
"cache_write_5m": 6.25,
|
|
225
|
+
"cache_write_1h": 10,
|
|
226
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
227
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
228
|
+
"long_context": "none"
|
|
229
|
+
},
|
|
230
|
+
"claude-haiku-4.5": {
|
|
231
|
+
"input": 1,
|
|
232
|
+
"output": 5,
|
|
233
|
+
"cache_read": 0.1,
|
|
234
|
+
"cache_write_5m": 1.25,
|
|
235
|
+
"cache_write_1h": 2,
|
|
236
|
+
"source": "https://platform.claude.com/docs/en/about-claude/pricing",
|
|
237
|
+
"read": "2026-11-25 (corpo da pagina oficial, tabela Model pricing, Claude API, global)",
|
|
238
|
+
"long_context": "none"
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
**English** | Português: [CAPACIDADES.md](CAPACIDADES.md) (historical log, longer)
|
|
2
|
+
|
|
3
|
+
# What each client really allows
|
|
4
|
+
|
|
5
|
+
Status as of 2026-11-25. VERIFIED = run against the real software. DOC = documentation or types only. No paid model was called.
|
|
6
|
+
|
|
7
|
+
## Honest summary
|
|
8
|
+
|
|
9
|
+
- **OpenCode does not preview cost before the model on its own.** This plugin computes the preview inside the `chat.message` hook, which runs before the model.
|
|
10
|
+
- **The tool gate (`tool.execute.before` plus a session limit) is not a spending cap.** By the time a tool is requested the model has already been called and billed. Only the prompt gate acts before the first spend of a task, and it does not limit spend inside an approved task.
|
|
11
|
+
- Neither gate stops long loops started by an approved prompt.
|
|
12
|
+
|
|
13
|
+
| Capability | OpenCode 1.19.6 (plugin V1) | Claude Code (hooks) |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Plugin/hook loads | VERIFIED (`opencode serve` listed the `precost_estimate` tool; shim + npm package also verified) | VERIFIED with 2.1.332 (`--plugin-dir`, fake server) |
|
|
16
|
+
| Hook receives the prompt before the model | VERIFIED (`chat.message` fired with the real prompt before any processing event) | VERIFIED (`UserPromptSubmit` gets `prompt`, `session_id`, `transcript_path`, `cwd`) |
|
|
17
|
+
| Block a prompt | VERIFIED: throwing in `chat.message` keeps the prompt out of the session (0 messages) and away from the model. Undocumented behavior; the client sees a generic error, the TUI shows the text in an error box | VERIFIED: `{"decision":"block","reason":...}` blocks; the model server counter stayed at 0; text visible in `claude -p` and in the interactive TUI |
|
|
18
|
+
| Block, approve, resend, single use | VERIFIED on a real server: messages 0, 0, 0, 1, 1 | VERIFIED with real client and fake server (1 model call after approval, blocked again on the next resend) |
|
|
19
|
+
| Active model | `chat.message` receives `input.model.modelID` | The event does **not** carry the model. Tracked by `SessionStart.model` (optional) and `PostModelSwitch.to_model`; otherwise by the last transcript response, the process `--model` flag (Linux only), declared sources, or the worst case |
|
|
20
|
+
| Real spend per message | `message.updated` of the assistant carries `cost` and `tokens` (checked against a fake provider) | transcript `usage` fields (checked against a fake server) |
|
|
21
|
+
| Automatic prompts | n/a | DOC: `UserPromptSubmit` also fires for scheduled tasks, background subagents and messages from other sessions; the gate can block them |
|
|
22
|
+
|
|
23
|
+
## Approval (explicit and bound)
|
|
24
|
+
|
|
25
|
+
Resending the same prompt never approves it. To approve, type `precost approve CODE` (a random code for the pending block). The approval binds prompt, model, session, price table hash, limit and estimated ceiling. It lasts a TTL (default 10 minutes), works once, and `precost revoke CODE|all` revokes it. Any change to those items invalidates it.
|
|
26
|
+
|
|
27
|
+
## Estimator limits
|
|
28
|
+
|
|
29
|
+
- The observed input is characters. Tokens = chars/4. System/tool overhead is an assumption (8k OpenCode, 13k Claude Code, derived from measured request body size).
|
|
30
|
+
- Without history (fewer than 5 sessions of the same model and project): three fixed scenarios with assumptions, not measurements. With history: P25/P50/P75 aggregates.
|
|
31
|
+
- Claude 4.7+ tokenizer: observed tokens x1.3 (approximate, from the official note). All new input is priced as 5-minute cache write (conservative, may overestimate).
|
|
32
|
+
- Long context: `none` (no tier on the page), an object (e.g. 3.1 Pro, Haiku 5.5 at 100K) or `unknown` (Gemini 4: only a lower bound, requires approval).
|
|
33
|
+
- Price table: official pages read on 2026-11-25 (Standard, Global). Not modeled: Batch, Priority, Flex, Fast mode, data residency (1.1x). Raw Carbon/Argon price is inferred (the page describes 50% credits back); the gate uses the raw price. Access to those models on a given account was not verified.
|
|
34
|
+
|
|
35
|
+
## Safety model
|
|
36
|
+
|
|
37
|
+
- Approval state lives in files of the same user (`~/.cache/precost`, Windows `%LOCALAPPDATA%\precost\state`). An agent with a shell or write access as that user can forge an approval or read the code. The gate protects against accidental spend, not an adversarial agent.
|
|
38
|
+
- `precost approve` is accepted only as typed user prompt text. The local CLI approves nothing; `precost last` only shows the last block.
|
|
39
|
+
- **Fail closed** (when `limitUsd` is set): a non-numeric or negative limit, invalid TTL, unreadable config or price table, internal error, unreadable hook input, unknown or unpriced model, a cost with only a lower bound, or a context file that could not be counted (large, outside the project, secret) all block and ask for approval or a fix. Without `limitUsd` the tool only informs and says "NO GATE".
|
|
40
|
+
- **Hook failure** (Claude Code): with `onFailure: "block"`, a script crash, missing `node` or timeout never reaches the model (real client, negative control included). Without it, or with `continue`, the prompt goes through.
|
|
41
|
+
- **OpenCode:** depends on undocumented throw behavior, so the version is pinned to 1.19.6 (read from `/global/health` or the binary); a different or unknown version blocks unless `allowUnverifiedVersion: true`.
|
|
42
|
+
- Files referenced in a prompt (`@path` in Claude Code, `file` parts in OpenCode) are read inside the project, counted in the estimate, and their content hash is part of the approval. Ignored files (secret, large) are not read; their size+mtime signature binds the approval (a change that preserves both is not detected).
|
|
43
|
+
|
|
44
|
+
## Model resolution in Claude Code
|
|
45
|
+
|
|
46
|
+
The hook does not receive the model. Chain: `PRECOST_MODEL` (an operator declaration, treated as proven, but it does not force the request) > tracker > last transcript response > process `--model` flag (observed: they do not prove the model of the next prompt after `/model`) > `ANTHROPIC_MODEL`, settings, `config.model` (declared). An unproven model uses the worst case across all candidate `claude-*` models and says so; the approval is bound to that state. Conflicting declared sources are never proven. `trustConfiguredModel: true` accepts a single consistent observed/declared model, except when the transcript records a `/model` after the last response (then the worst case applies).
|
|
47
|
+
|
|
48
|
+
## History
|
|
49
|
+
|
|
50
|
+
With at least 5 sessions of the same model and project, the preview uses real consumption. The peak per call is the largest recorded (not a quantile). Each compared line uses only its own model's history. Token semantics were checked against real events and transcripts with fake providers: `input` excludes cache. No comparison with a real invoice has been made.
|
|
51
|
+
|
|
52
|
+
## Not verified
|
|
53
|
+
|
|
54
|
+
Real invoice comparison, `PostModelSwitch` in a user install, subagents and scheduled runs, raw Carbon/Argon price, approval flow visuals in the OpenCode TUI beyond the tested pty cycle, and real end-to-end use on macOS and Windows (see the matrix in INSTALLATION.md).
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# O que cada ferramenta permite de verdade
|
|
2
|
+
|
|
3
|
+
Estado em 25/nov/2026. VERIFICADO = rodei aqui contra o software real. DOC = so li documentacao/tipos. Nada foi chamado com modelo pago.
|
|
4
|
+
|
|
5
|
+
## Resumo honesto
|
|
6
|
+
- **OpenCode NAO faz previa automatica antes do modelo por conta propria.** Este plugin e que calcula a previa dentro do hook `chat.message`, que roda antes do modelo.
|
|
7
|
+
- **O gate de ferramenta (`tool.execute.before` + limite de sessao) NAO e teto de gasto do LLM**: o modelo ja foi chamado e cobrado quando a ferramenta e pedida; o gate so impede a proxima ferramenta depois que o gasto passou do limite. So o gate de prompt (`chat.message`) age antes do primeiro gasto da tarefa, e nao limita o gasto dentro de uma tarefa ja aprovada.
|
|
8
|
+
- Nenhum dos dois impede loops longos de um prompt aprovado.
|
|
9
|
+
|
|
10
|
+
| Capacidade | OpenCode 1.19.6 (plugin V1) | Claude Code (hooks) |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| Plugin/hook carrega | VERIFICADO: `opencode serve` listou a tool `precost_estimate` (evidence-opencode-1.19.6-load.log) | NAO TESTADO em Claude Code real (nao instalado/autenticado) |
|
|
13
|
+
| Hook recebe o prompt antes do modelo | VERIFICADO: `chat.message` disparou com o prompt real no servidor, antes de qualquer evento de processamento (evidence-opencode-events.log) | DOC: `UserPromptSubmit` recebe `prompt` (hooks.md, secao UserPromptSubmit input) |
|
|
14
|
+
| Bloquear prompt | VERIFICADO: lancar erro em `chat.message` impede o prompt de entrar na sessao (0 mensagens) e de chegar ao modelo (evidence-opencode-chatmessage-throw.log). Efeito nao documentado; o cliente so ve erro generico "Unexpected server error"; o texto vai por toast (melhor esforco, nao verificado sem TUI) e log | DOC: `{"decision":"block","reason":...}` com exit 0 bloqueia; `reason` aparece ao usuario. Testado so com JSON simulado |
|
|
15
|
+
| Ciclo bloqueio -> approve -> reenvio -> uso unico | VERIFICADO no servidor real: msgs 0, 0, 0, 1, 1 (evidence-opencode-gate-cycle.log, scripts/opencode-gate-e2e.sh); a etapa do provedor falhou por falta de credencial (esperado) | Testado com hook simulado (test/cc-hook.test.js, test/gate.test.js) |
|
|
16
|
+
| Modelo ativo | `chat.message` recebe `input.model.modelID` | Evento UserPromptSubmit NAO traz modelo. Rastreado por SessionStart (`model`, opcional) e PostModelSwitch (`to_model`); sem eles, `config.model` ou sem gate (doc: "no $CLAUDE_MODEL") |
|
|
17
|
+
| Gasto real por mensagem | DOC/tipo: `message.updated` do assistente traz `cost` e `tokens`. Nao observado: so ocorre com resposta do modelo | transcript_path existe; formato nao verificado |
|
|
18
|
+
| Prompts automaticos | n/d | DOC: UserPromptSubmit tambem dispara em tarefas agendadas, subagente em segundo plano e mensagem de outra sessao; o gate pode bloqueá-los |
|
|
19
|
+
|
|
20
|
+
## Aprovacao (explicita e vinculada)
|
|
21
|
+
Reenviar o mesmo prompt nao aprova. Para aprovar: digitar `precost approve CODIGO` (codigo aleatorio da pendencia). A aprovacao liga prompt + modelo + sessao + hash da tabela de precos + limite + teto estimado, vale por ttl (padrao 10 min), uso unico, e `precost revoke CODIGO|all` revoga. Qualquer mudanca nesses itens invalida.
|
|
22
|
+
|
|
23
|
+
## Limites do estimador
|
|
24
|
+
- Observado = caracteres. Tokens = chars/4; sistema/ferramentas = 8k de premissa. Custos sao estimativas.
|
|
25
|
+
- Sem historico (<5 sessoes): tres cenarios com premissas fixas, nao medidas. Com historico: P25/P50/P75 agregados, sem tier >200K.
|
|
26
|
+
- Tabela de precos: pagina oficial lida no corpo em 25/nov/2026 (Standard, Global). Desconhecidos explicitos: Gemini 4 sem faixa >200K na tabela; cache write nao modelado (valores so a partir de 12/jan/2027); creditos promocionais de Carbon/Argon sao "50% de volta" (preco efetivo, nao fatura); Priority/Batch/Flex nao modelados; acesso a Neon/Carbon na conta nao verificado; precos Anthropic/OpenAI nao incluidos (Claude Code precisaria deles).
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
## Atualizacao (revisao independente, 25/nov/2026)
|
|
30
|
+
- **Limite de seguranca (declarado):** a aprovacao e estado em arquivos do mesmo usuario (`~/.cache/precost`). Um agente com shell ou escrita nesse usuario pode forjar aprovacao ou ler o codigo. Nao ha autoridade fora do alcance do modelo nem prometo protecao contra autoaprovacao. O gate protege contra gasto acidental, nao contra agente adversario. O comando `precost approve` so e aceito como texto de prompt do usuario (no OpenCode ele e barrado no `chat.message`; no Claude Code, no hook, e nao chega ao modelo). A CLI local nao aprova nada; `precost last` so mostra o ultimo bloqueio.
|
|
31
|
+
- **Falha fechada** (quando `limitUsd` esta configurado): limite nao numerico/negativo, ttl invalido, config ilegivel, tabela de precos ilegivel, erro interno, entrada do hook ilegivel, modelo ativo desconhecido ou sem preco, custo so com limite inferior, arquivo de contexto nao contado (grande, fora do projeto, segredo): tudo bloqueia e pede aprovacao ou correcao. Sem `limitUsd` e so informativo e diz "SEM GATE".
|
|
32
|
+
- **OpenCode: dependencia do throw nao documentado.** Versao fixada em 1.19.6 (`PINNED_OPENCODE`, devDependency exata). Em runtime o plugin le `/global/health`; versao diferente ou nao identificada bloqueia, salvo `allowUnverifiedVersion: true`. Regressao: `npm run e2e:opencode` (servidor real, falha com exit 1 se a contagem de mensagens 0,0,0,1,1 nao bater).
|
|
33
|
+
- **Contexto observado:** arquivos (`@caminho` no Claude Code, partes `file` no OpenCode) sao lidos dentro do projeto, entram na estimativa e o hash do conteudo entra no vinculo da aprovacao. Arquivos sem leitura contam como "NAO contado" e exigem aprovacao.
|
|
34
|
+
- **Historico:** com >=5 sessoes soma-se uma vez a entrada observada da tarefa; ainda nao escala com o tamanho alem disso. Faixa alta e P75/cenario grande, nao teto.
|
|
35
|
+
- **Promocao Gemini 4 Carbon/Argon:** cobranca BRUTA (preco de lista 4/20, inferido) e beneficio condicional (50% de creditos de volta, ate 30/nov) sao mostrados separados; o gate usa o bruto.
|
|
36
|
+
- **Contexto longo:** `long_context` = `none` (pagina sem faixa), objeto (3.1 Pro, Haiku 5.5 a 100K) ou `unknown` (Gemini 4: so limite inferior, exige aprovacao).
|
|
37
|
+
- **Precos Claude** (platform.claude.com/docs/en/about-claude/pricing, lido 25/nov/2026): Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5 (faixa a 100K), Sonnet 4.6, Opus 4.5, Haiku 4.5. Nao modelados: cache write, Batch, Fast mode, residencia de dados (1,1x). Tokenizador 4.7+ gera ~30% mais tokens: chars/4 subestima.
|
|
38
|
+
- **Ledger:** dedup por id de mensagem agora persiste em disco (nao duplica gasto apos reinicio).
|
|
39
|
+
|
|
40
|
+
## Atualizacao 2 (comandos e historico)
|
|
41
|
+
- **Comandos digitados pelo usuario, sem modelo e sem gasto** (OpenCode `chat.message` e Claude Code hook): `precost estimate <texto da tarefa>` mostra a previa; `precost last` mostra o ultimo bloqueio completo; `precost approve CODIGO` / `precost revoke CODIGO|all`. Previa nunca aprova nada. Nao e um slash command nativo (`/precost` segue pendente).
|
|
42
|
+
- **Historico agregado e limiar por chamada:** o limiar de contexto longo vale por chamada. Com historico, usa-se a media de tokens por chamada (entrada+cache / turnos). Media acima do limiar = limite inferior; abaixo = so nota de que o pico por chamada e desconhecido (nao soma todos os turnos).
|
|
43
|
+
- **Preco bruto de Carbon/Argon e INFERIDO** (4/20 = preco pos-promocao; a pagina so descreve 50% de creditos de volta). Sem validacao em fonte primaria de faturamento: estimativa conservadora, nunca "cobranca exata".
|
|
44
|
+
- Limite fundamental mantido: estado em arquivos do mesmo usuario; agente com shell pode alterar. Nao e seguranca resolvida.
|
|
45
|
+
|
|
46
|
+
## Atualizacao 3 (conjunto consolidado)
|
|
47
|
+
- **Subestimativas conhecidas agora entram no custo (conservador):** Claude 4.7+ usa x1.3 nos tokens observados (nota oficial de ~30%, valor aproximado); cache write: toda entrada nova e cobrada como cache write 5min (Claude), o que pode superestimar. Resta: chars/4 e a premissa de 8k de sistema (premissas rotuladas).
|
|
48
|
+
- **Pico por chamada:** o ledger registra o maior contexto real por sessao (`peakCtx`). Historico agregado so afirma sem faixa longa com pico real registrado; media por chamada nao prova ausencia de picos; pico desconhecido = limite inferior (exige aprovacao).
|
|
49
|
+
- **Historico filtrado:** so sessoes do mesmo modelo e do mesmo projeto (diretorio) entram; sessao com varios modelos fica fora. `cache_write` agora e registrado e custeado. Semantica de `input` vs `cache` dos eventos reais nao validada (nenhuma resposta de modelo observada).
|
|
50
|
+
- **Arquivos ignorados** (segredo, grande): o conteudo nao e lido; a aprovacao e vinculada a assinatura tamanho+mtime. Mudanca que preserve tamanho e mtime nao e detectada (limite declarado).
|
|
51
|
+
- **UX:** canal verificado = terminal (`precost estimate`, `precost last`). Comandos no prompt: contrato lido (Claude Code) e erro+toast (OpenCode) sem evidencia de TUI/UI real de que o texto aparece.
|
|
52
|
+
- **Reproducao:** `npm ci && npm test` (47 testes); sem `npm ci` o teste do adaptador OpenCode falha por dependencia ausente.
|
|
53
|
+
|
|
54
|
+
## Atualizacao 4 (correcoes da revisao 8f5f7a3)
|
|
55
|
+
- Prompt so com arquivo (sem texto) passa pelo gate no OpenCode. Comandos `precost estimate|last|approve|revoke` sao interceptados SEMPRE (OpenCode e Claude Code, com ou sem `limitUsd`/config), nunca chegam ao modelo.
|
|
56
|
+
- Pico por chamada no historico = MAIOR registrado (nao quantil); o texto da base diz isso.
|
|
57
|
+
- Historico por modelo em cada linha (`history` aceita mapa `{modelo: sessoes}`); linhas comparadas nao se misturam; base mista e rotulada por linha.
|
|
58
|
+
- `precost last` escopado por sessao (arquivo por sessao); a CLI de terminal mostra o mais recente de qualquer sessao e diz isso.
|
|
59
|
+
- Hook do Claude Code: carga dos modulos por import dinamico; falha de carga com limite configurado bloqueia (antes um erro de modulo sairia nao-bloqueante).
|
|
60
|
+
- Escopo: recorte de prova de conceito local, nao produto pronto nem seguranca forte. 47 testes.
|
|
61
|
+
|
|
62
|
+
## Atualizacao 5
|
|
63
|
+
- Regressao do revisor (ledger com 3.7 ~10k e 3.8 ~400k, mesmo projeto): tool, gate com compare e preview usam o historico de cada modelo (3.8 >20x 3.7 nos tres caminhos). A CLI recusa `--history` em lista quando ha varios modelos (exige mapa por modelo). 47 testes.
|
|
64
|
+
|
|
65
|
+
## Atualizacao 6 (validacao real contra servidores falsos, 25/nov/2026)
|
|
66
|
+
Sem chamada paga e sem credencial real: Claude Code 2.1.332 e OpenCode 1.19.6 reais, instalados so no sandbox, apontados para servidores locais falsos (`scripts/mock-anthropic.mjs`, `scripts/mock-openai.mjs`). Logs em `docs/evidence/`.
|
|
67
|
+
- **Claude Code REAL (`npm run e2e:claude`)**: `UserPromptSubmit` recebe `prompt`, `session_id`, `transcript_path`, `cwd`, `permission_mode` (docs/evidence/claude-code-2.1.332-userpromptsubmit-input.json). **Nao traz modelo**, e `SessionStart` (modo -p) tambem nao. Bloqueio por `decision: block` NAO chama o modelo (contador do servidor falso 0), o texto aparece em `claude -p`; approve, reenvio permitido (1 chamada), uso unico e `precost estimate` funcionaram; o modelo passa a vir da ultima resposta do transcript e corrige um `config.model` divergente a partir da 2a mensagem. `--resume` preserva o `session_id`, entao a aprovacao vale na mesma sessao.
|
|
68
|
+
- **Nao verificado no Claude Code**: modo interativo (TUI), `PostModelSwitch` (nao ocorreu em `-p`), subagentes e tarefas agendadas.
|
|
69
|
+
- **OpenCode REAL com provedor falso (`npm run e2e:opencode-ledger`)**: evento `message.updated` real do assistente: `tokens.input` EXCLUI `cache.read`; custo = input*preco + output*preco + cache_read*preco do config do OpenCode; pico por chamada = input + cache.read = prompt_tokens. O ledger bate (inclusive modelo e projeto).
|
|
70
|
+
- **Transcripts do Claude Code**: linhas `assistant` com `message.id/model/usage` (`input_tokens` exclui cache; `cache_read_input_tokens`; `cache_creation_input_tokens`). Formato lido de uma sessao real em 2.1.332, usado para modelo ativo e historico (dedup por `message.id`, maior valor). Os valores de uso vieram do servidor falso, entao a comparacao com fatura real segue pendente.
|
|
71
|
+
- **Premissa de sistema medida em bytes**: corpo da requisicao do Claude Code = 48.919 bytes e do OpenCode = 32.576 bytes para prompts de poucos caracteres (docs/evidence/*requests.log). Convertidos por chars/4: ~12,2K e ~8,1K tokens. Padroes: 13K (Claude Code) e 8K (OpenCode). CLAUDE.md, MCPs e skills do usuario aumentam isso.
|
|
72
|
+
- 49 testes.
|
|
73
|
+
|
|
74
|
+
## Atualização 7 (rc2): modelo efetivo e TUI
|
|
75
|
+
|
|
76
|
+
- O hook do Claude Code nao traz o modelo. Cadeia: PRECOST_MODEL (COMPROVADO) > tracker > ultima resposta no transcript > `--model` do processo (/proc, Linux) (OBSERVADOS, REVISTO no rc3: nao provam o modelo do proximo prompt apos `/model`) > ANTHROPIC_MODEL, settings.json, `config.model` (DECLARADOS).
|
|
77
|
+
- Modelo nao comprovado: o gate usa o PIOR CASO entre todos os candidatos claude-* (e diz o modelo e o valor), nunca aprova silenciosamente o preco de outro modelo. A aprovacao fica presa a esse estado (muda a fonte/modelo, perde validade). Conflito entre fontes declaradas nunca e comprovado. `trustConfiguredModel: true` no config aceita um unico modelo declarado e consistente.
|
|
78
|
+
- TUI interativa REAL do Claude Code 2.1.332 testada em pty contra servidor falso (`npm run e2e:claude-tui`, captura em docs/evidence/claude-tui-pty-capture.txt): bloqueio aparece na TUI, 0 chamadas ao modelo. Nao testado: TUI do OpenCode (toast), PostModelSwitch, subagentes, macOS/Windows (a deteccao por /proc e so Linux; fora dele cai no pior caso).
|
|
79
|
+
|
|
80
|
+
## Atualização 8 (rc3)
|
|
81
|
+
- Observado nunca e comprovado sozinho. `trustConfiguredModel:true` aceita um modelo observado/declarado consistente, MAS o transcript registra `/model` (entrada `<command-name>/model</command-name>`, observada no 2.1.332 em TUI real): troca depois da ultima resposta = pior caso rotulado. Cobre instalacao parcial sem PostModelSwitch/SessionStart. Limite residual com trust: troca de modelo que nao deixa rastro no transcript (nao observada).
|
|
82
|
+
- Pior caso = maior preco do CATALOGO suportado; nao e teto universal, nem prova do modelo, nem cobre modelo desconhecido (esse fecha o gate).
|
|
83
|
+
- onFailure: exemplo agora "block". Reproduzido com Claude Code 2.1.332 real: sem onFailure ou com "continue", hook que falha/trava deixa o prompt chegar ao modelo; com "block", 0 chamadas (crash do script, node ausente, timeout). `npm run e2e:claude-failure`, com controle negativo.
|
|
84
|
+
- decide(): historico em lista unica com varios modelos e rejeitado (estimate lanca erro; gate bloqueia por config invalida); use mapa {modelo: lista}.
|
|
85
|
+
- OpenCode TUI real 1.19.6 (pty): ANTES, o plugin bloqueava tudo na TUI porque `serverUrl` ali e fantasma (http://localhost:4096 sem servidor) e a versao nao era identificada (falha fechada: "versao do OpenCode nao identificada"). DEPOIS: versao lida do proprio binario (`process.execPath --version`), previa/bloqueio aparece na TUI (caixa de erro) e no log do gate. Approve/reenvio na TUI nao testado (chamaria provedor); ciclo approve foi validado por `serve` real.
|
|
86
|
+
- OpenCode TUI com provedor FALSO local (mock/m1): ciclo completo bloqueio -> approve -> reenvio (1 chamada ao mock) -> uso unico, em TUI real (`npm run e2e:opencode-tui`).
|
|
87
|
+
- Ainda nao verificado: PostModelSwitch em instalacao propria do usuario, subagentes/agendadas, macOS/Windows, fatura real, preco bruto Carbon/Argon.
|
|
88
|
+
- PRECOST_MODEL e declaracao do operador, nao prova tecnica: nao forca o request. Nomenclatura corrigida no hook, README e fonte.
|
|
89
|
+
- Chamada auxiliar do OpenCode (geracao de titulo da sessao): observada na TUI 1.19.6 com provedor falso. NAO ocorre enquanto o prompt esta bloqueado (0 requisicoes ao provedor apos bloqueio e apos approve) e ocorre junto com a primeira mensagem aprovada (corpo ~2,4 KB, alem da chamada principal de ~32,6 KB). Portanto "0 chamadas ate aprovar" vale para a tarefa principal e, neste teste, tambem para a auxiliar; mas depois da aprovacao ha uma chamada auxiliar que a estimativa NAO inclui e que pode usar o modelo pequeno do provedor real: custo pequeno, nao medido, nao contabilizado no gate. Medido so contra provedor falso; em provedor real nao verificado.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Distribution (maintainer notes)
|
|
2
|
+
|
|
3
|
+
Status: nothing below is published yet. `package.json` keeps `"private": true` until publication is approved.
|
|
4
|
+
|
|
5
|
+
## Claude Code: own marketplace (this repository)
|
|
6
|
+
|
|
7
|
+
`.claude-plugin/marketplace.json` makes the repository itself a marketplace (`precost-marketplace`, plugin `precost`).
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
claude plugin validate . # before every release
|
|
11
|
+
claude plugin marketplace add glauberportella/opencode-precost
|
|
12
|
+
claude plugin install precost@precost-marketplace
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Works once the repository is reachable by the user (public, or private with their GitHub access).
|
|
16
|
+
This is a self-hosted marketplace. It is not the Anthropic directory and does not appear there.
|
|
17
|
+
|
|
18
|
+
## Claude Code: Anthropic directory (optional, separate)
|
|
19
|
+
|
|
20
|
+
Submit through claude.ai/directory/manage ("Plugin bundle"). Needs a GitHub repo you can push to, a connected GitHub
|
|
21
|
+
account, and a plan/role allowed to submit. The directory scans one commit, asks listing and data-handling answers,
|
|
22
|
+
and requires compliance with the Anthropic Software Directory Terms and Policy. The repository can be private while
|
|
23
|
+
validating and must be public before the listing goes live. Read the current pre-submission checklist first.
|
|
24
|
+
|
|
25
|
+
## OpenCode
|
|
26
|
+
|
|
27
|
+
- Local/shim: copy the shim into `.opencode/plugins/` (see INSTALLATION.md). Verified on OpenCode 1.19.6.
|
|
28
|
+
- npm (NOT validated yet): the package must be published first. On OpenCode 1.19.6 (checked with `opencode debug config`),
|
|
29
|
+
the config key that is honored is `plugin`; `plugins` (shown on the current opencode.ai docs page) is ignored, and
|
|
30
|
+
there is no `opencode plugin add` subcommand (only `opencode plugin <module>`, which installs and edits the config).
|
|
31
|
+
Re-test with the real published package and the exact OpenCode version before documenting an npm install command.
|
|
32
|
+
Publishing also needs removing `private`, then `npm publish` from the owner's account with 2FA.
|
|
33
|
+
- Community lists: pull request to awesome-opencode, form at opencode.im/submit.
|
|
34
|
+
- Pinned to OpenCode 1.19.6. Re-test on each OpenCode release before widening the peer range.
|
|
35
|
+
|
|
36
|
+
## Release checklist
|
|
37
|
+
|
|
38
|
+
1. `npm test`, e2e scripts, CI green on Linux, Windows and macOS (see the matrix in INSTALLATION.md).
|
|
39
|
+
2. Refresh `data/prices.json` (see PRICES.md).
|
|
40
|
+
3. Bump version in `package.json` and `.claude-plugin/plugin.json`, tag `vX.Y.Z`.
|
|
41
|
+
4. `claude plugin validate .`, `npm pack --dry-run` (check the file list), then publish.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[English](INSTALLATION.md) | **Português (Brasil)**
|
|
2
|
+
|
|
3
|
+
# Instalação e verificação (v0.3.2)
|
|
4
|
+
|
|
5
|
+
Nada aqui chama modelo pago nem publica pacote. Requisitos: Node >= 20, git, acesso ao repositório privado.
|
|
6
|
+
|
|
7
|
+
## Matriz de validacao (o que foi realmente executado)
|
|
8
|
+
|
|
9
|
+
| Verificacao (CI run #8 no 21bec84: 70 testes unitarios; run #9 no 6e57c76: 71) | Linux x64 | macOS arm64 (macos-26) | macOS Intel x64 (macos-15-intel) | Windows x64 |
|
|
10
|
+
|---|---|---|---|---|
|
|
11
|
+
| Testes unitarios, Node 22 | OK | OK | OK | OK |
|
|
12
|
+
| Testes unitarios, Node 20 | OK | OK (apos uma reexecucao) | nao rodou | OK |
|
|
13
|
+
| e2e-native: Claude Code (plugin) e OpenCode 1.19.6 reais vs servidores falsos | OK | OK (apos uma reexecucao) | OK | OK |
|
|
14
|
+
| Scripts e2e em bash (mesmos clientes) | OK | OK no 6e57c76 (run #9; nao adquirido 2x no 21bec84) | OK no 6e57c76 (run #9) | nao se aplica (bash) |
|
|
15
|
+
|
|
16
|
+
Evidencia anterior ao i18n, separada (commit f50909a, run #6): Windows unit 63/63 em Node 20 e 22 e e2e-native OK. Todos os jobs de macOS dessa execucao nao foram adquiridos.
|
|
17
|
+
Nao coberto: os clientes foram exercitados so contra servidores de modelo falsos, nunca contra um modelo real pago. A checagem da flag `--model` do processo claude usa `/proc` e roda so no Linux.
|
|
18
|
+
|
|
19
|
+
Linux nao e validacao de macOS/Windows. Caminhos de dados por plataforma (`~/.config/precost` no Linux/macOS, `%APPDATA%\precost` no Windows) estao implementados e passam nos testes unitarios e no e2e-native nas tres plataformas (ver tabela). Falta qualquer teste com modelo real. Run #9 (commit 6e57c76, so docs e CI; codigo igual ao 21bec84) passou em todos os 14 jobs (os 7 jobs unitarios com 71/71).
|
|
20
|
+
|
|
21
|
+
## Instalar por cliente
|
|
22
|
+
|
|
23
|
+
- **Claude Code (plugin):** `claude --plugin-dir /caminho/opencode-precost` para testar; depois de publicado, `/plugin marketplace add <repo>` e `/plugin install precost@precost-marketplace`. Hooks em `hooks/hooks.json` (fail-closed). Plugin ainda NAO publicado em nenhum marketplace.
|
|
24
|
+
- **Claude Code (manual):** secao 3 abaixo (settings.json).
|
|
25
|
+
- **OpenCode:** `npm i opencode-precost @opencode-ai/plugin@1.19.6` no projeto (pacote ainda nao publicado: use `npm pack` do clone) e o arquivo `.opencode/plugins/precost.js` da secao 4 importando `'opencode-precost'`. So a versao 1.19.6 e aceita; o carregamento apenas por `opencode.json` nao foi verificado.
|
|
26
|
+
- **Primeiro passo em qualquer cliente:** `precost doctor` e depois a tabela de precos: `precost prices` e `precost update-prices --from URL|ARQUIVO` (sem `--from` usa a fonte padrao: a tabela no `main` do repositorio do projeto, ver PRICES.md; so funciona depois que o repo for publico, ate la falha com HTTP 404, mantem a tabela atual e sai com 1).
|
|
27
|
+
|
|
28
|
+
## 1. Obter e testar
|
|
29
|
+
```
|
|
30
|
+
git clone git@github.com:glauberportella/opencode-precost.git && cd opencode-precost
|
|
31
|
+
git checkout v0.3.2 # ou fique no main
|
|
32
|
+
npm ci && npm test # 71 testes
|
|
33
|
+
```
|
|
34
|
+
Testes reais com software de terceiros contra servidores FALSOS locais (sem gasto, baixam versões fixas via npx): `npm run e2e:claude`, `e2e:claude-tui`, `e2e:claude-failure`, `e2e:opencode`, `e2e:opencode-ledger`, `e2e:opencode-tui`.
|
|
35
|
+
|
|
36
|
+
## 2. Configuração (`~/.config/precost/config.json`)
|
|
37
|
+
```
|
|
38
|
+
{"model":"claude-sonnet-5.5","limitUsd":5}
|
|
39
|
+
```
|
|
40
|
+
Sem `limitUsd`, o hook só informa e nunca bloqueia. `trustConfiguredModel:true` é decisão sua de aceitar um modelo observado/declarado como efetivo (ver README.pt-BR.md, item 3).
|
|
41
|
+
|
|
42
|
+
## 3. Claude Code (testado 2.1.332)
|
|
43
|
+
Copie `adapters/claude-code/settings.example.json` para `~/.claude/settings.json` (ou `.claude/settings.json` do projeto) e troque `/CAMINHO/opencode-precost` pelo caminho do clone. Mantenha `"onFailure":"block"` no UserPromptSubmit: sem ele, crash, timeout ou node ausente deixam o prompt chegar ao modelo.
|
|
44
|
+
|
|
45
|
+
## 4. OpenCode (testado 1.19.6; outra versão bloqueia)
|
|
46
|
+
Em `.opencode/plugins/precost.js` do projeto:
|
|
47
|
+
```
|
|
48
|
+
import { PrecostPlugin } from '/CAMINHO/opencode-precost/adapters/opencode/index.js';
|
|
49
|
+
export const P = async (input) => PrecostPlugin(input, { limitUsd: 5 });
|
|
50
|
+
```
|
|
51
|
+
Instale `@opencode-ai/plugin@1.19.6` onde o OpenCode resolver o plugin se ele pedir (ver `package.json`).
|
|
52
|
+
|
|
53
|
+
## 5. Verificar a instalação (sem chamada paga)
|
|
54
|
+
```
|
|
55
|
+
node bin/precost.js doctor [--project DIR] [--claude-settings ARQUIVO]
|
|
56
|
+
```
|
|
57
|
+
O `doctor` confere config, preços, hook/plugin nos arquivos, `onFailure`, rastreadores e executa o hook localmente (estado temporário). Sai com código 1 em qualquer FALHA.
|
|
58
|
+
**Limite:** o `doctor` não prova que o cliente carregou o hook/plugin na sua sessão. O fail-closed só vale com hook/plugin carregado; se não carregar, prompts grandes passam sem prévia nem gate. Procedimento seguro em sessão real: digite `precost last` primeiro. Com o hook carregado, a resposta vem do precost, sem modelo. Se o modelo responder, o hook NÃO está carregado (custo: um prompt curto).
|
|
59
|
+
|
|
60
|
+
## 6. Uso
|
|
61
|
+
`precost estimate <tarefa>`, `precost last`, `precost approve CODIGO`, `precost revoke CODIGO|all` digitados no prompt (não chegam ao modelo). Terminal: `node bin/precost.js estimate "..." --model ...`.
|
|
62
|
+
|
|
63
|
+
## Escopo suportado e limites (resumo; detalhes em CAPACIDADES.md)
|
|
64
|
+
- Estimativa, não custo; faixa alta não é teto; o gate age antes do prompt e não limita gasto durante a tarefa.
|
|
65
|
+
- OpenCode não tem prévia automática antes do modelo; o gate é de ferramenta, não teto de gasto do LLM. Depois da aprovação há uma chamada auxiliar (título) fora da estimativa.
|
|
66
|
+
- Aprovação é arquivo local do mesmo usuário: protege contra gasto acidental, não contra agente com shell.
|
|
67
|
+
- Pior caso de modelo = maior preço do catálogo suportado, rótulo, não garantia.
|
|
68
|
+
- Não verificado: fatura real, PostModelSwitch na sua instalação, subagentes/agendadas, preço bruto Carbon/Argon (inferido).
|
|
69
|
+
|
|
70
|
+
## Estado da instalacao no OpenCode (verificado em Linux, OpenCode 1.19.6)
|
|
71
|
+
|
|
72
|
+
- Verificado: `npm i opencode-precost @opencode-ai/plugin` + `.opencode/plugins/precost.js` importando `'opencode-precost'` carrega o plugin e bloqueia a mensagem (teste com provedor inexistente).
|
|
73
|
+
- NAO verificado: carregar so por `opencode.json` (chave `plugin` com o nome do pacote). Nos testes o plugin nao foi carregado assim. A chave `plugins` e ignorada pelo 1.19.6. Use o shim acima.
|
|
74
|
+
- O pacote ainda nao esta publicado no npm; o teste usou o tarball de `npm pack`.
|
|
75
|
+
|
|
76
|
+
## Falha do hook no plugin Claude Code (verificado em Linux)
|
|
77
|
+
|
|
78
|
+
`npm run e2e:claude-plugin-failure` (Claude Code 2.1.332 real, `--plugin-dir`, servidor falso, sem gasto): crash do script, `node` ausente e travamento (timeout) do hook NAO deixam o prompt chegar ao modelo (`onFailure: block`). Controle negativo: com `onFailure: continue` o prompt passa. Nao testado em macOS/Windows.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
**English** | [Português (Brasil)](INSTALACAO.pt-BR.md)
|
|
2
|
+
|
|
3
|
+
# Installation and verification (v0.3.2)
|
|
4
|
+
|
|
5
|
+
Nothing here calls a paid model or publishes a package. Requirements: Node >= 20, git, access to the repository.
|
|
6
|
+
|
|
7
|
+
## Validation matrix
|
|
8
|
+
|
|
9
|
+
What was actually executed (GitHub-hosted runners and local runs). Linux is not validation of macOS or Windows.
|
|
10
|
+
|
|
11
|
+
Status of 0.3.2 (the packaged install, with its npm dependencies): in CircleCI (Free plan) the packed tarball is installed clean and the native E2E runs from the installed copy on Linux x64, macOS arm64 (m4pro, Xcode 26.6 image, Node 22.12.0) and Windows x64 (Node from Chocolatey LTS). It uses real Claude Code 2.1.332 and opencode-ai 1.19.6 against fake servers, no paid calls. macOS Intel is NOT covered (CircleCI no longer offers it). The table below is for 0.3.0 and does not cover 0.3.2.
|
|
12
|
+
|
|
13
|
+
| Check (CI run #8 at 21bec84: 70 unit tests; run #9 at 6e57c76: 71) | Linux x64 | macOS arm64 (macos-26) | macOS Intel x64 (macos-15-intel) | Windows x64 |
|
|
14
|
+
|---|---|---|---|---|
|
|
15
|
+
| Unit tests, Node 22 | OK | OK | OK | OK |
|
|
16
|
+
| Unit tests, Node 20 | OK | OK (after one rerun) | not run | OK |
|
|
17
|
+
| e2e-native: real Claude Code plugin and real OpenCode 1.19.6 vs fake servers | OK | OK (after one rerun) | OK | OK |
|
|
18
|
+
| bash e2e scripts (same clients) | OK | OK at 6e57c76 (run #9; not acquired twice at 21bec84) | OK at 6e57c76 (run #9) | not applicable (bash) |
|
|
19
|
+
|
|
20
|
+
Pre-i18n evidence, kept separate (commit f50909a, run #6): Windows unit 63/63 on Node 20 and 22 and Windows e2e-native OK. All macOS jobs in that run were not acquired.
|
|
21
|
+
Not covered: Claude Code and OpenCode have been exercised against fake model servers only, never against a paid real model. The check that reads the `--model` flag of the claude process uses `/proc` and runs on Linux only.
|
|
22
|
+
|
|
23
|
+
This table is updated from CI results only. Run #9 (commit 6e57c76, docs and CI only, code unchanged from 21bec84) was green in all 14 jobs (all 7 unit jobs 71/71), including the bash e2e on macOS arm64 and Intel.
|
|
24
|
+
|
|
25
|
+
Official client support on Windows (docs read 2026-11-25): Claude Code runs natively on Windows 10 1809+ / Server 2019+ (Git for Windows recommended; without it Claude Code uses PowerShell) - https://code.claude.com/docs/en/setup . OpenCode can run directly on Windows but its documentation recommends WSL - https://opencode.ai/docs/windows-wsl/ .
|
|
26
|
+
|
|
27
|
+
## 1. Get it and test it
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
git clone git@github.com:glauberportella/opencode-precost.git && cd opencode-precost
|
|
31
|
+
git checkout v0.3.2 # or stay on main
|
|
32
|
+
npm ci && npm test # 71 tests
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
End-to-end tests against real third-party clients and FAKE local servers (no spend; they download pinned versions through npx): `npm run e2e:native` (all systems), or the bash variants `e2e:claude-plugin`, `e2e:claude-plugin-failure`, `e2e:claude`, `e2e:claude-tui`, `e2e:claude-failure`, `e2e:opencode`, `e2e:opencode-ledger`, `e2e:opencode-tui` (Linux/macOS).
|
|
36
|
+
|
|
37
|
+
## 2. Configuration (`~/.config/precost/config.json`, Windows `%APPDATA%\precost\config.json`)
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
{"model":"claude-sonnet-5.5","limitUsd":5}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Without `limitUsd` the hook only informs and never blocks. `trustConfiguredModel: true` is your decision to accept an observed or declared model as the effective one (see the README, "Limits").
|
|
44
|
+
|
|
45
|
+
## 3. Claude Code (tested with 2.1.332)
|
|
46
|
+
|
|
47
|
+
- **Plugin:** `claude --plugin-dir /path/to/opencode-precost` to try it. After the repository is public: `/plugin marketplace add <repo>` and `/plugin install precost@precost-marketplace`. Hooks are in `hooks/hooks.json` with `onFailure: "block"`. Not published to any marketplace yet.
|
|
48
|
+
- **Manual:** copy `adapters/claude-code/settings.example.json` into `~/.claude/settings.json` (or the project's `.claude/settings.json`) and replace `/CAMINHO/opencode-precost` with the clone path. Keep `"onFailure": "block"` on `UserPromptSubmit`; without it a crash, timeout or missing node lets the prompt reach the model.
|
|
49
|
+
|
|
50
|
+
## 4. OpenCode (tested with 1.19.6; other versions block)
|
|
51
|
+
|
|
52
|
+
In the project: `npm i opencode-precost @opencode-ai/plugin@1.19.6` (not on npm yet: run `npm pack` in a clone and install the tarball), then create `.opencode/plugins/precost.js`:
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
import { PrecostPlugin } from 'opencode-precost';
|
|
56
|
+
export const P = async (input) => PrecostPlugin(input, { limitUsd: 5 });
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Verified on Linux with OpenCode 1.19.6: this shim loads the plugin and blocks the message. Not verified: loading it only through `opencode.json` (the `plugin` key did not load it in tests; the `plugins` key is ignored by 1.19.6). Use the shim.
|
|
60
|
+
|
|
61
|
+
## 5. Check the install (no paid call)
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
node bin/precost.js doctor [--project DIR] [--claude-settings FILE]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`doctor` checks config, prices, hook/plugin files, `onFailure` and trackers, and runs the hook locally with temporary state. It exits 1 on any FAIL.
|
|
68
|
+
**Limit:** `doctor` cannot prove that the client loaded the hook or plugin in your session. The fail-closed behavior only holds while it is loaded. In a real session type `precost last` first: with the hook loaded, precost answers without a model. If a model answers, the hook is NOT loaded (cost: one short prompt).
|
|
69
|
+
|
|
70
|
+
## 6. Prices
|
|
71
|
+
|
|
72
|
+
`precost prices` shows the table in use. `precost update-prices --from FILE_OR_URL` validates and prints a diff; add `--yes` to write it. Without `--from` it uses the default source, the table on `main` of the project repository (see PRICES.md). That works only once the repository is public; until then it fails with HTTP 404, keeps the current table and exits 1. Use `--from` or `PRECOST_PRICES_SOURCE` for another source.
|
|
73
|
+
|
|
74
|
+
## 7. Use
|
|
75
|
+
|
|
76
|
+
`precost estimate <task>`, `precost last`, `precost approve CODE`, `precost revoke CODE|all`, typed in the prompt (they do not reach the model). In a terminal: `node bin/precost.js estimate "..." --model ...`.
|
|
77
|
+
|
|
78
|
+
## Supported scope and limits (summary; details in CAPABILITIES.md)
|
|
79
|
+
|
|
80
|
+
- An estimate, not a cost. The high end is not a cap. The gate acts before the prompt and does not limit spend during the task.
|
|
81
|
+
- OpenCode has no automatic preview before the model. After approval there is one auxiliary call (session title) that the estimate does not include (observed only against a fake provider).
|
|
82
|
+
- Approval is a local file of the same user: it protects against accidental spend, not against an agent with a shell.
|
|
83
|
+
- Worst-case model = highest price in the supported catalog. It is a label, not a guarantee.
|
|
84
|
+
- Not verified: a real invoice, `PostModelSwitch` in your install, subagents and scheduled runs, raw Carbon/Argon price (inferred).
|
|
85
|
+
|
|
86
|
+
> Model detection from the `--model` flag of the claude process reads `/proc`, so it works on Linux only. On macOS and Windows that source is simply absent: the gate then relies on the other sources (tracker, transcript, declared model, `PRECOST_MODEL`) and otherwise uses the worst case, which is the safe direction.
|
|
87
|
+
|
|
88
|
+
## Hook failure in the Claude Code plugin (Linux)
|
|
89
|
+
|
|
90
|
+
`npm run e2e:claude-plugin-failure` (real Claude Code 2.1.332, `--plugin-dir`, fake server, no spend): a script crash, a missing `node` and a hook timeout do NOT let the prompt reach the model (`onFailure: block`). Negative control: with `onFailure: continue` the prompt goes through.
|
|
91
|
+
|
|
92
|
+
Note on the e2e scripts: the Claude mock server listens on the fixed port 4590 on 127.0.0.1. After an aborted run, stop the leftover mock process before running again, or the next run can fail for that reason.
|