@osovv/vv-opencode 2.0.1 → 2.1.0

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 +42 -0
  2. package/README.md +87 -86
  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 +19 -15
  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,46 +1,184 @@
1
1
  // FILE: src/plugins/tool-history-compaction/index.ts
2
- // VERSION: 0.2.0
2
+ // VERSION: 2.1.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Register the tool-history-compaction plugin: load vvoc config, gate on the enabled toggle, and rewrite only the in-memory message copy the model is about to receive via experimental.chat.messages.transform.
5
- // SCOPE: Plugin entry point, config loading, transform hook registration, and disabled no-op.
6
- // DEPENDS: [@opencode-ai/plugin, src/lib/config-layers.ts, src/plugins/tool-history-compaction/config.ts, src/plugins/tool-history-compaction/transform.ts, src/plugins/v2-runtime/index.ts]
7
- // LINKS: [M-PLUGIN-TOOL-HISTORY-COMPACTION]
4
+ // PURPOSE: Register the native tool-history-compaction plugin: acquire the shared snapshot runtime, register the native session context hook unconditionally, and rewrite only the in-memory provider-context copy the model is about to receive, gated per bound family by its immutable captured policy.
5
+ // SCOPE: Native Plugin.define entry, per-family policy resolution from the captured vvoc config (unknown policy compacts nothing), per-request native message-time correlation through the authenticated client's session context, and lifecycle cleanup. No V1 fake SDK, no startup-global toggle, no cross-request time cache (a running turn's stored timestamps can still change), and no mutation of stored session messages or user inputs.
6
+ // DEPENDS: [@opencode/plugin, src/lib/plugin-toggle-config.ts, src/runtime/context.ts, src/runtime/types.ts, src/plugins/tool-history-compaction/config.ts, src/plugins/tool-history-compaction/transform.ts]
7
+ // LINKS: [M-PLUGIN-TOOL-HISTORY-COMPACTION, M-NATIVE-RUNTIME, V-M-PLUGIN-TOOL-HISTORY-COMPACTION]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
10
10
  // END_MODULE_CONTRACT
11
11
  //
12
12
  // START_MODULE_MAP
13
- // ToolHistoryCompactionPlugin - OpenCode plugin that compacts old tool outputs in the replay without touching storage or inputs.
14
- // default - Dual subpath entrypoint: v2 setup() seam plus v1 server() delegating to the named factory.
13
+ // ToolHistoryCompactionPolicy - Resolved per-family compaction policy.
14
+ // ToolHistoryCompactionDiagnostic - Bounded credential-safe diagnostic event.
15
+ // ToolHistoryCompactionPluginOptions - Optional injectable runtime acquisition and diagnostic sink for tests.
16
+ // createToolHistoryCompactionPlugin - Native plugin factory; the default export acquires the real shared runtime.
17
+ // ToolHistoryCompactionPlugin - Default production native tool-history-compaction plugin object.
18
+ // default - Default export alias of ToolHistoryCompactionPlugin.
15
19
  // END_MODULE_MAP
16
20
  //
17
21
  // START_CHANGE_SUMMARY
18
- // LAST_CHANGE: [C-OPENCODE-V2-MIGRATION T-001 - Added the dual subpath entrypoint so the plugin loads under OpenCode v1 via server() and v2 via setup(). Prior: v0.2.0 - Recent-message window, retained-budget fix, and recoverable pruning.]
22
+ // LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-006 attempt 2 - Correlation is re-read per request instead of cached, and logical grouping over the pinned split multi-call representation lives in transform.ts.]
19
23
  // END_CHANGE_SUMMARY
20
- import { loadVvocConfig } from "../../lib/config-layers.js";
21
- import { parseToolHistoryCompactionEntry } from "./config.js";
24
+ import { Plugin } from "@opencode/plugin";
25
+ import { isVvocPluginEnabled } from "../../lib/plugin-toggle-config.js";
26
+ import { acquireNativeSnapshotRuntime, } from "../../runtime/context.js";
27
+ import { parseToolHistoryCompactionEntry, } from "./config.js";
22
28
  import { compactMessages } from "./transform.js";
23
- // START_BLOCK_PLUGIN
24
- export const ToolHistoryCompactionPlugin = async ({ directory }) => {
25
- const vvoc = await loadVvocConfig({ cwd: directory });
26
- const entry = parseToolHistoryCompactionEntry(vvoc.config.plugins?.["tool-history-compaction"]);
27
- if (!entry.enabled)
28
- return {};
29
- return {
30
- "experimental.chat.messages.transform": async (_input, output) => {
31
- compactMessages(output.messages, entry.config);
32
- },
29
+ const MAX_LOG_CHARS = 500;
30
+ // START_BLOCK_LOG
31
+ /** Bounded credential-safe console diagnostic. */
32
+ function createConsoleLog() {
33
+ return (event) => {
34
+ const line = `[tool-history-compaction][${event.level}] ${event.message}`;
35
+ console.error(line.length > MAX_LOG_CHARS ? `${line.slice(0, MAX_LOG_CHARS)}…` : line);
36
+ };
37
+ }
38
+ // END_BLOCK_LOG
39
+ // START_BLOCK_POLICY
40
+ /**
41
+ * Resolve the bound-family compaction policy; never falls back to current or
42
+ * default config. An unbound but staged family is reconciled through native
43
+ * acceptance before a second read. Unknown policy compacts nothing.
44
+ */
45
+ async function resolvePolicy(runtime, sessionID, log) {
46
+ const read = async () => {
47
+ try {
48
+ return await runtime.snapshots.configFor(sessionID);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
33
53
  };
34
- };
35
- // END_BLOCK_PLUGIN
36
- // START_BLOCK_DUAL_SUBPATH_ENTRY
37
- import { defineDualPlugin } from "../v2-runtime/index.js";
38
- import { createV2Adapter } from "../v2-runtime/setup.js";
39
- import { setupToolHistoryCompactionV2 } from "./v2.js";
40
- export default defineDualPlugin({
41
- id: "vvoc.tool-history-compaction",
42
- v1: ToolHistoryCompactionPlugin,
43
- v2: (ctx) => setupToolHistoryCompactionV2(createV2Adapter(ctx)),
44
- });
45
- // END_BLOCK_DUAL_SUBPATH_ENTRY
54
+ let capture = await read();
55
+ if (capture === undefined) {
56
+ try {
57
+ await runtime.snapshots.accept({ sessionID });
58
+ }
59
+ catch {
60
+ // fall through to the second read; absence is unknown policy below
61
+ }
62
+ capture = await read();
63
+ }
64
+ if (capture === undefined)
65
+ return undefined;
66
+ if (!isVvocPluginEnabled(capture.vvoc, "tool-history-compaction"))
67
+ return { enabled: false };
68
+ try {
69
+ const entry = parseToolHistoryCompactionEntry(capture.vvoc.plugins?.["tool-history-compaction"]);
70
+ return { enabled: entry.enabled, config: entry.config };
71
+ }
72
+ catch {
73
+ // A corrupt captured entry is unknown policy, never a silent rewrite with defaults.
74
+ log({ level: "warn", message: "captured compaction config could not be resolved; skipping" });
75
+ return undefined;
76
+ }
77
+ }
78
+ // END_BLOCK_POLICY
79
+ // START_BLOCK_TIMES
80
+ /**
81
+ * Read an epoch-millisecond time from a native session message timestamp. The
82
+ * host's generated client type declares `time.created` as a number, while the
83
+ * decoded Effect `DateTime.Utc` value also exposes epoch milliseconds; accept
84
+ * both so correlation survives either representation.
85
+ */
86
+ function readTimeValue(value) {
87
+ if (typeof value === "number" && Number.isFinite(value))
88
+ return value;
89
+ if (typeof value === "object" && value !== null) {
90
+ const record = value;
91
+ if (typeof record.epochMilliseconds === "number" && Number.isFinite(record.epochMilliseconds)) {
92
+ return record.epochMilliseconds;
93
+ }
94
+ if (typeof record.epochMillis === "number" && Number.isFinite(record.epochMillis)) {
95
+ return record.epochMillis;
96
+ }
97
+ }
98
+ return undefined;
99
+ }
100
+ function readRecencyTime(message) {
101
+ if (typeof message !== "object" || message === null)
102
+ return undefined;
103
+ const time = message.time;
104
+ if (typeof time !== "object" || time === null)
105
+ return undefined;
106
+ const record = time;
107
+ for (const value of [record.completed, record.created, record.streamed]) {
108
+ const parsed = readTimeValue(value);
109
+ if (parsed !== undefined)
110
+ return parsed;
111
+ }
112
+ return undefined;
113
+ }
114
+ /**
115
+ * Correlate native stored-message recency by message id. The dispatched AI
116
+ * context carries no time, so the authenticated client's `session.context`
117
+ * (the same post-compaction history the request was built from) supplies the
118
+ * trustworthy id-to-time mapping. The read is fresh on every request because a
119
+ * running turn's stored timestamps can still change. Failures degrade to no
120
+ * correlation, which falls back to deterministic array-position ordering.
121
+ */
122
+ async function fetchMessageTimes(runtime, sessionID) {
123
+ const times = new Map();
124
+ try {
125
+ const client = await runtime.client();
126
+ const messages = await client.session.context({ sessionID });
127
+ for (const message of messages) {
128
+ if (typeof message !== "object" || message === null)
129
+ continue;
130
+ const id = message.id;
131
+ if (typeof id !== "string")
132
+ continue;
133
+ const time = readRecencyTime(message);
134
+ if (time !== undefined)
135
+ times.set(id, time);
136
+ }
137
+ }
138
+ catch {
139
+ // Unavailable correlation degrades to no times; callers use array order.
140
+ }
141
+ return times;
142
+ }
143
+ // END_BLOCK_TIMES
144
+ // START_BLOCK_PLUGIN_ENTRY
145
+ /** Native plugin factory; the default export acquires the real shared runtime. */
146
+ export function createToolHistoryCompactionPlugin(options = {}) {
147
+ return Plugin.define({
148
+ id: "vvoc.tool-history-compaction",
149
+ setup: async (ctx) => {
150
+ const acquire = options.acquireRuntime ?? ((c) => acquireNativeSnapshotRuntime(c));
151
+ const runtime = await acquire(ctx);
152
+ const log = options.log ?? createConsoleLog();
153
+ const registration = await ctx.session.hook("context", async (event) => {
154
+ try {
155
+ const policy = await resolvePolicy(runtime, String(event.sessionID), log);
156
+ if (policy === undefined || !policy.enabled)
157
+ return;
158
+ const messages = event.messages;
159
+ if (!Array.isArray(messages) || messages.length === 0)
160
+ return;
161
+ const sessionID = String(event.sessionID);
162
+ const times = await fetchMessageTimes(runtime, sessionID);
163
+ compactMessages(messages, policy.config, times);
164
+ }
165
+ catch (error) {
166
+ // Compaction must never fail a request; report a bounded diagnostic only.
167
+ log({
168
+ level: "warn",
169
+ message: "compaction pass failed",
170
+ extra: { error: error instanceof Error ? error.name : typeof error },
171
+ });
172
+ }
173
+ });
174
+ return async () => {
175
+ await registration.dispose();
176
+ await runtime.release();
177
+ };
178
+ },
179
+ });
180
+ }
181
+ export const ToolHistoryCompactionPlugin = createToolHistoryCompactionPlugin();
182
+ export default ToolHistoryCompactionPlugin;
183
+ // END_BLOCK_PLUGIN_ENTRY
46
184
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/plugins/tool-history-compaction/index.ts"],"names":[],"mappings":"AAAA,qDAAqD;AACrD,iBAAiB;AACjB,wBAAwB;AACxB,4NAA4N;AAC5N,gGAAgG;AAChG,+LAA+L;AAC/L,8CAA8C;AAC9C,kBAAkB;AAClB,sBAAsB;AACtB,sBAAsB;AACtB,EAAE;AACF,mBAAmB;AACnB,mIAAmI;AACnI,yGAAyG;AACzG,iBAAiB;AACjB,EAAE;AACF,uBAAuB;AACvB,iPAAiP;AACjP,qBAAqB;AAGrB,OAAO,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,KAAK,CAAC,QAAQ,CAAC;oBAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;wBAAE,OAAO;oBAC9D,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;oBAC1C,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;oBAC1D,eAAe,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;gBAClD,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,0EAA0E;oBAC1E,GAAG,CAAC;wBACF,KAAK,EAAE,MAAM;wBACb,OAAO,EAAE,wBAAwB;wBACjC,KAAK,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,KAAK,EAAE;qBACrE,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,OAAO,KAAK,IAAI,EAAE;gBAChB,MAAM,YAAY,CAAC,OAAO,EAAE,CAAC;gBAC7B,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;YAC1B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,2BAA2B,GAAkB,iCAAiC,EAAE,CAAC;AAC9F,eAAe,2BAA2B,CAAC;AAC3C,yBAAyB"}
@@ -1,25 +1,56 @@
1
- import type { Part } from "@opencode-ai/sdk";
1
+ import type { Message } from "@opencode/ai";
2
2
  import type { ToolHistoryCompactionConfig } from "./config.js";
3
+ /**
4
+ * Structural mutable view of one native AI message. The native hook delivers
5
+ * `@opencode/ai` `Message` instances whose schema-derived types are readonly;
6
+ * the event contract is to mutate them in place, so the transform works on this
7
+ * documented structural view and never changes structure or ordering.
8
+ */
3
9
  export interface TransformMessage {
4
- info: unknown;
5
- parts: Part[];
10
+ id?: string | undefined;
11
+ content: TransformContentPart[];
12
+ }
13
+ /** Structural mutable view of one native content part; only tool-call/tool-result parts are inspected. */
14
+ export interface TransformContentPart {
15
+ type: string;
16
+ id?: unknown;
17
+ name?: unknown;
18
+ input?: unknown;
19
+ result?: unknown;
20
+ }
21
+ /** Structural mutable view of one native completed textual tool result. */
22
+ export interface TransformToolResultPart extends TransformContentPart {
23
+ type: "tool-result";
24
+ id: string;
25
+ name: string;
26
+ result: {
27
+ type: "text";
28
+ value: unknown;
29
+ } & Record<string, unknown>;
6
30
  }
7
31
  /**
8
- * Compute the indices of the newest `count` messages by recency time.
9
- * Ties are broken by array position (later index wins); messages without
10
- * usable times fall back to array-position ordering so the newest entries are
11
- * still selected deterministically.
12
- * @param messages - the transform hook's message list.
13
- * @param count - how many newest messages to protect; 0 or negative disables the window.
14
- * @returns the set of protected message indices.
32
+ * Compute the physical indices of the newest `count` logical source messages by
33
+ * correlated recency time. Each id-bearing native row is one logical source
34
+ * message; id-less tool-result children join their source row by the real native
35
+ * call id, so a turn with multiple results counts once and all of its physical
36
+ * rows are protected together. Groups without a correlated time fall back to
37
+ * array-position ordering (later source row wins) so the newest entries are
38
+ * still selected deterministically. Rows with no resolvable source identity are
39
+ * always protected. Never fabricates a time.
40
+ * @param messages - the native hook's message list.
41
+ * @param count - how many newest logical messages to protect; 0 or negative disables the window.
42
+ * @param times - native source message id to recency time in epoch milliseconds.
43
+ * @returns the set of protected physical message indices.
15
44
  */
16
- export declare function recentMessageIndexes(messages: TransformMessage[], count: number): Set<number>;
45
+ export declare function recentMessageIndexes(messages: Message[] | TransformMessage[], count: number, times?: ReadonlyMap<string, number> | undefined): Set<number>;
17
46
  /**
18
- * Deterministically rewrite eligible tool part outputs in place.
47
+ * Deterministically rewrite eligible native tool result text in place.
19
48
  * Model-agnostic: the current model is not needed. Non-destructive to inputs,
20
- * part structure, and ordering. Idempotent: already-compacted parts are skipped
21
- * by their markers, so a second pass is a no-op.
22
- * @param messages - the transform hook's in-memory message list.
49
+ * content structure, part ordering, and non-textual or already-compacted
50
+ * results. Idempotent: marker-carrying text is skipped, so a second pass is a
51
+ * no-op.
52
+ * @param messages - the native context hook's in-memory message list.
23
53
  * @param config - resolved compaction config.
54
+ * @param times - native message id to recency time in epoch milliseconds.
24
55
  */
25
- export declare function compactMessages(messages: TransformMessage[], config: ToolHistoryCompactionConfig): void;
56
+ export declare function compactMessages(messages: Message[], config: ToolHistoryCompactionConfig, times?: ReadonlyMap<string, number> | undefined): void;
@@ -1,113 +1,229 @@
1
1
  // FILE: src/plugins/tool-history-compaction/transform.ts
2
- // VERSION: 0.2.0
2
+ // VERSION: 2.0.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Apply tool-history compaction to the in-memory message list the model is about to receive: compute an absolute recent-message window from message recency times, walk messages newest-first, dispatch retained/read/other tools to the right compaction layer, persist full pruned outputs for recoverable markers, and mutate only completed tool part outputs.
5
- // SCOPE: Recency-time window computation, completed-tool-part detection, per-call protection accounting outside the window, retention dispatch, read-slim and prune application, optional disk-backed prune recovery, and idempotent in-place output rewrites.
6
- // DEPENDS: [src/plugins/tool-history-compaction/config.ts, src/plugins/tool-history-compaction/retention.ts, src/plugins/tool-history-compaction/prune.ts, src/plugins/tool-history-compaction/read-slim.ts, src/plugins/tool-history-compaction/saved-output.ts]
7
- // LINKS: [M-PLUGIN-TOOL-HISTORY-COMPACTION]
4
+ // PURPOSE: Apply tool-history compaction to the native provider-context message list the model is about to receive: compute an absolute recent-message window from correlated native message recency times, walk messages newest-first, dispatch retained/read/other tools to the right compaction layer, persist full pruned outputs for recoverable markers, and rewrite only eligible completed textual tool results.
5
+ // SCOPE: Recency-time window computation over native AI messages with preceding-message inheritance, completed textual tool-result detection, per-call protection accounting outside the window, retention dispatch, read-slim and prune application, optional disk-backed prune recovery, and idempotent in-place result rewrites that never touch stored storage, inputs, structure, order, opaque/media/JSON result fields, or non-textual results.
6
+ // DEPENDS: [@opencode/ai, src/plugins/tool-history-compaction/config.ts, src/plugins/tool-history-compaction/retention.ts, src/plugins/tool-history-compaction/prune.ts, src/plugins/tool-history-compaction/read-slim.ts, src/plugins/tool-history-compaction/saved-output.ts]
7
+ // LINKS: [M-PLUGIN-TOOL-HISTORY-COMPACTION, V-M-PLUGIN-TOOL-HISTORY-COMPACTION]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
10
10
  // END_MODULE_CONTRACT
11
11
  //
12
12
  // START_MODULE_MAP
13
- // TransformMessage - One message entry in the transform hook output.
14
- // recentMessageIndexes - Indices of the newest messages by recency time (array-position tie-break and fallback).
15
- // compactMessages - Deterministically rewrite eligible tool part outputs in place.
13
+ // TransformMessage - Structural mutable view of one native AI message used for in-place rewriting.
14
+ // TransformContentPart - Structural mutable view of one native content part inspected by the transform.
15
+ // TransformToolResultPart - Structural mutable view of one native completed textual tool result.
16
+ // recentMessageIndexes - Indices of the newest native messages by correlated recency time (preceding-message inheritance and array-position fallback).
17
+ // compactMessages - Deterministically rewrite eligible native tool result text in place.
16
18
  // END_MODULE_MAP
17
19
  //
18
20
  // START_CHANGE_SUMMARY
19
- // LAST_CHANGE: [v0.2.0 - Added recency-time recent-message window, fixed retained-tool budget leak, and added recoverable disk-backed pruning.]
21
+ // LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-006 - Ported the V1 experimental.chat.messages.transform over SDK parts to native @opencode/ai Message/ToolResultPart content, rewriting only completed textual tool results and correlating stored message recency by native message id.]
20
22
  // END_CHANGE_SUMMARY
21
23
  import { pruneOutput } from "./prune.js";
22
24
  import { slimReadOutput } from "./read-slim.js";
23
25
  import { isRetainedTool } from "./retention.js";
24
26
  import { savePrunedOutputOnce } from "./saved-output.js";
25
- function isCompletedToolPart(part) {
26
- return part.type === "tool" && part.state.status === "completed";
27
+ // END_BLOCK_TYPES
28
+ // START_BLOCK_GUARDS
29
+ function asMessages(messages) {
30
+ // The native hook hands mutable instances; the readonly schema view is a
31
+ // type-level constraint only. No structure is changed by this view.
32
+ return messages;
27
33
  }
28
- function isCompactedByOpencode(part) {
29
- const time = part.state.time;
30
- return (typeof time === "object" && time !== null && "compacted" in time && time.compacted !== undefined);
34
+ function isToolResult(part) {
35
+ if (part.type !== "tool-result")
36
+ return false;
37
+ if (typeof part.id !== "string" || typeof part.name !== "string")
38
+ return false;
39
+ const result = part.result;
40
+ if (typeof result !== "object" || result === null)
41
+ return false;
42
+ const record = result;
43
+ return record.type === "text" && typeof record.value === "string";
44
+ }
45
+ /**
46
+ * Index every native tool-call input by call id. Native tool-result parts do
47
+ * not carry the call input, so read-slim recovers the file from the matching
48
+ * tool-call part within the same dispatched context.
49
+ */
50
+ function indexToolCalls(messages) {
51
+ const calls = new Map();
52
+ for (const message of messages) {
53
+ if (!Array.isArray(message.content))
54
+ continue;
55
+ for (const part of message.content) {
56
+ if (part.type !== "tool-call")
57
+ continue;
58
+ if (typeof part.id !== "string" || typeof part.name !== "string")
59
+ continue;
60
+ calls.set(part.id, { name: part.name, input: part.input });
61
+ }
62
+ }
63
+ return calls;
31
64
  }
32
65
  function isReadTool(tool) {
33
66
  return tool.toLowerCase() === "read";
34
67
  }
35
- function messageRecencyTime(message) {
36
- const info = message?.info;
37
- const time = info?.time;
38
- return time?.completed ?? time?.created ?? Number.NEGATIVE_INFINITY;
68
+ /** Native call/result ids carried by one content row. */
69
+ function extractCallIds(message) {
70
+ const ids = [];
71
+ if (!Array.isArray(message.content))
72
+ return ids;
73
+ for (const part of message.content) {
74
+ if (part.type !== "tool-call" && part.type !== "tool-result")
75
+ continue;
76
+ if (typeof part.id === "string" && part.id.length > 0)
77
+ ids.push(part.id);
78
+ }
79
+ return ids;
80
+ }
81
+ /**
82
+ * Collapse physical protocol rows into logical source messages. The pinned host
83
+ * translator emits one id-bearing assistant row containing tool calls followed
84
+ * by separate id-less `Message.tool(result)` children, so children are joined to
85
+ * their source row by the native tool call/result id. Rows whose source identity
86
+ * cannot be established are reported as unknown and are never compacted
87
+ * (fail-safe: an unrecognized row may still be protected knowledge).
88
+ */
89
+ function buildLogicalGroups(messages, times) {
90
+ const groups = new Map();
91
+ const callToKey = new Map();
92
+ const pending = [];
93
+ const unknown = new Set();
94
+ const ensure = (key) => {
95
+ const existing = groups.get(key);
96
+ if (existing !== undefined)
97
+ return existing;
98
+ const created = {
99
+ key,
100
+ indices: [],
101
+ recency: Number.NEGATIVE_INFINITY,
102
+ maxIndex: -1,
103
+ };
104
+ groups.set(key, created);
105
+ return created;
106
+ };
107
+ messages.forEach((message, index) => {
108
+ const callIds = extractCallIds(message);
109
+ const id = message.id;
110
+ if (typeof id === "string") {
111
+ const key = `msg:${id}`;
112
+ const group = ensure(key);
113
+ group.indices.push(index);
114
+ group.maxIndex = Math.max(group.maxIndex, index);
115
+ const time = times?.get(id);
116
+ if (typeof time === "number" && Number.isFinite(time)) {
117
+ group.recency = Math.max(group.recency, time);
118
+ }
119
+ for (const callId of callIds)
120
+ callToKey.set(callId, key);
121
+ return;
122
+ }
123
+ pending.push({ index, callIds });
124
+ });
125
+ for (const { index, callIds } of pending) {
126
+ let key;
127
+ for (const callId of callIds) {
128
+ const found = callToKey.get(callId);
129
+ if (found !== undefined) {
130
+ key = found;
131
+ break;
132
+ }
133
+ }
134
+ if (key === undefined) {
135
+ // No id and no resolvable source call: unknown identity, never compacted.
136
+ unknown.add(index);
137
+ continue;
138
+ }
139
+ const group = ensure(key);
140
+ group.indices.push(index);
141
+ group.maxIndex = Math.max(group.maxIndex, index);
142
+ }
143
+ return { groups: [...groups.values()], unknown };
39
144
  }
145
+ // END_BLOCK_LOGICAL_GROUPS
146
+ // START_BLOCK_WINDOW
40
147
  /**
41
- * Compute the indices of the newest `count` messages by recency time.
42
- * Ties are broken by array position (later index wins); messages without
43
- * usable times fall back to array-position ordering so the newest entries are
44
- * still selected deterministically.
45
- * @param messages - the transform hook's message list.
46
- * @param count - how many newest messages to protect; 0 or negative disables the window.
47
- * @returns the set of protected message indices.
148
+ * Compute the physical indices of the newest `count` logical source messages by
149
+ * correlated recency time. Each id-bearing native row is one logical source
150
+ * message; id-less tool-result children join their source row by the real native
151
+ * call id, so a turn with multiple results counts once and all of its physical
152
+ * rows are protected together. Groups without a correlated time fall back to
153
+ * array-position ordering (later source row wins) so the newest entries are
154
+ * still selected deterministically. Rows with no resolvable source identity are
155
+ * always protected. Never fabricates a time.
156
+ * @param messages - the native hook's message list.
157
+ * @param count - how many newest logical messages to protect; 0 or negative disables the window.
158
+ * @param times - native source message id to recency time in epoch milliseconds.
159
+ * @returns the set of protected physical message indices.
48
160
  */
49
- export function recentMessageIndexes(messages, count) {
161
+ export function recentMessageIndexes(messages, count, times) {
50
162
  const result = new Set();
51
163
  if (count <= 0 || messages.length === 0)
52
164
  return result;
53
- const ranked = messages
54
- .map((message, index) => ({ index, recency: messageRecencyTime(message) }))
55
- .sort((a, b) => {
165
+ const { groups, unknown } = buildLogicalGroups(messages, times);
166
+ for (const index of unknown)
167
+ result.add(index);
168
+ const ranked = groups.slice().sort((a, b) => {
56
169
  if (b.recency !== a.recency)
57
170
  return b.recency - a.recency;
58
- return b.index - a.index;
171
+ return b.maxIndex - a.maxIndex;
59
172
  });
60
173
  const take = Math.min(count, ranked.length);
61
174
  for (let k = 0; k < take; k++) {
62
- const entry = ranked[k];
63
- if (entry)
64
- result.add(entry.index);
175
+ const group = ranked[k];
176
+ if (!group)
177
+ continue;
178
+ for (const index of group.indices)
179
+ result.add(index);
65
180
  }
66
181
  return result;
67
182
  }
68
183
  // END_BLOCK_WINDOW
69
184
  // START_BLOCK_COMPACT
70
185
  /**
71
- * Deterministically rewrite eligible tool part outputs in place.
186
+ * Deterministically rewrite eligible native tool result text in place.
72
187
  * Model-agnostic: the current model is not needed. Non-destructive to inputs,
73
- * part structure, and ordering. Idempotent: already-compacted parts are skipped
74
- * by their markers, so a second pass is a no-op.
75
- * @param messages - the transform hook's in-memory message list.
188
+ * content structure, part ordering, and non-textual or already-compacted
189
+ * results. Idempotent: marker-carrying text is skipped, so a second pass is a
190
+ * no-op.
191
+ * @param messages - the native context hook's in-memory message list.
76
192
  * @param config - resolved compaction config.
193
+ * @param times - native message id to recency time in epoch milliseconds.
77
194
  */
78
- export function compactMessages(messages, config) {
195
+ export function compactMessages(messages, config, times) {
196
+ const view = asMessages(messages);
197
+ const calls = indexToolCalls(view);
79
198
  // The newest message is always protected; protectRecentMessages widens the window.
80
199
  const windowSize = Math.max(1, config.protectRecentMessages);
81
- const protectedMessages = recentMessageIndexes(messages, windowSize);
200
+ const protectedMessages = recentMessageIndexes(view, windowSize, times);
82
201
  let remainingProtection = config.protectLastCalls;
83
- for (let i = messages.length - 1; i >= 0; i--) {
84
- const message = messages[i];
85
- if (!message)
202
+ for (let i = view.length - 1; i >= 0; i--) {
203
+ const message = view[i];
204
+ if (!message || !Array.isArray(message.content))
86
205
  continue;
87
206
  const withinWindow = protectedMessages.has(i);
88
- for (let j = message.parts.length - 1; j >= 0; j--) {
89
- const part = message.parts[j];
90
- if (!part || part.type !== "tool")
91
- continue;
92
- if (!isCompletedToolPart(part))
93
- continue;
94
- if (isCompactedByOpencode(part))
207
+ for (let j = message.content.length - 1; j >= 0; j--) {
208
+ const part = message.content[j];
209
+ if (!part || !isToolResult(part))
95
210
  continue;
96
211
  // Absolute recent-message window: nothing inside the newest messages is rewritten.
97
212
  if (withinWindow)
98
213
  continue;
99
214
  // Retained tools are never compacted and do not consume the per-call budget.
100
- if (isRetainedTool(part.tool, config.retainTools))
215
+ if (isRetainedTool(part.name, config.retainTools))
101
216
  continue;
102
217
  // Per-call protection budget applies only to compaction-eligible parts outside the window.
103
218
  if (remainingProtection > 0) {
104
219
  remainingProtection -= 1;
105
220
  continue;
106
221
  }
107
- const output = part.state.output;
222
+ const output = part.result.value;
223
+ const input = calls.get(part.id)?.input;
108
224
  let rewritten;
109
- if (config.readSlim && isReadTool(part.tool)) {
110
- const slim = slimReadOutput(part.state.input, output, config);
225
+ if (config.readSlim && isReadTool(part.name)) {
226
+ const slim = slimReadOutput(input, output, config);
111
227
  if (slim) {
112
228
  rewritten = slim.output;
113
229
  }
@@ -121,7 +237,7 @@ export function compactMessages(messages, config) {
121
237
  const basePruned = pruneOutput(output, config);
122
238
  if (basePruned) {
123
239
  if (config.savePrunedOutput) {
124
- const savedPath = savePrunedOutputOnce(output, part.callID);
240
+ const savedPath = savePrunedOutputOnce(output, part.id);
125
241
  if (savedPath) {
126
242
  const recoverable = pruneOutput(output, config, savedPath);
127
243
  rewritten = recoverable ? recoverable.output : basePruned.output;
@@ -136,7 +252,9 @@ export function compactMessages(messages, config) {
136
252
  }
137
253
  }
138
254
  if (rewritten !== undefined && rewritten !== output) {
139
- part.state.output = rewritten;
255
+ // Rewrite only the textual result value; structure, id, name, input,
256
+ // ordering, and every opaque/media/JSON field stay untouched.
257
+ part.result.value = rewritten;
140
258
  }
141
259
  }
142
260
  }