memindex 0.0.0-stage → 1.0.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 (247) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +17 -0
  3. package/.claude-plugin/plugin.json +24 -0
  4. package/.codex-plugin/plugin.json +46 -0
  5. package/.qoder-plugin/plugin.json +15 -0
  6. package/LICENSE +202 -0
  7. package/NOTICE +8 -0
  8. package/README.md +123 -2
  9. package/dist/bug-report/index.js +248 -0
  10. package/dist/npx-cli/index.js +10465 -0
  11. package/dist/opencode-plugin/index.js +79 -0
  12. package/dist/pi-extension/LICENSE.txt +21 -0
  13. package/dist/pi-extension/TYPEBOX-LICENSE.txt +23 -0
  14. package/dist/pi-extension/TYPEBOX-PROVENANCE.json +13 -0
  15. package/dist/pi-extension/UPSTREAM-LICENSE.txt +202 -0
  16. package/dist/pi-extension/UPSTREAM-NOTICE.txt +8 -0
  17. package/dist/pi-extension/index.js +13 -0
  18. package/integrations/dsh/LICENSE +220 -0
  19. package/integrations/dsh/NOTICE +11 -0
  20. package/integrations/dsh/THIRD-PARTY-LICENSES.txt +233 -0
  21. package/integrations/dsh/cordis.patch.yml +2 -0
  22. package/integrations/dsh/lib/index.js +85 -0
  23. package/integrations/dsh/package.json +22 -0
  24. package/integrations/dsh/transcript-schema.json +59 -0
  25. package/integrations/hermes/memindex/README.md +61 -0
  26. package/integrations/hermes/memindex/__init__.py +234 -0
  27. package/integrations/hermes/memindex/client.py +622 -0
  28. package/integrations/hermes/memindex/plugin.yaml +8 -0
  29. package/integrations/omp/README.md +109 -0
  30. package/integrations/omp/hooks/memindex.ts +273 -0
  31. package/integrations/openclaw/Dockerfile.e2e +46 -0
  32. package/integrations/openclaw/SKILL.md +432 -0
  33. package/integrations/openclaw/TESTING.md +279 -0
  34. package/integrations/openclaw/dist/index.js +21 -0
  35. package/integrations/openclaw/e2e-verify.sh +222 -0
  36. package/integrations/openclaw/install.sh +1815 -0
  37. package/integrations/openclaw/openclaw.plugin.json +105 -0
  38. package/integrations/openclaw/package.json +21 -0
  39. package/integrations/openclaw/skills/agent-cost-report/CHECKSUMS.txt +50 -0
  40. package/integrations/openclaw/skills/agent-cost-report/SKILL.md +241 -0
  41. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/__init__.py +1 -0
  42. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/behavior.py +303 -0
  43. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/classify.py +83 -0
  44. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/costs.py +119 -0
  45. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/devices.py +88 -0
  46. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/evidence.py +160 -0
  47. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/labels.py +115 -0
  48. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/measure.py +89 -0
  49. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/mistakes.py +310 -0
  50. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/patterns.py +391 -0
  51. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/period.py +98 -0
  52. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/prices.py +95 -0
  53. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/render.py +586 -0
  54. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/rollup.py +355 -0
  55. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/rules.json +4 -0
  56. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/rules.py +76 -0
  57. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/sample.py +45 -0
  58. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/snapshot.py +53 -0
  59. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/sync.py +79 -0
  60. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/transcripts.py +126 -0
  61. package/integrations/openclaw/skills/agent-cost-report/scripts/acr/wins.py +341 -0
  62. package/integrations/openclaw/skills/agent-cost-report/scripts/acr.py +219 -0
  63. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/_db.py +49 -0
  64. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/_paths.py +9 -0
  65. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonl +4 -0
  66. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/make_report_fixtures.py +46 -0
  67. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/prices_sample.json +6 -0
  68. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonl +8 -0
  69. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonl +1 -0
  70. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-1day.json +823 -0
  71. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-30day.json +2213 -0
  72. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-7day.json +1252 -0
  73. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-empty.json +536 -0
  74. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-session.json +662 -0
  75. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_behavior.py +299 -0
  76. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_devices.py +99 -0
  77. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_labels.py +96 -0
  78. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_measure.py +120 -0
  79. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_pdf_windows.py +54 -0
  80. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_period.py +137 -0
  81. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_prices.py +126 -0
  82. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_render.py +238 -0
  83. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_render_encoding.py +70 -0
  84. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_rollup.py +263 -0
  85. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_snapshot.py +63 -0
  86. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_sync.py +52 -0
  87. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_transcript_encoding.py +109 -0
  88. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_transcripts.py +151 -0
  89. package/integrations/openclaw/skills/agent-cost-report/scripts/tests/test_wins.py +222 -0
  90. package/integrations/openclaw/src/index.test.ts +1247 -0
  91. package/integrations/openclaw/src/index.ts +1173 -0
  92. package/integrations/openclaw/test-e2e.sh +40 -0
  93. package/integrations/openclaw/test-install.sh +2022 -0
  94. package/integrations/openclaw/test-sse-consumer.js +98 -0
  95. package/integrations/openclaw/tsconfig.json +27 -0
  96. package/integrations/pi/THIRD-PARTY-LICENSE.txt +21 -0
  97. package/integrations/pi/TYPEBOX-LICENSE.txt +23 -0
  98. package/integrations/pi/TYPEBOX-PROVENANCE.json +13 -0
  99. package/package.json +224 -4
  100. package/plugin/.claude-plugin/plugin.json +24 -0
  101. package/plugin/.codex-plugin/plugin.json +46 -0
  102. package/plugin/.mcp.json +12 -0
  103. package/plugin/.qoder-plugin/plugin.json +15 -0
  104. package/plugin/bun.lock +161 -0
  105. package/plugin/hooks/bugfixes-2026-01-10.md +92 -0
  106. package/plugin/hooks/codex-hooks.json +79 -0
  107. package/plugin/hooks/hooks.json +134 -0
  108. package/plugin/hooks/qoder-hooks.json +97 -0
  109. package/plugin/hooks/qoder-repo-hooks.json +97 -0
  110. package/plugin/modes/code--ar.json +24 -0
  111. package/plugin/modes/code--bn.json +24 -0
  112. package/plugin/modes/code--chill.json +8 -0
  113. package/plugin/modes/code--cs.json +24 -0
  114. package/plugin/modes/code--da.json +24 -0
  115. package/plugin/modes/code--de.json +24 -0
  116. package/plugin/modes/code--el.json +24 -0
  117. package/plugin/modes/code--es.json +24 -0
  118. package/plugin/modes/code--fi.json +24 -0
  119. package/plugin/modes/code--fr.json +24 -0
  120. package/plugin/modes/code--he.json +24 -0
  121. package/plugin/modes/code--hi.json +24 -0
  122. package/plugin/modes/code--hu.json +24 -0
  123. package/plugin/modes/code--id.json +24 -0
  124. package/plugin/modes/code--it.json +24 -0
  125. package/plugin/modes/code--ja.json +24 -0
  126. package/plugin/modes/code--ko.json +24 -0
  127. package/plugin/modes/code--nl.json +24 -0
  128. package/plugin/modes/code--no.json +24 -0
  129. package/plugin/modes/code--pl.json +24 -0
  130. package/plugin/modes/code--pt-br.json +24 -0
  131. package/plugin/modes/code--ro.json +24 -0
  132. package/plugin/modes/code--ru.json +24 -0
  133. package/plugin/modes/code--sv.json +24 -0
  134. package/plugin/modes/code--th.json +24 -0
  135. package/plugin/modes/code--tr.json +24 -0
  136. package/plugin/modes/code--uk.json +24 -0
  137. package/plugin/modes/code--ur.json +25 -0
  138. package/plugin/modes/code--vi.json +24 -0
  139. package/plugin/modes/code--zh.json +24 -0
  140. package/plugin/modes/code.json +146 -0
  141. package/plugin/package.json +76 -0
  142. package/plugin/qoder.mcp.json +12 -0
  143. package/plugin/scripts/bun-runner.js +305 -0
  144. package/plugin/scripts/context-generator.cjs +125 -0
  145. package/plugin/scripts/context-generator.cjs.map +6 -0
  146. package/plugin/scripts/mcp-server.cjs +337 -0
  147. package/plugin/scripts/mcp-server.cjs.map +6 -0
  148. package/plugin/scripts/qoder-hook-launcher.cjs +114 -0
  149. package/plugin/scripts/server-service.cjs +10305 -0
  150. package/plugin/scripts/server-service.cjs.map +6 -0
  151. package/plugin/scripts/statusline-counts.js +42 -0
  152. package/plugin/scripts/transcript-watcher.cjs +59 -0
  153. package/plugin/scripts/transcript-watcher.cjs.map +6 -0
  154. package/plugin/scripts/version-check.js +399 -0
  155. package/plugin/scripts/worker-service.cjs +3196 -0
  156. package/plugin/scripts/worker-service.cjs.map +6 -0
  157. package/plugin/scripts/worker-wrapper.cjs +2 -0
  158. package/plugin/skills/agent-cost-report/CHECKSUMS.txt +50 -0
  159. package/plugin/skills/agent-cost-report/SKILL.md +241 -0
  160. package/plugin/skills/agent-cost-report/scripts/acr/__init__.py +1 -0
  161. package/plugin/skills/agent-cost-report/scripts/acr/behavior.py +303 -0
  162. package/plugin/skills/agent-cost-report/scripts/acr/classify.py +83 -0
  163. package/plugin/skills/agent-cost-report/scripts/acr/costs.py +119 -0
  164. package/plugin/skills/agent-cost-report/scripts/acr/devices.py +88 -0
  165. package/plugin/skills/agent-cost-report/scripts/acr/evidence.py +160 -0
  166. package/plugin/skills/agent-cost-report/scripts/acr/labels.py +115 -0
  167. package/plugin/skills/agent-cost-report/scripts/acr/measure.py +89 -0
  168. package/plugin/skills/agent-cost-report/scripts/acr/mistakes.py +310 -0
  169. package/plugin/skills/agent-cost-report/scripts/acr/patterns.py +391 -0
  170. package/plugin/skills/agent-cost-report/scripts/acr/period.py +98 -0
  171. package/plugin/skills/agent-cost-report/scripts/acr/prices.py +95 -0
  172. package/plugin/skills/agent-cost-report/scripts/acr/render.py +586 -0
  173. package/plugin/skills/agent-cost-report/scripts/acr/rollup.py +355 -0
  174. package/plugin/skills/agent-cost-report/scripts/acr/rules.json +4 -0
  175. package/plugin/skills/agent-cost-report/scripts/acr/rules.py +76 -0
  176. package/plugin/skills/agent-cost-report/scripts/acr/sample.py +45 -0
  177. package/plugin/skills/agent-cost-report/scripts/acr/snapshot.py +53 -0
  178. package/plugin/skills/agent-cost-report/scripts/acr/sync.py +79 -0
  179. package/plugin/skills/agent-cost-report/scripts/acr/transcripts.py +126 -0
  180. package/plugin/skills/agent-cost-report/scripts/acr/wins.py +341 -0
  181. package/plugin/skills/agent-cost-report/scripts/acr.py +219 -0
  182. package/plugin/skills/agent-cost-report/scripts/tests/_db.py +49 -0
  183. package/plugin/skills/agent-cost-report/scripts/tests/_paths.py +9 -0
  184. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonl +4 -0
  185. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/make_report_fixtures.py +46 -0
  186. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/prices_sample.json +6 -0
  187. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonl +8 -0
  188. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonl +1 -0
  189. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-1day.json +823 -0
  190. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-30day.json +2213 -0
  191. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-7day.json +1252 -0
  192. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-empty.json +536 -0
  193. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-session.json +662 -0
  194. package/plugin/skills/agent-cost-report/scripts/tests/test_behavior.py +299 -0
  195. package/plugin/skills/agent-cost-report/scripts/tests/test_devices.py +99 -0
  196. package/plugin/skills/agent-cost-report/scripts/tests/test_labels.py +96 -0
  197. package/plugin/skills/agent-cost-report/scripts/tests/test_measure.py +120 -0
  198. package/plugin/skills/agent-cost-report/scripts/tests/test_pdf_windows.py +54 -0
  199. package/plugin/skills/agent-cost-report/scripts/tests/test_period.py +137 -0
  200. package/plugin/skills/agent-cost-report/scripts/tests/test_prices.py +126 -0
  201. package/plugin/skills/agent-cost-report/scripts/tests/test_render.py +238 -0
  202. package/plugin/skills/agent-cost-report/scripts/tests/test_render_encoding.py +70 -0
  203. package/plugin/skills/agent-cost-report/scripts/tests/test_rollup.py +263 -0
  204. package/plugin/skills/agent-cost-report/scripts/tests/test_snapshot.py +63 -0
  205. package/plugin/skills/agent-cost-report/scripts/tests/test_sync.py +52 -0
  206. package/plugin/skills/agent-cost-report/scripts/tests/test_transcript_encoding.py +109 -0
  207. package/plugin/skills/agent-cost-report/scripts/tests/test_transcripts.py +151 -0
  208. package/plugin/skills/agent-cost-report/scripts/tests/test_wins.py +222 -0
  209. package/plugin/skills/babysit/SKILL.md +87 -0
  210. package/plugin/skills/design-is/SKILL.md +312 -0
  211. package/plugin/skills/do/SKILL.md +45 -0
  212. package/plugin/skills/handoff/SKILL.md +121 -0
  213. package/plugin/skills/how-it-works/SKILL.md +22 -0
  214. package/plugin/skills/how-it-works/onboarding-explainer.md +17 -0
  215. package/plugin/skills/knowledge-agent/SKILL.md +80 -0
  216. package/plugin/skills/learn-codebase/SKILL.md +21 -0
  217. package/plugin/skills/make-plan/SKILL.md +67 -0
  218. package/plugin/skills/mem-search/SKILL.md +93 -0
  219. package/plugin/skills/mode-creator/SKILL.md +122 -0
  220. package/plugin/skills/mode-creator/evals/evals.json +23 -0
  221. package/plugin/skills/mode-creator/references/mode-authoring.md +94 -0
  222. package/plugin/skills/mode-creator/scripts/install-mode.mjs +244 -0
  223. package/plugin/skills/oh-my-issues/SKILL.md +226 -0
  224. package/plugin/skills/pathfinder/SKILL.md +111 -0
  225. package/plugin/skills/screenpipe/SKILL.md +78 -0
  226. package/plugin/skills/screenpipe/screenpipe.mjs +196 -0
  227. package/plugin/skills/smart-explore/SKILL.md +193 -0
  228. package/plugin/skills/standup/SKILL.md +142 -0
  229. package/plugin/skills/standup/agent-brief.md +47 -0
  230. package/plugin/skills/standup/standup.mjs +586 -0
  231. package/plugin/skills/timeline-report/SKILL.md +211 -0
  232. package/plugin/skills/weekly-digests/SKILL.md +262 -0
  233. package/plugin/skills/what-the/SKILL.md +6 -0
  234. package/plugin/skills/wowerpoint/SKILL.md +205 -0
  235. package/plugin/sqlite/SessionStore.js +1135 -0
  236. package/plugin/sqlite/SessionStore.js.map +6 -0
  237. package/plugin/sqlite/observations/files.js +13 -0
  238. package/plugin/sqlite/observations/files.js.map +6 -0
  239. package/plugin/ui/assets/fonts/monaspace-radon-var.woff +0 -0
  240. package/plugin/ui/assets/fonts/monaspace-radon-var.woff2 +0 -0
  241. package/plugin/ui/icon-thick-completed.svg +8 -0
  242. package/plugin/ui/icon-thick-investigated.svg +8 -0
  243. package/plugin/ui/icon-thick-learned.svg +12 -0
  244. package/plugin/ui/icon-thick-next-steps.svg +8 -0
  245. package/plugin/ui/tv.html +506 -0
  246. package/plugin/ui/viewer-bundle.js +68 -0
  247. package/plugin/ui/viewer.html +2709 -0
@@ -0,0 +1,85 @@
1
+ import { createRequire as __cmCreateRequire } from "node:module"; const require = __cmCreateRequire(import.meta.url);
2
+ import{createRequire as mn}from"node:module";var Ji=mn(import.meta.url);function k(e){return e==null}function ht(e){return e&&typeof e=="object"&&!Array.isArray(e)}function yn(e,t){return Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n)))}function z(e,t){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t(n,r)]))}function gn(e,t,r){if(!t)return{...e};let n={};for(let o of t)(r||e[o]!==void 0)&&(n[o]=e[o]);return n}function F(e,t,r){return Object.defineProperty(e,t,{writable:!0,value:r,enumerable:!1})}var bn=Symbol.for("cosmokit.volatile.write");function $e(e){return typeof e=="object"&&e!==null&&bn in e}function U(e,t){return arguments.length===1?r=>U(e,r):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function Ie(e){return U("ArrayBuffer",e)||U("SharedArrayBuffer",e)}function wn(e){return Ie(e)||ArrayBuffer.isView(e)}var D;(function(e){e.is=Ie,e.isSource=wn;function t(a){return ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a}e.fromSource=t;function r(a){if(a=t(a),typeof Buffer<"u")return Buffer.from(a).toString("base64");let s="",l=new Uint8Array(a);for(let c=0;c<l.byteLength;c++)s+=String.fromCharCode(l[c]);return btoa(s)}e.toBase64=r;function n(a){return typeof Buffer<"u"?t(Buffer.from(a,"base64")):Uint8Array.from(atob(a),s=>s.charCodeAt(0))}e.fromBase64=n;function o(a){return a=t(a),typeof Buffer<"u"?Buffer.from(a).toString("hex"):Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")}e.toHex=o;function i(a){if(typeof Buffer<"u")return t(Buffer.from(a,"hex"));let s=a.length%2===0?a:a.slice(0,a.length-1),l=[];for(let c=0;c<s.length;c+=2)l.push(parseInt(`${s[c]}${s[c+1]}`,16));return Uint8Array.from(l).buffer}e.fromHex=i})(D||(D={}));var Li=D.fromBase64,Wi=D.toBase64,Bi=D.fromHex,zi=D.toHex;function rt(e,t=new Map){if(!e||typeof e!="object")return e;if(U("Date",e))return new Date(e.valueOf());if(U("RegExp",e))return new RegExp(e.source,e.flags);if(Ie(e))return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let r=t.get(e);if(r)return r;if(Array.isArray(e)){let o=[];return t.set(e,o),e.forEach((i,a)=>{o[a]=Reflect.apply(rt,null,[i,t])}),o}let n=Object.create(Object.getPrototypeOf(e));t.set(e,n);for(let o of Reflect.ownKeys(e)){let i={...Reflect.getOwnPropertyDescriptor(e,o)};"value"in i&&(i.value=Reflect.apply(rt,null,[i.value,t])),Reflect.defineProperty(n,o,i)}return n}function nt(e,t,r){let n=new Set;function o(i,a){if(i===a)return!0;if($e(i)||$e(a))return $e(i)&&$e(a);if(!r&&k(i)&&k(a))return!0;if(typeof i!=typeof a||typeof i!="object"||!i||!a||n.has(i))return!1;function s(l,c){return l(i)?l(a)?c(i,a):!1:l(a)?!1:void 0}n.add(i);try{return s(Array.isArray,(l,c)=>{if(l.length!==c.length)return!1;for(let u=0;u<l.length;u++)if(!o(l[u],c[u]))return!1;return!0})??s(U("Date"),(l,c)=>l.valueOf()===c.valueOf())??s(U("URL"),(l,c)=>l.href===c.href)??s(U("RegExp"),(l,c)=>l.source===c.source&&l.flags===c.flags)??s(Ie,(l,c)=>{if(l.byteLength!==c.byteLength)return!1;let u=new Uint8Array(l),h=new Uint8Array(c);for(let f=0;f<u.length;f++)if(u[f]!==h[f])return!1;return!0})??((!r||[i,a].every(l=>Object.getPrototypeOf(l)===Object.prototype||Object.getPrototypeOf(l)===null))&&Object.keys({...i,...a}).every(l=>o(i[l],a[l])))}finally{n.delete(i)}}return o(e,t)}function vn(e,t,r){let n=[],o=0;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=65&&a<=90){if(o===1){let s=e.charCodeAt(i+1);s>=97&&s<=122&&n.push(r),n.push(a+32)}else o!==0&&n.push(r),n.push(a+32);o=1}else a>=97&&a<=122?(n.push(a),o=2):t.includes(a)?(o!==0&&n.push(r),o=0):n.push(a)}return String.fromCharCode(...n)}function xn(e){return vn(e,[45,95],45)}var On=xn,Lt;(function(e){e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function r(p){t=p}e.setTimezoneOffset=r;function n(){return t}e.getTimezoneOffset=n;function o(p=new Date,m){return typeof p=="number"&&(p=new Date(p)),m===void 0&&(m=t),Math.floor((p.valueOf()/e.minute-m)/1440)}e.getDateNumber=o;function i(p,m){let g=new Date(p*e.day);return m===void 0&&(m=t),new Date(+g+m*e.minute)}e.fromDateNumber=i;let a=/\d+(?:\.\d+)?/.source,s=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(p=>`(${a}${p})?`).join("")}$`);function l(p){let m=s.exec(p);return m?(parseFloat(m[1])*e.week||0)+(parseFloat(m[2])*e.day||0)+(parseFloat(m[3])*e.hour||0)+(parseFloat(m[4])*e.minute||0)+(parseFloat(m[5])*e.second||0):0}e.parseTime=l;function c(p){let m=l(p);return m?p=Date.now()+m:/^\d{1,2}(:\d{1,2}){1,2}$/.test(p)?p=`${new Date().toLocaleDateString()}-${p}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(p)&&(p=`${new Date().getFullYear()}-${p}`),p?new Date(p):new Date}e.parseDate=c;function u(p){let m=Math.abs(p);return m>=e.day-e.hour/2?Math.round(p/e.day)+"d":m>=e.hour-e.minute/2?Math.round(p/e.hour)+"h":m>=e.minute-e.second/2?Math.round(p/e.minute)+"m":m>=e.second?Math.round(p/e.second)+"s":p+"ms"}e.format=u;function h(p,m=2){return p.toString().padStart(m,"0")}e.toDigits=h;function f(p,m=new Date){return p.replace("yyyy",m.getFullYear().toString()).replace("yy",m.getFullYear().toString().slice(2)).replace("MM",h(m.getMonth()+1)).replace("dd",h(m.getDate())).replace("hh",h(m.getHours())).replace("mm",h(m.getMinutes())).replace("ss",h(m.getSeconds())).replace("SSS",h(m.getMilliseconds(),3))}e.template=f})(Lt||(Lt={}));var De=Symbol.for("schemastery"),hr=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;var w=class extends TypeError{options;name="ValidationError";constructor(e,t){let r="$";for(let n of t.path||[])typeof n=="string"?r+="."+n:typeof n=="number"?r+="["+n+"]":typeof n=="symbol"&&(r+=`[Symbol(${n.toString()})]`);r.startsWith(".")&&(r=r.slice(1)),super((r==="$"?"":`${r} `)+e),this.options=t}static is(e){return!!e?.[hr]}};Object.defineProperty(w.prototype,hr,{value:!0});var d=function(e){let t=function(r,n={}){return d.resolve(r,t,n)[0]};if(e.refs){let r=z(e.refs,o=>new d(o)),n=o=>r[o];for(let o in r){let i=r[o];i.sKey=n(i.sKey),i.inner=n(i.inner),i.list=i.list&&i.list.map(n),i.dict=i.dict&&z(i.dict,n)}return r[e.uid]}if(Object.assign(t,e),typeof t.callback=="string")try{t.callback=new Function("return "+t.callback)()}catch{}return Object.defineProperty(t,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(t,d.prototype),t.meta||={},t.toString=t.toString.bind(t),t};d.prototype=Object.create(Function.prototype);d.prototype[De]=!0;Object.defineProperty(d.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:e=>{try{return{value:d.resolve(e,this,{})[0]}}catch(t){if(w.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}}}}});d.ValidationError=w;d.prototype.toJSON=function(){if(globalThis.__schemastery_refs__)return globalThis.__schemastery_refs__[this.uid]??=JSON.parse(JSON.stringify({...this})),this.uid;globalThis.__schemastery_refs__={[this.uid]:{...this}},globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));let e={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,e};d.prototype.set=function(e,t){return this.dict[e]=t,this};d.prototype.push=function(e){return this.list.push(e),this};function Sn(e,t){let r=typeof e=="string"?{"":e}:{...e};for(let n in t){let o=t[n];o?.$description||o?.$desc?r[n]=o.$description||o.$desc:typeof o=="string"&&(r[n]=o)}return r}function ce(e){return e?.$value??e?.$inner}function Wt(e){return yn(e??{},t=>!t.startsWith("$"))}d.prototype.i18n=function(e){let t=d(this),r=Sn(t.meta.description,e);return Object.keys(r).length&&(t.meta.description=r),t.dict&&(t.dict=z(t.dict,(n,o)=>n.i18n(z(e,i=>ce(i)?.[o]??i?.[o])))),t.list&&(t.list=t.list.map((n,o)=>n.i18n(z(e,(i={})=>Array.isArray(ce(i))?ce(i)[o]:Array.isArray(i)?i[o]:Wt(i))))),t.inner&&(t.inner=t.inner.i18n(z(e,n=>ce(n)?ce(n):Wt(n)))),t.sKey&&(t.sKey=t.sKey.i18n(z(e,n=>n?.$key))),t};d.prototype.extra=function(e,t){let r=d(this);return r.meta={...r.meta,[e]:t},r};for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(d.prototype,{[e](t=!0){let r=d(this);return r.meta={...r.meta,[e]:t},r}});d.prototype.deprecated=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"deprecated",type:"danger"}),e};d.prototype.experimental=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"experimental",type:"warning"}),e};d.prototype.pattern=function(e){let t=d(this),r=gn(e,["source","flags"]);return t.meta={...t.meta,pattern:r},t};d.prototype.simplify=function(e){if(nt(e,this.meta.default,this.type==="dict"))return null;if(k(e))return e;if(this.type==="object"||this.type==="dict"){let t={};for(let r in e){let n=(this.type==="object"?this.dict[r]:this.inner)?.simplify(e[r]);(this.type==="dict"||!k(n))&&(t[r]=n)}return nt(t,this.meta.default,this.type==="dict")?null:t}else if(this.type==="array"||this.type==="tuple"){let t=[];return e.forEach((r,n)=>{let o=this.type==="array"?this.inner:this.list[n],i=o?o.simplify(r):r;t.push(i)}),t}else if(this.type==="intersect"){let t={};for(let r of this.list)Object.assign(t,r.simplify(e));return t}else if(this.type==="union")for(let t of this.list)try{return d.resolve(e,t,{}),t.simplify(e)}catch{}return e};d.prototype.toString=function(e){return yr[this.type]?.(this,e)??`Schema<${this.type}>`};d.prototype.role=function(e,t){let r=d(this);return r.meta={...r.meta,role:e,extra:t},r};for(let e of["default","link","comment","description","max","min","step"])Object.assign(d.prototype,{[e](t){let r=d(this);return r.meta={...r.meta,[e]:t},r}});var mr={};d.extend=function(e,t){mr[e]=t};d.resolve=function(e,t,r={},n=!1){if(!t)return[e];if(r.ignore?.(e,t))return[e];if(k(e)&&t.type!=="lazy"){if(t.meta.required)throw new w("missing required value",r);let i=t,a=t.meta.default;for(;i?.type==="intersect"&&k(a);)i=i.list[0],a=i?.meta.default;if(k(a))return[e];e=rt(a)}let o=mr[t.type];if(!o)throw new w(`unsupported type "${t.type}"`,r);try{return o(e,t,r,n)}catch(i){if(!t.meta.loose)throw i;return[t.meta.default]}};d.from=function(e){if(k(e))return d.any();if(["string","number","boolean"].includes(typeof e))return d.const(e).required();if(e[De])return e;if(typeof e=="function")switch(e){case String:return d.string().required();case Number:return d.number().required();case Boolean:return d.boolean().required();case Function:return d.function().required();default:return d.is(e).required()}else throw new TypeError(`cannot infer schema from ${e}`)};d.lazy=function(e){let t=()=>(r.inner[De]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),r=new d({type:"lazy",builder:e,inner:{toJSON:t}});return r};d.natural=function(){return d.number().step(1).min(0)};d.percent=function(){return d.number().step(.01).min(0).max(1).role("slider")};d.date=function(){return d.union([d.is(Date),d.transform(d.string().role("datetime"),(e,t)=>{let r=new Date(e);if(isNaN(+r))throw new w(`invalid date "${e}"`,t);return r},!0)])};d.regExp=function(e=""){return d.union([d.is(RegExp),d.transform(d.string().role("regexp",{flag:e}),(t,r)=>{try{return new RegExp(t,e)}catch(n){throw new w(n.message,r)}},!0)])};d.arrayBuffer=function(e){return d.union([d.is(ArrayBuffer),d.is(SharedArrayBuffer),d.transform(d.any(),(t,r)=>{if(D.isSource(t))return D.fromSource(t);throw new w(`expected ArrayBufferSource but got ${t}`,r)},!0),...e?[d.transform(d.string(),(t,r)=>{try{return e==="base64"?D.fromBase64(t):D.fromHex(t)}catch(n){throw new w(n.message,r)}},!0)]:[]])};d.extend("lazy",(e,t,r,n)=>(t.inner[De]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta}),d.resolve(e,t.inner,r,n)));d.extend("any",e=>[e]);d.extend("never",(e,t,r)=>{throw new w(`expected nullable but got ${e}`,r)});d.extend("const",(e,{value:t},r)=>{if(nt(e,t))return[t];throw new w(`expected ${t} but got ${e}`,r)});function mt(e,t,r,n,o=!1){let{max:i=1/0,min:a=-1/0}=t;if(e>i)throw new w(`expected ${r} <= ${i} but got ${e}`,n);if(e<a&&!o)throw new w(`expected ${r} >= ${a} but got ${e}`,n)}d.extend("string",(e,{meta:t},r)=>{if(typeof e!="string")throw new w(`expected string but got ${e}`,r);if(t.pattern){let n=new RegExp(t.pattern.source,t.pattern.flags);if(!n.test(e))throw new w(`expect string to match regexp ${n}`,r)}return mt(e.length,t,"string length",r),[e]});function Ue(e,t){let r=e.toString();if(r.includes("e"))return e*Math.pow(10,t);let n=r.indexOf(".");if(n===-1)return e*Math.pow(10,t);let o=r.slice(n+1),i=r.slice(0,n);return o.length<=t?+(i+o.padEnd(t,"0")):+(i+o.slice(0,t)+"."+o.slice(t))}function kn(e,t,r){if(r=Math.abs(r),!/^\d+\.\d+$/.test(r.toString()))return(e-t)%r===0;let n=r.toString().indexOf("."),o=r.toString().slice(n+1).length;return Math.abs(Ue(e,o)-Ue(t,o))%Ue(r,o)===0}d.extend("number",(e,{meta:t},r)=>{if(typeof e!="number")throw new w(`expected number but got ${e}`,r);mt(e,t,"number",r);let{step:n}=t;if(n&&!kn(e,t.min??0,n))throw new w(`expected number multiple of ${n} but got ${e}`,r);return[e]});d.extend("boolean",(e,t,r)=>{if(typeof e=="boolean")return[e];throw new w(`expected boolean but got ${e}`,r)});d.extend("bitset",(e,{bits:t,meta:r},n)=>{let o=0,i=[];if(typeof e=="number"){o=e;for(let a in t)e&t[a]&&i.push(a)}else if(Array.isArray(e)){i=e;for(let a of i){if(typeof a!="string")throw new w(`expected string but got ${a}`,n);a in t&&(o|=t[a])}}else throw new w(`expected number or array but got ${e}`,n);return o===r.default?[o]:[o,i]});d.extend("function",(e,t,r)=>{if(typeof e=="function")return[e];throw new w(`expected function but got ${e}`,r)});d.extend("is",(e,{constructor:t},r)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new w(`expected ${t.name} but got ${e}`,r)}else{if(k(e))throw new w(`expected ${t} but got ${e}`,r);let n=Object.getPrototypeOf(e);for(;n;){if(n.constructor?.name===t)return[e];n=Object.getPrototypeOf(n)}throw new w(`expected ${t} but got ${e}`,r)}});function Pe(e,t,r,n){try{let[o,i]=d.resolve(e[t],r,{...n,path:[...n.path||[],t]});return i!==void 0&&(e[t]=i),o}catch(o){if(!n?.autofix)throw o;return delete e[t],r.meta.default}}d.extend("array",(e,{inner:t,meta:r},n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,n);return mt(e.length,r,"array length",n,!k(t.meta.default)),[e.map((o,i)=>Pe(e,i,t,n))]});d.extend("dict",(e,{inner:t,sKey:r},n,o)=>{if(!ht(e))throw new w(`expected object but got ${e}`,n);let i={};for(let a in e){let s;try{s=d.resolve(a,r,n)[0]}catch(l){if(o)continue;throw l}i[s]=Pe(e,a,t,n),e[s]=e[a],a!==s&&delete e[a]}return[i]});d.extend("tuple",(e,{list:t},r,n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,r);let o=t.map((i,a)=>Pe(e,a,i,r));return n?[o]:(o.push(...e.slice(t.length)),[o])});function ot(e,t){for(let r in t)r in e||(e[r]=t[r])}d.extend("object",(e,{dict:t},r,n)=>{if(!ht(e))throw new w(`expected object but got ${e}`,r);let o={};for(let i in t){let a=Pe(e,i,t[i],r);(!k(a)||i in e)&&(o[i]=a)}return n||ot(o,e),[o]});d.extend("union",(e,{list:t,toString:r},n,o)=>{let i=[];for(let a of t)try{return d.resolve(e,a,n,o)}catch(s){i.push(s)}throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)});d.extend("intersect",(e,{list:t,toString:r},n,o)=>{if(!t.length)return[e];let i;for(let a of t){let s=d.resolve(e,a,n,!0)[0];if(!k(s))if(k(i))i=s;else{if(typeof i!=typeof s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n);if(typeof s=="object")ot(i??={},s);else if(i!==s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)}}return!o&&ht(e)&&ot(i,e),[i]});d.extend("transform",(e,{inner:t,callback:r,preserve:n},o)=>{let[i,a=e]=d.resolve(e,t,o,!0);return n?[r(i)]:[r(i),r(a)]});var yr={};function E(e,t,r){yr[e]=r,Object.assign(d,{[e](...n){let o=new d({type:e});return t.forEach((i,a)=>{switch(i){case"sKey":o.sKey=n[a]??d.string();break;case"inner":o.inner=d.from(n[a]);break;case"list":o.list=n[a].map(d.from);break;case"dict":o.dict=z(n[a],d.from);break;case"bits":o.bits={};for(let s in n[a])typeof n[a][s]=="number"&&(o.bits[s]=n[a][s]);break;case"callback":{let s=o.callback=n[a];s.toJSON||=()=>s.toString();break}case"constructor":{let s=o.constructor=n[a];typeof s=="function"&&(s.toJSON||=()=>s.name);break}default:o[i]=n[a]}}),e==="object"||e==="dict"?o.meta.default={}:e==="array"||e==="tuple"?o.meta.default=[]:e==="bitset"&&(o.meta.default=0),o}})}E("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);E("any",[],()=>"any");E("never",[],()=>"never");E("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);E("string",[],()=>"string");E("number",[],()=>"number");E("boolean",[],()=>"boolean");E("bitset",["bits"],()=>"bitset");E("function",[],()=>"function");E("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);E("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);E("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);E("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,r])=>`${t}${r.meta.required?"":"?"}: ${r.toString()}`).join(", ")} }`);E("union",["list"],({list:e},t)=>{let r=e.map(({toString:n})=>n()).join(" | ");return t?`(${r})`:r});E("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);E("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t));var yt=class{sn=0;map=new Map;weak=new WeakMap;get length(){return this.map.size}push(e){let t=++this.sn;return this.map.set(t,e),this.weak.set(e,t),()=>this.map.delete(t)}delete(e){let t=this.weak.get(e);return t?this.map.delete(t):!1}clear(){let e=[...this.map.values()];return this.map.clear(),e.reverse()}[Symbol.iterator](){return this.map.values()}[Symbol.for("nodejs.util.inspect.custom")](){return[...this]}},y={shadow:Symbol.for("cordis.shadow"),receiver:Symbol.for("cordis.receiver"),original:Symbol.for("cordis.original"),metadata:Symbol.for("cordis.metadata"),initHooks:Symbol.for("cordis.initHooks"),checkProto:Symbol.for("cordis.checkProto"),effect:Symbol.for("cordis.effect"),filter:Symbol.for("cordis.filter"),isolate:Symbol.for("cordis.isolate"),intercept:Symbol.for("cordis.intercept"),init:Symbol.for("cordis.init"),check:Symbol.for("cordis.check"),config:Symbol.for("cordis.config"),invoke:Symbol.for("cordis.invoke"),extend:Symbol.for("cordis.extend"),tracker:Symbol.for("cordis.tracker"),resolveConfig:Symbol.for("cordis.resolveConfig")},En=function*(){}.constructor,Bt=async function*(){}.constructor;function jn(e){return!(!e.prototype||e instanceof En||Bt!==Function&&e instanceof Bt)}function gt(e,t){if(e===Object.prototype)return t;let r=Object.create(gt(Object.getPrototypeOf(e),t));for(let n of Reflect.ownKeys(e))Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n));return r}function re(e){return e&&(typeof e=="object"||typeof e=="function")}function $n(e,t){let r=e;for(;r;){let n=Reflect.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function Q(e,t){if(!re(t))return t;if(Object.hasOwn(t,y.shadow))return Object.getPrototypeOf(t);let r=t[y.tracker];return r?bt(e,t,r):t}function Ae(e,t){return t?new Proxy(e,{get:(r,n,o)=>n in t&&n!=="constructor"?Reflect.get(t,n,o):Reflect.get(r,n,o),set:(r,n,o,i)=>n in t&&n!=="constructor"?Reflect.set(t,n,o,i):Reflect.set(r,n,o,i)}):e}function it(e,t,r){return Ae(e,Object.defineProperty(Object.create(null),t,{value:r,writable:!1}))}function He(e,t,r,n){if(!r)return n;let o=Reflect.getOwnPropertyDescriptor(t,r)?.value;return o?it(n,r,e.extend({[y.shadow]:o})):n}function _n(e,t,r,n){return new Proxy(t,{apply:(o,i,a)=>(i===r&&(i=n),Q(e,Reflect.apply(o,i,a)))})}function bt(e,t,r){e[y.shadow]&&!r.noShadow&&(e=Object.getPrototypeOf(e));let n=new Proxy(t,{get:(o,i,a)=>{if(i===y.original)return o;if(i===r.property)return e;if(typeof i=="symbol")return Reflect.get(o,i,a);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.get(e,`${r.associate}.${i}`,it(e,y.receiver,a));let s,l,c=$n(o,i);c&&"value"in c?l=c.value:(s=He(e,o,r.property,a),l=Reflect.get(o,i,s));let u=l?.[y.tracker];return u?bt(e,l,u):!r.noShadow&&typeof l=="function"?(s??=He(e,o,r.property,a),_n(e,l,a,s)):l},set:(o,i,a,s)=>{if(i===y.original||i===r.property)return!1;if(typeof i=="symbol")return Reflect.set(o,i,a,s);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.set(e,`${r.associate}.${i}`,a,it(e,y.receiver,s));let l=He(e,o,r.property,s);return Reflect.set(o,i,a,l)},apply:(o,i,a)=>gr(n,o,i,a)});return n}function gr(e,t,r,n){return t[y.invoke]?t[y.invoke].apply(e,n):Reflect.apply(t,r,n)}function st(e,t,r){let n=function(...o){return gr(bt(n.ctx,n,r),n,this,o)};return F(n,"name",e),Object.setPrototypeOf(n,t)}function zt(e,t,r){let n=e.error.stack.split(`
3
+ `);if(typeof t?.stack!="string"){let a=new Error(t),s=a.stack.split(`
4
+ `);throw s.splice(1,1/0,...r()),a.stack=s.join(`
5
+ `),a}let o=t.stack.split(`
6
+ `),i=o.indexOf(n[2]);if(i===-1)throw t;for(i-=e.offset;i>0&&o[i-1].endsWith(" (<anonymous>)");)i-=1;throw o.splice(i,1/0,...r()),t.stack=o.join(`
7
+ `),t}function Ut(e,t=wt()){let r={offset:1,error:new Error};try{let n=e(r);return re(n)&&"then"in n?n.then(void 0,o=>zt(r,o,t)):n}catch(n){zt(r,n,t)}}function wt(e=0){let t=new Error;return()=>t.stack.split(`
8
+ `).slice(3+e)}function Ht(e){return e!==null&&e!==!1&&e!==void 0}var Rn=class{ctx;_hooks={};constructor(e){this.ctx=e,F(this,y.tracker,{property:"ctx",noShadow:!0}),this.on("internal/listener",function(t,r,n){if(t==="internal/update"&&!n.global)return(this.fiber._hooks["internal/update"]??=new yt)[n.prepend?"unshift":"push"](r)}),this.on("internal/update",function(t,r,n){let o=[...this._hooks["internal/update"]||[]],i=()=>(o.shift()??n).call(this,t,r,i);return i()},{global:!0,prepend:!0})}dispatch(e,t){let r=typeof t[0]=="object"||typeof t[0]=="function"?t.shift():null,n=t.shift();n.startsWith("internal/")||this.emit("internal/dispatch",e,n,t,r);let o=r?.[Z.filter];return(this._hooks[n]||[]).filter(i=>i.global||!o||o.call(r,i.ctx)).map(i=>i.callback.bind(r))}async parallel(...e){let t=(await Promise.allSettled(this.dispatch("emit",e).map(async r=>r(...e)))).filter(r=>r.status==="rejected");if(t.length)throw new AggregateError(t.map(r=>r.reason))}emit(...e){this.dispatch("emit",e).map(t=>t(...e))}async serial(...e){for(let t of this.dispatch("serial",e)){let r=await t(...e);if(Ht(r))return r}}bail(...e){for(let t of this.dispatch("bail",e)){let r=t(...e);if(Ht(r))return r}}waterfall(...e){let t=this.dispatch("waterfall",e),r=e.pop(),n=()=>(t.shift()??r)(...e);return e.push(n),n()}register(e,t,r,n){let o=n.prepend?"unshift":"push";return this.ctx.fiber.effect(()=>(t[o]({ctx:this.ctx,callback:r,...n}),()=>this.unregister(t,r)),e)}unregister(e,t){let r=e.findIndex(n=>n.callback===t);if(r>=0)return e.splice(r,1),!0}on(e,t,r){typeof r!="object"&&(r={prepend:r}),this.ctx.fiber.assertActive(),t=this.ctx.reflect.bind(t);let n=this.bail(this.ctx,"internal/listener",e,t,r);if(n)return n;let o=this._hooks[e]||=[],i=`ctx.on(${typeof e=="string"?JSON.stringify(e):e.toString()})`;return this.register(i,o,t,r)}once(e,t,r){let n=this.on(e,function(...o){return n(),t.apply(this,o)},r);return n}},Kt={s:e=>String(e),d:e=>Math.trunc(Number(e)),i:e=>Math.trunc(Number(e)),f:e=>Number(e),o:e=>JSON.stringify(e),O:e=>JSON.stringify(e),c:()=>"",C:(e,t,r)=>at.color(t,at.code(r.name,t.colors),e)};function An(e){return e instanceof Error&&Array.isArray(e.errors)}var at=class{service;static color(e,t,r,n=""){return e.colors?`\x1B[3${t<8?t:"8;5;"+t}${e.colors>=2?n:""}m${r}\x1B[0m`:""+r}static code(e,t){let r=0;for(let o=0;o<e.length;o++)r=(r<<3)-r+e.charCodeAt(o)+13,r|=0;let n=t?t>=2?Nn:Cn:[];return n[Math.abs(r)%n.length]}static format(e,t){let r=t.args.slice();r[0]instanceof Error?(r[0]=r[0].stack||r[0].message,r.unshift("%s")):typeof r[0]!="string"&&r.unshift("%o");let n=r.shift();n=n.replace(/%([a-zA-Z%])/g,(a,s)=>{if(a==="%%")return"%";let l=e.formatters?.[s]??Kt[s];return typeof l=="function"?l(r.shift(),e,t):a});let o=e.formatters?.o??Kt.o;for(let a of r)typeof a=="object"&&a&&(a=o(a,e,t)),n+=" "+a;let{maxLength:i=10240}=e;return n.split(/\r?\n/g).map(a=>a.slice(0,i)+(a.length>i?"...":"")).join(`
9
+ `)}constructor(e,t){this.service=t,Object.assign(this,e),this.error=this._method("error",0),this.info=this._method("info",1),this.warn=this._method("warn",2),this.debug=this._method("debug",3)}_method(e,t){return(...r)=>{if(r.length===1&&r[0]instanceof Error){if(r[0].cause)this[e](r[0].cause);else if(An(r[0])){r[0].errors.forEach(i=>this[e](i));return}}let n=++this.service._snMessage,o=Date.now();for(let i of this.service.exporters.values()){if((i.levels?.[this.name]??i.levels?.default??this.level??1)<t)continue;let a={sn:n,ts:o,type:e,level:t,name:this.name,...this.meta,args:r};i.export(a)}}}},Cn=[6,2,3,4,5,1],Nn=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221],Tn=class br{bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(t){let r={property:"ctx",noShadow:!0},n=st("logger",gt(Object.getPrototypeOf(this),Function.prototype),r);return Object.assign(n,this),n.ctx=t,F(n,y.tracker,r),n.exporter({colors:3,export:o=>{n.buffer.push(o),n.buffer.length>n.bufferSize&&(n.buffer=n.buffer.slice(-n.bufferSize))}}),n}exporter(t){return this.ctx.effect(()=>(this.exporters.set(++this._snExporter,t),()=>this.exporters.delete(this._snExporter)),"ctx.logger.exporter()")}_resolveConfig(){let t=this.ctx[y.intercept],r=[];for(;"logger"in t;)Object.hasOwn(t,"logger")&&r.unshift(t.logger),t=Object.getPrototypeOf(t);return Object.assign({},...r)}[y.invoke](t){let r=this._resolveConfig(),n=(this.ctx[y.shadow]??this.ctx).fiber;return t??=r.name,t??=On(n.name),new at({name:t,level:r.level,meta:{fiber:new WeakRef(n)}},this)}static{for(let t of["error","info","warn","debug"])br.prototype[t]=function(...r){return this()[t](...r)}}};function Ke(e){let t=e.stack.split(`
10
+ `);return t.splice(0,2,`Error: ${e.message}`),e.stack=t.join(`
11
+ `),e}var Mn=["prototype","then"];function Ve(e){return typeof e=="symbol"||Mn.includes(e)||parseInt(e).toString()===e||e.startsWith("_")}var Vt=class{ctx;static handler={get:(e,t,r)=>{if(Ve(t))return Reflect.get(e,t,r);if(Reflect.has(e,t))return Q(r,Reflect.get(e,t,r));let n=new Error(`cannot get property "${t}" without inject`);try{let o=e.reflect.props[t];return o?.type==="accessor"?o.get.call(r,r[y.receiver],n):r.fiber.runtime?r.events.waterfall("internal/get",r,t,n,()=>{let i=e[y.isolate][t],a=(r[y.shadow]??r).fiber;for(;;){let s=a.store?.[t];if(s)return Q(r,s.value);if(t in a.inject)throw n.message=`cannot get required service "${t}" in inactive context`,n;if(!a.runtime||a.parent[y.isolate][t]!==i)throw n;a=a.parent.fiber}}):r.reflect.get(t,!1)}catch(o){throw o===n?Ke(o):o}},set:(e,t,r,n)=>{if(Ve(t))return Reflect.set(e,t,r,n);let o=new Error(`cannot set property "${t}" without provide`),i=e.reflect.props[t];if(!i){if(!n.fiber.runtime)return Reflect.set(e,t,r,n);throw Ke(o)}try{return i.type==="accessor"?i.set?i.set.call(n,r,n[y.receiver],o):!1:n.events.waterfall("internal/set",n,t,r,o,()=>n.reflect.set(t,r,o))}catch(a){throw a===o?Ke(a):a}},has:(e,t)=>Ve(t)?Reflect.has(e,t):Reflect.has(e,t)?!0:!!e.reflect.props[t]};store=Object.create(null);props=Object.create(null);constructor(e){this.ctx=e,F(this,y.tracker,{property:"ctx",noShadow:!0}),this.mixin("reflect",["get","set","provide","accessor","mixin"]),this.mixin("fiber",["runtime","effect"]),this.mixin("registry",["inject","plugin"]),this.mixin("events",["on","once","parallel","emit","serial","bail","waterfall"])}get(e,t=!0){return Q(this.ctx,this._getImpl(e,t)?.value)}_getImpl(e,t=!0){let r=this.ctx[y.isolate][e],n=r&&this.store[r];if(n&&!(t&&n.fiber.state!==2))return n}set(e,t,r){let n=this.ctx[y.isolate][e],o=this.store[n];if(!o)throw new Error(`cannot set property "${e}" without provide`);if(o.fiber!==this.ctx.fiber)throw new Error(`cannot set property "${e}" in multiple fibers`);return o.value=t,!0}provide(e,t,r){return this.ctx.fiber.effect(()=>{if(!this.props[e])this.props[e]??={type:"service"};else if(this.props[e].type!=="service")throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);this.props[e]={type:"service"},this.ctx.root[y.isolate][e]??=Symbol(e);let n=this.ctx[y.isolate][e],o={name:e,value:t,fiber:this.ctx.fiber,check:r};if(this.store[n])throw new Error(`service "${e}" has been registered at <${this.store[n].fiber.name}>`);return this.store[n]=o,this.ctx.fiber.store[e]=o,this.ctx.fiber.state===2&&this.notify([e]),async()=>{delete this.store[n];let i=this.notify([e]);await Promise.allSettled(i.map(a=>a.await())),delete this.ctx.fiber.store[e]}},`ctx.provide(${JSON.stringify(e)})`)}notify(e,t=(r,n)=>r[y.isolate][n]===this.ctx[y.isolate][n]){let r=[];for(let n of this.ctx.registry.values())for(let o of n.fibers){let i=!1;for(let a of e)a in o.inject&&t(o.ctx,a)&&(i=!0,o._checkImpl(a));i&&(o._refresh(),r.push(o))}for(let n of e){let o=Object.create(this.ctx);o[y.filter]=i=>t(i,n),this.ctx.events.emit(o,"internal/service",n,this._getImpl(n,!1)?.value)}return r}accessor(e,t){return this.ctx.fiber.effect(()=>{if(e in this.props)throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);return this.props[e]={type:"accessor",...t},()=>delete this.props[e]},`ctx.accessor(${JSON.stringify(e)})`)}mixin(e,t){let r=this;return this.ctx.fiber.effect(function*(){let n=Array.isArray(t)?t.map(i=>[i,i]):Object.entries(t),o=(i,a)=>i[e];for(let[i,a]of n)yield r.accessor(a,{get(s,l){let c=o(this,l);if(k(c))return c;let u=s?Ae(s,c):c,h=Reflect.get(c,i,u);return typeof h!="function"?h:h.bind(u??c)},set(s,l,c){let u=o(this,c),h=l?Ae(l,u):u;return Reflect.set(u,i,s,h)}})},`ctx.mixin(${JSON.stringify(e)})`)}trace(e){return Q(this.ctx,e)}bind(e){return new Proxy(e,{apply:(t,r,n)=>Reflect.apply(t,this.trace(r),n.map(o=>this.trace(o))),construct:(t,r,n)=>Reflect.construct(t,r.map(o=>this.trace(o)),n)})}},In=Symbol.for("ValidationError"),wr=class extends TypeError{name="ValidationError";constructor(e){super(`invalid config:
12
+ `+e.map(t=>t.path?` - ${t.message} (at ${t.path.join(".")})`:` - ${t.message}`).join(`
13
+ `))}};Object.defineProperty(wr.prototype,In,{value:!0});function Dn(e,t){if(!e.Config)return t;let r=e.Config["~standard"].validate(t);if("then"in r)throw new TypeError("Async config validation is not supported");if(r.issues)throw new wr(r.issues);return r.value}var vr=new WeakMap;function Xe(e){let t=e();return vr.get(e)?.()??t}function Pn(e,t){let r=["internal/plugin",t],n;try{n=e.events.dispatch("emit",r)}catch(o){e.logger.error(o);return}for(let o of n)try{let i=o(...r);Promise.resolve(i).catch(a=>e.logger.error(a))}catch(i){e.logger.error(i)}}var Ce=class xr extends Error{code;constructor(t,r){super(r??xr.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(Ce||(Ce={}));var I="__INACTIVE__",Or=class{parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new yt;context;_error;_runner;_store=Object.create(null);constructor(e,t,r,n,o){this.parent=e,this.inject=r,this.runtime=n,this._config=t;let i=a=>{this._disposables.push(a)};if(n){this.uid=e.registry.counter,this.ctx=this.context=e.extend({fiber:this});let a=Object.entries(this.inject);if(a.length){this.ctx[Z.intercept]=Object.create(e[Z.intercept]);for(let[s,l]of a)k(l)||(this.ctx[Z.intercept][s]=l)}this._runner={epoch:I,getOuterStack:o,execute:function(){if(jn(n.callback)){let s=new n.callback(this.ctx,this.config);for(let l of s?.[y.initHooks]??[])l();return s?.[y.init]?.()}else return n.callback(this.ctx,this.config)},collect:i},this.dispose=e.fiber.effect(()=>{let s=n.fibers.push(this);return async()=>{for(this.uid=null,Pn(this.context,this),this.ctx.registry.has(n.callback)&&(s(),n.fibers.length||this.ctx.registry.delete(n.callback)),this._setEpoch(I),this.inertia||this._updateState(()=>(this.inertia=this._unload(),5));this.inertia;)await this.inertia}},"ctx.plugin()");try{this.context.emit("internal/plugin",this)}catch(s){throw Promise.resolve(this.dispose()).catch(l=>this.ctx.logger.error(l)),s}if(this.uid!==null&&e.fiber.state!==5){for(let s of Object.keys(this.inject))this._checkImpl(s);this._refresh()}}else this.uid=0,this.ctx=this.context=e,this.state=2,this.store=Object.create(null),this._runner={epoch:"",getOuterStack:o,execute:()=>{},collect:i},this.dispose=()=>this.restart()}get name(){let e=this;do{if(e.runtime?.name)return e.runtime.name;e=e.parent.fiber}while(e!==e.parent.fiber);return"root"}assertActive(){if(this.uid===null)throw new Ce("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return Ut(r=>{let n=i=>{if(typeof i=="function")e.collect(i);else if(!k(i))throw new TypeError("Invalid effect")},o=e.execute.call(this);if(typeof o=="function")return e.collect(o);if(!k(o))if(re(o)){if("then"in o)return o.then(n);if(Symbol.iterator in o){r.error=new Error;let i=o[Symbol.iterator]();for(;;){let a=i.next();if(n(a.value),a.done)return}}else if(Symbol.asyncIterator in o){let i=o[Symbol.asyncIterator]();return(async()=>{for(await Promise.resolve(),r.error=new Error;;){if(e.epoch!==t)return;let a=await i.next();if(n(a.value),a.done)return}})()}else throw new TypeError("Invalid effect")}else throw new TypeError("Invalid effect")},e.getOuterStack)}effect(e,t="anonymous"){if(this.assertActive(),this.state===5)throw new Ce("INACTIVE_EFFECT");let r=[],n=!1,o,i=()=>{if(n)return o;n=!0;let v;for(let O of r.splice(0).reverse())if(v)v=v.then(()=>Xe(O));else{let A=Xe(O);re(A)&&"then"in A&&(v=A)}return o=v},a={label:t,children:[]},s={execute:e,epoch:!0,collect:v=>{r.push(v),this._disposables.delete(v),v[y.effect]&&a.children.push(v[y.effect])},getOuterStack:wt()},l,c=!0,u,h,f,p=!1,m,g=()=>!1,j=()=>(f??=new Promise((v,O)=>{u=v,h=O}),f),M=v=>Promise.resolve(v).then(()=>i(),async O=>{throw await i(),O}),R=v=>{let O;try{O=v()}catch(A){throw g(),A}if(re(O)&&"then"in O){let A=Promise.resolve(O).finally(()=>{g(),m===A&&(m=void 0)});return m=A}return g(),O},V=F(()=>s.epoch?(s.epoch=!1,R(()=>c?M(j()):l?M(l):i())):p?m:void 0,y.effect,a);vr.set(V,()=>m),g=this._disposables.push(V);try{l=this._execute(s)}catch(v){c=!1,p=!0,s.epoch=!1;let O;try{O=R(i)}finally{h?.(v)}throw re(O)&&"then"in O&&O.catch(A=>this.ctx.logger.error(A)),v}c=!1,f&&Promise.resolve(l).then(u,h),l?.catch(()=>s.epoch?R(i):i()).catch(v=>this.ctx.logger.error(v));let te=()=>{if(s.epoch)return s.epoch=!1,R(i)};return V.then=async(v,O)=>Promise.resolve(l).then(()=>te).then(v,O),V}getEffects(){return[...this._disposables].map(e=>e[y.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==I?2:0}_updateState(e){let t=this.state;if(this.state=e()??this._getState(),t!==this.state&&(this.context.emit("internal/status",this,t),!(t!==2&&this.state!==2)))for(let r of Reflect.ownKeys(this.ctx.reflect.store)){let n=this.ctx.reflect.store[r];n.fiber===this&&this.ctx.reflect.notify([n.name])}}_checkImpl(e){let t=this.ctx.reflect._getImpl(e,!0);if(!t)return delete this._store[e];try{if(t.check&&!t.check.call(Q(this.ctx,t.value)))return delete this._store[e]}catch(r){return t.fiber.ctx.logger.error(r),delete this._store[e]}this._store[e]=t}_refresh(){let e=!1;e="";for(let t of Object.keys(this.inject)){let r=this._store[t];if(!r){e=I;break}e+=":"+r.fiber.uid}this._setEpoch(e)}_setEpoch(e){let t=this._runner.epoch;e!==t&&(this._runner.epoch=e,!this.inertia&&this._updateState(()=>e!==I&&t===I?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?Dn(this.runtime,e):e}async _reload(){this.store={...this._store};let e=this._runner.epoch;try{await Promise.resolve(),this._runner.epoch===e&&(this.config=this._resolveConfig(this._config),await this._execute(this._runner),this._error=void 0)}catch(t){this.ctx.logger.error(t),this._error=t,this._runner.epoch=I}this._updateState(()=>{if(this._runner.epoch===e)this.inertia=void 0;else return this.inertia=this._unload(),5})}async _unload(){await Promise.all(this._disposables.clear().map(async e=>{try{await Ut(async t=>{await Promise.resolve(),t.error=new Error,await Xe(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===I)this.inertia=void 0;else return this.inertia=this._reload(),1})}async await(){for(;this.inertia;)await this.inertia;if(this._error)throw this._error;return this}async restart(){this.assertActive(),this._setEpoch(I),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(I),this._refresh();return}return e=this._resolveConfig(e),this.context.waterfall(this,"internal/update",e,t,()=>(this.config=e,this._error=void 0,this.restart()))}};function qn(e){return e&&typeof e=="object"&&typeof e.apply=="function"}function lt(e,t){return function(r,n){if(n.kind==="class")Object.hasOwn(r,"inject")||(F(r,"inject",Object.create(Object.getPrototypeOf(r).inject??null)),F(r.inject,y.checkProto,!0)),r.inject[e]=t;else if(n.kind==="method"){let o=(r[y.metadata]??={}).inject??=Object.create(null);o[e]=t,n.addInitializer(function(){let i=this[y.tracker]?.property;(this[y.initHooks]??=[]).push(()=>{this.ctx.inject(o,a=>r.call(i?Ae(this,{[i]:a}):this))})})}else throw new Error("@Inject() can only be used on class or class methods")}}(function(e){function t(r,n=Object.create(null)){if(!r)return n;if(Array.isArray(r))for(let o of r)n[o]=null;else if(Reflect.has(r,y.checkProto)){Object.assign(n,t(Object.getPrototypeOf(r)));for(let o of Object.keys(r))n[o]=r[o]??null}else for(let o of Object.keys(r))n[o]=r[o]??null;return n}e.resolve=t})(lt||(lt={}));var Fn=class{ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,F(this,y.tracker,{property:"ctx",noShadow:!0})}get counter(){return++this._counter}get size(){return this._internal.size}resolve(e){try{if(typeof e=="function")return e;if(qn(e))return e.apply}catch{}}get(e){let t=this.resolve(e);return t&&this._internal.get(t)}has(e){let t=this.resolve(e);return!!t&&this._internal.has(t)}delete(e){let t=this.resolve(e),r=t&&this._internal.get(t);if(r){this._internal.delete(t);for(let n of r.fibers)n.dispose();return r}}keys(){return this._internal.keys()}values(){return this._internal.values()}entries(){return this._internal.entries()}forEach(e){return this._internal.forEach(e)}inject(e,t){return this.plugin({inject:e,apply:t,name:t.name})}plugin(e,t,r=wt()){let n=this.resolve(e);if(!n)throw new Error('invalid plugin, expect function or object with an "apply" method, received '+typeof e);this.ctx.fiber.assertActive();let o=this._internal.get(n);if(!o){let s=e.name;s==="apply"&&(s=void 0),o={name:s,callback:n,fibers:new yt,Config:e.Config},this._internal.set(n,o)}let i=new Or(this.ctx,t,lt.resolve(e.inject),o,r),a=Object.create(i);return a.then=(s,l)=>i.await().then(s,l),a}},Z=class me{static effect=y.effect;static filter=y.filter;static isolate=y.isolate;static intercept=y.intercept;static is(t){return!!t?.[me.is]}static{me.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),me.prototype[me.is]=!0}constructor(){this[y.isolate]=Object.create(null),this[y.intercept]=Object.create(null);let t=new Proxy(this,Vt.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new Or(t,{},Object.create(null),null,()=>[]),this.reflect=new Vt(t),this.registry=new Fn(t),this.events=new Rn(t),this.logger=new Tn(t),this.fiber._disposables.clear(),t}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.fiber.name}>`}extend(t={}){let r=Reflect.getOwnPropertyDescriptor(this,y.shadow)?.value,n=Object.create(Q(this,this));for(let o of Reflect.ownKeys(t))Object.defineProperty(n,o,Reflect.getOwnPropertyDescriptor(t,o));return r?Object.assign(Object.create(n),{[y.shadow]:r}):n}isolate(t,r){let n=Object.create(this[y.isolate]);return n[t]=r??Symbol(t),this.extend({[y.isolate]:n})}intercept(t,r){let n=Object.create(this[y.intercept]);return n[t]=r,this.extend({[y.intercept]:n})}},Jn=class Sr{ctx;static init=y.init;static check=y.check;static config=y.config;static invoke=y.invoke;static extend=y.extend;static tracker=y.tracker;static resolveConfig=y.resolveConfig;name;constructor(t,r){this.ctx=t,r??=this.constructor.provide;let n=this,o={associate:r,property:"ctx"};return n[y.invoke]&&(n=st(r,gt(Object.getPrototypeOf(this),Function.prototype),o)),n.ctx=t,n.name=r,F(n,y.tracker,o),n.ctx.reflect.provide(r,n,this[y.check]),n}[y.filter](t){return t[y.isolate][this.name]===this.ctx[y.isolate][this.name]}[y.extend](t){let r;return this[Sr.invoke]?r=st(this.name,this,this[y.tracker]):r=Object.create(this),Object.assign(r,t)}[y.resolveConfig](t,r){let n=this.ctx[Z.intercept],o=[];for(;this.name in n;)Object.hasOwn(n,this.name)&&o.unshift(n[this.name]),n=Object.getPrototypeOf(n);return t&&o.unshift(t),r&&o.push(r),this.Config?.merge?this.Config.merge(...o):Object.assign({},...o)}static[Symbol.hasInstance](t){if(!t)return!1;let r=t.constructor;for(;r;){if(r=r.prototype?.constructor,r===this)return!0;r&&=Object.getPrototypeOf(r)}return!1}},Ln=class{duplicateError;data=new Map;constructor(e){this.duplicateError=e}insert(e,t){let r=this.data;if(r.has(e))throw this.duplicateError(e);r.set(e,t);let n=!0;return()=>{n&&(n=!1,r.delete(e),r.size===0&&this.data===r&&(this.data=new Map))}}get(e){return this.data.get(e)}has(e){return this.data.has(e)}keys(){return this.data.keys()}entries(){return this.data.entries()}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Xt=class{data=new Map;append(e){let t=this.data,r=Symbol();t.set(r,e);let n=!0;return()=>{n&&(n=!1,t.delete(r),t.size===0&&this.data===t&&(this.data=new Map))}}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Wn=class{createLayer;onChange;global;scoped=new Map;constructor(e,t){this.createLayer=e,this.onChange=t,this.global=e(void 0)}peek(e){if(e!==void 0)return this.scoped.get(e)}chainLayers(e){let t=[];for(let r of Un(e).reverse()){let n=this.scoped.get(r);n!==void 0&&t.push(n)}return t}merge(e,t){let r=new Map(t(this.global).entries());for(let n of this.chainLayers(e))for(let[o,i]of t(n).entries())r.set(o,i);return r}effect(e,t,r){let n=Ne(e),o=r.notify??!0;return e.effect(function*(){let i,a=!1;if(n===void 0)i=this.global;else{let l=this.scoped.get(n);l===void 0?(i=this.createLayer(n),this.scoped.set(n,i),a=!0):i=l}let s;try{s=t(i)}catch(l){throw n!==void 0&&a&&i.isEmpty()&&this.scoped.delete(n),l}yield()=>{s(),n!==void 0&&i.isEmpty()&&this.scoped.delete(n),o&&this.onChange()},o&&this.onChange()}.bind(this),r.label)}},Bn=Symbol("dsh.scope"),zn=new WeakMap,kr=new WeakMap;function Un(e){let t=[];for(let r=e;r!==void 0;r=kr.get(r))t.push(r);return t}function Ne(e){return e[Bn]}function ue(e,t){let r=e[Z.filter],n={[Z.filter](o){if(r!==void 0&&!r.call(e,o))return!1;let i=Ne(o);if(i===void 0)return!0;for(let a=t;a!==void 0;a=kr.get(a))if(a===i)return!0;return!1}};return zn.set(n,t),n}var Gt=2147483647;function ye(e){let t=new WeakSet,r=[{kind:"visit",node:e}];for(;r.length>0;){let n=r.pop();if(n===void 0)continue;if(n.kind==="property"){r.push({kind:"visit",node:n.source[n.key]});continue}let o=n.node;if(o===null||typeof o!="object"||o instanceof AbortSignal||t.has(o))continue;t.add(o),Object.freeze(o);let i=Object.keys(o);for(let a=i.length-1;a>=0;a--){let s=i[a];s!==void 0&&r.push({kind:"property",source:o,key:s})}}return e}function Hn(e){return ye(structuredClone(e))}function Kn(e){return Hn({...e,id:crypto.randomUUID()})}function Er(e){return Kn({...e,role:"user"})}var oe=class extends Error{code;constructor(e,t,r){super(e,r),this.code=t,this.name=new.target.name}},Vn="EMPTY_RESPONSE",Ui=new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]`+String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`,"i"),Hi=new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?`+String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?`+String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`,"i"),Ki=new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}`+String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}`+String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`,"i"),Xn=2,Gn=500,Yn=1e4,Qn=.1,Zn=Object.freeze([Vn,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),jr=d.object({initialDelayMs:d.number().max(Gt).default(Gn),maxDelayMs:d.number().max(Gt).default(Yn),jitterRatio:d.number().min(0).max(1).default(Qn)}),eo=d.object({mode:d.const("normal").required(),maxRetries:d.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(Xn),retryableCodes:d.array(d.string()).default([...Zn]),backoff:jr}),to=d.object({mode:d.const("always").required(),backoff:jr}),Vi=d.union([eo,to]),{version:Xi}={version:"0.0.1-rc.1"};function ge(e,t){let r=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${r}`)}function $r(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function _r(e){return Object.getPrototypeOf(e)===null&&$r(e,"Object")}function ro(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!$r(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&_r(r)}function no(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&_r(t)}function oo(e){let t=Reflect.ownKeys(e);if(!t.some(r=>typeof r!="string"||!Object.prototype.propertyIsEnumerable.call(e,r)))return t}function Rr(e,t){let r=new Set,n,o=(a,s)=>{a!==void 0&&(a.kind==="root"?n=s:a.kind==="array"?a.target[a.index]=s:Object.defineProperty(a.target,a.key,{value:s,enumerable:!0,configurable:!0,writable:!0}))},i=[{kind:"visit",value:e,...t?{destination:{kind:"root"}}:{}}];for(let a=i.pop();a!==void 0;a=i.pop()){if(a.kind==="leave"){r.delete(a.source);continue}if(a.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(a.source,a.index))return;i.push({kind:"visit",value:a.source[a.index],...a.target===void 0?{}:{destination:{kind:"array",target:a.target,index:a.index}}});continue}if(a.kind==="object-property"){i.push({kind:"visit",value:a.source[a.key],...a.target===void 0?{}:{destination:{kind:"object",target:a.target,key:a.key}}});continue}let s=a.value;if(s===null){o(a.destination,null);continue}if(typeof s=="boolean"||typeof s=="string"){o(a.destination,s);continue}if(typeof s=="number"){if(!Number.isFinite(s)||Object.is(s,-0))return;o(a.destination,s);continue}if(typeof s!="object"||r.has(s))return;if(Array.isArray(s)){if(!ro(s))return;let u=s.length;if(Reflect.ownKeys(s).length!==u+1)return;let h=t?[]:void 0;h!==void 0&&o(a.destination,h),r.add(s),i.push({kind:"leave",source:s});for(let f=u-1;f>=0;f--)i.push({kind:"array-item",source:s,index:f,...h===void 0?{}:{target:h}});continue}if(!no(s))return;let l=oo(s);if(l===void 0)return;let c=t?{}:void 0;c!==void 0&&o(a.destination,c),r.add(s),i.push({kind:"leave",source:s});for(let u=l.length-1;u>=0;u--){let h=l[u];if(h===void 0)return;i.push({kind:"object-property",source:s,key:h,...c===void 0?{}:{target:c}})}}return t?n:!0}function H(e){return Rr(e,!0)}function Ar(e){return Rr(e,!1)===!0}var Cr=class extends oe{violations;constructor(e){super(`unsupported JSON schema: ${e.join("; ")}`,"UNSUPPORTED_SCHEMA"),this.name="JsonSchemaError",this.violations=e}},io=new Set(["type","oneOf","properties","required","additionalProperties","items","enum","const"]),so=new Set(["description","title","default","examples"]),ct=["object","array","string","number","integer","boolean","null"];function Nr(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function Tr(e){return Object.getPrototypeOf(e)===null&&Nr(e,"Object")}function Mr(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Tr(t)}catch{return!1}}function ao(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Nr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Tr(r)}function lo(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function ne(e){return Mr(e)&&lo(e)}function be(e){if(!Array.isArray(e))return!1;try{if(!ao(e)||Reflect.ownKeys(e).length!==e.length+1)return!1;for(let t=0;t<e.length;t++)if(!Object.hasOwn(e,t))return!1;return!0}catch{return!1}}function Te(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function Yt(e,t){switch(e){case"string":return typeof t=="string";case"number":return Te(t);case"integer":return Te(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return ge(e,"JsonSchemaType")}}var Qt=["properties","required","additionalProperties","items","enum","const"];function co(e,t,r,n){let o=Object.hasOwn(e,"required"),i=o?e.required:void 0;if(o)if(!be(i)||i.some(a=>typeof a!="string"))n.push(`${t}.required must be an array of strings`);else{let a=ne(r)?r:{};for(let s of i)Object.hasOwn(a,s)||n.push(`${t}.required names "${s}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&n.push(`${t}.additionalProperties must be a boolean`)}function uo(e,t,r,n){let o=[{kind:"enter",node:e,path:t}];for(let i=o.pop();i!==void 0;i=o.pop()){if(i.kind==="leave"){n.delete(i.node);continue}if(i.kind==="one-of-tail"){for(let f of Qt)Object.hasOwn(i.node,f)&&r.push(`${i.path}.${f} is not supported beside oneOf`);continue}if(i.kind==="object-tail"){co(i.node,i.path,i.properties,r);continue}let{node:a,path:s}=i;if(!ne(a)){r.push(`${s} must be a schema object`);continue}if(n.has(a)){r.push(`${s} is circular`);continue}n.add(a),o.push({kind:"leave",node:a});for(let f of Object.keys(a))if(!io.has(f)){if(so.has(f)){try{Ar(a[f])||r.push(`${s}.${f} annotation must be lossless JSON data`)}catch{r.push(`${s}.${f} annotation must be lossless JSON data`)}continue}r.push(`${s}.${f} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`)}Object.hasOwn(a,"description")&&typeof a.description!="string"&&r.push(`${s}.description must be a string`),Object.hasOwn(a,"title")&&typeof a.title!="string"&&r.push(`${s}.title must be a string`);let l=Object.hasOwn(a,"type"),c=Object.hasOwn(a,"oneOf");if(l&&c){r.push(`${s} cannot declare both type and oneOf`);continue}if(!l&&!c){for(let f of Qt)Object.hasOwn(a,f)&&r.push(`${s}.${f} requires type or oneOf`);continue}if(c){let f=a.oneOf;if(o.push({kind:"one-of-tail",node:a,path:s}),!be(f)||f.length<2)r.push(`${s}.oneOf must be an array of at least two schemas`);else for(let p=f.length-1;p>=0;p--)o.push({kind:"enter",node:f[p],path:`${s}.oneOf[${p}]`});continue}let u=a.type;if(typeof u!="string"||!ct.includes(u)){r.push(Array.isArray(u)?`${s}.type must be a single type string (type arrays are not supported)`:`${s}.type must be one of ${ct.join("/")}`);continue}let h=u;for(let[f,p]of Object.entries({properties:["object"],required:["object"],additionalProperties:["object"],items:["array"],enum:["string","number","integer","boolean","null"],const:["string","number","integer","boolean","null"]}))Object.hasOwn(a,f)&&!p.includes(h)&&r.push(`${s}.${f} is not supported on type "${h}"`);switch(h){case"object":{let f=Object.hasOwn(a,"properties")?a.properties:void 0;if(o.push({kind:"object-tail",node:a,path:s,properties:f}),Object.hasOwn(a,"properties"))if(!ne(f))r.push(`${s}.properties must be an object of schemas`);else{let p=Object.entries(f);for(let m=p.length-1;m>=0;m--){let g=p[m];g!==void 0&&o.push({kind:"enter",node:g[1],path:`${s}.properties.${g[0]}`})}}break}case"array":Object.hasOwn(a,"items")&&o.push({kind:"enter",node:a.items,path:`${s}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let f=Object.hasOwn(a,"enum"),p=f?a.enum:void 0,m=be(p)&&p.length>0&&p.every(R=>Yt(h,R));f&&!m&&r.push(`${s}.enum must be a non-empty array of ${h} values`);let g=Object.hasOwn(a,"const"),j=g?a.const:void 0,M=Yt(h,j);g&&(M?m&&!p.includes(j)&&r.push(`${s}.const must be one of ${s}.enum when both are declared`):r.push(`${s}.const must be a ${h} value`));break}default:ge(h,"JsonSchemaType")}}}function xe(e){let t=[];if(uo(e,"schema",t,new Set),t.length>0)throw new Cr(t)}function Ge(e){try{return Ar(e)}catch{return!1}}function $(e){return e===""?"arguments":e}function Ye(e,t){return e===""?t:`${e}.${t}`}function Qe(e){return[`"${$(e)}" must be a lossless JSON value`]}function Zt(e,t){for(let r of t)e.push(r)}function er(e,t,r){return{node:e,value:t,path:r,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function de(e,t,r){let n=Object.hasOwn(e,"enum")?e.enum:void 0;return n!==void 0&&!n.includes(t)?[`"${$(r)}" must be one of ${JSON.stringify(n)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${$(r)}" must be ${JSON.stringify(e.const)}`]:[]}function po(e,t,r){let n=[er(e,t,r)],o,i=s=>{let l=n.at(-1);if(l===void 0){o=s;return}l.kind==="oneOf"?s.length===0&&l.matches++:Zt(l.violations,s)},a=s=>{n.pop(),i(s)};for(;n.length>0;){let s=n.at(-1);if(s===void 0)break;try{if(s.phase==="children"){if(s.childIndex<s.children.length){let u=s.children[s.childIndex];if(u===void 0)throw new Error("missing schema-value child frame");s.childIndex++,n.push(er(u.node,u.value,u.path));continue}if(s.kind==="oneOf"){a(s.matches===1?[]:[`"${$(s.path)}" must match exactly one oneOf branch (matched ${s.matches})`]);continue}Zt(s.violations,s.tailViolations),s.violations.length>0?a(s.violations):s.kind==="object"?a(Ge(s.value)?[]:[`"${$(s.path)}" must be a lossless JSON object`]):a(Ge(s.value)?[]:[`"${$(s.path)}" must be a dense lossless JSON array`]);continue}let l=Object.hasOwn(s.node,"type")?s.node.type:void 0;s.catches=!(l!==void 0&&!ct.includes(l));let c=Object.hasOwn(s.node,"oneOf")?s.node.oneOf:void 0;if(c!==void 0){s.kind="oneOf",s.children=Array.from(c,u=>({node:u,value:s.value,path:s.path})),s.childIndex=0,s.matches=0,s.phase="children";continue}if(l===void 0){a(Ge(s.value)?[]:Qe(s.path));continue}switch(l){case"object":{if(!Mr(s.value)){a([`"${$(s.path)}" must be an object`]);break}let u=Object.hasOwn(s.node,"properties")?s.node.properties??{}:{},h=[],f=Object.hasOwn(s.node,"required")?s.node.required??[]:[];for(let g of f)(!Object.hasOwn(s.value,g)||s.value[g]===void 0)&&h.push(`missing required property "${Ye(s.path,g)}"`);let p=[];for(let[g,j]of Object.entries(u))!Object.hasOwn(s.value,g)||s.value[g]===void 0||p.push({node:j,value:s.value[g],path:Ye(s.path,g)});let m=[];if(Object.hasOwn(s.node,"additionalProperties")&&s.node.additionalProperties===!1)for(let g of Object.keys(s.value))Object.hasOwn(u,g)||m.push(`"${Ye(s.path,g)}" is not a declared property (additionalProperties: false)`);s.kind="object",s.children=p,s.childIndex=0,s.violations=h,s.tailViolations=m,s.phase="children";break}case"array":{if(!Array.isArray(s.value)){a([`"${$(s.path)}" must be an array`]);break}let u=Object.hasOwn(s.node,"items")?s.node.items:void 0,h=u===void 0?[]:s.value.flatMap((f,p)=>[{node:u,value:f,path:`${s.path}[${p}]`}]);s.kind="array",s.children=h,s.childIndex=0,s.violations=[],s.phase="children";break}case"string":a(typeof s.value=="string"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a string`]);break;case"number":a(typeof s.value!="number"?[`"${$(s.path)}" must be a number`]:Te(s.value)?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a finite JSON number`]);break;case"integer":a(!Te(s.value)||!Number.isInteger(s.value)?[`"${$(s.path)}" must be an integer`]:de(s.node,s.value,s.path));break;case"boolean":a(typeof s.value=="boolean"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a boolean`]);break;case"null":a(s.value===null?de(s.node,s.value,s.path):[`"${$(s.path)}" must be null`]);break;default:a(ge(l,"JsonSchemaType"))}}catch(l){let c=n.pop();for(;c!==void 0&&!c.catches;)c=n.pop();if(c===void 0)throw l;i(Qe(c.path))}}return o??Qe(r)}function Ir(e,t,r="value"){return po(e,t,r)}var fo=["description","title","default","examples"];function _(e){throw new Cr([e])}function pe(e,t){Object.hasOwn(e,"description")&&(t.description=e.description),Object.hasOwn(e,"title")&&(t.title=e.title),Object.hasOwn(e,"default")&&(t.default=e.default),Object.hasOwn(e,"examples")&&(t.examples=e.examples)}function fe(e,t,r){for(let n of Object.keys(e))r.includes(n)||_(`${t}.${n} is not supported by the value schema DSL`)}function ho(e,t){switch(e.kind){case"root":e.holder.value=t;break;case"property":Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0});break;case"item":e.target.items=t;break;case"one-of":e.target[e.index]=t;break}}function mo(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function Dr(e){let t=new Set,r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="leave"){t.delete(n.input);continue}if(n.kind==="property-map-tail"){n.required.length>0&&(n.compiled.required=n.required,n.destination.kind==="object"&&(n.destination.target.required=n.required));continue}if(n.kind==="property"){ne(n.property)||_(`${n.path} must be a value schema object`),Object.hasOwn(n.property,"required")&&n.property.required!==!0&&_(`${n.path}.required must be true when present`),Object.hasOwn(n.property,"required")&&n.property.required===!0&&n.required.push(n.key),r.push({kind:"value",input:n.property,path:n.path,allowRequired:!0,destination:{kind:"property",target:n.properties,key:n.key}});continue}if(n.kind==="property-map"){ne(n.input)||_(`${n.path} must be an object of value schemas`),t.has(n.input)&&_(`${n.path} is circular`),t.add(n.input);let c={properties:{}},u=[];mo(n.destination,c),r.push({kind:"leave",input:n.input}),r.push({kind:"property-map-tail",compiled:c,required:u,destination:n.destination});let h=Object.entries(n.input);for(let f=h.length-1;f>=0;f--){let p=h[f];p!==void 0&&r.push({kind:"property",property:p[1],path:`${n.path}.${p[0]}`,key:p[0],properties:c.properties,required:u})}continue}let{input:o,path:i}=n;ne(o)||_(`${i} must be a value schema object`),t.has(o)&&_(`${i} is circular`),t.add(o);let a=[...fo,...n.allowRequired?["required"]:[]],s={};if(ho(n.destination,s),r.push({kind:"leave",input:o}),Object.hasOwn(o,"oneOf")){fe(o,i,[...a,"oneOf","type"]),Object.hasOwn(o,"type")&&_(`${i} cannot declare both type and oneOf`),be(o.oneOf)||_(`${i}.oneOf must be an array of at least two value schemas`);let c=[];s.oneOf=c,pe(o,s);for(let u=o.oneOf.length-1;u>=0;u--)r.push({kind:"value",input:o.oneOf[u],path:`${i}.oneOf[${u}]`,allowRequired:!1,destination:{kind:"one-of",target:c,index:u}});continue}let l=Object.hasOwn(o,"type")?o.type:void 0;switch(l){case"json":fe(o,i,[...a,"type"]),pe(o,s);break;case"object":fe(o,i,[...a,"type","properties","additionalProperties"]),(!Object.hasOwn(o,"additionalProperties")||typeof o.additionalProperties!="boolean")&&_(`${i}.additionalProperties must be explicitly true or false`),s.type="object",pe(o,s),s.additionalProperties=o.additionalProperties,Object.hasOwn(o,"properties")&&r.push({kind:"property-map",input:o.properties,path:`${i}.properties`,destination:{kind:"object",target:s}});break;case"array":fe(o,i,[...a,"type","items"]),s.type="array",pe(o,s),Object.hasOwn(o,"items")&&r.push({kind:"value",input:o.items,path:`${i}.items`,allowRequired:!1,destination:{kind:"item",target:s}});break;case"string":case"number":case"integer":case"boolean":case"null":fe(o,i,[...a,"type","enum","const"]),s.type=l,pe(o,s),Object.hasOwn(o,"enum")&&(be(o.enum)||_(`${i}.enum must be a non-empty array of scalar values`),s.enum=Array.from(o.enum,c=>c)),Object.hasOwn(o,"const")&&(s.const=o.const);break;default:_(`${i}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function yo(e,t){let r={};return Dr({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function go(e,t){let r={};return Dr({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function bo(e){let t=go(e,"schema");return xe(t),t}function Pr(e){let t=yo(e,"parameters"),r={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return xe(r),r}var wo=class extends oe{violations;constructor(e){super(`invalid arguments: ${e.join("; ")}`,"INVALID_ARGS"),this.name="ToolArgsError",this.violations=e}};function vt(e){let t=e.execute,r=e.finalizeContent,n=e.output.render,o=e.output.presentationMeta,i=e.presentCall,a=e.presentResult,s=e.isConcurrencySafe;if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0))throw new Error(`defineTool(${e.name}): timeoutMs must be a positive finite number`);let l=Pr(e.parameters),c=bo(e.output.schema),u=f=>Ir(l,f,""),h={name:e.name,description:e.description,parameters:l,output:{schema:c,render(f,p){return n(f,p)},...o!==void 0?{presentationMeta(f,p){return o(f,p)}}:{}},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(f,p){let m=u(f);if(m.length>0)throw new wo(m);return t(f,p)}};return r&&(h.finalizeContent=(f,p)=>r(f,p)),i&&(h.presentCall=f=>{if(!(u(f).length>0))return i(f)}),a&&(h.presentResult=(f,p)=>{if(!(u(f).length>0))return a(f,p)}),s&&(h.isConcurrencySafe=f=>u(f).length>0?!1:s(f)),h}var B="run_code",Me={description:"Execute a TypeScript program against the available tools. Write the BODY of an async function (erasable syntax only; top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back \u2014 curate it.",codeDescription:"The program: the body of an async TypeScript function."},Ze={typescript:Me,python:{description:"Execute a Python program against the available tools. Write the BODY of an async function (top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Answer with `print(...)` and/or `return <value>` \u2014 only that comes back, so curate it.",codeDescription:"The program: the body of an async Python function."}},tr='Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; "Read failing test and its fixture"; "Rename config key in every cordis.yml".';function rr(e){let t=e();if(t===void 0)return Me;let r=Ze[t.language];if(!Object.hasOwn(Ze,t.language)||r===void 0){let n=Object.keys(Ze).map(o=>JSON.stringify(o)).join(", ");throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(t.language)} (known: ${n})`)}return r}var vo=class extends oe{constructor(e){super(e,"CODE_RUN_FAILED"),this.name="CodeRunFailedError"}};function xo(e){let t;try{t=H(e)}catch(n){throw new Error(`tool arguments must be lossless JSON: ${n instanceof Error?n.message:String(n)}`)}if(t===void 0)throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");let r=H(t);if(r===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:r}}var _e=" ",Oo=10;function So(e){let t=[],r=[{kind:"value",value:e,depth:0,compact:!1}];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="text"){t.push(n.text);continue}let o=n.value;if(o===null||typeof o=="boolean"||typeof o=="number"){t.push(String(o));continue}if(typeof o=="string"){t.push(JSON.stringify(o));continue}let i=n.compact||(n.depth+1)*2>Oo,a=n.depth+1;if(Array.isArray(o)){if(t.push("["),o.length===0){t.push("]");continue}r.push({kind:"text",text:i?"]":`
14
+ ${_e.repeat(n.depth)}]`});for(let l=o.length-1;l>=0;l--){let c=o[l];if(c===void 0)throw new Error("cannot render a sparse JSON array");r.push({kind:"value",value:c,depth:a,compact:i}),r.push({kind:"text",text:i?l===0?"":",":`${l===0?`
15
+ `:`,
16
+ `}${_e.repeat(a)}`})}continue}let s=Object.keys(o);if(t.push("{"),s.length===0){t.push("}");continue}r.push({kind:"text",text:i?"}":`
17
+ ${_e.repeat(n.depth)}}`});for(let l=s.length-1;l>=0;l--){let c=s[l];if(c===void 0)throw new Error("cannot render a missing JSON object key");let u=o[c];if(u===void 0)throw new Error("cannot render an undefined JSON object property");r.push({kind:"value",value:u,depth:a,compact:i}),r.push({kind:"text",text:i?`${l===0?"":","}${JSON.stringify(c)}:`:`${l===0?`
18
+ `:`,
19
+ `}${_e.repeat(a)}${JSON.stringify(c)}: `})}}return t.join("")}function ko(e){return typeof e=="string"?e:So(e)}function Eo(e,t){let{requireRuntime:r,peekRuntime:n,maxParallel:o,shapeDispatchLog:i}=t,a=vt({name:B,description:Me.description,parameters:{code:{type:"string",required:!0,description:Me.codeDescription},description:{type:"string",required:!0,description:tr}},output:{schema:{type:"object",additionalProperties:!1,properties:{logs:{type:"array",required:!0,items:{type:"string"}},result:{type:"json"}}},render:(s,l)=>{let c=l.result===void 0?"":ko(l.result),u=[l.logs.join(`
20
+ `),c].filter(h=>h.length>0);return[{type:"text",text:u.length>0?u.join(`
21
+ `):"(run_code completed with no output)"}]}},async execute(s,l){if(s.description.trim().length===0)throw new Error("invalid description: expected a non-empty string");let c=r(),u=new AbortController,h=()=>{u.abort(l.signal.reason)};l.signal.addEventListener("abort",h,{once:!0});let f=0,p=[],m=new Set,g=new Set,j=[],M=!1,R=!1,V=Promise.resolve(),te,v=()=>{let x=te;te=void 0,x?.()},O=()=>(R||(R=!0,V=(async()=>{try{for(;;){let x=new Promise(X=>{te=X}),J=j[0];if(J!==void 0&&J.settled){j.shift(),await J.commit(),J.mode==="exclusive"&&(M=!1);continue}let N=p[0];if(N!==void 0){if(u.signal.aborted){p.shift(),N.abandon();continue}let X=N.classify();if(!M&&(X==="exclusive"?m.size===0:m.size<o)){X==="exclusive"&&(M=!0),N.mode=X,p.shift(),j.push(N),await N.start();let G=N.flight.finally(()=>{m.delete(G),v()});m.add(G);continue}}if(p.length===0&&j.length===0&&m.size===0)return;await x}}finally{R=!1,te=void 0}})()),V),A=async()=>{for(await O();g.size>0;)await Promise.allSettled([...g])},Pt=()=>u.signal.aborted,un=x=>async J=>{if(Pt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} not dispatched`);let N=xo(J),X=++f,G=`${String(l.callId)}:code:${X}`,Ft={callId:G,rootCallId:l.rootCallId,name:x,arguments:N.dispatched,...l.agent?{agent:l.agent}:{},parent:l.token,signal:u.signal},je=e[Wr],ze=await new Promise((dn,pn)=>{let L,fn=S=>{dn(S.isError?{isError:!0,message:S.error.message}:{isError:!1,value:S.value});let W=l.agent;if(W===void 0)return;let Jt=(async()=>{let hn=await i({exec:l,agent:W,subCallId:G,name:x,isError:S.isError,content:S.content});W.session.append("tool/code-dispatch",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:G,name:x,arguments:N.logged,isError:S.isError,content:hn})})().finally(()=>{g.delete(Jt)});g.add(Jt)};p.push({flight:Promise.resolve(),settled:!1,classify:()=>e.executionMode(Ft).kind,abandon:()=>{pn(new Error(`run_code run is over (${String(u.signal.reason)}); ${x} tool call abandoned`))},async start(){l.agent?.session.append("tool/code-dispatch-start",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:G,name:x,arguments:N.logged});let S=await je.prepare(Ft);if(S.kind==="dispatch"){this.flight=je.dispatch(S.exec).then(W=>{L={kind:W.kind,exec:S.exec,result:W.result},this.settled=!0});return}L={kind:S.kind,exec:S.exec,result:S.result},this.settled=!0},async commit(){if(L===void 0)return;let S=L.kind==="post-result"?await je.finalize(L.exec,L.result):je.finish(L.exec,L.result);for(let W of S.additionalContexts??[])l.deferContext(W);for(S.concludesTurn&&l.concludeTurn(),fn(S);g.size>o;)await Promise.race(g)}}),v(),O()});if(Pt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} result discarded`);if(ze.isError)throw new Error(ze.message);return ze.value},qt=Object.create(null);for(let x of e.schemas(l.agent))x.name!=="run_code"&&Object.defineProperty(qt,x.name,{enumerable:!0,value:un(x.name)});try{let x;try{x=await c.run({program:s.code,bindings:[{global:"tools",functions:qt,errorClass:{name:"ToolCallError",memberNameProperty:"toolName"}}],signal:u.signal})}finally{u.abort("run_code settled"),await A()}if(x.error){let J=x.logs.length>0?`
22
+ Captured output:
23
+ ${x.logs.join(`
24
+ `)}`:"";throw new vo(`code run failed (${x.error.kind}): ${x.error.message}${J}`)}return{logs:x.logs,...x.value!==void 0?{result:x.value}:{}}}finally{l.signal.removeEventListener("abort",h)}},presentCall:s=>({card:"generic",title:s.description,kind:"execute",rawInput:s.code})});return Object.defineProperty(a,"description",{enumerable:!0,get:()=>rr(n).description}),Object.defineProperty(a,"parameters",{enumerable:!0,get:()=>Pr({code:{type:"string",required:!0,description:rr(n).codeDescription},description:{type:"string",required:!0,description:tr}})}),a}var jo=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ut(e){return jo.test(e)?e:JSON.stringify(e)}function we(e){return" ".repeat(e)}function qr(e,t){if(typeof e!="string"||e.length===0)return[];let r=e.replace(/\s+/g," ").trim();return[`${we(t)}/** ${r.replaceAll("*/",String.raw`*\/`)} */`]}function nr(e){return JSON.stringify(e)}function $o(e,t){let r=t==="integer"?"number":t;return Object.hasOwn(e,"const")?nr(e.const):Object.hasOwn(e,"enum")?e.enum.map(nr).join(" | "):r}function dt(e){return{parts:e,containsUnionOrIntersection:e.some(t=>typeof t=="string"?t.includes("|")||t.includes("&"):t.containsUnionOrIntersection)}}function q(...e){return dt(e)}function _o(e){let t=[],r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(typeof n=="string"){t.push(n);continue}for(let o=n.parts.length-1;o>=0;o--){let i=n.parts[o];i!==void 0&&r.push(i)}}return t.join("")}function or(e,t){return{node:e,indent:t,phase:"start",children:[],childIndex:0,childDocuments:[],entries:[]}}function Ro(e,t){let r=[or(e,t)],n,o=i=>{r.pop();let a=r.at(-1);a===void 0?n=i:a.childDocuments.push(i)};for(;r.length>0;){let i=r.at(-1);if(i===void 0)break;if(i.phase==="children"){if(i.childIndex<i.children.length){let u=i.children[i.childIndex];if(u===void 0)throw new Error("missing schema render child");i.childIndex++,r.push(or(u.node,u.indent));continue}if(i.kind==="oneOf"){let u=[];for(let h=0;h<i.childDocuments.length;h++){h>0&&u.push(" | ");let f=i.childDocuments[h];f!==void 0&&u.push(f)}o(dt(u));continue}if(i.kind==="array"){let u=i.childDocuments[0];if(u===void 0)throw new Error("missing array item type");o(u.containsUnionOrIntersection?q("(",u,")[]"):q(u,"[]"));continue}let s=new Set(i.node.required),l=["{"];for(let u=0;u<i.entries.length;u++){let h=i.entries[u],f=i.childDocuments[u];if(h===void 0||f===void 0)throw new Error("missing object property type");let[p,m]=h;for(let g of qr(m.description,i.indent+1))l.push(`
25
+ `,g);l.push(`
26
+ `,`${we(i.indent+1)}${ut(p)}${s.has(p)?"":"?"}: `,f,";")}l.push(`
27
+ `,`${we(i.indent)}}`);let c=dt(l);o(i.node.additionalProperties===!1?c:q(c," & Record<string, JsonValue>"));continue}let a=i.node;if(a.oneOf!==void 0){i.kind="oneOf",i.children=Array.from(a.oneOf,s=>({node:s,indent:i.indent})),i.childIndex=0,i.childDocuments=[],i.phase="children";continue}if(a.type===void 0){o(q("JsonValue"));continue}switch(a.type){case"string":case"number":case"integer":case"boolean":case"null":o(q($o(a,a.type)));break;case"array":a.items===void 0?o(q("JsonValue[]")):(i.kind="array",i.children=[{node:a.items,indent:i.indent}],i.childIndex=0,i.childDocuments=[],i.phase="children");break;case"object":{let s=a.additionalProperties!==!1,l=Object.entries(a.properties??{});l.length===0?o(q(s?"Record<string, JsonValue>":"Record<string, never>")):(i.kind="object",i.entries=l,i.children=l.map(([,c])=>({node:c,indent:i.indent+1})),i.childIndex=0,i.childDocuments=[],i.phase="children");break}default:o(q("unknown"))}}return n??q("unknown")}function ir(e,t=0){try{return xe(e),_o(Ro(e,t))}catch{return"unknown"}}var Ao='## Writing code for run_code\n\nPass `run_code` the body of an async TypeScript function (erasable syntax only \u2014 no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value. Tool arguments must be lossless JSON.\n- A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable \u2014 `try/catch` it to handle and continue.\n- Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit results with `return` and/or `console.log(...)`. ONLY what you print or return comes back to you \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function Co(e){let t=[...e].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0),r=[],n=[];for(let o of t)r.push(...qr(o.description,1)),r.push(`${we(1)}${ut(o.name)}: ${ir(o.parameters,1)};`),n.push(`${we(1)}${ut(o.name)}: ${ir(o.output,1)};`);return`${Ao}
28
+
29
+ \`\`\`ts
30
+ type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
31
+
32
+ ${[`interface ToolArgsMap {${r.length>0?`
33
+ ${r.join(`
34
+ `)}
35
+ `:""}}`,`interface ToolOutputMap {${n.length>0?`
36
+ ${n.join(`
37
+ `)}
38
+ `:""}}`,"type ToolName = keyof ToolOutputMap",["declare class ToolCallError extends Error {",' readonly name: "ToolCallError";'," readonly toolName: ToolName;","}"].join(`
39
+ `),["declare const tools: {"," [K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;","}"].join(`
40
+ `)].join(`
41
+
42
+ `)}
43
+ \`\`\``}var No=new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$","u");function Fr(e){return No.test(e)&&e.normalize("NFKC")===e}var Jr=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","__debug__"]),To=["Any","Literal","NotRequired","Protocol","TypedDict"];function T(e){return" ".repeat(e)}var Mo=/[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g,Io=/[\ud800-\udfff]/gu;function xt(e){let t=e.description;if(typeof t!="string")return;let r=t.replace(/\s+/g," ").replace(Mo,n=>`\\x${n.charCodeAt(0).toString(16).padStart(2,"0")}`).replace(Io,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`).trim();return r.length===0?void 0:r}function Do(e,t){let r=xt({description:e});if(r===void 0)return[];let n=r.replaceAll("\\","\\\\").replaceAll('"','\\"');return[`${T(t)}"""${n}"""`]}function pt(e){let t=e.split(/[^\p{XID_Continue}]+|_+/u).filter(r=>r.length>0).map(r=>`${r.charAt(0).toUpperCase()}${r.slice(1)}`).join("").normalize("NFKC");return(new RegExp("^\\p{XID_Start}","u").test(t)?t:`Tool${t}`).normalize("NFKC")}var sr=120,Po=180;function Lr(e){if(e.length<=sr)return e;let t=e.slice(0,sr);return/[\uD800-\uDBFF]$/.test(t)?t.slice(0,-1):t}function qo(e,t){let r=Lr(e),n=r;if(t.usedClassNames.has(n)){let o=t.nextClassCounter.get(r)??2;for(;t.usedClassNames.has(`${r}${o}`);)o++;n=`${r}${o}`,t.nextClassCounter.set(r,o+1)}return t.usedClassNames.add(n),n}function ar(e,t){return Lr(`${e}${t}`.normalize("NFKC"))}function lr(e){return e===!0?"True":e===!1?"False":typeof e=="string"?JSON.stringify(e):typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e)?BigInt(e).toString():String(e)}function Re(e,t,r){return e.const!==void 0?(r.typing.add("Literal"),`Literal[${lr(e.const)}]`):e.enum!==void 0?(r.typing.add("Literal"),`Literal[${e.enum.map(lr).join(", ")}]`):t}function cr(e,t,r){let n=(o,i,a)=>({schema:o,className:i,phase:"start",listDepth:a,children:[],childIndex:0,childTypes:[],entries:[]});try{xe(e);let o=[n(e,t,0)],i,a=s=>{o.pop();let l=o.at(-1);l===void 0?i=s:l.childTypes.push(s)};for(;o.length>0;){let s=o.at(-1);if(s===void 0)break;if(s.phase==="children"){if(s.childIndex<s.children.length){let p=s.children[s.childIndex];if(p===void 0)throw new Error("missing python render child");s.childIndex++,o.push(n(p.schema,p.className,p.listDepth));continue}if(s.kind==="oneOf"){let p="";for(let[m,g]of s.childTypes.entries())p=m===0?g:`${p} | ${g}`;a(p);continue}if(s.kind==="array"){a(`list[${s.childTypes[0]??"Any"}]`);continue}let c=s.node,u=s.allocated;if(c===void 0||u===void 0)throw new Error("missing typeddict frame state");let h=new Set(c.required),f=[`class ${u}(TypedDict):`];for(let p=0;p<s.entries.length;p++){let m=s.entries[p],g=s.childTypes[p];if(m===void 0||g===void 0)throw new Error("missing typeddict field type");let[j,M]=m,R=xt(M);R!==void 0&&f.push(`${T(1)}# ${R}`),h.has(j)?f.push(`${T(1)}${j}: ${g}`):(r.typing.add("NotRequired"),f.push(`${T(1)}${j}: NotRequired[${g}]`))}c.additionalProperties!==!1&&f.push(`${T(1)}# Additional keys beyond those declared are allowed.`),f.length===1&&f.push(`${T(1)}pass`),r.classes.push(f.join(`
44
+ `)),a(u);continue}s.phase="children";let l=s.schema;if(l.oneOf!==void 0){s.kind="oneOf",s.children=l.oneOf.map((c,u)=>({schema:c,className:ar(s.className,`${u+1}`),listDepth:s.listDepth}));continue}if(l.type===void 0){r.typing.add("Any"),a("Any");continue}switch(l.type){case"string":a(Re(l,"str",r));break;case"number":a(Re(l,"float",r));break;case"integer":a(Re(l,"int",r));break;case"boolean":a(Re(l,"bool",r));break;case"null":a("None");break;case"array":if(l.items===void 0){r.typing.add("Any"),a("list[Any]");break}if(s.listDepth>=Po){r.typing.add("Any"),a("Any");break}s.kind="array",s.children=[{schema:l.items,className:s.className,listDepth:s.listDepth+1}];break;case"object":{let c=Object.entries(l.properties??{});if(t===""||!c.every(([u])=>Fr(u)&&!Jr.has(u)&&!(u.startsWith("__")&&!u.endsWith("__")))){r.typing.add("Any"),a("dict[str, Any]");break}if(c.length===0&&l.additionalProperties!==!1){r.typing.add("Any"),a("dict[str, Any]");break}s.kind="typeddict",s.node=l,s.allocated=qo(s.className,r),r.typing.add("TypedDict"),s.entries=c,s.children=c.map(([u,h])=>({schema:h,className:ar(s.allocated??"",pt(u)),listDepth:1}));break}default:r.typing.add("Any"),a("Any")}}return i??"Any"}catch{return r.typing.add("Any"),"Any"}}var Fo='## Writing code for run_code\n\nPass `run_code` the body of an async Python function (top-level `await` and `return` both work). At run time exactly two of the names declared below are bound: `tools` and `ToolCallError`. Everything else is a STATIC STUB describing argument and return types \u2014 in particular the `TypedDict` classes do NOT exist at run time, so build arguments as plain `dict`/`list` JSON values: `await tools.name({"field": 1})`, never `FooArgs(field=1)`, which raises `NameError`. Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 subscript access for exotic, reserved, or underscore-leading names: `await tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value (each method\'s return type below). Tool arguments must be lossless JSON.\n- A FAILED tool call raises `ToolCallError`, whose `toolName` identifies the failed tool and whose message is human-readable \u2014 wrap in `try/except` to handle and continue.\n- Independent read-only calls MAY overlap under `asyncio.gather` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit the run\'s answer with `print(...)` and/or a top-level `return <value>`; the returned value must be lossless JSON. ONLY what you print and the returned value come back \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function Jo(e){let t=[...e].sort((l,c)=>l.name<c.name?-1:l.name>c.name?1:0),r={classes:[],usedClassNames:new Set,nextClassCounter:new Map,typing:new Set(["Protocol"])},n=[],o=0;for(let l of t){let c=cr(l.parameters,`${pt(l.name)}Args`,r),u=cr(l.output,`${pt(l.name)}Output`,r);if(Fr(l.name)&&!Jr.has(l.name)&&!l.name.startsWith("_")){let h=Do(l.description,2);n.push(h.length>0?`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}:`:`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}: ...`),n.push(...h),o+=1}else{n.push(`${T(1)}# tools[${JSON.stringify(l.name)}](args: ${c}) -> ${u}`);let h=xt(l);h!==void 0&&n.push(`${T(1)}# ${h}`)}}let i=(o>0?n:[`${T(1)}pass`,...n]).join(`
45
+ `),a=To.filter(l=>r.typing.has(l)),s=r.classes.length>0?`${r.classes.join(`
46
+
47
+ `)}
48
+
49
+ `:"";return`${Fo}
50
+
51
+ \`\`\`python
52
+ ${`from typing import ${a.join(", ")}
53
+
54
+ class ToolCallError(Exception):
55
+ toolName: str
56
+
57
+ ${s}class Tools(Protocol):
58
+ ${i}
59
+
60
+ tools: Tools`}
61
+ \`\`\``}var et={typescript:Co,python:Jo},Wr=Symbol("@deepseek-ai/dsh-tools.scheduler"),Lo="ABORTED",Wo="ABORTED_BEFORE_DISPATCH",tt=class extends oe{constructor(e){super(`unknown tool "${e}"`,"UNKNOWN_TOOL"),this.name="ToolNotFoundError"}},ee=class extends oe{violations;constructor(e,t){super(`tool "${e}" returned invalid output: ${t.join("; ")}`,"INVALID_TOOL_OUTPUT"),this.name="ToolOutputError",this.violations=t}};function ft(e,t,r){return new ee(e,[`output.${t} failed: ${ve(r)}`])}function ur(e,t,r){try{let n=H(r);if(n===void 0)throw new ee(e,[`output.${t} returned non-lossless JSON`]);return n}catch(n){throw n instanceof ee?n:ft(e,t,n)}}function Bo(e,t){try{let r=H(t);if(r===void 0)throw new ee(e,["value is not lossless JSON"]);return r}catch(r){throw r instanceof ee?r:new ee(e,[`value snapshot failed: ${ve(r)}`])}}function ve(e){try{return e instanceof Error||typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:String(e)}catch{return"<unprintable thrown value>"}}function zo(e){let t=e.map(r=>r.type==="text"?r.text:`[${r.type} content]`).join(`
62
+ `);return t.length>0?t:"tool result blocked by post-execute policy"}function dr(e){let t=H(e);if(t===void 0)throw new TypeError("tool result must be losslessly JSON-serializable");return ye(t)}function Uo(e){try{return e instanceof oe?{name:e.name,code:e.code}:void 0}catch{return}}var Ho=class{tools;restrictions=new Xt;guards=new Xt;mode;constructor(e){this.tools=new Ln(t=>new Error(e===void 0?`tool "${t}" is already registered (for a per-agent variant, register through that agent's \`agent.ctx\` instead)`:`tool "${t}" is already registered in this scope`))}isEmpty(){return this.tools.isEmpty()&&this.restrictions.isEmpty()&&this.guards.isEmpty()&&this.mode===void 0}admits(e){for(let t of this.restrictions.values())if(t.allow!==void 0&&!t.allow.has(e)||t.deny!==void 0&&t.deny.has(e))return!1;return!0}guardReason(e){for(let t of this.guards.values()){let r=t(e);if(r!==void 0)return r}}};function Ko(e){let t=e??10;if(!Number.isInteger(t)||t<1)throw new Error("maxParallelSubCalls must be a positive integer");return t}var Gi=class extends Jn{static inject=["systemPrompt"];static Config=d.object({mode:d.union(["native","code","both"]).default("native"),maxParallelSubCalls:d.natural().min(1).default(10)});[Wr]={prepare:e=>this.prepareScheduledExecution(e),dispatch:e=>this.dispatchScheduledExecution(e),finalize:(e,t)=>this.finalizeScheduledExecution(e,t),finish:(e,t)=>this.finishScheduledExecution(e,t)};deferredContexts=new WeakMap;concludingExecutions=new WeakSet;cancellationStates=new WeakMap;contentFinalizers=new WeakMap;layers=new Wn(e=>new Ho(e),()=>{this.ctx.emit("tools/change")});defaultMode;maxParallelSubCalls;codeTransport;constructor(e,t={}){super(e,"tools"),this.defaultMode=t.mode??"native",this.maxParallelSubCalls=Ko(t.maxParallelSubCalls),e.systemPrompt.tools(r=>this.wireSchemas(r.scope)),this.defaultMode!=="native"&&e.systemPrompt.section(this.sdkSection())}sdkSection(){return{name:"tools:sdk",order:150,text:e=>{let t=this.modeFor(e.scope);if(t==="native")return"";let r=this.requireCodeRuntime(t),n=et[r.language];if(n===void 0)throw new Error(`dsh-tools: no SDK renderer for ${r.language}`);return n(this.sdkSchemas(e.scope))}}}modeFor(e){let t=this.layers.chainLayers(e);for(let r=t.length-1;r>=0;r-=1){let n=t[r]?.mode;if(n!==void 0)return n}return this.defaultMode}requireCodeTransport(){return this.codeTransport??=Eo(this,{requireRuntime:()=>this.requireCodeRuntime(this.defaultMode),peekRuntime:()=>this.ctx.get("codeRuntime"),maxParallel:this.maxParallelSubCalls,shapeDispatchLog:e=>this.shapeDispatchLog(e)}),this.codeTransport}presentAs(e){let t=this.ctx;if(Ne(t)===void 0)throw new Error("tools.presentAs() requires a scoped context (agent.ctx): a context-global presentation is the `mode` config field on the tools row");return t.effect(function*(){yield this.layers.effect(t,r=>{if(r.mode!==void 0)throw new Error(`tools.presentAs("${e}") conflicts with "${r.mode}" already declared for this agent; one composition selects one presentation`);return r.mode=e,()=>{r.mode=void 0}},{label:"tools.presentAs()"}),e!=="native"&&(yield t.systemPrompt.section(this.sdkSection()))}.bind(this),"tools.presentAs()")}wireSchemas(e){let t=this.view(e),r=this.modeFor(e);if(r==="native")return{schemas:[...t.visible.values()].map(o=>this.schemaOf(o,!1)),knownNames:[...t.knownNames]};this.requireCodeRuntime(r);let n=[...t.visible.values()].map(o=>this.schemaOf(o,!1));return r==="code"?{schemas:n.filter(o=>o.name===B),knownNames:[B]}:{schemas:n,knownNames:[...t.knownNames,B]}}requireCodeRuntime(e){let t=this.ctx.get("codeRuntime");if(!t)throw new Error(`dsh-tools: mode "${e}" requires a code runtime \u2014 load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker) or set tools mode to "native"`);if(!Object.hasOwn(et,t.language)){let r=Object.keys(et).map(n=>JSON.stringify(n)).join(", ");throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(t.language)} (known: ${r})`)}return t}register(e){let t=e.name,r=e.output;if(r===void 0||typeof r!="object"||typeof r.render!="function"||r.presentationMeta!==void 0&&typeof r.presentationMeta!="function")throw new TypeError(`tool "${t}" must declare output { schema, render, presentationMeta? }`);xe(r.schema);let n=e.timeoutMs;if(n!==void 0&&(!Number.isFinite(n)||n<=0))throw new TypeError(`tool "${t}" timeoutMs must be a positive finite number`);if(t==="run_code")throw new Error(`tool name "${B}" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`);return this.layers.effect(this.ctx,o=>o.tools.insert(t,e),{label:"tools.register()"})}restrict(e){let t=Ne(this.ctx);if(t===void 0)throw new Error("tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent \u2014 deny the tool for the intended agent instead");let r=e.allow,n=e.deny;if(r===void 0&&n===void 0)throw new Error("tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)");let o={...r!==void 0?{allow:new Set(r)}:{},...n!==void 0?{deny:new Set(n)}:{}};if([...r??[],...n??[]].includes("run_code"))throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport "${B}"; restrict end-capability tools instead`);let i=this.view(t).restrictableNames,a=[...r??[],...n??[]].filter(s=>!i.has(s));if(a.length>0)throw new Error(`tools.restrict() names unknown inherited tool${a.length>1?"s":""} ${a.map(s=>`"${s}"`).join(", ")}; a restriction filters what this scope inherits, never what it registers itself. Restrictable tools: ${[...i].sort().join(", ")||"(none)"}`);return this.layers.effect(this.ctx,s=>s.restrictions.append(o),{label:"tools.restrict()"})}guard(e){return this.layers.effect(this.ctx,t=>t.guards.append(e),{label:"tools.guard()",notify:!1})}guardReason(e){let t=this.layers.global.guardReason(e);if(t!==void 0)return t;if(e.agent!==void 0)for(let r of this.layers.chainLayers(e.agent)){let n=r.guardReason(e);if(n!==void 0)return n}}view(e){let t=this.layers.chainLayers(e),r=this.layers.peek(e),n=new Map(this.layers.global.tools.entries());for(let s of t)if(s!==r)for(let[l,c]of s.tools.entries())n.set(l,c);let o=new Map,i=new Set,a=new Set;for(let[s,l]of n)i.add(s),a.add(s),t.every(c=>c.admits(s))&&o.set(s,l);if(r!==void 0)for(let[s,l]of r.tools.entries())i.add(s),o.set(s,l);return this.modeFor(e)!=="native"&&o.set(B,this.requireCodeTransport()),{visible:o,knownNames:i,restrictableNames:a}}get(e,t){return this.view(t).visible.get(e)}schemas(e){return[...this.view(e).visible.values()].map(t=>this.schemaOf(t,!0))}sdkSchemas(e){return[...this.view(e).visible.values()].filter(t=>t.name!==B).map(t=>{let r=H(t.output.schema);if(r===void 0)throw new Error(`tool "${t.name}" output schema must be lossless JSON before SDK projection`);return{...this.schemaOf(t,!0),output:r}})}schemaOf(e,t){let{name:r,description:n,parameters:o}=e,i=t?H(o):o;if(i===void 0)throw new Error(`tool "${r}" parameters must be lossless JSON before schema projection`);return{name:r,description:n,parameters:i}}executionMode(e){let t=this.get(e.name,e.agent);if(!t?.isConcurrencySafe)return{kind:"exclusive"};try{return t.isConcurrencySafe(e.arguments)===!0?{kind:"parallel"}:{kind:"exclusive"}}catch{return{kind:"exclusive"}}}async shapeDispatchLog(e){try{return await this.ctx.waterfall(ue(this,e.agent),"tools/code-dispatch-log",e,()=>Promise.resolve(e.content))}catch(t){return this.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${e.name}: ${ve(t)}; logging the original settled content`),e.content}}async execute(e){return this.prepareExecution(e,t=>this.completeScheduledExecution(t))}async completeScheduledExecution(e){switch(e.kind){case"dispatch":{let t=await this.dispatchScheduledExecution(e.exec);return t.kind==="post-result"?await this.finalizeScheduledExecution(e.exec,t.result):this.finishScheduledExecution(e.exec,t.result)}case"post-result":return await this.finalizeScheduledExecution(e.exec,e.result);case"final-result":return this.finishScheduledExecution(e.exec,e.result);default:return ge(e,"scheduled tool preparation")}}createExecution(e){let t=[],r=Vo(),n=e.callId,o=e.rootCallId??n,i=e.name,a=e.agent,s=e.parent,l=e.signal,c=this.get(i,a),u=c?.finalizeContent?.bind(c),h=this.concludingExecutions,f={token:r,callId:n,rootCallId:o,name:i,signal:l,...a!==void 0?{agent:a}:{},...s!==void 0?{parent:s}:{},deferContext(p){t.push(p)},concludeTurn(){h.add(this)}};try{let p=H(e.arguments);if(p===void 0)throw new TypeError("tool execution arguments must be losslessly JSON-serializable");let m={...f,arguments:ye(p)};return this.deferredContexts.set(m,t),this.contentFinalizers.set(m,u),this.cancellationStates.set(m,{callerSignal:l,bodyInvoked:!1}),{kind:"ready",exec:m}}catch(p){let m={...f,arguments:void 0};return this.contentFinalizers.set(m,u),{kind:"final-result",exec:m,result:Y(p)}}}async prepareScheduledExecution(e){return this.prepareExecution(e,t=>t)}async prepareExecution(e,t){let r=this.createExecution(e);if(r.kind!=="ready")return t(r);let n=r.exec;if(this.callerCancelled(n))return t({kind:"final-result",exec:n,result:he()});try{let o=ue(this,n.agent),i=await this.ctx.waterfall(o,"tools/pre-execute",n,()=>Promise.resolve({kind:"allow"})),a=i.kind==="ask"?await this.serviceAsk(n,i):{decision:i,approvalCancelled:!1},{decision:s}=a;if(this.callerCancelled(n)&&a.approvalCancelled)return await t({kind:"post-result",exec:n,result:he()});let l=s.kind==="allow"?this.guardReason(n):s.reason;return l!==void 0?await t({kind:"post-result",exec:n,result:this.materializeFinalResult({content:[{type:"text",text:`Error: ${l}`}],isError:!0,error:{message:l}})}):this.callerCancelled(n)?await t({kind:"post-result",exec:n,result:he()}):await t({kind:"dispatch",exec:n})}catch(o){return t({kind:"final-result",exec:n,result:Y(o)})}}callerCancelled(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return t.callerSignal.aborted}cancellationResult(e,t){let r=this.cancellationStates.get(e);if(r===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return r.bodyInvoked?fr(t):he(t)}async dispatchToolBody(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");let r=e.signal,n=Xo(t.callerSignal,r),o=n.signal;if(pr(o))return n.dispose(),he();e.signal=o;try{let i=this.get(e.name,e.agent);if(!i)throw new tt(e.name);t.bodyInvoked=!0;let a=await i.execute(e.arguments,e),s=this.createSuccessResult(e,i,a);return pr(o)?fr(s):s}catch(i){return Y(i)}finally{n.dispose(),e.signal=r}}async dispatchScheduledExecution(e){try{let t=e,r=ue(this,e.agent),n=await this.ctx.waterfall(r,"tools/execute",t,()=>this.dispatchToolBody(t)),o=this.normalizeDispatchResult(e,n),i=this.deferredContexts.get(e);if(i===void 0)throw new Error("tool registry scheduler invariant violated: unprepared execution");let a=i.length===0?o:this.markCanonical(e,{...o,additionalContexts:[...i,...o.additionalContexts??[]]});return{kind:"post-result",result:this.callerCancelled(e)&&!a.isError?this.cancellationResult(e,a):a}}catch(t){return{kind:"final-result",result:Y(t)}}}async finalizeScheduledExecution(e,t){try{let r=await this.postExecute(e,t);return this.finishScheduledExecution(e,this.callerCancelled(e)&&!r.isError?this.cancellationResult(e,r):r)}catch(r){return this.finishScheduledExecution(e,Y(r))}}finishScheduledExecution(e,t){let r;try{r=this.materializeFinalResult(t)}catch(o){r=this.materializeFinalResult(Y(o))}let n;try{n=this.materializeFinalResult(this.applyFinalContent(e,r))}catch(o){n=this.materializeFinalResult(Y(o))}return this.notifyResult(e,n),n}applyFinalContent(e,t){let r=this.contentFinalizers.get(e);if(r===void 0)return t;let n=r(e,t);return n===void 0?t:{...t,content:n}}notifyResult(e,t){Object.freeze(e);let{name:r,callId:n}=e,o=a=>{this.ctx.logger.warn(`tool "${r}" (${n}): tools/result observer failed: ${ve(a)}`)},i=this.ctx.events.dispatch("emit",[ue(this,e.agent),"tools/result",e,t]);for(let a of i)try{let s=a(e,t);Promise.resolve(s).catch(o)}catch(s){o(s)}}async serviceAsk(e,t){let r=this.ctx.get("approval");if(r===void 0)return{decision:{kind:"deny",reason:t.reason??`tool "${e.name}" requires approval (not yet supported)`},approvalCancelled:!1};if(e.agent===void 0)return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but the call has no agent to route it through`},approvalCancelled:!1};let n=await r.request({agent:e.agent,toolName:e.name,callId:e.callId,...t.reason!==void 0?{reason:t.reason}:{},signal:e.signal});switch(n){case"allowed-once":return{decision:{kind:"allow"},approvalCancelled:!1};case"rejected":return{decision:{kind:"deny",reason:`the user rejected tool "${e.name}"`},approvalCancelled:!1};case"cancelled":return{decision:{kind:"deny",reason:`approval for tool "${e.name}" was cancelled`},approvalCancelled:!0};case"unavailable":return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but no approval channel is available`},approvalCancelled:!1};default:return ge(n,"ApprovalOutcome")}}async postExecute(e,t){let r=await this.ctx.waterfall(ue(this,e.agent),"tools/post-execute",e,t,()=>Promise.resolve({kind:"accept"})),n=r.additionalContexts??[];if(r.kind==="block"){let i=zo(r.feedback);return this.markCanonical(e,{content:r.feedback,isError:!0,error:{message:i},...n.length>0?{additionalContexts:n}:{}})}if(Object.hasOwn(r,"content")&&Object.hasOwn(r,"value"))throw new TypeError("tools/post-execute accept decision cannot replace both value and content");let o=[...t.additionalContexts??[],...n];if(Object.hasOwn(r,"value")){if(t.isError)throw new TypeError("tools/post-execute cannot replace the value of a failed result");let i=this.get(e.name,e.agent);if(i===void 0)throw new tt(e.name);let a=this.createSuccessResult(e,i,r.value);return this.markCanonical(e,{...a,...o.length>0?{additionalContexts:o}:{}})}return this.markCanonical(e,{...t,...r.content!==void 0?{content:r.content}:{},...o.length>0?{additionalContexts:o}:{}})}canonicalResults=new WeakMap;markCanonical(e,t){return this.canonicalResults.set(t,e.token),t}createSuccessResult(e,t,r){let n=Bo(t.name,r),o=Ir(t.output.schema,n,"value");if(o.length>0)throw new ee(t.name,o);let i=ye(n),a;try{a=t.output.render(e.arguments,i)}catch(u){throw ft(t.name,"render",u)}let s=ur(t.name,"render",a),l;if(e.parent===void 0&&t.output.presentationMeta!==void 0){let u;try{u=t.output.presentationMeta(e.arguments,i)}catch(h){throw ft(t.name,"presentationMeta",h)}l=ur(t.name,"presentationMeta",u)}let c=this.concludingExecutions.has(e);return this.markCanonical(e,this.materializeFinalResult({isError:!1,value:i,content:s,...l!==void 0?{meta:l}:{},...c?{concludesTurn:!0}:{}}))}normalizeDispatchResult(e,t){if(this.canonicalResults.get(t)===e.token)return t;if(t.isError)return this.markCanonical(e,{isError:!0,error:t.error,content:t.content,...t.meta!==void 0?{meta:t.meta}:{},...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}});let r=this.get(e.name,e.agent);if(r===void 0)throw new tt(e.name);let n=this.createSuccessResult(e,r,t.value);return this.markCanonical(e,{...n,...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}})}materializeFinalResult(e){let t={content:e.content,...e.meta!==void 0?{meta:e.meta}:{},...e.additionalContexts!==void 0?{additionalContexts:e.additionalContexts}:{}};return e.isError?dr({isError:!0,error:e.error,...t}):ye({...dr({isError:!1,...t,...e.concludesTurn===!0?{concludesTurn:!0}:{}}),value:e.value})}};function Vo(){return Symbol("dsh.tool.execution")}function Y(e){let t=Uo(e),r=ve(e);return{content:[{type:"text",text:`Error: ${r}`}],isError:!0,error:{message:r,...t?{info:t}:{}}}}function pr(e){return e.aborted}function Xo(e,t){if(e===t)return{signal:e,dispose(){}};let r=new AbortController,n=!1,o=()=>{n&&(n=!1,e.removeEventListener("abort",a),t.removeEventListener("abort",s))},i=l=>{let c=l.reason;r.abort(c),o()},a=()=>{i(e)},s=()=>{i(t)};return t.aborted?s():e.aborted?a():(n=!0,e.addEventListener("abort",a,{once:!0}),t.addEventListener("abort",s,{once:!0})),{signal:r.signal,dispose:o}}function fr(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted"}],isError:!0,error:{message:"tool call aborted",info:{name:"AbortError",code:Lo}},...t.length>0?{additionalContexts:t}:{}}}function he(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted before dispatch"}],isError:!0,error:{message:"tool call aborted before dispatch",info:{name:"AbortError",code:Wo}},...t.length>0?{additionalContexts:t}:{}}}var C=class extends Error{constructor(r,n,o){super(r,o);this.code=n;this.name="MemError"}code};var Ot=e=>e.toLowerCase().replace(/\s+/gu," ").trim();function Yo(e){let t=[e.title,e.subtitle,e.text,e.narrative].map(n=>Ot(n??"")),r=(e.facts??[]).map(Ot);return t.some(Boolean)||r.some(Boolean)?JSON.stringify([...t,r]):""}function Br(e){let t=new Set;return e.filter(r=>{let n=Yo(r);return n?t.has(n)?!1:(t.add(n),!0):!0})}function zr(e){let t=new Set;return e.split(`
63
+ `).filter(r=>{if(!/^\|\s*#\d+\s*\|.*\|$/u.test(r))return!0;let n=r.slice(1,-1).split("|");if(n.length<5)return!0;let o=JSON.stringify(n.slice(2).map(Ot));return t.has(o)?!1:(t.add(o),!0)}).join(`
64
+ `)}import{randomBytes as Vr}from"node:crypto";import{constants as Xr,openSync as Yr,closeSync as Qr,readFileSync as bi,writeFileSync as wi,fstatSync as vi,fchmodSync as xi,fsyncSync as Oi,linkSync as Si,unlinkSync as ki,mkdirSync as Ei}from"node:fs";import{join as Et}from"node:path";import{join as K,dirname as ai,basename as li}from"path";import{homedir as Kr}from"os";import{existsSync as ci,mkdirSync as Xs}from"fs";import{fileURLToPath as ui}from"url";import{closeSync as Os,existsSync as Ss,fsyncSync as ks,lstatSync as Es,mkdirSync as js,openSync as $s,readFileSync as Qo,readlinkSync as _s,realpathSync as Rs,renameSync as As,statSync as Cs,unlinkSync as Ns,writeSync as Ts}from"fs";var bs=Promise.resolve();var Is=process.platform==="win32";function Zo(e){return e.replace(/^\uFEFF/,"")}function ei(e){return JSON.parse(Zo(e))}function St(e){return ei(Qo(e,"utf-8"))}var ie="MEMINDEX_",ti="AGENT_MEM_",Oe=[ti];function qe(e){return e.startsWith(ie)||Oe.some(t=>e.startsWith(t))}function kt(e){if(!e.startsWith(ie))return[];let t=e.slice(ie.length);return Oe.map(r=>r+t)}function ri(e=process.env){for(let t of Oe)for(let r of Object.keys(e)){if(!r.startsWith(t))continue;let n=ie+r.slice(t.length);e[n]===void 0&&(e[n]=e[r])}}function Ur(e){let t=null;for(let r of Oe)for(let n of Object.keys(e)){if(!n.startsWith(r))continue;let o=ie+n.slice(r.length);(t??e)[o]===void 0&&(t??={...e},t[o]=e[n])}return t??e}ri();var ni=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function oi(e){let t=e.env;return ni(t)&&Object.keys(t).some(qe)?"nested":"flat"}function Hr(e){return oi(e)==="nested"?e.env:e}import{homedir as ii}from"os";import{join as si}from"path";function se(e,t=process.platform,r=ii()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?si(r,e.slice(2)):e}function di(){return typeof __dirname<"u"?__dirname:ai(ui(import.meta.url))}var ra=di();function pi(e){let t=process.env.MEMINDEX_TEST_FORBIDDEN_DATA_DIR;if(t&&e===t)throw new Error(`A test resolved the real data folder ${e}. Point MEMINDEX_DATA_DIR at a temporary directory (and pass env: process.env to any child process the test starts).`);return e}function Se(){return pi(fi())}function fi(){if(process.env.MEMINDEX_DATA_DIR)return se(process.env.MEMINDEX_DATA_DIR);let e=K(Kr(),".memindex"),t=K(e,"settings.json");try{if(ci(t)){let r=St(t);if(r===null||typeof r!="object"||Array.isArray(r))return e;let n=Ur(Hr(r));if(typeof n.MEMINDEX_DATA_DIR=="string"&&n.MEMINDEX_DATA_DIR)return se(n.MEMINDEX_DATA_DIR)}}catch{}return e}var Fe=Se(),hi=K(Kr(),".claude"),mi=process.env.CLAUDE_CONFIG_DIR||hi,na=K(mi,"plugins","marketplaces","memindex"),oa=K(Fe,"logs"),ia=K(Fe,"settings.json"),yi="memindex.db";var sa=K(Fe,yi),gi=K(Fe,"observer-sessions"),aa=li(gi);var ji="X-Memindex-Secret",Zr="worker-secret",$i=/^[a-f0-9]{64}$/;function Gr(e=Se()){let t=Yr(Et(e,Zr),Xr.O_RDONLY|(Xr.O_NOFOLLOW??0));try{let r=vi(t);if(!r.isFile()||process.getuid&&r.uid!==process.getuid()||process.platform!=="win32"&&(r.mode&63)!==0)throw new Error("Worker secret must be an owner-only file");let n=bi(t,"utf8");if(!$i.test(n))throw new Error("Invalid worker secret");return n}finally{Qr(t)}}function _i(e=Se()){Ei(e,{recursive:!0,mode:448});let t=Et(e,Zr);try{return Gr(e)}catch(o){if(o.code!=="ENOENT")throw o}let r=Et(e,`.worker-secret-${Vr(16).toString("hex")}`),n=Yr(r,"wx",384);try{xi(n,384),wi(n,Vr(32).toString("hex")),Oi(n)}finally{Qr(n)}try{try{Si(r,t)}catch(o){if(o.code!=="EEXIST")throw o}}finally{ki(r)}return Gr(e)}function Je(e,t=Se()){if(!["POST","PUT","PATCH","DELETE"].includes((e.method??"GET").toUpperCase()))return e;let r=new Headers(e.headers);return r.set(ji,_i(t)),{...e,headers:r,redirect:"error"}}function jt(e,t={}){let r=new URLSearchParams;return Object.entries(e).forEach(([n,o])=>{o!==void 0&&r.set(t[n]??n,String(o))}),r.size?`?${r}`:""}var Le=class{constructor(t){this.settings=t}settings;search(t,r){return this.readIndex("/api/search",jt({...t},{obsType:"obs_type"}),r)}timeline(t,r){let n=jt({...t},{depthBefore:"depth_before",depthAfter:"depth_after"});return this.readIndex("/api/timeline",n,r)}async getObservations(t,r){if(!t.ids.length)throw new C("Choose at least one memory id.","MEM_INVALID_REQUEST");let n=await this.exchange("/api/observations/batch",r,t);return{items:Array.isArray(n)?n.map(tn):[]}}async save(t,r){if(!t.text.trim())throw new C("Enter some memory text.","MEM_INVALID_REQUEST");return await this.exchange("/api/memory/save",r,t)}async context(t,r){let n=t.projects?.trim(),o=t.cwd?.trim();if(!n&&!o)throw new C("Choose a project or checkout folder.","MEM_INVALID_REQUEST");let i=jt({...t,projects:n||void 0,cwd:o||void 0});return await this.exchange(`/api/context/inject${i}`,r,void 0,!0)}async sessionInit(t,r){await this.exchange("/api/sessions/init",r,t)}async sessionSummarize(t,r){await this.exchange("/api/sessions/summarize",r,t)}async readIndex(t,r,n){let o=await this.exchange(`${t}${r}`,n),i=$t(o),a=Array.isArray(o)?o:Array.isArray(i.items)?i.items:[],l=(Array.isArray(i.content)?i.content:[]).flatMap(h=>{let f=$t(h);return f.type==="text"&&typeof f.text=="string"?[f.text]:[]}),c=a.map(tn),u=l.length?l.join(`
65
+ `):void 0;return this.settings.dedupe!==!1&&(c=Br(c),u!==void 0&&(u=zr(u))),u===void 0?{items:c}:{items:c,content:u}}async exchange(t,r,n,o=!1){if(r?.aborted)throw new C("Memory operation cancelled.","MEM_ABORTED");let i=new AbortController,a=()=>i.abort(r?.reason);r?.addEventListener("abort",a,{once:!0});let s=!1,l=this.settings.timeoutMs>0?setTimeout(()=>{s=!0,i.abort()},this.settings.timeoutMs):void 0;try{let c={signal:i.signal,method:n===void 0?"GET":"POST"};n!==void 0&&(c.headers={"Content-Type":"application/json"},c.body=JSON.stringify(n));let u=await fetch(this.settings.baseUrl.replace(/\/+$/u,"")+t,Je(c));if(!u.ok){let h=await u.text();throw new C(`Worker HTTP ${u.status}: ${h.substring(0,500)}`,"MEM_PROVIDER_ERROR")}return o?await u.text():await u.json()}catch(c){if(s)throw new C(`Memory operation exceeded ${this.settings.timeoutMs} ms.`,"MEM_TIMEOUT");if(r?.aborted)throw new C("Memory operation cancelled.","MEM_ABORTED");if(c instanceof C)throw c;let u=c instanceof Error?c.message:String(c);throw new C(`Unable to read the memory worker: ${u}`,"MEM_PROVIDER_ERROR",{cause:c})}finally{clearTimeout(l),r?.removeEventListener("abort",a)}}};function $t(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function en(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var Ri={memory_session_id:"memorySessionId",type:"type",project:"project",subtitle:"subtitle",text:"text",narrative:"narrative",created_at:"createdAt",content_hash:"contentHash",generated_by_model:"generatedByModel",merged_into_project:"mergedIntoProject",agent_type:"agentType",agent_id:"agentId",origin_device_id:"originDeviceId",origin_local_id:"originLocalId",sync_rev:"syncRev"},Ai={created_at_epoch:"createdAtEpoch",prompt_number:"promptNumber",discovery_tokens:"discoveryTokens",relevance_count:"relevanceCount",synced_at:"syncedAt"},Ci={facts:"facts",concepts:"concepts",files_read:"filesRead",files_modified:"filesModified"};function tn(e){let t=$t(e),r=Number(t.id),n={id:Number.isFinite(r)?r:0,title:typeof t.title=="string"?t.title:""};Object.entries(Ri).forEach(([i,a])=>{typeof t[i]=="string"&&(n[a]=t[i])}),Object.entries(Ai).forEach(([i,a])=>{let s=t[i]??t[a];typeof s=="number"&&Number.isFinite(s)&&(n[a]=s)}),Object.entries(Ci).forEach(([i,a])=>{let s=en(t[i]);Array.isArray(s)&&(n[a]=s.filter(l=>typeof l=="string"))});let o=en(t.metadata);return o&&typeof o=="object"&&!Array.isArray(o)&&(n.metadata=o),n}import{basename as Di}from"node:path";import{existsSync as nn,readFileSync as Ti}from"node:fs";import{homedir as on}from"node:os";import{join as ae}from"node:path";import{spawn as Mi}from"node:child_process";var Ni=new Set(["ECONNREFUSED","ConnectionRefused"]);function _t(e,t){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),e instanceof Error&&e.message.includes("ECONNREFUSED"))return!0;let r=e;return typeof r.code=="string"&&Ni.has(r.code)||_t(r.cause,t)?!0:Array.isArray(r.errors)&&r.errors.some(n=>_t(n,t))}function rn(e){return _t(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}var Rt=5e3;function We(){let e=se(process.env.MEMINDEX_DATA_DIR||process.env.AGENT_MEM_DATA_DIR||ae(on(),".memindex")),t={};try{let s=JSON.parse(Ti(ae(e,"settings.json"),"utf8").replace(/^\uFEFF/,"")),l=s?.env;t=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).some(qe)?l:s??{}}catch{}let r=s=>typeof t[s]=="string"&&t[s]?String(t[s]):"",n=(s,l)=>process.env[s]||kt(s).map(c=>process.env[c]).find(Boolean)||r(s)||kt(s).map(r).find(Boolean)||l,o=n("MEMINDEX_WORKER_HOST","127.0.0.1"),i=o==="localhost"?"127.0.0.1":o,a=n("MEMINDEX_WORKER_PORT",String(38700+(process.getuid?.()??77)%100));return"http://"+(i.includes(":")&&!i.startsWith("[")?"["+i+"]":i)+":"+a}var ke;function Ii(){if(ke)return ke;let e=ae(process.env.CLAUDE_CONFIG_DIR||ae(on(),".claude"),"plugins","marketplaces","memindex"),t=ae(e,"plugin","scripts","bun-runner.js"),r=ae(e,"plugin","scripts","worker-service.cjs");return!nn(t)||!nn(r)?Promise.reject(new Error("Run npx memindex install to install the worker.")):(ke=new Promise((o,i)=>{let a=Mi(process.execPath,[t,r,"start"],{stdio:"ignore",windowsHide:!0,timeout:15e3});a.once("error",i),a.once("close",s=>s===0?o():i(new Error("memindex worker could not start")))}).finally(()=>{ke=void 0}),ke)}function sn(){let e=We();return{reset(){e=We()},async ready(){try{let t=await fetch(e+"/api/health",{signal:AbortSignal.timeout(Rt)});if(t.ok)return;throw new Error("memindex health check returned "+t.status)}catch(t){if(!rn(t))throw t;await Ii()}},async request(t,r={}){let n=await fetch(e+t,Je({...r,signal:r.signal?AbortSignal.any([r.signal,AbortSignal.timeout(Rt)]):AbortSignal.timeout(Rt)}));if(!n.ok)throw new Error("memindex "+t+" returned "+n.status);return n},async post(t,r){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}}}function an(e,t,r){let n=r.platformSource?{platformSource:r.platformSource}:{},o=i=>r.project?.trim()?r.project:Di(i.session.header.cwd||"")||"dsh";if(e.on("agent/created",async({agent:i})=>{if(r.injectContext)try{r.startLocalWorker&&await sn().ready();let a=i.session.header.cwd,s=r.project?.trim()?r.project:void 0;if(!a&&!s)return;let l=await t.context({...n,...a?{cwd:a}:{},...s?{projects:s}:{}});l&&i.inject(Er({source:{kind:"plugin:memindex"},content:[{text:l,type:"text"}]}))}catch{}}),r.ingest){let i=new Set(r.toolFilter.names);e.on("tools/result",async(a,s)=>{if(s.isError||!a.agent||!i.has(a.name))return;let l=s.content.flatMap(c=>c.type==="text"&&typeof c.text=="string"?[c.text]:[]).join(`
66
+ `).trim();if(l)try{await t.save({project:o(a.agent),text:`[${a.name}] ${l}`})}catch{}})}r.summarize&&e.on("agent/turn-stopping",async({agent:i})=>{try{await t.sessionSummarize({...n,project:o(i),contentSessionId:i.session.id})}catch{}})}var b=(e,t)=>t?{type:e,description:t}:{type:e},Tt=e=>({additionalProperties:!1,properties:e,type:"object"}),It=e=>({items:e,type:"array"}),P=e=>({...e,required:!0}),Pi=It(b("string")),Ee={title:P(b("string")),id:P(b("number")),narrative:b("string"),createdAtEpoch:b("number"),project:b("string"),type:b("string")},le={...Ee};for(let e of["memorySessionId","subtitle","text","createdAt","contentHash","generatedByModel","mergedIntoProject","agentType","agentId","originDeviceId","originLocalId","syncRev"])le[e]=b("string");for(let e of["promptNumber","discoveryTokens","relevanceCount","syncedAt"])le[e]=b("number");for(let e of["facts","concepts","filesRead","filesModified"])le[e]=Pi;le.metadata={additionalProperties:!0,type:"object"};var At=e=>Tt({content:b("string"),items:P(It(Tt(e)))}),Be=b("string","Keep records belonging to this project."),Ct=b("string","Limit recall to a host platform; leave unset for shared memory.");function Nt(e,t){let r=e.items.map(n=>Object.fromEntries(Object.keys(t).filter(o=>n[o]!==void 0).map(o=>[o,structuredClone(n[o])])));return e.content===void 0?{items:r}:{items:r,content:e.content}}function ln(e,t,r){function n(i,a,s,l,c,u){e.tools.register(vt({name:i,parameters:s,description:a,execute:c,timeoutMs:r.timeoutMs,isConcurrencySafe:()=>!0,output:{schema:l,render:(h,f)=>[{text:u(f),type:"text"}]}}))}r.search!==!1&&n("mem_search","Find earlier work by topic. Review this compact list before opening individual memories.",{query:P(b("string","Words describing the work or decision to recall.")),project:Be,platformSource:Ct,limit:b("integer","Upper bound on returned matches; the worker defaults to 20."),offset:b("integer","Number of matches already read."),type:b("string","Record collection: observations, sessions, or prompts."),obsType:b("string","Observation categories separated by commas."),dateStart:b("string","Earliest included ISO date."),dateEnd:b("string","Latest included ISO date."),orderBy:b("string","Chronological ordering: date_asc or date_desc.")},At(Ee),async(i,a)=>{let s={...i,query:i.query.trim()};return["date_asc","date_desc"].includes(s.orderBy)||delete s.orderBy,Nt(await t.search(s,a.signal),Ee)},Mt),r.timeline!==!1&&n("mem_timeline","Read the neighboring memories around a known record or a matching topic.",{anchor:b("integer","Record identifier at the center of the window."),query:b("string","Topic used to locate the center when its identifier is unknown."),depthBefore:b("integer","Earlier records to include; defaults to 3."),depthAfter:b("integer","Later records to include; defaults to 3."),project:Be,platformSource:Ct},At(Ee),async(i,a)=>Nt(await t.timeline(i,a.signal),Ee),Mt),r.getObservations!==!1&&n("mem_get_observations","Open selected memory records with their complete stored details.",{ids:{...P(It(b("integer"))),description:"Identifiers selected from recall results."},project:Be},At(le),async(i,a)=>{if(!i.ids.length)throw new Error("Choose one or more memory identifiers.");return Nt(await t.getObservations(i,a.signal),le)},qi);let o={};for(let i of["title","project","message"])o[i]=P(b("string"));o.id=P(b("number")),o.success=P(b("boolean")),r.save!==!1&&n("mem_save","Keep a note for future sessions. The supplied text is stored directly.",{text:P(b("string","The durable note to record.")),title:b("string","Short heading for this note."),project:Be,metadata:{type:"object",additionalProperties:!0,description:"Extra JSON attributes to retain with the note."}},Tt(o),(i,a)=>t.save({...i,text:i.text.trim()},a.signal),i=>`Saved observation #${i.id} (${i.title})`),r.context!==!1&&n("mem_context","Read the startup memory briefing prepared by the worker for the requested projects.",{projects:P(b("string","Comma-separated project ancestry, ending with the active project.")),platformSource:Ct,full:b("boolean","Include the expanded briefing."),colors:b("boolean","Allow ANSI color codes in the briefing.")},b("string"),(i,a)=>{if(!i.projects.trim())throw new Error("Choose a project for the memory briefing.");return t.context(i,a.signal)},i=>i)}function Mt(e){return e.content?e.content:e.items.length?e.items.map(t=>[`#${t.id} ${t.title}${t.type===void 0?"":` [${t.type}]`}${t.project===void 0?"":` (${t.project})`}`,...t.narrative===void 0?[]:[` ${t.narrative}`]].join(`
67
+ `)).join(`
68
+ `):"No results found."}function qi(e){return e.content||!e.items.length?Mt(e):e.items.map(t=>{let r=[`#${t.id} ${t.title}`];for(let[n,o]of Object.entries(t))n==="id"||n==="title"||o===void 0||r.push(`${n}: ${typeof o=="object"?JSON.stringify(o):o}`);return r.join(`
69
+ `)}).join(`
70
+
71
+ `)}var cn={source:"bundled",name:"mem-search",description:"Recall decisions, fixes, and context recorded during earlier work.",content:`# Recall earlier work
72
+
73
+ When an answer depends on work outside this conversation, look for recorded evidence.
74
+ Start with mem_search and a few distinctive words from the topic. Inspect the returned
75
+ headings and identifiers, then choose the records that can answer the question.
76
+ Open only those identifiers with mem_get_observations. Use mem_timeline when the events
77
+ before or after a chosen record matter. Broaden the query when the first results miss
78
+ the topic; an empty result is not evidence that the work never happened.
79
+
80
+ Search spans host platforms unless platformSource explicitly narrows it. Add a project
81
+ filter when the question is about one codebase. mem_context provides that project's
82
+ startup briefing. Use mem_save for a durable fact or decision the user wants retained;
83
+ do not save guesses as established facts. Cite the records that support your answer.
84
+ `};var La="memindex",Wa=["tools","skills"],Dt=["read","write","edit","bash"],Ba=d.object({project:d.string().default(""),platformSource:d.string().default(""),baseUrl:d.string().default(""),timeoutMs:d.number().default(3e4),dedupe:d.boolean().default(!0),injectContext:d.boolean().default(!0),ingest:d.boolean().default(!1),summarize:d.boolean().default(!1),toolFilter:d.object({names:d.array(d.string()).default(Dt)}).default({names:Dt})});function za(e,t={}){let r=t.timeoutMs??3e4;if(!(Number.isSafeInteger(r)&&r>0))throw new Error("MemIndex timeoutMs must be a positive whole number.");let n=We(),i=(t.baseUrl||process.env.DSH_MEM_BASE_URL||n).replace(/\/+$/,""),a=new Le({baseUrl:i,timeoutMs:r,dedupe:t.dedupe??!0});e.skills.register(cn),ln(e,a,{timeoutMs:r}),an(e,a,{injectContext:t.injectContext??!0,ingest:t.ingest??!1,summarize:t.summarize??!1,project:t.project??"",platformSource:t.platformSource??"",startLocalWorker:i===n.replace(/\/+$/,""),toolFilter:{names:t.toolFilter?.names??[...Dt]}})}export{Ba as Config,za as apply,Wa as inject,La as name};
85
+ /*! Vendored DeepSeek public SDK helpers. See integrations/dsh/THIRD-PARTY-LICENSES.txt and vendor/provenance.json. */
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@memindex/dsh",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "description": "First-party DeepSeek Harness memory integration",
6
+ "type": "module",
7
+ "main": "./lib/index.js",
8
+ "license": "Apache-2.0",
9
+ "files": [
10
+ "lib",
11
+ "cordis.patch.yml",
12
+ "LICENSE",
13
+ "NOTICE",
14
+ "transcript-schema.json",
15
+ "THIRD-PARTY-LICENSES.txt"
16
+ ],
17
+ "dsh": {
18
+ "bundle": {
19
+ "patch": "./cordis.patch.yml"
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "dsh",
3
+ "version": "0.2",
4
+ "description": "Map Harness journal records to MemIndex capture actions.",
5
+ "sessionIdPath": "id",
6
+ "events": [
7
+ {
8
+ "name": "checkout",
9
+ "action": "session_context",
10
+ "fields": { "cwd": { "path": "cwd" } },
11
+ "match": { "in": ["session"], "path": "type" }
12
+ },
13
+ {
14
+ "name": "prompt",
15
+ "action": "user_message",
16
+ "fields": { "message": { "path": "data.content" } },
17
+ "match": {
18
+ "path": "type", "in": ["user/message"],
19
+ "any": [
20
+ { "path": "data.source.kind", "equals": "user" },
21
+ { "exists": false, "path": "data.source.kind" }
22
+ ]
23
+ }
24
+ },
25
+ {
26
+ "name": "reply",
27
+ "action": "assistant_message",
28
+ "fields": { "message": { "path": "data.message.content" } },
29
+ "match": { "in": ["assistant/message"], "path": "type" }
30
+ },
31
+ {
32
+ "name": "invocation",
33
+ "action": "tool_use",
34
+ "fields": {
35
+ "toolInput": { "path": "data.arguments" },
36
+ "toolName": { "path": "data.name" },
37
+ "toolId": { "path": "data.callId" }
38
+ },
39
+ "match": {
40
+ "path": "type", "in": ["tool/call"],
41
+ "all": [{ "not_starts_with": "mem_", "path": "data.name" }]
42
+ }
43
+ },
44
+ {
45
+ "name": "completion",
46
+ "action": "tool_result",
47
+ "fields": {
48
+ "toolId": { "coalesce": [{ "path": "data.message.toolCallId" }, { "path": "data.message.content[0].toolCallId" }] },
49
+ "toolResponse": { "coalesce": [{ "path": "data.message.content[0].content" }, { "path": "data.message.content" }] }
50
+ },
51
+ "match": { "in": ["tool/result"], "path": "type" }
52
+ },
53
+ {
54
+ "name": "settled-turn",
55
+ "action": "session_end",
56
+ "match": { "in": ["turn/end"], "path": "type" }
57
+ }
58
+ ]
59
+ }
@@ -0,0 +1,61 @@
1
+ # MemIndex memory for Hermes Agent
2
+
3
+ A Hermes memory provider. Hermes and your other coding agents share one MemIndex
4
+ memory per project.
5
+
6
+ ## What it does
7
+
8
+ | Hermes event | MemIndex call | Why |
9
+ |---|---|---|
10
+ | `on_turn_start` | `POST /api/sessions/init` | Records each user prompt, in order |
11
+ | `post_tool_call` hook | `POST /api/sessions/observations` | Records each tool call after its prompt |
12
+ | `prefetch(query)` | `POST /api/context/semantic` | Notes that match this prompt, from every agent in the project |
13
+ | `system_prompt_block()` | `GET /api/context/inject` | The project's recent work, once at session start |
14
+ | `on_memory_write` (add/replace) | `POST /api/memory/save` | Hermes's own memory notes become MemIndex notes |
15
+ | `on_session_end` / `on_session_switch` | `POST /api/sessions/summarize` | Closes the session with its last answer |
16
+
17
+ - The project is never named here: each call carries the session's working
18
+ directory and MemIndex works out the project the same way it does for Claude
19
+ Code, so a Hermes session and a Claude Code session in one checkout share notes.
20
+ - Writes go through one background thread, in order, so Hermes never waits on
21
+ them. Reads wait at most 3 seconds.
22
+ - Scheduled jobs and other non-primary Hermes agents read memory but record nothing.
23
+ - Private sections and injected memory are removed before recall. A prompt with
24
+ nothing public left makes no recall request.
25
+ - When MemIndex is not running, every call fails quietly; three failures in a row
26
+ pause calls for 30 seconds.
27
+ - With `MEMINDEX_RUNTIME=server` and `MEMINDEX_SERVER_URL`,
28
+ `MEMINDEX_SERVER_API_KEY` and `MEMINDEX_SERVER_PROJECT_ID` set (in the
29
+ environment or `~/.memindex/settings.json`), the same events go to the hosted
30
+ server's `/v1` API instead.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npx memindex install --ide hermes
36
+ ```
37
+
38
+ This copies the plugin to `$HERMES_HOME/plugins/memindex/`. When `HERMES_HOME`
39
+ is unset, Hermes uses `~/.hermes` on macOS and Linux, or `%LOCALAPPDATA%\hermes`
40
+ on Windows (`%USERPROFILE%\AppData\Local\hermes` if `LOCALAPPDATA` is unset).
41
+ In that home's `config.yaml`, the installer sets:
42
+
43
+ ```yaml
44
+ memory:
45
+ provider: memindex
46
+ mcp_servers:
47
+ memindex:
48
+ command: "/path/to/node"
49
+ args:
50
+ - "/path/to/memindex/plugin/scripts/mcp-server.cjs"
51
+ enabled: true
52
+ ```
53
+
54
+ The MCP entry gives Hermes MemIndex's search tools (`mem_search`, `search`,
55
+ `timeline`, `get_observations`, `save_memory`). An existing `mcp_servers.memindex`
56
+ entry you wrote yourself is left alone.
57
+ Header comments and YAML document-end markers are preserved during installation
58
+ and removal.
59
+
60
+ `npx memindex uninstall` removes the plugin files, puts back the memory provider
61
+ you had before, and removes the MCP entry only if the installer added it.