@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,50 +1,51 @@
1
1
  // FILE: src/plugins/hashline-edit/index.ts
2
- // VERSION: 0.10.0
2
+ // VERSION: 2.0.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Route per-model edit tooling: register hashline_edit and dsh str_replace_editor from the single-source contracts, publish their strict input JSON Schemas, validate owned-tool arguments at the hook and direct entries, resolve the session edit mode from vvoc routing config, expose exactly one edit tool per model (the host built-in edit/apply_patch for their cohorts, the plugin profiles otherwise), and transform read output with anchors for hashline sessions.
5
- // SCOPE: Routing config loading, session model/file caches, chat.message tool-visibility mutation, a shared per-session model visibility guard applied first by both the tool.execute.before hook and every registered execute entry, owned tool.definition publication plus structural/branch argument guards, routed read transformation, hashline/str_replace_editor execution through the schema validators and normalizer, bounded post-edit diff feedback, and editMode telemetry metadata with a bounded reporting-failure distinction that never echoes the thrown message and never misreports an applied edit as invalid or pristine.
6
- // DEPENDS: [@opencode-ai/plugin, node:fs/promises, node:path, src/lib/agent-tool-contract.ts, src/lib/config-layers.ts, src/plugins/hashline-edit/diff-summary.ts, src/plugins/hashline-edit/edit-operations.ts, src/plugins/hashline-edit/file-text-canonicalization.ts, src/plugins/hashline-edit/hash-computation.ts, src/plugins/hashline-edit/normalize-edits.ts, src/plugins/hashline-edit/routing.ts, src/plugins/hashline-edit/schemas.ts, src/plugins/hashline-edit/session-state.ts, src/plugins/hashline-edit/str-replace-editor.ts, src/plugins/hashline-edit/validation.ts, src/plugins/v2-runtime/index.ts]
7
- // LINKS: [M-PLUGIN-HASHLINE-EDIT, M-AGENT-TOOL-CONTRACT]
4
+ // PURPOSE: Route per-model native edit tooling: register hashline_edit and str_replace_editor as native OpenCode 2.0.18 tools, resolve the session edit mode from the captured vvoc routing config, expose exactly one plugin edit tool per actual session model (never touching the host edit/patch contracts), require a native resource permission before any write, and transform native read results with true line anchors and freshness tracking.
5
+ // SCOPE: Native Plugin.define entry, per-bound-family captured routing resolution, session model capture from native context/model.request hooks, native session context tool-list visibility enforcement, execute.before visibility/structural guards, execute.after read-anchor transformation and freshness recording, native tool execution with awaited permission before mutation and respected caller abort, bounded post-edit metadata reporting, and editMode telemetry. Pure edit algorithms, anchors, encoding, normalization, and error semantics are unchanged. No V1 chat.message/tool.execute hooks, no V1 tool()/ToolContext.
6
+ // DEPENDS: [@opencode/plugin, @opencode/plugin/promise/tool, effect (Schema.toJsonSchemaDocument; direct dep T009), zod, zod/v4/core, node:fs/promises, node:path, src/lib/agent-tool-contract.ts, src/plugins/hashline-edit/diff-summary.ts, src/plugins/hashline-edit/edit-operations.ts, src/plugins/hashline-edit/file-text-canonicalization.ts, src/plugins/hashline-edit/hash-computation.ts, src/plugins/hashline-edit/normalize-edits.ts, src/plugins/hashline-edit/routing.ts, src/plugins/hashline-edit/schemas.ts, src/plugins/hashline-edit/session-state.ts, src/plugins/hashline-edit/str-replace-editor.ts, src/plugins/hashline-edit/validation.ts, src/runtime/context.ts]
7
+ // LINKS: [M-PLUGIN-HASHLINE-EDIT, M-AGENT-TOOL-CONTRACT, M-NATIVE-RUNTIME, V-M-PLUGIN-HASHLINE-EDIT]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
10
10
  // END_MODULE_CONTRACT
11
11
  //
12
12
  // START_MODULE_MAP
13
- // HashlineEditPlugin - Registers routed edit tools (hashline_edit, str_replace_editor), per-model tool visibility, owned contract hooks, and the routed read-output enhancer.
14
- // default - Dual subpath entrypoint: v2 setup() seam plus v1 server() delegating to the named factory.
15
- // EDIT_VISIBILITY_TOOLS - Edit tool ids whose visibility routing manages.
16
- // isEditTypeTool - Type guard for the two owned edit tool ids.
17
- // visibleToolsForMode - Edit tools visible for one edit mode.
18
- // assertEditToolVisible - Deny a hidden edit tool for a session before argument detail.
19
- // statSnapshot - File stat snapshot for the session file cache.
20
- // isReadTool - Read tool id guard.
21
- // isHashlineEligibleReadOutput - Guard for read outputs worth transforming.
22
- // readArgFilePath - FilePath extraction from read tool arguments.
23
- // readSourceLines - Source lines for read arguments when available.
24
- // transformReadOutput - Routed read transformation with anchors.
25
- // executeHashlineEdit - Owned hashline_edit executor.
26
- // executeStrReplaceEditor - Owned str_replace_editor executor.
27
- // default - Dual subpath entrypoint: v2 setup() seam plus v1 server() delegating to the named factory.
13
+ // nativeToolJsonSchema - Serialize a genuine native tool input ValueSchema to JSON Schema via public SDK APIs.
14
+ // captureNativeToolDefinitions - Capture genuine activated native tool definitions into a map.
15
+ // HashlinePermissionGuard - Narrow native resource-permission guard awaited before writes.
16
+ // HashlineEditDependencies - Injectable per-family routing settings, permission guard and diagnostics.
17
+ // HashlineEditHandlers - Native session/tool hook handlers plus the two native tool infos.
18
+ // HashlineEditRegistration - Handlers plus cleanup-owning dispose.
19
+ // createHashlineEditHandlers - Build routing state, native hook handlers and the two tool infos.
20
+ // HashlineEditPluginOptions - Optional injectable runtime acquisition for tests.
21
+ // createHashlineEditPlugin - Native plugin factory; the default export acquires the real shared runtime.
22
+ // HashlineEditPlugin - Default production native hashline-edit plugin object.
23
+ // default - Default export alias of HashlineEditPlugin.
28
24
  // END_MODULE_MAP
29
25
  //
30
26
  // START_CHANGE_SUMMARY
31
- // 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: C-AGENT-TOOL-CONTRACTS T-005 - Registered both edit tools from schemas.ts, published the strict input JSON Schema through tool.definition, added owned argument validation after the existing visibility denial and at direct entries, and narrowed post-write metadata reporting failures without changing literal edit, routing, or anchor semantics.]
27
+ // LAST_CHANGE: [T-009 - Detects genuine Effect Schema codecs via Schema.isSchema before the isPlainRecord gate in nativeToolJsonSchema, so a callable effect@4 codec is converted through Schema.toJsonSchemaDocument instead of being rejected as non-plain-record.]
32
28
  // END_CHANGE_SUMMARY
33
- import { tool } from "@opencode-ai/plugin";
34
- import { resolve } from "node:path";
29
+ import { Plugin } from "@opencode/plugin";
30
+ import { Schema } from "effect";
31
+ import { z } from "zod";
32
+ import { $ZodType, toJSONSchema } from "zod/v4/core";
33
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
34
+ import { existsSync } from "node:fs";
35
+ import { homedir } from "node:os";
35
36
  import { readFile, readdir, stat, writeFile } from "node:fs/promises";
36
- import { ContractInputError, createToolDefinitionAdapter, formatContractIssues, } from "../../lib/agent-tool-contract.js";
37
+ import { acquireNativeSnapshotRuntime, } from "../../runtime/context.js";
38
+ import { ContractInputError, formatContractIssues } from "../../lib/agent-tool-contract.js";
37
39
  import { findFirstChangedLine, summarizeEditDiff } from "./diff-summary.js";
38
40
  import { applyHashlineEditsWithReport } from "./edit-operations.js";
39
41
  import { canonicalizeFileText, restoreFileText } from "./file-text-canonicalization.js";
40
42
  import { computeAnchorHash, computeLineHash } from "./hash-computation.js";
41
43
  import { normalizeHashlineEdits } from "./normalize-edits.js";
42
44
  import { parseHashlineEditPluginEntry, resolveEditMode, } from "./routing.js";
43
- import { editToolContracts, hashlineEditArgs, hashlineEditContract, strReplaceEditorArgs, strReplaceEditorContract, validateHashlineEditToolInput, validateStrReplaceEditorToolInput, } from "./schemas.js";
45
+ import { hashlineEditContract, strReplaceEditorContract, validateHashlineEditToolInput, validateStrReplaceEditorToolInput, } from "./schemas.js";
44
46
  import { SessionFileCache, SessionModelCache } from "./session-state.js";
45
47
  import { StrReplaceEditor, } from "./str-replace-editor.js";
46
48
  import { HashlineMismatchError } from "./validation.js";
47
- import { loadVvocConfig } from "../../lib/config-layers.js";
48
49
  const CONTENT_OPEN_TAG = "<content>";
49
50
  const CONTENT_CLOSE_TAG = "</content>";
50
51
  const FILE_OPEN_TAG = "<file>";
@@ -53,50 +54,195 @@ const OPENCODE_LINE_TRUNCATION_SUFFIX = "... (line truncated to 2000 chars)";
53
54
  const COLON_READ_LINE_PATTERN = /^\s*(\d+): ?(.*)$/;
54
55
  const PIPE_READ_LINE_PATTERN = /^\s*(\d+)\| ?(.*)$/;
55
56
  // START_BLOCK_ROUTING_CONSTANTS
56
- // Edit tools whose visibility chat.message manages. Includes the host
57
- // built-in `edit` so deepseek/hashline cohorts see exactly one edit tool;
58
- // `apply_patch` is deliberately absent (its visibility is owned by the host
59
- // gate and never forced by this plugin).
60
- export const EDIT_VISIBILITY_TOOLS = ["hashline_edit", "edit", "str_replace_editor"];
61
- // Plugin-owned edit tools only. The host built-in edit/apply_patch are never
62
- // registered or blocked by this plugin; they serve the `edit`/`apply_patch`
63
- // routing modes with their native behavior.
57
+ // Native tools whose definitions the plugin may capture/restore.
58
+ const NATIVE_TOOL_NAMES = [
59
+ "hashline_edit",
60
+ "str_replace_editor",
61
+ "edit",
62
+ "write",
63
+ "patch",
64
+ ];
65
+ // Existing-file editor tools whose visibility the selected mode governs. Native
66
+ // `write` is deliberately absent: baseline v1.7.0 never hid it, so new-file
67
+ // creation stays available alongside the one selected existing-file editor.
68
+ const HIDDEN_MODE_TOOLS = ["hashline_edit", "str_replace_editor", "edit", "patch"];
69
+ // Native edit tools whose EXECUTION the mode enforces. `write` is always allowed
70
+ // (creation), matching the baseline.
71
+ const MANAGED_NATIVE_TOOLS = new Set(["edit", "patch"]);
64
72
  const EDIT_TYPE_TOOLS = ["hashline_edit", "str_replace_editor"];
65
- export function isEditTypeTool(toolName) {
73
+ function isEditTypeTool(toolName) {
66
74
  return EDIT_TYPE_TOOLS.includes(toolName);
67
75
  }
68
- export function visibleToolsForMode(mode) {
76
+ /**
77
+ * Tools that must be visible for a mode; canonical `apply_patch` maps to native
78
+ * `patch` once. Native `write` stays for every mode except `apply_patch` (where
79
+ * the native patch plugin itself owns file creation), preserving baseline
80
+ * new-file creation next to the selected existing-file editor.
81
+ */
82
+ function visibleToolsForMode(mode) {
69
83
  switch (mode) {
70
84
  case "hashline_edit":
71
- return ["hashline_edit"];
85
+ return ["hashline_edit", "write"];
72
86
  case "str_replace_editor":
73
- return ["str_replace_editor"];
74
- // The host owns these tools; the plugin exposes none of its own edit
75
- // tools for `edit` (built-in edit stays visible) and `apply_patch`
76
- // (the host gate shows it to gpt/codex cohorts).
87
+ return ["str_replace_editor", "write"];
77
88
  case "edit":
89
+ return ["edit", "write"];
78
90
  case "apply_patch":
79
- return [];
91
+ return ["patch"];
80
92
  }
81
93
  }
94
+ function isNativeToolDefinition(value) {
95
+ return (typeof value === "object" &&
96
+ value !== null &&
97
+ typeof value.description === "string" &&
98
+ "input" in value);
99
+ }
100
+ function isPlainRecord(value) {
101
+ return typeof value === "object" && value !== null && !Array.isArray(value);
102
+ }
82
103
  /**
83
- * Shared per-session model visibility guard. Both the tool.execute.before hook
84
- * and every registered execute entry use it, so a directly invoked registered
85
- * tool cannot bypass the model routing the hook enforces. It resolves only the
86
- * session's cached model identity and performs no argument inspection, filesystem
87
- * access, cache update, or metadata report.
104
+ * Serialize a genuine registered native tool input ValueSchema to JSON Schema
105
+ * using only public SDK/Effect APIs, mirroring the pinned host projection.
106
+ * Effect Schema codecs are detected first because an Effect codec is a callable
107
+ * value, not a plain record; the plain-record gate below applies only to the
108
+ * Standard JSON Schema (`~standard.jsonSchema.input`), Zod (`zod/v4/core`) and
109
+ * literal JSON schema shapes.
88
110
  */
89
- export function assertEditToolVisible(toolName, sessionID, resolveMode) {
90
- const mode = resolveMode(sessionID);
91
- const visible = visibleToolsForMode(mode);
92
- if (visible.includes(toolName)) {
93
- return;
111
+ export function nativeToolJsonSchema(input) {
112
+ if (input === undefined || input === null)
113
+ return undefined;
114
+ if (Schema.isSchema(input)) {
115
+ const document = Schema.toJsonSchemaDocument(input);
116
+ const schema = document.schema;
117
+ const definitions = document.definitions;
118
+ return definitions !== undefined && Object.keys(definitions).length > 0
119
+ ? { ...schema, $defs: definitions }
120
+ : schema;
94
121
  }
95
- const preferred = visible[0] ?? "the host-provided edit tool (for example apply_patch)";
96
- throw new Error(`${toolName} is not available for this session's model (edit mode: ${mode}). Use ${preferred} instead.`);
122
+ if (!isPlainRecord(input))
123
+ return undefined;
124
+ const standard = input["~standard"];
125
+ if (isPlainRecord(standard)) {
126
+ const jsonSchema = standard
127
+ .jsonSchema;
128
+ if (jsonSchema !== undefined && typeof jsonSchema.input === "function") {
129
+ const projected = jsonSchema.input({ target: "draft-2020-12" });
130
+ if (isPlainRecord(projected))
131
+ return projected;
132
+ }
133
+ if (input instanceof $ZodType) {
134
+ return toJSONSchema(input, { target: "draft-2020-12", io: "input" });
135
+ }
136
+ return input;
137
+ }
138
+ // A literal JSON schema is already in the host's expected shape.
139
+ return input;
140
+ }
141
+ /** Capture genuine native tool definitions from the activated registry. */
142
+ export function captureNativeToolDefinitions(infos, target) {
143
+ for (const info of infos) {
144
+ const schema = nativeToolJsonSchema(info.input);
145
+ if (schema !== undefined)
146
+ target.set(info.name, { description: info.description, input: schema });
147
+ }
148
+ }
149
+ // END_BLOCK_ROUTING_CONSTANTS
150
+ // START_BLOCK_PATH_BOUNDARY
151
+ /** Reject empty/whitespace-only caller paths before any location resolution. */
152
+ function requireNonEmptyPath(value) {
153
+ if (typeof value !== "string")
154
+ return undefined;
155
+ const trimmed = value.trim();
156
+ return trimmed.length === 0 ? undefined : trimmed;
157
+ }
158
+ /** Mirror the pinned Windows shell-path normalization (no-op on non-Windows). */
159
+ function windowsPath(value) {
160
+ if (process.platform !== "win32")
161
+ return value;
162
+ return value
163
+ .replace(/^\/([a-zA-Z]):(?:[\\/]|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
164
+ .replace(/^\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
165
+ .replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
166
+ .replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`);
167
+ }
168
+ /**
169
+ * Resolve one caller path against the trusted native invocation location exactly
170
+ * once, mirroring pinned `FileAccess.resolvePath`: normalize Windows shell paths,
171
+ * expand leading `~` against the trusted host home, then resolve relative to the
172
+ * location directory. Absolute paths keep their contract.
173
+ */
174
+ function normalizeTargetPath(baseDir, callerPath, hostHome) {
175
+ const normalized = windowsPath(callerPath);
176
+ if (normalized === "~")
177
+ return resolve(baseDir, hostHome);
178
+ if (normalized.startsWith("~/") ||
179
+ (process.platform === "win32" && normalized.startsWith("~\\"))) {
180
+ return resolve(baseDir, join(hostHome, normalized.slice(2)));
181
+ }
182
+ return resolve(baseDir, normalized);
183
+ }
184
+ /** Pinned `FSUtil.contains` semantics: `child` is `parent` or lexically inside it. */
185
+ function containsPath(parent, child) {
186
+ const rel = relative(parent, child);
187
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
188
+ }
189
+ /**
190
+ * Pinned `Project.root` semantics using metadata only: walk up from a directory
191
+ * to the nearest ancestor containing a `.git`/`.hg` marker. It runs no git
192
+ * command and never reads file content, so it cannot modify user git config.
193
+ */
194
+ function findExternalProjectRoot(directory) {
195
+ let current = resolve(directory);
196
+ const filesystemRoot = parse(current).root;
197
+ for (;;) {
198
+ for (const marker of [".git", ".hg"]) {
199
+ try {
200
+ if (existsSync(join(current, marker)))
201
+ return current;
202
+ }
203
+ catch {
204
+ // Unreadable directories are treated as no match.
205
+ }
206
+ }
207
+ if (current === filesystemRoot)
208
+ return undefined;
209
+ const parent = dirname(current);
210
+ if (parent === current)
211
+ return undefined;
212
+ current = parent;
213
+ }
214
+ }
215
+ /**
216
+ * Map one resolved absolute target to the pinned permission resources: native
217
+ * internal scope is the current location plus its trusted project/worktree root
218
+ * (except the filesystem root special case), producing a location-relative
219
+ * resource; everything else is external and gets an `external_directory`
220
+ * `<dir>/*` boundary with the absolute resource.
221
+ */
222
+ function locateResource(locationDir, projectRoot, target, kind) {
223
+ const worktree = projectRoot === undefined ? undefined : resolve(projectRoot);
224
+ const internal = containsPath(locationDir, target) ||
225
+ (worktree !== undefined && worktree !== parse(worktree).root && containsPath(worktree, target));
226
+ if (internal) {
227
+ return {
228
+ internal: true,
229
+ resource: (relative(locationDir, target) || ".").split(sep).join("/"),
230
+ };
231
+ }
232
+ const directory = kind === "directory" ? target : dirname(target);
233
+ const outsideRoot = findExternalProjectRoot(directory) ?? directory;
234
+ return {
235
+ internal: false,
236
+ resource: target.split(sep).join("/"),
237
+ externalDirectory: {
238
+ directory,
239
+ resource: join(directory, "*").split(sep).join("/"),
240
+ save: join(outsideRoot, "*").split(sep).join("/"),
241
+ },
242
+ };
97
243
  }
98
244
  // START_BLOCK_FS_HELPERS
99
- export async function statSnapshot(filePath) {
245
+ async function statSnapshot(filePath) {
100
246
  try {
101
247
  const info = await stat(filePath);
102
248
  if (!info.isFile()) {
@@ -108,6 +254,15 @@ export async function statSnapshot(filePath) {
108
254
  return undefined;
109
255
  }
110
256
  }
257
+ /** Metadata-only target kind used to select the native external directory boundary. */
258
+ async function inferTargetKind(target) {
259
+ try {
260
+ return (await stat(target)).isDirectory() ? "directory" : "file";
261
+ }
262
+ catch {
263
+ return "file";
264
+ }
265
+ }
111
266
  function createNodeStrReplaceFs() {
112
267
  return {
113
268
  async exists(path) {
@@ -151,44 +306,23 @@ function createNodeStrReplaceFs() {
151
306
  },
152
307
  };
153
308
  }
154
- // END_BLOCK_FS_HELPERS
155
309
  function canCreateFromMissingFile(edits) {
156
310
  if (edits.length === 0) {
157
311
  return false;
158
312
  }
159
313
  return edits.every((edit) => (edit.op === "append" || edit.op === "prepend") && edit.pos === undefined);
160
314
  }
161
- function publishSuccessMetadata(args) {
162
- args.context.metadata({
163
- title: args.filePath,
164
- metadata: {
165
- filePath: args.filePath,
166
- path: args.filePath,
167
- file: args.filePath,
168
- noopEdits: args.noopEdits,
169
- deduplicatedEdits: args.deduplicatedEdits,
170
- firstChangedLine: findFirstChangedLine(args.beforeContent, args.afterContent),
171
- editMode: args.telemetry.editMode,
172
- providerID: args.telemetry.providerID,
173
- modelID: args.telemetry.modelID,
174
- filediff: {
175
- file: args.filePath,
176
- path: args.filePath,
177
- filePath: args.filePath,
178
- before: args.beforeContent,
179
- after: args.afterContent,
180
- },
181
- },
182
- });
183
- }
184
- export function isReadTool(toolName) {
315
+ function isReadTool(toolName) {
185
316
  return toolName.toLowerCase() === "read";
186
317
  }
187
318
  function isTextFileOutput(output) {
188
319
  const firstLine = output.split("\n")[0] ?? "";
189
320
  return COLON_READ_LINE_PATTERN.test(firstLine) || PIPE_READ_LINE_PATTERN.test(firstLine);
190
321
  }
191
- export function isHashlineEligibleReadOutput(output) {
322
+ function hasNumberedReadLines(lines) {
323
+ return lines.some((line) => parseReadLineParsed(line) !== null);
324
+ }
325
+ function isHashlineEligibleReadOutput(output) {
192
326
  if (!output) {
193
327
  return false;
194
328
  }
@@ -206,9 +340,11 @@ export function isHashlineEligibleReadOutput(output) {
206
340
  const firstFileLine = inlineFirst ?? lines[blockStart + 1] ?? "";
207
341
  return isTextFileOutput(firstFileLine);
208
342
  }
209
- return isTextFileOutput(lines[0] ?? "");
343
+ // Native read text prepends a human summary header ("Read file <path>, lines
344
+ // N-M"); anchors are still applicable when any numbered line is present.
345
+ return isTextFileOutput(lines[0] ?? "") || hasNumberedReadLines(lines);
210
346
  }
211
- export function readArgFilePath(args) {
347
+ function readArgFilePath(args) {
212
348
  if (!args || typeof args !== "object") {
213
349
  return undefined;
214
350
  }
@@ -220,11 +356,7 @@ export function readArgFilePath(args) {
220
356
  }
221
357
  return undefined;
222
358
  }
223
- export async function readSourceLines(args) {
224
- const filePath = readArgFilePath(args);
225
- if (!filePath) {
226
- return undefined;
227
- }
359
+ async function readSourceLinesAt(filePath) {
228
360
  try {
229
361
  const file = Bun.file(filePath);
230
362
  if (!(await file.exists())) {
@@ -316,7 +448,7 @@ function formatReadLines(parsedLines, rawLines, sourceLines) {
316
448
  }
317
449
  return result;
318
450
  }
319
- export function transformReadOutput(output, sourceLines) {
451
+ function transformReadOutput(output, sourceLines) {
320
452
  if (!output) {
321
453
  return output;
322
454
  }
@@ -340,9 +472,8 @@ export function transformReadOutput(output, sourceLines) {
340
472
  const parsedLines = [];
341
473
  for (const line of fileLines) {
342
474
  const parsed = parseReadLineParsed(line);
343
- if (!parsed) {
475
+ if (!parsed)
344
476
  break;
345
- }
346
477
  parsedLines.push(parsed);
347
478
  }
348
479
  const result = formatReadLines(parsedLines, fileLines, sourceMatchesVisibleRows(sourceLines, parsedLines) ? sourceLines : undefined);
@@ -351,82 +482,97 @@ export function transformReadOutput(output, sourceLines) {
351
482
  : lines.slice(0, blockStart + 1);
352
483
  return [...prefixLines, ...result, ...lines.slice(blockEnd)].join("\n");
353
484
  }
354
- if (!isTextFileOutput(lines[0] ?? "")) {
355
- return output;
485
+ // Native read text prepends a summary header and may append a truncation
486
+ // marker; transform the numbered block in place and keep every other line.
487
+ const numberedStart = lines.findIndex((line) => parseReadLineParsed(line) !== null);
488
+ if (numberedStart < 0) {
489
+ if (!isTextFileOutput(lines[0] ?? ""))
490
+ return output;
356
491
  }
492
+ const contentLines = lines.slice(Math.max(numberedStart, 0));
357
493
  const parsedLines = [];
358
- for (const line of lines) {
494
+ for (const line of contentLines) {
359
495
  const parsed = parseReadLineParsed(line);
360
- if (!parsed) {
496
+ if (!parsed)
361
497
  break;
362
- }
363
498
  parsedLines.push(parsed);
364
499
  }
365
- const result = formatReadLines(parsedLines, lines, sourceMatchesVisibleRows(sourceLines, parsedLines) ? sourceLines : undefined);
366
- return result.join("\n");
500
+ const result = formatReadLines(parsedLines, contentLines, sourceMatchesVisibleRows(sourceLines, parsedLines) ? sourceLines : undefined);
501
+ return [...lines.slice(0, Math.max(numberedStart, 0)), ...result].join("\n");
367
502
  }
368
- // START_BLOCK_HASHLINE_EXECUTE
369
- export async function executeHashlineEdit(args, context, telemetry) {
503
+ async function executeHashlineEdit(args, telemetry, publish, baseDir, hostHome) {
370
504
  try {
371
505
  const validation = validateHashlineEditToolInput(args);
372
506
  if (!validation.ok) {
373
507
  return `Error: ${formatContractIssues(validation.issues)}`;
374
508
  }
375
- const { filePath, rename, delete: deleteMode } = validation.data;
509
+ const requestedPath = requireNonEmptyPath(validation.data.filePath);
510
+ if (requestedPath === undefined) {
511
+ return "Error: filePath must be a non-empty path";
512
+ }
513
+ const sourcePath = normalizeTargetPath(baseDir, requestedPath, hostHome);
514
+ const requestedRename = validation.data.rename;
515
+ const renamePath = requestedRename === undefined
516
+ ? undefined
517
+ : normalizeTargetPath(baseDir, requireNonEmptyPath(requestedRename) ?? requestedRename, hostHome);
518
+ const deleteMode = validation.data.delete === true;
376
519
  const edits = deleteMode ? [] : normalizeHashlineEdits(validation.data.edits);
377
- const file = Bun.file(filePath);
520
+ const file = Bun.file(sourcePath);
378
521
  const exists = await file.exists();
379
522
  if (!exists && !deleteMode && !canCreateFromMissingFile(edits)) {
380
- return `Error: File not found: ${filePath}`;
523
+ return `Error: File not found: ${sourcePath}`;
381
524
  }
382
525
  if (deleteMode) {
383
526
  if (!exists) {
384
- return `Error: File not found: ${filePath}`;
527
+ return `Error: File not found: ${sourcePath}`;
385
528
  }
386
529
  await file.delete();
387
- return `Successfully deleted ${filePath}`;
530
+ return `Successfully deleted ${sourcePath}`;
388
531
  }
389
532
  const rawOldContent = exists ? Buffer.from(await file.arrayBuffer()).toString("utf8") : "";
390
533
  const oldEnvelope = canonicalizeFileText(rawOldContent);
391
534
  const applyResult = applyHashlineEditsWithReport(oldEnvelope.content, edits);
392
535
  const canonicalNewContent = applyResult.content;
393
- if (canonicalNewContent === oldEnvelope.content && !rename) {
394
- let diagnostic = `No changes made to ${filePath}. The edits produced identical content.`;
536
+ if (canonicalNewContent === oldEnvelope.content && renamePath === undefined) {
537
+ let diagnostic = `No changes made to ${sourcePath}. The edits produced identical content.`;
395
538
  if (applyResult.noopEdits > 0) {
396
539
  diagnostic += ` No-op edits: ${applyResult.noopEdits}. Re-read the file and provide content that differs from the current lines.`;
397
540
  }
398
541
  return `Error: ${diagnostic}`;
399
542
  }
400
543
  const writeContent = restoreFileText(canonicalNewContent, oldEnvelope);
401
- // Resolve the rename target up front so path-equivalent strings (e.g.
402
- // /tmp/a and /tmp/./a) are detected as the same file and never cause a
403
- // write-then-delete data loss.
404
- const sourcePath = resolve(filePath);
405
- const targetPath = rename ? resolve(rename) : undefined;
406
- const isMove = targetPath !== undefined && targetPath !== sourcePath;
407
- if (isMove && (await Bun.file(targetPath).exists())) {
408
- return `Error: rename target already exists: ${rename}. Refusing to overwrite an existing file.`;
409
- }
410
- await Bun.write(filePath, writeContent);
544
+ const isMove = renamePath !== undefined && renamePath !== sourcePath;
545
+ if (isMove && (await Bun.file(renamePath).exists())) {
546
+ return `Error: rename target already exists: ${renamePath}. Refusing to overwrite an existing file.`;
547
+ }
548
+ await Bun.write(sourcePath, writeContent);
411
549
  if (isMove) {
412
- await Bun.write(targetPath, writeContent);
413
- await Bun.file(filePath).delete();
414
- }
415
- const effectivePath = isMove ? targetPath : filePath;
416
- // The content write already happened. A metadata/reporting failure must not
417
- // be reported as an input rejection or a pristine file: keep the truthful
418
- // applied result and tell the caller to inspect before retrying. The thrown
419
- // message is intentionally not echoed — it may be unbounded or sensitive.
550
+ await Bun.write(renamePath, writeContent);
551
+ await Bun.file(sourcePath).delete();
552
+ }
553
+ const effectivePath = isMove ? renamePath : sourcePath;
420
554
  let metadataReportFailed = false;
421
555
  try {
422
- publishSuccessMetadata({
423
- context,
424
- filePath: effectivePath,
425
- beforeContent: oldEnvelope.content,
426
- afterContent: canonicalNewContent,
427
- noopEdits: applyResult.noopEdits,
428
- deduplicatedEdits: applyResult.deduplicatedEdits,
429
- telemetry,
556
+ await publish({
557
+ title: effectivePath,
558
+ metadata: {
559
+ filePath: effectivePath,
560
+ path: effectivePath,
561
+ file: effectivePath,
562
+ noopEdits: applyResult.noopEdits,
563
+ deduplicatedEdits: applyResult.deduplicatedEdits,
564
+ firstChangedLine: findFirstChangedLine(oldEnvelope.content, canonicalNewContent),
565
+ editMode: telemetry.editMode,
566
+ providerID: telemetry.providerID,
567
+ modelID: telemetry.modelID,
568
+ filediff: {
569
+ file: effectivePath,
570
+ path: effectivePath,
571
+ filePath: effectivePath,
572
+ before: oldEnvelope.content,
573
+ after: canonicalNewContent,
574
+ },
575
+ },
430
576
  });
431
577
  }
432
578
  catch {
@@ -436,7 +582,7 @@ export async function executeHashlineEdit(args, context, telemetry) {
436
582
  const firstChangedLine = findFirstChangedLine(oldEnvelope.content, canonicalNewContent);
437
583
  const stats = `+${diffSummary.additions}/-${diffSummary.deletions}${firstChangedLine !== undefined ? `, first change line ${firstChangedLine}` : ""}`;
438
584
  const headline = isMove
439
- ? `Moved ${filePath} to ${rename} (${stats})`
585
+ ? `Moved ${sourcePath} to ${renamePath} (${stats})`
440
586
  : `Updated ${effectivePath} (${stats})`;
441
587
  const outputParts = [headline];
442
588
  if (metadataReportFailed) {
@@ -459,28 +605,30 @@ export async function executeHashlineEdit(args, context, telemetry) {
459
605
  return `Error: ${message}`;
460
606
  }
461
607
  }
462
- // END_BLOCK_HASHLINE_EXECUTE
463
- // START_BLOCK_STR_REPLACE_EXECUTE
464
- export async function executeStrReplaceEditor(args, context, sessionID, fileCache, telemetry) {
608
+ async function executeStrReplaceEditor(args, sessionID, fileCache, telemetry, publish, baseDir, hostHome) {
609
+ const requestedPath = requireNonEmptyPath(args.path);
610
+ if (requestedPath === undefined) {
611
+ return "Error: path must be a non-empty path";
612
+ }
613
+ const targetPath = normalizeTargetPath(baseDir, requestedPath, hostHome);
614
+ const resolvedArgs = { ...args, path: targetPath };
465
615
  const editor = new StrReplaceEditor({
466
616
  fs: createNodeStrReplaceFs(),
467
617
  onViewed: (path, snapshot) => fileCache.record(sessionID, path, snapshot),
468
618
  checkFreshness: (path, current) => fileCache.check(sessionID, path, current),
469
619
  });
470
- const result = await editor.execute(args);
620
+ const result = await editor.execute(resolvedArgs);
471
621
  if (!result.ok) {
472
622
  return `Error: ${result.error}`;
473
623
  }
474
- if (args.command !== "view") {
475
- // The editor already wrote the file. Keep the truthful success output if the
476
- // metadata report fails, and direct the caller to inspect before retrying.
624
+ if (resolvedArgs.command !== "view") {
477
625
  try {
478
- context.metadata({
479
- title: args.path,
626
+ await publish({
627
+ title: targetPath,
480
628
  metadata: {
481
- filePath: args.path,
482
- path: args.path,
483
- file: args.path,
629
+ filePath: targetPath,
630
+ path: targetPath,
631
+ file: targetPath,
484
632
  editMode: telemetry.editMode,
485
633
  providerID: telemetry.providerID,
486
634
  modelID: telemetry.modelID,
@@ -488,133 +636,420 @@ export async function executeStrReplaceEditor(args, context, sessionID, fileCach
488
636
  });
489
637
  }
490
638
  catch {
491
- // Do not echo an arbitrary thrown message (unbounded or sensitive); state
492
- // only that the applied edit's report failed and that inspection precedes retry.
493
- return `${result.output}\nWarning: the edit was applied to ${args.path} but reporting metadata failed; inspect the file before retrying.`;
639
+ return `${result.output}\nWarning: the edit was applied to ${targetPath} but reporting metadata failed; inspect the file before retrying.`;
494
640
  }
495
641
  }
496
642
  return result.output;
497
643
  }
498
- // END_BLOCK_STR_REPLACE_EXECUTE
499
- // START_BLOCK_PLUGIN
500
- export const HashlineEditPlugin = async ({ directory }) => {
501
- const vvoc = await loadVvocConfig({ cwd: directory });
502
- const settings = parseHashlineEditPluginEntry(vvoc.config.plugins?.["hashline-edit"]);
503
- if (!settings.enabled)
504
- return {};
505
- const routing = settings.routing;
644
+ // END_BLOCK_EXECUTE
645
+ // START_BLOCK_HANDLERS
646
+ function modelOf(model) {
647
+ if (model === undefined)
648
+ return undefined;
649
+ if (typeof model.providerID !== "string" || typeof model.id !== "string")
650
+ return undefined;
651
+ return { providerID: model.providerID, modelID: model.id };
652
+ }
653
+ /** Build routing state, native hook handlers and the two native tool infos. */
654
+ export function createHashlineEditHandlers(deps, options = {}) {
506
655
  const modelCache = new SessionModelCache();
507
656
  const fileCache = new SessionFileCache();
508
- const resolveSessionMode = (sessionID) => resolveEditMode(routing, modelCache.get(sessionID));
509
- const telemetryFor = (sessionID) => {
657
+ const nativeDefinitions = options.nativeDefinitions ?? new Map();
658
+ const resolveMode = (sessionID, settings) => resolveEditMode(settings.routing, modelCache.get(sessionID));
659
+ const requireLocation = async (sessionID) => {
660
+ const directory = await deps.locationFor(sessionID);
661
+ if (typeof directory !== "string" || directory.length === 0)
662
+ return undefined;
663
+ return resolve(directory);
664
+ };
665
+ const permissionSource = (context) => ({
666
+ type: "tool",
667
+ messageID: String(context.messageID),
668
+ id: String(context.id),
669
+ });
670
+ /**
671
+ * Request the pinned file boundary before any effect. External targets first
672
+ * obtain `external_directory` (`<dir>/*`) approval; reads then always request
673
+ * `read` (location authority is not permission); edits request `edit` with
674
+ * location-relative resources for internal targets and absolute resources for
675
+ * external ones, `save: ["*"]`.
676
+ */
677
+ const requestFileEffect = async (context, baseDir, projectRoot, action, targets, tool, effect, kind) => {
678
+ const located = [];
679
+ for (const target of targets) {
680
+ const targetKind = kind ?? (await inferTargetKind(target));
681
+ located.push(locateResource(baseDir, projectRoot, target, targetKind));
682
+ }
683
+ const seenBoundaries = new Set();
684
+ const externals = located
685
+ .flatMap((entry) => (entry.externalDirectory === undefined ? [] : [entry.externalDirectory]))
686
+ .filter((entry) => {
687
+ if (seenBoundaries.has(entry.resource))
688
+ return false;
689
+ seenBoundaries.add(entry.resource);
690
+ return true;
691
+ });
692
+ const source = permissionSource(context);
693
+ if (externals.length > 0) {
694
+ await deps.permission.guard({
695
+ sessionID: context.sessionID,
696
+ action: "external_directory",
697
+ resources: externals.map((entry) => entry.resource),
698
+ save: externals.map((entry) => entry.save),
699
+ metadata: { tool, boundary: "external_directory" },
700
+ ...(context.agent === undefined ? {} : { agent: String(context.agent) }),
701
+ source,
702
+ }, () => undefined, { signal: context.signal });
703
+ }
704
+ return deps.permission.guard({
705
+ sessionID: context.sessionID,
706
+ action,
707
+ resources: located.map((entry) => entry.resource),
708
+ save: ["*"],
709
+ metadata: { tool },
710
+ ...(context.agent === undefined ? {} : { agent: String(context.agent) }),
711
+ source,
712
+ }, effect, { signal: context.signal });
713
+ };
714
+ const assertVisible = async (toolName, sessionID) => {
715
+ const settings = await deps.settingsFor(sessionID);
716
+ if (settings === undefined) {
717
+ throw new Error(`${toolName} is not available for this session: no hashline-edit family policy is bound.`);
718
+ }
719
+ if (!settings.enabled) {
720
+ throw new Error(`${toolName} is not available for this session: the hashline-edit plugin is disabled for the captured policy.`);
721
+ }
722
+ const mode = resolveMode(sessionID, settings);
723
+ const visible = visibleToolsForMode(mode);
724
+ if (visible.includes(toolName))
725
+ return;
726
+ const preferred = visible[0] ?? "the host-provided edit tool";
727
+ throw new Error(`${toolName} is not available for this session's model (edit mode: ${mode}). Use ${preferred} instead.`);
728
+ };
729
+ const telemetryFor = async (sessionID) => {
730
+ const settings = await deps.settingsFor(sessionID);
510
731
  const model = modelCache.get(sessionID);
511
732
  return {
512
- editMode: resolveEditMode(routing, model),
733
+ editMode: settings === undefined ? "edit" : resolveEditMode(settings.routing, model),
513
734
  providerID: model?.providerID,
514
735
  modelID: model?.modelID,
515
736
  };
516
737
  };
517
- // Owned-only contract publication: the strict input JSON Schema is published
518
- // through the host's observable jsonSchema member without replacing the host
519
- // decoder (T-001-proven seam).
520
- const toolDefinitionAdapter = createToolDefinitionAdapter([...editToolContracts]);
521
- return {
522
- "chat.message": async (input, output) => {
523
- const model = output.message?.model;
524
- if (input.sessionID &&
525
- model &&
526
- typeof model.providerID === "string" &&
527
- typeof model.modelID === "string") {
528
- modelCache.set(input.sessionID, { providerID: model.providerID, modelID: model.modelID });
738
+ const nativeResult = (output, metadata) => ({
739
+ output,
740
+ content: output,
741
+ ...(metadata === undefined ? {} : { metadata }),
742
+ });
743
+ const tools = {
744
+ hashline_edit: {
745
+ name: "hashline_edit",
746
+ description: hashlineEditContract.description,
747
+ input: hashlineEditContract.runtimeSchema,
748
+ output: z.string(),
749
+ options: { codemode: false },
750
+ async execute(input, context) {
751
+ await assertVisible("hashline_edit", context.sessionID);
752
+ const validation = validateHashlineEditToolInput(input);
753
+ if (!validation.ok) {
754
+ // Structural/branch rejection returns an error result rather than a
755
+ // retryable host failure; the host schema independently rejects before
756
+ // the handler in production.
757
+ return nativeResult(`Error: ${formatContractIssues(validation.issues)}`);
758
+ }
759
+ const baseDir = await requireLocation(context.sessionID);
760
+ if (baseDir === undefined) {
761
+ return nativeResult("Error: no trusted session location is available for this session");
762
+ }
763
+ const requestedPath = requireNonEmptyPath(validation.data.filePath);
764
+ if (requestedPath === undefined) {
765
+ return nativeResult("Error: filePath must be a non-empty path");
766
+ }
767
+ const hostHome = deps.hostHome();
768
+ const projectRoot = await deps.projectRootFor(context.sessionID);
769
+ const sourcePath = normalizeTargetPath(baseDir, requestedPath, hostHome);
770
+ const renamePath = validation.data.rename === undefined
771
+ ? undefined
772
+ : normalizeTargetPath(baseDir, requireNonEmptyPath(validation.data.rename) ?? validation.data.rename, hostHome);
773
+ const telemetry = await telemetryFor(context.sessionID);
774
+ const targets = renamePath === undefined ? [sourcePath] : [sourcePath, renamePath];
775
+ const output = await requestFileEffect(context, baseDir, projectRoot, "edit", targets, "hashline_edit", () => executeHashlineEdit(validation.data, telemetry, (u) => context.progress(u), baseDir, hostHome));
776
+ return nativeResult(output);
777
+ },
778
+ },
779
+ str_replace_editor: {
780
+ name: "str_replace_editor",
781
+ description: strReplaceEditorContract.description,
782
+ input: strReplaceEditorContract.runtimeSchema,
783
+ output: z.string(),
784
+ options: { codemode: false },
785
+ async execute(input, context) {
786
+ await assertVisible("str_replace_editor", context.sessionID);
787
+ const validation = validateStrReplaceEditorToolInput(input);
788
+ if (!validation.ok) {
789
+ return nativeResult(`Error: ${formatContractIssues(validation.issues)}`);
790
+ }
791
+ const baseDir = await requireLocation(context.sessionID);
792
+ if (baseDir === undefined) {
793
+ return nativeResult("Error: no trusted session location is available for this session");
794
+ }
795
+ const requestedPath = requireNonEmptyPath(validation.data.path);
796
+ if (requestedPath === undefined) {
797
+ return nativeResult("Error: path must be a non-empty path");
798
+ }
799
+ const hostHome = deps.hostHome();
800
+ const projectRoot = await deps.projectRootFor(context.sessionID);
801
+ const targetPath = normalizeTargetPath(baseDir, requestedPath, hostHome);
802
+ const telemetry = await telemetryFor(context.sessionID);
803
+ const run = () => executeStrReplaceEditor(validation.data, context.sessionID, fileCache, telemetry, (u) => context.progress(u), baseDir, hostHome);
804
+ const output = await requestFileEffect(context, baseDir, projectRoot, validation.data.command === "view" ? "read" : "edit", [targetPath], "str_replace_editor", run);
805
+ return nativeResult(output);
806
+ },
807
+ },
808
+ };
809
+ const handlers = {
810
+ tools,
811
+ recordModel(event) {
812
+ const model = modelOf(event.model);
813
+ if (model !== undefined)
814
+ modelCache.set(event.sessionID, model);
815
+ },
816
+ recordModelRequest(event) {
817
+ const model = modelOf(event.model);
818
+ if (model !== undefined)
819
+ modelCache.set(event.sessionID, model);
820
+ },
821
+ async sessionContext(event) {
822
+ const model = modelOf(event.model);
823
+ if (model !== undefined)
824
+ modelCache.set(event.sessionID, model);
825
+ const tools = event.tools;
826
+ if (tools === undefined)
827
+ return;
828
+ // Capture whichever genuine native definitions this session exposes before
829
+ // any mutation, so a host gate that removed one can still be overridden.
830
+ for (const name of NATIVE_TOOL_NAMES) {
831
+ const value = tools[name];
832
+ if (isNativeToolDefinition(value))
833
+ nativeDefinitions.set(name, value);
529
834
  }
530
- const mode = resolveEditMode(routing, model);
531
- const visible = new Set(visibleToolsForMode(mode));
532
- const message = output.message;
533
- if (!message)
835
+ const settings = await deps.settingsFor(event.sessionID);
836
+ if (settings === undefined || !settings.enabled) {
837
+ // Disabled/unbound: never force an edit mode; hide only the owned tools
838
+ // and leave the host gate's native decision in place (including write).
839
+ delete tools.hashline_edit;
840
+ delete tools.str_replace_editor;
534
841
  return;
535
- const toolsMap = message.tools ?? {};
536
- for (const toolName of EDIT_VISIBILITY_TOOLS) {
537
- if (toolName === "edit" && mode === "edit") {
538
- // The host built-in edit stays visible for the edit cohort.
842
+ }
843
+ const mode = resolveMode(event.sessionID, settings);
844
+ const desired = new Set(visibleToolsForMode(mode));
845
+ for (const toolName of HIDDEN_MODE_TOOLS) {
846
+ if (!desired.has(toolName))
847
+ delete tools[toolName];
848
+ }
849
+ // Ensure every desired tool is present; native write is restored for
850
+ // creation when the host gate removed it, never fabricated.
851
+ for (const toolName of desired) {
852
+ if (tools[toolName] !== undefined)
539
853
  continue;
854
+ const captured = nativeDefinitions.get(toolName);
855
+ if (captured === undefined) {
856
+ throw new Error(`hashline-edit: cannot expose native tool ${toolName} for edit mode ${mode}: no genuine native definition was observed.`);
540
857
  }
541
- if (!visible.has(toolName)) {
542
- toolsMap[toolName] = false;
543
- }
858
+ tools[toolName] = captured;
544
859
  }
545
- message.tools = toolsMap;
546
860
  },
547
- "tool.execute.before": async (input, output) => {
548
- if (!isEditTypeTool(input.tool)) {
861
+ async before(event) {
862
+ if (isEditTypeTool(event.tool)) {
863
+ // Visibility denial stays first: a tool this session's model must not use
864
+ // is refused without exposing argument-level detail.
865
+ await assertVisible(event.tool, event.sessionID);
866
+ const validation = event.tool === "hashline_edit"
867
+ ? validateHashlineEditToolInput(event.input)
868
+ : validateStrReplaceEditorToolInput(event.input);
869
+ if (!validation.ok) {
870
+ throw new ContractInputError(event.tool, validation.issues);
871
+ }
549
872
  return;
550
873
  }
551
- // Visibility denial stays first and unchanged: a tool that this session's
552
- // model must not use is refused without exposing argument-level detail.
553
- assertEditToolVisible(input.tool, input.sessionID, resolveSessionMode);
554
- // Allowed tool: reject structural/operation-invalid raw arguments before
555
- // the handler runs. This never mutates output.args and grants no eligibility.
556
- const validation = input.tool === "hashline_edit"
557
- ? validateHashlineEditToolInput(output.args)
558
- : validateStrReplaceEditorToolInput(output.args);
559
- if (!validation.ok) {
560
- throw new ContractInputError(input.tool, validation.issues);
874
+ if (!MANAGED_NATIVE_TOOLS.has(event.tool))
875
+ return;
876
+ const settings = await deps.settingsFor(event.sessionID);
877
+ if (settings === undefined || !settings.enabled)
878
+ return;
879
+ const mode = resolveMode(event.sessionID, settings);
880
+ if (!visibleToolsForMode(mode).includes(event.tool)) {
881
+ throw new Error(`${event.tool} is not available for this session's model (edit mode: ${mode}); the session routing exposes a different edit tool.`);
561
882
  }
562
883
  },
563
- "tool.execute.after": async (input, output) => {
564
- if (!isReadTool(input.tool)) {
884
+ async after(event) {
885
+ // V2 triggers execute.after on errors too: a denied or failed native read
886
+ // must not stat an unapproved file, establish freshness, or reread content.
887
+ if (!isReadTool(event.tool))
565
888
  return;
566
- }
567
- const filePath = readArgFilePath(input.args);
568
- if (filePath) {
569
- const snapshot = await statSnapshot(filePath);
570
- if (snapshot) {
571
- fileCache.record(input.sessionID, filePath, snapshot);
572
- }
573
- }
574
- if (typeof output.output !== "string") {
889
+ if (event.status !== "completed" || event.result === undefined)
575
890
  return;
891
+ const baseDir = await requireLocation(event.sessionID);
892
+ const rawPath = readArgFilePath(event.input);
893
+ const targetPath = baseDir !== undefined && rawPath !== undefined
894
+ ? normalizeTargetPath(baseDir, rawPath, deps.hostHome())
895
+ : undefined;
896
+ // A successful native read always establishes freshness (needed by the
897
+ // str_replace editor); anchoring additionally requires hashline mode.
898
+ if (targetPath !== undefined) {
899
+ const snapshot = await statSnapshot(targetPath);
900
+ if (snapshot)
901
+ fileCache.record(event.sessionID, targetPath, snapshot);
576
902
  }
577
- if (resolveSessionMode(input.sessionID) !== "hashline_edit") {
903
+ const settings = await deps.settingsFor(event.sessionID);
904
+ if (settings === undefined || !settings.enabled)
578
905
  return;
579
- }
580
- if (!isHashlineEligibleReadOutput(output.output)) {
906
+ if (resolveMode(event.sessionID, settings) !== "hashline_edit")
907
+ return;
908
+ const sourceLines = targetPath === undefined ? undefined : await readSourceLinesAt(targetPath);
909
+ const content = event.result.content;
910
+ // Native Tool.Result.content is normalized to an array before execute.after.
911
+ if (typeof content === "string") {
912
+ if (isHashlineEligibleReadOutput(content)) {
913
+ event.result.content = transformReadOutput(content, sourceLines);
914
+ }
581
915
  return;
582
916
  }
583
- output.output = transformReadOutput(output.output, await readSourceLines(input.args));
917
+ if (!Array.isArray(content))
918
+ return;
919
+ let changed = false;
920
+ const next = content.map((part) => {
921
+ if (part === null || typeof part !== "object")
922
+ return part;
923
+ const record = part;
924
+ if (record.type !== "text" || typeof record.text !== "string")
925
+ return part;
926
+ if (!isHashlineEligibleReadOutput(record.text))
927
+ return part;
928
+ changed = true;
929
+ return { ...record, text: transformReadOutput(record.text, sourceLines) };
930
+ });
931
+ if (changed)
932
+ event.result.content = next;
584
933
  },
585
- tool: {
586
- hashline_edit: tool({
587
- description: hashlineEditContract.description,
588
- args: hashlineEditArgs,
589
- execute: async (args, context) => {
590
- // Direct registered execute must not bypass the session model routing
591
- // the hook enforces: deny before argument details, filesystem access,
592
- // cache updates, or metadata reports.
593
- assertEditToolVisible("hashline_edit", context.sessionID, resolveSessionMode);
594
- return executeHashlineEdit(args, context, telemetryFor(context.sessionID));
595
- },
596
- }),
597
- str_replace_editor: tool({
598
- description: strReplaceEditorContract.description,
599
- args: strReplaceEditorArgs,
600
- execute: async (args, context) => {
601
- assertEditToolVisible("str_replace_editor", context.sessionID, resolveSessionMode);
602
- return executeStrReplaceEditor(args, context, context.sessionID, fileCache, telemetryFor(context.sessionID));
603
- },
604
- }),
934
+ };
935
+ return {
936
+ handlers,
937
+ dispose() {
938
+ modelCache.clear();
939
+ fileCache.clear();
605
940
  },
606
- "tool.definition": toolDefinitionAdapter,
607
941
  };
608
- };
609
- // END_BLOCK_PLUGIN
610
- // START_BLOCK_DUAL_SUBPATH_ENTRY
611
- import { defineDualPlugin } from "../v2-runtime/index.js";
612
- import { createV2Adapter } from "../v2-runtime/setup.js";
613
- import { setupHashlineEditV2 } from "./v2.js";
614
- export default defineDualPlugin({
615
- id: "vvoc.hashline-edit",
616
- v1: HashlineEditPlugin,
617
- v2: (ctx) => setupHashlineEditV2(createV2Adapter(ctx)),
618
- });
619
- // END_BLOCK_DUAL_SUBPATH_ENTRY
942
+ }
943
+ // END_BLOCK_HANDLERS
944
+ // START_BLOCK_PLUGIN_ENTRY
945
+ /** Resolve captured per-family hashline-edit settings; unbound/disabled fails closed. */
946
+ async function resolveSettings(runtime, sessionID) {
947
+ let capture;
948
+ try {
949
+ capture = await runtime.snapshots.configFor(sessionID);
950
+ }
951
+ catch {
952
+ capture = undefined;
953
+ }
954
+ if (capture === undefined) {
955
+ try {
956
+ await runtime.snapshots.accept({ sessionID });
957
+ }
958
+ catch {
959
+ // fall through to the second read
960
+ }
961
+ try {
962
+ capture = await runtime.snapshots.configFor(sessionID);
963
+ }
964
+ catch {
965
+ capture = undefined;
966
+ }
967
+ }
968
+ if (capture === undefined)
969
+ return undefined;
970
+ try {
971
+ return parseHashlineEditPluginEntry(capture.vvoc.plugins?.["hashline-edit"]);
972
+ }
973
+ catch {
974
+ return undefined;
975
+ }
976
+ }
977
+ function createConsoleLog() {
978
+ return (event) => {
979
+ if (event.level === "info")
980
+ return;
981
+ console.error(`[hashline-edit][${event.level}] ${event.message}${event.extra === undefined ? "" : ` ${JSON.stringify(event.extra)}`}`.slice(0, 1000));
982
+ };
983
+ }
984
+ /** Native hashline-edit plugin factory; the default export uses the real shared runtime. */
985
+ export function createHashlineEditPlugin(options = {}) {
986
+ return Plugin.define({
987
+ id: "vvoc.hashline-edit",
988
+ setup: async (ctx) => {
989
+ const acquire = options.acquireRuntime ?? ((c) => acquireNativeSnapshotRuntime(c));
990
+ const runtime = await acquire(ctx);
991
+ // Capture the genuine activated native tool definitions BEFORE any
992
+ // per-session visibility gate runs, so a cold GPT->edit override can
993
+ // restore the real native edit/write schema without a prior request.
994
+ const seededNativeDefinitions = new Map();
995
+ try {
996
+ captureNativeToolDefinitions(await ctx.tool.list(), seededNativeDefinitions);
997
+ }
998
+ catch {
999
+ // A registry read failure leaves the map empty; visibility then refuses
1000
+ // (honest incompatibility) rather than fabricating a schema.
1001
+ }
1002
+ // The trusted invocation location is the host session's location; the
1003
+ // plugin's own location is only a fallback when the session cannot be read.
1004
+ let clientPromise;
1005
+ const locationFor = async (sessionID) => {
1006
+ try {
1007
+ const client = (await (clientPromise ??=
1008
+ runtime.client()));
1009
+ const info = (await client.session.get({ sessionID }));
1010
+ const directory = info?.location?.directory;
1011
+ if (typeof directory === "string" && directory.length > 0)
1012
+ return directory;
1013
+ }
1014
+ catch {
1015
+ // fall through to the plugin location
1016
+ }
1017
+ return ctx.location?.directory;
1018
+ };
1019
+ const registration = createHashlineEditHandlers({
1020
+ settingsFor: (sessionID) => resolveSettings(runtime, sessionID),
1021
+ locationFor,
1022
+ projectRootFor: async () => ctx.location?.project?.directory ?? ctx.location?.directory,
1023
+ hostHome: () => process.env.OPENCODE_TEST_HOME ?? homedir(),
1024
+ permission: runtime.permissions,
1025
+ log: createConsoleLog(),
1026
+ }, { nativeDefinitions: seededNativeDefinitions });
1027
+ const h = registration.handlers;
1028
+ const toolRegistration = await ctx.tool.transform((editor) => {
1029
+ editor.add(h.tools.hashline_edit);
1030
+ editor.add(h.tools.str_replace_editor);
1031
+ });
1032
+ const beforeRegistration = await ctx.tool.hook("execute.before", (event) => h.before(event));
1033
+ const afterRegistration = await ctx.tool.hook("execute.after", (event) => h.after(event));
1034
+ const contextRegistration = await ctx.session.hook("context", (event) => h.sessionContext(event));
1035
+ const compactionRegistration = await ctx.session.hook("compaction", (event) => h.sessionContext(event));
1036
+ const generateRegistration = await ctx.session.hook("generate", (event) => h.sessionContext(event));
1037
+ const modelRegistration = await ctx.session.hook("model.request", (event) => h.recordModelRequest(event));
1038
+ return async () => {
1039
+ await modelRegistration.dispose();
1040
+ await generateRegistration.dispose();
1041
+ await compactionRegistration.dispose();
1042
+ await contextRegistration.dispose();
1043
+ await afterRegistration.dispose();
1044
+ await beforeRegistration.dispose();
1045
+ await toolRegistration.dispose();
1046
+ registration.dispose();
1047
+ await runtime.release();
1048
+ };
1049
+ },
1050
+ });
1051
+ }
1052
+ export const HashlineEditPlugin = createHashlineEditPlugin();
1053
+ export default HashlineEditPlugin;
1054
+ // END_BLOCK_PLUGIN_ENTRY
620
1055
  //# sourceMappingURL=index.js.map