@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
@@ -0,0 +1,2307 @@
1
+ import {
2
+ estimateTokens
3
+ } from "./index-1qb0z7wa.js";
4
+ import {
5
+ getHarness2
6
+ } from "./index-pavzsdc6.js";
7
+ import {
8
+ log2
9
+ } from "./index-8j7gqj40.js";
10
+
11
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
12
+ import { promises as fs2 } from "node:fs";
13
+ import { debuglog } from "node:util";
14
+
15
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
16
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
17
+
18
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
19
+ import net from "node:net";
20
+
21
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/envelope.js
22
+ var PROTOCOL_VERSION = 2;
23
+ var HEADER_LEN = 21;
24
+ var FROZEN_PREFIX_LEN = 5;
25
+ var MAX_FRAME_BODY_LEN = 64 * 1024 * 1024;
26
+ var FrameType;
27
+ (function(FrameType) {
28
+ FrameType[FrameType["Request"] = 0] = "Request";
29
+ FrameType[FrameType["Response"] = 1] = "Response";
30
+ FrameType[FrameType["Push"] = 2] = "Push";
31
+ FrameType[FrameType["StreamData"] = 3] = "StreamData";
32
+ FrameType[FrameType["StreamEnd"] = 4] = "StreamEnd";
33
+ FrameType[FrameType["Error"] = 5] = "Error";
34
+ FrameType[FrameType["Cancel"] = 6] = "Cancel";
35
+ FrameType[FrameType["Ping"] = 7] = "Ping";
36
+ FrameType[FrameType["Pong"] = 8] = "Pong";
37
+ FrameType[FrameType["Hello"] = 9] = "Hello";
38
+ FrameType[FrameType["HelloAck"] = 10] = "HelloAck";
39
+ FrameType[FrameType["Goodbye"] = 11] = "Goodbye";
40
+ })(FrameType || (FrameType = {}));
41
+ var FRAME_TYPE_MAX = FrameType.Goodbye;
42
+ function isPureHeader(ty) {
43
+ return ty === FrameType.Cancel || ty === FrameType.Ping || ty === FrameType.Pong || ty === FrameType.Goodbye;
44
+ }
45
+ var Priority;
46
+ (function(Priority) {
47
+ Priority[Priority["Passive"] = 0] = "Passive";
48
+ Priority[Priority["Interactive"] = 1] = "Interactive";
49
+ Priority[Priority["Background"] = 2] = "Background";
50
+ })(Priority || (Priority = {}));
51
+ var AdmissionClass;
52
+ (function(AdmissionClass) {
53
+ AdmissionClass[AdmissionClass["Normal"] = 0] = "Normal";
54
+ AdmissionClass[AdmissionClass["Expedite"] = 1] = "Expedite";
55
+ AdmissionClass[AdmissionClass["Sheddable"] = 2] = "Sheddable";
56
+ })(AdmissionClass || (AdmissionClass = {}));
57
+ var FLAG_BINARY = 1;
58
+ var FLAG_PRIORITY_MASK = 6;
59
+ var FLAG_PRIORITY_SHIFT = 1;
60
+ var FLAG_LAST = 8;
61
+ var FLAG_ADMISSION_MASK = 48;
62
+ var FLAG_ADMISSION_SHIFT = 4;
63
+ var FLAG_RESERVED_MASK = 128;
64
+ function buildFlags(binary, priority, last, admissionClass = AdmissionClass.Normal) {
65
+ let flags = 0;
66
+ if (binary)
67
+ flags |= FLAG_BINARY;
68
+ flags |= priority << FLAG_PRIORITY_SHIFT;
69
+ if (last)
70
+ flags |= FLAG_LAST;
71
+ flags |= admissionClass << FLAG_ADMISSION_SHIFT;
72
+ return flags;
73
+ }
74
+ function hasBinary(flags) {
75
+ return (flags & FLAG_BINARY) !== 0;
76
+ }
77
+ function encodeHeader(header) {
78
+ const buffer = new Uint8Array(HEADER_LEN);
79
+ const view = new DataView(buffer.buffer);
80
+ view.setUint32(0, header.len, true);
81
+ buffer[4] = header.ver;
82
+ buffer[5] = header.ty;
83
+ buffer[6] = header.flags;
84
+ view.setUint16(7, header.channel, true);
85
+ view.setUint32(9, header.epoch, true);
86
+ view.setBigUint64(13, header.corr, true);
87
+ return buffer;
88
+ }
89
+
90
+ class DecodeError extends Error {
91
+ code;
92
+ constructor(message, code) {
93
+ super(message);
94
+ this.code = code;
95
+ this.name = "DecodeError";
96
+ }
97
+ }
98
+ function validateHeaderFields(header) {
99
+ const len = header.len >>> 0;
100
+ const ver = header.ver >>> 0 & 255;
101
+ const typeByte = header.ty >>> 0 & 255;
102
+ const flags = header.flags >>> 0 & 255;
103
+ const channel = header.channel >>> 0 & 65535;
104
+ const epoch = header.epoch >>> 0;
105
+ BigInt.asUintN(64, header.corr);
106
+ if (ver !== PROTOCOL_VERSION)
107
+ throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
108
+ if (typeByte > FRAME_TYPE_MAX)
109
+ throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
110
+ const ty = typeByte;
111
+ if ((flags & FLAG_RESERVED_MASK) !== 0) {
112
+ throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
113
+ }
114
+ if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
115
+ throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
116
+ }
117
+ const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
118
+ if (admission === 3) {
119
+ throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
120
+ }
121
+ if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
122
+ throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
123
+ }
124
+ if (channel === 0 && epoch !== 0) {
125
+ throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
126
+ }
127
+ if (isPureHeader(ty) && len !== 0) {
128
+ throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
129
+ }
130
+ }
131
+ function decodeHeader(bytes) {
132
+ if (bytes.length < FROZEN_PREFIX_LEN) {
133
+ throw new DecodeError(`header shorter than frozen prefix: have ${bytes.length} bytes`, "too_short_for_prefix");
134
+ }
135
+ const ver = bytes[4];
136
+ if (ver !== PROTOCOL_VERSION)
137
+ throw new DecodeError(`unsupported envelope version ${ver}`, "unsupported_version");
138
+ if (bytes.length < HEADER_LEN) {
139
+ throw new DecodeError(`header too short for version: have ${bytes.length} bytes, need ${HEADER_LEN}`, "too_short_for_header");
140
+ }
141
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
142
+ const len = view.getUint32(0, true);
143
+ const typeByte = bytes[5];
144
+ if (typeByte > FRAME_TYPE_MAX)
145
+ throw new DecodeError(`unknown frame type byte ${typeByte}`, "unknown_frame_type");
146
+ const ty = typeByte;
147
+ const flags = bytes[6];
148
+ if ((flags & FLAG_RESERVED_MASK) !== 0) {
149
+ throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_flag_bits");
150
+ }
151
+ if ((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT === 3) {
152
+ throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_priority_bits");
153
+ }
154
+ const admission = (flags & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT;
155
+ if (admission === 3) {
156
+ throw new DecodeError(`reserved admission class set in flags 0b${flags.toString(2).padStart(8, "0")}`, "reserved_admission_class");
157
+ }
158
+ if (admission === AdmissionClass.Sheddable && ty !== FrameType.Push && ty !== FrameType.StreamData) {
159
+ throw new DecodeError(`SHEDDABLE admission class is illegal on ${FrameType[ty]} in flags 0b${flags.toString(2).padStart(8, "0")}`, "sheddable_illegal_frame_type");
160
+ }
161
+ const channel = view.getUint16(7, true);
162
+ const epoch = view.getUint32(9, true);
163
+ if (channel === 0 && epoch !== 0) {
164
+ throw new DecodeError(`control channel carried nonzero epoch ${epoch}`, "nonzero_epoch_on_control_channel");
165
+ }
166
+ if (isPureHeader(ty) && len !== 0) {
167
+ throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`, "pure_header_frame_with_body");
168
+ }
169
+ return { len, ver, ty, flags, channel, epoch, corr: view.getBigUint64(13, true) };
170
+ }
171
+ function buildFrame(ty, flags, channel, epoch, corr, body) {
172
+ return buildFrameWithVersion(PROTOCOL_VERSION, ty, flags, channel, epoch, corr, body);
173
+ }
174
+ function buildFrameWithVersion(ver, ty, flags, channel, epoch, corr, body) {
175
+ if (body.length > MAX_FRAME_BODY_LEN) {
176
+ throw new DecodeError(`frame body ${body.length} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
177
+ }
178
+ const header = { len: body.length, ver, ty, flags, channel, epoch, corr };
179
+ validateHeaderFields(header);
180
+ return { header, body };
181
+ }
182
+ function encodeFrame(frame) {
183
+ if (frame.header.len !== frame.body.length) {
184
+ throw new DecodeError(`frame header length ${frame.header.len} does not match body length ${frame.body.length}`, "frame_length_mismatch");
185
+ }
186
+ const header = encodeHeader(frame.header);
187
+ const output = new Uint8Array(header.length + frame.body.length);
188
+ output.set(header, 0);
189
+ output.set(frame.body, header.length);
190
+ return output;
191
+ }
192
+
193
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/socket.js
194
+ class SocketClosedError extends Error {
195
+ }
196
+
197
+ class SocketTimeoutError extends Error {
198
+ }
199
+
200
+ class SocketWriteNotQueuedError extends Error {
201
+ cause;
202
+ constructor(message, cause) {
203
+ super(message);
204
+ this.cause = cause;
205
+ }
206
+ }
207
+
208
+ class SocketWriteQueuedError extends Error {
209
+ cause;
210
+ constructor(message, cause) {
211
+ super(message);
212
+ this.cause = cause;
213
+ }
214
+ }
215
+ function toWriteBuffer(bytes) {
216
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
217
+ }
218
+ var WRITE_BORROWED = Symbol("subc.socket.writeBorrowed");
219
+ var WRITE_TRACKED_BORROWED = Symbol("subc.socket.writeTrackedBorrowed");
220
+ function writeBorrowed(socket, bytes, deadlineMs) {
221
+ const borrowed = socket[WRITE_BORROWED];
222
+ return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.write(bytes, deadlineMs);
223
+ }
224
+ function writeTrackedBorrowed(socket, bytes, deadlineMs) {
225
+ const borrowed = socket[WRITE_TRACKED_BORROWED];
226
+ return borrowed ? borrowed.call(socket, bytes, deadlineMs) : socket.writeTracked(bytes, deadlineMs);
227
+ }
228
+
229
+ class SubcSocket {
230
+ sock;
231
+ chunks = [];
232
+ buffered = 0;
233
+ waiter = null;
234
+ closedErr = null;
235
+ bufferedBytes() {
236
+ return this.buffered;
237
+ }
238
+ constructor(sock) {
239
+ this.sock = sock;
240
+ sock.on("data", (chunk) => {
241
+ this.chunks.push(chunk);
242
+ this.buffered += chunk.length;
243
+ this.tryServe();
244
+ });
245
+ const fail = (err) => {
246
+ if (!this.closedErr)
247
+ this.closedErr = err;
248
+ this.tryServe();
249
+ };
250
+ sock.on("error", (err) => fail(err instanceof Error ? err : new Error(String(err))));
251
+ sock.on("end", () => fail(new SocketClosedError("subc closed the connection")));
252
+ sock.on("close", () => fail(new SocketClosedError("subc connection closed")));
253
+ }
254
+ localPort() {
255
+ return this.sock.localPort ?? null;
256
+ }
257
+ static connect(host, port, deadlineMs) {
258
+ return new Promise((resolve, reject) => {
259
+ const sock = net.connect({ host, port });
260
+ sock.setNoDelay(true);
261
+ const timer = setTimeout(() => {
262
+ sock.destroy();
263
+ reject(new SocketTimeoutError(`timed out connecting to ${host}:${port}`));
264
+ }, Math.max(0, deadlineMs - Date.now()));
265
+ sock.once("connect", () => {
266
+ clearTimeout(timer);
267
+ resolve(new SubcSocket(sock));
268
+ });
269
+ sock.once("error", (err) => {
270
+ clearTimeout(timer);
271
+ reject(err);
272
+ });
273
+ });
274
+ }
275
+ async readFrame(headerDeadlineMs, bodyDeadline, onHeader) {
276
+ const prefix = await this.readExact(FROZEN_PREFIX_LEN, headerDeadlineMs);
277
+ const version = prefix[4];
278
+ if (version !== PROTOCOL_VERSION)
279
+ throw new DecodeError(`unsupported envelope version ${version}`, "unsupported_version");
280
+ const remainder = await this.readExact(HEADER_LEN - FROZEN_PREFIX_LEN, headerDeadlineMs);
281
+ const headerBytes = new Uint8Array(HEADER_LEN);
282
+ headerBytes.set(prefix);
283
+ headerBytes.set(remainder, FROZEN_PREFIX_LEN);
284
+ const header = decodeHeader(headerBytes);
285
+ if (header.len > MAX_FRAME_BODY_LEN) {
286
+ throw new DecodeError(`frame body ${header.len} exceeds max ${MAX_FRAME_BODY_LEN}`, "frame_body_too_large");
287
+ }
288
+ onHeader?.();
289
+ const bodyDeadlineMs = typeof bodyDeadline === "number" ? bodyDeadline : Date.now() + bodyDeadline.afterHeaderMs;
290
+ const body = header.len === 0 ? new Uint8Array(0) : await this.readExact(header.len, bodyDeadlineMs);
291
+ return { header, body };
292
+ }
293
+ readExact(n, deadlineMs) {
294
+ if (this.waiter) {
295
+ return Promise.reject(new Error("concurrent readExact is not supported"));
296
+ }
297
+ if (n === 0)
298
+ return Promise.resolve(new Uint8Array(0));
299
+ return new Promise((resolve, reject) => {
300
+ let timer = null;
301
+ if (Number.isFinite(deadlineMs)) {
302
+ const remaining = deadlineMs - Date.now();
303
+ if (remaining <= 0) {
304
+ reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
305
+ return;
306
+ }
307
+ timer = setTimeout(() => {
308
+ this.waiter = null;
309
+ reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
310
+ }, remaining);
311
+ }
312
+ this.waiter = { need: n, resolve, reject, timer };
313
+ this.tryServe();
314
+ });
315
+ }
316
+ async write(bytes, deadlineMs) {
317
+ await this.writeBuffer(Buffer.from(bytes), deadlineMs);
318
+ }
319
+ writeTracked(bytes, deadlineMs) {
320
+ return this.writeTrackedBuffer(Buffer.from(bytes), deadlineMs);
321
+ }
322
+ async[WRITE_BORROWED](bytes, deadlineMs) {
323
+ await this.writeBuffer(toWriteBuffer(bytes), deadlineMs);
324
+ }
325
+ [WRITE_TRACKED_BORROWED](bytes, deadlineMs) {
326
+ return this.writeTrackedBuffer(toWriteBuffer(bytes), deadlineMs);
327
+ }
328
+ async writeBuffer(buffer, deadlineMs) {
329
+ try {
330
+ await this.writeTrackedBuffer(buffer, deadlineMs).completed;
331
+ } catch (err) {
332
+ if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError) {
333
+ throw err.cause ?? err;
334
+ }
335
+ throw err;
336
+ }
337
+ }
338
+ writeTrackedBuffer(buffer, deadlineMs) {
339
+ if (this.closedErr) {
340
+ return {
341
+ queued: false,
342
+ completed: Promise.reject(new SocketWriteNotQueuedError("subc socket was closed before bytes could be queued", this.closedErr))
343
+ };
344
+ }
345
+ let queued = false;
346
+ let settled = false;
347
+ let timer = null;
348
+ const completed = new Promise((resolve, reject) => {
349
+ const settle = (run) => {
350
+ if (settled)
351
+ return;
352
+ settled = true;
353
+ if (timer)
354
+ clearTimeout(timer);
355
+ run();
356
+ };
357
+ const remaining = deadlineMs - Date.now();
358
+ if (remaining <= 0) {
359
+ settle(() => reject(new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", new SocketTimeoutError("timed out writing to subc"))));
360
+ return;
361
+ }
362
+ timer = setTimeout(() => {
363
+ const timeout = new SocketTimeoutError("timed out writing to subc");
364
+ 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)));
365
+ }, remaining);
366
+ try {
367
+ this.sock.write(buffer, (err) => {
368
+ settle(() => {
369
+ if (err) {
370
+ reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
371
+ } else {
372
+ resolve();
373
+ }
374
+ });
375
+ });
376
+ queued = true;
377
+ } catch (err) {
378
+ settle(() => reject(new SocketWriteNotQueuedError("subc socket write threw before bytes could be queued", err instanceof Error ? err : new Error(String(err)))));
379
+ }
380
+ });
381
+ return { queued, completed };
382
+ }
383
+ close() {
384
+ this.sock.destroy();
385
+ }
386
+ tryServe() {
387
+ const w = this.waiter;
388
+ if (!w)
389
+ return;
390
+ if (this.buffered >= w.need) {
391
+ const out = this.take(w.need);
392
+ this.waiter = null;
393
+ if (w.timer)
394
+ clearTimeout(w.timer);
395
+ w.resolve(out);
396
+ return;
397
+ }
398
+ if (this.closedErr) {
399
+ this.waiter = null;
400
+ if (w.timer)
401
+ clearTimeout(w.timer);
402
+ w.reject(this.closedErr);
403
+ }
404
+ }
405
+ take(n) {
406
+ const out = Buffer.allocUnsafe(n);
407
+ let off = 0;
408
+ while (off < n) {
409
+ const head = this.chunks[0];
410
+ const want = n - off;
411
+ if (head.length <= want) {
412
+ head.copy(out, off);
413
+ off += head.length;
414
+ this.chunks.shift();
415
+ } else {
416
+ head.copy(out, off, 0, want);
417
+ this.chunks[0] = head.subarray(want);
418
+ off += want;
419
+ }
420
+ }
421
+ this.buffered -= n;
422
+ return out;
423
+ }
424
+ }
425
+
426
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/auth.js
427
+ var NONCE_LEN = 32;
428
+ var MAX_AUTH_MESSAGE_LEN = 4096;
429
+ var SERVER_PROOF_DOMAIN = "subc-server-v1";
430
+ var CLIENT_AUTH_DOMAIN = "subc-client-v1";
431
+ var DEFAULT_CLIENT_ROLE = "client";
432
+
433
+ class AuthError extends Error {
434
+ }
435
+ function computeProof(key, domain, clientNonce, serverNonce, daemonId) {
436
+ const mac = createHmac("sha256", Buffer.from(key));
437
+ mac.update(Buffer.from(domain, "utf8"));
438
+ mac.update(Buffer.from(clientNonce));
439
+ mac.update(Buffer.from(serverNonce));
440
+ mac.update(Buffer.from(daemonId));
441
+ return new Uint8Array(mac.digest());
442
+ }
443
+ function constantTimeEq(a, b) {
444
+ if (a.length !== b.length)
445
+ return false;
446
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
447
+ }
448
+ async function writeMessage(sock, value, deadlineMs) {
449
+ const json = Buffer.from(JSON.stringify(value), "utf8");
450
+ if (json.length > MAX_AUTH_MESSAGE_LEN) {
451
+ throw new AuthError(`auth message too large: ${json.length} > ${MAX_AUTH_MESSAGE_LEN}`);
452
+ }
453
+ const lenPrefix = new Uint8Array(4);
454
+ new DataView(lenPrefix.buffer).setUint32(0, json.length, true);
455
+ await writeBorrowed(sock, lenPrefix, deadlineMs);
456
+ await writeBorrowed(sock, json, deadlineMs);
457
+ }
458
+ async function readMessage(sock, deadlineMs) {
459
+ const lenBytes = await sock.readExact(4, deadlineMs);
460
+ const len = new DataView(lenBytes.buffer, lenBytes.byteOffset, 4).getUint32(0, true);
461
+ if (len > MAX_AUTH_MESSAGE_LEN) {
462
+ throw new AuthError(`auth message too large: ${len} > ${MAX_AUTH_MESSAGE_LEN}`);
463
+ }
464
+ const body = len === 0 ? new Uint8Array(0) : await sock.readExact(len, deadlineMs);
465
+ try {
466
+ return JSON.parse(Buffer.from(body).toString("utf8"));
467
+ } catch (err) {
468
+ throw new AuthError(`auth message JSON decode failed: ${String(err)}`);
469
+ }
470
+ }
471
+ function authBytes(value, field) {
472
+ if (!Array.isArray(value)) {
473
+ throw new AuthError(`auth field '${field}' must be a byte array`);
474
+ }
475
+ for (const byte of value) {
476
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
477
+ throw new AuthError(`auth field '${field}' has invalid byte ${String(byte)}`);
478
+ }
479
+ }
480
+ return Uint8Array.from(value);
481
+ }
482
+ async function authenticateClient(sock, conn, deadlineMs) {
483
+ const clientNonce = new Uint8Array(randomBytes(NONCE_LEN));
484
+ await writeMessage(sock, { client_nonce: Array.from(clientNonce), role: DEFAULT_CLIENT_ROLE }, deadlineMs);
485
+ const proof = await readMessage(sock, deadlineMs);
486
+ const serverNonce = authBytes(proof.server_nonce, "server_nonce");
487
+ const daemonId = authBytes(proof.daemon_id, "daemon_id");
488
+ const serverProof = authBytes(proof.server_proof, "server_proof");
489
+ const expected = computeProof(conn.key, SERVER_PROOF_DOMAIN, clientNonce, serverNonce, daemonId);
490
+ if (!constantTimeEq(expected, serverProof)) {
491
+ throw new AuthError("server proof mismatch — wrong key or impostor daemon");
492
+ }
493
+ if (!constantTimeEq(daemonId, conn.daemonId)) {
494
+ throw new AuthError("daemon id mismatch — connection file points at a different daemon");
495
+ }
496
+ const clientAuth = computeProof(conn.key, CLIENT_AUTH_DOMAIN, clientNonce, serverNonce, daemonId);
497
+ await writeMessage(sock, { client_auth: Array.from(clientAuth) }, deadlineMs);
498
+ }
499
+
500
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/connection-file.js
501
+ import { promises as fs } from "node:fs";
502
+ var SCHEMA_VERSION = 1;
503
+ var MIN_KEY_LEN = 32;
504
+ var DAEMON_ID_LEN = 16;
505
+
506
+ class ConnectionFileError extends Error {
507
+ }
508
+ function toBytes(value, field) {
509
+ if (!Array.isArray(value)) {
510
+ throw new ConnectionFileError(`connection file field '${field}' must be a JSON array of bytes`);
511
+ }
512
+ for (const byte of value) {
513
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
514
+ throw new ConnectionFileError(`connection file field '${field}' has invalid byte ${String(byte)}`);
515
+ }
516
+ }
517
+ return Uint8Array.from(value);
518
+ }
519
+ function validate(info) {
520
+ if (info.schema !== SCHEMA_VERSION) {
521
+ throw new ConnectionFileError(`unsupported connection file schema ${info.schema}; expected ${SCHEMA_VERSION}`);
522
+ }
523
+ if (info.endpoints.length === 0) {
524
+ throw new ConnectionFileError("connection file must include at least one endpoint");
525
+ }
526
+ if (info.key.length < MIN_KEY_LEN) {
527
+ throw new ConnectionFileError(`connection file key is too short: ${info.key.length} bytes, need at least ${MIN_KEY_LEN}`);
528
+ }
529
+ if (info.daemonId.length !== DAEMON_ID_LEN) {
530
+ throw new ConnectionFileError(`connection file daemon_id must be ${DAEMON_ID_LEN} bytes, got ${info.daemonId.length}`);
531
+ }
532
+ }
533
+ async function verifyOwnerOnly(path) {
534
+ if (process.platform === "win32")
535
+ return;
536
+ const stat = await fs.stat(path);
537
+ const mode = stat.mode & 511;
538
+ if ((mode & 63) !== 0) {
539
+ throw new ConnectionFileError(`connection file ${path} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
540
+ }
541
+ }
542
+ async function readConnectionFile(path) {
543
+ await verifyOwnerOnly(path);
544
+ const raw = await fs.readFile(path, "utf8");
545
+ let parsed;
546
+ try {
547
+ parsed = JSON.parse(raw);
548
+ } catch (err) {
549
+ throw new ConnectionFileError(`connection file JSON read failed for ${path}: ${String(err)}`);
550
+ }
551
+ const wireVersion = parsed.wire_version;
552
+ if (wireVersion !== undefined && wireVersion !== PROTOCOL_VERSION) {
553
+ throw new ConnectionFileError(`connection file wire_version ${String(wireVersion)} but this client speaks ${PROTOCOL_VERSION}; the client library must be upgraded`);
554
+ }
555
+ const endpointsRaw = parsed.endpoints;
556
+ if (!Array.isArray(endpointsRaw)) {
557
+ throw new ConnectionFileError("connection file 'endpoints' must be an array");
558
+ }
559
+ const endpoints = endpointsRaw.map((e) => {
560
+ const ep = e;
561
+ if (typeof ep.host !== "string" || typeof ep.port !== "number") {
562
+ throw new ConnectionFileError("connection file endpoint must be { host: string, port: number }");
563
+ }
564
+ return { host: ep.host, port: ep.port };
565
+ });
566
+ const info = {
567
+ schema: parsed.schema,
568
+ endpoints,
569
+ key: toBytes(parsed.key, "key"),
570
+ daemonId: toBytes(parsed.daemon_id, "daemon_id"),
571
+ pid: parsed.pid,
572
+ daemonVer: parsed.daemon_ver ?? ""
573
+ };
574
+ validate(info);
575
+ return info;
576
+ }
577
+
578
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/route-handle.js
579
+ var connectionToken = new WeakMap;
580
+
581
+ class RouteHandle {
582
+ channel;
583
+ epoch;
584
+ constructor(channel, epoch, token) {
585
+ if (!Number.isInteger(channel) || channel <= 0 || channel > 65535) {
586
+ throw new RangeError(`route channel must be an integer in 1..65535, got ${channel}`);
587
+ }
588
+ if (!Number.isInteger(epoch) || epoch <= 0 || epoch > 4294967295) {
589
+ throw new RangeError(`route epoch must be an integer in 1..4294967295, got ${epoch}`);
590
+ }
591
+ this.channel = channel;
592
+ this.epoch = epoch;
593
+ connectionToken.set(this, token);
594
+ Object.freeze(this);
595
+ }
596
+ static create(channel, epoch, token) {
597
+ return new RouteHandle(channel, epoch, token);
598
+ }
599
+ }
600
+ function createRouteHandle(channel, epoch, token) {
601
+ const factory = RouteHandle;
602
+ return factory.create(channel, epoch, token);
603
+ }
604
+
605
+ class StaleRouteHandleError extends Error {
606
+ handle;
607
+ code = "stale_route_handle";
608
+ constructor(handle) {
609
+ super(`route handle (${handle.channel}, ${handle.epoch}) is not live on the current connection`);
610
+ this.handle = handle;
611
+ this.name = "StaleRouteHandleError";
612
+ }
613
+ }
614
+ function newConnectionToken() {
615
+ return Object.freeze({});
616
+ }
617
+ function belongsToConnection(handle, token) {
618
+ return connectionToken.get(handle) === token;
619
+ }
620
+ function sameRouteHandle(left, right) {
621
+ return left === right;
622
+ }
623
+
624
+ // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
625
+ var debug = debuglog("subc-client");
626
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 1e4;
627
+ var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
628
+ var TIMEOUT_ARBITRATION_GRACE_MS = 50;
629
+ var LIVENESS_PROBE_WINDOW_MS = 2000;
630
+ var REQUEST_DEADLINE_MARKER = "request_deadline";
631
+ var DEADLINE_NO_DROP_CODE = "deadline_exceeded_no_drop_observed";
632
+ var ROUTE_OPEN_RETRY_DEADLINE_MS = 30000;
633
+ var BODY_READ_TIMEOUT_MS = 30000;
634
+ var EMPTY_BODY = new Uint8Array(0);
635
+ var DEFAULT_MANAGED_TARGET_KIND = "management_surface";
636
+ var SUBC_MODULE_ID_ENV = "SUBC_MODULE_ID";
637
+ var SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
638
+ var DEFAULT_RECONNECT_BACKOFF = {
639
+ baseMs: 100,
640
+ capMs: 2000,
641
+ maxAttempts: 6
642
+ };
643
+
644
+ class SubcCallError extends Error {
645
+ kind;
646
+ code;
647
+ cause;
648
+ constructor(kind, message, code, cause) {
649
+ super(message);
650
+ this.kind = kind;
651
+ this.code = code;
652
+ this.cause = cause;
653
+ this.name = "SubcCallError";
654
+ }
655
+ get detail() {
656
+ return this.cause instanceof SubcError ? this.cause.detail : undefined;
657
+ }
658
+ }
659
+
660
+ class SubcError extends Error {
661
+ code;
662
+ detail;
663
+ constructor(message, code, detail) {
664
+ super(message);
665
+ this.code = code;
666
+ this.detail = detail;
667
+ }
668
+ }
669
+ function requireBinaryBody(body) {
670
+ if (body instanceof Uint8Array)
671
+ return body;
672
+ const type = body === null ? "null" : Array.isArray(body) ? "array" : typeof body;
673
+ throw new SubcError(`binary request body must be a Uint8Array; got ${type}`, "binary_body_required");
674
+ }
675
+ class SubcClient {
676
+ sock;
677
+ currentConn;
678
+ opts;
679
+ nextCorr = 1n;
680
+ pending = new Map;
681
+ lateResponses = new Map;
682
+ routes = new Map;
683
+ liveRoutes = new Map;
684
+ connectionToken = newConnectionToken();
685
+ ingressEpochDropCount = 0;
686
+ closedErr = null;
687
+ closeStarted = false;
688
+ reconnecting = null;
689
+ generation = 1;
690
+ readerActive = false;
691
+ constructor(sock, currentConn, opts) {
692
+ this.sock = sock;
693
+ this.currentConn = currentConn;
694
+ this.opts = opts;
695
+ this.readLoop(sock, this.generation);
696
+ }
697
+ get conn() {
698
+ return this.currentConn;
699
+ }
700
+ static async connect(opts) {
701
+ const normalized = normalizeConnectOptions(opts);
702
+ const opened = await SubcClient.openConnection(normalized);
703
+ return new SubcClient(opened.sock, opened.conn, normalized);
704
+ }
705
+ async catalogList(moduleId) {
706
+ const body = this.encode(moduleId === undefined ? { op: "catalog.list" } : { op: "catalog.list", module_id: moduleId });
707
+ const reply = await this.controlRpc(body);
708
+ const parsed = this.parseJson(reply);
709
+ return parsed.modules ?? [];
710
+ }
711
+ async resolveProvider(capability) {
712
+ const claimants = await this.resolveProviders(capability);
713
+ if (claimants.length === 0) {
714
+ throw new SubcError(`no catalog claimant for capability ${capability}`, "capability_unprovided");
715
+ }
716
+ if (claimants.length > 1) {
717
+ throw new SubcError(`multiple catalog claimants for capability ${capability}: ${claimants.join(", ")}`, "capability_ambiguous");
718
+ }
719
+ return claimants[0];
720
+ }
721
+ async resolveProviders(capability) {
722
+ if (!isValidCapabilityIdentifier(capability)) {
723
+ throw new SubcError(`malformed capability identifier ${JSON.stringify(capability)}`, "invalid_capability_identifier");
724
+ }
725
+ const modules = await this.catalogList();
726
+ return modules.filter((module) => module.capabilities?.provides.includes(capability) ?? false).map((module) => module.module_id).sort();
727
+ }
728
+ async routeOpen(target, identity, opts = {}) {
729
+ const consumerIdentity = routeOpenConsumerIdentity(opts);
730
+ const consumerCapabilities = opts.consumerCapabilities;
731
+ const body = this.encode({
732
+ op: "route.open",
733
+ target,
734
+ identity,
735
+ ...consumerIdentity ? { consumer_identity: consumerIdentity } : {},
736
+ ...consumerCapabilities !== undefined ? { consumer_capabilities: consumerCapabilities } : {}
737
+ });
738
+ let installed = null;
739
+ const install = (frame) => {
740
+ if (frame.header.ty !== FrameType.Response)
741
+ return true;
742
+ const parsed = this.parseJson(frame);
743
+ if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number") {
744
+ throw new SubcError(`route.open returned no route handle: ${JSON.stringify(parsed)}`);
745
+ }
746
+ installed = this.installRoute(parsed.route_channel, parsed.route_epoch);
747
+ return true;
748
+ };
749
+ const closeLateRoute = (frame) => {
750
+ if (frame.header.ty !== FrameType.Response)
751
+ return;
752
+ try {
753
+ const parsed = this.parseJson(frame);
754
+ if (typeof parsed.route_channel !== "number" || typeof parsed.route_epoch !== "number")
755
+ return;
756
+ const lateHandle = this.installRoute(parsed.route_channel, parsed.route_epoch);
757
+ this.failHandle(lateHandle, new SubcError("late route.open was closed", "route_closed"));
758
+ this.liveRoutes.delete(lateHandle.channel);
759
+ this.sendRouteGoodbye(lateHandle, true);
760
+ } catch {
761
+ this.closeConnectionAfterCleanupFailure();
762
+ }
763
+ };
764
+ await this.controlRpc(body, install, closeLateRoute);
765
+ if (!installed)
766
+ throw new SubcError("route.open response was not installed");
767
+ return installed;
768
+ }
769
+ async request(handle, body, opts = {}) {
770
+ this.assertLiveHandle(handle);
771
+ const binary = opts.binary ?? false;
772
+ const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
773
+ const priority = opts.priority ?? Priority.Interactive;
774
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
775
+ const reply = await this.send(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, undefined, undefined, binary);
776
+ return this.decodeReply(reply);
777
+ }
778
+ async call(moduleId, method, params, opts = {}) {
779
+ if (opts.binary) {
780
+ 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");
781
+ }
782
+ const body = params === undefined ? { method } : { method, params };
783
+ return await this.managedCall(moduleId, body, opts);
784
+ }
785
+ async callBinary(moduleId, body, opts = {}) {
786
+ const bytes = requireBinaryBody(body);
787
+ return this.managedCall(moduleId, bytes, { ...opts, binary: true });
788
+ }
789
+ async managedCall(moduleId, body, opts) {
790
+ let retriedUnknownChannel = false;
791
+ for (;; ) {
792
+ const routeHandle = await this.cachedRouteHandle(moduleId, opts);
793
+ try {
794
+ return await this.managedRequest(routeHandle, body, opts);
795
+ } catch (err) {
796
+ if (!(err instanceof SubcCallError))
797
+ throw this.terminalCallError("managed call failed", err);
798
+ const deadBindCode = err.code === "unknown_channel" || err.code === "stale_route_epoch";
799
+ if (deadBindCode && !retriedUnknownChannel && !this.closeStarted) {
800
+ retriedUnknownChannel = true;
801
+ this.evictRouteHandle(routeHandle);
802
+ continue;
803
+ }
804
+ if (deadBindCode && retriedUnknownChannel) {
805
+ this.evictRouteHandle(routeHandle);
806
+ }
807
+ if (err.kind === "not_sent") {
808
+ try {
809
+ await this.reconnectAfterDrop(err);
810
+ } catch (reconnectErr) {
811
+ throw this.notSentRecoveryError("managed call was not sent", reconnectErr);
812
+ }
813
+ continue;
814
+ }
815
+ if (err.kind === "outcome_unknown" && err.code !== DEADLINE_NO_DROP_CODE) {
816
+ this.scheduleReconnectAfterDrop(err);
817
+ } else if (err.kind === "outcome_unknown" && err.code === DEADLINE_NO_DROP_CODE) {
818
+ this.probeLivenessAfterDeadline();
819
+ }
820
+ throw err;
821
+ }
822
+ }
823
+ }
824
+ subscribe(handle, body, onEvent, opts = {}) {
825
+ this.assertLiveHandle(handle);
826
+ const bytes = body instanceof Uint8Array ? body : this.encode(body);
827
+ const priority = opts.priority ?? Priority.Interactive;
828
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
829
+ const corr = this.allocateCorr();
830
+ const key = pendingKey(handle, corr);
831
+ let subscriptionPending = null;
832
+ let resolveClosed = null;
833
+ const closed = new Promise((resolve, reject) => {
834
+ if (this.closedErr) {
835
+ reject(this.closedErr);
836
+ return;
837
+ }
838
+ resolveClosed = resolve;
839
+ subscriptionPending = {
840
+ handle,
841
+ resolve: () => resolve(),
842
+ reject,
843
+ onProgress: onEvent,
844
+ timer: null,
845
+ subscription: true
846
+ };
847
+ this.pending.set(key, subscriptionPending);
848
+ const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), handle.channel, handle.epoch, corr, bytes);
849
+ writeBorrowed(this.sock, encodeFrame(frame), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch((err) => {
850
+ const pending = this.pending.get(key);
851
+ if (pending)
852
+ this.rejectPending(key, pending, err instanceof Error ? err : new SubcError(String(err)));
853
+ });
854
+ });
855
+ let cancelled = false;
856
+ const unsubscribe = () => {
857
+ if (cancelled)
858
+ return;
859
+ cancelled = true;
860
+ if (subscriptionPending && resolveClosed)
861
+ this.settle(key, subscriptionPending, resolveClosed);
862
+ if (this.isLiveHandle(handle))
863
+ this.cancel(handle, corr, priority);
864
+ };
865
+ return { unsubscribe, closed };
866
+ }
867
+ cancel(handle, corr, priority = Priority.Interactive) {
868
+ this.assertLiveHandle(handle);
869
+ const cancel = buildFrame(FrameType.Cancel, buildFlags(false, priority, false), handle.channel, handle.epoch, corr, EMPTY_BODY);
870
+ writeBorrowed(this.sock, encodeFrame(cancel), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch(() => {
871
+ return;
872
+ });
873
+ }
874
+ async routePoll(handle, kind) {
875
+ this.assertLiveHandle(handle);
876
+ const body = this.encode({
877
+ op: "route.poll",
878
+ route_channel: handle.channel,
879
+ route_epoch: handle.epoch,
880
+ kind
881
+ });
882
+ const reply = await this.controlRpc(body, (frame) => {
883
+ if (frame.header.ty !== FrameType.Response)
884
+ return true;
885
+ const parsed = this.parseJson(frame);
886
+ return parsed.route_channel === handle.channel && parsed.route_epoch === handle.epoch;
887
+ });
888
+ return this.parseJson(reply);
889
+ }
890
+ async closeRoute(handle, opts = {}) {
891
+ this.assertLiveHandle(handle);
892
+ for (const [key, cached] of this.routes) {
893
+ if (cached.handle && sameRouteHandle(cached.handle, handle)) {
894
+ cached.closed = true;
895
+ cached.handle = null;
896
+ this.routes.delete(key);
897
+ }
898
+ }
899
+ if (opts.drain)
900
+ await this.drainUnaryOnHandle(handle);
901
+ this.failHandle(handle, new SubcError("route closed by closeRoute", "route_closed"));
902
+ if (this.liveRoutes.get(handle.channel) === handle)
903
+ this.liveRoutes.delete(handle.channel);
904
+ this.sendRouteGoodbye(handle);
905
+ }
906
+ async closeManagedRoute(target, identity, opts = {}) {
907
+ const key = routeCacheKey(target, identity, routeOpenConsumerIdentity(opts));
908
+ const cached = this.routes.get(key);
909
+ if (!cached)
910
+ return;
911
+ cached.closed = true;
912
+ this.routes.delete(key);
913
+ const handle = cached.handle;
914
+ cached.handle = null;
915
+ if (handle)
916
+ await this.closeRoute(handle, opts);
917
+ }
918
+ async closeRouteChannel(handle, opts = {}) {
919
+ await this.closeRoute(handle, opts);
920
+ }
921
+ close() {
922
+ this.closeStarted = true;
923
+ this.fail(new SubcError("client closed"));
924
+ this.sock.close();
925
+ }
926
+ drainUnaryOnHandle(handle) {
927
+ const waiters = [];
928
+ for (const pending of this.pending.values()) {
929
+ if (pending.handle === handle && !pending.subscription) {
930
+ waiters.push(new Promise((resolve) => {
931
+ const previous = pending.onSettle;
932
+ pending.onSettle = () => {
933
+ previous?.();
934
+ resolve();
935
+ };
936
+ }));
937
+ }
938
+ }
939
+ return Promise.all(waiters).then(() => {
940
+ return;
941
+ });
942
+ }
943
+ sendRouteGoodbye(handle, closeOnQueueFailure = false) {
944
+ this.assertLiveConnection(handle);
945
+ if (this.closedErr) {
946
+ if (closeOnQueueFailure)
947
+ this.closeConnectionAfterCleanupFailure();
948
+ return;
949
+ }
950
+ const goodbye = buildFrame(FrameType.Goodbye, buildFlags(false, Priority.Interactive, false), handle.channel, handle.epoch, 0n, EMPTY_BODY);
951
+ const write = writeTrackedBorrowed(this.sock, encodeFrame(goodbye), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS);
952
+ if (!write.queued && closeOnQueueFailure)
953
+ this.closeConnectionAfterCleanupFailure();
954
+ write.completed.catch(() => {
955
+ if (closeOnQueueFailure && !write.queued)
956
+ this.closeConnectionAfterCleanupFailure();
957
+ });
958
+ }
959
+ static async openConnection(opts) {
960
+ const conn = await readConnectionFile(opts.connectionFile);
961
+ const deadline = Date.now() + (opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);
962
+ const endpoint = conn.endpoints[0];
963
+ const sock = await SubcSocket.connect(endpoint.host, endpoint.port, deadline);
964
+ try {
965
+ await authenticateClient(sock, conn, deadline);
966
+ } catch (err) {
967
+ sock.close();
968
+ throw err;
969
+ }
970
+ return { sock, conn };
971
+ }
972
+ async controlRpc(body, acceptFrame, onLateResponse) {
973
+ return this.send(null, body, Priority.Interactive, AdmissionClass.Normal, undefined, undefined, acceptFrame, onLateResponse);
974
+ }
975
+ send(handle, body, priority, admission, timeoutMs, onProgress, acceptFrame, onLateResponse, binary = false) {
976
+ if (handle)
977
+ this.assertLiveHandle(handle);
978
+ if (this.closedErr)
979
+ return Promise.reject(this.closedErr);
980
+ let corr;
981
+ try {
982
+ corr = this.allocateCorr();
983
+ } catch (error) {
984
+ return Promise.reject(error);
985
+ }
986
+ const key = pendingKey(handle, corr);
987
+ const channel = handle?.channel ?? 0;
988
+ const epoch = handle?.epoch ?? 0;
989
+ const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), channel, epoch, corr, body);
990
+ return new Promise((resolve, reject) => {
991
+ const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
992
+ const pending = {
993
+ handle,
994
+ resolve,
995
+ reject,
996
+ onProgress,
997
+ timer: null,
998
+ acceptFrame,
999
+ onLateResponse
1000
+ };
1001
+ pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, channel, corr, ms), ms);
1002
+ this.pending.set(key, pending);
1003
+ writeBorrowed(this.sock, encodeFrame(frame), Date.now() + ms).catch((error) => {
1004
+ const current = this.pending.get(key);
1005
+ if (current)
1006
+ this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
1007
+ });
1008
+ });
1009
+ }
1010
+ arbitrateTimeout(key, pending, channel, corr, ms) {
1011
+ const settleAsTimeout = () => {
1012
+ if (pending.onLateResponse)
1013
+ this.lateResponses.set(key, pending.onLateResponse);
1014
+ this.rejectPending(key, pending, new SubcError(this.timeoutMessage(channel, corr, ms), REQUEST_DEADLINE_MARKER));
1015
+ };
1016
+ const graceDeadline = Date.now() + this.opts.timeoutArbitrationGraceMs;
1017
+ const arbitrate = () => {
1018
+ if (this.pending.get(key) !== pending)
1019
+ return;
1020
+ const readerDraining = this.readerActive || this.sock.bufferedBytes() > 0;
1021
+ if (readerDraining && Date.now() < graceDeadline) {
1022
+ setImmediate(arbitrate);
1023
+ return;
1024
+ }
1025
+ settleAsTimeout();
1026
+ };
1027
+ setImmediate(arbitrate);
1028
+ }
1029
+ async managedRequest(handle, body, opts) {
1030
+ const binary = opts.binary ?? false;
1031
+ const bytes = binary ? requireBinaryBody(body) : body instanceof Uint8Array ? body : this.encode(body);
1032
+ const priority = opts.priority ?? Priority.Interactive;
1033
+ const admission = opts.admissionClass ?? AdmissionClass.Normal;
1034
+ try {
1035
+ const reply = await this.sendManaged(handle, bytes, priority, admission, opts.timeoutMs, opts.onProgress, binary);
1036
+ return this.decodeReply(reply);
1037
+ } catch (error) {
1038
+ if (error instanceof SubcCallError)
1039
+ throw error;
1040
+ throw this.terminalCallError("managed call failed", error);
1041
+ }
1042
+ }
1043
+ sendManaged(handle, body, priority, admission, timeoutMs, onProgress, binary = false) {
1044
+ try {
1045
+ this.assertLiveHandle(handle);
1046
+ } catch (error) {
1047
+ return Promise.reject(this.notSentCallError("request used a stale route handle", error));
1048
+ }
1049
+ if (this.closedErr) {
1050
+ return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed", this.closedErr));
1051
+ }
1052
+ let corr;
1053
+ try {
1054
+ corr = this.allocateCorr();
1055
+ } catch (error) {
1056
+ return Promise.reject(this.notSentCallError("request correlation allocator was exhausted", error));
1057
+ }
1058
+ const key = pendingKey(handle, corr);
1059
+ const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), handle.channel, handle.epoch, corr, body);
1060
+ let handedToSocket = false;
1061
+ const classifyFailure = (error) => {
1062
+ if (!handedToSocket)
1063
+ return this.notSentCallError("request bytes were not queued to the subc socket", error);
1064
+ if (error instanceof SubcError && error.code === REQUEST_DEADLINE_MARKER) {
1065
+ 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);
1066
+ }
1067
+ return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error);
1068
+ };
1069
+ return new Promise((resolve, reject) => {
1070
+ const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1071
+ const pending = {
1072
+ handle,
1073
+ resolve,
1074
+ reject,
1075
+ onProgress,
1076
+ timer: null,
1077
+ classifyFailure
1078
+ };
1079
+ pending.timer = setTimeout(() => this.arbitrateTimeout(key, pending, handle.channel, corr, ms), ms);
1080
+ this.pending.set(key, pending);
1081
+ const write = writeTrackedBorrowed(this.sock, encodeFrame(frame), Date.now() + ms);
1082
+ handedToSocket = write.queued;
1083
+ write.completed.catch((error) => {
1084
+ const current = this.pending.get(key);
1085
+ if (current)
1086
+ this.rejectPending(key, current, error instanceof Error ? error : new SubcError(String(error)));
1087
+ });
1088
+ });
1089
+ }
1090
+ async cachedRouteHandle(moduleId, opts) {
1091
+ const identity = opts.identity ?? this.opts.identity;
1092
+ if (!identity) {
1093
+ throw new SubcCallError("terminal", "managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })", "missing_identity");
1094
+ }
1095
+ const target = { kind: opts.targetKind ?? this.opts.targetKind, module_id: moduleId };
1096
+ const consumerIdentity = routeOpenConsumerIdentity(opts);
1097
+ const key = routeCacheKey(target, identity, consumerIdentity);
1098
+ let cached = this.routes.get(key);
1099
+ if (!cached) {
1100
+ cached = {
1101
+ key,
1102
+ moduleId,
1103
+ target,
1104
+ identity,
1105
+ consumerIdentity,
1106
+ handle: null,
1107
+ opening: null
1108
+ };
1109
+ this.routes.set(key, cached);
1110
+ }
1111
+ if (cached.handle && this.isLiveHandle(cached.handle))
1112
+ return cached.handle;
1113
+ if (!cached.opening) {
1114
+ cached.opening = this.openCachedRoute(cached).finally(() => {
1115
+ cached.opening = null;
1116
+ });
1117
+ }
1118
+ return cached.opening;
1119
+ }
1120
+ async openCachedRoute(cached) {
1121
+ const routeRetryDeadline = Date.now() + this.opts.routeOpenRetryDeadlineMs;
1122
+ let routeRetryDelay = this.opts.reconnectBackoff.baseMs;
1123
+ let routeRetryAttempt = 0;
1124
+ for (;; ) {
1125
+ if (cached.closed)
1126
+ throw this.routeClosedDuringOpen();
1127
+ try {
1128
+ await this.ensureConnectedForManaged();
1129
+ } catch (error) {
1130
+ throw this.notSentRecoveryError("route.open could not run because reconnect failed", error);
1131
+ }
1132
+ if (cached.handle && this.isLiveHandle(cached.handle))
1133
+ return cached.handle;
1134
+ try {
1135
+ const handle = await this.routeOpen(cached.target, cached.identity, {
1136
+ consumerIdentity: cached.consumerIdentity ?? null
1137
+ });
1138
+ if (cached.closed) {
1139
+ this.liveRoutes.delete(handle.channel);
1140
+ this.sendRouteGoodbye(handle);
1141
+ throw this.routeClosedDuringOpen();
1142
+ }
1143
+ cached.handle = handle;
1144
+ return handle;
1145
+ } catch (error) {
1146
+ if (error instanceof SubcCallError && error.code === "route_closed")
1147
+ throw error;
1148
+ if (!this.closeStarted && isConsumerReconnectTransient(error)) {
1149
+ try {
1150
+ await this.reconnectAfterDrop(error);
1151
+ } catch (reconnectError) {
1152
+ throw this.notSentRecoveryError("route.open was not sent and reconnect failed", reconnectError);
1153
+ }
1154
+ continue;
1155
+ }
1156
+ if (!this.closeStarted && error instanceof SubcError && isRetryableRouteOpenCode(error.code)) {
1157
+ routeRetryAttempt += 1;
1158
+ if (Date.now() < routeRetryDeadline) {
1159
+ await this.opts.sleep(routeRetryDelay);
1160
+ routeRetryDelay = Math.min(routeRetryDelay * 2, this.opts.reconnectBackoff.capMs);
1161
+ continue;
1162
+ }
1163
+ throw this.notSentCallError(`route.open failed for module ${cached.moduleId}: ${error.code} (retry deadline exhausted after ${routeRetryAttempt} attempts)`, error);
1164
+ }
1165
+ throw this.terminalCallError(`route.open failed for module ${cached.moduleId}`, error);
1166
+ }
1167
+ }
1168
+ }
1169
+ lastInboundAtMs = 0;
1170
+ livenessProbe = null;
1171
+ hasControlPending() {
1172
+ for (const pending of this.pending.values()) {
1173
+ if (pending.handle === null)
1174
+ return true;
1175
+ }
1176
+ return false;
1177
+ }
1178
+ probeLivenessAfterDeadline() {
1179
+ if (this.livenessProbe || this.closeStarted || this.closedErr)
1180
+ return;
1181
+ if (this.hasControlPending())
1182
+ return;
1183
+ const sock = this.sock;
1184
+ const generation = this.generation;
1185
+ let corr;
1186
+ try {
1187
+ corr = this.allocateCorr();
1188
+ } catch {
1189
+ return;
1190
+ }
1191
+ const t0 = Date.now();
1192
+ const ping = buildFrame(FrameType.Ping, buildFlags(false, Priority.Interactive, false, AdmissionClass.Normal), 0, 0, corr, new Uint8Array);
1193
+ const probe = (async () => {
1194
+ await writeBorrowed(sock, encodeFrame(ping), t0 + this.opts.livenessProbeWindowMs).catch(() => {});
1195
+ await this.opts.sleep(this.opts.livenessProbeWindowMs);
1196
+ if (this.sock !== sock || this.generation !== generation || this.closeStarted)
1197
+ return;
1198
+ if (this.lastInboundAtMs >= t0)
1199
+ return;
1200
+ if (this.hasControlPending())
1201
+ return;
1202
+ 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`));
1203
+ sock.close();
1204
+ })().finally(() => {
1205
+ this.livenessProbe = null;
1206
+ });
1207
+ this.livenessProbe = probe;
1208
+ }
1209
+ async ensureConnectedForManaged() {
1210
+ if (this.closeStarted)
1211
+ throw new SubcError("client closed");
1212
+ if (this.reconnecting)
1213
+ await this.reconnecting;
1214
+ if (this.closedErr)
1215
+ await this.reconnectAfterDrop(this.closedErr);
1216
+ }
1217
+ scheduleReconnectAfterDrop(err) {
1218
+ if (this.closeStarted || this.reconnecting)
1219
+ return;
1220
+ this.reconnectAfterDrop(err).catch(() => {});
1221
+ }
1222
+ reconnectAfterDrop(trigger) {
1223
+ if (this.closeStarted)
1224
+ return Promise.reject(new SubcError("client closed"));
1225
+ if (this.reconnecting)
1226
+ return this.reconnecting;
1227
+ const promise = this.reconnectWithRetry(trigger).finally(() => {
1228
+ if (this.reconnecting === promise)
1229
+ this.reconnecting = null;
1230
+ });
1231
+ this.reconnecting = promise;
1232
+ return promise;
1233
+ }
1234
+ async reconnectWithRetry(_trigger) {
1235
+ let attempt = 0;
1236
+ let delay = this.opts.reconnectBackoff.baseMs;
1237
+ for (;; ) {
1238
+ if (this.closeStarted)
1239
+ throw new SubcError("client closed");
1240
+ attempt += 1;
1241
+ try {
1242
+ const opened = await SubcClient.openConnection(this.opts);
1243
+ if (this.closeStarted) {
1244
+ opened.sock.close();
1245
+ throw new SubcError("client closed");
1246
+ }
1247
+ this.replaceConnection(opened);
1248
+ await this.reopenCachedRoutes();
1249
+ return;
1250
+ } catch (err) {
1251
+ if (!isConsumerReconnectTransient(err) || attempt >= this.opts.reconnectBackoff.maxAttempts) {
1252
+ if (err instanceof AuthError && attempt > 1) {
1253
+ 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`);
1254
+ }
1255
+ throw err;
1256
+ }
1257
+ await this.opts.sleep(delay);
1258
+ delay = Math.min(delay * 2, this.opts.reconnectBackoff.capMs);
1259
+ }
1260
+ }
1261
+ }
1262
+ replaceConnection(opened) {
1263
+ this.sock.close();
1264
+ this.sock = opened.sock;
1265
+ this.currentConn = opened.conn;
1266
+ this.closedErr = null;
1267
+ this.generation += 1;
1268
+ this.connectionToken = newConnectionToken();
1269
+ this.liveRoutes.clear();
1270
+ this.lateResponses.clear();
1271
+ this.nextCorr = 1n;
1272
+ this.readLoop(opened.sock, this.generation);
1273
+ }
1274
+ async reopenCachedRoutes() {
1275
+ const routeKeys = [...this.routes.keys()];
1276
+ for (const key of routeKeys) {
1277
+ const cached = this.routes.get(key);
1278
+ if (cached)
1279
+ cached.handle = null;
1280
+ }
1281
+ for (const key of routeKeys) {
1282
+ const cached = this.routes.get(key);
1283
+ if (!cached || cached.closed)
1284
+ continue;
1285
+ try {
1286
+ const handle = await this.routeOpen(cached.target, cached.identity, {
1287
+ consumerIdentity: cached.consumerIdentity ?? null
1288
+ });
1289
+ if (cached.closed) {
1290
+ this.liveRoutes.delete(handle.channel);
1291
+ this.sendRouteGoodbye(handle);
1292
+ continue;
1293
+ }
1294
+ cached.handle = handle;
1295
+ } catch (error) {
1296
+ if (isRouteOpenRefusal(error)) {
1297
+ this.routes.delete(key);
1298
+ continue;
1299
+ }
1300
+ throw error;
1301
+ }
1302
+ }
1303
+ }
1304
+ timeoutMessage(channel, corr, ms) {
1305
+ const port = this.sock.localPort();
1306
+ const where = port === null ? "channel" : `local_port=${port} channel`;
1307
+ return `request on ${where} ${channel} corr ${corr} timed out after ${ms}ms`;
1308
+ }
1309
+ routeClosedDuringOpen() {
1310
+ return new SubcCallError("not_sent", "route was closed before route.open completed", "route_closed");
1311
+ }
1312
+ async readLoop(sock, generation) {
1313
+ try {
1314
+ for (;; ) {
1315
+ this.readerActive = false;
1316
+ const frame = await sock.readFrame(Number.POSITIVE_INFINITY, { afterHeaderMs: BODY_READ_TIMEOUT_MS }, () => {
1317
+ this.readerActive = true;
1318
+ });
1319
+ try {
1320
+ if (this.sock === sock && this.generation === generation)
1321
+ this.dispatch(frame);
1322
+ } finally {
1323
+ this.readerActive = false;
1324
+ }
1325
+ }
1326
+ } catch (error) {
1327
+ if (this.sock === sock && this.generation === generation) {
1328
+ this.fail(error instanceof Error ? error : new SubcError(String(error)));
1329
+ }
1330
+ }
1331
+ }
1332
+ dispatch(frame) {
1333
+ this.lastInboundAtMs = Date.now();
1334
+ if (frame.header.channel === 0 && frame.header.ty === FrameType.Push) {
1335
+ const observer = this.opts.onControlPush;
1336
+ if (observer) {
1337
+ let parsed = null;
1338
+ try {
1339
+ const body = this.parseJson(frame);
1340
+ if (body && typeof body.op === "string")
1341
+ parsed = { op: body.op, body };
1342
+ } catch {}
1343
+ if (parsed) {
1344
+ try {
1345
+ observer(parsed);
1346
+ } catch {}
1347
+ }
1348
+ }
1349
+ return;
1350
+ }
1351
+ let handle = null;
1352
+ if (frame.header.channel !== 0) {
1353
+ handle = this.liveRoutes.get(frame.header.channel) ?? null;
1354
+ if (!handle || handle.epoch !== frame.header.epoch) {
1355
+ this.ingressEpochDropCount += 1;
1356
+ return;
1357
+ }
1358
+ }
1359
+ const key = pendingKey(handle, frame.header.corr);
1360
+ const pending = this.pending.get(key);
1361
+ if (pending) {
1362
+ if (pending.acceptFrame && !pending.acceptFrame(frame))
1363
+ return;
1364
+ switch (frame.header.ty) {
1365
+ case FrameType.Push:
1366
+ case FrameType.StreamData:
1367
+ try {
1368
+ pending.onProgress?.(frame.body);
1369
+ } catch {}
1370
+ return;
1371
+ case FrameType.Response:
1372
+ case FrameType.StreamEnd:
1373
+ this.settle(key, pending, () => pending.resolve(frame));
1374
+ return;
1375
+ case FrameType.Error:
1376
+ this.settle(key, pending, () => pending.reject(this.errorFromFrame(frame)));
1377
+ return;
1378
+ default:
1379
+ return;
1380
+ }
1381
+ }
1382
+ const late = this.lateResponses.get(key);
1383
+ if (late && (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error)) {
1384
+ this.lateResponses.delete(key);
1385
+ late(frame);
1386
+ return;
1387
+ }
1388
+ if (frame.header.ty === FrameType.Goodbye && handle) {
1389
+ this.failHandle(handle, new SubcError("route closed by subc (GOODBYE)", "route_closed"));
1390
+ if (this.liveRoutes.get(handle.channel) === handle)
1391
+ this.liveRoutes.delete(handle.channel);
1392
+ this.evictRouteHandle(handle);
1393
+ return;
1394
+ }
1395
+ if (frame.header.ty === FrameType.Response || frame.header.ty === FrameType.Error || frame.header.ty === FrameType.StreamEnd) {
1396
+ 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() ?? "?");
1397
+ }
1398
+ }
1399
+ settle(key, pending, run) {
1400
+ if (this.pending.get(key) !== pending)
1401
+ return false;
1402
+ this.pending.delete(key);
1403
+ if (pending.timer)
1404
+ clearTimeout(pending.timer);
1405
+ run();
1406
+ pending.onSettle?.();
1407
+ return true;
1408
+ }
1409
+ rejectPending(key, pending, err) {
1410
+ this.settle(key, pending, () => pending.reject(pending.classifyFailure?.(err) ?? err));
1411
+ }
1412
+ errorFromFrame(frame) {
1413
+ try {
1414
+ const parsed = JSON.parse(Buffer.from(frame.body).toString("utf8"));
1415
+ return new SubcError(parsed.message ?? "subc error", parsed.code, parsed.detail);
1416
+ } catch {
1417
+ return new SubcError(Buffer.from(frame.body).toString("utf8") || "subc error");
1418
+ }
1419
+ }
1420
+ evictRouteHandle(handle) {
1421
+ for (const cached of this.routes.values()) {
1422
+ if (cached.handle && sameRouteHandle(cached.handle, handle))
1423
+ cached.handle = null;
1424
+ }
1425
+ }
1426
+ failHandle(handle, error) {
1427
+ for (const [key, pending] of this.pending) {
1428
+ if (pending.handle && sameRouteHandle(pending.handle, handle))
1429
+ this.rejectPending(key, pending, error);
1430
+ }
1431
+ }
1432
+ fail(err) {
1433
+ if (!this.closedErr)
1434
+ this.closedErr = err;
1435
+ for (const [key, pending] of this.pending) {
1436
+ this.rejectPending(key, pending, err);
1437
+ }
1438
+ }
1439
+ notSentCallError(message, cause) {
1440
+ return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1441
+ }
1442
+ outcomeUnknownCallError(message, cause) {
1443
+ return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1444
+ }
1445
+ terminalCallError(message, cause) {
1446
+ if (cause instanceof SubcCallError)
1447
+ return cause;
1448
+ return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
1449
+ }
1450
+ notSentRecoveryError(message, cause) {
1451
+ if (cause instanceof SubcCallError)
1452
+ return cause;
1453
+ if (isConsumerReconnectTransient(cause))
1454
+ return this.notSentCallError(message, cause);
1455
+ return this.terminalCallError(message, cause);
1456
+ }
1457
+ get droppedIngressFrames() {
1458
+ return this.ingressEpochDropCount;
1459
+ }
1460
+ installRoute(channel, epoch) {
1461
+ const handle = createRouteHandle(channel, epoch, this.connectionToken);
1462
+ this.liveRoutes.set(channel, handle);
1463
+ return handle;
1464
+ }
1465
+ isLiveHandle(handle) {
1466
+ return belongsToConnection(handle, this.connectionToken) && this.liveRoutes.get(handle.channel) === handle;
1467
+ }
1468
+ assertLiveConnection(handle) {
1469
+ if (!belongsToConnection(handle, this.connectionToken))
1470
+ throw new StaleRouteHandleError(handle);
1471
+ }
1472
+ assertLiveHandle(handle) {
1473
+ if (!this.isLiveHandle(handle))
1474
+ throw new StaleRouteHandleError(handle);
1475
+ }
1476
+ allocateCorr() {
1477
+ const maximum = 0xffffffffffffffffn;
1478
+ if (this.nextCorr > maximum) {
1479
+ const error = new SubcError("channel-0 correlation id allocator exhausted", "corr_exhausted");
1480
+ this.fail(error);
1481
+ this.sock.close();
1482
+ this.scheduleReconnectAfterDrop(error);
1483
+ throw error;
1484
+ }
1485
+ const corr = this.nextCorr;
1486
+ this.nextCorr += 1n;
1487
+ return corr;
1488
+ }
1489
+ closeConnectionAfterCleanupFailure() {
1490
+ const error = new SubcError("late route cleanup could not be queued", "late_route_cleanup_failed");
1491
+ this.fail(error);
1492
+ this.sock.close();
1493
+ this.scheduleReconnectAfterDrop(error);
1494
+ }
1495
+ encode(value) {
1496
+ return Buffer.from(JSON.stringify(value), "utf8");
1497
+ }
1498
+ decodeReply(frame) {
1499
+ return hasBinary(frame.header.flags) ? frame.body : this.parseJson(frame);
1500
+ }
1501
+ parseJson(frame) {
1502
+ const b = frame.body;
1503
+ return JSON.parse(Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("utf8"));
1504
+ }
1505
+ }
1506
+ function isConsumerReconnectTransient(err) {
1507
+ if (err instanceof SocketClosedError || err instanceof SocketTimeoutError)
1508
+ return true;
1509
+ if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError)
1510
+ return true;
1511
+ if (err instanceof SubcCallError)
1512
+ return err.kind === "not_sent" || err.kind === "outcome_unknown";
1513
+ if (err instanceof AuthError)
1514
+ return true;
1515
+ if (err instanceof SubcError || err instanceof ConnectionFileError)
1516
+ return false;
1517
+ const code = errorCode(err);
1518
+ return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
1519
+ }
1520
+ function isRouteOpenRefusal(err) {
1521
+ return err instanceof SubcError && typeof err.code === "string";
1522
+ }
1523
+ function isRetryableRouteOpenCode(code) {
1524
+ if (code === "capability_forbidden")
1525
+ return false;
1526
+ return code === "unknown_module" || code === "module_reloading" || code === "module_warming" || code === "target_unavailable" || code === "module_timeout";
1527
+ }
1528
+ async function connectionFileExists(path) {
1529
+ try {
1530
+ await fs2.access(path);
1531
+ return true;
1532
+ } catch {
1533
+ return false;
1534
+ }
1535
+ }
1536
+ function normalizeConnectOptions(opts) {
1537
+ return {
1538
+ connectionFile: opts.connectionFile,
1539
+ handshakeTimeoutMs: opts.handshakeTimeoutMs,
1540
+ identity: opts.identity,
1541
+ targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
1542
+ reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
1543
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
1544
+ routeOpenRetryDeadlineMs: opts.routeOpenRetryDeadlineMs ?? ROUTE_OPEN_RETRY_DEADLINE_MS,
1545
+ timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS,
1546
+ livenessProbeWindowMs: opts.livenessProbeWindowMs ?? LIVENESS_PROBE_WINDOW_MS,
1547
+ onControlPush: opts.onControlPush
1548
+ };
1549
+ }
1550
+ function isValidCapabilityIdentifier(identifier) {
1551
+ if (/\s/u.test(identifier))
1552
+ return false;
1553
+ const separator = identifier.indexOf("/v");
1554
+ if (separator <= 0 || identifier.indexOf("/v", separator + 1) !== -1)
1555
+ return false;
1556
+ const name = identifier.slice(0, separator);
1557
+ const version = identifier.slice(separator + 2);
1558
+ if (new TextEncoder().encode(name).byteLength > 64 || version.length === 0)
1559
+ return false;
1560
+ if (!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test(name) && !/^[a-z]$/u.test(name))
1561
+ return false;
1562
+ if (name.includes("--"))
1563
+ return false;
1564
+ if (!/^\d+$/u.test(version) || version.length > 1 && version.startsWith("0"))
1565
+ return false;
1566
+ const numericVersion = Number(version);
1567
+ return Number.isSafeInteger(numericVersion) && numericVersion >= 1 && numericVersion <= 4294967295;
1568
+ }
1569
+ function routeCacheKey(target, identity, consumerIdentity) {
1570
+ const consumerPart = consumerIdentity ? `${consumerIdentity.module_id}\x00${consumerIdentity.launch_nonce}` : "";
1571
+ return `${target.kind}\x00${target.module_id}\x00${identity.project_root}\x00${identity.harness}\x00${identity.session}\x00${consumerPart}`;
1572
+ }
1573
+ function routeOpenConsumerIdentity(opts = {}) {
1574
+ if (opts.consumerIdentity !== undefined)
1575
+ return opts.consumerIdentity ?? undefined;
1576
+ const moduleId = process.env[SUBC_MODULE_ID_ENV];
1577
+ const launchNonce = process.env[SUBC_LAUNCH_NONCE_ENV];
1578
+ if (!moduleId || !launchNonce)
1579
+ return;
1580
+ return { module_id: moduleId, launch_nonce: launchNonce };
1581
+ }
1582
+ function errorCode(err) {
1583
+ if (typeof err === "object" && err !== null && "code" in err) {
1584
+ const code = err.code;
1585
+ if (typeof code === "string")
1586
+ return code;
1587
+ }
1588
+ return;
1589
+ }
1590
+ function causeMessage(cause) {
1591
+ if (cause === undefined)
1592
+ return "";
1593
+ return `: ${cause instanceof Error ? cause.message : String(cause)}`;
1594
+ }
1595
+ function pendingKey(handle, corr) {
1596
+ return handle ? `${handle.channel}:${handle.epoch}:${corr}` : `0:0:${corr}`;
1597
+ }
1598
+ // src/features/magic-context/memory/embedding-synapse.ts
1599
+ import { createHash } from "node:crypto";
1600
+ var SYNAPSE_DEFAULT_MODEL = "gte-modernbert-base-f16";
1601
+ var SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS = 3000;
1602
+ var SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS = 120000;
1603
+ var SYNAPSE_CERTIFICATION_REFUSAL_REASONS = new Set([
1604
+ "not_certified",
1605
+ "probe_required",
1606
+ "migration_required"
1607
+ ]);
1608
+ var embeddingRowMetadata = new WeakMap;
1609
+ function isSynapseEmbeddingTruncated(vector) {
1610
+ return embeddingRowMetadata.get(vector)?.truncated === true;
1611
+ }
1612
+ function toSynapseLaneDescriptor(metadata) {
1613
+ const tokenBudget = metadata.recommended_token_budget;
1614
+ return {
1615
+ lane: metadata.model,
1616
+ ...metadata.device_class ? { device_class: metadata.device_class } : {},
1617
+ max_tokens: metadata.max_tokens,
1618
+ max_tokens_source: metadata.max_tokens_source,
1619
+ ...metadata.bucket_ladder ? { bucket_ladder: [...metadata.bucket_ladder] } : {},
1620
+ ...metadata.dims ? { dims: metadata.dims } : {},
1621
+ ...metadata.dtype ? { dtype: metadata.dtype } : {},
1622
+ ...typeof metadata.certified === "boolean" ? { certified: metadata.certified } : {},
1623
+ ...metadata.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: metadata.warm_load_cost_hint_ms } : {},
1624
+ ...metadata.recommended_batch ? {
1625
+ recommended_batch: {
1626
+ rows: metadata.recommended_batch,
1627
+ ...tokenBudget !== undefined ? { token_budget: tokenBudget } : {}
1628
+ }
1629
+ } : {},
1630
+ warm: metadata.max_tokens_source === "runtime_bucket" || metadata.max_tokens_source === "worker_bucket"
1631
+ };
1632
+ }
1633
+ function formatSynapseLaneDescriptor(descriptor) {
1634
+ const certified = descriptor.certified === undefined ? "unknown" : String(descriptor.certified);
1635
+ 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"}`;
1636
+ }
1637
+
1638
+ class SynapseEmbeddingError extends Error {
1639
+ code;
1640
+ retryAfterMs;
1641
+ permanent;
1642
+ refusalReason;
1643
+ constructor(code, message, options) {
1644
+ super(message, options?.cause === undefined ? undefined : { cause: options.cause });
1645
+ this.name = "SynapseEmbeddingError";
1646
+ this.code = code;
1647
+ this.permanent = options?.permanent ?? isPermanentSynapseCode(code);
1648
+ this.retryAfterMs = options?.retryAfterMs ?? (this.permanent ? undefined : 100);
1649
+ this.refusalReason = options?.refusalReason;
1650
+ }
1651
+ }
1652
+ function isPermanentSynapseCode(code) {
1653
+ 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";
1654
+ }
1655
+ function asRecord(value) {
1656
+ return value !== null && typeof value === "object" ? value : null;
1657
+ }
1658
+ function responseBody(value) {
1659
+ const record = asRecord(value);
1660
+ const result = asRecord(record?.result);
1661
+ const payload = asRecord(result?.payload ?? record?.payload);
1662
+ return {
1663
+ ...record ?? {},
1664
+ ...result ?? {},
1665
+ ...payload ?? {}
1666
+ };
1667
+ }
1668
+ function readRetryAfter(value) {
1669
+ const record = asRecord(value);
1670
+ const candidate = record?.retry_after_ms ?? record?.retryAfterMs;
1671
+ if (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)
1672
+ return;
1673
+ return Math.ceil(candidate);
1674
+ }
1675
+ function readErrorCode(value) {
1676
+ const record = asRecord(value);
1677
+ if (typeof record?.code === "string")
1678
+ return record.code;
1679
+ if (value instanceof Error && "code" in value && typeof value.code === "string") {
1680
+ return value.code;
1681
+ }
1682
+ return;
1683
+ }
1684
+ function readCertificationRefusalReason(value) {
1685
+ if (!(value instanceof SubcCallError))
1686
+ return;
1687
+ const detail = value.detail;
1688
+ if (typeof detail === "string")
1689
+ return detail;
1690
+ const record = asRecord(detail);
1691
+ return typeof record?.reason === "string" ? record.reason : undefined;
1692
+ }
1693
+ function classifyError(value) {
1694
+ if (value instanceof SynapseEmbeddingError)
1695
+ return value;
1696
+ const code = readErrorCode(value) ?? (value instanceof Error ? value.name : "transport");
1697
+ const normalized = code.toLowerCase();
1698
+ const refusalReason = readCertificationRefusalReason(value);
1699
+ let mapped = "transport";
1700
+ if (normalized.includes("queue_full"))
1701
+ mapped = "queue_full";
1702
+ else if (normalized.includes("model_loading"))
1703
+ mapped = "model_loading";
1704
+ else if (normalized.includes("timeout") || normalized.includes("deadline"))
1705
+ mapped = "timeout";
1706
+ else if (normalized.includes("artifact_invalid"))
1707
+ mapped = "artifact_invalid";
1708
+ else if (normalized.includes("substitution"))
1709
+ mapped = "substitution_rejected";
1710
+ else if (normalized === "certification_refused")
1711
+ mapped = "certification_refused";
1712
+ else if (normalized.includes("not_certified"))
1713
+ mapped = "not_certified";
1714
+ else if (normalized.includes("probe_required"))
1715
+ mapped = "probe_required";
1716
+ else if (normalized.includes("idempotency_conflict"))
1717
+ mapped = "idempotency_conflict";
1718
+ else if (normalized.includes("needs_reauth"))
1719
+ mapped = "needs_reauth";
1720
+ else if (normalized.includes("schema"))
1721
+ mapped = "schema_violation";
1722
+ else if (normalized.includes("module_restarted") || normalized.includes("module restarted"))
1723
+ mapped = "module_restarted";
1724
+ const message = value instanceof Error ? value.message : String(value);
1725
+ return new SynapseEmbeddingError(mapped, message, {
1726
+ retryAfterMs: readRetryAfter(value) ?? (isPermanentSynapseCode(mapped) ? undefined : 100),
1727
+ cause: value,
1728
+ refusalReason
1729
+ });
1730
+ }
1731
+ function embeddingFailureFor(error) {
1732
+ const typedReason = error.refusalReason;
1733
+ if (typedReason !== undefined && SYNAPSE_CERTIFICATION_REFUSAL_REASONS.has(typedReason) || error.code === "not_certified" || error.code === "probe_required") {
1734
+ return {
1735
+ class: "certification_refusal",
1736
+ reason: `SYNAPSE certification refused embedding: ${typedReason ?? error.code}`,
1737
+ retryable: false
1738
+ };
1739
+ }
1740
+ if (error.code === "certification_refused") {
1741
+ return {
1742
+ class: "certification_refusal",
1743
+ reason: `SYNAPSE certification refused embedding: ${typedReason ?? "unknown reason"}`,
1744
+ retryable: false
1745
+ };
1746
+ }
1747
+ if (typedReason === "needs_reauth" || typedReason === "needs_reauth_expired") {
1748
+ return {
1749
+ class: "credential_required",
1750
+ reason: "SYNAPSE requires reauthentication",
1751
+ retryable: false
1752
+ };
1753
+ }
1754
+ if (error.code === "substitution_rejected") {
1755
+ return { class: "substitution_rejected", reason: error.message, retryable: false };
1756
+ }
1757
+ if (error.code === "schema_violation" || error.code === "artifact_invalid") {
1758
+ return { class: "invalid_envelope", reason: error.message, retryable: false };
1759
+ }
1760
+ return { class: "transport_error", reason: error.message, retryable: !error.permanent };
1761
+ }
1762
+ function wait(ms) {
1763
+ return new Promise((resolve) => setTimeout(resolve, ms));
1764
+ }
1765
+ function sha256(value) {
1766
+ return createHash("sha256").update(value).digest("hex");
1767
+ }
1768
+ function stableJson(value) {
1769
+ if (Array.isArray(value))
1770
+ return `[${value.map(stableJson).join(",")}]`;
1771
+ if (value && typeof value === "object") {
1772
+ return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
1773
+ }
1774
+ return JSON.stringify(value);
1775
+ }
1776
+ function getSynapseLaneIdentity(model, fingerprint) {
1777
+ return `synapse:v1:${sha256(stableJson({ model, fingerprint }))}`;
1778
+ }
1779
+ function getSynapseBatchRequestKey(args) {
1780
+ return sha256(stableJson({
1781
+ op: "embed.batch",
1782
+ model: args.model,
1783
+ required_fingerprint: args.fingerprint,
1784
+ required_epoch: args.tableEpoch,
1785
+ allow_equivalent: false,
1786
+ accept_declared: false,
1787
+ ids: args.items.map((item) => item.id),
1788
+ content_sha256: args.items.map((item) => item.contentSha256),
1789
+ ...args.purpose === "query" ? { purpose: args.purpose } : {}
1790
+ }));
1791
+ }
1792
+ function hashContent(text) {
1793
+ return sha256(text);
1794
+ }
1795
+ function extractCatalogEntries(value) {
1796
+ const body = responseBody(value);
1797
+ const raw = Array.isArray(body.models) ? body.models : Array.isArray(body.entries) ? body.entries : Array.isArray(value) ? value : [];
1798
+ const envelopeEpoch = typeof body.table_epoch === "number" && Number.isInteger(body.table_epoch) ? body.table_epoch : undefined;
1799
+ const maxTokenSources = new Set([
1800
+ "runtime_bucket",
1801
+ "worker_bucket",
1802
+ "catalog",
1803
+ "catalog_unloaded"
1804
+ ]);
1805
+ return raw.flatMap((entry) => {
1806
+ const record = asRecord(entry);
1807
+ if (!record)
1808
+ return [];
1809
+ const model = typeof record.model === "string" && record.model.length > 0 ? record.model : typeof record.model_id === "string" ? record.model_id : "";
1810
+ const fingerprint = typeof record.fingerprint === "string" && record.fingerprint.length > 0 ? record.fingerprint : Array.isArray(record.fingerprints) && typeof record.fingerprints[0] === "string" ? record.fingerprints[0] : "";
1811
+ const entryEpoch = record.table_epoch ?? record.tableEpoch;
1812
+ const tableEpoch = typeof entryEpoch === "number" && Number.isInteger(entryEpoch) ? entryEpoch : envelopeEpoch;
1813
+ const maxTokens = record.max_tokens;
1814
+ const maxTokensSource = record.max_tokens_source;
1815
+ 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)) {
1816
+ return [];
1817
+ }
1818
+ const dims = record.dims ?? record.dimensions;
1819
+ const rawBatch = record.recommended_batch ?? record.recommendedBatch;
1820
+ const batchRecord = asRecord(rawBatch);
1821
+ const recommendedBatch = typeof rawBatch === "number" ? rawBatch : batchRecord ? batchRecord.rows : undefined;
1822
+ const recommendedTokenBudget = batchRecord ? batchRecord.token_budget : undefined;
1823
+ const bucketLadder = Array.isArray(record.bucket_ladder) ? record.bucket_ladder.filter((bucket) => typeof bucket === "number" && Number.isInteger(bucket) && bucket > 0) : undefined;
1824
+ const state = typeof record.state === "string" ? record.state : undefined;
1825
+ const warmLoadCostHint = record.warm_load_cost_hint_ms;
1826
+ return [
1827
+ {
1828
+ model,
1829
+ fingerprint,
1830
+ table_epoch: tableEpoch,
1831
+ max_tokens: maxTokens,
1832
+ max_tokens_source: maxTokensSource,
1833
+ ...bucketLadder && bucketLadder.length > 0 ? { bucket_ladder: [...new Set(bucketLadder)].sort((a, b) => a - b) } : {},
1834
+ ...typeof dims === "number" && Number.isInteger(dims) && dims > 0 ? { dims } : {},
1835
+ ...typeof record.dtype === "string" && record.dtype.length > 0 ? { dtype: record.dtype } : {},
1836
+ ...typeof record.device_class === "string" && record.device_class.length > 0 ? { device_class: record.device_class } : {},
1837
+ ...typeof recommendedBatch === "number" && recommendedBatch > 0 ? { recommended_batch: Math.floor(recommendedBatch) } : {},
1838
+ ...typeof recommendedTokenBudget === "number" && recommendedTokenBudget > 0 ? { recommended_token_budget: Math.floor(recommendedTokenBudget) } : {},
1839
+ ...record.provenance !== undefined ? { provenance: record.provenance } : {},
1840
+ ...typeof record.certified === "boolean" ? { certified: record.certified } : {},
1841
+ ...typeof warmLoadCostHint === "number" && Number.isFinite(warmLoadCostHint) && warmLoadCostHint >= 0 ? { warm_load_cost_hint_ms: warmLoadCostHint } : {},
1842
+ ...typeof record.status === "string" ? { status: record.status } : state ? { status: state } : {}
1843
+ }
1844
+ ];
1845
+ });
1846
+ }
1847
+ function extractVector(value) {
1848
+ const body = responseBody(value);
1849
+ const item = Array.isArray(body.vectors) ? asRecord(body.vectors[0]) : null;
1850
+ const raw = item?.vector;
1851
+ if (!item || !Array.isArray(raw) || raw.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
1852
+ return null;
1853
+ }
1854
+ const disclosure = Array.isArray(body.truncation_disclosures) ? asRecord(body.truncation_disclosures[0]) : null;
1855
+ return { vector: Float32Array.from(raw), item, disclosure, metadata: body };
1856
+ }
1857
+ function extractBatchItems(value) {
1858
+ const body = responseBody(value);
1859
+ const raw = Array.isArray(body.vectors) ? body.vectors : Array.isArray(body.items) ? body.items : Array.isArray(body.results) ? body.results : [];
1860
+ return raw.flatMap((item) => {
1861
+ const record = asRecord(item);
1862
+ return record ? [record] : [];
1863
+ });
1864
+ }
1865
+ function extractTruncationDisclosures(value) {
1866
+ const body = responseBody(value);
1867
+ if (!Array.isArray(body.truncation_disclosures))
1868
+ return [];
1869
+ return body.truncation_disclosures.map((disclosure) => asRecord(disclosure));
1870
+ }
1871
+ function validateWireRow(item, disclosure, expected) {
1872
+ const submittedSha256 = item.submitted_sha256;
1873
+ const contentSha256 = item.content_sha256;
1874
+ const expectedSubmittedSha256 = hashContent(expected.text);
1875
+ if (typeof submittedSha256 !== "string") {
1876
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted submitted_sha256`);
1877
+ }
1878
+ if (submittedSha256 !== expectedSubmittedSha256) {
1879
+ throw new SynapseEmbeddingError("schema_violation", `Synapse submitted hash mismatch for item ${expected.id}`);
1880
+ }
1881
+ if (typeof contentSha256 !== "string") {
1882
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} omitted content_sha256`);
1883
+ }
1884
+ const hashesDiffer = contentSha256 !== submittedSha256;
1885
+ const disclosedTruncation = disclosure?.truncated === true;
1886
+ const effectiveTokens = disclosure?.effective_tokens;
1887
+ if (disclosure && (typeof disclosure.truncated !== "boolean" || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0)) {
1888
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} returned an invalid truncation disclosure`);
1889
+ }
1890
+ if (hashesDiffer) {
1891
+ if (!disclosedTruncation || typeof effectiveTokens !== "number" || !Number.isInteger(effectiveTokens) || effectiveTokens < 0) {
1892
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} changed content without a valid truncation disclosure`);
1893
+ }
1894
+ } else if (disclosedTruncation) {
1895
+ throw new SynapseEmbeddingError("schema_violation", `Synapse item ${expected.id} disclosed truncation but returned matching hashes`);
1896
+ }
1897
+ return {
1898
+ truncated: hashesDiffer,
1899
+ submittedSha256,
1900
+ contentSha256,
1901
+ ...typeof effectiveTokens === "number" && Number.isInteger(effectiveTokens) && effectiveTokens >= 0 ? { effectiveTokens } : {}
1902
+ };
1903
+ }
1904
+ var sharedClient = null;
1905
+ var sharedClientFile = null;
1906
+ var sharedClientPromise = null;
1907
+ var factoryClients = new WeakMap;
1908
+ async function getSharedClient(options) {
1909
+ if (options.clientFactory) {
1910
+ let promise = factoryClients.get(options.clientFactory);
1911
+ if (!promise) {
1912
+ promise = options.clientFactory();
1913
+ factoryClients.set(options.clientFactory, promise);
1914
+ }
1915
+ return promise;
1916
+ }
1917
+ if (sharedClient && sharedClientFile === options.connectionFile)
1918
+ return sharedClient;
1919
+ if (sharedClientPromise && sharedClientFile === options.connectionFile)
1920
+ return sharedClientPromise;
1921
+ sharedClientFile = options.connectionFile;
1922
+ sharedClientPromise = SubcClient.connect({ connectionFile: options.connectionFile }).then((client) => {
1923
+ sharedClient = client;
1924
+ return client;
1925
+ });
1926
+ return sharedClientPromise;
1927
+ }
1928
+
1929
+ class SynapseEmbeddingProvider {
1930
+ modelId;
1931
+ metadata;
1932
+ get maxInputTokens() {
1933
+ return this.metadata?.max_tokens;
1934
+ }
1935
+ options;
1936
+ client = null;
1937
+ initialized = false;
1938
+ initializing = null;
1939
+ permanentFailure = false;
1940
+ lastFailureReason = null;
1941
+ batchLimit = 16;
1942
+ tokenBudget = null;
1943
+ constructor(options) {
1944
+ this.options = options;
1945
+ const model = options.model || SYNAPSE_DEFAULT_MODEL;
1946
+ const fingerprint = options.fingerprint ?? "";
1947
+ const descriptor = options.descriptor;
1948
+ this.metadata = options.metadata ? {
1949
+ ...options.metadata,
1950
+ bucket_ladder: options.metadata.bucket_ladder ? [...options.metadata.bucket_ladder] : undefined
1951
+ } : fingerprint && Number.isInteger(options.tableEpoch) && descriptor ? {
1952
+ model,
1953
+ fingerprint,
1954
+ table_epoch: options.tableEpoch,
1955
+ max_tokens: descriptor.max_tokens,
1956
+ max_tokens_source: descriptor.max_tokens_source,
1957
+ ...descriptor.bucket_ladder ? { bucket_ladder: [...descriptor.bucket_ladder] } : {},
1958
+ ...options.dims ?? descriptor.dims ? { dims: options.dims ?? descriptor.dims } : {},
1959
+ ...descriptor.dtype ? { dtype: descriptor.dtype } : {},
1960
+ ...descriptor.device_class ? { device_class: descriptor.device_class } : {},
1961
+ ...options.recommendedBatch ?? descriptor.recommended_batch?.rows ? {
1962
+ recommended_batch: Math.max(1, Math.floor(options.recommendedBatch ?? descriptor.recommended_batch?.rows))
1963
+ } : {},
1964
+ ...options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget ? {
1965
+ recommended_token_budget: Math.max(1, Math.floor(options.recommendedTokenBudget ?? descriptor.recommended_batch?.token_budget))
1966
+ } : {},
1967
+ ...options.provenance !== undefined ? { provenance: options.provenance } : {},
1968
+ ...typeof descriptor.certified === "boolean" ? { certified: descriptor.certified } : {},
1969
+ ...descriptor.warm_load_cost_hint_ms !== undefined ? { warm_load_cost_hint_ms: descriptor.warm_load_cost_hint_ms } : {},
1970
+ laneIdentity: getSynapseLaneIdentity(model, fingerprint)
1971
+ } : null;
1972
+ this.modelId = this.metadata?.laneIdentity ?? "synapse:v1:pending";
1973
+ this.batchLimit = this.metadata?.recommended_batch ?? 16;
1974
+ this.tokenBudget = this.metadata?.recommended_token_budget ?? null;
1975
+ }
1976
+ nextPage(items, start) {
1977
+ const hardEnd = Math.min(items.length, start + this.batchLimit);
1978
+ if (this.tokenBudget === null)
1979
+ return items.slice(start, hardEnd);
1980
+ let end = start;
1981
+ let tokens = 0;
1982
+ while (end < hardEnd) {
1983
+ tokens += estimateTokens(items[end].text);
1984
+ if (tokens > this.tokenBudget && end > start)
1985
+ break;
1986
+ end += 1;
1987
+ }
1988
+ return items.slice(start, Math.max(end, start + 1));
1989
+ }
1990
+ static async discover(options) {
1991
+ const provider = new SynapseEmbeddingProvider(options);
1992
+ if (!await provider.initialize() || !provider.metadata) {
1993
+ throw new SynapseEmbeddingError("not_certified", "Synapse lane is not ready");
1994
+ }
1995
+ return provider.metadata;
1996
+ }
1997
+ async initialize() {
1998
+ if (this.initialized)
1999
+ return true;
2000
+ if (this.permanentFailure)
2001
+ return false;
2002
+ if (this.initializing)
2003
+ return this.initializing;
2004
+ this.initializing = (async () => {
2005
+ try {
2006
+ if (!this.options.clientFactory && !await connectionFileExists(this.options.connectionFile)) {
2007
+ throw new SynapseEmbeddingError("transport", `Synapse connection file is unavailable: ${this.options.connectionFile}`);
2008
+ }
2009
+ this.client = await getSharedClient(this.options);
2010
+ if (!this.metadata) {
2011
+ const discovered = await this.callWithRetry("models.list", {}, this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, false);
2012
+ const entries = extractCatalogEntries(discovered);
2013
+ const requested = this.options.model?.trim() || SYNAPSE_DEFAULT_MODEL;
2014
+ const entry = entries.find((candidate) => candidate.model === requested);
2015
+ if (!entry) {
2016
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse models.list did not return requested model ${requested}`);
2017
+ }
2018
+ if (entry.certified === false || entry.status === "not_certified") {
2019
+ throw new SynapseEmbeddingError("not_certified", `Synapse model ${entry.model} is not certified`);
2020
+ }
2021
+ const metadata = {
2022
+ ...entry,
2023
+ laneIdentity: getSynapseLaneIdentity(entry.model, entry.fingerprint)
2024
+ };
2025
+ this.metadata = metadata;
2026
+ this.modelId = metadata.laneIdentity;
2027
+ this.batchLimit = metadata.recommended_batch ?? this.batchLimit;
2028
+ this.tokenBudget = metadata.recommended_token_budget ?? this.tokenBudget;
2029
+ }
2030
+ this.initialized = true;
2031
+ this.recordSuccess();
2032
+ return true;
2033
+ } catch (error) {
2034
+ const classified = classifyError(error);
2035
+ this.recordFailure(classified);
2036
+ if (classified.permanent) {
2037
+ this.permanentFailure = true;
2038
+ log2(`[magic-context] Synapse lane disabled: ${classified.code}: ${classified.message}`);
2039
+ } else {
2040
+ log2(`[magic-context] Synapse lane unavailable: ${classified.message}`);
2041
+ }
2042
+ this.initialized = false;
2043
+ return false;
2044
+ } finally {
2045
+ this.initializing = null;
2046
+ }
2047
+ })();
2048
+ return this.initializing;
2049
+ }
2050
+ async embed(text, signal, purpose = "passage") {
2051
+ if (!await this.initialize() || signal?.aborted || !this.metadata)
2052
+ return null;
2053
+ if (estimateTokens(text) > this.metadata.max_tokens)
2054
+ return null;
2055
+ try {
2056
+ const id = "query";
2057
+ const value = await this.callWithRetry("embed.query", this.requestConstraints({
2058
+ id,
2059
+ text,
2060
+ purpose,
2061
+ deadline_ms: this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS
2062
+ }), this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, true, signal);
2063
+ const extracted = extractVector(value);
2064
+ if (!extracted) {
2065
+ throw new SynapseEmbeddingError("schema_violation", "Synapse query returned no vector row");
2066
+ }
2067
+ if (extracted.item.id !== id) {
2068
+ throw new SynapseEmbeddingError("schema_violation", `Synapse query returned unexpected item ${String(extracted.item.id)}`);
2069
+ }
2070
+ const rowMetadata = validateWireRow(extracted.item, extracted.disclosure, { id, text });
2071
+ this.validateResponse(extracted.metadata, extracted.vector.length);
2072
+ embeddingRowMetadata.set(extracted.vector, rowMetadata);
2073
+ this.recordSuccess();
2074
+ return extracted.vector;
2075
+ } catch (error) {
2076
+ this.logCallFailure(error, "embed.query");
2077
+ return null;
2078
+ }
2079
+ }
2080
+ async embedBatch(texts, signal, purpose = "passage") {
2081
+ if (texts.length === 0)
2082
+ return [];
2083
+ const items = texts.map((text, index) => ({
2084
+ id: `item:${index}`,
2085
+ text,
2086
+ contentSha256: hashContent(text)
2087
+ }));
2088
+ const map = await this.embedItems(items, signal, purpose);
2089
+ return items.map((item) => map.get(item.id) ?? null);
2090
+ }
2091
+ async embedItems(items, signal, purpose = "passage") {
2092
+ const output = new Map;
2093
+ if (items.length === 0 || !await this.initialize() || !this.metadata || signal?.aborted) {
2094
+ return output;
2095
+ }
2096
+ const maxTokens = this.metadata.max_tokens;
2097
+ const eligibleItems = items.filter((item) => estimateTokens(item.text) <= maxTokens).map((item) => ({ ...item, contentSha256: hashContent(item.text) }));
2098
+ for (let start = 0;start < eligibleItems.length; ) {
2099
+ if (signal?.aborted || this.permanentFailure)
2100
+ break;
2101
+ const page = this.nextPage(eligibleItems, start);
2102
+ start += page.length;
2103
+ try {
2104
+ const requestKey = this.requestKey(page, purpose);
2105
+ let body = {};
2106
+ let restarted = false;
2107
+ for (;; ) {
2108
+ try {
2109
+ body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey, purpose), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
2110
+ const first = responseBody(body);
2111
+ const jobId = typeof first.job_id === "string" ? first.job_id : null;
2112
+ if (jobId)
2113
+ body = await this.pollBatch(jobId, requestKey, signal);
2114
+ break;
2115
+ } catch (error) {
2116
+ const classified = classifyError(error);
2117
+ if (classified.code !== "module_restarted" || restarted)
2118
+ throw classified;
2119
+ restarted = true;
2120
+ }
2121
+ }
2122
+ const batchEnvelope = responseBody(body);
2123
+ const disclosures = extractTruncationDisclosures(body);
2124
+ for (const [index, item] of extractBatchItems(body).entries()) {
2125
+ const id = typeof item.id === "string" ? item.id : "";
2126
+ const vector = item.vector ?? item.embedding;
2127
+ if (!id || !Array.isArray(vector) || vector.some((component) => typeof component !== "number" || !Number.isFinite(component))) {
2128
+ throw new SynapseEmbeddingError("schema_violation", "Synapse batch item is malformed");
2129
+ }
2130
+ const expected = page.find((candidate) => candidate.id === id);
2131
+ if (!expected) {
2132
+ throw new SynapseEmbeddingError("schema_violation", `Synapse returned unknown item ${id}`);
2133
+ }
2134
+ const rowMetadata = validateWireRow(item, disclosures[index] ?? null, expected);
2135
+ const vectorArray = Float32Array.from(vector);
2136
+ this.validateResponse({ ...batchEnvelope, ...item }, vectorArray.length);
2137
+ embeddingRowMetadata.set(vectorArray, rowMetadata);
2138
+ output.set(id, vectorArray);
2139
+ this.recordSuccess();
2140
+ }
2141
+ } catch (error) {
2142
+ const classified = classifyError(error);
2143
+ this.logCallFailure(classified, "embed.batch");
2144
+ if (classified.code === "idempotency_conflict" || classified.code === "schema_violation") {
2145
+ throw classified;
2146
+ }
2147
+ if (classified.permanent) {
2148
+ this.permanentFailure = true;
2149
+ this.initialized = false;
2150
+ break;
2151
+ }
2152
+ }
2153
+ }
2154
+ return output;
2155
+ }
2156
+ async dispose() {
2157
+ this.initialized = false;
2158
+ this.client = null;
2159
+ }
2160
+ isLoaded() {
2161
+ return this.initialized;
2162
+ }
2163
+ getLastFailureReason() {
2164
+ return this.lastFailureReason;
2165
+ }
2166
+ requestConstraints(extra) {
2167
+ const metadata = this.metadata;
2168
+ if (!metadata)
2169
+ return extra;
2170
+ return {
2171
+ ...extra,
2172
+ model: metadata.model,
2173
+ required_fingerprint: metadata.fingerprint,
2174
+ required_epoch: metadata.table_epoch,
2175
+ allow_equivalent: false,
2176
+ accept_declared: false
2177
+ };
2178
+ }
2179
+ batchRequest(items, requestKey, purpose) {
2180
+ return this.requestConstraints({
2181
+ items: items.map((item) => ({
2182
+ id: item.id,
2183
+ text: item.text,
2184
+ content_sha256: item.contentSha256
2185
+ })),
2186
+ request_key: requestKey,
2187
+ purpose
2188
+ });
2189
+ }
2190
+ requestKey(items, purpose) {
2191
+ if (!this.metadata)
2192
+ throw new SynapseEmbeddingError("transport", "Synapse metadata is unavailable");
2193
+ return getSynapseBatchRequestKey({
2194
+ model: this.metadata.model,
2195
+ fingerprint: this.metadata.fingerprint,
2196
+ tableEpoch: this.metadata.table_epoch,
2197
+ items,
2198
+ purpose
2199
+ });
2200
+ }
2201
+ async pollBatch(jobId, requestKey, signal) {
2202
+ let cursor = null;
2203
+ const allItems = [];
2204
+ const allDisclosures = [];
2205
+ for (;; ) {
2206
+ if (signal?.aborted)
2207
+ return {};
2208
+ const body = await this.callWithRetry("embed.result", this.requestConstraints({
2209
+ job_id: jobId,
2210
+ cursor,
2211
+ request_key: requestKey
2212
+ }), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
2213
+ const parsed = responseBody(body);
2214
+ const items = extractBatchItems(body);
2215
+ const disclosures = extractTruncationDisclosures(body);
2216
+ allItems.push(...items);
2217
+ allDisclosures.push(...items.map((_, index) => disclosures[index] ?? null));
2218
+ const nextCursor = parsed.next_cursor ?? parsed.cursor;
2219
+ const done = parsed.done === true || parsed.complete === true || nextCursor === undefined || nextCursor === null;
2220
+ if (done) {
2221
+ return {
2222
+ ...parsed,
2223
+ vectors: allItems,
2224
+ truncation_disclosures: allDisclosures
2225
+ };
2226
+ }
2227
+ cursor = nextCursor;
2228
+ }
2229
+ }
2230
+ async callWithRetry(method, params, timeoutMs, retryEmbeddings, signal) {
2231
+ let attempt = 0;
2232
+ for (;; ) {
2233
+ if (signal?.aborted)
2234
+ throw new SynapseEmbeddingError("transport", "Synapse request aborted");
2235
+ try {
2236
+ if (!this.client)
2237
+ throw new SynapseEmbeddingError("transport", "Synapse client is unavailable");
2238
+ return await this.client.call(this.options.moduleId ?? "synapse", method, params, {
2239
+ timeoutMs,
2240
+ targetKind: "management_surface",
2241
+ identity: {
2242
+ project_root: this.options.projectRoot,
2243
+ harness: getHarness2(),
2244
+ session: this.options.session
2245
+ }
2246
+ });
2247
+ } catch (error) {
2248
+ const classified = classifyError(error);
2249
+ if (classified.code === "idempotency_conflict")
2250
+ throw classified;
2251
+ const outcomeUnknown = error instanceof SubcCallError && error.kind === "outcome_unknown";
2252
+ const retryable = !classified.permanent && (retryEmbeddings || !outcomeUnknown);
2253
+ if (!retryable || attempt >= 3)
2254
+ throw classified;
2255
+ const delay = classified.retryAfterMs ?? Math.min(2000, 100 * 2 ** attempt);
2256
+ attempt += 1;
2257
+ await wait(delay);
2258
+ }
2259
+ }
2260
+ }
2261
+ validateResponse(body, dims) {
2262
+ const metadata = this.metadata;
2263
+ if (!metadata) {
2264
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse lane metadata missing");
2265
+ }
2266
+ if (metadata.dims === undefined) {
2267
+ const envelopeDims = body.dims;
2268
+ if (typeof envelopeDims === "number" && envelopeDims !== dims) {
2269
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse envelope declares ${envelopeDims} dimensions but the vector has ${dims}`);
2270
+ }
2271
+ metadata.dims = dims;
2272
+ }
2273
+ if (dims !== metadata.dims) {
2274
+ throw new SynapseEmbeddingError("artifact_invalid", `Synapse returned ${dims} dimensions, expected ${metadata.dims}`);
2275
+ }
2276
+ const fingerprint = body.fingerprint ?? body.served_fingerprint;
2277
+ if (typeof fingerprint !== "string") {
2278
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served fingerprint");
2279
+ }
2280
+ if (fingerprint !== metadata.fingerprint) {
2281
+ throw new SynapseEmbeddingError("substitution_rejected", `Synapse fingerprint changed from ${metadata.fingerprint} to ${fingerprint}`);
2282
+ }
2283
+ const epoch = body.table_epoch ?? body.tableEpoch;
2284
+ if (typeof epoch !== "number") {
2285
+ throw new SynapseEmbeddingError("artifact_invalid", "Synapse response omitted the served table epoch");
2286
+ }
2287
+ if (epoch !== metadata.table_epoch) {
2288
+ throw new SynapseEmbeddingError("substitution_rejected", `Synapse table epoch changed from ${metadata.table_epoch} to ${epoch}`);
2289
+ }
2290
+ }
2291
+ logCallFailure(error, operation) {
2292
+ const classified = classifyError(error);
2293
+ this.recordFailure(classified);
2294
+ if (classified.permanent)
2295
+ this.permanentFailure = true;
2296
+ const suffix = classified.retryAfterMs === undefined ? "" : ` retry_after_ms=${classified.retryAfterMs}`;
2297
+ log2(`[magic-context] Synapse ${operation} failed: ${classified.code}${suffix}: ${classified.message}`);
2298
+ }
2299
+ recordFailure(error) {
2300
+ this.lastFailureReason = embeddingFailureFor(error);
2301
+ }
2302
+ recordSuccess() {
2303
+ this.lastFailureReason = null;
2304
+ }
2305
+ }
2306
+
2307
+ export { Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, SYNAPSE_DEFAULT_MODEL, isSynapseEmbeddingTruncated, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, getSynapseLaneIdentity, getSynapseBatchRequestKey, SynapseEmbeddingProvider };