@graphrefly/graphrefly 0.31.0 → 0.32.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 (177) hide show
  1. package/dist/chunk-2JNT5NDF.js +61 -0
  2. package/dist/{chunk-KN4Q5MQO.js → chunk-2RH4QNDQ.js} +1 -1
  3. package/dist/chunk-4JBKKUCJ.js +7 -0
  4. package/dist/{chunk-WLPVGXQ6.js → chunk-4YGJ7KZ6.js} +1 -1
  5. package/dist/{chunk-3Q2WXM6X.js → chunk-5PBXUVHI.js} +1 -1
  6. package/dist/{chunk-WYJTXYWX.js → chunk-7EMUF2RY.js} +1 -1
  7. package/dist/chunk-7JZ3YORY.js +80 -0
  8. package/dist/{chunk-I4U3TPK2.js → chunk-7QS77X6G.js} +1 -1
  9. package/dist/{chunk-ZM7C2FUM.js → chunk-BU4SUZSA.js} +1 -1
  10. package/dist/{chunk-GF5T7PGC.js → chunk-CNXUW2CU.js} +1 -1
  11. package/dist/{chunk-Z3UWIJ3A.js → chunk-EIFHFDFD.js} +1 -1
  12. package/dist/{chunk-3JRKP4BH.js → chunk-JAHAJU4G.js} +1 -1
  13. package/dist/{chunk-4ZPO2EL5.js → chunk-JYMNVEH6.js} +1 -1
  14. package/dist/{chunk-4KAUNEKV.js → chunk-KD3IYBTD.js} +1 -1
  15. package/dist/{chunk-X2VHDT26.js → chunk-LG73TUF4.js} +2 -2
  16. package/dist/{chunk-JXRZXP3N.js → chunk-LJGPOJHS.js} +1 -1
  17. package/dist/{chunk-YQJPYEAL.js → chunk-M2VFLRPJ.js} +1 -1
  18. package/dist/{chunk-7EQPXQ7H.js → chunk-MFNOZ5E6.js} +1 -1
  19. package/dist/{chunk-YZ6VYLFD.js → chunk-PWKLZ2XU.js} +1 -1
  20. package/dist/{chunk-OKQUPJRY.js → chunk-TOCCHQI6.js} +1 -1
  21. package/dist/{chunk-PZP4MEXK.js → chunk-UXEB35L4.js} +1 -1
  22. package/dist/{chunk-EBQ6FXKW.js → chunk-VXJX3ZZP.js} +1 -1
  23. package/dist/{chunk-7EJTWGKW.js → chunk-WE32AFFA.js} +1 -1
  24. package/dist/{chunk-JMGGCSIC.js → chunk-WF3V5X2L.js} +1 -1
  25. package/dist/{chunk-YZKGGMPT.js → chunk-X4OOM6QU.js} +1 -1
  26. package/dist/{chunk-5LJAQTSS.js → chunk-ZWETYYQG.js} +1 -1
  27. package/dist/compat/index.cjs +1 -1
  28. package/dist/compat/index.d.cts +5 -5
  29. package/dist/compat/index.d.ts +5 -5
  30. package/dist/compat/index.js +1 -1
  31. package/dist/compat/nestjs/index.cjs +1 -1
  32. package/dist/compat/nestjs/index.d.cts +3 -3
  33. package/dist/compat/nestjs/index.d.ts +3 -3
  34. package/dist/compat/nestjs/index.js +1 -1
  35. package/dist/compat/zustand/index.cjs +1 -1
  36. package/dist/compat/zustand/index.d.cts +2 -2
  37. package/dist/compat/zustand/index.d.ts +2 -2
  38. package/dist/compat/zustand/index.js +1 -1
  39. package/dist/extra/index.cjs +1 -1
  40. package/dist/extra/index.d.cts +2 -2
  41. package/dist/extra/index.d.ts +2 -2
  42. package/dist/extra/index.js +1 -1
  43. package/dist/graph/index.cjs +1 -1
  44. package/dist/graph/index.d.cts +3 -3
  45. package/dist/graph/index.d.ts +3 -3
  46. package/dist/graph/index.js +1 -1
  47. package/dist/{graph-CWeI0aHd.d.ts → graph-BOhEGJ6E.d.ts} +10 -0
  48. package/dist/{graph-C4Uxwv0T.d.cts → graph-CdJeX7O7.d.cts} +10 -0
  49. package/dist/{index-B-z8WaSd.d.cts → index-BDLy6CQ9.d.cts} +1 -1
  50. package/dist/{index-iBp74eGU.d.cts → index-BJDXj9Wf.d.cts} +2 -2
  51. package/dist/{index-BBINVimG.d.ts → index-BUZPTPSQ.d.ts} +2 -2
  52. package/dist/{index-DnrZghBB.d.ts → index-BbcSZCAG.d.ts} +1 -1
  53. package/dist/{index-lKuLYmHO.d.cts → index-BiGeETJs.d.cts} +1 -1
  54. package/dist/{index-Dm3_D5Ta.d.cts → index-BmZb8fNF.d.cts} +2 -2
  55. package/dist/{index-Docdiu9a.d.ts → index-Bnmttu35.d.ts} +1 -1
  56. package/dist/{index-CZChc85Q.d.cts → index-BuN2wGJs.d.cts} +297 -22
  57. package/dist/{index-Cy7eFeIX.d.cts → index-BwdPDWI4.d.cts} +1 -1
  58. package/dist/{index-DylQCKEL.d.cts → index-BzxU4yhV.d.cts} +11 -2
  59. package/dist/{index-D9Y_u6BG.d.cts → index-C-Gsh-0a.d.cts} +2 -2
  60. package/dist/{index-DD7RhHNJ.d.cts → index-C22aTC1X.d.cts} +4 -4
  61. package/dist/{index-yIdWFo2b.d.cts → index-C4QTaDli.d.cts} +2 -2
  62. package/dist/{index-CJymKyzT.d.ts → index-C7RqYbOZ.d.ts} +1 -1
  63. package/dist/{index-C5Ghnp5B.d.ts → index-C9qCLIN4.d.ts} +2 -2
  64. package/dist/{index-DVNLe3pS.d.cts → index-CCdg0JLX.d.cts} +1 -1
  65. package/dist/{index-B5iVOD7w.d.ts → index-CEoU-r-g.d.ts} +2 -2
  66. package/dist/{index-CfFYyLR8.d.ts → index-CHfBm51k.d.ts} +11 -2
  67. package/dist/{index-BXzl1NDD.d.ts → index-CNyiYQWF.d.ts} +4 -4
  68. package/dist/{index-C6NBfXj-.d.ts → index-CVevMZ0n.d.ts} +2 -2
  69. package/dist/{index-DGb1awva.d.ts → index-CZUzi6Dy.d.ts} +2 -2
  70. package/dist/{index-FrYrV-Vf.d.ts → index-Ckl03Q0s.d.ts} +1 -1
  71. package/dist/{index-Bvi5uJxX.d.ts → index-CmSjld-4.d.ts} +1 -1
  72. package/dist/{index-9iguV3bF.d.cts → index-CnjUhRbs.d.cts} +2 -2
  73. package/dist/{index-C98oJsEs.d.cts → index-D3HcdZ4d.d.cts} +1 -1
  74. package/dist/{index-IZ3l_vQ9.d.ts → index-DD1czHj3.d.ts} +1 -1
  75. package/dist/{index-gJQqJTKx.d.cts → index-DNhTQReY.d.cts} +1 -1
  76. package/dist/{index-UZO988ox.d.cts → index-DSawGt8n.d.cts} +2 -2
  77. package/dist/{index-CcpEvuPl.d.cts → index-DUkuH3jP.d.cts} +1 -1
  78. package/dist/{index-CRAkoq-y.d.cts → index-DY2QbdoP.d.cts} +1 -1
  79. package/dist/{index-CvS9IuTG.d.ts → index-Dbmj0iYR.d.ts} +1 -1
  80. package/dist/{index-Bd6oFZqO.d.ts → index-DhlAMlm9.d.ts} +297 -22
  81. package/dist/{index-BMe3pCom.d.cts → index-DlGaEBW5.d.cts} +2 -2
  82. package/dist/{index-CotRMjtJ.d.ts → index-Dp_pS7Bw.d.ts} +1 -1
  83. package/dist/{index-DxMS0cHM.d.ts → index-Dxk-pUQI.d.ts} +2 -2
  84. package/dist/{index-DBQUKh59.d.cts → index-EGjF6iSY.d.cts} +3 -3
  85. package/dist/{index-D9HrBx2J.d.ts → index-LGzAYqdR.d.ts} +1 -1
  86. package/dist/{index-DR3gf_DG.d.cts → index-LzCJ0kMT.d.cts} +2 -2
  87. package/dist/{index-RQg6lTrN.d.ts → index-MV2yGIAq.d.ts} +2 -2
  88. package/dist/{index-Bs3-LC83.d.cts → index-_BXz9K7b.d.cts} +1 -1
  89. package/dist/{index-SSGqF8mI.d.cts → index-aBqZUx3B.d.cts} +1 -1
  90. package/dist/{index-CFW32Dy1.d.ts → index-eYHRkoK-.d.ts} +1 -1
  91. package/dist/{index-CwhcFzTA.d.ts → index-gXTVbSax.d.ts} +2 -2
  92. package/dist/{index-D-kHVedZ.d.cts → index-j33Lfb1G.d.cts} +22 -1
  93. package/dist/{index-BEpRsvhg.d.ts → index-lpGUhTBn.d.ts} +3 -3
  94. package/dist/{index-CcS0t-l2.d.ts → index-zMQIQuDu.d.ts} +22 -1
  95. package/dist/index.cjs +53 -50
  96. package/dist/index.d.cts +26 -26
  97. package/dist/index.d.ts +26 -26
  98. package/dist/index.js +1 -1
  99. package/dist/patterns/ai/index.cjs +21 -18
  100. package/dist/patterns/ai/index.d.cts +6 -6
  101. package/dist/patterns/ai/index.d.ts +6 -6
  102. package/dist/patterns/ai/index.js +1 -1
  103. package/dist/patterns/audit/index.cjs +1 -1
  104. package/dist/patterns/audit/index.d.cts +3 -3
  105. package/dist/patterns/audit/index.d.ts +3 -3
  106. package/dist/patterns/audit/index.js +1 -1
  107. package/dist/patterns/cqrs/index.cjs +1 -1
  108. package/dist/patterns/cqrs/index.d.cts +2 -2
  109. package/dist/patterns/cqrs/index.d.ts +2 -2
  110. package/dist/patterns/cqrs/index.js +1 -1
  111. package/dist/patterns/demo-shell/index.cjs +1 -1
  112. package/dist/patterns/demo-shell/index.d.cts +3 -3
  113. package/dist/patterns/demo-shell/index.d.ts +3 -3
  114. package/dist/patterns/demo-shell/index.js +1 -1
  115. package/dist/patterns/domain-templates/index.cjs +5 -5
  116. package/dist/patterns/domain-templates/index.d.cts +2 -2
  117. package/dist/patterns/domain-templates/index.d.ts +2 -2
  118. package/dist/patterns/domain-templates/index.js +1 -1
  119. package/dist/patterns/graphspec/index.cjs +27 -25
  120. package/dist/patterns/graphspec/index.d.cts +2 -2
  121. package/dist/patterns/graphspec/index.d.ts +2 -2
  122. package/dist/patterns/graphspec/index.js +1 -1
  123. package/dist/patterns/guarded-execution/index.cjs +5 -5
  124. package/dist/patterns/guarded-execution/index.d.cts +4 -4
  125. package/dist/patterns/guarded-execution/index.d.ts +4 -4
  126. package/dist/patterns/guarded-execution/index.js +1 -1
  127. package/dist/patterns/harness/index.cjs +12 -11
  128. package/dist/patterns/harness/index.d.cts +5 -5
  129. package/dist/patterns/harness/index.d.ts +5 -5
  130. package/dist/patterns/harness/index.js +1 -1
  131. package/dist/patterns/job-queue/index.cjs +1 -1
  132. package/dist/patterns/job-queue/index.d.cts +2 -2
  133. package/dist/patterns/job-queue/index.d.ts +2 -2
  134. package/dist/patterns/job-queue/index.js +1 -1
  135. package/dist/patterns/lens/index.cjs +1 -1
  136. package/dist/patterns/lens/index.d.cts +3 -3
  137. package/dist/patterns/lens/index.d.ts +3 -3
  138. package/dist/patterns/lens/index.js +1 -1
  139. package/dist/patterns/memory/index.cjs +1 -1
  140. package/dist/patterns/memory/index.d.cts +2 -2
  141. package/dist/patterns/memory/index.d.ts +2 -2
  142. package/dist/patterns/memory/index.js +1 -1
  143. package/dist/patterns/messaging/index.cjs +1 -1
  144. package/dist/patterns/messaging/index.d.cts +2 -2
  145. package/dist/patterns/messaging/index.d.ts +2 -2
  146. package/dist/patterns/messaging/index.js +1 -1
  147. package/dist/patterns/orchestration/index.cjs +7 -7
  148. package/dist/patterns/orchestration/index.d.cts +2 -2
  149. package/dist/patterns/orchestration/index.d.ts +2 -2
  150. package/dist/patterns/orchestration/index.js +1 -1
  151. package/dist/patterns/reactive-layout/index.cjs +1 -1
  152. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  153. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  154. package/dist/patterns/reactive-layout/index.js +1 -1
  155. package/dist/patterns/reduction/index.cjs +1 -1
  156. package/dist/patterns/reduction/index.d.cts +2 -2
  157. package/dist/patterns/reduction/index.d.ts +2 -2
  158. package/dist/patterns/reduction/index.js +1 -1
  159. package/dist/patterns/refine-loop/index.cjs +3 -3
  160. package/dist/patterns/refine-loop/index.d.cts +3 -3
  161. package/dist/patterns/refine-loop/index.d.ts +3 -3
  162. package/dist/patterns/refine-loop/index.js +1 -1
  163. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  164. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  165. package/dist/patterns/resilient-pipeline/index.js +1 -1
  166. package/dist/patterns/surface/index.cjs +15 -13
  167. package/dist/patterns/surface/index.d.cts +3 -3
  168. package/dist/patterns/surface/index.d.ts +3 -3
  169. package/dist/patterns/surface/index.js +1 -1
  170. package/dist/{reactive-layout-BAr6-_o5.d.ts → reactive-layout-Bq0rA2Wb.d.ts} +1 -1
  171. package/dist/{reactive-layout-5oEn8lHM.d.cts → reactive-layout-Dhhe54Oj.d.cts} +1 -1
  172. package/dist/{topology-tree-CVREibAc.d.cts → topology-tree-CpSjvIXp.d.cts} +1 -1
  173. package/dist/{topology-tree-CkjojcB6.d.ts → topology-tree-DAbCV2Yw.d.ts} +1 -1
  174. package/package.json +1 -1
  175. package/dist/chunk-ASDKRNOJ.js +0 -60
  176. package/dist/chunk-PSQNYY72.js +0 -7
  177. package/dist/chunk-XEFAMCEA.js +0 -78
@@ -1,7 +1,7 @@
1
- export { C as CatalogFnEntry, a as CatalogSourceEntry, b as ConfigFieldSchema, F as FnFactory, G as GraphSpec, c as GraphSpecCatalog, d as GraphSpecFeedbackEdge, e as GraphSpecNode, f as GraphSpecTemplate, g as GraphSpecTemplateRef, h as GraphSpecValidation, S as SourceFactory } from '../../index-D-kHVedZ.cjs';
2
- export { C as CreateGraphOptions, R as ReduceOptions, a as RestoreSnapshotOptions, S as SNAPSHOT_WIRE_VERSION, b as SaveSnapshotResult, c as SurfaceError, d as SurfaceErrorCode, e as SurfaceErrorPayload, f as asSurfaceError, g as createGraph, h as deleteSnapshot, i as diffSnapshots, l as listSnapshots, r as restoreSnapshot, j as runReduction, s as saveSnapshot } from '../../index-BMe3pCom.cjs';
1
+ export { C as CatalogFnEntry, a as CatalogSourceEntry, b as ConfigFieldSchema, F as FnFactory, G as GraphSpec, c as GraphSpecCatalog, d as GraphSpecFeedbackEdge, e as GraphSpecNode, f as GraphSpecTemplate, g as GraphSpecTemplateRef, h as GraphSpecValidation, S as SourceFactory } from '../../index-j33Lfb1G.cjs';
2
+ export { C as CreateGraphOptions, R as ReduceOptions, a as RestoreSnapshotOptions, S as SNAPSHOT_WIRE_VERSION, b as SaveSnapshotResult, c as SurfaceError, d as SurfaceErrorCode, e as SurfaceErrorPayload, f as asSurfaceError, g as createGraph, h as deleteSnapshot, i as diffSnapshots, l as listSnapshots, r as restoreSnapshot, j as runReduction, s as saveSnapshot } from '../../index-DlGaEBW5.cjs';
3
3
  import '../../node-BVV7G1bq.cjs';
4
- import '../../graph-C4Uxwv0T.cjs';
4
+ import '../../graph-CdJeX7O7.cjs';
5
5
  import '../../meta-COtmHLwT.cjs';
6
6
  import '../../extra/storage-core.cjs';
7
7
  import '../../types-BgMqbc7N.cjs';
@@ -1,7 +1,7 @@
1
- export { C as CatalogFnEntry, a as CatalogSourceEntry, b as ConfigFieldSchema, F as FnFactory, G as GraphSpec, c as GraphSpecCatalog, d as GraphSpecFeedbackEdge, e as GraphSpecNode, f as GraphSpecTemplate, g as GraphSpecTemplateRef, h as GraphSpecValidation, S as SourceFactory } from '../../index-CcS0t-l2.js';
2
- export { C as CreateGraphOptions, R as ReduceOptions, a as RestoreSnapshotOptions, S as SNAPSHOT_WIRE_VERSION, b as SaveSnapshotResult, c as SurfaceError, d as SurfaceErrorCode, e as SurfaceErrorPayload, f as asSurfaceError, g as createGraph, h as deleteSnapshot, i as diffSnapshots, l as listSnapshots, r as restoreSnapshot, j as runReduction, s as saveSnapshot } from '../../index-DxMS0cHM.js';
1
+ export { C as CatalogFnEntry, a as CatalogSourceEntry, b as ConfigFieldSchema, F as FnFactory, G as GraphSpec, c as GraphSpecCatalog, d as GraphSpecFeedbackEdge, e as GraphSpecNode, f as GraphSpecTemplate, g as GraphSpecTemplateRef, h as GraphSpecValidation, S as SourceFactory } from '../../index-zMQIQuDu.js';
2
+ export { C as CreateGraphOptions, R as ReduceOptions, a as RestoreSnapshotOptions, S as SNAPSHOT_WIRE_VERSION, b as SaveSnapshotResult, c as SurfaceError, d as SurfaceErrorCode, e as SurfaceErrorPayload, f as asSurfaceError, g as createGraph, h as deleteSnapshot, i as diffSnapshots, l as listSnapshots, r as restoreSnapshot, j as runReduction, s as saveSnapshot } from '../../index-Dxk-pUQI.js';
3
3
  import '../../node-BVV7G1bq.js';
4
- import '../../graph-CWeI0aHd.js';
4
+ import '../../graph-BOhEGJ6E.js';
5
5
  import '../../meta-BMwx3ExI.js';
6
6
  import '../../extra/storage-core.js';
7
7
  import '../../types-CdfO2QTt.js';
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j}from"../../chunk-WYJTXYWX.js";import"../../chunk-XEFAMCEA.js";import"../../chunk-JMGGCSIC.js";import"../../chunk-K54OKWNY.js";import"../../chunk-LWGLBCMU.js";import"../../chunk-PSQNYY72.js";import"../../chunk-SGS4OJGS.js";import"../../chunk-ESMPEKEV.js";import"../../chunk-N2KKISCE.js";import"../../chunk-WQ7I7JVU.js";import"../../chunk-4VVTGLXJ.js";import"../../chunk-UMH3HSP7.js";import"../../chunk-7AJKUA36.js";import"../../chunk-CK2E7BTU.js";import"../../chunk-QYADASLV.js";export{e as SNAPSHOT_WIRE_VERSION,a as SurfaceError,b as asSurfaceError,c as createGraph,j as deleteSnapshot,h as diffSnapshots,i as listSnapshots,g as restoreSnapshot,d as runReduction,f as saveSnapshot};
1
+ import{a,b,c,d,e,f,g,h,i,j}from"../../chunk-7EMUF2RY.js";import"../../chunk-7JZ3YORY.js";import"../../chunk-WF3V5X2L.js";import"../../chunk-K54OKWNY.js";import"../../chunk-LWGLBCMU.js";import"../../chunk-4JBKKUCJ.js";import"../../chunk-SGS4OJGS.js";import"../../chunk-ESMPEKEV.js";import"../../chunk-N2KKISCE.js";import"../../chunk-WQ7I7JVU.js";import"../../chunk-4VVTGLXJ.js";import"../../chunk-UMH3HSP7.js";import"../../chunk-7AJKUA36.js";import"../../chunk-CK2E7BTU.js";import"../../chunk-QYADASLV.js";export{e as SNAPSHOT_WIRE_VERSION,a as SurfaceError,b as asSurfaceError,c as createGraph,j as deleteSnapshot,h as diffSnapshots,i as listSnapshots,g as restoreSnapshot,d as runReduction,f as saveSnapshot};
@@ -1,5 +1,5 @@
1
1
  import { a as Node } from './node-BVV7G1bq.js';
2
- import { G as Graph } from './graph-CWeI0aHd.js';
2
+ import { G as Graph } from './graph-BOhEGJ6E.js';
3
3
 
4
4
  /** Pluggable measurement backend. */
5
5
  interface MeasurementAdapter {
@@ -1,5 +1,5 @@
1
1
  import { a as Node } from './node-BVV7G1bq.cjs';
2
- import { G as Graph } from './graph-C4Uxwv0T.cjs';
2
+ import { G as Graph } from './graph-CdJeX7O7.cjs';
3
3
 
4
4
  /** Pluggable measurement backend. */
5
5
  interface MeasurementAdapter {
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-C4Uxwv0T.cjs';
1
+ import { G as Graph, T as TopologyEvent } from './graph-CdJeX7O7.cjs';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
@@ -1,4 +1,4 @@
1
- import { G as Graph, T as TopologyEvent } from './graph-CWeI0aHd.js';
1
+ import { G as Graph, T as TopologyEvent } from './graph-BOhEGJ6E.js';
2
2
 
3
3
  /**
4
4
  * Subscribe to structural changes across `graph` and every transitively
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphrefly/graphrefly",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "packageManager": "pnpm@10.33.0+sha512.10568bb4a6afb58c9eb3630da90cc9516417abebd3fabbe6739f0ae795728da1491e9db5a544c76ad8eb7570f5c4bb3d6c637b2cb41bfdcdb47fa823c8649319",
5
5
  "description": "Reactive harness layer for agent workflows. Describe automations in plain language, trace every decision, enforce policies, persist checkpoints. Zero dependencies.",
6
6
  "repository": {
@@ -1,60 +0,0 @@
1
- import{a as ht,b as bt,d as Tt,e as Mt}from"./chunk-OKQUPJRY.js";import{e as yt}from"./chunk-5LJAQTSS.js";import{h as vt}from"./chunk-XEFAMCEA.js";import{e as He}from"./chunk-EBQ6FXKW.js";import{a as jt,b as Wt,c as Ut,d as Kt,e as Vt,f as Ve,g as Ht}from"./chunk-PNTBXOQ6.js";import{a as Ue,b as H,c as Ee,d as pe,e as re,f as q,g as Ft,h as Ke,i as Gt,j as Bt,k as $t}from"./chunk-FTA5TB2A.js";import{c as pt}from"./chunk-K54OKWNY.js";import{b as gt}from"./chunk-7QMVU3IX.js";import{b as dt,c as Ae,d as ut,f as We}from"./chunk-RWGJQQLT.js";import{b as Se}from"./chunk-LWGLBCMU.js";import{b as Te}from"./chunk-XRSHMHEG.js";import{j as de}from"./chunk-PSQNYY72.js";import{a as te}from"./chunk-ESMPEKEV.js";import{R as ft,x as J}from"./chunk-WQ7I7JVU.js";import{B as F,f as ct,m as k,w as le,y as mt}from"./chunk-UMH3HSP7.js";import{D as ce,E as L,F as $e,G as M,H as me,m as se,o as X,p as Re}from"./chunk-7AJKUA36.js";import{b as V,d as be,i as ae,j as Q}from"./chunk-CK2E7BTU.js";import{b as Dt}from"./chunk-QYADASLV.js";var Vr={};Dt(Vr,{AgentLoopGraph:()=>Be,AllTiersExhaustedError:()=>Vt,BudgetExhaustedError:()=>Pe,ChatStreamGraph:()=>Fe,CircuitOpenError:()=>Ae,DEFAULT_DECAY_RATE:()=>st,FallbackMissError:()=>Bt,LLMTimeoutError:()=>ve,ReplayCacheMissError:()=>Ft,ToolRegistryGraph:()=>Ge,admissionFilter3D:()=>Dr,agentLoop:()=>Ir,agentMemory:()=>jr,anthropicAdapter:()=>jt,canonicalJson:()=>Gt,cascadingLlmAdapter:()=>Ve,chatStream:()=>rt,composePricing:()=>Xt,computePrice:()=>qe,contentGate:()=>Ar,costMeterExtractor:()=>xr,createAdapter:()=>Kt,createCapabilitiesRegistry:()=>qt,createPricingRegistry:()=>Yt,dryRunAdapter:()=>Ue,fallbackAdapter:()=>$t,fromLLM:()=>cr,frozenContext:()=>yr,gatedStream:()=>Mr,gaugesAsContext:()=>Fr,googleAdapter:()=>Wt,graphFromSpec:()=>Gr,handoff:()=>Or,keywordFlagExtractor:()=>wr,knobsAsTools:()=>$r,llmConsolidator:()=>at,llmExtractor:()=>ot,observableAdapter:()=>zt,openAICompatAdapter:()=>Ut,parseRateLimitFromError:()=>Qe,pricingFor:()=>Zt,promptNode:()=>br,redactor:()=>Sr,registryPricing:()=>Qt,resilientAdapter:()=>ur,streamExtractor:()=>Lr,streamingPromptNode:()=>Tr,suggestStrategy:()=>Ur,systemPromptBuilder:()=>vr,tier:()=>Ht,toolCallExtractor:()=>Cr,toolRegistry:()=>nt,toolSelector:()=>Pr,validateGraphDef:()=>Kr,withBreaker:()=>ze,withBudgetGate:()=>Ye,withDryRun:()=>tr,withRateLimiter:()=>Ze,withReplayCache:()=>Ke,withRetry:()=>et,withTimeout:()=>tt,zeroPrice:()=>Oe});function we(t,e){return`${t}::${e}`}function qt(t){let e=Se({name:"capabilitiesRegistry"}),r=i=>{e.set(we(i.provider,i.id),i)};if(t)for(let i of t)r(i);let n=(i,d)=>{let c=e.get(we(i,d));if(c)return c;let p=e.entries.cache;if(!p)return;let m;for(let[,g]of p){if(g.provider!==i)continue;let y=g.id;d.startsWith(y)&&(!m||y.length>m.id.length)&&(m=g)}return m},o=128,a=new Map,s=new Map,l=(i,d,c,p)=>{for(i.has(d)&&i.delete(d),i.set(d,c);i.size>p;){let m=i.keys().next().value;if(m===void 0)break;i.delete(m)}},u=M([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:r,lookup:n,remove(i,d){let c=e.has(we(i,d));return c&&e.delete(we(i,d)),c},entries(){let i=e.entries.cache;return(function*(){if(i)for(let d of i.values())yield d})()},lookupNode(i,d){let c=we(i,d),p=a.get(c);if(p)return a.delete(c),a.set(c,p),p;let m=M([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,c,m,o),m},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let c=M([u],([p])=>p.filter(m=>m.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,c,o),c}}}function Z(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function ie(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function kt(){return{input:{regular:0},output:{regular:0}}}function zt(t,e){let r=e?.logMax??1e3,n=Te(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),o=L(null,{name:"adapterStats/lastCall"}),a=M([n.entries],([y])=>y.length,{name:"adapterStats/totalCalls",initial:0}),s=M([n.entries],([y])=>y.reduce((f,b)=>f+Z(b.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),l=M([n.entries],([y])=>y.reduce((f,b)=>f+ie(b.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[F(a),F(s),F(l)],i=y=>{n.append(y),o.emit(y)},d=()=>{n.clear(),o.emit(null)},c=H(t,{invoke(y,f){let b=X(),O=Re(),v=t.model??f?.model??"",A=S=>(i(pe({provider:t.provider,model:t.model??f?.model??S.model??"",tier:f?.tier??S.tier,usage:S.usage??re(),startNs:b,startWallClockNs:O,method:"invoke"})),S),C=S=>{let $=S;i(pe({provider:t.provider,model:v,tier:f?.tier,usage:re(),startNs:b,startWallClockNs:O,method:"invoke",error:{type:$?.name??"Error",message:$?.message??String(S)}}))};return Ee(t.invoke(y,f),{onResp:A,onError:C,name:"adapterStats/invokeTap"})},async*stream(y,f){let b=X(),O=Re(),v=t.model??f?.model??"",A;try{for await(let C of t.stream(y,f))C.type==="usage"&&(A=C.usage),yield C;i(pe({provider:t.provider,model:v,tier:f?.tier,usage:A??re(),startNs:b,startWallClockNs:O,method:"stream"}))}catch(C){let S=C;throw i(pe({provider:t.provider,model:v,tier:f?.tier,usage:A??re(),startNs:b,startWallClockNs:O,method:"stream",error:{type:S?.name??"Error",message:S?.message??String(C)}})),C}}});q(c,"observableAdapter",t);let p=!1;return{adapter:c,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!p){p=!0;for(let y of u)y();u.length=0}}}}}function Jt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Oe(t="USD"){return{total:0,currency:t}}function qe(t,e,r){let n=Z(t),o=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,l=0,u=(f,b,O)=>{if(!b||O==null)return;let v=Jt(O,n),A=b*v/1e6;l+=A,a&&(s[f]=(s[f]??0)+A)},i=t.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,b]of Object.entries(i.extensions))u(`input.ext.${f}`,b,d.extensions[f]);let c=t.output,p=e.output;if(p&&(u("output.regular",c.regular,p.regular),u("output.reasoning",c.reasoning??0,p.reasoning),u("output.audio",c.audio??0,p.audio),u("output.predictionAccepted",c.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",c.predictionRejected??0,p.predictionRejected),c.extensions&&p.extensions))for(let[f,b]of Object.entries(c.extensions))u(`output.ext.${f}`,b,p.extensions[f]);let m=r?.tier;if(m&&e.tierMultipliers){let f=e.tierMultipliers[m];if(f!=null&&(l*=f,a))for(let b of Object.keys(s))s[b]*=f}let g=t.auxiliary,y=e.auxiliary;if(g&&y)for(let[f,b]of Object.entries(g)){let O=y[f];if(O==null||!b)continue;let v=b*O;l+=v,a&&(s[`auxiliary.${f}`]=v)}return a?{total:l,currency:o,breakdown:s}:{total:l,currency:o}}function Ie(t,e){return`${t}::${e}`}function Yt(t){let e=new Map,r=new Map,n=(o,a,s)=>{e.set(Ie(o,a),{provider:o,model:a,pricing:s});let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(a)};if(t)for(let[o,a,s]of t)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Ie(o,a));if(s)return s.pricing;let l=r.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Ie(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Ie(o,a));if(s){let l=r.get(o);l?.delete(a),l&&l.size===0&&r.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}function Qt(t,e="USD"){return(r,n)=>{let o=t.lookup(n.provider,n.model);return o?qe(r,o,{tier:n.tier,withBreakdown:n.withBreakdown}):Oe(e)}}function Xt(...t){return(e,r)=>{for(let n of t){let o=n(e,r);if(o.total!==0)return o}return t.length>0?t[0](e,r):Oe()}}function Zt(t,e,r){return t?.pricing?qe(e,t.pricing,r):Oe()}function ze(t,e={}){let r=e.breaker??ut(e),n=H(t,{async invoke(o,a){if(!r.canExecute())throw new Ae;try{let s=await le(k(t.invoke(o,a)));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(o,a){if(!r.canExecute())throw new Ae;try{for await(let s of t.stream(o,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}});return q(n,"withBreaker",t),{adapter:n,breaker:r}}var Pe=class extends Error{constructor(r,n,o){super(`Budget exhausted: ${r} (limit=${n}, observed=${o})`);this.which=r;this.limit=n;this.observed=o}name="BudgetExhaustedError"},Je=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),xt=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Ye(t,e){let r=Te(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=L(xt(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=M([n],([i])=>{let d=i;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(F(o),e.onExhausted!=null){let i=e.onExhausted,d=!1,c=!0;o.subscribe(p=>{for(let m of p)if(m[0]===V){let g=m[1];if(d&&c&&g===!1){let y=Rt(n.cache??Je,e.caps);y&&i(y)}c=g,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??Je,d=Rt(i,e.caps);return new Pe(d??"budget",e.caps[d??"calls"]??0,er(i,d??"calls"))}},s=(i,d)=>{let c=t.provider,p=pe({provider:c,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});r.append(p);let m=n.cache??Je,g=e.pricingFn?m.usd+e.pricingFn(i,{model:d.model,provider:c,tier:d.tier}).total:m.usd;n.emit({calls:m.calls+1,inputTokens:m.inputTokens+Z(i),outputTokens:m.outputTokens+ie(i),usd:g})},l=()=>{r.clear(),n.emit(xt())},u=H(t,{invoke(i,d){let c=a();if(c)return Promise.reject(c);let p=X(),m=t.model??d?.model??"",g=f=>(s(f.usage??re(),{model:t.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:p,method:"invoke"}),f),y=f=>{let b=f;s(re(),{model:m,tier:d?.tier,startNs:p,method:"invoke",error:{type:b?.name??"Error",message:b?.message??String(f)}})};return Ee(t.invoke(i,d),{onResp:g,onError:y,name:"budgetGate/invokeTap"})},async*stream(i,d){let c=a();if(c)throw c;let p=X(),m;try{for await(let g of t.stream(i,d))g.type==="usage"&&(m=g.usage),yield g;s(m??re(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(g){let y=g;throw s(m??re(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:y?.name??"Error",message:y?.message??String(g)}}),g}}});return q(u,"withBudgetGate",t),{adapter:u,budget:{totals:n,isOpen:o,log:r,reset:l}}}function Rt(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function er(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function tr(t,e){let r=e.mock??Ue({provider:t.provider,model:t.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?k(e.enabled):void 0,a;o&&(a=F(o));let s=()=>n!==void 0?n:!!o?.cache,l=H(t,{invoke(i,d){return s()?r.invoke(i,d):t.invoke(i,d)},stream(i,d){return s()?r.stream(i,d):t.stream(i,d)}});return q(l,"withDryRun",t),{adapter:l,dispose:()=>{a&&(a(),a=void 0)}}}function Qe(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,n=rr(e.headers);if(r!==429&&r!==503&&!lr(e.message))return;let o={},a=n("retry-after"),s=or(a);s!=null&&(o.retryAfterMs=s);let l=n("anthropic-ratelimit-requests-reset");if(l){let m=wt(l);m!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,m))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let m=wt(u);m!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,m))}let i=_e(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=_e(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let c=_e(n,"x-ratelimit-remaining-requests"),p=_e(n,"x-ratelimit-remaining-tokens");if(c!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-c/i),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let m=sr(e.message);m!=null&&(o.retryAfterMs=m)}return e.headers&&(o.metadata={headers:nr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function rr(t){if(!t)return()=>{};if(typeof t.get=="function"){let n=t;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=t,r={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(r[n.toLowerCase()]=a)}return n=>r[n.toLowerCase()]}function nr(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,n)=>{e[n]=r}),e;for(let[r,n]of Object.entries(t))n!=null&&(e[r]=Array.isArray(n)?n.join(", "):n);return e}function _e(t,e){let r=t(e);if(r==null)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function or(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function wt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ar=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function sr(t){let e=ar.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return r;if(n.startsWith("s"))return r*1e3;if(n.startsWith("m"))return r*6e4}var ir=/rate\s*limit|too\s*many\s*requests|quota|429/i;function lr(t){return!!t&&ir.test(t)}function Xe(t){let e=new Error(t);return e.name="AbortError",e}function Nt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,n=t.rpm!=null?k(t.rpm):L(Number.POSITIVE_INFINITY),o=t.tpm!=null?k(t.tpm):L(Number.POSITIVE_INFINITY),a=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=L({},{name:"adaptiveRateLimiter/lastSignal"}),u=M([n,a],([w,I])=>Math.min(Number(w??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=M([o,s],([w,I])=>Math.min(Number(w??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Me(Number(n.cache??Number.POSITIVE_INFINITY),e),c=Me(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,m=!1,g=u.subscribe(w=>{for(let I of w)if(I[0]===V){let _=Number(I[1]);Number.isFinite(_)&&_>0?(d=Me(_,e),p=!1):_===1/0?(d=Me(1/0,e),p=!1):_<=0&&(p=!0)}}),y=i.subscribe(w=>{for(let I of w)if(I[0]===V){let _=Number(I[1]);Number.isFinite(_)&&_>0?(c=Me(_,e),m=!1):_===1/0?(c=Me(1/0,e),m=!1):_<=0&&(m=!0)}}),f=0,b=new te,O=new te,v;t.adaptation!=null&&(v=k(t.adaptation).subscribe(I=>{for(let _ of I)_[0]===V&&A(_[1])}));function A(w){if(l.emit(w),w.rpmCap!=null&&Number.isFinite(w.rpmCap)&&w.rpmCap>=0&&(a.emit(w.rpmCap),Number.isFinite(r)&&r>0&&b.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),w.tpmCap!=null&&Number.isFinite(w.tpmCap)&&w.tpmCap>=0&&(s.emit(w.tpmCap),Number.isFinite(r)&&r>0&&O.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),w.retryAfterMs!=null&&w.retryAfterMs>0){let I=X()+w.retryAfterMs*1e6;I>f&&(f=I)}}let C=L(0,{name:"adaptiveRateLimiter/pending"}),S=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),$=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),U=w=>{C.emit((C.cache??0)+w)},W=()=>{S.emit(d.available()),$.emit(c.available())};async function Y(w={}){let I=w.requestCost??1,_=w.tokenCost??0,T=w.signal;U(1);try{for(;;){if(T?.aborted)throw Xe("AdaptiveRateLimiter.acquire aborted");let h=X();if(f>h){let ne=Math.ceil((f-h)/1e6);await De(ne,T);continue}if(I>0&&p||_>0&&m){await De(250,T);continue}let x=d,R=c;if(!x.tryConsume(I)){await De(Lt(x,I),T);continue}if(!(_>0?R.tryConsume(_):!0)){x.putBack(I),await De(Lt(R,_),T);continue}W();return}}finally{U(-1)}}function K(w){w>0?c.tryConsume(w):w<0&&c.putBack(-w),W()}function G(){g(),y(),v?.(),b.cancel(),O.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:C,rpmAvailable:S,tpmAvailable:$,acquire:Y,recordUsage:K,recordSignal:A,dispose:G}}function Me(t,e){if(!Number.isFinite(t)||t===1/0)return We(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),n=t/60;return We(r,n)}function Lt(t,e){let r=t.available(),n=Math.max(0,e-r);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function De(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xe("AdaptiveRateLimiter.acquire aborted")):new Promise((r,n)=>{let o=new te,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(Xe("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ze(t,e={}){let r=e.limiter??Nt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=Qe(s);l&&r.recordSignal(l)},a=H(t,{async invoke(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await le(k(t.invoke(s,l))),d=i.usage??kt(),p=Z(d)+ie(d)-u;return p>0&&r.recordUsage(p),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let c of t.stream(s,l))c.type==="usage"&&(i=Z(c.usage)+ie(c.usage)),yield c;let d=i-u;d>0&&r.recordUsage(d)}catch(i){throw o(i),i}}});return q(a,"withRateLimiter",t),{adapter:a,limiter:r}}function je(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Ct(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(je()):new Promise((r,n)=>{let o=new te,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(je())},e.addEventListener("abort",a,{once:!0}))})}function et(t,e={}){let r=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,l=e.shouldRetry??dr,u=e.retryStreaming??!0,i=(c,p)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,p*3));return n+Math.random()*(f-n)}let m=a==="exp"?n*2**(c-1):n*c,g=Math.min(o,m);if(!s)return g;let y=g*(.5+Math.random());return Math.min(o,y)},d=H(t,{async invoke(c,p){if(p?.signal?.aborted)throw je();let m,g=n;for(let y=1;y<=r;y++)try{return await le(k(t.invoke(c,p)))}catch(f){if(m=f,y>=r||!l(f,y))throw f;let b=i(y,g);g=b,await Ct(b,p?.signal)}throw m},async*stream(c,p){if(p?.signal?.aborted)throw je();if(!u){for await(let y of t.stream(c,p))yield y;return}let m,g=n;for(let y=1;y<=r;y++){let f=!1;try{for await(let b of t.stream(c,p))f=!0,yield b;return}catch(b){if(m=b,f||y>=r||!l(b,y))throw b;let O=i(y,g);g=O,await Ct(O,p?.signal)}}throw m}});return q(d,"withRetry",t),d}function dr(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var ve=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function tt(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=a=>{let s=new AbortController,l=!1,u,i=new te;return a&&(a.aborted?s.abort(a.reason):(u=()=>{i.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),i.start(e,()=>{l=!0,s.abort(new ve(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ve)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ve(e);throw i.cause=a,i}throw a},o=H(t,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{return await le(k(t.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{for await(let d of t.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}finally{u()}}});return q(o,"withTimeout",t),o}function ur(t,e={}){let r={adapter:t},n=t;if(e.rateLimit){let o=Ze(n,e.rateLimit);n=o.adapter,r.rateLimiter=o.limiter}if(e.budget){let o=Ye(n,e.budget);n=o.adapter,r.budget=o.budget}if(e.breaker){let o=ze(n,e.breaker);n=o.adapter,r.breaker=o.breaker}if(e.timeoutMs!=null&&(n=tt(n,e.timeoutMs)),e.retry&&(n=et(n,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),n=Ve([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Ke(n,e.cache)),r.adapter=n,r}function cr(t,e,r){let n=k(e);return J(n,a=>{if(!a||a.length===0)return L(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return pt("ai",t,e)}function mr(t){return t!=null&&typeof t.then=="function"}function pr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function fr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var gr=3e4;function At(t,e){if(t.status==="settled"){let n=t.cache;if(n!==void 0)return Promise.resolve(n)}let r=e?.timeoutMs??gr;return new Promise((n,o)=>{let a=new te,s=t.subscribe(l=>{for(let u of l){if(u[0]===V){a.cancel(),s(),n(u[1]);return}if(u[0]===Q){a.cancel(),s(),o(u[1]);return}if(u[0]===ae){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function fe(t){return mr(t)?fe(await t):pr(t)?At(t):fr(t)?At(k(t)):t}function ke(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function yr(t,e){let r=k(t),n=e?.refreshTrigger!=null?k(e.refreshTrigger):null;return n==null?ce([r],(o,a,s)=>{if(s.store.emitted===!0)return;let u=o[0],i=u!=null&&u.length>0?u.at(-1):s.prevData[0];if(i!==void 0)return s.store.emitted=!0,a.emit(i),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")}):ce([r,n],(o,a,s)=>{let l=o[1];if(!(l!=null&&l.length>0))return;let i=o[0],d=i!=null&&i.length>0?i.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")})}function hr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function br(t,e,r,n){let o=n?.format??"text",a=n?.retries??0,s=n?.cache??!1,l=s?new Map:null,u=M(e,d=>{if(d.some(m=>m==null))return[];let c=typeof r=="string"?r:r(...d);if(!c)return[];let p=[];return n?.systemPrompt&&p.push({role:"system",content:n.systemPrompt}),p.push({role:"user",content:c}),p},{name:n?.name?`${n.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(u,d=>{if(!d||d.length===0)return L(null);let c=s?JSON.stringify(d.map(m=>[m.role,m.content])):"";if(l?.has(c))return L(l.get(c));async function p(m){try{let g=await new Promise((b,O)=>{let v=t.invoke(d,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt});v&&typeof v.then=="function"?v.then(b,O):v&&typeof v.subscribe=="function"?b(v.cache):b(v)}),y=hr(g),f;return o==="json"?f=JSON.parse(ke(y)):f=y,l?.set(c,f),f}catch(g){if(m>0)return p(m-1);throw g}}return p(a)})}async function St(t,e,r,n){let o="",a=0;for await(let s of t.stream(e,r))n.publish({...s,seq:a++,ts:Re()}),s.type==="token"&&(o+=s.delta);return o}function Et(t,e){if(e==="json")try{return JSON.parse(ke(t))}catch(r){let n=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${r.message}; content preview: ${n}`)}return t}function It(t,e){return M([t.latest],([r],n)=>{let o=n.store;if(r==null)return o.acc??"";let a=r;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:N("accumulated_text"),initial:""})}function Tr(t,e,r,n){let o=n?.name??"llm",a=n?.format??"text",s=He(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),l=M(e,c=>{if(c.some(m=>m==null))return[];let p=typeof r=="string"?r:r(...c);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:N("prompt_node::messages"),initial:[]}),u=J(l,c=>{let p=c;if(!p||p.length===0)return L(null);let m=new AbortController;async function*g(){try{let y=await St(t,p,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:m.signal},s);yield Et(y,a)}finally{m.abort()}}return k(g())}),i=It(s,`${o}::accumulatedText`),d=F(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Mr(t,e,r,n,o,a){let s=L(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",c=He(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),p=M(u,A=>{let C=A.slice(0,-1);if(C.some($=>$==null))return[];let S=typeof o=="string"?o:o(...C);return S?[{role:"user",content:S}]:[]},{name:`${i}::messages`,meta:N("prompt_node::messages"),initial:[]}),m=J(p,A=>{let C=A;if(!C||C.length===0)return L(null);let S=new AbortController;async function*$(){try{let U=await St(r,C,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:S.signal},c);yield Et(U,d)}finally{S.abort()}}return k($())}),g=It(c,`${i}::accumulatedText`),y=M([m],([A])=>{if(A!=null)return A},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let f=yt(t,`${e}/gate`,`${e}/raw`,a?.gate),b=F(m),O=f.reject.bind(f),v={...f,reject(A=1){se(()=>{O(A),s.emit(++l)})}};return{output:f.node,deltaTopic:c,accumulatedText:g,gate:v,dispose:()=>{b(),c.destroy()}}}function vr(t,e){let r=e?.separator??`
2
-
3
- `,n=t.map(s=>typeof s=="string"?L(s):k(s)),o=M(n,s=>s.filter(l=>l!=null&&l!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=F(o);return Object.assign(o,{dispose:a})}var kr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function xr(t,e){let r=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return M([t.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=Z(s.usage)+ie(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/r);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:N("cost_meter_extractor"),equals:kr})}var Rr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function wr(t,e){let r=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>r)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${r}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return M([t],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-r),d=s.slice(i),c=!1;for(let{pattern:p,label:m,compiled:g}of n){g.lastIndex=0;for(let y of d.matchAll(g)){let f=i+(y.index??0);f+y[0].length<=u||(l.push({label:m,pattern:p,match:y[0],position:f}),c=!0)}}return a.store.scannedTo=s.length,c?[...l]:l.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:Rr})}function Lr(t,e,r){return M([t],([n])=>n==null?null:e(n),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Nr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function Cr(t,e){return M([t],([r],n)=>{if(r==null)return[];let o=r;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,c=!1;for(let m=u;m<o.length;m++){let g=o[m];if(c)g==="\\"&&m+1<o.length?m++:g==='"'&&(c=!1);else if(g==='"')c=!0;else if(g==="{")i++;else if(g==="}"&&(i--,i===0)){d=m;break}}if(d===-1){n.store.scanFrom=u;break}let p=o.slice(u,d+1);try{let m=JSON.parse(p);typeof m.name=="string"&&m.arguments!=null&&typeof m.arguments=="object"&&(a.push({name:m.name,arguments:m.arguments,raw:p,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Nr})}function Ar(t,e,r,n){let o=r*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[t];return a&&s.push(e),M(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=r?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function Sr(t,e,r,n){let o=r??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return M([t],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var Fe=class extends de{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=Te([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=M([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(F(this.latest)),this.messageCount=M([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(F(this.messageCount))}append(e,r,n){this._log.append({role:e,content:r,...n})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function rt(t,e){return new Fe(t,e)}var Ge=class extends de{definitions;schemas;_bundle;constructor(e,r={}){super(e,r.graph),this._bundle=Se({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=M([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(F(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=n.handler(r);return fe(o)}executeReactive(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return k(n.handler(r))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function nt(t,e){return new Ge(t,e)}var Be=class extends de{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=rt(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=nt(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let T of r.tools)this.tools.register(T);this.status=L("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=L(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=L(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(T=>{for(let h of T)h[0]===V&&(n=h[1])}),a=!1,s=this.aborted.subscribe(T=>{for(let h of T)h[0]===V&&(a=h[1])}),l=r.adapter,u=r.systemPrompt,i=r.model,d=r.temperature,c=r.maxTokens,p=r.maxTurns??10,m=r.stopWhen,g=this.chat,y=this.tools,f=this.status,b=this.turn,O=this.aborted,v=ce([f],(T,h,x)=>{if(Le(T,x.prevData,0,"idle")!=="thinking"||a||n>=p){h.down([[be]]);return}let P=g.allMessages();if(P.length===0){h.down([[be]]);return}let E=y.schemas.cache??[];h.emit({messages:P,tools:E})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(v,T=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),k(Promise.resolve(l.invoke(T.messages,{tools:T.tools.length>0?T.tools:void 0,systemPrompt:u,model:i,temperature:d,maxTokens:c,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),C=L(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=C;let S=ce([C,f],(T,h,x)=>{let R=Le(T,x.prevData,0,null);if(Le(T,x.prevData,1,"idle")!=="acting"){h.down([[be]]);return}let E=R?.toolCalls;if(E==null||E.length===0){h.down([[be]]);return}h.emit(E)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),$=r.interceptToolCalls?r.interceptToolCalls(S):S;this.toolCalls=$;let U=(T,h)=>{if(T===h)return!0;if(T.length!==h.length)return!1;for(let x=0;x<T.length;x++){let R=T[x],P=h[x];if(R?.id!==P?.id||R?.content!==P?.content)return!1}return!0},W=J($,T=>{if(T==null||T.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let h=T.map(x=>Er(x,y));return M(h,x=>x.map((R,P)=>{let E=R;return E!=null&&typeof E=="object"&&"id"in E&&"content"in E?E:{id:T[P].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:U})});this.toolResults=W;let Y=me([A],([T])=>{if(a)return;let h=T,x=n+1,R=h.toolCalls!=null&&h.toolCalls.length>0,P=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),E=m?.(h)===!0,ne=x>=p,oe=E||P||!R||ne?"done":"acting";se(()=>{C.emit(h),f.emit(oe),b.emit(x),g.append("assistant",h.content,{toolCalls:h.toolCalls})})}),K=me([W],([T])=>{if(a)return;let h=T;if(h.length===0)return;let x=n>=p?"done":"thinking";se(()=>{f.emit(x);for(let R of h)g.appendToolResult(R.id,R.content)})}),G=me([O],([T])=>{T===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),f.emit("done"))}),w=F(Y),I=F(K),_=F(G);this._terminalResult=ce([f,C],(T,h,x)=>{let R=Le(T,x.prevData,0,"idle"),P=Le(T,x.prevData,1,null);if(R==="done"){if(P!=null){h.emit({response:P,runVersion:this._runVersion});return}let E=new Error("agentLoop: aborted");E.name="AbortError",h.down([[Q,E]]);return}if(R==="error"){h.down([[Q,new Error("agentLoop: errored")]]);return}h.down([[be]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(w),this.addDisposer(I),this.addDisposer(_),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n=++this._runVersion;se(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),o=()=>r.removeEventListener("abort",a)}try{return(await mt(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===n})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Er(t,e){let r=dt(()=>k(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),n=M([r],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return ft(n,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function Le(t,e,r,n){let o=t[r];if(o!=null&&o.length>0)return o[o.length-1];let a=e[r];return a!==void 0?a:n}function Ir(t,e){return new Be(t,e)}function Or(t,e,r){let n=k(t),o=r?.condition!=null?k(r.condition):null,a=L(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(o==null)return J(n,l=>{if(l==null)return a;let u=L(l);return e(u)});let s=M([n,o],([l,u])=>({v:l,open:u===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return L(l);let i=L(l);return e(i)})}function Pr(t,e,r){let n=k(t),o=e.map(s=>k(s)),a=[n,...o];return M(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),equals:(s,l)=>{let u=s,i=l;if(u.length!==i.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==i[d])return!1;return!0}})}function _r(t){return{persistence:.5,structure:.5,personalValue:.5}}function Dr(t={}){let e=t.scoreFn??_r,r=t.persistenceThreshold??.3,n=t.personalValueThreshold??.3,o=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<n||o&&s.structure<=0)}}function ot(t,e){return(r,n)=>{let o=[...n.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:o})}];return $e(s=>{let l=!0,u=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=k(u).subscribe(c=>{if(!l)return;let p=!1;for(let m of c){if(p)break;if(m[0]===V){let g=m[1];try{let y=JSON.parse(g.content);s.emit(y),s.down([[ae]])}catch{s.down([[Q,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else m[0]===Q?(s.down([[Q,m[1]]]),p=!0):m[0]===ae?(s.down([[ae]]),p=!0):s.down([[m[0],m[1]]])}});return()=>{d(),l=!1}})}}function at(t,e){return r=>{let n=[...r.entries()].map(([a,s])=>({key:a,value:s})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:n})}];return $e(a=>{let s=!0,l=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),i=k(l).subscribe(d=>{if(!s)return;let c=!1;for(let p of d){if(c)break;if(p[0]===V){let m=p[1];try{let g=JSON.parse(m.content);a.emit(g),a.down([[ae]])}catch{a.down([[Q,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}c=!0}else p[0]===Q?(a.down([[Q,p[1]]]),c=!0):p[0]===ae?(a.down([[ae]]),c=!0):a.down([[p[0],p[1]]])}});return()=>{i(),s=!1}})}}var st=Math.LN2/604800;function Ne(t){return t instanceof Map?t:new Map}function jr(t,e,r){let n=new de(t,r.graph),o=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=ot(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(v,A)=>v==null?{upsert:[]}:a(v,A),l=e;if(r.admissionFilter){let v=k(e),A=r.admissionFilter;l=M([v],([C])=>{if(A(C))return C},{name:"admissionFilter",describeKind:"derived"})}let u;r.consolidateFn?u=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(u=at(r.consolidatePrompt,{adapter:r.adapter}));let i=r.consolidateTrigger;if(!i&&u&&r.reflection?.enabled!==!1){let v=r.reflection?.interval??3e5;i=ct(v,{period:v})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:u,consolidateTrigger:i},c=gt(l,s,d);n.add(c.store.entries,{name:"store"}),n.add(c.compact,{name:"compact"}),n.add(c.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=Tt({dimension:r.vectorDimensions}),n.add(p.entries,{name:"vectorIndex"}));let m=null;r.enableKnowledgeGraph&&(m=Mt(`${t}-kg`),n.mount("kg",m));let g=null;if(r.tiers){let v=r.tiers,A=v.decayRate??st,C=v.maxActive??1e3,S=v.archiveThreshold??.1,$=v.permanentFilter??(()=>!1),U=bt({name:"permanent"});n.add(U.entries,{name:"permanent"});let W=new Set,Y=h=>W.has(h)?"permanent":Ne(c.store.entries.cache).has(h)?"active":"archived",K=(h,x)=>{W.add(h),U.upsert(h,x)},G=new Map,w=c.store.entries,I=r.context?k(r.context):L(null),_=me([w,I],([h,x])=>{let R=Ne(h),P=X(),E=[],ne=[];for(let[j,ee]of R){if(G.has(j)||G.set(j,P),$(j,ee)){ne.push({key:j,value:ee});continue}let z=r.score(ee,x),D=G.get(j)??P,B=Number(P-D)/1e9;ht(z,B,A)<S&&E.push(j)}for(let j of G.keys())R.has(j)||G.delete(j);for(let{key:j,value:ee}of ne)W.has(j)||K(j,ee);let oe=R.size-W.size;if(oe>C){let j=[...R.entries()].filter(([z])=>!W.has(z)).map(([z,D])=>({key:z,score:r.score(D,x)})).sort((z,D)=>z.score-D.score),ee=oe-C;for(let z=0;z<ee&&z<j.length;z++){let D=j[z].key;E.includes(D)||E.push(D)}}E.length>0&&se(()=>{for(let j of E)c.store.delete(j)})});o.push(_.subscribe(()=>{}));let T=null;v.archiveTier&&(T=n.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),g={permanent:U,activeEntries:w,archiveHandle:T,tierOf:Y,markPermanent:K}}if(p||m){let v=r.embedFn,A=r.entityFn,C=c.store.entries,S=me([C],([$])=>{let U=Ne($);for(let[W,Y]of U){if(p&&v){let K=v(Y);K&&p.upsert(W,K,Y)}if(m&&A){let K=A(W,Y);if(K){for(let G of K.entities??[])m.upsertEntity(G.id,G.value);for(let G of K.relations??[])m.link(G.from,G.to,G.relation,G.weight)}}}});o.push(S.subscribe(()=>{}))}let y=null,f=null,b=null,O=null;if(p||m){let v=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,C=r.budget??2e3,S=r.cost,$=r.score,U=r.contextOf,W=r.contextWeight??0,Y=r.context?k(r.context):L(null),K=(T,h)=>{if(!T||!h)return 0;let x=Math.min(T.length,h.length),R=0;for(;R<x&&T[R]===h[R];)R++;return R},G=(T,h,x)=>{let R=new Map,P=[];if(p&&x.vector){P=p.search(x.vector,v);for(let D of P){let B=T.get(D.id);B&&R.set(D.id,{value:B,sources:new Set(["vector"])})}}let E=[];if(m){let D=[...x.entityIds??[],...R.keys()],B=new Set,ge=D;for(let ye=0;ye<A;ye++){let ue=[];for(let xe of ge){if(B.has(xe))continue;B.add(xe);let Ce=m.related(xe);for(let _t of Ce){let he=_t.to;if(!B.has(he)){ue.push(he);let it=T.get(he);if(it){let lt=R.get(he);lt?lt.sources.add("graph"):R.set(he,{value:it,sources:new Set(["graph"])}),E.push(he)}}}}ge=ue}}for(let[D,B]of T)R.has(D)||R.set(D,{value:B,sources:new Set(["store"])});let ne=x.context?.length??0,oe=[];for(let[D,{value:B,sources:ge}]of R){let ye=U?U(B):void 0,ue=$(B,h);if(W>0&&ne>0){let Ce=K(x.context,ye);Ce>0&&(ue=ue*(1+W*Ce/ne))}let xe=ye?{key:D,value:B,score:ue,sources:[...ge],context:ye}:{key:D,value:B,score:ue,sources:[...ge]};oe.push(xe)}oe.sort((D,B)=>B.score-D.score);let j=[],ee=0;for(let D of oe){let B=S(D.value);if(ee+B>C&&j.length>0)break;j.push(D),ee+=B}return{packed:j,trace:{vectorCandidates:P,graphExpanded:E,ranked:oe,packed:j}}},w=L([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});n.add(w,{name:"retrieval"}),y=w;let I=L(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});n.add(I,{name:"retrievalTrace"}),f=I,b=T=>{let h=Ne(c.store.entries.cache),{packed:x,trace:R}=G(h,Y.cache,T);return se(()=>{w.emit(x),I.emit(R)}),x},O=T=>{let h=k(T);return M([c.store.entries,Y,h],([x,R,P])=>{if(P==null)return[];let E=Ne(x);return G(E,R,P).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return n.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(n,{distillBundle:c,compact:c.compact,size:c.size,vectors:p,kg:m,memoryTiers:g,retrieval:y,retrievalTrace:f,retrieve:b,retrieveReactive:O})}function Fr(t,e,r){let n=t.describe({actor:e,detail:"full"}),o=r?.groupByTags??!0,a=r?.separator??`
4
- `,s=[],l=r?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},c=d.description,p=d.format;if(!c&&!p)continue;if(l!=null&&i.v!=null){let b=l.get(u);if(b!=null&&b.id===i.v.id&&i.v.version<=b.version)continue}let m=c??u,g=i.value,y=d.unit,f;p==="currency"&&typeof g=="number"?f=`$${g.toFixed(2)}`:p==="percentage"&&typeof g=="number"?f=`${(g*100).toFixed(1)}%`:g==null?f="(no value)":f=String(g),y&&p!=="currency"&&p!=="percentage"&&(f=`${f} ${y}`),s.push({path:u,description:m,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let c of s){let m=n.nodes[c.path].meta?.tags;if(m&&m.length>0){let g=m[0],y=u.get(g);y||(y=[],u.set(g,y)),y.push(c)}else i.push(c)}if(u.size===0)return s.map(c=>`- ${c.description}: ${c.formatted}`).join(a);let d=[];for(let[c,p]of[...u.entries()].sort((m,g)=>m[0].localeCompare(g[0])))d.push(`[${c}]${a}${p.map(m=>`- ${m.description}: ${m.formatted}`).join(a)}`);return i.length>0&&d.push(i.map(c=>`- ${c.description}: ${c.formatted}`).join(a)),d.join(a+a)}return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a)}var Ot=`You are a graph architect for GraphReFly, a reactive graph protocol.
5
-
6
- Given a natural-language description, produce a JSON graph specification with this structure:
7
-
8
- {
9
- "name": "<graph_name>",
10
- "nodes": {
11
- "<node_name>": {
12
- "type": "state" | "derived" | "producer" | "effect" | "operator",
13
- "initial": <initial_value_for_state_nodes>,
14
- "deps": ["<dep_node_name>", ...],
15
- "meta": {
16
- "description": "<human-readable purpose>",
17
- "type": "string" | "number" | "boolean" | "integer" | "enum",
18
- "range": [min, max],
19
- "values": ["a", "b"],
20
- "format": "currency" | "percentage" | "status",
21
- "access": "human" | "llm" | "both" | "system",
22
- "unit": "<unit>",
23
- "tags": ["<tag>"]
24
- }
25
- }
26
- }
27
- }
28
-
29
- Rules:
30
- - "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
31
- - "derived" nodes have deps and compute from them (pure, no side effects).
32
- - "effect" nodes have deps but produce side effects (no return value).
33
- - "producer" nodes have no deps but generate values asynchronously.
34
- - "operator" nodes are parameterized transformations with deps.
35
- - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
36
- - meta.description is required for every node.
37
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Gr(t,e,r){let o=[{role:"system",content:r?.systemPromptExtra?`${Ot}
38
-
39
- ${r.systemPromptExtra}`:Ot},{role:"user",content:t}],a=e.invoke(o,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),l=(await fe(a)).content.trim();l.startsWith("```")&&(l=ke(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return vt(u,{catalog:r?.catalog})}function Br(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function $r(t,e){let r=t.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,l]of Object.entries(r.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,c=Br(u),p={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},m=s.replace(/::/g,"__");n.push({type:"function",function:{name:m,description:d,parameters:p}}),o.push({name:s,description:d,inputSchema:p});let g=t,y=e,f=l.v;a.push({name:s,description:d,parameters:p,handler(b){return g.set(s,b.value,y?{actor:y}:void 0),b.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var Wr=`You are a reactive graph optimizer for GraphReFly.
40
-
41
- Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
42
-
43
- Return ONLY valid JSON with this structure:
44
- {
45
- "summary": "<one-line summary of the strategy>",
46
- "reasoning": "<explanation of why these changes help>",
47
- "operations": [
48
- { "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
49
- { "type": "remove_node", "name": "<name>" },
50
- { "type": "connect", "from": "<source>", "to": "<target>" },
51
- { "type": "disconnect", "from": "<source>", "to": "<target>" },
52
- { "type": "set_value", "name": "<name>", "value": <new_value> },
53
- { "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
54
- ]
55
- }
56
-
57
- Rules:
58
- - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
59
- - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
60
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Ur(t,e,r,n){let{expand:o,...a}=t.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:Wr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],l=r.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),i=(await fe(l)).content.trim();i.startsWith("```")&&(i=i.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(i)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${i.slice(0,200)}`)}let c=d;if(typeof c.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof c.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(c.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:c.summary,reasoning:c.reasoning,operations:c.operations}}var Pt=new Set(["state","derived","producer","operator","effect"]);function Kr(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(r.nodes));for(let[o,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Pt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Pt].join(", ")})`),Array.isArray(s.deps))for(let l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{qt as a,zt as b,Oe as c,qe as d,Yt as e,Qt as f,Xt as g,Zt as h,ze as i,Pe as j,Ye as k,tr as l,Qe as m,Ze as n,et as o,ve as p,tt as q,ur as r,cr as s,yr as t,br as u,Tr as v,Mr as w,vr as x,xr as y,wr as z,Lr as A,Cr as B,Ar as C,Sr as D,Fe as E,rt as F,Ge as G,nt as H,Be as I,Ir as J,Or as K,Pr as L,Dr as M,ot as N,at as O,st as P,jr as Q,Fr as R,Gr as S,$r as T,Ur as U,Kr as V,Vr as W};
@@ -1,7 +0,0 @@
1
- import{a as Se}from"./chunk-SGS4OJGS.js";import{a as Le}from"./chunk-ESMPEKEV.js";import{a as re,b as _e}from"./chunk-N2KKISCE.js";import{B as Ee}from"./chunk-UMH3HSP7.js";import{A as we,C as L,E as ne,F as Me,G as Oe,e as $e,f as Te,i as Y,k as Ne,l as xe,m as Ae,o as K,p as Pe,s as W}from"./chunk-7AJKUA36.js";import{b as Q,c as me,d as be,e as Z,f as ye,g as ve,h as z,i as ee,j as te}from"./chunk-CK2E7BTU.js";function Ie(e,t,r,n={}){let o=t in e.nodes,s=r in e.nodes;if(!o)return se(t,r,"no-such-from");if(!s)return se(t,r,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(t===r){if(n.findCycle===!0){let u=lt(e,t,n);if(u!=null)return u}let l=oe(t,e.nodes[t],0,n);return ie(t,r,[l])}if(i===0)return se(t,r,"no-path");let a=je(e,t,r,i);return a.found?ie(t,r,Be(e,a.pathOrder,n)):se(t,r,a.truncated?"max-depth-exceeded":"no-path")}function je(e,t,r,n){let o=new Map,s=[{path:r,depth:0}],i=new Set([r]),a=0,l=!1;for(;a<s.length;){let h=s[a++];if(h.path===t)break;if(n!=null&&h.depth>=n){let g=e.nodes[h.path];g?.deps&&g.deps.length>0&&(l=!0);continue}let p=e.nodes[h.path];if(p==null)continue;let f=p.deps??[],c=new Map;for(let g=0;g<f.length;g++){let b=f[g];if(!b)continue;let v=c.get(b);v==null&&(v=[],c.set(b,v)),v.push(g)}for(let[g,b]of c)i.has(g)||(i.add(g),o.set(g,{from:h.path,depIndices:b}),s.push({path:g,depth:h.depth+1}))}if(!o.has(t))return{found:!1,pathOrder:[],truncated:l};let u=[{path:t}],d=t;for(;d!==r;){let h=o.get(d);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),d=h.from}return{found:!0,pathOrder:u,truncated:!1}}function lt(e,t,r){let n=e.nodes[t];if(n==null)return null;let o=n.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===t&&s.push(a);if(s.length>0){let a=oe(t,n,0,r);a.dep_index=s[0];let l=oe(t,n,1,r);return ie(t,t,[a,l])}let i=null;for(let a=0;a<o.length;a++){let l=o[a];if(!l||l===t)continue;let u=je(e,l,t,r.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:t,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:ie(t,t,Be(e,i.pathOrder,r))}function Be(e,t,r){return t.map((n,o)=>{let s=e.nodes[n.path],i=oe(n.path,s,o,r);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function oe(e,t,r,n){let o={path:e,type:t.type,hop:r};t.status!==void 0&&(o.status=t.status),"value"in t&&(o.value=t.value),t.v!=null&&(o.v=t.v);let s=n.annotations?.get(e)??t.annotation;s!=null&&(o.annotation=s);let i=n.lastMutations?.get(e)??t.lastMutation;return i!=null&&(o.lastMutation=i),o}function ie(e,t,r){return Fe(e,t,!0,"ok",r)}function se(e,t,r){return Fe(e,t,!1,r,[])}function Fe(e,t,r,n,o){let s=ct(e,t,r,n,o);return{from:e,to:t,found:r,reason:n,steps:o,text:s,toJSON(){return{from:e,to:t,found:r,reason:n,steps:o}}}}function ct(e,t,r,n,o){if(!r)switch(n){case"no-such-from":return`explainPath: no node named "${e}"`;case"no-such-to":return`explainPath: no node named "${t}"`;case"max-depth-exceeded":return`explainPath: no path from "${e}" to "${t}" within maxDepth`;default:return`explainPath: no path from "${e}" to "${t}"`}let s=[`Causal path: ${e} \u2192 ${t} (${o.length} step(s))`];for(let i of o){let l=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(l),"value"in i&&s.push(` value: ${dt(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
2
- `)}function dt(e){if(e===void 0)return"<sentinel>";if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return t.length>80?`${t.slice(0,77)}...`:t}catch{return String(e)}}var A={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},ft=Symbol.for("sizeof");function He(e){let t=new WeakSet,r=new WeakSet,n=[e],o=0;for(;n.length>0;){let s=n.pop();o+=pt(s,t,r,n)}return o}function pt(e,t,r,n){if(e==null)return 0;switch(typeof e){case"number":return A.number;case"boolean":return A.boolean;case"string":return A.string+e.length*2;case"bigint":return A.bigint+ht(e);case"symbol":return A.symbol;case"function":return t.has(e)?0:(t.add(e),A.function);case"undefined":return 0}let s=e;if(t.has(s))return 0;t.add(s);let i=s[ft];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return A.date;if(s instanceof RegExp)return A.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return A.error+u+d}if(typeof URL<"u"&&s instanceof URL)return A.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return A.promise;if(s instanceof WeakMap)return A.weakmap;if(s instanceof WeakSet)return A.weakset;if(s instanceof Map){let u=A.map;for(let[d,h]of s)u+=A.mapEntry,n.push(d),n.push(h);return u}if(s instanceof Set){let u=A.set;for(let d of s)u+=A.setEntry,n.push(d);return u}if(Array.isArray(s)){let u=A.array+s.length*8;for(let d of s)n.push(d);return u}if(s instanceof ArrayBuffer)return r.has(s)?0:(r.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return r.has(u.buffer)?48:(r.add(u.buffer),u.buffer.byteLength+48)}let a=A.object,l=Object.keys(s);for(let u of l){a+=A.string+u.length*2;try{n.push(s[u])}catch{}}return a}function ht(e){let t=e<0n?-e:e;if(t===0n)return 0;let r=t.toString(2).length;return Math.ceil(r/32)*8}function Ve(e,t){let r=t?.topN??10,n=e.describe({detail:"standard"}),o=[],s=e._collectObserveTargets;typeof s=="function"&&s.call(e,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(n.nodes)){let c=i.get(p),g=c instanceof L?c:null,b=g?He(g.cache):0,v=g?g._sinkCount:0,w=f.deps?.length??0,m=f.type==="effect"&&v===0,y=v===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:b,subscriberCount:v,depCount:w,isOrphanEffect:m,orphanKind:y})}let l=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((c,g)=>g[p]-c[p])).slice(0,r),d=a.filter(p=>p.orphanKind!=null),h=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:l,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:d,orphanEffects:h}}function Re(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e>=1552&&e<=1562||e>=1611&&e<=1631||e>=1648&&e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2304&&e<=2307||e>=2362&&e<=2383||e>=2385&&e<=2391||e>=2402&&e<=2403||e>=2433&&e<=2435||e>=2492&&e<=2509||e>=2561&&e<=2563||e>=2620&&e<=2641||e>=2672&&e<=2673||e>=2677&&e===2677||e>=3633&&e===3633||e>=3636&&e<=3642||e>=3655&&e<=3662||e>=3761&&e===3761||e>=3764&&e<=3772||e>=3784&&e<=3790||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65024&&e<=65039||e>=65056&&e<=65071||e===8205?0:e>=4352&&e<=4447||e>=8986&&e<=8987||e>=9001&&e<=9002||e>=9193&&e<=9203||e>=9208&&e<=9210||e>=9725&&e<=9726||e>=9748&&e<=9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e>=9898&&e<=9899||e>=9917&&e<=9918||e>=9924&&e<=9925||e===9934||e===9940||e===9962||e>=9970&&e<=9971||e===9973||e===9978||e===9981||e===9986||e===9989||e>=9992&&e<=9997||e===9999||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e>=10548&&e<=10549||e>=11013&&e<=11015||e>=11035&&e<=11036||e===11088||e===11093||e>=11904&&e<=12350||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=40959||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=126980&&e===126980||e===127183||e>=127344&&e<=127345||e===127358||e===127359||e===127374||e>=127377&&e<=127386||e>=127456&&e<=127487||e>=127488&&e<=127490||e===127514||e===127535||e>=127538&&e<=127546||e>=127568&&e<=127569||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=129792&&e<=130047||e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}function ae(e){let t=0;for(let r of e)t+=Re(r.codePointAt(0));return t}function ze(e,t){if(t<=0)return"";let r=0,n="";for(let o of e){let s=Re(o.codePointAt(0));if(r+s>t){if(t<=1)return"\u2026";for(;r+1>t&&n.length>0;){let i=[...n].pop();n=n.slice(0,-i.length),r-=Re(i.codePointAt(0))}return`${n}\u2026`}n+=o,r+=s}return n}var gt={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},mt={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Ue(e,t){let r=t.charset==="ascii"?mt:gt,n=e.width,o=e.height,s=Array.from({length:o},()=>Array.from({length:n},()=>" ")),i=Array.from({length:o},()=>Array.from({length:n},()=>"empty"));for(let a of e.edges)yt(s,i,r,a);for(let a of e.boxes)bt(s,i,r,a,t.labelOf(a.id));return s.map(a=>Ot(a.join(""))).join(`
3
- `)}function bt(e,t,r,n,o){let{x:s,y:i,w:a,h:l}=n;if(a<2||l<2){l>0&&Ke(e,t,s,i,a,o);return}V(e,t,s,i,r.boxTL);for(let d=s+1;d<s+a-1;d+=1)V(e,t,d,i,r.boxH);V(e,t,s+a-1,i,r.boxTR);for(let d=i+1;d<i+l-1;d+=1){V(e,t,s,d,r.boxV);for(let h=s+1;h<s+a-1;h+=1)Je(e,t,h,d," ","empty");V(e,t,s+a-1,d,r.boxV)}V(e,t,s,i+l-1,r.boxBL);for(let d=s+1;d<s+a-1;d+=1)V(e,t,d,i+l-1,r.boxH);V(e,t,s+a-1,i+l-1,r.boxBR);let u=i+Math.floor(l/2);Ke(e,t,s+1,u,a-2,o)}function V(e,t,r,n,o){Je(e,t,r,n,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Je(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];r<0||r>=i.length||(i[r]=o,t[n][r]=s)}function Ke(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=r,a=o;for(let l of s){let u=ae(l);if(u!==0){if(a<u)break;i>=0&&i<e[n].length&&(e[n][i]=l,t[n][i]="label",u===2&&i+1<e[n].length&&(e[n][i+1]="",t[n][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<e[n].length&&(e[n][i]=" ",t[n][i]="empty"),i+=1,a-=1}function yt(e,t,r,n){let o=n.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)vt(e,t,r,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let u=o[l-1],d=o[l],h=o[l+1],p=xt(u,d,h,r);p&&qe(e,t,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=wt(i,s,r);a&&qe(e,t,s.x,s.y,a,"arrow")}function vt(e,t,r,n,o){if(!(n.x===o.x&&n.y===o.y)){if(n.y===o.y){let s=n.y,i=Math.min(n.x,o.x),a=Math.max(n.x,o.x);for(let l=i;l<=a;l+=1)We(e,t,l,s,r,"h")}else if(n.x===o.x){let s=n.x,i=Math.min(n.y,o.y),a=Math.max(n.y,o.y);for(let l=i;l<=a;l+=1)We(e,t,s,l,r,"v")}}}function We(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];if(r<0||r>=i.length)return;let a=t[n][r];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[r]=s==="h"?o.horizontal:o.vertical,t[n][r]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[r]=o.cross,t[n][r]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[r]=o.cross,t[n][r]="edgeCorner";return}}}function qe(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];if(r<0||r>=i.length)return;let a=t[n][r];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[r]=o,t[n][r]=s)}function xt(e,t,r,n){let o=e.y===t.y,s=t.y===r.y;if(o===s)return;if(o){let l=e.x<t.x,u=r.y>t.y;return l&&u?n.cornerTR:l&&!u?n.cornerBR:!l&&u?n.cornerTL:n.cornerBL}let i=e.y<t.y,a=r.x>t.x;return i&&a?n.cornerBL:i&&!a?n.cornerBR:!i&&a?n.cornerTL:n.cornerTR}function wt(e,t,r){if(t.x>e.x)return r.arrowRight;if(t.x<e.x)return r.arrowLeft;if(t.y>e.y)return r.arrowDown;if(t.y<e.y)return r.arrowUp}function Ot(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===32;)t-=1;return e.slice(0,t)}function Qe(e){let t=Et(e);_t(t),St(t),Rt(t),Dt(t,e);let r=kt(t,e),{width:n,height:o}=Tt(t),s=[];for(let i of t.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:r,width:n,height:o}}function Et(e){let t=new Map;for(let o of e.nodes)t.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:e.widthCells(o),h:e.heightCells(o),in:[],out:[]});let r=[],n=0;for(let o of e.edges){if(o.from===o.to)continue;let s=t.get(o.from),i=t.get(o.to);if(!s||!i)continue;let a={chainId:n++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),r.push(a)}return{nodes:t,layers:[],hops:r}}function _t(e){let t=new Map;for(let s of e.nodes.values())t.set(s.id,s.in.length);let r=[];for(let s of e.nodes.values())(t.get(s.id)??0)===0&&(s.layer=0,r.push(s));let n=new Set,o=0;for(;o<r.length;){let s=r[o++];if(!n.has(s.id)){n.add(s.id);for(let i of s.out){let a=e.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(t.get(a.id)??0)-1;t.set(a.id,l),l<=0&&r.push(a)}}}for(let s of e.nodes.values())s.layer<0&&(s.layer=0)}function St(e){let t=Math.max(0,...Array.from(e.nodes.values(),s=>s.layer)),r=Array.from({length:t+1},()=>[]);for(let s of e.nodes.values())r[s.layer].push(s);let n=[],o=0;for(let s of e.hops){let i=e.nodes.get(s.fromId),a=e.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,n.push(s);continue}i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);let u=i;for(let h=1;h<l;h+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};e.nodes.set(p,f),r[f.layer].push(f);let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:h-1,chainLen:l};u.out.push(c),f.in.push(c),n.push(c),u=f}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:l-1,chainLen:l};u.out.push(d),a.in.push(d),n.push(d)}for(let s of r)for(let i=0;i<s.length;i+=1)s[i].order=i;e.layers=r,e.hops=n}function Rt(e){for(let r=0;r<4;r+=1){for(let n=1;n<e.layers.length;n+=1)Ye(e,e.layers[n],"in"),ue(e.layers[n]);for(let n=e.layers.length-2;n>=0;n-=1)Ye(e,e.layers[n],"out"),ue(e.layers[n])}for(let r=0;r<2;r+=1){let n=!1;for(let o=1;o<e.layers.length;o+=1){let s=e.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Xe(e,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],ue(s),Xe(e,s[i],s[i+1],"in")<a?n=!0:([s[i],s[i+1]]=[s[i+1],s[i]],ue(s))}}if(!n)break}}function Ye(e,t,r){let n=new Map;for(let o of t){let s=r==="in"?o.in:o.out;if(s.length===0){n.set(o.id,o.order);continue}let i=0,a=0;for(let l of s){let u=e.nodes.get(r==="in"?l.fromId:l.toId);u&&(i+=u.order,a+=1)}n.set(o.id,a===0?o.order:i/a)}t.sort((o,s)=>{let i=n.get(o.id),a=n.get(s.id);return i!==a?i-a:o.order-s.order})}function ue(e){for(let t=0;t<e.length;t+=1)e[t].order=t}function Xe(e,t,r,n){let o=n==="in"?t.in:t.out,s=n==="in"?r.in:r.out,i=0;for(let a of o)for(let l of s){let u=e.nodes.get(n==="in"?a.fromId:a.toId)?.order??0,d=e.nodes.get(n==="in"?l.fromId:l.toId)?.order??0;(t.order<r.order&&u>d||t.order>r.order&&u<d)&&(i+=1)}return i}function Dt(e,t){t.direction==="LR"?Gt(e,t):Ct(e,t)}function Gt(e,t){let r=[],n=0;for(let o=0;o<e.layers.length;o+=1){r.push(n);let s=0;for(let i of e.layers[o])s=Math.max(s,i.w);n+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.x=r[o];for(let o of e.layers){let s=0;for(let i of o)i.y=s,s+=i.h+t.nodeGap}Ze(e,t,"y")}function Ct(e,t){let r=[],n=0;for(let o=0;o<e.layers.length;o+=1){r.push(n);let s=0;for(let i of e.layers[o])s=Math.max(s,i.h);n+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.y=r[o];for(let o of e.layers){let s=0;for(let i of o)i.x=s,s+=i.w+t.nodeGap}Ze(e,t,"x")}function Ze(e,t,r){let n=s=>r==="y"?s.h:s.w,o=t.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?e.layers.slice(1):e.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let h=s===0?d.in:d.out;if(h.length===0)continue;let p=[];for(let c of h){let g=e.nodes.get(s===0?c.fromId:c.toId);if(!g)continue;let b=r==="y"?g.y:g.x;p.push(b+Math.floor(n(g)/2))}if(p.length===0)continue;p.sort((c,g)=>c-g);let f=p[Math.floor(p.length/2)];l.set(d.id,f-Math.floor(n(d)/2))}let u=0;for(let d of a){let h=l.get(d.id),p=r==="y"?d.y:d.x,c=Math.max(h??p,u);r==="y"?d.y=c:d.x=c,u=c+n(d)+o}}}}function kt(e,t){let r=new Map;for(let u of e.hops){let d=r.get(u.chainId);d?d.push(u):r.set(u.chainId,[u])}for(let u of r.values())u.sort((d,h)=>d.hopIndex-h.hopIndex);let n=t.direction==="LR",o=u=>n?u.x:u.y,s=u=>n?u.w:u.h,i=u=>n?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<e.layers.length;u+=1){let d=e.layers[u],h=e.layers[u+1],p=0;for(let _ of d)p=Math.max(p,o(_)+s(_));let f=Number.POSITIVE_INFINITY;for(let _ of h)f=Math.min(f,o(_));let c=Number.isFinite(f)?f-1:p,g=Math.max(1,c-p+1),b=[];for(let _ of d)for(let R of _.out)b.push(R);b.sort((_,R)=>{let k=i(e.nodes.get(_.fromId)),$=i(e.nodes.get(R.fromId));if(k!==$)return k-$;let G=i(e.nodes.get(_.toId)),D=i(e.nodes.get(R.toId));return G-D});let v=[],w=new Map;for(let _ of b){let R=i(e.nodes.get(_.fromId)),k=i(e.nodes.get(_.toId)),$=Math.min(R,k),G=Math.max(R,k),D=-1;for(let P=0;P<v.length;P+=1){let F=v[P],H=!0;for(let U of F)if(U.lo<=G&&$<=U.hi){H=!1;break}if(H){F.push({lo:$,hi:G}),D=P;break}}D<0&&(v.push([{lo:$,hi:G}]),D=v.length-1),w.set(_,D)}let m=v.length,y=g>=Math.max(3,m+2),S=y?p+1:p,x=y?c-1:c,O=Math.max(1,x-S+1);for(let _ of b){let R=w.get(_),k;if(m<=1)k=S+Math.floor(O/2);else{let $=(O-1)/(m-1);k=S+Math.floor(R*$)}a.set(_,Math.max(p,Math.min(c,k)))}}let l=[];for(let[,u]of r){let d=[];for(let p=0;p<u.length;p+=1){let f=u[p],c=e.nodes.get(f.fromId),g=e.nodes.get(f.toId),b=a.get(f),v=c.isVirtual?o(c):o(c)+s(c),w=g.isVirtual?o(g):o(g)-1,m=i(c),y=i(g);p===0&&le(d,n,v,m),m!==y&&(le(d,n,b,m),le(d,n,b,y)),le(d,n,w,y)}let h=u[0];l.push({from:h.chainFrom,to:h.chainTo,points:$t(d)})}return l}function le(e,t,r,n){e.push(t?{x:r,y:n}:{x:n,y:r})}function $t(e){let t=[];for(let r of e){let n=t[t.length-1];(!n||n.x!==r.x||n.y!==r.y)&&t.push(r)}return t}function Tt(e){let t=0,r=0;for(let n of e.layers)for(let o of n)t=Math.max(t,o.x+o.w),r=Math.max(r,o.y+o.h);return{width:t,height:r}}var Nt=24,At=4,Pt=1,Mt=3;function et(e,t){let r=Lt(t.direction),n=Math.max(3,t.maxLabelWidth??Nt),o=t.asciiCharset??"unicode",s=Object.keys(e.nodes).sort(),i=new Set(s),a=e.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,u=new Map;for(let f of s){let c=ze(f,n);l.set(f,c),u.set(f,ae(c)+4)}let d=Qe({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>Mt,layerGap:At,nodeGap:Pt,direction:r}),h=Ue(d,{charset:o,labelOf:f=>l.get(f)??f}),p=t.logger;return p&&p(h),h}function Lt(e){if(e===void 0||e==="LR")return"LR";if(e==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(e)}`)}var N="::",B="__meta__",q=1;function tt(e,t){let r=Math.max(16,e.size*4),n=0;for(;e.size>0;){if(n++>=r){console.error(`[Graph "${t}".destroy] disposer drain exceeded cap (${r}); ${e.size} disposer(s) discarded`),e.clear();return}let o=e.values().next();if(o.done)return;let s=o.value;e.delete(s);try{s()}catch(i){console.error(`[Graph "${t}".destroy] disposer threw:`,i)}}}function It(e){let t=[];for(let r of Object.keys(e).sort()){let n=e[r].v;n!=null&&t.push(`${r} ${n.id} ${n.version}`)}return t.join(`
4
- `)}function nt(e){if(e.version!==q)throw new Error(`unsupported snapshot version ${String(e.version)} (expected ${q})`);for(let t of["name","nodes","edges","subgraphs"])if(!(t in e))throw new Error(`snapshot missing required key "${t}"`);if(typeof e.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof e.nodes!="object"||e.nodes===null||Array.isArray(e.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(e.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(e.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function jt(e,t){let r=new WeakMap,n=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=r.get(o);if(i==null&&(i=new WeakSet,r.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,l=s.constructor;if(a!==l)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!n(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,c]of o)if(!p.has(f)||!n(c,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let c=!1;for(let g of p)if(n(f,g)){c=!0;break}if(!c)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let c=0;c<p.length;c++)if(p[c]!==f[c])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let h=new Set(d);for(let p of u)if(!h.has(p)||!n(o[p],s[p]))return!1;return!0};return n(e,t)}function Ge(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ge);let t=e,r=Object.keys(t).sort(),n={};for(let o of r)n[o]=Ge(t[o]);return n}function Bt(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ft(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ht(e){return e==="TD"?"down":e==="BT"?"up":e==="RL"?"left":"right"}function ot(e){let t=new Set,r=[];function n(o,s){let i=`${o}\0${s}`;t.has(i)||(t.add(i),r.push([o,s]))}for(let[o,s]of Object.entries(e.nodes)){let i=s.deps;if(i)for(let a of i)n(a,o)}for(let o of e.edges)n(o.from,o.to);return r}function it(e){if(e===void 0)return"LR";if(e==="TD"||e==="LR"||e==="BT"||e==="RL")return e;throw new Error(`invalid diagram direction ${String(e)}; expected one of: TD, LR, BT, RL`)}function Vt(e,t){let r=t.includeEdges??!0,n=t.includeSubgraphs??!0,{expand:o,...s}=e,i={...s,edges:r?e.edges:[],subgraphs:n?e.subgraphs:[]},a=JSON.stringify(Ge(i),null,t.indent??2);return t.logger?.(a),a}function zt(e,t){let r=t.includeEdges??!0,n=t.includeSubgraphs??!0,o=[];o.push(`Graph ${e.name}`),o.push("Nodes:");for(let i of Object.keys(e.nodes).sort()){let a=e.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${de(a.value)}`)}if(r){o.push("Edges:");for(let i of e.edges)o.push(`- ${i.from} -> ${i.to}`)}if(n){o.push("Subgraphs:");for(let i of e.subgraphs)o.push(`- ${i}`)}let s=o.join(`
5
- `);return t.logger?.(s),s}function at(e,t){let r=it(t.direction),n=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<n.length;i+=1)o.set(n[i],`n${i}`);let s=[`flowchart ${r}`];for(let i of n){let a=o.get(i);s.push(` ${a}["${Bt(i)}"]`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(` ${l} --> ${u}`)}return s.join(`
6
- `)}function Kt(e,t){let r=at(e,t);return Wt(r)}function Wt(e,t){let r=t?.theme??"default",n=t?.autoSync??!0,s=JSON.stringify({code:e,mermaid:{theme:r},autoSync:n}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function qt(e,t){let r=it(t.direction),n=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<n.length;i+=1)o.set(n[i],`n${i}`);let s=[`direction: ${Ht(r)}`];for(let i of n){let a=o.get(i);s.push(`${a}: "${Ft(i)}"`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(`${l} -> ${u}`)}return s.join(`
7
- `)}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ce(e){let t="^";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="*"){t+=".*";continue}if(n==="?"){t+=".";continue}if(n==="["){let o=e.indexOf("]",r+1);if(o<=r+1){t+="\\[";continue}let s=e.slice(r+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),t+=`[${s}]`,r=o;continue}t+=Ut(n)}return t+="$",new RegExp(t)}var Jt={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Yt={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function de(e){if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Xt(e){return e==="none"?Yt:e==="ansi"||e==null?Jt:{data:e.data??"",dirty:e.dirty??"",resolved:e.resolved??"",invalidate:e.invalidate??"",pause:e.pause??"",resume:e.resume??"",complete:e.complete??"",error:e.error??"",teardown:e.teardown??"",derived:e.derived??"",path:e.path??"",reset:e.reset??""}}function rt(e){if(e==null)return{};let t=e.detail;return t==="full"?{...e,structured:e.structured??!0,timeline:e.timeline??!0,causal:e.causal??!0,derived:e.derived??!0}:t==="minimal"?{...e,structured:e.structured??!0}:e.format==="stage-log"?{...e,structured:e.structured??!0,timeline:e.timeline??!0}:e}function Qt(e,t,r){for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o<32||o===127)throw new Error(`Graph "${t}": ${r} "${e}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function De(e,t,r){if(e==="")throw new Error(`Graph "${t}": ${r} name must be non-empty`);if(e.includes(N))throw new Error(`Graph "${t}": ${r} "${e}" must not contain '${N}' (path separator)`);if(e===B)throw new Error(`Graph "${t}": ${r} name "${B}" is reserved for meta companion paths`);Qt(e,t,r)}function Zt(e,t){if(e==="")throw new Error(`Graph "${t}": resolve path must be non-empty`);let r=e.split(N);for(let n of r)if(n==="")throw new Error(`Graph "${t}": resolve path has empty segment`);return r}function en(e,t){let r=!1;for(let o of e)if(!t.isMetaPassthrough(o[0])){r=!0;break}return r?e.filter(o=>t.isMetaPassthrough(o[0])):e}function ut(e){for(let t of e._mounts.values())ut(t);for(let t of e._nodes.values())try{t.down([[z]],{internal:!0})}catch{}}var Ce=class e{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(t,r){if(t==="")throw new Error("Graph name must be non-empty");if(t.includes(N))throw new Error(`Graph name must not contain '${N}' (got "${t}")`);if(t===B)throw new Error(`Graph name "${B}" is reserved for meta companion paths`);this.name=t,this.opts=Object.freeze({...r??{}}),this.config=r?.config??we,this._traceRing=new Se(r?.traceCapacity??1e3),r?.versioning!=null&&this.setVersioning(r.versioning)}ancestors(t=!0){let r=[],n=t?this:this._parent;for(;n!=null;)r.push(n),n=n._parent;return r}get topology(){return this._topology==null&&(this._topology=Me(t=>{let r=n=>{t.emit(n)};return this._topologyEmitters.add(r),()=>{this._topologyEmitters.delete(r)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(t){if(!(this._topology==null||this._topologyEmitters.size===0))for(let r of this._topologyEmitters)r(t)}add(t,r){let n=t.name,o=r?.name??n;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=r?.annotation;if(De(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(t);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,t),this._nodeToName.set(t,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:K()})),t}setVersioning(t){if(t!=null)for(let r of this._nodes.values())r instanceof L&&r._applyVersioning(t)}remove(t){De(t,this.name,"remove");let r=this._mounts.get(t);if(r){let s={kind:"mount",nodes:[],mounts:[]},i=[];r._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${N}${B}${N}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(t),s.mounts.push(...r._collectSubgraphs(`${t}${N}`)),this._mounts.delete(t),r._parent=void 0,ut(r),this._emitTopology({kind:"removed",name:t,nodeKind:"mount",audit:s}),s}let n=this._nodes.get(t);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${t}"`);this._nodes.delete(t),this._nodeToName.delete(n),n.down([[z]],{internal:!0});let o={kind:"node",nodes:[t],mounts:[]};return this._emitTopology({kind:"removed",name:t,nodeKind:"node",audit:o}),o}removeAll(t){let r=typeof t=="function"?t:(()=>{let s=ce(t);return i=>s.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>r(s));for(let s of o){let i=this.remove(s);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let t=[...this._nodes.keys()].sort(),r=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=t.length)return{value:void 0,done:!0};let o=t[n++];return{value:[o,r.get(o)],done:!1}}}}node(t){if(t==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(t.includes(N))return this.resolve(t);let r=this._nodes.get(t);if(!r)throw new Error(`Graph "${this.name}": unknown node "${t}"`);return r}get(t){return this.node(t).cache}set(t,r,n){let o=n?.internal===!0;this.node(t).down([[Q,r]],{actor:n?.actor,internal:o,delivery:"write"})}setAll(t,r){let n=Symbol.iterator in t?t:Object.entries(t);Ae(()=>{for(let[o,s]of n)this.set(o,s,r)})}invalidate(t,r){let n=r?.internal===!0;this.node(t).down([[Z]],{actor:r?.actor,internal:n,delivery:"write"})}error(t,r,n){let o=n?.internal===!0;this.node(t).down([[te,r]],{actor:n?.actor,internal:o,delivery:"write"})}complete(t,r){let n=r?.internal===!0;this.node(t).down([[ee]],{actor:r?.actor,internal:n,delivery:"write"})}edges(t){let r=t?.recursive===!0,n=new Map;if(!r){for(let[l,u]of this._nodes)n.set(u,l);let a=[];for(let[l,u]of this._nodes)if(u instanceof L)for(let d of u._deps){let h=n.get(d.node);h!=null&&a.push([h,l])}return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:l[1]<u[1]?-1:l[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,l]of o)s.set(l,a);let i=[];for(let[a,l]of o)if(l instanceof L)for(let u of l._deps){let d=s.get(u.node);d!=null&&i.push([d,a])}return i.sort((a,l)=>a[0]<l[0]?-1:a[0]>l[0]?1:a[1]<l[1]?-1:a[1]>l[1]?1:0),i}mount(t,r){if(De(t,this.name,"mount"),this._nodes.has(t))throw new Error(`Graph "${this.name}": cannot mount at "${t}" \u2014 node with that name exists`);if(this._mounts.has(t))throw new Error(`Graph "${this.name}": mount "${t}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let n=this;n!=null;n=n._parent)if(n===r)throw new Error(`Graph "${this.name}": mount("${t}", \u2026) would create a mount cycle`);return this._mounts.set(t,r),r._parent=this,this._emitTopology({kind:"added",name:t,nodeKind:"mount"}),r}resolve(t){let r=Zt(t,this.name);return this._resolveFromSegments(r)}tryResolve(t){try{return this.resolve(t)}catch{return}}_resolveFromSegments(t){let r=t;if(r[0]===this.name&&(r=r.slice(1),r.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=r[0],o=r.slice(1);if(o.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let s=this._nodes.get(n);if(s&&o.length>0&&o[0]===B)return this._resolveMetaChainFromNode(s,o,r.join(N));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${o.join(N)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(o.join(N))}_resolveMetaChainFromNode(t,r,n){let o=t,s=0,i=[...r];for(;s<i.length;){if(i[s]!==B)throw new Error(`Graph "${this.name}": expected ${B} segment in meta path "${n}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${B} in "${n}"`);let a=i[s+1],l=o.meta[a];if(!l)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);o=l,s+=2}return o}signal(t,r){if(r?.internal!==!0){for(let o of t)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(t,r??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(t,r,n,o){for(let l of this._mounts.values())l._signalDeliver(t,r,n,o);let i=r.internal===!0?{internal:!0}:{actor:r.actor,delivery:"signal"},a=en(t,this.config);for(let l of[...this._nodes.keys()].sort()){let u=this._nodes.get(l);if(!n.has(u)){n.add(u);try{u.down(t,i)}catch(d){if(d instanceof W)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,o)}}}_signalMetaSubtree(t,r,n,o,s){for(let i of Object.keys(t.meta).sort()){let a=t.meta[i];if(!n.has(a)){n.add(a);try{a.down(r,o)}catch(l){if(l instanceof W)throw l;s.push(l)}this._signalMetaSubtree(a,r,n,o,s)}}}describe(t){if(t?.reactive===!0)return this._describeReactive(t);let r=t?.actor,n=t?.filter,o=re(t?.detail,t?.fields),s=t?.format==="spec",i=s?re("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[x,O]of a)l.set(O,x);let u=[];{let x=a.map(([,R])=>R),O=new Set(l.values()),_=0;for(;x.length>0;){let R=x.shift();if(R instanceof L)for(let k of R._deps){let $=k.node;if(l.has($))continue;let G=$.name??"",D=G;if(!D||O.has(D))if(G){let P=2;for(;O.has(`${G}#${P}`);)P++;D=`${G}#${P}`}else for(D=`__internal__/${_++}`;O.has(D);)D=`__internal__/${_++}`;l.set($,D),O.add(D),u.push([D,$]),x.push($)}}}let d=[...a,...u],h={};for(let[x,O]of d){if(r!=null&&!O.allowsObserve(r))continue;let _=_e(O,i),R=O instanceof L?O._deps.map(D=>l.get(D.node)??D.node.name??""):[],{name:k,...$}=_,G={...$,deps:R};if(!s){let D=this._annotations.get(x);D!=null&&(G.annotation=D)}if(n!=null)if(typeof n=="function"){let D=n;if(!(D.length>=2?D(x,G):D(G)))continue}else{let D=!0;for(let[P,F]of Object.entries(n)){let H=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(H==="depsIncludes"){if(!G.deps.includes(String(F))){D=!1;break}continue}if(H==="metaHas"){if(!Object.hasOwn(G.meta??{},String(F))){D=!1;break}continue}if(G[H]!==F){D=!1;break}}if(!D)continue}h[x]=G}let p=new Set(Object.keys(h)),f=[];for(let[x,O]of d)if(O instanceof L)for(let _ of O._deps){let R=l.get(_.node);R!=null&&f.push([R,x])}f.sort((x,O)=>x[0]<O[0]?-1:x[0]>O[0]?1:x[1]<O[1]?-1:x[1]>O[1]?1:0);let c=f.map(([x,O])=>({from:x,to:O}));(r!=null||n!=null)&&(c=c.filter(x=>p.has(x.from)&&p.has(x.to)));let g=this._collectSubgraphs(""),b=r!=null||n!=null?g.filter(x=>{let O=`${x}${N}`;return[...p].some(_=>_===x||_.startsWith(O))}):g,v=this,w=t,m={name:this.name,nodes:h,edges:c,subgraphs:b,expand(x){let O={...w,format:void 0};return Array.isArray(x)?(O.fields=x,O.detail=void 0):(O.detail=x,O.fields=void 0),v.describe(O)}},y=t??{},S=y.format;return S==="json"?Vt(m,y):S==="pretty"?zt(m,y):S==="mermaid"?at(m,y):S==="mermaid-url"?Kt(m,y):S==="d2"?qt(m,y):S==="ascii"?et(m,y):m}_collectSubgraphs(t){let r=[];for(let n of[...this._mounts.keys()].sort()){let o=t===""?n:`${t}${n}`;r.push(o),r.push(...this._mounts.get(n)._collectSubgraphs(`${o}${N}`))}return r}resourceProfile(t){return Ve(this,t)}reachable(t,r,n={}){return n.withDetail===!0?st(this.describe(),t,r,{...n,withDetail:!0}):st(this.describe(),t,r,n)}explain(t,r,n){return n?.reactive===!0?this._explainReactive(t,r,n):this._explainStatic(t,r,n)}_explainStatic(t,r,n){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,l]of Object.entries(o.nodes))l.lastMutation!=null&&i.set(a,l.lastMutation);return Ie(o,t,r,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(t){let r={...t,reactive:!1},n=t.reactiveName??"describe",o=0,s=ne(o,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=()=>{a||l||(a=!0,xe(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),h=[],p=new WeakSet,f=b=>{if(p.has(b)||l)return;p.add(b);let v=b.topology.subscribe(w=>{for(let m of w){if(m[0]!==Q)continue;let y=m[1];if(u(),y.kind==="added"&&y.nodeKind==="mount"){let S=b._mounts.get(y.name);S!=null&&f(S)}}});h.push(v);for(let w of b._mounts.keys()){let m=b._mounts.get(w);m!=null&&f(m)}};f(this);let c;try{c=Oe([s],()=>this.describe(r),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){d();for(let v of h)v();throw i.dispose(),b}let g=Ee(c);return{node:c,dispose(){l=!0,d();for(let b of h)b();h.length=0,i.dispose(),g()}}}_explainReactive(t,r,n){let o=0,s=ne(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=i.onEvent(f=>{let c=f.type;c!=="data"&&c!=="error"&&c!=="complete"&&c!=="teardown"||a||l||(a=!0,xe(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{}},h;try{h=Oe([s],()=>this._explainStatic(t,r,d),{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:t,to:r},equals:(f,c)=>f.found===c.found&&f.reason===c.reason&&f.steps.length===c.steps.length&&nn(f.steps,c.steps)})}catch(f){throw u(),i.dispose(),f}let p=Ee(h);return{node:h,dispose(){l=!0,u(),i.dispose(),p()}}}_pathsMatching(t){let r=ce(t),n=[];return this._collectObserveTargets("",n),n.map(([o])=>o).filter(o=>r.test(o))}_collectObserveTargets(t,r){for(let n of[...this._mounts.keys()].sort()){let o=t===""?n:`${t}${N}${n}`;this._mounts.get(n)._collectObserveTargets(o,r)}for(let n of[...this._nodes.keys()].sort()){let o=this._nodes.get(n),s=t===""?n:`${t}${N}${n}`;r.push([s,o]),this._appendMetaObserveTargets(s,o,r)}}_appendMetaObserveTargets(t,r,n){for(let o of Object.keys(r.meta).sort()){let s=r.meta[o],i=`${t}${N}${B}${N}${o}`;n.push([i,s]),this._appendMetaObserveTargets(i,s,n)}}observe(t,r){let n=typeof t=="string",s=rt(n?r:t),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(n){let d=t,h=this.resolve(d);if(a!=null&&!h.allowsObserve(a))throw new W({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,h]],s,"one"):{subscribe(p){return h.subscribe(p)},up(p){try{h.up?.(p)}catch(f){if(f instanceof W)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let u=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let h=u.map(([p,f])=>f.subscribe(c=>{d(p,c)}));return()=>{for(let p of h)p()}},up:(d,h)=>{try{this.resolve(d).up?.(h)}catch(p){if(p instanceof W)return;throw p}}}}_buildStructuredObserver(t,r,n){let o=n==="one"?t[0]?.[0]:void 0,s=i=>{if(n==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let l=i.actor,u=l==null?a:a.filter(([,d])=>d.allowsObserve(l));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(t,r,s)}_createObserveResult(t,r,n){let o=r.timeline===!0,s=r.causal===!0,i=r.derived===!0,a=r.detail==="minimal",l=this.config.inspectorEnabled,u=(s||i)&&l,d=r.maxEvents,h=d!=null&&d>0?new Se(d):null,p=[],f=new Set,c={},g=new Set,b=0,v=0,w=0,m=0,y=0,S=0,x=!1,O=!1,_=0,R=new Map,k=new Map,$=new Map,G=E=>{h?h.push(E):p.push(E);for(let T of f)T(E)},D=()=>o?{timestamp_ns:K(),in_batch:Ne(),batch_id:_}:{},P=(E,T)=>{if(!(!u||!(E instanceof L)))return E._setInspectorHook(I=>{if(I.kind==="dep_message")R.set(E,I.depIndex);else if(I.kind==="run"){let J=I.batchData.map((C,M)=>C!=null&&C.length>0?C.at(-1):I.prevData[M]);k.set(E,J);let j=I.batchData.map(C=>C!=null?[...C]:void 0);$.set(E,j),i&&G({type:"derived",path:T,dep_values:J,dep_batches:j,...D()})}})},F=E=>{let T=R.get(E),I=k.get(E);if(!s||I==null)return{};let j=(T!=null&&T>=0&&E instanceof L?E._deps[T]:void 0)?.node,C=j?.v,M=$.get(E);return{trigger_dep_index:T,trigger_dep_name:j?.name,...C!=null?{trigger_version:{id:C.id,version:C.version}}:{},dep_values:[...I],...M!=null?{dep_batches:M}:{}}},H=[],U=[];for(let[E,T]of t){let I=P(T,E);I&&H.push(I),U.push(T.subscribe(J=>{_++;for(let j of J){let C=j[0],M=D();if(C===Q){c[E]=j[1];let ge=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"data",path:E,data:j[1],actor:ge,...M,...F(T)})}else if(a)C===me?b++:C===be?v++:C===Z?w++:C===ye?m++:C===ve?y++:C===z?S++:C===ee&&!g.has(E)?x=!0:C===te&&(O=!0,g.add(E));else if(C===me)b++,G({type:"dirty",path:E,...M});else if(C===be)v++,G({type:"resolved",path:E,...M,...F(T)});else if(C===Z)w++,G({type:"invalidate",path:E,...M});else if(C===ye)m++,G({type:"pause",path:E,lockId:j[1],...M});else if(C===ve)y++,G({type:"resume",path:E,lockId:j[1],...M});else if(C===ee)g.has(E)||(x=!0),G({type:"complete",path:E,...M});else if(C===te){O=!0,g.add(E);let ge=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"error",path:E,data:j[1],actor:ge,...M})}else C===z&&(S++,G({type:"teardown",path:E,...M}))}}))}let fe=!1,pe=()=>{if(!fe){fe=!0;for(let E of U)E();for(let E of H)E();for(let E of X)E({value:void 0,done:!0});X.length=0}},he=[],X=[];f.add(E=>{let T=X.shift();T?T({value:E,done:!1}):he.push(E)});let ke={get values(){return c},get dirtyCount(){return b},get resolvedCount(){return v},get invalidateCount(){return w},get pauseCount(){return m},get resumeCount(){return y},get teardownCount(){return S},get events(){return h?h.toArray():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return O},get completedWithoutErrors(){return x&&!O},onEvent(E){return f.add(E),()=>f.delete(E)},dispose:pe,expand(E){pe();let T={...r};return typeof E=="string"?T.detail=E:Object.assign(T,E),n(rt(T))},[Symbol.asyncIterator](){return{next(){return he.length>0?Promise.resolve({value:he.shift(),done:!1}):fe?Promise.resolve({value:void 0,done:!0}):new Promise(E=>X.push(E))},return(){return pe(),Promise.resolve({value:void 0,done:!0})}}}};return r.format!=null&&this._attachFormatLogger(ke,r),ke}_attachFormatLogger(t,r){let n=r.format;if(n==null)return;let o=r.logger??(c=>console.log(c)),s=r.includeTypes?new Set(r.includeTypes):null,i=r.excludeTypes?new Set(r.excludeTypes):null,a=s==null&&i==null?()=>!0:c=>(s==null||s.has(c))&&(i==null||!i.has(c)),l=Xt(r.theme),u=n==="stage-log"?K():0,d=c=>c==null?"":r.stageLabels?.[c]??c,h=(c,g)=>c.length>g?`${c.slice(0,g-1)}\u2026`:c,p=c=>c.type==="data"||c.type==="error"?h(de(c.data),120):"",f=c=>{if(n==="stage-log"){let O=(K()-u)/1e9,_=d(c.path).padEnd(9);if(c.type==="data"){let R=p(c);return`[${O.toFixed(3)}s] ${_} \u2190${R?` ${R}`:""}`}if(c.type==="error"){let R=p(c);return`[${O.toFixed(3)}s] ${_} \u2717${R?` ${R}`:""}`}return c.type==="complete"?`[${O.toFixed(3)}s] ${_} \u25A0 complete`:`[${O.toFixed(3)}s] ${_} ${c.type}`}if(n==="json")try{return JSON.stringify(c)}catch{return JSON.stringify({type:c.type,path:c.path,data:"[unserializable]"})}let g=l[c.type]??"",b=c.path?`${l.path}${c.path}${l.reset} `:"",v=c.type==="data"||c.type==="error",w=c.type==="pause"||c.type==="resume",m=v?` ${de(c.data)}`:w?` ${de(c.lockId)}`:"",y=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,S=y?.trigger_dep_name!=null?` <- ${y.trigger_dep_name}`:y?.trigger_dep_index!=null?` <- #${y.trigger_dep_index}`:"",x=c.in_batch?" [batch]":"";return`${b}${g}${c.type.toUpperCase()}${l.reset}${m}${S}${x}`};t.onEvent(c=>{a(c.type)&&o(f(c),c)})}addDisposer(t){return this._disposers.add(t),()=>{this._disposers.delete(t)}}destroy(){tt(this._disposers,this.name),this.signal([[z]],{internal:!0}),tt(this._storageDisposers,this.name);for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(t){let{expand:r,...n}=this.describe({detail:"full"}),o={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:l,guard:u,...d}=n.nodes[a];o[a]=d}let s=[...n.subgraphs].sort(),i={...n,version:1,nodes:o,subgraphs:s};if(t?.format==null)return i;if(t.format==="json-string")return JSON.stringify(i);if(t.format==="bytes"){if(t.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(t.codec);if(a==null)throw new Error(`snapshot: codec "${t.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return $e(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(t.format)}"`)}static decode(t,r){let n=r?.config??we,{codec:o,codecVersion:s,payload:i}=Te(t,n);return o.decode(i,s)}restore(t,r){if(nt(t),t.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${t.name}" does not match this graph`);let n=r?.only==null?null:(Array.isArray(r.only)?r.only:[r.only]).map(s=>ce(s)),o=r?.includeProducers===!0;for(let s of Object.keys(t.nodes).sort()){if(n!==null&&!n.some(a=>a.test(s)))continue;let i=t.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&r?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let l=this.tryResolve(s)?.v;if(l!=null&&l.id===i.v.id&&l.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){r?.onError?.(s,a)}}}}}static fromSnapshot(t,r){nt(t);let n=typeof r=="function"?r:r?.build,o=typeof r=="function"?void 0:r?.factories,s=new e(t.name);if(n)return n(s),s.restore(t),s;for(let f of[...t.subgraphs].sort((c,g)=>{let b=c.split(N).length,v=g.split(N).length;return b!==v?b-v:c<g?-1:c>g?1:0})){let c=f.split(N),g=s;for(let b of c)g._mounts.has(b)||g.mount(b,new e(b)),g=g._mounts.get(b)}let i=o?Object.entries(o).map(([f,c])=>({re:ce(f),factory:c})):[],a=f=>{for(let c of i)if(c.re.test(f))return c.factory},l=f=>{let c=f.split(N),g=c.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let b=s;for(let v of c){let w=b._mounts.get(v);if(!w)throw new Error(`unknown mount "${v}" in path "${f}"`);b=w}return[b,g]},u=Object.entries(t.nodes).filter(([f])=>!f.includes(`${N}${B}${N}`)).sort((f,c)=>f[0]<c[0]?-1:f[0]>c[0]?1:0),d=new Map(u),h=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,c]of[...d.entries()]){let g=c?.deps??[];if(!g.every(S=>h.has(S)))continue;let[b,v]=l(f),w={...c?.meta??{}},m=a(f),y;if(c?.type==="state")y=ne(c.value,{meta:w});else{if(m==null)continue;y=m(v,{path:f,type:c.type,value:c.value,meta:w,deps:g,resolvedDeps:g.map(S=>h.get(S))})}b.add(y,{name:v}),h.set(f,y),d.delete(f),p=!0}}if(d.size>0){let f=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(t),s}toJSON(){return this.snapshot()}attachStorage(t,r={}){let n=t.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));r.autoRestore===!0&&this._cascadeRestore(t,r.onError);let o=(u,d)=>{if(u.disposed)return;let h=It(d.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let p=u.seq+1,f=Pe(),b=u.lastSnapshot==null||p%u.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:q}:{mode:"diff",diff:tn(u.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:q};if(u.tier.filter&&!u.tier.filter(this.name,b))return;let v;try{v=u.tier.save(this.name,b)}catch(w){r.onError?.(w,u.tier);return}if(v&&typeof v.then=="function"){let y=(u.savePending??Promise.resolve()).then(()=>v,()=>v).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h)},S=>{r.onError?.(S,u.tier)});u.savePending=y.finally(()=>{u.savePending===y&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h},s=(u,d)=>{try{o(u,d)}catch(h){r.onError?.(h,u.tier)}},i=(u,d)=>{if(!d.some(c=>{let g=this.config.messageTier(c[0]);return g>=3&&g<5}))return;if(r.filter){let c=this.tryResolve(u);if(c==null)return;let g=_e(c,re("standard"));if(!r.filter(u,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let c of n)c.disposed||(c.debounceMs===0?s(c,f()):(c.timer==null&&(c.timer=new Le),c.timer.start(c.debounceMs,()=>{c.disposed||s(c,this.snapshot())})))},a;if(r.paths!=null){let d=(typeof r.paths=="string"?this._pathsMatching(r.paths):r.paths).map(h=>{let p=this.tryResolve(h);return p==null?()=>{}:p.subscribe(f=>i(h,f))});a=()=>{for(let h of d)h()}}else a=this.observe().subscribe((u,d)=>i(u,d));let l=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(l)};return this._storageDisposers.add(l),{dispose:l}}async _cascadeRestore(t,r){for(let n of t){let o;try{o=await n.load(this.name)}catch(i){r?.(i,n);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===q&&s.nodes!=null)return this.restore(s),!0}catch(i){r?.(i,n)}}return!1}static async fromStorage(t,r,n){for(let o of r){let s;try{s=await o.load(t)}catch(l){n?.onError?.(l,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===q&&i.nodes!=null?i:void 0;if(a!=null)try{return e.fromSnapshot(a,n)}catch(l){n?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${t}" across ${r.length} tier(s)`)}_annotations=new Map;_traceRing;trace(t,r,n){if(t!=null&&r!=null){if(this.tryResolve(t)==null)return;if(this._annotations.set(t,r),this.config.inspectorEnabled){let o={path:t,annotation:r,timestamp_ns:K(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(o)}return}return t!=null?this.config.inspectorEnabled?this._annotations.get(t):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(t){return this._annotations.get(t)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(t){let r=this._traceRing.toArray().filter(o=>!t(o)),n=this._traceRing.size-r.length;this._traceRing.clear();for(let o of r)this._traceRing.push(o);return n}static diff(t,r){let n=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(r.nodes)),s=[...o].filter(w=>!n.has(w)).sort(),i=[...n].filter(w=>!o.has(w)).sort(),a=[],l=[];for(let w of n){if(!o.has(w))continue;let m=t.nodes[w],y=r.nodes[w],S=m.v,x=y.v;S!=null&&x!=null&&S.id===x.id&&S.version!==x.version&&l.push({path:w,id:S.id,from:S.version,to:x.version});let O=S!=null&&x!=null&&S.id===x.id&&S.version===x.version;for(let _ of["type","status","sentinel"]){let R=m[_],k=y[_];R!==k&&a.push({path:w,field:_,from:R,to:k})}if(!O)for(let _ of["value","meta"]){let R=m[_],k=y[_];jt(R,k)||a.push({path:w,field:_,from:R,to:k})}}let u=w=>`${w.from} ${w.to}`,d=new Set(t.edges.map(u)),h=new Set(r.edges.map(u)),p=r.edges.filter(w=>!d.has(u(w))),f=t.edges.filter(w=>!h.has(u(w))),c=new Set(t.subgraphs),g=new Set(r.subgraphs),b=[...g].filter(w=>!c.has(w)).sort(),v=[...c].filter(w=>!g.has(w)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:p,edgesRemoved:f,subgraphsAdded:b,subgraphsRemoved:v}}};function tn(e,t){let r=Ce.diff(e,t),n={};for(let o of r.nodesAdded){let s=t.nodes[o];s!=null&&(n[o]=s)}return{...r,nodesAddedFull:n}}function st(e,t,r,n={}){let o={paths:[],depths:new Map,truncated:!1};if(!t)return n.withDetail?o:[];if(!n.both&&r!=="upstream"&&r!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=n.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return n.withDetail?o:[];let i=new Map,a=new Map,l=new Map,u=new Map,d=new Set;for(let[m,y]of Object.entries(e.nodes)){if(!m)continue;d.add(m);let S=y.deps??[];i.set(m,S);for(let x of S)x&&(d.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(m))}for(let m of e.edges){if(m==null||typeof m!="object")continue;let y=typeof m.from=="string"?m.from:"",S=typeof m.to=="string"?m.to:"";!y||!S||(d.add(y),d.add(S),u.has(y)||u.set(y,new Set),u.get(y).add(S),l.has(S)||l.set(S,new Set),l.get(S).add(y))}if(!d.has(t))return n.withDetail?o:[];let h=n.both===!0,p=m=>{if(h){let O=i.get(m)??[],_=l.get(m),R=a.get(m),k=u.get(m),$=[...O];return _&&$.push(..._),R&&$.push(...R),k&&$.push(...k),$}if(r==="upstream"){let O=i.get(m)??[],_=l.get(m);return _?[...O,..._]:O}let y=a.get(m),S=u.get(m),x=y?[...y]:[];return S&&x.push(...S),x},f=new Set([t]),c=new Map,g=[{path:t,depth:0}],b=0,v=!1;for(;b<g.length;){let m=g[b++];if(s!=null&&m.depth>=s){p(m.path).length>0&&(v=!0);continue}for(let y of p(m.path))!y||f.has(y)||(f.add(y),c.set(y,m.depth+1),g.push({path:y,depth:m.depth+1}))}let w=[...c.keys()].sort((m,y)=>m<y?-1:m>y?1:0);return n.withDetail?{paths:w,depths:c,truncated:v}:w}function nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){let n=e[r],o=t[r];if(n.path!==o.path||n.type!==o.type||n.status!==o.status||n.hop!==o.hop||n.dep_index!==o.dep_index||n.annotation!==o.annotation||n.value!==o.value||n.lastMutation!==o.lastMutation)return!1;let s=n.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}export{ae as a,Ie as b,A as c,ft as d,He as e,Ve as f,B as g,q as h,Wt as i,Ce as j,tn as k,st as l};
@@ -1,78 +0,0 @@
1
- import{b as q}from"./chunk-JMGGCSIC.js";import{g as W,j as D}from"./chunk-PSQNYY72.js";import{E as M,F as A,G as L,H as T}from"./chunk-7AJKUA36.js";import{b as Q}from"./chunk-QYADASLV.js";var ie={};Q(ie,{compileSpec:()=>ne,decompileGraph:()=>se,extractFnFactory:()=>z,extractSourceFactory:()=>U,generateCatalogPrompt:()=>V,isRichFnEntry:()=>_,isRichSourceEntry:()=>J,llmCompose:()=>ae,llmRefine:()=>H,specDiff:()=>re,validateSpec:()=>E,validateSpecAgainstCatalog:()=>I});function _(a){return typeof a=="object"&&a!==null&&"factory"in a}function J(a){return typeof a=="object"&&a!==null&&"factory"in a}function z(a){return _(a)?a.factory:a}function U(a){return J(a)?a.factory:a}function V(a){let o=[];if(a.fns){let n=new Map;for(let[p,i]of Object.entries(a.fns)){let l=_(i)?i.tags?.[0]??"Other":"Other";n.has(l)||n.set(l,[]),n.get(l).push(X(p,i))}for(let[p,i]of n)o.push(`${p}:
2
- ${i.join(`
3
- `)}`)}if(a.sources){let n=[];for(let[p,i]of Object.entries(a.sources))n.push(Z(p,i));n.length>0&&o.push(`Sources:
4
- ${n.join(`
5
- `)}`)}return o.join(`
6
-
7
- `)}function X(a,o){if(!_(o))return`- ${a}`;let n=`- ${a}: ${o.description}`;if(o.configSchema){let p=Object.entries(o.configSchema).map(([i,l])=>{let s=`${i}: ${l.type}`;return l.enum&&(s+=` (${l.enum.join("|")})`),l.required===!1&&(s+="?"),s});n+=`. Config: { ${p.join(", ")} }`}return n}function Z(a,o){if(!J(o))return`- ${a}`;let n=`- ${a}: ${o.description}`;if(o.configSchema){let p=Object.entries(o.configSchema).map(([i,l])=>{let s=`${i}: ${l.type}`;return l.required===!1&&(s+="?"),s});n+=`. Config: { ${p.join(", ")} }`}return n}function I(a,o){let n=[],p=new Set(Object.keys(o.fns??{})),i=new Set(Object.keys(o.sources??{}));for(let[l,s]of Object.entries(a.nodes)){if(s.type==="template")continue;let c=s;if(c.fn&&p.size>0&&!p.has(c.fn))if(i.has(c.fn))n.push(`Node "${l}": fn "${c.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...p].join(", ")}`);else{let e=P(c.fn,p);n.push(`Node "${l}": fn "${c.fn}" not found in catalog`+(e?`. Did you mean "${e}"?`:""))}if(c.source&&i.size>0&&!i.has(c.source))if(p.has(c.source))n.push(`Node "${l}": source "${c.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...i].join(", ")}`);else{let e=P(c.source,i);n.push(`Node "${l}": source "${c.source}" not found in catalog`+(e?`. Did you mean "${e}"?`:""))}if(c.fn&&c.config&&o.fns?.[c.fn]){let e=o.fns[c.fn];if(_(e)&&e.configSchema){for(let[m,$]of Object.entries(e.configSchema))if($.required!==!1&&!(m in c.config)&&n.push(`Node "${l}": config missing required field "${m}"`),m in c.config&&$.enum){let w=c.config[m];$.enum.includes(w)||n.push(`Node "${l}": config.${m} = ${JSON.stringify(w)}, expected one of: ${$.enum.join(", ")}`)}}}}if(a.templates){for(let[l,s]of Object.entries(a.templates))for(let[c,e]of Object.entries(s.nodes))if(e.fn&&p.size>0&&!p.has(e.fn)){let m=P(e.fn,p);n.push(`Template "${l}" node "${c}": fn "${e.fn}" not found in catalog`+(m?`. Did you mean "${m}"?`:""))}}return{valid:n.length===0,errors:n}}function P(a,o){let n=null,p=1/0,i=a.toLowerCase();for(let l of o){let s=ee(i,l.toLowerCase());s<p&&s<=Math.max(3,Math.floor(a.length/2))&&(p=s,n=l)}return n}function ee(a,o){let n=a.length,p=o.length,i=Array.from({length:n+1},(l,s)=>Array.from({length:p+1},(c,e)=>s===0?e:e===0?s:0));for(let l=1;l<=n;l++)for(let s=1;s<=p;s++)i[l][s]=a[l-1]===o[s-1]?i[l-1][s-1]:1+Math.min(i[l-1][s],i[l][s-1],i[l-1][s-1]);return i[n][p]}var Y=new Set(["state","producer","derived","effect","operator","template"]),te=new Set(["state","producer","derived","effect","operator"]);function E(a){let o=[];if(a==null||typeof a!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"]};let n=a;if((typeof n.name!="string"||n.name.length===0)&&o.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return o.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:o};let p=new Set(Object.keys(n.nodes)),i=new Map,l=new Map;if(n.templates!=null&&typeof n.templates=="object"&&!Array.isArray(n.templates)){for(let[s,c]of Object.entries(n.templates))if(c!=null&&typeof c=="object"){let e=c;l.set(s,{params:Array.isArray(e.params)?e.params:[]})}}if(n.templates!=null)if(typeof n.templates!="object"||Array.isArray(n.templates))o.push("'templates' must be an object");else for(let[s,c]of Object.entries(n.templates)){if(c==null||typeof c!="object"){o.push(`Template "${s}": must be an object`);continue}let e=c;if(Array.isArray(e.params)||o.push(`Template "${s}": missing 'params' array`),e.nodes==null||typeof e.nodes!="object"||Array.isArray(e.nodes))o.push(`Template "${s}": missing or invalid 'nodes' object`);else{let m=new Set(Array.isArray(e.params)?e.params:[]),$=new Set(Object.keys(e.nodes));for(let[w,R]of Object.entries(e.nodes)){if(R==null||typeof R!="object"){o.push(`Template "${s}" node "${w}": must be an object`);continue}let r=R;if((typeof r.type!="string"||!te.has(r.type))&&o.push(`Template "${s}" node "${w}": invalid type`),Array.isArray(r.deps))for(let f of r.deps)!$.has(f)&&!m.has(f)&&o.push(`Template "${s}" node "${w}": dep "${f}" is not an inner node or param`)}typeof e.output!="string"?o.push(`Template "${s}": missing 'output' string`):e.nodes[e.output]||o.push(`Template "${s}": output "${e.output}" is not a declared node`)}}for(let[s,c]of Object.entries(n.nodes)){if(c==null||typeof c!="object"){o.push(`Node "${s}": must be an object`);continue}let e=c;if(typeof e.type!="string"||!Y.has(e.type)){o.push(`Node "${s}": invalid type "${String(e.type)}" (expected: ${[...Y].join(", ")})`);continue}if(i.set(s,e.type),e.type==="template")if(typeof e.template!="string"||!l.has(e.template))o.push(`Node "${s}": template "${String(e.template)}" not found in templates`);else if(e.bind==null||typeof e.bind!="object"||Array.isArray(e.bind))o.push(`Node "${s}": template ref requires 'bind' object`);else{let m=l.get(e.template),$=e.bind;for(let w of m.params)w in $||o.push(`Node "${s}": template param "${w}" is not bound (template "${e.template}")`);for(let[,w]of Object.entries($))typeof w=="string"&&!p.has(w)&&o.push(`Node "${s}": bind target "${w}" does not reference an existing node`)}else{if(Array.isArray(e.deps))for(let m of e.deps)m===s?o.push(`Node "${s}": self-referencing dep`):p.has(m)||o.push(`Node "${s}": dep "${m}" does not reference an existing node`);(e.type==="derived"||e.type==="effect"||e.type==="operator")&&!Array.isArray(e.deps)&&o.push(`Node "${s}": ${e.type} node should have a 'deps' array`)}}if(n.feedback!=null)if(!Array.isArray(n.feedback))o.push("'feedback' must be an array");else for(let s=0;s<n.feedback.length;s++){let c=n.feedback[s];if(c==null||typeof c!="object"){o.push(`Feedback [${s}]: must be an object`);continue}let e=c;(typeof e.from!="string"||!p.has(e.from))&&o.push(`Feedback [${s}]: 'from' "${String(e.from)}" does not reference an existing node`),typeof e.from=="string"&&e.from===e.to&&o.push(`Feedback [${s}]: 'from' and 'to' must be different nodes`),typeof e.to!="string"||!p.has(e.to)?o.push(`Feedback [${s}]: 'to' "${String(e.to)}" does not reference an existing node`):typeof e.to=="string"&&i.get(e.to)!=="state"&&o.push(`Feedback [${s}]: 'to' node "${e.to}" must be a state node (got "${i.get(e.to)??"unknown"}")`)}return{valid:o.length===0,errors:o}}function ne(a,o){let n=E(a);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
8
- ${n.errors.join(`
9
- `)}`);let p=o?.catalog??{},i=new D(a.name),l=a.templates??{},s=I(a,p);if(!s.valid)throw new Error(`compileSpec: catalog validation errors:
10
- ${s.errors.join(`
11
- `)}`);let c=r=>{let f=p.fns?.[r];return f?z(f):void 0},e=r=>{let f=p.sources?.[r];return f?U(f):void 0},m=new Map,$=[];for(let[r,f]of Object.entries(a.nodes)){if(f.type==="template")continue;let d=f;if(d.type==="state"){let h=M(d.initial,{name:r,meta:d.meta?{...d.meta}:void 0});i.add(h,{name:r}),m.set(r,h)}else if(d.type==="producer"){let h=d.source?e(d.source):void 0,b=d.fn?c(d.fn):void 0;if(h){let t=h(d.config??{});i.add(t,{name:r}),m.set(r,t)}else if(b){let t=b([],d.config??{});i.add(t,{name:r}),m.set(r,t)}else{let t=A(()=>{},{name:r,meta:{...d.meta,_specFn:d.fn,_specSource:d.source}});i.add(t,{name:r}),m.set(r,t)}}else $.push([r,d])}let w=!0,R=new Map($);for(;R.size>0&&w;){w=!1;for(let[r,f]of[...R.entries()]){let d=f.deps??[];if(!d.every(y=>m.has(y)))continue;let h=d.map(y=>m.get(y)),b=f.fn?c(f.fn):void 0,t;b?t=b(h,f.config??{}):f.type==="effect"?t=T(h,()=>{}):t=L(h,y=>y[0]),i.add(t,{name:r}),m.set(r,t),R.delete(r),w=!0}}if(R.size>0){let r=[...R.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${r}`)}for(let[r,f]of Object.entries(a.nodes)){if(f.type!=="template")continue;let d=f,h=l[d.template],b=new D(r),t=new Map,y=[];for(let[g,u]of Object.entries(h.nodes)){let v=(u.deps??[]).map(j=>j.startsWith("$")&&d.bind[j]?d.bind[j]:j),F={...u,deps:v};if(u.type==="state"){let j=M(u.initial,{name:g,meta:u.meta?{...u.meta}:void 0});b.add(j,{name:g}),t.set(g,j)}else if(u.type==="producer"){let j=u.source?e(u.source):void 0,O=u.fn?c(u.fn):void 0;if(j){let S=j(u.config??{});b.add(S,{name:g}),t.set(g,S)}else if(O){let S=O([],u.config??{});b.add(S,{name:g}),t.set(g,S)}else{let S=A(()=>{},{name:g,meta:{...u.meta,_specFn:u.fn,_specSource:u.source}});b.add(S,{name:g}),t.set(g,S)}}else y.push([g,F])}let N=!0,k=new Map(y);for(;k.size>0&&N;){N=!1;for(let[g,u]of[...k.entries()]){let v=u.deps??[];if(!v.every(G=>t.has(G)||m.has(G)))continue;let j=v.map(G=>t.get(G)??m.get(G)),O=u.fn?c(u.fn):void 0,S;O?S=O(j,u.config??{}):u.type==="effect"?S=T(j,()=>{}):S=L(j,G=>G[0]),b.add(S,{name:g}),t.set(g,S),k.delete(g),N=!0}}if(k.size>0){let g=[...k.keys()].sort().join(", ");throw new Error(`compileSpec: template "${d.template}" has unresolvable deps: ${g}`)}i.mount(r,b);let x=`${r}::${h.output}`;m.set(r,i.resolve(x));try{let g=i.resolve(x);g.meta._templateName?.emit(d.template),g.meta._templateBind?.emit(d.bind)}catch{}}for(let r of a.feedback??[])q(i,r.from,r.to,{maxIterations:r.maxIterations});return i}var oe=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function se(a){let o=a.describe({detail:"standard"}),n={},p=[],i=`::${W}::`,l=/^__feedback_(?!effect_)(.+)$/,s=new Set;for(let r of Object.keys(o.nodes)){if(r.includes(i))continue;let f=l.exec(r);if(f){s.add(f[1]);let d=o.nodes[r]?.meta;d?.feedbackFrom&&d?.feedbackTo&&p.push({from:d.feedbackFrom,to:d.feedbackTo,...d.maxIterations?{maxIterations:d.maxIterations}:{}})}}for(let[r,f]of Object.entries(o.nodes)){if(r.includes(i)||l.test(r)||f.meta?._internal||r.startsWith("__feedback_effect_")||r.startsWith("__bridge_")||r.includes("::"))continue;let d={type:f.type};if(f.deps.length>0&&(d.deps=f.deps.filter(h=>!h.includes("::"))),f.type==="state"&&f.value!==void 0&&(d.initial=f.value),f.meta&&Object.keys(f.meta).length>0){let h={};for(let[b,t]of Object.entries(f.meta))oe.has(b)||(h[b]=t);Object.keys(h).length>0&&(d.meta=h)}n[r]=d}let c={},e={},m=new Set;for(let r of o.subgraphs){let f=`${r}::`;for(let[d,h]of Object.entries(o.nodes)){if(!d.startsWith(f)||d.includes(i))continue;let b=h.meta;if(b?._templateName&&b?._templateBind){let t=b._templateName,y=b._templateBind;if(!c[t]){let N={},k=new Set,x=`${r}::`;for(let[O,S]of Object.entries(o.nodes)){if(!O.startsWith(x)||O.includes(i))continue;let G=O.slice(x.length);G.includes("::")||(k.add(G),N[G]={type:S.type,...S.deps.length>0?{deps:S.deps.map(C=>C.startsWith(x)?C.slice(x.length):C)}:{}})}let g=[],u=new Map;for(let O of Object.values(N))for(let S of O.deps??[])if(!k.has(S)&&!u.has(S)){let G=`$${S}`;g.push(G),u.set(S,G)}for(let O of Object.values(N))O.deps&&(O.deps=O.deps.map(S=>u.get(S)??S));let v=new Set;for(let O of Object.values(N))for(let S of O.deps??[])k.has(S)&&v.add(S);let j=[...k].filter(O=>!v.has(O))[0]??[...k].pop();c[t]={params:g,nodes:N,output:j}}delete n[r],e[r]={type:"template",template:t,bind:y},m.add(r);break}}}let $=new Map;for(let r of o.subgraphs){if(m.has(r))continue;let f={},d=`${r}::`;for(let[b,t]of Object.entries(o.nodes)){if(b.includes(i)||!b.startsWith(d))continue;let y=b.slice(d.length);y.includes("::")||(f[y]={type:t.type,...t.deps.length>0?{deps:t.deps.map(N=>N.startsWith(d)?N.slice(d.length):N)}:{}})}let h=JSON.stringify(Object.fromEntries(Object.entries(f).sort(([b],[t])=>b.localeCompare(t)).map(([b,t])=>[b,{type:t.type,deps:t.deps??[]}])));$.has(h)||$.set(h,[]),$.get(h).push({name:r,nodes:f})}for(let[,r]of $){if(r.length<2)continue;let f=`${r[0].name}_template`,d=r[0].nodes,h=new Set(Object.keys(d)),b=[],t=new Map;for(let g of Object.values(d))for(let u of g.deps??[])if(!h.has(u)&&!t.has(u)){let v=`$${u}`;b.push(v),t.set(u,v)}let y=new Set;for(let g of Object.values(d))for(let u of g.deps??[])h.has(u)&&y.add(u);let k=[...h].filter(g=>!y.has(g))[0]??[...h].pop(),x={};for(let[g,u]of Object.entries(d))x[g]={...u,deps:u.deps?.map(v=>t.get(v)??v)};c[f]={params:b,nodes:x,output:k};for(let g of r){delete n[g.name];let u={},v=new Set(Object.keys(g.nodes));for(let F of Object.values(g.nodes))for(let j of F.deps??[])if(!v.has(j)){let O=t.get(j)??`$${j}`;u[O]=j}e[g.name]={type:"template",template:f,bind:u}}}let w={...n,...e},R={name:o.name,nodes:w};return Object.keys(c).length>0&&(R.templates=c),p.length>0&&(R.feedback=p),R}function re(a,o){let n=[];a.name!==o.name&&n.push({type:"changed",path:"name",detail:`"${a.name}" \u2192 "${o.name}"`});let p=new Set(Object.keys(a.nodes)),i=new Set(Object.keys(o.nodes));for(let t of i)if(!p.has(t)){let y=o.nodes[t];n.push({type:"added",path:`nodes.${t}`,detail:`type: ${y.type}`})}for(let t of p)i.has(t)||n.push({type:"removed",path:`nodes.${t}`});for(let t of p){if(!i.has(t))continue;let y=a.nodes[t],N=o.nodes[t];if(JSON.stringify(y)!==JSON.stringify(N)){let k=[];y.type!==N.type&&k.push(`type: ${y.type} \u2192 ${N.type}`),JSON.stringify(y.deps)!==JSON.stringify(N.deps)&&k.push("deps changed"),y.fn!==N.fn&&k.push(`fn: ${y.fn} \u2192 ${N.fn}`),JSON.stringify(y.config)!==JSON.stringify(N.config)&&k.push("config changed"),n.push({type:"changed",path:`nodes.${t}`,detail:k.join("; ")||"modified"})}}let l=a.templates??{},s=o.templates??{},c=new Set(Object.keys(l)),e=new Set(Object.keys(s));for(let t of e)c.has(t)||n.push({type:"added",path:`templates.${t}`});for(let t of c)e.has(t)||n.push({type:"removed",path:`templates.${t}`});for(let t of c)e.has(t)&&JSON.stringify(l[t])!==JSON.stringify(s[t])&&n.push({type:"changed",path:`templates.${t}`,detail:"template definition changed"});let m=a.feedback??[],$=o.feedback??[],w=new Set(m.map(t=>`${t.from}->${t.to}`)),R=new Set($.map(t=>`${t.from}->${t.to}`));for(let t of $){let y=`${t.from}->${t.to}`;w.has(y)||n.push({type:"added",path:`feedback.${y}`,detail:`maxIterations: ${t.maxIterations??10}`})}for(let t of m){let y=`${t.from}->${t.to}`;R.has(y)||n.push({type:"removed",path:`feedback.${y}`})}for(let t of m){let y=`${t.from}->${t.to}`,N=$.find(k=>k.from===t.from&&k.to===t.to);N&&JSON.stringify(t)!==JSON.stringify(N)&&n.push({type:"changed",path:`feedback.${y}`,detail:`maxIterations: ${t.maxIterations??10} \u2192 ${N.maxIterations??10}`})}let r=n.filter(t=>t.type==="added").length,f=n.filter(t=>t.type==="removed").length,d=n.filter(t=>t.type==="changed").length,h=[];r&&h.push(`${r} added`),f&&h.push(`${f} removed`),d&&h.push(`${d} changed`);let b=h.length>0?h.join(", "):"no changes";return{entries:n,summary:b}}var B=`You are a graph architect for GraphReFly, a reactive graph protocol.
12
-
13
- Given a natural-language description, produce a JSON GraphSpec with this structure:
14
-
15
- {
16
- "name": "<graph_name>",
17
- "nodes": {
18
- "<node_name>": {
19
- "type": "state" | "derived" | "producer" | "effect" | "operator",
20
- "deps": ["<dep_node_name>", ...],
21
- "fn": "<catalog_function_name>",
22
- "source": "<catalog_source_name>",
23
- "config": { ... },
24
- "initial": <value>,
25
- "meta": { "description": "<purpose>" }
26
- },
27
- "<template_instance>": {
28
- "type": "template",
29
- "template": "<template_name>",
30
- "bind": { "$param": "node_name" }
31
- }
32
- },
33
- "templates": {
34
- "<template_name>": {
35
- "params": ["$param1", "$param2"],
36
- "nodes": { ... },
37
- "output": "<output_node>"
38
- }
39
- },
40
- "feedback": [
41
- { "from": "<condition_node>", "to": "<state_node>", "maxIterations": 10 }
42
- ]
43
- }
44
-
45
- Rules:
46
- - "state" nodes hold user/LLM-writable values (knobs). Use "initial" for default values.
47
- - "derived" nodes compute from deps using a named "fn".
48
- - "effect" nodes produce side effects from deps.
49
- - "producer" nodes generate values from a named "source".
50
- - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
51
- - Use "feedback" for bounded cycles where a derived value writes back to a state node.
52
- - meta.description is required for every node.
53
- - Return ONLY valid JSON, no markdown fences or commentary.`;function K(a){let o=a.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return o?o[1]:a}async function ae(a,o,n){let p=B,i=n?.catalogDescription??(n?.catalog?V(n.catalog):void 0);i&&(p+=`
54
-
55
- Available catalog (use ONLY these names):
56
- ${i}`),n?.systemPromptExtra&&(p+=`
57
-
58
- ${n.systemPromptExtra}`);let l=[{role:"system",content:p},{role:"user",content:a}],e=(await o.invoke(l,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();e.startsWith("```")&&(e=K(e));let m;try{m=JSON.parse(e)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${e.slice(0,200)}`)}let $=E(m);if(!$.valid)throw new Error(`llmCompose: invalid GraphSpec:
59
- ${$.errors.join(`
60
- `)}`);let w=m;if(n?.catalog){let R=n.maxAutoRefine??0;for(let r=0;r<=R;r++){let f=I(w,n.catalog);if(f.valid)break;if(r===R)throw new Error(`llmCompose: catalog validation failed after ${R} refine attempts:
61
- ${f.errors.join(`
62
- `)}`);w=await H(w,`Fix these catalog errors:
63
- ${f.errors.join(`
64
- `)}
65
-
66
- Use ONLY functions and sources from the catalog.`,o,{...n,catalogDescription:i})}}return w}async function H(a,o,n,p){let i=B;p?.catalogDescription&&(i+=`
67
-
68
- Available catalog:
69
- ${p.catalogDescription}`),p?.systemPromptExtra&&(i+=`
70
-
71
- ${p.systemPromptExtra}`);let l=[{role:"system",content:i},{role:"user",content:`Current GraphSpec:
72
- ${JSON.stringify(a,null,2)}
73
-
74
- Modification request: ${o}
75
-
76
- Return the complete modified GraphSpec as JSON.`}],e=(await n.invoke(l,{model:p?.model,temperature:p?.temperature??0,maxTokens:p?.maxTokens})).content.trim();e.startsWith("```")&&(e=K(e));let m;try{m=JSON.parse(e)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${e.slice(0,200)}`)}let $=E(m);if(!$.valid)throw new Error(`llmRefine: invalid GraphSpec:
77
- ${$.errors.join(`
78
- `)}`);return m}export{_ as a,J as b,z as c,U as d,V as e,I as f,E as g,ne as h,se as i,re as j,ae as k,H as l,ie as m};