sygnal 5.4.0 → 6.1.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 (360) hide show
  1. package/CHANGELOG.md +716 -0
  2. package/README.md +24 -9
  3. package/dist/ai.cjs.js +115 -0
  4. package/dist/ai.cjs.js.map +1 -0
  5. package/dist/ai.esm.js +2 -0
  6. package/dist/ai.esm.js.map +1 -0
  7. package/dist/astro/client.cjs.js +16 -9
  8. package/dist/astro/client.cjs.js.map +1 -1
  9. package/dist/astro/client.mjs +16 -9
  10. package/dist/astro/client.mjs.map +1 -1
  11. package/dist/astro/index.cjs.js +958 -92
  12. package/dist/astro/index.cjs.js.map +1 -1
  13. package/dist/astro/index.mjs +958 -93
  14. package/dist/astro/index.mjs.map +1 -1
  15. package/dist/astro/server.cjs.js +3396 -165
  16. package/dist/astro/server.cjs.js.map +1 -1
  17. package/dist/astro/server.mjs +3396 -165
  18. package/dist/astro/server.mjs.map +1 -1
  19. package/dist/devtools.cjs.js +1840 -0
  20. package/dist/devtools.cjs.js.map +1 -0
  21. package/dist/devtools.esm.js +1827 -0
  22. package/dist/devtools.esm.js.map +1 -0
  23. package/dist/diagnostics.cjs.js +3190 -296
  24. package/dist/diagnostics.cjs.js.map +1 -1
  25. package/dist/diagnostics.esm.js +3190 -296
  26. package/dist/diagnostics.esm.js.map +1 -1
  27. package/dist/element.cjs.js +230 -0
  28. package/dist/element.cjs.js.map +1 -0
  29. package/dist/element.esm.js +228 -0
  30. package/dist/element.esm.js.map +1 -0
  31. package/dist/guide/accessibility.md +310 -0
  32. package/dist/guide/adapters.md +221 -0
  33. package/dist/guide/agent.md +588 -0
  34. package/dist/guide/ai-chat.md +693 -0
  35. package/dist/guide/ai-decisions.md +330 -0
  36. package/dist/guide/behaviors.md +312 -0
  37. package/dist/guide/browser-sources.md +203 -0
  38. package/dist/guide/drag-and-drop.md +342 -0
  39. package/dist/guide/element-commands.md +306 -0
  40. package/dist/guide/error-boundaries.md +169 -0
  41. package/dist/guide/forms-reference.md +409 -0
  42. package/dist/guide/forms.md +251 -0
  43. package/dist/guide/http.md +301 -0
  44. package/dist/guide/inputs.md +173 -0
  45. package/dist/guide/mcp-apps.md +272 -0
  46. package/dist/guide/persistence.md +245 -0
  47. package/dist/guide/recipes/ai-form-fill.md +163 -0
  48. package/dist/guide/recipes/ai-summarize.md +155 -0
  49. package/dist/guide/recipes/ai-support-inbox.md +190 -0
  50. package/dist/guide/recipes/carousel.md +155 -0
  51. package/dist/guide/recipes/charts.md +177 -0
  52. package/dist/guide/recipes/code-editor.md +135 -0
  53. package/dist/guide/recipes/data-grid.md +155 -0
  54. package/dist/guide/recipes/data-table.md +196 -0
  55. package/dist/guide/recipes/i18n.md +222 -0
  56. package/dist/guide/recipes/icons.md +115 -0
  57. package/dist/guide/recipes/overview.md +43 -0
  58. package/dist/guide/recipes/rich-text.md +154 -0
  59. package/dist/guide/resources.md +471 -0
  60. package/dist/guide/ssr.md +255 -0
  61. package/dist/guide/timers.md +178 -0
  62. package/dist/guide/ui/accordion.md +93 -0
  63. package/dist/guide/ui/combobox.md +144 -0
  64. package/dist/guide/ui/dialog.md +124 -0
  65. package/dist/guide/ui/disclosure.md +60 -0
  66. package/dist/guide/ui/menu.md +125 -0
  67. package/dist/guide/ui/overview.md +166 -0
  68. package/dist/guide/ui/popover.md +101 -0
  69. package/dist/guide/ui/select.md +114 -0
  70. package/dist/guide/ui/tabs.md +161 -0
  71. package/dist/guide/ui/toaster.md +152 -0
  72. package/dist/guide/ui/tooltip.md +103 -0
  73. package/dist/guide/undo.md +178 -0
  74. package/dist/guide/virtual-collections.md +183 -0
  75. package/dist/guide/web-components.md +179 -0
  76. package/dist/guide/webmcp.md +226 -0
  77. package/dist/guide/widgets.md +217 -0
  78. package/dist/index.cjs.js +19288 -7408
  79. package/dist/index.cjs.js.map +1 -1
  80. package/dist/index.d.ts +4466 -552
  81. package/dist/index.esm.js +19274 -7461
  82. package/dist/index.esm.js.map +1 -1
  83. package/dist/jsx-dev-runtime.cjs.js +26 -334
  84. package/dist/jsx-dev-runtime.cjs.js.map +1 -1
  85. package/dist/jsx-dev-runtime.esm.js +19 -327
  86. package/dist/jsx-dev-runtime.esm.js.map +1 -1
  87. package/dist/jsx-runtime.cjs.js +26 -334
  88. package/dist/jsx-runtime.cjs.js.map +1 -1
  89. package/dist/jsx-runtime.esm.js +19 -327
  90. package/dist/jsx-runtime.esm.js.map +1 -1
  91. package/dist/jsx.cjs.js +10 -314
  92. package/dist/jsx.cjs.js.map +1 -1
  93. package/dist/jsx.esm.js +8 -315
  94. package/dist/jsx.esm.js.map +1 -1
  95. package/dist/react.cjs.js +117 -0
  96. package/dist/react.cjs.js.map +1 -0
  97. package/dist/react.esm.js +115 -0
  98. package/dist/react.esm.js.map +1 -0
  99. package/dist/shims/globalthis.cjs +20 -0
  100. package/dist/sygnal.min.js +1 -1
  101. package/dist/sygnal.min.js.map +1 -1
  102. package/dist/ui-combobox.cjs.js +169 -0
  103. package/dist/ui-combobox.cjs.js.map +1 -0
  104. package/dist/ui-combobox.esm.js +148 -0
  105. package/dist/ui-combobox.esm.js.map +1 -0
  106. package/dist/ui-menu.cjs.js +87 -0
  107. package/dist/ui-menu.cjs.js.map +1 -0
  108. package/dist/ui-menu.esm.js +66 -0
  109. package/dist/ui-menu.esm.js.map +1 -0
  110. package/dist/ui-select.cjs.js +104 -0
  111. package/dist/ui-select.cjs.js.map +1 -0
  112. package/dist/ui-select.esm.js +83 -0
  113. package/dist/ui-select.esm.js.map +1 -0
  114. package/dist/ui.cjs.js +738 -0
  115. package/dist/ui.cjs.js.map +1 -0
  116. package/dist/ui.esm.js +727 -0
  117. package/dist/ui.esm.js.map +1 -0
  118. package/dist/vike/ClientOnly.cjs.js +4 -14
  119. package/dist/vike/ClientOnly.cjs.js.map +1 -1
  120. package/dist/vike/ClientOnly.mjs +4 -14
  121. package/dist/vike/ClientOnly.mjs.map +1 -1
  122. package/dist/vike/{+config.js → config/+config.js} +9 -1
  123. package/dist/vike/config/+config.js.map +1 -0
  124. package/dist/vike/config/package.json +6 -0
  125. package/dist/vike/onRenderClient.cjs.js +165 -95
  126. package/dist/vike/onRenderClient.cjs.js.map +1 -1
  127. package/dist/vike/onRenderClient.mjs +165 -95
  128. package/dist/vike/onRenderClient.mjs.map +1 -1
  129. package/dist/vike/onRenderHtml.cjs.js +59 -24
  130. package/dist/vike/onRenderHtml.cjs.js.map +1 -1
  131. package/dist/vike/onRenderHtml.mjs +60 -25
  132. package/dist/vike/onRenderHtml.mjs.map +1 -1
  133. package/dist/vite/plugin.cjs.js +919 -89
  134. package/dist/vite/plugin.cjs.js.map +1 -1
  135. package/dist/vite/plugin.mjs +919 -90
  136. package/dist/vite/plugin.mjs.map +1 -1
  137. package/dist/zag.cjs.js +408 -0
  138. package/dist/zag.cjs.js.map +1 -0
  139. package/dist/zag.esm.js +405 -0
  140. package/dist/zag.esm.js.map +1 -0
  141. package/llms.txt +172 -103
  142. package/package.json +112 -14
  143. package/src/ai.d.ts +1186 -0
  144. package/src/ai.ts +23 -0
  145. package/src/astro/client.ts +27 -16
  146. package/src/astro/index.d.ts +24 -0
  147. package/src/astro/index.ts +69 -3
  148. package/src/astro/server.ts +8 -2
  149. package/src/collection.ts +6 -93
  150. package/src/core/actions.ts +134 -0
  151. package/src/core/cell.ts +202 -0
  152. package/src/core/debug.ts +23 -0
  153. package/src/core/define.ts +242 -0
  154. package/src/core/hooks.ts +314 -0
  155. package/src/core/hosts/collection.ts +325 -0
  156. package/src/core/hosts/switchable.ts +146 -0
  157. package/src/core/instance.ts +592 -0
  158. package/src/core/markers/clientonly.ts +13 -0
  159. package/src/core/markers/lazy.ts +40 -0
  160. package/src/core/markers/portal.ts +96 -0
  161. package/src/core/markers/suspense.ts +41 -0
  162. package/src/core/markers/transition.ts +70 -0
  163. package/src/core/registry.ts +25 -0
  164. package/src/core/runtime.ts +573 -0
  165. package/src/core/statics.ts +104 -0
  166. package/src/core/teardown.ts +60 -0
  167. package/src/core/view.ts +37 -0
  168. package/src/cycle/dom/DocumentDOMSource.ts +13 -8
  169. package/src/cycle/dom/ElementFinder.ts +7 -9
  170. package/src/cycle/dom/EventDelegator.ts +174 -223
  171. package/src/cycle/dom/IsolateModule.ts +65 -35
  172. package/src/cycle/dom/MainDOMSource.ts +9 -2
  173. package/src/cycle/dom/PriorityQueue.ts +4 -2
  174. package/src/cycle/dom/SymbolTree.ts +18 -47
  175. package/src/cycle/dom/classNameModule.ts +9 -7
  176. package/src/cycle/dom/controlledInputModule.ts +23 -6
  177. package/src/cycle/dom/enrichEventStream.ts +25 -47
  178. package/src/cycle/dom/fragment.ts +7 -0
  179. package/src/cycle/dom/isolate.ts +30 -27
  180. package/src/cycle/dom/makeDOMDriver.ts +115 -56
  181. package/src/cycle/dom/mockDOMSource.ts +21 -1
  182. package/src/cycle/dom/modules.ts +16 -3
  183. package/src/cycle/dom/propsModule.ts +65 -0
  184. package/src/cycle/dom/selectModule.ts +22 -17
  185. package/src/cycle/dom/snabbdom.ts +1 -6
  186. package/src/cycle/dom/thunk.ts +3 -0
  187. package/src/cycle/dom/utils.ts +98 -0
  188. package/src/cycle/dom/viewTransition.ts +43 -0
  189. package/src/cycle/state/StateSource.ts +19 -3
  190. package/src/cycle/state/objIsEqual.ts +50 -0
  191. package/src/cycle/state/types.ts +0 -10
  192. package/src/defineComponent.ts +34 -0
  193. package/src/devtools.d.ts +170 -0
  194. package/src/devtools.ts +37 -0
  195. package/src/element.d.ts +59 -0
  196. package/src/element.ts +235 -0
  197. package/src/extra/ai/agent/index.ts +484 -0
  198. package/src/extra/ai/answers.ts +115 -0
  199. package/src/extra/ai/chat/behavior.ts +336 -0
  200. package/src/extra/ai/chat/driver.ts +271 -0
  201. package/src/extra/ai/chat/memoryTransport.ts +61 -0
  202. package/src/extra/ai/chat/output.ts +37 -0
  203. package/src/extra/ai/commandBar.ts +281 -0
  204. package/src/extra/ai/decide.ts +104 -0
  205. package/src/extra/ai/index.ts +42 -0
  206. package/src/extra/ai/link.ts +90 -0
  207. package/src/extra/ai/mcpApp.ts +314 -0
  208. package/src/extra/ai/messages.ts +51 -0
  209. package/src/extra/ai/schema/index.ts +166 -0
  210. package/src/extra/ai/schema/jsonSchema.ts +72 -0
  211. package/src/extra/ai/schema/strict.ts +152 -0
  212. package/src/extra/ai/transports/agui.ts +177 -0
  213. package/src/extra/ai/transports/anthropicMessages.ts +175 -0
  214. package/src/extra/ai/transports/chatCompletions.ts +105 -0
  215. package/src/extra/ai/transports/chromePrompt.ts +77 -0
  216. package/src/extra/ai/transports/encodeOpenResponses.ts +87 -0
  217. package/src/extra/ai/transports/fromAISDK.ts +126 -0
  218. package/src/extra/ai/transports/openResponses.ts +105 -0
  219. package/src/extra/ai/transports/shared.ts +125 -0
  220. package/src/extra/ai/transports/tools.ts +59 -0
  221. package/src/extra/ai/transports/uiMessageStream.ts +107 -0
  222. package/src/extra/ai/webmcp.ts +260 -0
  223. package/src/extra/backoff.ts +9 -0
  224. package/src/extra/behaviors.ts +169 -0
  225. package/src/extra/browserSignals.ts +23 -0
  226. package/src/extra/browserSources.ts +326 -0
  227. package/src/extra/command.ts +3 -3
  228. package/src/extra/controls.ts +47 -0
  229. package/src/extra/copyAsTest.ts +286 -0
  230. package/src/extra/devMcp.ts +386 -0
  231. package/src/extra/devtools.ts +101 -31
  232. package/src/extra/devtoolsActions.ts +379 -0
  233. package/src/extra/devtoolsHook.ts +9 -0
  234. package/src/extra/devtoolsNext.ts +83 -0
  235. package/src/extra/diagnostics/checks/actionLog.ts +108 -0
  236. package/src/extra/diagnostics/checks/behaviors.ts +49 -0
  237. package/src/extra/diagnostics/checks/browserSources.ts +96 -0
  238. package/src/extra/diagnostics/checks/chat.ts +71 -0
  239. package/src/extra/diagnostics/checks/collections.ts +1 -1
  240. package/src/extra/diagnostics/checks/controls.ts +148 -0
  241. package/src/extra/diagnostics/checks/dataset.ts +57 -0
  242. package/src/extra/diagnostics/checks/dom.ts +20 -11
  243. package/src/extra/diagnostics/checks/elementCommands.ts +175 -0
  244. package/src/extra/diagnostics/checks/events.ts +17 -2
  245. package/src/extra/diagnostics/checks/fetch.ts +135 -0
  246. package/src/extra/diagnostics/checks/forms.ts +171 -0
  247. package/src/extra/diagnostics/checks/index.ts +103 -4
  248. package/src/extra/diagnostics/checks/inspect.ts +140 -32
  249. package/src/extra/diagnostics/checks/next.ts +417 -0
  250. package/src/extra/diagnostics/checks/persist.ts +54 -0
  251. package/src/extra/diagnostics/checks/props.ts +10 -5
  252. package/src/extra/diagnostics/checks/public.d.ts +115 -7
  253. package/src/extra/diagnostics/checks/replies.ts +128 -0
  254. package/src/extra/diagnostics/checks/router.ts +100 -0
  255. package/src/extra/diagnostics/checks/rxjsHints.ts +1 -1
  256. package/src/extra/diagnostics/checks/shared.ts +86 -2
  257. package/src/extra/diagnostics/checks/shorthand.ts +115 -0
  258. package/src/extra/diagnostics/checks/sortable.ts +129 -0
  259. package/src/extra/diagnostics/checks/state.ts +100 -7
  260. package/src/extra/diagnostics/checks/statics.ts +48 -0
  261. package/src/extra/diagnostics/checks/strict.ts +10 -67
  262. package/src/extra/diagnostics/checks/timers.ts +80 -0
  263. package/src/extra/diagnostics/checks/viewTransitions.ts +47 -0
  264. package/src/extra/diagnostics/checks/virtual.ts +73 -0
  265. package/src/extra/diagnostics/checks/widgets.ts +109 -0
  266. package/src/extra/diagnostics/checks/wiring.ts +69 -10
  267. package/src/extra/diagnostics/codes.ts +335 -23
  268. package/src/extra/diagnostics/index.ts +34 -9
  269. package/src/extra/diagnostics/legacy.ts +17 -0
  270. package/src/extra/driverFactories.ts +83 -19
  271. package/src/extra/elementCommands.ts +53 -0
  272. package/src/extra/fetchDriver.ts +519 -0
  273. package/src/extra/focusWithin.ts +27 -0
  274. package/src/extra/form.ts +284 -0
  275. package/src/extra/formHelpers.ts +139 -0
  276. package/src/extra/formTool.ts +150 -0
  277. package/src/extra/head.ts +106 -0
  278. package/src/extra/hmr.ts +2 -3
  279. package/src/extra/owned.ts +24 -0
  280. package/src/extra/pager.ts +50 -0
  281. package/src/extra/persist.ts +133 -0
  282. package/src/extra/pwa.ts +1 -1
  283. package/src/extra/queryCache.ts +107 -0
  284. package/src/extra/reducers.ts +1 -1
  285. package/src/extra/reduxDevtools.ts +92 -0
  286. package/src/extra/replies.ts +54 -0
  287. package/src/extra/router.ts +323 -0
  288. package/src/extra/run.ts +90 -217
  289. package/src/extra/selection.ts +76 -0
  290. package/src/extra/socketDriver.ts +265 -0
  291. package/src/extra/sortable.ts +377 -0
  292. package/src/extra/ssr.ts +427 -160
  293. package/src/extra/standardSchema.ts +27 -0
  294. package/src/extra/testing.ts +2550 -175
  295. package/src/extra/timers.ts +95 -0
  296. package/src/extra/undo.ts +261 -0
  297. package/src/extra/viewTransitions.ts +38 -0
  298. package/src/extra/virtual.ts +513 -0
  299. package/src/extra/widget.ts +201 -0
  300. package/src/index.d.ts +2754 -127
  301. package/src/index.ts +45 -4
  302. package/src/jsx-runtime.ts +15 -1
  303. package/src/jsx.ts +2 -1
  304. package/src/lazy.ts +50 -7
  305. package/src/portal.ts +3 -1
  306. package/src/pragma/index.ts +256 -133
  307. package/src/react-peers.d.ts +5 -0
  308. package/src/react.d.ts +43 -0
  309. package/src/react.ts +110 -0
  310. package/src/shared.ts +57 -0
  311. package/src/slot.ts +1 -1
  312. package/src/suspense.ts +3 -1
  313. package/src/switchable.ts +6 -121
  314. package/src/transition.ts +3 -1
  315. package/src/ui/accordion.ts +64 -0
  316. package/src/ui/dialog.ts +129 -0
  317. package/src/ui/disclosure.ts +35 -0
  318. package/src/ui/popover.ts +45 -0
  319. package/src/ui/shared.ts +94 -0
  320. package/src/ui/tabs.ts +82 -0
  321. package/src/ui/toaster.ts +198 -0
  322. package/src/ui/tooltip.ts +70 -0
  323. package/src/ui/zag/combobox.ts +115 -0
  324. package/src/ui/zag/menu.ts +40 -0
  325. package/src/ui/zag/select.ts +54 -0
  326. package/src/ui/zag/shared.ts +43 -0
  327. package/src/ui-combobox.d.ts +20 -0
  328. package/src/ui-combobox.ts +6 -0
  329. package/src/ui-menu.d.ts +30 -0
  330. package/src/ui-menu.ts +6 -0
  331. package/src/ui-select.d.ts +17 -0
  332. package/src/ui-select.ts +6 -0
  333. package/src/ui-zag-types.d.ts +42 -0
  334. package/src/ui.d.ts +208 -0
  335. package/src/ui.ts +15 -0
  336. package/src/vike/+config.ts +9 -1
  337. package/src/vike/ClientOnly.ts +1 -1
  338. package/src/vike/onRenderClient.ts +144 -96
  339. package/src/vike/onRenderHtml.ts +69 -26
  340. package/src/vike/types.ts +7 -1
  341. package/src/vite/globalthis-shim.ts +18 -0
  342. package/src/vite/globalthis.ts +56 -0
  343. package/src/vite/mcp.ts +568 -0
  344. package/src/vite/plugin.d.ts +47 -3
  345. package/src/vite/plugin.ts +262 -25
  346. package/src/zag.d.ts +64 -0
  347. package/src/zag.ts +238 -0
  348. package/dist/vike/+config.cjs.js +0 -66
  349. package/dist/vike/+config.cjs.js.map +0 -1
  350. package/dist/vike/+config.js.map +0 -1
  351. package/src/component.ts +0 -2301
  352. package/src/cycle/isolate/index.ts +0 -196
  353. package/src/cycle/run/index.ts +0 -151
  354. package/src/cycle/run/internals.ts +0 -143
  355. package/src/cycle/state/Collection.ts +0 -184
  356. package/src/cycle/state/index.ts +0 -5
  357. package/src/cycle/state/pickCombine.ts +0 -201
  358. package/src/cycle/state/pickMerge.ts +0 -122
  359. package/src/cycle/state/withState.ts +0 -47
  360. package/src/pragma/fn.ts +0 -55
@@ -0,0 +1,330 @@
1
+ <!-- Generated from docs/src/content/docs/guide by scripts/copy-guides.mjs; online: https://sygnal.js.org/guide/ -->
2
+ # AI Decisions
3
+
4
+ A **decision model** answers typed questions about some state: which category is this ticket, is it urgent, how upset is the customer. You send the state and the questions; it sends back a probability for every answer. It writes no text and streams nothing, so it is fast (a few hundred milliseconds) and cheap, and its answers are calibrated: a confidence of 0.4 means it is unsure, and you can act on that.
5
+
6
+ Decision models in this shape:
7
+
8
+ | Model | Where | `model` |
9
+ |---|---|---|
10
+ | TypeSafe Jev | TypeSafe's `/v1/systemone` (through your server) | `'jev-latest'` |
11
+ | Ollama 0.35 or later | `http://localhost:11434/v1/systemone`, on your machine | `'nimble'`, `'clef'`, `'clef-flash'` |
12
+ | OpenRouter | OpenRouter's decisions endpoint (through your server) | the model's OpenRouter id |
13
+ | Vercel AI Gateway | the gateway's decisions endpoint (through your server) | the model's gateway id |
14
+ | OpenAI Decisions | `POST /v1/decisions` (through your server), with [`decide.openai()`](#openai-decisions) | e.g. `'gpt-6-luna'` |
15
+
16
+ A decision is an ordinary HTTP request, so there is no new driver: `decide()` from `sygnal/ai` builds a request for the [fetch driver](./http.md). Register it in `main.js` as usual:
17
+
18
+ ```js
19
+ import { run, makeFetchDriver } from 'sygnal'
20
+ import App from './App.jsx'
21
+
22
+ run(App, { HTTP: makeFetchDriver() })
23
+ ```
24
+
25
+ To try it with no key, pull a decision model into Ollama (`ollama pull nimble`) and point `decide()` at it: `decide({ url: 'http://localhost:11434/v1/systemone', model: 'nimble', ... })`.
26
+
27
+ ## Questions
28
+
29
+ Three builders make the questions. Give each a name; the answers come back under the same names.
30
+
31
+ ```js
32
+ import { choice, noul, score } from 'sygnal/ai'
33
+
34
+ export const questions = {
35
+ // pick one option: name → description
36
+ topic: choice('What is this ticket about?', {
37
+ billing: 'Payments, invoices, plans, refunds',
38
+ bug: 'Something in the product is broken',
39
+ account: 'Login, access or profile',
40
+ }),
41
+ // the probability of yes; the criteria say what counts as true and false
42
+ urgent: noul('Does the customer need this handled today?', {
43
+ true: 'Blocked, losing money, or a deadline',
44
+ false: 'A question or a minor issue',
45
+ }),
46
+ // an ordered scale, lowest first
47
+ mood: score('How upset is the customer?', ['calm', 'annoyed', 'angry']),
48
+ }
49
+ ```
50
+
51
+ | Question | Answer |
52
+ |---|---|
53
+ | `choice(instructions, options)` | `{ type: 'choice', choice, probabilities, confidence }`: the most likely option, every option's probability (they sum to 1), and how strongly the model favours one |
54
+ | `noul(instructions, criteria?)` | `{ type: 'noul', noul }`: the probability of yes, 0 to 1 |
55
+ | `score(instructions, levels)` | `{ type: 'score', score, legend, probabilities, confidence }`: the probability-weighted level index (0 is the first level; 1.4 is between the second and third), each level's probability, and the confidence |
56
+
57
+ - `options` can also be a plain list of names: `choice('Which language?', ['en', 'fr', 'de'])`.
58
+ - `instructions` can be text, or an object or array that holds the question with the data it names.
59
+ - Write `noul` criteria: answers are better calibrated with them.
60
+ - Questions are answered in parallel, so a few more cost little time.
61
+
62
+ **Typed answers.** In TypeScript the answers are typed from the questions: `answers.topic.choice` is `'billing' | 'bug' | 'account'`. Name the reply type with `Decision<typeof questions>`:
63
+
64
+ ```ts
65
+ import type { Decision } from 'sygnal/ai'
66
+ import { questions } from './questions'
67
+
68
+ type Triage = Decision<typeof questions>
69
+
70
+ const label = (d: Triage) => (d.answers.urgent.noul > 0.5 ? `${d.answers.topic.choice} (urgent)` : d.answers.topic.choice)
71
+ ```
72
+
73
+ ## As a resource
74
+
75
+ Most decisions describe some state the app already has: a ticket, a message, a form. Declare the decision as a [resource](./resources.md), and it runs again whenever the state it depends on changes. A stale answer is never shown for new text: the earlier request is aborted.
76
+
77
+ ```jsx
78
+ import { decide } from 'sygnal/ai'
79
+ import { questions } from './questions.js'
80
+
81
+ function Ticket({ state }) {
82
+ const t = state.triage
83
+ return (
84
+ <article>
85
+ <p>{state.text}</p>
86
+ {t.status === 'loading' && <p>Triaging…</p>}
87
+ {t.status === 'success' && <p className="topic">{t.data.answers.topic.choice}</p>}
88
+ {t.status === 'error' && <p role="alert">Could not triage: {t.error.message}</p>}
89
+ </article>
90
+ )
91
+ }
92
+
93
+ Ticket.initialState = { text: 'I was charged twice this month' }
94
+
95
+ Ticket.resources = {
96
+ triage: (state) => state.text && decide({ model: 'jev-latest', state: state.text, questions }),
97
+ }
98
+ ```
99
+
100
+ `decide()` returns `{ url, method: 'POST', json: { model, state, questions } }`. The default `url` is `'/api/decide'`, a route on your own server that adds the key ([below](#keys-stay-on-the-server)). Every other key passes through to the request: `ok`, `error`, `key`, `latest`, `headers`, `timeoutMs`, `retry`, and the resource options `keepPrevious`, `refetchEvery` and `background`.
101
+
102
+ ## As a request
103
+
104
+ A decision the user asks for (a button, a submit) is a request with reply actions, like any HTTP request:
105
+
106
+ ```jsx
107
+ import { decide } from 'sygnal/ai'
108
+ import { questions } from './questions.js'
109
+
110
+ Inbox.model = {
111
+ TRIAGE: {
112
+ STATE: (state) => ({ ...state, triaging: true }),
113
+ HTTP: (state, ticket) => decide({ model: 'jev-latest', state: ticket.text, questions, ok: 'TRIAGED', error: 'TRIAGE_FAILED' }),
114
+ },
115
+ TRIAGED: (state, { answers }) => ({ ...state, triaging: false, topic: answers.topic.choice, urgent: answers.urgent.noul > 0.5 }),
116
+ TRIAGE_FAILED: (state, { error }) => ({ ...state, triaging: false, error: error.message }),
117
+ }
118
+ ```
119
+
120
+ `state` can be text, or an object or array, sent as JSON: `state: { subject, body, plan: customer.plan }`. Models that read images take `images`: base64 PNG, JPEG or WebP files shared by every question.
121
+
122
+ ## Confidence and escalation
123
+
124
+ `confidence` (0 to 1) says how strongly the model favours one option over the others. It is not a promise that the answer is right, but a low value is a reliable sign that the question is hard for this input: the text is ambiguous, or fits two options. That is when to ask something slower and smarter. Sending only the unsure cases to a chat model keeps the cost and the wait of a decision for most inputs, and gets a written reason for the rest.
125
+
126
+ In this demo, the resource's `ok` action looks at the confidence. Above 0.6 the decision stands; below it, the component asks the chat model (the [chat driver](./ai-chat.md), as `LLM`) for a second opinion, which streams in. The first ticket is ambiguous, so the escalation runs as soon as the demo shows. Try "The app crashes when I open settings".
127
+
128
+ ```js live-server
129
+ import { encodeOpenResponses } from 'sygnal/ai'
130
+
131
+ const has = (text, words) => words.some((w) => text.toLowerCase().includes(w))
132
+
133
+ export default {
134
+ // the decision model
135
+ 'POST /v1/systemone': ({ json }) => {
136
+ const t = String(json.state)
137
+ const topic = has(t, ['charge', 'refund', 'invoice']) ? 'billing' : has(t, ['crash', 'broken', 'error']) ? 'bug' : 'account'
138
+ const sure = has(t, ['charge', 'crash', 'password']) ? 0.94 : 0.41
139
+ const others = ['billing', 'bug', 'account'].filter((k) => k !== topic)
140
+ return {
141
+ delayMs: 400,
142
+ json: {
143
+ model: json.model,
144
+ answers: {
145
+ topic: { type: 'choice', choice: topic, confidence: sure, probabilities: { [topic]: sure, [others[0]]: (1 - sure) / 2, [others[1]]: (1 - sure) / 2 } },
146
+ urgent: { type: 'noul', noul: has(t, ['twice', 'now', 'today']) ? 0.9 : 0.15 },
147
+ },
148
+ },
149
+ }
150
+ },
151
+ // the chat model, for the unsure ones
152
+ 'POST /v1/responses': () => ({
153
+ sse: encodeOpenResponses(['account: ', 'the customer ', 'cannot open ', 'their invoices, ', 'which sounds like ', 'an access problem, ', 'not a payment one.']),
154
+ delayMs: 300,
155
+ chunkMs: 80,
156
+ }),
157
+ }
158
+ ```
159
+
160
+ ```jsx live live-height=220
161
+ import { ABORT } from 'sygnal'
162
+ import { decide, choice, noul } from 'sygnal/ai'
163
+
164
+ const questions = {
165
+ topic: choice('What is this ticket about?', {
166
+ billing: 'Payments, invoices, plans, refunds',
167
+ bug: 'Something in the product is broken',
168
+ account: 'Login, access or profile',
169
+ }),
170
+ urgent: noul('Does the customer need this handled today?', {
171
+ true: 'Blocked, losing money, or a deadline',
172
+ false: 'A question or a minor issue',
173
+ }),
174
+ }
175
+
176
+ const SURE = 0.6
177
+
178
+ const secondOpinion = (text) => ({
179
+ instructions: 'Classify the support ticket as billing, bug or account. Answer with the category, a colon, and one short reason.',
180
+ messages: [{ role: 'user', content: text }],
181
+ key: 'opinion',
182
+ delta: 'OPINION',
183
+ ok: 'OPINION',
184
+ error: 'OPINION_FAILED',
185
+ })
186
+
187
+ function Ticket({ state }) {
188
+ const t = state.triage
189
+ const answers = t.status === 'success' && t.data.answers
190
+ return (
191
+ <article className="ticket">
192
+ <form className="triage">
193
+ <label>Ticket <input className="text" value={state.draft} /></label>
194
+ <button type="submit">Triage</button>
195
+ </form>
196
+ <p aria-live="polite">
197
+ {t.status === 'loading' && 'Triaging…'}
198
+ {answers && <>
199
+ <b className="topic">{answers.topic.choice}</b> ({Math.round(answers.topic.confidence * 100)}% sure)
200
+ {answers.urgent.noul > 0.5 && <strong> urgent</strong>}
201
+ </>}
202
+ {t.status === 'error' && `Could not triage: ${t.error.message}`}
203
+ </p>
204
+ {state.opinion && <p className="opinion" aria-live="polite"><b>Second opinion:</b> {state.opinion}</p>}
205
+ </article>
206
+ )
207
+ }
208
+
209
+ Ticket.initialState = { draft: 'I cannot see my invoices anymore', text: 'I cannot see my invoices anymore', opinion: '' }
210
+
211
+ Ticket.intent = ({ DOM }) => ({
212
+ TYPE: DOM.input('.text').value(),
213
+ TRIAGE: DOM.select('.triage').events('submit', { preventDefault: true }),
214
+ })
215
+
216
+ Ticket.resources = {
217
+ triage: (state) => state.text.trim() && decide({ url: '/v1/systemone', model: 'nimble', state: state.text, questions, ok: 'TRIAGED' }),
218
+ }
219
+
220
+ Ticket.model = {
221
+ TYPE: (state, draft) => ({ ...state, draft }),
222
+ TRIAGE: (state) => (state.draft.trim() ? { ...state, text: state.draft, opinion: '' } : ABORT),
223
+ // runs after the resource is written: escalate only the unsure ones
224
+ TRIAGED: {
225
+ LLM: (state, { answers }) => (answers.topic.confidence < SURE ? secondOpinion(state.text) : ABORT),
226
+ },
227
+ OPINION: (state, { text }) => ({ ...state, opinion: text }),
228
+ OPINION_FAILED: (state, { error }) => ({ ...state, opinion: `(no second opinion: ${error.message})` }),
229
+ }
230
+ ```
231
+
232
+ - **The threshold is yours to tune.** Look at the confidence of a few dozen real inputs. With a threshold of 0.6, an experiment with a local `nimble` sent about one ticket in ten to the chat model.
233
+ - **`delta` and `ok` can name the same action** when the finished reply needs nothing more than the text so far.
234
+ - A chat request's `key` (`'opinion'`) keeps it apart from other chat requests of the component, and `latest` aborts the second opinion of an earlier ticket.
235
+ - `score` answers have a `confidence` too. A `noul` answer has none: its `noul` itself says how sure it is (near 0.5 is unsure).
236
+
237
+ The [support inbox](./recipes/ai-support-inbox.md) recipe puts this into a whole inbox.
238
+
239
+ ## OpenAI Decisions
240
+
241
+ OpenAI Decisions takes the same idea in another form: an array of questions (`predicate`, `choice`, `score`) and per-question refusals. `decide.openai()` takes the same options and questions as `decide()`, sends OpenAI's form, and maps the reply back. Your reply actions and resources get the same `{ answers: { name: answer } }` shape whichever you use:
242
+
243
+ ```js
244
+ Ticket.resources = {
245
+ triage: (state) => state.text && decide.openai({ model: 'gpt-6-luna', state: state.text, questions }),
246
+ }
247
+ ```
248
+
249
+ A `noul` question becomes a `predicate` whose instructions include the criteria. OpenAI may refuse a question: its answer is then `{ type: 'refusal', … }`, so check `answer.type` before reading `choice`. The type `Decision<Q, RefusalAnswer>` includes it.
250
+
251
+ ## Keys stay on the server
252
+
253
+ The browser never holds a provider key ([SYG670](https://sygnal.js.org/reference/errors/#syg670) refuses to send one to another origin). `decide()` posts to `/api/decide` on your own server by default, and that route adds the key. Keep it narrow, as for [chat](./ai-chat.md#shipping-it): fix the model, require a session, and limit the size of `state`, so the route can't be used as a free decision API.
254
+
255
+ ```js
256
+ // server: POST /api/decide
257
+ import { currentUser } from './auth.js' // your session check
258
+
259
+ const MODELS = new Set(['jev-latest'])
260
+
261
+ export async function POST(req) {
262
+ if (!(await currentUser(req))) return new Response('Sign in first', { status: 401 })
263
+ const { model, state, questions } = await req.json()
264
+ if (!MODELS.has(model) || JSON.stringify(state).length > 20000) return new Response('Bad request', { status: 400 })
265
+
266
+ // DECIDE_URL: the provider's decisions endpoint, e.g. TypeSafe's /v1/systemone
267
+ const res = await fetch(process.env.DECIDE_URL, {
268
+ method: 'POST',
269
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.DECIDE_API_KEY}` },
270
+ body: JSON.stringify({ model, state, questions }),
271
+ })
272
+ return new Response(res.body, { status: res.status, headers: { 'content-type': 'application/json' } })
273
+ }
274
+ ```
275
+
276
+ For a local Ollama in development there is no key and no route: point `url` at `http://localhost:11434/v1/systemone`. To switch per environment, build the options in one place: `const DECIDE = import.meta.env.DEV ? { url: 'http://localhost:11434/v1/systemone', model: 'nimble' } : { model: 'jev-latest' }`, then `decide({ ...DECIDE, state, questions })`.
277
+
278
+ ## Testing
279
+
280
+ `renderComponent` answers the `HTTP` sink with its fetch fake ([HTTP testing](./http.md#testing-without-a-driver)). `answers(questions, picks)` from `sygnal/ai` builds the reply a decision model would send, typed from the questions: pick the answers the test cares about, and the rest are filled in (a `choice` gets its first option at confidence 0.9, a `noul` false, a `score` 0).
281
+
282
+ Here `Ticket.jsx` is the escalation demo's component, with `export const questions` and `export default Ticket`:
283
+
284
+ ```js
285
+ import { it, expect } from 'vitest'
286
+ import { renderComponent } from 'sygnal'
287
+ import { answers } from 'sygnal/ai'
288
+ import Ticket, { questions } from './Ticket.jsx'
289
+
290
+ it('trusts a confident triage', async () => {
291
+ const t = renderComponent(Ticket)
292
+ await t.respond('HTTP', answers(questions, { topic: 'billing', urgent: true }), 'triage')
293
+ expect(t.html()).toContain('billing')
294
+ expect(t.requests('LLM')).toEqual([])
295
+ t.dispose()
296
+ })
297
+
298
+ it('asks the chat model when the triage is unsure', async () => {
299
+ const t = renderComponent(Ticket)
300
+ await t.respond('HTTP', answers(questions, { topic: { choice: 'account', confidence: 0.4 } }), 'triage')
301
+ await t.respond('LLM', 'account: an access problem.')
302
+ expect(t.state.opinion).toBe('account: an access problem.')
303
+ t.dispose()
304
+ })
305
+ ```
306
+
307
+ - A pick is an option name, `{ choice, confidence }` or `{ probabilities }` for a `choice`; `true`, `false` or a probability for a `noul`; a level index, a level description or `{ score, confidence }` for a `score`. An unknown question name, option or level throws, so a test can't drift from the questions.
308
+ - For `decide.openai()`, answer with `answers.openai(questions, picks)`: OpenAI's array form, which the request's `parse` maps back as in the app.
309
+ - The resource's request is sent after the first render; `t.respond` by the resource name (`'triage'`) waits for it.
310
+
311
+ ## A command bar
312
+
313
+ The `commandBar` behavior from `sygnal/ai` puts a decision model in front of your components' agent actions: the user types "mark the milk as bought", one decision picks the action and the item, and the behavior runs it. Below the confidence you set, it hands the command to a chat assistant instead (`escalate`), or tells the user it is unsure:
314
+
315
+ ```jsx
316
+ import { commandBar } from 'sygnal/ai'
317
+
318
+ TodoApp.uses = {
319
+ cmd: commandBar({ input: '.command', decide: { url: '/api/decide', model: 'jev-latest' }, below: 0.6, escalate: 'assistant' }),
320
+ }
321
+ ```
322
+
323
+ It reads the actions from the components' [`agent` declarations](./agent.md#the-agent-static), the same ones the in-app assistant and browser agents use. [Agents: a command bar](./agent.md#a-command-bar-commandbar) documents it: the questions it asks, its options and state, escalation, free-text arguments, and a live demo.
324
+
325
+ ## Related
326
+
327
+ - [Agents](./agent.md): the `agent` static, the command bar and the in-app assistant
328
+ - [AI Chat](./ai-chat.md): the chat driver, transports, and shipping an AI SDK route
329
+ - [Resources and Caching](./resources.md): the rules a decision resource follows
330
+ - [Support inbox](./recipes/ai-support-inbox.md): triage, sorting and escalation in a whole inbox
@@ -0,0 +1,312 @@
1
+ <!-- Generated from docs/src/content/docs/guide by scripts/copy-guides.mjs; online: https://sygnal.js.org/guide/ -->
2
+ # Behaviors
3
+
4
+ A **behavior** is a piece of state, intent and model that several components share: a pager, a selection, an undo history, a disclosure. A component lists the behaviors it uses in its `uses` static, each under a state key. The behavior then runs on that slice of the component's state, and its actions are named after the key (`pager.NEXT`).
5
+
6
+ Sygnal ships four behaviors: [`pager`](#pager), [`selection`](#selection), [`undo`](./undo.md) and [`form`](./forms.md). You write your own with [`defineBehavior`](#writing-a-behavior). The [UI parts](./ui/overview.md) in `sygnal/ui` (dialog, popover, tooltip, tabs, accordion, disclosure) are behaviors too.
7
+
8
+ ## Using a behavior
9
+
10
+ `uses` maps a state key to a behavior, called with its options:
11
+
12
+ ```jsx
13
+ TaskList.uses = { pager: pager({ pageSize: 10, next: '.newer', prev: '.older' }) }
14
+ ```
15
+
16
+ This gives the component:
17
+
18
+ - **state** at `state.pager`: the behavior's own state (`{ page, pageSize, total }`), with its calculated fields (`offset`, `pages`, `hasPrev`, `hasNext`) stored on the slice;
19
+ - **actions** `pager.NEXT`, `pager.PREV`, `pager.GOTO` and `pager.SET_TOTAL`, which change only `state.pager`;
20
+ - **triggers**: the behavior's intent listens to what its options name. Here a click on the `Newer` button dispatches `pager.NEXT`.
21
+
22
+ The options that tell a behavior what to listen to take a CSS selector: `next: '.newer'` listens to clicks on the view's `<button className="newer">`. They take a [control](https://sygnal.js.org/guide/controls/) too.
23
+
24
+ Options that name a key of the behavior's state (`pageSize` here) set its starting value.
25
+
26
+ ### Pager
27
+
28
+ A page cursor over a list. The view slices the list with the calculated `offset`, and the buttons disable at the ends. In this demo, a stand-in server returns 23 tasks:
29
+
30
+ ```js live-server
31
+ const tasks = Array.from({ length: 23 }, (_, i) => ({ id: i + 1, title: `Task ${i + 1}` }))
32
+
33
+ export default {
34
+ 'GET /api/tasks': () => ({ json: tasks }),
35
+ }
36
+ ```
37
+
38
+ ```jsx live
39
+ import { pager } from 'sygnal'
40
+
41
+ export function TaskList({ state }) {
42
+ const { offset, pageSize, page, pages, hasPrev, hasNext } = state.pager
43
+ return (
44
+ <div>
45
+ <ul>
46
+ {state.tasks.slice(offset, offset + pageSize).map(task => <li>{task.title}</li>)}
47
+ </ul>
48
+ <nav>
49
+ <button className="older" disabled={!hasPrev}>Older</button>
50
+ <span className="page">Page {page + 1} of {pages}</span>
51
+ <button className="newer" disabled={!hasNext}>Newer</button>
52
+ </nav>
53
+ </div>
54
+ )
55
+ }
56
+
57
+ TaskList.initialState = { tasks: [] }
58
+ TaskList.uses = { pager: pager({ pageSize: 10, next: '.newer', prev: '.older' }) }
59
+ TaskList.model = {
60
+ BOOTSTRAP: { HTTP: () => ({ url: '/api/tasks', ok: 'LOADED' }) },
61
+ LOADED: (state, tasks) => ({ ...state, tasks, pager: { ...state.pager, total: tasks.length } }),
62
+ }
63
+ ```
64
+
65
+ | | |
66
+ |---|---|
67
+ | Options | `pageSize` (20), `page` (0), `total` (`null`: unknown), `next` and `prev` (what to listen to for clicks) |
68
+ | State | `page`, `pageSize`, `total`; calculated `offset`, `pages` (`null` while `total` is unknown), `hasPrev`, `hasNext` |
69
+ | Actions | `NEXT`, `PREV` (no change at the first and last page), `GOTO` (a page number, kept in range), `SET_TOTAL` (the item count) |
70
+
71
+ Without a `total`, `NEXT` has no upper bound. Set it with an option, with `pager.SET_TOTAL`, or, as the `LOADED` reducer above does, by writing `state.pager.total` from a host reducer: the calculated fields follow.
72
+
73
+ ### Selection
74
+
75
+ Single or multiple selection over a list, with a select-all toggle:
76
+
77
+ ```jsx live
78
+ import { selection, isSelected } from 'sygnal'
79
+
80
+ export function Inbox({ state }) {
81
+ const { count } = state.sel
82
+ return (
83
+ <div>
84
+ <label>
85
+ <input className="pick-all" type="checkbox" checked={count > 0 && count === state.mails.length} /> Select all
86
+ </label>
87
+ <button className="archive" disabled={count === 0}>Archive ({count})</button>
88
+ <ul>
89
+ {state.mails.map(mail => (
90
+ <li>
91
+ <label>
92
+ <input className="pick" type="checkbox" data-id={mail.id} checked={isSelected(state.sel, mail.id)} /> {mail.subject}
93
+ </label>
94
+ </li>
95
+ ))}
96
+ </ul>
97
+ </div>
98
+ )
99
+ }
100
+
101
+ Inbox.initialState = {
102
+ mails: [{ id: 1, subject: 'Lunch?' }, { id: 2, subject: 'Invoice' }, { id: 3, subject: 'Re: plans' }],
103
+ }
104
+ Inbox.uses = { sel: selection({ multi: true, item: '.pick', all: '.pick-all', from: 'mails' }) }
105
+ Inbox.intent = ({ DOM }) => ({ ARCHIVE: DOM.click('.archive') })
106
+ Inbox.model = {
107
+ ARCHIVE: (state) => ({
108
+ ...state,
109
+ mails: state.mails.filter(mail => !isSelected(state.sel, mail.id)),
110
+ sel: { ...state.sel, selected: [] },
111
+ }),
112
+ }
113
+ ```
114
+
115
+ | | |
116
+ |---|---|
117
+ | Options | `multi` (false: a click replaces the selection; true: it toggles the item), `item` (a selector for the element on each item), `attr` (the item element's attribute that holds its id, default `data-id`), `all` (a select-all toggle), `clear`, `from` (the host state key of the list, for select-all), `idField` (`'id'`) |
118
+ | State | `selected` (the ids, as strings, in selection order); calculated `count` |
119
+ | Actions | `SELECT` (an id, or a click on an item), `SELECT_ALL` (an array of ids, or every id of `state[from]`), `TOGGLE_ALL` (all selected → none, else all), `CLEAR` |
120
+
121
+ Read the selection with `isSelected(state.sel, id)`. Ids compare as strings, so `isSelected(state.sel, 1)` and `isSelected(state.sel, '1')` agree.
122
+
123
+ ### Undo
124
+
125
+ `undo({ key: 'doc' })` records the changes to `state.doc` and adds `history.UNDO` and `history.REDO`. See [Undo and Redo](./undo.md).
126
+
127
+ ### Sortable
128
+
129
+ `sortable({ from: 'tasks', item: '.task', handle: '.grip' })` reorders `state.tasks` by mouse, touch and keyboard, announces each step in `state.sort.message` for a live region, and dispatches `sort.DROPPED` once per completed move. See [Drag and Drop](./drag-and-drop.md#sortable-lists).
130
+
131
+ ### Form
132
+
133
+ `form(schema, { values, submit })` is a form with validation: `state.form` holds the values, errors and touched fields, the fields inside the form element are matched by `name`, and a valid submit dispatches the `submit` action with the validated values. See [Forms](./forms.md).
134
+
135
+ ## Writing a behavior
136
+
137
+ `defineBehavior()` takes the same parts as a component, without a view: `initialState`, `intent`, `model`, `calculated` and `timers`. It returns a factory: call it with the options of one use.
138
+
139
+ ```js live-file=./behaviors/disclosure.js
140
+ // behaviors/disclosure.js
141
+ import { ABORT, defineBehavior } from 'sygnal'
142
+
143
+ export const disclosure = defineBehavior({
144
+ initialState: { open: false },
145
+ intent: ({ DOM }, { toggle }) => ({ TOGGLE: DOM.click(toggle) }),
146
+ model: {
147
+ TOGGLE: (slice) => ({ ...slice, open: !slice.open }),
148
+ CLOSE: (slice) => (slice.open ? { ...slice, open: false } : ABORT),
149
+ },
150
+ calculated: {
151
+ label: (slice) => (slice.open ? 'Hide details' : 'Show details'),
152
+ },
153
+ })
154
+ ```
155
+
156
+ - `initialState` is the slice a host starts with.
157
+ - `intent` receives the host's sources (its DOM, `STATE`, `EVENTS`, `CHILD` and drivers) and the options. Name the actions without the key: the host sees `TOGGLE` as `more.TOGGLE` when it uses the behavior under `more`.
158
+ - The `model` reducers receive the slice, not the host's state, and return the new slice. `ABORT` (or the slice itself) means no change. `next('CLOSE')` inside the behavior names its own action.
159
+ - `calculated` fields are computed on the slice and stored on it (`state.more.label`).
160
+ - A behavior's entries can use every sink a component can: `EVENTS`, `PARENT`, `EFFECT`, drivers.
161
+
162
+ A host uses it like a first-party behavior:
163
+
164
+ ```jsx live
165
+ // Product.jsx
166
+ import { disclosure } from './behaviors/disclosure.js'
167
+
168
+ export function Product({ state }) {
169
+ return (
170
+ <section>
171
+ <h2>{state.name}</h2>
172
+ <button className="toggle" aria-expanded={String(state.more.open)}>{state.more.label}</button>
173
+ {state.more.open && <p>{state.description}</p>}
174
+ </section>
175
+ )
176
+ }
177
+
178
+ Product.initialState = { name: 'Desk lamp', description: 'Warm light, three brightness levels.' }
179
+ Product.uses = { more: disclosure({ toggle: '.toggle' }) }
180
+ ```
181
+
182
+ `state.more` is `{ open: false, label: 'Show details' }` to begin with, and a click on the `.toggle` button dispatches `more.TOGGLE`. To start it open, pass the state key as an option: `disclosure({ toggle: '.toggle', open: true })`.
183
+
184
+ Two components can use the same behavior, and so can every item of a [Collection](https://sygnal.js.org/guide/collections/): each instance gets its own slice. In a Collection item (or any child that gets its state from its parent), `state[key]` reads as the behavior's initial state until the first action writes it.
185
+
186
+ ### Options, the key, host state and timers
187
+
188
+ Every model handler of a behavior gets the use's options and its key after the usual arguments: `(slice, data, next, props, options, key)`, and the intent gets `(sources, options, key)`. `props.state` is the host's whole state.
189
+
190
+ Two more parts are for behaviors that reach past their slice:
191
+
192
+ - **`HOST`**: a model entry `{ HOST: (state, data, next, props, options, key) => newState }` is a reducer on the host's whole state, for a behavior that edits a host field (reordering `state[options.from]`, say). `ABORT`, or the same state, means no change. An entry can have both: `STATE` runs first (on the slice), then `HOST` gets the whole state with that update applied; an `ABORT` from one keeps the other's change.
193
+ - **`timers: (slice, options, key) => ({ name: spec })`** declares [timers](./timers.md) for the host, as the `timers` static does (the app needs `makeTimerDriver()`). The host sees them as `'<key>.<name>'`; a spec whose `action` names one of the behavior's actions is sent to that action (`'SHOW'` arrives as `'tip.SHOW'`), any other action name goes to the host as written. They run alongside the host's own `timers`.
194
+
195
+ ```js live-file=./behaviors/hoverDelay.js
196
+ // behaviors/hoverDelay.js
197
+ import { defineBehavior } from 'sygnal'
198
+
199
+ export const hoverDelay = defineBehavior({
200
+ initialState: { pending: false, open: false },
201
+ intent: ({ DOM }, { target }) => ({ ENTER: DOM.mouseenter(target), LEAVE: DOM.mouseleave(target) }),
202
+ timers: (slice, { delay = 300 }) => ({ show: slice.pending && { after: delay, action: 'SHOW' } }),
203
+ model: {
204
+ ENTER: (slice) => ({ ...slice, pending: true }),
205
+ LEAVE: (slice) => ({ ...slice, pending: false, open: false }),
206
+ SHOW: (slice) => ({ ...slice, pending: false, open: true }),
207
+ },
208
+ })
209
+ ```
210
+
211
+ A host uses it with its own delay:
212
+
213
+ ```jsx live
214
+ // Card.jsx
215
+ import { hoverDelay } from './behaviors/hoverDelay.js'
216
+
217
+ export function Card({ state }) {
218
+ return (
219
+ <div>
220
+ <button className="help">Help</button>
221
+ {state.tip.open && <p className="tip">Shown half a second after the pointer entered Help.</p>}
222
+ </div>
223
+ )
224
+ }
225
+
226
+ Card.uses = { tip: hoverDelay({ target: '.help', delay: 500 }) }
227
+ ```
228
+
229
+ `state.tip.open` turns true half a second after the pointer enters `.help` (`tip.show` is the timer, `tip.SHOW` its action), and false when it leaves. A behavior that sends a driver request names its [reply actions](./http.md) with the key, so they reach its own model: `ok: key + '.LOADED'`.
230
+
231
+ ### Persisted state and undo steps
232
+
233
+ Two markers say how a behavior's state relates to the app's data:
234
+
235
+ - **`persist: false`**: the slice is UI state (an open menu, a drag in progress). A root's [`persist()`](./persistence.md) neither saves nor restores that `uses` key, whatever `pick` / `omit` say. This covers the root component's own `uses` only: the slice of a behavior on a sub-component or a Collection item is part of the data around it (`state.list.sort`, `state.lanes[0].sort`) and is saved with it. The behavior has to cope with a restored slice (sortable resets restored drag state when the host starts, and leaves the data as it is).
236
+ - **`undoStep: ['DONE']`**: the actions that complete one undoable step. With the [`undo` behavior](./undo.md) on the same host, the behavior's other actions are steps of a gesture: their changes to the undo key aren't recorded, and `DONE` records the value from before the gesture as one entry. A gesture that ends without `DONE` (cancelled) records nothing, and so does one whose steps bring the value back to where it started: the same value, or an array or plain object with the same entries (compared one level deep, by identity; return the earlier entry objects, not copies, when a step puts them back). The order of the two in `uses` doesn't matter. A recorded change, UNDO or REDO in the middle of a gesture first records the value from before it. Only the behavior that started a gesture completes it: another gesture behavior's `DONE` on the same host doesn't record it. With `track` naming none of the behavior's actions, its gestures aren't recorded.
237
+
238
+ [`sortable`](./drag-and-drop.md) declares both: `persist: false`, and `undoStep: ['DROPPED']`, so one drag is one undo step. It also tells `undo` (internally) when a drag ends without a drop, so a cancelled drag never leaves a step pending.
239
+
240
+ ## Extending a behavior's actions
241
+
242
+ The host can trigger a behavior action, and add its own entry for one. Both use the namespaced name:
243
+
244
+ ```jsx live
245
+ // Faq.jsx
246
+ import { ABORT } from 'sygnal'
247
+ import { disclosure } from './behaviors/disclosure.js'
248
+
249
+ export function Faq({ state }) {
250
+ return (
251
+ <section>
252
+ <button className="toggle" aria-expanded={String(state.answer.open)}>{state.answer.label}</button>
253
+ {state.answer.open && <p>{state.text}</p>}
254
+ <p className="opened">Opened {state.opened} times</p>
255
+ </section>
256
+ )
257
+ }
258
+
259
+ Faq.initialState = { text: 'Yes, returns are free for 30 days.', opened: 0 }
260
+ Faq.uses = { answer: disclosure({ toggle: '.toggle' }) }
261
+ Faq.intent = ({ DOM }) => ({
262
+ // a behavior action triggered by the host: Escape closes the answer
263
+ 'answer.CLOSE': DOM.keydown('document').key().filter(key => key === 'Escape'),
264
+ })
265
+ Faq.model = {
266
+ // runs after the behavior's own TOGGLE, on the full state with its update applied
267
+ 'answer.TOGGLE': (state) => (state.answer.open ? { ...state, opened: state.opened + 1 } : ABORT),
268
+ }
269
+ ```
270
+
271
+ The merge rules:
272
+
273
+ | Host adds | Effect |
274
+ |---|---|
275
+ | An intent action with a behavior's name (`'answer.CLOSE'`) | Triggers that action. If the behavior has its own trigger for it, the host's replaces it (see [keyboard shortcuts for undo](./undo.md#keyboard-shortcuts)). |
276
+ | A STATE reducer for a behavior action (`'answer.TOGGLE'`) | Runs after the behavior's, on the full state with the behavior's update applied. Its `ABORT` keeps that update. |
277
+ | An `EFFECT` for a behavior action | Runs after the behavior's `EFFECT`. |
278
+ | A value sink (`EVENTS`, `PARENT`, a driver) for a behavior action | Replaces the behavior's value for that sink. |
279
+ | A reducer for another action that changes `state[key]` | The slice's calculated fields are recomputed. |
280
+
281
+ A behavior's [reply actions](./http.md) (`ok: 'LOADED'` on a request it sends) arrive under the name it gives; to reach its own model, it names them with its key (`ok: key + '.LOADED'`, see above).
282
+
283
+ ## Testing
284
+
285
+ `simulateAction` takes the namespaced name, and [`t.actions`](https://sygnal.js.org/integration/testing/#action-log-tactions-and-texplain) lists behavior actions under it. A click on a behavior's trigger has the cause `'behavior'`:
286
+
287
+ ```jsx
288
+ import { expect } from 'vitest'
289
+ import { renderComponent } from 'sygnal'
290
+ import { Faq } from './Faq.jsx'
291
+
292
+ const t = renderComponent(Faq)
293
+ t.simulateAction('answer.TOGGLE')
294
+ await t.next(s => s.answer.open)
295
+ expect(t.state.opened).toBe(1)
296
+ expect(t.actions.at(-1)).toMatchObject({ type: 'answer.TOGGLE', cause: 'simulateAction', component: 'Faq' })
297
+ t.dispose()
298
+ ```
299
+
300
+ ## SYG127
301
+
302
+ A `uses` entry that can't work is [SYG127](https://sygnal.js.org/reference/errors/#syg127), an error:
303
+
304
+ - the host's `initialState` already has the key (`initialState = { pager: … }` with `uses = { pager: … }`): set the behavior's values through its options instead;
305
+ - the value isn't a behavior: a plain object, or the factory without the call (`uses = { pager }` instead of `pager()`);
306
+ - an option the behavior never reads, usually a typo (`pager({ nxt: '.newer' })`). Only `sygnal-check` reports this one.
307
+
308
+ `sygnal-check` follows `uses` entries to their `defineBehavior()` call in the same file or a relative import, and knows the first-party behaviors (the `sygnal/ui` parts too: an option typo such as `dialog({ clse: '.close' })` is SYG127), so its other rules ([SYG101](https://sygnal.js.org/reference/errors/#syg101), [SYG102](https://sygnal.js.org/reference/errors/#syg102), …) see the behavior's actions too. A behavior imported from a package is not checked. The dev checks report SYG127 once per component definition.
309
+
310
+ ## TypeScript
311
+
312
+ `UsesState<typeof uses>` is the state a `uses` object adds and `UsesActions<typeof uses>` its namespaced actions, for a component's state and action types: `type State = { tasks: Task[] } & UsesState<typeof uses>`.