pantheon-opencode 1.6.0 → 1.6.1

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.
@@ -14,8 +14,27 @@ const TABLE = {
14
14
  en: {
15
15
  installing: 'Installing...',
16
16
  dryRun: 'DRY RUN',
17
- canceled: 'Installation canceled — nothing was broken; run init again anytime.',
18
- canceledShort: 'Installation canceled.',
17
+ // Every termination that applies nothing names WHERE it stopped and WHAT
18
+ // the consequence is. `cancelPoints` are stable machine keys: the same key
19
+ // goes into the on-disk run record, so a re-run can report the point
20
+ // without parsing prose.
21
+ cancelPoints: {
22
+ components: 'component selection',
23
+ target: 'install location',
24
+ confirmation: 'pre-install confirmation',
25
+ review: 'review prompt',
26
+ interrupt: 'interrupt (Ctrl-C)',
27
+ },
28
+ // "no configuration was changed", not "no files were written": a cancel
29
+ // does write `.pantheon/last-run.json` (that is the point of #262), so the
30
+ // stronger claim would be false.
31
+ canceledAt: (point) =>
32
+ `Installation canceled at ${point} — nothing was applied; no configuration was changed.`,
33
+ declinedAt: (point) =>
34
+ `Installation declined at ${point} — nothing was applied; no configuration was changed; ` +
35
+ 're-run init to review the plan again.',
36
+ previousRun: (summary) => `Previous run recorded on disk: ${summary}`,
37
+ runRecordFailed: (msg) => `Could not write the run record: ${msg}`,
19
38
  installFailed: (msg) => `Installation failed: ${msg}`,
20
39
  failHintNoMcp:
21
40
  ' Run with --no-mcp to skip Python dependencies:\n npx pantheon-opencode init --no-mcp',
@@ -65,7 +84,6 @@ const TABLE = {
65
84
  `the server's tools remain available and no permission prompt is shown. ` +
66
85
  `Use "deny" with action "${server}_*" in "permissions", or disable the server in the host MCP config.`,
67
86
  v2Migrating: 'Migrating config to V2 native format...',
68
- nothingApplied: 'Nothing applied.',
69
87
  planOnlyNoYes: 'Plan only — re-run with --yes to apply.',
70
88
  driftHeader: 'State changed since preview — aborting before any write:',
71
89
  driftAbort: 'No files were written. Re-run to re-review.',
@@ -90,8 +108,20 @@ const TABLE = {
90
108
  pt: {
91
109
  installing: 'Instalando...',
92
110
  dryRun: 'SIMULAÇÃO',
93
- canceled: 'Instalação cancelada — nada foi quebrado; rode init de novo quando quiser.',
94
- canceledShort: 'Instalação cancelada.',
111
+ cancelPoints: {
112
+ components: 'seleção de componentes',
113
+ target: 'local da instalação',
114
+ confirmation: 'confirmação antes de instalar',
115
+ review: 'prompt de revisão',
116
+ interrupt: 'interrupção (Ctrl-C)',
117
+ },
118
+ canceledAt: (point) =>
119
+ `Instalação cancelada em ${point} — nada foi aplicado; nenhuma configuração foi alterada.`,
120
+ declinedAt: (point) =>
121
+ `Instalação recusada em ${point} — nada foi aplicado; nenhuma configuração foi alterada; ` +
122
+ 'rode init de novo para revisar o plano.',
123
+ previousRun: (summary) => `Execução anterior registrada em disco: ${summary}`,
124
+ runRecordFailed: (msg) => `Não foi possível gravar o registro da execução: ${msg}`,
95
125
  installFailed: (msg) => `Instalação falhou: ${msg}`,
96
126
  failHintNoMcp:
97
127
  ' Rode com --no-mcp para pular dependências Python:\n npx pantheon-opencode init --no-mcp',
@@ -141,7 +171,6 @@ const TABLE = {
141
171
  `as tools do servidor continuam disponíveis e nenhum prompt de permissão é exibido. ` +
142
172
  `Use "deny" com a action "${server}_*" em "permissions", ou desative o servidor na config de MCP do host.`,
143
173
  v2Migrating: 'Migrando config para o formato nativo V2...',
144
- nothingApplied: 'Nada foi aplicado.',
145
174
  planOnlyNoYes: 'Apenas o plano — rode de novo com --yes para aplicar.',
146
175
  driftHeader: 'O estado mudou desde o preview — abortando antes de qualquer escrita:',
147
176
  driftAbort: 'Nenhum arquivo foi escrito. Rode de novo para revisar.',
@@ -0,0 +1,205 @@
1
+ /**
2
+ * v2-capabilities.mjs — what the OpenCode V2 plugin surface ACTUALLY is.
3
+ *
4
+ * Two reporting defects this module exists to prevent, both of them statements
5
+ * that were narrower than the truth:
6
+ *
7
+ * 1. The installer printed `listV2UnsupportedFeatures()` under the heading
8
+ * "Unsupported features", which reads like the complete list of what V2
9
+ * does. That list is a SEED: the live set is this seed PLUS markers the
10
+ * plugin appends at runtime when a host API turns out to be missing
11
+ * (`tool-transform`, `event-stream`, …), which cannot be known at install
12
+ * time. So the printed list must say what it is.
13
+ * 2. "Reduced surface" alone is misleading in the other direction: V2 is not
14
+ * a stub. It registers session `context`/`prompt`/`compaction` hooks, tool
15
+ * `execute.before`/`execute.after` hooks, a permission `evaluate` hook,
16
+ * `tool`/`agent`/`command`/`reference` transforms and five session events.
17
+ * A user deciding between generations is entitled to both halves.
18
+ *
19
+ * The registered surface below is derived from `src/plugin-v2.ts` (the
20
+ * registration sites, not the module header: the header still claims the
21
+ * caller/target matrix is enforced, while the enforcement guard's own docstring
22
+ * records that omitting the hierarchy wiring skips that branch — the gap is
23
+ * stated here as a gap).
24
+ *
25
+ * The seed itself is IMPORTED, never copied: an installer that restated these
26
+ * strings could drift from `src/pantheon/v2-unsupported.mjs`, and a test pins
27
+ * the two together.
28
+ *
29
+ * @module v2-capabilities
30
+ */
31
+
32
+ import { listV2UnsupportedFeatures } from '../../src/pantheon/v2-unsupported.mjs'
33
+
34
+ /** Tools registered unconditionally through `ctx.tool.transform`. */
35
+ export const V2_REGISTERED_TOOLS = Object.freeze([
36
+ 'hashline_edit',
37
+ 'pantheon_cost',
38
+ 'pantheon_model',
39
+ ])
40
+
41
+ /** Tools registered only when the host exposes the API they need. */
42
+ export const V2_HOST_DEPENDENT_TOOLS = Object.freeze(['vision_describe', 'pantheon_bounded_read'])
43
+
44
+ /** Session hooks V2 registers. */
45
+ export const V2_SESSION_HOOKS = Object.freeze(['context', 'prompt', 'compaction'])
46
+
47
+ /** Tool hooks V2 registers. */
48
+ export const V2_TOOL_HOOKS = Object.freeze(['execute.before', 'execute.after'])
49
+
50
+ /** Permission hooks V2 registers. */
51
+ export const V2_PERMISSION_HOOKS = Object.freeze(['evaluate'])
52
+
53
+ /** Transform domains V2 registers. */
54
+ export const V2_TRANSFORMS = Object.freeze(['tool', 'agent', 'command', 'reference'])
55
+
56
+ /** Host events V2 subscribes to. */
57
+ export const V2_EVENTS = Object.freeze([
58
+ 'session.created',
59
+ 'session.idle',
60
+ 'session.deleted',
61
+ 'session.error',
62
+ 'session.compacted',
63
+ ])
64
+
65
+ /** Scope line that keeps the seed from reading as the complete list. */
66
+ export const V2_NOT_REGISTERED_SCOPE =
67
+ 'statically known seed; the live plugin adds further markers at runtime when a host API is missing'
68
+
69
+ /**
70
+ * Machine-readable capability description for the V2 generation.
71
+ *
72
+ * JSON-safe by construction: `--json` carries this object, so the same facts
73
+ * are available to a machine as to a reader.
74
+ *
75
+ * @returns {{
76
+ * generation: 'v2',
77
+ * registered: {
78
+ * tools: string[],
79
+ * host_dependent_tools: string[],
80
+ * session_hooks: string[],
81
+ * tool_hooks: string[],
82
+ * permission_hooks: string[],
83
+ * transforms: string[],
84
+ * events: string[],
85
+ * },
86
+ * not_registered: string[],
87
+ * not_registered_scope: string,
88
+ * }}
89
+ */
90
+ export function v2Capabilities() {
91
+ return {
92
+ generation: 'v2',
93
+ registered: {
94
+ tools: [...V2_REGISTERED_TOOLS],
95
+ host_dependent_tools: [...V2_HOST_DEPENDENT_TOOLS],
96
+ session_hooks: [...V2_SESSION_HOOKS],
97
+ tool_hooks: [...V2_TOOL_HOOKS],
98
+ permission_hooks: [...V2_PERMISSION_HOOKS],
99
+ transforms: [...V2_TRANSFORMS],
100
+ events: [...V2_EVENTS],
101
+ },
102
+ not_registered: listV2UnsupportedFeatures(),
103
+ not_registered_scope: V2_NOT_REGISTERED_SCOPE,
104
+ }
105
+ }
106
+
107
+ /**
108
+ * The human-readable capability notice.
109
+ *
110
+ * Deliberately multi-line: one wrapped paragraph of eleven facts is unreadable
111
+ * on a 60-column terminal. `notice()` prefixes only the first line, so the
112
+ * continuation lines are indented to align under the marker.
113
+ *
114
+ * @param {ReturnType<typeof v2Capabilities>} [capabilities]
115
+ * @returns {string}
116
+ */
117
+ export function formatV2CapabilityNotice(capabilities = v2Capabilities()) {
118
+ const { registered, not_registered, not_registered_scope } = capabilities
119
+ const indent = ' '.repeat(7) // aligns under the `[INFO] ` prefix notice() adds
120
+ return [
121
+ 'V2 plugin generation — what this install registers:',
122
+ `${indent}tools: ${registered.tools.join(', ')} (plus ${registered.host_dependent_tools.join(', ')} when the host exposes them)`,
123
+ `${indent}hooks: session ${registered.session_hooks.join('/')}; tool ${registered.tool_hooks.join('/')}; permission ${registered.permission_hooks.join('/')}`,
124
+ `${indent}transforms: ${registered.transforms.join(', ')}; events: ${registered.events.join(', ')}`,
125
+ `${indent}not registered (${not_registered_scope}): ${not_registered.join(', ')}`,
126
+ ].join('\n')
127
+ }
128
+
129
+ /**
130
+ * Whether a `plugins` list registers the Pantheon V2 entry.
131
+ *
132
+ * Matched on the `plugin-v2` marker so every real spelling counts: the
133
+ * canonical directory, an absolute path to it, and the package export.
134
+ *
135
+ * @param {unknown} ref
136
+ * @returns {boolean}
137
+ */
138
+ export function isPantheonV2Reference(ref) {
139
+ const candidate =
140
+ typeof ref === 'string'
141
+ ? ref
142
+ : ref && typeof ref === 'object'
143
+ ? (ref.package ?? ref.path ?? ref.source ?? ref.id ?? ref.name)
144
+ : undefined
145
+ return typeof candidate === 'string' && candidate.includes('plugin-v2')
146
+ }
147
+
148
+ /**
149
+ * Whether the installed Pantheon V2 entry can receive plugin `options`.
150
+ *
151
+ * The host hands a plugin its `options` only from the OBJECT form
152
+ * (`{ package, options }`); a bare string entry leaves `ctx.options` empty, and
153
+ * `context_pruner` / `memory_injection` read exactly that object. A fresh
154
+ * install that emitted a bare string therefore had no reachable opt-in switch
155
+ * at all — this is the check that reports it after install.
156
+ *
157
+ * @param {unknown} plugins the `plugins` array from the config
158
+ * @returns {{registered: boolean, reachable: boolean, form: 'object'|'string'|'absent', detail: string}}
159
+ */
160
+ export function describePluginOptionsReachability(plugins) {
161
+ const list = Array.isArray(plugins) ? plugins : []
162
+ const entries = list.filter((ref) => isPantheonV2Reference(ref))
163
+ if (entries.length === 0) {
164
+ return {
165
+ registered: false,
166
+ reachable: false,
167
+ form: 'absent',
168
+ detail: 'no Pantheon V2 entry is registered, so plugin options are not read at all',
169
+ }
170
+ }
171
+ const forms = entries.map((entry) => {
172
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return 'string'
173
+ const options = entry.options
174
+ return typeof options === 'object' && options !== null && !Array.isArray(options)
175
+ ? 'object-with-options'
176
+ : 'object-without-options'
177
+ })
178
+ const reachable = forms.includes('object-with-options')
179
+ if (reachable) {
180
+ const extra = forms.filter((form) => form !== 'object-with-options')
181
+ return {
182
+ registered: true,
183
+ reachable: true,
184
+ form: 'object',
185
+ detail:
186
+ 'at least one Pantheon V2 entry carries an "options" object, so context_pruner and ' +
187
+ 'memory_injection can be configured there' +
188
+ (extra.length === 0
189
+ ? ''
190
+ : `; ${extra.length} other Pantheon entr${extra.length === 1 ? 'y' : 'ies'} in the same list cannot carry options`),
191
+ }
192
+ }
193
+ const stringOnly = forms.every((form) => form === 'string')
194
+ return {
195
+ registered: true,
196
+ reachable: false,
197
+ form: stringOnly ? 'string' : 'object',
198
+ detail: stringOnly
199
+ ? 'the Pantheon V2 entry is a bare string, so the host passes no options and ' +
200
+ 'context_pruner/memory_injection cannot be enabled; the object form ' +
201
+ '{"package": …, "options": {…}} makes them reachable'
202
+ : 'the Pantheon V2 entry has no "options" object, so the host passes an empty ' +
203
+ 'options bag and context_pruner/memory_injection stay at their defaults',
204
+ }
205
+ }
@@ -71,7 +71,6 @@ const UNSUPPORTED_HOSTS = new Set(KNOWN_BROKEN_HOSTS)
71
71
  * needs to exercise a different host.
72
72
  */
73
73
  const DEFAULT_MATRIX = [
74
- { host: '1.19.4', line: '1.19.x', kind: 'v1-permission' },
75
74
  { host: '2.0.29', line: '2.x', kind: 'sandbox-v2' },
76
75
  { host: '2.0.30', line: '2.x', kind: 'sandbox-v2' },
77
76
  { host: '2.1.0', line: '2.x', kind: 'sandbox-v2' },
@@ -467,8 +466,14 @@ function installGate(options) {
467
466
  }
468
467
 
469
468
  const binary = join(root, 'home', '.npm-global', 'bin', 'opencode')
469
+ const packageRoot = join(root, 'home', '.npm-global', 'lib', 'node_modules', 'pantheon-opencode')
470
470
  const canary = run('tool-canary', 'npm', ['run', 'test:tool-canary'], {
471
- env: { PANTHEON_TOOL_CANARY_BIN: binary },
471
+ env: {
472
+ PANTHEON_TOOL_CANARY_BIN: binary,
473
+ PANTHEON_TOOL_CANARY_PACKAGE_ROOT: packageRoot,
474
+ PANTHEON_TOOL_CANARY_EXPECT_HOST: host,
475
+ PANTHEON_TOOL_CANARY_EXPECT_PACKAGE_VERSION: options.version,
476
+ },
472
477
  })
473
478
  // The canary itself skips when no binary is found. In release context that
474
479
  // skip is not a PASS, so a skip marker fails the gate.
@@ -4,7 +4,7 @@
4
4
  # Memory search is FTS5 (SQLite stdlib): sqlite-vec and fastembed were removed
5
5
  # with the vector pipeline — the server no longer imports either.
6
6
  mcp==2.2.0
7
- fastmcp==4.0.10
7
+ fastmcp==4.1.2
8
8
  pydantic==2.12.5
9
9
  pydantic-settings==2.14.2
10
10
  pyyaml==6.0.3
@@ -1,5 +1,5 @@
1
1
  mcp==2.2.0
2
- fastmcp==4.0.10
2
+ fastmcp==4.1.2
3
3
  pydantic==2.12.5
4
4
  pydantic-settings==2.14.2
5
5
  httpx==0.28.1
@@ -63,8 +63,18 @@ export interface CostRow {
63
63
  tokensInput: number
64
64
  tokensOutput: number
65
65
  tokensTotal: number
66
- /** USD for this row; absent when any contributing model is unpriced. */
66
+ /**
67
+ * USD for this row: the sum of every contributing model's own priced cost.
68
+ * Absent only when NO contributing model could be priced — a row that mixes
69
+ * priced and unpriced models keeps its numeric part.
70
+ */
67
71
  costUsd?: number
72
+ /**
73
+ * Number of contributing model groups the catalog could not price. Present
74
+ * only alongside `costUsd`, so the reader can tell a partially priced row
75
+ * (money shown, some tokens unpriced) from a fully priced one.
76
+ */
77
+ unpricedModels?: number
68
78
  }
69
79
 
70
80
  /** One aggregated row per (agent, phase, provider, model). */
@@ -92,7 +102,10 @@ export interface CostSessionRow {
92
102
  tokensCacheRead: number
93
103
  tokensCacheWrite: number
94
104
  tokensTotal: number
105
+ /** Sum of the priced model rows in this session; absent when none priced. */
95
106
  costUsd?: number
107
+ /** Unpriced model rows folded into this session; present with `costUsd`. */
108
+ unpricedModels?: number
96
109
  unpricedReason?: UnpricedReason
97
110
  }
98
111
 
@@ -566,8 +579,12 @@ interface SessionAccumulator {
566
579
  tokensOutput: number
567
580
  tokensCacheRead: number
568
581
  tokensCacheWrite: number
569
- usd: number | undefined
570
- unpriced: boolean
582
+ /** Priced dollars accumulated; meaningful only when `priced` > 0. */
583
+ usd: number
584
+ /** Model rows that produced a price. */
585
+ priced: number
586
+ /** Model rows with no usable catalog price. */
587
+ unpricedModels: number
571
588
  reason: UnpricedReason | undefined
572
589
  }
573
590
 
@@ -729,7 +746,8 @@ function queryWithSqlite(
729
746
  tokensCacheRead: 0,
730
747
  tokensCacheWrite: 0,
731
748
  usd: 0,
732
- unpriced: false,
749
+ priced: 0,
750
+ unpricedModels: 0,
733
751
  reason: undefined,
734
752
  }
735
753
  sessionAcc.agents.add(agent)
@@ -737,24 +755,26 @@ function queryWithSqlite(
737
755
  sessionAcc.tokensOutput += tokens.output
738
756
  sessionAcc.tokensCacheRead += tokens.cacheRead
739
757
  sessionAcc.tokensCacheWrite += tokens.cacheWrite
740
- if ('usd' in priced && sessionAcc.usd !== undefined) {
758
+ if ('usd' in priced) {
741
759
  sessionAcc.usd += priced.usd
760
+ sessionAcc.priced += 1
742
761
  } else {
743
- sessionAcc.unpriced = true
744
- sessionAcc.usd = undefined
745
- sessionAcc.reason = sessionAcc.reason ?? ('reason' in priced ? priced.reason : undefined)
762
+ sessionAcc.unpricedModels += 1
763
+ sessionAcc.reason = sessionAcc.reason ?? priced.reason
746
764
  }
747
765
  sessions.set(sessionId, sessionAcc)
748
766
  }
749
767
  }
750
768
 
751
769
  // The by-agent table is derived from the model groups, so every table in
752
- // the report is backed by exactly one set of token sums. `costUsd` is the
753
- // only added field, and only when every contributing model was priced, so
754
- // the historical row shape keeps its old keys.
770
+ // the report is backed by exactly one set of token sums. Cost is attributed
771
+ // per model and summed here: a bucket that spans several models is a sum of
772
+ // its priced models, never `—`, because an ambiguous bucket is not the same
773
+ // thing as an unknown price. `unpricedModels` records how many contributors
774
+ // had no catalog price, so `(partial)` keeps a single, honest meaning.
755
775
  const byAgentPhase = new Map<
756
776
  string,
757
- { row: CostRow; usd: number | undefined; unpriced: boolean }
777
+ { row: CostRow; usd: number; priced: number; unpricedModels: number }
758
778
  >()
759
779
  for (const acc of models.values()) {
760
780
  const key = `${acc.agent}\u0000${acc.phase}`
@@ -767,26 +787,29 @@ function queryWithSqlite(
767
787
  tokensTotal: 0,
768
788
  },
769
789
  usd: 0,
770
- unpriced: false,
790
+ priced: 0,
791
+ unpricedModels: 0,
771
792
  }
772
793
  entry.row.tokensInput += acc.tokensInput
773
794
  entry.row.tokensOutput += acc.tokensOutput
774
795
  entry.row.tokensTotal += acc.tokensInput + acc.tokensOutput
775
- if (acc.unpriced || entry.usd === undefined) {
776
- entry.unpriced = true
777
- entry.usd = undefined
778
- } else if (acc.usd !== undefined) {
796
+ if (acc.usd === undefined) {
797
+ entry.unpricedModels += 1
798
+ } else {
779
799
  entry.usd += acc.usd
800
+ entry.priced += 1
780
801
  }
781
802
  byAgentPhase.set(key, entry)
782
803
  }
783
804
 
784
805
  const rows: CostRow[] = [...byAgentPhase.values()]
785
- .map((entry) =>
786
- entry.unpriced || entry.usd === undefined
787
- ? { ...entry.row }
788
- : { ...entry.row, costUsd: entry.usd },
789
- )
806
+ .map(({ row, usd, priced, unpricedModels }) => ({
807
+ ...row,
808
+ // Absent cost means "nothing in this row could be priced"; a numeric
809
+ // cost with `unpricedModels` means "this row is partly priced".
810
+ ...(priced === 0 ? {} : { costUsd: usd }),
811
+ ...(priced === 0 || unpricedModels === 0 ? {} : { unpricedModels }),
812
+ }))
790
813
  .sort((a, b) => b.tokensTotal - a.tokensTotal)
791
814
 
792
815
  const byModel: CostModelRow[] = [...models.values()]
@@ -820,7 +843,10 @@ function queryWithSqlite(
820
843
  tokensCacheRead: acc.tokensCacheRead,
821
844
  tokensCacheWrite: acc.tokensCacheWrite,
822
845
  tokensTotal: acc.tokensInput + acc.tokensOutput,
823
- ...(acc.usd === undefined ? {} : { costUsd: acc.usd }),
846
+ ...(acc.priced === 0 ? {} : { costUsd: acc.usd }),
847
+ ...(acc.priced === 0 || acc.unpricedModels === 0
848
+ ? {}
849
+ : { unpricedModels: acc.unpricedModels }),
824
850
  ...(acc.reason === undefined ? {} : { unpricedReason: acc.reason }),
825
851
  }
826
852
  })
@@ -935,7 +961,8 @@ function formatUsd(usd: number | undefined): string {
935
961
  *
936
962
  * With no priced row at all the cell is `—`, not `$0.00`: a report that could
937
963
  * not price anything has not measured zero spend, and this number is what a
938
- * tier decision would be made on.
964
+ * tier decision would be made on. `unpricedRows` counts every row that is not
965
+ * FULLY priced, including rows whose numeric part is shown but incomplete.
939
966
  */
940
967
  function totalCostCell(pricedUsd: number, pricedRows: number, unpricedRows: number): string {
941
968
  if (pricedRows === 0) return unpricedRows === 0 ? '**$0.00**' : '**—** (nothing priceable)'
@@ -943,6 +970,18 @@ function totalCostCell(pricedUsd: number, pricedRows: number, unpricedRows: numb
943
970
  return unpricedRows === 0 ? cell : `${cell} (partial)`
944
971
  }
945
972
 
973
+ /**
974
+ * A per-row cost cell.
975
+ *
976
+ * A row that mixed priced and unpriced models shows the money it could account
977
+ * for, marked `(partial)`: hiding it behind `—` under-reported the total, and
978
+ * showing it unmarked claimed the row was fully priced.
979
+ */
980
+ function rowCostCell(usd: number | undefined, unpricedModels: number | undefined): string {
981
+ const cell = formatUsd(usd)
982
+ return unpricedModels === undefined || usd === undefined ? cell : `${cell} (partial)`
983
+ }
984
+
946
985
  /** Session rows shown before the tail is summarised. */
947
986
  const MAX_SESSION_ROWS = 20
948
987
 
@@ -1005,7 +1044,39 @@ function pricingNote(pricing: PricingSnapshot | undefined): string[] {
1005
1044
  return [`${head}.`]
1006
1045
  }
1007
1046
 
1008
- /** Model rows collapsed across agents: one line per provider/model pair. */
1047
+ /**
1048
+ * One line that reconciles the two dollar totals.
1049
+ *
1050
+ * Every dollar is attributed per `(agent, model)` and then summed, so a fully
1051
+ * priced report produces the SAME by-agent and by-model totals by construction.
1052
+ * The only legitimate difference is a model with no catalog price: its tokens
1053
+ * remain measured in both token columns and its cost is absent from both dollar
1054
+ * totals. The exclusion clause is shared by both branches, so one line can
1055
+ * never both claim agreement and name a difference for the same tokens.
1056
+ */
1057
+ function reconciliationNote(
1058
+ rows: readonly CostRow[],
1059
+ byModel: readonly CostModelRow[] | undefined,
1060
+ ): string | undefined {
1061
+ if (byModel === undefined) return undefined
1062
+ const unpriced = byModel.filter((row) => row.costUsd === undefined)
1063
+ if (unpriced.length === 0) return undefined
1064
+ const agentUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1065
+ const modelUsd = byModel.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1066
+ const totalTokens = byModel.reduce((sum, row) => sum + row.tokensTotal, 0)
1067
+ const unpricedTokens = unpriced.reduce((sum, row) => sum + row.tokensTotal, 0)
1068
+ const pricedRows = byModel.length - unpriced.length
1069
+ const totals =
1070
+ pricedRows === 0
1071
+ ? 'nothing in either table could be priced'
1072
+ : Math.abs(agentUsd - modelUsd) < 0.005
1073
+ ? `by-agent and by-model priced totals agree at ${formatUsd(agentUsd)}`
1074
+ : `by-agent ${formatUsd(agentUsd)} and by-model ${formatUsd(modelUsd)} differ by ${formatUsd(Math.abs(agentUsd - modelUsd))}`
1075
+ // The exclusion is stated once, in the same words in every branch: the count
1076
+ // can never be read as applying to one total but not the other.
1077
+ return `Cost reconciliation: ${totals}; ${unpricedTokens} token(s) from ${unpriced.length} unpriced model row(s) are counted in the token columns and excluded from both dollar totals (${totalTokens - unpricedTokens} priced token(s) carry the money).`
1078
+ }
1079
+
1009
1080
  function modelTotals(byModel: readonly CostModelRow[]): Array<{
1010
1081
  provider: string
1011
1082
  model: string
@@ -1015,6 +1086,7 @@ function modelTotals(byModel: readonly CostModelRow[]): Array<{
1015
1086
  tokensCacheWrite: number
1016
1087
  tokensTotal: number
1017
1088
  costUsd: number | undefined
1089
+ unpricedModels?: number
1018
1090
  }> {
1019
1091
  const groups = new Map<
1020
1092
  string,
@@ -1026,8 +1098,9 @@ function modelTotals(byModel: readonly CostModelRow[]): Array<{
1026
1098
  tokensCacheRead: number
1027
1099
  tokensCacheWrite: number
1028
1100
  tokensTotal: number
1029
- usd: number | undefined
1030
- unpriced: boolean
1101
+ usd: number
1102
+ priced: number
1103
+ unpricedModels: number
1031
1104
  }
1032
1105
  >()
1033
1106
  for (const row of byModel) {
@@ -1041,18 +1114,19 @@ function modelTotals(byModel: readonly CostModelRow[]): Array<{
1041
1114
  tokensCacheWrite: 0,
1042
1115
  tokensTotal: 0,
1043
1116
  usd: 0,
1044
- unpriced: false,
1117
+ priced: 0,
1118
+ unpricedModels: 0,
1045
1119
  }
1046
1120
  acc.tokensInput += row.tokensInput
1047
1121
  acc.tokensOutput += row.tokensOutput
1048
1122
  acc.tokensCacheRead += row.tokensCacheRead
1049
1123
  acc.tokensCacheWrite += row.tokensCacheWrite
1050
1124
  acc.tokensTotal += row.tokensTotal
1051
- if (row.costUsd === undefined || acc.usd === undefined) {
1052
- acc.unpriced = true
1053
- acc.usd = undefined
1125
+ if (row.costUsd === undefined) {
1126
+ acc.unpricedModels += 1
1054
1127
  } else {
1055
1128
  acc.usd += row.costUsd
1129
+ acc.priced += 1
1056
1130
  }
1057
1131
  groups.set(key, acc)
1058
1132
  }
@@ -1065,7 +1139,13 @@ function modelTotals(byModel: readonly CostModelRow[]): Array<{
1065
1139
  tokensCacheRead: acc.tokensCacheRead,
1066
1140
  tokensCacheWrite: acc.tokensCacheWrite,
1067
1141
  tokensTotal: acc.tokensTotal,
1068
- costUsd: acc.unpriced ? undefined : acc.usd,
1142
+ // Same rule as the by-agent table: a model bucket that spans several
1143
+ // agent/phase groups is the SUM of its priced groups, and `unpricedModels`
1144
+ // records how many groups had no usable price.
1145
+ costUsd: acc.priced === 0 ? undefined : acc.usd,
1146
+ ...(acc.priced === 0 || acc.unpricedModels === 0
1147
+ ? {}
1148
+ : { unpricedModels: acc.unpricedModels }),
1069
1149
  }))
1070
1150
  .sort((a, b) => b.tokensTotal - a.tokensTotal)
1071
1151
  }
@@ -1080,7 +1160,9 @@ function renderModelSection(byModel: readonly CostModelRow[] | undefined, days:
1080
1160
  const totals = modelTotals(byModel)
1081
1161
  const pricedUsd = totals.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1082
1162
  const priced = totals.filter((row) => row.costUsd !== undefined).length
1083
- const unpriced = totals.length - priced
1163
+ const unpriced = totals.filter(
1164
+ (row) => row.costUsd === undefined || (row.unpricedModels ?? 0) > 0,
1165
+ ).length
1084
1166
  const totalCell = totalCostCell(pricedUsd, priced, unpriced)
1085
1167
  return [
1086
1168
  header,
@@ -1089,7 +1171,7 @@ function renderModelSection(byModel: readonly CostModelRow[] | undefined, days:
1089
1171
  '|----------|-------|----------:|-----------:|-----------:|------------:|-----------:|',
1090
1172
  ...totals.map(
1091
1173
  (row) =>
1092
- `| ${row.provider} | ${row.model} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${formatUsd(row.costUsd)} |`,
1174
+ `| ${row.provider} | ${row.model} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${rowCostCell(row.costUsd, row.unpricedModels)} |`,
1093
1175
  ),
1094
1176
  `| **Total** | — | **${totals.reduce((sum, row) => sum + row.tokensInput, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensOutput, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensCacheRead, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensCacheWrite, 0)}** | ${totalCell} |`,
1095
1177
  ]
@@ -1129,14 +1211,16 @@ function renderSessionSection(query: CostQuery, days: number): string[] {
1129
1211
  const hidden = query.bySession.length - shown.length
1130
1212
  const pricedUsd = query.bySession.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1131
1213
  const priced = query.bySession.filter((row) => row.costUsd !== undefined).length
1132
- const unpriced = query.bySession.length - priced
1214
+ const unpriced = query.bySession.filter(
1215
+ (row) => row.costUsd === undefined || (row.unpricedModels ?? 0) > 0,
1216
+ ).length
1133
1217
  const totalCell = totalCostCell(pricedUsd, priced, unpriced)
1134
1218
  lines.push(
1135
1219
  '| Session | Title | Agent | Tokens In | Tokens Out | Cache Read | Cache Write | Tokens Total | Cost (USD) |',
1136
1220
  '|---------|-------|-------|----------:|-----------:|-----------:|------------:|-------------:|-----------:|',
1137
1221
  ...shown.map(
1138
1222
  (row) =>
1139
- `| ${row.sessionId} | ${shortTitle(row.title)} | ${row.agents.join(', ') || '—'} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${row.tokensTotal} | ${formatUsd(row.costUsd)} |`,
1223
+ `| ${row.sessionId} | ${shortTitle(row.title)} | ${row.agents.join(', ') || '—'} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${row.tokensTotal} | ${rowCostCell(row.costUsd, row.unpricedModels)} |`,
1140
1224
  ),
1141
1225
  `| **${scope === undefined ? 'Total' : 'Root + descendants'}** | — | — | **${query.bySession.reduce((sum, row) => sum + row.tokensInput, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensOutput, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensCacheRead, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensCacheWrite, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensTotal, 0)}** | ${totalCell} |`,
1142
1226
  )
@@ -1154,12 +1238,14 @@ function renderMarkdown(
1154
1238
  ): string {
1155
1239
  const { rows, coverage } = query
1156
1240
  const header = `## Token and cost usage by agent and phase (last ${days} days)`
1241
+ const reconciliation = reconciliationNote(rows, query.byModel)
1157
1242
  const footer = [
1158
1243
  formatCoverage(coverage, days),
1159
1244
  'Window: rolling 24-hour days from query time (not calendar days or session boundaries).',
1160
1245
  'Aggregation: per agent and phase (phase may be unknown on V2), per model, and per session.',
1161
1246
  'Attribution: a session row covers that session alone; passing session:<id> sums the root session and its descendant sessions.',
1162
- 'Limits: costs are catalog list prices (USD per 1M tokens), not a provider invoice; a row mixing a priced and an unpriced model reads — and is excluded from the totals, because an unknown model is never priced at zero.',
1247
+ 'Limits: costs are catalog list prices (USD per 1M tokens), not a provider invoice; a row that mixes priced and unpriced models shows its priced part and is reported as partial, and an unknown model is never priced at zero.',
1248
+ ...(reconciliation === undefined ? [] : [reconciliation]),
1163
1249
  ...pricingNote(pricing),
1164
1250
  `Source: opencode.db (read-only) — table families: ${coverage.sources.join(' + ')} — ${coverage.assistantRows} assistant row(s) scanned`,
1165
1251
  ].join('\n')
@@ -1193,12 +1279,13 @@ function renderMarkdown(
1193
1279
  else {
1194
1280
  acc.usd += r.costUsd
1195
1281
  acc.priced += 1
1282
+ if ((r.unpricedModels ?? 0) > 0) acc.partial += 1
1196
1283
  }
1197
1284
  return acc
1198
1285
  },
1199
- { tokensInput: 0, tokensOutput: 0, tokensTotal: 0, usd: 0, unpriced: 0, priced: 0 },
1286
+ { tokensInput: 0, tokensOutput: 0, tokensTotal: 0, usd: 0, unpriced: 0, priced: 0, partial: 0 },
1200
1287
  )
1201
- const totalCost = totalCostCell(total.usd, total.priced, total.unpriced)
1288
+ const totalCost = totalCostCell(total.usd, total.priced, total.unpriced + total.partial)
1202
1289
  const lines = [
1203
1290
  header,
1204
1291
  '',
@@ -1206,7 +1293,7 @@ function renderMarkdown(
1206
1293
  '|-------|-------|----------:|-----------:|-------------:|-----------:|',
1207
1294
  ...rows.map(
1208
1295
  (r) =>
1209
- `| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} | ${formatUsd(r.costUsd)} |`,
1296
+ `| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} | ${rowCostCell(r.costUsd, r.unpricedModels)} |`,
1210
1297
  ),
1211
1298
  `| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** | ${totalCost} |`,
1212
1299
  '',