@callbag-recharge/callbag-recharge 0.17.0 → 0.19.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.
- package/README.md +109 -31
- package/dist/adapters/http.cjs +4 -4
- package/dist/adapters/http.js +1 -1
- package/dist/adapters/index.cjs +9 -9
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/llm.cjs +5 -5
- package/dist/adapters/llm.js +1 -1
- package/dist/adapters/mcp.cjs +5 -5
- package/dist/adapters/mcp.js +1 -1
- package/dist/adapters/sse.cjs +10 -10
- package/dist/adapters/sse.js +1 -1
- package/dist/adapters/webhook.cjs +4 -4
- package/dist/adapters/webhook.js +1 -1
- package/dist/adapters/websocket.cjs +4 -4
- package/dist/adapters/websocket.js +1 -1
- package/dist/{chunk-JFJC5QME.js → chunk-22FZRVAU.js} +1 -1
- package/dist/{chunk-VFN2CV32.js → chunk-2F6QWERG.js} +1 -1
- package/dist/{chunk-VD74HJ6V.js → chunk-2HSHE2EI.js} +1 -1
- package/dist/chunk-2L6223KN.js +4 -0
- package/dist/{chunk-JJ6PHYH4.js → chunk-2QHNHL5Y.js} +1 -1
- package/dist/{chunk-DQVIVUSC.js → chunk-2ZFSL4MA.js} +1 -1
- package/dist/{chunk-ULQ5NNM4.js → chunk-35BBDNSG.js} +1 -1
- package/dist/{chunk-I54FHPCO.js → chunk-3TGYRIQB.js} +1 -1
- package/dist/{chunk-HVBJTUBY.js → chunk-3VEB4GWB.js} +1 -1
- package/dist/{chunk-T6LJTPKW.js → chunk-4CA73RLN.js} +1 -1
- package/dist/{chunk-L4HKWJB7.js → chunk-4RCV2AVX.js} +1 -1
- package/dist/{chunk-TLGNAGQV.js → chunk-54BT6MU4.js} +1 -1
- package/dist/{chunk-7FZVRQD6.js → chunk-5I4THZPQ.js} +1 -1
- package/dist/{chunk-2IUCXBY7.js → chunk-5JSJZFLR.js} +1 -1
- package/dist/{chunk-S2U5T7BO.js → chunk-5LLYKN4X.js} +1 -1
- package/dist/{chunk-2JMVH3GO.js → chunk-6QFOVQRL.js} +1 -1
- package/dist/{chunk-NE372A6P.js → chunk-7BXTCJFE.js} +1 -1
- package/dist/{chunk-U5WIJOXK.js → chunk-7WPMCM7F.js} +1 -1
- package/dist/{chunk-6X7HQUZI.js → chunk-A4HLU3K4.js} +1 -1
- package/dist/chunk-ABE7NDDH.js +1 -0
- package/dist/{chunk-JEZ26E63.js → chunk-BKJEZSZY.js} +1 -1
- package/dist/{chunk-LYNZX3UN.js → chunk-BWH53TL4.js} +1 -1
- package/dist/{chunk-UZFZ4IZM.js → chunk-CNTT2H6Y.js} +1 -1
- package/dist/{chunk-6OLBRXMG.js → chunk-E2AW7OYE.js} +1 -1
- package/dist/{chunk-7FX2AO6N.js → chunk-EAK2HKAD.js} +1 -1
- package/dist/{chunk-INHXATTB.js → chunk-EV5DA5VJ.js} +1 -1
- package/dist/{chunk-E4FSSIC6.js → chunk-F5EXEEZL.js} +1 -1
- package/dist/{chunk-56MXCPRP.js → chunk-F5UMSRLI.js} +1 -1
- package/dist/{chunk-LN2UGCTK.js → chunk-FLKDEQGB.js} +1 -1
- package/dist/{chunk-PFMEQCU6.js → chunk-FZ6IJLYN.js} +1 -1
- package/dist/chunk-G65KU7M5.js +1 -0
- package/dist/{chunk-LYOCP7L4.js → chunk-GI7IGLWO.js} +1 -1
- package/dist/{chunk-4NQIEZ33.js → chunk-HHJFEHV3.js} +1 -1
- package/dist/chunk-HTZLRRTE.js +1 -0
- package/dist/chunk-JCENQEPP.js +1 -0
- package/dist/{chunk-N7Y355ED.js → chunk-JLWDE534.js} +1 -1
- package/dist/{chunk-7XK265LH.js → chunk-JTNG3QAI.js} +1 -1
- package/dist/{chunk-XQ2NZAPZ.js → chunk-JVKWUVKQ.js} +1 -1
- package/dist/{chunk-PQPV3OXB.js → chunk-JW2KZLSD.js} +1 -1
- package/dist/{chunk-IMVCIYVC.js → chunk-KJW2EGU5.js} +1 -1
- package/dist/{chunk-CNOFRRHZ.js → chunk-LHEDPW3C.js} +1 -1
- package/dist/{chunk-R3QYN4IJ.js → chunk-LQ4T5H3N.js} +1 -1
- package/dist/{chunk-FJYFNUBJ.js → chunk-NT5AUV6U.js} +1 -1
- package/dist/{chunk-VN3XFROF.js → chunk-NYLNL2Y5.js} +1 -1
- package/dist/{chunk-RTXA6LFA.js → chunk-OA7V2X54.js} +1 -1
- package/dist/{chunk-4KVPJXBF.js → chunk-ODEEQ7UH.js} +1 -1
- package/dist/{chunk-NNNXS2D4.js → chunk-ODNVGOOO.js} +1 -1
- package/dist/{chunk-44EYVDK3.js → chunk-OGDTSFTW.js} +1 -1
- package/dist/{chunk-HKKF37VH.js → chunk-PKAASLJ7.js} +1 -1
- package/dist/{chunk-VO4IUQZE.js → chunk-PV347CGV.js} +1 -1
- package/dist/{chunk-RX4JY356.js → chunk-Q5DHO5II.js} +1 -1
- package/dist/{chunk-MGXREBEX.js → chunk-QX7UQF6F.js} +1 -1
- package/dist/{chunk-AEY2TDOX.js → chunk-RVW6YZVJ.js} +1 -1
- package/dist/chunk-RWOVH7KX.js +1 -0
- package/dist/{chunk-YEUF4R7R.js → chunk-SFO5COGM.js} +1 -1
- package/dist/{chunk-DXSHVZHS.js → chunk-SWGLEZSU.js} +1 -1
- package/dist/{chunk-HIKTBIQS.js → chunk-TLLIQ7WA.js} +1 -1
- package/dist/{chunk-QQG3L5XP.js → chunk-TPKLTDRR.js} +1 -1
- package/dist/{chunk-GXBPIPK5.js → chunk-TWZZYGMB.js} +1 -1
- package/dist/{chunk-CZBLKO6T.js → chunk-U3FGSR3I.js} +1 -1
- package/dist/{chunk-MENCMIG7.js → chunk-UVORPAQM.js} +1 -1
- package/dist/{chunk-SG4NXKP5.js → chunk-VEJRX4GP.js} +1 -1
- package/dist/{chunk-EINLCORW.js → chunk-VFXNSORS.js} +1 -1
- package/dist/{chunk-GKPIYIW2.js → chunk-VWMY3GUZ.js} +1 -1
- package/dist/chunk-W7A67MEA.js +1 -0
- package/dist/{chunk-4TVMJG2B.js → chunk-WEPYOEEV.js} +1 -1
- package/dist/{chunk-FP4IGNQK.js → chunk-YBVQC3GP.js} +1 -1
- package/dist/{chunk-ZPIHW4HI.js → chunk-YXMKE3MO.js} +1 -1
- package/dist/{chunk-Y7KZXCQE.js → chunk-ZCAW32S7.js} +1 -1
- package/dist/{chunk-RWZ3CCF6.js → chunk-ZDGVUX5G.js} +1 -1
- package/dist/{chunk-5ULT22VV.js → chunk-ZJCF5NYF.js} +1 -1
- package/dist/compat/jotai/index.cjs +4 -4
- package/dist/compat/jotai/index.js +1 -1
- package/dist/compat/nanostores/index.cjs +4 -4
- package/dist/compat/nanostores/index.js +1 -1
- package/dist/compat/signals/index.cjs +4 -4
- package/dist/compat/signals/index.js +1 -1
- package/dist/compat/zustand/index.cjs +4 -4
- package/dist/compat/zustand/index.js +1 -1
- package/dist/data/index.cjs +4 -4
- package/dist/data/index.d.cts +38 -0
- package/dist/data/index.d.ts +38 -0
- package/dist/data/index.js +1 -1
- package/dist/extra/buffer.cjs +4 -4
- package/dist/extra/buffer.js +1 -1
- package/dist/extra/bufferTime.cjs +4 -4
- package/dist/extra/bufferTime.js +1 -1
- package/dist/extra/combine.cjs +4 -4
- package/dist/extra/combine.js +1 -1
- package/dist/extra/concat.cjs +4 -4
- package/dist/extra/concat.js +1 -1
- package/dist/extra/concatMap.cjs +4 -4
- package/dist/extra/concatMap.js +1 -1
- package/dist/extra/debounce.cjs +4 -4
- package/dist/extra/debounce.js +1 -1
- package/dist/extra/delay.cjs +4 -4
- package/dist/extra/delay.js +1 -1
- package/dist/extra/distinctUntilChanged.cjs +4 -4
- package/dist/extra/distinctUntilChanged.js +1 -1
- package/dist/extra/elementAt.cjs +4 -4
- package/dist/extra/elementAt.js +1 -1
- package/dist/extra/empty.cjs +4 -4
- package/dist/extra/empty.js +1 -1
- package/dist/extra/exhaustMap.cjs +4 -4
- package/dist/extra/exhaustMap.js +1 -1
- package/dist/extra/filter.cjs +4 -4
- package/dist/extra/filter.js +1 -1
- package/dist/extra/find.cjs +4 -4
- package/dist/extra/find.js +1 -1
- package/dist/extra/first.cjs +4 -4
- package/dist/extra/first.js +1 -1
- package/dist/extra/flat.cjs +4 -4
- package/dist/extra/flat.js +1 -1
- package/dist/extra/fromEvent.cjs +4 -4
- package/dist/extra/fromEvent.js +1 -1
- package/dist/extra/fromIter.cjs +4 -4
- package/dist/extra/fromIter.js +1 -1
- package/dist/extra/fromObs.cjs +4 -4
- package/dist/extra/fromObs.js +1 -1
- package/dist/extra/fromPromise.cjs +4 -4
- package/dist/extra/fromPromise.js +1 -1
- package/dist/extra/index.cjs +4 -4
- package/dist/extra/index.d.cts +1 -1
- package/dist/extra/index.d.ts +1 -1
- package/dist/extra/index.js +1 -1
- package/dist/extra/interval.cjs +4 -4
- package/dist/extra/interval.js +1 -1
- package/dist/extra/last.cjs +4 -4
- package/dist/extra/last.js +1 -1
- package/dist/extra/map.cjs +4 -4
- package/dist/extra/map.js +1 -1
- package/dist/extra/merge.cjs +4 -4
- package/dist/extra/merge.js +1 -1
- package/dist/extra/never.cjs +4 -4
- package/dist/extra/never.js +1 -1
- package/dist/extra/of.cjs +4 -4
- package/dist/extra/of.js +1 -1
- package/dist/extra/pairwise.cjs +4 -4
- package/dist/extra/pairwise.js +1 -1
- package/dist/extra/partition.cjs +4 -4
- package/dist/extra/partition.js +1 -1
- package/dist/extra/pipeRaw.cjs +4 -4
- package/dist/extra/pipeRaw.js +1 -1
- package/dist/extra/remember.cjs +4 -4
- package/dist/extra/remember.js +1 -1
- package/dist/extra/repeat.cjs +4 -4
- package/dist/extra/repeat.js +1 -1
- package/dist/extra/rescue.cjs +4 -4
- package/dist/extra/rescue.js +1 -1
- package/dist/extra/sample.cjs +4 -4
- package/dist/extra/sample.js +1 -1
- package/dist/extra/scan.cjs +4 -4
- package/dist/extra/scan.js +1 -1
- package/dist/extra/skip.cjs +4 -4
- package/dist/extra/skip.js +1 -1
- package/dist/extra/startWith.cjs +4 -4
- package/dist/extra/startWith.js +1 -1
- package/dist/extra/streamParse.cjs +4 -4
- package/dist/extra/streamParse.js +1 -1
- package/dist/extra/subject.cjs +4 -4
- package/dist/extra/subject.js +1 -1
- package/dist/extra/switchMap.cjs +4 -4
- package/dist/extra/switchMap.js +1 -1
- package/dist/extra/take.cjs +4 -4
- package/dist/extra/take.js +1 -1
- package/dist/extra/takeUntil.cjs +4 -4
- package/dist/extra/takeUntil.js +1 -1
- package/dist/extra/takeWhile.cjs +4 -4
- package/dist/extra/takeWhile.js +1 -1
- package/dist/extra/tap.cjs +4 -4
- package/dist/extra/tap.js +1 -1
- package/dist/extra/throttle.cjs +4 -4
- package/dist/extra/throttle.js +1 -1
- package/dist/extra/throwError.cjs +4 -4
- package/dist/extra/throwError.js +1 -1
- package/dist/extra/timeout.cjs +4 -4
- package/dist/extra/timeout.js +1 -1
- package/dist/gate-DyykYri7.d.ts +80 -0
- package/dist/gate-mtVc8Lmp.d.cts +80 -0
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +130 -3
- package/dist/index.d.ts +130 -3
- package/dist/index.js +1 -1
- package/dist/memory/index.cjs +4 -4
- package/dist/memory/index.js +1 -1
- package/dist/messaging/index.cjs +6 -6
- package/dist/messaging/index.js +1 -1
- package/dist/orchestrate/index.cjs +7 -7
- package/dist/orchestrate/index.d.cts +112 -117
- package/dist/orchestrate/index.d.ts +112 -117
- package/dist/orchestrate/index.js +5 -5
- package/dist/patterns/agentLoop/index.cjs +4 -4
- package/dist/patterns/agentLoop/index.d.cts +35 -7
- package/dist/patterns/agentLoop/index.d.ts +35 -7
- package/dist/patterns/agentLoop/index.js +1 -1
- package/dist/patterns/chatStream/index.cjs +4 -4
- package/dist/patterns/chatStream/index.js +1 -1
- package/dist/patterns/createStore/index.cjs +4 -4
- package/dist/patterns/createStore/index.js +1 -1
- package/dist/patterns/formField/index.cjs +4 -4
- package/dist/patterns/formField/index.js +1 -1
- package/dist/patterns/hybridRoute/index.cjs +4 -4
- package/dist/patterns/hybridRoute/index.js +1 -1
- package/dist/patterns/memoryStore/index.cjs +4 -4
- package/dist/patterns/memoryStore/index.js +1 -1
- package/dist/patterns/pagination/index.cjs +4 -4
- package/dist/patterns/pagination/index.js +1 -1
- package/dist/patterns/rateLimiter/index.cjs +4 -4
- package/dist/patterns/rateLimiter/index.js +1 -1
- package/dist/patterns/textBuffer/index.cjs +8 -8
- package/dist/patterns/textBuffer/index.js +1 -1
- package/dist/patterns/textEditor/index.cjs +14 -14
- package/dist/patterns/textEditor/index.js +1 -1
- package/dist/patterns/toolCallState/index.cjs +4 -4
- package/dist/patterns/toolCallState/index.js +1 -1
- package/dist/patterns/undoRedo/index.cjs +4 -4
- package/dist/patterns/undoRedo/index.js +1 -1
- package/dist/utils/index.cjs +5 -3
- package/dist/utils/index.d.cts +136 -26
- package/dist/utils/index.d.ts +136 -26
- package/dist/utils/index.js +3 -1
- package/package.json +2 -3
- package/dist/chunk-6WXC33WR.js +0 -1
- package/dist/chunk-CTSKV2CN.js +0 -1
- package/dist/chunk-IEGBHQQI.js +0 -1
- package/dist/chunk-L3ZTIVH6.js +0 -1
- package/dist/chunk-NEYVAVAH.js +0 -1
- package/dist/chunk-SOIVZBGE.js +0 -4
- package/dist/chunk-ZWFSO5A4.js +0 -1
package/README.md
CHANGED
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
**State that flows.** Reactive state management for TypeScript — from simple atoms to streaming pipelines, in one library.
|
|
4
4
|
|
|
5
5
|
- **6 primitives** — `state`, `derived`, `dynamicDerived`, `effect`, `producer`, `operator`
|
|
6
|
-
- **
|
|
6
|
+
- **70+ operators** — `switchMap`, `debounce`, `scan`, `retry`, and more — tree-shakeable
|
|
7
|
+
- **170+ modules** across 12 categories — core, extra, utils, data, orchestrate, messaging, worker, memory, patterns, adapters, compat, raw
|
|
7
8
|
- **Glitch-free** — two-phase push resolves diamonds correctly, every time
|
|
8
9
|
- **Streaming-native** — LLM chunks, WebSocket, SSE are first-class, not bolted on
|
|
10
|
+
- **Lifecycle signals** — RESET, PAUSE, RESUME, TEARDOWN propagate through the graph as TYPE 3 STATE signals
|
|
9
11
|
- **Inspectable** — every node in the graph is observable via `Inspector` — names, edges, phases, values
|
|
10
|
-
- **Framework-agnostic** —
|
|
12
|
+
- **Framework-agnostic** — Vue, React, Svelte, Solid bindings via `compat/`; works anywhere JS runs
|
|
11
13
|
- Zero dependencies
|
|
12
14
|
|
|
13
15
|
```ts
|
|
@@ -31,12 +33,14 @@ count.set(5)
|
|
|
31
33
|
- **Streaming data** — LLM token streams, WebSocket, SSE flowing into reactive state via `producer` or `fromAsyncIter`
|
|
32
34
|
- **Cancellable async** — `switchMap` auto-cancels the previous operation when a new one starts
|
|
33
35
|
- **Derived values you can trust** — diamond-safe, cached, always consistent
|
|
34
|
-
- **On-device / edge LLM streaming** — manage WebLLM, Ollama, or ExecuTorch token streams as reactive sources
|
|
35
|
-
- **Hybrid cloud+edge model routing** — confidence-based routing between local and cloud LLMs with automatic fallback via `route()` + `rescue()
|
|
36
|
-
- **Tool call state machines** — reactive state machines for LLM tool call lifecycle
|
|
36
|
+
- **On-device / edge LLM streaming** — manage WebLLM, Ollama, or ExecuTorch token streams as reactive sources
|
|
37
|
+
- **Hybrid cloud+edge model routing** — confidence-based routing between local and cloud LLMs with automatic fallback via `route()` + `rescue()`
|
|
38
|
+
- **Tool call state machines** — reactive state machines for LLM tool call lifecycle using `stateMachine` + `producer`
|
|
37
39
|
- **Agentic workflows** — session state, tool call lifecycle, multi-agent coordination, memory with decay-scored eviction
|
|
38
40
|
- **Event pipelines** — transform, buffer, window, throttle, retry — compose with `pipe`
|
|
39
41
|
- **Reactive data structures** — `reactiveMap`, `reactiveLog`, `reactiveIndex` with near-native read performance
|
|
42
|
+
- **Messaging** — Pulsar-inspired `topic`/`subscription` with `jobQueue`, `jobFlow`, and `repeatPublish`
|
|
43
|
+
- **Cross-thread reactivity** — `workerBridge`/`workerSelf` for Web Workers, SharedWorker, and service workers
|
|
40
44
|
- **Scheduled pipelines** — cron triggers, task state tracking, DAG validation — Airflow-in-TypeScript
|
|
41
45
|
- **Durable workflows** — checkpoint persistence (file, SQLite, IndexedDB), execution logging, pipeline builder with topological sort
|
|
42
46
|
|
|
@@ -50,11 +54,13 @@ Most state managers stop at atoms and computed values. Most streaming libraries
|
|
|
50
54
|
|
|
51
55
|
- **Glitch-free diamond resolution** — when A → B, A → C, B+C → D, D computes exactly once with consistent values. Jotai, Nanostores, and vanilla signals all glitch here.
|
|
52
56
|
- **Streaming operators as first-class citizens** — `switchMap`, `debounce`, `throttle`, `scan`, `retry`, `bufferTime` — not an afterthought, not a separate library.
|
|
57
|
+
- **Lifecycle signals** — RESET, PAUSE, RESUME, TEARDOWN propagate through the reactive graph as TYPE 3 STATE signals. No imperative teardown lists.
|
|
53
58
|
- **Inspectable graph** — every store has a name, a kind, dependency edges, and a status. `Inspector.graph()` shows the full picture. No other state manager gives you this without runtime cost in production.
|
|
54
59
|
- **Effects with dirty tracking** — `effect()` knows which deps changed and waits for all to resolve before running. Smarter than `useEffect`, `autorun`, or `watch`.
|
|
55
60
|
- **Completion and error semantics** — stores can complete and error, just like streams. `retry`, `rescue`, `repeat` handle recovery. No ad-hoc try/catch.
|
|
56
61
|
- **Built-in batching** — `batch()` defers value propagation until all writes finish. No torn reads mid-update.
|
|
57
|
-
- **Reactive data structures** — `reactiveMap
|
|
62
|
+
- **Reactive data structures** — `reactiveMap`, `reactiveLog`, `reactiveIndex` — near-native reactive collections that no competitor offers.
|
|
63
|
+
- **Full-stack reactive** — messaging, worker bridges, adapters (LLM, WebSocket, SSE, MCP), and framework bindings — all built on the same 6 primitives.
|
|
58
64
|
|
|
59
65
|
---
|
|
60
66
|
|
|
@@ -105,15 +111,15 @@ Inspector.graph()
|
|
|
105
111
|
|
|
106
112
|
---
|
|
107
113
|
|
|
108
|
-
##
|
|
114
|
+
## 70+ operators, tree-shakeable
|
|
109
115
|
|
|
110
116
|
Import only what you need from `callbag-recharge/extra`.
|
|
111
117
|
|
|
112
|
-
**Sources** — `interval` · `fromIter` · `fromAsyncIter` · `fromEvent` · `fromPromise` · `fromObs` · `of` · `empty` · `throwError` · `never`
|
|
118
|
+
**Sources** — `interval` · `fromIter` · `fromAsyncIter` · `fromEvent` · `fromPromise` · `fromObs` · `fromAny` · `fromTimer` · `fromTrigger` · `fromCron` · `of` · `empty` · `throwError` · `never`
|
|
113
119
|
|
|
114
|
-
**Filtering** — `filter` · `take` · `skip` · `first` · `last` · `find` · `elementAt` · `distinctUntilChanged` · `takeUntil`
|
|
120
|
+
**Filtering** — `filter` · `take` · `skip` · `first` · `last` · `find` · `elementAt` · `distinctUntilChanged` · `takeUntil` · `takeWhile`
|
|
115
121
|
|
|
116
|
-
**Transformation** — `map` · `scan` · `pairwise` · `startWith` · `flat` · `switchMap` · `concatMap` · `exhaustMap` · `groupBy`
|
|
122
|
+
**Transformation** — `map` · `scan` · `pairwise` · `startWith` · `flat` · `switchMap` · `concatMap` · `exhaustMap` · `groupBy` · `streamParse`
|
|
117
123
|
|
|
118
124
|
**Combination** — `merge` · `combine` · `concat` · `race` · `withLatestFrom` · `partition`
|
|
119
125
|
|
|
@@ -125,9 +131,9 @@ Import only what you need from `callbag-recharge/extra`.
|
|
|
125
131
|
|
|
126
132
|
**Aggregation** — `reduce` · `toArray`
|
|
127
133
|
|
|
128
|
-
**Error handling** — `rescue` · `retry` · `repeat`
|
|
134
|
+
**Error handling** — `rescue` · `retry` · `repeat` · `route`
|
|
129
135
|
|
|
130
|
-
**Utilities** — `tap` · `share` · `remember` · `subject` · `wrap`
|
|
136
|
+
**Utilities** — `tap` · `share` · `remember` · `cached` · `pausable` · `subject` · `wrap` · `firstValueFrom`
|
|
131
137
|
|
|
132
138
|
**Piping** — `pipeRaw` · `SKIP`
|
|
133
139
|
|
|
@@ -165,7 +171,7 @@ const log = reactiveLog<string>({ maxSize: 1000 })
|
|
|
165
171
|
log.append('event happened')
|
|
166
172
|
const recent = log.slice(-10) // Store<string[]> — reactive
|
|
167
173
|
|
|
168
|
-
// Reactive Index — dual-key lookup, 1.
|
|
174
|
+
// Reactive Index — dual-key lookup, ~1.2x native Map.get speed on reads
|
|
169
175
|
const index = reactiveIndex<string, string, Item>()
|
|
170
176
|
index.set('pk', 'sk', item)
|
|
171
177
|
const found = index.select('pk', 'sk') // Store<Item | undefined>
|
|
@@ -175,33 +181,37 @@ const found = index.select('pk', 'sk') // Store<Item | undefined>
|
|
|
175
181
|
|
|
176
182
|
## Scheduling & orchestration
|
|
177
183
|
|
|
178
|
-
|
|
184
|
+
17 orchestration nodes — diamond resolution IS the DAG executor.
|
|
179
185
|
|
|
180
186
|
```ts
|
|
181
|
-
import {
|
|
187
|
+
import { task, pipeline, gate, sensor, forEach } from 'callbag-recharge/orchestrate'
|
|
182
188
|
import { pipe } from 'callbag-recharge'
|
|
183
189
|
import { exhaustMap, retry } from 'callbag-recharge/extra'
|
|
184
190
|
|
|
185
|
-
//
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
191
|
+
// Pipeline — DAG with topological sort, checkpoints, execution logging
|
|
192
|
+
const etl = pipeline('daily-etl', [
|
|
193
|
+
task('fetch-bank', () => plaid.sync()),
|
|
194
|
+
task('fetch-cards', () => stripe.charges()),
|
|
195
|
+
task('aggregate', () => merge(bank, cards), { deps: ['fetch-bank', 'fetch-cards'] }),
|
|
196
|
+
])
|
|
189
197
|
|
|
190
|
-
//
|
|
191
|
-
const
|
|
198
|
+
// Gate — hold values until a condition store is true
|
|
199
|
+
const approved = gate(data, approvalStore)
|
|
192
200
|
|
|
193
|
-
//
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
201
|
+
// Sensor — reactive condition monitor
|
|
202
|
+
const ready = sensor([dbHealth, cacheHealth], () => dbHealth.get() && cacheHealth.get())
|
|
203
|
+
|
|
204
|
+
// forEach — run a side-effect for each value from a source
|
|
205
|
+
forEach(events, (signal, event) => process(event))
|
|
198
206
|
```
|
|
199
207
|
|
|
208
|
+
`task` · `taskState` · `pipeline` · `pipelineRunner` · `gate` · `sensor` · `forEach` · `branch` · `join` · `loop` · `wait` · `approval` · `onFailure` · `subPipeline` · `executionLog` · `diagram` · `fromCron`
|
|
209
|
+
|
|
200
210
|
---
|
|
201
211
|
|
|
202
212
|
## Agent memory
|
|
203
213
|
|
|
204
|
-
Reactive memory primitives for agentic workflows —
|
|
214
|
+
Reactive memory primitives for agentic workflows — decay-scored eviction, O(1) tag retrieval, push-based score tracking.
|
|
205
215
|
|
|
206
216
|
```ts
|
|
207
217
|
import { collection, memoryNode } from 'callbag-recharge/memory'
|
|
@@ -209,26 +219,94 @@ import { collection, memoryNode } from 'callbag-recharge/memory'
|
|
|
209
219
|
const memory = collection<string>({ maxSize: 100 })
|
|
210
220
|
memory.add('User prefers TypeScript', { id: 'pref-1', tags: ['preference'] })
|
|
211
221
|
|
|
212
|
-
//
|
|
222
|
+
// O(1) tag-based retrieval via reactive index
|
|
213
223
|
memory.tagIndex.select('preference').get() // Set{'pref-1'}
|
|
214
224
|
|
|
215
|
-
//
|
|
225
|
+
// O(log n) eviction — live min-heap, scores update reactively as nodes are
|
|
226
|
+
// touched/tagged. No O(n) scan at eviction time.
|
|
227
|
+
memory.add('Older fact', { tags: ['context'] })
|
|
228
|
+
memory.add('Recent fact', { tags: ['context'] }) // touches bump score
|
|
229
|
+
// When maxSize exceeded, lowest-scoring node evicted automatically
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
234
|
+
## Messaging
|
|
235
|
+
|
|
236
|
+
Pulsar-inspired reactive pub/sub — topics, subscriptions, and job processing built on callbag stores.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { topic, subscription, jobQueue, jobFlow } from 'callbag-recharge/messaging'
|
|
240
|
+
|
|
241
|
+
// Topic — named pub/sub channel
|
|
242
|
+
const events = topic<{ type: string; payload: unknown }>('events')
|
|
243
|
+
|
|
244
|
+
// Subscription — filtered, reactive consumer
|
|
245
|
+
const clicks = subscription(events, msg => msg.type === 'click')
|
|
246
|
+
|
|
247
|
+
// Job queue — ordered processing with concurrency control
|
|
248
|
+
const queue = jobQueue<Task>(tasks, { concurrency: 3 })
|
|
249
|
+
|
|
250
|
+
// Job flow — multi-step pipeline with per-step handlers
|
|
251
|
+
const flow = jobFlow<Input, Output>(source, [step1, step2, step3])
|
|
216
252
|
```
|
|
217
253
|
|
|
218
254
|
---
|
|
219
255
|
|
|
256
|
+
## Worker bridge
|
|
257
|
+
|
|
258
|
+
Cross-thread reactive stores — Web Workers, SharedWorker, and service workers.
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
// Main thread
|
|
262
|
+
import { workerBridge } from 'callbag-recharge/worker'
|
|
263
|
+
const bridge = workerBridge(new Worker('./worker.ts'))
|
|
264
|
+
const remoteCount = bridge.get('count') // Store<number> — reactive across threads
|
|
265
|
+
|
|
266
|
+
// Worker thread
|
|
267
|
+
import { workerSelf } from 'callbag-recharge/worker'
|
|
268
|
+
const self = workerSelf()
|
|
269
|
+
self.expose('count', countStore)
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Patterns
|
|
275
|
+
|
|
276
|
+
16 ready-made patterns built on the primitives — import and go.
|
|
277
|
+
|
|
278
|
+
`createStore` · `chatStream` · `commandBus` · `focusManager` · `formField` · `hybridRoute` · `memoryStore` · `pagination` · `rateLimiter` · `selection` · `textBuffer` · `textEditor` · `toolCallState` · `undoRedo` · `agentLoop`
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## Adapters & compatibility
|
|
283
|
+
|
|
284
|
+
**Adapters** (`callbag-recharge/adapters`) — `fromLLM` · `fromWebSocket` · `fromSSE` · `fromWebhook` · `fromHTTP` · `fromMCP`
|
|
285
|
+
|
|
286
|
+
**Framework bindings** (`callbag-recharge/compat/*`) — Vue · React · Svelte · Solid · Zustand · Jotai · Nanostores · TC39 Signals
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
220
290
|
## Callbag interop
|
|
221
291
|
|
|
222
|
-
Every store exposes a `.source` property — a standard callbag source function. State management signals (DIRTY, RESOLVED) flow on the type 3 STATE channel, keeping type 1 DATA for real values only.
|
|
292
|
+
Every store exposes a `.source` property — a standard callbag source function. State management signals (DIRTY, RESOLVED) and lifecycle signals (RESET, PAUSE, RESUME, TEARDOWN) flow on the type 3 STATE channel, keeping type 1 DATA for real values only.
|
|
223
293
|
|
|
224
294
|
```ts
|
|
225
|
-
import { STATE, DIRTY, RESOLVED } from 'callbag-recharge'
|
|
295
|
+
import { STATE, DIRTY, RESOLVED, RESET, PAUSE, RESUME, TEARDOWN } from 'callbag-recharge'
|
|
226
296
|
|
|
227
297
|
store.source(0, (type, data) => {
|
|
228
298
|
if (type === 3 && data === DIRTY) { /* invalidation */ }
|
|
229
299
|
if (type === 3 && data === RESOLVED) { /* resolved unchanged */ }
|
|
300
|
+
if (type === 3 && data === PAUSE) { /* paused */ }
|
|
301
|
+
if (type === 3 && data === RESET) { /* reset to initial */ }
|
|
230
302
|
if (type === 1) { /* value */ }
|
|
231
303
|
})
|
|
304
|
+
|
|
305
|
+
// Send lifecycle signals through the graph
|
|
306
|
+
sub.signal(PAUSE) // pause downstream
|
|
307
|
+
sub.signal(RESUME) // resume downstream
|
|
308
|
+
sub.signal(RESET) // reset to initial state
|
|
309
|
+
sub.signal(TEARDOWN) // tear down the subgraph
|
|
232
310
|
```
|
|
233
311
|
|
|
234
312
|
---
|
package/dist/adapters/http.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}static _signalLabel(e){return e===
|
|
3
|
-
`)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],
|
|
4
|
-
`)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var J=1,
|
|
1
|
+
"use strict";var te=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var Le=(t,e)=>{for(var i in e)te(t,i,{get:e[i],enumerable:!0})},Ae=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Oe.call(t,s)&&s!==i&&te(t,s,{get:()=>e[s],enumerable:!(n=Re(e,s))||n.enumerable});return t};var Ie=t=>Ae(te({},"__esModule",{value:!0}),t);var je={};Le(je,{fromHTTP:()=>Me});module.exports=Ie(je);var D=Symbol("DIRTY"),M=Symbol("RESOLVED"),le=Symbol("SINGLE_DEP"),P=Symbol("RESET"),se=Symbol("PAUSE"),ie=Symbol("RESUME"),re=Symbol("TEARDOWN");function ue(t){return t===P||t===se||t===ie||t===re}var ce=0,fe=1,de=2,pe=3,ge=4,he=5,R=7,oe=7<<R,$e=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Te(t){return $e[(t&oe)>>>R]}var h=0,_=1,g=2,S=3,H=0,q=[],ne=!1;function j(t){H++;try{return t()}finally{if(H--,H===0&&!ne){ne=!0;for(let e=0;e<q.length;e++)q[e]();q.length=0,ne=!1}}}function $(){return H>0}function z(t){q.push(t)}var G=0,B=[];function Se(){G++}function _e(){if(G--,G===0){for(let t=0;t<B.length;t++)B[t]();B.length=0}}function me(t){G>0?B.push(t):t()}var A=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(s=>t._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let i=t._keys.get(e)??t._names.get(e);if(i)return i;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,i){if(!t.enabled)return;i?.name&&t._names.set(e,i.name),i?.kind&&t._kinds.set(e,i.kind);let n=t._nextId++,s=i?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let r=t._depSuffix(i?.deps);s=r?`${s}(${r})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let r=i?.kind??"store",a=t._depSuffix(i?.deps);s=a?`${r}(${a})`:`${r}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}t._usedKeys.add(s),t._keys.set(e,s),t._stores.add(new WeakRef(e))}static registerEdge(e,i){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(i),r=t._edges.get(n);r?r.includes(s)||r.push(s):t._edges.set(n,[s])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,i=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let r=t._resolveKey(s);i.add(r),e.set(r,t.inspect(s))}for(let[n,s]of t._edges){if(!i.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let r=s.filter(a=>i.has(a));r.length===0?t._edges.delete(n):r.length!==s.length&&t._edges.set(n,r)}return e}static trace(e,i){let n=null,s=e.get();return e.source(h,(r,a)=>{if(r===h&&(n=a),r===g){n=null;return}if(r===1){let l=a;if(!Object.is(l,s)){let u=s;s=l,i(l,u)}}}),()=>n?.(g)}static dumpGraph(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let[a,l]of i)for(let u of l){let f=n.get(u);f?f.includes(a)||f.push(a):n.set(u,[a])}let s=[];for(let[a,l]of e){let u=n.get(a),f=i.get(a),o=u?.length?` \u2190 [${u.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";s.push(` ${a} (${l.kind}) = ${JSON.stringify(l.value)} [${l.status??"?"}]${o}${c}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
|
|
2
|
+
`)}static _signalLabel(e){return e===D?"DIRTY":e===M?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,i,n){let s=null,r=!1,a=i??t.getName(e),l=[],u={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return u.ended&&!r},get errored(){return u.ended&&r},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return l},dispose:()=>s?.(g),reconnect:()=>(s?.(g),t._observe(e,i,n))};return e.source(h,(f,o)=>{if(f===h){s=o;return}let c=$();f===_?(u.values.push(o),u.events.push({type:"data",data:o,inBatch:c}),l.push(o),n&&n(`[${a}] DATA:`,o)):f===S?(u.signals.push(o),u.events.push({type:"signal",data:o,inBatch:c}),l.push(t._signalLabel(o)),o===D?u.dirtyCount++:o===M&&u.resolvedCount++,n&&n(`[${a}] STATE:`,o)):f===g&&(u.ended=!0,u.endError=o,r=o!==void 0,u.events.push({type:"end",data:o,inBatch:c}),l.push(r?["END",o]:"END"),n&&n(`[${a}] END`,o!==void 0?o:""),s=null)}),u}static observe(e){return t._observe(e)}static activate(e){let i=null;return e.source(h,(n,s)=>{n===h&&(i=s),n===g&&(i=null)}),()=>i?.(g)}static tap(e,i){let n=i??`tap(${t.getName(e)??"anon"})`,s={get:()=>e.get(),source:e.source};return t.register(s,{name:n,kind:"tap"}),t.registerEdge(e,s),s}static spy(e,i){let n=i?.name??t.getName(e)??"spy",s=i?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let a of t._stores){let l=a.deref();if(!l)continue;let u=t._annotations.get(l);u!==void 0&&n.set(t._resolveKey(l),u)}let s=[];for(let[a,l]of e){let u={name:a,kind:l.kind,value:l.value,status:l.status},f=n.get(a);f!==void 0&&(u.annotation=f),s.push(u)}let r=[];for(let[a,l]of i)for(let u of l)r.push({from:a,to:u});return{nodes:s,edges:r,trace:t.traceLog()}}static toMermaid(e){let i=e?.direction??"TD",n=t.snapshot(),s=[`graph ${i}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function l(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of n.nodes){let c=l(o.name);u.set(o.name,c);let d=`${o.name} (${o.kind}) = ${f(o.value)}`,p=r[o.status??""]??"";s.push(` ${c}["${d}"]${p}`)}for(let o of n.edges){let c=u.get(o.from)??l(o.from),d=u.get(o.to)??l(o.to);s.push(` ${c} --> ${d}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
|
|
3
|
+
`)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function l(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of n.nodes){let c=l(o.name);u.set(o.name,c);let d=r[o.kind]??"rectangle",p=`${o.name} (${o.kind}) = ${f(o.value)}`,y=o.status?` [${o.status}]`:"";s.push(`${c}: "${p}${y}" { shape: ${d} }`)}n.edges.length>0&&s.push("");for(let o of n.edges){let c=u.get(o.from)??l(o.from),d=u.get(o.to)??l(o.to);s.push(`${c} -> ${d}`)}return s.join(`
|
|
4
|
+
`)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static timeline(e){let i=null,n=[];return e.source(h,(s,r)=>{if(s===h){i=r;return}let a={timestamp:Date.now(),type:s===_?"data":s===S?"signal":"end",data:r,inBatch:$()};n.push(a),s===g&&(i=null)}),{entries:n,dispose:()=>i?.(g)}}static observeDerived(e){let i=[],n=e,s=n._fn;if(typeof s!="function"||!Array.isArray(n._deps))return{...t.observe(e),evaluations:i};n._fn=()=>{let u=n._deps.map(o=>o.get()),f=s();return i.push({result:f,depValues:u,timestamp:Date.now()}),f};let r=t._observe(e),a=r.dispose;return{...r,evaluations:i,dispose:()=>{n._fn=s,a()},reconnect:()=>(n._fn=s,a(),t.observeDerived(e))}}static observeTaskState(e){let i=e.status.get(),n=[],s=null;return e.status.source(h,(r,a)=>{if(r===h){s=a;return}if(r===_){let l=a;if(l!==i){let u={from:i,to:l,timestamp:Date.now()};l==="error"&&(u.error=e.error.get()),n.push(u),i=l}}r===g&&(s=null)}),{transitions:n,get currentStatus(){return e.status.get()},dispose:()=>{s?.(g)}}}static causalityTrace(e){let i=[],n=e,s=n._fn;if(typeof s!="function"||!Array.isArray(n._deps))return{...t.observe(e),causality:i};let r=n._deps,a=r.map(o=>o.get());n._fn=()=>{let o=r.map(p=>p.get()),c=s(),d=-1;for(let p=0;p<r.length;p++)if(!Object.is(o[p],a[p])){d=p;break}return i.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?t.getName(r[d]):void 0,depValues:o,timestamp:Date.now()}),a=o,c};let l=t._observe(e),u=l.dispose;return{...l,causality:i,dispose:()=>{n._fn=s,u()},reconnect:()=>(n._fn=s,u(),t.causalityTrace(e))}}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var J=1,E=64,m=2,N=4,ye=8,be=16,I=32,k=1024,T=oe,C=fe<<R,W=de<<R,Z=ce<<R,Pe=ge<<R,Ne=he<<R,Ce=pe<<R,F=class{_value;_output=null;_flags;get _status(){return Te(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,i){this._value=i?.initial,this._fn=e,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=N),i?.resetOnTeardown&&(n|=ye),i?.resubscribable&&(n|=be),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||A.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,i){let n=this._output;if(n)if(this._flags&E)for(let s of n)s(e,i);else n(e,i)}emit(e){this._flags&m||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&($()?this._flags&I||(this._flags|=I,this._flags&N&&(this._flags=this._flags&~T|C,this._dispatch(S,D)),z(()=>{this._flags&=~I,this._flags=this._flags&~T|W,this._dispatch(_,this._value)})):(this._flags&N&&!(this._flags&k)&&(this._flags=this._flags&~T|C,this._dispatch(S,D)),this._flags=this._flags&~T|W,this._dispatch(_,this._value))))}signal(e){this._flags&m||!this._output||(e===D?this._flags=this._flags&~T|C:e===M&&(this._flags=this._flags&~T|Ce),this._dispatch(S,e))}complete(){if(this._flags&m)return;this._flags=(this._flags|m)&~T|Pe;let e=this._output,i=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),e)if(i)for(let n of e)n(g);else e(g)}error(e){if(this._flags&m)return;this._flags=(this._flags|m)&~T|Ne;let i=this._output,n=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(g,e);else i(g,e)}_start(){if(this._flags&J||!this._fn)return;this._flags|=J,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i),onSignal:i=>{this._onLifecycleSignal=i}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&J&&(this._flags&=~J,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&ye&&(this._value=this._initial),this._flags&m||(this._flags=this._flags&~T|Z))}_handleLifecycleSignal(e){if(!(this._flags&m)){if(e===re){this._onLifecycleSignal?.(e),this.complete();return}e===P&&(this._value=this._initial,this._flags&=~I),this._onLifecycleSignal?.(e),e===P&&this.emit(this._initial)}}source(e,i){if(e===h){let n=i;if(this._flags&m)if(this._flags&be&&this._output===null)this._flags=this._flags&~(m|T)|Z;else{n(h,r=>{}),n(g);return}if(this._output===null)this._output=n;else if(this._flags&E)this._output.add(n);else{let r=new Set;r.add(this._output),r.add(n),this._output=r,this._flags=(this._flags|E)&~k}let s=!1;n(h,(r,a)=>{if(r===_&&n(_,this._value),r===S){a===le&&!s?(s=!0,this._singleDepCount++,this._flags&E||(this._flags|=k)):ue(a)&&this._handleLifecycleSignal(a);return}if(r===g){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&E){let l=this._output;l.delete(n),l.size===1?(this._output=l.values().next().value,this._flags&=~E,this._singleDepCount>0&&(this._flags|=k)):l.size===0&&(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._flags=this._flags&~T|Z,this._stop())}else this._output===n&&(this._output=null,this._flags&=~k,this._singleDepCount=0,this._flags=this._flags&~T|Z,this._stop())}}),me(()=>this._start())}}};function Q(t,e){return new F(t,e)}var ae=class extends F{constructor(e,i){super(void 0,{initial:e,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),A.register(this,{kind:"state",...i})}get(){return this._value}set(e){this._flags&m||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&($()?this._flags&I||(this._flags|=I,this._flags&N&&(this._flags=this._flags&~T|C,this._dispatch(S,D)),z(()=>{this._flags&=~I,this._flags=this._flags&~T|W,this._dispatch(_,this._value)})):(this._flags&N&&!(this._flags&k)&&(this._flags=this._flags&~T|C,this._dispatch(S,D)),this._flags=this._flags&~T|W,this._dispatch(_,this._value))))}update(e){this.set(e(this._value))}};function K(t,e){return new ae(t,e)}function ve(t,e,i){let n=null;Se(),t.source(h,(r,a)=>{if(r===h&&(n=a),r===g){n=null,i?.onEnd?.(a);return}if(r===1){let l=a,u=s;s=l,e(l,u)}});let s;try{s=t.get()}catch{}return _e(),{unsubscribe(){n?.(g),n=null},signal(r){n?.(S,r)}}}function Ee(t,e){let i=e?.initialStatus??"pending",n=K(i,{name:"withStatus:status",equals:Object.is}),s=K(void 0,{name:"withStatus:error",equals:Object.is}),r=Q(({emit:l,complete:u,error:f})=>{n.set(i),s.set(void 0);let o=ve(t,c=>{n.get()==="errored"?j(()=>{s.set(void 0),n.set("active")}):n.set("active"),l(c)},{onEnd:c=>{if(c!==void 0){let d=c instanceof Error?c:new Error(String(c));j(()=>{s.set(d),n.set("errored")}),f(c)}else n.set("completed"),u()}});return()=>{o.unsubscribe()}},{initial:t.get(),resubscribable:!0}),a={get:()=>t.get(),source:(l,u)=>r.source(l,u),get _status(){return r._status},status:n,error:s};return A.register(a,{kind:"withStatus"}),a}function Me(t,e){let i=e?.name??"http",n=e?.method??"GET",s=e?.headers,r=e?.body,a=e?.poll??0,l=e?.transform??(w=>w.json()),u=e?.timeout??3e4,f=K(0,{name:`${i}:fetchCount`}),o=null,c=null,d=null,p=null,y=null,b=!1;async function V(){if(!b||!o)return;y=new AbortController;let w=[y.signal];e?.signal&&w.push(e.signal);let O=new AbortController;for(let v of w){if(v.aborted){O.abort(v.reason);break}v.addEventListener("abort",()=>O.abort(v.reason),{once:!0})}let ee=setTimeout(()=>O.abort(new Error("Request timeout")),u);try{let v=r!==void 0?typeof r=="string"?r:JSON.stringify(r):void 0,L=await fetch(t,{method:n,headers:s,body:v,signal:O.signal});if(!b)return;if(!L.ok)throw new Error(`HTTP ${L.status}: ${L.statusText}`);let ke=await l(L);if(!b)return;j(()=>{f.update(xe=>xe+1),o?.(ke)})}catch(v){if(!b||v?.name==="AbortError")return;c?.(v)}finally{clearTimeout(ee),y=null}}function U(){!b||x||a<=0||(p=setTimeout(()=>{p=null,V().then(()=>{b&&!x&&U()}).catch(()=>{})},a))}let X=null,x=!1,De=Q(({emit:w,error:O,complete:ee,onSignal:v})=>(o=w,c=O,d=ee,b=!0,x=!1,X=()=>{V()},v(L=>{L===se?(x=!0,p!==null&&(clearTimeout(p),p=null)):L===ie?(x=!1,U()):L===P&&(y?.abort(),y=null,p!==null&&(clearTimeout(p),p=null),f.set(0),x=!1,V().then(()=>{b&&!x&&U()}))}),V().then(()=>{b&&!x&&U()}),()=>{b=!1,x=!1,o=null,c=null,d=null,X=null,y?.abort(),y=null,p!==null&&(clearTimeout(p),p=null)}),{name:i,kind:"http"}),Y=Ee(De);return{get:()=>Y.get(),source:(w,O)=>Y.source(w,O),status:Y.status,error:Y.error,fetchCount:f,refetch(){X?.()},stop(){b=!1,y?.abort(),y=null,p!==null&&(clearTimeout(p),p=null),d?.()}}}0&&(module.exports={fromHTTP});
|
package/dist/adapters/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../chunk-
|
|
1
|
+
import{a}from"../chunk-ZDGVUX5G.js";import"../chunk-5LLYKN4X.js";import"../chunk-GMLWTZFM.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{a as fromHTTP};
|
package/dist/adapters/index.cjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var Ue=Object.create;var
|
|
2
|
-
`)}static _signalLabel(
|
|
3
|
-
`)}static toD2(
|
|
4
|
-
`)}static annotate(t,r){if(!e.enabled)return;e._annotations.set(t,r);let n={node:e._resolveKey(t),reason:r,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(n):(e._traceLog[e._traceHead]=n,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var ce=1,N=64,W=2,Y=4,Pe=8,Ae=16,q=32,U=1024,L=he,J=ve<<H,X=ke<<H,fe=_e<<H,Ge=we<<H,Qe=xe<<H,Ze=Ee<<H,ee=class{_value;_output=null;_flags;get _status(){return Re(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(t,r){this._value=r?.initial,this._fn=t,this._eqFn=r?.equals,this._getterFn=r?.getter,this._initial=r?.initial;let n=0;r?.autoDirty!==!1&&(n|=Y),r?.resetOnTeardown&&(n|=Pe),r?.resubscribable&&(n|=Ae),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),r?._skipInspect||A.register(this,{kind:"producer",...r})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,r){let n=this._output;if(n)if(this._flags&N)for(let o of n)o(t,r);else n(t,r)}emit(t){this._flags&W||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(le()?this._flags&q||(this._flags|=q,this._flags&Y&&(this._flags=this._flags&~L|J,this._dispatch($,I)),ue(()=>{this._flags&=~q,this._flags=this._flags&~L|X,this._dispatch(F,this._value)})):(this._flags&Y&&!(this._flags&U)&&(this._flags=this._flags&~L|J,this._dispatch($,I)),this._flags=this._flags&~L|X,this._dispatch(F,this._value))))}signal(t){this._flags&W||!this._output||(t===I?this._flags=this._flags&~L|J:t===Z&&(this._flags=this._flags&~L|Ze),this._dispatch($,t))}complete(){if(this._flags&W)return;this._flags=(this._flags|W)&~L|Ge;let t=this._output,r=this._flags&N;if(this._output=null,this._flags&=~(N|U),this._singleDepCount=0,this._stop(),t)if(r)for(let n of t)n(R);else t(R)}error(t){if(this._flags&W)return;this._flags=(this._flags|W)&~L|Qe;let r=this._output,n=this._flags&N;if(this._output=null,this._flags&=~(N|U),this._singleDepCount=0,this._stop(),r)if(n)for(let o of r)o(R,t);else r(R,t)}_start(){if(this._flags&ce||!this._fn)return;this._flags|=ce,this._onLifecycleSignal=void 0;let t=this._fn({emit:this.emit,signal:r=>this.signal(r),complete:()=>this.complete(),error:r=>this.error(r),onSignal:r=>{this._onLifecycleSignal=r}});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&ce&&(this._flags&=~ce,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Pe&&(this._value=this._initial),this._flags&W||(this._flags=this._flags&~L|fe))}_handleLifecycleSignal(t){if(!(this._flags&W)){if(t===me){this._onLifecycleSignal?.(t),this.complete();return}t===j&&(this._value=this._initial,this._flags&=~q),this._onLifecycleSignal?.(t),t===j&&this.emit(this._initial)}}source(t,r){if(t===C){let n=r;if(this._flags&W)if(this._flags&Ae&&this._output===null)this._flags=this._flags&~(W|L)|fe;else{n(C,s=>{}),n(R);return}if(this._output===null)this._output=n;else if(this._flags&N)this._output.add(n);else{let s=new Set;s.add(this._output),s.add(n),this._output=s,this._flags=(this._flags|N)&~U}let o=!1;n(C,(s,l)=>{if(s===F&&n(F,this._value),s===$){l===be&&!o?(o=!0,this._singleDepCount++,this._flags&N||(this._flags|=U)):ye(l)&&this._handleLifecycleSignal(l);return}if(s===R){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&N){let a=this._output;a.delete(n),a.size===1?(this._output=a.values().next().value,this._flags&=~N,this._singleDepCount>0&&(this._flags|=U)):a.size===0&&(this._output=null,this._flags&=~(N|U),this._singleDepCount=0,this._flags=this._flags&~L|fe,this._stop())}else this._output===n&&(this._output=null,this._flags&=~U,this._singleDepCount=0,this._flags=this._flags&~L|fe,this._stop())}}),Ce(()=>this._start())}}};function B(e,t){return new ee(e,t)}var Se=class extends ee{constructor(t,r){super(void 0,{initial:t,autoDirty:!0,equals:r?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),A.register(this,{kind:"state",...r})}get(){return this._value}set(t){this._flags&W||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(le()?this._flags&q||(this._flags|=q,this._flags&Y&&(this._flags=this._flags&~L|J,this._dispatch($,I)),ue(()=>{this._flags&=~q,this._flags=this._flags&~L|X,this._dispatch(F,this._value)})):(this._flags&Y&&!(this._flags&U)&&(this._flags=this._flags&~L|J,this._dispatch($,I)),this._flags=this._flags&~L|X,this._dispatch(F,this._value))))}update(t){this.set(t(this._value))}};function k(e,t){return new Se(e,t)}function G(e,t,r){let n=null;Le(),e.source(C,(s,l)=>{if(s===C&&(n=l),s===R){n=null,r?.onEnd?.(l);return}if(s===1){let a=l,c=o;o=a,t(a,c)}});let o;try{o=e.get()}catch{}return De(),{unsubscribe(){n?.(R),n=null},signal(s){n?.($,s)}}}function Q(e,t){let r=t?.initialStatus??"pending",n=k(r,{name:"withStatus:status",equals:Object.is}),o=k(void 0,{name:"withStatus:error",equals:Object.is}),s=B(({emit:a,complete:c,error:f})=>{n.set(r),o.set(void 0);let i=G(e,u=>{n.get()==="errored"?P(()=>{o.set(void 0),n.set("active")}):n.set("active"),a(u)},{onEnd:u=>{if(u!==void 0){let g=u instanceof Error?u:new Error(String(u));P(()=>{o.set(g),n.set("errored")}),f(u)}else n.set("completed"),c()}});return()=>{i.unsubscribe()}},{initial:e.get(),resubscribable:!0}),l={get:()=>e.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},status:n,error:o};return A.register(l,{kind:"withStatus"}),l}function Oe(e,t){let r=t?.name??"http",n=t?.method??"GET",o=t?.headers,s=t?.body,l=t?.poll??0,a=t?.transform??(w=>w.json()),c=t?.timeout??3e4,f=k(0,{name:`${r}:fetchCount`}),i=null,u=null,g=null,m=null,b=null,T=!1;async function x(){if(!T||!i)return;b=new AbortController;let w=[b.signal];t?.signal&&w.push(t.signal);let _=new AbortController;for(let E of w){if(E.aborted){_.abort(E.reason);break}E.addEventListener("abort",()=>_.abort(E.reason),{once:!0})}let v=setTimeout(()=>_.abort(new Error("Request timeout")),c);try{let E=s!==void 0?typeof s=="string"?s:JSON.stringify(s):void 0,D=await fetch(e,{method:n,headers:o,body:E,signal:_.signal});if(!T)return;if(!D.ok)throw new Error(`HTTP ${D.status}: ${D.statusText}`);let M=await a(D);if(!T)return;P(()=>{f.update(O=>O+1),i?.(M)})}catch(E){if(!T||E?.name==="AbortError")return;u?.(E)}finally{clearTimeout(v),b=null}}function h(){!T||p||l<=0||(m=setTimeout(()=>{m=null,x().then(()=>{T&&!p&&h()}).catch(()=>{})},l))}let d=null,p=!1,S=B(({emit:w,error:_,complete:v,onSignal:E})=>(i=w,u=_,g=v,T=!0,p=!1,d=()=>{x()},E(D=>{D===K?(p=!0,m!==null&&(clearTimeout(m),m=null)):D===z?(p=!1,h()):D===j&&(b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null),f.set(0),p=!1,x().then(()=>{T&&!p&&h()}))}),x().then(()=>{T&&!p&&h()}),()=>{T=!1,p=!1,i=null,u=null,g=null,d=null,b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null)}),{name:r,kind:"http"}),y=Q(S);return{get:()=>y.get(),source:(w,_)=>y.source(w,_),status:y.status,error:y.error,fetchCount:f,refetch(){d?.()},stop(){T=!1,b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null),g?.()}}}function Xe(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function et(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function tt(e,t,r,n){let o={model:t,messages:r,stream:!0};return n?.temperature!==void 0&&(o.temperature=n.temperature),n?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:n.maxTokens}:o.max_tokens=n.maxTokens),n?.stop&&(o.stop=n.stop),o}function nt(e,t){let r={"Content-Type":"application/json"};return t&&(r.Authorization=`Bearer ${t}`),r}function Me(e){let t=e.name??"llm",r=e.provider,n=e.baseURL??Xe(r),o=e.model??"",s=e.fetch??globalThis.fetch,l=k("",{name:`${t}.store`}),a=k({},{name:`${t}.tokens`}),c=k("pending",{name:`${t}.status`}),f=k(void 0,{name:`${t}.error`}),i=null;function u(){i&&(i.abort(),i=null),c.get()==="active"&&P(()=>{l.set(""),c.set("pending")})}function g(b,T){u(),i=new AbortController;let x=T?.signal?st(i.signal,T.signal):i.signal;P(()=>{l.set(""),a.set({}),f.set(void 0),c.set("active")});let h=et(r,n),d=tt(r,o,b,T),p=nt(r,e.apiKey);m(h,p,d,x).catch(()=>{})}async function m(b,T,x,h){try{let d=await s(b,{method:"POST",headers:T,body:JSON.stringify(x),signal:h});if(!d.ok){let _=await d.text().catch(()=>"");throw new Error(`LLM API error ${d.status}: ${_}`)}let p=d.body?.getReader();if(!p)throw new Error("No response body");let S=new TextDecoder,y="",w="";for(;;){if(h.aborted)return;let{done:_,value:v}=await p.read();if(_)break;w+=S.decode(v,{stream:!0});let E=w.split(`
|
|
5
|
-
`);w=E.pop()??"";for(let
|
|
6
|
-
`),E=new Error(v||"MCP tool returned error");
|
|
1
|
+
"use strict";var Ue=Object.create;var oe=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,qe=Object.prototype.hasOwnProperty;var Ke=(t,e)=>{for(var r in e)oe(t,r,{get:e[r],enumerable:!0})},Te=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of He(e))!qe.call(t,o)&&o!==r&&oe(t,o,{get:()=>e[o],enumerable:!(n=Be(e,o))||n.enumerable});return t};var ze=(t,e,r)=>(r=t!=null?Ue(Ve(t)):{},Te(e||!t||!t.__esModule?oe(r,"default",{value:t,enumerable:!0}):r,t)),Ye=t=>Te(oe({},"__esModule",{value:!0}),t);var it={};Ke(it,{fromHTTP:()=>Ae,fromLLM:()=>Me,fromMCP:()=>$e,fromWebSocket:()=>je,fromWebhook:()=>Ie,toSSE:()=>Ne,toWebSocket:()=>Fe});module.exports=Ye(it);var j=Symbol("DIRTY"),X=Symbol("RESOLVED"),be=Symbol("SINGLE_DEP"),F=Symbol("RESET"),q=Symbol("PAUSE"),K=Symbol("RESUME"),me=Symbol("TEARDOWN");function ye(t){return t===F||t===q||t===K||t===me}var _e=0,ve=1,ke=2,Ee=3,we=4,xe=5,B=7,he=7<<B,Je=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Re(t){return Je[(t&he)>>>B]}var D=0,W=1,x=2,M=3,se=0,ie=[],ge=!1;function O(t){se++;try{return t()}finally{if(se--,se===0&&!ge){ge=!0;for(let e=0;e<ie.length;e++)ie[e]();ie.length=0,ge=!1}}}function z(){return se>0}function le(t){ie.push(t)}var ue=0,ae=[];function De(){ue++}function Le(){if(ue--,ue===0){for(let t=0;t<ae.length;t++)ae[t]();ae.length=0}}function Ce(t){ue>0?ae.push(t):t()}var P=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(o=>t._names.get(o)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let r=t._keys.get(e)??t._names.get(e);if(r)return r;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,r){if(!t.enabled)return;r?.name&&t._names.set(e,r.name),r?.kind&&t._kinds.set(e,r.kind);let n=t._nextId++,o=r?.name;if(!(o&&!t._usedKeys.has(o)))if(o){let s=t._depSuffix(r?.deps);o=s?`${o}(${s})`:`${o}_${n}`,t._usedKeys.has(o)&&(o=`${o}_${n}`)}else{let s=r?.kind??"store",u=t._depSuffix(r?.deps);o=u?`${s}(${u})`:`${s}_${n}`,t._usedKeys.has(o)&&(o=`${o}_${n}`)}t._usedKeys.add(o),t._keys.set(e,o),t._stores.add(new WeakRef(e))}static registerEdge(e,r){if(!t.enabled)return;let n=t._resolveKey(e),o=t._resolveKey(r),s=t._edges.get(n);s?s.includes(o)||s.push(o):t._edges.set(n,[o])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,r=new Set;for(let n of t._stores){let o=n.deref();if(!o){t._stores.delete(n);continue}let s=t._resolveKey(o);r.add(s),e.set(s,t.inspect(o))}for(let[n,o]of t._edges){if(!r.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let s=o.filter(u=>r.has(u));s.length===0?t._edges.delete(n):s.length!==o.length&&t._edges.set(n,s)}return e}static trace(e,r){let n=null,o=e.get();return e.source(D,(s,u)=>{if(s===D&&(n=u),s===x){n=null;return}if(s===1){let a=u;if(!Object.is(a,o)){let c=o;o=a,r(a,c)}}}),()=>n?.(x)}static dumpGraph(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let[u,a]of r)for(let c of a){let f=n.get(c);f?f.includes(u)||f.push(u):n.set(c,[u])}let o=[];for(let[u,a]of e){let c=n.get(u),f=r.get(u),i=c?.length?` \u2190 [${c.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";o.push(` ${u} (${a.kind}) = ${JSON.stringify(a.value)} [${a.status??"?"}]${i}${l}`)}return[`Store Graph (${e.size} nodes):`,...o].join(`
|
|
2
|
+
`)}static _signalLabel(e){return e===j?"DIRTY":e===X?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,r,n){let o=null,s=!1,u=r??t.getName(e),a=[],c={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return c.ended&&!s},get errored(){return c.ended&&s},dirtyCount:0,resolvedCount:0,name:u,get eventLog(){return a},dispose:()=>o?.(x),reconnect:()=>(o?.(x),t._observe(e,r,n))};return e.source(D,(f,i)=>{if(f===D){o=i;return}let l=z();f===W?(c.values.push(i),c.events.push({type:"data",data:i,inBatch:l}),a.push(i),n&&n(`[${u}] DATA:`,i)):f===M?(c.signals.push(i),c.events.push({type:"signal",data:i,inBatch:l}),a.push(t._signalLabel(i)),i===j?c.dirtyCount++:i===X&&c.resolvedCount++,n&&n(`[${u}] STATE:`,i)):f===x&&(c.ended=!0,c.endError=i,s=i!==void 0,c.events.push({type:"end",data:i,inBatch:l}),a.push(s?["END",i]:"END"),n&&n(`[${u}] END`,i!==void 0?i:""),o=null)}),c}static observe(e){return t._observe(e)}static activate(e){let r=null;return e.source(D,(n,o)=>{n===D&&(r=o),n===x&&(r=null)}),()=>r?.(x)}static tap(e,r){let n=r??`tap(${t.getName(e)??"anon"})`,o={get:()=>e.get(),source:e.source};return t.register(o,{name:n,kind:"tap"}),t.registerEdge(e,o),o}static spy(e,r){let n=r?.name??t.getName(e)??"spy",o=r?.log??console.log;return t._observe(e,n,o)}static snapshot(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let u of t._stores){let a=u.deref();if(!a)continue;let c=t._annotations.get(a);c!==void 0&&n.set(t._resolveKey(a),c)}let o=[];for(let[u,a]of e){let c={name:u,kind:a.kind,value:a.value,status:a.status},f=n.get(u);f!==void 0&&(c.annotation=f),o.push(c)}let s=[];for(let[u,a]of r)for(let c of a)s.push({from:u,to:c});return{nodes:o,edges:s,trace:t.traceLog()}}static toMermaid(e){let r=e?.direction??"TD",n=t.snapshot(),o=[`graph ${r}`],s={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},u=new Map;function a(i){let l=i.replace(/[^a-zA-Z0-9_]/g,"_"),g=u.get(l);return g===void 0?(u.set(l,1),l):(u.set(l,g+1),`${l}__${g}`)}let c=new Map;function f(i){let l=JSON.stringify(i);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let i of n.nodes){let l=a(i.name);c.set(i.name,l);let g=`${i.name} (${i.kind}) = ${f(i.value)}`,m=s[i.status??""]??"";o.push(` ${l}["${g}"]${m}`)}for(let i of n.edges){let l=c.get(i.from)??a(i.from),g=c.get(i.to)??a(i.to);o.push(` ${l} --> ${g}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
|
|
3
|
+
`)}static toD2(e){let r=e?.direction??"down",n=t.snapshot(),o=[`direction: ${r}`,""],s={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},u=new Map;function a(i){let l=i.replace(/[^a-zA-Z0-9_]/g,"_"),g=u.get(l);return g===void 0?(u.set(l,1),l):(u.set(l,g+1),`${l}__${g}`)}let c=new Map;function f(i){let l=JSON.stringify(i);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let i of n.nodes){let l=a(i.name);c.set(i.name,l);let g=s[i.kind]??"rectangle",m=`${i.name} (${i.kind}) = ${f(i.value)}`,b=i.status?` [${i.status}]`:"";o.push(`${l}: "${m}${b}" { shape: ${g} }`)}n.edges.length>0&&o.push("");for(let i of n.edges){let l=c.get(i.from)??a(i.from),g=c.get(i.to)??a(i.to);o.push(`${l} -> ${g}`)}return o.join(`
|
|
4
|
+
`)}static annotate(e,r){if(!t.enabled)return;t._annotations.set(e,r);let n={node:t._resolveKey(e),reason:r,timestamp:Date.now()},o=t.maxTraceEntries;o<=0||(t._traceLog.length<o?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%o)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static timeline(e){let r=null,n=[];return e.source(D,(o,s)=>{if(o===D){r=s;return}let u={timestamp:Date.now(),type:o===W?"data":o===M?"signal":"end",data:s,inBatch:z()};n.push(u),o===x&&(r=null)}),{entries:n,dispose:()=>r?.(x)}}static observeDerived(e){let r=[],n=e,o=n._fn;if(typeof o!="function"||!Array.isArray(n._deps))return{...t.observe(e),evaluations:r};n._fn=()=>{let c=n._deps.map(i=>i.get()),f=o();return r.push({result:f,depValues:c,timestamp:Date.now()}),f};let s=t._observe(e),u=s.dispose;return{...s,evaluations:r,dispose:()=>{n._fn=o,u()},reconnect:()=>(n._fn=o,u(),t.observeDerived(e))}}static observeTaskState(e){let r=e.status.get(),n=[],o=null;return e.status.source(D,(s,u)=>{if(s===D){o=u;return}if(s===W){let a=u;if(a!==r){let c={from:r,to:a,timestamp:Date.now()};a==="error"&&(c.error=e.error.get()),n.push(c),r=a}}s===x&&(o=null)}),{transitions:n,get currentStatus(){return e.status.get()},dispose:()=>{o?.(x)}}}static causalityTrace(e){let r=[],n=e,o=n._fn;if(typeof o!="function"||!Array.isArray(n._deps))return{...t.observe(e),causality:r};let s=n._deps,u=s.map(i=>i.get());n._fn=()=>{let i=s.map(m=>m.get()),l=o(),g=-1;for(let m=0;m<s.length;m++)if(!Object.is(i[m],u[m])){g=m;break}return r.push({result:l,triggerDepIndex:g,triggerDepName:g>=0?t.getName(s[g]):void 0,depValues:i,timestamp:Date.now()}),u=i,l};let a=t._observe(e),c=a.dispose;return{...a,causality:r,dispose:()=>{n._fn=o,c()},reconnect:()=>(n._fn=o,c(),t.causalityTrace(e))}}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var ce=1,I=64,N=2,J=4,Oe=8,Pe=16,H=32,U=1024,L=he,G=ve<<B,ee=ke<<B,fe=_e<<B,Ge=we<<B,Qe=xe<<B,Ze=Ee<<B,te=class{_value;_output=null;_flags;get _status(){return Re(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,r){this._value=r?.initial,this._fn=e,this._eqFn=r?.equals,this._getterFn=r?.getter,this._initial=r?.initial;let n=0;r?.autoDirty!==!1&&(n|=J),r?.resetOnTeardown&&(n|=Oe),r?.resubscribable&&(n|=Pe),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),r?._skipInspect||P.register(this,{kind:"producer",...r})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,r){let n=this._output;if(n)if(this._flags&I)for(let o of n)o(e,r);else n(e,r)}emit(e){this._flags&N||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(z()?this._flags&H||(this._flags|=H,this._flags&J&&(this._flags=this._flags&~L|G,this._dispatch(M,j)),le(()=>{this._flags&=~H,this._flags=this._flags&~L|ee,this._dispatch(W,this._value)})):(this._flags&J&&!(this._flags&U)&&(this._flags=this._flags&~L|G,this._dispatch(M,j)),this._flags=this._flags&~L|ee,this._dispatch(W,this._value))))}signal(e){this._flags&N||!this._output||(e===j?this._flags=this._flags&~L|G:e===X&&(this._flags=this._flags&~L|Ze),this._dispatch(M,e))}complete(){if(this._flags&N)return;this._flags=(this._flags|N)&~L|Ge;let e=this._output,r=this._flags&I;if(this._output=null,this._flags&=~(I|U),this._singleDepCount=0,this._stop(),e)if(r)for(let n of e)n(x);else e(x)}error(e){if(this._flags&N)return;this._flags=(this._flags|N)&~L|Qe;let r=this._output,n=this._flags&I;if(this._output=null,this._flags&=~(I|U),this._singleDepCount=0,this._stop(),r)if(n)for(let o of r)o(x,e);else r(x,e)}_start(){if(this._flags&ce||!this._fn)return;this._flags|=ce,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:r=>this.signal(r),complete:()=>this.complete(),error:r=>this.error(r),onSignal:r=>{this._onLifecycleSignal=r}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ce&&(this._flags&=~ce,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Oe&&(this._value=this._initial),this._flags&N||(this._flags=this._flags&~L|fe))}_handleLifecycleSignal(e){if(!(this._flags&N)){if(e===me){this._onLifecycleSignal?.(e),this.complete();return}e===F&&(this._value=this._initial,this._flags&=~H),this._onLifecycleSignal?.(e),e===F&&this.emit(this._initial)}}source(e,r){if(e===D){let n=r;if(this._flags&N)if(this._flags&Pe&&this._output===null)this._flags=this._flags&~(N|L)|fe;else{n(D,s=>{}),n(x);return}if(this._output===null)this._output=n;else if(this._flags&I)this._output.add(n);else{let s=new Set;s.add(this._output),s.add(n),this._output=s,this._flags=(this._flags|I)&~U}let o=!1;n(D,(s,u)=>{if(s===W&&n(W,this._value),s===M){u===be&&!o?(o=!0,this._singleDepCount++,this._flags&I||(this._flags|=U)):ye(u)&&this._handleLifecycleSignal(u);return}if(s===x){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&I){let a=this._output;a.delete(n),a.size===1?(this._output=a.values().next().value,this._flags&=~I,this._singleDepCount>0&&(this._flags|=U)):a.size===0&&(this._output=null,this._flags&=~(I|U),this._singleDepCount=0,this._flags=this._flags&~L|fe,this._stop())}else this._output===n&&(this._output=null,this._flags&=~U,this._singleDepCount=0,this._flags=this._flags&~L|fe,this._stop())}}),Ce(()=>this._start())}}};function V(t,e){return new te(t,e)}var Se=class extends te{constructor(e,r){super(void 0,{initial:e,autoDirty:!0,equals:r?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),P.register(this,{kind:"state",...r})}get(){return this._value}set(e){this._flags&N||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(z()?this._flags&H||(this._flags|=H,this._flags&J&&(this._flags=this._flags&~L|G,this._dispatch(M,j)),le(()=>{this._flags&=~H,this._flags=this._flags&~L|ee,this._dispatch(W,this._value)})):(this._flags&J&&!(this._flags&U)&&(this._flags=this._flags&~L|G,this._dispatch(M,j)),this._flags=this._flags&~L|ee,this._dispatch(W,this._value))))}update(e){this.set(e(this._value))}};function k(t,e){return new Se(t,e)}function Q(t,e,r){let n=null;De(),t.source(D,(s,u)=>{if(s===D&&(n=u),s===x){n=null,r?.onEnd?.(u);return}if(s===1){let a=u,c=o;o=a,e(a,c)}});let o;try{o=t.get()}catch{}return Le(),{unsubscribe(){n?.(x),n=null},signal(s){n?.(M,s)}}}function Z(t,e){let r=e?.initialStatus??"pending",n=k(r,{name:"withStatus:status",equals:Object.is}),o=k(void 0,{name:"withStatus:error",equals:Object.is}),s=V(({emit:a,complete:c,error:f})=>{n.set(r),o.set(void 0);let i=Q(t,l=>{n.get()==="errored"?O(()=>{o.set(void 0),n.set("active")}):n.set("active"),a(l)},{onEnd:l=>{if(l!==void 0){let g=l instanceof Error?l:new Error(String(l));O(()=>{o.set(g),n.set("errored")}),f(l)}else n.set("completed"),c()}});return()=>{i.unsubscribe()}},{initial:t.get(),resubscribable:!0}),u={get:()=>t.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},status:n,error:o};return P.register(u,{kind:"withStatus"}),u}function Ae(t,e){let r=e?.name??"http",n=e?.method??"GET",o=e?.headers,s=e?.body,u=e?.poll??0,a=e?.transform??(w=>w.json()),c=e?.timeout??3e4,f=k(0,{name:`${r}:fetchCount`}),i=null,l=null,g=null,m=null,b=null,T=!1;async function R(){if(!T||!i)return;b=new AbortController;let w=[b.signal];e?.signal&&w.push(e.signal);let _=new AbortController;for(let E of w){if(E.aborted){_.abort(E.reason);break}E.addEventListener("abort",()=>_.abort(E.reason),{once:!0})}let v=setTimeout(()=>_.abort(new Error("Request timeout")),c);try{let E=s!==void 0?typeof s=="string"?s:JSON.stringify(s):void 0,C=await fetch(t,{method:n,headers:o,body:E,signal:_.signal});if(!T)return;if(!C.ok)throw new Error(`HTTP ${C.status}: ${C.statusText}`);let $=await a(C);if(!T)return;O(()=>{f.update(A=>A+1),i?.($)})}catch(E){if(!T||E?.name==="AbortError")return;l?.(E)}finally{clearTimeout(v),b=null}}function h(){!T||p||u<=0||(m=setTimeout(()=>{m=null,R().then(()=>{T&&!p&&h()}).catch(()=>{})},u))}let d=null,p=!1,S=V(({emit:w,error:_,complete:v,onSignal:E})=>(i=w,l=_,g=v,T=!0,p=!1,d=()=>{R()},E(C=>{C===q?(p=!0,m!==null&&(clearTimeout(m),m=null)):C===K?(p=!1,h()):C===F&&(b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null),f.set(0),p=!1,R().then(()=>{T&&!p&&h()}))}),R().then(()=>{T&&!p&&h()}),()=>{T=!1,p=!1,i=null,l=null,g=null,d=null,b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null)}),{name:r,kind:"http"}),y=Z(S);return{get:()=>y.get(),source:(w,_)=>y.source(w,_),status:y.status,error:y.error,fetchCount:f,refetch(){d?.()},stop(){T=!1,b?.abort(),b=null,m!==null&&(clearTimeout(m),m=null),g?.()}}}function Xe(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function et(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function tt(t,e,r,n){let o={model:e,messages:r,stream:!0};return n?.temperature!==void 0&&(o.temperature=n.temperature),n?.maxTokens!==void 0&&(t==="ollama"?o.options={num_predict:n.maxTokens}:o.max_tokens=n.maxTokens),n?.stop&&(o.stop=n.stop),o}function nt(t,e){let r={"Content-Type":"application/json"};return e&&(r.Authorization=`Bearer ${e}`),r}function Me(t){let e=t.name??"llm",r=t.provider,n=t.baseURL??Xe(r),o=t.model??"",s=t.fetch??globalThis.fetch,u=k("",{name:`${e}.store`}),a=k({},{name:`${e}.tokens`}),c=k("pending",{name:`${e}.status`}),f=k(void 0,{name:`${e}.error`}),i=null;function l(){i&&(i.abort(),i=null),c.get()==="active"&&O(()=>{u.set(""),c.set("pending")})}function g(b,T){l(),i=new AbortController;let R=T?.signal?st(i.signal,T.signal):i.signal;O(()=>{u.set(""),a.set({}),f.set(void 0),c.set("active")});let h=et(r,n),d=tt(r,o,b,T),p=nt(r,t.apiKey);m(h,p,d,R).catch(()=>{})}async function m(b,T,R,h){try{let d=await s(b,{method:"POST",headers:T,body:JSON.stringify(R),signal:h});if(!d.ok){let _=await d.text().catch(()=>"");throw new Error(`LLM API error ${d.status}: ${_}`)}let p=d.body?.getReader();if(!p)throw new Error("No response body");let S=new TextDecoder,y="",w="";for(;;){if(h.aborted)return;let{done:_,value:v}=await p.read();if(_)break;w+=S.decode(v,{stream:!0});let E=w.split(`
|
|
5
|
+
`);w=E.pop()??"";for(let C of E){if(h.aborted)return;let $=C.trim();if(!$||$.startsWith(":")||!$.startsWith("data: "))continue;let A=$.slice(6);if(A!=="[DONE]")try{let ne=JSON.parse(A),Y=rt(r,ne);Y&&(y+=Y,u.set(y));let re=ot(r,ne);re&&a.set(re)}catch{}}}if(S.decode(),h.aborted)return;c.set("completed"),i=null}catch(d){if(h.aborted)return;O(()=>{f.set(d),c.set("errored")}),i=null}finally{h._cleanup?.()}}return{get:()=>u.get(),source:(b,T)=>u.source(b,T),tokens:a,status:c,error:f,generate:g,abort:l}}function rt(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function ot(t,e){let r=t==="ollama"?e:e?.usage;if(r){if(t==="ollama")return e.eval_count!==void 0||e.prompt_eval_count!==void 0?{promptTokens:e.prompt_eval_count,completionTokens:e.eval_count,totalTokens:(e.prompt_eval_count??0)+(e.eval_count??0)}:void 0;if(r.prompt_tokens!==void 0||r.completion_tokens!==void 0)return{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}}}function st(t,e){let r=new AbortController,n=()=>{t.removeEventListener("abort",o),e.removeEventListener("abort",o)},o=()=>{r.abort(),n()};t.addEventListener("abort",o,{once:!0}),e.addEventListener("abort",o,{once:!0});let s=r.signal;return s._cleanup=n,s}function $e(t){let e=t.name??"mcp",r=t.client,n=k([],{name:`${e}.tools`}),o=k([],{name:`${e}.resources`}),s=k(void 0,{name:`${e}.refreshError`});function u(f){s.set(f);let i=t.onRefreshError;if(i==="warn")console.warn(`[${e}] refresh error:`,f);else{if(i==="error")throw f;typeof i=="function"&&i(f)}}async function a(){if(s.set(void 0),r.listTools)try{let f=await r.listTools();n.set(f.tools)}catch(f){u(f)}if(r.listResources)try{let f=await r.listResources();o.set(f.resources)}catch(f){u(f)}}function c(f){let i=`${e}:${f}`,l=k(void 0,{name:`${i}.result`}),g=k("idle",{name:`${i}.status`}),m=k(void 0,{name:`${i}.error`}),b=k(void 0,{name:`${i}.lastArgs`}),T=k(void 0,{name:`${i}.duration`}),R=!1;async function h(d){if(R)return;R=!0,O(()=>{b.set(d),m.set(void 0),g.set("active")});let p=Date.now();try{let S=await r.callTool({name:f,arguments:d}),y=Date.now()-p;if(S.isError){let v=S.content.filter(C=>C.type==="text").map(C=>C.text??"").join(`
|
|
6
|
+
`),E=new Error(v||"MCP tool returned error");O(()=>{T.set(y),m.set(E),g.set("errored")});return}let w=S.content.filter(v=>v.type==="text"),_;if(w.length===1){let v=w[0].text;if(v!==void 0)try{_=JSON.parse(v)}catch{_=v}}else w.length>1?_=w.map(v=>v.text??""):_=S.content;O(()=>{T.set(y),l.set(_),g.set("completed")})}catch(S){let y=Date.now()-p;O(()=>{T.set(y),m.set(S),g.set("errored")})}finally{R=!1}}return{get:()=>l.get(),source:(d,p)=>l.source(d,p),status:g,error:m,call:h,lastArgs:b,duration:T}}return{tool:c,tools:n,resources:o,refresh:a,refreshError:s}}function We(t,e,r){let n=null;return t(0,(o,s)=>{if(o===0){n=s;return}if(o===2){n=null,r?.onEnd?.(s);return}o===1&&e(s)}),{unsubscribe(){n?.(2),n=null}}}function de(t,e){return new Promise((r,n)=>{let o=We(t,s=>{(!e||e(s))&&(o.unsubscribe(),r(s))},{onEnd:s=>{n(s??new Error("source completed without matching value"))}})})}function pe(t){return(e,r)=>{if(e!==0)return;let n=!1,o;r(0,s=>{s===2&&!n&&(n=!0,o?.())});try{o=t(s=>{n||(n=!0,r(1,s),r(2))},s=>{n||(n=!0,r(2,s))})}catch(s){n||(n=!0,r(2,s))}}}function Ne(t,e){let r=e?.path??"/",n=e?.name??"sse",o=e?.hostname??"0.0.0.0",s=e?.serialize??JSON.stringify,u=e?.eventName??"message",a=e?.pingInterval??3e4,c=k(0,{name:`${n}:connections`}),f=new Set,i=new Map,l=null;function g(){l||(l=Q(t,d=>{let p=s(d),S=`event: ${u}
|
|
7
7
|
data: ${p}
|
|
8
8
|
|
|
9
|
-
`;for(let y of f)try{y.write(S)}catch{m(y)}}))}function m(d){f.delete(d);let p=i.get(d);p&&(clearInterval(p),i.delete(d)),c.set(f.size),f.size===0&&
|
|
9
|
+
`;for(let y of f)try{y.write(S)}catch{m(y)}}))}function m(d){f.delete(d);let p=i.get(d);p&&(clearInterval(p),i.delete(d)),c.set(f.size),f.size===0&&l&&(l.unsubscribe(),l=null)}function b(d,p){let S=d.method?.toUpperCase();if((d.url??"/").split("?")[0]!==r){p.writeHead(404,{"Content-Type":"text/plain"}),p.end("Not found");return}if(S==="OPTIONS"){p.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),p.end();return}if(S!=="GET"){p.writeHead(405,{"Content-Type":"text/plain"}),p.end("Method not allowed");return}p.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),p.write(`:ok
|
|
10
10
|
|
|
11
|
-
`),f.add(p),c.set(f.size);try{let _=
|
|
11
|
+
`),f.add(p),c.set(f.size);try{let _=t.get();if(_!==void 0){let v=s(_);p.write(`event: ${u}
|
|
12
12
|
data: ${v}
|
|
13
13
|
|
|
14
14
|
`)}}catch{}if(a>0){let _=setInterval(()=>{try{p.write(`:ping
|
|
15
15
|
|
|
16
|
-
`)}catch{m(p)}},a);i.set(p,_)}d.on("close",()=>m(p)),g()}let T=null;async function
|
|
16
|
+
`)}catch{m(p)}},a);i.set(p,_)}d.on("close",()=>m(p)),g()}let T=null;async function R(){if(!e?.port)throw new Error("toSSE: port is required for listen()");if(T)throw new Error("toSSE: already listening. Call close() first.");let d=await import("http");return de(pe((p,S)=>{T=d.createServer(b),T.once("listening",()=>p()),T.once("error",y=>{T=null,S(y)}),T.listen(e.port,o)}))}function h(){for(let d of f)try{d.end()}catch{}f.clear();for(let d of i.values())clearInterval(d);i.clear(),c.set(0),l?.unsubscribe(),l=null,T?.close(),T=null}return P.register(c,{kind:"sse"}),{connectionCount:c,handler:b,listen:R,close:h}}function Ie(t){let e=t?.path??"/",r=t?.parse??JSON.parse,n=t?.name??"webhook",o=t?.hostname??"0.0.0.0",s=t?.maxBodySize??1024*1024,u=t?.responseTimeout??3e4,a=k(0,{name:`${n}:count`}),c=null,f=!1,i=V(({emit:h,onSignal:d})=>(c=h,f=!1,d(p=>{p===q?f=!0:p===K?f=!1:p===F&&(f=!1,a.set(0))}),()=>{c=null,f=!1}),{name:n,kind:"webhook"});P.register(i,{kind:"webhook"});let l=Z(i),g=null,m=new Set;function b(h,d){let p=h.method?.toUpperCase(),y=(h.url??"/").split("?")[0];if(p!=="POST"||y!==e){d.writeHead(404,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:"Not found"}));return}if(f){d.writeHead(503,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:"Service paused"}));return}let w=[],_=0,v=!1;h.on("error",()=>{v=!0,d.headersSent||(d.writeHead(400,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:"Request aborted"})))}),h.on("data",E=>{if(!v){if(_+=E.length,_>s){v=!0,d.writeHead(413,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:"Payload too large"})),h.destroy?.();return}w.push(E)}}),h.on("end",()=>{if(!v)try{let E=Buffer.concat(w).toString("utf-8"),C=E.length>0?r(E):void 0;a.update(Y=>Y+1);let $=!1,A=null,ne={body:C,get responded(){return $},respond(Y,re=200){$||($=!0,A!==null&&(clearTimeout(A),m.delete(A),A=null),d.writeHead(re,{"Content-Type":"application/json"}),d.end(JSON.stringify(Y)))}};A=setTimeout(()=>{m.delete(A),A=null,$||($=!0,d.writeHead(504,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:"Response timeout"})))},u),m.add(A),c?.(ne)}catch(E){d.writeHead(400,{"Content-Type":"application/json"}),d.end(JSON.stringify({error:E?.message??"Parse error"}))}})}function T(){return t?.port?g?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):de(pe((h,d)=>{try{g=require("http").createServer(b),g.once("listening",()=>h()),g.once("error",S=>{g=null,d(S)}),g.listen(t.port,o);return}catch(p){d(p);return}})):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function R(){for(let h of m)clearTimeout(h);m.clear(),g?.close(),g=null}return{get:()=>l.get(),source:(h,d)=>l.source(h,d),status:l.status,error:l.error,requestCount:a,handler:b,listen:T,close:R}}function je(t,e){let r=e?.name??"websocket",n=e?.parse??(S=>S),o=e?.reconnect??!1,s=e?.onParseError??"warn",u=k("connecting",{name:`${r}:connectionState`,equals:()=>!1}),a=null,c=null,f=null,i=null,l=null,g=!1,m=null,b=[];function T(){for(;b.length>0&&a?.readyState===WebSocket.OPEN;)a.send(b.shift())}function R(){g=!1,u.set("connecting");try{a=new WebSocket(t,e?.protocols)}catch(S){u.set("closed"),f?.(S);return}a.onopen=()=>{u.set("open"),T()},a.onmessage=S=>{if(!h)try{let y=n(S.data);c?.(y)}catch(y){s==="error"?f?.(y):s==="warn"&&console.warn(`[${r}] parse error:`,y)}},a.onerror=()=>{m=new Error(`WebSocket error on ${t}`)},a.onclose=()=>{u.set("closed"),a=null;let S=m;m=null,!g&&o!==!1?l=setTimeout(()=>{l=null,c&&R()},o):S&&!g?f?.(S):i?.()}}let h=!1,d=V(({emit:S,error:y,complete:w,onSignal:_})=>(c=S,f=y,i=w,h=!1,R(),_(v=>{v===q?h=!0:v===K?h=!1:v===F&&(h=!1,b.length=0,l!==null&&(clearTimeout(l),l=null),a&&(g=!0,a.onopen=null,a.onmessage=null,a.onerror=null,a.onclose=null,a.close(),a=null),u.set("closed"),R())}),()=>{c=null,f=null,i=null,h=!1,g=!0,b.length=0,l!==null&&(clearTimeout(l),l=null),a&&(a.onopen=null,a.onmessage=null,a.onerror=null,a.onclose=null,a.close(),a=null),u.set("closed")}),{name:r,kind:"websocket"});P.register(d,{kind:"websocket"});let p=Z(d);return{get:()=>p.get(),source:(S,y)=>p.source(S,y),status:p.status,error:p.error,connectionState:u,send(S){a?.readyState===WebSocket.OPEN?a.send(S):b.push(S)},close(S,y){g=!0,b.length=0,l!==null&&(clearTimeout(l),l=null),a?.close(S,y)}}}function Fe(t,e,r){let n=u=>typeof u=="string"?u:JSON.stringify(u),o=r?.serialize??n,s="send"in t&&typeof t.send=="function"?t.send.bind(t):null;if(!s)throw new Error("toWebSocket: invalid WebSocket target");return Q(e,u=>{try{let a=o(u);s(a)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
|
package/dist/adapters/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"../chunk-
|
|
1
|
+
import{a as o}from"../chunk-ZDGVUX5G.js";import{a as e}from"../chunk-7WPMCM7F.js";import{a as t}from"../chunk-Q5DHO5II.js";import{a as r}from"../chunk-NYLNL2Y5.js";import{a as p}from"../chunk-JLWDE534.js";import"../chunk-XEU7KSEO.js";import"../chunk-LLARZ7J7.js";import{a as m,b as S}from"../chunk-U3FGSR3I.js";import"../chunk-5LLYKN4X.js";import"../chunk-GMLWTZFM.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
|