@wcomp/elementum 0.0.0-stage → 0.2.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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/custom-elements.json +3613 -0
  4. package/mcp/server.js +593 -0
  5. package/package.json +77 -4
  6. package/skills/elementum-break-ui/CATALOG.md +11 -0
  7. package/skills/elementum-break-ui/SKILL.md +16 -0
  8. package/skills/elementum-mobile/SKILL.md +18 -0
  9. package/skills/elementum-motion/SKILL.md +18 -0
  10. package/skills/elementum-motion/STANDARDS.md +15 -0
  11. package/skills/elementum-penpot/SKILL.md +45 -0
  12. package/skills/elementum-ui/CATALOG.md +14 -0
  13. package/skills/elementum-ui/SKILL.md +21 -0
  14. package/src/ag-ui.js +474 -0
  15. package/src/behaviors/index.js +760 -0
  16. package/src/components/el-accordion.js +201 -0
  17. package/src/components/el-alert-dialog.js +186 -0
  18. package/src/components/el-alert.js +254 -0
  19. package/src/components/el-aspect-ratio.js +73 -0
  20. package/src/components/el-autocomplete.js +775 -0
  21. package/src/components/el-avatar.js +271 -0
  22. package/src/components/el-badge.js +131 -0
  23. package/src/components/el-border-beam.js +135 -0
  24. package/src/components/el-breadcrumb.js +203 -0
  25. package/src/components/el-button.js +231 -0
  26. package/src/components/el-calendar.js +436 -0
  27. package/src/components/el-callout.js +158 -0
  28. package/src/components/el-card.js +298 -0
  29. package/src/components/el-carousel.js +308 -0
  30. package/src/components/el-chart.js +632 -0
  31. package/src/components/el-checkbox-card.js +221 -0
  32. package/src/components/el-checkbox.js +208 -0
  33. package/src/components/el-chip.js +276 -0
  34. package/src/components/el-code-block.js +230 -0
  35. package/src/components/el-collapsible.js +124 -0
  36. package/src/components/el-command.js +556 -0
  37. package/src/components/el-context-menu.js +328 -0
  38. package/src/components/el-data-list.js +210 -0
  39. package/src/components/el-datepicker.js +192 -0
  40. package/src/components/el-dialog.js +272 -0
  41. package/src/components/el-diff-viewer.js +441 -0
  42. package/src/components/el-drawer.js +782 -0
  43. package/src/components/el-dropdown.js +182 -0
  44. package/src/components/el-dropzone.js +242 -0
  45. package/src/components/el-empty-state.js +130 -0
  46. package/src/components/el-field.js +394 -0
  47. package/src/components/el-form.js +185 -0
  48. package/src/components/el-input.js +229 -0
  49. package/src/components/el-inset.js +90 -0
  50. package/src/components/el-insight-card.js +263 -0
  51. package/src/components/el-kbd.js +151 -0
  52. package/src/components/el-menubar.js +254 -0
  53. package/src/components/el-meter.js +183 -0
  54. package/src/components/el-navbar.js +294 -0
  55. package/src/components/el-navigation-menu.js +327 -0
  56. package/src/components/el-number-field.js +510 -0
  57. package/src/components/el-number-flow.js +164 -0
  58. package/src/components/el-otp-input.js +266 -0
  59. package/src/components/el-pagination.js +231 -0
  60. package/src/components/el-popover.js +288 -0
  61. package/src/components/el-preview-card.js +202 -0
  62. package/src/components/el-progress.js +179 -0
  63. package/src/components/el-prompt-input.js +383 -0
  64. package/src/components/el-radio-card.js +360 -0
  65. package/src/components/el-radio.js +257 -0
  66. package/src/components/el-rating.js +165 -0
  67. package/src/components/el-reasoning-card.js +293 -0
  68. package/src/components/el-resizable.js +324 -0
  69. package/src/components/el-router.js +305 -0
  70. package/src/components/el-scroll-area.js +150 -0
  71. package/src/components/el-segmented-control.js +282 -0
  72. package/src/components/el-select.js +220 -0
  73. package/src/components/el-separator.js +85 -0
  74. package/src/components/el-sidebar.js +386 -0
  75. package/src/components/el-skeleton.js +156 -0
  76. package/src/components/el-slider.js +351 -0
  77. package/src/components/el-sources.js +288 -0
  78. package/src/components/el-spinner.js +159 -0
  79. package/src/components/el-streaming-text.js +199 -0
  80. package/src/components/el-switch.js +221 -0
  81. package/src/components/el-table.js +397 -0
  82. package/src/components/el-tabs.js +235 -0
  83. package/src/components/el-task-list.js +230 -0
  84. package/src/components/el-textarea.js +175 -0
  85. package/src/components/el-theme-switch.js +120 -0
  86. package/src/components/el-timeline.js +254 -0
  87. package/src/components/el-toast.js +778 -0
  88. package/src/components/el-toggle.js +311 -0
  89. package/src/components/el-tool-call.js +386 -0
  90. package/src/components/el-toolbar.js +183 -0
  91. package/src/components/el-tooltip.js +172 -0
  92. package/src/components/el-tree-view.js +261 -0
  93. package/src/components/el-visually-hidden.js +32 -0
  94. package/src/elementum.js +504 -0
  95. package/src/index.d.ts +1093 -0
  96. package/src/index.js +112 -0
  97. package/src/signal.js +215 -0
  98. package/src/ssr.js +136 -0
  99. package/src/template.js +321 -0
  100. package/src/tokens.css +416 -0
  101. package/tokens/figma-tokens.json +69 -0
  102. package/tokens/penpot-tokens.json +98 -0
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: elementum-break-ui
3
+ description: Adversarial UI stress-testing skill for Web Components and Elementum pages. Systematically attempts to break layout, contrast, responsiveness, focus management, and reactivity before shipping.
4
+ ---
5
+
6
+ # Elementum Break-UI Stress-Test Skill
7
+
8
+ Before declaring a component or page "done", actively try to break it across every vector in [CATALOG.md](./CATALOG.md).
9
+
10
+ ## Stress-Test Workflow
11
+ 1. **Viewport & Overflow**: Resize to `320px`, `375px`, `768px`, and `1440px`. Verify zero horizontal page overflow (`document.documentElement.scrollWidth <= window.innerWidth`), responsive `<el-navbar>` collapse, and scrollable `<el-table>` containers.
12
+ 2. **Dark Mode & Contrast**: Toggle `:root[data-theme="dark"]` and hover/focus every button, badge, toggle, tooltip, and input. Confirm WCAG 2.2 AA contrast (≥ 4.5:1 for text, ≥ 3:1 for UI controls) and ensure isolated preview canvases stay independent of page theme.
13
+ 3. **Extreme Content**: Test empty states (`""`, `[]`), 1-character labels, 120-character unbroken strings, and 50+ list items. Verify avatars never squish (`flex-shrink: 0`) and numbers never jitter (`tabular-nums`).
14
+ 4. **Keyboard & Focus**: Tab through the entire flow without a mouse. Verify `<el-dialog>` and `<el-drawer>` restore focus on close, `Escape` dismisses overlays, and roving `tabindex` works on `<el-tabs>`, `<el-toolbar>`, `<el-menubar>`, and `<el-radio-group>`.
15
+ 5. **Rapid & Edge Interactions**: Double-click submit buttons, open/close drawers rapidly, toggle `disabled` mid-interaction, and verify zero uncaught console errors or leaked listeners after element removal (`disconnected()`).
16
+ 6. **Automated Gates**: Run `npm test` (including `test/catalog-contract.test.js` and `test/craft-contract.test.js`) and `node --test test/pages-smoke.test.js`.
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: elementum-mobile
3
+ description: Mobile-native CSS and interaction standards for @wcomp/elementum Web Components — preventing sticky hover states, tap highlight flashes, iOS input auto-zoom, 100vh clipping, and background scroll bleed.
4
+ ---
5
+
6
+ # Elementum Mobile-Native Craft Skill
7
+
8
+ Use this skill when building or auditing mobile views, PWAs, bottom sheets, or touch interactions with Elementum Web Components.
9
+
10
+ ## Mobile-Native Checklist
11
+ 1. **Eliminate Tap Delay & Grey Flash**: Set `touch-action: manipulation` and `-webkit-tap-highlight-color: transparent` on interactive buttons, toggles, chips, and segmented controls.
12
+ 2. **Prevent Sticky Touch Hover**: Guard decorative `:hover` effects with `@media (hover: hover) and (pointer: fine)` when hover states would otherwise stick after a tap.
13
+ 3. **Prevent iOS Safari Input Auto-Zoom**: Inside `@media (pointer: coarse)`, ensure `input`, `select`, and `textarea` use `font-size: max(16px, 1em)` so focusing a field never zooms the page.
14
+ 4. **Use Dynamic Viewport (`100dvh`) + Safe Areas**: Never rely on bare `100vh` for sheets or modals—pair with `100dvh` and `env(safe-area-inset-bottom, 0px)` so iOS home indicators and dynamic toolbars never obscure controls.
15
+ 5. **Contain Overlay Scroll**: Set `overscroll-behavior: contain` on `<el-drawer>`, `<el-dialog>`, and scrollable menus so scrolling inside an overlay never triggers pull-to-refresh or scrolls the background page.
16
+ 6. **Prevent Accidental Text Selection**: Keep `user-select: none` on buttons, tabs, and drag handles so long-pressing doesn't highlight UI labels.
17
+
18
+ These rules are automatically enforced by `test/craft-contract.test.js`.
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: elementum-motion
3
+ description: Author, audit, and refine CSS animations, micro-interactions, and motion physics in Shadow DOM Web Components. Use when adding transitions, reviewing motion diffs, or removing sluggish/unnecessary animations.
4
+ ---
5
+
6
+ # Elementum Motion & Craft Skill
7
+
8
+ High-craft UI motion feels crisp, physical, and unobtrusive. Follow [STANDARDS.md](./STANDARDS.md) whenever authoring or reviewing Shadow DOM component CSS.
9
+
10
+ ## Quick Rules
11
+ 1. **Never use `transition: all`**: Explicitly list transitioned properties (`transform`, `opacity`, `background-color`, `border-color`, `box-shadow`).
12
+ 2. **Choose the Right Easing & Duration**:
13
+ - Entrances & popovers: `ease-out` or `--el-ease-out-expo` (`cubic-bezier(0.16, 1, 0.3, 1)`), **120ms–250ms** (never `ease-in` on entrances).
14
+ - Micro-feedback (`:active` press): **100ms–150ms** with `transform: scale(0.97)`.
15
+ 3. **Origin-Aware Overlays**: Popovers, dropdowns, tooltips, and context menus scale from their trigger edge (`transform-origin: bottom center` when placed `top`, `top center` when `bottom`, etc.). Modals (`<el-dialog>`) stay centered.
16
+ 4. **Compositor-Only Motion**: Animate `transform` and `opacity` (and keep animated `blur()` ≤ `20px`). Avoid animating `width`, `height`, `top`, or `left` on high-frequency interactions.
17
+ 5. **Respect Reduced Motion**: Every component with `@keyframes` or transform transitions must include `@media (prefers-reduced-motion: reduce)` to disable or calm animations.
18
+ 6. **Know What NOT to Animate**: Keep keyboard-driven interactions (`<el-command>` `⌘K` selection, `<el-tabs>` arrow switching, table row focus) snappy and instant—motion should clarify spatial changes, never delay power users.
@@ -0,0 +1,15 @@
1
+ # Elementum Motion & UI Craft Standards
2
+
3
+ | Problem | Elementum Standard |
4
+ | :--- | :--- |
5
+ | Random properties animate or stutter | Ban `transition: all`; list exact properties (`transform`, `opacity`, `background-color`, `border-color`). |
6
+ | Buttons / toggles feel unresponsive | Apply `transform: scale(0.97)` on `:active:not(:disabled)` (reset under `prefers-reduced-motion`). |
7
+ | Dropdowns / tooltips feel sluggish | Use `ease-out` / `var(--el-ease-out-expo)` under `250ms`; never use `ease-in` for entrances. |
8
+ | Popover grows from wrong spot | Set `transform-origin` toward the trigger edge (modals remain centered). |
9
+ | Avatars squish in flex containers | Always set `flex-shrink: 0` on `:host` in `<el-avatar>`. |
10
+ | Numbers jitter during live updates | Set `font-variant-numeric: tabular-nums` on `<el-number-flow>`, `<el-number-field>`, `<el-meter>`, `<el-progress>`, `<el-pagination>`, and `<el-table>`. |
11
+ | Motion causes vestibular discomfort | Guard every `@keyframes` and transform transition with `@media (prefers-reduced-motion: reduce)`. |
12
+ | Long prose lines fatigue readers | Constrain body paragraphs with `max-width: 65ch` and tighten large headings (`letter-spacing: -0.02em`). |
13
+ | Flat 1px opaque borders look generic | Prefer `--el-border-translucent` (`rgba(15, 23, 42, 0.08)`) paired with layered ambient `--el-shadow-card`. |
14
+
15
+ These rules are enforced automatically in CI by `test/craft-contract.test.js`.
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: elementum-penpot
3
+ description: Bidirectional Penpot MCP design system workflow for Elementum — syncing W3C DTCG tokens, 165 component variants into Penpot, and generating live Web Components apps from Penpot pages.
4
+ ---
5
+
6
+ # Elementum Penpot MCP Skill
7
+
8
+ Use this skill when syncing Elementum's design system into [Penpot](https://design.penpot.app) or generating live Elementum Web Components apps from a Penpot design file.
9
+
10
+ ## Security First
11
+ - **Never** hardcode, log, or commit a user's personal `userToken` JWT into source control or docs.
12
+ - Always pass it via `PENPOT_MCP_URL`, `PENPOT_MCP_TOKEN`, or runtime `--url` / `--token` CLI flags.
13
+ - Only publish Penpot's read-only viewer share URLs (`https://design.penpot.app/?screen=viewer&...&share-id=...`) in public docs.
14
+
15
+ ## Workflows
16
+
17
+ ### 1. Code → Penpot Design System (`npm run penpot:mcp`)
18
+ Generates 54 W3C DTCG tokens (`Elementum Core`, `Elementum Light`, `Elementum Dark`), 28 library colors, `00 · Foundations`, and 8 category pages (`01 · Actions & Buttons` .. `08 · AI & Specialist`) with 165 Master Component variants:
19
+ ```bash
20
+ npm run penpot:mcp -- --url "https://design.penpot.app/mcp/stream?userToken=<YOUR_TOKEN>"
21
+ # Validate locally without network:
22
+ npm run penpot:mcp -- --dry-run
23
+ ```
24
+
25
+ ### 2. Penpot → Live Elementum App (`npm run penpot:generate`)
26
+ Name Penpot component boards using `el-*` annotations (e.g., `el-navbar | brand="LedgerFlow" badge="Finance"`), then extract the Penpot tree, validate tags against Elementum's catalog, export a PNG mockup, and generate a working zero-dependency HTML app:
27
+ ```bash
28
+ npm run penpot:generate -- \
29
+ --url "https://design.penpot.app/mcp/stream?userToken=<YOUR_TOKEN>" \
30
+ --page "LedgerFlow App" \
31
+ --out examples/ledgerflow.html \
32
+ --export-png docs/assets/ledgerflow-penpot.png
33
+ ```
34
+
35
+ ### 3. Penpot → CSS Tokens (`npm run tokens:sync`)
36
+ Export W3C DTCG JSON from Penpot to `tokens/penpot-tokens.json` and compile to `src/tokens.css`:
37
+ ```bash
38
+ npm run tokens:sync tokens/penpot-tokens.json
39
+ ```
40
+
41
+ ## Penpot API Gotchas
42
+ - `penpot.createPage()` takes **0 arguments**; assign `page.name = '...'` and `await penpot.openPage(page)` before creating shapes.
43
+ - Penpot's default font supports weights `200, 300, 400, 600, 700, 900` (not `500`).
44
+ - Use uppercase 6-digit hex strings (`#2563EB`) for `fills`, `strokes`, and `LibraryColor.color`.
45
+ - Keep the Penpot browser tab active/visible so Chrome does not throttle the Penpot MCP Plugin heartbeat.
@@ -0,0 +1,14 @@
1
+ # Elementum Component Quick Catalog (8 Categories · 105 Elements)
2
+
3
+ | Category | Key Components |
4
+ | :--- | :--- |
5
+ | **Actions & Buttons** | `<el-button>`, `<el-toggle>`, `<el-toggle-group>`, `<el-segmented-control>`, `<el-toolbar>` |
6
+ | **Forms & Inputs** | `<el-input>`, `<el-textarea>`, `<el-select>`, `<el-autocomplete>`, `<el-checkbox>`, `<el-checkbox-card>`, `<el-radio>`, `<el-radio-group>`, `<el-radio-card>`, `<el-switch>`, `<el-slider>`, `<el-number-field>`, `<el-otp-input>`, `<el-rating>`, `<el-calendar>`, `<el-datepicker>`, `<el-dropzone>`, `<el-field>`, `<el-form>` |
7
+ | **Data Display** | `<el-card>`, `<el-table>`, `<el-chart>`, `<el-badge>`, `<el-chip>`, `<el-avatar>`, `<el-avatar-group>`, `<el-accordion>`, `<el-timeline>`, `<el-tree-view>`, `<el-data-list>`, `<el-code-block>`, `<el-kbd>`, `<el-number-flow>`, `<el-carousel>`, `<el-empty-state>` |
8
+ | **Feedback & Status** | `<el-alert>`, `<el-callout>`, `<el-toast>` / `<el-toaster>`, `<el-progress>`, `<el-meter>`, `<el-spinner>`, `<el-skeleton>` |
9
+ | **Overlays & Dialogs** | `<el-dialog>`, `<el-alert-dialog>`, `<el-drawer>`, `<el-dropdown>`, `<el-popover>`, `<el-tooltip>`, `<el-command>`, `<el-context-menu>`, `<el-preview-card>` |
10
+ | **Navigation** | `<el-navbar>`, `<el-sidebar>`, `<el-tabs>`, `<el-tab>`, `<el-breadcrumb>`, `<el-pagination>`, `<el-menubar>`, `<el-navigation-menu>`, `<el-router>`, `<el-route>`, `<el-route-link>` |
11
+ | **Layout & Primitives** | `<el-separator>`, `<el-resizable>`, `<el-scroll-area>`, `<el-aspect-ratio>`, `<el-collapsible>`, `<el-inset>`, `<el-visually-hidden>`, `<el-theme-switch>` |
12
+ | **AI & Specialist** | `<el-prompt-input>`, `<el-reasoning-card>`, `<el-streaming-text>`, `<el-tool-call>`, `<el-border-beam>` |
13
+
14
+ For full attribute, slot, event, and CSS `::part()` schemas, query `mcp/server.js` (`get_component_doc`) or inspect `custom-elements.json`.
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: elementum-ui
3
+ description: Compose accessible, zero-dependency user interfaces using @wcomp/elementum's 105 Web Components, micro-signals, and Form-Associated Custom Elements (FACE). Use when building or refactoring UI with Elementum.
4
+ ---
5
+
6
+ # Elementum UI Engineering Skill
7
+
8
+ Use `@wcomp/elementum` primitives directly—do **not** reach for React, Tailwind utility walls, or hand-rolled `<div>` modals/inputs when an Elementum Custom Element exists.
9
+
10
+ ## Core Rules
11
+ 1. **Zero Runtime Dependencies**: Import `@wcomp/elementum` and `@wcomp/elementum/tokens.css` via native ES modules (`<script type="module">`).
12
+ 2. **Verify Schema Before Writing Markup**: Read [CATALOG.md](./CATALOG.md) or query the Elementum MCP server (`list_components`, `get_component_doc`) so you never invent nonexistent attributes or slots.
13
+ 3. **Reactive Signal Bindings**:
14
+ - Inside `html` tagged templates, pass either the signal object (`${this.count}`) or a closure (`${() => this.count.value}`).
15
+ - **Never** evaluate `${this.count.value}` directly outside an arrow function—it unwraps once at mount and stops updating.
16
+ - Use `.prop=${...}` for JS properties, `?attr=${...}` for boolean attributes, and `@event=${...}` for listeners.
17
+ 4. **Native Form Participation (FACE)**: Place `<el-input>`, `<el-select>`, `<el-textarea>`, `<el-checkbox>`, `<el-radio-group>`, `<el-switch>`, `<el-slider>`, `<el-datepicker>`, `<el-otp-input>`, `<el-autocomplete>`, and `<el-segmented-control>` inside native `<form>` elements—they integrate with `FormData`, `reportValidity()`, and `form.reset()`.
18
+ 5. **Theming & Contrast**:
19
+ - Use `--el-*` CSS custom properties (`--el-surface-base`, `--el-surface-card`, `--el-text-primary`, `--el-border-translucent`, `--el-shadow-card`) rather than hardcoded hex colors.
20
+ - Always test both Light (`:root`) and Dark (`:root[data-theme="dark"]`) modes, especially hover states on secondary/ghost controls.
21
+ 6. **Agentic / AG-UI Frontends**: Use `createAgUiStore()` + `<el-prompt-input>`, `<el-reasoning-card>`, `<el-streaming-text>`, `<el-tool-call>` (HITL approval), and `<el-number-flow>` to bind live SSE agent streams directly to DOM nodes without virtual-DOM re-render cascades.
package/src/ag-ui.js ADDED
@@ -0,0 +1,474 @@
1
+ /**
2
+ * AG-UI (Agent-User Interaction Protocol) Adapter for @wcomp/elementum
3
+ * Bridges streaming AG-UI events (RUN_*, STEP_*, TEXT_MESSAGE_*, TOOL_CALL_*, STATE_*)
4
+ * into fine-grained Elementum micro-signals and Web Component properties.
5
+ */
6
+
7
+ import { signal, isSignal } from './signal.js';
8
+
9
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
10
+
11
+ function cloneValue(val) {
12
+ if (val === null || typeof val !== 'object') return val;
13
+ if (typeof structuredClone === 'function') {
14
+ return structuredClone(val);
15
+ }
16
+ return JSON.parse(JSON.stringify(val));
17
+ }
18
+
19
+ function decodePointerToken(token) {
20
+ return String(token).replace(/~1/g, '/').replace(/~0/g, '~');
21
+ }
22
+
23
+ function parsePointer(pointer) {
24
+ if (!pointer || pointer === '/') return pointer === '/' ? [''] : [];
25
+ const raw = String(pointer);
26
+ const parts = (raw.startsWith('/') ? raw.slice(1) : raw).split('/');
27
+ return parts.map(decodePointerToken);
28
+ }
29
+
30
+ /**
31
+ * Resolve an RFC 6901 JSON Pointer against an object.
32
+ */
33
+ export function getByPointer(obj, pointer) {
34
+ if (!pointer) return obj;
35
+ const tokens = parsePointer(pointer);
36
+ let cur = obj;
37
+ for (const key of tokens) {
38
+ if (cur === null || typeof cur !== 'object' || FORBIDDEN_KEYS.has(key)) {
39
+ return undefined;
40
+ }
41
+ cur = cur[key];
42
+ }
43
+ return cur;
44
+ }
45
+
46
+ /**
47
+ * Apply an array of RFC 6902 JSON Patch operations immutably to a target object.
48
+ */
49
+ export function applyJsonPatch(target, patch = []) {
50
+ let root = cloneValue(target ?? {});
51
+ if (!Array.isArray(patch) || patch.length === 0) return root;
52
+
53
+ for (const operation of patch) {
54
+ if (!operation || !operation.op) continue;
55
+ const tokens = parsePointer(operation.path);
56
+ if (tokens.length === 0) {
57
+ if (operation.op === 'replace' || operation.op === 'add') {
58
+ root = cloneValue(operation.value);
59
+ }
60
+ continue;
61
+ }
62
+
63
+ if (tokens.some((t) => FORBIDDEN_KEYS.has(t))) continue;
64
+
65
+ let parent = root;
66
+ for (let i = 0; i < tokens.length - 1; i++) {
67
+ const seg = tokens[i];
68
+ if (parent[seg] === undefined || parent[seg] === null || typeof parent[seg] !== 'object') {
69
+ parent[seg] = Number.isInteger(Number(tokens[i + 1])) ? [] : {};
70
+ }
71
+ parent = parent[seg];
72
+ }
73
+
74
+ const last = tokens[tokens.length - 1];
75
+ const op = operation.op;
76
+
77
+ if (op === 'remove') {
78
+ if (Array.isArray(parent)) {
79
+ const idx = Number(last);
80
+ if (Number.isInteger(idx) && idx >= 0 && idx < parent.length) {
81
+ parent.splice(idx, 1);
82
+ }
83
+ } else if (parent && typeof parent === 'object') {
84
+ delete parent[last];
85
+ }
86
+ continue;
87
+ }
88
+
89
+ if (op === 'add' || op === 'replace') {
90
+ const nextVal = cloneValue(operation.value);
91
+ if (Array.isArray(parent)) {
92
+ if (last === '-') {
93
+ parent.push(nextVal);
94
+ } else {
95
+ const idx = Number(last);
96
+ if (Number.isInteger(idx) && idx >= 0) {
97
+ if (op === 'add' && idx <= parent.length) {
98
+ parent.splice(idx, 0, nextVal);
99
+ } else {
100
+ parent[idx] = nextVal;
101
+ }
102
+ }
103
+ }
104
+ } else if (parent && typeof parent === 'object') {
105
+ parent[last] = nextVal;
106
+ }
107
+ }
108
+ }
109
+
110
+ return root;
111
+ }
112
+
113
+ function setElementProp(el, prop, value) {
114
+ if (!el) return;
115
+ const targetProp = el[prop];
116
+ if (isSignal(targetProp)) {
117
+ targetProp.value = value;
118
+ return;
119
+ }
120
+ const attrName = prop.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
121
+ if (typeof value === 'boolean') {
122
+ if (value) el.setAttribute(attrName, '');
123
+ else el.removeAttribute(attrName);
124
+ return;
125
+ }
126
+ el[prop] = value;
127
+ if (typeof value !== 'object' && value !== null && value !== undefined) {
128
+ el.setAttribute(attrName, String(value));
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Create a reactive Elementum signal store for an AG-UI session.
134
+ */
135
+ export function createAgUiStore(initialState = {}) {
136
+ const state = signal(cloneValue(initialState));
137
+ const status = signal('idle');
138
+ const runId = signal('');
139
+ const stepName = signal('');
140
+ const thinking = signal(false);
141
+ const thinkingText = signal('');
142
+ const currentText = signal('');
143
+ const messages = signal([]);
144
+ const toolCalls = signal([]);
145
+ const error = signal(null);
146
+ const events = signal([]);
147
+
148
+ const listeners = new Set();
149
+
150
+ function upsertToolCall(callId, updater) {
151
+ const list = [...toolCalls.peek()];
152
+ const idx = list.findIndex((tc) => tc.id === callId);
153
+ if (idx === -1) {
154
+ list.push(updater({ id: callId, name: 'tool_call', args: '', result: '', status: 'running', approval: false }));
155
+ } else {
156
+ list[idx] = updater({ ...list[idx] });
157
+ }
158
+ toolCalls.value = list;
159
+ }
160
+
161
+ function dispatch(event) {
162
+ if (!event || !event.type) return;
163
+ events.value = [...events.peek(), event];
164
+
165
+ switch (event.type) {
166
+ case 'RUN_STARTED':
167
+ status.value = 'running';
168
+ runId.value = event.runId || '';
169
+ error.value = null;
170
+ break;
171
+
172
+ case 'RUN_FINISHED':
173
+ status.value = 'finished';
174
+ thinking.value = false;
175
+ break;
176
+
177
+ case 'RUN_ERROR':
178
+ status.value = 'error';
179
+ error.value = event.message || 'AG-UI run error';
180
+ thinking.value = false;
181
+ break;
182
+
183
+ case 'STEP_STARTED':
184
+ case 'THINKING_START':
185
+ thinking.value = true;
186
+ if (event.stepName || event.title) {
187
+ stepName.value = event.stepName || event.title;
188
+ }
189
+ break;
190
+
191
+ case 'THINKING_TEXT_MESSAGE_CONTENT':
192
+ thinkingText.value = thinkingText.peek() + (event.delta || '');
193
+ break;
194
+
195
+ case 'STEP_FINISHED':
196
+ case 'THINKING_END':
197
+ thinking.value = false;
198
+ break;
199
+
200
+ case 'TEXT_MESSAGE_START': {
201
+ const msgId = event.messageId || `msg-${Date.now()}`;
202
+ currentText.value = '';
203
+ messages.value = [
204
+ ...messages.peek(),
205
+ { id: msgId, role: event.role || 'assistant', content: '' },
206
+ ];
207
+ break;
208
+ }
209
+
210
+ case 'TEXT_MESSAGE_CONTENT': {
211
+ const delta = event.delta || '';
212
+ const nextText = currentText.peek() + delta;
213
+ currentText.value = nextText;
214
+
215
+ const list = [...messages.peek()];
216
+ const msgId = event.messageId;
217
+ let idx = msgId ? list.findIndex((m) => m.id === msgId) : list.length - 1;
218
+ if (idx === -1) {
219
+ list.push({ id: msgId || `msg-${Date.now()}`, role: 'assistant', content: nextText });
220
+ } else {
221
+ list[idx] = { ...list[idx], content: (list[idx].content || '') + delta };
222
+ }
223
+ messages.value = list;
224
+ break;
225
+ }
226
+
227
+ case 'TEXT_MESSAGE_END':
228
+ break;
229
+
230
+ case 'TOOL_CALL_START': {
231
+ const callId = event.toolCallId || `tc-${toolCalls.peek().length + 1}`;
232
+ const requiresApproval = Boolean(event.requiresApproval);
233
+ upsertToolCall(callId, (prev) => ({
234
+ ...prev,
235
+ name: event.toolCallName || event.name || prev.name,
236
+ args: '',
237
+ result: '',
238
+ approval: requiresApproval,
239
+ status: requiresApproval ? 'awaiting-approval' : 'running',
240
+ }));
241
+ break;
242
+ }
243
+
244
+ case 'TOOL_CALL_ARGS': {
245
+ const callId = event.toolCallId || toolCalls.peek().at(-1)?.id || 'tc-1';
246
+ upsertToolCall(callId, (prev) => ({
247
+ ...prev,
248
+ args: (prev.args || '') + (event.delta || ''),
249
+ }));
250
+ break;
251
+ }
252
+
253
+ case 'TOOL_CALL_END': {
254
+ const callId = event.toolCallId || toolCalls.peek().at(-1)?.id || 'tc-1';
255
+ upsertToolCall(callId, (prev) => ({
256
+ ...prev,
257
+ status: prev.approval ? 'awaiting-approval' : (event.status || 'completed'),
258
+ }));
259
+ break;
260
+ }
261
+
262
+ case 'TOOL_CALL_RESULT': {
263
+ const callId = event.toolCallId || toolCalls.peek().at(-1)?.id || 'tc-1';
264
+ const resVal = typeof event.result === 'string' ? event.result : JSON.stringify(event.result ?? '', null, 2);
265
+ upsertToolCall(callId, (prev) => ({
266
+ ...prev,
267
+ result: resVal,
268
+ approval: false,
269
+ status: event.status || 'completed',
270
+ }));
271
+ break;
272
+ }
273
+
274
+ case 'STATE_SNAPSHOT':
275
+ state.value = cloneValue(event.snapshot || {});
276
+ break;
277
+
278
+ case 'STATE_DELTA':
279
+ state.value = applyJsonPatch(state.peek(), event.delta || []);
280
+ break;
281
+
282
+ case 'MESSAGES_SNAPSHOT':
283
+ messages.value = Array.isArray(event.messages) ? cloneValue(event.messages) : [];
284
+ break;
285
+
286
+ default:
287
+ break;
288
+ }
289
+
290
+ for (const fn of listeners) {
291
+ fn(event);
292
+ }
293
+ }
294
+
295
+ function pathSignal(pointer, fallback = undefined) {
296
+ const initial = getByPointer(state.peek(), pointer);
297
+ const derived = signal(initial !== undefined ? initial : fallback);
298
+ state.subscribe((nextState) => {
299
+ const val = getByPointer(nextState, pointer);
300
+ derived.value = val !== undefined ? val : fallback;
301
+ });
302
+ return derived;
303
+ }
304
+
305
+ function onEvent(listener) {
306
+ listeners.add(listener);
307
+ return () => listeners.delete(listener);
308
+ }
309
+
310
+ function bindComponents({
311
+ promptInput = null,
312
+ streamingText = null,
313
+ reasoningCard = null,
314
+ toolCallCard = null,
315
+ stateBindings = {},
316
+ } = {}) {
317
+ const unsubs = [];
318
+
319
+ if (promptInput) {
320
+ unsubs.push(
321
+ status.subscribe((st) => {
322
+ setElementProp(promptInput, 'loading', st === 'running');
323
+ })
324
+ );
325
+ }
326
+
327
+ if (streamingText) {
328
+ unsubs.push(
329
+ status.subscribe((st) => {
330
+ if (st !== 'running') {
331
+ if (isSignal(streamingText.isStreaming)) streamingText.isStreaming.value = false;
332
+ if (currentText.peek() && isSignal(streamingText.isComplete)) streamingText.isComplete.value = true;
333
+ }
334
+ }),
335
+ currentText.subscribe((txt) => {
336
+ if (isSignal(streamingText.text)) {
337
+ streamingText.text.value = txt;
338
+ } else {
339
+ streamingText.setAttribute?.('text', txt);
340
+ }
341
+ if (isSignal(streamingText.displayedText)) {
342
+ streamingText.displayedText.value = txt;
343
+ }
344
+ if (isSignal(streamingText.isStreaming)) {
345
+ streamingText.isStreaming.value = status.peek() === 'running';
346
+ }
347
+ if (isSignal(streamingText.isComplete)) {
348
+ streamingText.isComplete.value = status.peek() !== 'running' && Boolean(txt);
349
+ }
350
+ })
351
+ );
352
+ }
353
+
354
+ if (reasoningCard) {
355
+ unsubs.push(
356
+ thinking.subscribe((isThinking) => {
357
+ setElementProp(reasoningCard, 'thinking', isThinking);
358
+ }),
359
+ stepName.subscribe((summary) => {
360
+ if (summary) setElementProp(reasoningCard, 'summary', summary);
361
+ })
362
+ );
363
+ }
364
+
365
+ if (toolCallCard) {
366
+ unsubs.push(
367
+ toolCalls.subscribe((list) => {
368
+ const latest = list.at(-1);
369
+ if (!latest) return;
370
+ setElementProp(toolCallCard, 'callId', latest.id);
371
+ setElementProp(toolCallCard, 'name', latest.name);
372
+ setElementProp(toolCallCard, 'status', latest.status);
373
+ setElementProp(toolCallCard, 'args', latest.args);
374
+ setElementProp(toolCallCard, 'result', latest.result);
375
+ setElementProp(toolCallCard, 'approval', Boolean(latest.approval));
376
+ })
377
+ );
378
+ }
379
+
380
+ for (const [pointer, binding] of Object.entries(stateBindings)) {
381
+ if (!binding) continue;
382
+ const [el, propName = 'value'] = Array.isArray(binding) ? binding : [binding.element, binding.prop || 'value'];
383
+ if (!el) continue;
384
+ const pSig = pathSignal(pointer);
385
+ unsubs.push(
386
+ pSig.subscribe((val) => {
387
+ if (val !== undefined) {
388
+ setElementProp(el, propName, val);
389
+ }
390
+ })
391
+ );
392
+ }
393
+
394
+ return () => {
395
+ for (const unsub of unsubs) unsub();
396
+ };
397
+ }
398
+
399
+ async function connectSSE(source) {
400
+ if (!source) return;
401
+
402
+ // 1. Fetch Response or ReadableStream of bytes
403
+ const stream = typeof source.getReader === 'function'
404
+ ? source
405
+ : (source.body && typeof source.body.getReader === 'function' ? source.body : null);
406
+
407
+ if (stream) {
408
+ const reader = stream.getReader();
409
+ const decoder = new TextDecoder();
410
+ let buffer = '';
411
+
412
+ while (true) {
413
+ const { done, value } = await reader.read();
414
+ if (done) break;
415
+ buffer += typeof value === 'string' ? value : decoder.decode(value, { stream: true });
416
+ const lines = buffer.split(/\r?\n/);
417
+ buffer = lines.pop() ?? '';
418
+ for (const line of lines) {
419
+ const trimmed = line.trim();
420
+ if (trimmed.startsWith('data:')) {
421
+ const payload = trimmed.slice(5).trim();
422
+ if (payload && payload !== '[DONE]') {
423
+ dispatch(JSON.parse(payload));
424
+ }
425
+ }
426
+ }
427
+ }
428
+
429
+ if (buffer.trim().startsWith('data:')) {
430
+ const payload = buffer.trim().slice(5).trim();
431
+ if (payload && payload !== '[DONE]') {
432
+ dispatch(JSON.parse(payload));
433
+ }
434
+ }
435
+ return;
436
+ }
437
+
438
+ // 2. Async or sync iterable of AG-UI event objects or SSE strings
439
+ for await (const chunk of source) {
440
+ if (typeof chunk === 'string') {
441
+ for (const line of chunk.split(/\r?\n/)) {
442
+ const trimmed = line.trim();
443
+ if (trimmed.startsWith('data:')) {
444
+ const payload = trimmed.slice(5).trim();
445
+ if (payload && payload !== '[DONE]') {
446
+ dispatch(JSON.parse(payload));
447
+ }
448
+ }
449
+ }
450
+ } else if (chunk && typeof chunk === 'object') {
451
+ dispatch(chunk);
452
+ }
453
+ }
454
+ }
455
+
456
+ return {
457
+ state,
458
+ status,
459
+ runId,
460
+ stepName,
461
+ thinking,
462
+ thinkingText,
463
+ currentText,
464
+ messages,
465
+ toolCalls,
466
+ error,
467
+ events,
468
+ dispatch,
469
+ pathSignal,
470
+ onEvent,
471
+ bindComponents,
472
+ connectSSE,
473
+ };
474
+ }