@osovv/vv-opencode 2.0.1 → 2.1.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.
Files changed (296) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +88 -87
  3. package/dist/commands/completion.js +0 -1
  4. package/dist/commands/completion.js.map +1 -1
  5. package/dist/commands/doctor.js +6 -9
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/commands/init.d.ts +2 -1
  8. package/dist/commands/init.js +7 -12
  9. package/dist/commands/init.js.map +1 -1
  10. package/dist/commands/install.d.ts +4 -0
  11. package/dist/commands/install.js +40 -37
  12. package/dist/commands/install.js.map +1 -1
  13. package/dist/commands/launch.d.ts +2 -1
  14. package/dist/commands/launch.js +18 -14
  15. package/dist/commands/launch.js.map +1 -1
  16. package/dist/commands/patch-provider.d.ts +225 -307
  17. package/dist/commands/patch-provider.js +92 -296
  18. package/dist/commands/patch-provider.js.map +1 -1
  19. package/dist/commands/status.js +7 -10
  20. package/dist/commands/status.js.map +1 -1
  21. package/dist/commands/sync.d.ts +4 -0
  22. package/dist/commands/sync.js +38 -35
  23. package/dist/commands/sync.js.map +1 -1
  24. package/dist/index.d.ts +25 -5
  25. package/dist/index.js +73 -34
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/agent-tool-catalog.d.ts +1 -1
  28. package/dist/lib/agent-tool-catalog.js +3 -6
  29. package/dist/lib/agent-tool-catalog.js.map +1 -1
  30. package/dist/lib/agent-tool-contract.d.ts +22 -13
  31. package/dist/lib/agent-tool-contract.js +20 -20
  32. package/dist/lib/agent-tool-contract.js.map +1 -1
  33. package/dist/lib/analytics/types.d.ts +7 -1
  34. package/dist/lib/analytics/types.js +2 -2
  35. package/dist/lib/analytics/types.js.map +1 -1
  36. package/dist/lib/config-layers.d.ts +28 -6
  37. package/dist/lib/config-layers.js +268 -73
  38. package/dist/lib/config-layers.js.map +1 -1
  39. package/dist/lib/managed-agents.d.ts +24 -2
  40. package/dist/lib/managed-agents.js +45 -15
  41. package/dist/lib/managed-agents.js.map +1 -1
  42. package/dist/lib/model-roles.d.ts +5 -0
  43. package/dist/lib/model-roles.js +22 -1
  44. package/dist/lib/model-roles.js.map +1 -1
  45. package/dist/lib/opencode/agent-registrations.d.ts +4 -4
  46. package/dist/lib/opencode/agent-registrations.js +386 -197
  47. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  48. package/dist/lib/opencode/inspection.d.ts +13 -13
  49. package/dist/lib/opencode/inspection.js +69 -106
  50. package/dist/lib/opencode/inspection.js.map +1 -1
  51. package/dist/lib/opencode/model-overrides.d.ts +2 -2
  52. package/dist/lib/opencode/model-overrides.js +192 -47
  53. package/dist/lib/opencode/model-overrides.js.map +1 -1
  54. package/dist/lib/opencode/paths.d.ts +6 -2
  55. package/dist/lib/opencode/paths.js +12 -11
  56. package/dist/lib/opencode/paths.js.map +1 -1
  57. package/dist/lib/opencode/plugin-registration.d.ts +10 -11
  58. package/dist/lib/opencode/plugin-registration.js +76 -138
  59. package/dist/lib/opencode/plugin-registration.js.map +1 -1
  60. package/dist/lib/opencode/shared-utils.d.ts +47 -3
  61. package/dist/lib/opencode/shared-utils.js +346 -15
  62. package/dist/lib/opencode/shared-utils.js.map +1 -1
  63. package/dist/lib/opencode.d.ts +5 -6
  64. package/dist/lib/opencode.js +10 -10
  65. package/dist/lib/opencode.js.map +1 -1
  66. package/dist/lib/vvoc-config.js +4 -4
  67. package/dist/lib/vvoc-config.js.map +1 -1
  68. package/dist/lib/vvoc-paths.d.ts +7 -0
  69. package/dist/lib/vvoc-paths.js +15 -1
  70. package/dist/lib/vvoc-paths.js.map +1 -1
  71. package/dist/lib/vvoc-preset-registry.d.ts +38 -50
  72. package/dist/lib/vvoc-preset-registry.js +38 -48
  73. package/dist/lib/vvoc-preset-registry.js.map +1 -1
  74. package/dist/plugins/analytics/index.d.ts +20 -14
  75. package/dist/plugins/analytics/index.js +281 -133
  76. package/dist/plugins/analytics/index.js.map +1 -1
  77. package/dist/plugins/guardian/index.d.ts +63 -42
  78. package/dist/plugins/guardian/index.js +217 -759
  79. package/dist/plugins/guardian/index.js.map +1 -1
  80. package/dist/plugins/hashline-edit/index.d.ts +145 -31
  81. package/dist/plugins/hashline-edit/index.js +679 -244
  82. package/dist/plugins/hashline-edit/index.js.map +1 -1
  83. package/dist/plugins/hashline-edit/schemas.d.ts +1 -1
  84. package/dist/plugins/hashline-edit/schemas.js +3 -3
  85. package/dist/plugins/hashline-edit/schemas.js.map +1 -1
  86. package/dist/plugins/model-roles/index.d.ts +18 -4
  87. package/dist/plugins/model-roles/index.js +44 -181
  88. package/dist/plugins/model-roles/index.js.map +1 -1
  89. package/dist/plugins/peak-hours/index.d.ts +23 -23
  90. package/dist/plugins/peak-hours/index.js +211 -180
  91. package/dist/plugins/peak-hours/index.js.map +1 -1
  92. package/dist/plugins/secrets-redaction/deep.js +35 -51
  93. package/dist/plugins/secrets-redaction/deep.js.map +1 -1
  94. package/dist/plugins/secrets-redaction/index.d.ts +96 -8
  95. package/dist/plugins/secrets-redaction/index.js +290 -102
  96. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  97. package/dist/plugins/secrets-redaction/session.d.ts +9 -0
  98. package/dist/plugins/secrets-redaction/session.js +21 -4
  99. package/dist/plugins/secrets-redaction/session.js.map +1 -1
  100. package/dist/plugins/secrets-redaction/stream.d.ts +92 -0
  101. package/dist/plugins/secrets-redaction/stream.js +772 -0
  102. package/dist/plugins/secrets-redaction/stream.js.map +1 -0
  103. package/dist/plugins/spec-guard/index.d.ts +49 -18
  104. package/dist/plugins/spec-guard/index.js +231 -129
  105. package/dist/plugins/spec-guard/index.js.map +1 -1
  106. package/dist/plugins/system-context-injection/index.d.ts +10 -4
  107. package/dist/plugins/system-context-injection/index.js +271 -78
  108. package/dist/plugins/system-context-injection/index.js.map +1 -1
  109. package/dist/plugins/tool-history-compaction/index.d.ts +26 -4
  110. package/dist/plugins/tool-history-compaction/index.js +170 -32
  111. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  112. package/dist/plugins/tool-history-compaction/transform.d.ts +47 -16
  113. package/dist/plugins/tool-history-compaction/transform.js +173 -55
  114. package/dist/plugins/tool-history-compaction/transform.js.map +1 -1
  115. package/dist/plugins/web-tools/fetch-service.d.ts +51 -13
  116. package/dist/plugins/web-tools/fetch-service.js +106 -75
  117. package/dist/plugins/web-tools/fetch-service.js.map +1 -1
  118. package/dist/plugins/web-tools/index.d.ts +58 -16
  119. package/dist/plugins/web-tools/index.js +202 -91
  120. package/dist/plugins/web-tools/index.js.map +1 -1
  121. package/dist/plugins/web-tools/media-loader.d.ts +3 -3
  122. package/dist/plugins/web-tools/media-loader.js +3 -3
  123. package/dist/plugins/web-tools/media-loader.js.map +1 -1
  124. package/dist/plugins/web-tools/providers/native-fetch.d.ts +2 -2
  125. package/dist/plugins/web-tools/providers/native-fetch.js +1 -1
  126. package/dist/plugins/web-tools/providers/native-fetch.js.map +1 -1
  127. package/dist/plugins/web-tools/providers/spider.d.ts +2 -2
  128. package/dist/plugins/web-tools/providers/spider.js +1 -1
  129. package/dist/plugins/web-tools/providers/spider.js.map +1 -1
  130. package/dist/plugins/web-tools/providers/zai.d.ts +2 -2
  131. package/dist/plugins/web-tools/providers/zai.js +1 -1
  132. package/dist/plugins/web-tools/providers/zai.js.map +1 -1
  133. package/dist/plugins/web-tools/schemas.d.ts +1 -1
  134. package/dist/plugins/web-tools/schemas.js +3 -3
  135. package/dist/plugins/web-tools/schemas.js.map +1 -1
  136. package/dist/plugins/web-tools/search-service.d.ts +81 -12
  137. package/dist/plugins/web-tools/search-service.js +104 -57
  138. package/dist/plugins/web-tools/search-service.js.map +1 -1
  139. package/dist/plugins/workflow/authorization.d.ts +44 -10
  140. package/dist/plugins/workflow/authorization.js +113 -73
  141. package/dist/plugins/workflow/authorization.js.map +1 -1
  142. package/dist/plugins/workflow/cancellation.d.ts +86 -0
  143. package/dist/plugins/workflow/cancellation.js +202 -0
  144. package/dist/plugins/workflow/cancellation.js.map +1 -0
  145. package/dist/plugins/workflow/checkpoints.d.ts +7 -1
  146. package/dist/plugins/workflow/checkpoints.js +141 -21
  147. package/dist/plugins/workflow/checkpoints.js.map +1 -1
  148. package/dist/plugins/workflow/delegated.d.ts +14 -0
  149. package/dist/plugins/workflow/delegated.js +6 -5
  150. package/dist/plugins/workflow/delegated.js.map +1 -1
  151. package/dist/plugins/workflow/host.d.ts +81 -0
  152. package/dist/plugins/workflow/host.js +189 -0
  153. package/dist/plugins/workflow/host.js.map +1 -0
  154. package/dist/plugins/workflow/index.d.ts +69 -4
  155. package/dist/plugins/workflow/index.js +1391 -1026
  156. package/dist/plugins/workflow/index.js.map +1 -1
  157. package/dist/plugins/workflow/recovery.d.ts +3 -5
  158. package/dist/plugins/workflow/recovery.js +18 -33
  159. package/dist/plugins/workflow/recovery.js.map +1 -1
  160. package/dist/plugins/workflow/repair.d.ts +31 -5
  161. package/dist/plugins/workflow/repair.js +116 -48
  162. package/dist/plugins/workflow/repair.js.map +1 -1
  163. package/dist/plugins/workflow/results.d.ts +31 -31
  164. package/dist/plugins/workflow/results.js +4 -4
  165. package/dist/plugins/workflow/results.js.map +1 -1
  166. package/dist/plugins/workflow/schemas.d.ts +3 -3
  167. package/dist/plugins/workflow/schemas.js +5 -5
  168. package/dist/plugins/workflow/schemas.js.map +1 -1
  169. package/dist/plugins/workflow/system-instruction.md +4 -0
  170. package/dist/plugins/workflow/tooling.d.ts +6 -0
  171. package/dist/plugins/workflow/tooling.js +3 -1
  172. package/dist/plugins/workflow/tooling.js.map +1 -1
  173. package/dist/runtime/auxiliary.d.ts +13 -0
  174. package/dist/runtime/auxiliary.js +108 -0
  175. package/dist/runtime/auxiliary.js.map +1 -0
  176. package/dist/runtime/client.d.ts +88 -0
  177. package/dist/runtime/client.js +174 -0
  178. package/dist/runtime/client.js.map +1 -0
  179. package/dist/runtime/context-inspection-contract.d.ts +397 -0
  180. package/dist/runtime/context-inspection-contract.js +622 -0
  181. package/dist/runtime/context-inspection-contract.js.map +1 -0
  182. package/dist/runtime/context-inspection.d.ts +52 -0
  183. package/dist/runtime/context-inspection.js +324 -0
  184. package/dist/runtime/context-inspection.js.map +1 -0
  185. package/dist/runtime/context.d.ts +192 -0
  186. package/dist/runtime/context.js +1246 -0
  187. package/dist/runtime/context.js.map +1 -0
  188. package/dist/runtime/coordination.d.ts +40 -0
  189. package/dist/runtime/coordination.js +87 -0
  190. package/dist/runtime/coordination.js.map +1 -0
  191. package/dist/runtime/model-registry.d.ts +34 -0
  192. package/dist/runtime/model-registry.js +227 -0
  193. package/dist/runtime/model-registry.js.map +1 -0
  194. package/dist/runtime/permissions.d.ts +20 -0
  195. package/dist/runtime/permissions.js +250 -0
  196. package/dist/runtime/permissions.js.map +1 -0
  197. package/dist/runtime/snapshot-config.d.ts +80 -0
  198. package/dist/runtime/snapshot-config.js +268 -0
  199. package/dist/runtime/snapshot-config.js.map +1 -0
  200. package/dist/runtime/snapshot-store.d.ts +25 -0
  201. package/dist/runtime/snapshot-store.js +519 -0
  202. package/dist/runtime/snapshot-store.js.map +1 -0
  203. package/dist/runtime/snapshots.d.ts +59 -0
  204. package/dist/runtime/snapshots.js +721 -0
  205. package/dist/runtime/snapshots.js.map +1 -0
  206. package/dist/runtime/types.d.ts +713 -0
  207. package/dist/runtime/types.js +190 -0
  208. package/dist/runtime/types.js.map +1 -0
  209. package/dist/tui/analytics/indicator.d.ts +25 -26
  210. package/dist/tui/analytics/indicator.js +66 -74
  211. package/dist/tui/analytics/indicator.js.map +1 -1
  212. package/dist/tui/branding/footer.d.ts +7 -12
  213. package/dist/tui/branding/footer.js +16 -24
  214. package/dist/tui/branding/footer.js.map +1 -1
  215. package/dist/tui/context/analyze.d.ts +20 -9
  216. package/dist/tui/context/analyze.js +295 -257
  217. package/dist/tui/context/analyze.js.map +1 -1
  218. package/dist/tui/context/collect.d.ts +29 -3
  219. package/dist/tui/context/collect.js +450 -66
  220. package/dist/tui/context/collect.js.map +1 -1
  221. package/dist/tui/context/plugin.d.ts +21 -7
  222. package/dist/tui/context/plugin.js +65 -70
  223. package/dist/tui/context/plugin.js.map +1 -1
  224. package/dist/tui/context/types.d.ts +174 -43
  225. package/dist/tui/context/types.js +25 -19
  226. package/dist/tui/context/types.js.map +1 -1
  227. package/dist/tui/context/view.d.ts +33 -7
  228. package/dist/tui/context/view.js +136 -81
  229. package/dist/tui/context/view.js.map +1 -1
  230. package/dist/tui/peak-hours/banner.d.ts +13 -11
  231. package/dist/tui/peak-hours/banner.js +48 -80
  232. package/dist/tui/peak-hours/banner.js.map +1 -1
  233. package/dist/tui/policy.d.ts +69 -0
  234. package/dist/tui/policy.js +169 -0
  235. package/dist/tui/policy.js.map +1 -0
  236. package/dist/tui.d.ts +3 -8
  237. package/dist/tui.js +72 -68
  238. package/dist/tui.js.map +1 -1
  239. package/package.json +18 -14
  240. package/schemas/vvoc/v3.json +1 -1
  241. package/server.js +3 -5
  242. package/templates/agents/enhancer.md +10 -5
  243. package/templates/agents/guardian.md +10 -4
  244. package/templates/agents/investigator.md +4 -2
  245. package/templates/agents/vv-code-reviewer.md +4 -2
  246. package/templates/agents/vv-spec-reviewer.md +4 -2
  247. package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
  248. package/tui.js +3 -5
  249. package/dist/plugins/analytics/v2.d.ts +0 -21
  250. package/dist/plugins/analytics/v2.js +0 -133
  251. package/dist/plugins/analytics/v2.js.map +0 -1
  252. package/dist/plugins/guardian/v2.d.ts +0 -13
  253. package/dist/plugins/guardian/v2.js +0 -204
  254. package/dist/plugins/guardian/v2.js.map +0 -1
  255. package/dist/plugins/hashline-edit/v2.d.ts +0 -12
  256. package/dist/plugins/hashline-edit/v2.js +0 -145
  257. package/dist/plugins/hashline-edit/v2.js.map +0 -1
  258. package/dist/plugins/model-roles/v2.d.ts +0 -24
  259. package/dist/plugins/model-roles/v2.js +0 -274
  260. package/dist/plugins/model-roles/v2.js.map +0 -1
  261. package/dist/plugins/peak-hours/v2.d.ts +0 -12
  262. package/dist/plugins/peak-hours/v2.js +0 -99
  263. package/dist/plugins/peak-hours/v2.js.map +0 -1
  264. package/dist/plugins/secrets-redaction/v2.d.ts +0 -19
  265. package/dist/plugins/secrets-redaction/v2.js +0 -138
  266. package/dist/plugins/secrets-redaction/v2.js.map +0 -1
  267. package/dist/plugins/spec-guard/v2.d.ts +0 -12
  268. package/dist/plugins/spec-guard/v2.js +0 -139
  269. package/dist/plugins/spec-guard/v2.js.map +0 -1
  270. package/dist/plugins/system-context-injection/agent-contexts.d.ts +0 -5
  271. package/dist/plugins/system-context-injection/agent-contexts.js +0 -164
  272. package/dist/plugins/system-context-injection/agent-contexts.js.map +0 -1
  273. package/dist/plugins/system-context-injection/v2.d.ts +0 -13
  274. package/dist/plugins/system-context-injection/v2.js +0 -60
  275. package/dist/plugins/system-context-injection/v2.js.map +0 -1
  276. package/dist/plugins/tool-history-compaction/v2.d.ts +0 -11
  277. package/dist/plugins/tool-history-compaction/v2.js +0 -56
  278. package/dist/plugins/tool-history-compaction/v2.js.map +0 -1
  279. package/dist/plugins/v2-runtime/config-watcher.d.ts +0 -26
  280. package/dist/plugins/v2-runtime/config-watcher.js +0 -111
  281. package/dist/plugins/v2-runtime/config-watcher.js.map +0 -1
  282. package/dist/plugins/v2-runtime/index.d.ts +0 -50
  283. package/dist/plugins/v2-runtime/index.js +0 -114
  284. package/dist/plugins/v2-runtime/index.js.map +0 -1
  285. package/dist/plugins/v2-runtime/location-config.d.ts +0 -51
  286. package/dist/plugins/v2-runtime/location-config.js +0 -91
  287. package/dist/plugins/v2-runtime/location-config.js.map +0 -1
  288. package/dist/plugins/v2-runtime/setup.d.ts +0 -48
  289. package/dist/plugins/v2-runtime/setup.js +0 -174
  290. package/dist/plugins/v2-runtime/setup.js.map +0 -1
  291. package/dist/plugins/web-tools/v2.d.ts +0 -11
  292. package/dist/plugins/web-tools/v2.js +0 -99
  293. package/dist/plugins/web-tools/v2.js.map +0 -1
  294. package/dist/plugins/workflow/v2.d.ts +0 -76
  295. package/dist/plugins/workflow/v2.js +0 -283
  296. package/dist/plugins/workflow/v2.js.map +0 -1
@@ -1,59 +1,65 @@
1
1
  // FILE: src/tui/context/analyze.ts
2
- // VERSION: 1.1.0
2
+ // VERSION: 2.1.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Derive measured usage plus reconciled category, per-tool, and per-MCP active context attribution from observable OpenCode session data.
5
- // SCOPE: Compaction cutoff, provider usage baseline, context-limit percentages, skill/tool/message categorization, deterministic MCP ownership, explicit schema observability, residual unknown context, and sorted detail aggregates.
6
- // DEPENDS: [@opencode-ai/sdk/v2, src/tui/context/estimate.ts, src/tui/context/types.ts]
4
+ // PURPOSE: Derive honest measured usage plus reconciled observed-context and per-tool attribution from native tagged session data, keeping the registered catalog budget separate.
5
+ // SCOPE: Native compaction cutoff via message order/timestamps, provider-reported usage with per-field unknown semantics and explicit model/variant + compaction relation, context-limit percentages, skill/tool/message/attachment categorization, deterministic non-guessing tool ownership, residual unknown context, and sorted detail aggregates. Unknown limits and missing usage stay unknown rather than zero.
6
+ // DEPENDS: [src/tui/context/estimate.ts, src/tui/context/types.ts]
7
7
  // LINKS: [M-PLUGIN-CONTEXT-TUI, DF-CONTEXT-INSPECTION, V-M-PLUGIN-CONTEXT-TUI]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
10
10
  // END_MODULE_CONTRACT
11
11
  //
12
12
  // START_MODULE_MAP
13
- // analyzeContext - Produce the complete overview and detailed context analysis rendered by the TUI plugin.
14
- // selectActiveMessages - Keep only the latest compaction summary and subsequent turns.
13
+ // analyzeContext - Produce the overview and detailed native context analysis rendered by the TUI plugin.
15
14
  // createTokenMetric - Pair estimated tokens with a percentage only when a positive context limit exists.
16
- // sanitizeMcpName - Mirror OpenCode's MCP name sanitization contract.
17
- // classifyToolSource - Classify known tools and uniquely matched MCP prefixes without guessing.
18
- // ContextToolClassification - Source result plus explicit ambiguous MCP candidates.
15
+ // classifyToolSource - Classify known native built-in/vvoc tools and leave everything else explicitly unattributed.
19
16
  // compareToolUsage - Sort tool detail by combined total descending and ID ascending.
17
+ // findCompactionCutoff - Latest completed compaction message with its active-context index.
18
+ // sameModelRef - True when two provider/model/variant references refer to the same real selection.
20
19
  // END_MODULE_MAP
21
20
  //
22
21
  // START_CHANGE_SUMMARY
23
- // LAST_CHANGE: [C-DELEGATED-WORKFLOW-ASTRA-PRESETS - Classified the delegated control tools as vvoc-managed.]
22
+ // LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-008 attempt 3 - Measured usage now matches the pinned native contextUsage sum of all five token fields (input+output+reasoning+cacheRead+cacheWrite).]
24
23
  // END_CHANGE_SUMMARY
25
24
  import { estimateTextTokens, estimateValueTokens } from "./estimate.js";
25
+ /**
26
+ * Native built-in tool names (core/src/tool/plugin/*). Unknown tools are never
27
+ * classified as built-in; they stay explicitly unattributed.
28
+ */
26
29
  const BUILTIN_TOOL_IDS = new Set([
27
- "bash",
30
+ "read",
31
+ "write",
32
+ "edit",
33
+ "patch",
28
34
  "glob",
29
35
  "grep",
30
- "list",
31
- "read",
36
+ "shell",
37
+ "subagent",
38
+ "webfetch",
39
+ "websearch",
32
40
  "question",
33
41
  "skill",
34
- "task",
35
- "todowrite",
36
- "webfetch",
37
- "write",
42
+ "execute",
43
+ "list_mcp_resources",
44
+ "read_mcp_resource",
45
+ "opencode",
46
+ "models",
47
+ "session_move",
48
+ "session_rename",
38
49
  ]);
39
50
  const VVOC_TOOL_IDS = new Set([
40
- "edit",
51
+ "web_search",
52
+ "web_fetch",
41
53
  "work_item_open",
42
54
  "work_item_list",
43
55
  "work_item_close",
44
56
  "work_item_decide",
45
57
  "work_checkpoint",
46
- "web_search",
47
- "web_fetch",
48
58
  ]);
49
- const MAX_ATTRIBUTION_WARNINGS = 3;
50
59
  const CATEGORY_LABELS = {
51
60
  system: "Agent/system instructions",
52
61
  "skill-catalog": "Skill catalog",
53
62
  "loaded-skills": "Loaded skill results",
54
- "builtin-tool-schemas": "Built-in tool schemas",
55
- "vvoc-tool-schemas": "vvoc tool schemas",
56
- "external-tool-schemas": "External/plugin/MCP schemas",
57
63
  "user-messages": "User messages",
58
64
  "assistant-messages": "Assistant messages",
59
65
  "tool-results": "Tool calls and results",
@@ -63,103 +69,94 @@ const CATEGORY_LABELS = {
63
69
  };
64
70
  // START_BLOCK_CONTEXT_ANALYSIS
65
71
  export function analyzeContext(input) {
66
- const activeMessages = selectActiveMessages(input.messages);
67
- const activeMessageIDs = new Set(activeMessages.map((message) => message.id));
68
- const activeParts = input.parts.filter((part) => activeMessageIDs.has(part.messageID));
69
- const latestAssistant = findLatestAssistant(activeMessages);
70
- const latestUser = findLatestUser(activeMessages);
72
+ const compaction = findCompactionCutoff(input.activeMessages);
73
+ const compacted = compaction !== undefined ||
74
+ (input.historyMessages.length > 0 &&
75
+ input.activeMessages.length < input.historyMessages.length);
76
+ const latestAssistant = findLatestAssistant(input.activeMessages);
77
+ const latestUser = findLatestUser(input.activeMessages);
71
78
  const currentAgent = latestAssistant?.agent ?? latestUser?.agent;
72
79
  const counters = createCategoryCounter();
73
- const agentPrompt = input.agents.find((agent) => agent.name === currentAgent)?.prompt;
80
+ // Native agents carry both an id and a display name; message.agent is the id.
81
+ const agentPrompt = input.agents.find((agent) => agent.id === currentAgent)?.system;
74
82
  counters.system += estimateTextTokens(agentPrompt);
75
- counters.system += estimateTextTokens(latestUser?.system);
76
83
  for (const skill of input.skills) {
77
84
  counters["skill-catalog"] += estimateValueTokens({
78
85
  name: skill.name,
79
86
  description: skill.description,
80
- location: skill.location,
87
+ path: skill.path,
81
88
  });
82
89
  }
90
+ // Registered catalog schemas are a budget for the Tools tab, never part of
91
+ // the observed-context subtotal. They are collected here and kept separate.
83
92
  const toolDrafts = new Map();
93
+ let catalogSchemaBudget = 0;
84
94
  for (const tool of input.tools) {
85
- const draft = getToolDraft(toolDrafts, tool.id);
86
- draft.schemaListed = true;
87
- draft.schemaTokens = estimateValueTokens({
88
- id: tool.id,
89
- description: tool.description,
90
- parameters: tool.parameters,
91
- });
92
- }
93
- const messageByID = new Map(activeMessages.map((message) => [message.id, message]));
94
- const toolPartsByCall = new Map();
95
- for (const part of activeParts) {
96
- if (part.type === "tool") {
97
- toolPartsByCall.set(`${part.tool}\u0000${part.callID}`, part);
98
- continue;
95
+ const draft = getToolDraft(toolDrafts, tool.effectiveID, tool);
96
+ draft.schemaListed = tool.status === "registered";
97
+ if (tool.status === "registered") {
98
+ const tokens = estimateValueTokens({
99
+ id: tool.effectiveID,
100
+ description: tool.description,
101
+ namespace: tool.namespace,
102
+ parameters: tool.inputJSONSchema,
103
+ });
104
+ draft.schemaTokens = tokens;
105
+ catalogSchemaBudget += tokens;
99
106
  }
100
- countPart(part, messageByID.get(part.messageID), counters);
101
107
  }
102
- for (const part of toolPartsByCall.values()) {
103
- const historyTokens = countToolPart(part, counters);
104
- const draft = getToolDraft(toolDrafts, part.tool);
105
- draft.calls += 1;
106
- draft.historyTokens += historyTokens;
108
+ for (const message of input.activeMessages) {
109
+ countMessage(message, counters, toolDrafts);
107
110
  }
108
- const contextLimit = normalizeContextLimit(input.model?.contextLimit);
109
- const detail = buildToolAttribution(toolDrafts, input.mcpServers, contextLimit, input.mcpSchemaCatalogAvailable ?? false);
110
- counters["builtin-tool-schemas"] =
111
- detail.attribution.reconciliation.schema.builtin.estimatedTokens;
112
- counters["vvoc-tool-schemas"] = detail.attribution.reconciliation.schema.vvoc.estimatedTokens;
113
- counters["external-tool-schemas"] =
114
- detail.attribution.reconciliation.schema.external.estimatedTokens;
115
- counters["tool-results"] = detail.attribution.reconciliation.history.toolResults.estimatedTokens;
116
- counters["loaded-skills"] =
117
- detail.attribution.reconciliation.history.loadedSkills.estimatedTokens;
111
+ // Unknown limits stay unknown; only the selected model's configured limit may
112
+ // be applied, and only to usage attributed to that exact model/variant.
113
+ const contextLimit = normalizeContextLimit(input.selectedModel?.contextLimit);
114
+ const attribution = buildToolAttribution(toolDrafts, contextLimit);
115
+ counters["tool-results"] = attribution.reconciliation.history.toolResults.estimatedTokens;
116
+ counters["loaded-skills"] = attribution.reconciliation.history.loadedSkills.estimatedTokens;
118
117
  const categories = buildKnownCategories(counters, contextLimit);
119
118
  const estimatedKnownTokens = categories.reduce((total, category) => total + category.estimatedTokens, 0);
120
119
  const measured = latestAssistant
121
- ? createMeasuredUsage(latestAssistant, input.model?.contextLimit)
120
+ ? createMeasuredUsage(latestAssistant, input.activeMessages, input.selectedModel, contextLimit)
122
121
  : undefined;
123
- const providerOnlyTokens = measured ? Math.max(0, measured.usedTokens - estimatedKnownTokens) : 0;
124
- const estimationDriftTokens = measured
125
- ? Math.max(0, estimatedKnownTokens - measured.usedTokens)
126
- : 0;
122
+ const providerOnlyTokens = measured?.usedTokens === undefined
123
+ ? 0
124
+ : Math.max(0, measured.usedTokens - estimatedKnownTokens);
125
+ const estimationDriftTokens = measured?.usedTokens === undefined
126
+ ? 0
127
+ : Math.max(0, estimatedKnownTokens - measured.usedTokens);
127
128
  if (providerOnlyTokens > 0) {
128
129
  categories.push({
129
130
  id: "provider-only",
130
131
  label: CATEGORY_LABELS["provider-only"],
131
132
  ...createTokenMetric(providerOnlyTokens, contextLimit),
132
- detail: "Measured provider usage not attributable through public TUI/SDK data",
133
+ detail: "Measured provider usage not attributable through observable native data",
133
134
  source: "provider-residual",
134
135
  });
135
136
  }
136
137
  return {
137
138
  sessionID: input.sessionID,
139
+ selectedModel: input.selectedModel,
140
+ historyModel: latestAssistant === undefined ? undefined : modelFromRef(latestAssistant.model),
138
141
  agent: currentAgent,
139
- model: input.model,
140
142
  measured,
141
143
  categories,
142
144
  estimatedKnownTokens,
143
145
  estimatedTotalTokens: estimatedKnownTokens + providerOnlyTokens,
144
146
  estimationDriftTokens,
145
- compacted: activeMessages.length < input.messages.length,
146
- activeMessageCount: activeMessages.length,
147
+ ...(input.tools.length === 0
148
+ ? {}
149
+ : { catalogSchemaBudget: createTokenMetric(catalogSchemaBudget, contextLimit) }),
150
+ compacted,
151
+ ...(compaction === undefined ? {} : { compactionCutoffId: compaction.message.id }),
152
+ activeMessageCount: input.activeMessages.length,
153
+ totalMessageCount: input.historyMessages.length,
147
154
  mcpServers: [...input.mcpServers],
148
- toolAttribution: detail.attribution,
149
- warnings: [...(input.warnings ?? []), ...detail.warnings],
155
+ toolCatalogStatus: input.toolCatalogStatus,
156
+ toolAttribution: attribution,
157
+ warnings: [...(input.warnings ?? []), ...buildCatalogWarnings(input)],
150
158
  };
151
159
  }
152
- export function selectActiveMessages(messages) {
153
- let summaryIndex = -1;
154
- for (let index = messages.length - 1; index >= 0; index -= 1) {
155
- const message = messages[index];
156
- if (message?.role === "assistant" && message.summary === true) {
157
- summaryIndex = index;
158
- break;
159
- }
160
- }
161
- return summaryIndex >= 0 ? messages.slice(summaryIndex) : messages;
162
- }
163
160
  // END_BLOCK_CONTEXT_ANALYSIS
164
161
  // START_BLOCK_DETAILED_ATTRIBUTION
165
162
  export function createTokenMetric(estimatedTokens, contextLimit) {
@@ -169,150 +166,111 @@ export function createTokenMetric(estimatedTokens, contextLimit) {
169
166
  return { estimatedTokens: tokens };
170
167
  return { estimatedTokens: tokens, percent: (tokens / limit) * 100 };
171
168
  }
172
- export function sanitizeMcpName(value) {
173
- return value.replace(/[^a-zA-Z0-9_-]/g, "_");
174
- }
175
- export function classifyToolSource(toolID, mcpServers) {
176
- if (VVOC_TOOL_IDS.has(toolID))
177
- return { source: { kind: "vvoc" } };
178
- if (BUILTIN_TOOL_IDS.has(toolID))
179
- return { source: { kind: "builtin" } };
180
- const uniqueServers = new Map(mcpServers.map((server) => [server.name, server]));
181
- const candidates = [...uniqueServers.values()]
182
- .map((server) => ({ name: server.name, prefix: `${sanitizeMcpName(server.name)}_` }))
183
- .filter((candidate) => toolID.startsWith(candidate.prefix));
184
- if (candidates.length === 0)
185
- return { source: { kind: "other" } };
186
- const longestLength = Math.max(...candidates.map((candidate) => candidate.prefix.length));
187
- const longest = candidates
188
- .filter((candidate) => candidate.prefix.length === longestLength)
189
- .sort((left, right) => compareText(left.name, right.name));
190
- if (longest.length !== 1) {
191
- return {
192
- source: { kind: "other" },
193
- ambiguousServers: longest.map((candidate) => candidate.name),
194
- };
195
- }
196
- return { source: { kind: "mcp", server: longest[0].name } };
169
+ /**
170
+ * Classify known native built-in and vvoc tools; every other tool is left
171
+ * explicitly unattributed. The registered namespace is a hint only and is never
172
+ * treated as authoritative MCP server provenance.
173
+ */
174
+ export function classifyToolSource(tool) {
175
+ const id = tool.effectiveID.toLowerCase();
176
+ const name = tool.name.toLowerCase();
177
+ if (VVOC_TOOL_IDS.has(id) || VVOC_TOOL_IDS.has(name))
178
+ return { kind: "vvoc" };
179
+ if (BUILTIN_TOOL_IDS.has(id) || BUILTIN_TOOL_IDS.has(name))
180
+ return { kind: "builtin" };
181
+ return tool.namespace === undefined
182
+ ? { kind: "other" }
183
+ : { kind: "other", namespace: tool.namespace };
197
184
  }
198
185
  export function compareToolUsage(left, right) {
199
186
  const totalDelta = right.total.estimatedTokens - left.total.estimatedTokens;
200
187
  return totalDelta || compareText(left.id, right.id);
201
188
  }
202
- function buildToolAttribution(drafts, mcpServers, contextLimit, mcpSchemaCatalogAvailable) {
203
- const serverByName = new Map(mcpServers.map((server) => [server.name, server]));
204
- const ambiguities = new Map();
189
+ /** Latest completed compaction message with its active-context index. */
190
+ export function findCompactionCutoff(messages) {
191
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
192
+ const message = messages[index];
193
+ if (message?.kind === "compaction" && message.status === "completed") {
194
+ return { message, index };
195
+ }
196
+ }
197
+ return undefined;
198
+ }
199
+ function buildToolAttribution(drafts, contextLimit) {
205
200
  const tools = [...drafts.values()]
206
201
  .map((draft) => {
207
- const classification = classifyToolSource(draft.id, mcpServers);
208
- if (classification.ambiguousServers) {
209
- ambiguities.set(draft.id, classification.ambiguousServers);
210
- }
211
- const server = classification.source.kind === "mcp"
212
- ? serverByName.get(classification.source.server)
213
- : undefined;
214
- const schema = resolveToolSchema(draft, classification.source, server, mcpSchemaCatalogAvailable);
202
+ // Per-row schema availability: a partial catalog does not make a row whose
203
+ // own schema converted unknown.
204
+ const schemaKnown = draft.schemaListed;
215
205
  return {
216
206
  id: draft.id,
217
- source: classification.source,
207
+ source: draft.source,
208
+ codeMode: draft.codeMode,
218
209
  calls: draft.calls,
219
- schemaKnown: schema.known,
220
- schema: createTokenMetric(schema.tokens, contextLimit),
210
+ schemaKnown,
211
+ schema: createTokenMetric(schemaKnown ? draft.schemaTokens : 0, contextLimit),
221
212
  history: createTokenMetric(draft.historyTokens, contextLimit),
222
- total: createTokenMetric(schema.tokens + draft.historyTokens, contextLimit),
213
+ total: createTokenMetric((schemaKnown ? draft.schemaTokens : 0) + draft.historyTokens, contextLimit),
223
214
  };
224
215
  })
225
216
  .sort(compareToolUsage);
226
217
  const schemaBuiltin = sumTools(tools, (tool) => tool.source.kind === "builtin", "schema");
227
218
  const schemaVvoc = sumTools(tools, (tool) => tool.source.kind === "vvoc", "schema");
228
- const schemaExternal = sumTools(tools, (tool) => tool.source.kind === "mcp" || tool.source.kind === "other", "schema");
219
+ const schemaExternal = sumTools(tools, (tool) => tool.source.kind === "other", "schema");
229
220
  const historyToolResults = sumTools(tools, (tool) => tool.id !== "skill", "history");
230
221
  const historyLoadedSkills = sumTools(tools, (tool) => tool.id === "skill", "history");
231
- const uniqueServers = [...serverByName.values()];
232
- const mcpUsage = uniqueServers
233
- .map((server) => {
234
- const serverTools = tools.filter((tool) => tool.source.kind === "mcp" && tool.source.server === server.name);
235
- const schemaKnown = server.status !== "connected" || mcpSchemaCatalogAvailable;
236
- const schemaTokens = schemaKnown ? sumTools(serverTools, () => true, "schema") : 0;
237
- const historyTokens = sumTools(serverTools, () => true, "history");
238
- return {
239
- ...server,
240
- toolCount: schemaKnown
241
- ? serverTools.filter((tool) => tool.schema.estimatedTokens > 0).length
242
- : undefined,
243
- schemaKnown,
244
- schema: createTokenMetric(schemaTokens, contextLimit),
245
- history: createTokenMetric(historyTokens, contextLimit),
246
- total: createTokenMetric(schemaTokens + historyTokens, contextLimit),
247
- tools: serverTools,
248
- };
249
- })
250
- .sort(compareMcpUsage);
251
222
  return {
252
- attribution: {
253
- tools,
254
- mcpServers: mcpUsage,
255
- otherTools: tools.filter((tool) => tool.source.kind === "other"),
256
- reconciliation: {
257
- schema: {
258
- builtin: createTokenMetric(schemaBuiltin, contextLimit),
259
- vvoc: createTokenMetric(schemaVvoc, contextLimit),
260
- external: createTokenMetric(schemaExternal, contextLimit),
261
- total: createTokenMetric(schemaBuiltin + schemaVvoc + schemaExternal, contextLimit),
262
- },
263
- history: {
264
- toolResults: createTokenMetric(historyToolResults, contextLimit),
265
- loadedSkills: createTokenMetric(historyLoadedSkills, contextLimit),
266
- total: createTokenMetric(historyToolResults + historyLoadedSkills, contextLimit),
267
- },
223
+ tools,
224
+ otherTools: tools.filter((tool) => tool.source.kind === "other"),
225
+ reconciliation: {
226
+ schema: {
227
+ builtin: createTokenMetric(schemaBuiltin, contextLimit),
228
+ vvoc: createTokenMetric(schemaVvoc, contextLimit),
229
+ external: createTokenMetric(schemaExternal, contextLimit),
230
+ total: createTokenMetric(schemaBuiltin + schemaVvoc + schemaExternal, contextLimit),
231
+ },
232
+ history: {
233
+ toolResults: createTokenMetric(historyToolResults, contextLimit),
234
+ loadedSkills: createTokenMetric(historyLoadedSkills, contextLimit),
235
+ total: createTokenMetric(historyToolResults + historyLoadedSkills, contextLimit),
268
236
  },
269
237
  },
270
- warnings: buildAmbiguityWarnings(ambiguities),
271
238
  };
272
239
  }
273
- function getToolDraft(drafts, id) {
240
+ function getToolDraft(drafts, id, tool) {
274
241
  const current = drafts.get(id);
275
242
  if (current)
276
243
  return current;
277
- const created = { id, schemaListed: false, schemaTokens: 0, historyTokens: 0, calls: 0 };
244
+ const created = {
245
+ id,
246
+ source: classifyToolSource(tool),
247
+ codeMode: tool.codeMode,
248
+ schemaListed: false,
249
+ schemaTokens: 0,
250
+ historyTokens: 0,
251
+ calls: 0,
252
+ };
278
253
  drafts.set(id, created);
279
254
  return created;
280
255
  }
281
- function resolveToolSchema(draft, source, server, mcpSchemaCatalogAvailable) {
282
- if (source.kind !== "mcp") {
283
- return { known: draft.schemaListed, tokens: draft.schemaTokens };
284
- }
285
- if (!server)
286
- return { known: false, tokens: 0 };
287
- if (server.status !== "connected")
288
- return { known: true, tokens: 0 };
289
- if (!mcpSchemaCatalogAvailable)
290
- return { known: false, tokens: 0 };
291
- return { known: true, tokens: draft.schemaListed ? draft.schemaTokens : 0 };
292
- }
293
256
  function sumTools(tools, include, metric) {
294
257
  return tools.reduce((total, tool) => total + (include(tool) ? tool[metric].estimatedTokens : 0), 0);
295
258
  }
296
- function compareMcpUsage(left, right) {
297
- const totalDelta = right.total.estimatedTokens - left.total.estimatedTokens;
298
- return totalDelta || compareText(left.name, right.name);
299
- }
300
259
  function compareText(left, right) {
301
260
  return left < right ? -1 : left > right ? 1 : 0;
302
261
  }
303
- function buildAmbiguityWarnings(ambiguities) {
304
- const entries = [...ambiguities.entries()].sort(([left], [right]) => compareText(left, right));
305
- const visible = entries.length > MAX_ATTRIBUTION_WARNINGS
306
- ? entries.slice(0, MAX_ATTRIBUTION_WARNINGS - 1)
307
- : entries;
308
- const warnings = visible.map(([toolID, servers]) => boundWarning(`MCP attribution ambiguous for "${toolID}": matches ${servers.join(", ")}; grouped under Other external/plugin.`));
309
- if (entries.length > MAX_ATTRIBUTION_WARNINGS) {
310
- warnings.push(`MCP attribution ambiguous for ${entries.length - visible.length} additional tool IDs; grouped under Other external/plugin.`);
262
+ function buildCatalogWarnings(input) {
263
+ if (input.toolCatalogStatus === "unavailable") {
264
+ return [
265
+ "Registered tool catalog is unavailable; tool schemas and code-mode intent are unknown.",
266
+ ];
311
267
  }
312
- return warnings;
313
- }
314
- function boundWarning(value) {
315
- return value.length > 180 ? `${value.slice(0, 177)}...` : value;
268
+ if (input.toolCatalogStatus === "partial") {
269
+ return [
270
+ "Registered tool catalog is incomplete; unavailable schemas are shown as unknown, not zero.",
271
+ ];
272
+ }
273
+ return [];
316
274
  }
317
275
  // END_BLOCK_DETAILED_ATTRIBUTION
318
276
  // START_BLOCK_CATEGORY_COUNTING
@@ -321,9 +279,6 @@ function createCategoryCounter() {
321
279
  system: 0,
322
280
  "skill-catalog": 0,
323
281
  "loaded-skills": 0,
324
- "builtin-tool-schemas": 0,
325
- "vvoc-tool-schemas": 0,
326
- "external-tool-schemas": 0,
327
282
  "user-messages": 0,
328
283
  "assistant-messages": 0,
329
284
  "tool-results": 0,
@@ -331,71 +286,79 @@ function createCategoryCounter() {
331
286
  "compacted-summary": 0,
332
287
  };
333
288
  }
334
- function countPart(part, message, counters) {
335
- switch (part.type) {
336
- case "text": {
337
- if (part.ignored)
338
- return;
339
- if (message?.role === "user") {
340
- counters["user-messages"] += estimateTextTokens(part.text);
341
- }
342
- else if (message?.role === "assistant" && message.summary) {
343
- counters["compacted-summary"] += estimateTextTokens(part.text);
344
- }
345
- else {
346
- counters["assistant-messages"] += estimateTextTokens(part.text);
289
+ function countMessage(message, counters, drafts) {
290
+ switch (message.kind) {
291
+ case "user":
292
+ counters["user-messages"] += estimateTextTokens(message.text);
293
+ for (const attachment of message.files ?? []) {
294
+ counters.files += estimateValueTokens({
295
+ name: attachment.name,
296
+ mime: attachment.mime,
297
+ sourceType: attachment.sourceType,
298
+ sourceURI: attachment.sourceURI,
299
+ byteLength: attachment.byteLength,
300
+ });
347
301
  }
348
302
  return;
349
- }
350
- case "reasoning":
351
- counters["assistant-messages"] += estimateTextTokens(part.text);
303
+ case "synthetic":
304
+ counters["user-messages"] += estimateValueTokens({
305
+ text: message.text,
306
+ description: message.description,
307
+ });
352
308
  return;
353
- case "subtask":
354
- counters["assistant-messages"] += estimateValueTokens({
355
- prompt: part.prompt,
356
- description: part.description,
357
- agent: part.agent,
309
+ case "system":
310
+ counters.system += estimateValueTokens({
311
+ text: message.text,
312
+ description: message.description,
358
313
  });
359
314
  return;
360
- case "agent":
361
- counters["user-messages"] += estimateValueTokens({
362
- name: part.name,
363
- source: part.source?.value,
315
+ case "skill":
316
+ counters["loaded-skills"] += estimateValueTokens({ name: message.name, text: message.text });
317
+ return;
318
+ case "shell":
319
+ counters["tool-results"] += estimateValueTokens({
320
+ command: message.command,
321
+ output: message.output,
364
322
  });
365
323
  return;
366
- case "file":
367
- counters.files += estimateValueTokens({
368
- filename: part.filename,
369
- mime: part.mime,
370
- source: part.source?.text.value,
371
- url: part.url.startsWith("data:") ? undefined : part.url,
324
+ case "compaction":
325
+ counters["compacted-summary"] += estimateValueTokens({
326
+ summary: message.summary,
327
+ recent: message.recent,
372
328
  });
373
329
  return;
330
+ case "assistant":
331
+ countAssistant(message, counters, drafts);
332
+ return;
374
333
  default:
375
334
  return;
376
335
  }
377
336
  }
378
- function countToolPart(part, counters) {
379
- const state = part.state;
380
- const payload = {
381
- tool: part.tool,
382
- input: state.input,
383
- output: state.status === "completed" ? state.output : undefined,
384
- error: state.status === "error" ? state.error : undefined,
385
- };
386
- const target = part.tool === "skill" ? "loaded-skills" : "tool-results";
387
- const historyTokens = estimateValueTokens(payload);
388
- counters[target] += historyTokens;
389
- if (state.status === "completed") {
390
- for (const attachment of state.attachments ?? []) {
391
- counters.files += estimateValueTokens({
392
- filename: attachment.filename,
393
- mime: attachment.mime,
394
- source: attachment.source?.text.value,
395
- });
337
+ function countAssistant(message, counters, drafts) {
338
+ for (const content of message.content) {
339
+ if (content.type === "text" || content.type === "reasoning") {
340
+ counters["assistant-messages"] += estimateTextTokens(content.text);
341
+ continue;
396
342
  }
343
+ const historyTokens = estimateValueTokens(toolPayload(content));
344
+ const draft = getToolDraft(drafts, content.name, {
345
+ effectiveID: content.name,
346
+ name: content.name,
347
+ codeMode: false,
348
+ });
349
+ draft.calls += 1;
350
+ draft.historyTokens += historyTokens;
351
+ const target = content.name === "skill" ? "loaded-skills" : "tool-results";
352
+ counters[target] += historyTokens;
397
353
  }
398
- return historyTokens;
354
+ }
355
+ function toolPayload(content) {
356
+ return {
357
+ tool: content.name,
358
+ input: content.input,
359
+ output: content.state === "completed" ? content.output : undefined,
360
+ error: content.state === "error" ? content.error : undefined,
361
+ };
399
362
  }
400
363
  function buildKnownCategories(counters, contextLimit) {
401
364
  return Object.entries(counters)
@@ -409,17 +372,92 @@ function buildKnownCategories(counters, contextLimit) {
409
372
  }
410
373
  // END_BLOCK_CATEGORY_COUNTING
411
374
  // START_BLOCK_MEASURED_USAGE
412
- function createMeasuredUsage(message, contextLimit) {
413
- const usedTokens = message.tokens.input + message.tokens.cache.read + message.tokens.output;
414
- const normalizedLimit = normalizeContextLimit(contextLimit);
375
+ function createMeasuredUsage(message, activeMessages, selectedModel, contextLimit) {
376
+ const tokens = message.tokens;
377
+ // Absent or entirely malformed usage stays unknown; a report with at least one
378
+ // usable field is surfaced with the unknown fields left undefined.
379
+ if (tokens === undefined)
380
+ return undefined;
381
+ const input = tokens.input;
382
+ const cacheRead = tokens.cacheRead;
383
+ const cacheWrite = tokens.cacheWrite;
384
+ const output = tokens.output;
385
+ const reasoning = tokens.reasoning;
386
+ if ([input, cacheRead, cacheWrite, output, reasoning].every((value) => value === undefined)) {
387
+ return undefined;
388
+ }
389
+ // Pinned native `contextUsage` sums ALL five token fields and ignores a
390
+ // non-positive total; missing fields stay unknown.
391
+ const usedTokens = sumKnown([input, output, reasoning, cacheRead, cacheWrite]);
392
+ if (usedTokens !== undefined && usedTokens <= 0)
393
+ return undefined;
394
+ const matchesSelectedModel = selectedModel !== undefined && sameModelRef(message.model, selectedModel);
395
+ const normalizedLimit = matchesSelectedModel ? normalizeContextLimit(contextLimit) : undefined;
396
+ const relation = compactionRelation(message, activeMessages);
397
+ return {
398
+ ...(usedTokens === undefined ? {} : { usedTokens }),
399
+ ...(normalizedLimit === undefined ? {} : { contextLimit: normalizedLimit }),
400
+ ...(normalizedLimit === undefined || usedTokens === undefined
401
+ ? {}
402
+ : { remainingTokens: Math.max(0, normalizedLimit - usedTokens) }),
403
+ ...(normalizedLimit === undefined || usedTokens === undefined
404
+ ? {}
405
+ : { percentUsed: (usedTokens / normalizedLimit) * 100 }),
406
+ ...(input === undefined ? {} : { inputTokens: input }),
407
+ ...(cacheRead === undefined ? {} : { cacheReadTokens: cacheRead }),
408
+ ...(cacheWrite === undefined ? {} : { cacheWriteTokens: cacheWrite }),
409
+ ...(output === undefined ? {} : { outputTokens: output }),
410
+ ...(reasoning === undefined ? {} : { reasoningTokens: reasoning }),
411
+ model: message.model,
412
+ ...(message.createdAt === undefined ? {} : { reportedAt: message.createdAt }),
413
+ compactionRelation: relation,
414
+ matchesSelectedModel,
415
+ label: measuredLabel(message, matchesSelectedModel, relation),
416
+ };
417
+ }
418
+ /** Temporal relation of a usage report to the latest completed compaction in the active context. */
419
+ function compactionRelation(message, activeMessages) {
420
+ const compaction = findCompactionCutoff(activeMessages);
421
+ if (compaction === undefined)
422
+ return "none";
423
+ const messageIndex = activeMessages.indexOf(message);
424
+ if (messageIndex >= 0)
425
+ return messageIndex > compaction.index ? "after" : "before";
426
+ if (message.createdAt !== undefined && compaction.message.createdAt !== undefined) {
427
+ return message.createdAt >= compaction.message.createdAt ? "after" : "before";
428
+ }
429
+ return "none";
430
+ }
431
+ function measuredLabel(message, matchesSelectedModel, relation) {
432
+ const model = `${message.model.providerID}/${message.model.modelID}${message.model.variant === undefined ? "" : `#${message.model.variant}`}`;
433
+ if (!matchesSelectedModel) {
434
+ return `Latest provider-reported step usage for ${model}, which differs from the selected model; not current occupancy.`;
435
+ }
436
+ if (relation === "before") {
437
+ return "Reported before the most recent compaction; not the resulting post-compaction occupancy.";
438
+ }
439
+ return "Latest provider-reported step usage for the selected model.";
440
+ }
441
+ /** True when two provider/model/variant references refer to the same real selection. */
442
+ export function sameModelRef(left, right) {
443
+ return (left.providerID === right.providerID &&
444
+ left.modelID === right.modelID &&
445
+ (left.variant ?? undefined) === (right.variant ?? undefined));
446
+ }
447
+ function sumKnown(values) {
448
+ let total = 0;
449
+ for (const value of values) {
450
+ if (value === undefined || !Number.isFinite(value))
451
+ return undefined;
452
+ total += value;
453
+ }
454
+ return total;
455
+ }
456
+ function modelFromRef(ref) {
415
457
  return {
416
- usedTokens,
417
- contextLimit: normalizedLimit,
418
- remainingTokens: normalizedLimit === undefined ? undefined : Math.max(0, normalizedLimit - usedTokens),
419
- percentUsed: normalizedLimit === undefined ? undefined : (usedTokens / normalizedLimit) * 100,
420
- inputTokens: message.tokens.input,
421
- cacheReadTokens: message.tokens.cache.read,
422
- outputTokens: message.tokens.output,
458
+ providerID: ref.providerID,
459
+ modelID: ref.modelID,
460
+ ...(ref.variant === undefined ? {} : { variant: ref.variant }),
423
461
  };
424
462
  }
425
463
  function normalizeContextLimit(contextLimit) {
@@ -430,7 +468,7 @@ function normalizeContextLimit(contextLimit) {
430
468
  function findLatestAssistant(messages) {
431
469
  for (let index = messages.length - 1; index >= 0; index -= 1) {
432
470
  const message = messages[index];
433
- if (message?.role === "assistant")
471
+ if (message?.kind === "assistant")
434
472
  return message;
435
473
  }
436
474
  return undefined;
@@ -438,7 +476,7 @@ function findLatestAssistant(messages) {
438
476
  function findLatestUser(messages) {
439
477
  for (let index = messages.length - 1; index >= 0; index -= 1) {
440
478
  const message = messages[index];
441
- if (message?.role === "user")
479
+ if (message?.kind === "user")
442
480
  return message;
443
481
  }
444
482
  return undefined;