tekivex-ui 3.5.0 → 3.18.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 (114) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +146 -33
  3. package/dist/agent.cjs +1 -0
  4. package/dist/agent.js +17 -0
  5. package/dist/charts.cjs +1 -1
  6. package/dist/charts.js +41 -22
  7. package/dist/experimental.cjs +1 -0
  8. package/dist/experimental.js +39 -0
  9. package/dist/headless.cjs +1 -1
  10. package/dist/headless.js +55 -1
  11. package/dist/i18n.cjs +1 -1
  12. package/dist/i18n.js +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.d.ts +29 -6
  15. package/dist/index.js +694 -586
  16. package/dist/quantum.cjs +1 -1
  17. package/dist/quantum.js +59 -74
  18. package/dist/realtime.cjs +1 -1
  19. package/dist/realtime.js +1 -1
  20. package/dist/src/agent/a2a/A2AClient.d.ts +32 -0
  21. package/dist/src/agent/a2a/a2aTool.d.ts +11 -0
  22. package/dist/src/agent/a2a/createA2ARoute.d.ts +5 -0
  23. package/dist/src/agent/bindings/solid.d.ts +12 -0
  24. package/dist/src/agent/bindings/svelte.d.ts +10 -0
  25. package/dist/src/agent/bindings/vanilla.d.ts +17 -0
  26. package/dist/src/agent/bindings/vue.d.ts +15 -0
  27. package/dist/src/agent/components/TkxAgentMessage.d.ts +15 -0
  28. package/dist/src/agent/components/TkxReasoningTrace.d.ts +9 -0
  29. package/dist/src/agent/components/TkxToolCallCard.d.ts +12 -0
  30. package/dist/src/agent/content/helpers.d.ts +17 -0
  31. package/dist/src/agent/core/Agent.d.ts +29 -0
  32. package/dist/src/agent/core/Memory.d.ts +12 -0
  33. package/dist/src/agent/core/Middleware.d.ts +10 -0
  34. package/dist/src/agent/core/Provider.d.ts +44 -0
  35. package/dist/src/agent/core/Sanitizer.d.ts +4 -0
  36. package/dist/src/agent/core/Tool.d.ts +13 -0
  37. package/dist/src/agent/core/Transport.d.ts +18 -0
  38. package/dist/src/agent/core/events.d.ts +19 -0
  39. package/dist/src/agent/core/sse.d.ts +6 -0
  40. package/dist/src/agent/core/types.d.ts +39 -0
  41. package/dist/src/agent/devtools/DevToolsPanel.d.ts +8 -0
  42. package/dist/src/agent/devtools/useEventCollector.d.ts +8 -0
  43. package/dist/src/agent/eval/runEval.d.ts +31 -0
  44. package/dist/src/agent/index.d.ts +54 -0
  45. package/dist/src/agent/mcp/MCPClient.d.ts +33 -0
  46. package/dist/src/agent/mcp/mcpAdapter.d.ts +3 -0
  47. package/dist/src/agent/memory/SlidingWindowMemory.d.ts +10 -0
  48. package/dist/src/agent/memory/SummarizingMemory.d.ts +16 -0
  49. package/dist/src/agent/memory/VectorMemory.d.ts +17 -0
  50. package/dist/src/agent/middleware/guardrails.d.ts +20 -0
  51. package/dist/src/agent/middleware/otel.d.ts +13 -0
  52. package/dist/src/agent/middleware/retry.d.ts +11 -0
  53. package/dist/src/agent/middleware/tokenUsage.d.ts +27 -0
  54. package/dist/src/agent/multi/agentAsTool.d.ts +11 -0
  55. package/dist/src/agent/providers/anthropic.d.ts +16 -0
  56. package/dist/src/agent/providers/gemini.d.ts +16 -0
  57. package/dist/src/agent/providers/ollama.d.ts +14 -0
  58. package/dist/src/agent/providers/openai.d.ts +16 -0
  59. package/dist/src/agent/rag/Retriever.d.ts +13 -0
  60. package/dist/src/agent/rag/retrievalTool.d.ts +11 -0
  61. package/dist/src/agent/react/useAgent.d.ts +12 -0
  62. package/dist/src/agent/replay/ReplayProvider.d.ts +13 -0
  63. package/dist/src/agent/replay/recorder.d.ts +16 -0
  64. package/dist/src/agent/research/DeepResearch.d.ts +37 -0
  65. package/dist/src/agent/research/citations.d.ts +10 -0
  66. package/dist/src/agent/server/createAgentClient.d.ts +11 -0
  67. package/dist/src/agent/server/createAgentRoute.d.ts +10 -0
  68. package/dist/src/agent/structured/generateObject.d.ts +19 -0
  69. package/dist/src/agent/tools/cancellable.d.ts +6 -0
  70. package/dist/src/charts/TkxDataExplorer.d.ts +17 -0
  71. package/dist/src/charts/index.d.ts +2 -0
  72. package/dist/src/components/TkxAppBar.d.ts +2 -1
  73. package/dist/src/components/TkxButton.d.ts +1 -0
  74. package/dist/src/components/TkxCommandPalette.d.ts +32 -0
  75. package/dist/src/components/TkxDataGrid.d.ts +37 -1
  76. package/dist/src/components/TkxFlowChart.d.ts +52 -0
  77. package/dist/src/components/TkxFormBuilder.d.ts +34 -0
  78. package/dist/src/components/TkxFormulaBar.d.ts +19 -0
  79. package/dist/src/components/TkxFunnelChart.d.ts +21 -0
  80. package/dist/src/components/TkxGantt.d.ts +29 -0
  81. package/dist/src/components/TkxGauge.d.ts +21 -0
  82. package/dist/src/components/TkxHeatmap.d.ts +25 -0
  83. package/dist/src/components/TkxHolographic.d.ts +2 -0
  84. package/dist/src/components/TkxHolographicAdvanced.d.ts +48 -0
  85. package/dist/src/components/TkxMindMap.d.ts +22 -0
  86. package/dist/src/components/TkxPivotTable.d.ts +21 -0
  87. package/dist/src/components/TkxSparkline.d.ts +15 -0
  88. package/dist/src/components/TkxSpreadsheet.d.ts +33 -0
  89. package/dist/src/components/TkxTreemap.d.ts +21 -0
  90. package/dist/src/components/TkxTypography.d.ts +1 -1
  91. package/dist/src/components/index.d.ts +5 -3
  92. package/dist/src/engine/security.d.ts +3 -0
  93. package/dist/src/experimental/index.d.ts +8 -0
  94. package/dist/src/headless/index.d.ts +6 -0
  95. package/dist/src/headless/rhfBindings.d.ts +59 -0
  96. package/dist/src/headless/useFormState.d.ts +12 -2
  97. package/dist/src/headless/valibotResolver.d.ts +25 -0
  98. package/dist/src/headless/zodResolver.d.ts +25 -0
  99. package/dist/src/i18n/index.d.ts +20 -0
  100. package/dist/src/i18n/plurals.d.ts +4 -0
  101. package/dist/src/quantum/index.d.ts +0 -2
  102. package/dist/src/themes/index.d.ts +7 -1
  103. package/dist/themes.cjs +1 -0
  104. package/dist/themes.js +1 -0
  105. package/package.json +32 -8
  106. package/dist/chunk-BHX35YDv.js +0 -1
  107. package/dist/chunk-BpuJ3-K8.js +0 -1
  108. package/dist/chunk-Bze40nDX.js +0 -1
  109. package/dist/chunk-C8Wy8P59.js +0 -1
  110. package/dist/chunk-D7-yknXg.js +0 -1
  111. package/dist/chunk-DTO-RrPx.js +0 -3
  112. package/dist/chunk-DcVMayoM.js +0 -1
  113. package/dist/chunk-DdHSYetV.js +0 -1
  114. package/dist/chunk-DmRB1Blb.js +0 -1
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 007krcs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 007krcs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  # ⚡ TekiVex UI
4
4
 
5
- **The first React UI library with a security kernel built in.**
5
+ **The React component library that ships with a threat model.**
6
6
 
7
- WCAG 2.1 AAA · WAI-ARIA 1.2 · **SecurityCore** (XSS · clickjacking · Trojan Source · CSP · PII · magic-byte MIME) · 99 Components · Zero Dependencies
7
+ WCAG 2.1 AAA (audit-firm engagement open) · WAI-ARIA 1.2 · **SecurityCore** (XSS · clickjacking · Trojan Source · CSP · PII · magic-byte MIME · Trusted Types) · **115 production components** (+ 4 experimental, opt-in) · Zero runtime dependencies in core
8
8
 
9
- 📄 **[Security Threat Model](./docs/SECURITY-THREAT-MODEL.md)** — the only mainstream React UI library that publishes one.
9
+ 📄 **[Security Threat Model](./docs/SECURITY-THREAT-MODEL.md)** — the only mainstream React UI library that publishes one. 15 STRIDE-mapped threats with CWE references.
10
10
 
11
11
  [![npm version](https://img.shields.io/npm/v/tekivex-ui?color=00f5d4&label=tekivex-ui&logo=npm)](https://www.npmjs.com/package/tekivex-ui)
12
12
  [![npm downloads](https://img.shields.io/npm/dw/tekivex-ui?color=00f5d4)](https://www.npmjs.com/package/tekivex-ui)
@@ -14,8 +14,10 @@ WCAG 2.1 AAA · WAI-ARIA 1.2 · **SecurityCore** (XSS · clickjacking · Trojan
14
14
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.6-3178c6.svg?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
15
15
  [![React](https://img.shields.io/badge/React-18+-61dafb.svg?logo=react&logoColor=white)](https://react.dev/)
16
16
  [![WCAG 2.1 AAA](https://img.shields.io/badge/WCAG-2.1%20AAA-00c853.svg)](https://www.w3.org/TR/WCAG21/)
17
- [![Tests](https://img.shields.io/badge/Tests-1034%20passing-00c853.svg)](#testing)
17
+ [![Tests](https://img.shields.io/badge/Tests-1777%20passing-00c853.svg)](#testing)
18
18
  [![SecurityCore](https://img.shields.io/badge/SecurityCore-v3.0-f72585.svg)](./docs/SECURITY-THREAT-MODEL.md)
19
+ [![Socket.dev](https://socket.dev/api/badge/npm/package/tekivex-ui)](https://socket.dev/npm/package/tekivex-ui)
20
+ [![SBOM](https://img.shields.io/badge/SBOM-CycloneDX%201.5-7c5cff.svg)](https://ui.tekivex.com/security/sbom.json)
19
21
 
20
22
  <br/>
21
23
 
@@ -23,35 +25,105 @@ WCAG 2.1 AAA · WAI-ARIA 1.2 · **SecurityCore** (XSS · clickjacking · Trojan
23
25
  npm install tekivex-ui
24
26
  ```
25
27
 
26
- [📖 Docs](https://ui.tekivex.com) · [🚀 Demo](https://ui.tekivex.com) · [📦 npm](https://www.npmjs.com/package/tekivex-ui) · [🐛 Report Issue](https://github.com/novaai0401-ui/tekivex-issue-report/issues) · [⭐ Star](https://github.com/novaai0401-ui/tekivex-issue-report/stargazers)
28
+ [📖 Docs](https://ui.tekivex.com) · [🚀 Demo](https://ui.tekivex.com) · [📦 npm](https://www.npmjs.com/package/tekivex-ui) · [🐛 Report Issue](https://github.com/007krcs/tekivex-ui/issues) · [⭐ Star](https://github.com/007krcs/tekivex-ui/stargazers)
27
29
 
28
30
  </div>
29
31
 
30
32
  ---
31
33
 
34
+ ## Project status — read before adopting
35
+
36
+ TekiVex UI is **pre-1.0** and currently maintained by a single developer
37
+ ([007krcs](https://github.com/007krcs)) on `novaai0401@gmail.com`. We
38
+ publish to npm with [provenance attestations](https://docs.npmjs.com/generating-provenance-statements),
39
+ ship a public [CycloneDX SBOM](https://ui.tekivex.com/security/sbom.json),
40
+ a [security threat model](./docs/SECURITY-THREAT-MODEL.md) (15 STRIDE
41
+ threats with CWE refs), and 1,777 tests at the published version — but
42
+ none of that substitutes for the human-scale risk of any pre-1.0,
43
+ single-maintainer library.
44
+
45
+ **Honest guidance:**
46
+
47
+ - **Pin your version** (`"tekivex-ui": "3.18.0"`, not `"^3.18.0"`) until v4.0
48
+ - **Read [TROUBLESHOOTING.md](./TROUBLESHOOTING.md)** before integrating — covers known Next.js / RSC / SSR / hydration issues
49
+ - **Audit the SBOM** at [`ui.tekivex.com/security/sbom.json`](https://ui.tekivex.com/security/sbom.json) — verifies zero runtime deps
50
+ - **Verify the package** with `npm view tekivex-ui` before installing if you're concerned about typosquats (the legitimate name is exactly `tekivex-ui`)
51
+ - **Check Socket.dev** [![Socket.dev](https://socket.dev/api/badge/npm/package/tekivex-ui)](https://socket.dev/npm/package/tekivex-ui) for supply-chain risk score
52
+ - **For regulated-industry teams**: the [design-partner program](./docs/design-partners/README.md) gets a direct Slack channel + priority response + custom-components on demand. Free.
53
+
54
+ **Expect breaking changes at v4.0** — see [docs/ROADMAP.md](./docs/ROADMAP.md).
55
+ Until then, the API surface marked stable will not break in minor or
56
+ patch releases.
57
+
58
+ **Recent compatibility fixes** (v3.18, published 2026-05-28):
59
+
60
+ - Build no longer emits Vite's chunk runtime format — **works in Next.js / RSC** (was broken pre-v3.18)
61
+ - ThemeProvider `mode="auto"` is now SSR-safe + `themeInitScript()` helper for FOUC-free initialisation
62
+ - `'use client'` directives on every hook-using component
63
+ - `isDisabled` absorbed as a deprecated alias (no longer pollutes DOM)
64
+ - `background` / `backgroundImage` shorthand conflict removed
65
+
66
+ ---
67
+
68
+ ## Standalone template repos
69
+
70
+ The resume + biodata templates have moved into their own repos so apps that only need the templates don't have to pull the entire `tekivex-ui` install:
71
+
72
+ | Use case | Install |
73
+ | ------------------------ | ------------------------------------------------------------------------------------------------------ |
74
+ | Resume builder | [`tekivex-resume-templates`](https://github.com/007krcs/tekivex-resume-templates) — 12 templates + smart generator + paywall + browser-only PDF |
75
+ | Marriage biodata builder | [`tekivex-biodata-templates`](https://github.com/007krcs/tekivex-biodata-templates) — 12 templates with auto religious symbols + custom logo upload + 11 vendored biodata-app helpers |
76
+
77
+ Both repos ship the same generator pattern (form → A4 preview → 1-page print), the same locked-by-default policy, and the same image-upload UX as the original `TkxTemplateGenerator` in this repo (which is staying for backward compatibility).
78
+
79
+ ---
80
+
81
+ ## What's new in v3.6 → v3.15
82
+
83
+ | Component | Lands in | Tests | Coverage |
84
+ | ------------------------ | -------- | ----- | --------------------- |
85
+ | `TkxFormBuilder` | v3.6 | 17 | (full unit) |
86
+ | `TkxMindMap` | v3.7 | 12 | (full unit) |
87
+ | `TkxGantt` | v3.8 | 14 | (full unit) |
88
+ | `TkxSpreadsheet` | v3.9 | 29 | (full unit) |
89
+ | `TkxPivotTable` | v3.10 | 12 | (full unit) |
90
+ | `TkxDataExplorer` | v3.11 | 21 | (full unit) |
91
+ | `TkxHolographicAdvanced` | v3.12 | 28 | 93 / 94 / 91 / 89 |
92
+ | `TkxCommandPalette` | v3.13 | 16 | (full unit) |
93
+ | `TkxFormulaBar` | v3.14 | 18 | **100 / 100 / 100 / 90** |
94
+ | `TkxFlowChart` | v3.15 | 40 | **97 / 96 / 95 / 86** |
95
+
96
+ Coverage notation: lines / statements / functions / branches.
97
+
98
+ Pair `tekivex-ui` with [`tekivex-3d`](./packages/tekivex-3d/) for the
99
+ spatial UI toolkit (Scene, Panorama360, Hotspot, XRSession, Model3D,
100
+ Logo3D, ParticleField, OrbitControls, Starfield, Planet, OrbitPath,
101
+ Portal3D, Avatar3D — 14 primitives at source v0.7).
102
+
103
+ ---
104
+
32
105
  ## Why TekiVex UI?
33
106
 
34
107
  | Feature | TekiVex UI | MUI | Ant Design | Mantine | shadcn/ui |
35
108
  |---|:---:|:---:|:---:|:---:|:---:|
36
- | WCAG **AAA** (not just AA) | ✅ | ❌ | ❌ | ❌ | ❌ |
37
- | **XSS** — automatic sanitisation on every prop | ✅ | ❌ | ❌ | ❌ | ❌ |
38
- | **Clickjacking** — `isFramed()` + `frame-ancestors` CSP | ✅ | ❌ | ❌ | ❌ | ❌ |
39
- | **Trojan Source** — bidi/zero-width stripped on inputs | ✅ | ❌ | ❌ | ❌ | ❌ |
40
- | **Prototype pollution** — safe `JSON.parse` | ✅ | ❌ | ❌ | ❌ | ❌ |
41
- | **File upload** — magic-byte MIME verification | ✅ | ❌ | ❌ | ❌ | ❌ |
109
+ | WCAG **AAA** target (third-party audit-firm engagement open) | ✅ | ❌ | ❌ | ❌ | ❌ |
110
+ | **XSS** — string props sanitised by default across all text components | ✅ | ❌ | ❌ | ❌ | ❌ |
111
+ | **Clickjacking** — `isFramed()` detection + `frame-ancestors` CSP | ✅ | ❌ | ❌ | ❌ | ❌ |
112
+ | **Trojan Source** — bidi/zero-width stripped from text inputs | ✅ | ❌ | ❌ | ❌ | ❌ |
113
+ | **Prototype pollution** — `sanitizeJSON()` safe parser | ✅ | ❌ | ❌ | ❌ | ❌ |
114
+ | **File upload** — magic-byte MIME verification (real signatures) | ✅ | ❌ | ❌ | ❌ | ❌ |
42
115
  | **CSP builder** — one-line strict policy | ✅ | ❌ | ❌ | ❌ | ❌ |
43
116
  | **Trusted Types** — one-call policy install | ✅ | ❌ | ❌ | ❌ | ❌ |
44
- | **PII redaction** — pre-LLM / pre-analytics | ✅ | ❌ | ❌ | ❌ | ❌ |
45
- | **Rate limiter** — client-side DoS guard | ✅ | ❌ | ❌ | ❌ | ❌ |
46
- | Immutable security audit trail + integrity check | ✅ | ❌ | ❌ | ❌ | ❌ |
117
+ | **PII redaction** — regex + Luhn-validated CC, pre-LLM/pre-analytics | ✅ | ❌ | ❌ | ❌ | ❌ |
118
+ | **Rate limiter** — client-side token-bucket DoS guard | ✅ | ❌ | ❌ | ❌ | ❌ |
119
+ | Tamper-evident SHA-256 hash-chained audit trail | ✅ | ❌ | ❌ | ❌ | ❌ |
47
120
  | Published threat model | ✅ | ❌ | ❌ | ❌ | ❌ |
48
121
  | Full-featured DataGrid — **free** | ✅ | 💰 Pro | Partial | Partial | ❌ |
49
- | 80+ production components — **free** | ✅ | ✅ | ✅ | ✅ | 30 |
122
+ | 115 production components — **free** | ✅ | ✅ | ✅ | ✅ | 30 |
50
123
  | Hooks layer (a11y, theme, i18n) | ✅ | ❌ | ❌ | ✅ | ✅ |
51
- | i18n — 27 locales incl. RTL | ✅ | ✅ | ✅ | Partial | ❌ |
124
+ | i18n — 44 locales incl. RTL | ✅ | ✅ | ✅ | Partial | ❌ |
52
125
  | Plugin-extensible CSS engine | ✅ | ❌ | ❌ | ❌ | ❌ |
53
- | Zero extra dependencies | ✅ | ❌ | ❌ | ❌ | ✅ |
54
- | **No `src/` in npm tarball** (IP protection) | ✅ | ❌ | ❌ | ❌ | ❌ |
126
+ | Zero runtime deps in core (recharts optional) | ✅ | ❌ | ❌ | ❌ | ✅ |
55
127
 
56
128
  ---
57
129
 
@@ -104,7 +176,7 @@ export default function App() {
104
176
 
105
177
  ## Package Exports
106
178
 
107
- TekiVex UI ships as **three tree-shakeable entry points** — import only what you need:
179
+ TekiVex UI ships **tree-shakeable entry points** — import only what you need:
108
180
 
109
181
  ```ts
110
182
  // Core components + theme + engine (~120 kB gzip)
@@ -115,11 +187,16 @@ import { TkxAreaChart, TkxBarChart, TkxLineChart, TkxPieChart } from 'tekivex-ui
115
187
 
116
188
  // 10 headless hooks — zero styles, your UI (~2.6 kB gzip)
117
189
  import { useDisclosure, useFormState, useListSelection } from 'tekivex-ui/headless';
190
+
191
+ // Agent runtime — Anthropic/OpenAI/Gemini/Ollama, RAG, MCP, A2A, tools (~16 kB gzip)
192
+ import { createAgent, AnthropicProvider, useAgent } from 'tekivex-ui/agent';
118
193
  ```
119
194
 
195
+ 📘 **[Full agent runtime reference → docs/AGENT.md](./docs/AGENT.md)**
196
+
120
197
  ---
121
198
 
122
- ## Components (70+)
199
+ ## Components (115)
123
200
 
124
201
  <details>
125
202
  <summary><strong>Layout & Navigation</strong></summary>
@@ -227,6 +304,24 @@ import { useDisclosure, useFormState, useListSelection } from 'tekivex-ui/headle
227
304
 
228
305
  </details>
229
306
 
307
+ <details>
308
+ <summary><strong>Experimental (opt-in, API not stable)</strong></summary>
309
+
310
+ These components live in-tree but are excluded from the public barrel — the
311
+ API surface, prop names, and runtime behaviour MAY change in any minor
312
+ release. They are not counted in the 115-component headline number.
313
+
314
+ Import path: `import { TkxQuantumForm } from 'tekivex-ui/experimental';`
315
+
316
+ | Component | Notes |
317
+ |---|---|
318
+ | `TkxQuantumForm` | "Quantum-AI" form inference — research-grade, unverified accuracy claims |
319
+ | `TkxAIConfidenceBar` | Display widget for model-confidence values |
320
+ | `TkxAIThinking` | Animated "thinking" dots for chat surfaces |
321
+ | `TkxAIChatBubble` | Single chat-message bubble — overlaps `TkxChat`; prefer `TkxChat` for new code |
322
+
323
+ </details>
324
+
230
325
  ---
231
326
 
232
327
  ## Charts
@@ -345,7 +440,7 @@ CSS custom properties are injected automatically — no flash of unstyled conten
345
440
 
346
441
  ---
347
442
 
348
- ## Internationalisation (27 locales)
443
+ ## Internationalisation (44 locales)
349
444
 
350
445
  ```tsx
351
446
  import { I18nProvider, zhCN, arSA, jaJP, ptBR } from 'tekivex-ui';
@@ -469,6 +564,8 @@ import { TkxDataGrid } from 'tekivex-ui';
469
564
  |---|:---:|:---:|:---:|
470
565
  | Sorting | ✅ | ✅ | ✅ |
471
566
  | Column filtering | ✅ | 💰 Pro | ✅ |
567
+ | Column pinning (left/right) | ✅ | 💰 Pro | ✅ |
568
+ | Row grouping + aggregations | ✅ | 💰 Pro | 💰 Enterprise |
472
569
  | Pagination | ✅ | ✅ | ✅ |
473
570
  | Row selection | ✅ | ✅ | ✅ |
474
571
  | CSV export | ✅ | 💰 Pro | 💰 Enterprise |
@@ -502,7 +599,7 @@ npm install
502
599
  # Build the library
503
600
  npm run build
504
601
 
505
- # Run all 1034 tests
602
+ # Run all 1777 tests
506
603
  npm test
507
604
 
508
605
  # Run tests with coverage report
@@ -532,11 +629,11 @@ npm run security:audit
532
629
  ## Testing
533
630
 
534
631
  ```
535
- 82 test files · 1034 tests · 0 failures · 1 todo
536
- Coverage: 64.84% lines · 51.10% functions · 56.77% branches · 61.41% statements
632
+ 90 dedicated component test files · 1777 tests · 0 failures · 1 todo
633
+ Coverage: 64.84% lines · 51.10% functions · 56.77% branches · 61.41% statements (ratchet enforced in CI)
537
634
  ```
538
635
 
539
- Coverage includes unit tests for all 99 components, 7 chart types, headless hooks (incl. useWebSocket / useSSE / useMediaQuery), the TKX CSS engine, the WCAG engine, the security (Shield) engine, the i18n provider, and Indian KYC validators (Aadhaar Verhoeff, PAN, Voter ID, DL).
636
+ Coverage includes dedicated unit tests for 88 of 115 production components plus smoke coverage for the rest, 7 chart types, headless hooks (incl. useWebSocket / useSSE / useMediaQuery), the TKX CSS engine, the WCAG engine, the security (Shield) engine, the i18n provider, and Indian KYC validators (Aadhaar Verhoeff, PAN, Voter ID, DL).
540
637
 
541
638
  Coverage thresholds are enforced as a CI ratchet in `vitest.config.ts` — the floor never drops between releases. Path to 90/90/85 is documented in [`docs/test-coverage-roadmap.md`](./docs/test-coverage-roadmap.md).
542
639
 
@@ -544,13 +641,29 @@ Coverage thresholds are enforced as a CI ratchet in `vitest.config.ts` — the f
544
641
 
545
642
  ## Roadmap
546
643
 
547
- - [ ] Storybook integration + published Storybook site
548
- - [ ] Figma design token export
549
- - [ ] Zod / Valibot schema resolver for `TkxForm`
550
- - [ ] 40+ additional locales (target: 70+ matching Ant Design)
551
- - [ ] Third-party WCAG 2.1 AAA accessibility audit certificate
552
- - [ ] Heatmap, Funnel, Treemap, Gauge chart types
553
- - [ ] Column pinning and row grouping in DataGrid
644
+ Full roadmap with version targets, owners, and definition-of-done at
645
+ **[`docs/ROADMAP.md`](./docs/ROADMAP.md)**.
646
+
647
+ **Nearest milestones:**
648
+
649
+ - **v3.18** (target 2026-07-15) *"Land the audit + first partner."* Sign
650
+ a third-party WCAG audit SOW (Deque / TPGi / WebAIM), land 1 design-partner
651
+ logo, lift `TkxDataGrid` to 50+ tests. No new components.
652
+ - **v3.19** (target 2026-09-01) — *"Coverage + DataGrid completeness."*
653
+ Ratchet coverage 64.84% → 75% lines, ship DataGrid column-pinning and
654
+ row-grouping, deep-test `TkxSelect`, `TkxDatePicker`, `TkxMenu`,
655
+ `TkxOrgChart`, `TkxTreeView`.
656
+ - **v3.20** (target 2026-10-15) — *"Forms + i18n depth."* Zod + Valibot
657
+ resolvers for `TkxForm`, RHF adapter, drop hardcoded-string count below
658
+ 100, ship 9 new locales (35 → 44).
659
+ - **v3.21** (target 2026-12-01) — *"Charts + visualizations."* New
660
+ `TkxHeatmap`, `TkxFunnelChart`, `TkxTreemap`, `TkxGauge`, `TkxSparkline`.
661
+ - **v4.0** (target 2026-12 to 2027-Q1) — *"Stable."* Third-party AAA VPAT
662
+ published, 90/90/85 coverage, 70+ locales, 5 published case studies,
663
+ React 19 required, codemod for the v3 → v4 migration.
664
+
665
+ [Read the full plan, what we WILL NOT do, and how to propose changes →
666
+ `docs/ROADMAP.md`](./docs/ROADMAP.md)
554
667
 
555
668
  ---
556
669
 
@@ -558,7 +671,7 @@ Coverage thresholds are enforced as a CI ratchet in `vitest.config.ts` — the f
558
671
 
559
672
  Found a bug or have a feature request? Please open an issue on our dedicated issue tracker:
560
673
 
561
- **👉 [github.com/novaai0401-ui/tekivex-issue-report/issues](https://github.com/novaai0401-ui/tekivex-issue-report/issues)**
674
+ **👉 [github.com/007krcs/tekivex-ui/issues](https://github.com/007krcs/tekivex-ui/issues)**
562
675
 
563
676
  When reporting, please include:
564
677
  - tekivex-ui version (`npm list tekivex-ui`)
package/dist/agent.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let t=require("react/jsx-runtime"),e=require("react");var r=class{constructor(){this.messages=[]}append(t){this.messages.push(t)}all(){return this.messages.slice()}clear(){this.messages=[]}},o={async request(t){const e=await fetch(t.url,{method:t.method,headers:t.headers,body:t.body,signal:t.signal}),r={};return e.headers.forEach((t,e)=>{r[e]=t}),{status:e.status,headers:r,body:e.body,json:()=>e.json(),text:()=>e.text()}}};async function*n(t){const e=t.getReader(),r=new TextDecoder;let o="";try{for(;;){const{done:t,value:n}=await e.read();if(t)break;o+=r.decode(n,{stream:!0});let a=s(o);for(;-1!==a.index;){const t=o.slice(0,a.index);o=o.slice(a.index+a.length);const e=i(t);e&&(yield e),a=s(o)}}if(o.length>0){const t=i(o);t&&(yield t)}}finally{e.releaseLock()}}function s(t){const e=t.indexOf("\n\n"),r=t.indexOf("\r\n\r\n");return-1===e&&-1===r?{index:-1,length:0}:-1===e?{index:r,length:4}:-1===r||e<r?{index:e,length:2}:{index:r,length:4}}function i(t){let e,r;const o=[];for(const n of t.split(/\r?\n/))n.startsWith(":")||(n.startsWith("event:")?e=n.slice(6).trim():n.startsWith("id:")?r=n.slice(3).trim():n.startsWith("data:")&&o.push(n.slice(5).replace(/^ /,"")));return 0===o.length?null:{event:e,id:r,data:o.join("\n")}}var a=class{constructor(t){this.opts=t,this.memory=t.memory??new r,this.toolByName=new Map((t.tools??[]).map(t=>[t.name,t])),this.toolDefs=(t.tools??[]).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}async*run(t){const e=this.opts.middleware??[],r=this.opts.maxSteps??10;await Promise.resolve(this.memory.append({role:"user",content:t.message}));for(let n=0;n<r;n++){const r={type:"step_start",step:n};yield r,await c(e,r);const s=await Promise.resolve(this.memory.all()),i=[],a=new Map;let l="",p="end_turn";const d={model:this.opts.model,messages:s,system:this.opts.system,tools:this.toolDefs.length?this.toolDefs:void 0,maxTokens:this.opts.maxTokens,temperature:this.opts.temperature,signal:t.signal};try{for await(const t of this.opts.provider.stream(d))if("text_delta"===t.type)l+=t.text,yield t,await c(e,t);else if("tool_call_start"===t.type)l&&(i.push({type:"text",text:l}),l=""),a.set(t.id,{name:t.name,input:void 0}),yield t,await c(e,t);else if("tool_call_delta"===t.type)yield t,await c(e,t);else if("tool_call_end"===t.type){const r=a.get(t.id);r&&(r.input=t.input,i.push({type:"tool_use",id:t.id,name:r.name,input:t.input})),yield t,await c(e,t)}else if("message_stop"===t.type)l&&(i.push({type:"text",text:l}),l=""),p=t.reason,yield t,await c(e,t);else if("error"===t.type)return yield t,await c(e,t),await u(e,t.error),void(yield{type:"done",reason:"error"})}catch(o){const t=o instanceof Error?o:new Error(String(o)),r={type:"error",error:t};return yield r,await c(e,r),await u(e,t),void(yield{type:"done",reason:"error"})}if(i.length>0&&await Promise.resolve(this.memory.append({role:"assistant",content:i})),"tool_use"!==p||0===a.size)return void(yield{type:"done",reason:p});const f=[];for(const[n,{name:h,input:y}]of a){const r=this.toolByName.get(h);if(!r){const t={type:"tool_error",id:n,name:h,error:new Error(`Tool not registered: ${h}`)};yield t,await c(e,t),f.push({type:"tool_result",toolUseId:n,output:`Error: tool '${h}' is not registered`,isError:!0});continue}try{const o=r.parse?r.parse(y):y,s=await r.execute(o,{signal:t.signal,messages:await Promise.resolve(this.memory.all())}),i={type:"tool_result",id:n,name:h,output:s};yield i,await c(e,i),f.push({type:"tool_result",toolUseId:n,name:h,output:s})}catch(o){const t=o instanceof Error?o:new Error(String(o)),r={type:"tool_error",id:n,name:h,error:t};yield r,await c(e,r),await u(e,t),f.push({type:"tool_result",toolUseId:n,output:t.message,isError:!0})}}await Promise.resolve(this.memory.append({role:"tool",content:f}))}yield{type:"done",reason:"max_tokens"}}};function l(t){return new a(t)}async function c(t,e){for(const r of t)if(r.onEvent)try{await r.onEvent(e)}catch{}}async function u(t,e){for(const r of t)if(r.onError)try{await r.onError(e)}catch{}}function p(t){switch(t){case"end_turn":case"tool_use":case"max_tokens":case"stop_sequence":return t;default:return"end_turn"}}function d(t){return{model:t.model,max_tokens:t.maxTokens??4096,system:t.system,messages:t.messages.filter(t=>"system"!==t.role).map(h),tools:t.tools?.map(f),temperature:t.temperature,top_p:t.topP,stop_sequences:t.stopSequences,stream:!0}}function f(t){return{name:t.name,description:t.description,input_schema:t.inputSchema}}function h(t){return"tool"===t.role?{role:"user",content:(Array.isArray(t.content)?t.content:[]).map(y)}:"string"==typeof t.content?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(y)}}function y(t){switch(t.type){case"text":return t.cacheControl?{type:"text",text:t.text,cache_control:t.cacheControl}:{type:"text",text:t.text};case"image":return{type:"image",source:"base64"===t.source.kind?{type:"base64",media_type:t.source.mediaType??"image/png",data:t.source.data}:{type:"url",url:t.source.data}};case"tool_use":return{type:"tool_use",id:t.id,name:t.name,input:t.input};case"tool_result":return{type:"tool_result",tool_use_id:t.toolUseId,content:"string"==typeof t.output?t.output:JSON.stringify(t.output),is_error:t.isError}}}function m(t){switch(t){case"stop":default:return"end_turn";case"tool_calls":case"function_call":return"tool_use";case"length":return"max_tokens";case"content_filter":return"stop_sequence"}}function g(t){const e=[];t.system&&e.push({role:"system",content:t.system});for(const r of t.messages)if("system"===r.role)e.push({role:"system",content:_(r.content)});else if("tool"===r.role){const t=Array.isArray(r.content)?r.content:[];for(const r of t)"tool_result"===r.type&&e.push({role:"tool",tool_call_id:r.toolUseId,content:"string"==typeof r.output?r.output:JSON.stringify(r.output)})}else"assistant"===r.role?e.push(x(r)):e.push({role:"user",content:b(r.content)});return{model:t.model,messages:e,tools:t.tools?.map(w),max_tokens:t.maxTokens,temperature:t.temperature,top_p:t.topP,stop:t.stopSequences,stream:!0}}function w(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}}function x(t){if("string"==typeof t.content)return{role:"assistant",content:t.content};const e=[],r=[];for(const n of t.content)"text"===n.type?e.push(n.text):"tool_use"===n.type&&r.push({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.input)}});const o={role:"assistant",content:e.length?e.join(""):null};return r.length&&(o.tool_calls=r),o}function _(t){return"string"==typeof t?t:t.filter(t=>"text"===t.type).map(t=>t.text).join("")}function b(t){if("string"==typeof t)return t;const e=[];for(const r of t)if("text"===r.type)e.push({type:"text",text:r.text});else if("image"===r.type){const t="base64"===r.source.kind?`data:${r.source.mediaType??"image/png"};base64,${r.source.data}`:r.source.data;e.push({type:"image_url",image_url:{url:t}})}return e}function S(t){switch(t){case"STOP":default:return"end_turn";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"RECITATION":return"stop_sequence"}}function v(t){return{contents:t.messages.filter(t=>"system"!==t.role).map(E),systemInstruction:t.system?{parts:[{text:t.system}]}:void 0,tools:t.tools?.length?[{functionDeclarations:t.tools.map(T)}]:void 0,generationConfig:{maxOutputTokens:t.maxTokens,temperature:t.temperature,topP:t.topP,stopSequences:t.stopSequences}}}function T(t){return{name:t.name,description:t.description,parameters:t.inputSchema}}function E(t){if("tool"===t.role)return{role:"function",parts:(Array.isArray(t.content)?t.content:[]).flatMap(t=>"tool_result"===t.type?[{functionResponse:{name:t.name??"",response:"object"==typeof t.output&&null!==t.output?t.output:{result:String(t.output)}}}]:[])};const e="assistant"===t.role?"model":"user";return"string"==typeof t.content?{role:e,parts:[{text:t.content}]}:{role:e,parts:t.content.flatMap(k)}}function k(t){return"text"===t.type?[{text:t.text}]:"image"===t.type?"base64"===t.source.kind?[{inlineData:{mimeType:t.source.mediaType??"image/png",data:t.source.data}}]:[{fileData:{fileUri:t.source.data,mimeType:t.source.mediaType}}]:"tool_use"===t.type?[{functionCall:{name:t.name,args:t.input}}]:[]}function O(t){const e=[];t.system&&e.push({role:"system",content:t.system});for(const r of t.messages)if("tool"===r.role){const t=Array.isArray(r.content)?r.content:[];for(const r of t)"tool_result"===r.type&&e.push({role:"tool",content:"string"==typeof r.output?r.output:JSON.stringify(r.output)})}else if("string"==typeof r.content)e.push({role:r.role,content:r.content});else{const t=r.content.filter(t=>"text"===t.type).map(t=>t.text).join(""),o=r.content.filter(t=>"tool_use"===t.type),n={role:r.role,content:t};o.length&&(n.tool_calls=o.map(t=>({function:{name:t.name,arguments:t.input}}))),e.push(n)}return{model:t.model,messages:e,tools:t.tools?.map($),stream:!0,options:{temperature:t.temperature,top_p:t.topP,num_predict:t.maxTokens,stop:t.stopSequences}}}function $(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}}function N(t){return{name:t.name??"search_knowledge",description:t.description??"Search the internal knowledge base. Use this whenever the user asks about content that may exist in stored documents.",inputSchema:{type:"object",properties:{query:{type:"string",description:"A complete question or topic phrase — not a single keyword."}},required:["query"]},async execute({query:e},r){const o=await t.retriever.retrieve(e,{topK:t.topK??4,signal:r.signal});return 0===o.length?"No relevant documents found.":o.map((t,e)=>`[Source ${e+1} | score=${t.score.toFixed(3)}]\n${t.text}`).join("\n\n---\n\n")}}}function J(t,e,r,o,n){const s=Math.min(e*Math.pow(o,t),r);return n?Math.random()*s:s}function A(t,e){return new Promise((r,o)=>{if(e?.aborted)return void o(new Error("aborted"));const n=setTimeout(()=>{e?.removeEventListener("abort",s),r()},t),s=()=>{clearTimeout(n),o(new Error("aborted"))};e?.addEventListener("abort",s,{once:!0})})}var q=class extends Error{constructor(t,e){super(`Guardrail violation [${t}]: ${e}`),this.guardrailName=t,this.reason=e,this.name="GuardrailViolation"}};async function P(t,e,r){let o=t;for(const n of e){const t="input"===r?n.checkInput:n.checkOutput;if(!t)continue;const e=await t(o);if(!e.allow)return{allow:!1,reason:e.reason,replacement:o};e.replacement&&(o=e.replacement)}return{allow:!0,replacement:o}}var D=[{regex:/\b\d{3}-\d{2}-\d{4}\b/g,label:"SSN"},{regex:/\b(?:\d[ -]*?){13,16}\b/g,label:"CREDIT_CARD"},{regex:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,label:"EMAIL"}],M={name:"pii-redactor",checkInput(t){let e=t;for(const{regex:r,label:o}of D)e=e.replace(r,`[REDACTED:${o}]`);return{allow:!0,replacement:e}}},j=[/ignore (?:all )?previous instructions/i,/disregard (?:the )?system prompt/i,/you are now (?:a |an )?different/i],R={name:"prompt-injection",checkInput(t){for(const e of j)if(e.test(t))return{allow:!1,reason:`potential prompt injection: ${e}`};return{allow:!0}}},I=class extends Error{constructor(t,e){super(t),this.raw=e,this.name="StructuredOutputError"}};async function C(t){const e=`${t.system?`${t.system}\n\n`:""}You MUST respond with valid JSON only — no commentary, no markdown fences. The JSON must conform to this JSON Schema:\n${JSON.stringify(t.schema,null,2)}`,r=t.maxRetries??1;let o="",n=null;for(let i=0;i<=r;i++){let r="";for await(const o of t.provider.stream({model:t.model,messages:[{role:"user",content:t.prompt}],system:e,maxTokens:t.maxTokens,temperature:t.temperature??0,signal:t.signal}))if("text_delta"===o.type&&(r+=o.text),"error"===o.type)throw o.error;o=r;try{const e=z(r),o=JSON.parse(e);return t.parse?t.parse(o):o}catch(s){n=s instanceof Error?s:new Error(String(s))}}throw new I(`Failed to parse JSON after ${r+1} attempt(s): ${n?.message}`,o)}function z(t){const e=t.trim(),r=e.match(/```(?:json)?\s*([\s\S]+?)\s*```/);if(r)return r[1].trim();const o=Math.min(...["[","{"].map(t=>{const r=e.indexOf(t);return-1===r?1/0:r})),n=Math.max(e.lastIndexOf("]"),e.lastIndexOf("}"));return o!==1/0&&n>o?e.slice(o,n+1):e}var U=class extends Error{constructor(t){super(`Tool '${t}' aborted`),this.toolName=t,this.name="ToolAbortError"}},F=class{constructor(t){this.opts=t}async run(t,e){const r=e??this.opts.signal,o=[...this.opts.tools??[]];this.opts.retriever&&o.push(N({retriever:this.opts.retriever}));const n=await C({provider:this.opts.provider,model:this.opts.model,schema:{type:"object",properties:{subtasks:{type:"array",maxItems:this.opts.maxSubtasks??5,items:{type:"object",properties:{id:{type:"string"},question:{type:"string"}},required:["id","question"]}}},required:["subtasks"]},system:"You are a research planner. Break the user's question into 3-5 atomic, independently researchable sub-questions.",prompt:t,signal:r}),s=this.opts.concurrency??3,i=await async function(t,e,r){const o=new Array(t.length);let n=0;return await Promise.all(Array.from({length:Math.min(e,t.length)},async function(){for(;;){const e=n++;if(e>=t.length)return;o[e]=await r(t[e])}})),o}(n.subtasks,s,t=>this.research(t.id,t.question,o,r)),a=l({provider:this.opts.provider,model:this.opts.model,system:"Synthesize sub-agent findings into one coherent answer. Preserve citations and call out conflicts."}),c=`Original question: ${t}\n\n`+i.map(t=>`## Sub-question [${t.id}]: ${t.question}\n`+(t.error?`(Error: ${t.error})`:t.findings)).join("\n\n---\n\n");let u="";for await(const l of a.run({message:c,signal:r}))"text_delta"===l.type&&(u+=l.text);return{question:t,plan:n,subFindings:i,synthesis:u}}async research(t,e,r,o){const n=l({provider:this.opts.provider,model:this.opts.model,tools:r,system:"Investigate the question rigorously. Cite sources inline as [Source N]."});let s="";try{for await(const t of n.run({message:e,signal:o}))"text_delta"===t.type&&(s+=t.text);return{id:t,question:e,findings:s}}catch(i){return{id:t,question:e,findings:"",error:i instanceof Error?i.message:String(i)}}}};function G(t){const e=t.memory??new r,o=new a({...t,memory:e});let n={messages:[],streamingText:"",isStreaming:!1,error:null};const s=new Set;let i=null;function l(t){n={...n,...t};for(const e of s)e(n)}return{getState:()=>n,subscribe:t=>(s.add(t),()=>s.delete(t)),async send(t){if(!t.trim())return;l({error:null,streamingText:"",isStreaming:!0,messages:[...n.messages,{role:"user",content:t}]}),i=new AbortController;let r="";try{for await(const e of o.run({message:t,signal:i.signal}))"text_delta"===e.type&&(r+=e.text,l({streamingText:r}));l({messages:await Promise.resolve(e.all()),streamingText:"",isStreaming:!1})}catch(s){l({error:s instanceof Error?s:new Error(String(s)),isStreaming:!1})}finally{i=null}},stop(){i?.abort()},reset(){Promise.resolve(e.clear()),l({messages:[],streamingText:"",error:null})},dispose(){i?.abort(),s.clear()}}}function L(t){if(t&&"object"==typeof t&&"error"in t&&t.error instanceof Error){const e=t;return{...t,error:{message:e.error.message,name:e.error.name}}}return t}var B=new Set(["text_delta","tool_call_start","tool_call_delta","tool_call_end","message_stop","error"]);function K(t){return"error"in t&&t.error instanceof Error?{...t,error:t.error.message}:t}var Y=class{constructor(t){this.opts=t,this.transport=t.transport??o}async sendTask(t,e){const r=await this.transport.request({url:this.opts.endpoint,method:"POST",headers:{"content-type":"application/json",...this.opts.headers},body:JSON.stringify(t),signal:e});if(r.status>=400)throw new Error(`A2A ${r.status}: ${await r.text()}`);return await r.json()}static newTaskId(){return`task_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}};exports.A2AClient=Y,exports.Agent=a,exports.AnthropicProvider=class{constructor(t={}){this.opts=t,this.name="anthropic",this.transport=t.transport??o}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream","anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"https://api.anthropic.com/v1/messages",method:"POST",headers:e,body:JSON.stringify(d(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:new Error(`Anthropic ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:new Error("Anthropic: empty response body")});const o=new Map;let s,i="end_turn";for await(const l of n(r.body)){let t;try{t=JSON.parse(l.data)}catch{continue}const e=t.type??l.event,r=t.index??0;if("content_block_start"===e){const e=t.content_block;"tool_use"===e?.type&&e.id&&e.name&&(o.set(r,{id:e.id,name:e.name,json:""}),yield{type:"tool_call_start",id:e.id,name:e.name})}else if("content_block_delta"===e){const e=t.delta;if("text_delta"===e?.type&&"string"==typeof e.text)yield{type:"text_delta",text:e.text};else if("input_json_delta"===e?.type&&"string"==typeof e.partial_json){const t=o.get(r);t&&(t.json+=e.partial_json,yield{type:"tool_call_delta",id:t.id,argsDelta:e.partial_json})}}else if("content_block_stop"===e){const t=o.get(r);if(t){let e={};if(t.json)try{e=JSON.parse(t.json)}catch(a){return void(yield{type:"error",error:a})}yield{type:"tool_call_end",id:t.id,input:e},o.delete(r)}}else if("message_delta"===e)t.delta?.stop_reason&&(i=p(t.delta.stop_reason)),t.usage&&(s={inputTokens:t.usage.input_tokens,outputTokens:t.usage.output_tokens});else{if("message_stop"===e)return void(yield{type:"message_stop",reason:i,usage:s});if("error"===e)return void(yield{type:"error",error:new Error(t.error?.message??"Anthropic stream error")})}}}},exports.DeepResearch=F,exports.DevToolsPanel=function({events:r,onClear:o,position:n="bottom-right",startOpen:s=!1}){const[i,a]=(0,e.useState)(s),[l,c]=(0,e.useState)("all"),u="all"===l?r:r.filter(t=>t.type===l),p={position:"fixed",bottom:n.includes("bottom")?16:void 0,top:n.includes("top")?16:void 0,right:n.includes("right")?16:void 0,left:n.includes("left")?16:void 0,width:i?480:"auto",maxHeight:i?"60vh":"auto",background:"rgba(15, 15, 35, 0.96)",color:"#f0f0ff",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,padding:12,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:12,zIndex:1e4,display:"flex",flexDirection:"column",gap:8,boxShadow:"0 8px 32px rgba(0,0,0,0.4)"},d={background:"rgba(255,255,255,0.06)",color:"inherit",border:"1px solid rgba(255,255,255,0.2)",padding:"4px 8px",borderRadius:4,cursor:"pointer",fontFamily:"inherit",fontSize:"inherit"};return(0,t.jsxs)("aside",{style:p,"aria-label":"Agent DevTools",children:[(0,t.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,t.jsx)("button",{onClick:()=>a(!i),style:d,children:i?"▾ Agent DevTools":"▸ Agent"}),(0,t.jsxs)("span",{style:{opacity:.6},children:[r.length," events"]}),i&&o&&(0,t.jsx)("button",{onClick:o,style:{...d,marginLeft:"auto"},children:"Clear"})]}),i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("select",{value:l,onChange:t=>c(t.target.value),style:{...d,cursor:"pointer"},children:[(0,t.jsx)("option",{value:"all",children:"All events"}),(0,t.jsx)("option",{value:"step_start",children:"Step starts"}),(0,t.jsx)("option",{value:"tool_call_start",children:"Tool starts"}),(0,t.jsx)("option",{value:"tool_result",children:"Tool results"}),(0,t.jsx)("option",{value:"tool_error",children:"Tool errors"}),(0,t.jsx)("option",{value:"message_stop",children:"Message stops"}),(0,t.jsx)("option",{value:"error",children:"Errors"})]}),(0,t.jsx)("div",{style:{overflow:"auto",flex:1},children:u.map((e,r)=>{return(0,t.jsxs)("div",{style:{padding:"6px 0",borderBottom:"1px solid rgba(255,255,255,0.06)"},children:[(0,t.jsx)("code",{style:{color:(o=e.type,o.startsWith("tool_call")?"#f9a826":"tool_result"===o?"#00c853":"error"===o||"tool_error"===o?"#ff6b6b":"message_stop"===o||"done"===o?"#00f5d4":"step_start"===o?"#6366f1":"#a0a0c0")},children:e.type}),(0,t.jsx)("pre",{style:{margin:"4px 0 0 0",fontSize:11,opacity:.85,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:JSON.stringify(K(e),null,1)})]},r);var o})})]})]})},exports.GeminiProvider=class{constructor(t={}){this.opts=t,this.name="gemini",this.transport=t.transport??o}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream",...this.opts.headers},r=await this.transport.request({url:this.buildUrl(t.model),method:"POST",headers:e,body:JSON.stringify(v(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:new Error(`Gemini ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:new Error("Gemini: empty response body")});let o,s="end_turn",i=0;for await(const a of n(r.body)){let t;try{t=JSON.parse(a.data)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error.message??"Gemini error")});t.usageMetadata&&(o={inputTokens:t.usageMetadata.promptTokenCount,outputTokens:t.usageMetadata.candidatesTokenCount});const e=t.candidates?.[0];if(e){for(const t of e.content?.parts??[])if("string"==typeof t.text&&t.text.length>0)yield{type:"text_delta",text:t.text};else if(t.functionCall?.name){const e="gemini_call_"+i++,r=JSON.stringify(t.functionCall.args??{});yield{type:"tool_call_start",id:e,name:t.functionCall.name},yield{type:"tool_call_delta",id:e,argsDelta:r},yield{type:"tool_call_end",id:e,input:t.functionCall.args??{}}}if(e.finishReason)return s=S(e.finishReason),void(yield{type:"message_stop",reason:s,usage:o})}}}buildUrl(t){const e=`${this.opts.endpoint??"https://generativelanguage.googleapis.com/v1beta"}/models/${t}:streamGenerateContent?alt=sse`;return this.opts.apiKey?`${e}&key=${encodeURIComponent(this.opts.apiKey)}`:e}},exports.GuardrailViolation=q,exports.InMemoryStore=r,exports.MCPClient=class{constructor(t){this.opts=t,this.idSeq=0,this.initialized=!1,this.transport=t.transport??o}async initialize(t){this.initialized||(await this.call("initialize",{protocolVersion:"2024-11-05",capabilities:{tools:{}},clientInfo:this.opts.clientInfo??{name:"tekivex-ui-agent",version:"1.0"}},t),this.initialized=!0)}async listTools(t){return await this.initialize(t),(await this.call("tools/list",{},t)).tools??[]}async callTool(t,e,r){return await this.initialize(r),await this.call("tools/call",{name:t,arguments:e},r)}async call(t,e,r){const o=++this.idSeq,n=await this.transport.request({url:this.opts.endpoint,method:"POST",headers:{"content-type":"application/json",accept:"application/json",...this.opts.headers},body:JSON.stringify({jsonrpc:"2.0",id:o,method:t,params:e}),signal:r});if(n.status>=400){const e=await n.text();throw new Error(`MCP ${t} failed (${n.status}): ${e}`)}const s=await n.json();if(s.error)throw new Error(`MCP error ${s.error.code}: ${s.error.message}`);return s.result}},exports.OllamaProvider=class{constructor(t={}){this.opts=t,this.name="ollama",this.transport=t.transport??o}async*stream(t){const e={"content-type":"application/json",...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"http://localhost:11434/api/chat",method:"POST",headers:e,body:JSON.stringify(O(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:new Error(`Ollama ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:new Error("Ollama: empty response body")});let o,n="end_turn",s=0,i=!1;for await(const a of async function*(t){const e=t.getReader(),r=new TextDecoder;let o="";try{for(;;){const{done:t,value:n}=await e.read();if(t)break;o+=r.decode(n,{stream:!0});let s=o.indexOf("\n");for(;-1!==s;){const t=o.slice(0,s).trim();o=o.slice(s+1),t&&(yield t),s=o.indexOf("\n")}}o.trim()&&(yield o.trim())}finally{e.releaseLock()}}(r.body)){let t;try{t=JSON.parse(a)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error)});"number"!=typeof t.prompt_eval_count&&"number"!=typeof t.eval_count||(o={inputTokens:t.prompt_eval_count,outputTokens:t.eval_count});const e=t.message;if(e?.content&&(yield{type:"text_delta",text:e.content}),e?.tool_calls?.length){i=!0;for(const t of e.tool_calls){const e=t.function?.name;if(!e)continue;const r=t.function?.arguments??{},o="ollama_call_"+s++;yield{type:"tool_call_start",id:o,name:e},yield{type:"tool_call_delta",id:o,argsDelta:JSON.stringify(r)},yield{type:"tool_call_end",id:o,input:r}}}if(t.done)return n=i?"tool_use":"length"===t.done_reason?"max_tokens":"end_turn",void(yield{type:"message_stop",reason:n,usage:o})}}},exports.OpenAIProvider=class{constructor(t={}){this.opts=t,this.name="openai",this.transport=t.transport??o}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.organization?{"openai-organization":this.opts.organization}:{},...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"https://api.openai.com/v1/chat/completions",method:"POST",headers:e,body:JSON.stringify(g(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:new Error(`OpenAI ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:new Error("OpenAI: empty response body")});const o=new Map;let s,i="end_turn";for await(const a of n(r.body)){if("[DONE]"===a.data)break;let t;try{t=JSON.parse(a.data)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error.message??"OpenAI error")});t.usage&&(s={inputTokens:t.usage.prompt_tokens,outputTokens:t.usage.completion_tokens});const e=t.choices?.[0];if(e){if(e.delta?.content&&(yield{type:"text_delta",text:e.delta.content}),e.delta?.tool_calls)for(const t of e.delta.tool_calls){let e=o.get(t.index);e||(e={id:t.id??`tool_${t.index}`,name:"",args:"",started:!1},o.set(t.index,e)),t.id&&(e.id=t.id),t.function?.name&&(e.name=t.function.name),!e.started&&e.id&&e.name&&(yield{type:"tool_call_start",id:e.id,name:e.name},e.started=!0),t.function?.arguments&&(e.args+=t.function.arguments,e.started&&(yield{type:"tool_call_delta",id:e.id,argsDelta:t.function.arguments}))}if(e.finish_reason){for(const t of o.values()){let e={};if(t.args)try{e=JSON.parse(t.args)}catch{e=t.args}yield{type:"tool_call_end",id:t.id,input:e}}return i=m(e.finish_reason),void(yield{type:"message_stop",reason:i,usage:s})}}}}},exports.Recorder=class{constructor(){this.events=[],this.started=Date.now()}record(t){this.events.push(t)}snapshot(){return{events:this.events.slice(),startedAt:this.started}}toJSONL(){return this.events.map(t=>JSON.stringify(function(t){return"error"in t&&t.error instanceof Error?{...t,error:{message:t.error.message,name:t.error.name}}:t}(t))).join("\n")}static fromJSONL(t){return{events:t.split("\n").filter(t=>t.trim()).map(t=>function(t){if(t&&"object"==typeof t&&"error"in t&&"object"==typeof t.error){const e=t;return{...t,error:new Error(e.error?.message??"unknown")}}return t}(JSON.parse(t))),startedAt:Date.now()}}reset(){this.events=[],this.started=Date.now()}asMiddleware(){return{name:"recorder",onEvent:t=>this.record(t)}}},exports.ReplayProvider=class{constructor(t){this.opts=t,this.name="replay",this.events=t.recording.events.filter(t=>B.has(t.type))}async*stream(t){for(const e of this.events)if(this.opts.delayMsBetweenEvents&&await new Promise(t=>setTimeout(t,this.opts.delayMsBetweenEvents)),yield e,"message_stop"===e.type)return}},exports.SlidingWindowMemory=class{constructor(t){if(this.windowSize=t,this.messages=[],t<1)throw new Error("windowSize must be >= 1")}append(t){for(this.messages.push(t);this.messages.length>this.windowSize;)this.messages.shift()}all(){return this.messages.slice()}clear(){this.messages=[]}},exports.StructuredOutputError=I,exports.SummarizingMemory=class{constructor(t){if(this.opts=t,this.messages=[],this.summary="",t.threshold<2)throw new Error("threshold must be >= 2")}async append(t){this.messages.push(t);const e=this.opts.keepRecent??4;if(this.messages.length>this.opts.threshold){const t=this.messages.slice(0,this.messages.length-e);this.messages=this.messages.slice(-e);const r=await this.opts.summarizer(t);this.summary=this.summary?`${this.summary}\n${r}`:r}}all(){return this.summary?[{role:"system",content:`Prior conversation summary:\n${this.summary}`},...this.messages]:this.messages.slice()}clear(){this.messages=[],this.summary=""}},exports.TkxAgentMessage=function({message:e,streamingText:r,renderToolCall:o,renderToolResult:n,className:s,style:i}){const a="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;return(0,t.jsxs)("div",{className:s,style:i,"data-role":e.role,role:"article","aria-label":`${e.role} message`,children:[a.map((e,r)=>"text"===e.type?(0,t.jsx)("div",{"data-block":"text",children:e.text},r):"tool_use"===e.type?(0,t.jsx)("div",{"data-block":"tool_use",children:o?o(e):(0,t.jsxs)("code",{children:[e.name,"(",JSON.stringify(e.input),")"]})},r):"tool_result"===e.type?(0,t.jsx)("div",{"data-block":"tool_result",children:n?n(e):(0,t.jsx)("pre",{children:"string"==typeof e.output?e.output:JSON.stringify(e.output,null,2)})},r):"image"===e.type?(0,t.jsx)("img",{src:"base64"===e.source.kind?`data:${e.source.mediaType??"image/png"};base64,${e.source.data}`:e.source.data,alt:"","data-block":"image"},r):null),r?(0,t.jsx)("div",{"data-block":"streaming",children:r}):null]})},exports.TkxReasoningTrace=function({events:e,hideTextDeltas:r=!0,className:o,style:n}){return(0,t.jsx)("ol",{className:o,style:n,"aria-label":"Reasoning trace",children:e.map((e,o)=>function(e,r,o){switch(e.type){case"step_start":return(0,t.jsxs)("li",{"data-type":"step",children:["Step ",e.step]},r);case"text_delta":return o?null:(0,t.jsx)("li",{"data-type":"text",children:e.text},r);case"tool_call_start":return(0,t.jsxs)("li",{"data-type":"tool-start",children:["→ ",e.name," ",(0,t.jsxs)("small",{children:["(",e.id,")"]})]},r);case"tool_call_end":return(0,t.jsxs)("li",{"data-type":"tool-args",children:["input: ",(0,t.jsx)("code",{children:JSON.stringify(e.input)})]},r);case"tool_result":return(0,t.jsxs)("li",{"data-type":"tool-result",children:["✓ ",e.name," returned"]},r);case"tool_error":return(0,t.jsxs)("li",{"data-type":"tool-error",children:["✗ ",e.name,": ",e.error.message]},r);case"message_stop":return(0,t.jsxs)("li",{"data-type":"stop",children:["stop (",e.reason,")"]},r);case"done":return(0,t.jsxs)("li",{"data-type":"done",children:["done (",e.reason,")"]},r);case"error":return(0,t.jsxs)("li",{"data-type":"error",children:["error: ",e.error.message]},r);default:return null}}(e,o,r))})},exports.TkxToolCallCard=function({name:e,input:r,output:o,error:n,status:s,className:i,style:a}){return(0,t.jsxs)("section",{className:i,style:a,"data-status":s,role:"region","aria-label":`Tool call ${e}`,children:[(0,t.jsxs)("header",{children:[(0,t.jsx)("strong",{children:e}),(0,t.jsx)("span",{"data-role":"status","aria-live":"polite",children:s})]}),(0,t.jsxs)("details",{children:[(0,t.jsx)("summary",{children:"Input"}),(0,t.jsx)("pre",{children:JSON.stringify(r,null,2)})]}),void 0!==o&&(0,t.jsxs)("details",{open:!0,children:[(0,t.jsx)("summary",{children:"Output"}),(0,t.jsx)("pre",{children:"string"==typeof o?o:JSON.stringify(o,null,2)})]}),n&&(0,t.jsx)("p",{role:"alert","data-role":"error",children:n.message})]})},exports.ToolAbortError=U,exports.VectorMemory=class{constructor(t){this.opts=t,this.messages=[]}async append(t){this.messages.push(t),await(this.opts.onAppend?.(t))}async all(){const t=this.opts.keepRecent??6,e=this.messages.slice(-t),r=[...this.messages].reverse().find(t=>"user"===t.role);if(!r)return e;const o="string"==typeof r.content?r.content:"";if(!o)return e;const n=await this.opts.retriever.retrieve(o,{topK:this.opts.topK??4});return 0===n.length?e:[{role:"system",content:`Long-term memory recall:\n${n.map((t,e)=>`[${e+1}] (score=${t.score.toFixed(3)}) ${t.text}`).join("\n\n")}`},...e]}clear(){this.messages=[]}},exports.a2aTool=function(t){return{name:t.name,description:t.description,inputSchema:{type:"object",properties:{input:{type:"string",description:t.inputDescription??"Task for the remote agent."}},required:["input"]},async execute({input:e},r){const o=await t.client.sendTask({id:Y.newTaskId(),message:{role:"user",parts:[{type:"text",text:e}]}},r.signal),n=o.messages.filter(t=>"agent"===t.role).flatMap(t=>t.parts.map(t=>t.text)).join("");return"failed"===o.status?`Remote agent failed: ${n||"(no detail)"}`:n||"(no response)"}}},exports.agentAsTool=function(t){return{name:t.name,description:t.description,inputSchema:{type:"object",properties:{input:{type:"string",description:t.inputDescription??"Task or question for this sub-agent."}},required:["input"]},async execute({input:e},r){let o="";for await(const n of t.agent.run({message:e,signal:r.signal}))"text_delta"===n.type&&(o+=n.text);return o||"(sub-agent produced no output)"}}},exports.applyMiddleware=function(t,e){return 0===e.length?t:{async request(r){let o=r;for(const t of e)t.beforeRequest&&(o=await t.beforeRequest(o));let n=await t.request(o);for(const t of e)t.afterResponse&&(n=await t.afterResponse(n,o));return n}}},exports.cacheable=function(t){return{type:"text",text:t,cacheControl:{type:"ephemeral"}}},exports.cancellable=function(t){return{name:t.name,description:t.description,inputSchema:t.inputSchema,parse:t.parse,async execute(e,r){if(r.signal?.aborted)throw new U(t.name);return r.signal?Promise.race([t.execute(e,r),new Promise((e,o)=>{r.signal.addEventListener("abort",()=>o(new U(t.name)),{once:!0})})]):t.execute(e,r)}}},exports.checkGuardrails=P,exports.createA2ARoute=function(t){return async e=>{if("POST"!==e.method)return new Response("Method not allowed",{status:405});let o;try{o=await e.json()}catch{return new Response("Invalid JSON",{status:400})}const n=o.message?.parts?.filter(t=>"text"===t.type).map(t=>t.text).join("")??"";if(!n)return new Response("Empty task",{status:400});const s=await t.agent(e),i=new a({...s,memory:s.memory??new r});let l="";try{for await(const e of i.run({message:n}))"text_delta"===e.type&&(l+=e.text);const t={id:o.id,status:"completed",messages:[{role:"agent",parts:[{type:"text",text:l}]}]};return new Response(JSON.stringify(t),{status:200,headers:{"content-type":"application/json"}})}catch(c){const t={id:o.id,status:"failed",messages:[{role:"agent",parts:[{type:"text",text:c instanceof Error?c.message:String(c)}]}]};return new Response(JSON.stringify(t),{status:500,headers:{"content-type":"application/json"}})}}},exports.createAgent=l,exports.createAgentClient=function(t){const e=t.transport??o;return{async*run(r,o){const s=await e.request({url:t.endpoint,method:"POST",headers:{"content-type":"application/json",...t.headers},body:JSON.stringify({message:r}),signal:o});if(s.body){if(s.status>=400){const t=await s.text();throw new Error(`Agent route ${s.status}: ${t}`)}for await(const t of n(s.body)){if("[DONE]"===t.data)return;let e;try{const r=JSON.parse(t.data);r.error&&"string"==typeof r.error.message&&(r.error=new Error(r.error.message)),e=r}catch{continue}yield e}}}}},exports.createAgentController=G,exports.createAgentRoute=function(t){return async e=>{if("POST"!==e.method)return new Response("Method not allowed",{status:405});let o;try{o=await e.json()}catch{return new Response("Invalid JSON",{status:400})}const n=(t.parseInput?await t.parseInput(e,o):o).message;if("string"!=typeof n||!n.trim())return new Response("Missing message",{status:400});const s=await t.agent(e),i=new a({...s,memory:s.memory??new r}),l=new TextEncoder,c=new ReadableStream({async start(t){function e(e){t.enqueue(l.encode(`data: ${JSON.stringify(e)}\n\n`))}try{for await(const t of i.run({message:n}))e(L(t));t.enqueue(l.encode("data: [DONE]\n\n"))}catch(r){e({type:"error",error:{message:r instanceof Error?r.message:String(r)}})}finally{t.close()}}});return new Response(c,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform",connection:"keep-alive"}})}},exports.createAgentStore=function(t){const e=G(t),r=new Set;return e.subscribe(t=>{for(const e of r)e(t)}),{subscribe:t=>(t(e.getState()),r.add(t),()=>r.delete(t)),send:e.send,stop:e.stop,reset:e.reset,dispose:e.dispose}},exports.createDeepResearch=function(t){return new F(t)},exports.createTokenUsageTracker=function(t={}){const e={inputTokens:0,outputTokens:0,cachedInputTokens:0,totalCostUSD:0,byModel:{}};return{middleware:{name:"token-usage",onEvent(r){if("message_stop"!==r.type||!r.usage)return;const o=r.usage.inputTokens??0,n=r.usage.outputTokens??0,s=r.usage.cachedInputTokens??0;e.inputTokens+=o,e.outputTokens+=n,e.cachedInputTokens+=s,t.model&&(e.totalCostUSD+=function(r,o,n){const s=e.byModel[r]??={inputTokens:0,outputTokens:0,costUSD:0};s.inputTokens+=o,s.outputTokens+=n;const i=t.pricing?.[r];let a=0;return i&&(a=o*i.inputPerMillion/1e6+n*i.outputPerMillion/1e6,s.costUSD+=a),a}(t.model,o,n)),t.onUpdate?.(structuredClone(e))}},totals:()=>structuredClone(e),reset(){e.inputTokens=0,e.outputTokens=0,e.cachedInputTokens=0,e.totalCostUSD=0,e.byModel={}}}},exports.createUseAgentSolid=function(t){return function(e){const r=G(e),[o,n]=t.createSignal(r.getState()),s=r.subscribe(t=>n(t));return t.onCleanup(()=>{s(),r.dispose()}),{state:o,send:r.send,stop:r.stop,reset:r.reset}}},exports.createUseAgentVue=function(t){return function(e){const r=G(e),o=t.shallowRef(r.getState()),n=r.subscribe(t=>o.value=t);return t.onScopeDispose(()=>{n(),r.dispose()}),{state:o,send:r.send,stop:r.stop,reset:r.reset}}},exports.defineTool=function(t){return t},exports.extractCitations=function(t){const e=[];for(const r of t.matchAll(/\[Source\s+(\d+)(?:\s*\|\s*score=([\d.]+))?\]\s*\n?([^[]+?)(?=\n\n\[Source|\n---|$)/gs))e.push({id:r[1],score:r[2]?parseFloat(r[2]):void 0,text:r[3].trim()});return e},exports.fetchTransport=o,exports.formatCitationsList=function(t){return t.map(t=>`[${t.id}] ${t.source?`${t.source} — `:""}${t.text.slice(0,240)}`).join("\n")},exports.generateObject=C,exports.guardrailsMiddleware=function(t){return{name:"guardrails",async beforeRequest(e){if("string"!=typeof e.body)return e;let r;try{r=JSON.parse(e.body)}catch{return e}const o=r.messages;if(!Array.isArray(o))return e;let n=!1;for(const s of o){if("user"!==s.role)continue;if("string"!=typeof s.content)continue;const e=await P(s.content,t,"input");if(!e.allow)throw new q("input",e.reason??"blocked");e.replacement&&e.replacement!==s.content&&(s.content=e.replacement,n=!0)}return n?{...e,body:JSON.stringify(r)}:e}}},exports.imageBlock=function(t){return"base64"in t?{type:"image",source:{kind:"base64",data:t.base64,mediaType:t.mediaType??"image/png"}}:{type:"image",source:{kind:"url",data:t.url,mediaType:t.mediaType}}},exports.judgeWithLLM=function(t,e,r){return async(o,n)=>{const s=`Criteria: ${r}\n\n`+(n?`Expected: ${n}\n\n`:"")+`Actual output:\n${o}\n\nRespond with exactly "PASS" or "FAIL".`;let i="";for await(const r of t.stream({model:e,messages:[{role:"user",content:s}],maxTokens:8,temperature:0}))"text_delta"===r.type&&(i+=r.text);return/pass/i.test(i.trim())}},exports.mcpTools=async function(t,e){return(await t.listTools(e)).map(e=>function(t,e){return{name:e.name,description:e.description??"",inputSchema:e.inputSchema,execute:async(r,o)=>function(t){const e=(t.content??[]).filter(t=>"text"===t.type&&"string"==typeof t.text).map(t=>t.text).join("\n");return t.isError?`Tool reported error: ${e}`:e||"(empty result)"}(await t.callTool(e.name,r,o.signal))}}(t,e))},exports.mergeCitations=function(...t){const e=new Map;let r=1;for(const o of t)for(const t of o){const o=(t.source??"")+"|"+t.text.slice(0,80);e.has(o)||e.set(o,{...t,id:String(r++)})}return Array.from(e.values())},exports.noopSanitizer={sanitize:t=>t},exports.otelMiddleware=function(t){let e=null;const r=new Map;return{name:"otel",beforeRequest:e=>(t.sink.event("agent.http.request",{url:e.url,method:e.method,service:t.serviceName}),e),afterResponse:(e,r)=>(t.sink.event("agent.http.response",{url:r.url,status:e.status}),e),onEvent(o){"step_start"===o.type?(e?.end(),e=t.sink.spanStart("agent.step",{step:o.step})):"tool_call_start"===o.type?r.set(o.id,t.sink.spanStart("agent.tool",{name:o.name,id:o.id})):"tool_result"===o.type?(r.get(o.id)?.end({ok:!0}),r.delete(o.id)):"tool_error"===o.type?(r.get(o.id)?.end({ok:!1,error:o.error.message}),r.delete(o.id)):"message_stop"===o.type?t.sink.event("agent.message_stop",{reason:o.reason,inputTokens:o.usage?.inputTokens,outputTokens:o.usage?.outputTokens}):"done"===o.type&&(e?.end({reason:o.reason}),e=null)},onError(r){t.sink.event("agent.error",{message:r.message}),e?.end({error:!0}),e=null}}},exports.parseSSE=n,exports.piiRedactor=M,exports.promptInjectionDetector=R,exports.retrievalTool=N,exports.runEval=async function(t,e,r){const o=[];let n=0;for(const a of e){const s=Date.now();let l,c="";try{for await(const e of t.run({message:a.input,signal:r?.signal}))if("text_delta"===e.type&&(c+=e.text),"error"===e.type)throw e.error}catch(i){l=i instanceof Error?i:new Error(String(i))}const u=Date.now()-s;let p=!1;l||(p=a.judge?await a.judge(c,a.expected):void 0!==a.expected?c.toLowerCase().includes(a.expected.toLowerCase()):c.length>0),o.push({name:a.name,input:a.input,output:c,passed:p,durationMs:u,error:l,meta:a.meta}),r?.onProgress?.(++n,e.length)}const s=o.filter(t=>t.passed).length;return{total:o.length,passed:s,failed:o.length-s,passRate:0===o.length?0:s/o.length,totalDurationMs:o.reduce((t,e)=>t+e.durationMs,0),results:o}},exports.textBlock=function(t,e){return e?.cacheControl?{type:"text",text:t,cacheControl:e.cacheControl}:{type:"text",text:t}},exports.toolResultBlock=function(t,e,r){return{type:"tool_result",toolUseId:t,output:e,name:r?.name,isError:r?.isError}},exports.toolUseBlock=function(t,e,r){return{type:"tool_use",id:t,name:e,input:r}},exports.useAgent=function(t){const o=(0,e.useRef)(t.memory??new r),n=(0,e.useMemo)(()=>new a({...t,memory:o.current}),[t.provider,t.model]),[s,i]=(0,e.useState)([]),[l,c]=(0,e.useState)(""),[u,p]=(0,e.useState)(!1),[d,f]=(0,e.useState)(null),h=(0,e.useRef)(null),y=(0,e.useCallback)(async t=>{if(!t.trim())return;f(null),c(""),p(!0);const e=new AbortController;h.current=e,i(e=>[...e,{role:"user",content:t}]);let r="";try{for await(const o of n.run({message:t,signal:e.signal}))"text_delta"===o.type&&(r+=o.text,c(r));i(await Promise.resolve(o.current.all())),c("")}catch(s){f(s instanceof Error?s:new Error(String(s)))}finally{p(!1),h.current=null}},[n]),m=(0,e.useCallback)(()=>{h.current?.abort()},[]),g=(0,e.useCallback)(()=>{Promise.resolve(o.current.clear()),i([]),c(""),f(null)},[]);return(0,e.useEffect)(()=>()=>h.current?.abort(),[]),{messages:s,streamingText:l,isStreaming:u,error:d,send:y,stop:m,reset:g}},exports.useEventCollector=function(){const[t,r]=(0,e.useState)([]);return{events:t,middleware:(0,e.useMemo)(()=>({name:"devtools-collector",onEvent:t=>r(e=>[...e,t])}),[]),clear:(0,e.useCallback)(()=>r([]),[])}},exports.withRetry=function(t,e={}){const r=e.maxRetries??3,o=e.initialDelayMs??500,n=e.maxDelayMs??3e4,s=e.factor??2,i=e.jitter??!0,a=e.retryOn??(t=>429===t.status||t.status>=500&&t.status<600),l=e.retryOnError??(()=>!0);return{async request(e){let c,u=0;for(;u<=r;)try{const l=await t.request(e);if(u<r&&a(l)){await A(J(u,o,n,s,i),e.signal),u++;continue}return l}catch(p){if(c=p,e.signal?.aborted)throw p;if(u>=r||!l(p))throw p;await A(J(u,o,n,s,i),e.signal),u++}throw c??new Error("retry: exhausted")}}};
package/dist/agent.js ADDED
@@ -0,0 +1,17 @@
1
+ import{Fragment as t,jsx as e,jsxs as r}from"react/jsx-runtime";import{useCallback as n,useEffect as o,useMemo as s,useRef as i,useState as a}from"react";function l(t){return t}var c=class{constructor(){this.messages=[]}append(t){this.messages.push(t)}all(){return this.messages.slice()}clear(){this.messages=[]}},u={async request(t){const e=await fetch(t.url,{method:t.method,headers:t.headers,body:t.body,signal:t.signal}),r={};return e.headers.forEach((t,e)=>{r[e]=t}),{status:e.status,headers:r,body:e.body,json:()=>e.json(),text:()=>e.text()}}};function d(t,e){return 0===e.length?t:{async request(r){let n=r;for(const t of e)t.beforeRequest&&(n=await t.beforeRequest(n));let o=await t.request(n);for(const t of e)t.afterResponse&&(o=await t.afterResponse(o,n));return o}}}var p={sanitize:t=>t};async function*f(t){const e=t.getReader(),r=new TextDecoder;let n="";try{for(;;){const{done:t,value:o}=await e.read();if(t)break;n+=r.decode(o,{stream:!0});let s=h(n);for(;-1!==s.index;){const t=n.slice(0,s.index);n=n.slice(s.index+s.length);const e=y(t);e&&(yield e),s=h(n)}}if(n.length>0){const t=y(n);t&&(yield t)}}finally{e.releaseLock()}}function h(t){const e=t.indexOf("\n\n"),r=t.indexOf("\r\n\r\n");return-1===e&&-1===r?{index:-1,length:0}:-1===e?{index:r,length:4}:-1===r||e<r?{index:e,length:2}:{index:r,length:4}}function y(t){let e,r;const n=[];for(const o of t.split(/\r?\n/))o.startsWith(":")||(o.startsWith("event:")?e=o.slice(6).trim():o.startsWith("id:")?r=o.slice(3).trim():o.startsWith("data:")&&n.push(o.slice(5).replace(/^ /,"")));return 0===n.length?null:{event:e,id:r,data:n.join("\n")}}var m=class{constructor(t){this.opts=t,this.memory=t.memory??new c,this.toolByName=new Map((t.tools??[]).map(t=>[t.name,t])),this.toolDefs=(t.tools??[]).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}async*run(t){const e=this.opts.middleware??[],r=this.opts.maxSteps??10;await Promise.resolve(this.memory.append({role:"user",content:t.message}));for(let o=0;o<r;o++){const r={type:"step_start",step:o};yield r,await w(e,r);const s=await Promise.resolve(this.memory.all()),i=[],a=/* @__PURE__ */new Map;let l="",c="end_turn";const u={model:this.opts.model,messages:s,system:this.opts.system,tools:this.toolDefs.length?this.toolDefs:void 0,maxTokens:this.opts.maxTokens,temperature:this.opts.temperature,signal:t.signal};try{for await(const t of this.opts.provider.stream(u))if("text_delta"===t.type)l+=t.text,yield t,await w(e,t);else if("tool_call_start"===t.type)l&&(i.push({type:"text",text:l}),l=""),a.set(t.id,{name:t.name,input:void 0}),yield t,await w(e,t);else if("tool_call_delta"===t.type)yield t,await w(e,t);else if("tool_call_end"===t.type){const r=a.get(t.id);r&&(r.input=t.input,i.push({type:"tool_use",id:t.id,name:r.name,input:t.input})),yield t,await w(e,t)}else if("message_stop"===t.type)l&&(i.push({type:"text",text:l}),l=""),c=t.reason,yield t,await w(e,t);else if("error"===t.type)return yield t,await w(e,t),await _(e,t.error),void(yield{type:"done",reason:"error"})}catch(n){const t=n instanceof Error?n:new Error(String(n)),r={type:"error",error:t};return yield r,await w(e,r),await _(e,t),void(yield{type:"done",reason:"error"})}if(i.length>0&&await Promise.resolve(this.memory.append({role:"assistant",content:i})),"tool_use"!==c||0===a.size)return void(yield{type:"done",reason:c});const d=[];for(const[o,{name:p,input:f}]of a){const r=this.toolByName.get(p);if(!r){const t={type:"tool_error",id:o,name:p,error:/* @__PURE__ */new Error(`Tool not registered: ${p}`)};yield t,await w(e,t),d.push({type:"tool_result",toolUseId:o,output:`Error: tool '${p}' is not registered`,isError:!0});continue}try{const n=r.parse?r.parse(f):f,s=await r.execute(n,{signal:t.signal,messages:await Promise.resolve(this.memory.all())}),i={type:"tool_result",id:o,name:p,output:s};yield i,await w(e,i),d.push({type:"tool_result",toolUseId:o,name:p,output:s})}catch(n){const t=n instanceof Error?n:new Error(String(n)),r={type:"tool_error",id:o,name:p,error:t};yield r,await w(e,r),await _(e,t),d.push({type:"tool_result",toolUseId:o,output:t.message,isError:!0})}}await Promise.resolve(this.memory.append({role:"tool",content:d}))}yield{type:"done",reason:"max_tokens"}}};function g(t){return new m(t)}async function w(t,e){for(const r of t)if(r.onEvent)try{await r.onEvent(e)}catch{}}async function _(t,e){for(const r of t)if(r.onError)try{await r.onError(e)}catch{}}var x=class{constructor(t={}){this.opts=t,this.name="anthropic",this.transport=t.transport??u}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream","anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"https://api.anthropic.com/v1/messages",method:"POST",headers:e,body:JSON.stringify(v(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:/* @__PURE__ */new Error(`Anthropic ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:/* @__PURE__ */new Error("Anthropic: empty response body")});const n=/* @__PURE__ */new Map;let o,s="end_turn";for await(const a of f(r.body)){let t;try{t=JSON.parse(a.data)}catch{continue}const e=t.type??a.event,r=t.index??0;if("content_block_start"===e){const e=t.content_block;"tool_use"===e?.type&&e.id&&e.name&&(n.set(r,{id:e.id,name:e.name,json:""}),yield{type:"tool_call_start",id:e.id,name:e.name})}else if("content_block_delta"===e){const e=t.delta;if("text_delta"===e?.type&&"string"==typeof e.text)yield{type:"text_delta",text:e.text};else if("input_json_delta"===e?.type&&"string"==typeof e.partial_json){const t=n.get(r);t&&(t.json+=e.partial_json,yield{type:"tool_call_delta",id:t.id,argsDelta:e.partial_json})}}else if("content_block_stop"===e){const t=n.get(r);if(t){let e={};if(t.json)try{e=JSON.parse(t.json)}catch(i){return void(yield{type:"error",error:i})}yield{type:"tool_call_end",id:t.id,input:e},n.delete(r)}}else if("message_delta"===e)t.delta?.stop_reason&&(s=b(t.delta.stop_reason)),t.usage&&(o={inputTokens:t.usage.input_tokens,outputTokens:t.usage.output_tokens});else{if("message_stop"===e)return void(yield{type:"message_stop",reason:s,usage:o});if("error"===e)return void(yield{type:"error",error:new Error(t.error?.message??"Anthropic stream error")})}}}};function b(t){switch(t){case"end_turn":case"tool_use":case"max_tokens":case"stop_sequence":return t;default:return"end_turn"}}function v(t){return{model:t.model,max_tokens:t.maxTokens??4096,system:t.system,messages:t.messages.filter(t=>"system"!==t.role).map(T),tools:t.tools?.map(S),temperature:t.temperature,top_p:t.topP,stop_sequences:t.stopSequences,stream:!0}}function S(t){return{name:t.name,description:t.description,input_schema:t.inputSchema}}function T(t){return"tool"===t.role?{role:"user",content:(Array.isArray(t.content)?t.content:[]).map(E)}:"string"==typeof t.content?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(E)}}function E(t){switch(t.type){case"text":return t.cacheControl?{type:"text",text:t.text,cache_control:t.cacheControl}:{type:"text",text:t.text};case"image":return{type:"image",source:"base64"===t.source.kind?{type:"base64",media_type:t.source.mediaType??"image/png",data:t.source.data}:{type:"url",url:t.source.data}};case"tool_use":return{type:"tool_use",id:t.id,name:t.name,input:t.input};case"tool_result":return{type:"tool_result",tool_use_id:t.toolUseId,content:"string"==typeof t.output?t.output:JSON.stringify(t.output),is_error:t.isError}}}var k=class{constructor(t={}){this.opts=t,this.name="openai",this.transport=t.transport??u}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.organization?{"openai-organization":this.opts.organization}:{},...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"https://api.openai.com/v1/chat/completions",method:"POST",headers:e,body:JSON.stringify($(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:/* @__PURE__ */new Error(`OpenAI ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:/* @__PURE__ */new Error("OpenAI: empty response body")});const n=/* @__PURE__ */new Map;let o,s="end_turn";for await(const i of f(r.body)){if("[DONE]"===i.data)break;let t;try{t=JSON.parse(i.data)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error.message??"OpenAI error")});t.usage&&(o={inputTokens:t.usage.prompt_tokens,outputTokens:t.usage.completion_tokens});const e=t.choices?.[0];if(e){if(e.delta?.content&&(yield{type:"text_delta",text:e.delta.content}),e.delta?.tool_calls)for(const t of e.delta.tool_calls){let e=n.get(t.index);e||(e={id:t.id??`tool_${t.index}`,name:"",args:"",started:!1},n.set(t.index,e)),t.id&&(e.id=t.id),t.function?.name&&(e.name=t.function.name),!e.started&&e.id&&e.name&&(yield{type:"tool_call_start",id:e.id,name:e.name},e.started=!0),t.function?.arguments&&(e.args+=t.function.arguments,e.started&&(yield{type:"tool_call_delta",id:e.id,argsDelta:t.function.arguments}))}if(e.finish_reason){for(const t of n.values()){let e={};if(t.args)try{e=JSON.parse(t.args)}catch{e=t.args}yield{type:"tool_call_end",id:t.id,input:e}}return s=O(e.finish_reason),void(yield{type:"message_stop",reason:s,usage:o})}}}}};function O(t){switch(t){case"stop":default:return"end_turn";case"tool_calls":case"function_call":return"tool_use";case"length":return"max_tokens";case"content_filter":return"stop_sequence"}}function $(t){const e=[];t.system&&e.push({role:"system",content:t.system});for(const r of t.messages)if("system"===r.role)e.push({role:"system",content:A(r.content)});else if("tool"===r.role){const t=Array.isArray(r.content)?r.content:[];for(const r of t)"tool_result"===r.type&&e.push({role:"tool",tool_call_id:r.toolUseId,content:"string"==typeof r.output?r.output:JSON.stringify(r.output)})}else"assistant"===r.role?e.push(J(r)):e.push({role:"user",content:q(r.content)});return{model:t.model,messages:e,tools:t.tools?.map(N),max_tokens:t.maxTokens,temperature:t.temperature,top_p:t.topP,stop:t.stopSequences,stream:!0}}function N(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}}function J(t){if("string"==typeof t.content)return{role:"assistant",content:t.content};const e=[],r=[];for(const o of t.content)"text"===o.type?e.push(o.text):"tool_use"===o.type&&r.push({id:o.id,type:"function",function:{name:o.name,arguments:JSON.stringify(o.input)}});const n={role:"assistant",content:e.length?e.join(""):null};return r.length&&(n.tool_calls=r),n}function A(t){return"string"==typeof t?t:t.filter(t=>"text"===t.type).map(t=>t.text).join("")}function q(t){if("string"==typeof t)return t;const e=[];for(const r of t)if("text"===r.type)e.push({type:"text",text:r.text});else if("image"===r.type){const t="base64"===r.source.kind?`data:${r.source.mediaType??"image/png"};base64,${r.source.data}`:r.source.data;e.push({type:"image_url",image_url:{url:t}})}return e}var P=class{constructor(t={}){this.opts=t,this.name="gemini",this.transport=t.transport??u}async*stream(t){const e={"content-type":"application/json",accept:"text/event-stream",...this.opts.headers},r=await this.transport.request({url:this.buildUrl(t.model),method:"POST",headers:e,body:JSON.stringify(M(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:/* @__PURE__ */new Error(`Gemini ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:/* @__PURE__ */new Error("Gemini: empty response body")});let n,o="end_turn",s=0;for await(const i of f(r.body)){let t;try{t=JSON.parse(i.data)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error.message??"Gemini error")});t.usageMetadata&&(n={inputTokens:t.usageMetadata.promptTokenCount,outputTokens:t.usageMetadata.candidatesTokenCount});const e=t.candidates?.[0];if(e){for(const t of e.content?.parts??[])if("string"==typeof t.text&&t.text.length>0)yield{type:"text_delta",text:t.text};else if(t.functionCall?.name){const e="gemini_call_"+s++,r=JSON.stringify(t.functionCall.args??{});yield{type:"tool_call_start",id:e,name:t.functionCall.name},yield{type:"tool_call_delta",id:e,argsDelta:r},yield{type:"tool_call_end",id:e,input:t.functionCall.args??{}}}if(e.finishReason)return o=D(e.finishReason),void(yield{type:"message_stop",reason:o,usage:n})}}}buildUrl(t){const e=`${this.opts.endpoint??"https://generativelanguage.googleapis.com/v1beta"}/models/${t}:streamGenerateContent?alt=sse`;return this.opts.apiKey?`${e}&key=${encodeURIComponent(this.opts.apiKey)}`:e}};function D(t){switch(t){case"STOP":default:return"end_turn";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"RECITATION":return"stop_sequence"}}function M(t){return{contents:t.messages.filter(t=>"system"!==t.role).map(R),systemInstruction:t.system?{parts:[{text:t.system}]}:void 0,tools:t.tools?.length?[{functionDeclarations:t.tools.map(j)}]:void 0,generationConfig:{maxOutputTokens:t.maxTokens,temperature:t.temperature,topP:t.topP,stopSequences:t.stopSequences}}}function j(t){return{name:t.name,description:t.description,parameters:t.inputSchema}}function R(t){if("tool"===t.role)return{role:"function",parts:(Array.isArray(t.content)?t.content:[]).flatMap(t=>"tool_result"===t.type?[{functionResponse:{name:t.name??"",response:"object"==typeof t.output&&null!==t.output?t.output:{result:String(t.output)}}}]:[])};const e="assistant"===t.role?"model":"user";return"string"==typeof t.content?{role:e,parts:[{text:t.content}]}:{role:e,parts:t.content.flatMap(I)}}function I(t){return"text"===t.type?[{text:t.text}]:"image"===t.type?"base64"===t.source.kind?[{inlineData:{mimeType:t.source.mediaType??"image/png",data:t.source.data}}]:[{fileData:{fileUri:t.source.data,mimeType:t.source.mediaType}}]:"tool_use"===t.type?[{functionCall:{name:t.name,args:t.input}}]:[]}var C=class{constructor(t={}){this.opts=t,this.name="ollama",this.transport=t.transport??u}async*stream(t){const e={"content-type":"application/json",...this.opts.headers},r=await this.transport.request({url:this.opts.endpoint??"http://localhost:11434/api/chat",method:"POST",headers:e,body:JSON.stringify(z(t)),signal:t.signal});if(r.status>=400){const t=await r.text();return void(yield{type:"error",error:/* @__PURE__ */new Error(`Ollama ${r.status}: ${t}`)})}if(!r.body)return void(yield{type:"error",error:/* @__PURE__ */new Error("Ollama: empty response body")});let n,o="end_turn",s=0,i=!1;for await(const a of async function*(t){const e=t.getReader(),r=new TextDecoder;let n="";try{for(;;){const{done:t,value:o}=await e.read();if(t)break;n+=r.decode(o,{stream:!0});let s=n.indexOf("\n");for(;-1!==s;){const t=n.slice(0,s).trim();n=n.slice(s+1),t&&(yield t),s=n.indexOf("\n")}}n.trim()&&(yield n.trim())}finally{e.releaseLock()}}(r.body)){let t;try{t=JSON.parse(a)}catch{continue}if(t.error)return void(yield{type:"error",error:new Error(t.error)});"number"!=typeof t.prompt_eval_count&&"number"!=typeof t.eval_count||(n={inputTokens:t.prompt_eval_count,outputTokens:t.eval_count});const e=t.message;if(e?.content&&(yield{type:"text_delta",text:e.content}),e?.tool_calls?.length){i=!0;for(const t of e.tool_calls){const e=t.function?.name;if(!e)continue;const r=t.function?.arguments??{},n="ollama_call_"+s++;yield{type:"tool_call_start",id:n,name:e},yield{type:"tool_call_delta",id:n,argsDelta:JSON.stringify(r)},yield{type:"tool_call_end",id:n,input:r}}}if(t.done)return o=i?"tool_use":"length"===t.done_reason?"max_tokens":"end_turn",void(yield{type:"message_stop",reason:o,usage:n})}}};function z(t){const e=[];t.system&&e.push({role:"system",content:t.system});for(const r of t.messages)if("tool"===r.role){const t=Array.isArray(r.content)?r.content:[];for(const r of t)"tool_result"===r.type&&e.push({role:"tool",content:"string"==typeof r.output?r.output:JSON.stringify(r.output)})}else if("string"==typeof r.content)e.push({role:r.role,content:r.content});else{const t=r.content.filter(t=>"text"===t.type).map(t=>t.text).join(""),n=r.content.filter(t=>"tool_use"===t.type),o={role:r.role,content:t};n.length&&(o.tool_calls=n.map(t=>({function:{name:t.name,arguments:t.input}}))),e.push(o)}return{model:t.model,messages:e,tools:t.tools?.map(U),stream:!0,options:{temperature:t.temperature,top_p:t.topP,num_predict:t.maxTokens,stop:t.stopSequences}}}function U(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}}function F(t){return{name:t.name??"search_knowledge",description:t.description??"Search the internal knowledge base. Use this whenever the user asks about content that may exist in stored documents.",inputSchema:{type:"object",properties:{query:{type:"string",description:"A complete question or topic phrase — not a single keyword."}},required:["query"]},async execute({query:e},r){const n=await t.retriever.retrieve(e,{topK:t.topK??4,signal:r.signal});return 0===n.length?"No relevant documents found.":n.map((t,e)=>`[Source ${e+1} | score=${t.score.toFixed(3)}]\n${t.text}`).join("\n\n---\n\n")}}}function G(t){return{name:t.name,description:t.description,inputSchema:{type:"object",properties:{input:{type:"string",description:t.inputDescription??"Task or question for this sub-agent."}},required:["input"]},async execute({input:e},r){let n="";for await(const o of t.agent.run({message:e,signal:r.signal}))"text_delta"===o.type&&(n+=o.text);return n||"(sub-agent produced no output)"}}}function L(t={}){const e={inputTokens:0,outputTokens:0,cachedInputTokens:0,totalCostUSD:0,byModel:{}};return{middleware:{name:"token-usage",onEvent(r){if("message_stop"!==r.type||!r.usage)return;const n=r.usage.inputTokens??0,o=r.usage.outputTokens??0,s=r.usage.cachedInputTokens??0;e.inputTokens+=n,e.outputTokens+=o,e.cachedInputTokens+=s,t.model&&(e.totalCostUSD+=function(r,n,o){const s=e.byModel[r]??={inputTokens:0,outputTokens:0,costUSD:0};s.inputTokens+=n,s.outputTokens+=o;const i=t.pricing?.[r];let a=0;return i&&(a=n*i.inputPerMillion/1e6+o*i.outputPerMillion/1e6,s.costUSD+=a),a}(t.model,n,o)),t.onUpdate?.(structuredClone(e))}},totals:()=>structuredClone(e),reset(){e.inputTokens=0,e.outputTokens=0,e.cachedInputTokens=0,e.totalCostUSD=0,e.byModel={}}}}function B(t,e={}){const r=e.maxRetries??3,n=e.initialDelayMs??500,o=e.maxDelayMs??3e4,s=e.factor??2,i=e.jitter??!0,a=e.retryOn??(t=>429===t.status||t.status>=500&&t.status<600),l=e.retryOnError??(()=>!0);return{async request(e){let c,u=0;for(;u<=r;)try{const l=await t.request(e);if(u<r&&a(l)){await Y(K(u,n,o,s,i),e.signal),u++;continue}return l}catch(d){if(c=d,e.signal?.aborted)throw d;if(u>=r||!l(d))throw d;await Y(K(u,n,o,s,i),e.signal),u++}throw c??/* @__PURE__ */new Error("retry: exhausted")}}}function K(t,e,r,n,o){const s=Math.min(e*Math.pow(n,t),r);return o?Math.random()*s:s}function Y(t,e){return new Promise((r,n)=>{if(e?.aborted)return void n(/* @__PURE__ */new Error("aborted"));const o=setTimeout(()=>{e?.removeEventListener("abort",s),r()},t),s=()=>{clearTimeout(o),n(/* @__PURE__ */new Error("aborted"))};e?.addEventListener("abort",s,{once:!0})})}function Z(t){let e=null;const r=/* @__PURE__ */new Map;return{name:"otel",beforeRequest:e=>(t.sink.event("agent.http.request",{url:e.url,method:e.method,service:t.serviceName}),e),afterResponse:(e,r)=>(t.sink.event("agent.http.response",{url:r.url,status:e.status}),e),onEvent(n){"step_start"===n.type?(e?.end(),e=t.sink.spanStart("agent.step",{step:n.step})):"tool_call_start"===n.type?r.set(n.id,t.sink.spanStart("agent.tool",{name:n.name,id:n.id})):"tool_result"===n.type?(r.get(n.id)?.end({ok:!0}),r.delete(n.id)):"tool_error"===n.type?(r.get(n.id)?.end({ok:!1,error:n.error.message}),r.delete(n.id)):"message_stop"===n.type?t.sink.event("agent.message_stop",{reason:n.reason,inputTokens:n.usage?.inputTokens,outputTokens:n.usage?.outputTokens}):"done"===n.type&&(e?.end({reason:n.reason}),e=null)},onError(r){t.sink.event("agent.error",{message:r.message}),e?.end({error:!0}),e=null}}}var V=class extends Error{constructor(t,e){super(`Guardrail violation [${t}]: ${e}`),this.guardrailName=t,this.reason=e,this.name="GuardrailViolation"}};async function H(t,e,r){let n=t;for(const o of e){const t="input"===r?o.checkInput:o.checkOutput;if(!t)continue;const e=await t(n);if(!e.allow)return{allow:!1,reason:e.reason,replacement:n};e.replacement&&(n=e.replacement)}return{allow:!0,replacement:n}}function X(t){return{name:"guardrails",async beforeRequest(e){if("string"!=typeof e.body)return e;let r;try{r=JSON.parse(e.body)}catch{return e}const n=r.messages;if(!Array.isArray(n))return e;let o=!1;for(const s of n){if("user"!==s.role)continue;if("string"!=typeof s.content)continue;const e=await H(s.content,t,"input");if(!e.allow)throw new V("input",e.reason??"blocked");e.replacement&&e.replacement!==s.content&&(s.content=e.replacement,o=!0)}return o?{...e,body:JSON.stringify(r)}:e}}}var Q=[{regex:/\b\d{3}-\d{2}-\d{4}\b/g,label:"SSN"},{regex:/\b(?:\d[ -]*?){13,16}\b/g,label:"CREDIT_CARD"},{regex:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,label:"EMAIL"}],W={name:"pii-redactor",checkInput(t){let e=t;for(const{regex:r,label:n}of Q)e=e.replace(r,`[REDACTED:${n}]`);return{allow:!0,replacement:e}}},tt=[/ignore (?:all )?previous instructions/i,/disregard (?:the )?system prompt/i,/you are now (?:a |an )?different/i],et={name:"prompt-injection",checkInput(t){for(const e of tt)if(e.test(t))return{allow:!1,reason:`potential prompt injection: ${e}`};return{allow:!0}}},rt=class{constructor(t){if(this.windowSize=t,this.messages=[],t<1)throw new Error("windowSize must be >= 1")}append(t){for(this.messages.push(t);this.messages.length>this.windowSize;)this.messages.shift()}all(){return this.messages.slice()}clear(){this.messages=[]}},nt=class{constructor(t){if(this.opts=t,this.messages=[],this.summary="",t.threshold<2)throw new Error("threshold must be >= 2")}async append(t){this.messages.push(t);const e=this.opts.keepRecent??4;if(this.messages.length>this.opts.threshold){const t=this.messages.slice(0,this.messages.length-e);this.messages=this.messages.slice(-e);const r=await this.opts.summarizer(t);this.summary=this.summary?`${this.summary}\n${r}`:r}}all(){return this.summary?[{role:"system",content:`Prior conversation summary:\n${this.summary}`},...this.messages]:this.messages.slice()}clear(){this.messages=[],this.summary=""}},ot=class{constructor(t){this.opts=t,this.messages=[]}async append(t){this.messages.push(t),await(this.opts.onAppend?.(t))}async all(){const t=this.opts.keepRecent??6,e=this.messages.slice(-t),r=[...this.messages].reverse().find(t=>"user"===t.role);if(!r)return e;const n="string"==typeof r.content?r.content:"";if(!n)return e;const o=await this.opts.retriever.retrieve(n,{topK:this.opts.topK??4});return 0===o.length?e:[{role:"system",content:`Long-term memory recall:\n${o.map((t,e)=>`[${e+1}] (score=${t.score.toFixed(3)}) ${t.text}`).join("\n\n")}`},...e]}clear(){this.messages=[]}},st=class extends Error{constructor(t,e){super(t),this.raw=e,this.name="StructuredOutputError"}};async function it(t){const e=`${t.system?`${t.system}\n\n`:""}You MUST respond with valid JSON only — no commentary, no markdown fences. The JSON must conform to this JSON Schema:\n${JSON.stringify(t.schema,null,2)}`,r=t.maxRetries??1;let n="",o=null;for(let i=0;i<=r;i++){let r="";for await(const n of t.provider.stream({model:t.model,messages:[{role:"user",content:t.prompt}],system:e,maxTokens:t.maxTokens,temperature:t.temperature??0,signal:t.signal}))if("text_delta"===n.type&&(r+=n.text),"error"===n.type)throw n.error;n=r;try{const e=at(r),n=JSON.parse(e);return t.parse?t.parse(n):n}catch(s){o=s instanceof Error?s:new Error(String(s))}}throw new st(`Failed to parse JSON after ${r+1} attempt(s): ${o?.message}`,n)}function at(t){const e=t.trim(),r=e.match(/```(?:json)?\s*([\s\S]+?)\s*```/);if(r)return r[1].trim();const n=Math.min(...["[","{"].map(t=>{const r=e.indexOf(t);return-1===r?1/0:r})),o=Math.max(e.lastIndexOf("]"),e.lastIndexOf("}"));return n!==1/0&&o>n?e.slice(n,o+1):e}function lt(t,e){return e?.cacheControl?{type:"text",text:t,cacheControl:e.cacheControl}:{type:"text",text:t}}function ct(t){return{type:"text",text:t,cacheControl:{type:"ephemeral"}}}function ut(t){return"base64"in t?{type:"image",source:{kind:"base64",data:t.base64,mediaType:t.mediaType??"image/png"}}:{type:"image",source:{kind:"url",data:t.url,mediaType:t.mediaType}}}function dt(t,e,r){return{type:"tool_use",id:t,name:e,input:r}}function pt(t,e,r){return{type:"tool_result",toolUseId:t,output:e,name:r?.name,isError:r?.isError}}var ft=class{constructor(t){this.opts=t,this.idSeq=0,this.initialized=!1,this.transport=t.transport??u}async initialize(t){this.initialized||(await this.call("initialize",{protocolVersion:"2024-11-05",capabilities:{tools:{}},clientInfo:this.opts.clientInfo??{name:"tekivex-ui-agent",version:"1.0"}},t),this.initialized=!0)}async listTools(t){return await this.initialize(t),(await this.call("tools/list",{},t)).tools??[]}async callTool(t,e,r){return await this.initialize(r),await this.call("tools/call",{name:t,arguments:e},r)}async call(t,e,r){const n=++this.idSeq,o=await this.transport.request({url:this.opts.endpoint,method:"POST",headers:{"content-type":"application/json",accept:"application/json",...this.opts.headers},body:JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:e}),signal:r});if(o.status>=400){const e=await o.text();throw new Error(`MCP ${t} failed (${o.status}): ${e}`)}const s=await o.json();if(s.error)throw new Error(`MCP error ${s.error.code}: ${s.error.message}`);return s.result}};async function ht(t,e){return(await t.listTools(e)).map(e=>function(t,e){return{name:e.name,description:e.description??"",inputSchema:e.inputSchema,execute:async(r,n)=>function(t){const e=(t.content??[]).filter(t=>"text"===t.type&&"string"==typeof t.text).map(t=>t.text).join("\n");return t.isError?`Tool reported error: ${e}`:e||"(empty result)"}(await t.callTool(e.name,r,n.signal))}}(t,e))}async function yt(t,e,r){const n=[];let o=0;for(const a of e){const s=Date.now();let l,c="";try{for await(const e of t.run({message:a.input,signal:r?.signal}))if("text_delta"===e.type&&(c+=e.text),"error"===e.type)throw e.error}catch(i){l=i instanceof Error?i:new Error(String(i))}const u=Date.now()-s;let d=!1;l||(d=a.judge?await a.judge(c,a.expected):void 0!==a.expected?c.toLowerCase().includes(a.expected.toLowerCase()):c.length>0),n.push({name:a.name,input:a.input,output:c,passed:d,durationMs:u,error:l,meta:a.meta}),r?.onProgress?.(++o,e.length)}const s=n.filter(t=>t.passed).length;return{total:n.length,passed:s,failed:n.length-s,passRate:0===n.length?0:s/n.length,totalDurationMs:n.reduce((t,e)=>t+e.durationMs,0),results:n}}function mt(t,e,r){return async(n,o)=>{const s=`Criteria: ${r}\n\n`+(o?`Expected: ${o}\n\n`:"")+`Actual output:\n${n}\n\nRespond with exactly "PASS" or "FAIL".`;let i="";for await(const r of t.stream({model:e,messages:[{role:"user",content:s}],maxTokens:8,temperature:0}))"text_delta"===r.type&&(i+=r.text);return/pass/i.test(i.trim())}}var gt=class extends Error{constructor(t){super(`Tool '${t}' aborted`),this.toolName=t,this.name="ToolAbortError"}};function wt(t){return{name:t.name,description:t.description,inputSchema:t.inputSchema,parse:t.parse,async execute(e,r){if(r.signal?.aborted)throw new gt(t.name);return r.signal?Promise.race([t.execute(e,r),new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(new gt(t.name)),{once:!0})})]):t.execute(e,r)}}}function _t({message:t,streamingText:n,renderToolCall:o,renderToolResult:s,className:i,style:a}){const l="string"==typeof t.content?[{type:"text",text:t.content}]:t.content;/* @__PURE__ */
2
+ return r("div",{className:i,style:a,"data-role":t.role,role:"article","aria-label":`${t.role} message`,children:[l.map((t,n)=>"text"===t.type?/* @__PURE__ */e("div",{"data-block":"text",children:t.text},n):"tool_use"===t.type?/* @__PURE__ */e("div",{"data-block":"tool_use",children:o?o(t):/* @__PURE__ */r("code",{children:[t.name,"(",JSON.stringify(t.input),")"]})},n):"tool_result"===t.type?/* @__PURE__ */e("div",{"data-block":"tool_result",children:s?s(t):/* @__PURE__ */e("pre",{children:"string"==typeof t.output?t.output:JSON.stringify(t.output,null,2)})},n):"image"===t.type?/* @__PURE__ */e("img",{src:"base64"===t.source.kind?`data:${t.source.mediaType??"image/png"};base64,${t.source.data}`:t.source.data,alt:"","data-block":"image"},n):null),n?/* @__PURE__ */e("div",{"data-block":"streaming",children:n}):null]})}function xt({name:t,input:n,output:o,error:s,status:i,className:a,style:l}){/* @__PURE__ */
3
+ return r("section",{className:a,style:l,"data-status":i,role:"region","aria-label":`Tool call ${t}`,children:[
4
+ /* @__PURE__ */r("header",{children:[/* @__PURE__ */e("strong",{children:t}),/* @__PURE__ */e("span",{"data-role":"status","aria-live":"polite",children:i})]}),
5
+ /* @__PURE__ */r("details",{children:[/* @__PURE__ */e("summary",{children:"Input"}),/* @__PURE__ */e("pre",{children:JSON.stringify(n,null,2)})]}),void 0!==o&&/* @__PURE__ */r("details",{open:!0,children:[/* @__PURE__ */e("summary",{children:"Output"}),/* @__PURE__ */e("pre",{children:"string"==typeof o?o:JSON.stringify(o,null,2)})]}),s&&/* @__PURE__ */e("p",{role:"alert","data-role":"error",children:s.message})]})}function bt({events:t,hideTextDeltas:n=!0,className:o,style:s}){/* @__PURE__ */
6
+ return e("ol",{className:o,style:s,"aria-label":"Reasoning trace",children:t.map((t,o)=>function(t,n,o){switch(t.type){case"step_start":/* @__PURE__ */return r("li",{"data-type":"step",children:["Step ",t.step]},n);case"text_delta":return o?null:/* @__PURE__ */e("li",{"data-type":"text",children:t.text},n);case"tool_call_start":/* @__PURE__ */return r("li",{"data-type":"tool-start",children:["→ ",t.name," ",
7
+ /* @__PURE__ */r("small",{children:["(",t.id,")"]})]},n);case"tool_call_end":/* @__PURE__ */return r("li",{"data-type":"tool-args",children:["input: ",/* @__PURE__ */e("code",{children:JSON.stringify(t.input)})]},n);case"tool_result":/* @__PURE__ */return r("li",{"data-type":"tool-result",children:["✓ ",t.name," returned"]},n);case"tool_error":/* @__PURE__ */return r("li",{"data-type":"tool-error",children:["✗ ",t.name,": ",t.error.message]},n);case"message_stop":/* @__PURE__ */return r("li",{"data-type":"stop",children:["stop (",t.reason,")"]},n);case"done":/* @__PURE__ */return r("li",{"data-type":"done",children:["done (",t.reason,")"]},n);case"error":/* @__PURE__ */return r("li",{"data-type":"error",children:["error: ",t.error.message]},n);default:return null}}(t,o,n))})}var vt=class{constructor(t){this.opts=t}async run(t,e){const r=e??this.opts.signal,n=[...this.opts.tools??[]];this.opts.retriever&&n.push(F({retriever:this.opts.retriever}));const o=await it({provider:this.opts.provider,model:this.opts.model,schema:{type:"object",properties:{subtasks:{type:"array",maxItems:this.opts.maxSubtasks??5,items:{type:"object",properties:{id:{type:"string"},question:{type:"string"}},required:["id","question"]}}},required:["subtasks"]},system:"You are a research planner. Break the user's question into 3-5 atomic, independently researchable sub-questions.",prompt:t,signal:r}),s=this.opts.concurrency??3,i=await async function(t,e,r){const n=new Array(t.length);let o=0;return await Promise.all(Array.from({length:Math.min(e,t.length)},async function(){for(;;){const e=o++;if(e>=t.length)return;n[e]=await r(t[e])}})),n}(o.subtasks,s,t=>this.research(t.id,t.question,n,r)),a=g({provider:this.opts.provider,model:this.opts.model,system:"Synthesize sub-agent findings into one coherent answer. Preserve citations and call out conflicts."}),l=`Original question: ${t}\n\n`+i.map(t=>`## Sub-question [${t.id}]: ${t.question}\n`+(t.error?`(Error: ${t.error})`:t.findings)).join("\n\n---\n\n");let c="";for await(const u of a.run({message:l,signal:r}))"text_delta"===u.type&&(c+=u.text);return{question:t,plan:o,subFindings:i,synthesis:c}}async research(t,e,r,n){const o=g({provider:this.opts.provider,model:this.opts.model,tools:r,system:"Investigate the question rigorously. Cite sources inline as [Source N]."});let s="";try{for await(const t of o.run({message:e,signal:n}))"text_delta"===t.type&&(s+=t.text);return{id:t,question:e,findings:s}}catch(i){return{id:t,question:e,findings:"",error:i instanceof Error?i.message:String(i)}}}};function St(t){return new vt(t)}function Tt(t){const e=[];for(const r of t.matchAll(/\[Source\s+(\d+)(?:\s*\|\s*score=([\d.]+))?\]\s*\n?([^[]+?)(?=\n\n\[Source|\n---|$)/gs))e.push({id:r[1],score:r[2]?parseFloat(r[2]):void 0,text:r[3].trim()});return e}function Et(...t){const e=/* @__PURE__ */new Map;let r=1;for(const n of t)for(const t of n){const n=(t.source??"")+"|"+t.text.slice(0,80);e.has(n)||e.set(n,{...t,id:String(r++)})}return Array.from(e.values())}function kt(t){return t.map(t=>`[${t.id}] ${t.source?`${t.source} — `:""}${t.text.slice(0,240)}`).join("\n")}function Ot(t){const e=t.memory??new c,r=new m({...t,memory:e});let n={messages:[],streamingText:"",isStreaming:!1,error:null};const o=/* @__PURE__ */new Set;let s=null;function i(t){n={...n,...t};for(const e of o)e(n)}return{getState:()=>n,subscribe:t=>(o.add(t),()=>o.delete(t)),async send(t){if(!t.trim())return;i({error:null,streamingText:"",isStreaming:!0,messages:[...n.messages,{role:"user",content:t}]}),s=new AbortController;let o="";try{for await(const e of r.run({message:t,signal:s.signal}))"text_delta"===e.type&&(o+=e.text,i({streamingText:o}));i({messages:await Promise.resolve(e.all()),streamingText:"",isStreaming:!1})}catch(a){i({error:a instanceof Error?a:new Error(String(a)),isStreaming:!1})}finally{s=null}},stop(){s?.abort()},reset(){Promise.resolve(e.clear()),i({messages:[],streamingText:"",error:null})},dispose(){s?.abort(),o.clear()}}}function $t(t){return function(e){const r=Ot(e),n=t.shallowRef(r.getState()),o=r.subscribe(t=>n.value=t);return t.onScopeDispose(()=>{o(),r.dispose()}),{state:n,send:r.send,stop:r.stop,reset:r.reset}}}function Nt(t){const e=Ot(t),r=/* @__PURE__ */new Set;return e.subscribe(t=>{for(const e of r)e(t)}),{subscribe:t=>(t(e.getState()),r.add(t),()=>r.delete(t)),send:e.send,stop:e.stop,reset:e.reset,dispose:e.dispose}}function Jt(t){return function(e){const r=Ot(e),[n,o]=t.createSignal(r.getState()),s=r.subscribe(t=>o(t));return t.onCleanup(()=>{s(),r.dispose()}),{state:n,send:r.send,stop:r.stop,reset:r.reset}}}function At(t){return async e=>{if("POST"!==e.method)return new Response("Method not allowed",{status:405});let r;try{r=await e.json()}catch{return new Response("Invalid JSON",{status:400})}const n=(t.parseInput?await t.parseInput(e,r):r).message;if("string"!=typeof n||!n.trim())return new Response("Missing message",{status:400});const o=await t.agent(e),s=new m({...o,memory:o.memory??new c}),i=new TextEncoder,a=new ReadableStream({async start(t){function e(e){t.enqueue(i.encode(`data: ${JSON.stringify(e)}\n\n`))}try{for await(const t of s.run({message:n}))e(qt(t));t.enqueue(i.encode("data: [DONE]\n\n"))}catch(r){e({type:"error",error:{message:r instanceof Error?r.message:String(r)}})}finally{t.close()}}});return new Response(a,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform",connection:"keep-alive"}})}}function qt(t){if(t&&"object"==typeof t&&"error"in t&&t.error instanceof Error){const e=t;return{...t,error:{message:e.error.message,name:e.error.name}}}return t}function Pt(t){const e=t.transport??u;return{async*run(r,n){const o=await e.request({url:t.endpoint,method:"POST",headers:{"content-type":"application/json",...t.headers},body:JSON.stringify({message:r}),signal:n});if(o.body){if(o.status>=400){const t=await o.text();throw new Error(`Agent route ${o.status}: ${t}`)}for await(const t of f(o.body)){if("[DONE]"===t.data)return;let e;try{const r=JSON.parse(t.data);r.error&&"string"==typeof r.error.message&&(r.error=new Error(r.error.message)),e=r}catch{continue}yield e}}}}}var Dt=class{constructor(){this.events=[],this.started=Date.now()}record(t){this.events.push(t)}snapshot(){return{events:this.events.slice(),startedAt:this.started}}toJSONL(){return this.events.map(t=>JSON.stringify(function(t){return"error"in t&&t.error instanceof Error?{...t,error:{message:t.error.message,name:t.error.name}}:t}(t))).join("\n")}static fromJSONL(t){return{events:t.split("\n").filter(t=>t.trim()).map(t=>function(t){if(t&&"object"==typeof t&&"error"in t&&"object"==typeof t.error){const e=t;return{...t,error:new Error(e.error?.message??"unknown")}}return t}(JSON.parse(t))),startedAt:Date.now()}}reset(){this.events=[],this.started=Date.now()}asMiddleware(){return{name:"recorder",onEvent:t=>this.record(t)}}},Mt=new Set(["text_delta","tool_call_start","tool_call_delta","tool_call_end","message_stop","error"]),jt=class{constructor(t){this.opts=t,this.name="replay",this.events=t.recording.events.filter(t=>Mt.has(t.type))}async*stream(t){for(const e of this.events)if(this.opts.delayMsBetweenEvents&&await new Promise(t=>setTimeout(t,this.opts.delayMsBetweenEvents)),yield e,"message_stop"===e.type)return}};function Rt({events:n,onClear:o,position:s="bottom-right",startOpen:i=!1}){const[l,c]=a(i),[u,d]=a("all"),p="all"===u?n:n.filter(t=>t.type===u),f={position:"fixed",bottom:s.includes("bottom")?16:void 0,top:s.includes("top")?16:void 0,right:s.includes("right")?16:void 0,left:s.includes("left")?16:void 0,width:l?480:"auto",maxHeight:l?"60vh":"auto",background:"rgba(15, 15, 35, 0.96)",color:"#f0f0ff",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,padding:12,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:12,zIndex:1e4,display:"flex",flexDirection:"column",gap:8,boxShadow:"0 8px 32px rgba(0,0,0,0.4)"},h={background:"rgba(255,255,255,0.06)",color:"inherit",border:"1px solid rgba(255,255,255,0.2)",padding:"4px 8px",borderRadius:4,cursor:"pointer",fontFamily:"inherit",fontSize:"inherit"};/* @__PURE__ */
8
+ return r("aside",{style:f,"aria-label":"Agent DevTools",children:[/* @__PURE__ */r("header",{style:{display:"flex",alignItems:"center",gap:8},children:[
9
+ /* @__PURE__ */e("button",{onClick:()=>c(!l),style:h,children:l?"▾ Agent DevTools":"▸ Agent"}),
10
+ /* @__PURE__ */r("span",{style:{opacity:.6},children:[n.length," events"]}),l&&o&&/* @__PURE__ */e("button",{onClick:o,style:{...h,marginLeft:"auto"},children:"Clear"})]}),l&&/* @__PURE__ */r(t,{children:[/* @__PURE__ */r("select",{value:u,onChange:t=>d(t.target.value),style:{...h,cursor:"pointer"},children:[
11
+ /* @__PURE__ */e("option",{value:"all",children:"All events"}),
12
+ /* @__PURE__ */e("option",{value:"step_start",children:"Step starts"}),
13
+ /* @__PURE__ */e("option",{value:"tool_call_start",children:"Tool starts"}),
14
+ /* @__PURE__ */e("option",{value:"tool_result",children:"Tool results"}),
15
+ /* @__PURE__ */e("option",{value:"tool_error",children:"Tool errors"}),
16
+ /* @__PURE__ */e("option",{value:"message_stop",children:"Message stops"}),
17
+ /* @__PURE__ */e("option",{value:"error",children:"Errors"})]}),/* @__PURE__ */e("div",{style:{overflow:"auto",flex:1},children:p.map((t,n)=>{/* @__PURE__ */return r("div",{style:{padding:"6px 0",borderBottom:"1px solid rgba(255,255,255,0.06)"},children:[/* @__PURE__ */e("code",{style:{color:(o=t.type,o.startsWith("tool_call")?"#f9a826":"tool_result"===o?"#00c853":"error"===o||"tool_error"===o?"#ff6b6b":"message_stop"===o||"done"===o?"#00f5d4":"step_start"===o?"#6366f1":"#a0a0c0")},children:t.type}),/* @__PURE__ */e("pre",{style:{margin:"4px 0 0 0",fontSize:11,opacity:.85,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:JSON.stringify(It(t),null,1)})]},n);var o})})]})]})}function It(t){return"error"in t&&t.error instanceof Error?{...t,error:t.error.message}:t}function Ct(){const[t,e]=a([]);return{events:t,middleware:s(()=>({name:"devtools-collector",onEvent:t=>e(e=>[...e,t])}),[]),clear:n(()=>e([]),[])}}var zt=class{constructor(t){this.opts=t,this.transport=t.transport??u}async sendTask(t,e){const r=await this.transport.request({url:this.opts.endpoint,method:"POST",headers:{"content-type":"application/json",...this.opts.headers},body:JSON.stringify(t),signal:e});if(r.status>=400)throw new Error(`A2A ${r.status}: ${await r.text()}`);return await r.json()}static newTaskId(){return`task_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}};function Ut(t){return{name:t.name,description:t.description,inputSchema:{type:"object",properties:{input:{type:"string",description:t.inputDescription??"Task for the remote agent."}},required:["input"]},async execute({input:e},r){const n=await t.client.sendTask({id:zt.newTaskId(),message:{role:"user",parts:[{type:"text",text:e}]}},r.signal),o=n.messages.filter(t=>"agent"===t.role).flatMap(t=>t.parts.map(t=>t.text)).join("");return"failed"===n.status?`Remote agent failed: ${o||"(no detail)"}`:o||"(no response)"}}}function Ft(t){return async e=>{if("POST"!==e.method)return new Response("Method not allowed",{status:405});let r;try{r=await e.json()}catch{return new Response("Invalid JSON",{status:400})}const n=r.message?.parts?.filter(t=>"text"===t.type).map(t=>t.text).join("")??"";if(!n)return new Response("Empty task",{status:400});const o=await t.agent(e),s=new m({...o,memory:o.memory??new c});let i="";try{for await(const e of s.run({message:n}))"text_delta"===e.type&&(i+=e.text);const t={id:r.id,status:"completed",messages:[{role:"agent",parts:[{type:"text",text:i}]}]};return new Response(JSON.stringify(t),{status:200,headers:{"content-type":"application/json"}})}catch(a){const t={id:r.id,status:"failed",messages:[{role:"agent",parts:[{type:"text",text:a instanceof Error?a.message:String(a)}]}]};return new Response(JSON.stringify(t),{status:500,headers:{"content-type":"application/json"}})}}}function Gt(t){const e=i(t.memory??new c),r=s(()=>new m({...t,memory:e.current}),[t.provider,t.model]),[l,u]=a([]),[d,p]=a(""),[f,h]=a(!1),[y,g]=a(null),w=i(null),_=n(async t=>{if(!t.trim())return;g(null),p(""),h(!0);const n=new AbortController;w.current=n,u(e=>[...e,{role:"user",content:t}]);let o="";try{for await(const e of r.run({message:t,signal:n.signal}))"text_delta"===e.type&&(o+=e.text,p(o));u(await Promise.resolve(e.current.all())),p("")}catch(s){g(s instanceof Error?s:new Error(String(s)))}finally{h(!1),w.current=null}},[r]),x=n(()=>{w.current?.abort()},[]),b=n(()=>{Promise.resolve(e.current.clear()),u([]),p(""),g(null)},[]);return o(()=>()=>w.current?.abort(),[]),{messages:l,streamingText:d,isStreaming:f,error:y,send:_,stop:x,reset:b}}export{zt as A2AClient,m as Agent,x as AnthropicProvider,vt as DeepResearch,Rt as DevToolsPanel,P as GeminiProvider,V as GuardrailViolation,c as InMemoryStore,ft as MCPClient,C as OllamaProvider,k as OpenAIProvider,Dt as Recorder,jt as ReplayProvider,rt as SlidingWindowMemory,st as StructuredOutputError,nt as SummarizingMemory,_t as TkxAgentMessage,bt as TkxReasoningTrace,xt as TkxToolCallCard,gt as ToolAbortError,ot as VectorMemory,Ut as a2aTool,G as agentAsTool,d as applyMiddleware,ct as cacheable,wt as cancellable,H as checkGuardrails,Ft as createA2ARoute,g as createAgent,Pt as createAgentClient,Ot as createAgentController,At as createAgentRoute,Nt as createAgentStore,St as createDeepResearch,L as createTokenUsageTracker,Jt as createUseAgentSolid,$t as createUseAgentVue,l as defineTool,Tt as extractCitations,u as fetchTransport,kt as formatCitationsList,it as generateObject,X as guardrailsMiddleware,ut as imageBlock,mt as judgeWithLLM,ht as mcpTools,Et as mergeCitations,p as noopSanitizer,Z as otelMiddleware,f as parseSSE,W as piiRedactor,et as promptInjectionDetector,F as retrievalTool,yt as runEval,lt as textBlock,pt as toolResultBlock,dt as toolUseBlock,Gt as useAgent,Ct as useEventCollector,B as withRetry};