@cortexkit/opencode-magic-context 0.45.0 → 0.46.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 (385) hide show
  1. package/README.md +26 -0
  2. package/dist/{announcement-f75t58v9.js → announcement-y35wzg2r.js} +1 -1
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/live-run-config.d.ts.map +1 -1
  5. package/dist/config/migrate-config-location.d.ts.map +1 -1
  6. package/dist/config/schema/magic-context.d.ts +10 -4
  7. package/dist/config/schema/magic-context.d.ts.map +1 -1
  8. package/dist/{conflict-warning-hook-5yrz2r24.js → conflict-warning-hook-7fj2b9jw.js} +6 -5
  9. package/dist/context-8dkpszy5.js +4483 -0
  10. package/dist/{derive-budgets-a63zsm5c.js → derive-budgets-7nj7r1rv.js} +2 -2
  11. package/dist/embedding-worker.js +4 -4
  12. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts +45 -0
  13. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts.map +1 -0
  14. package/dist/features/magic-context/checkout-claim.d.ts +155 -0
  15. package/dist/features/magic-context/checkout-claim.d.ts.map +1 -0
  16. package/dist/features/magic-context/compaction-marker.d.ts +20 -3
  17. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  18. package/dist/features/magic-context/compartment-storage.d.ts +23 -2
  19. package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  21. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts +6 -2
  23. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/provider-output-failure.test-support.d.ts +30 -0
  25. package/dist/features/magic-context/dreamer/provider-output-failure.test-support.d.ts.map +1 -0
  26. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  27. package/dist/features/magic-context/dreamer/task-executor.d.ts +9 -0
  28. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  29. package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
  30. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  31. package/dist/features/magic-context/dreamer/verify-diff.d.ts.map +1 -1
  32. package/dist/features/magic-context/dreamer/verify-gate.d.ts.map +1 -1
  33. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  34. package/dist/features/magic-context/git-commits/search-git-commits.d.ts.map +1 -1
  35. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  36. package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -1
  37. package/dist/features/magic-context/memory/storage-memory-verifications.d.ts.map +1 -1
  38. package/dist/features/magic-context/memory/storage-memory.d.ts +3 -0
  39. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  40. package/dist/features/magic-context/memory/verification-paths.d.ts +2 -2
  41. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  42. package/dist/features/magic-context/merged-reasoning-decisions.d.ts.map +1 -1
  43. package/dist/features/magic-context/message-index-async.d.ts +3 -3
  44. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  45. package/dist/features/magic-context/message-index.d.ts +2 -0
  46. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  47. package/dist/features/magic-context/migration-v95-perf-indexes.d.ts +12 -0
  48. package/dist/features/magic-context/migration-v95-perf-indexes.d.ts.map +1 -0
  49. package/dist/features/magic-context/migration-worker-client.d.ts +4 -4
  50. package/dist/features/magic-context/migration-worker-client.d.ts.map +1 -1
  51. package/dist/features/magic-context/migrations.d.ts +1 -0
  52. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  53. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  54. package/dist/features/magic-context/mural/resolve-mural.d.ts +15 -4
  55. package/dist/features/magic-context/mural/resolve-mural.d.ts.map +1 -1
  56. package/dist/features/magic-context/mural/source-revision.d.ts +7 -0
  57. package/dist/features/magic-context/mural/source-revision.d.ts.map +1 -0
  58. package/dist/features/magic-context/mural/storage-mural-cues.d.ts.map +1 -1
  59. package/dist/features/magic-context/reclaim-protection.d.ts +15 -10
  60. package/dist/features/magic-context/reclaim-protection.d.ts.map +1 -1
  61. package/dist/features/magic-context/session-cache-ttl.d.ts +4 -2
  62. package/dist/features/magic-context/session-cache-ttl.d.ts.map +1 -1
  63. package/dist/features/magic-context/smart-notes/capabilities.d.ts +3 -0
  64. package/dist/features/magic-context/smart-notes/capabilities.d.ts.map +1 -1
  65. package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
  66. package/dist/features/magic-context/smart-notes/github-token.d.ts +5 -0
  67. package/dist/features/magic-context/smart-notes/github-token.d.ts.map +1 -0
  68. package/dist/features/magic-context/smart-notes/runner.d.ts +1 -0
  69. package/dist/features/magic-context/smart-notes/runner.d.ts.map +1 -1
  70. package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts +12 -0
  71. package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts.map +1 -1
  72. package/dist/features/magic-context/smart-notes/ssrf-guard.d.ts +6 -0
  73. package/dist/features/magic-context/smart-notes/ssrf-guard.d.ts.map +1 -1
  74. package/dist/features/magic-context/smart-notes/storage.d.ts.map +1 -1
  75. package/dist/features/magic-context/smart-notes/types.d.ts +2 -0
  76. package/dist/features/magic-context/smart-notes/types.d.ts.map +1 -1
  77. package/dist/features/magic-context/storage-clone.d.ts.map +1 -1
  78. package/dist/features/magic-context/storage-db.d.ts +6 -9
  79. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  80. package/dist/features/magic-context/storage-meta-shared.d.ts +1 -1
  81. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  82. package/dist/features/magic-context/storage-ops.d.ts +8 -1
  83. package/dist/features/magic-context/storage-ops.d.ts.map +1 -1
  84. package/dist/features/magic-context/storage-replay-document.d.ts +7 -0
  85. package/dist/features/magic-context/storage-replay-document.d.ts.map +1 -1
  86. package/dist/features/magic-context/storage-schema-helpers.d.ts +2 -0
  87. package/dist/features/magic-context/storage-schema-helpers.d.ts.map +1 -1
  88. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  89. package/dist/features/magic-context/storage-source.d.ts.map +1 -1
  90. package/dist/features/magic-context/storage-tags.d.ts +11 -3
  91. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  92. package/dist/features/magic-context/storage.d.ts +2 -2
  93. package/dist/features/magic-context/storage.d.ts.map +1 -1
  94. package/dist/features/magic-context/temporal-decisions.d.ts +10 -0
  95. package/dist/features/magic-context/temporal-decisions.d.ts.map +1 -0
  96. package/dist/features/magic-context/tool-definition-tokens.d.ts +2 -0
  97. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  98. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  99. package/dist/features/magic-context/types.d.ts +7 -6
  100. package/dist/features/magic-context/types.d.ts.map +1 -1
  101. package/dist/features/magic-context/window-report-ledger.d.ts.map +1 -1
  102. package/dist/hooks/auto-update-checker/index.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/apply-operations.d.ts +8 -0
  104. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/cache-busting-signals.d.ts +6 -3
  106. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/channel2-cycle.d.ts +2 -0
  108. package/dist/hooks/magic-context/channel2-cycle.d.ts.map +1 -1
  109. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +7 -0
  110. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  111. package/dist/hooks/magic-context/compartment-prompt.d.ts +2 -2
  112. package/dist/hooks/magic-context/compartment-prompt.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/compartment-render-epoch.d.ts +8 -0
  114. package/dist/hooks/magic-context/compartment-render-epoch.d.ts.map +1 -1
  115. package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts +18 -4
  116. package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  118. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  120. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts +12 -0
  121. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts.map +1 -1
  122. package/dist/hooks/magic-context/decision-calibration.d.ts +3 -0
  123. package/dist/hooks/magic-context/decision-calibration.d.ts.map +1 -1
  124. package/dist/hooks/magic-context/default-protection-pressure.test-support.d.ts +37 -0
  125. package/dist/hooks/magic-context/default-protection-pressure.test-support.d.ts.map +1 -0
  126. package/dist/hooks/magic-context/drop-stale-reduce-calls.d.ts +4 -0
  127. package/dist/hooks/magic-context/drop-stale-reduce-calls.d.ts.map +1 -1
  128. package/dist/hooks/magic-context/edit-marker.d.ts.map +1 -1
  129. package/dist/hooks/magic-context/emergency-drop.d.ts +2 -0
  130. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  131. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +21 -1
  132. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  133. package/dist/hooks/magic-context/event-handler.d.ts +5 -0
  134. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  135. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +30 -1
  136. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  137. package/dist/hooks/magic-context/heuristic-cleanup.d.ts +2 -0
  138. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  139. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +4 -2
  140. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  141. package/dist/hooks/magic-context/hook.d.ts +2 -1
  142. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  143. package/dist/hooks/magic-context/inject-compartments.d.ts +9 -10
  144. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  145. package/dist/hooks/magic-context/lkg-measured-request.d.ts +69 -0
  146. package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -0
  147. package/dist/hooks/magic-context/lkg-persist.d.ts +2 -0
  148. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  149. package/dist/hooks/magic-context/lkg-replay-fit.d.ts +14 -0
  150. package/dist/hooks/magic-context/lkg-replay-fit.d.ts.map +1 -1
  151. package/dist/hooks/magic-context/lkg-replay.d.ts +10 -1
  152. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  153. package/dist/hooks/magic-context/lkg-slot.d.ts +4 -0
  154. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  155. package/dist/hooks/magic-context/module-state-sync.d.ts +2 -0
  156. package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
  157. package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
  158. package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
  159. package/dist/hooks/magic-context/note-nudger.d.ts +17 -5
  160. package/dist/hooks/magic-context/note-nudger.d.ts.map +1 -1
  161. package/dist/hooks/magic-context/read-session-chunk.d.ts +1 -1
  162. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  163. package/dist/hooks/magic-context/read-session-db.d.ts +1 -0
  164. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  165. package/dist/hooks/magic-context/read-session-formatting.d.ts +7 -0
  166. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  167. package/dist/hooks/magic-context/read-session-raw.d.ts +4 -0
  168. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  169. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  170. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +2 -0
  171. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  172. package/dist/hooks/magic-context/reference-retrieval.d.ts +27 -17
  173. package/dist/hooks/magic-context/reference-retrieval.d.ts.map +1 -1
  174. package/dist/hooks/magic-context/request-hook-order.d.ts +56 -0
  175. package/dist/hooks/magic-context/request-hook-order.d.ts.map +1 -0
  176. package/dist/hooks/magic-context/rust-mode-transform.d.ts +22 -3
  177. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  178. package/dist/hooks/magic-context/strip-content.d.ts +4 -2
  179. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  180. package/dist/hooks/magic-context/supersession-reclaim.d.ts +4 -0
  181. package/dist/hooks/magic-context/supersession-reclaim.d.ts.map +1 -1
  182. package/dist/hooks/magic-context/system-prompt-hash.d.ts +7 -0
  183. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  184. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +12 -3
  185. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  186. package/dist/hooks/magic-context/temporal-awareness.d.ts +6 -3
  187. package/dist/hooks/magic-context/temporal-awareness.d.ts.map +1 -1
  188. package/dist/hooks/magic-context/temporal-served-projection.d.ts +4 -0
  189. package/dist/hooks/magic-context/temporal-served-projection.d.ts.map +1 -0
  190. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  191. package/dist/hooks/magic-context/tool-reclaim.d.ts +2 -0
  192. package/dist/hooks/magic-context/tool-reclaim.d.ts.map +1 -1
  193. package/dist/hooks/magic-context/transform-message-helpers.d.ts +5 -0
  194. package/dist/hooks/magic-context/transform-message-helpers.d.ts.map +1 -1
  195. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +41 -17
  196. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  197. package/dist/hooks/magic-context/transform.d.ts +12 -0
  198. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  199. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  200. package/dist/{index-vvtfyw1z.js → index-0d3g3461.js} +5 -13
  201. package/dist/index-1bc61ans.js +154 -0
  202. package/dist/{index-n96ag4rk.js → index-1zx87sdm.js} +5 -1
  203. package/dist/{index-4krbw8z9.js → index-3h0ybwah.js} +608 -102
  204. package/dist/{index-gd5qx1j9.js → index-5eqk6z3s.js} +62 -1
  205. package/dist/index-5gq3b2ya.js +494 -0
  206. package/dist/{index-75zjgwga.js → index-7qw742ev.js} +1 -1
  207. package/dist/{index-f85teqck.js → index-8da2zjhz.js} +3 -256
  208. package/dist/{index-w9jwmntv.js → index-b35pxds2.js} +9 -1
  209. package/dist/{index-8fgkmxmy.js → index-e2dtv0ra.js} +4 -3
  210. package/dist/{v2/server-a4m2b1yv.js → index-fg34g6a5.js} +55 -1
  211. package/dist/{index-xgt9k6c6.js → index-j7fvnjye.js} +2 -1
  212. package/dist/{index-2aq21j41.js → index-k4404na5.js} +418 -127
  213. package/dist/{index-2ntg5sd4.js → index-k5bdx1bx.js} +9 -5
  214. package/dist/{index-bmzf7zxv.js → index-majxda46.js} +23 -5
  215. package/dist/{index-16ny736w.js → index-p821bjdb.js} +14406 -13726
  216. package/dist/{index-remp7e2g.js → index-q4yp4b52.js} +16 -1
  217. package/dist/index-qr6r7akd.js +28505 -0
  218. package/dist/{index-fr2z4qy8.js → index-r5hmbx3t.js} +132 -169
  219. package/dist/index-sfnj6h8h.js +259 -0
  220. package/dist/index-sj29b3z2.js +30 -0
  221. package/dist/{index-q7yesyk9.js → index-yasgb8ej.js} +23 -24
  222. package/dist/index.d.ts.map +1 -1
  223. package/dist/index.js +1983 -33118
  224. package/dist/{message-time-backfill-an311pmk.js → message-time-backfill-68gj6t3e.js} +2 -2
  225. package/dist/migration-worker.js +12 -7
  226. package/dist/plugin/dream-timer.d.ts +25 -1
  227. package/dist/plugin/dream-timer.d.ts.map +1 -1
  228. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -1
  229. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  230. package/dist/plugin/messages-transform.d.ts +13 -0
  231. package/dist/plugin/messages-transform.d.ts.map +1 -1
  232. package/dist/plugin/rpc-handlers.d.ts +4 -0
  233. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  234. package/dist/plugin/subagent-tool-policy.d.ts +14 -0
  235. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -0
  236. package/dist/plugin/tool-registry.d.ts +1 -0
  237. package/dist/plugin/tool-registry.d.ts.map +1 -1
  238. package/dist/{read-session-chunk-8rxs0tc9.js → read-session-chunk-egz7r68d.js} +8 -8
  239. package/dist/{recomp-orchestrator-nzamtw29.js → recomp-orchestrator-ejq7ex5d.js} +15 -15
  240. package/dist/{send-session-notification-nqpv7cne.js → send-session-notification-dyw42dtr.js} +4 -4
  241. package/dist/shared/announcement.d.ts.map +1 -1
  242. package/dist/shared/cache-ttl-display.d.ts +6 -4
  243. package/dist/shared/cache-ttl-display.d.ts.map +1 -1
  244. package/dist/shared/model-cache-ttl.d.ts +1 -1
  245. package/dist/shared/model-cache-ttl.d.ts.map +1 -1
  246. package/dist/shared/model-suggestion-retry.d.ts +2 -0
  247. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  248. package/dist/shared/models-dev-cache.d.ts.map +1 -1
  249. package/dist/shared/protected-tools-policy.d.ts +6 -0
  250. package/dist/shared/protected-tools-policy.d.ts.map +1 -0
  251. package/dist/shared/quota-diagnostic.d.ts +4 -0
  252. package/dist/shared/quota-diagnostic.d.ts.map +1 -0
  253. package/dist/shared/rpc-server.d.ts.map +1 -1
  254. package/dist/shared/sqlite-context-pragmas.d.ts +12 -0
  255. package/dist/shared/sqlite-context-pragmas.d.ts.map +1 -0
  256. package/dist/shared/sqlite-helpers.d.ts +9 -0
  257. package/dist/shared/sqlite-helpers.d.ts.map +1 -1
  258. package/dist/shared/sqlite.d.ts +10 -0
  259. package/dist/shared/sqlite.d.ts.map +1 -1
  260. package/dist/shared/status-summary.d.ts +1 -0
  261. package/dist/shared/status-summary.d.ts.map +1 -1
  262. package/dist/shared/status-view-check.d.ts.map +1 -1
  263. package/dist/shared/status-view.d.ts +4 -0
  264. package/dist/shared/status-view.d.ts.map +1 -1
  265. package/dist/shared/storage-permissions.d.ts +24 -0
  266. package/dist/shared/storage-permissions.d.ts.map +1 -1
  267. package/dist/shared/temporal-upgrade-fixture.d.ts +19 -0
  268. package/dist/shared/temporal-upgrade-fixture.d.ts.map +1 -0
  269. package/dist/shared/user-facing-codes.d.ts +5 -0
  270. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  271. package/dist/shared/write-transaction-timing.d.ts +8 -1
  272. package/dist/shared/write-transaction-timing.d.ts.map +1 -1
  273. package/dist/tools/ctx-expand/render.d.ts.map +1 -1
  274. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  275. package/dist/tools/ctx-reduce/constants.d.ts +2 -0
  276. package/dist/tools/ctx-reduce/constants.d.ts.map +1 -1
  277. package/dist/tools/ctx-reduce/tools.d.ts +4 -4
  278. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  279. package/dist/{transform-postprocess-phase-414phndq.js → transform-postprocess-phase-tz3pat2p.js} +15 -15
  280. package/dist/v2/context-8vgtb6sz.js +52166 -0
  281. package/dist/v2/{derive-budgets-v0krf3t7.js → derive-budgets-kdgp4s3r.js} +4 -3
  282. package/dist/v2/embedding-worker.js +6 -5
  283. package/dist/v2/fold/boundary.d.ts +2 -0
  284. package/dist/v2/fold/boundary.d.ts.map +1 -1
  285. package/dist/v2/fold/owner.d.ts.map +1 -1
  286. package/dist/v2/hooks/channel2.d.ts +2 -0
  287. package/dist/v2/hooks/channel2.d.ts.map +1 -1
  288. package/dist/v2/hooks/context.d.ts +2 -2
  289. package/dist/v2/hooks/context.d.ts.map +1 -1
  290. package/dist/v2/hooks/dream-timer.d.ts +39 -0
  291. package/dist/v2/hooks/dream-timer.d.ts.map +1 -0
  292. package/dist/v2/hooks/payload.d.ts.map +1 -1
  293. package/dist/v2/hooks/store.d.ts.map +1 -1
  294. package/dist/v2/hooks/tools.d.ts +1 -1
  295. package/dist/v2/hooks/tools.d.ts.map +1 -1
  296. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  297. package/dist/v2/{message-time-backfill-0n93vrd7.js → message-time-backfill-r6qkem1x.js} +3 -3
  298. package/dist/v2/migration-worker.js +13 -8
  299. package/dist/v2/{read-session-chunk-hjza38hr.js → read-session-chunk-8vjp6581.js} +9 -9
  300. package/dist/v2/recomp-orchestrator-5xj0yzyk.js +39 -0
  301. package/dist/v2/{safe-notification-target-wtj0bbc2.js → safe-notification-target-eb1n1vfb.js} +2 -2
  302. package/dist/v2/{send-session-notification-mq9frrtm.js → send-session-notification-qs0j78v6.js} +6 -6
  303. package/dist/v2/server-14vq4kpm.js +30 -0
  304. package/dist/v2/server-1bc61ans.js +154 -0
  305. package/dist/v2/{server-n96ag4rk.js → server-1zx87sdm.js} +5 -1
  306. package/dist/v2/server-3n4q9xme.js +79 -0
  307. package/dist/v2/server-4663ejam.js +3351 -0
  308. package/dist/v2/{server-rhdgxp1t.js → server-51dv1pr5.js} +63 -2
  309. package/dist/v2/{server-5317ykaf.js → server-6r257mf5.js} +1 -1
  310. package/dist/v2/server-84w6rvvf.js +14 -0
  311. package/dist/v2/{server-qpg6wf72.js → server-ajzeteqw.js} +9 -1
  312. package/dist/{index-a4m2b1yv.js → v2/server-fg34g6a5.js} +55 -1
  313. package/dist/v2/{server-e36nf2p1.js → server-frbm99q5.js} +1595 -1599
  314. package/dist/v2/{server-remp7e2g.js → server-g0fjrkta.js} +16 -1
  315. package/dist/v2/{server-z19x7eqz.js → server-mcfawjgc.js} +4 -4
  316. package/dist/v2/server-p2en78c8.js +3892 -0
  317. package/dist/v2/{server-hfjfbg59.js → server-qp5hx1ad.js} +608 -105
  318. package/dist/v2/{server-c4g2y1z8.js → server-vnh7r35f.js} +2778 -5383
  319. package/dist/v2/server-vs5gpnd4.js +493 -0
  320. package/dist/v2/{server-w99cyt6a.js → server-wvjvfhck.js} +14 -6
  321. package/dist/v2/{server-v5xgft5v.js → server-xtp687da.js} +186 -3533
  322. package/dist/v2/{server-0jqw05sa.js → server-y8maxeft.js} +6 -84
  323. package/dist/v2/server.d.ts.map +1 -1
  324. package/dist/v2/server.js +104 -49288
  325. package/dist/v2/store-reader.d.ts +39 -1
  326. package/dist/v2/store-reader.d.ts.map +1 -1
  327. package/dist/v2/tool-result.d.ts +8 -0
  328. package/dist/v2/tool-result.d.ts.map +1 -0
  329. package/dist/v2/tui/index.d.ts.map +1 -1
  330. package/dist/v2/{wrapup-orchestrator-tbyx78dz.js → wrapup-orchestrator-r5t1pyj8.js} +20 -16
  331. package/dist/wrapup-orchestrator-kw3x3myw.js +26 -0
  332. package/package.json +22 -7
  333. package/src/config/index.ts +21 -4
  334. package/src/config/latch-permanence-guard.test.ts +6 -1
  335. package/src/config/live-run-config.ts +1 -0
  336. package/src/config/migrate-config-location.test.ts +31 -1
  337. package/src/config/migrate-config-location.ts +8 -41
  338. package/src/config/protected-tools.test.ts +70 -0
  339. package/src/config/raw-loader.test.ts +15 -0
  340. package/src/config/raw-loader.ts +1 -1
  341. package/src/config/removed-agent-source-fence.test.ts +10 -1
  342. package/src/config/schema/magic-context.test.ts +20 -1
  343. package/src/config/schema/magic-context.ts +21 -7
  344. package/src/shared/announcement.ts +6 -5
  345. package/src/shared/cache-ttl-display.test.ts +1 -1
  346. package/src/shared/cache-ttl-display.ts +17 -16
  347. package/src/shared/fold-render-lock-fence.test.ts +84 -0
  348. package/src/shared/fold-render-lock-fixtures.test.ts +276 -0
  349. package/src/shared/model-cache-ttl.test.ts +2 -2
  350. package/src/shared/model-cache-ttl.ts +8 -4
  351. package/src/shared/model-suggestion-retry.test.ts +104 -1
  352. package/src/shared/model-suggestion-retry.ts +63 -6
  353. package/src/shared/models-dev-cache.ts +3 -11
  354. package/src/shared/protected-tools-policy.ts +23 -0
  355. package/src/shared/quota-diagnostic.ts +9 -0
  356. package/src/shared/rpc-server.ts +6 -54
  357. package/src/shared/sqlite-context-pragmas.test.ts +105 -0
  358. package/src/shared/sqlite-context-pragmas.ts +24 -0
  359. package/src/shared/sqlite-helpers.ts +17 -0
  360. package/src/shared/sqlite.ts +75 -0
  361. package/src/shared/status-detail-text.test.ts +18 -1
  362. package/src/shared/status-summary.ts +11 -0
  363. package/src/shared/status-view-check.ts +5 -0
  364. package/src/shared/status-view.test.ts +11 -2
  365. package/src/shared/status-view.ts +12 -1
  366. package/src/shared/storage-permissions.test.ts +204 -0
  367. package/src/shared/storage-permissions.ts +192 -0
  368. package/src/shared/temporal-upgrade-fixture.ts +50 -0
  369. package/src/shared/user-facing-codes.ts +6 -0
  370. package/src/shared/write-transaction-timing.test.ts +39 -0
  371. package/src/shared/write-transaction-timing.ts +25 -1
  372. package/src/tui/dialogs/status-dialog-render.test.ts +1 -1
  373. package/src/tui/index.tsx +3 -1
  374. package/src/tui/startup-order.test.ts +16 -0
  375. package/src/tui-compiled/index.tsx +3 -1
  376. package/src/v2/tui/index.ts +9 -2
  377. package/dist/index-anq4nn6f.js +0 -131
  378. package/dist/index-e44zzy84.js +0 -10
  379. package/dist/index-x23gah8c.js +0 -16
  380. package/dist/v2/recomp-orchestrator-1aq7h44c.js +0 -36
  381. package/dist/v2/server-e44zzy84.js +0 -10
  382. package/dist/v2/server-fgmxwrgy.js +0 -16
  383. package/dist/v2/server-r7cmye3k.js +0 -131
  384. package/dist/wrapup-orchestrator-h28bqsy6.js +0 -26
  385. package/dist/v2/{server-ckpc8pxy.js → server-1qbnzc80.js} +8 -8
@@ -0,0 +1,3351 @@
1
+ import {
2
+ DEFAULT_LOCAL_EMBEDDING_MODEL
3
+ } from "./server-xtp687da.js";
4
+ import {
5
+ getHarness,
6
+ getMagicContextStorageDir,
7
+ importPluginModule,
8
+ log
9
+ } from "./server-1qbnzc80.js";
10
+ import {
11
+ estimateTokens
12
+ } from "./server-51dv1pr5.js";
13
+ import {
14
+ shouldEnforcePrivateStoragePermissions,
15
+ ensureStorageDirectorySync,
16
+ writeStorageFileAsync,
17
+ writeStorageFileHandleAsync,
18
+ createStorageFileHandleAsync
19
+ } from "./server-1bc61ans.js";
20
+
21
+ // src/features/magic-context/memory/embedding-local.ts
22
+ import { readdirSync, statSync } from "node:fs";
23
+ import { stat, unlink } from "node:fs/promises";
24
+ import { dirname, join } from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import { workerData } from "node:worker_threads";
27
+
28
+ // src/features/magic-context/memory/embedding-failure.ts
29
+ function errorMessage(error) {
30
+ return error instanceof Error ? error.message : String(error ?? "unknown error");
31
+ }
32
+ function nestedMessages(error) {
33
+ const messages = [errorMessage(error)];
34
+ if (error && typeof error === "object" && "cause" in error) {
35
+ const cause = error.cause;
36
+ if (cause !== undefined)
37
+ messages.push(...nestedMessages(cause));
38
+ }
39
+ return messages;
40
+ }
41
+ function safeErrorDetail(message) {
42
+ return message.replace(/https?:\/\/[^\s"']+/gi, "<remote URL>").replace(/\/(?:Users|home)\/[^/\s]+/g, "~").replace(/\s+/g, " ").trim().slice(0, 240);
43
+ }
44
+ function hasAny(messages, patterns) {
45
+ return messages.some((message) => {
46
+ const lower = message.toLowerCase();
47
+ return patterns.some((pattern) => lower.includes(pattern));
48
+ });
49
+ }
50
+ function classifyLocalEmbeddingFailure(error, context = {}) {
51
+ const primaryMessages = nestedMessages(error);
52
+ const nativeMessages = context.nativeError === undefined ? [] : nestedMessages(context.nativeError);
53
+ if (hasAny(primaryMessages, [
54
+ "mc_embedding_fs_unavailable",
55
+ "file system cache is not available"
56
+ ]) || context.usesWasm && hasAny(primaryMessages, ["unable to get model file path or buffer"])) {
57
+ return {
58
+ class: "local_fs_unavailable",
59
+ reason: "the WASM model cache cannot access the Node filesystem",
60
+ retryable: false
61
+ };
62
+ }
63
+ if (hasAny(primaryMessages, [
64
+ "failed to fetch",
65
+ "fetch failed",
66
+ "network error",
67
+ "enotfound",
68
+ "econnreset",
69
+ "econnrefused",
70
+ "certificate",
71
+ "unable to load file",
72
+ "unauthorized access to file",
73
+ "forbidden access to file",
74
+ "not found at"
75
+ ]) || primaryMessages.some((message) => /\bHTTP\s+[45]\d\d\b/i.test(message))) {
76
+ return {
77
+ class: "local_download_failure",
78
+ reason: `the embedding model download failed: ${safeErrorDetail(primaryMessages[0])}`,
79
+ retryable: true
80
+ };
81
+ }
82
+ const bindingMessages = [...primaryMessages, ...nativeMessages];
83
+ if (hasAny(bindingMessages, [
84
+ "onnxruntime_binding.node",
85
+ "cannot find package 'onnxruntime-node'",
86
+ 'cannot find package "onnxruntime-node"',
87
+ "cannot find module 'onnxruntime-node'",
88
+ 'cannot find module "onnxruntime-node"',
89
+ "could not resolve: onnxruntime-node"
90
+ ])) {
91
+ const platform = context.platform ?? process.platform;
92
+ const arch = context.arch ?? process.arch;
93
+ return {
94
+ class: "local_binding_missing",
95
+ reason: platform === "darwin" && arch === "x64" ? "onnxruntime-node has no darwin/x64 native binding and the WASM fallback could not complete" : `onnxruntime-node has no usable native binding for ${platform}/${arch} and the WASM fallback could not complete`,
96
+ retryable: false
97
+ };
98
+ }
99
+ return {
100
+ class: "local_runtime_error",
101
+ reason: `the local embedding runtime failed: ${safeErrorDetail(primaryMessages[0])}`,
102
+ retryable: false
103
+ };
104
+ }
105
+ function dominantEmbeddingFailure(failures) {
106
+ const counts = new Map;
107
+ for (const failure of failures) {
108
+ const key = `${failure.class}\x00${failure.reason}`;
109
+ const current = counts.get(key);
110
+ if (current)
111
+ current.count += 1;
112
+ else
113
+ counts.set(key, { failure, count: 1 });
114
+ }
115
+ let dominant;
116
+ for (const candidate of counts.values()) {
117
+ if (!dominant || candidate.count > dominant.count)
118
+ dominant = candidate;
119
+ }
120
+ return dominant?.failure;
121
+ }
122
+
123
+ // src/features/magic-context/memory/embedding-model-match.ts
124
+ function parseEmbeddingModel(model) {
125
+ const lastColon = model.lastIndexOf(":");
126
+ if (lastColon > model.lastIndexOf("/")) {
127
+ return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
128
+ }
129
+ return { base: model };
130
+ }
131
+ function normalizeEmbeddingModelId(model) {
132
+ return parseEmbeddingModel(model.trim().toLowerCase()).base;
133
+ }
134
+ function matchNormalizedEmbeddingModels(a, b) {
135
+ if (a.length === 0 || b.length === 0)
136
+ return true;
137
+ if (a === b)
138
+ return true;
139
+ const longer = a.length >= b.length ? a : b;
140
+ const shorter = a.length >= b.length ? b : a;
141
+ const isBoundary = (ch) => ch === "-" || ch === "/";
142
+ if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
143
+ return true;
144
+ if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
145
+ return true;
146
+ return false;
147
+ }
148
+ function embeddingModelsMatch(served, requested) {
149
+ const servedNormalized = served.trim().toLowerCase();
150
+ const requestedNormalized = requested.trim().toLowerCase();
151
+ const servedModel = parseEmbeddingModel(servedNormalized);
152
+ const requestedModel = parseEmbeddingModel(requestedNormalized);
153
+ if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
154
+ return false;
155
+ }
156
+ return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
157
+ }
158
+ var QWEN3_QUERY_INSTRUCTION = `Instruct: Given a web search query, retrieve relevant passages that answer the query
159
+ Query: `;
160
+ var INSTRUCT_WEB_SEARCH_QUERY_PREFIX = QWEN3_QUERY_INSTRUCTION;
161
+ var EMBEDDING_MODEL_PREFIX_FAMILIES = [
162
+ {
163
+ family: "qwen3-embedding",
164
+ basenamePattern: /^qwen3-embedding(?:-|$)/,
165
+ prefixes: { queryPrefix: QWEN3_QUERY_INSTRUCTION, documentPrefix: "" }
166
+ },
167
+ {
168
+ family: "gte-qwen-instruct",
169
+ basenamePattern: /^gte-qwen.*-instruct(?:-|$)/,
170
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
171
+ },
172
+ {
173
+ family: "e5-instruct",
174
+ basenamePattern: /^(?:multilingual-)?e5-.*-instruct(?:-|$)/,
175
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
176
+ },
177
+ {
178
+ family: "nomic-embed-text",
179
+ basenamePattern: /^nomic-embed-text(?:-|$)/,
180
+ prefixes: { queryPrefix: "search_query: ", documentPrefix: "search_document: " }
181
+ }
182
+ ];
183
+ function modelBasename(model) {
184
+ const normalized = normalizeEmbeddingModelId(model);
185
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
186
+ }
187
+ function resolveEmbeddingTextPrefixes(model, queryInstruction, documentPrefix) {
188
+ const family = EMBEDDING_MODEL_PREFIX_FAMILIES.find(({ basenamePattern }) => basenamePattern.test(modelBasename(model)));
189
+ return {
190
+ queryPrefix: queryInstruction === false ? "" : queryInstruction !== undefined ? queryInstruction : family?.prefixes.queryPrefix ?? "",
191
+ documentPrefix: documentPrefix ?? family?.prefixes.documentPrefix ?? ""
192
+ };
193
+ }
194
+
195
+ // src/features/magic-context/memory/embedding-synapse.ts
196
+ import { createHash } from "node:crypto";
197
+
198
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
199
+ import { promises as fs2 } from "node:fs";
200
+ import { debuglog } from "node:util";
201
+
202
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
203
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
204
+
205
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
206
+ import net from "node:net";
207
+
208
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/envelope.js
209
+ var PROTOCOL_VERSION = 2;
210
+ var HEADER_LEN = 21;
211
+ var FROZEN_PREFIX_LEN = 5;
212
+ var MAX_FRAME_BODY_LEN = 64 * 1024 * 1024;
213
+ var FrameType;
214
+ (function(FrameType) {
215
+ FrameType[FrameType["Request"] = 0] = "Request";
216
+ FrameType[FrameType["Response"] = 1] = "Response";
217
+ FrameType[FrameType["Push"] = 2] = "Push";
218
+ FrameType[FrameType["StreamData"] = 3] = "StreamData";
219
+ FrameType[FrameType["StreamEnd"] = 4] = "StreamEnd";
220
+ FrameType[FrameType["Error"] = 5] = "Error";
221
+ FrameType[FrameType["Cancel"] = 6] = "Cancel";
222
+ FrameType[FrameType["Ping"] = 7] = "Ping";
223
+ FrameType[FrameType["Pong"] = 8] = "Pong";
224
+ FrameType[FrameType["Hello"] = 9] = "Hello";
225
+ FrameType[FrameType["HelloAck"] = 10] = "HelloAck";
226
+ FrameType[FrameType["Goodbye"] = 11] = "Goodbye";
227
+ })(FrameType || (FrameType = {}));
228
+ var FRAME_TYPE_MAX = FrameType.Goodbye;
229
+ function isPureHeader(ty) {
230
+ return ty === FrameType.Cancel || ty === FrameType.Ping || ty === FrameType.Pong || ty === FrameType.Goodbye;
231
+ }
232
+ var Priority;
233
+ (function(Priority) {
234
+ Priority[Priority["Passive"] = 0] = "Passive";
235
+ Priority[Priority["Interactive"] = 1] = "Interactive";
236
+ Priority[Priority["Background"] = 2] = "Background";
237
+ })(Priority || (Priority = {}));
238
+ var AdmissionClass;
239
+ (function(AdmissionClass) {
240
+ AdmissionClass[AdmissionClass["Normal"] = 0] = "Normal";
241
+ AdmissionClass[AdmissionClass["Expedite"] = 1] = "Expedite";
242
+ AdmissionClass[AdmissionClass["Sheddable"] = 2] = "Sheddable";
243
+ })(AdmissionClass || (AdmissionClass = {}));
244
+ var FLAG_BINARY = 1;
245
+ var FLAG_PRIORITY_MASK = 6;
246
+ var FLAG_PRIORITY_SHIFT = 1;
247
+ var FLAG_LAST = 8;
248
+ var FLAG_ADMISSION_MASK = 48;
249
+ var FLAG_ADMISSION_SHIFT = 4;
250
+ var FLAG_RESERVED_MASK = 128;
251
+ function buildFlags(binary, priority, last, admissionClass = AdmissionClass.Normal) {
252
+ let flags = 0;
253
+ if (binary)
254
+ flags |= FLAG_BINARY;
255
+ flags |= priority << FLAG_PRIORITY_SHIFT;
256
+ if (last)
257
+ flags |= FLAG_LAST;
258
+ flags |= admissionClass << FLAG_ADMISSION_SHIFT;
259
+ return flags;
260
+ }
261
+ function hasBinary(flags) {
262
+ return (flags & FLAG_BINARY) !== 0;
263
+ }
264
+ function encodeHeader(header) {
265
+ const buffer = new Uint8Array(HEADER_LEN);
266
+ const view = new DataView(buffer.buffer);
267
+ view.setUint32(0, header.len, true);
268
+ buffer[4] = header.ver;
269
+ buffer[5] = header.ty;
270
+ buffer[6] = header.flags;
271
+ view.setUint16(7, header.channel, true);
272
+ view.setUint32(9, header.epoch, true);
273
+ view.setBigUint64(13, header.corr, true);
274
+ return buffer;
275
+ }
276
+
277
+ class DecodeError extends Error {
278
+ code;
279
+ constructor(message, code) {
280
+ super(message);
281
+ this.code = code;
282
+ this.name = "DecodeError";
283
+ }
284
+ }
285
+ function validateHeaderFields(header) {
286
+ const len = header.len >>> 0;
287
+ const ver = header.ver >>> 0 & 255;
288
+ const typeByte = header.ty >>> 0 & 255;
289
+ const flags = header.flags >>> 0 & 255;
290
+ const channel = header.channel >>> 0 & 65535;
291
+ const epoch = header.epoch >>> 0;
292
+ BigInt.asUintN(64, header.corr);
293
+ if (ver !== PROTOCOL_VERSION)
294
+ throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
295
+ if (typeByte > FRAME_TYPE_MAX)
296
+ throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
297
+ const ty = typeByte;
298
+ if ((flags & FLAG_RESERVED_MASK) !== 0) {
299
+ throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
300
+ }
301
+ if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
302
+ throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
303
+ }
304
+ const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
305
+ if (admission === 3) {
306
+ throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
307
+ }
308
+ if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
309
+ throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
310
+ }
311
+ if (channel === 0 && epoch !== 0) {
312
+ throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
313
+ }
314
+ if (isPureHeader(ty) && len !== 0) {
315
+ throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
316
+ }
317
+ }
318
+ function decodeHeader(bytes) {
319
+ if (bytes.length < FROZEN_PREFIX_LEN) {
320
+ throw new DecodeError(`header shorter than frozen prefix: have ${bytes.length} bytes`, "too_short_for_prefix");
321
+ }
322
+ const ver = bytes[4];
323
+ if (ver !== PROTOCOL_VERSION)
324
+ throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
325
+ if (bytes.length < HEADER_LEN) {
326
+ throw new DecodeError(`header too short for version: have ${bytes.length} bytes, need ${HEADER_LEN}`, "too_short_for_header");
327
+ }
328
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
329
+ const len = view.getUint32(0, true);
330
+ const typeByte = bytes[5];
331
+ if (typeByte > FRAME_TYPE_MAX)
332
+ throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
333
+ const ty = typeByte;
334
+ const flags = bytes[6];
335
+ if ((flags & FLAG_RESERVED_MASK) !== 0) {
336
+ throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
337
+ }
338
+ if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
339
+ throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
340
+ }
341
+ const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
342
+ if (admission === 3) {
343
+ throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
344
+ }
345
+ if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
346
+ throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
347
+ }
348
+ const channel = view.getUint16(7, true);
349
+ const epoch = view.getUint32(9, true);
350
+ if (channel === 0 && epoch !== 0) {
351
+ throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
352
+ }
353
+ if (isPureHeader(ty) && len !== 0) {
354
+ throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
355
+ }
356
+ return { len, ver, ty, flags, channel, epoch, corr: view.getBigUint64(13, true) };
357
+ }
358
+ function buildFrame(ty, flags, channel, epoch, corr, body) {
359
+ return buildFrameWithVersion(PROTOCOL_VERSION, ty, flags, channel, epoch, corr, body);
360
+ }
361
+ function buildFrameWithVersion(ver, ty, flags, channel, epoch, corr, body) {
362
+ if (body.length > MAX_FRAME_BODY_LEN) {
363
+ throw new DecodeError(`frame body ${body.length} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
364
+ }
365
+ const header = { len: body.length, ver, ty, flags, channel, epoch, corr };
366
+ validateHeaderFields(header);
367
+ return { header, body };
368
+ }
369
+ function encodeFrame(frame) {
370
+ if (frame.header.len !== frame.body.length) {
371
+ throw new DecodeError(`frame header length ${frame.header.len} does not match body length ${frame.body.length}`, "frame_length_mismatch");
372
+ }
373
+ const header = encodeHeader(frame.header);
374
+ const output = new Uint8Array(header.length + frame.body.length);
375
+ output.set(header, 0);
376
+ output.set(frame.body, header.length);
377
+ return output;
378
+ }
379
+
380
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
381
+ class SocketClosedError extends Error {
382
+ }
383
+
384
+ class SocketTimeoutError extends Error {
385
+ }
386
+
387
+ class SocketWriteNotQueuedError extends Error {
388
+ cause;
389
+ constructor(message, cause) {
390
+ super(message);
391
+ this.cause = cause;
392
+ }
393
+ }
394
+
395
+ class SocketWriteQueuedError extends Error {
396
+ cause;
397
+ constructor(message, cause) {
398
+ super(message);
399
+ this.cause = cause;
400
+ }
401
+ }
402
+ function toWriteBuffer(bytes) {
403
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
404
+ }
405
+ var WRITE_BORROWED = Symbol("subc.socket.writeBorrowed");
406
+ var WRITE_TRACKED_BORROWED = Symbol("subc.socket.writeTrackedBorrowed");
407
+ function writeBorrowed(socket, bytes, deadlineMs) {
408
+ const borrowed = socket[WRITE_BORROWED];
409
+ return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.write(bytes, deadlineMs);
410
+ }
411
+ function writeTrackedBorrowed(socket, bytes, deadlineMs) {
412
+ const borrowed = socket[WRITE_TRACKED_BORROWED];
413
+ return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.writeTracked(bytes, deadlineMs);
414
+ }
415
+
416
+ class SubcSocket {
417
+ sock;
418
+ chunks = [];
419
+ buffered = 0;
420
+ waiter = null;
421
+ closedErr = null;
422
+ bufferedBytes() {
423
+ return this.buffered;
424
+ }
425
+ constructor(sock) {
426
+ this.sock = sock;
427
+ sock.on("data", (chunk) => {
428
+ this.chunks.push(chunk);
429
+ this.buffered += chunk.length;
430
+ this.tryServe();
431
+ });
432
+ const fail = (err) => {
433
+ if (!this.closedErr)
434
+ this.closedErr = err;
435
+ this.tryServe();
436
+ };
437
+ sock.on("error", (err) => fail(err instanceof Error ? err : new Error(String(err))));
438
+ sock.on("end", () => fail(new SocketClosedError("subc closed the connection")));
439
+ sock.on("close", () => fail(new SocketClosedError("subc connection closed")));
440
+ }
441
+ localPort() {
442
+ return this.sock.localPort ?? null;
443
+ }
444
+ static connect(host, port, deadlineMs) {
445
+ return new Promise((resolve, reject) => {
446
+ const sock = net.connect({ host, port });
447
+ sock.setNoDelay(true);
448
+ const timer = setTimeout(() => {
449
+ sock.destroy();
450
+ reject(new SocketTimeoutError(`timed out connecting to ${host}:${port}`));
451
+ }, Math.max(0, deadlineMs - Date.now()));
452
+ sock.once("connect", () => {
453
+ clearTimeout(timer);
454
+ resolve(new SubcSocket(sock));
455
+ });
456
+ sock.once("error", (err) => {
457
+ clearTimeout(timer);
458
+ reject(err);
459
+ });
460
+ });
461
+ }
462
+ async readFrame(headerDeadlineMs, bodyDeadline, onHeader) {
463
+ const prefix = await this.readExact(FROZEN_PREFIX_LEN, headerDeadlineMs);
464
+ const version = prefix[4];
465
+ if (version !== PROTOCOL_VERSION)
466
+ throw new DecodeError(`unsupported envelope version ${version}`, "unsupported_version");
467
+ const remainder = await this.readExact(HEADER_LEN - FROZEN_PREFIX_LEN, headerDeadlineMs);
468
+ const headerBytes = new Uint8Array(HEADER_LEN);
469
+ headerBytes.set(prefix);
470
+ headerBytes.set(remainder, FROZEN_PREFIX_LEN);
471
+ const header = decodeHeader(headerBytes);
472
+ if (header.len > MAX_FRAME_BODY_LEN) {
473
+ throw new DecodeError(`frame body ${header.len} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
474
+ }
475
+ onHeader?.();
476
+ const bodyDeadlineMs = typeof bodyDeadline === "number" ? bodyDeadline : Date.now() + bodyDeadline.afterHeaderMs;
477
+ const body = header.len === 0 ? new Uint8Array(0) : await this.readExact(header.len, bodyDeadlineMs);
478
+ return { header, body };
479
+ }
480
+ readExact(n, deadlineMs) {
481
+ if (this.waiter) {
482
+ return Promise.reject(new Error("concurrent readExact is not supported"));
483
+ }
484
+ if (n === 0)
485
+ return Promise.resolve(new Uint8Array(0));
486
+ return new Promise((resolve, reject) => {
487
+ let timer = null;
488
+ if (Number.isFinite(deadlineMs)) {
489
+ const remaining = deadlineMs - Date.now();
490
+ if (remaining <= 0) {
491
+ reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
492
+ return;
493
+ }
494
+ timer = setTimeout(() => {
495
+ this.waiter = null;
496
+ reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
497
+ }, remaining);
498
+ }
499
+ this.waiter = { need: n, resolve, reject, timer };
500
+ this.tryServe();
501
+ });
502
+ }
503
+ async write(bytes, deadlineMs) {
504
+ await this.writeBuffer(Buffer.from(bytes), deadlineMs);
505
+ }
506
+ writeTracked(bytes, deadlineMs) {
507
+ return this.writeTrackedBuffer(Buffer.from(bytes), deadlineMs);
508
+ }
509
+ async[WRITE_BORROWED](bytes, deadlineMs) {
510
+ await this.writeBuffer(toWriteBuffer(bytes), deadlineMs);
511
+ }
512
+ [WRITE_TRACKED_BORROWED](bytes, deadlineMs) {
513
+ return this.writeTrackedBuffer(toWriteBuffer(bytes), deadlineMs);
514
+ }
515
+ async writeBuffer(buffer, deadlineMs) {
516
+ try {
517
+ await this.writeTrackedBuffer(buffer, deadlineMs).completed;
518
+ } catch (err) {
519
+ if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError) {
520
+ throw err.cause ?? err;
521
+ }
522
+ throw err;
523
+ }
524
+ }
525
+ writeTrackedBuffer(buffer, deadlineMs) {
526
+ if (this.closedErr) {
527
+ return {
528
+ queued: false,
529
+ completed: Promise.reject(new SocketWriteNotQueuedError("subc socket was closed before bytes could be queued", this.closedErr))
530
+ };
531
+ }
532
+ let queued = false;
533
+ let settled = false;
534
+ let timer = null;
535
+ const completed = new Promise((resolve, reject) => {
536
+ const settle = (run) => {
537
+ if (settled)
538
+ return;
539
+ settled = true;
540
+ if (timer)
541
+ clearTimeout(timer);
542
+ run();
543
+ };
544
+ const remaining = deadlineMs - Date.now();
545
+ if (remaining <= 0) {
546
+ settle(() => reject(new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", new SocketTimeoutError("timed out writing to subc"))));
547
+ return;
548
+ }
549
+ timer = setTimeout(() => {
550
+ const timeout = new SocketTimeoutError("timed out writing to subc");
551
+ settle(() => reject(queued ? new SocketWriteQueuedError("timed out after bytes were handed to the subc socket", timeout) : new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", timeout)));
552
+ }, remaining);
553
+ try {
554
+ this.sock.write(buffer, (err) => {
555
+ settle(() => {
556
+ if (err) {
557
+ reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
558
+ } else {
559
+ resolve();
560
+ }
561
+ });
562
+ });
563
+ queued = true;
564
+ } catch (err) {
565
+ settle(() => reject(new SocketWriteNotQueuedError("subc socket write threw before bytes could be queued", err instanceof Error ? err : new Error(String(err)))));
566
+ }
567
+ });
568
+ return { queued, completed };
569
+ }
570
+ close() {
571
+ this.sock.destroy();
572
+ }
573
+ tryServe() {
574
+ const w = this.waiter;
575
+ if (!w)
576
+ return;
577
+ if (this.buffered >= w.need) {
578
+ const out = this.take(w.need);
579
+ this.waiter = null;
580
+ if (w.timer)
581
+ clearTimeout(w.timer);
582
+ w.resolve(out);
583
+ return;
584
+ }
585
+ if (this.closedErr) {
586
+ this.waiter = null;
587
+ if (w.timer)
588
+ clearTimeout(w.timer);
589
+ w.reject(this.closedErr);
590
+ }
591
+ }
592
+ take(n) {
593
+ const out = Buffer.allocUnsafe(n);
594
+ let off = 0;
595
+ while (off < n) {
596
+ const head = this.chunks[0];
597
+ const want = n - off;
598
+ if (head.length <= want) {
599
+ head.copy(out, off);
600
+ off += head.length;
601
+ this.chunks.shift();
602
+ } else {
603
+ head.copy(out, off, 0, want);
604
+ this.chunks[0] = head.subarray(want);
605
+ off += want;
606
+ }
607
+ }
608
+ this.buffered -= n;
609
+ return out;
610
+ }
611
+ }
612
+
613
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
614
+ var NONCE_LEN = 32;
615
+ var MAX_AUTH_MESSAGE_LEN = 4096;
616
+ var SERVER_PROOF_DOMAIN = "subc-server-v1";
617
+ var CLIENT_AUTH_DOMAIN = "subc-client-v1";
618
+ var DEFAULT_CLIENT_ROLE = "client";
619
+
620
+ class AuthError extends Error {
621
+ }
622
+ function computeProof(key, domain, clientNonce, serverNonce, daemonId) {
623
+ const mac = createHmac("sha256", Buffer.from(key));
624
+ mac.update(Buffer.from(domain, "utf8"));
625
+ mac.update(Buffer.from(clientNonce));
626
+ mac.update(Buffer.from(serverNonce));
627
+ mac.update(Buffer.from(daemonId));
628
+ return new Uint8Array(mac.digest());
629
+ }
630
+ function constantTimeEq(a, b) {
631
+ if (a.length !== b.length)
632
+ return false;
633
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
634
+ }
635
+ async function writeMessage(sock, value, deadlineMs) {
636
+ const json = Buffer.from(JSON.stringify(value), "utf8");
637
+ if (json.length > MAX_AUTH_MESSAGE_LEN) {
638
+ throw new AuthError(`auth message too large: ${json.length} > ${MAX_AUTH_MESSAGE_LEN}`);
639
+ }
640
+ const lenPrefix = new Uint8Array(4);
641
+ new DataView(lenPrefix.buffer).setUint32(0, json.length, true);
642
+ await writeBorrowed(sock, lenPrefix, deadlineMs);
643
+ await writeBorrowed(sock, json, deadlineMs);
644
+ }
645
+ async function readMessage(sock, deadlineMs) {
646
+ const lenBytes = await sock.readExact(4, deadlineMs);
647
+ const len = new DataView(lenBytes.buffer, lenBytes.byteOffset, 4).getUint32(0, true);
648
+ if (len > MAX_AUTH_MESSAGE_LEN) {
649
+ throw new AuthError(`auth message too large: ${len} > ${MAX_AUTH_MESSAGE_LEN}`);
650
+ }
651
+ const body = len === 0 ? new Uint8Array(0) : await sock.readExact(len, deadlineMs);
652
+ try {
653
+ return JSON.parse(Buffer.from(body).toString("utf8"));
654
+ } catch (err) {
655
+ throw new AuthError(`auth message JSON decode failed: ${String(err)}`);
656
+ }
657
+ }
658
+ function authBytes(value, field) {
659
+ if (!Array.isArray(value)) {
660
+ throw new AuthError(`auth field '${field}' must be a byte array`);
661
+ }
662
+ for (const byte of value) {
663
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
664
+ throw new AuthError(`auth field '${field}' has invalid byte ${String(byte)}`);
665
+ }
666
+ }
667
+ return Uint8Array.from(value);
668
+ }
669
+ async function authenticateClient(sock, conn, deadlineMs) {
670
+ const clientNonce = new Uint8Array(randomBytes(NONCE_LEN));
671
+ await writeMessage(sock, { client_nonce: Array.from(clientNonce), role: DEFAULT_CLIENT_ROLE }, deadlineMs);
672
+ const proof = await readMessage(sock, deadlineMs);
673
+ const serverNonce = authBytes(proof.server_nonce, "server_nonce");
674
+ const daemonId = authBytes(proof.daemon_id, "daemon_id");
675
+ const serverProof = authBytes(proof.server_proof, "server_proof");
676
+ const expected = computeProof(conn.key, SERVER_PROOF_DOMAIN, clientNonce, serverNonce, daemonId);
677
+ if (!constantTimeEq(expected, serverProof)) {
678
+ throw new AuthError("server proof mismatch — wrong key or impostor daemon");
679
+ }
680
+ if (!constantTimeEq(daemonId, conn.daemonId)) {
681
+ throw new AuthError("daemon id mismatch — connection file points at a different daemon");
682
+ }
683
+ const clientAuth = computeProof(conn.key, CLIENT_AUTH_DOMAIN, clientNonce, serverNonce, daemonId);
684
+ await writeMessage(sock, { client_auth: Array.from(clientAuth) }, deadlineMs);
685
+ }
686
+
687
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/connection-file.js
688
+ import { promises as fs } from "node:fs";
689
+ var SCHEMA_VERSION = 1;
690
+ var MIN_KEY_LEN = 32;
691
+ var DAEMON_ID_LEN = 16;
692
+
693
+ class ConnectionFileError extends Error {
694
+ }
695
+ function toBytes(value, field) {
696
+ if (!Array.isArray(value)) {
697
+ throw new ConnectionFileError(`connection file field '${field}' must be a JSON array of bytes`);
698
+ }
699
+ for (const byte of value) {
700
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
701
+ throw new ConnectionFileError(`connection file field '${field}' has invalid byte ${String(byte)}`);
702
+ }
703
+ }
704
+ return Uint8Array.from(value);
705
+ }
706
+ function validate(info) {
707
+ if (info.schema !== SCHEMA_VERSION) {
708
+ throw new ConnectionFileError(`unsupported connection file schema ${info.schema}; expected ${SCHEMA_VERSION}`);
709
+ }
710
+ if (info.endpoints.length === 0) {
711
+ throw new ConnectionFileError("connection file must include at least one endpoint");
712
+ }
713
+ if (info.key.length < MIN_KEY_LEN) {
714
+ throw new ConnectionFileError(`connection file key is too short: ${info.key.length} bytes, need at least ${MIN_KEY_LEN}`);
715
+ }
716
+ if (info.daemonId.length !== DAEMON_ID_LEN) {
717
+ throw new ConnectionFileError(`connection file daemon_id must be ${DAEMON_ID_LEN} bytes, got ${info.daemonId.length}`);
718
+ }
719
+ }
720
+ async function verifyOwnerOnly(path) {
721
+ if (process.platform === "win32")
722
+ return;
723
+ const stat = await fs.stat(path);
724
+ const mode = stat.mode & 511;
725
+ if ((mode & 63) !== 0) {
726
+ throw new ConnectionFileError(`connection file ${path} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
727
+ }
728
+ }
729
+ async function readConnectionFile(path) {
730
+ await verifyOwnerOnly(path);
731
+ const raw = await fs.readFile(path, "utf8");
732
+ let parsed;
733
+ try {
734
+ parsed = JSON.parse(raw);
735
+ } catch (err) {
736
+ throw new ConnectionFileError(`connection file JSON read failed for ${path}: ${String(err)}`);
737
+ }
738
+ const wireVersion = parsed.wire_version;
739
+ if (wireVersion !== undefined && wireVersion !== PROTOCOL_VERSION) {
740
+ throw new ConnectionFileError(`connection file wire_version ${String(wireVersion)} but this client speaks ${PROTOCOL_VERSION}; the client library must be upgraded`);
741
+ }
742
+ const endpointsRaw = parsed.endpoints;
743
+ if (!Array.isArray(endpointsRaw)) {
744
+ throw new ConnectionFileError("connection file 'endpoints' must be an array");
745
+ }
746
+ const endpoints = endpointsRaw.map((e) => {
747
+ const ep = e;
748
+ if (typeof ep.host !== "string" || typeof ep.port !== "number") {
749
+ throw new ConnectionFileError("connection file endpoint must be { host: string, port: number }");
750
+ }
751
+ return { host: ep.host, port: ep.port };
752
+ });
753
+ const info = {
754
+ schema: parsed.schema,
755
+ endpoints,
756
+ key: toBytes(parsed.key, "key"),
757
+ daemonId: toBytes(parsed.daemon_id, "daemon_id"),
758
+ pid: parsed.pid,
759
+ daemonVer: parsed.daemon_ver ?? ""
760
+ };
761
+ validate(info);
762
+ return info;
763
+ }
764
+
765
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/route-handle.js
766
+ var connectionToken = new WeakMap;
767
+
768
+ class RouteHandle {
769
+ channel;
770
+ epoch;
771
+ constructor(channel, epoch, token) {
772
+ if (!Number.isInteger(channel) || channel <= 0 || channel > 65535) {
773
+ throw new RangeError(`route channel must be an integer in 1..65535, got ${channel}`);
774
+ }
775
+ if (!Number.isInteger(epoch) || epoch <= 0 || epoch > 4294967295) {
776
+ throw new RangeError(`route epoch must be an integer in 1..4294967295, got ${epoch}`);
777
+ }
778
+ this.channel = channel;
779
+ this.epoch = epoch;
780
+ connectionToken.set(this, token);
781
+ Object.freeze(this);
782
+ }
783
+ static create(channel, epoch, token) {
784
+ return new RouteHandle(channel, epoch, token);
785
+ }
786
+ }
787
+ function createRouteHandle(channel, epoch, token) {
788
+ const factory = RouteHandle;
789
+ return factory.create(channel, epoch, token);
790
+ }
791
+
792
+ class StaleRouteHandleError extends Error {
793
+ handle;
794
+ code = "stale_route_handle";
795
+ constructor(handle) {
796
+ super(`route handle (${handle.channel}, ${handle.epoch}) is not live on the current connection`);
797
+ this.handle = handle;
798
+ this.name = "StaleRouteHandleError";
799
+ }
800
+ }
801
+ function newConnectionToken() {
802
+ return Object.freeze({});
803
+ }
804
+ function belongsToConnection(handle, token) {
805
+ return connectionToken.get(handle) === token;
806
+ }
807
+ function sameRouteHandle(left, right) {
808
+ return left === right;
809
+ }
810
+
811
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
812
+ var debug = debuglog("subc-client");
813
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 1e4;
814
+ var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
815
+ var TIMEOUT_ARBITRATION_GRACE_MS = 50;
816
+ var LIVENESS_PROBE_WINDOW_MS = 2000;
817
+ var REQUEST_DEADLINE_MARKER = "request_deadline";
818
+ var DEADLINE_NO_DROP_CODE = "deadline_exceeded_no_drop_observed";
819
+ var ROUTE_OPEN_RETRY_DEADLINE_MS = 30000;
820
+ var BODY_READ_TIMEOUT_MS = 30000;
821
+ var EMPTY_BODY = new Uint8Array(0);
822
+ var DEFAULT_MANAGED_TARGET_KIND = "management_surface";
823
+ var SUBC_MODULE_ID_ENV = "SUBC_MODULE_ID";
824
+ var SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
825
+ var DEFAULT_RECONNECT_BACKOFF = {
826
+ baseMs: 100,
827
+ capMs: 2000,
828
+ maxAttempts: 6
829
+ };
830
+
831
+ class SubcCallError extends Error {
832
+ kind;
833
+ code;
834
+ cause;
835
+ constructor(kind, message, code, cause) {
836
+ super(message);
837
+ this.kind = kind;
838
+ this.code = code;
839
+ this.cause = cause;
840
+ this.name = "SubcCallError";
841
+ }
842
+ get detail() {
843
+ return this.cause instanceof SubcError ? this.cause.detail : undefined;
844
+ }
845
+ }
846
+
847
+ class SubcError extends Error {
848
+ code;
849
+ detail;
850
+ constructor(message, code, detail) {
851
+ super(message);
852
+ this.code = code;
853
+ this.detail = detail;
854
+ }
855
+ }
856
+ function requireBinaryBody(body) {
857
+ if (body instanceof Uint8Array)
858
+ return body;
859
+ const type = body === null ? "null" : Array.isArray(body) ? "array" : typeof body;
860
+ throw new SubcError(`binary request body must be a Uint8Array; got ${type}`, "binary_body_required");
861
+ }
862
+ class SubcClient {
863
+ sock;
864
+ currentConn;
865
+ opts;
866
+ nextCorr = 1n;
867
+ pending = new Map;
868
+ lateResponses = new Map;
869
+ routes = new Map;
870
+ liveRoutes = new Map;
871
+ connectionToken = newConnectionToken();
872
+ ingressEpochDropCount = 0;
873
+ closedErr = null;
874
+ closeStarted = false;
875
+ reconnecting = null;
876
+ generation = 1;
877
+ readerActive = false;
878
+ constructor(sock, currentConn, opts) {
879
+ this.sock = sock;
880
+ this.currentConn = currentConn;
881
+ this.opts = opts;
882
+ this.readLoop(sock, this.generation);
883
+ }
884
+ get conn() {
885
+ return this.currentConn;
886
+ }
887
+ static async connect(opts) {
888
+ const normalized = normalizeConnectOptions(opts);
889
+ const opened = await SubcClient.openConnection(normalized);
890
+ return new SubcClient(opened.sock, opened.conn, normalized);
891
+ }
892
+ async catalogList(moduleId) {
893
+ const body = this.encode(moduleId === undefined ? { op: "catalog.list" } : { op: "catalog.list", module_id: moduleId });
894
+ const reply = await this.controlRpc(body);
895
+ const parsed = this.parseJson(reply);
896
+ return parsed.modules ?? [];
897
+ }
898
+ async resolveProvider(capability) {
899
+ const claimants = await this.resolveProviders(capability);
900
+ if (claimants.length === 0) {
901
+ throw new SubcError(`no catalog claimant for capability ${capability}`, "capability_unprovided");
902
+ }
903
+ if (claimants.length > 1) {
904
+ throw new SubcError(`multiple catalog claimants for capability ${capability}: ${claimants.join(", ")}`, "capability_ambiguous");
905
+ }
906
+ return claimants[0];
907
+ }
908
+ async resolveProviders(capability) {
909
+ if (!isValidCapabilityIdentifier(capability)) {
910
+ throw new SubcError(`malformed capability identifier ${JSON.stringify(capability)}`, "invalid_capability_identifier");
911
+ }
912
+ const modules = await this.catalogList();
913
+ return modules.filter((module) => module.capabilities?.provides.includes(capability) ?? false).map((module) => module.module_id).sort();
914
+ }
915
+ async routeOpen(target, identity, opts = {}) {
916
+ const consumerIdentity = routeOpenConsumerIdentity(opts);
917
+ const consumerCapabilities = opts.consumerCapabilities;
918
+ const body = this.encode({
919
+ op: "route.open",
920
+ target,
921
+ identity,
922
+ ...consumerIdentity ? { consumer_identity: consumerIdentity } : {},
923
+ ...consumerCapabilities !== undefined ? { consumer_capabilities: consumerCapabilities } : {}
924
+ });
925
+ let installed = null;
926
+ const install = (frame) => {
927
+ if (frame.header.ty !== FrameType.Response)
928
+ return true;
929
+ const parsed = this.parseJson(frame);
930
+ if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number") {
931
+ throw new SubcError(`route.open returned no route handle: ${JSON.stringify(parsed)}`);
932
+ }
933
+ installed = this.installRoute(parsed.route_channel, parsed.route_epoch);
934
+ return true;
935
+ };
936
+ const closeLateRoute = (frame) => {
937
+ if (frame.header.ty !== FrameType.Response)
938
+ return;
939
+ try {
940
+ const parsed = this.parseJson(frame);
941
+ if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number")
942
+ return;
943
+ const lateHandle = this.installRoute(parsed.route_channel, parsed.route_epoch);
944
+ this.failHandle(lateHandle, new SubcError("late route.open was closed", "route_closed"));
945
+ this.liveRoutes.delete(lateHandle.channel);
946
+ this.sendRouteGoodbye(lateHandle, true);
947
+ } catch {
948
+ this.closeConnectionAfterCleanupFailure();
949
+ }
950
+ };
951
+ await this.controlRpc(body, install, closeLateRoute);
952
+ if (!installed)
953
+ throw new SubcError("route.open response was not installed");
954
+ return installed;
955
+ }
956
+ async request(handle, body, opts = {}) {
957
+ this.assertLiveHandle(handle);
958
+ const binary = opts.binary ?? false;
959
+ const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
960
+ const priority = opts.priority ?? Priority.Interactive;
961
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
962
+ const reply = await this.send(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, undefined, undefined, binary);
963
+ return this.decodeReply(reply);
964
+ }
965
+ async call(moduleId, method, params, opts = {}) {
966
+ if (opts.binary) {
967
+ throw new SubcError("call() builds a JSON body and cannot send a binary request; use callBinary(moduleId, body, opts) with a Uint8Array", "binary_call_requires_call_binary");
968
+ }
969
+ const body = params === undefined ? { method } : { method, params };
970
+ return await this.managedCall(moduleId, body, opts);
971
+ }
972
+ async callBinary(moduleId, body, opts = {}) {
973
+ const bytes = requireBinaryBody(body);
974
+ return this.managedCall(moduleId, bytes, { ...opts, binary: true });
975
+ }
976
+ async managedCall(moduleId, body, opts) {
977
+ let retriedUnknownChannel = false;
978
+ for (;; ) {
979
+ const routeHandle = await this.cachedRouteHandle(moduleId, opts);
980
+ try {
981
+ return await this.managedRequest(routeHandle, body, opts);
982
+ } catch (err) {
983
+ if (!(err instanceof SubcCallError))
984
+ throw this.terminalCallError("managed call failed", err);
985
+ const deadBindCode = err.code === "unknown_channel" || err.code === "stale_route_epoch";
986
+ if (deadBindCode && !retriedUnknownChannel && !this.closeStarted) {
987
+ retriedUnknownChannel = true;
988
+ this.evictRouteHandle(routeHandle);
989
+ continue;
990
+ }
991
+ if (deadBindCode && retriedUnknownChannel) {
992
+ this.evictRouteHandle(routeHandle);
993
+ }
994
+ if (err.kind === "not_sent") {
995
+ try {
996
+ await this.reconnectAfterDrop(err);
997
+ } catch (reconnectErr) {
998
+ throw this.notSentRecoveryError("managed call was not sent", reconnectErr);
999
+ }
1000
+ continue;
1001
+ }
1002
+ if (err.kind === "outcome_unknown" && err.code !== DEADLINE_NO_DROP_CODE) {
1003
+ this.scheduleReconnectAfterDrop(err);
1004
+ } else if (err.kind === "outcome_unknown" && err.code === DEADLINE_NO_DROP_CODE) {
1005
+ this.probeLivenessAfterDeadline();
1006
+ }
1007
+ throw err;
1008
+ }
1009
+ }
1010
+ }
1011
+ subscribe(handle, body, onEvent, opts = {}) {
1012
+ this.assertLiveHandle(handle);
1013
+ const bytes = body instanceof Uint8Array ? body : this.encode(body);
1014
+ const priority = opts.priority ?? Priority.Interactive;
1015
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
1016
+ const corr = this.allocateCorr();
1017
+ const key = pendingKey(handle, corr);
1018
+ let subscriptionPending = null;
1019
+ let resolveClosed = null;
1020
+ const closed = new Promise((resolve, reject) => {
1021
+ if (this.closedErr) {
1022
+ reject(this.closedErr);
1023
+ return;
1024
+ }
1025
+ resolveClosed = resolve;
1026
+ subscriptionPending = {
1027
+ handle,
1028
+ resolve: () => resolve(),
1029
+ reject,
1030
+ onProgress: onEvent,
1031
+ timer: null,
1032
+ subscription: true
1033
+ };
1034
+ this.pending.set(key, subscriptionPending);
1035
+ const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), handle.channel, handle.epoch, corr, bytes);
1036
+ writeBorrowed(this.sock, encodeFrame(frame), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch((err) => {
1037
+ const pending = this.pending.get(key);
1038
+ if (pending)
1039
+ this.rejectPending(key, pending, err instanceof Error ? err : new SubcError(String(err)));
1040
+ });
1041
+ });
1042
+ let cancelled = false;
1043
+ const unsubscribe = () => {
1044
+ if (cancelled)
1045
+ return;
1046
+ cancelled = true;
1047
+ if (subscriptionPending && resolveClosed)
1048
+ this.settle(key, subscriptionPending, resolveClosed);
1049
+ if (this.isLiveHandle(handle))
1050
+ this.cancel(handle, corr, priority);
1051
+ };
1052
+ return { unsubscribe, closed };
1053
+ }
1054
+ cancel(handle, corr, priority = Priority.Interactive) {
1055
+ this.assertLiveHandle(handle);
1056
+ const cancel = buildFrame(FrameType.Cancel, buildFlags(false, priority, false), handle.channel, handle.epoch, corr, EMPTY_BODY);
1057
+ writeBorrowed(this.sock, encodeFrame(cancel), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch(() => {
1058
+ return;
1059
+ });
1060
+ }
1061
+ async routePoll(handle, kind) {
1062
+ this.assertLiveHandle(handle);
1063
+ const body = this.encode({
1064
+ op: "route.poll",
1065
+ route_channel: handle.channel,
1066
+ route_epoch: handle.epoch,
1067
+ kind
1068
+ });
1069
+ const reply = await this.controlRpc(body, (frame) => {
1070
+ if (frame.header.ty !== FrameType.Response)
1071
+ return true;
1072
+ const parsed = this.parseJson(frame);
1073
+ return parsed.route_channel === handle.channel && parsed.route_epoch === handle.epoch;
1074
+ });
1075
+ return this.parseJson(reply);
1076
+ }
1077
+ async closeRoute(handle, opts = {}) {
1078
+ this.assertLiveHandle(handle);
1079
+ for (const [key, cached] of this.routes) {
1080
+ if (cached.handle && sameRouteHandle(cached.handle, handle)) {
1081
+ cached.closed = true;
1082
+ cached.handle = null;
1083
+ this.routes.delete(key);
1084
+ }
1085
+ }
1086
+ if (opts.drain)
1087
+ await this.drainUnaryOnHandle(handle);
1088
+ this.failHandle(handle, new SubcError("route closed by closeRoute", "route_closed"));
1089
+ if (this.liveRoutes.get(handle.channel) === handle)
1090
+ this.liveRoutes.delete(handle.channel);
1091
+ this.sendRouteGoodbye(handle);
1092
+ }
1093
+ async closeManagedRoute(target, identity, opts = {}) {
1094
+ const key = routeCacheKey(target, identity, routeOpenConsumerIdentity(opts));
1095
+ const cached = this.routes.get(key);
1096
+ if (!cached)
1097
+ return;
1098
+ cached.closed = true;
1099
+ this.routes.delete(key);
1100
+ const handle = cached.handle;
1101
+ cached.handle = null;
1102
+ if (handle)
1103
+ await this.closeRoute(handle, opts);
1104
+ }
1105
+ async closeRouteChannel(handle, opts = {}) {
1106
+ await this.closeRoute(handle, opts);
1107
+ }
1108
+ close() {
1109
+ this.closeStarted = true;
1110
+ this.fail(new SubcError("client closed"));
1111
+ this.sock.close();
1112
+ }
1113
+ drainUnaryOnHandle(handle) {
1114
+ const waiters = [];
1115
+ for (const pending of this.pending.values()) {
1116
+ if (pending.handle === handle && !pending.subscription) {
1117
+ waiters.push(new Promise((resolve) => {
1118
+ const previous = pending.onSettle;
1119
+ pending.onSettle = () => {
1120
+ previous?.();
1121
+ resolve();
1122
+ };
1123
+ }));
1124
+ }
1125
+ }
1126
+ return Promise.all(waiters).then(() => {
1127
+ return;
1128
+ });
1129
+ }
1130
+ sendRouteGoodbye(handle, closeOnQueueFailure = false) {
1131
+ this.assertLiveConnection(handle);
1132
+ if (this.closedErr) {
1133
+ if (closeOnQueueFailure)
1134
+ this.closeConnectionAfterCleanupFailure();
1135
+ return;
1136
+ }
1137
+ const goodbye = buildFrame(FrameType.Goodbye, buildFlags(false, Priority.Interactive, false), handle.channel, handle.epoch, 0n, EMPTY_BODY);
1138
+ const write = writeTrackedBorrowed(this.sock, encodeFrame(goodbye), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS);
1139
+ if (!write.queued && closeOnQueueFailure)
1140
+ this.closeConnectionAfterCleanupFailure();
1141
+ write.completed.catch(() => {
1142
+ if (closeOnQueueFailure && !write.queued)
1143
+ this.closeConnectionAfterCleanupFailure();
1144
+ });
1145
+ }
1146
+ static async openConnection(opts) {
1147
+ const conn = await readConnectionFile(opts.connectionFile);
1148
+ const deadline = Date.now() + (opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);
1149
+ const endpoint = conn.endpoints[0];
1150
+ const sock = await SubcSocket.connect(endpoint.host, endpoint.port, deadline);
1151
+ try {
1152
+ await authenticateClient(sock, conn, deadline);
1153
+ } catch (err) {
1154
+ sock.close();
1155
+ throw err;
1156
+ }
1157
+ return { sock, conn };
1158
+ }
1159
+ async controlRpc(body, acceptFrame, onLateResponse) {
1160
+ return this.send(null, body, Priority.Interactive, AdmissionClass.Normal, undefined, undefined, acceptFrame, onLateResponse);
1161
+ }
1162
+ send(handle, body, priority, admission, timeoutMs, onProgress, acceptFrame, onLateResponse, binary = false) {
1163
+ if (handle)
1164
+ this.assertLiveHandle(handle);
1165
+ if (this.closedErr)
1166
+ return Promise.reject(this.closedErr);
1167
+ let corr;
1168
+ try {
1169
+ corr = this.allocateCorr();
1170
+ } catch (error) {
1171
+ return Promise.reject(error);
1172
+ }
1173
+ const key = pendingKey(handle, corr);
1174
+ const channel = handle?.channel ?? 0;
1175
+ const epoch = handle?.epoch ?? 0;
1176
+ const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), channel, epoch, corr, body);
1177
+ return new Promise((resolve, reject) => {
1178
+ const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1179
+ const pending = {
1180
+ handle,
1181
+ resolve,
1182
+ reject,
1183
+ onProgress,
1184
+ timer: null,
1185
+ acceptFrame,
1186
+ onLateResponse
1187
+ };
1188
+ pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, channel, corr, ms), ms);
1189
+ this.pending.set(key, pending);
1190
+ writeBorrowed(this.sock, encodeFrame(frame), Date.now() + ms).catch((error) => {
1191
+ const current = this.pending.get(key);
1192
+ if (current)
1193
+ this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
1194
+ });
1195
+ });
1196
+ }
1197
+ arbitrateTimeout(key, pending, channel, corr, ms) {
1198
+ const settleAsTimeout = () => {
1199
+ if (pending.onLateResponse)
1200
+ this.lateResponses.set(key, pending.onLateResponse);
1201
+ this.rejectPending(key, pending, new SubcError(this.timeoutMessage(channel, corr, ms), REQUEST_DEADLINE_MARKER));
1202
+ };
1203
+ const graceDeadline = Date.now() + this.opts.timeoutArbitrationGraceMs;
1204
+ const arbitrate = () => {
1205
+ if (this.pending.get(key) !== pending)
1206
+ return;
1207
+ const readerDraining = this.readerActive || this.sock.bufferedBytes() > 0;
1208
+ if (readerDraining && Date.now() < graceDeadline) {
1209
+ setImmediate(arbitrate);
1210
+ return;
1211
+ }
1212
+ settleAsTimeout();
1213
+ };
1214
+ setImmediate(arbitrate);
1215
+ }
1216
+ async managedRequest(handle, body, opts) {
1217
+ const binary = opts.binary ?? false;
1218
+ const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
1219
+ const priority = opts.priority ?? Priority.Interactive;
1220
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
1221
+ try {
1222
+ const reply = await this.sendManaged(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, binary);
1223
+ return this.decodeReply(reply);
1224
+ } catch (error) {
1225
+ if (error instanceof SubcCallError)
1226
+ throw error;
1227
+ throw this.terminalCallError("managed call failed", error);
1228
+ }
1229
+ }
1230
+ sendManaged(handle, body, priority, admission, timeoutMs, onProgress, binary = false) {
1231
+ try {
1232
+ this.assertLiveHandle(handle);
1233
+ } catch (error) {
1234
+ return Promise.reject(this.notSentCallError("request used a stale route handle", error));
1235
+ }
1236
+ if (this.closedErr) {
1237
+ return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed", this.closedErr));
1238
+ }
1239
+ let corr;
1240
+ try {
1241
+ corr = this.allocateCorr();
1242
+ } catch (error) {
1243
+ return Promise.reject(this.notSentCallError("request correlation allocator was exhausted", error));
1244
+ }
1245
+ const key = pendingKey(handle, corr);
1246
+ const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), handle.channel, handle.epoch, corr, body);
1247
+ let handedToSocket = false;
1248
+ const classifyFailure = (error) => {
1249
+ if (!handedToSocket)
1250
+ return this.notSentCallError("request bytes were not queued to the subc socket", error);
1251
+ if (error instanceof SubcError && error.code === REQUEST_DEADLINE_MARKER) {
1252
+ return new SubcCallError("outcome_unknown", `managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${causeMessage(error)}`, DEADLINE_NO_DROP_CODE, error);
1253
+ }
1254
+ return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error);
1255
+ };
1256
+ return new Promise((resolve, reject) => {
1257
+ const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1258
+ const pending = {
1259
+ handle,
1260
+ resolve,
1261
+ reject,
1262
+ onProgress,
1263
+ timer: null,
1264
+ classifyFailure
1265
+ };
1266
+ pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, handle.channel, corr, ms), ms);
1267
+ this.pending.set(key, pending);
1268
+ const write = writeTrackedBorrowed(this.sock, encodeFrame(frame), Date.now() + ms);
1269
+ handedToSocket = write.queued;
1270
+ write.completed.catch((error) => {
1271
+ const current = this.pending.get(key);
1272
+ if (current)
1273
+ this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
1274
+ });
1275
+ });
1276
+ }
1277
+ async cachedRouteHandle(moduleId, opts) {
1278
+ const identity = opts.identity ?? this.opts.identity;
1279
+ if (!identity) {
1280
+ throw new SubcCallError("terminal", "managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })", "missing_identity");
1281
+ }
1282
+ const target = { kind: opts.targetKind ?? this.opts.targetKind, module_id: moduleId };
1283
+ const consumerIdentity = routeOpenConsumerIdentity(opts);
1284
+ const key = routeCacheKey(target, identity, consumerIdentity);
1285
+ let cached = this.routes.get(key);
1286
+ if (!cached) {
1287
+ cached = {
1288
+ key,
1289
+ moduleId,
1290
+ target,
1291
+ identity,
1292
+ consumerIdentity,
1293
+ handle: null,
1294
+ opening: null
1295
+ };
1296
+ this.routes.set(key, cached);
1297
+ }
1298
+ if (cached.handle && this.isLiveHandle(cached.handle))
1299
+ return cached.handle;
1300
+ if (!cached.opening) {
1301
+ cached.opening = this.openCachedRoute(cached).finally(() => {
1302
+ cached.opening = null;
1303
+ });
1304
+ }
1305
+ return cached.opening;
1306
+ }
1307
+ async openCachedRoute(cached) {
1308
+ const routeRetryDeadline = Date.now() + this.opts.routeOpenRetryDeadlineMs;
1309
+ let routeRetryDelay = this.opts.reconnectBackoff.baseMs;
1310
+ let routeRetryAttempt = 0;
1311
+ for (;; ) {
1312
+ if (cached.closed)
1313
+ throw this.routeClosedDuringOpen();
1314
+ try {
1315
+ await this.ensureConnectedForManaged();
1316
+ } catch (error) {
1317
+ throw this.notSentRecoveryError("route.open could not run because reconnect failed", error);
1318
+ }
1319
+ if (cached.handle && this.isLiveHandle(cached.handle))
1320
+ return cached.handle;
1321
+ try {
1322
+ const handle = await this.routeOpen(cached.target, cached.identity, {
1323
+ consumerIdentity: cached.consumerIdentity ?? null
1324
+ });
1325
+ if (cached.closed) {
1326
+ this.liveRoutes.delete(handle.channel);
1327
+ this.sendRouteGoodbye(handle);
1328
+ throw this.routeClosedDuringOpen();
1329
+ }
1330
+ cached.handle = handle;
1331
+ return handle;
1332
+ } catch (error) {
1333
+ if (error instanceof SubcCallError && error.code === "route_closed")
1334
+ throw error;
1335
+ if (!this.closeStarted && isConsumerReconnectTransient(error)) {
1336
+ try {
1337
+ await this.reconnectAfterDrop(error);
1338
+ } catch (reconnectError) {
1339
+ throw this.notSentRecoveryError("route.open was not sent and reconnect failed", reconnectError);
1340
+ }
1341
+ continue;
1342
+ }
1343
+ if (!this.closeStarted && error instanceof SubcError && isRetryableRouteOpenCode(error.code)) {
1344
+ routeRetryAttempt += 1;
1345
+ if (Date.now() < routeRetryDeadline) {
1346
+ await this.opts.sleep(routeRetryDelay);
1347
+ routeRetryDelay = Math.min(routeRetryDelay * 2, this.opts.reconnectBackoff.capMs);
1348
+ continue;
1349
+ }
1350
+ throw this.notSentCallError(`route.open failed for module ${cached.moduleId}: ${error.code} (retry deadline exhausted after ${routeRetryAttempt} attempts)`, error);
1351
+ }
1352
+ throw this.terminalCallError(`route.open failed for module ${cached.moduleId}`, error);
1353
+ }
1354
+ }
1355
+ }
1356
+ lastInboundAtMs = 0;
1357
+ livenessProbe = null;
1358
+ hasControlPending() {
1359
+ for (const pending of this.pending.values()) {
1360
+ if (pending.handle === null)
1361
+ return true;
1362
+ }
1363
+ return false;
1364
+ }
1365
+ probeLivenessAfterDeadline() {
1366
+ if (this.livenessProbe || this.closeStarted || this.closedErr)
1367
+ return;
1368
+ if (this.hasControlPending())
1369
+ return;
1370
+ const sock = this.sock;
1371
+ const generation = this.generation;
1372
+ let corr;
1373
+ try {
1374
+ corr = this.allocateCorr();
1375
+ } catch {
1376
+ return;
1377
+ }
1378
+ const t0 = Date.now();
1379
+ const ping = buildFrame(FrameType.Ping, buildFlags(false, Priority.Interactive, false, AdmissionClass.Normal), 0, 0, corr, new Uint8Array);
1380
+ const probe = (async () => {
1381
+ await writeBorrowed(sock, encodeFrame(ping), t0 + this.opts.livenessProbeWindowMs).catch(() => {});
1382
+ await this.opts.sleep(this.opts.livenessProbeWindowMs);
1383
+ if (this.sock !== sock || this.generation !== generation || this.closeStarted)
1384
+ return;
1385
+ if (this.lastInboundAtMs >= t0)
1386
+ return;
1387
+ if (this.hasControlPending())
1388
+ return;
1389
+ this.fail(new SocketClosedError(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`));
1390
+ sock.close();
1391
+ })().finally(() => {
1392
+ this.livenessProbe = null;
1393
+ });
1394
+ this.livenessProbe = probe;
1395
+ }
1396
+ async ensureConnectedForManaged() {
1397
+ if (this.closeStarted)
1398
+ throw new SubcError("client closed");
1399
+ if (this.reconnecting)
1400
+ await this.reconnecting;
1401
+ if (this.closedErr)
1402
+ await this.reconnectAfterDrop(this.closedErr);
1403
+ }
1404
+ scheduleReconnectAfterDrop(err) {
1405
+ if (this.closeStarted || this.reconnecting)
1406
+ return;
1407
+ this.reconnectAfterDrop(err).catch(() => {});
1408
+ }
1409
+ reconnectAfterDrop(trigger) {
1410
+ if (this.closeStarted)
1411
+ return Promise.reject(new SubcError("client closed"));
1412
+ if (this.reconnecting)
1413
+ return this.reconnecting;
1414
+ const promise = this.reconnectWithRetry(trigger).finally(() => {
1415
+ if (this.reconnecting === promise)
1416
+ this.reconnecting = null;
1417
+ });
1418
+ this.reconnecting = promise;
1419
+ return promise;
1420
+ }
1421
+ async reconnectWithRetry(_trigger) {
1422
+ let attempt = 0;
1423
+ let delay = this.opts.reconnectBackoff.baseMs;
1424
+ for (;; ) {
1425
+ if (this.closeStarted)
1426
+ throw new SubcError("client closed");
1427
+ attempt += 1;
1428
+ try {
1429
+ const opened = await SubcClient.openConnection(this.opts);
1430
+ if (this.closeStarted) {
1431
+ opened.sock.close();
1432
+ throw new SubcError("client closed");
1433
+ }
1434
+ this.replaceConnection(opened);
1435
+ await this.reopenCachedRoutes();
1436
+ return;
1437
+ } catch (err) {
1438
+ if (!isConsumerReconnectTransient(err) || attempt >= this.opts.reconnectBackoff.maxAttempts) {
1439
+ if (err instanceof AuthError && attempt > 1) {
1440
+ throw new AuthError(`reconnect gave up after ${attempt} attempts: ${err.message} — the connection file and the daemon's key disagree persistently ` + `(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); ` + `check the daemon, then restart this host app`);
1441
+ }
1442
+ throw err;
1443
+ }
1444
+ await this.opts.sleep(delay);
1445
+ delay = Math.min(delay * 2, this.opts.reconnectBackoff.capMs);
1446
+ }
1447
+ }
1448
+ }
1449
+ replaceConnection(opened) {
1450
+ this.sock.close();
1451
+ this.sock = opened.sock;
1452
+ this.currentConn = opened.conn;
1453
+ this.closedErr = null;
1454
+ this.generation += 1;
1455
+ this.connectionToken = newConnectionToken();
1456
+ this.liveRoutes.clear();
1457
+ this.lateResponses.clear();
1458
+ this.nextCorr = 1n;
1459
+ this.readLoop(opened.sock, this.generation);
1460
+ }
1461
+ async reopenCachedRoutes() {
1462
+ const routeKeys = [...this.routes.keys()];
1463
+ for (const key of routeKeys) {
1464
+ const cached = this.routes.get(key);
1465
+ if (cached)
1466
+ cached.handle = null;
1467
+ }
1468
+ for (const key of routeKeys) {
1469
+ const cached = this.routes.get(key);
1470
+ if (!cached || cached.closed)
1471
+ continue;
1472
+ try {
1473
+ const handle = await this.routeOpen(cached.target, cached.identity, {
1474
+ consumerIdentity: cached.consumerIdentity ?? null
1475
+ });
1476
+ if (cached.closed) {
1477
+ this.liveRoutes.delete(handle.channel);
1478
+ this.sendRouteGoodbye(handle);
1479
+ continue;
1480
+ }
1481
+ cached.handle = handle;
1482
+ } catch (error) {
1483
+ if (isRouteOpenRefusal(error)) {
1484
+ this.routes.delete(key);
1485
+ continue;
1486
+ }
1487
+ throw error;
1488
+ }
1489
+ }
1490
+ }
1491
+ timeoutMessage(channel, corr, ms) {
1492
+ const port = this.sock.localPort();
1493
+ const where = port === null ? "channel" : `local_port=${port} channel`;
1494
+ return `request on ${where} ${channel} corr ${corr} timed out after ${ms}ms`;
1495
+ }
1496
+ routeClosedDuringOpen() {
1497
+ return new SubcCallError("not_sent", "route was closed before route.open completed", "route_closed");
1498
+ }
1499
+ async readLoop(sock, generation) {
1500
+ try {
1501
+ for (;; ) {
1502
+ this.readerActive = false;
1503
+ const frame = await sock.readFrame(Number.POSITIVE_INFINITY, { afterHeaderMs: BODY_READ_TIMEOUT_MS }, () => {
1504
+ this.readerActive = true;
1505
+ });
1506
+ try {
1507
+ if (this.sock === sock && this.generation === generation)
1508
+ this.dispatch(frame);
1509
+ } finally {
1510
+ this.readerActive = false;
1511
+ }
1512
+ }
1513
+ } catch (error) {
1514
+ if (this.sock === sock && this.generation === generation) {
1515
+ this.fail(error instanceof Error ? error : new SubcError(String(error)));
1516
+ }
1517
+ }
1518
+ }
1519
+ dispatch(frame) {
1520
+ this.lastInboundAtMs = Date.now();
1521
+ if (frame.header.channel === 0 && frame.header.ty === FrameType.Push) {
1522
+ const observer = this.opts.onControlPush;
1523
+ if (observer) {
1524
+ let parsed = null;
1525
+ try {
1526
+ const body = this.parseJson(frame);
1527
+ if (body && typeof body.op === "string")
1528
+ parsed = { op: body.op, body };
1529
+ } catch {}
1530
+ if (parsed) {
1531
+ try {
1532
+ observer(parsed);
1533
+ } catch {}
1534
+ }
1535
+ }
1536
+ return;
1537
+ }
1538
+ let handle = null;
1539
+ if (frame.header.channel !== 0) {
1540
+ handle = this.liveRoutes.get(frame.header.channel) ?? null;
1541
+ if (!handle || handle.epoch !== frame.header.epoch) {
1542
+ this.ingressEpochDropCount += 1;
1543
+ return;
1544
+ }
1545
+ }
1546
+ const key = pendingKey(handle, frame.header.corr);
1547
+ const pending = this.pending.get(key);
1548
+ if (pending) {
1549
+ if (pending.acceptFrame && !pending.acceptFrame(frame))
1550
+ return;
1551
+ switch (frame.header.ty) {
1552
+ case FrameType.Push:
1553
+ case FrameType.StreamData:
1554
+ try {
1555
+ pending.onProgress?.(frame.body);
1556
+ } catch {}
1557
+ return;
1558
+ case FrameType.Response:
1559
+ case FrameType.StreamEnd:
1560
+ this.settle(key, pending, () => pending.resolve(frame));
1561
+ return;
1562
+ case FrameType.Error:
1563
+ this.settle(key, pending, () => pending.reject(this.errorFromFrame(frame)));
1564
+ return;
1565
+ default:
1566
+ return;
1567
+ }
1568
+ }
1569
+ const late = this.lateResponses.get(key);
1570
+ if (late && (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error)) {
1571
+ this.lateResponses.delete(key);
1572
+ late(frame);
1573
+ return;
1574
+ }
1575
+ if (frame.header.ty === FrameType.Goodbye && handle) {
1576
+ this.failHandle(handle, new SubcError("route closed by subc (GOODBYE)", "route_closed"));
1577
+ if (this.liveRoutes.get(handle.channel) === handle)
1578
+ this.liveRoutes.delete(handle.channel);
1579
+ this.evictRouteHandle(handle);
1580
+ return;
1581
+ }
1582
+ if (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error || frame.header.ty === FrameType.StreamEnd) {
1583
+ debug("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s", frame.header.ty, frame.header.channel, frame.header.epoch, frame.header.corr, this.sock.localPort() ?? "?");
1584
+ }
1585
+ }
1586
+ settle(key, pending, run) {
1587
+ if (this.pending.get(key) !== pending)
1588
+ return false;
1589
+ this.pending.delete(key);
1590
+ if (pending.timer)
1591
+ clearTimeout(pending.timer);
1592
+ run();
1593
+ pending.onSettle?.();
1594
+ return true;
1595
+ }
1596
+ rejectPending(key, pending, err) {
1597
+ this.settle(key, pending, () => pending.reject(pending.classifyFailure?.(err) ?? err));
1598
+ }
1599
+ errorFromFrame(frame) {
1600
+ try {
1601
+ const parsed = JSON.parse(Buffer.from(frame.body).toString("utf8"));
1602
+ return new SubcError(parsed.message ?? "subc error", parsed.code, parsed.detail);
1603
+ } catch {
1604
+ return new SubcError(Buffer.from(frame.body).toString("utf8") || "subc error");
1605
+ }
1606
+ }
1607
+ evictRouteHandle(handle) {
1608
+ for (const cached of this.routes.values()) {
1609
+ if (cached.handle && sameRouteHandle(cached.handle, handle))
1610
+ cached.handle = null;
1611
+ }
1612
+ }
1613
+ failHandle(handle, error) {
1614
+ for (const [key, pending] of this.pending) {
1615
+ if (pending.handle && sameRouteHandle(pending.handle, handle))
1616
+ this.rejectPending(key, pending, error);
1617
+ }
1618
+ }
1619
+ fail(err) {
1620
+ if (!this.closedErr)
1621
+ this.closedErr = err;
1622
+ for (const [key, pending] of this.pending) {
1623
+ this.rejectPending(key, pending, err);
1624
+ }
1625
+ }
1626
+ notSentCallError(message, cause) {
1627
+ return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1628
+ }
1629
+ outcomeUnknownCallError(message, cause) {
1630
+ return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1631
+ }
1632
+ terminalCallError(message, cause) {
1633
+ if (cause instanceof SubcCallError)
1634
+ return cause;
1635
+ return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1636
+ }
1637
+ notSentRecoveryError(message, cause) {
1638
+ if (cause instanceof SubcCallError)
1639
+ return cause;
1640
+ if (isConsumerReconnectTransient(cause))
1641
+ return this.notSentCallError(message, cause);
1642
+ return this.terminalCallError(message, cause);
1643
+ }
1644
+ get droppedIngressFrames() {
1645
+ return this.ingressEpochDropCount;
1646
+ }
1647
+ installRoute(channel, epoch) {
1648
+ const handle = createRouteHandle(channel, epoch, this.connectionToken);
1649
+ this.liveRoutes.set(channel, handle);
1650
+ return handle;
1651
+ }
1652
+ isLiveHandle(handle) {
1653
+ return belongsToConnection(handle, this.connectionToken) && this.liveRoutes.get(handle.channel) === handle;
1654
+ }
1655
+ assertLiveConnection(handle) {
1656
+ if (!belongsToConnection(handle, this.connectionToken))
1657
+ throw new StaleRouteHandleError(handle);
1658
+ }
1659
+ assertLiveHandle(handle) {
1660
+ if (!this.isLiveHandle(handle))
1661
+ throw new StaleRouteHandleError(handle);
1662
+ }
1663
+ allocateCorr() {
1664
+ const maximum = 0xffffffffffffffffn;
1665
+ if (this.nextCorr > maximum) {
1666
+ const error = new SubcError("channel-0 correlation id allocator exhausted", "corr_exhausted");
1667
+ this.fail(error);
1668
+ this.sock.close();
1669
+ this.scheduleReconnectAfterDrop(error);
1670
+ throw error;
1671
+ }
1672
+ const corr = this.nextCorr;
1673
+ this.nextCorr += 1n;
1674
+ return corr;
1675
+ }
1676
+ closeConnectionAfterCleanupFailure() {
1677
+ const error = new SubcError("late route cleanup could not be queued", "late_route_cleanup_failed");
1678
+ this.fail(error);
1679
+ this.sock.close();
1680
+ this.scheduleReconnectAfterDrop(error);
1681
+ }
1682
+ encode(value) {
1683
+ return Buffer.from(JSON.stringify(value), "utf8");
1684
+ }
1685
+ decodeReply(frame) {
1686
+ return hasBinary(frame.header.flags) ? frame.body : this.parseJson(frame);
1687
+ }
1688
+ parseJson(frame) {
1689
+ const b = frame.body;
1690
+ return JSON.parse(Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("utf8"));
1691
+ }
1692
+ }
1693
+ function isConsumerReconnectTransient(err) {
1694
+ if (err instanceof SocketClosedError || err instanceof SocketTimeoutError)
1695
+ return true;
1696
+ if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError)
1697
+ return true;
1698
+ if (err instanceof SubcCallError)
1699
+ return err.kind === "not_sent" || err.kind === "outcome_unknown";
1700
+ if (err instanceof AuthError)
1701
+ return true;
1702
+ if (err instanceof SubcError || err instanceof ConnectionFileError)
1703
+ return false;
1704
+ const code = errorCode(err);
1705
+ return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
1706
+ }
1707
+ function isRouteOpenRefusal(err) {
1708
+ return err instanceof SubcError && typeof err.code === "string";
1709
+ }
1710
+ function isRetryableRouteOpenCode(code) {
1711
+ if (code === "capability_forbidden")
1712
+ return false;
1713
+ return code === "unknown_module" || code === "module_reloading" || code === "module_warming" || code === "target_unavailable" || code === "module_timeout";
1714
+ }
1715
+ async function connectionFileExists(path) {
1716
+ try {
1717
+ await fs2.access(path);
1718
+ return true;
1719
+ } catch {
1720
+ return false;
1721
+ }
1722
+ }
1723
+ function normalizeConnectOptions(opts) {
1724
+ return {
1725
+ connectionFile: opts.connectionFile,
1726
+ handshakeTimeoutMs: opts.handshakeTimeoutMs,
1727
+ identity: opts.identity,
1728
+ targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
1729
+ reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
1730
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
1731
+ routeOpenRetryDeadlineMs: opts.routeOpenRetryDeadlineMs ?? ROUTE_OPEN_RETRY_DEADLINE_MS,
1732
+ timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS,
1733
+ livenessProbeWindowMs: opts.livenessProbeWindowMs ?? LIVENESS_PROBE_WINDOW_MS,
1734
+ onControlPush: opts.onControlPush
1735
+ };
1736
+ }
1737
+ function isValidCapabilityIdentifier(identifier) {
1738
+ if (/\s/u.test(identifier))
1739
+ return false;
1740
+ const separator = identifier.indexOf("/v");
1741
+ if (separator <= 0 || identifier.indexOf("/v", separator + 1) !== -1)
1742
+ return false;
1743
+ const name = identifier.slice(0, separator);
1744
+ const version = identifier.slice(separator + 2);
1745
+ if (new TextEncoder().encode(name).byteLength > 64 || version.length === 0)
1746
+ return false;
1747
+ if (!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test(name) && !/^[a-z]$/u.test(name))
1748
+ return false;
1749
+ if (name.includes("--"))
1750
+ return false;
1751
+ if (!/^\d+$/u.test(version) || version.length > 1 && version.startsWith("0"))
1752
+ return false;
1753
+ const numericVersion = Number(version);
1754
+ return Number.isSafeInteger(numericVersion) && numericVersion >= 1 && numericVersion <= 4294967295;
1755
+ }
1756
+ function routeCacheKey(target, identity, consumerIdentity) {
1757
+ const consumerPart = consumerIdentity ? `${consumerIdentity.module_id}\x00${consumerIdentity.launch_nonce}` : "";
1758
+ return `${target.kind}\x00${target.module_id}\x00${identity.project_root}\x00${identity.harness}\x00${identity.session}\x00${consumerPart}`;
1759
+ }
1760
+ function routeOpenConsumerIdentity(opts = {}) {
1761
+ if (opts.consumerIdentity !== undefined)
1762
+ return opts.consumerIdentity ?? undefined;
1763
+ const moduleId = process.env[SUBC_MODULE_ID_ENV];
1764
+ const launchNonce = process.env[SUBC_LAUNCH_NONCE_ENV];
1765
+ if (!moduleId || !launchNonce)
1766
+ return;
1767
+ return { module_id: moduleId, launch_nonce: launchNonce };
1768
+ }
1769
+ function errorCode(err) {
1770
+ if (typeof err === "object" && err !== null && "code" in err) {
1771
+ const code = err.code;
1772
+ if (typeof code === "string")
1773
+ return code;
1774
+ }
1775
+ return;
1776
+ }
1777
+ function causeMessage(cause) {
1778
+ if (cause === undefined)
1779
+ return "";
1780
+ return `: ${cause instanceof Error ? cause.message : String(cause)}`;
1781
+ }
1782
+ function pendingKey(handle, corr) {
1783
+ return handle ? `${handle.channel}:${handle.epoch}:${corr}` : `0:0:${corr}`;
1784
+ }
1785
+ // src/features/magic-context/memory/embedding-synapse.ts
1786
+ var SYNAPSE_DEFAULT_MODEL = "gte-modernbert-base-f16";
1787
+ var SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS = 3000;
1788
+ var SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS = 120000;
1789
+ var SYNAPSE_CERTIFICATION_REFUSAL_REASONS = new Set([
1790
+ "not_certified",
1791
+ "probe_required",
1792
+ "migration_required"
1793
+ ]);
1794
+ var embeddingRowMetadata = new WeakMap;
1795
+ function isSynapseEmbeddingTruncated(vector) {
1796
+ return embeddingRowMetadata.get(vector)?.truncated === true;
1797
+ }
1798
+ function toSynapseLaneDescriptor(metadata) {
1799
+ const tokenBudget = metadata.recommended_token_budget;
1800
+ return {
1801
+ lane: metadata.model,
1802
+ ...metadata.device_class ? { device_class: metadata.device_class } : {},
1803
+ max_tokens: metadata.max_tokens,
1804
+ max_tokens_source: metadata.max_tokens_source,
1805
+ ...metadata.bucket_ladder ? { bucket_ladder: [...metadata.bucket_ladder] } : {},
1806
+ ...metadata.dims ? { dims: metadata.dims } : {},
1807
+ ...metadata.dtype ? { dtype: metadata.dtype } : {},
1808
+ ...typeof metadata.certified === "boolean" ? { certified: metadata.certified } : {},
1809
+ ...metadata.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: metadata.warm_load_cost_hint_ms } : {},
1810
+ ...metadata.recommended_batch ? {
1811
+ recommended_batch: {
1812
+ rows: metadata.recommended_batch,
1813
+ ...tokenBudget !== undefined ? { token_budget: tokenBudget } : {}
1814
+ }
1815
+ } : {},
1816
+ warm: metadata.max_tokens_source === "runtime_bucket" || metadata.max_tokens_source === "worker_bucket"
1817
+ };
1818
+ }
1819
+ function formatSynapseLaneDescriptor(descriptor) {
1820
+ const certified = descriptor.certified === undefined ? "unknown" : String(descriptor.certified);
1821
+ return `lane=${descriptor.lane}; device_class=${descriptor.device_class ?? "unknown"}; ` + `max_tokens=${descriptor.max_tokens} (${descriptor.max_tokens_source}); ` + `certified=${certified}; warm=${descriptor.warm ? "yes" : "no"}; ` + `warm_load_cost_hint_ms=${descriptor.warm_load_cost_hint_ms ?? "unknown"}`;
1822
+ }
1823
+
1824
+ class SynapseEmbeddingError extends Error {
1825
+ code;
1826
+ retryAfterMs;
1827
+ permanent;
1828
+ refusalReason;
1829
+ constructor(code, message, options) {
1830
+ super(message, options?.cause === undefined ? undefined : { cause: options.cause });
1831
+ this.name = "SynapseEmbeddingError";
1832
+ this.code = code;
1833
+ this.permanent = options?.permanent ?? isPermanentSynapseCode(code);
1834
+ this.retryAfterMs = options?.retryAfterMs ?? (this.permanent ? undefined : 100);
1835
+ this.refusalReason = options?.refusalReason;
1836
+ }
1837
+ }
1838
+ function isPermanentSynapseCode(code) {
1839
+ return code === "artifact_invalid" || code === "substitution_rejected" || code === "not_certified" || code === "probe_required" || code === "idempotency_conflict" || code === "schema_violation" || code === "certification_refused" || code === "needs_reauth";
1840
+ }
1841
+ function asRecord(value) {
1842
+ return value !== null && typeof value === "object" ? value : null;
1843
+ }
1844
+ function responseBody(value) {
1845
+ const record = asRecord(value);
1846
+ const result = asRecord(record?.result);
1847
+ const payload = asRecord(result?.payload ?? record?.payload);
1848
+ return {
1849
+ ...record ?? {},
1850
+ ...result ?? {},
1851
+ ...payload ?? {}
1852
+ };
1853
+ }
1854
+ function readRetryAfter(value) {
1855
+ const record = asRecord(value);
1856
+ const candidate = record?.retry_after_ms ?? record?.retryAfterMs;
1857
+ if (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)
1858
+ return;
1859
+ return Math.ceil(candidate);
1860
+ }
1861
+ function readErrorCode(value) {
1862
+ const record = asRecord(value);
1863
+ if (typeof record?.code === "string")
1864
+ return record.code;
1865
+ if (value instanceof Error && "code" in value && typeof value.code === "string") {
1866
+ return value.code;
1867
+ }
1868
+ return;
1869
+ }
1870
+ function readCertificationRefusalReason(value) {
1871
+ if (!(value instanceof SubcCallError))
1872
+ return;
1873
+ const detail = value.detail;
1874
+ if (typeof detail === "string")
1875
+ return detail;
1876
+ const record = asRecord(detail);
1877
+ return typeof record?.reason === "string" ? record.reason : undefined;
1878
+ }
1879
+ function classifyError(value) {
1880
+ if (value instanceof SynapseEmbeddingError)
1881
+ return value;
1882
+ const code = readErrorCode(value) ?? (value instanceof Error ? value.name : "transport");
1883
+ const normalized = code.toLowerCase();
1884
+ const refusalReason = readCertificationRefusalReason(value);
1885
+ let mapped = "transport";
1886
+ if (normalized.includes("queue_full"))
1887
+ mapped = "queue_full";
1888
+ else if (normalized.includes("model_loading"))
1889
+ mapped = "model_loading";
1890
+ else if (normalized.includes("timeout") || normalized.includes("deadline"))
1891
+ mapped = "timeout";
1892
+ else if (normalized.includes("artifact_invalid"))
1893
+ mapped = "artifact_invalid";
1894
+ else if (normalized.includes("substitution"))
1895
+ mapped = "substitution_rejected";
1896
+ else if (normalized === "certification_refused")
1897
+ mapped = "certification_refused";
1898
+ else if (normalized.includes("not_certified"))
1899
+ mapped = "not_certified";
1900
+ else if (normalized.includes("probe_required"))
1901
+ mapped = "probe_required";
1902
+ else if (normalized.includes("idempotency_conflict"))
1903
+ mapped = "idempotency_conflict";
1904
+ else if (normalized.includes("needs_reauth"))
1905
+ mapped = "needs_reauth";
1906
+ else if (normalized.includes("schema"))
1907
+ mapped = "schema_violation";
1908
+ else if (normalized.includes("module_restarted") || normalized.includes("module restarted"))
1909
+ mapped = "module_restarted";
1910
+ const message = value instanceof Error ? value.message : String(value);
1911
+ return new SynapseEmbeddingError(mapped, message, {
1912
+ retryAfterMs: readRetryAfter(value) ?? (isPermanentSynapseCode(mapped) ? undefined : 100),
1913
+ cause: value,
1914
+ refusalReason
1915
+ });
1916
+ }
1917
+ function embeddingFailureFor(error) {
1918
+ const typedReason = error.refusalReason;
1919
+ if (typedReason !== undefined && SYNAPSE_CERTIFICATION_REFUSAL_REASONS.has(typedReason) || error.code === "not_certified" || error.code === "probe_required") {
1920
+ return {
1921
+ class: "certification_refusal",
1922
+ reason: `SYNAPSE certification refused embedding: ${typedReason ?? error.code}`,
1923
+ retryable: false
1924
+ };
1925
+ }
1926
+ if (error.code === "certification_refused") {
1927
+ return {
1928
+ class: "certification_refusal",
1929
+ reason: `SYNAPSE certification refused embedding: ${typedReason ?? "unknown reason"}`,
1930
+ retryable: false
1931
+ };
1932
+ }
1933
+ if (typedReason === "needs_reauth" || typedReason === "needs_reauth_expired") {
1934
+ return {
1935
+ class: "credential_required",
1936
+ reason: "SYNAPSE requires reauthentication",
1937
+ retryable: false
1938
+ };
1939
+ }
1940
+ if (error.code === "substitution_rejected") {
1941
+ return { class: "substitution_rejected", reason: error.message, retryable: false };
1942
+ }
1943
+ if (error.code === "schema_violation" || error.code === "artifact_invalid") {
1944
+ return { class: "invalid_envelope", reason: error.message, retryable: false };
1945
+ }
1946
+ return { class: "transport_error", reason: error.message, retryable: !error.permanent };
1947
+ }
1948
+ function wait(ms) {
1949
+ return new Promise((resolve) => setTimeout(resolve, ms));
1950
+ }
1951
+ function sha256(value) {
1952
+ return createHash("sha256").update(value).digest("hex");
1953
+ }
1954
+ function stableJson(value) {
1955
+ if (Array.isArray(value))
1956
+ return `[${value.map(stableJson).join(",")}]`;
1957
+ if (value && typeof value === "object") {
1958
+ return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
1959
+ }
1960
+ return JSON.stringify(value);
1961
+ }
1962
+ function getSynapseLaneIdentity(model, fingerprint) {
1963
+ return `synapse:v1:${sha256(stableJson({ model, fingerprint }))}`;
1964
+ }
1965
+ function getSynapseBatchRequestKey(args) {
1966
+ return sha256(stableJson({
1967
+ op: "embed.batch",
1968
+ model: args.model,
1969
+ required_fingerprint: args.fingerprint,
1970
+ required_epoch: args.tableEpoch,
1971
+ allow_equivalent: false,
1972
+ accept_declared: false,
1973
+ ids: args.items.map((item) => item.id),
1974
+ content_sha256: args.items.map((item) => item.contentSha256),
1975
+ ...args.purpose === "query" ? { purpose: args.purpose } : {}
1976
+ }));
1977
+ }
1978
+ function hashContent(text) {
1979
+ return sha256(text);
1980
+ }
1981
+ function extractCatalogEntries(value) {
1982
+ const body = responseBody(value);
1983
+ const raw = Array.isArray(body.models) ? body.models : Array.isArray(body.entries) ? body.entries : Array.isArray(value) ? value : [];
1984
+ const envelopeEpoch = typeof body.table_epoch === "number" && Number.isInteger(body.table_epoch) ? body.table_epoch : undefined;
1985
+ const maxTokenSources = new Set([
1986
+ "runtime_bucket",
1987
+ "worker_bucket",
1988
+ "catalog",
1989
+ "catalog_unloaded"
1990
+ ]);
1991
+ return raw.flatMap((entry) => {
1992
+ const record = asRecord(entry);
1993
+ if (!record)
1994
+ return [];
1995
+ const model = typeof record.model === "string" && record.model.length > 0 ? record.model : typeof record.model_id === "string" ? record.model_id : "";
1996
+ const fingerprint = typeof record.fingerprint === "string" && record.fingerprint.length > 0 ? record.fingerprint : Array.isArray(record.fingerprints) && typeof record.fingerprints[0] === "string" ? record.fingerprints[0] : "";
1997
+ const entryEpoch = record.table_epoch ?? record.tableEpoch;
1998
+ const tableEpoch = typeof entryEpoch === "number" && Number.isInteger(entryEpoch) ? entryEpoch : envelopeEpoch;
1999
+ const maxTokens = record.max_tokens;
2000
+ const maxTokensSource = record.max_tokens_source;
2001
+ if (model.length === 0 || fingerprint.length === 0 || typeof tableEpoch !== "number" || !Number.isInteger(tableEpoch) || typeof maxTokens !== "number" || !Number.isInteger(maxTokens) || maxTokens <= 0 || typeof maxTokensSource !== "string" || !maxTokenSources.has(maxTokensSource)) {
2002
+ return [];
2003
+ }
2004
+ const dims = record.dims ?? record.dimensions;
2005
+ const rawBatch = record.recommended_batch ?? record.recommendedBatch;
2006
+ const batchRecord = asRecord(rawBatch);
2007
+ const recommendedBatch = typeof rawBatch === "number" ? rawBatch : batchRecord ? batchRecord.rows : undefined;
2008
+ const recommendedTokenBudget = batchRecord ? batchRecord.token_budget : undefined;
2009
+ const bucketLadder = Array.isArray(record.bucket_ladder) ? record.bucket_ladder.filter((bucket) => typeof bucket === "number" && Number.isInteger(bucket) && bucket > 0) : undefined;
2010
+ const state = typeof record.state === "string" ? record.state : undefined;
2011
+ const warmLoadCostHint = record.warm_load_cost_hint_ms;
2012
+ return [
2013
+ {
2014
+ model,
2015
+ fingerprint,
2016
+ table_epoch: tableEpoch,
2017
+ max_tokens: maxTokens,
2018
+ max_tokens_source: maxTokensSource,
2019
+ ...bucketLadder && bucketLadder.length > 0 ? { bucket_ladder: [...new Set(bucketLadder)].sort((a, b) => a - b) } : {},
2020
+ ...typeof dims === "number" && Number.isInteger(dims) && dims > 0 ? { dims } : {},
2021
+ ...typeof record.dtype === "string" && record.dtype.length > 0 ? { dtype: record.dtype } : {},
2022
+ ...typeof record.device_class === "string" && record.device_class.length > 0 ? { device_class: record.device_class } : {},
2023
+ ...typeof recommendedBatch === "number" && recommendedBatch > 0 ? { recommended_batch: Math.floor(recommendedBatch) } : {},
2024
+ ...typeof recommendedTokenBudget === "number" && recommendedTokenBudget > 0 ? { recommended_token_budget: Math.floor(recommendedTokenBudget) } : {},
2025
+ ...record.provenance !== undefined ? { provenance: record.provenance } : {},
2026
+ ...typeof record.certified === "boolean" ? { certified: record.certified } : {},
2027
+ ...typeof warmLoadCostHint === "number" && Number.isFinite(warmLoadCostHint) && warmLoadCostHint >= 0 ? { warm_load_cost_hint_ms: warmLoadCostHint } : {},
2028
+ ...typeof record.status === "string" ? { status: record.status } : state ? { status: state } : {}
2029
+ }
2030
+ ];
2031
+ });
2032
+ }
2033
+ function extractVector(value) {
2034
+ const body = responseBody(value);
2035
+ const item = Array.isArray(body.vectors) ? asRecord(body.vectors[0]) : null;
2036
+ const raw = item?.vector;
2037
+ if (!item || !Array.isArray(raw) || raw.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
2038
+ return null;
2039
+ }
2040
+ const disclosure = Array.isArray(body.truncation_disclosures) ? asRecord(body.truncation_disclosures[0]) : null;
2041
+ return { vector: Float32Array.from(raw), item, disclosure, metadata: body };
2042
+ }
2043
+ function extractBatchItems(value) {
2044
+ const body = responseBody(value);
2045
+ const raw = Array.isArray(body.vectors) ? body.vectors : Array.isArray(body.items) ? body.items : Array.isArray(body.results) ? body.results : [];
2046
+ return raw.flatMap((item) => {
2047
+ const record = asRecord(item);
2048
+ return record ? [record] : [];
2049
+ });
2050
+ }
2051
+ function extractTruncationDisclosures(value) {
2052
+ const body = responseBody(value);
2053
+ if (!Array.isArray(body.truncation_disclosures))
2054
+ return [];
2055
+ return body.truncation_disclosures.map((disclosure) => asRecord(disclosure));
2056
+ }
2057
+ function validateWireRow(item, disclosure, expected) {
2058
+ const submittedSha256 = item.submitted_sha256;
2059
+ const contentSha256 = item.content_sha256;
2060
+ const expectedSubmittedSha256 = hashContent(expected.text);
2061
+ if (typeof submittedSha256 !== "string") {
2062
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted submitted_sha256`);
2063
+ }
2064
+ if (submittedSha256 !== expectedSubmittedSha256) {
2065
+ throw new SynapseEmbeddingError("schema_violation", `Synapse submitted hash mismatch for item ${expected.id}`);
2066
+ }
2067
+ if (typeof contentSha256 !== "string") {
2068
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted content_sha256`);
2069
+ }
2070
+ const hashesDiffer = contentSha256 !== submittedSha256;
2071
+ const disclosedTruncation = disclosure?.truncated === true;
2072
+ const effectiveTokens = disclosure?.effective_tokens;
2073
+ if (disclosure && (typeof disclosure.truncated !== "boolean" || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0)) {
2074
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} returned an invalid truncation disclosure`);
2075
+ }
2076
+ if (hashesDiffer) {
2077
+ if (!disclosedTruncation || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0) {
2078
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} changed content without a valid truncation disclosure`);
2079
+ }
2080
+ } else if (disclosedTruncation) {
2081
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} disclosed truncation but returned matching hashes`);
2082
+ }
2083
+ return {
2084
+ truncated: hashesDiffer,
2085
+ submittedSha256,
2086
+ contentSha256,
2087
+ ...typeof effectiveTokens === "number" && Number.isInteger(effectiveTokens) && effectiveTokens >= 0 ? { effectiveTokens } : {}
2088
+ };
2089
+ }
2090
+ var sharedClient = null;
2091
+ var sharedClientFile = null;
2092
+ var sharedClientPromise = null;
2093
+ var factoryClients = new WeakMap;
2094
+ async function getSharedClient(options) {
2095
+ if (options.clientFactory) {
2096
+ let promise = factoryClients.get(options.clientFactory);
2097
+ if (!promise) {
2098
+ promise = options.clientFactory();
2099
+ factoryClients.set(options.clientFactory, promise);
2100
+ }
2101
+ return promise;
2102
+ }
2103
+ if (sharedClient && sharedClientFile === options.connectionFile)
2104
+ return sharedClient;
2105
+ if (sharedClientPromise && sharedClientFile === options.connectionFile)
2106
+ return sharedClientPromise;
2107
+ sharedClientFile = options.connectionFile;
2108
+ sharedClientPromise = SubcClient.connect({ connectionFile: options.connectionFile }).then((client) => {
2109
+ sharedClient = client;
2110
+ return client;
2111
+ });
2112
+ return sharedClientPromise;
2113
+ }
2114
+
2115
+ class SynapseEmbeddingProvider {
2116
+ modelId;
2117
+ metadata;
2118
+ get maxInputTokens() {
2119
+ return this.metadata?.max_tokens;
2120
+ }
2121
+ options;
2122
+ client = null;
2123
+ initialized = false;
2124
+ initializing = null;
2125
+ permanentFailure = false;
2126
+ lastFailureReason = null;
2127
+ batchLimit = 16;
2128
+ tokenBudget = null;
2129
+ constructor(options) {
2130
+ this.options = options;
2131
+ const model = options.model || SYNAPSE_DEFAULT_MODEL;
2132
+ const fingerprint = options.fingerprint ?? "";
2133
+ const descriptor = options.descriptor;
2134
+ this.metadata = options.metadata ? {
2135
+ ...options.metadata,
2136
+ bucket_ladder: options.metadata.bucket_ladder ? [...options.metadata.bucket_ladder] : undefined
2137
+ } : fingerprint && Number.isInteger(options.tableEpoch) && descriptor ? {
2138
+ model,
2139
+ fingerprint,
2140
+ table_epoch: options.tableEpoch,
2141
+ max_tokens: descriptor.max_tokens,
2142
+ max_tokens_source: descriptor.max_tokens_source,
2143
+ ...descriptor.bucket_ladder ? { bucket_ladder: [...descriptor.bucket_ladder] } : {},
2144
+ ...options.dims ?? descriptor.dims ? { dims: options.dims ?? descriptor.dims } : {},
2145
+ ...descriptor.dtype ? { dtype: descriptor.dtype } : {},
2146
+ ...descriptor.device_class ? { device_class: descriptor.device_class } : {},
2147
+ ...options.recommendedBatch ?? descriptor.recommended_batch?.rows ? {
2148
+ recommended_batch: Math.max(1, Math.floor(options.recommendedBatch ?? descriptor.recommended_batch?.rows))
2149
+ } : {},
2150
+ ...options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget ? {
2151
+ recommended_token_budget: Math.max(1, Math.floor(options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget))
2152
+ } : {},
2153
+ ...options.provenance !== undefined ? { provenance: options.provenance } : {},
2154
+ ...typeof descriptor.certified === "boolean" ? { certified: descriptor.certified } : {},
2155
+ ...descriptor.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: descriptor.warm_load_cost_hint_ms } : {},
2156
+ laneIdentity: getSynapseLaneIdentity(model, fingerprint)
2157
+ } : null;
2158
+ this.modelId = this.metadata?.laneIdentity ?? "synapse:v1:pending";
2159
+ this.batchLimit = this.metadata?.recommended_batch ?? 16;
2160
+ this.tokenBudget = this.metadata?.recommended_token_budget ?? null;
2161
+ }
2162
+ nextPage(items, start) {
2163
+ const hardEnd = Math.min(items.length, start + this.batchLimit);
2164
+ if (this.tokenBudget === null)
2165
+ return items.slice(start, hardEnd);
2166
+ let end = start;
2167
+ let tokens = 0;
2168
+ while (end < hardEnd) {
2169
+ tokens += estimateTokens(items[end].text);
2170
+ if (tokens > this.tokenBudget && end > start)
2171
+ break;
2172
+ end += 1;
2173
+ }
2174
+ return items.slice(start, Math.max(end, start + 1));
2175
+ }
2176
+ static async discover(options) {
2177
+ const provider = new SynapseEmbeddingProvider(options);
2178
+ if (!await provider.initialize() || !provider.metadata) {
2179
+ throw new SynapseEmbeddingError("not_certified", "Synapse lane is not ready");
2180
+ }
2181
+ return provider.metadata;
2182
+ }
2183
+ async initialize() {
2184
+ if (this.initialized)
2185
+ return true;
2186
+ if (this.permanentFailure)
2187
+ return false;
2188
+ if (this.initializing)
2189
+ return this.initializing;
2190
+ this.initializing = (async () => {
2191
+ try {
2192
+ if (!this.options.clientFactory && !await connectionFileExists(this.options.connectionFile)) {
2193
+ throw new SynapseEmbeddingError("transport", `Synapse connection file is unavailable: ${this.options.connectionFile}`);
2194
+ }
2195
+ this.client = await getSharedClient(this.options);
2196
+ if (!this.metadata) {
2197
+ const discovered = await this.callWithRetry("models.list", {}, this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, false);
2198
+ const entries = extractCatalogEntries(discovered);
2199
+ const requested = this.options.model?.trim() || SYNAPSE_DEFAULT_MODEL;
2200
+ const entry = entries.find((candidate) => candidate.model === requested);
2201
+ if (!entry) {
2202
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse models.list did not return requested model ${requested}`);
2203
+ }
2204
+ if (entry.certified === false || entry.status === "not_certified") {
2205
+ throw new SynapseEmbeddingError("not_certified", `Synapse model ${entry.model} is not certified`);
2206
+ }
2207
+ const metadata = {
2208
+ ...entry,
2209
+ laneIdentity: getSynapseLaneIdentity(entry.model, entry.fingerprint)
2210
+ };
2211
+ this.metadata = metadata;
2212
+ this.modelId = metadata.laneIdentity;
2213
+ this.batchLimit = metadata.recommended_batch ?? this.batchLimit;
2214
+ this.tokenBudget = metadata.recommended_token_budget ?? this.tokenBudget;
2215
+ }
2216
+ this.initialized = true;
2217
+ this.recordSuccess();
2218
+ return true;
2219
+ } catch (error) {
2220
+ const classified = classifyError(error);
2221
+ this.recordFailure(classified);
2222
+ if (classified.permanent) {
2223
+ this.permanentFailure = true;
2224
+ log(`[magic-context] Synapse lane disabled: ${classified.code}: ${classified.message}`);
2225
+ } else {
2226
+ log(`[magic-context] Synapse lane unavailable: ${classified.message}`);
2227
+ }
2228
+ this.initialized = false;
2229
+ return false;
2230
+ } finally {
2231
+ this.initializing = null;
2232
+ }
2233
+ })();
2234
+ return this.initializing;
2235
+ }
2236
+ async embed(text, signal, purpose = "passage") {
2237
+ if (!await this.initialize() || signal?.aborted || !this.metadata)
2238
+ return null;
2239
+ if (estimateTokens(text) > this.metadata.max_tokens)
2240
+ return null;
2241
+ try {
2242
+ const id = "query";
2243
+ const value = await this.callWithRetry("embed.query", this.requestConstraints({
2244
+ id,
2245
+ text,
2246
+ purpose,
2247
+ deadline_ms: this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS
2248
+ }), this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, true, signal);
2249
+ const extracted = extractVector(value);
2250
+ if (!extracted) {
2251
+ throw new SynapseEmbeddingError("schema_violation", "Synapse query returned no vector row");
2252
+ }
2253
+ if (extracted.item.id !== id) {
2254
+ throw new SynapseEmbeddingError("schema_violation", `Synapse query returned unexpected item ${String(extracted.item.id)}`);
2255
+ }
2256
+ const rowMetadata = validateWireRow(extracted.item, extracted.disclosure, { id, text });
2257
+ this.validateResponse(extracted.metadata, extracted.vector.length);
2258
+ embeddingRowMetadata.set(extracted.vector, rowMetadata);
2259
+ this.recordSuccess();
2260
+ return extracted.vector;
2261
+ } catch (error) {
2262
+ this.logCallFailure(error, "embed.query");
2263
+ return null;
2264
+ }
2265
+ }
2266
+ async embedBatch(texts, signal, purpose = "passage") {
2267
+ if (texts.length === 0)
2268
+ return [];
2269
+ const items = texts.map((text, index) => ({
2270
+ id: `item:${index}`,
2271
+ text,
2272
+ contentSha256: hashContent(text)
2273
+ }));
2274
+ const map = await this.embedItems(items, signal, purpose);
2275
+ return items.map((item) => map.get(item.id) ?? null);
2276
+ }
2277
+ async embedItems(items, signal, purpose = "passage") {
2278
+ const output = new Map;
2279
+ if (items.length === 0 || !await this.initialize() || !this.metadata || signal?.aborted) {
2280
+ return output;
2281
+ }
2282
+ const maxTokens = this.metadata.max_tokens;
2283
+ const eligibleItems = items.filter((item) => estimateTokens(item.text) <= maxTokens).map((item) => ({ ...item, contentSha256: hashContent(item.text) }));
2284
+ for (let start = 0;start < eligibleItems.length; ) {
2285
+ if (signal?.aborted || this.permanentFailure)
2286
+ break;
2287
+ const page = this.nextPage(eligibleItems, start);
2288
+ start += page.length;
2289
+ try {
2290
+ const requestKey = this.requestKey(page, purpose);
2291
+ let body = {};
2292
+ let restarted = false;
2293
+ for (;; ) {
2294
+ try {
2295
+ body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey, purpose), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
2296
+ const first = responseBody(body);
2297
+ const jobId = typeof first.job_id === "string" ? first.job_id : null;
2298
+ if (jobId)
2299
+ body = await this.pollBatch(jobId, requestKey, signal);
2300
+ break;
2301
+ } catch (error) {
2302
+ const classified = classifyError(error);
2303
+ if (classified.code !== "module_restarted" || restarted)
2304
+ throw classified;
2305
+ restarted = true;
2306
+ }
2307
+ }
2308
+ const batchEnvelope = responseBody(body);
2309
+ const disclosures = extractTruncationDisclosures(body);
2310
+ for (const [index, item] of extractBatchItems(body).entries()) {
2311
+ const id = typeof item.id === "string" ? item.id : "";
2312
+ const vector = item.vector ?? item.embedding;
2313
+ if (!id || !Array.isArray(vector) || vector.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
2314
+ throw new SynapseEmbeddingError("schema_violation", "Synapse batch item is malformed");
2315
+ }
2316
+ const expected = page.find((candidate) => candidate.id === id);
2317
+ if (!expected) {
2318
+ throw new SynapseEmbeddingError("schema_violation", `Synapse returned unknown item ${id}`);
2319
+ }
2320
+ const rowMetadata = validateWireRow(item, disclosures[index] ?? null, expected);
2321
+ const vectorArray = Float32Array.from(vector);
2322
+ this.validateResponse({ ...batchEnvelope, ...item }, vectorArray.length);
2323
+ embeddingRowMetadata.set(vectorArray, rowMetadata);
2324
+ output.set(id, vectorArray);
2325
+ this.recordSuccess();
2326
+ }
2327
+ } catch (error) {
2328
+ const classified = classifyError(error);
2329
+ this.logCallFailure(classified, "embed.batch");
2330
+ if (classified.code === "idempotency_conflict" || classified.code === "schema_violation") {
2331
+ throw classified;
2332
+ }
2333
+ if (classified.permanent) {
2334
+ this.permanentFailure = true;
2335
+ this.initialized = false;
2336
+ break;
2337
+ }
2338
+ }
2339
+ }
2340
+ return output;
2341
+ }
2342
+ async dispose() {
2343
+ this.initialized = false;
2344
+ this.client = null;
2345
+ }
2346
+ isLoaded() {
2347
+ return this.initialized;
2348
+ }
2349
+ getLastFailureReason() {
2350
+ return this.lastFailureReason;
2351
+ }
2352
+ requestConstraints(extra) {
2353
+ const metadata = this.metadata;
2354
+ if (!metadata)
2355
+ return extra;
2356
+ return {
2357
+ ...extra,
2358
+ model: metadata.model,
2359
+ required_fingerprint: metadata.fingerprint,
2360
+ required_epoch: metadata.table_epoch,
2361
+ allow_equivalent: false,
2362
+ accept_declared: false
2363
+ };
2364
+ }
2365
+ batchRequest(items, requestKey, purpose) {
2366
+ return this.requestConstraints({
2367
+ items: items.map((item) => ({
2368
+ id: item.id,
2369
+ text: item.text,
2370
+ content_sha256: item.contentSha256
2371
+ })),
2372
+ request_key: requestKey,
2373
+ purpose
2374
+ });
2375
+ }
2376
+ requestKey(items, purpose) {
2377
+ if (!this.metadata)
2378
+ throw new SynapseEmbeddingError("transport", "Synapse metadata is unavailable");
2379
+ return getSynapseBatchRequestKey({
2380
+ model: this.metadata.model,
2381
+ fingerprint: this.metadata.fingerprint,
2382
+ tableEpoch: this.metadata.table_epoch,
2383
+ items,
2384
+ purpose
2385
+ });
2386
+ }
2387
+ async pollBatch(jobId, requestKey, signal) {
2388
+ let cursor = null;
2389
+ const allItems = [];
2390
+ const allDisclosures = [];
2391
+ for (;; ) {
2392
+ if (signal?.aborted)
2393
+ return {};
2394
+ const body = await this.callWithRetry("embed.result", this.requestConstraints({
2395
+ job_id: jobId,
2396
+ cursor,
2397
+ request_key: requestKey
2398
+ }), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
2399
+ const parsed = responseBody(body);
2400
+ const items = extractBatchItems(body);
2401
+ const disclosures = extractTruncationDisclosures(body);
2402
+ allItems.push(...items);
2403
+ allDisclosures.push(...items.map((_, index) => disclosures[index] ?? null));
2404
+ const nextCursor = parsed.next_cursor ?? parsed.cursor;
2405
+ const done = parsed.done === true || parsed.complete === true || nextCursor === undefined || nextCursor === null;
2406
+ if (done) {
2407
+ return {
2408
+ ...parsed,
2409
+ vectors: allItems,
2410
+ truncation_disclosures: allDisclosures
2411
+ };
2412
+ }
2413
+ cursor = nextCursor;
2414
+ }
2415
+ }
2416
+ async callWithRetry(method, params, timeoutMs, retryEmbeddings, signal) {
2417
+ let attempt = 0;
2418
+ for (;; ) {
2419
+ if (signal?.aborted)
2420
+ throw new SynapseEmbeddingError("transport", "Synapse request aborted");
2421
+ try {
2422
+ if (!this.client)
2423
+ throw new SynapseEmbeddingError("transport", "Synapse client is unavailable");
2424
+ return await this.client.call(this.options.moduleId ?? "synapse", method, params, {
2425
+ timeoutMs,
2426
+ targetKind: "management_surface",
2427
+ identity: {
2428
+ project_root: this.options.projectRoot,
2429
+ harness: getHarness(),
2430
+ session: this.options.session
2431
+ }
2432
+ });
2433
+ } catch (error) {
2434
+ const classified = classifyError(error);
2435
+ if (classified.code === "idempotency_conflict")
2436
+ throw classified;
2437
+ const outcomeUnknown = error instanceof SubcCallError && error.kind === "outcome_unknown";
2438
+ const retryable = !classified.permanent && (retryEmbeddings || !outcomeUnknown);
2439
+ if (!retryable || attempt >= 3)
2440
+ throw classified;
2441
+ const delay = classified.retryAfterMs ?? Math.min(2000, 100 * 2 ** attempt);
2442
+ attempt += 1;
2443
+ await wait(delay);
2444
+ }
2445
+ }
2446
+ }
2447
+ validateResponse(body, dims) {
2448
+ const metadata = this.metadata;
2449
+ if (!metadata) {
2450
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse lane metadata missing");
2451
+ }
2452
+ if (metadata.dims === undefined) {
2453
+ const envelopeDims = body.dims;
2454
+ if (typeof envelopeDims === "number" && envelopeDims !== dims) {
2455
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse envelope declares ${envelopeDims} dimensions but the vector has ${dims}`);
2456
+ }
2457
+ metadata.dims = dims;
2458
+ }
2459
+ if (dims !== metadata.dims) {
2460
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse returned ${dims} dimensions, expected ${metadata.dims}`);
2461
+ }
2462
+ const fingerprint = body.fingerprint ?? body.served_fingerprint;
2463
+ if (typeof fingerprint !== "string") {
2464
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served fingerprint");
2465
+ }
2466
+ if (fingerprint !== metadata.fingerprint) {
2467
+ throw new SynapseEmbeddingError("substitution_rejected", `Synapse fingerprint changed from ${metadata.fingerprint} to ${fingerprint}`);
2468
+ }
2469
+ const epoch = body.table_epoch ?? body.tableEpoch;
2470
+ if (typeof epoch !== "number") {
2471
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served table epoch");
2472
+ }
2473
+ if (epoch !== metadata.table_epoch) {
2474
+ throw new SynapseEmbeddingError("substitution_rejected", `Synapse table epoch changed from ${metadata.table_epoch} to ${epoch}`);
2475
+ }
2476
+ }
2477
+ logCallFailure(error, operation) {
2478
+ const classified = classifyError(error);
2479
+ this.recordFailure(classified);
2480
+ if (classified.permanent)
2481
+ this.permanentFailure = true;
2482
+ const suffix = classified.retryAfterMs === undefined ? "" : ` retry_after_ms=${classified.retryAfterMs}`;
2483
+ log(`[magic-context] Synapse ${operation} failed: ${classified.code}${suffix}: ${classified.message}`);
2484
+ }
2485
+ recordFailure(error) {
2486
+ this.lastFailureReason = embeddingFailureFor(error);
2487
+ }
2488
+ recordSuccess() {
2489
+ this.lastFailureReason = null;
2490
+ }
2491
+ }
2492
+
2493
+ // src/features/magic-context/memory/normalize-hash.ts
2494
+ import { createHash as createHash2 } from "node:crypto";
2495
+ function normalizeMemoryContent(content) {
2496
+ return content.toLowerCase().replace(/\s+/g, " ").trim();
2497
+ }
2498
+ function computeNormalizedHash(content) {
2499
+ const normalized = normalizeMemoryContent(content);
2500
+ return createHash2("md5").update(normalized).digest("hex");
2501
+ }
2502
+
2503
+ // src/features/magic-context/memory/embedding-identity.ts
2504
+ function normalizeEndpoint(endpoint) {
2505
+ return endpoint?.trim().replace(/\/+$/, "") ?? "";
2506
+ }
2507
+ var LOCAL_EMBEDDING_RUNTIME_FINGERPRINT = "transformers@4.3.0;onnxruntime-node@1.30.0;onnxruntime-web@1.26.0-dev.20260416-b7804b056c";
2508
+ function getEmbeddingProviderIdentity(config) {
2509
+ if (config.provider === "off") {
2510
+ return "embedding-provider:off";
2511
+ }
2512
+ if (config.provider === "synapse") {
2513
+ const resolved = config;
2514
+ if (!resolved.model || !resolved.synapse_fingerprint)
2515
+ return "synapse:v1:pending";
2516
+ return getSynapseLaneIdentity(resolved.model, resolved.synapse_fingerprint);
2517
+ }
2518
+ if (config.provider !== "local" && config.provider !== "openai-compatible") {
2519
+ throw new Error("Unknown embedding provider");
2520
+ }
2521
+ const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
2522
+ const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
2523
+ const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
2524
+ const identityInput = config.provider === "openai-compatible" ? {
2525
+ provider: "openai-compatible",
2526
+ model: config.model.trim(),
2527
+ endpoint: normalizeEndpoint(config.endpoint),
2528
+ apiKeyPresent: Boolean(config.api_key?.trim()),
2529
+ inputType: config.input_type?.trim() || "",
2530
+ ...documentPrefix ? { documentPrefix } : {},
2531
+ ...truncate ? { truncate } : {}
2532
+ } : {
2533
+ provider: "local",
2534
+ model: config.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
2535
+ endpoint: "",
2536
+ apiKeyPresent: false,
2537
+ runtimeFingerprint: LOCAL_EMBEDDING_RUNTIME_FINGERPRINT,
2538
+ ...localDtype ? { localDtype } : {}
2539
+ };
2540
+ return `embedding-provider:${computeNormalizedHash(JSON.stringify(identityInput))}`;
2541
+ }
2542
+
2543
+ // src/features/magic-context/memory/embedding-worker-client.ts
2544
+ import { Worker } from "node:worker_threads";
2545
+ class EmbeddingWorkerClient {
2546
+ data;
2547
+ entry;
2548
+ timeoutMs;
2549
+ worker = null;
2550
+ nextId = 1;
2551
+ pending = new Map;
2552
+ disposed = false;
2553
+ constructor(data, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker.ts" : "./embedding-worker.js", import.meta.url), timeoutMs = 5 * 60000) {
2554
+ this.data = data;
2555
+ this.entry = entry;
2556
+ this.timeoutMs = timeoutMs;
2557
+ }
2558
+ start() {
2559
+ if (this.disposed)
2560
+ throw new Error("embedding worker disposed");
2561
+ if (this.worker)
2562
+ return this.worker;
2563
+ const worker = new Worker(this.entry, { workerData: this.data });
2564
+ this.worker = worker;
2565
+ worker.unref();
2566
+ worker.on("message", (reply) => {
2567
+ if (this.worker !== worker)
2568
+ return;
2569
+ const request = this.pending.get(reply.id);
2570
+ if (!request)
2571
+ return;
2572
+ clearTimeout(request.timer);
2573
+ this.pending.delete(reply.id);
2574
+ if (reply.error)
2575
+ request.reject(new Error(reply.error));
2576
+ else
2577
+ request.resolve(reply);
2578
+ if (this.pending.size === 0)
2579
+ worker.unref();
2580
+ });
2581
+ const fail = (error) => {
2582
+ if (this.worker !== worker)
2583
+ return;
2584
+ this.worker = null;
2585
+ for (const request of this.pending.values()) {
2586
+ clearTimeout(request.timer);
2587
+ request.reject(error);
2588
+ }
2589
+ this.pending.clear();
2590
+ log("[magic-context] embedding worker exited unexpectedly:", error);
2591
+ worker.terminate();
2592
+ };
2593
+ worker.on("error", fail);
2594
+ worker.on("exit", (code) => fail(new Error(`embedding worker exited (${code})`)));
2595
+ return worker;
2596
+ }
2597
+ isRunning() {
2598
+ return this.worker !== null;
2599
+ }
2600
+ request(texts, signal) {
2601
+ if (signal?.aborted)
2602
+ return Promise.reject(new Error("embedding request aborted"));
2603
+ return new Promise((resolve, reject) => {
2604
+ const worker = this.start();
2605
+ const id = this.nextId++;
2606
+ const timer = setTimeout(() => {
2607
+ this.stop(new Error("embedding worker request timed out"));
2608
+ }, this.timeoutMs);
2609
+ const abort = () => {
2610
+ clearTimeout(timer);
2611
+ this.pending.delete(id);
2612
+ signal?.removeEventListener("abort", abort);
2613
+ reject(new Error("embedding request aborted"));
2614
+ if (this.pending.size === 0)
2615
+ worker.unref();
2616
+ };
2617
+ signal?.addEventListener("abort", abort, { once: true });
2618
+ const cleanup = () => signal?.removeEventListener("abort", abort);
2619
+ this.pending.set(id, {
2620
+ timer,
2621
+ resolve: (reply) => {
2622
+ cleanup();
2623
+ resolve(reply);
2624
+ },
2625
+ reject: (error) => {
2626
+ cleanup();
2627
+ reject(error);
2628
+ }
2629
+ });
2630
+ worker.ref();
2631
+ try {
2632
+ worker.postMessage({ id, texts });
2633
+ } catch (error) {
2634
+ this.stop(error instanceof Error ? error : new Error(String(error)));
2635
+ }
2636
+ });
2637
+ }
2638
+ async stop(error) {
2639
+ const worker = this.worker;
2640
+ this.worker = null;
2641
+ for (const request of this.pending.values()) {
2642
+ clearTimeout(request.timer);
2643
+ request.reject(error);
2644
+ }
2645
+ this.pending.clear();
2646
+ await worker?.terminate();
2647
+ }
2648
+ async dispose() {
2649
+ this.disposed = true;
2650
+ await this.stop(new Error("embedding worker disposed"));
2651
+ }
2652
+ }
2653
+
2654
+ // src/features/magic-context/memory/transformers-remote-host.ts
2655
+ var DEFAULT_TRANSFORMERS_REMOTE_HOST = "https://huggingface.co/";
2656
+ function readHuggingFaceEndpoint() {
2657
+ return globalThis.process?.env?.HF_ENDPOINT;
2658
+ }
2659
+ function configureTransformersRemoteHost(env, endpoint = readHuggingFaceEndpoint()) {
2660
+ const normalized = endpoint?.trim().replace(/\/+$/, "");
2661
+ env.remoteHost = normalized ? `${normalized}/` : DEFAULT_TRANSFORMERS_REMOTE_HOST;
2662
+ }
2663
+
2664
+ // src/features/magic-context/memory/embedding-local.ts
2665
+ var BUN_NAPI_TEARDOWN_FIX_VERSION = [1, 4, 0];
2666
+ function currentLocalEmbeddingHost() {
2667
+ const bun = globalThis.Bun;
2668
+ const hasProcess = typeof process !== "undefined";
2669
+ const bunVersion = hasProcess && typeof process.versions?.bun === "string" ? process.versions.bun : undefined;
2670
+ return {
2671
+ isElectron: hasProcess && Boolean(process.versions?.electron),
2672
+ isBun: Boolean(bun) || Boolean(bunVersion),
2673
+ bunVersion,
2674
+ hasNodeFilesystem: hasProcess && (typeof process.versions?.node === "string" || typeof bunVersion === "string")
2675
+ };
2676
+ }
2677
+ function bunHasNapiTeardownFix(version) {
2678
+ const match = version?.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
2679
+ if (!match || match[4])
2680
+ return false;
2681
+ const parsed = [Number(match[1]), Number(match[2]), Number(match[3])];
2682
+ return parsed.some((part) => !Number.isSafeInteger(part)) ? false : parsed[0] > BUN_NAPI_TEARDOWN_FIX_VERSION[0] || parsed[0] === BUN_NAPI_TEARDOWN_FIX_VERSION[0] && (parsed[1] > BUN_NAPI_TEARDOWN_FIX_VERSION[1] || parsed[1] === BUN_NAPI_TEARDOWN_FIX_VERSION[1] && parsed[2] >= BUN_NAPI_TEARDOWN_FIX_VERSION[2]);
2683
+ }
2684
+ function resolveLocalEmbeddingRuntime(preference = "auto", host = currentLocalEmbeddingHost()) {
2685
+ if (preference === "native" || preference === "wasm")
2686
+ return preference;
2687
+ if (host.isElectron)
2688
+ return "electron";
2689
+ if (host.isBun && !bunHasNapiTeardownFix(host.bunVersion))
2690
+ return "wasm";
2691
+ return "native";
2692
+ }
2693
+ function resolveLocalEmbeddingWorkerRuntime(preference = "auto", host = currentLocalEmbeddingHost()) {
2694
+ if (host.isBun && !bunHasNapiTeardownFix(host.bunVersion) && preference === "native")
2695
+ return "wasm";
2696
+ return resolveLocalEmbeddingRuntime(preference, host);
2697
+ }
2698
+ var LOCK_POLL_MS = 150;
2699
+ var STALE_LOCK_MS = 3 * 60000;
2700
+ var MAX_LOCK_WAIT_MS = 5 * 60000;
2701
+ async function acquireModelLoadLock(lockPath) {
2702
+ const waitStart = Date.now();
2703
+ while (true) {
2704
+ try {
2705
+ const handle = await createStorageFileHandleAsync(lockPath, "wx");
2706
+ try {
2707
+ await writeStorageFileHandleAsync(handle, `pid=${process.pid} started=${Date.now()}
2708
+ `);
2709
+ } catch {}
2710
+ await handle.close();
2711
+ return async () => {
2712
+ try {
2713
+ await unlink(lockPath);
2714
+ } catch {}
2715
+ };
2716
+ } catch (error) {
2717
+ const code = error.code;
2718
+ if (code !== "EEXIST" && code !== "EPERM") {
2719
+ throw error;
2720
+ }
2721
+ try {
2722
+ const info = await stat(lockPath);
2723
+ if (Date.now() - info.mtimeMs > STALE_LOCK_MS) {
2724
+ log(`[magic-context] embedding-load lock stale (>${STALE_LOCK_MS}ms), taking over`);
2725
+ try {
2726
+ await unlink(lockPath);
2727
+ } catch {}
2728
+ continue;
2729
+ }
2730
+ } catch {
2731
+ continue;
2732
+ }
2733
+ if (Date.now() - waitStart > MAX_LOCK_WAIT_MS) {
2734
+ throw new Error(`[magic-context] embedding-load lock wait exceeded ${MAX_LOCK_WAIT_MS}ms; another process is still loading the model. Skipping this init attempt to avoid an unsynchronized native load.`);
2735
+ }
2736
+ await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
2737
+ }
2738
+ }
2739
+ }
2740
+ function startLockHeartbeat(lockPath) {
2741
+ const HEARTBEAT_MS = Math.floor(STALE_LOCK_MS / 3);
2742
+ const timer = setInterval(() => {
2743
+ writeStorageFileAsync(lockPath, `pid=${process.pid} alive=${Date.now()}
2744
+ `).catch(() => {});
2745
+ }, HEARTBEAT_MS);
2746
+ timer.unref?.();
2747
+ return () => clearInterval(timer);
2748
+ }
2749
+ var ONNX_RUNTIME_WEB_SPECIFIER = "onnxruntime-web";
2750
+ var useInThreadTestRuntime = false;
2751
+ var workerFactoryForTests;
2752
+ var localEmbeddingRuntimeMode = "native";
2753
+ var localEmbeddingProcessFailure = null;
2754
+ var wasmRuntimeInjected = false;
2755
+ var localEmbeddingHostForRuntime = currentLocalEmbeddingHost;
2756
+ var resolveWasmOrtForRuntime = () => {
2757
+ try {
2758
+ return typeof import.meta.resolve === "function" ? import.meta.resolve(ONNX_RUNTIME_WEB_SPECIFIER) : undefined;
2759
+ } catch {
2760
+ return;
2761
+ }
2762
+ };
2763
+ var importWasmOrtModule = async (specifier) => await import(specifier);
2764
+ var importWasmOrtModuleForRuntime = importWasmOrtModule;
2765
+ var importWasmOrtForRuntime = async () => {
2766
+ const { createRequire: createRequireFn } = await import("node:module");
2767
+ const requireFn = createRequireFn(import.meta.url);
2768
+ const ortEntry = requireFn.resolve(ONNX_RUNTIME_WEB_SPECIFIER);
2769
+ const ortSpecifier = resolveWasmOrtForRuntime() ?? ONNX_RUNTIME_WEB_SPECIFIER;
2770
+ return {
2771
+ module: await importWasmOrtModuleForRuntime(ortSpecifier),
2772
+ entryPath: ortEntry
2773
+ };
2774
+ };
2775
+ var importTransformersForRuntime = async () => {
2776
+ return await importPluginModule(() => import("./transformers.node-hj754h7s.js"));
2777
+ };
2778
+ var importTransformersWasmFallbackForRuntime = async () => {
2779
+ const webEntry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "../../../../dist/transformers-web.js" : "./transformers-web.js", import.meta.url).href;
2780
+ return await importPluginModule(() => import(webEntry));
2781
+ };
2782
+ var importTransformersNodeWasmFallbackForRuntime = async () => {
2783
+ const nodeWasmEntry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "../../../../dist/transformers-node-wasm.js" : "./transformers-node-wasm.js", import.meta.url).href;
2784
+ return await importPluginModule(() => import(nodeWasmEntry));
2785
+ };
2786
+ var modelCacheDirForRuntime = () => workerData?.magicContextEmbeddingWorker && typeof workerData.modelCacheDir === "string" ? workerData.modelCacheDir : join(getMagicContextStorageDir(), "models");
2787
+ var logForRuntime = log;
2788
+ var injectWasmOrtForRuntime = injectWasmOrt;
2789
+ var loadedLocalEmbeddingRuntimes = new Map;
2790
+ var nextLocalEmbeddingRuntimeId = 1;
2791
+ function directoryBytes(path) {
2792
+ let total = 0;
2793
+ try {
2794
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
2795
+ const entryPath = join(path, entry.name);
2796
+ if (entry.isDirectory()) {
2797
+ const childBytes = directoryBytes(entryPath);
2798
+ if (childBytes === null)
2799
+ return null;
2800
+ total += childBytes;
2801
+ } else if (entry.isFile()) {
2802
+ total += statSync(entryPath).size;
2803
+ }
2804
+ }
2805
+ return total;
2806
+ } catch (error) {
2807
+ return error.code === "ENOENT" ? 0 : null;
2808
+ }
2809
+ }
2810
+ function getLocalEmbeddingNativeMemoryStats() {
2811
+ const loaded = [...loadedLocalEmbeddingRuntimes.values()];
2812
+ return {
2813
+ loaded: loaded.length > 0,
2814
+ providerCount: loaded.length,
2815
+ models: [...new Set(loaded.map((entry) => entry.model))].sort(),
2816
+ runtimes: [...new Set(loaded.map((entry) => entry.runtime))].sort(),
2817
+ modelCacheBytes: loaded.length > 0 ? directoryBytes(modelCacheDirForRuntime()) : 0,
2818
+ rssDeltaAtLoad: loaded.reduce((sum, entry) => sum + entry.rssDeltaAtLoad, 0),
2819
+ externalDeltaAtLoad: loaded.reduce((sum, entry) => sum + entry.externalDeltaAtLoad, 0),
2820
+ arrayBuffersDeltaAtLoad: loaded.reduce((sum, entry) => sum + entry.arrayBuffersDeltaAtLoad, 0)
2821
+ };
2822
+ }
2823
+ async function ensureWasmOrtInjected() {
2824
+ if (wasmRuntimeInjected)
2825
+ return true;
2826
+ if (!await injectWasmOrtForRuntime())
2827
+ return false;
2828
+ wasmRuntimeInjected = true;
2829
+ return true;
2830
+ }
2831
+ async function injectWasmOrt() {
2832
+ if (wasmRuntimeInjected)
2833
+ return true;
2834
+ try {
2835
+ const { module: ortWeb, entryPath } = await importWasmOrtForRuntime();
2836
+ if (ortWeb.env?.wasm) {
2837
+ ortWeb.env.wasm.numThreads = 1;
2838
+ ortWeb.env.wasm.wasmPaths = `${pathToFileURL(dirname(entryPath)).href}/`;
2839
+ }
2840
+ globalThis[Symbol.for("onnxruntime")] = ortWeb;
2841
+ wasmRuntimeInjected = true;
2842
+ return true;
2843
+ } catch (error) {
2844
+ log("[magic-context] failed to inject onnxruntime-web:", error instanceof Error ? error.message : String(error));
2845
+ return false;
2846
+ }
2847
+ }
2848
+ function likelyMuslHint() {
2849
+ if (process.platform !== "linux" || typeof process.report?.getReport !== "function")
2850
+ return "";
2851
+ try {
2852
+ const report = process.report.getReport();
2853
+ return typeof report.header?.glibcVersionRuntime === "string" ? "" : " Linux process report has no glibc runtime version (musl likely).";
2854
+ } catch {
2855
+ return "";
2856
+ }
2857
+ }
2858
+ function localEmbeddingRuntimeIsDisabled() {
2859
+ return localEmbeddingRuntimeMode === "disabled";
2860
+ }
2861
+
2862
+ class LocalEmbeddingFallbackError extends Error {
2863
+ nativeError;
2864
+ constructor(nativeError, wasmError) {
2865
+ super("the native local embedding runtime and its WASM fallback both failed", {
2866
+ cause: wasmError
2867
+ });
2868
+ this.name = "LocalEmbeddingFallbackError";
2869
+ this.nativeError = nativeError;
2870
+ }
2871
+ }
2872
+
2873
+ class LocalEmbeddingFsUnavailableError extends Error {
2874
+ code = "MC_EMBEDDING_FS_UNAVAILABLE";
2875
+ constructor() {
2876
+ super("MC_EMBEDDING_FS_UNAVAILABLE: Node WASM bundle has no filesystem cache");
2877
+ this.name = "LocalEmbeddingFsUnavailableError";
2878
+ }
2879
+ }
2880
+ async function importWasmTransformersForHost() {
2881
+ const host = localEmbeddingHostForRuntime();
2882
+ if (host.isElectron) {
2883
+ return importTransformersForRuntime();
2884
+ }
2885
+ return host.hasNodeFilesystem ? importTransformersNodeWasmFallbackForRuntime() : importTransformersWasmFallbackForRuntime();
2886
+ }
2887
+ function disableLocalEmbeddingsAfterRuntimeFailure(detail) {
2888
+ localEmbeddingRuntimeMode = "disabled";
2889
+ logForRuntime(`[magic-context] local embeddings are disabled because both the onnxruntime-node native binding and the onnxruntime-web (WASM) fallback failed to load. Native failure: ${detail}. Run \`npx @cortexkit/magic-context@latest doctor\` for diagnostics; reinstalling repairs missing package files but cannot add a native binding that upstream does not ship. Alternatively, configure an \`openai-compatible\` embedding HTTP endpoint. Existing memories are unaffected.`);
2890
+ }
2891
+ async function loadTransformersForLocalEmbedding(runtimePreference) {
2892
+ if (localEmbeddingRuntimeMode === "disabled") {
2893
+ throw new Error("local embedding runtime is disabled");
2894
+ }
2895
+ const resolvedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, localEmbeddingHostForRuntime());
2896
+ if (resolvedRuntime === "wasm") {
2897
+ if (!await ensureWasmOrtInjected()) {
2898
+ disableLocalEmbeddingsAfterRuntimeFailure("the selected WASM runtime is unavailable");
2899
+ throw new Error("onnxruntime-web failed to load");
2900
+ }
2901
+ return { module: await importWasmTransformersForHost(), usesWasm: true };
2902
+ }
2903
+ if (localEmbeddingRuntimeMode === "wasm") {
2904
+ if (!await ensureWasmOrtInjected()) {
2905
+ disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime is unavailable");
2906
+ throw new Error("onnxruntime-web failed to load");
2907
+ }
2908
+ try {
2909
+ return { module: await importWasmTransformersForHost(), usesWasm: true };
2910
+ } catch (wasmError) {
2911
+ disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime failed to load");
2912
+ throw wasmError;
2913
+ }
2914
+ }
2915
+ const electron = resolvedRuntime === "electron";
2916
+ if (electron) {
2917
+ const wasInjected = wasmRuntimeInjected;
2918
+ if (await ensureWasmOrtInjected()) {
2919
+ if (!wasInjected) {
2920
+ logForRuntime("[magic-context] Electron detected — using onnxruntime-web (WASM) for embeddings (bypasses onnxruntime-node native load)");
2921
+ }
2922
+ return { module: await importTransformersForRuntime(), usesWasm: true };
2923
+ }
2924
+ }
2925
+ try {
2926
+ return { module: await importTransformersForRuntime(), usesWasm: false };
2927
+ } catch (nativeError) {
2928
+ if (!isNativeRuntimeMissingError(nativeError) || electron) {
2929
+ throw nativeError;
2930
+ }
2931
+ if (!await ensureWasmOrtInjected()) {
2932
+ disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
2933
+ throw nativeError;
2934
+ }
2935
+ localEmbeddingRuntimeMode = "wasm";
2936
+ try {
2937
+ const module = await importWasmTransformersForHost();
2938
+ logForRuntime("[magic-context] onnxruntime-node failed to load; using onnxruntime-web (WASM) for local embeddings. WASM inference is slower than native; a remote `openai-compatible` provider may be faster." + likelyMuslHint());
2939
+ return { module, usesWasm: true };
2940
+ } catch (wasmError) {
2941
+ disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
2942
+ throw new LocalEmbeddingFallbackError(nativeError, wasmError);
2943
+ }
2944
+ }
2945
+ }
2946
+ var DEFAULT_LOCAL_DTYPE = "fp32";
2947
+ async function withQuietConsole(fn) {
2948
+ const origWarn = console.warn;
2949
+ const origError = console.error;
2950
+ const redirect = (...args) => {
2951
+ const message = args.map((a) => typeof a === "string" ? a : String(a)).join(" ");
2952
+ log(`[transformers] ${message}`);
2953
+ };
2954
+ console.warn = redirect;
2955
+ console.error = redirect;
2956
+ try {
2957
+ return await fn();
2958
+ } finally {
2959
+ console.warn = origWarn;
2960
+ console.error = origError;
2961
+ }
2962
+ }
2963
+ function isNativeRuntimeMissingError(error) {
2964
+ const message = error instanceof Error ? error.message : String(error ?? "");
2965
+ const lower = message.toLowerCase();
2966
+ const code = error?.code;
2967
+ const name = error?.name;
2968
+ if (code === "ERR_DLOPEN_FAILED" && lower.includes("onnxruntime")) {
2969
+ return true;
2970
+ }
2971
+ if (lower.includes('could not load the "sharp" module'))
2972
+ return true;
2973
+ const mentionsNativeRuntime = lower.includes("onnxruntime-node") || lower.includes("onnxruntime_binding");
2974
+ if (!mentionsNativeRuntime)
2975
+ return false;
2976
+ return code === "ERR_MODULE_NOT_FOUND" || name === "ResolveMessage" || lower.includes("cannot find package") || lower.includes("cannot find module") || lower.includes("err_module_not_found");
2977
+ }
2978
+ function isTransientLoadError(error) {
2979
+ const message = error instanceof Error ? error.message : String(error ?? "");
2980
+ if (!message)
2981
+ return false;
2982
+ const lower = message.toLowerCase();
2983
+ return lower.includes("protobuf parsing failed") || lower.includes("unable to get model file path or buffer") || lower.includes("ebusy") || lower.includes("resource busy") || lower.includes("resource temporarily unavailable");
2984
+ }
2985
+ function isArrayLikeNumber(value) {
2986
+ if (typeof value !== "object" || value === null || !("length" in value)) {
2987
+ return false;
2988
+ }
2989
+ const arr = value;
2990
+ if (typeof arr.length !== "number") {
2991
+ return false;
2992
+ }
2993
+ return arr.length === 0 || typeof arr[0] === "number";
2994
+ }
2995
+ function toFloat32Array(values) {
2996
+ return values instanceof Float32Array ? new Float32Array(values) : Float32Array.from(Array.from(values));
2997
+ }
2998
+ function extractBatchEmbeddings(result, expectedCount) {
2999
+ const { data } = result;
3000
+ if (Array.isArray(data) && data.length === expectedCount && data.every((entry) => typeof entry !== "number" && isArrayLikeNumber(entry))) {
3001
+ return data.map((entry) => toFloat32Array(entry));
3002
+ }
3003
+ if (!isArrayLikeNumber(data)) {
3004
+ log("[magic-context] embedding batch returned unexpected data shape");
3005
+ return Array.from({ length: expectedCount }, () => null);
3006
+ }
3007
+ const flatData = toFloat32Array(data);
3008
+ const dimension = result.dims?.at(-1) ?? flatData.length / expectedCount;
3009
+ if (!Number.isInteger(dimension) || dimension <= 0 || flatData.length !== expectedCount * dimension) {
3010
+ log("[magic-context] embedding batch returned invalid dimensions");
3011
+ return Array.from({ length: expectedCount }, () => null);
3012
+ }
3013
+ const embeddings = [];
3014
+ for (let index = 0;index < expectedCount; index++) {
3015
+ embeddings.push(flatData.slice(index * dimension, (index + 1) * dimension));
3016
+ }
3017
+ return embeddings;
3018
+ }
3019
+
3020
+ class LocalEmbeddingProvider {
3021
+ modelId;
3022
+ maxInputTokens;
3023
+ memoryStatsId = nextLocalEmbeddingRuntimeId++;
3024
+ model;
3025
+ dtype;
3026
+ runtimePreference;
3027
+ pipeline = null;
3028
+ workerClient;
3029
+ workerLoaded = false;
3030
+ initPromise = null;
3031
+ lastFailureReason = null;
3032
+ usesWasm = false;
3033
+ inFlight = 0;
3034
+ disposing = false;
3035
+ disposePromise = null;
3036
+ inFlightWaiters = [];
3037
+ constructor(model = DEFAULT_LOCAL_EMBEDDING_MODEL, maxInputTokens = 512, dtype = DEFAULT_LOCAL_DTYPE, runtimePreference = "auto") {
3038
+ this.model = model;
3039
+ this.maxInputTokens = maxInputTokens;
3040
+ this.dtype = dtype || DEFAULT_LOCAL_DTYPE;
3041
+ this.runtimePreference = runtimePreference;
3042
+ this.workerClient = !workerData?.magicContextEmbeddingWorker && !useInThreadTestRuntime ? (workerFactoryForTests ?? ((data) => new EmbeddingWorkerClient(data)))({
3043
+ magicContextEmbeddingWorker: true,
3044
+ modelCacheDir: modelCacheDirForRuntime(),
3045
+ enforcePrivateStoragePermissions: shouldEnforcePrivateStoragePermissions(),
3046
+ harness: getHarness(),
3047
+ model,
3048
+ maxInputTokens,
3049
+ dtype: this.dtype,
3050
+ runtimePreference
3051
+ }) : null;
3052
+ this.modelId = getEmbeddingProviderIdentity({
3053
+ provider: "local",
3054
+ model,
3055
+ local_runtime: runtimePreference,
3056
+ ...dtype && dtype !== DEFAULT_LOCAL_DTYPE ? { local_dtype: dtype } : {}
3057
+ });
3058
+ }
3059
+ async initialize() {
3060
+ if (this.workerClient && !this.disposing) {
3061
+ if (this.workerLoaded && this.workerClient.isRunning())
3062
+ return true;
3063
+ try {
3064
+ const reply = await this.workerClient.request();
3065
+ this.recordWorkerReply(reply);
3066
+ return reply.loaded;
3067
+ } catch (error) {
3068
+ this.recordWorkerFailure(error);
3069
+ return false;
3070
+ }
3071
+ }
3072
+ if (this.disposing) {
3073
+ return false;
3074
+ }
3075
+ if (this.pipeline) {
3076
+ return true;
3077
+ }
3078
+ if (localEmbeddingRuntimeMode === "disabled") {
3079
+ this.lastFailureReason = localEmbeddingProcessFailure ?? classifyLocalEmbeddingFailure(new Error("local embedding runtime is disabled"));
3080
+ return false;
3081
+ }
3082
+ if (this.initPromise) {
3083
+ await this.initPromise;
3084
+ return this.pipeline !== null;
3085
+ }
3086
+ const memoryBeforeLoad = process.memoryUsage();
3087
+ this.initPromise = (async () => {
3088
+ try {
3089
+ if (this.disposing) {
3090
+ return;
3091
+ }
3092
+ const { module: transformersModule, usesWasm } = await loadTransformersForLocalEmbedding(this.runtimePreference);
3093
+ this.usesWasm = usesWasm;
3094
+ const env = transformersModule.env;
3095
+ configureTransformersRemoteHost(env);
3096
+ const LogLevel = transformersModule.LogLevel;
3097
+ if (LogLevel && "ERROR" in LogLevel) {
3098
+ env.logLevel = LogLevel.ERROR;
3099
+ }
3100
+ const host = localEmbeddingHostForRuntime();
3101
+ if (usesWasm && host.hasNodeFilesystem && !host.isElectron && (env.useFS !== true || env.useFSCache !== true)) {
3102
+ throw new LocalEmbeddingFsUnavailableError;
3103
+ }
3104
+ const modelCacheDir = modelCacheDirForRuntime();
3105
+ try {
3106
+ ensureStorageDirectorySync(modelCacheDir);
3107
+ env.cacheDir = modelCacheDir;
3108
+ } catch {
3109
+ log("[magic-context] could not create model cache dir, using library default");
3110
+ }
3111
+ const createPipeline = transformersModule.pipeline;
3112
+ const lockPath = join(modelCacheDir, ".load.lock");
3113
+ const releaseLock = await acquireModelLoadLock(lockPath);
3114
+ const stopHeartbeat = startLockHeartbeat(lockPath);
3115
+ try {
3116
+ const MAX_ATTEMPTS = 3;
3117
+ let lastError;
3118
+ for (let attempt = 1;attempt <= MAX_ATTEMPTS; attempt++) {
3119
+ try {
3120
+ const pipeline = await withQuietConsole(() => createPipeline("feature-extraction", this.model, {
3121
+ dtype: this.dtype,
3122
+ ...usesWasm ? { device: "auto" } : {}
3123
+ }));
3124
+ if (this.disposing) {
3125
+ await pipeline.dispose?.();
3126
+ this.pipeline = null;
3127
+ } else {
3128
+ this.pipeline = pipeline;
3129
+ }
3130
+ lastError = undefined;
3131
+ break;
3132
+ } catch (error) {
3133
+ lastError = error;
3134
+ if (!isTransientLoadError(error) || attempt === MAX_ATTEMPTS) {
3135
+ break;
3136
+ }
3137
+ const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
3138
+ log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
3139
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
3140
+ }
3141
+ }
3142
+ if (this.pipeline) {
3143
+ this.lastFailureReason = null;
3144
+ localEmbeddingProcessFailure = null;
3145
+ const memoryAfterLoad = process.memoryUsage();
3146
+ loadedLocalEmbeddingRuntimes.set(this.memoryStatsId, {
3147
+ model: this.model,
3148
+ runtime: this.usesWasm ? "wasm" : "native",
3149
+ rssDeltaAtLoad: memoryAfterLoad.rss - memoryBeforeLoad.rss,
3150
+ externalDeltaAtLoad: memoryAfterLoad.external - memoryBeforeLoad.external,
3151
+ arrayBuffersDeltaAtLoad: memoryAfterLoad.arrayBuffers - memoryBeforeLoad.arrayBuffers
3152
+ });
3153
+ log(`[magic-context] embedding model loaded: ${this.model}`);
3154
+ } else if (this.disposing) {
3155
+ return;
3156
+ } else {
3157
+ throw lastError ?? new Error("unknown embedding load failure");
3158
+ }
3159
+ } finally {
3160
+ stopHeartbeat();
3161
+ await releaseLock();
3162
+ }
3163
+ } catch (error) {
3164
+ const nativeError = error instanceof LocalEmbeddingFallbackError ? error.nativeError : undefined;
3165
+ const failure = classifyLocalEmbeddingFailure(error, {
3166
+ platform: process.platform,
3167
+ arch: process.arch,
3168
+ usesWasm: this.usesWasm,
3169
+ nativeError
3170
+ });
3171
+ this.lastFailureReason = failure;
3172
+ localEmbeddingProcessFailure = failure;
3173
+ if (!localEmbeddingRuntimeIsDisabled() && isNativeRuntimeMissingError(error)) {
3174
+ disableLocalEmbeddingsAfterRuntimeFailure(error instanceof Error ? error.message : String(error));
3175
+ }
3176
+ logForRuntime(`[magic-context] embedding model failed to load (${failure.class}: ${failure.reason}):`, error);
3177
+ this.pipeline = null;
3178
+ } finally {
3179
+ this.initPromise = null;
3180
+ }
3181
+ })();
3182
+ await this.initPromise;
3183
+ return this.pipeline !== null;
3184
+ }
3185
+ waitForInFlightToDrain() {
3186
+ if (this.inFlight === 0) {
3187
+ return Promise.resolve();
3188
+ }
3189
+ return new Promise((resolve) => {
3190
+ this.inFlightWaiters.push(resolve);
3191
+ });
3192
+ }
3193
+ finishInFlight() {
3194
+ this.inFlight = Math.max(0, this.inFlight - 1);
3195
+ if (this.inFlight !== 0)
3196
+ return;
3197
+ const waiters = this.inFlightWaiters.splice(0);
3198
+ for (const waiter of waiters) {
3199
+ waiter();
3200
+ }
3201
+ }
3202
+ async embed(text, signal, _purpose) {
3203
+ if (this.workerClient)
3204
+ return (await this.embedBatch([text], signal, _purpose))[0] ?? null;
3205
+ if (signal?.aborted)
3206
+ return null;
3207
+ if (this.disposing)
3208
+ return null;
3209
+ this.inFlight += 1;
3210
+ try {
3211
+ if (!await this.initialize()) {
3212
+ return null;
3213
+ }
3214
+ const pipeline = this.pipeline;
3215
+ if (!pipeline) {
3216
+ return null;
3217
+ }
3218
+ const result = await withQuietConsole(() => pipeline(text, {
3219
+ pooling: "mean",
3220
+ normalize: true
3221
+ }));
3222
+ const embedding = extractBatchEmbeddings(result, 1)[0] ?? null;
3223
+ if (!embedding) {
3224
+ this.lastFailureReason = classifyLocalEmbeddingFailure(new Error("local embedding pipeline returned no vector"), { usesWasm: this.usesWasm });
3225
+ } else {
3226
+ this.lastFailureReason = null;
3227
+ }
3228
+ return embedding;
3229
+ } catch (error) {
3230
+ const failure = classifyLocalEmbeddingFailure(error, { usesWasm: this.usesWasm });
3231
+ this.lastFailureReason = failure;
3232
+ logForRuntime(`[magic-context] embedding failed (${failure.class}: ${failure.reason}):`, error);
3233
+ return null;
3234
+ } finally {
3235
+ this.finishInFlight();
3236
+ }
3237
+ }
3238
+ async embedBatch(texts, signal, _purpose) {
3239
+ if (this.workerClient) {
3240
+ if (!texts.length)
3241
+ return [];
3242
+ if (signal?.aborted || this.disposing)
3243
+ return texts.map(() => null);
3244
+ try {
3245
+ const reply = await this.workerClient.request(texts, signal);
3246
+ this.recordWorkerReply(reply);
3247
+ return reply.vectors ?? texts.map(() => null);
3248
+ } catch (error) {
3249
+ this.recordWorkerFailure(error);
3250
+ return texts.map(() => null);
3251
+ }
3252
+ }
3253
+ if (texts.length === 0) {
3254
+ return [];
3255
+ }
3256
+ if (signal?.aborted) {
3257
+ return Array.from({ length: texts.length }, () => null);
3258
+ }
3259
+ if (this.disposing) {
3260
+ return Array.from({ length: texts.length }, () => null);
3261
+ }
3262
+ this.inFlight += 1;
3263
+ try {
3264
+ if (!await this.initialize()) {
3265
+ return Array.from({ length: texts.length }, () => null);
3266
+ }
3267
+ const pipeline = this.pipeline;
3268
+ if (!pipeline) {
3269
+ return Array.from({ length: texts.length }, () => null);
3270
+ }
3271
+ const result = await withQuietConsole(() => pipeline(texts, {
3272
+ pooling: "mean",
3273
+ normalize: true
3274
+ }));
3275
+ const embeddings = extractBatchEmbeddings(result, texts.length);
3276
+ if (embeddings.every((embedding) => embedding === null)) {
3277
+ this.lastFailureReason = classifyLocalEmbeddingFailure(new Error("local embedding pipeline returned no vectors"), { usesWasm: this.usesWasm });
3278
+ } else {
3279
+ this.lastFailureReason = null;
3280
+ }
3281
+ return embeddings;
3282
+ } catch (error) {
3283
+ const failure = classifyLocalEmbeddingFailure(error, { usesWasm: this.usesWasm });
3284
+ this.lastFailureReason = failure;
3285
+ logForRuntime(`[magic-context] embedding batch failed (${failure.class}: ${failure.reason}):`, error);
3286
+ return Array.from({ length: texts.length }, () => null);
3287
+ } finally {
3288
+ this.finishInFlight();
3289
+ }
3290
+ }
3291
+ recordWorkerReply(reply) {
3292
+ this.workerLoaded = reply.loaded;
3293
+ this.lastFailureReason = reply.failure ?? null;
3294
+ if (reply.loaded && reply.stats) {
3295
+ loadedLocalEmbeddingRuntimes.set(this.memoryStatsId, {
3296
+ model: this.model,
3297
+ runtime: reply.stats.runtimes[0] ?? "wasm",
3298
+ rssDeltaAtLoad: reply.stats.rssDeltaAtLoad,
3299
+ externalDeltaAtLoad: reply.stats.externalDeltaAtLoad,
3300
+ arrayBuffersDeltaAtLoad: reply.stats.arrayBuffersDeltaAtLoad
3301
+ });
3302
+ } else
3303
+ loadedLocalEmbeddingRuntimes.delete(this.memoryStatsId);
3304
+ }
3305
+ recordWorkerFailure(error) {
3306
+ loadedLocalEmbeddingRuntimes.delete(this.memoryStatsId);
3307
+ this.workerLoaded = false;
3308
+ this.lastFailureReason = classifyLocalEmbeddingFailure(error);
3309
+ logForRuntime("[magic-context] embedding worker failed:", error);
3310
+ }
3311
+ async dispose() {
3312
+ if (this.workerClient) {
3313
+ this.disposing = true;
3314
+ this.workerLoaded = false;
3315
+ loadedLocalEmbeddingRuntimes.delete(this.memoryStatsId);
3316
+ await this.workerClient.dispose();
3317
+ return;
3318
+ }
3319
+ if (this.disposePromise) {
3320
+ return this.disposePromise;
3321
+ }
3322
+ this.disposing = true;
3323
+ this.disposePromise = (async () => {
3324
+ if (this.initPromise) {
3325
+ await this.initPromise;
3326
+ }
3327
+ await this.waitForInFlightToDrain();
3328
+ const pipelineToDispose = this.pipeline;
3329
+ this.pipeline = null;
3330
+ this.initPromise = null;
3331
+ loadedLocalEmbeddingRuntimes.delete(this.memoryStatsId);
3332
+ if (!pipelineToDispose) {
3333
+ return;
3334
+ }
3335
+ try {
3336
+ await pipelineToDispose.dispose?.();
3337
+ } catch (error) {
3338
+ log("[magic-context] embedding model dispose failed:", error);
3339
+ }
3340
+ })();
3341
+ return this.disposePromise;
3342
+ }
3343
+ isLoaded() {
3344
+ return this.workerClient ? this.workerLoaded && this.workerClient.isRunning() : this.pipeline !== null;
3345
+ }
3346
+ getLastFailureReason() {
3347
+ return this.lastFailureReason;
3348
+ }
3349
+ }
3350
+
3351
+ export { Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, SYNAPSE_DEFAULT_MODEL, isSynapseEmbeddingTruncated, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, getSynapseBatchRequestKey, SynapseEmbeddingProvider, dominantEmbeddingFailure, embeddingModelsMatch, resolveEmbeddingTextPrefixes, computeNormalizedHash, getEmbeddingProviderIdentity, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };