@cortexkit/opencode-magic-context 0.47.0 → 0.48.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 (366) hide show
  1. package/dist/agents/magic-context-prompt.d.ts +1 -1
  2. package/dist/agents/magic-context-prompt.d.ts.map +1 -1
  3. package/dist/{announcement-y35wzg2r.js → announcement-fp14dw0n.js} +3 -2
  4. package/dist/auto-search-worker.js +27 -30
  5. package/dist/config/index.d.ts.map +1 -1
  6. package/dist/config/mural-model-deprecation.d.ts +15 -0
  7. package/dist/config/mural-model-deprecation.d.ts.map +1 -0
  8. package/dist/config/project-security.d.ts +0 -3
  9. package/dist/config/project-security.d.ts.map +1 -1
  10. package/dist/config/schema/magic-context.d.ts +10 -6
  11. package/dist/config/schema/magic-context.d.ts.map +1 -1
  12. package/dist/{conflict-warning-hook-z44ynfz7.js → conflict-warning-hook-w8cykrnf.js} +12 -10
  13. package/dist/{context-wq4ffwyb.js → context-m0cy262m.js} +2690 -1903
  14. package/dist/{derive-budgets-ke12jnnh.js → derive-budgets-sg0xsq7s.js} +4 -3
  15. package/dist/embedding-activity-g1dhes6g.js +10 -0
  16. package/dist/embedding-backfill-9rcm1mfy.js +21 -0
  17. package/dist/embedding-cache-mgyr73ef.js +16 -0
  18. package/dist/embedding-worker.js +11 -9
  19. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts +1 -0
  21. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/task-config.d.ts +3 -3
  23. package/dist/features/magic-context/dreamer/task-config.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/task-executor.d.ts +1 -1
  25. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  26. package/dist/features/magic-context/dreamer/task-registry.d.ts +1 -0
  27. package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
  28. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  29. package/dist/features/magic-context/message-index-async.d.ts +16 -3
  30. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  31. package/dist/features/magic-context/message-index-bounded.d.ts +17 -0
  32. package/dist/features/magic-context/message-index-bounded.d.ts.map +1 -0
  33. package/dist/features/magic-context/message-index.d.ts +7 -1
  34. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  35. package/dist/features/magic-context/mural/render-trigger.d.ts +7 -4
  36. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  37. package/dist/features/magic-context/pi-content-decisions.d.ts +7 -1
  38. package/dist/features/magic-context/pi-content-decisions.d.ts.map +1 -1
  39. package/dist/features/magic-context/search.d.ts +29 -0
  40. package/dist/features/magic-context/search.d.ts.map +1 -1
  41. package/dist/features/magic-context/session-activity.d.ts.map +1 -1
  42. package/dist/features/magic-context/smart-notes/runner.d.ts +1 -0
  43. package/dist/features/magic-context/smart-notes/runner.d.ts.map +1 -1
  44. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  45. package/dist/features/magic-context/storage-meta-session.d.ts +6 -0
  46. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  47. package/dist/features/magic-context/storage-tag-identity-revision.d.ts +30 -0
  48. package/dist/features/magic-context/storage-tag-identity-revision.d.ts.map +1 -0
  49. package/dist/features/magic-context/storage-tags.d.ts +144 -4
  50. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  51. package/dist/features/magic-context/subagent-token-capture.d.ts.map +1 -1
  52. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  53. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  54. package/dist/harness-e4avh192.js +10 -0
  55. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +2 -0
  56. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +32 -3
  58. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  59. package/dist/hooks/magic-context/command-handler.d.ts +1 -0
  60. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  61. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  62. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  64. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/hook.d.ts +1 -1
  66. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  67. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  68. package/dist/hooks/magic-context/lkg-persist.d.ts +4 -3
  69. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  70. package/dist/hooks/magic-context/lkg-replay.d.ts +13 -8
  71. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  72. package/dist/hooks/magic-context/lkg-slot.d.ts +139 -2
  73. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/message-search-accepting-silent-worker.fixture.d.ts +2 -0
  75. package/dist/hooks/magic-context/message-search-accepting-silent-worker.fixture.d.ts.map +1 -0
  76. package/dist/hooks/magic-context/oc-stall-r2-warmup-worker.fixture.d.ts +2 -0
  77. package/dist/hooks/magic-context/oc-stall-r2-warmup-worker.fixture.d.ts.map +1 -0
  78. package/dist/hooks/magic-context/oc-stall-search-review.fixture.d.ts +2 -0
  79. package/dist/hooks/magic-context/oc-stall-search-review.fixture.d.ts.map +1 -0
  80. package/dist/hooks/magic-context/opencode1-to-model-messages.fixture.d.ts +63 -0
  81. package/dist/hooks/magic-context/opencode1-to-model-messages.fixture.d.ts.map +1 -0
  82. package/dist/hooks/magic-context/provider-visible-parts.d.ts +45 -0
  83. package/dist/hooks/magic-context/provider-visible-parts.d.ts.map +1 -0
  84. package/dist/hooks/magic-context/raw-ordinal-warmup-silent-worker.fixture.d.ts +2 -0
  85. package/dist/hooks/magic-context/raw-ordinal-warmup-silent-worker.fixture.d.ts.map +1 -0
  86. package/dist/hooks/magic-context/raw-ordinal-warmup-worker.d.ts +2 -0
  87. package/dist/hooks/magic-context/raw-ordinal-warmup-worker.d.ts.map +1 -0
  88. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts +87 -0
  89. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -0
  90. package/dist/hooks/magic-context/read-session-chunk.d.ts +12 -0
  91. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  92. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  93. package/dist/hooks/magic-context/read-session-formatting.d.ts +5 -0
  94. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/read-session-raw.d.ts +83 -1
  96. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  98. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
  99. package/dist/hooks/magic-context/sentinel.d.ts +41 -1
  100. package/dist/hooks/magic-context/sentinel.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/strip-content.d.ts +14 -2
  102. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/system-prompt-hash.d.ts +1 -0
  104. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/tag-messages.d.ts +8 -0
  106. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/tag-owner-warmup.d.ts +6 -0
  108. package/dist/hooks/magic-context/tag-owner-warmup.d.ts.map +1 -0
  109. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  110. package/dist/hooks/magic-context/token-count-exact.d.ts +35 -0
  111. package/dist/hooks/magic-context/token-count-exact.d.ts.map +1 -0
  112. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/transform.d.ts +8 -2
  114. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  115. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  116. package/dist/{index-w2t4ah5j.js → index-0an7742d.js} +14072 -14286
  117. package/dist/index-0qhce371.js +120 -0
  118. package/dist/{index-q6hef7fh.js → index-0sahzkwr.js} +6 -19
  119. package/dist/{index-k5bdx1bx.js → index-0w56v4fm.js} +3 -5
  120. package/dist/index-14cjxt20.js +819 -0
  121. package/dist/{v2/server-51dv1pr5.js → index-1qb0z7wa.js} +301 -27
  122. package/dist/index-2bvekkfy.js +11 -0
  123. package/dist/{index-sj29b3z2.js → index-2y0s2hep.js} +3 -3
  124. package/dist/index-4dhv7mqz.js +131 -0
  125. package/dist/{index-b35pxds2.js → index-58e3y90n.js} +1 -18
  126. package/dist/index-5zygecde.js +152 -0
  127. package/dist/{index-6d9e1m08.js → index-692jzy0p.js} +17775 -17450
  128. package/dist/index-72nhv486.js +2307 -0
  129. package/dist/index-7jzrrxap.js +931 -0
  130. package/dist/{v2/server-njt3np1k.js → index-7mx8v0pw.js} +220 -961
  131. package/dist/index-8ajstryz.js +18 -0
  132. package/dist/{index-sfpzqvdz.js → index-8cd2j99z.js} +2 -3
  133. package/dist/{index-hybnrwq0.js → index-8j7gqj40.js} +131 -128
  134. package/dist/index-bdckkfw6.js +3261 -0
  135. package/dist/{index-m5fe6jch.js → index-bhvjj0ys.js} +152 -2453
  136. package/dist/index-c43kr12f.js +3030 -0
  137. package/dist/index-cb7emxgj.js +984 -0
  138. package/dist/index-d9vfe7xq.js +16 -0
  139. package/dist/{index-5gq3b2ya.js → index-db7zwa3v.js} +147 -209
  140. package/dist/index-dhwzyd54.js +1142 -0
  141. package/dist/{index-8da2zjhz.js → index-eeezr5zz.js} +9 -7
  142. package/dist/{index-cwf6s3ay.js → index-f0h6xwqm.js} +2828 -2618
  143. package/dist/index-fb3zxn06.js +13 -0
  144. package/dist/index-fbv1dn35.js +171 -0
  145. package/dist/index-fr0wbhdn.js +43 -0
  146. package/dist/{index-mc22ayvf.js → index-ghc9f0n7.js} +11 -9
  147. package/dist/{index-fzbvakh0.js → index-jcbd3znx.js} +3 -3
  148. package/dist/{index-5a2r0p9f.js → index-k1xb52kd.js} +20 -13
  149. package/dist/index-k9nnwad5.js +3532 -0
  150. package/dist/{index-wx8a6bw3.js → index-kb9nn0a0.js} +270 -53
  151. package/dist/index-knh4y330.js +566 -0
  152. package/dist/{v2/server-fq7kq32k.js → index-mfkzp7qj.js} +1 -16
  153. package/dist/{index-gg8j07zz.js → index-mmyh6d8f.js} +4 -4
  154. package/dist/index-pavzsdc6.js +17 -0
  155. package/dist/{index-0c82743p.js → index-pdecwzrd.js} +17 -15
  156. package/dist/index-pg50n748.js +1060 -0
  157. package/dist/{index-92bp57hg.js → index-q2tqeqde.js} +123 -80
  158. package/dist/{index-rrrsepyw.js → index-q7h7csab.js} +90 -85
  159. package/dist/{v2/server-yr3zj7e7.js → index-qt1qqasc.js} +6 -7
  160. package/dist/{index-6wkcswft.js → index-ty64eqcn.js} +28 -18
  161. package/dist/{index-adwfkpex.js → index-yq8n9qcb.js} +23 -23
  162. package/dist/{index-9pk9exrb.js → index-z8e0psj8.js} +18 -18
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +586 -344
  165. package/dist/logger-d3wex3dz.js +20 -0
  166. package/dist/message-index-bounded-7ezbgddp.js +124 -0
  167. package/dist/{v2/message-time-backfill-1f9tzvcs.js → message-time-backfill-brbd63hv.js} +8 -6
  168. package/dist/migration-worker.js +25 -18
  169. package/dist/{model-resolution-xhfmyyvy.js → model-resolution-nx97z3x7.js} +1 -1
  170. package/dist/plugin/dream-timer.d.ts +1 -1
  171. package/dist/plugin/dream-timer.d.ts.map +1 -1
  172. package/dist/plugin/hooks/create-session-hooks.d.ts +1 -0
  173. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  174. package/dist/plugin/host-stall-profiler-report.d.ts +1 -66
  175. package/dist/plugin/host-stall-profiler-report.d.ts.map +1 -1
  176. package/dist/plugin/host-stall-profiler.d.ts +2 -95
  177. package/dist/plugin/host-stall-profiler.d.ts.map +1 -1
  178. package/dist/plugin/messages-transform.d.ts +0 -13
  179. package/dist/plugin/messages-transform.d.ts.map +1 -1
  180. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  181. package/dist/plugin/tool-registry.d.ts.map +1 -1
  182. package/dist/project-embedding-registry-7qzptcw7.js +88 -0
  183. package/dist/raw-ordinal-warmup-worker.js +60 -0
  184. package/dist/{read-session-chunk-4jey7hpt.js → read-session-chunk-6k83m4fj.js} +15 -9
  185. package/dist/read-session-raw-3g9qy1xa.js +58 -0
  186. package/dist/recomp-orchestrator-d3fp1cy0.js +57 -0
  187. package/dist/{v2/safe-notification-target-eb1n1vfb.js → safe-notification-target-5ffqq32m.js} +4 -2
  188. package/dist/search-epax1ecv.js +45 -0
  189. package/dist/{v2/send-session-notification-c0wtscea.js → send-session-notification-erecz4y4.js} +10 -7
  190. package/dist/shared/conflict-detector.d.ts.map +1 -1
  191. package/dist/shared/host-stall-profiler-bun.d.ts +46 -0
  192. package/dist/shared/host-stall-profiler-bun.d.ts.map +1 -0
  193. package/dist/shared/host-stall-profiler-common.d.ts +58 -0
  194. package/dist/shared/host-stall-profiler-common.d.ts.map +1 -0
  195. package/dist/shared/host-stall-profiler-node.d.ts +36 -0
  196. package/dist/shared/host-stall-profiler-node.d.ts.map +1 -0
  197. package/dist/shared/host-stall-profiler-report.d.ts +68 -0
  198. package/dist/shared/host-stall-profiler-report.d.ts.map +1 -0
  199. package/dist/shared/host-stall-profiler.d.ts +5 -0
  200. package/dist/shared/host-stall-profiler.d.ts.map +1 -0
  201. package/dist/shared/model-resolution.d.ts +2 -3
  202. package/dist/shared/model-resolution.d.ts.map +1 -1
  203. package/dist/shared/sqlite.d.ts +30 -0
  204. package/dist/shared/sqlite.d.ts.map +1 -1
  205. package/dist/shared/stable-json.d.ts.map +1 -1
  206. package/dist/shared/user-facing-codes.d.ts +0 -5
  207. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  208. package/dist/sqlite-context-pragmas-mv9jqwjh.js +6 -0
  209. package/dist/sqlite-mhjkerzq.js +46 -0
  210. package/dist/storage-memory-07fx57k6.js +71 -0
  211. package/dist/storage-tags-d3b0v2ss.js +131 -0
  212. package/dist/{task-config-v81k8jvk.js → task-config-cgpg0nvh.js} +2 -2
  213. package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
  214. package/dist/tools/ctx-note/constants.d.ts +4 -0
  215. package/dist/tools/ctx-note/constants.d.ts.map +1 -1
  216. package/dist/tools/ctx-note/tools.d.ts +1 -0
  217. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  218. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  219. package/dist/tools/parameter-descriptions.d.ts +2 -2
  220. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  221. package/dist/{transform-postprocess-phase-z5hzpsxv.js → transform-postprocess-phase-spcy2qre.js} +35 -20
  222. package/dist/transformers-node-wasm.js +18415 -18415
  223. package/dist/v2/auto-search-worker.js +27 -30
  224. package/dist/v2/{context-14v1hr8b.js → context-sf98kstd.js} +3737 -3004
  225. package/dist/v2/{derive-budgets-nc9avxz8.js → derive-budgets-3vc0y84t.js} +4 -3
  226. package/dist/v2/embedding-activity-g1dhes6g.js +10 -0
  227. package/dist/v2/embedding-backfill-vn8g1nh1.js +21 -0
  228. package/dist/v2/embedding-cache-mgyr73ef.js +16 -0
  229. package/dist/v2/embedding-worker.js +12 -9
  230. package/dist/v2/fold/host-media.d.ts +4 -0
  231. package/dist/v2/fold/host-media.d.ts.map +1 -1
  232. package/dist/v2/fold/memory-cache.d.ts +70 -0
  233. package/dist/v2/fold/memory-cache.d.ts.map +1 -0
  234. package/dist/v2/fold/native-codec.d.ts +10 -0
  235. package/dist/v2/fold/native-codec.d.ts.map +1 -0
  236. package/dist/v2/fold/native-replay.d.ts +58 -0
  237. package/dist/v2/fold/native-replay.d.ts.map +1 -0
  238. package/dist/v2/fold/policy.d.ts +24 -0
  239. package/dist/v2/fold/policy.d.ts.map +1 -0
  240. package/dist/v2/harness-e4avh192.js +10 -0
  241. package/dist/v2/hooks/context.d.ts +2 -2
  242. package/dist/v2/hooks/context.d.ts.map +1 -1
  243. package/dist/v2/hooks/dream-manual.d.ts +1 -1
  244. package/dist/v2/hooks/dream-manual.d.ts.map +1 -1
  245. package/dist/v2/hooks/dream-timer.d.ts.map +1 -1
  246. package/dist/v2/hooks/dream-trigger.d.ts +1 -2
  247. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  248. package/dist/v2/hooks/payload.d.ts.map +1 -1
  249. package/dist/v2/hooks/tools.d.ts.map +1 -1
  250. package/dist/v2/hooks/types.d.ts +6 -0
  251. package/dist/v2/hooks/types.d.ts.map +1 -1
  252. package/dist/v2/logger-mxd0ym09.js +19 -0
  253. package/dist/v2/message-index-bounded-dy3s2k1e.js +123 -0
  254. package/dist/{message-time-backfill-r5epkzj3.js → v2/message-time-backfill-gtx1pwk1.js} +7 -7
  255. package/dist/v2/migration-worker.js +24 -17
  256. package/dist/v2/{model-resolution-xhfmyyvy.js → model-resolution-nx97z3x7.js} +1 -1
  257. package/dist/v2/project-embedding-registry-1tgba5dv.js +86 -0
  258. package/dist/v2/raw-ordinal-warmup-worker.js +60 -0
  259. package/dist/v2/{read-session-chunk-gyyv7w2r.js → read-session-chunk-rh4khdkv.js} +14 -8
  260. package/dist/v2/read-session-raw-bsbmf0vj.js +57 -0
  261. package/dist/v2/recomp-orchestrator-az61rfcg.js +57 -0
  262. package/dist/{safe-notification-target-43r8jsxw.js → v2/safe-notification-target-73ax1p5v.js} +3 -3
  263. package/dist/v2/search-nzkwrc6n.js +45 -0
  264. package/dist/{send-session-notification-0m68ms3n.js → v2/send-session-notification-6km439kn.js} +9 -8
  265. package/dist/{index-5eqk6z3s.js → v2/server-1r6pmz4f.js} +301 -27
  266. package/dist/v2/server-2bvekkfy.js +11 -0
  267. package/dist/v2/server-2fbhp79z.js +3205 -0
  268. package/dist/v2/{server-ajzeteqw.js → server-2ra6pwf3.js} +1 -18
  269. package/dist/v2/server-4dhv7mqz.js +131 -0
  270. package/dist/v2/{server-y10vbq6y.js → server-4k748ke6.js} +11 -1053
  271. package/dist/v2/{server-vs5gpnd4.js → server-52awr2mw.js} +81 -145
  272. package/dist/v2/{server-1qbnzc80.js → server-5m3dt5r1.js} +136 -148
  273. package/dist/v2/server-686jg6eb.js +3508 -0
  274. package/dist/v2/server-7jzrrxap.js +931 -0
  275. package/dist/v2/server-7wwc2nga.js +3023 -0
  276. package/dist/v2/server-8ajstryz.js +18 -0
  277. package/dist/v2/{server-sfpzqvdz.js → server-8cd2j99z.js} +2 -3
  278. package/dist/v2/{server-d0sraw7m.js → server-8pyt7hev.js} +291 -286
  279. package/dist/v2/server-8tqanswc.js +984 -0
  280. package/dist/v2/{server-14vq4kpm.js → server-aan4q8mx.js} +3 -3
  281. package/dist/v2/server-d9vfe7xq.js +16 -0
  282. package/dist/{index-x3kwrmqk.js → v2/server-e0vdaae2.js} +35 -792
  283. package/dist/v2/server-ezhze64f.js +1048 -0
  284. package/dist/v2/server-fb3zxn06.js +13 -0
  285. package/dist/v2/server-fr0wbhdn.js +43 -0
  286. package/dist/v2/server-g5r0n3b6.js +1137 -0
  287. package/dist/v2/server-gjcr4w98.js +154 -0
  288. package/dist/v2/server-k228xhjg.js +171 -0
  289. package/dist/v2/{server-nf82q6pt.js → server-k8x2rbxc.js} +5946 -5602
  290. package/dist/v2/{server-wx8a6bw3.js → server-kb9nn0a0.js} +270 -53
  291. package/dist/{index-rrbbspwh.js → v2/server-mfkzp7qj.js} +1 -16
  292. package/dist/v2/server-pavzsdc6.js +17 -0
  293. package/dist/v2/{server-e0c1b7a7.js → server-psqc7e9n.js} +122 -79
  294. package/dist/{index-yr3zj7e7.js → v2/server-qt1qqasc.js} +6 -7
  295. package/dist/v2/server-qye6ykf7.js +120 -0
  296. package/dist/v2/{server-qdjnb2z1.js → server-r5p3b1wy.js} +11 -9
  297. package/dist/v2/server-sggvvzhb.js +759 -0
  298. package/dist/v2/{server-cpepxy2q.js → server-v06jcv0w.js} +14 -12
  299. package/dist/v2/server-vqpf3167.js +1048 -0
  300. package/dist/v2/{server-rz514f14.js → server-x2g40a71.js} +2044 -2060
  301. package/dist/v2/{server-vd4e7174.js → server-xdfwt6kh.js} +20 -16
  302. package/dist/v2/{server-efhwzx05.js → server-xxm59eww.js} +23 -23
  303. package/dist/v2/server-yczc713m.js +564 -0
  304. package/dist/v2/{server-fcdehk1s.js → server-z2037m6z.js} +4 -4
  305. package/dist/v2/{server-50hvkg3v.js → server-zm570tr2.js} +160 -158
  306. package/dist/v2/{server-6r257mf5.js → server-zxhgvsf9.js} +3 -3
  307. package/dist/v2/server.js +16 -14
  308. package/dist/v2/sqlite-context-pragmas-mv9jqwjh.js +6 -0
  309. package/dist/v2/sqlite-mhjkerzq.js +46 -0
  310. package/dist/v2/storage-memory-07fx57k6.js +71 -0
  311. package/dist/v2/storage-tags-w4tv77sn.js +130 -0
  312. package/dist/v2/store-reader.d.ts +16 -0
  313. package/dist/v2/store-reader.d.ts.map +1 -1
  314. package/dist/v2/{task-config-tbndqyny.js → task-config-x0hq3qfd.js} +2 -2
  315. package/dist/v2/transformers-node-wasm.js +18415 -18415
  316. package/dist/v2/tui/index.d.ts.map +1 -1
  317. package/dist/v2/tui/types.d.ts +1 -10
  318. package/dist/v2/tui/types.d.ts.map +1 -1
  319. package/dist/v2/{wrapup-orchestrator-nbz854vc.js → wrapup-orchestrator-mz7efs7w.js} +51 -30
  320. package/dist/wrapup-orchestrator-amzta1t4.js +44 -0
  321. package/package.json +4 -3
  322. package/src/agents/magic-context-prompt.ts +27 -2
  323. package/src/agents/smart-notes-enabled.test.ts +294 -0
  324. package/src/agents/smart-notes-on.golden.json +70 -0
  325. package/src/config/index.test.ts +67 -1
  326. package/src/config/index.ts +2 -0
  327. package/src/config/latch-permanence-guard.test.ts +4 -0
  328. package/src/config/mural-model-deprecation.ts +24 -0
  329. package/src/config/project-security.hostile-matrix.test.ts +4 -44
  330. package/src/config/project-security.test.ts +9 -14
  331. package/src/config/project-security.ts +13 -55
  332. package/src/config/schema/magic-context.test.ts +2 -2
  333. package/src/config/schema/magic-context.ts +16 -10
  334. package/src/features/magic-context/dreamer/task-registry.ts +6 -0
  335. package/src/shared/conflict-detector.test.ts +56 -0
  336. package/src/shared/conflict-detector.ts +16 -5
  337. package/src/shared/host-stall-profiler-bun.ts +358 -0
  338. package/src/shared/host-stall-profiler-common.ts +159 -0
  339. package/src/shared/host-stall-profiler-node.test.ts +234 -0
  340. package/src/shared/host-stall-profiler-node.ts +274 -0
  341. package/src/shared/host-stall-profiler-report.ts +248 -0
  342. package/src/shared/host-stall-profiler.ts +57 -0
  343. package/src/shared/model-resolution.test.ts +54 -17
  344. package/src/shared/model-resolution.ts +6 -17
  345. package/src/shared/sqlite.test.ts +52 -0
  346. package/src/shared/sqlite.ts +339 -23
  347. package/src/shared/stable-json-linear.test.ts +109 -0
  348. package/src/shared/stable-json.ts +37 -7
  349. package/src/shared/user-facing-codes.ts +2 -6
  350. package/src/shared/write-transaction-attribution.test.ts +2 -2
  351. package/src/v2/tui/host-contract.test.ts +41 -67
  352. package/src/v2/tui/index.ts +6 -214
  353. package/src/v2/tui/types.ts +5 -17
  354. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts +0 -45
  355. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts.map +0 -1
  356. package/dist/features/magic-context/checkout-claim.d.ts +0 -155
  357. package/dist/features/magic-context/checkout-claim.d.ts.map +0 -1
  358. package/dist/index-bb36vgr3.js +0 -6608
  359. package/dist/index-fnn5pjtt.js +0 -6554
  360. package/dist/recomp-orchestrator-rervg6q4.js +0 -42
  361. package/dist/v2/recomp-orchestrator-42vjba7p.js +0 -42
  362. package/dist/v2/server-3trjk1hx.js +0 -6360
  363. package/dist/v2/server-nm9n3aqq.js +0 -6461
  364. package/dist/wrapup-orchestrator-b2dztrar.js +0 -29
  365. /package/dist/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
  366. /package/dist/v2/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
@@ -1,19 +1,22 @@
1
1
  import {
2
- toolTemplateError,
3
- DEFAULT_PROTECTED_TOOLS,
4
- mergeProtectedTools
5
- } from "./index-rrbbspwh.js";
2
+ toolTemplateError
3
+ } from "./index-mfkzp7qj.js";
4
+ import {
5
+ getSynapseLaneIdentity
6
+ } from "./index-72nhv486.js";
7
+ import {
8
+ getHarness2
9
+ } from "./index-pavzsdc6.js";
6
10
  import {
7
- getHarness,
8
11
  getMagicContextStorageDir
9
- } from "./index-q6hef7fh.js";
12
+ } from "./index-0sahzkwr.js";
10
13
  import {
11
14
  importPluginModule,
12
- log
13
- } from "./index-hybnrwq0.js";
15
+ log2
16
+ } from "./index-8j7gqj40.js";
14
17
  import {
15
- estimateTokens
16
- } from "./index-5eqk6z3s.js";
18
+ computeNormalizedHash
19
+ } from "./index-2bvekkfy.js";
17
20
  import {
18
21
  shouldEnforcePrivateStoragePermissions,
19
22
  ensureStorageDirectorySync,
@@ -21,6 +24,10 @@ import {
21
24
  writeStorageFileHandleAsync,
22
25
  createStorageFileHandleAsync
23
26
  } from "./index-1bc61ans.js";
27
+ import {
28
+ DEFAULT_PROTECTED_TOOLS,
29
+ mergeProtectedTools
30
+ } from "./index-d9vfe7xq.js";
24
31
  import {
25
32
  modelRefLookupOrder
26
33
  } from "./index-avwt563y.js";
@@ -97,13 +104,6 @@ function buildPrimaryLanguageDirective(language) {
97
104
  return `Use ${target} for your natural-language replies to the user unless the user explicitly asks for another language. Keep code, identifiers, file paths, commands, logs, and quoted text verbatim.`;
98
105
  }
99
106
 
100
- // src/features/magic-context/memory/embedding-local.ts
101
- import { readdirSync, statSync } from "node:fs";
102
- import { stat, unlink } from "node:fs/promises";
103
- import { dirname, join } from "node:path";
104
- import { pathToFileURL } from "node:url";
105
- import { workerData } from "node:worker_threads";
106
-
107
107
  // src/config/schema/magic-context.ts
108
108
  import { homedir } from "node:os";
109
109
 
@@ -5610,7 +5610,7 @@ var MagicContextConfigSchema = object({
5610
5610
  allow_home_project: boolean2().default(false).describe("Allow Magic Context sessions launched from the exact canonical home directory. A non-git home uses its deterministic dir: identity; a home repository uses its git: identity. USER-LEVEL ONLY: project config is ignored. The home identity is excluded from registry seed exports, never resolves descendants by containment, and cannot join a workspace."),
5611
5611
  mural: object({
5612
5612
  enabled: boolean2().default(false),
5613
- model: string().trim().min(1).optional().describe("Model for the compress-cues task that compresses each memory into a mural cue. The mural image itself is rendered deterministically (no author model).")
5613
+ model: unknown().optional().describe("Deprecated: ignored. compress-cues now uses the dreamer model for each harness, like every other dreamer task; override it with dreamer.opencode.tasks.compress-cues.model (or the pi/omp equivalent). Remove this key; it no longer does anything.").meta({ deprecated: true })
5614
5614
  }).default({ enabled: false }).describe("Experimental mural: a single deterministically-rendered image of project memories that did not fit the context budget. Cues are compressed per-memory by the compress-cues dreamer task."),
5615
5615
  transform_mode: _enum(["ts", "rust"]).default("ts").describe('Experimental: routes the entire Magic Context runtime for the project through the ck-mc Rust module over subc (requires user-level `subc` config); "ts" is the current TypeScript pipeline.'),
5616
5616
  auto_update: boolean2().optional().describe("Enable automatic npm self-update checks for the OpenCode plugin. Security: USER-only in config loader, so hostile project configs cannot suppress updates."),
@@ -5620,8 +5620,9 @@ var MagicContextConfigSchema = object({
5620
5620
  historian: HistorianConfigSchema.describe("Historian metadata plus independent strict OpenCode, Pi, and OMP execution blocks. Retained metadata stays at historian; model, fallback_models, variant, and thinking_level belong only in historian.opencode, historian.pi, or historian.omp."),
5621
5621
  dreamer: DreamerConfigSchema.optional().describe("Dreamer metadata and scheduling plus independent strict OpenCode, Pi, and OMP execution blocks. schedule and promotion_threshold stay at dreamer.tasks; model, fallback_models, variant, thinking_level, and timeout_minutes belong only in the matching harness block."),
5622
5622
  smart_notes: object({
5623
+ enabled: boolean2().default(true).describe("Enable smart-note authoring and condition evaluation. User-level only: tool definitions are process-wide. Changes require a host restart and rebuild each session's cached prompt once. Pending notes remain stored and unchecked; already-ready notes still surface."),
5623
5624
  retina_handoff: boolean2().default(false).describe("When true, dreamer skips smart notes whose surface conditions compiled to retina provider configs at authoring time. Default false keeps both paths active until the retina consumer is deployed.")
5624
- }).default({ retina_handoff: false }).describe("Smart-note ownership transition controls."),
5625
+ }).default({ enabled: true, retina_handoff: false }).describe("Smart-note ownership transition controls."),
5625
5626
  cache_ttl: union([string(), object({ default: string() }).catchall(string())]).default("5m").describe(`How long Magic Context assumes the provider's cached prefix stays valid. This is MC's own deferral gate — it does not change the provider's actual cache lifetime. String (e.g. "5m", "1h", "30s") or per-model object ({ default: "5m", "provider/model": "1h", "provider/*": "never" }); keys resolve most-specific first (exact provider/model, bare model ID, shorter dash-prefixes, then the provider/* wildcard, then default). User and project settings, including an explicit "5m" or object default, apply on the next pass. Only built-in defaults are frozen per session, including across restarts: when unset, GPT-5.6 and later (including gpt-6*, through any provider prefix) use 30m, other models use 5m. /ctx-status shows the effective TTL and whether it comes from your config or a frozen built-in default. Editing the TTL does not itself rewrite prompt bytes; a lowered TTL rebuilds only after normal idle expiry. OpenAI documents at least 30 minutes since the latest write or reuse: https://developers.openai.com/api/docs/guides/prompt-caching (Cache lifetime and Summary of model differences). Set to "never" to mean MC never assumes expiry (for lanes kept warm externally by a cache-keep tool) — disables the idle-TTL heuristic so MC never initiates a rebuild based on elapsed time. Provider-side extended TTL is a separate request-level concern (cache_control: { ttl } in the request body).`),
5626
5627
  prompt_surface: PromptSurfaceConfigSchema.default({ default: "full" }).describe("Prompt-surface presets: default is full; models use bare model IDs, provider/model, or provider/* routing keys. Guidance and tool-description overrides are user-level only. OpenCode 1.x, Pi, and OMP register tool descriptions once per process (they follow the default preset). OpenCode 2 rewrites the five ctx_* descriptions per request from the draft model."),
5627
5628
  output_reserve: union([
@@ -5726,7 +5727,6 @@ var MagicContextConfigSchema = object({
5726
5727
  });
5727
5728
  var LIVE_RELOAD_CONFIG_PATHS = [
5728
5729
  "cache_ttl",
5729
- "mural.model",
5730
5730
  "toast_duration_ms",
5731
5731
  "historian.opencode.model",
5732
5732
  "historian.opencode.fallback_models",
@@ -5797,6 +5797,125 @@ function deriveDefaultProtectedTokens(usableSoft) {
5797
5797
  return Math.min(64000, Math.max(lowerBound, target));
5798
5798
  }
5799
5799
 
5800
+ // src/features/magic-context/memory/embedding-model-match.ts
5801
+ function parseEmbeddingModel(model) {
5802
+ const lastColon = model.lastIndexOf(":");
5803
+ if (lastColon > model.lastIndexOf("/")) {
5804
+ return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
5805
+ }
5806
+ return { base: model };
5807
+ }
5808
+ function normalizeEmbeddingModelId(model) {
5809
+ return parseEmbeddingModel(model.trim().toLowerCase()).base;
5810
+ }
5811
+ function matchNormalizedEmbeddingModels(a, b) {
5812
+ if (a.length === 0 || b.length === 0)
5813
+ return true;
5814
+ if (a === b)
5815
+ return true;
5816
+ const longer = a.length >= b.length ? a : b;
5817
+ const shorter = a.length >= b.length ? b : a;
5818
+ const isBoundary = (ch) => ch === "-" || ch === "/";
5819
+ if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
5820
+ return true;
5821
+ if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
5822
+ return true;
5823
+ return false;
5824
+ }
5825
+ function embeddingModelsMatch(served, requested) {
5826
+ const servedNormalized = served.trim().toLowerCase();
5827
+ const requestedNormalized = requested.trim().toLowerCase();
5828
+ const servedModel = parseEmbeddingModel(servedNormalized);
5829
+ const requestedModel = parseEmbeddingModel(requestedNormalized);
5830
+ if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
5831
+ return false;
5832
+ }
5833
+ return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
5834
+ }
5835
+ var QWEN3_QUERY_INSTRUCTION = `Instruct: Given a web search query, retrieve relevant passages that answer the query
5836
+ Query: `;
5837
+ var INSTRUCT_WEB_SEARCH_QUERY_PREFIX = QWEN3_QUERY_INSTRUCTION;
5838
+ var EMBEDDING_MODEL_PREFIX_FAMILIES = [
5839
+ {
5840
+ family: "qwen3-embedding",
5841
+ basenamePattern: /^qwen3-embedding(?:-|$)/,
5842
+ prefixes: { queryPrefix: QWEN3_QUERY_INSTRUCTION, documentPrefix: "" }
5843
+ },
5844
+ {
5845
+ family: "gte-qwen-instruct",
5846
+ basenamePattern: /^gte-qwen.*-instruct(?:-|$)/,
5847
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
5848
+ },
5849
+ {
5850
+ family: "e5-instruct",
5851
+ basenamePattern: /^(?:multilingual-)?e5-.*-instruct(?:-|$)/,
5852
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
5853
+ },
5854
+ {
5855
+ family: "nomic-embed-text",
5856
+ basenamePattern: /^nomic-embed-text(?:-|$)/,
5857
+ prefixes: { queryPrefix: "search_query: ", documentPrefix: "search_document: " }
5858
+ }
5859
+ ];
5860
+ function modelBasename(model) {
5861
+ const normalized = normalizeEmbeddingModelId(model);
5862
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
5863
+ }
5864
+ function resolveEmbeddingTextPrefixes(model, queryInstruction, documentPrefix) {
5865
+ const family = EMBEDDING_MODEL_PREFIX_FAMILIES.find(({ basenamePattern }) => basenamePattern.test(modelBasename(model)));
5866
+ return {
5867
+ queryPrefix: queryInstruction === false ? "" : queryInstruction !== undefined ? queryInstruction : family?.prefixes.queryPrefix ?? "",
5868
+ documentPrefix: documentPrefix ?? family?.prefixes.documentPrefix ?? ""
5869
+ };
5870
+ }
5871
+
5872
+ // src/features/magic-context/memory/embedding-identity.ts
5873
+ function normalizeEndpoint(endpoint) {
5874
+ return endpoint?.trim().replace(/\/+$/, "") ?? "";
5875
+ }
5876
+ var LOCAL_EMBEDDING_RUNTIME_FINGERPRINT = "transformers@4.3.0;onnxruntime-node@1.30.0;onnxruntime-web@1.26.0-dev.20260416-b7804b056c";
5877
+ function getEmbeddingProviderIdentity(config) {
5878
+ if (config.provider === "off") {
5879
+ return "embedding-provider:off";
5880
+ }
5881
+ if (config.provider === "synapse") {
5882
+ const resolved = config;
5883
+ if (!resolved.model || !resolved.synapse_fingerprint)
5884
+ return "synapse:v1:pending";
5885
+ return getSynapseLaneIdentity(resolved.model, resolved.synapse_fingerprint);
5886
+ }
5887
+ if (config.provider !== "local" && config.provider !== "openai-compatible") {
5888
+ throw new Error("Unknown embedding provider");
5889
+ }
5890
+ const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
5891
+ const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
5892
+ const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
5893
+ const identityInput = config.provider === "openai-compatible" ? {
5894
+ provider: "openai-compatible",
5895
+ model: config.model.trim(),
5896
+ endpoint: normalizeEndpoint(config.endpoint),
5897
+ apiKeyPresent: Boolean(config.api_key?.trim()),
5898
+ inputType: config.input_type?.trim() || "",
5899
+ ...documentPrefix ? { documentPrefix } : {},
5900
+ ...truncate ? { truncate } : {}
5901
+ } : {
5902
+ provider: "local",
5903
+ model: config.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
5904
+ endpoint: "",
5905
+ apiKeyPresent: false,
5906
+ runtimeFingerprint: LOCAL_EMBEDDING_RUNTIME_FINGERPRINT,
5907
+ ...localDtype ? { localDtype } : {}
5908
+ };
5909
+ return `embedding-provider:${computeNormalizedHash(JSON.stringify(identityInput))}`;
5910
+ }
5911
+
5912
+ // src/features/magic-context/memory/embedding-local.ts
5913
+ import { readdirSync, statSync } from "node:fs";
5914
+ import { stat, unlink } from "node:fs/promises";
5915
+ import { dirname, join } from "node:path";
5916
+ import { pathToFileURL } from "node:url";
5917
+ import { workerData } from "node:worker_threads";
5918
+
5800
5919
  // src/features/magic-context/memory/embedding-failure.ts
5801
5920
  function errorMessage(error) {
5802
5921
  return error instanceof Error ? error.message : String(error ?? "unknown error");
@@ -5892,2426 +6011,6 @@ function dominantEmbeddingFailure(failures) {
5892
6011
  return dominant?.failure;
5893
6012
  }
5894
6013
 
5895
- // src/features/magic-context/memory/embedding-model-match.ts
5896
- function parseEmbeddingModel(model) {
5897
- const lastColon = model.lastIndexOf(":");
5898
- if (lastColon > model.lastIndexOf("/")) {
5899
- return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
5900
- }
5901
- return { base: model };
5902
- }
5903
- function normalizeEmbeddingModelId(model) {
5904
- return parseEmbeddingModel(model.trim().toLowerCase()).base;
5905
- }
5906
- function matchNormalizedEmbeddingModels(a, b) {
5907
- if (a.length === 0 || b.length === 0)
5908
- return true;
5909
- if (a === b)
5910
- return true;
5911
- const longer = a.length >= b.length ? a : b;
5912
- const shorter = a.length >= b.length ? b : a;
5913
- const isBoundary = (ch) => ch === "-" || ch === "/";
5914
- if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
5915
- return true;
5916
- if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
5917
- return true;
5918
- return false;
5919
- }
5920
- function embeddingModelsMatch(served, requested) {
5921
- const servedNormalized = served.trim().toLowerCase();
5922
- const requestedNormalized = requested.trim().toLowerCase();
5923
- const servedModel = parseEmbeddingModel(servedNormalized);
5924
- const requestedModel = parseEmbeddingModel(requestedNormalized);
5925
- if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
5926
- return false;
5927
- }
5928
- return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
5929
- }
5930
- var QWEN3_QUERY_INSTRUCTION = `Instruct: Given a web search query, retrieve relevant passages that answer the query
5931
- Query: `;
5932
- var INSTRUCT_WEB_SEARCH_QUERY_PREFIX = QWEN3_QUERY_INSTRUCTION;
5933
- var EMBEDDING_MODEL_PREFIX_FAMILIES = [
5934
- {
5935
- family: "qwen3-embedding",
5936
- basenamePattern: /^qwen3-embedding(?:-|$)/,
5937
- prefixes: { queryPrefix: QWEN3_QUERY_INSTRUCTION, documentPrefix: "" }
5938
- },
5939
- {
5940
- family: "gte-qwen-instruct",
5941
- basenamePattern: /^gte-qwen.*-instruct(?:-|$)/,
5942
- prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
5943
- },
5944
- {
5945
- family: "e5-instruct",
5946
- basenamePattern: /^(?:multilingual-)?e5-.*-instruct(?:-|$)/,
5947
- prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
5948
- },
5949
- {
5950
- family: "nomic-embed-text",
5951
- basenamePattern: /^nomic-embed-text(?:-|$)/,
5952
- prefixes: { queryPrefix: "search_query: ", documentPrefix: "search_document: " }
5953
- }
5954
- ];
5955
- function modelBasename(model) {
5956
- const normalized = normalizeEmbeddingModelId(model);
5957
- return normalized.slice(normalized.lastIndexOf("/") + 1);
5958
- }
5959
- function resolveEmbeddingTextPrefixes(model, queryInstruction, documentPrefix) {
5960
- const family = EMBEDDING_MODEL_PREFIX_FAMILIES.find(({ basenamePattern }) => basenamePattern.test(modelBasename(model)));
5961
- return {
5962
- queryPrefix: queryInstruction === false ? "" : queryInstruction !== undefined ? queryInstruction : family?.prefixes.queryPrefix ?? "",
5963
- documentPrefix: documentPrefix ?? family?.prefixes.documentPrefix ?? ""
5964
- };
5965
- }
5966
-
5967
- // src/features/magic-context/memory/embedding-synapse.ts
5968
- import { createHash } from "node:crypto";
5969
-
5970
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
5971
- import { promises as fs2 } from "node:fs";
5972
- import { debuglog } from "node:util";
5973
-
5974
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
5975
- import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
5976
-
5977
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
5978
- import net from "node:net";
5979
-
5980
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/envelope.js
5981
- var PROTOCOL_VERSION = 2;
5982
- var HEADER_LEN = 21;
5983
- var FROZEN_PREFIX_LEN = 5;
5984
- var MAX_FRAME_BODY_LEN = 64 * 1024 * 1024;
5985
- var FrameType;
5986
- (function(FrameType) {
5987
- FrameType[FrameType["Request"] = 0] = "Request";
5988
- FrameType[FrameType["Response"] = 1] = "Response";
5989
- FrameType[FrameType["Push"] = 2] = "Push";
5990
- FrameType[FrameType["StreamData"] = 3] = "StreamData";
5991
- FrameType[FrameType["StreamEnd"] = 4] = "StreamEnd";
5992
- FrameType[FrameType["Error"] = 5] = "Error";
5993
- FrameType[FrameType["Cancel"] = 6] = "Cancel";
5994
- FrameType[FrameType["Ping"] = 7] = "Ping";
5995
- FrameType[FrameType["Pong"] = 8] = "Pong";
5996
- FrameType[FrameType["Hello"] = 9] = "Hello";
5997
- FrameType[FrameType["HelloAck"] = 10] = "HelloAck";
5998
- FrameType[FrameType["Goodbye"] = 11] = "Goodbye";
5999
- })(FrameType || (FrameType = {}));
6000
- var FRAME_TYPE_MAX = FrameType.Goodbye;
6001
- function isPureHeader(ty) {
6002
- return ty === FrameType.Cancel || ty === FrameType.Ping || ty === FrameType.Pong || ty === FrameType.Goodbye;
6003
- }
6004
- var Priority;
6005
- (function(Priority) {
6006
- Priority[Priority["Passive"] = 0] = "Passive";
6007
- Priority[Priority["Interactive"] = 1] = "Interactive";
6008
- Priority[Priority["Background"] = 2] = "Background";
6009
- })(Priority || (Priority = {}));
6010
- var AdmissionClass;
6011
- (function(AdmissionClass) {
6012
- AdmissionClass[AdmissionClass["Normal"] = 0] = "Normal";
6013
- AdmissionClass[AdmissionClass["Expedite"] = 1] = "Expedite";
6014
- AdmissionClass[AdmissionClass["Sheddable"] = 2] = "Sheddable";
6015
- })(AdmissionClass || (AdmissionClass = {}));
6016
- var FLAG_BINARY = 1;
6017
- var FLAG_PRIORITY_MASK = 6;
6018
- var FLAG_PRIORITY_SHIFT = 1;
6019
- var FLAG_LAST = 8;
6020
- var FLAG_ADMISSION_MASK = 48;
6021
- var FLAG_ADMISSION_SHIFT = 4;
6022
- var FLAG_RESERVED_MASK = 128;
6023
- function buildFlags(binary, priority, last, admissionClass = AdmissionClass.Normal) {
6024
- let flags = 0;
6025
- if (binary)
6026
- flags |= FLAG_BINARY;
6027
- flags |= priority << FLAG_PRIORITY_SHIFT;
6028
- if (last)
6029
- flags |= FLAG_LAST;
6030
- flags |= admissionClass << FLAG_ADMISSION_SHIFT;
6031
- return flags;
6032
- }
6033
- function hasBinary(flags) {
6034
- return (flags & FLAG_BINARY) !== 0;
6035
- }
6036
- function encodeHeader(header) {
6037
- const buffer = new Uint8Array(HEADER_LEN);
6038
- const view = new DataView(buffer.buffer);
6039
- view.setUint32(0, header.len, true);
6040
- buffer[4] = header.ver;
6041
- buffer[5] = header.ty;
6042
- buffer[6] = header.flags;
6043
- view.setUint16(7, header.channel, true);
6044
- view.setUint32(9, header.epoch, true);
6045
- view.setBigUint64(13, header.corr, true);
6046
- return buffer;
6047
- }
6048
-
6049
- class DecodeError extends Error {
6050
- code;
6051
- constructor(message, code) {
6052
- super(message);
6053
- this.code = code;
6054
- this.name = "DecodeError";
6055
- }
6056
- }
6057
- function validateHeaderFields(header) {
6058
- const len = header.len >>> 0;
6059
- const ver = header.ver >>> 0 & 255;
6060
- const typeByte = header.ty >>> 0 & 255;
6061
- const flags = header.flags >>> 0 & 255;
6062
- const channel = header.channel >>> 0 & 65535;
6063
- const epoch = header.epoch >>> 0;
6064
- BigInt.asUintN(64, header.corr);
6065
- if (ver !== PROTOCOL_VERSION)
6066
- throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
6067
- if (typeByte > FRAME_TYPE_MAX)
6068
- throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
6069
- const ty = typeByte;
6070
- if ((flags & FLAG_RESERVED_MASK) !== 0) {
6071
- throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
6072
- }
6073
- if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
6074
- throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
6075
- }
6076
- const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
6077
- if (admission === 3) {
6078
- throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
6079
- }
6080
- if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
6081
- throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
6082
- }
6083
- if (channel === 0 && epoch !== 0) {
6084
- throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
6085
- }
6086
- if (isPureHeader(ty) && len !== 0) {
6087
- throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
6088
- }
6089
- }
6090
- function decodeHeader(bytes) {
6091
- if (bytes.length < FROZEN_PREFIX_LEN) {
6092
- throw new DecodeError(`header shorter than frozen prefix: have ${bytes.length} bytes`, "too_short_for_prefix");
6093
- }
6094
- const ver = bytes[4];
6095
- if (ver !== PROTOCOL_VERSION)
6096
- throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
6097
- if (bytes.length < HEADER_LEN) {
6098
- throw new DecodeError(`header too short for version: have ${bytes.length} bytes, need ${HEADER_LEN}`, "too_short_for_header");
6099
- }
6100
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
6101
- const len = view.getUint32(0, true);
6102
- const typeByte = bytes[5];
6103
- if (typeByte > FRAME_TYPE_MAX)
6104
- throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
6105
- const ty = typeByte;
6106
- const flags = bytes[6];
6107
- if ((flags & FLAG_RESERVED_MASK) !== 0) {
6108
- throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
6109
- }
6110
- if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
6111
- throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
6112
- }
6113
- const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
6114
- if (admission === 3) {
6115
- throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
6116
- }
6117
- if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
6118
- throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
6119
- }
6120
- const channel = view.getUint16(7, true);
6121
- const epoch = view.getUint32(9, true);
6122
- if (channel === 0 && epoch !== 0) {
6123
- throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
6124
- }
6125
- if (isPureHeader(ty) && len !== 0) {
6126
- throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
6127
- }
6128
- return { len, ver, ty, flags, channel, epoch, corr: view.getBigUint64(13, true) };
6129
- }
6130
- function buildFrame(ty, flags, channel, epoch, corr, body) {
6131
- return buildFrameWithVersion(PROTOCOL_VERSION, ty, flags, channel, epoch, corr, body);
6132
- }
6133
- function buildFrameWithVersion(ver, ty, flags, channel, epoch, corr, body) {
6134
- if (body.length > MAX_FRAME_BODY_LEN) {
6135
- throw new DecodeError(`frame body ${body.length} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
6136
- }
6137
- const header = { len: body.length, ver, ty, flags, channel, epoch, corr };
6138
- validateHeaderFields(header);
6139
- return { header, body };
6140
- }
6141
- function encodeFrame(frame) {
6142
- if (frame.header.len !== frame.body.length) {
6143
- throw new DecodeError(`frame header length ${frame.header.len} does not match body length ${frame.body.length}`, "frame_length_mismatch");
6144
- }
6145
- const header = encodeHeader(frame.header);
6146
- const output = new Uint8Array(header.length + frame.body.length);
6147
- output.set(header, 0);
6148
- output.set(frame.body, header.length);
6149
- return output;
6150
- }
6151
-
6152
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
6153
- class SocketClosedError extends Error {
6154
- }
6155
-
6156
- class SocketTimeoutError extends Error {
6157
- }
6158
-
6159
- class SocketWriteNotQueuedError extends Error {
6160
- cause;
6161
- constructor(message, cause) {
6162
- super(message);
6163
- this.cause = cause;
6164
- }
6165
- }
6166
-
6167
- class SocketWriteQueuedError extends Error {
6168
- cause;
6169
- constructor(message, cause) {
6170
- super(message);
6171
- this.cause = cause;
6172
- }
6173
- }
6174
- function toWriteBuffer(bytes) {
6175
- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
6176
- }
6177
- var WRITE_BORROWED = Symbol("subc.socket.writeBorrowed");
6178
- var WRITE_TRACKED_BORROWED = Symbol("subc.socket.writeTrackedBorrowed");
6179
- function writeBorrowed(socket, bytes, deadlineMs) {
6180
- const borrowed = socket[WRITE_BORROWED];
6181
- return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.write(bytes, deadlineMs);
6182
- }
6183
- function writeTrackedBorrowed(socket, bytes, deadlineMs) {
6184
- const borrowed = socket[WRITE_TRACKED_BORROWED];
6185
- return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.writeTracked(bytes, deadlineMs);
6186
- }
6187
-
6188
- class SubcSocket {
6189
- sock;
6190
- chunks = [];
6191
- buffered = 0;
6192
- waiter = null;
6193
- closedErr = null;
6194
- bufferedBytes() {
6195
- return this.buffered;
6196
- }
6197
- constructor(sock) {
6198
- this.sock = sock;
6199
- sock.on("data", (chunk) => {
6200
- this.chunks.push(chunk);
6201
- this.buffered += chunk.length;
6202
- this.tryServe();
6203
- });
6204
- const fail = (err) => {
6205
- if (!this.closedErr)
6206
- this.closedErr = err;
6207
- this.tryServe();
6208
- };
6209
- sock.on("error", (err) => fail(err instanceof Error ? err : new Error(String(err))));
6210
- sock.on("end", () => fail(new SocketClosedError("subc closed the connection")));
6211
- sock.on("close", () => fail(new SocketClosedError("subc connection closed")));
6212
- }
6213
- localPort() {
6214
- return this.sock.localPort ?? null;
6215
- }
6216
- static connect(host, port, deadlineMs) {
6217
- return new Promise((resolve, reject) => {
6218
- const sock = net.connect({ host, port });
6219
- sock.setNoDelay(true);
6220
- const timer = setTimeout(() => {
6221
- sock.destroy();
6222
- reject(new SocketTimeoutError(`timed out connecting to ${host}:${port}`));
6223
- }, Math.max(0, deadlineMs - Date.now()));
6224
- sock.once("connect", () => {
6225
- clearTimeout(timer);
6226
- resolve(new SubcSocket(sock));
6227
- });
6228
- sock.once("error", (err) => {
6229
- clearTimeout(timer);
6230
- reject(err);
6231
- });
6232
- });
6233
- }
6234
- async readFrame(headerDeadlineMs, bodyDeadline, onHeader) {
6235
- const prefix = await this.readExact(FROZEN_PREFIX_LEN, headerDeadlineMs);
6236
- const version = prefix[4];
6237
- if (version !== PROTOCOL_VERSION)
6238
- throw new DecodeError(`unsupported envelope version ${version}`, "unsupported_version");
6239
- const remainder = await this.readExact(HEADER_LEN - FROZEN_PREFIX_LEN, headerDeadlineMs);
6240
- const headerBytes = new Uint8Array(HEADER_LEN);
6241
- headerBytes.set(prefix);
6242
- headerBytes.set(remainder, FROZEN_PREFIX_LEN);
6243
- const header = decodeHeader(headerBytes);
6244
- if (header.len > MAX_FRAME_BODY_LEN) {
6245
- throw new DecodeError(`frame body ${header.len} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
6246
- }
6247
- onHeader?.();
6248
- const bodyDeadlineMs = typeof bodyDeadline === "number" ? bodyDeadline : Date.now() + bodyDeadline.afterHeaderMs;
6249
- const body = header.len === 0 ? new Uint8Array(0) : await this.readExact(header.len, bodyDeadlineMs);
6250
- return { header, body };
6251
- }
6252
- readExact(n, deadlineMs) {
6253
- if (this.waiter) {
6254
- return Promise.reject(new Error("concurrent readExact is not supported"));
6255
- }
6256
- if (n === 0)
6257
- return Promise.resolve(new Uint8Array(0));
6258
- return new Promise((resolve, reject) => {
6259
- let timer = null;
6260
- if (Number.isFinite(deadlineMs)) {
6261
- const remaining = deadlineMs - Date.now();
6262
- if (remaining <= 0) {
6263
- reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
6264
- return;
6265
- }
6266
- timer = setTimeout(() => {
6267
- this.waiter = null;
6268
- reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
6269
- }, remaining);
6270
- }
6271
- this.waiter = { need: n, resolve, reject, timer };
6272
- this.tryServe();
6273
- });
6274
- }
6275
- async write(bytes, deadlineMs) {
6276
- await this.writeBuffer(Buffer.from(bytes), deadlineMs);
6277
- }
6278
- writeTracked(bytes, deadlineMs) {
6279
- return this.writeTrackedBuffer(Buffer.from(bytes), deadlineMs);
6280
- }
6281
- async[WRITE_BORROWED](bytes, deadlineMs) {
6282
- await this.writeBuffer(toWriteBuffer(bytes), deadlineMs);
6283
- }
6284
- [WRITE_TRACKED_BORROWED](bytes, deadlineMs) {
6285
- return this.writeTrackedBuffer(toWriteBuffer(bytes), deadlineMs);
6286
- }
6287
- async writeBuffer(buffer, deadlineMs) {
6288
- try {
6289
- await this.writeTrackedBuffer(buffer, deadlineMs).completed;
6290
- } catch (err) {
6291
- if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError) {
6292
- throw err.cause ?? err;
6293
- }
6294
- throw err;
6295
- }
6296
- }
6297
- writeTrackedBuffer(buffer, deadlineMs) {
6298
- if (this.closedErr) {
6299
- return {
6300
- queued: false,
6301
- completed: Promise.reject(new SocketWriteNotQueuedError("subc socket was closed before bytes could be queued", this.closedErr))
6302
- };
6303
- }
6304
- let queued = false;
6305
- let settled = false;
6306
- let timer = null;
6307
- const completed = new Promise((resolve, reject) => {
6308
- const settle = (run) => {
6309
- if (settled)
6310
- return;
6311
- settled = true;
6312
- if (timer)
6313
- clearTimeout(timer);
6314
- run();
6315
- };
6316
- const remaining = deadlineMs - Date.now();
6317
- if (remaining <= 0) {
6318
- settle(() => reject(new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", new SocketTimeoutError("timed out writing to subc"))));
6319
- return;
6320
- }
6321
- timer = setTimeout(() => {
6322
- const timeout = new SocketTimeoutError("timed out writing to subc");
6323
- 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)));
6324
- }, remaining);
6325
- try {
6326
- this.sock.write(buffer, (err) => {
6327
- settle(() => {
6328
- if (err) {
6329
- reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
6330
- } else {
6331
- resolve();
6332
- }
6333
- });
6334
- });
6335
- queued = true;
6336
- } catch (err) {
6337
- settle(() => reject(new SocketWriteNotQueuedError("subc socket write threw before bytes could be queued", err instanceof Error ? err : new Error(String(err)))));
6338
- }
6339
- });
6340
- return { queued, completed };
6341
- }
6342
- close() {
6343
- this.sock.destroy();
6344
- }
6345
- tryServe() {
6346
- const w = this.waiter;
6347
- if (!w)
6348
- return;
6349
- if (this.buffered >= w.need) {
6350
- const out = this.take(w.need);
6351
- this.waiter = null;
6352
- if (w.timer)
6353
- clearTimeout(w.timer);
6354
- w.resolve(out);
6355
- return;
6356
- }
6357
- if (this.closedErr) {
6358
- this.waiter = null;
6359
- if (w.timer)
6360
- clearTimeout(w.timer);
6361
- w.reject(this.closedErr);
6362
- }
6363
- }
6364
- take(n) {
6365
- const out = Buffer.allocUnsafe(n);
6366
- let off = 0;
6367
- while (off < n) {
6368
- const head = this.chunks[0];
6369
- const want = n - off;
6370
- if (head.length <= want) {
6371
- head.copy(out, off);
6372
- off += head.length;
6373
- this.chunks.shift();
6374
- } else {
6375
- head.copy(out, off, 0, want);
6376
- this.chunks[0] = head.subarray(want);
6377
- off += want;
6378
- }
6379
- }
6380
- this.buffered -= n;
6381
- return out;
6382
- }
6383
- }
6384
-
6385
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
6386
- var NONCE_LEN = 32;
6387
- var MAX_AUTH_MESSAGE_LEN = 4096;
6388
- var SERVER_PROOF_DOMAIN = "subc-server-v1";
6389
- var CLIENT_AUTH_DOMAIN = "subc-client-v1";
6390
- var DEFAULT_CLIENT_ROLE = "client";
6391
-
6392
- class AuthError extends Error {
6393
- }
6394
- function computeProof(key, domain, clientNonce, serverNonce, daemonId) {
6395
- const mac = createHmac("sha256", Buffer.from(key));
6396
- mac.update(Buffer.from(domain, "utf8"));
6397
- mac.update(Buffer.from(clientNonce));
6398
- mac.update(Buffer.from(serverNonce));
6399
- mac.update(Buffer.from(daemonId));
6400
- return new Uint8Array(mac.digest());
6401
- }
6402
- function constantTimeEq(a, b) {
6403
- if (a.length !== b.length)
6404
- return false;
6405
- return timingSafeEqual(Buffer.from(a), Buffer.from(b));
6406
- }
6407
- async function writeMessage(sock, value, deadlineMs) {
6408
- const json = Buffer.from(JSON.stringify(value), "utf8");
6409
- if (json.length > MAX_AUTH_MESSAGE_LEN) {
6410
- throw new AuthError(`auth message too large: ${json.length} > ${MAX_AUTH_MESSAGE_LEN}`);
6411
- }
6412
- const lenPrefix = new Uint8Array(4);
6413
- new DataView(lenPrefix.buffer).setUint32(0, json.length, true);
6414
- await writeBorrowed(sock, lenPrefix, deadlineMs);
6415
- await writeBorrowed(sock, json, deadlineMs);
6416
- }
6417
- async function readMessage(sock, deadlineMs) {
6418
- const lenBytes = await sock.readExact(4, deadlineMs);
6419
- const len = new DataView(lenBytes.buffer, lenBytes.byteOffset, 4).getUint32(0, true);
6420
- if (len > MAX_AUTH_MESSAGE_LEN) {
6421
- throw new AuthError(`auth message too large: ${len} > ${MAX_AUTH_MESSAGE_LEN}`);
6422
- }
6423
- const body = len === 0 ? new Uint8Array(0) : await sock.readExact(len, deadlineMs);
6424
- try {
6425
- return JSON.parse(Buffer.from(body).toString("utf8"));
6426
- } catch (err) {
6427
- throw new AuthError(`auth message JSON decode failed: ${String(err)}`);
6428
- }
6429
- }
6430
- function authBytes(value, field) {
6431
- if (!Array.isArray(value)) {
6432
- throw new AuthError(`auth field '${field}' must be a byte array`);
6433
- }
6434
- for (const byte of value) {
6435
- if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
6436
- throw new AuthError(`auth field '${field}' has invalid byte ${String(byte)}`);
6437
- }
6438
- }
6439
- return Uint8Array.from(value);
6440
- }
6441
- async function authenticateClient(sock, conn, deadlineMs) {
6442
- const clientNonce = new Uint8Array(randomBytes(NONCE_LEN));
6443
- await writeMessage(sock, { client_nonce: Array.from(clientNonce), role: DEFAULT_CLIENT_ROLE }, deadlineMs);
6444
- const proof = await readMessage(sock, deadlineMs);
6445
- const serverNonce = authBytes(proof.server_nonce, "server_nonce");
6446
- const daemonId = authBytes(proof.daemon_id, "daemon_id");
6447
- const serverProof = authBytes(proof.server_proof, "server_proof");
6448
- const expected = computeProof(conn.key, SERVER_PROOF_DOMAIN, clientNonce, serverNonce, daemonId);
6449
- if (!constantTimeEq(expected, serverProof)) {
6450
- throw new AuthError("server proof mismatch — wrong key or impostor daemon");
6451
- }
6452
- if (!constantTimeEq(daemonId, conn.daemonId)) {
6453
- throw new AuthError("daemon id mismatch — connection file points at a different daemon");
6454
- }
6455
- const clientAuth = computeProof(conn.key, CLIENT_AUTH_DOMAIN, clientNonce, serverNonce, daemonId);
6456
- await writeMessage(sock, { client_auth: Array.from(clientAuth) }, deadlineMs);
6457
- }
6458
-
6459
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/connection-file.js
6460
- import { promises as fs } from "node:fs";
6461
- var SCHEMA_VERSION = 1;
6462
- var MIN_KEY_LEN = 32;
6463
- var DAEMON_ID_LEN = 16;
6464
-
6465
- class ConnectionFileError extends Error {
6466
- }
6467
- function toBytes(value, field) {
6468
- if (!Array.isArray(value)) {
6469
- throw new ConnectionFileError(`connection file field '${field}' must be a JSON array of bytes`);
6470
- }
6471
- for (const byte of value) {
6472
- if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
6473
- throw new ConnectionFileError(`connection file field '${field}' has invalid byte ${String(byte)}`);
6474
- }
6475
- }
6476
- return Uint8Array.from(value);
6477
- }
6478
- function validate(info) {
6479
- if (info.schema !== SCHEMA_VERSION) {
6480
- throw new ConnectionFileError(`unsupported connection file schema ${info.schema}; expected ${SCHEMA_VERSION}`);
6481
- }
6482
- if (info.endpoints.length === 0) {
6483
- throw new ConnectionFileError("connection file must include at least one endpoint");
6484
- }
6485
- if (info.key.length < MIN_KEY_LEN) {
6486
- throw new ConnectionFileError(`connection file key is too short: ${info.key.length} bytes, need at least ${MIN_KEY_LEN}`);
6487
- }
6488
- if (info.daemonId.length !== DAEMON_ID_LEN) {
6489
- throw new ConnectionFileError(`connection file daemon_id must be ${DAEMON_ID_LEN} bytes, got ${info.daemonId.length}`);
6490
- }
6491
- }
6492
- async function verifyOwnerOnly(path) {
6493
- if (process.platform === "win32")
6494
- return;
6495
- const stat = await fs.stat(path);
6496
- const mode = stat.mode & 511;
6497
- if ((mode & 63) !== 0) {
6498
- throw new ConnectionFileError(`connection file ${path} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
6499
- }
6500
- }
6501
- async function readConnectionFile(path) {
6502
- await verifyOwnerOnly(path);
6503
- const raw = await fs.readFile(path, "utf8");
6504
- let parsed;
6505
- try {
6506
- parsed = JSON.parse(raw);
6507
- } catch (err) {
6508
- throw new ConnectionFileError(`connection file JSON read failed for ${path}: ${String(err)}`);
6509
- }
6510
- const wireVersion = parsed.wire_version;
6511
- if (wireVersion !== undefined && wireVersion !== PROTOCOL_VERSION) {
6512
- throw new ConnectionFileError(`connection file wire_version ${String(wireVersion)} but this client speaks ${PROTOCOL_VERSION}; the client library must be upgraded`);
6513
- }
6514
- const endpointsRaw = parsed.endpoints;
6515
- if (!Array.isArray(endpointsRaw)) {
6516
- throw new ConnectionFileError("connection file 'endpoints' must be an array");
6517
- }
6518
- const endpoints = endpointsRaw.map((e) => {
6519
- const ep = e;
6520
- if (typeof ep.host !== "string" || typeof ep.port !== "number") {
6521
- throw new ConnectionFileError("connection file endpoint must be { host: string, port: number }");
6522
- }
6523
- return { host: ep.host, port: ep.port };
6524
- });
6525
- const info = {
6526
- schema: parsed.schema,
6527
- endpoints,
6528
- key: toBytes(parsed.key, "key"),
6529
- daemonId: toBytes(parsed.daemon_id, "daemon_id"),
6530
- pid: parsed.pid,
6531
- daemonVer: parsed.daemon_ver ?? ""
6532
- };
6533
- validate(info);
6534
- return info;
6535
- }
6536
-
6537
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/route-handle.js
6538
- var connectionToken = new WeakMap;
6539
-
6540
- class RouteHandle {
6541
- channel;
6542
- epoch;
6543
- constructor(channel, epoch, token) {
6544
- if (!Number.isInteger(channel) || channel <= 0 || channel > 65535) {
6545
- throw new RangeError(`route channel must be an integer in 1..65535, got ${channel}`);
6546
- }
6547
- if (!Number.isInteger(epoch) || epoch <= 0 || epoch > 4294967295) {
6548
- throw new RangeError(`route epoch must be an integer in 1..4294967295, got ${epoch}`);
6549
- }
6550
- this.channel = channel;
6551
- this.epoch = epoch;
6552
- connectionToken.set(this, token);
6553
- Object.freeze(this);
6554
- }
6555
- static create(channel, epoch, token) {
6556
- return new RouteHandle(channel, epoch, token);
6557
- }
6558
- }
6559
- function createRouteHandle(channel, epoch, token) {
6560
- const factory = RouteHandle;
6561
- return factory.create(channel, epoch, token);
6562
- }
6563
-
6564
- class StaleRouteHandleError extends Error {
6565
- handle;
6566
- code = "stale_route_handle";
6567
- constructor(handle) {
6568
- super(`route handle (${handle.channel}, ${handle.epoch}) is not live on the current connection`);
6569
- this.handle = handle;
6570
- this.name = "StaleRouteHandleError";
6571
- }
6572
- }
6573
- function newConnectionToken() {
6574
- return Object.freeze({});
6575
- }
6576
- function belongsToConnection(handle, token) {
6577
- return connectionToken.get(handle) === token;
6578
- }
6579
- function sameRouteHandle(left, right) {
6580
- return left === right;
6581
- }
6582
-
6583
- // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
6584
- var debug = debuglog("subc-client");
6585
- var DEFAULT_HANDSHAKE_TIMEOUT_MS = 1e4;
6586
- var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
6587
- var TIMEOUT_ARBITRATION_GRACE_MS = 50;
6588
- var LIVENESS_PROBE_WINDOW_MS = 2000;
6589
- var REQUEST_DEADLINE_MARKER = "request_deadline";
6590
- var DEADLINE_NO_DROP_CODE = "deadline_exceeded_no_drop_observed";
6591
- var ROUTE_OPEN_RETRY_DEADLINE_MS = 30000;
6592
- var BODY_READ_TIMEOUT_MS = 30000;
6593
- var EMPTY_BODY = new Uint8Array(0);
6594
- var DEFAULT_MANAGED_TARGET_KIND = "management_surface";
6595
- var SUBC_MODULE_ID_ENV = "SUBC_MODULE_ID";
6596
- var SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
6597
- var DEFAULT_RECONNECT_BACKOFF = {
6598
- baseMs: 100,
6599
- capMs: 2000,
6600
- maxAttempts: 6
6601
- };
6602
-
6603
- class SubcCallError extends Error {
6604
- kind;
6605
- code;
6606
- cause;
6607
- constructor(kind, message, code, cause) {
6608
- super(message);
6609
- this.kind = kind;
6610
- this.code = code;
6611
- this.cause = cause;
6612
- this.name = "SubcCallError";
6613
- }
6614
- get detail() {
6615
- return this.cause instanceof SubcError ? this.cause.detail : undefined;
6616
- }
6617
- }
6618
-
6619
- class SubcError extends Error {
6620
- code;
6621
- detail;
6622
- constructor(message, code, detail) {
6623
- super(message);
6624
- this.code = code;
6625
- this.detail = detail;
6626
- }
6627
- }
6628
- function requireBinaryBody(body) {
6629
- if (body instanceof Uint8Array)
6630
- return body;
6631
- const type = body === null ? "null" : Array.isArray(body) ? "array" : typeof body;
6632
- throw new SubcError(`binary request body must be a Uint8Array; got ${type}`, "binary_body_required");
6633
- }
6634
- class SubcClient {
6635
- sock;
6636
- currentConn;
6637
- opts;
6638
- nextCorr = 1n;
6639
- pending = new Map;
6640
- lateResponses = new Map;
6641
- routes = new Map;
6642
- liveRoutes = new Map;
6643
- connectionToken = newConnectionToken();
6644
- ingressEpochDropCount = 0;
6645
- closedErr = null;
6646
- closeStarted = false;
6647
- reconnecting = null;
6648
- generation = 1;
6649
- readerActive = false;
6650
- constructor(sock, currentConn, opts) {
6651
- this.sock = sock;
6652
- this.currentConn = currentConn;
6653
- this.opts = opts;
6654
- this.readLoop(sock, this.generation);
6655
- }
6656
- get conn() {
6657
- return this.currentConn;
6658
- }
6659
- static async connect(opts) {
6660
- const normalized = normalizeConnectOptions(opts);
6661
- const opened = await SubcClient.openConnection(normalized);
6662
- return new SubcClient(opened.sock, opened.conn, normalized);
6663
- }
6664
- async catalogList(moduleId) {
6665
- const body = this.encode(moduleId === undefined ? { op: "catalog.list" } : { op: "catalog.list", module_id: moduleId });
6666
- const reply = await this.controlRpc(body);
6667
- const parsed = this.parseJson(reply);
6668
- return parsed.modules ?? [];
6669
- }
6670
- async resolveProvider(capability) {
6671
- const claimants = await this.resolveProviders(capability);
6672
- if (claimants.length === 0) {
6673
- throw new SubcError(`no catalog claimant for capability ${capability}`, "capability_unprovided");
6674
- }
6675
- if (claimants.length > 1) {
6676
- throw new SubcError(`multiple catalog claimants for capability ${capability}: ${claimants.join(", ")}`, "capability_ambiguous");
6677
- }
6678
- return claimants[0];
6679
- }
6680
- async resolveProviders(capability) {
6681
- if (!isValidCapabilityIdentifier(capability)) {
6682
- throw new SubcError(`malformed capability identifier ${JSON.stringify(capability)}`, "invalid_capability_identifier");
6683
- }
6684
- const modules = await this.catalogList();
6685
- return modules.filter((module) => module.capabilities?.provides.includes(capability) ?? false).map((module) => module.module_id).sort();
6686
- }
6687
- async routeOpen(target, identity, opts = {}) {
6688
- const consumerIdentity = routeOpenConsumerIdentity(opts);
6689
- const consumerCapabilities = opts.consumerCapabilities;
6690
- const body = this.encode({
6691
- op: "route.open",
6692
- target,
6693
- identity,
6694
- ...consumerIdentity ? { consumer_identity: consumerIdentity } : {},
6695
- ...consumerCapabilities !== undefined ? { consumer_capabilities: consumerCapabilities } : {}
6696
- });
6697
- let installed = null;
6698
- const install = (frame) => {
6699
- if (frame.header.ty !== FrameType.Response)
6700
- return true;
6701
- const parsed = this.parseJson(frame);
6702
- if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number") {
6703
- throw new SubcError(`route.open returned no route handle: ${JSON.stringify(parsed)}`);
6704
- }
6705
- installed = this.installRoute(parsed.route_channel, parsed.route_epoch);
6706
- return true;
6707
- };
6708
- const closeLateRoute = (frame) => {
6709
- if (frame.header.ty !== FrameType.Response)
6710
- return;
6711
- try {
6712
- const parsed = this.parseJson(frame);
6713
- if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number")
6714
- return;
6715
- const lateHandle = this.installRoute(parsed.route_channel, parsed.route_epoch);
6716
- this.failHandle(lateHandle, new SubcError("late route.open was closed", "route_closed"));
6717
- this.liveRoutes.delete(lateHandle.channel);
6718
- this.sendRouteGoodbye(lateHandle, true);
6719
- } catch {
6720
- this.closeConnectionAfterCleanupFailure();
6721
- }
6722
- };
6723
- await this.controlRpc(body, install, closeLateRoute);
6724
- if (!installed)
6725
- throw new SubcError("route.open response was not installed");
6726
- return installed;
6727
- }
6728
- async request(handle, body, opts = {}) {
6729
- this.assertLiveHandle(handle);
6730
- const binary = opts.binary ?? false;
6731
- const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
6732
- const priority = opts.priority ?? Priority.Interactive;
6733
- const admission = opts.admissionClass ?? AdmissionClass.Normal;
6734
- const reply = await this.send(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, undefined, undefined, binary);
6735
- return this.decodeReply(reply);
6736
- }
6737
- async call(moduleId, method, params, opts = {}) {
6738
- if (opts.binary) {
6739
- 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");
6740
- }
6741
- const body = params === undefined ? { method } : { method, params };
6742
- return await this.managedCall(moduleId, body, opts);
6743
- }
6744
- async callBinary(moduleId, body, opts = {}) {
6745
- const bytes = requireBinaryBody(body);
6746
- return this.managedCall(moduleId, bytes, { ...opts, binary: true });
6747
- }
6748
- async managedCall(moduleId, body, opts) {
6749
- let retriedUnknownChannel = false;
6750
- for (;; ) {
6751
- const routeHandle = await this.cachedRouteHandle(moduleId, opts);
6752
- try {
6753
- return await this.managedRequest(routeHandle, body, opts);
6754
- } catch (err) {
6755
- if (!(err instanceof SubcCallError))
6756
- throw this.terminalCallError("managed call failed", err);
6757
- const deadBindCode = err.code === "unknown_channel" || err.code === "stale_route_epoch";
6758
- if (deadBindCode && !retriedUnknownChannel && !this.closeStarted) {
6759
- retriedUnknownChannel = true;
6760
- this.evictRouteHandle(routeHandle);
6761
- continue;
6762
- }
6763
- if (deadBindCode && retriedUnknownChannel) {
6764
- this.evictRouteHandle(routeHandle);
6765
- }
6766
- if (err.kind === "not_sent") {
6767
- try {
6768
- await this.reconnectAfterDrop(err);
6769
- } catch (reconnectErr) {
6770
- throw this.notSentRecoveryError("managed call was not sent", reconnectErr);
6771
- }
6772
- continue;
6773
- }
6774
- if (err.kind === "outcome_unknown" && err.code !== DEADLINE_NO_DROP_CODE) {
6775
- this.scheduleReconnectAfterDrop(err);
6776
- } else if (err.kind === "outcome_unknown" && err.code === DEADLINE_NO_DROP_CODE) {
6777
- this.probeLivenessAfterDeadline();
6778
- }
6779
- throw err;
6780
- }
6781
- }
6782
- }
6783
- subscribe(handle, body, onEvent, opts = {}) {
6784
- this.assertLiveHandle(handle);
6785
- const bytes = body instanceof Uint8Array ? body : this.encode(body);
6786
- const priority = opts.priority ?? Priority.Interactive;
6787
- const admission = opts.admissionClass ?? AdmissionClass.Normal;
6788
- const corr = this.allocateCorr();
6789
- const key = pendingKey(handle, corr);
6790
- let subscriptionPending = null;
6791
- let resolveClosed = null;
6792
- const closed = new Promise((resolve, reject) => {
6793
- if (this.closedErr) {
6794
- reject(this.closedErr);
6795
- return;
6796
- }
6797
- resolveClosed = resolve;
6798
- subscriptionPending = {
6799
- handle,
6800
- resolve: () => resolve(),
6801
- reject,
6802
- onProgress: onEvent,
6803
- timer: null,
6804
- subscription: true
6805
- };
6806
- this.pending.set(key, subscriptionPending);
6807
- const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), handle.channel, handle.epoch, corr, bytes);
6808
- writeBorrowed(this.sock, encodeFrame(frame), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch((err) => {
6809
- const pending = this.pending.get(key);
6810
- if (pending)
6811
- this.rejectPending(key, pending, err instanceof Error ? err : new SubcError(String(err)));
6812
- });
6813
- });
6814
- let cancelled = false;
6815
- const unsubscribe = () => {
6816
- if (cancelled)
6817
- return;
6818
- cancelled = true;
6819
- if (subscriptionPending && resolveClosed)
6820
- this.settle(key, subscriptionPending, resolveClosed);
6821
- if (this.isLiveHandle(handle))
6822
- this.cancel(handle, corr, priority);
6823
- };
6824
- return { unsubscribe, closed };
6825
- }
6826
- cancel(handle, corr, priority = Priority.Interactive) {
6827
- this.assertLiveHandle(handle);
6828
- const cancel = buildFrame(FrameType.Cancel, buildFlags(false, priority, false), handle.channel, handle.epoch, corr, EMPTY_BODY);
6829
- writeBorrowed(this.sock, encodeFrame(cancel), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch(() => {
6830
- return;
6831
- });
6832
- }
6833
- async routePoll(handle, kind) {
6834
- this.assertLiveHandle(handle);
6835
- const body = this.encode({
6836
- op: "route.poll",
6837
- route_channel: handle.channel,
6838
- route_epoch: handle.epoch,
6839
- kind
6840
- });
6841
- const reply = await this.controlRpc(body, (frame) => {
6842
- if (frame.header.ty !== FrameType.Response)
6843
- return true;
6844
- const parsed = this.parseJson(frame);
6845
- return parsed.route_channel === handle.channel && parsed.route_epoch === handle.epoch;
6846
- });
6847
- return this.parseJson(reply);
6848
- }
6849
- async closeRoute(handle, opts = {}) {
6850
- this.assertLiveHandle(handle);
6851
- for (const [key, cached] of this.routes) {
6852
- if (cached.handle && sameRouteHandle(cached.handle, handle)) {
6853
- cached.closed = true;
6854
- cached.handle = null;
6855
- this.routes.delete(key);
6856
- }
6857
- }
6858
- if (opts.drain)
6859
- await this.drainUnaryOnHandle(handle);
6860
- this.failHandle(handle, new SubcError("route closed by closeRoute", "route_closed"));
6861
- if (this.liveRoutes.get(handle.channel) === handle)
6862
- this.liveRoutes.delete(handle.channel);
6863
- this.sendRouteGoodbye(handle);
6864
- }
6865
- async closeManagedRoute(target, identity, opts = {}) {
6866
- const key = routeCacheKey(target, identity, routeOpenConsumerIdentity(opts));
6867
- const cached = this.routes.get(key);
6868
- if (!cached)
6869
- return;
6870
- cached.closed = true;
6871
- this.routes.delete(key);
6872
- const handle = cached.handle;
6873
- cached.handle = null;
6874
- if (handle)
6875
- await this.closeRoute(handle, opts);
6876
- }
6877
- async closeRouteChannel(handle, opts = {}) {
6878
- await this.closeRoute(handle, opts);
6879
- }
6880
- close() {
6881
- this.closeStarted = true;
6882
- this.fail(new SubcError("client closed"));
6883
- this.sock.close();
6884
- }
6885
- drainUnaryOnHandle(handle) {
6886
- const waiters = [];
6887
- for (const pending of this.pending.values()) {
6888
- if (pending.handle === handle && !pending.subscription) {
6889
- waiters.push(new Promise((resolve) => {
6890
- const previous = pending.onSettle;
6891
- pending.onSettle = () => {
6892
- previous?.();
6893
- resolve();
6894
- };
6895
- }));
6896
- }
6897
- }
6898
- return Promise.all(waiters).then(() => {
6899
- return;
6900
- });
6901
- }
6902
- sendRouteGoodbye(handle, closeOnQueueFailure = false) {
6903
- this.assertLiveConnection(handle);
6904
- if (this.closedErr) {
6905
- if (closeOnQueueFailure)
6906
- this.closeConnectionAfterCleanupFailure();
6907
- return;
6908
- }
6909
- const goodbye = buildFrame(FrameType.Goodbye, buildFlags(false, Priority.Interactive, false), handle.channel, handle.epoch, 0n, EMPTY_BODY);
6910
- const write = writeTrackedBorrowed(this.sock, encodeFrame(goodbye), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS);
6911
- if (!write.queued && closeOnQueueFailure)
6912
- this.closeConnectionAfterCleanupFailure();
6913
- write.completed.catch(() => {
6914
- if (closeOnQueueFailure && !write.queued)
6915
- this.closeConnectionAfterCleanupFailure();
6916
- });
6917
- }
6918
- static async openConnection(opts) {
6919
- const conn = await readConnectionFile(opts.connectionFile);
6920
- const deadline = Date.now() + (opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);
6921
- const endpoint = conn.endpoints[0];
6922
- const sock = await SubcSocket.connect(endpoint.host, endpoint.port, deadline);
6923
- try {
6924
- await authenticateClient(sock, conn, deadline);
6925
- } catch (err) {
6926
- sock.close();
6927
- throw err;
6928
- }
6929
- return { sock, conn };
6930
- }
6931
- async controlRpc(body, acceptFrame, onLateResponse) {
6932
- return this.send(null, body, Priority.Interactive, AdmissionClass.Normal, undefined, undefined, acceptFrame, onLateResponse);
6933
- }
6934
- send(handle, body, priority, admission, timeoutMs, onProgress, acceptFrame, onLateResponse, binary = false) {
6935
- if (handle)
6936
- this.assertLiveHandle(handle);
6937
- if (this.closedErr)
6938
- return Promise.reject(this.closedErr);
6939
- let corr;
6940
- try {
6941
- corr = this.allocateCorr();
6942
- } catch (error) {
6943
- return Promise.reject(error);
6944
- }
6945
- const key = pendingKey(handle, corr);
6946
- const channel = handle?.channel ?? 0;
6947
- const epoch = handle?.epoch ?? 0;
6948
- const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), channel, epoch, corr, body);
6949
- return new Promise((resolve, reject) => {
6950
- const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
6951
- const pending = {
6952
- handle,
6953
- resolve,
6954
- reject,
6955
- onProgress,
6956
- timer: null,
6957
- acceptFrame,
6958
- onLateResponse
6959
- };
6960
- pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, channel, corr, ms), ms);
6961
- this.pending.set(key, pending);
6962
- writeBorrowed(this.sock, encodeFrame(frame), Date.now() + ms).catch((error) => {
6963
- const current = this.pending.get(key);
6964
- if (current)
6965
- this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
6966
- });
6967
- });
6968
- }
6969
- arbitrateTimeout(key, pending, channel, corr, ms) {
6970
- const settleAsTimeout = () => {
6971
- if (pending.onLateResponse)
6972
- this.lateResponses.set(key, pending.onLateResponse);
6973
- this.rejectPending(key, pending, new SubcError(this.timeoutMessage(channel, corr, ms), REQUEST_DEADLINE_MARKER));
6974
- };
6975
- const graceDeadline = Date.now() + this.opts.timeoutArbitrationGraceMs;
6976
- const arbitrate = () => {
6977
- if (this.pending.get(key) !== pending)
6978
- return;
6979
- const readerDraining = this.readerActive || this.sock.bufferedBytes() > 0;
6980
- if (readerDraining && Date.now() < graceDeadline) {
6981
- setImmediate(arbitrate);
6982
- return;
6983
- }
6984
- settleAsTimeout();
6985
- };
6986
- setImmediate(arbitrate);
6987
- }
6988
- async managedRequest(handle, body, opts) {
6989
- const binary = opts.binary ?? false;
6990
- const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
6991
- const priority = opts.priority ?? Priority.Interactive;
6992
- const admission = opts.admissionClass ?? AdmissionClass.Normal;
6993
- try {
6994
- const reply = await this.sendManaged(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, binary);
6995
- return this.decodeReply(reply);
6996
- } catch (error) {
6997
- if (error instanceof SubcCallError)
6998
- throw error;
6999
- throw this.terminalCallError("managed call failed", error);
7000
- }
7001
- }
7002
- sendManaged(handle, body, priority, admission, timeoutMs, onProgress, binary = false) {
7003
- try {
7004
- this.assertLiveHandle(handle);
7005
- } catch (error) {
7006
- return Promise.reject(this.notSentCallError("request used a stale route handle", error));
7007
- }
7008
- if (this.closedErr) {
7009
- return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed", this.closedErr));
7010
- }
7011
- let corr;
7012
- try {
7013
- corr = this.allocateCorr();
7014
- } catch (error) {
7015
- return Promise.reject(this.notSentCallError("request correlation allocator was exhausted", error));
7016
- }
7017
- const key = pendingKey(handle, corr);
7018
- const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), handle.channel, handle.epoch, corr, body);
7019
- let handedToSocket = false;
7020
- const classifyFailure = (error) => {
7021
- if (!handedToSocket)
7022
- return this.notSentCallError("request bytes were not queued to the subc socket", error);
7023
- if (error instanceof SubcError && error.code === REQUEST_DEADLINE_MARKER) {
7024
- 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);
7025
- }
7026
- return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error);
7027
- };
7028
- return new Promise((resolve, reject) => {
7029
- const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
7030
- const pending = {
7031
- handle,
7032
- resolve,
7033
- reject,
7034
- onProgress,
7035
- timer: null,
7036
- classifyFailure
7037
- };
7038
- pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, handle.channel, corr, ms), ms);
7039
- this.pending.set(key, pending);
7040
- const write = writeTrackedBorrowed(this.sock, encodeFrame(frame), Date.now() + ms);
7041
- handedToSocket = write.queued;
7042
- write.completed.catch((error) => {
7043
- const current = this.pending.get(key);
7044
- if (current)
7045
- this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
7046
- });
7047
- });
7048
- }
7049
- async cachedRouteHandle(moduleId, opts) {
7050
- const identity = opts.identity ?? this.opts.identity;
7051
- if (!identity) {
7052
- throw new SubcCallError("terminal", "managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })", "missing_identity");
7053
- }
7054
- const target = { kind: opts.targetKind ?? this.opts.targetKind, module_id: moduleId };
7055
- const consumerIdentity = routeOpenConsumerIdentity(opts);
7056
- const key = routeCacheKey(target, identity, consumerIdentity);
7057
- let cached = this.routes.get(key);
7058
- if (!cached) {
7059
- cached = {
7060
- key,
7061
- moduleId,
7062
- target,
7063
- identity,
7064
- consumerIdentity,
7065
- handle: null,
7066
- opening: null
7067
- };
7068
- this.routes.set(key, cached);
7069
- }
7070
- if (cached.handle && this.isLiveHandle(cached.handle))
7071
- return cached.handle;
7072
- if (!cached.opening) {
7073
- cached.opening = this.openCachedRoute(cached).finally(() => {
7074
- cached.opening = null;
7075
- });
7076
- }
7077
- return cached.opening;
7078
- }
7079
- async openCachedRoute(cached) {
7080
- const routeRetryDeadline = Date.now() + this.opts.routeOpenRetryDeadlineMs;
7081
- let routeRetryDelay = this.opts.reconnectBackoff.baseMs;
7082
- let routeRetryAttempt = 0;
7083
- for (;; ) {
7084
- if (cached.closed)
7085
- throw this.routeClosedDuringOpen();
7086
- try {
7087
- await this.ensureConnectedForManaged();
7088
- } catch (error) {
7089
- throw this.notSentRecoveryError("route.open could not run because reconnect failed", error);
7090
- }
7091
- if (cached.handle && this.isLiveHandle(cached.handle))
7092
- return cached.handle;
7093
- try {
7094
- const handle = await this.routeOpen(cached.target, cached.identity, {
7095
- consumerIdentity: cached.consumerIdentity ?? null
7096
- });
7097
- if (cached.closed) {
7098
- this.liveRoutes.delete(handle.channel);
7099
- this.sendRouteGoodbye(handle);
7100
- throw this.routeClosedDuringOpen();
7101
- }
7102
- cached.handle = handle;
7103
- return handle;
7104
- } catch (error) {
7105
- if (error instanceof SubcCallError && error.code === "route_closed")
7106
- throw error;
7107
- if (!this.closeStarted && isConsumerReconnectTransient(error)) {
7108
- try {
7109
- await this.reconnectAfterDrop(error);
7110
- } catch (reconnectError) {
7111
- throw this.notSentRecoveryError("route.open was not sent and reconnect failed", reconnectError);
7112
- }
7113
- continue;
7114
- }
7115
- if (!this.closeStarted && error instanceof SubcError && isRetryableRouteOpenCode(error.code)) {
7116
- routeRetryAttempt += 1;
7117
- if (Date.now() < routeRetryDeadline) {
7118
- await this.opts.sleep(routeRetryDelay);
7119
- routeRetryDelay = Math.min(routeRetryDelay * 2, this.opts.reconnectBackoff.capMs);
7120
- continue;
7121
- }
7122
- throw this.notSentCallError(`route.open failed for module ${cached.moduleId}: ${error.code} (retry deadline exhausted after ${routeRetryAttempt} attempts)`, error);
7123
- }
7124
- throw this.terminalCallError(`route.open failed for module ${cached.moduleId}`, error);
7125
- }
7126
- }
7127
- }
7128
- lastInboundAtMs = 0;
7129
- livenessProbe = null;
7130
- hasControlPending() {
7131
- for (const pending of this.pending.values()) {
7132
- if (pending.handle === null)
7133
- return true;
7134
- }
7135
- return false;
7136
- }
7137
- probeLivenessAfterDeadline() {
7138
- if (this.livenessProbe || this.closeStarted || this.closedErr)
7139
- return;
7140
- if (this.hasControlPending())
7141
- return;
7142
- const sock = this.sock;
7143
- const generation = this.generation;
7144
- let corr;
7145
- try {
7146
- corr = this.allocateCorr();
7147
- } catch {
7148
- return;
7149
- }
7150
- const t0 = Date.now();
7151
- const ping = buildFrame(FrameType.Ping, buildFlags(false, Priority.Interactive, false, AdmissionClass.Normal), 0, 0, corr, new Uint8Array);
7152
- const probe = (async () => {
7153
- await writeBorrowed(sock, encodeFrame(ping), t0 + this.opts.livenessProbeWindowMs).catch(() => {});
7154
- await this.opts.sleep(this.opts.livenessProbeWindowMs);
7155
- if (this.sock !== sock || this.generation !== generation || this.closeStarted)
7156
- return;
7157
- if (this.lastInboundAtMs >= t0)
7158
- return;
7159
- if (this.hasControlPending())
7160
- return;
7161
- 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`));
7162
- sock.close();
7163
- })().finally(() => {
7164
- this.livenessProbe = null;
7165
- });
7166
- this.livenessProbe = probe;
7167
- }
7168
- async ensureConnectedForManaged() {
7169
- if (this.closeStarted)
7170
- throw new SubcError("client closed");
7171
- if (this.reconnecting)
7172
- await this.reconnecting;
7173
- if (this.closedErr)
7174
- await this.reconnectAfterDrop(this.closedErr);
7175
- }
7176
- scheduleReconnectAfterDrop(err) {
7177
- if (this.closeStarted || this.reconnecting)
7178
- return;
7179
- this.reconnectAfterDrop(err).catch(() => {});
7180
- }
7181
- reconnectAfterDrop(trigger) {
7182
- if (this.closeStarted)
7183
- return Promise.reject(new SubcError("client closed"));
7184
- if (this.reconnecting)
7185
- return this.reconnecting;
7186
- const promise = this.reconnectWithRetry(trigger).finally(() => {
7187
- if (this.reconnecting === promise)
7188
- this.reconnecting = null;
7189
- });
7190
- this.reconnecting = promise;
7191
- return promise;
7192
- }
7193
- async reconnectWithRetry(_trigger) {
7194
- let attempt = 0;
7195
- let delay = this.opts.reconnectBackoff.baseMs;
7196
- for (;; ) {
7197
- if (this.closeStarted)
7198
- throw new SubcError("client closed");
7199
- attempt += 1;
7200
- try {
7201
- const opened = await SubcClient.openConnection(this.opts);
7202
- if (this.closeStarted) {
7203
- opened.sock.close();
7204
- throw new SubcError("client closed");
7205
- }
7206
- this.replaceConnection(opened);
7207
- await this.reopenCachedRoutes();
7208
- return;
7209
- } catch (err) {
7210
- if (!isConsumerReconnectTransient(err) || attempt >= this.opts.reconnectBackoff.maxAttempts) {
7211
- if (err instanceof AuthError && attempt > 1) {
7212
- 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`);
7213
- }
7214
- throw err;
7215
- }
7216
- await this.opts.sleep(delay);
7217
- delay = Math.min(delay * 2, this.opts.reconnectBackoff.capMs);
7218
- }
7219
- }
7220
- }
7221
- replaceConnection(opened) {
7222
- this.sock.close();
7223
- this.sock = opened.sock;
7224
- this.currentConn = opened.conn;
7225
- this.closedErr = null;
7226
- this.generation += 1;
7227
- this.connectionToken = newConnectionToken();
7228
- this.liveRoutes.clear();
7229
- this.lateResponses.clear();
7230
- this.nextCorr = 1n;
7231
- this.readLoop(opened.sock, this.generation);
7232
- }
7233
- async reopenCachedRoutes() {
7234
- const routeKeys = [...this.routes.keys()];
7235
- for (const key of routeKeys) {
7236
- const cached = this.routes.get(key);
7237
- if (cached)
7238
- cached.handle = null;
7239
- }
7240
- for (const key of routeKeys) {
7241
- const cached = this.routes.get(key);
7242
- if (!cached || cached.closed)
7243
- continue;
7244
- try {
7245
- const handle = await this.routeOpen(cached.target, cached.identity, {
7246
- consumerIdentity: cached.consumerIdentity ?? null
7247
- });
7248
- if (cached.closed) {
7249
- this.liveRoutes.delete(handle.channel);
7250
- this.sendRouteGoodbye(handle);
7251
- continue;
7252
- }
7253
- cached.handle = handle;
7254
- } catch (error) {
7255
- if (isRouteOpenRefusal(error)) {
7256
- this.routes.delete(key);
7257
- continue;
7258
- }
7259
- throw error;
7260
- }
7261
- }
7262
- }
7263
- timeoutMessage(channel, corr, ms) {
7264
- const port = this.sock.localPort();
7265
- const where = port === null ? "channel" : `local_port=${port} channel`;
7266
- return `request on ${where} ${channel} corr ${corr} timed out after ${ms}ms`;
7267
- }
7268
- routeClosedDuringOpen() {
7269
- return new SubcCallError("not_sent", "route was closed before route.open completed", "route_closed");
7270
- }
7271
- async readLoop(sock, generation) {
7272
- try {
7273
- for (;; ) {
7274
- this.readerActive = false;
7275
- const frame = await sock.readFrame(Number.POSITIVE_INFINITY, { afterHeaderMs: BODY_READ_TIMEOUT_MS }, () => {
7276
- this.readerActive = true;
7277
- });
7278
- try {
7279
- if (this.sock === sock && this.generation === generation)
7280
- this.dispatch(frame);
7281
- } finally {
7282
- this.readerActive = false;
7283
- }
7284
- }
7285
- } catch (error) {
7286
- if (this.sock === sock && this.generation === generation) {
7287
- this.fail(error instanceof Error ? error : new SubcError(String(error)));
7288
- }
7289
- }
7290
- }
7291
- dispatch(frame) {
7292
- this.lastInboundAtMs = Date.now();
7293
- if (frame.header.channel === 0 && frame.header.ty === FrameType.Push) {
7294
- const observer = this.opts.onControlPush;
7295
- if (observer) {
7296
- let parsed = null;
7297
- try {
7298
- const body = this.parseJson(frame);
7299
- if (body && typeof body.op === "string")
7300
- parsed = { op: body.op, body };
7301
- } catch {}
7302
- if (parsed) {
7303
- try {
7304
- observer(parsed);
7305
- } catch {}
7306
- }
7307
- }
7308
- return;
7309
- }
7310
- let handle = null;
7311
- if (frame.header.channel !== 0) {
7312
- handle = this.liveRoutes.get(frame.header.channel) ?? null;
7313
- if (!handle || handle.epoch !== frame.header.epoch) {
7314
- this.ingressEpochDropCount += 1;
7315
- return;
7316
- }
7317
- }
7318
- const key = pendingKey(handle, frame.header.corr);
7319
- const pending = this.pending.get(key);
7320
- if (pending) {
7321
- if (pending.acceptFrame && !pending.acceptFrame(frame))
7322
- return;
7323
- switch (frame.header.ty) {
7324
- case FrameType.Push:
7325
- case FrameType.StreamData:
7326
- try {
7327
- pending.onProgress?.(frame.body);
7328
- } catch {}
7329
- return;
7330
- case FrameType.Response:
7331
- case FrameType.StreamEnd:
7332
- this.settle(key, pending, () => pending.resolve(frame));
7333
- return;
7334
- case FrameType.Error:
7335
- this.settle(key, pending, () => pending.reject(this.errorFromFrame(frame)));
7336
- return;
7337
- default:
7338
- return;
7339
- }
7340
- }
7341
- const late = this.lateResponses.get(key);
7342
- if (late && (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error)) {
7343
- this.lateResponses.delete(key);
7344
- late(frame);
7345
- return;
7346
- }
7347
- if (frame.header.ty === FrameType.Goodbye && handle) {
7348
- this.failHandle(handle, new SubcError("route closed by subc (GOODBYE)", "route_closed"));
7349
- if (this.liveRoutes.get(handle.channel) === handle)
7350
- this.liveRoutes.delete(handle.channel);
7351
- this.evictRouteHandle(handle);
7352
- return;
7353
- }
7354
- if (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error || frame.header.ty === FrameType.StreamEnd) {
7355
- 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() ?? "?");
7356
- }
7357
- }
7358
- settle(key, pending, run) {
7359
- if (this.pending.get(key) !== pending)
7360
- return false;
7361
- this.pending.delete(key);
7362
- if (pending.timer)
7363
- clearTimeout(pending.timer);
7364
- run();
7365
- pending.onSettle?.();
7366
- return true;
7367
- }
7368
- rejectPending(key, pending, err) {
7369
- this.settle(key, pending, () => pending.reject(pending.classifyFailure?.(err) ?? err));
7370
- }
7371
- errorFromFrame(frame) {
7372
- try {
7373
- const parsed = JSON.parse(Buffer.from(frame.body).toString("utf8"));
7374
- return new SubcError(parsed.message ?? "subc error", parsed.code, parsed.detail);
7375
- } catch {
7376
- return new SubcError(Buffer.from(frame.body).toString("utf8") || "subc error");
7377
- }
7378
- }
7379
- evictRouteHandle(handle) {
7380
- for (const cached of this.routes.values()) {
7381
- if (cached.handle && sameRouteHandle(cached.handle, handle))
7382
- cached.handle = null;
7383
- }
7384
- }
7385
- failHandle(handle, error) {
7386
- for (const [key, pending] of this.pending) {
7387
- if (pending.handle && sameRouteHandle(pending.handle, handle))
7388
- this.rejectPending(key, pending, error);
7389
- }
7390
- }
7391
- fail(err) {
7392
- if (!this.closedErr)
7393
- this.closedErr = err;
7394
- for (const [key, pending] of this.pending) {
7395
- this.rejectPending(key, pending, err);
7396
- }
7397
- }
7398
- notSentCallError(message, cause) {
7399
- return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
7400
- }
7401
- outcomeUnknownCallError(message, cause) {
7402
- return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
7403
- }
7404
- terminalCallError(message, cause) {
7405
- if (cause instanceof SubcCallError)
7406
- return cause;
7407
- return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
7408
- }
7409
- notSentRecoveryError(message, cause) {
7410
- if (cause instanceof SubcCallError)
7411
- return cause;
7412
- if (isConsumerReconnectTransient(cause))
7413
- return this.notSentCallError(message, cause);
7414
- return this.terminalCallError(message, cause);
7415
- }
7416
- get droppedIngressFrames() {
7417
- return this.ingressEpochDropCount;
7418
- }
7419
- installRoute(channel, epoch) {
7420
- const handle = createRouteHandle(channel, epoch, this.connectionToken);
7421
- this.liveRoutes.set(channel, handle);
7422
- return handle;
7423
- }
7424
- isLiveHandle(handle) {
7425
- return belongsToConnection(handle, this.connectionToken) && this.liveRoutes.get(handle.channel) === handle;
7426
- }
7427
- assertLiveConnection(handle) {
7428
- if (!belongsToConnection(handle, this.connectionToken))
7429
- throw new StaleRouteHandleError(handle);
7430
- }
7431
- assertLiveHandle(handle) {
7432
- if (!this.isLiveHandle(handle))
7433
- throw new StaleRouteHandleError(handle);
7434
- }
7435
- allocateCorr() {
7436
- const maximum = 0xffffffffffffffffn;
7437
- if (this.nextCorr > maximum) {
7438
- const error = new SubcError("channel-0 correlation id allocator exhausted", "corr_exhausted");
7439
- this.fail(error);
7440
- this.sock.close();
7441
- this.scheduleReconnectAfterDrop(error);
7442
- throw error;
7443
- }
7444
- const corr = this.nextCorr;
7445
- this.nextCorr += 1n;
7446
- return corr;
7447
- }
7448
- closeConnectionAfterCleanupFailure() {
7449
- const error = new SubcError("late route cleanup could not be queued", "late_route_cleanup_failed");
7450
- this.fail(error);
7451
- this.sock.close();
7452
- this.scheduleReconnectAfterDrop(error);
7453
- }
7454
- encode(value) {
7455
- return Buffer.from(JSON.stringify(value), "utf8");
7456
- }
7457
- decodeReply(frame) {
7458
- return hasBinary(frame.header.flags) ? frame.body : this.parseJson(frame);
7459
- }
7460
- parseJson(frame) {
7461
- const b = frame.body;
7462
- return JSON.parse(Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("utf8"));
7463
- }
7464
- }
7465
- function isConsumerReconnectTransient(err) {
7466
- if (err instanceof SocketClosedError || err instanceof SocketTimeoutError)
7467
- return true;
7468
- if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError)
7469
- return true;
7470
- if (err instanceof SubcCallError)
7471
- return err.kind === "not_sent" || err.kind === "outcome_unknown";
7472
- if (err instanceof AuthError)
7473
- return true;
7474
- if (err instanceof SubcError || err instanceof ConnectionFileError)
7475
- return false;
7476
- const code = errorCode(err);
7477
- return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
7478
- }
7479
- function isRouteOpenRefusal(err) {
7480
- return err instanceof SubcError && typeof err.code === "string";
7481
- }
7482
- function isRetryableRouteOpenCode(code) {
7483
- if (code === "capability_forbidden")
7484
- return false;
7485
- return code === "unknown_module" || code === "module_reloading" || code === "module_warming" || code === "target_unavailable" || code === "module_timeout";
7486
- }
7487
- async function connectionFileExists(path) {
7488
- try {
7489
- await fs2.access(path);
7490
- return true;
7491
- } catch {
7492
- return false;
7493
- }
7494
- }
7495
- function normalizeConnectOptions(opts) {
7496
- return {
7497
- connectionFile: opts.connectionFile,
7498
- handshakeTimeoutMs: opts.handshakeTimeoutMs,
7499
- identity: opts.identity,
7500
- targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
7501
- reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
7502
- sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
7503
- routeOpenRetryDeadlineMs: opts.routeOpenRetryDeadlineMs ?? ROUTE_OPEN_RETRY_DEADLINE_MS,
7504
- timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS,
7505
- livenessProbeWindowMs: opts.livenessProbeWindowMs ?? LIVENESS_PROBE_WINDOW_MS,
7506
- onControlPush: opts.onControlPush
7507
- };
7508
- }
7509
- function isValidCapabilityIdentifier(identifier) {
7510
- if (/\s/u.test(identifier))
7511
- return false;
7512
- const separator = identifier.indexOf("/v");
7513
- if (separator <= 0 || identifier.indexOf("/v", separator + 1) !== -1)
7514
- return false;
7515
- const name = identifier.slice(0, separator);
7516
- const version = identifier.slice(separator + 2);
7517
- if (new TextEncoder().encode(name).byteLength > 64 || version.length === 0)
7518
- return false;
7519
- if (!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test(name) && !/^[a-z]$/u.test(name))
7520
- return false;
7521
- if (name.includes("--"))
7522
- return false;
7523
- if (!/^\d+$/u.test(version) || version.length > 1 && version.startsWith("0"))
7524
- return false;
7525
- const numericVersion = Number(version);
7526
- return Number.isSafeInteger(numericVersion) && numericVersion >= 1 && numericVersion <= 4294967295;
7527
- }
7528
- function routeCacheKey(target, identity, consumerIdentity) {
7529
- const consumerPart = consumerIdentity ? `${consumerIdentity.module_id}\x00${consumerIdentity.launch_nonce}` : "";
7530
- return `${target.kind}\x00${target.module_id}\x00${identity.project_root}\x00${identity.harness}\x00${identity.session}\x00${consumerPart}`;
7531
- }
7532
- function routeOpenConsumerIdentity(opts = {}) {
7533
- if (opts.consumerIdentity !== undefined)
7534
- return opts.consumerIdentity ?? undefined;
7535
- const moduleId = process.env[SUBC_MODULE_ID_ENV];
7536
- const launchNonce = process.env[SUBC_LAUNCH_NONCE_ENV];
7537
- if (!moduleId || !launchNonce)
7538
- return;
7539
- return { module_id: moduleId, launch_nonce: launchNonce };
7540
- }
7541
- function errorCode(err) {
7542
- if (typeof err === "object" && err !== null && "code" in err) {
7543
- const code = err.code;
7544
- if (typeof code === "string")
7545
- return code;
7546
- }
7547
- return;
7548
- }
7549
- function causeMessage(cause) {
7550
- if (cause === undefined)
7551
- return "";
7552
- return `: ${cause instanceof Error ? cause.message : String(cause)}`;
7553
- }
7554
- function pendingKey(handle, corr) {
7555
- return handle ? `${handle.channel}:${handle.epoch}:${corr}` : `0:0:${corr}`;
7556
- }
7557
- // src/features/magic-context/memory/embedding-synapse.ts
7558
- var SYNAPSE_DEFAULT_MODEL = "gte-modernbert-base-f16";
7559
- var SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS = 3000;
7560
- var SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS = 120000;
7561
- var SYNAPSE_CERTIFICATION_REFUSAL_REASONS = new Set([
7562
- "not_certified",
7563
- "probe_required",
7564
- "migration_required"
7565
- ]);
7566
- var embeddingRowMetadata = new WeakMap;
7567
- function isSynapseEmbeddingTruncated(vector) {
7568
- return embeddingRowMetadata.get(vector)?.truncated === true;
7569
- }
7570
- function toSynapseLaneDescriptor(metadata) {
7571
- const tokenBudget = metadata.recommended_token_budget;
7572
- return {
7573
- lane: metadata.model,
7574
- ...metadata.device_class ? { device_class: metadata.device_class } : {},
7575
- max_tokens: metadata.max_tokens,
7576
- max_tokens_source: metadata.max_tokens_source,
7577
- ...metadata.bucket_ladder ? { bucket_ladder: [...metadata.bucket_ladder] } : {},
7578
- ...metadata.dims ? { dims: metadata.dims } : {},
7579
- ...metadata.dtype ? { dtype: metadata.dtype } : {},
7580
- ...typeof metadata.certified === "boolean" ? { certified: metadata.certified } : {},
7581
- ...metadata.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: metadata.warm_load_cost_hint_ms } : {},
7582
- ...metadata.recommended_batch ? {
7583
- recommended_batch: {
7584
- rows: metadata.recommended_batch,
7585
- ...tokenBudget !== undefined ? { token_budget: tokenBudget } : {}
7586
- }
7587
- } : {},
7588
- warm: metadata.max_tokens_source === "runtime_bucket" || metadata.max_tokens_source === "worker_bucket"
7589
- };
7590
- }
7591
- function formatSynapseLaneDescriptor(descriptor) {
7592
- const certified = descriptor.certified === undefined ? "unknown" : String(descriptor.certified);
7593
- 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"}`;
7594
- }
7595
-
7596
- class SynapseEmbeddingError extends Error {
7597
- code;
7598
- retryAfterMs;
7599
- permanent;
7600
- refusalReason;
7601
- constructor(code, message, options) {
7602
- super(message, options?.cause === undefined ? undefined : { cause: options.cause });
7603
- this.name = "SynapseEmbeddingError";
7604
- this.code = code;
7605
- this.permanent = options?.permanent ?? isPermanentSynapseCode(code);
7606
- this.retryAfterMs = options?.retryAfterMs ?? (this.permanent ? undefined : 100);
7607
- this.refusalReason = options?.refusalReason;
7608
- }
7609
- }
7610
- function isPermanentSynapseCode(code) {
7611
- 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";
7612
- }
7613
- function asRecord(value) {
7614
- return value !== null && typeof value === "object" ? value : null;
7615
- }
7616
- function responseBody(value) {
7617
- const record = asRecord(value);
7618
- const result = asRecord(record?.result);
7619
- const payload = asRecord(result?.payload ?? record?.payload);
7620
- return {
7621
- ...record ?? {},
7622
- ...result ?? {},
7623
- ...payload ?? {}
7624
- };
7625
- }
7626
- function readRetryAfter(value) {
7627
- const record = asRecord(value);
7628
- const candidate = record?.retry_after_ms ?? record?.retryAfterMs;
7629
- if (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)
7630
- return;
7631
- return Math.ceil(candidate);
7632
- }
7633
- function readErrorCode(value) {
7634
- const record = asRecord(value);
7635
- if (typeof record?.code === "string")
7636
- return record.code;
7637
- if (value instanceof Error && "code" in value && typeof value.code === "string") {
7638
- return value.code;
7639
- }
7640
- return;
7641
- }
7642
- function readCertificationRefusalReason(value) {
7643
- if (!(value instanceof SubcCallError))
7644
- return;
7645
- const detail = value.detail;
7646
- if (typeof detail === "string")
7647
- return detail;
7648
- const record = asRecord(detail);
7649
- return typeof record?.reason === "string" ? record.reason : undefined;
7650
- }
7651
- function classifyError(value) {
7652
- if (value instanceof SynapseEmbeddingError)
7653
- return value;
7654
- const code = readErrorCode(value) ?? (value instanceof Error ? value.name : "transport");
7655
- const normalized = code.toLowerCase();
7656
- const refusalReason = readCertificationRefusalReason(value);
7657
- let mapped = "transport";
7658
- if (normalized.includes("queue_full"))
7659
- mapped = "queue_full";
7660
- else if (normalized.includes("model_loading"))
7661
- mapped = "model_loading";
7662
- else if (normalized.includes("timeout") || normalized.includes("deadline"))
7663
- mapped = "timeout";
7664
- else if (normalized.includes("artifact_invalid"))
7665
- mapped = "artifact_invalid";
7666
- else if (normalized.includes("substitution"))
7667
- mapped = "substitution_rejected";
7668
- else if (normalized === "certification_refused")
7669
- mapped = "certification_refused";
7670
- else if (normalized.includes("not_certified"))
7671
- mapped = "not_certified";
7672
- else if (normalized.includes("probe_required"))
7673
- mapped = "probe_required";
7674
- else if (normalized.includes("idempotency_conflict"))
7675
- mapped = "idempotency_conflict";
7676
- else if (normalized.includes("needs_reauth"))
7677
- mapped = "needs_reauth";
7678
- else if (normalized.includes("schema"))
7679
- mapped = "schema_violation";
7680
- else if (normalized.includes("module_restarted") || normalized.includes("module restarted"))
7681
- mapped = "module_restarted";
7682
- const message = value instanceof Error ? value.message : String(value);
7683
- return new SynapseEmbeddingError(mapped, message, {
7684
- retryAfterMs: readRetryAfter(value) ?? (isPermanentSynapseCode(mapped) ? undefined : 100),
7685
- cause: value,
7686
- refusalReason
7687
- });
7688
- }
7689
- function embeddingFailureFor(error) {
7690
- const typedReason = error.refusalReason;
7691
- if (typedReason !== undefined && SYNAPSE_CERTIFICATION_REFUSAL_REASONS.has(typedReason) || error.code === "not_certified" || error.code === "probe_required") {
7692
- return {
7693
- class: "certification_refusal",
7694
- reason: `SYNAPSE certification refused embedding: ${typedReason ?? error.code}`,
7695
- retryable: false
7696
- };
7697
- }
7698
- if (error.code === "certification_refused") {
7699
- return {
7700
- class: "certification_refusal",
7701
- reason: `SYNAPSE certification refused embedding: ${typedReason ?? "unknown reason"}`,
7702
- retryable: false
7703
- };
7704
- }
7705
- if (typedReason === "needs_reauth" || typedReason === "needs_reauth_expired") {
7706
- return {
7707
- class: "credential_required",
7708
- reason: "SYNAPSE requires reauthentication",
7709
- retryable: false
7710
- };
7711
- }
7712
- if (error.code === "substitution_rejected") {
7713
- return { class: "substitution_rejected", reason: error.message, retryable: false };
7714
- }
7715
- if (error.code === "schema_violation" || error.code === "artifact_invalid") {
7716
- return { class: "invalid_envelope", reason: error.message, retryable: false };
7717
- }
7718
- return { class: "transport_error", reason: error.message, retryable: !error.permanent };
7719
- }
7720
- function wait(ms) {
7721
- return new Promise((resolve) => setTimeout(resolve, ms));
7722
- }
7723
- function sha256(value) {
7724
- return createHash("sha256").update(value).digest("hex");
7725
- }
7726
- function stableJson(value) {
7727
- if (Array.isArray(value))
7728
- return `[${value.map(stableJson).join(",")}]`;
7729
- if (value && typeof value === "object") {
7730
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
7731
- }
7732
- return JSON.stringify(value);
7733
- }
7734
- function getSynapseLaneIdentity(model, fingerprint) {
7735
- return `synapse:v1:${sha256(stableJson({ model, fingerprint }))}`;
7736
- }
7737
- function getSynapseBatchRequestKey(args) {
7738
- return sha256(stableJson({
7739
- op: "embed.batch",
7740
- model: args.model,
7741
- required_fingerprint: args.fingerprint,
7742
- required_epoch: args.tableEpoch,
7743
- allow_equivalent: false,
7744
- accept_declared: false,
7745
- ids: args.items.map((item) => item.id),
7746
- content_sha256: args.items.map((item) => item.contentSha256),
7747
- ...args.purpose === "query" ? { purpose: args.purpose } : {}
7748
- }));
7749
- }
7750
- function hashContent(text) {
7751
- return sha256(text);
7752
- }
7753
- function extractCatalogEntries(value) {
7754
- const body = responseBody(value);
7755
- const raw = Array.isArray(body.models) ? body.models : Array.isArray(body.entries) ? body.entries : Array.isArray(value) ? value : [];
7756
- const envelopeEpoch = typeof body.table_epoch === "number" && Number.isInteger(body.table_epoch) ? body.table_epoch : undefined;
7757
- const maxTokenSources = new Set([
7758
- "runtime_bucket",
7759
- "worker_bucket",
7760
- "catalog",
7761
- "catalog_unloaded"
7762
- ]);
7763
- return raw.flatMap((entry) => {
7764
- const record = asRecord(entry);
7765
- if (!record)
7766
- return [];
7767
- const model = typeof record.model === "string" && record.model.length > 0 ? record.model : typeof record.model_id === "string" ? record.model_id : "";
7768
- const fingerprint = typeof record.fingerprint === "string" && record.fingerprint.length > 0 ? record.fingerprint : Array.isArray(record.fingerprints) && typeof record.fingerprints[0] === "string" ? record.fingerprints[0] : "";
7769
- const entryEpoch = record.table_epoch ?? record.tableEpoch;
7770
- const tableEpoch = typeof entryEpoch === "number" && Number.isInteger(entryEpoch) ? entryEpoch : envelopeEpoch;
7771
- const maxTokens = record.max_tokens;
7772
- const maxTokensSource = record.max_tokens_source;
7773
- 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)) {
7774
- return [];
7775
- }
7776
- const dims = record.dims ?? record.dimensions;
7777
- const rawBatch = record.recommended_batch ?? record.recommendedBatch;
7778
- const batchRecord = asRecord(rawBatch);
7779
- const recommendedBatch = typeof rawBatch === "number" ? rawBatch : batchRecord ? batchRecord.rows : undefined;
7780
- const recommendedTokenBudget = batchRecord ? batchRecord.token_budget : undefined;
7781
- const bucketLadder = Array.isArray(record.bucket_ladder) ? record.bucket_ladder.filter((bucket) => typeof bucket === "number" && Number.isInteger(bucket) && bucket > 0) : undefined;
7782
- const state = typeof record.state === "string" ? record.state : undefined;
7783
- const warmLoadCostHint = record.warm_load_cost_hint_ms;
7784
- return [
7785
- {
7786
- model,
7787
- fingerprint,
7788
- table_epoch: tableEpoch,
7789
- max_tokens: maxTokens,
7790
- max_tokens_source: maxTokensSource,
7791
- ...bucketLadder && bucketLadder.length > 0 ? { bucket_ladder: [...new Set(bucketLadder)].sort((a, b) => a - b) } : {},
7792
- ...typeof dims === "number" && Number.isInteger(dims) && dims > 0 ? { dims } : {},
7793
- ...typeof record.dtype === "string" && record.dtype.length > 0 ? { dtype: record.dtype } : {},
7794
- ...typeof record.device_class === "string" && record.device_class.length > 0 ? { device_class: record.device_class } : {},
7795
- ...typeof recommendedBatch === "number" && recommendedBatch > 0 ? { recommended_batch: Math.floor(recommendedBatch) } : {},
7796
- ...typeof recommendedTokenBudget === "number" && recommendedTokenBudget > 0 ? { recommended_token_budget: Math.floor(recommendedTokenBudget) } : {},
7797
- ...record.provenance !== undefined ? { provenance: record.provenance } : {},
7798
- ...typeof record.certified === "boolean" ? { certified: record.certified } : {},
7799
- ...typeof warmLoadCostHint === "number" && Number.isFinite(warmLoadCostHint) && warmLoadCostHint >= 0 ? { warm_load_cost_hint_ms: warmLoadCostHint } : {},
7800
- ...typeof record.status === "string" ? { status: record.status } : state ? { status: state } : {}
7801
- }
7802
- ];
7803
- });
7804
- }
7805
- function extractVector(value) {
7806
- const body = responseBody(value);
7807
- const item = Array.isArray(body.vectors) ? asRecord(body.vectors[0]) : null;
7808
- const raw = item?.vector;
7809
- if (!item || !Array.isArray(raw) || raw.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
7810
- return null;
7811
- }
7812
- const disclosure = Array.isArray(body.truncation_disclosures) ? asRecord(body.truncation_disclosures[0]) : null;
7813
- return { vector: Float32Array.from(raw), item, disclosure, metadata: body };
7814
- }
7815
- function extractBatchItems(value) {
7816
- const body = responseBody(value);
7817
- const raw = Array.isArray(body.vectors) ? body.vectors : Array.isArray(body.items) ? body.items : Array.isArray(body.results) ? body.results : [];
7818
- return raw.flatMap((item) => {
7819
- const record = asRecord(item);
7820
- return record ? [record] : [];
7821
- });
7822
- }
7823
- function extractTruncationDisclosures(value) {
7824
- const body = responseBody(value);
7825
- if (!Array.isArray(body.truncation_disclosures))
7826
- return [];
7827
- return body.truncation_disclosures.map((disclosure) => asRecord(disclosure));
7828
- }
7829
- function validateWireRow(item, disclosure, expected) {
7830
- const submittedSha256 = item.submitted_sha256;
7831
- const contentSha256 = item.content_sha256;
7832
- const expectedSubmittedSha256 = hashContent(expected.text);
7833
- if (typeof submittedSha256 !== "string") {
7834
- throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted submitted_sha256`);
7835
- }
7836
- if (submittedSha256 !== expectedSubmittedSha256) {
7837
- throw new SynapseEmbeddingError("schema_violation", `Synapse submitted hash mismatch for item ${expected.id}`);
7838
- }
7839
- if (typeof contentSha256 !== "string") {
7840
- throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted content_sha256`);
7841
- }
7842
- const hashesDiffer = contentSha256 !== submittedSha256;
7843
- const disclosedTruncation = disclosure?.truncated === true;
7844
- const effectiveTokens = disclosure?.effective_tokens;
7845
- if (disclosure && (typeof disclosure.truncated !== "boolean" || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0)) {
7846
- throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} returned an invalid truncation disclosure`);
7847
- }
7848
- if (hashesDiffer) {
7849
- if (!disclosedTruncation || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0) {
7850
- throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} changed content without a valid truncation disclosure`);
7851
- }
7852
- } else if (disclosedTruncation) {
7853
- throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} disclosed truncation but returned matching hashes`);
7854
- }
7855
- return {
7856
- truncated: hashesDiffer,
7857
- submittedSha256,
7858
- contentSha256,
7859
- ...typeof effectiveTokens === "number" && Number.isInteger(effectiveTokens) && effectiveTokens >= 0 ? { effectiveTokens } : {}
7860
- };
7861
- }
7862
- var sharedClient = null;
7863
- var sharedClientFile = null;
7864
- var sharedClientPromise = null;
7865
- var factoryClients = new WeakMap;
7866
- async function getSharedClient(options) {
7867
- if (options.clientFactory) {
7868
- let promise = factoryClients.get(options.clientFactory);
7869
- if (!promise) {
7870
- promise = options.clientFactory();
7871
- factoryClients.set(options.clientFactory, promise);
7872
- }
7873
- return promise;
7874
- }
7875
- if (sharedClient && sharedClientFile === options.connectionFile)
7876
- return sharedClient;
7877
- if (sharedClientPromise && sharedClientFile === options.connectionFile)
7878
- return sharedClientPromise;
7879
- sharedClientFile = options.connectionFile;
7880
- sharedClientPromise = SubcClient.connect({ connectionFile: options.connectionFile }).then((client) => {
7881
- sharedClient = client;
7882
- return client;
7883
- });
7884
- return sharedClientPromise;
7885
- }
7886
-
7887
- class SynapseEmbeddingProvider {
7888
- modelId;
7889
- metadata;
7890
- get maxInputTokens() {
7891
- return this.metadata?.max_tokens;
7892
- }
7893
- options;
7894
- client = null;
7895
- initialized = false;
7896
- initializing = null;
7897
- permanentFailure = false;
7898
- lastFailureReason = null;
7899
- batchLimit = 16;
7900
- tokenBudget = null;
7901
- constructor(options) {
7902
- this.options = options;
7903
- const model = options.model || SYNAPSE_DEFAULT_MODEL;
7904
- const fingerprint = options.fingerprint ?? "";
7905
- const descriptor = options.descriptor;
7906
- this.metadata = options.metadata ? {
7907
- ...options.metadata,
7908
- bucket_ladder: options.metadata.bucket_ladder ? [...options.metadata.bucket_ladder] : undefined
7909
- } : fingerprint && Number.isInteger(options.tableEpoch) && descriptor ? {
7910
- model,
7911
- fingerprint,
7912
- table_epoch: options.tableEpoch,
7913
- max_tokens: descriptor.max_tokens,
7914
- max_tokens_source: descriptor.max_tokens_source,
7915
- ...descriptor.bucket_ladder ? { bucket_ladder: [...descriptor.bucket_ladder] } : {},
7916
- ...options.dims ?? descriptor.dims ? { dims: options.dims ?? descriptor.dims } : {},
7917
- ...descriptor.dtype ? { dtype: descriptor.dtype } : {},
7918
- ...descriptor.device_class ? { device_class: descriptor.device_class } : {},
7919
- ...options.recommendedBatch ?? descriptor.recommended_batch?.rows ? {
7920
- recommended_batch: Math.max(1, Math.floor(options.recommendedBatch ?? descriptor.recommended_batch?.rows))
7921
- } : {},
7922
- ...options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget ? {
7923
- recommended_token_budget: Math.max(1, Math.floor(options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget))
7924
- } : {},
7925
- ...options.provenance !== undefined ? { provenance: options.provenance } : {},
7926
- ...typeof descriptor.certified === "boolean" ? { certified: descriptor.certified } : {},
7927
- ...descriptor.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: descriptor.warm_load_cost_hint_ms } : {},
7928
- laneIdentity: getSynapseLaneIdentity(model, fingerprint)
7929
- } : null;
7930
- this.modelId = this.metadata?.laneIdentity ?? "synapse:v1:pending";
7931
- this.batchLimit = this.metadata?.recommended_batch ?? 16;
7932
- this.tokenBudget = this.metadata?.recommended_token_budget ?? null;
7933
- }
7934
- nextPage(items, start) {
7935
- const hardEnd = Math.min(items.length, start + this.batchLimit);
7936
- if (this.tokenBudget === null)
7937
- return items.slice(start, hardEnd);
7938
- let end = start;
7939
- let tokens = 0;
7940
- while (end < hardEnd) {
7941
- tokens += estimateTokens(items[end].text);
7942
- if (tokens > this.tokenBudget && end > start)
7943
- break;
7944
- end += 1;
7945
- }
7946
- return items.slice(start, Math.max(end, start + 1));
7947
- }
7948
- static async discover(options) {
7949
- const provider = new SynapseEmbeddingProvider(options);
7950
- if (!await provider.initialize() || !provider.metadata) {
7951
- throw new SynapseEmbeddingError("not_certified", "Synapse lane is not ready");
7952
- }
7953
- return provider.metadata;
7954
- }
7955
- async initialize() {
7956
- if (this.initialized)
7957
- return true;
7958
- if (this.permanentFailure)
7959
- return false;
7960
- if (this.initializing)
7961
- return this.initializing;
7962
- this.initializing = (async () => {
7963
- try {
7964
- if (!this.options.clientFactory && !await connectionFileExists(this.options.connectionFile)) {
7965
- throw new SynapseEmbeddingError("transport", `Synapse connection file is unavailable: ${this.options.connectionFile}`);
7966
- }
7967
- this.client = await getSharedClient(this.options);
7968
- if (!this.metadata) {
7969
- const discovered = await this.callWithRetry("models.list", {}, this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, false);
7970
- const entries = extractCatalogEntries(discovered);
7971
- const requested = this.options.model?.trim() || SYNAPSE_DEFAULT_MODEL;
7972
- const entry = entries.find((candidate) => candidate.model === requested);
7973
- if (!entry) {
7974
- throw new SynapseEmbeddingError("artifact_invalid", `Synapse models.list did not return requested model ${requested}`);
7975
- }
7976
- if (entry.certified === false || entry.status === "not_certified") {
7977
- throw new SynapseEmbeddingError("not_certified", `Synapse model ${entry.model} is not certified`);
7978
- }
7979
- const metadata = {
7980
- ...entry,
7981
- laneIdentity: getSynapseLaneIdentity(entry.model, entry.fingerprint)
7982
- };
7983
- this.metadata = metadata;
7984
- this.modelId = metadata.laneIdentity;
7985
- this.batchLimit = metadata.recommended_batch ?? this.batchLimit;
7986
- this.tokenBudget = metadata.recommended_token_budget ?? this.tokenBudget;
7987
- }
7988
- this.initialized = true;
7989
- this.recordSuccess();
7990
- return true;
7991
- } catch (error) {
7992
- const classified = classifyError(error);
7993
- this.recordFailure(classified);
7994
- if (classified.permanent) {
7995
- this.permanentFailure = true;
7996
- log(`[magic-context] Synapse lane disabled: ${classified.code}: ${classified.message}`);
7997
- } else {
7998
- log(`[magic-context] Synapse lane unavailable: ${classified.message}`);
7999
- }
8000
- this.initialized = false;
8001
- return false;
8002
- } finally {
8003
- this.initializing = null;
8004
- }
8005
- })();
8006
- return this.initializing;
8007
- }
8008
- async embed(text, signal, purpose = "passage") {
8009
- if (!await this.initialize() || signal?.aborted || !this.metadata)
8010
- return null;
8011
- if (estimateTokens(text) > this.metadata.max_tokens)
8012
- return null;
8013
- try {
8014
- const id = "query";
8015
- const value = await this.callWithRetry("embed.query", this.requestConstraints({
8016
- id,
8017
- text,
8018
- purpose,
8019
- deadline_ms: this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS
8020
- }), this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, true, signal);
8021
- const extracted = extractVector(value);
8022
- if (!extracted) {
8023
- throw new SynapseEmbeddingError("schema_violation", "Synapse query returned no vector row");
8024
- }
8025
- if (extracted.item.id !== id) {
8026
- throw new SynapseEmbeddingError("schema_violation", `Synapse query returned unexpected item ${String(extracted.item.id)}`);
8027
- }
8028
- const rowMetadata = validateWireRow(extracted.item, extracted.disclosure, { id, text });
8029
- this.validateResponse(extracted.metadata, extracted.vector.length);
8030
- embeddingRowMetadata.set(extracted.vector, rowMetadata);
8031
- this.recordSuccess();
8032
- return extracted.vector;
8033
- } catch (error) {
8034
- this.logCallFailure(error, "embed.query");
8035
- return null;
8036
- }
8037
- }
8038
- async embedBatch(texts, signal, purpose = "passage") {
8039
- if (texts.length === 0)
8040
- return [];
8041
- const items = texts.map((text, index) => ({
8042
- id: `item:${index}`,
8043
- text,
8044
- contentSha256: hashContent(text)
8045
- }));
8046
- const map = await this.embedItems(items, signal, purpose);
8047
- return items.map((item) => map.get(item.id) ?? null);
8048
- }
8049
- async embedItems(items, signal, purpose = "passage") {
8050
- const output = new Map;
8051
- if (items.length === 0 || !await this.initialize() || !this.metadata || signal?.aborted) {
8052
- return output;
8053
- }
8054
- const maxTokens = this.metadata.max_tokens;
8055
- const eligibleItems = items.filter((item) => estimateTokens(item.text) <= maxTokens).map((item) => ({ ...item, contentSha256: hashContent(item.text) }));
8056
- for (let start = 0;start < eligibleItems.length; ) {
8057
- if (signal?.aborted || this.permanentFailure)
8058
- break;
8059
- const page = this.nextPage(eligibleItems, start);
8060
- start += page.length;
8061
- try {
8062
- const requestKey = this.requestKey(page, purpose);
8063
- let body = {};
8064
- let restarted = false;
8065
- for (;; ) {
8066
- try {
8067
- body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey, purpose), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
8068
- const first = responseBody(body);
8069
- const jobId = typeof first.job_id === "string" ? first.job_id : null;
8070
- if (jobId)
8071
- body = await this.pollBatch(jobId, requestKey, signal);
8072
- break;
8073
- } catch (error) {
8074
- const classified = classifyError(error);
8075
- if (classified.code !== "module_restarted" || restarted)
8076
- throw classified;
8077
- restarted = true;
8078
- }
8079
- }
8080
- const batchEnvelope = responseBody(body);
8081
- const disclosures = extractTruncationDisclosures(body);
8082
- for (const [index, item] of extractBatchItems(body).entries()) {
8083
- const id = typeof item.id === "string" ? item.id : "";
8084
- const vector = item.vector ?? item.embedding;
8085
- if (!id || !Array.isArray(vector) || vector.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
8086
- throw new SynapseEmbeddingError("schema_violation", "Synapse batch item is malformed");
8087
- }
8088
- const expected = page.find((candidate) => candidate.id === id);
8089
- if (!expected) {
8090
- throw new SynapseEmbeddingError("schema_violation", `Synapse returned unknown item ${id}`);
8091
- }
8092
- const rowMetadata = validateWireRow(item, disclosures[index] ?? null, expected);
8093
- const vectorArray = Float32Array.from(vector);
8094
- this.validateResponse({ ...batchEnvelope, ...item }, vectorArray.length);
8095
- embeddingRowMetadata.set(vectorArray, rowMetadata);
8096
- output.set(id, vectorArray);
8097
- this.recordSuccess();
8098
- }
8099
- } catch (error) {
8100
- const classified = classifyError(error);
8101
- this.logCallFailure(classified, "embed.batch");
8102
- if (classified.code === "idempotency_conflict" || classified.code === "schema_violation") {
8103
- throw classified;
8104
- }
8105
- if (classified.permanent) {
8106
- this.permanentFailure = true;
8107
- this.initialized = false;
8108
- break;
8109
- }
8110
- }
8111
- }
8112
- return output;
8113
- }
8114
- async dispose() {
8115
- this.initialized = false;
8116
- this.client = null;
8117
- }
8118
- isLoaded() {
8119
- return this.initialized;
8120
- }
8121
- getLastFailureReason() {
8122
- return this.lastFailureReason;
8123
- }
8124
- requestConstraints(extra) {
8125
- const metadata = this.metadata;
8126
- if (!metadata)
8127
- return extra;
8128
- return {
8129
- ...extra,
8130
- model: metadata.model,
8131
- required_fingerprint: metadata.fingerprint,
8132
- required_epoch: metadata.table_epoch,
8133
- allow_equivalent: false,
8134
- accept_declared: false
8135
- };
8136
- }
8137
- batchRequest(items, requestKey, purpose) {
8138
- return this.requestConstraints({
8139
- items: items.map((item) => ({
8140
- id: item.id,
8141
- text: item.text,
8142
- content_sha256: item.contentSha256
8143
- })),
8144
- request_key: requestKey,
8145
- purpose
8146
- });
8147
- }
8148
- requestKey(items, purpose) {
8149
- if (!this.metadata)
8150
- throw new SynapseEmbeddingError("transport", "Synapse metadata is unavailable");
8151
- return getSynapseBatchRequestKey({
8152
- model: this.metadata.model,
8153
- fingerprint: this.metadata.fingerprint,
8154
- tableEpoch: this.metadata.table_epoch,
8155
- items,
8156
- purpose
8157
- });
8158
- }
8159
- async pollBatch(jobId, requestKey, signal) {
8160
- let cursor = null;
8161
- const allItems = [];
8162
- const allDisclosures = [];
8163
- for (;; ) {
8164
- if (signal?.aborted)
8165
- return {};
8166
- const body = await this.callWithRetry("embed.result", this.requestConstraints({
8167
- job_id: jobId,
8168
- cursor,
8169
- request_key: requestKey
8170
- }), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
8171
- const parsed = responseBody(body);
8172
- const items = extractBatchItems(body);
8173
- const disclosures = extractTruncationDisclosures(body);
8174
- allItems.push(...items);
8175
- allDisclosures.push(...items.map((_, index) => disclosures[index] ?? null));
8176
- const nextCursor = parsed.next_cursor ?? parsed.cursor;
8177
- const done = parsed.done === true || parsed.complete === true || nextCursor === undefined || nextCursor === null;
8178
- if (done) {
8179
- return {
8180
- ...parsed,
8181
- vectors: allItems,
8182
- truncation_disclosures: allDisclosures
8183
- };
8184
- }
8185
- cursor = nextCursor;
8186
- }
8187
- }
8188
- async callWithRetry(method, params, timeoutMs, retryEmbeddings, signal) {
8189
- let attempt = 0;
8190
- for (;; ) {
8191
- if (signal?.aborted)
8192
- throw new SynapseEmbeddingError("transport", "Synapse request aborted");
8193
- try {
8194
- if (!this.client)
8195
- throw new SynapseEmbeddingError("transport", "Synapse client is unavailable");
8196
- return await this.client.call(this.options.moduleId ?? "synapse", method, params, {
8197
- timeoutMs,
8198
- targetKind: "management_surface",
8199
- identity: {
8200
- project_root: this.options.projectRoot,
8201
- harness: getHarness(),
8202
- session: this.options.session
8203
- }
8204
- });
8205
- } catch (error) {
8206
- const classified = classifyError(error);
8207
- if (classified.code === "idempotency_conflict")
8208
- throw classified;
8209
- const outcomeUnknown = error instanceof SubcCallError && error.kind === "outcome_unknown";
8210
- const retryable = !classified.permanent && (retryEmbeddings || !outcomeUnknown);
8211
- if (!retryable || attempt >= 3)
8212
- throw classified;
8213
- const delay = classified.retryAfterMs ?? Math.min(2000, 100 * 2 ** attempt);
8214
- attempt += 1;
8215
- await wait(delay);
8216
- }
8217
- }
8218
- }
8219
- validateResponse(body, dims) {
8220
- const metadata = this.metadata;
8221
- if (!metadata) {
8222
- throw new SynapseEmbeddingError("artifact_invalid", "Synapse lane metadata missing");
8223
- }
8224
- if (metadata.dims === undefined) {
8225
- const envelopeDims = body.dims;
8226
- if (typeof envelopeDims === "number" && envelopeDims !== dims) {
8227
- throw new SynapseEmbeddingError("artifact_invalid", `Synapse envelope declares ${envelopeDims} dimensions but the vector has ${dims}`);
8228
- }
8229
- metadata.dims = dims;
8230
- }
8231
- if (dims !== metadata.dims) {
8232
- throw new SynapseEmbeddingError("artifact_invalid", `Synapse returned ${dims} dimensions, expected ${metadata.dims}`);
8233
- }
8234
- const fingerprint = body.fingerprint ?? body.served_fingerprint;
8235
- if (typeof fingerprint !== "string") {
8236
- throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served fingerprint");
8237
- }
8238
- if (fingerprint !== metadata.fingerprint) {
8239
- throw new SynapseEmbeddingError("substitution_rejected", `Synapse fingerprint changed from ${metadata.fingerprint} to ${fingerprint}`);
8240
- }
8241
- const epoch = body.table_epoch ?? body.tableEpoch;
8242
- if (typeof epoch !== "number") {
8243
- throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served table epoch");
8244
- }
8245
- if (epoch !== metadata.table_epoch) {
8246
- throw new SynapseEmbeddingError("substitution_rejected", `Synapse table epoch changed from ${metadata.table_epoch} to ${epoch}`);
8247
- }
8248
- }
8249
- logCallFailure(error, operation) {
8250
- const classified = classifyError(error);
8251
- this.recordFailure(classified);
8252
- if (classified.permanent)
8253
- this.permanentFailure = true;
8254
- const suffix = classified.retryAfterMs === undefined ? "" : ` retry_after_ms=${classified.retryAfterMs}`;
8255
- log(`[magic-context] Synapse ${operation} failed: ${classified.code}${suffix}: ${classified.message}`);
8256
- }
8257
- recordFailure(error) {
8258
- this.lastFailureReason = embeddingFailureFor(error);
8259
- }
8260
- recordSuccess() {
8261
- this.lastFailureReason = null;
8262
- }
8263
- }
8264
-
8265
- // src/features/magic-context/memory/normalize-hash.ts
8266
- import { createHash as createHash2 } from "node:crypto";
8267
- function normalizeMemoryContent(content) {
8268
- return content.toLowerCase().replace(/\s+/g, " ").trim();
8269
- }
8270
- function computeNormalizedHash(content) {
8271
- const normalized = normalizeMemoryContent(content);
8272
- return createHash2("md5").update(normalized).digest("hex");
8273
- }
8274
-
8275
- // src/features/magic-context/memory/embedding-identity.ts
8276
- function normalizeEndpoint(endpoint) {
8277
- return endpoint?.trim().replace(/\/+$/, "") ?? "";
8278
- }
8279
- var LOCAL_EMBEDDING_RUNTIME_FINGERPRINT = "transformers@4.3.0;onnxruntime-node@1.30.0;onnxruntime-web@1.26.0-dev.20260416-b7804b056c";
8280
- function getEmbeddingProviderIdentity(config) {
8281
- if (config.provider === "off") {
8282
- return "embedding-provider:off";
8283
- }
8284
- if (config.provider === "synapse") {
8285
- const resolved = config;
8286
- if (!resolved.model || !resolved.synapse_fingerprint)
8287
- return "synapse:v1:pending";
8288
- return getSynapseLaneIdentity(resolved.model, resolved.synapse_fingerprint);
8289
- }
8290
- if (config.provider !== "local" && config.provider !== "openai-compatible") {
8291
- throw new Error("Unknown embedding provider");
8292
- }
8293
- const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
8294
- const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
8295
- const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
8296
- const identityInput = config.provider === "openai-compatible" ? {
8297
- provider: "openai-compatible",
8298
- model: config.model.trim(),
8299
- endpoint: normalizeEndpoint(config.endpoint),
8300
- apiKeyPresent: Boolean(config.api_key?.trim()),
8301
- inputType: config.input_type?.trim() || "",
8302
- ...documentPrefix ? { documentPrefix } : {},
8303
- ...truncate ? { truncate } : {}
8304
- } : {
8305
- provider: "local",
8306
- model: config.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
8307
- endpoint: "",
8308
- apiKeyPresent: false,
8309
- runtimeFingerprint: LOCAL_EMBEDDING_RUNTIME_FINGERPRINT,
8310
- ...localDtype ? { localDtype } : {}
8311
- };
8312
- return `embedding-provider:${computeNormalizedHash(JSON.stringify(identityInput))}`;
8313
- }
8314
-
8315
6014
  // src/features/magic-context/memory/embedding-worker-client.ts
8316
6015
  import { Worker } from "node:worker_threads";
8317
6016
  class EmbeddingWorkerClient {
@@ -8359,7 +6058,7 @@ class EmbeddingWorkerClient {
8359
6058
  request.reject(error);
8360
6059
  }
8361
6060
  this.pending.clear();
8362
- log("[magic-context] embedding worker exited unexpectedly:", error);
6061
+ log2("[magic-context] embedding worker exited unexpectedly:", error);
8363
6062
  worker.terminate();
8364
6063
  };
8365
6064
  worker.on("error", fail);
@@ -8493,7 +6192,7 @@ async function acquireModelLoadLock(lockPath) {
8493
6192
  try {
8494
6193
  const info = await stat(lockPath);
8495
6194
  if (Date.now() - info.mtimeMs > STALE_LOCK_MS) {
8496
- log(`[magic-context] embedding-load lock stale (>${STALE_LOCK_MS}ms), taking over`);
6195
+ log2(`[magic-context] embedding-load lock stale (>${STALE_LOCK_MS}ms), taking over`);
8497
6196
  try {
8498
6197
  await unlink(lockPath);
8499
6198
  } catch {}
@@ -8556,7 +6255,7 @@ var importTransformersNodeWasmFallbackForRuntime = async () => {
8556
6255
  return await importPluginModule(() => import(nodeWasmEntry));
8557
6256
  };
8558
6257
  var modelCacheDirForRuntime = () => workerData?.magicContextEmbeddingWorker && typeof workerData.modelCacheDir === "string" ? workerData.modelCacheDir : join(getMagicContextStorageDir(), "models");
8559
- var logForRuntime = log;
6258
+ var logForRuntime = log2;
8560
6259
  var injectWasmOrtForRuntime = injectWasmOrt;
8561
6260
  var loadedLocalEmbeddingRuntimes = new Map;
8562
6261
  var nextLocalEmbeddingRuntimeId = 1;
@@ -8613,7 +6312,7 @@ async function injectWasmOrt() {
8613
6312
  wasmRuntimeInjected = true;
8614
6313
  return true;
8615
6314
  } catch (error) {
8616
- log("[magic-context] failed to inject onnxruntime-web:", error instanceof Error ? error.message : String(error));
6315
+ log2("[magic-context] failed to inject onnxruntime-web:", error instanceof Error ? error.message : String(error));
8617
6316
  return false;
8618
6317
  }
8619
6318
  }
@@ -8721,7 +6420,7 @@ async function withQuietConsole(fn) {
8721
6420
  const origError = console.error;
8722
6421
  const redirect = (...args) => {
8723
6422
  const message = args.map((a) => typeof a === "string" ? a : String(a)).join(" ");
8724
- log(`[transformers] ${message}`);
6423
+ log2(`[transformers] ${message}`);
8725
6424
  };
8726
6425
  console.warn = redirect;
8727
6426
  console.error = redirect;
@@ -8773,13 +6472,13 @@ function extractBatchEmbeddings(result, expectedCount) {
8773
6472
  return data.map((entry) => toFloat32Array(entry));
8774
6473
  }
8775
6474
  if (!isArrayLikeNumber(data)) {
8776
- log("[magic-context] embedding batch returned unexpected data shape");
6475
+ log2("[magic-context] embedding batch returned unexpected data shape");
8777
6476
  return Array.from({ length: expectedCount }, () => null);
8778
6477
  }
8779
6478
  const flatData = toFloat32Array(data);
8780
6479
  const dimension = result.dims?.at(-1) ?? flatData.length / expectedCount;
8781
6480
  if (!Number.isInteger(dimension) || dimension <= 0 || flatData.length !== expectedCount * dimension) {
8782
- log("[magic-context] embedding batch returned invalid dimensions");
6481
+ log2("[magic-context] embedding batch returned invalid dimensions");
8783
6482
  return Array.from({ length: expectedCount }, () => null);
8784
6483
  }
8785
6484
  const embeddings = [];
@@ -8815,7 +6514,7 @@ class LocalEmbeddingProvider {
8815
6514
  magicContextEmbeddingWorker: true,
8816
6515
  modelCacheDir: modelCacheDirForRuntime(),
8817
6516
  enforcePrivateStoragePermissions: shouldEnforcePrivateStoragePermissions(),
8818
- harness: getHarness(),
6517
+ harness: getHarness2(),
8819
6518
  model,
8820
6519
  maxInputTokens,
8821
6520
  dtype: this.dtype,
@@ -8878,7 +6577,7 @@ class LocalEmbeddingProvider {
8878
6577
  ensureStorageDirectorySync(modelCacheDir);
8879
6578
  env.cacheDir = modelCacheDir;
8880
6579
  } catch {
8881
- log("[magic-context] could not create model cache dir, using library default");
6580
+ log2("[magic-context] could not create model cache dir, using library default");
8882
6581
  }
8883
6582
  const createPipeline = transformersModule.pipeline;
8884
6583
  const lockPath = join(modelCacheDir, ".load.lock");
@@ -8907,7 +6606,7 @@ class LocalEmbeddingProvider {
8907
6606
  break;
8908
6607
  }
8909
6608
  const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
8910
- log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
6609
+ log2(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
8911
6610
  await new Promise((resolve) => setTimeout(resolve, delayMs));
8912
6611
  }
8913
6612
  }
@@ -8922,7 +6621,7 @@ class LocalEmbeddingProvider {
8922
6621
  externalDeltaAtLoad: memoryAfterLoad.external - memoryBeforeLoad.external,
8923
6622
  arrayBuffersDeltaAtLoad: memoryAfterLoad.arrayBuffers - memoryBeforeLoad.arrayBuffers
8924
6623
  });
8925
- log(`[magic-context] embedding model loaded: ${this.model}`);
6624
+ log2(`[magic-context] embedding model loaded: ${this.model}`);
8926
6625
  } else if (this.disposing) {
8927
6626
  return;
8928
6627
  } else {
@@ -9107,7 +6806,7 @@ class LocalEmbeddingProvider {
9107
6806
  try {
9108
6807
  await pipelineToDispose.dispose?.();
9109
6808
  } catch (error) {
9110
- log("[magic-context] embedding model dispose failed:", error);
6809
+ log2("[magic-context] embedding model dispose failed:", error);
9111
6810
  }
9112
6811
  })();
9113
6812
  return this.disposePromise;
@@ -9120,4 +6819,4 @@ class LocalEmbeddingProvider {
9120
6819
  }
9121
6820
  }
9122
6821
 
9123
- export { isValidLanguageCode, withContentLanguageDirective, buildPrimaryLanguageDirective, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, PROTECTED_TOKENS_MIN, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, DREAM_TASK_PROMOTION_DEFAULTS, MagicContextConfigSchema, LIVE_RELOAD_CONFIG_PATHS, deriveDefaultProtectedTokens, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, SYNAPSE_DEFAULT_MODEL, isSynapseEmbeddingTruncated, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, getSynapseBatchRequestKey, SynapseEmbeddingProvider, embeddingModelsMatch, resolveEmbeddingTextPrefixes, computeNormalizedHash, getEmbeddingProviderIdentity, dominantEmbeddingFailure, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };
6822
+ export { isValidLanguageCode, withContentLanguageDirective, buildPrimaryLanguageDirective, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, PROTECTED_TOKENS_MIN, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, DREAM_TASK_PROMOTION_DEFAULTS, MagicContextConfigSchema, LIVE_RELOAD_CONFIG_PATHS, deriveDefaultProtectedTokens, embeddingModelsMatch, resolveEmbeddingTextPrefixes, getEmbeddingProviderIdentity, dominantEmbeddingFailure, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };