@peerproblem/sw3-ui 0.0.0-stage → 0.3.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 (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/agent/components/accordion.md +95 -0
  4. package/agent/components/action-square.md +106 -0
  5. package/agent/components/agent-bridge.md +87 -0
  6. package/agent/components/agent-console.md +123 -0
  7. package/agent/components/alert-dialog.md +82 -0
  8. package/agent/components/app-shell.md +105 -0
  9. package/agent/components/area-chart.md +56 -0
  10. package/agent/components/async-options.md +47 -0
  11. package/agent/components/autocomplete.md +69 -0
  12. package/agent/components/avatar.md +88 -0
  13. package/agent/components/badge.md +51 -0
  14. package/agent/components/bar-chart.md +56 -0
  15. package/agent/components/bar-list.md +49 -0
  16. package/agent/components/breadcrumbs.md +43 -0
  17. package/agent/components/button.md +109 -0
  18. package/agent/components/calendar.md +114 -0
  19. package/agent/components/canvas.md +105 -0
  20. package/agent/components/card.md +78 -0
  21. package/agent/components/carousel.md +113 -0
  22. package/agent/components/chart-card.md +41 -0
  23. package/agent/components/chart-surface.md +56 -0
  24. package/agent/components/checkbox.md +88 -0
  25. package/agent/components/citation-chip.md +61 -0
  26. package/agent/components/collapsible.md +69 -0
  27. package/agent/components/color-picker.md +82 -0
  28. package/agent/components/combobox.md +104 -0
  29. package/agent/components/command.md +92 -0
  30. package/agent/components/dashboard-grid.md +73 -0
  31. package/agent/components/date-input.md +87 -0
  32. package/agent/components/date-picker.md +122 -0
  33. package/agent/components/dialog.md +97 -0
  34. package/agent/components/donut-chart.md +50 -0
  35. package/agent/components/drawer.md +101 -0
  36. package/agent/components/empty-state.md +52 -0
  37. package/agent/components/field.md +80 -0
  38. package/agent/components/file-input.md +84 -0
  39. package/agent/components/hover-card.md +64 -0
  40. package/agent/components/image-cropper.md +77 -0
  41. package/agent/components/input.md +49 -0
  42. package/agent/components/label.md +53 -0
  43. package/agent/components/line-chart.md +60 -0
  44. package/agent/components/listbox.md +84 -0
  45. package/agent/components/map-view.md +104 -0
  46. package/agent/components/menu.md +117 -0
  47. package/agent/components/menubar.md +67 -0
  48. package/agent/components/meter.md +59 -0
  49. package/agent/components/navigation-menu.md +98 -0
  50. package/agent/components/number-input.md +81 -0
  51. package/agent/components/otp-input.md +67 -0
  52. package/agent/components/pagination.md +80 -0
  53. package/agent/components/password-input.md +67 -0
  54. package/agent/components/pill-button.md +116 -0
  55. package/agent/components/popover.md +85 -0
  56. package/agent/components/poster-card.md +61 -0
  57. package/agent/components/preferences.md +92 -0
  58. package/agent/components/progress.md +63 -0
  59. package/agent/components/provider.md +47 -0
  60. package/agent/components/radio.md +91 -0
  61. package/agent/components/rating.md +66 -0
  62. package/agent/components/reorder.md +61 -0
  63. package/agent/components/resizable.md +87 -0
  64. package/agent/components/scatter-chart.md +49 -0
  65. package/agent/components/scroll-area.md +81 -0
  66. package/agent/components/segmented-control.md +56 -0
  67. package/agent/components/select.md +130 -0
  68. package/agent/components/separator.md +60 -0
  69. package/agent/components/shortcuts.md +50 -0
  70. package/agent/components/sidebar-nav.md +68 -0
  71. package/agent/components/skeleton.md +58 -0
  72. package/agent/components/slider.md +79 -0
  73. package/agent/components/sparkline.md +39 -0
  74. package/agent/components/squircle.md +58 -0
  75. package/agent/components/stat.md +58 -0
  76. package/agent/components/switch.md +48 -0
  77. package/agent/components/table.md +58 -0
  78. package/agent/components/tabs.md +108 -0
  79. package/agent/components/textarea.md +68 -0
  80. package/agent/components/time-input.md +84 -0
  81. package/agent/components/timeline.md +91 -0
  82. package/agent/components/toast.md +85 -0
  83. package/agent/components/toggle.md +76 -0
  84. package/agent/components/token-input.md +66 -0
  85. package/agent/components/toolbar.md +76 -0
  86. package/agent/components/tooltip.md +83 -0
  87. package/agent/components/tracker.md +47 -0
  88. package/agent/components/tree.md +87 -0
  89. package/agent/components/treemap.md +72 -0
  90. package/agent/components/trend-chart.md +80 -0
  91. package/agent/components/trigger-menu.md +67 -0
  92. package/agent/components/typography.md +51 -0
  93. package/agent/components/waterfall.md +78 -0
  94. package/agent/components/week-schedule.md +113 -0
  95. package/agent/llms/actions-and-layout.txt +1749 -0
  96. package/agent/llms/agents.txt +505 -0
  97. package/agent/llms/charts.txt +778 -0
  98. package/agent/llms/dashboards.txt +457 -0
  99. package/agent/llms/extend.txt +132 -0
  100. package/agent/llms/extras.txt +527 -0
  101. package/agent/llms/forms.txt +2152 -0
  102. package/agent/llms/foundations.txt +674 -0
  103. package/agent/llms/hooks.txt +178 -0
  104. package/agent/llms/maps.txt +229 -0
  105. package/agent/llms/overlays-and-navigation.txt +1167 -0
  106. package/agent/llms-full.txt +8717 -0
  107. package/agent/llms.txt +145 -0
  108. package/agent/registry.json +11289 -0
  109. package/agent/tokens.md +66 -0
  110. package/dist/agent/index.d.ts +235 -0
  111. package/dist/agent/index.js +21 -0
  112. package/dist/card-Ipm-Cj5f.d.ts +490 -0
  113. package/dist/charts/index.d.ts +289 -0
  114. package/dist/charts/index.js +815 -0
  115. package/dist/check/cli.d.ts +1 -0
  116. package/dist/check/cli.js +48 -0
  117. package/dist/check/rendered.d.ts +11 -0
  118. package/dist/check/rendered.js +77 -0
  119. package/dist/check/source.d.ts +13 -0
  120. package/dist/check/source.js +182 -0
  121. package/dist/chunk-3DXBM65D.js +65 -0
  122. package/dist/chunk-3H5X4ZP6.js +55 -0
  123. package/dist/chunk-6XC4BC5C.js +92 -0
  124. package/dist/chunk-7H6TEAWD.js +507 -0
  125. package/dist/chunk-I63ZTJOI.js +1089 -0
  126. package/dist/chunk-JCIRUM4W.js +33 -0
  127. package/dist/chunk-LTBEHZ3P.js +25 -0
  128. package/dist/chunk-QDPPLO4U.js +60 -0
  129. package/dist/chunk-U2XFBPU4.js +56 -0
  130. package/dist/chunk-UY2WH5AY.js +681 -0
  131. package/dist/extras.d.ts +203 -0
  132. package/dist/extras.js +904 -0
  133. package/dist/icons-BJiGEAnU.d.ts +68 -0
  134. package/dist/index.d.ts +3737 -0
  135. package/dist/index.js +14477 -0
  136. package/dist/map/index.d.ts +115 -0
  137. package/dist/map/index.js +394 -0
  138. package/dist/meta/index.d.ts +3314 -0
  139. package/dist/meta/index.js +5106 -0
  140. package/dist/rules-1RIZ_JZr.d.ts +38 -0
  141. package/dist/styles.css +4037 -0
  142. package/dist/themes/calm.css +42 -0
  143. package/dist/themes/frost.css +40 -0
  144. package/package.json +142 -4
@@ -0,0 +1,505 @@
1
+ # SW3 UI SDK · Agents
2
+
3
+ > Design check, operating rendered pages, the agent bridge (snapshot / query / act, WebMCP), AgentConsole and CitationChip.
4
+
5
+ Setup: `import "@peerproblem/sw3-ui/styles.css"` once, wrap the app in `<SwProvider>`, add `className="sw-root"` to the page. Charts: `@peerproblem/sw3-ui/charts`. Maps: `@peerproblem/sw3-ui/map`.
6
+ Optional peers: install `@unovis/react@~1.8.1 @unovis/ts@~1.8.1 d3-hierarchy@^3.1.0` for charts or `maplibre-gl@^6.18.0` for maps.
7
+ Index of all topics and components: llms.txt.
8
+
9
+ ---
10
+
11
+ # Guide for agents
12
+
13
+ ## 1. Discover
14
+
15
+ The docs live in `node_modules/@peerproblem/sw3-ui/agent/` (and at the docs site root). Read only what the task needs:
16
+
17
+ - `llms.txt`: the router. Setup, one line per topic file and one line per component.
18
+ - `llms/foundations.txt`: design principles, color, type, corners, motion, layout and tokens. Read it once per task.
19
+ - `llms/<topic>.txt`: everything for one area (`forms`, `overlays-and-navigation`, `dashboards`, `charts`, …), including the guide and each component's props, examples and rules.
20
+ - `components/<slug>.md`: one component.
21
+ - `registry.json` or `import { registry } from '@peerproblem/sw3-ui/meta'`: the same data as JSON, for tools. `llms-full.txt` has everything in one file for tools that can't follow links.
22
+
23
+ ## 2. Compose
24
+
25
+ 1. Wrap the app in `<SwProvider>` and import `@peerproblem/sw3-ui/styles.css` once.
26
+ 2. Pick components from the registry by `whenToUse`. Check `avoid` before using one.
27
+ 3. Copy the closest `examples[].code` and adapt it. The examples compile against the public API.
28
+ 4. Style only with tokens (`var(--sw-*)`) and props. Don't write `border-radius`, shadows or hex colors.
29
+ 5. Follow each component's `rules` and the structure rules in *Design principles*. Look rules are defaults: when the app has its own brand, change tokens, not structure.
30
+ 6. Give each visual group one frame. Use spacing or a divider for structure inside a card. Keep an inner boundary when it identifies an independent component or interaction area. Use `framed={false}` where supported when embedding a component in an existing surface.
31
+
32
+ ## 3. Check the design
33
+
34
+ Install TypeScript 5.9.3 or a compatible 5.x version as a dev dependency. Run the checker on app-owned TSX, JSX and CSS files or directories. Add the command to the app's existing lint or CI script.
35
+
36
+ ```sh
37
+ npx --no-install sw3-check src
38
+ ```
39
+
40
+ Each JSON finding includes `rule`, `file`, 1-based `line` and `column`, `message`, and `fix`. Exit code 0 means the checked files passed, 1 means there are findings, and 2 means the checker could not run on the input. Node tools can import `checkDesignSource(source, file)` from `@peerproblem/sw3-ui/check/source` and pass the diagnostics back to the agent.
41
+
42
+ For a rendered view, pass its root element to `checkDesign`. Run it after showing each state that the agent can build or change, including responsive and conditional views.
43
+
44
+ ```ts
45
+ import { checkDesign } from '@peerproblem/sw3-ui/check'
46
+
47
+ const findings = checkDesign(viewRoot)
48
+ ```
49
+
50
+ Rendered findings have a CSS `selector` in place of a source location. The checker counts visible accent Buttons and checks visible charts for a ChartCard and a non-empty `aria-label`. The inline `Sparkline` is a decorative KPI and table-cell exception. The source pass checks literal styles, chart color overrides, and SW3 radius props. The rendered pass can also inspect inline styles outside SDK component trees. It leaves stylesheet declarations to the source pass so computed token values are not mistaken for hard-coded colors.
51
+
52
+ Read each finding, fix the indicated element or declaration, and re-run the same check. Use the rendered check for variants and chart labels supplied by expressions and for views composed from multiple components.
53
+
54
+ The source checker recognizes direct SW3 imports and literal JSX values. Component wrappers, props assembled in JavaScript, and CSS utility classes can need separate review. Pass a root that includes any portals that belong to the view when checking them.
55
+
56
+ ## 4. Operate (reading and using a rendered page)
57
+
58
+ Every component renders `data-sw="<slug>"` on its root, plus state attributes. You can work a UI from the DOM without screenshots:
59
+
60
+ | Find | Selector | State |
61
+ | --- | --- | --- |
62
+ | Buttons | `[data-sw="button"]` | `data-variant`, `disabled`, `data-loading` |
63
+ | Switches | `[data-sw="switch"]` | `aria-checked` |
64
+ | Segmented | `[data-sw="segmented-control"] [role=radio]` | `aria-checked` |
65
+ | Radios (incl. card rows) | `[data-sw="radio"]` | `aria-checked` |
66
+ | Inputs | `[data-sw="input"] input` | `aria-invalid` |
67
+ | Charts | `[data-sw="chart"]` | `data-chart`, `aria-label` = takeaway |
68
+ | Map markers | `[data-sw="map-marker"]` | text = label |
69
+
70
+ All controls are native buttons and inputs with ARIA roles, so `click()`, keyboard events and accessibility-tree tools work.
71
+
72
+ **Prefer the agent bridge when the app has one.** `@peerproblem/sw3-ui/agent` lists every component with its label, state and actions, and changes them through the component's own API (`snapshot`, `query`, `act`). It is cheaper and more reliable than reading the DOM. See *Agent bridge*. Each component's `dom.operate` lists its bridge actions.
73
+
74
+ ## 5. Extend
75
+
76
+ If no component fits, compose from primitives and then propose a new component by following *Contributing components* and *Build a component*:
77
+
78
+ - Surfaces: `useSquircle` + `SquircleLayers`, tokens, motion presets.
79
+ - Floating UI: `usePopup` + `PopupPanel`, `useLayer`, `useFocusTrap`, `useScrollLock`, `useHoverIntent`.
80
+ - Lists: `useListNavigation`. State: `useControllableState`. Forms: `useFieldControl`.
81
+ - Agents: `useAgentBinding` so the bridge can read and change it.
82
+
83
+ ---
84
+
85
+ # Agent bridge
86
+
87
+ `@peerproblem/sw3-ui/agent` connects an agent to the SW3 components on a page. The agent reads each component's label, state and actions, then changes it through the component's own API. Change callbacks still run, so the app stays in charge.
88
+
89
+ ## Create the bridge
90
+
91
+ ```ts
92
+ import { createAgent } from '@peerproblem/sw3-ui/agent'
93
+
94
+ export const agent = createAgent()
95
+ ```
96
+
97
+ Create it once, at startup or when an assistant opens. It finds components that are already on the page and ones that mount later.
98
+ Pass `root: () => ref.current` to scope the bridge to a region. A null root exposes no controls. Omitting `root` uses `document.body`.
99
+
100
+ ## Read the page
101
+
102
+ ```ts
103
+ agent.snapshot()
104
+ // [
105
+ // { ref: 'c1', component: 'input', label: 'Project name', value: 'Apollo', actions: ['setValue', 'clear'] },
106
+ // { ref: 'c2', component: 'select', label: 'Region', value: 'eu', open: false, actions: ['setValue', 'open', 'close'] },
107
+ // { ref: 'c3', component: 'button', label: 'Save changes', actions: ['press'] },
108
+ // ]
109
+ ```
110
+
111
+ - `ref` is stable while the element stays on the page.
112
+ - `label` is the accessible name: `aria-label`, `aria-labelledby`, `<label for>`, the surrounding `<Field label>`, or the text. **Give every control a name.** It's how people using screen readers and agents find it.
113
+ - Values of password and OTP fields show as `••••`.
114
+ - Pages with more than 100 components list the first 100. Use `query` to find the rest.
115
+
116
+ ## Change things
117
+
118
+ ```ts
119
+ const result = await agent.act({
120
+ steps: [
121
+ { ref: 'Project name', action: 'setValue', args: ['Atlas'] },
122
+ { ref: 'Region', action: 'setValue', args: ['North America'] }, // label → value is resolved for you
123
+ { ref: 'Save changes', action: 'press', confirm: true },
124
+ ],
125
+ })
126
+ // { ok: true, steps: [{ ref, label, action, before, after }…], values: { 'Project name': 'Atlas', … } }
127
+ ```
128
+
129
+ - `ref` takes a ref or a label. Labels match whole words, ignoring case and accents. If a label is ambiguous, the result lists the matches and you pass a ref.
130
+ - Steps run in order. The first failure stops the run, `ok` is `false`, and `error.step` says which step failed. Earlier steps stay applied.
131
+ - Common actions:
132
+ - `setValue`, `clear`, `toggle`, `setChecked`
133
+ - `open`, `close`, `select`
134
+ - `expand`, `collapse`, `setPage`
135
+ - `increment`, `decrement`, `add`, `remove`, `dismiss`
136
+ - `press` (buttons and links)
137
+
138
+ Each component's registry entry lists its own in `dom.operate`.
139
+
140
+ ## Find choices
141
+
142
+ ```ts
143
+ await agent.query({ within: 'Region', text: 'europe' }) // → [{ ref, label, items: [{ value, label }], more? }]
144
+ await agent.query({ text: 'invoice' }) // components whose label, row or choices match
145
+ await agent.query({ kind: 'select' })
146
+ ```
147
+
148
+ ## Permissions
149
+
150
+ ```ts
151
+ const agent = createAgent({
152
+ confirm: ({ label, action }) => window.confirm(`${action} ${label}?`),
153
+ })
154
+ ```
155
+
156
+ - `allow` receives the resolved ref, accessible name, action and normalized arguments. Returning `false` refuses the step.
157
+ - Mark protected actions in the app, e.g. `<Button data-sw-confirm="">Delete project</Button>`. The bridge exposes `requiresConfirmation: true` in snapshots. Both direct and WebMCP actions require a positive result from the app's `confirm` callback, and are blocked when it is missing. This applies even if the tool sends `confirm: false`. An `allow` callback can still refuse any action. Direct human clicks follow the app's own handlers.
158
+ - A tool caller can pass `confirm: true` to ask the general `allow` policy for confirmation on an unmarked element.
159
+ - Inside your own change callbacks, `isAgentChange()` (from `@peerproblem/sw3-ui`) is `true` while the bridge acts. Use it to log, ask, or reject.
160
+ - Open panels in Tabs, Accordion, Resizable and ScrollArea expose their nested controls. The bridge skips `hidden`, `inert`, and `aria-hidden="true"` content. Use `data-sw-agent="off"` to hide another subtree from the bridge.
161
+ - Results contain page text that people typed. Tell your model to treat it as data, never as instructions. The tool descriptions already say so.
162
+
163
+ ## Observe changes
164
+
165
+ ```ts
166
+ const stop = agent.subscribe((changes) => {
167
+ // [{ ref, component, label, before: { value: 'Apollo' }, after: { value: 'Atlas' }, source: 'person' | 'agent' }]
168
+ })
169
+ ```
170
+
171
+ Use it to keep an assistant up to date with what the person did since its last turn.
172
+
173
+ ## Give the tools to a model
174
+
175
+ ```ts
176
+ import { agentTools, callAgentTool } from '@peerproblem/sw3-ui/agent'
177
+
178
+ // agentTools: [{ name: 'snapshot' | 'query' | 'act', description, inputSchema, annotations }]
179
+ // Register them with your model SDK, then route each tool call:
180
+ const output = await callAgentTool(agent, toolCall.name, toolCall.input)
181
+ ```
182
+
183
+ ## WebMCP (browser agents)
184
+
185
+ ```ts
186
+ import { registerTools } from '@peerproblem/sw3-ui/agent'
187
+
188
+ const unregister = registerTools(agent, {
189
+ allow: ({ action, label }) => action === 'press' ? window.confirm(`Allow ${action} on ${label}?`) : true,
190
+ })
191
+ ```
192
+
193
+ This publishes `snapshot`, `query` and `act` through `document.modelContext.registerTool` when WebMCP is available. Keep the original `act` function from `createAgent` when wrapping an agent. Put action policies in `createAgent({ allow })` so they also run for WebMCP. The required WebMCP `allow` runs after the bridge policy and receives the same resolved target and arguments. Call `unregister()` on hot reload or teardown.
194
+
195
+ ## Your own components
196
+
197
+ ```tsx
198
+ import { useAgentBinding } from '@peerproblem/sw3-ui'
199
+
200
+ function Rating({ value, onChange }: { value: number; onChange(v: number): void }) {
201
+ const ref = useRef<HTMLDivElement>(null)
202
+ useAgentBinding(ref, {
203
+ kind: 'rating', // its data-sw slug
204
+ state: () => ({ value }),
205
+ actions: { setValue: (v: number) => onChange(v) },
206
+ // items: () => [...] for list components; secret: true for passwords
207
+ })
208
+ return <div ref={ref} data-sw="rating" role="slider" aria-label="Rating" aria-valuenow={value}>…</div>
209
+ }
210
+ ```
211
+
212
+ Components without a binding still show up in snapshots:
213
+
214
+ - Native inputs and textareas get `setValue` and `clear`.
215
+ - Switches and checkboxes get `toggle` and `setChecked`.
216
+ - Radio groups and tab lists get `setValue`, with their items listed.
217
+ - Buttons and links get `press`.
218
+
219
+ This fallback reads the DOM contract, which is why every component carries `data-sw` and real ARIA.
220
+
221
+ Try the bridge live on the playground's **Agent bridge** page (`#/agent`). It's also on `window.agent` in the devtools console there.
222
+
223
+ ---
224
+
225
+ # Components
226
+
227
+ # CitationChip
228
+
229
+ > An inline source reference that opens citation details and a link to the original source.
230
+
231
+ Category: agents · Status: beta · Slug: `citation-chip`
232
+
233
+ ```tsx
234
+ import { CitationChip } from '@peerproblem/sw3-ui'
235
+ ```
236
+
237
+ ## When to use
238
+ - Citing a source next to a statement, metric, or table.
239
+
240
+ ## Avoid
241
+ - General navigation links or status labels.
242
+
243
+ ## Props
244
+
245
+ | Prop | Type | Default | Description |
246
+ | --- | --- | --- | --- |
247
+ | `reference` * | `string` | | Short visible source ID, such as S1. |
248
+ | `title` * | `string` | | Source title shown in the citation details. |
249
+ | `href` * | `string` | | Absolute HTTP or HTTPS URL. An invalid or empty URL omits the chip. |
250
+ | `publisher` | `string` | | Publisher or organization that issued the source. |
251
+ | `excerpt` | `string` | | Short plain-text passage from the source. |
252
+ | `open` | `boolean` | | Controlled open state of the citation preview. |
253
+ | `defaultOpen` | `boolean` | `false` | Initial open state when uncontrolled. |
254
+ | `onOpenChange` | `(open: boolean) => void` | | Called when it wants to open or close (trigger, Close part, Escape, outside press…). |
255
+
256
+ ## Examples
257
+
258
+ ### Inline source reference
259
+
260
+ ```tsx
261
+ <p>
262
+ The city closed one lane.{' '}
263
+ <CitationChip
264
+ reference="S1"
265
+ title="Road closure advisory"
266
+ href="https://example.com/road-closure"
267
+ publisher="City transportation department"
268
+ excerpt="The eastbound lane is closed until 18:00."
269
+ />
270
+ </p>
271
+ ```
272
+
273
+ ## Rules
274
+ - Use an identifiable source title and a short, distinct reference. The Open source link opens the original URL in a new tab.
275
+
276
+ ## Accessibility
277
+ - The leading note icon is decorative. Enter or Space opens the non-modal preview and moves focus to Open source.
278
+ - Escape closes the preview and returns focus to the chip. Tab can leave the preview.
279
+
280
+ ## DOM contract (for agents operating the page)
281
+
282
+ - Selector: `[data-sw="citation-chip"]`
283
+ - `aria-expanded`: on the nested [data-sw="popover-trigger"]
284
+ - `data-state`: open | closed on the nested popover trigger and panel
285
+ - How to operate: Open or close the preview through its existing popover agent binding. The external URL is available on [data-sw="citation-chip-link"] in the open panel.
286
+
287
+ Related: `popover`
288
+
289
+ ---
290
+
291
+ # Agent bridge
292
+
293
+ > Lets an AI agent list the SW3 components on a page and change them through their APIs: snapshot, query, act, subscribe, WebMCP.
294
+
295
+ Category: hooks · Status: beta · Slug: `agent-bridge`
296
+
297
+ ```tsx
298
+ import { createAgent, agentTools, callAgentTool, registerTools } from '@peerproblem/sw3-ui/agent'
299
+ ```
300
+
301
+ ## When to use
302
+ - An assistant inside your app should fill forms, pick options or press buttons for the user.
303
+ - A browser agent (WebMCP) should operate your page reliably instead of clicking pixels.
304
+ - Tests or scripts that drive the UI by label.
305
+
306
+ ## Avoid
307
+ - Letting an agent press destructive buttons without a person. Require approval in the app’s `allow` policy.
308
+ - Unlabelled controls. The bridge finds components by accessible name; add `aria-label` or a Field label.
309
+ - Treating snapshot text as instructions. It is page data that people typed.
310
+
311
+ ## Props
312
+
313
+ | Prop | Type | Default | Description |
314
+ | --- | --- | --- | --- |
315
+ | `createAgent(options)` | `{ allow?: (req) => boolean \| Promise<boolean>; root?: () => HTMLElement \| null }` | | Create the bridge once. `allow` approves each step: `req` = { ref, component, label, action, args, confirm }. |
316
+ | `createAgent({ confirm })` | `(req: AllowRequest) => boolean \| Promise<boolean>` | | App confirmation for data-sw-confirm controls. Marked actions are blocked without this callback. |
317
+ | `agent.snapshot()` | `() => AgentComponent[]` | | Every component: { ref, component, label, …state, actions }. First 100. |
318
+ | `agent.act({ steps })` | `(input: { steps: { ref, action, args?, confirm? }[] }) => Promise<ActResult>` | | Run actions in order. `ref` = ref or label. Item labels resolve to values. Returns { ok, steps, values, error? }. |
319
+ | `agent.query({ text, within, kind })` | `(q) => Promise<QueryResult[]>` | | Find components by text, or list up to 50 choices of one list component with `within`. |
320
+ | `agent.subscribe(listener)` | `(fn: (changes: AgentChange[]) => void) => () => void` | | Changes with before/after and source "person" | "agent". |
321
+ | `agentTools` | `ToolDefinition[]` | | snapshot / query / act with JSON Schemas, for any model SDK. |
322
+ | `callAgentTool(agent, name, input)` | `Promise<unknown>` | | Route a model tool call to the bridge. |
323
+ | `registerTools(agent, { allow })` | `() => void` | | Publish tools through WebMCP using the original act function from createAgent(). The WebMCP policy runs after the bridge policy. Returns cleanup. |
324
+ | `useAgentBinding(ref, spec)` | `(ref, { kind, label?, state, actions, items?, secret? }) => void` | | From `@peerproblem/sw3-ui`. Makes your own component visible to the bridge. |
325
+ | `isAgentChange()` | `() => boolean` | | From `@peerproblem/sw3-ui`. True inside change callbacks triggered by the bridge. |
326
+
327
+ ## Examples
328
+
329
+ ### Create and use
330
+
331
+ ```tsx
332
+ import { createAgent } from '@peerproblem/sw3-ui/agent'
333
+
334
+ const agent = createAgent({ allow: ({ confirm, action, label }) =>
335
+ action === 'press' || confirm ? window.confirm(`${action} ${label}?`) : true,
336
+ })
337
+
338
+ agent.snapshot()
339
+ await agent.act({ steps: [
340
+ { ref: 'Project name', action: 'setValue', args: ['Atlas'] },
341
+ { ref: 'Save changes', action: 'press', confirm: true },
342
+ ] })
343
+ ```
344
+
345
+ ### Give the tools to a model
346
+
347
+ ```tsx
348
+ import { agentTools, callAgentTool } from '@peerproblem/sw3-ui/agent'
349
+
350
+ // register agentTools with your model SDK, then for each tool call:
351
+ const output = await callAgentTool(agent, call.name, call.input)
352
+ ```
353
+
354
+ ### WebMCP
355
+
356
+ ```tsx
357
+ import { registerTools } from '@peerproblem/sw3-ui/agent'
358
+
359
+ const unregister = registerTools(agent, { allow: ({ action }) => action !== 'press' || window.confirm('Allow?') })
360
+ ```
361
+
362
+ ## Rules
363
+ - Create one bridge per app. It discovers components as they mount.
364
+ - Every control needs an accessible name. That name is its handle for agents.
365
+ - Use the app’s `allow` policy to decide which actions need a person to approve them. Treat `confirm: true` as a caller request for confirmation.
366
+ - Wrap private regions in `data-sw-agent="off"`.
367
+
368
+ ## Accessibility
369
+ - The bridge uses the same accessible names that assistive tech uses, so good a11y = good agent access.
370
+
371
+ ## DOM contract (for agents operating the page)
372
+
373
+ - Selector: `[data-sw]`
374
+ - `data-sw-agent="off"`: Region hidden from the bridge
375
+ - How to operate: Call snapshot() first, then act() with labels or refs. Each component meta lists its actions under dom.operate.
376
+
377
+ Related: `input`, `select`, `button`
378
+
379
+ ---
380
+
381
+ # AgentConsole
382
+
383
+ > A chat panel that turns a request into agent-bridge steps and runs them one at a time: it marks each field it changes, logs the exact agent.act() call and its result, then sums up.
384
+
385
+ Category: agents · Status: beta · Slug: `agent-console`
386
+
387
+ ```tsx
388
+ import { AgentConsole } from '@peerproblem/sw3-ui'
389
+ ```
390
+
391
+ ## When to use
392
+ - An in-app assistant that changes a form or settings page for the person, in plain sight.
393
+ - Demos and onboarding that show what an agent does on the page, step by step.
394
+ - Debugging an agent integration: every step shows its call and the before/after the bridge reported.
395
+
396
+ ## Avoid
397
+ - A general chat UI with no page actions — use your own message list; this console only narrates bridge steps.
398
+ - Running actions a person must approve without an app policy. Pass `agent={createAgent({ root, allow })}` and decide which actions need approval in `allow`.
399
+ - Putting the console inside the agent root: it hides its own composer from the bridge, but keep the console and the app side by side.
400
+
401
+ ## Props
402
+
403
+ | Prop | Type | Default | Description |
404
+ | --- | --- | --- | --- |
405
+ | `plan` * | `(message: string) => AgentStep[] \| { steps: AgentStep[]; reply?: string } \| Promise<…>` | | Turns the request into bridge steps. Real apps call a model with agent.snapshot() and agentTools; return { steps: [], reply } to answer without acting. |
406
+ | `root` | `(() => HTMLElement \| null) \| RefObject<HTMLElement>` | | The part of the page the agent works on. Creates the agent when `agent` is omitted and scopes the field marks. |
407
+ | `agent` | `Agent` | | A bridge from createAgent(). Use it to add `allow`, or to share one agent with WebMCP / your model loop. |
408
+ | `summarize` | `(result: ActResult, message: string) => string` | | The closing sentence. Default lists the labels that changed, or the error. |
409
+ | `defaultMessage` | `string` | `''` | Initial composer text; Reset puts it back. |
410
+ | `message` | `string` | | Controlled composer text (with onMessageChange). |
411
+ | `onMessageChange` | `(message: string) => void` | | Composer text changed. |
412
+ | `placeholder` | `string` | `'Ask the agent to change something'` | Composer placeholder. |
413
+ | `stepDelay` | `number` | `700` | Milliseconds between steps, so people can follow. Always 0 with reduced motion. |
414
+ | `onRunComplete` | `(result: ActResult, message: string) => void` | | After every run, with the combined steps, final values and any error. |
415
+ | `onReset` | `() => void` | | Reset pressed: restore your app's defaults. The console clears its own log and marks. |
416
+ | `title` | `ReactNode` | `'Agent'` | Mono header label; also names the region. |
417
+ | `variant` | `'framed' \| 'plain'` | `'framed'` | Own squircle frame, or plain to fill a pane of a larger frame. |
418
+ | `radius` | `RadiusToken \| number` | `'lg'` | Frame radius when framed. |
419
+ | `sendLabel` | `string` | `'Send'` | Composer button label. |
420
+ | `resetLabel` | `string` | `'Reset'` | Button label after a run while the composer is empty. |
421
+
422
+ ## Examples
423
+
424
+ ### Settings assistant next to the form
425
+
426
+ ```tsx
427
+ const settings = useRef<HTMLDivElement>(null)
428
+
429
+ <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
430
+ <AgentConsole
431
+ root={settings}
432
+ plan={async (message) => {
433
+ // Send message + agent.snapshot() to your model with agentTools; return its act() steps.
434
+ return [
435
+ { ref: 'Region', action: 'setValue', args: ['Asia Pacific'] },
436
+ { ref: 'Preview deployments', action: 'setChecked', args: [true] },
437
+ ]
438
+ }}
439
+ defaultMessage="Move to Asia Pacific and turn on previews."
440
+ onReset={() => resetForm()}
441
+ style={{ flex: '1 1 300px', height: 520 }}
442
+ />
443
+ <Card ref={settings} padding="lg" style={{ flex: '1 1 340px' }}>
444
+ <Field label="Region"><Select items={regions} value={region} onValueChange={setRegion} /></Field>
445
+ <Switch label="Preview deployments" checked={preview} onCheckedChange={setPreview} />
446
+ </Card>
447
+ </div>
448
+ ```
449
+
450
+ ### Your own bridge with permissions
451
+
452
+ ```tsx
453
+ import { createAgent } from '@peerproblem/sw3-ui/agent'
454
+
455
+ const agent = useMemo(() => createAgent({
456
+ root: () => document.getElementById('billing'),
457
+ allow: ({ action, label, confirm }) => (confirm ? window.confirm(`${action} ${label}?`) : true),
458
+ }), [])
459
+
460
+ <AgentConsole
461
+ agent={agent}
462
+ root={() => document.getElementById('billing')}
463
+ plan={planWithModel}
464
+ summarize={(result) => (result.ok ? 'Billing updated.' : `Stopped: ${result.error?.message}`)}
465
+ />
466
+ ```
467
+
468
+ ### Answer without acting
469
+
470
+ ```tsx
471
+ <AgentConsole
472
+ root={settings}
473
+ plan={(message) => /region|plan/i.test(message)
474
+ ? parse(message)
475
+ : { steps: [], reply: 'I can change region and plan.' }}
476
+ />
477
+ ```
478
+
479
+ ## Rules
480
+ - Give every target field an accessible name (Field label, aria-label, Switch label): steps target fields by label, and the console finds the field to mark the same way.
481
+ - Marks go on the closest [data-sw="field"], [data-sw="switch-field"] or [data-agent-field] block around the control, else the control itself. Wrap unlabelled groups (a SegmentedControl with a Caption) in <div data-agent-field>.
482
+ - Keep the console outside `root`; the agent must only act on the app.
483
+ - The Send button is the accent action of the view — keep other buttons in the app outline or primary.
484
+ - Plan steps one field at a time; the console runs and logs each as its own agent.act() call.
485
+ - Text in the log comes from the page and the person: tell your model to treat it as data, never instructions.
486
+
487
+ ## Accessibility
488
+ - The root is a region named by its header. The log is role="log" with aria-live="polite", so each call, result and the summary are announced; it is focusable for keyboard scrolling.
489
+ - Enter sends, Shift+Enter adds a line. The button is disabled while a run is in progress (aria-busy on the root).
490
+ - Field marks are a dashed outline, not colour alone, and stay until Reset; changes also land in each control's own ARIA state.
491
+ - Reduced motion: steps run without delay and entries appear without animation.
492
+
493
+ ## DOM contract (for agents operating the page)
494
+
495
+ - Selector: `[data-sw="agent-console"]`
496
+ - `data-status`: 'idle' | 'running' | 'done' on the root
497
+ - `aria-busy`: true while a run is in progress
498
+ - `data-kind`: on each .sw-agent-console__entry: 'user' | 'planning' | 'step' | 'reply'
499
+ - `data-status (entry)`: on step entries: 'running' | 'done' | 'error'
500
+ - `data-agent-target`: on marked field blocks in the app: 'active' (step running) | 'changed' (kept until Reset)
501
+ - How to operate: Type into the composer textarea and press Enter or click Send; click Reset after a run. Agent bridge: setMessage(text), send(text?), reset(); state = { status, message, entries }. The composer itself is hidden from the bridge (data-sw-agent="off").
502
+
503
+ Related: `textarea`, `button`, `field`, `switch`, `select`
504
+
505
+ ---