oneshot-gtm-server 0.2.0 → 0.4.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 (70) hide show
  1. package/dist/bin.mjs +2232 -1211
  2. package/dist/bin.mjs.map +1 -1
  3. package/dist/web/assets/Badge-B2tW85qr.js +1 -0
  4. package/dist/web/assets/Button-C-XcKplu.js +1 -0
  5. package/dist/web/assets/EmptyNote-zvLnRLPo.js +1 -0
  6. package/dist/web/assets/Field-BxSk5tbg.js +1 -0
  7. package/dist/web/assets/Modal-CU0ZPvE2.js +1 -0
  8. package/dist/web/assets/Skeleton-DNAfO8PV.js +1 -0
  9. package/dist/web/assets/StrategistPanel-DMjQbPlQ.js +6 -0
  10. package/dist/web/assets/cadences-CvBPoULf.js +1 -0
  11. package/dist/web/assets/chevron-down-CDjJN-YY.js +1 -0
  12. package/dist/web/assets/chevron-right-BTFaTdbr.js +1 -0
  13. package/dist/web/assets/cn-CS0Arupu.js +1 -0
  14. package/dist/web/assets/inbox-CzzgtWQf.js +1 -0
  15. package/dist/web/assets/index-B_nrqLlS.js +54 -0
  16. package/dist/web/assets/index-Ya_svHJk.css +2 -0
  17. package/dist/web/assets/loader-circle-CKkt6cSn.js +1 -0
  18. package/dist/web/assets/measure-CEgySDdR.js +1 -0
  19. package/dist/web/assets/plays-CuudkOHb.js +1 -0
  20. package/dist/web/assets/queue-C7vGtsQ5.js +1 -0
  21. package/dist/web/assets/receipts-B5u3oLpw.js +1 -0
  22. package/dist/web/assets/refresh-cw-Bz4Kdt55.js +1 -0
  23. package/dist/web/assets/routes-DHC_we4Z.js +1 -0
  24. package/dist/web/assets/run._playName-B9sG9Msq.js +4 -0
  25. package/dist/web/assets/send-Bv2Dd-HU.js +1 -0
  26. package/dist/web/assets/setup-BRVBiCEX.js +1 -0
  27. package/dist/web/assets/{summarizeRun-BsPt7szF.js → summarizeRun-CVWcweeA.js} +1 -2
  28. package/dist/web/assets/x-CPdidoxn.js +1 -0
  29. package/dist/web/index.html +3 -3
  30. package/package.json +1 -1
  31. package/dist/web/assets/Badge-DE7L41a6.js +0 -2
  32. package/dist/web/assets/Badge-DE7L41a6.js.map +0 -1
  33. package/dist/web/assets/Button-NJ1UVzeB.js +0 -2
  34. package/dist/web/assets/Button-NJ1UVzeB.js.map +0 -1
  35. package/dist/web/assets/EmptyNote-DkmaZWuo.js +0 -2
  36. package/dist/web/assets/EmptyNote-DkmaZWuo.js.map +0 -1
  37. package/dist/web/assets/Field-B4mT8TGa.js +0 -2
  38. package/dist/web/assets/Field-B4mT8TGa.js.map +0 -1
  39. package/dist/web/assets/Modal-frAt7msr.js +0 -2
  40. package/dist/web/assets/Modal-frAt7msr.js.map +0 -1
  41. package/dist/web/assets/Skeleton-d2p06ghN.js +0 -2
  42. package/dist/web/assets/Skeleton-d2p06ghN.js.map +0 -1
  43. package/dist/web/assets/cadences-CsU8vKw2.js +0 -2
  44. package/dist/web/assets/cadences-CsU8vKw2.js.map +0 -1
  45. package/dist/web/assets/chevron-right-BXb7J1cp.js +0 -2
  46. package/dist/web/assets/chevron-right-BXb7J1cp.js.map +0 -1
  47. package/dist/web/assets/inbox-Dzd9QYT4.js +0 -2
  48. package/dist/web/assets/inbox-Dzd9QYT4.js.map +0 -1
  49. package/dist/web/assets/index-ByTPAanr.css +0 -2
  50. package/dist/web/assets/index-CzTgATNQ.js +0 -60
  51. package/dist/web/assets/index-CzTgATNQ.js.map +0 -1
  52. package/dist/web/assets/loader-circle-BylpxA-u.js +0 -2
  53. package/dist/web/assets/loader-circle-BylpxA-u.js.map +0 -1
  54. package/dist/web/assets/measure-S3BWSb2L.js +0 -2
  55. package/dist/web/assets/measure-S3BWSb2L.js.map +0 -1
  56. package/dist/web/assets/plays-DHIZA49D.js +0 -2
  57. package/dist/web/assets/plays-DHIZA49D.js.map +0 -1
  58. package/dist/web/assets/queue-ClVxfeJ0.js +0 -2
  59. package/dist/web/assets/queue-ClVxfeJ0.js.map +0 -1
  60. package/dist/web/assets/receipts-BgXV3-De.js +0 -2
  61. package/dist/web/assets/receipts-BgXV3-De.js.map +0 -1
  62. package/dist/web/assets/refresh-cw-BpMRSA9y.js +0 -2
  63. package/dist/web/assets/refresh-cw-BpMRSA9y.js.map +0 -1
  64. package/dist/web/assets/routes-B9L9tBMF.js +0 -2
  65. package/dist/web/assets/routes-B9L9tBMF.js.map +0 -1
  66. package/dist/web/assets/run._playName-a3eeybKs.js +0 -5
  67. package/dist/web/assets/run._playName-a3eeybKs.js.map +0 -1
  68. package/dist/web/assets/setup-fs0DMLq4.js +0 -2
  69. package/dist/web/assets/setup-fs0DMLq4.js.map +0 -1
  70. package/dist/web/assets/summarizeRun-BsPt7szF.js.map +0 -1
@@ -0,0 +1 @@
1
+ import{i as e,s as t,t as n}from"./cn-CS0Arupu.js";var r=t(),i=e([`inline-flex items-center gap-1 rounded-[var(--radius-xs)]`,`px-1.5 py-[1.5px]`,`font-sans text-[10.5px] font-medium`,`tracking-[0.02em] uppercase`,`ring-1 ring-inset`,`whitespace-nowrap`].join(` `),{variants:{tone:{neutral:`bg-ink-surface-2 text-ink-cream-2 ring-ink-rule`,receipt:`bg-[color:var(--ink-receipt)]/10 text-[color:var(--ink-receipt-2)] ring-[color:var(--ink-receipt)]/30`,spend:`bg-[color:var(--ink-spend)]/10 text-[color:var(--ink-spend-2)] ring-[color:var(--ink-spend)]/30`,blocked:`bg-[color:var(--ink-blocked)]/10 text-[color:var(--ink-blocked-2)] ring-[color:var(--ink-blocked)]/30`,signal:`bg-[color:var(--ink-signal)]/10 text-[color:var(--ink-signal-2)] ring-[color:var(--ink-signal)]/30`}},defaultVariants:{tone:`neutral`}});function a({className:e,tone:t,...a}){return(0,r.jsx)(`span`,{className:n(i({tone:t}),e),...a})}export{a as t};
@@ -0,0 +1 @@
1
+ import{i as e,s as t,t as n}from"./cn-CS0Arupu.js";var r=t(),i=e([`relative inline-flex items-center justify-center gap-1.5`,`font-sans font-medium`,`rounded-[var(--radius-sm)]`,`transition-[background,color,border-color,box-shadow,transform]`,`duration-[var(--dur-stamp)] ease-[var(--ease-standard)]`,`active:translate-y-[0.5px]`,`focus-visible:outline-none`,`disabled:cursor-not-allowed disabled:opacity-50`].join(` `),{variants:{variant:{primary:[`bg-ink-cream text-ink-bg`,`hover:bg-ink-cream-2`,`shadow-[var(--shadow-stamp)]`].join(` `),secondary:[`bg-ink-surface text-ink-cream`,`border border-ink-rule`,`hover:bg-ink-surface-2 hover:border-ink-rule-2`].join(` `),ghost:[`bg-transparent text-ink-cream-2`,`hover:bg-ink-surface hover:text-ink-cream`].join(` `),danger:[`bg-transparent text-[color:var(--ink-blocked-2)]`,`border border-[color:var(--ink-blocked)]`,`hover:bg-[color:var(--ink-blocked)]/12`].join(` `),accent:[`bg-transparent text-[color:var(--ink-signal-2)]`,`border border-[color:var(--ink-signal)]`,`hover:bg-[color:var(--ink-signal)]/10`].join(` `)},size:{sm:`h-7 px-2.5 text-[12px] tracking-[0.005em]`,md:`h-8 px-3 text-[13px]`,lg:`h-10 px-4 text-[14px]`}},defaultVariants:{variant:`primary`,size:`md`}});function a({className:e,variant:t,size:a,...o}){return(0,r.jsx)(`button`,{className:n(i({variant:t,size:a}),e),...o})}export{a as t};
@@ -0,0 +1 @@
1
+ import{c as e,s as t,t as n,u as r}from"./cn-CS0Arupu.js";import{h as i,m as a}from"./index-B_nrqLlS.js";import{t as o}from"./Button-C-XcKplu.js";var s=r(e(),1),c=t();function l({note:e,cli:t,children:r,className:l}){let[u,d]=(0,s.useState)(!1);return(0,c.jsxs)(`div`,{className:n(`flex flex-col items-start gap-4 py-10 px-6`,`border border-dashed border-ink-rule rounded-[var(--radius-lg)]`,`bg-[color:var(--ink-surface)]/40`,l),children:[(0,c.jsx)(`div`,{className:`max-w-[56ch] text-ink-cream-2`,style:{fontSize:15,lineHeight:1.55,fontWeight:400},children:e}),t&&(0,c.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,c.jsxs)(`code`,{className:n(`ln-mono text-[12.5px] text-ink-cream-2`,`rounded-[var(--radius-sm)] border border-ink-rule bg-ink-bg-deep`,`px-2.5 py-1.5`),children:[`$ `,t]}),(0,c.jsxs)(o,{variant:`ghost`,size:`sm`,onClick:()=>{navigator.clipboard.writeText(t),d(!0),setTimeout(()=>d(!1),1200)},"aria-label":`copy command`,children:[u?(0,c.jsx)(i,{size:12}):(0,c.jsx)(a,{size:12}),(0,c.jsx)(`span`,{className:`text-[11px]`,children:u?`copied`:`copy`})]})]}),r&&(0,c.jsx)(`div`,{className:`mt-1`,children:r})]})}export{l as t};
@@ -0,0 +1 @@
1
+ import{s as e,t}from"./cn-CS0Arupu.js";var n=e();function r({checked:e,onChange:r,disabled:i,label:a,size:o=`md`,className:s,...c}){let l=o===`sm`?{w:24,h:14,dot:10,inset:2}:{w:28,h:16,dot:12,inset:2},u=e?l.w-l.dot-l.inset:l.inset;return(0,n.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,"aria-label":a,disabled:i,onClick:()=>!i&&r?.(!e),className:t(`relative inline-flex shrink-0 items-center`,`rounded-full border transition-[background,border-color,box-shadow]`,`duration-[var(--dur-stamp)] ease-[var(--ease-standard)]`,`focus-visible:outline-none`,`disabled:opacity-40 disabled:cursor-not-allowed`,e?`border-[color:var(--ink-signal)]/45 bg-[color:var(--ink-signal)]/35`:`border-ink-rule bg-ink-bg-deep hover:border-ink-rule-2`,s),style:{width:l.w,height:l.h},...c,children:(0,n.jsx)(`span`,{"aria-hidden":`true`,className:t(`pointer-events-none absolute rounded-full`,`transition-[transform,background,box-shadow]`,`duration-[var(--dur-stamp)] ease-[var(--ease-standard)]`,e?`bg-[color:var(--ink-signal-2)] shadow-[0_0_0_1px_color-mix(in_oklch,var(--ink-signal)_40%,transparent)]`:`bg-[color:var(--ink-muted)]`),style:{width:l.dot,height:l.dot,transform:`translateX(${u}px)`,top:(l.h-l.dot)/2,left:0}})})}function i({label:e,hint:r,error:i,children:a,className:o}){return(0,n.jsxs)(`label`,{className:t(`flex flex-col gap-1.5`,o),children:[(0,n.jsx)(`span`,{className:`ln-eyebrow`,children:e}),a,i?(0,n.jsx)(`span`,{className:`font-mono text-[11.5px] text-[color:var(--ink-blocked-2)]`,children:i}):r?(0,n.jsx)(`span`,{className:`text-[12px] text-ink-faint`,children:r}):null]})}var a=[`h-9 w-full`,`rounded-[var(--radius-sm)]`,`bg-ink-bg-deep text-ink-cream`,`border border-ink-rule`,`px-3 font-sans text-[13.5px] leading-none`,`placeholder:text-ink-faint`,`transition-[border-color,background] duration-[var(--dur-stamp)]`,`hover:border-ink-rule-2`,`focus:outline-none focus:border-[color:var(--ink-signal)]`,`focus:shadow-[0_0_0_3px_color-mix(in_oklch,var(--ink-signal)_20%,transparent)]`].join(` `);function o({className:e,...r}){return(0,n.jsx)(`input`,{className:t(a,e),...r})}function s({className:e,...r}){return(0,n.jsx)(`textarea`,{className:t(a,`h-auto min-h-[84px] resize-y py-2 font-prose leading-[1.5]`,e),...r})}function c({className:e,...r}){return(0,n.jsx)(`select`,{className:t(a,`appearance-none pr-8`,e),...r})}function l({label:e,checked:i,onChange:a,disabled:o,className:s,id:c}){return(0,n.jsxs)(`label`,{htmlFor:c,className:t(`inline-flex cursor-pointer items-center gap-2.5`,`font-sans text-[13px] text-ink-cream-2`,`hover:text-ink-cream`,o&&`cursor-not-allowed opacity-60 hover:text-ink-cream-2`,s),children:[(0,n.jsx)(r,{checked:!!i,disabled:o,label:e,onChange:e=>{a&&a({target:{checked:e},currentTarget:{checked:e}})}}),(0,n.jsx)(`span`,{children:e})]})}export{s as a,c as i,i as n,r as o,o as r,l as t};
@@ -0,0 +1 @@
1
+ import{c as e,s as t,t as n,u as r}from"./cn-CS0Arupu.js";import{t as i}from"./x-CPdidoxn.js";import{t as a}from"./Button-C-XcKplu.js";var o=r(e(),1),s=t();function c({open:e,title:t,subtitle:r,onClose:c,children:l,footer:u,width:d=560}){return(0,o.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&c()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,c]),e?(0,s.jsx)(`div`,{className:n(`fixed inset-0 z-50 grid place-items-center p-4`,`bg-[color:var(--ink-bg)]/80`),onClick:c,role:`dialog`,"aria-modal":`true`,"aria-label":t,children:(0,s.jsxs)(`div`,{className:n(`relative max-h-[84vh] overflow-hidden`,`rounded-[var(--radius-lg)] border border-ink-rule bg-ink-surface`,`shadow-[var(--shadow-ink-bleed)]`),style:{width:`min(${d}px, 92vw)`},onClick:e=>e.stopPropagation(),children:[(0,s.jsxs)(`div`,{className:`flex items-start justify-between border-b border-ink-rule px-5 py-3.5`,children:[(0,s.jsxs)(`div`,{className:`min-w-0`,children:[(0,s.jsx)(`div`,{className:`truncate text-ink-cream`,style:{fontFamily:`var(--font-display)`,fontSize:19,letterSpacing:`-0.01em`},children:t}),r&&(0,s.jsx)(`div`,{className:`mt-0.5 font-mono text-[11.5px] text-ink-muted`,children:r})]}),(0,s.jsx)(a,{variant:`ghost`,size:`sm`,onClick:c,"aria-label":`Close`,className:`-mr-1.5`,children:(0,s.jsx)(i,{size:14})})]}),(0,s.jsx)(`div`,{className:`max-h-[64vh] overflow-y-auto p-5`,children:l}),u&&(0,s.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-t border-ink-rule bg-ink-bg/40 px-5 py-3`,children:u})]})}):null}export{c as t};
@@ -0,0 +1 @@
1
+ import{s as e,t}from"./cn-CS0Arupu.js";var n=e();function r({className:e,lines:r=1,widths:a,rounded:o=!0}){let s=Array.from({length:r},(e,s)=>{let c=a?.[s]??i(s,r);return(0,n.jsx)(`span`,{className:t(`block h-[10px]`,o?`rounded-[2px]`:``,`bg-[color:var(--ink-rule)]/60`),style:{width:c,marginTop:s===0?0:8}},s)});return(0,n.jsx)(`span`,{className:t(`inline-flex w-full flex-col`,e),"aria-hidden":`true`,"data-skeleton":!0,children:s})}function i(e,t){return t===1?`72%`:e===t-1?`48%`:e%2==0?`92%`:`80%`}function a({className:e}){return(0,n.jsxs)(`div`,{"aria-hidden":`true`,className:t(`flex items-center gap-3 border-b border-ink-rule px-3 py-2.5`,e),children:[(0,n.jsx)(`span`,{className:`h-[10px] w-[120px] rounded-[2px] bg-[color:var(--ink-rule)]/60`}),(0,n.jsx)(`span`,{className:`h-[10px] flex-1 rounded-[2px] bg-[color:var(--ink-rule)]/45`}),(0,n.jsx)(`span`,{className:`h-[10px] w-[60px] rounded-[2px] bg-[color:var(--ink-rule)]/40`})]})}export{a as n,r as t};
@@ -0,0 +1,6 @@
1
+ import{a as e,c as t,l as n,s as r,u as i}from"./cn-CS0Arupu.js";import{t as a}from"./x-CPdidoxn.js";import{a as o,b as s,c,i as l,l as u,n as d,o as f,r as p,s as m}from"./index-B_nrqLlS.js";import{t as h}from"./Button-C-XcKplu.js";function ee(e){let t=[];for(let n of e.effectTasks)try{n()}catch(e){t.push(e)}if(t.length>0){if(t.length===1)throw t[0];for(let e of t)console.error(e);throw AggregateError(t,`Errors during commit`)}}function te(e){let t=[];for(let n of e.cells)if(n?.type===`effect`&&(n.deps=null,n.cleanup))try{n.cleanup?.()}catch(e){t.push(e)}finally{n.cleanup=void 0}if(t.length>0){if(t.length===1)throw t[0];for(let e of t)console.error(e);throw AggregateError(t,`Errors during cleanup`)}}var g=typeof process<`u`&&!1,_=null;function ne(e,t){e.currentIndex=0;let n=_;_=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{_=n}}function v(){if(!_)throw Error(`No resource fiber available`);return _}function y(e){return g?_?.devStrictMode?_.isFirstRender?`child`:`root`:e?`root`:null:null}function re(e,t){let n=e[ie];if(!n)throw Error(`ResourceElement.type is not a valid Resource`);return n(t)}var ie=Symbol(`fnSymbol`);function b(e,t,n=void 0,r=y(!1)){return{type:e,root:t,markDirty:n,devStrictMode:r,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function x(e){if(!e.isMounted)throw Error(`Tried to unmount a fiber that is already unmounted`);e.isMounted=!1,te(e)}function S(e,t){let n={effectTasks:[],props:t,output:void 0};return ne(e,()=>{e.renderContext=n;try{n.output=re(e.type,t)}finally{e.renderContext=void 0}}),n}function C(e,t){e.isMounted=!0,g&&e.isNeverMounted&&e.devStrictMode===`root`&&(e.isNeverMounted=!1,ee(t),te(e)),e.isNeverMounted=!1,ee(t)}var ae=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],dirtyCells:[]}),w=e=>{for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.current=t.workInProgress;e.committedVersion=e.version,e.changelog.length=0,e.dirtyCells.length=0},T=(e,t)=>{let n=e.version>t;if(e.version=t,n){for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.workInProgress=t.current;if(e.dirtyCells.length=0,t===e.committedVersion)e.changelog.length=0;else{if(e.committedVersion>t)throw Error(`Version is less than committed version`);for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop();e.changelog.forEach(e=>e()),w(e)}}},oe=(e,t)=>{t.dirty||(t.dirty=!0,e.markDirty?.(),e.root.dirtyCells.push(t))},E=i(t(),1),se=()=>{if(!g)return null;let e=(0,E.useRef)(0),t=e.current===0;return(0,E.useState)(()=>e.current++),e.current===2?t?`child`:`root`:null};function ce(e){let t=(0,E.useMemo)(()=>ae(e=>r(e)),[]),[n,r]=(0,E.useReducer)((e,n)=>(T(t,e),e+ +!!n()),0);T(t,n);let i=se(),a=(0,E.useMemo)(()=>(e.key,b(e.type,t,void 0,i)),[e.type,e.key,t,i]),o=S(a,e.props);return(0,E.useLayoutEffect)(()=>()=>x(a),[a]),(0,E.useLayoutEffect)(()=>{w(t),C(a,o)}),o.output}function D(e){let t=e=>({type:t,props:e});return t[ie]=e,t}function O(e,t){return{...t,key:e}}var le=(e,t)=>{let n=v(),r=n.currentIndex++;if(!n.isFirstRender&&r>=n.cells.length)throw Error(`Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.`);let i=n.cells[r];if(i||(i=t(),n.cells[r]=i),i.type!==e)throw Error(`Hook order changed between renders`);return i},ue=e=>{v().renderContext.effectTasks.push(e)},de=(e,t)=>{if(e.renderContext)throw Error(`Resource updated during render`);if(e.isNeverMounted)throw Error(`Resource updated before mount`);e.root.dispatchUpdate(()=>{let n=t();return n?(n(),e.root.changelog.push(n),!0):!1})};function fe(e,t,n,r){let i=le(`reducer`,()=>{let t=v(),a=r?r(n):n;return g&&t.devStrictMode&&r&&r(n),{type:`reducer`,queue:new Set,dirty:!1,workInProgress:a,current:a,reducer:e,dispatch:n=>{let r={action:n,hasEagerState:!1,eagerState:void 0};de(t,()=>t.root.dirtyCells.length===0&&!r.hasEagerState&&(r.eagerState=e(i.workInProgress,n),r.hasEagerState=!0,Object.is(i.current,r.eagerState))?null:()=>{oe(t,i),i.queue.add(r)})}}}),a=v(),o=e===i.reducer;i.reducer=e;for(let t of i.queue)(!t.hasEagerState||!o)&&(t.eagerState=e(i.workInProgress,t.action),t.hasEagerState=!0),g&&a.devStrictMode&&e(i.workInProgress,t.action),i.workInProgress=t.eagerState;if(i.queue.clear(),t){let e=t(i.workInProgress);Object.is(e,i.workInProgress)||(oe(a,i),i.workInProgress=e)}return[i.workInProgress,i.dispatch]}function pe(e,t,n){return fe(e,void 0,t,n)}function me(e,t,n,r){return fe(e,t,n,r)}var he=(e,t)=>typeof t==`function`?t(e):t,ge=e=>typeof e==`function`?e():e;function k(e){return pe(he,e,ge)}var _e=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},ve=()=>({type:`effect`,cleanup:void 0,deps:null});function A(e,t){let n=le(`effect`,ve);if(!(t&&n.deps&&_e(n.deps,t))){if(n.deps!==null&&!!t!=!!n.deps)throw Error(`tapEffect called with and without dependencies across re-renders`);ue(()=>{let r=[];try{n.cleanup?.()}catch(e){r.push(e)}finally{n.cleanup=void 0}try{let t=e();if(t!==void 0&&typeof t!=`function`)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof t}`);n.cleanup=t}catch(e){r.push(e)}if(n.deps=t,r.length>0){if(r.length===1)throw r[0];for(let e of r)console.error(e);throw AggregateError(r,`Errors during commit`)}})}}function j(e){let[t]=k(()=>({current:e}));return t}function M(e,t){let[n]=k(e);return n}var ye=()=>{throw Error(`Memo reducer should not be called`)},N=(e,t)=>{let n=v(),[r]=me(ye,r=>{if(r&&_e(r.deps,t))return r;let i=e();return g&&n.devStrictMode&&e(),{value:i,deps:t}},null);return r.value},be=(e,t)=>N(()=>e,t);function xe(e){let t=j(e);if(A(()=>{t.current=e}),g){let e=v();return be(((...n)=>{if(e.renderContext)throw Error(`tapEffectEvent cannot be called during render`);return t.current(...n)}),[e])}return t.current}function P(e,t){let n=v(),r=j(0),i=N(()=>(e.key,b(e.type,n.root,()=>{r.current++,n.markDirty?.()})),[e.type,e.key,n]),a=t?N(()=>S(i,e.props),[i,...t,r.current]):S(i,e.props);return A(()=>()=>x(i),[i]),A(()=>{C(i,a)},[i,a]),a.output}function Se(e,t){let n=j(0),r=n.current,i=M(v,[]),a=M(()=>()=>{n.current++,i.markDirty?.()},[]),o=M(()=>new Map,[]),s=t?be(e,t):e,c=N(()=>{let e=s(),t=new Set,n=[],r=0;for(let s=0;s<e.length;s++){let c=e[s],l=c.key;if(l===void 0)throw Error(`tapResources did not provide a key for array at index ${s}`);if(t.has(l))throw Error(`Duplicate key ${l} in tapResources`);t.add(l);let u=o.get(l);if(!u){let e=b(c.type,i.root,a),t=S(e,c.props);u={fiber:e,next:t},r++,o.set(l,u),n.push(t.output)}else if(u.fiber.type!==c.type){let e=b(c.type,i.root,a),t=S(e,c.props);u.next=[e,t],n.push(t.output)}else u.next=S(u.fiber,c.props),n.push(u.next.output)}if(o.size>n.length-r)for(let e of o.keys())t.has(e)||(o.get(e).next=`delete`);return n},[s,r]);return A(()=>()=>{for(let e of o.keys()){let t=o.get(e).fiber;x(t)}},[]),A(()=>{for(let[e,t]of o.entries())t.next===`delete`?(t.fiber.isMounted&&x(t.fiber),o.delete(e)):Array.isArray(t.next)?(x(t.fiber),t.fiber=t.next[0],C(t.fiber,t.next[1])):C(t.fiber,t.next)},[c]),c}var Ce=50,F={schedulers:new Set([]),isScheduled:!1},we=class{_task;_isDirty=!1;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,F.schedulers.add(this),Te()}runTask(){this._isDirty=!1,this._task()}},Te=()=>{F.isScheduled||(F.isScheduled=!0,De())},Ee=()=>{try{let e=[],t=0;for(let n of F.schedulers)if(F.schedulers.delete(n),n.isDirty){if(t++,t>Ce)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.`);try{n.runTask()}catch(t){e.push(t)}}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,`Errors occurred during flushSync`)}}finally{F.schedulers.clear(),F.isScheduled=!1}},De=(()=>{if(typeof MessageChannel<`u`){let e=new MessageChannel;return e.port1.onmessage=Ee,()=>e.port2.postMessage(null)}return()=>setTimeout(Ee,0)})(),Oe=e=>{let t=F;F={schedulers:new Set([]),isScheduled:!0};try{let t=e();return Ee(),t}finally{F=t}},ke=e=>{let t=M(()=>new we(()=>l(null)),[]),n=M(()=>[],[]),r=N(()=>(e.key,b(e.type,ae(e=>{!t.isDirty&&!e()||(n.push(e),t.markDirty())}))),[e.type,e.key]);T(r.root,r.root.committedVersion);let i=S(r,e.props),a=j(!1),o=j(e.props),s=j(i.output),c=M(()=>new Set,[]),l=xe(e=>{if(e===null&&(T(r.root,2),T(r.root,1),n.forEach(e=>{g&&r.devStrictMode&&e(),e()}),g&&r.devStrictMode&&S(r,o.current),e=S(r,o.current)),t.isDirty)throw Error(`Scheduler is dirty, this should never happen`);w(r.root),n.length=0,a.current&&C(r,e),!(t.isDirty||s.current===e.output)&&(s.current=e.output,c.forEach(e=>e()))});return A(()=>(a.current=!0,()=>{a.current=!1,x(r)}),[r]),A(()=>{o.current=i.props,w(r.root),C(r,i),!(t.isDirty||s.current===i.output)&&(s.current=i.output,c.forEach(e=>e()))}),N(()=>({getValue:()=>s.current,subscribe:e=>(c.add(e),()=>c.delete(e))}),[])},Ae=Symbol(`tap.Context`),je=e=>({[Ae]:e}),Me=(e,t,n)=>{let r=e[Ae];e[Ae]=t;try{return n()}finally{e[Ae]=r}},Ne=e=>e[Ae],Pe=Symbol(`assistant-ui.store.clientIndex`),Fe=e=>e[Pe],Ie=je([]),Le=()=>Ne(Ie),Re=(e,t)=>{let n=Le();return Me(Ie,N(()=>[...n,e],[n,e]),t)},ze=new Set([`$$typeof`,`nodeType`,`then`]),Be=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!ze.has(e))return!1}},Ve=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!1}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}},He=e=>{let t=D(e);return e=>{let n=t(e);return e.key===void 0?n:O(e.key,n)}},Ue=Symbol(`assistant-ui.store.getValue`),We=e=>{let t=e[Ue];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with tapClientResource(), not a plain resource.`);return t.getState?.()},Ge=new Map;function Ke(e){let t=Ge.get(e);return t||(t=function(...t){if(!this||typeof this!=`object`)throw Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);let n=this[Ue];if(!n)throw Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let r=n[e];if(!r)throw Error(`Method "${String(e)}" is not implemented.`);if(typeof r!=`function`)throw Error(`"${String(e)}" is not a function.`);return r(...t)},Ge.set(e,t)),t}var qe=class extends Ve{outputRef;index;boundFns;cachedReceiver;constructor(e,t){super(),this.outputRef=e,this.index=t}get(e,t,n){if(t===Ue)return this.outputRef.current;if(t===Pe)return this.index;let r=Be(t,`ClientProxy`);if(r!==!1)return r;let i=this.outputRef.current[t];if(typeof i==`function`){this.cachedReceiver!==n&&(this.boundFns=new Map,this.cachedReceiver=n);let e=this.boundFns.get(t);return e||(e=Ke(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===Ue||t===Pe?!0:t in this.outputRef.current}},Je=He(e=>{let t=j(null),n=Le().length,r=N(()=>new Proxy({},new qe(t,n)),[n]),i=Re(r,()=>P(e));return t.current||=i,A(()=>{t.current=i}),{methods:r,state:i.getState?.(),key:e.key}}),Ye=e=>P(Je(e)),I=Symbol(`assistant-ui.store.proxiedAssistantState`),Xe=e=>e===`on`||e===`subscribe`||typeof e==`symbol`,Ze=e=>{class t extends Ve{get(t,n){let r=Be(n,`AssistantState`);if(r!==!1)return r;let i=n;if(!Xe(i))return We(e[i]())}ownKeys(){return Object.keys(e).filter(e=>!Xe(e))}has(t,n){return!Xe(n)&&n in e}}return new Proxy({},new t)},Qe=e=>e[I],L=r(),$e=()=>()=>{},et=e=>{let t=(()=>{throw Error(e)});return t.source=null,t.query=null,t},tt=new Proxy({},new class extends Ve{get(e,t){if(t===`subscribe`||t===`on`)return $e;if(t===I)return nt;let n=Be(t,`DefaultAssistantClient`);return n===!1?et(`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`):n}ownKeys(){return[`subscribe`,`on`,I]}has(e,t){return t===`subscribe`||t===`on`||t===I}}),nt=Ze(tt),rt=()=>new Proxy({},{get(e,t){let n=Be(t,`AssistantClient`);return n===!1?et(`The current scope does not have a "${String(t)}" property.`):n}}),it=(0,E.createContext)(tt),at=()=>(0,E.useContext)(it),R=({value:e,children:t})=>(0,L.jsx)(it.Provider,{value:e,children:t}),z=D(e=>null),ot=Symbol(`assistant-ui.transform-scopes`);function st(e,t){let n=e;if(n[ot])throw Error(`transformScopes is already attached to this resource`);n[ot]=t}function ct(e){return e[ot]}function lt(e,t){let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(e.type===z||r.has(e.type))continue;r.add(e.type);let a=ct(e.type);if(a){a(n,t),i=!0;break}}}let a={},o={};for(let[e,t]of Object.entries(n))t.type===z?o[e]=t:a[e]=t;return{rootClients:a,derivedClients:o}}var ut=e=>N(()=>e,[...Object.entries(e).flat()]),dt=(e,t)=>{let{rootClients:n,derivedClients:r}=lt(e,t);return{rootClients:ut(n),derivedClients:ut(r)}},ft=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},pt=D(()=>M(()=>{let e=new Map,t=new Set,n=new Set;return{on(n,r){let i=r;if(n===`*`)return t.add(i),()=>t.delete(i);let a=e.get(n);return a||(a=new Set,e.set(n,a)),a.add(i),()=>{a.delete(i),a.size===0&&e.delete(n)}},emit(n,r,i){let a=e.get(n);!a&&t.size===0||queueMicrotask(()=>{let e=[];if(a)for(let t of a)try{t(r,i)}catch(t){e.push(t)}if(t.size>0){let a={event:n,payload:r};for(let n of t)try{n(a,i)}catch(t){e.push(t)}}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,`Errors occurred during event emission`)}})},subscribe(e){return n.add(e),()=>n.delete(e)},notifySubscribers(){for(let e of n)try{e()}catch(e){console.error(`NotificationManager: subscriber callback error`,e)}}}},[])),mt=je(null),ht=(e,t)=>Me(mt,e,t),gt=()=>{let e=Ne(mt);if(!e)throw Error(`AssistantTapContext is not available`);return e},_t=()=>gt().clientRef,vt=()=>{let{emit:e}=gt(),t=Le();return xe((n,r)=>{e(n,r,t)})},yt=e=>N(()=>e,e),bt=D(({element:e,emit:t,clientRef:n})=>{let{methods:r,state:i}=ht({clientRef:n,emit:t},()=>Ye(e));return N(()=>({state:i,methods:r}),[r,i])}),xt=D(({element:e,notifications:t,clientRef:n,name:r})=>{let i=ke(bt({element:e,emit:t.emit,clientRef:n}));return A(()=>i.subscribe(t.notifySubscribers),[i,t]),N(()=>{let e=()=>i.getValue().methods;return Object.defineProperties(e,{source:{value:`root`,writable:!1},query:{value:{},writable:!1},name:{value:r,configurable:!0}}),e},[i,r])}),St=D(()=>N(()=>({clients:[],subscribe:void 0,on:void 0}),[])),Ct=D(({clients:e,clientRef:t})=>{let n=P(pt());A(()=>t.parent.subscribe(n.notifySubscribers),[t,n]);let r=yt(Se(()=>Object.keys(e).map(r=>O(r,xt({element:e[r],notifications:n,clientRef:t,name:r}))),[e,n,t]));return N(()=>({clients:r,subscribe:n.subscribe,on:function(e,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=ft(e);if(i!==`*`&&this[i].source===null)throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let o=n.on(a,(e,t)=>{if(i===`*`){r(e);return}let n=this[i]();n===t[Fe(n)]&&r(e)});if(i!==`*`&&t.parent[i].source===null)return o;let s=t.parent.on(e,r);return()=>{o(),s()}}}),[r,n,t])}),wt=(e,t,n)=>{if(`source`in e&&`query`in e)return e;if(n.dep===e)return n.meta;let r=e.getMeta(t.current);return n.meta=r,n.dep=e,r},Tt=D(({element:e,clientRef:t,name:n})=>{let r=xe(()=>e.props);return N(()=>{let e=()=>r().get(t.current),i={};return Object.defineProperties(e,{source:{get:()=>wt(r(),t,i).source},query:{get:()=>wt(r(),t,i).query},name:{value:n,configurable:!0}}),e},[t,n])}),Et=D(({clients:e,clientRef:t})=>yt(Se(()=>Object.keys(e).map(n=>O(n,Tt({element:e[n],clientRef:t,name:n}))),[e,t]))),Dt=D(({parent:e,clients:t})=>{let{rootClients:n,derivedClients:r}=dt(t,e),i=j({parent:e,current:null}).current;A(()=>{i.current=s});let a=P(Object.keys(n).length>0?Ct({clients:n,clientRef:i}):St()),o=P(Et({clients:r,clientRef:i})),s=N(()=>{let t=e===tt?rt():e,n=Object.create(t);Object.assign(n,{subscribe:a.subscribe??e.subscribe,on:a.on??e.on,[I]:Ze(n)});for(let e of a.clients)n[e.name]=e;for(let e of o)n[e.name]=e;return n},[e,a,o]);return i.current===null&&(i.current=s),s});function B(e,{parent:t}={parent:at()}){if(e)return ce(Dt({parent:t??tt,clients:e}));if(t===null)throw Error(`received null parent, this usage is not allowed`);return t}var V=e=>{let t=B(),n=Qe(t),r=(0,E.useSyncExternalStore)(t.subscribe,()=>e(n),()=>e(n));if(r===n)throw Error(`You tried to return the entire AssistantState. This is not supported due to technical limitations.`);return(0,E.useDebugValue)(r),r},Ot=E.createContext(!0);function kt(){throw Error(`A function wrapped in useEffectEvent can't be called during rendering.`)}var At=`use`in E.default?()=>{try{return E.use(Ot)}catch{return!1}}:()=>!1;function jt(e){let t=E.useRef(kt);return E.useInsertionEffect(()=>{t.current=e},[e]),(...e)=>{At()&&kt();let n=t.current;return n(...e)}}var Mt=(e,t)=>{let n=B(),r=jt(t),{scope:i,event:a}=ft(e);(0,E.useEffect)(()=>n.on({scope:i,event:a},r),[n,i,a,r])},Nt=e=>{let t=B(),n=(0,E.useRef)(void 0);return V(()=>(n.current===void 0&&(n.current=e(t)),n.current)),()=>(n.current=void 0,e(t))},Pt=Object.freeze({});function Ft({getItemState:e,children:t}){return It(t(Nt(e)))}var It=e=>{let t=typeof e==`object`&&e&&`type`in e?e:null,n=t?.type,r=t?.key;return(0,E.useMemo)(()=>t,[n,r,typeof t?.props==`object`&&t.props!=null&&Object.entries(t.props).length===0?Pt:t?.props])??e},Lt=He(e=>{if(e.key===void 0)throw Error(`tapClientResource: Element has no key`);return P(Je(e))});function H(e,t){let n=Se(()=>e().map(e=>Lt(e)),t),r=N(()=>Object.keys(n),[n]),i=N(()=>n.reduce((e,t,n)=>(e[t.key]=n,e),{}),[n]);return{state:N(()=>n.map(e=>e.state),[n]),get:e=>{if(`index`in e){if(e.index<0||e.index>=r.length)throw Error(`tapClientLookup: Index ${e.index} out of bounds (length: ${r.length})`);return n[e.index].methods}let t=i[e.key];if(t===void 0)throw Error(`tapClientLookup: Key "${e.key}" not found`);return n[t].methods}}}var Rt=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},zt=(e=>e?Rt(e):Rt),Bt=e=>e;function Vt(e,t=Bt){let n=E.useSyncExternalStore(e.subscribe,E.useCallback(()=>t(e.getState()),[e,t]),E.useCallback(()=>t(e.getInitialState()),[e,t]));return E.useDebugValue(n),n}var Ht=e=>{let t=zt(e),n=e=>Vt(t,e);return Object.assign(n,t),n},U=(e=>e?Ht(e):Ht),Ut=n(((e,t)=>{var n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o}));function Wt(e){let t=[`ROOT`],n=-1,r=null,i=[],a;function o(){a!==void 0&&(i.push(JSON.parse(`"${a}"`)),a=void 0)}function s(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`),o();break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),o();break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),o();break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`),o();break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`),o();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop(),a=i.pop();break}}function l(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),a=(Number(a)+1).toString();break;case`]`:n=r,t.pop(),a=i.pop();break}}for(let o=0;o<e.length;o++){let u=e[o];switch(t[t.length-1]){case`ROOT`:s(u,o,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),a=``;break;case`}`:n=o,t.pop(),a=i.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),a=``;break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`),a+=u;break;default:a+=u;break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:s(u,o,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:c(u,o);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=o,a=i.pop();break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=o}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=o,t.pop(),a=i.pop();break;default:n=o,a=`0`,s(u,o,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),a=(Number(a)+1).toString();break;case`]`:n=o,t.pop(),a=i.pop();break;default:n=o;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:s(u,o,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),t[t.length-1]===`INSIDE_STRING`?n=o:t[t.length-1]===`INSIDE_OBJECT_KEY`&&(a+=u);break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=o;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&c(u,o);break;case`}`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&c(u,o);break;case`]`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o);break;default:t.pop(),a=i.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,o+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?c(u,o):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o)):n=o;break}}}let u=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:u+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:u+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:u+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?u+=`true`.slice(t.length):`false`.startsWith(t)?u+=`false`.slice(t.length):`null`.startsWith(t)&&(u+=`null`.slice(t.length))}}return[u,i]}var Gt=i(Ut(),1),Kt=Symbol(`aui.parse-partial-json-object.meta`),qt=e=>{if(e.length===0)return{[Kt]:{state:`partial`,partialPath:[]}};try{let t=Gt.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[Kt]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=Wt(e),r=Gt.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[Kt]={state:`partial`,partialPath:n},r}catch{return}}},Jt={toResponse(e,t){return new Response(Jt.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return Jt.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Yt=function(){let e,t,n=new Promise((n,r)=>{e=n,t=r});if(!e||!t)throw Error(`Failed to create promise`);return{promise:n,resolve:e,reject:t}},Xt=()=>{let e=[],t=!1,n,r,i=i=>{i.promise||=i.reader.read().then(({done:a,value:o})=>{i.promise=void 0,a?(e.splice(e.indexOf(i),1),t&&e.length===0&&n.close()):n.enqueue(o),r?.resolve(),r=void 0}).catch(t=>{console.error(t),e.forEach(e=>{e.reader.cancel()}),e.length=0,n.error(t),r?.reject(t),r=void 0})};return{readable:new ReadableStream({start(e){n=e},pull(){return r=Yt(),e.forEach(e=>{i(e)}),r.promise},cancel(){e.forEach(e=>{e.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(n){if(t)throw Error(`Cannot add streams after the run callback has settled.`);let r={reader:n.getReader()};e.push(r),i(r)},enqueue(e){this.addStream(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}}},Zt=class{_controller;_isClosed=!1;constructor(e){this._controller=e}append(e){return this._controller.enqueue({type:`text-delta`,path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:`part-finish`,path:[]}),this._controller.close())}},Qt=e=>new ReadableStream({start(t){return e.start?.(new Zt(t))},pull(t){return e.pull?.(new Zt(t))},cancel(t){return e.cancel?.(t)}}),$t=()=>{let e;return[Qt({start(t){e=t}}),e]},en=class{_controller;_isClosed=!1;_mergeTask;constructor(e){this._controller=e;let t=Qt({start:e=>{this._argsTextController=e}}),n=!1;this._mergeTask=t.pipeTo(new WritableStream({write:e=>{switch(e.type){case`text-delta`:n=!0,this._controller.enqueue(e);break;case`part-finish`:n||this._controller.enqueue({type:`text-delta`,textDelta:`{}`,path:[]}),this._controller.enqueue({type:`tool-call-args-text-finish`,path:[]});break;default:throw Error(`Unexpected chunk type: ${e.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:`result`,path:[],...e.artifact===void 0?{}:{artifact:e.artifact},result:e.result,isError:e.isError??!1,...e.messages===void 0?{}:{messages:e.messages}})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:`part-finish`,path:[]}),this._controller.close())}},tn=e=>new ReadableStream({start(t){return e.start?.(new en(t))},pull(t){return e.pull?.(new en(t))},cancel(t){return e.cancel?.(t)}}),nn=()=>{let e;return[tn({start(t){e=t}}),e]},rn=class{value=-1;up(){return++this.value}},an=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}};TransformStream;var on=class extends TransformStream{constructor(e){let t=new rn,n=new Map;super({transform(r,i){r.type===`part-start`&&r.path.length===0&&n.set(t.up(),e.up());let[a,...o]=r.path;if(a===void 0){i.enqueue(r);return}let s=n.get(a);if(s===void 0)throw Error(`Path not found`);i.enqueue({...r,path:[s,...o]})}})}},sn=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,`readable`,{value:t,writable:!1})}},cn=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},ln=cn(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),un=class e{_state;_parentId;constructor(e){this._state=e||{merger:Xt(),contentCounter:new rn}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:`part-start`,part:e,path:[]}),this._state.merger.addStream(t.pipeThrough(new an(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new on(this._state.contentCounter)))}appendText(e){this._state.append?.kind!==`text`&&(this._state.append={kind:`text`,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){this._state.append?.kind!==`reasoning`&&(this._state.append={kind:`reasoning`,controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,t]=$t();return this._addPart({type:`text`},e),t}addReasoningPart(){let[e,t]=$t();return this._addPart({type:`reasoning`},e),t}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??ln(),[i,a]=nn();return this._addPart({type:`tool-call`,toolName:n,toolCallId:r,...this._parentId&&{parentId:this._parentId}},i),t.argsText!==void 0&&(a.argsText.append(t.argsText),a.argsText.close()),t.args!==void 0&&(a.argsText.append(JSON.stringify(t.args)),a.argsText.close()),t.response!==void 0&&a.setResponse(t.response),a}_finishedPartStream(){return new ReadableStream({start(e){e.enqueue({type:`part-finish`,path:[]}),e.close()}})}_withParentIdOption(e){return this._parentId?{...e,parentId:this._parentId}:e}appendSource(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendFile(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendData(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}enqueue(e){this._state.merger.enqueue(e),e.type===`part-start`&&e.path.length===0&&this._state.contentCounter.up()}withParentId(t){let n=new e(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function dn(e){let t=new un;return(async()=>{try{await e(t)}catch(e){throw t.__internal_isClosed||t.enqueue({type:`error`,path:[],error:String(e)}),e}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}function fn(){let{resolve:e,promise:t}=Yt(),n;return[dn(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}var pn=class extends TransformStream{constructor(e,t,n){let[r,i]=fn(),a;super({start(t){return a=r.pipeTo(new WritableStream({write(e){t.enqueue(e)},abort(e){t.error(e)},close(){t.terminate()}})).catch(e=>{t.error(e)}),e.start?.(i)},transform(t){return e.transform?.(t,i)},async flush(){await e.flush?.(i),i.close(),await a}},t,n)}},mn=D(e=>({getState:()=>e})),hn=D(e=>{let[t]=k(()=>({suggestions:(e??[]).map(e=>typeof e==`string`?{title:e,label:``,prompt:e}:{title:e.title,label:e.label,prompt:e.prompt})})),n=H(()=>t.suggestions.map((e,t)=>O(t,mn(e))),[t.suggestions]);return{getState:()=>t,suggestion:({index:e})=>n.get({index:e})}}),gn=Object.freeze({type:`complete`}),_n=D(({parts:e,getMessagePart:t})=>{let[n,r]=k(!0),i=N(()=>e[e.length-1]?.status??gn,[e]),a=N(()=>({parts:e,collapsed:n,status:i}),[e,n,i]);return{getState:()=>a,setCollapsed:r,part:t}}),vn=e=>Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)).reduce((e,t)=>{if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[n,r]of Object.entries(t.tools)){let t=e.tools?.[n];if(t&&t!==r)throw Error(`You tried to define a tool with the name ${n}, but it already exists.`);e.tools||={},e.tools[n]=r}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),e},{}),yn=class{_providers=new Set;getModelContext(){return vn(this._providers)}registerModelContextProvider(e){this._providers.add(e);let t=e.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t?.(),this.notifySubscribers()}}_subscribers=new Set;notifySubscribers(){for(let e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},bn=1,xn=D(()=>{let[e]=k(()=>({version:bn+1})),t=N(()=>new yn,[]);return{getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:e=>t.subscribe(e),register:e=>t.registerModelContextProvider(e)}}),Sn=D(({toolkit:e})=>{let[t,n]=k(()=>({tools:{}})),r=_t(),i=be((e,t)=>(n(n=>({...n,tools:{...n.tools,[e]:[...n.tools[e]??[],t]}})),()=>{n(n=>({...n,tools:{...n.tools,[e]:n.tools[e]?.filter(e=>e!==t)??[]}}))}),[]);return A(()=>{if(!e)return;let t=[];for(let[n,r]of Object.entries(e))r.render&&t.push(i(n,r.render));let n=Object.entries(e).reduce((e,[t,n])=>{let{render:r,...i}=n;return e[t]=i,e},{});return t.push(r.current.modelContext().register({getModelContext:()=>({tools:n})})),()=>{t.forEach(e=>e())}},[e,i,r]),{getState:()=>t,setToolUI:i}});st(Sn,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=xn())});var Cn=D(()=>{let[e,t]=k(()=>({renderers:{}}));return{getState:()=>e,setDataUI:be((e,n)=>(t(t=>({...t,renderers:{...t.renderers,[e]:[...t.renderers[e]??[],n]}})),()=>{t(t=>({...t,renderers:{...t.renderers,[e]:t.renderers[e]?.filter(e=>e!==n)??[]}}))}),[])}}),wn=class e{_state;constructor(e=null){this._state=e}get state(){return this._state}append(t){this._state=t.reduce((t,n)=>e.apply(t,n),this._state)}static apply(t,n){let r=n.type;switch(r){case`set`:return e.updatePath(t,n.path,()=>n.value);case`append-text`:return e.updatePath(t,n.path,e=>{if(typeof e!=`string`)throw Error(`Expected string at path [${n.path.join(`, `)}]`);return e+n.value});default:throw Error(`Invalid operation type: ${r}`)}}static updatePath(e,t,n){if(t.length===0)return n(e);if(e??={},typeof e!=`object`)throw Error(`Invalid path: [${t.join(`, `)}]`);let[r,...i]=t;if(Array.isArray(e)){let a=Number(r);if(Number.isNaN(a))throw Error(`Expected array index at [${t.join(`, `)}]`);if(a>e.length||a<0)throw Error(`Insert array index out of bounds`);let o=[...e];return o[a]=this.updatePath(o[a],i,n),o}let a={...e};return a[r]=this.updatePath(a[r],i,n),a}},Tn=class{_streamStartTime;_firstTokenTime;_totalChunks=0;_toolCallIds=new Set;constructor(){this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){this._firstTokenTime===void 0&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){let n=Date.now()-this._streamStartTime,r=e&&e>0?e:t?Math.ceil(t.length/4):void 0,i=r&&n>0?r/n*1e3:void 0;return{streamStartTime:this._streamStartTime,...this._firstTokenTime===void 0?void 0:{firstTokenTime:this._firstTokenTime-this._streamStartTime},totalStreamTime:n,...r===void 0?void 0:{tokenCount:r},...i===void 0?void 0:{tokensPerSecond:i},totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}},En=({unstable_state:e=null}={})=>({role:`assistant`,status:{type:`running`},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Dn=(e,t,n)=>{if(e.parts.length===0)throw Error(`No parts available to update.`);if(t.path.length!==1)throw Error(`Nested paths are not supported yet.`);let r=t.path[0],i=n(e.parts[r]);return{...e,parts:[...e.parts.slice(0,r),i,...e.parts.slice(r+1)],get content(){return this.parts}}},On=(e,t)=>{let n=t.part;if(n.type===`text`||n.type===`reasoning`){let t={type:n.type,text:``,status:{type:`running`},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}else if(n.type===`tool-call`){let t={type:`tool-call`,state:`partial-call`,status:{type:`running`,isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:``,args:{},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}else if(n.type===`source`){let t={type:`source`,sourceType:n.sourceType,id:n.id,url:n.url,...n.title?{title:n.title}:void 0,...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}else if(n.type===`file`){let t={type:`file`,mimeType:n.mimeType,data:n.data,...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}else if(n.type===`data`){let t={type:`data`,name:n.name,data:n.data,...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}else throw Error(`Unsupported part type: ${n.type}`)},kn=(e,t)=>Dn(e,t,e=>{if(e.type!==`tool-call`)throw Error(`Last is not a tool call`);return e.state===`partial-call`?{...e,state:`call`}:e}),An=(e,t)=>Dn(e,t,e=>({...e,status:{type:`complete`,reason:`unknown`}})),jn=(e,t)=>Dn(e,t,e=>{if(e.type===`text`||e.type===`reasoning`)return{...e,text:e.text+t.textDelta};if(e.type===`tool-call`){let n=e.argsText+t.textDelta,r=qt(n)??e.args;return{...e,argsText:n,args:r}}else throw Error(`text-delta received but part is neither text nor tool-call`)}),Mn=(e,t)=>Dn(e,t,e=>{if(e.type===`tool-call`)return{...e,state:`result`,...t.artifact===void 0?{}:{artifact:t.artifact},result:t.result,isError:t.isError??!1,...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}};throw Error(`Result chunk received but part is not a tool-call`)}),Nn=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=Pn(t);return{...e,status:n}},Pn=e=>e.finishReason===`tool-calls`?{type:`requires-action`,reason:`tool-calls`}:e.finishReason===`stop`||e.finishReason===`unknown`?{type:`complete`,reason:e.finishReason}:{type:`incomplete`,reason:e.finishReason},Fn=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),In=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),Ln=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),Rn=(e,t)=>{let n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&n[r]?.state===`started`?n[r]={...n[r],state:`finished`,finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:`finished`,messageId:ln(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},zn=(e,t)=>({...e,status:{type:`incomplete`,reason:`error`,error:t.error}}),Bn=(e,t)=>{let n=new wn(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},Vn=(e,t)=>{let n=0;for(let e of t.metadata.steps)e.state===`finished`&&e.usage&&(n+=e.usage.outputTokens);let r=``;for(let e of t.parts)(e.type===`text`||e.type===`reasoning`)&&(r+=e.text);return e.getTiming(n>0?n:void 0,r||void 0)},Hn=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Un=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n}={}){let r=e??En(),i=new Tn,a,o=t?Hn(()=>{a?.enqueue(r)}):()=>{a?.enqueue(r)};super({start(e){a=e},transform(e){i.recordChunk();let t=e.type;switch(t){case`part-start`:r=On(r,e),e.part.type===`tool-call`&&i.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:r=kn(r,e);break;case`part-finish`:r=An(r,e);break;case`text-delta`:r=jn(r,e),i.recordFirstToken();break;case`result`:r=Mn(r,e);break;case`message-finish`:r=Nn(r,e);break;case`annotations`:r=Fn(r,e);break;case`data`:r=In(r,e);break;case`step-start`:r=Ln(r,e);break;case`step-finish`:r=Rn(r,e);break;case`error`:r=zn(r,e),n?.(e.error);break;case`update-state`:r=Bn(r,e);break;default:throw Error(`Unsupported chunk type: ${t}`)}r.status.type!==`running`&&(r={...r,metadata:{...r.metadata,timing:Vn(i,r)}}),o()},flush(e){if(r.status?.type===`running`){let t=r.parts?.some(e=>e.type===`tool-call`&&(e.state===`call`||e.state===`partial-call`)&&e.result===void 0)??!1;r=Nn(r,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),r={...r,metadata:{...r.metadata,timing:Vn(i,r)}},e.enqueue(r)}}})}},Wn=class extends sn{constructor(){super(e=>{let t=new pn({transform(e,t){t.appendText(e)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Gn=class e{readable;constructor(e){this.readable=e,this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new Un))}async unstable_result(){let e;for await(let t of this)e=t;return e||{role:`assistant`,status:{type:`complete`,reason:`unknown`},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){let e=this.readable.getReader();return{async next(){let{done:t,value:n}=await e.read();return t?{done:!0,value:void 0}:{done:!1,value:n}}}}tee(){let[t,n]=this.readable.tee();return[new e(t),new e(n)]}},Kn=Symbol.for(`aui.tool-response`),qn=class e{get[Kn](){return!0}artifact;result;isError;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact),this.result=e.result,this.isError=e.isError??!1,e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&Kn in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?`<no result>`:t})}},W=e=>{let[,t]=k(e.getState);return A(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Jn=D(({runtime:e})=>{let t=W(e);return{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}),Yn=D(({runtime:e})=>{let t=W(e);return{getState:()=>t,addToolResult:t=>e.addToolResult(t),resumeToolCall:t=>e.resumeToolCall(t),__internal_getRuntime:()=>e}}),Xn=D(({runtime:e,index:t})=>P(Jn({runtime:N(()=>e.getAttachmentByIndex(t),[e,t])}))),Zn=D(({threadIdRef:e,messageIdRef:t,runtime:n})=>{let r=W(n),i=vt();A(()=>{let r=[];for(let a of[`send`,`attachmentAdd`]){let o=n.unstable_on(a,()=>{i(`composer.${a}`,{threadId:e.current,...t&&{messageId:t.current}})});r.push(o)}return r.push(n.unstable_on(`attachmentAddError`,()=>{let r=n.getState().attachments.findLast(e=>e.status.type===`incomplete`&&e.status.reason===`error`);i(`composer.attachmentAddError`,{threadId:e.current,...t&&{messageId:t.current},...r&&{attachmentId:r.id}})})),()=>{for(let e of r)e()}},[n,i,e,t]);let a=H(()=>r.attachments.map((e,t)=>O(e.id,Xn({runtime:n,index:t}))),[r.attachments,n]),o=N(()=>({text:r.text,role:r.role,attachments:a.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:r.type??`thread`,dictation:r.dictation,quote:r.quote,queue:[]}),[r,a.state]);return{getState:()=>o,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:n.beginEdit??(()=>{throw Error(`beginEdit is not supported in this runtime`)}),startDictation:n.startDictation,stopDictation:n.stopDictation,setQuote:n.setQuote,attachment:e=>`id`in e?a.get({key:e.id}):a.get(e),queueItem:()=>{throw Error(`Queue is not supported in this runtime`)},__internal_getRuntime:()=>n}}),Qn=D(({runtime:e,index:t})=>P(Jn({runtime:N(()=>e.getAttachmentByIndex(t),[e,t])}))),$n=D(({runtime:e,index:t})=>P(Yn({runtime:N(()=>e.getMessagePartByIndex(t),[e,t])}))),er=D(({runtime:e,threadIdRef:t})=>{let n=W(e),[r,i]=k(!1),[a,o]=k(!1),s=N(()=>({get current(){return e.getState().id}}),[e]),c=Ye(Zn({runtime:e.composer,threadIdRef:t,messageIdRef:s})),l=H(()=>n.content.map((t,n)=>O(`toolCallId`in t&&t.toolCallId!=null?`toolCallId-${t.toolCallId}`:`index-${n}`,$n({runtime:e,index:n}))),[n.content,e]),u=H(()=>(n.attachments??[]).map((t,n)=>O(t.id,Qn({runtime:e,index:n}))),[n.attachments,e]),d=N(()=>({...n,parts:l.state,composer:c.state,isCopied:r,isHovering:a}),[n,l.state,c.state,r,a]);return{getState:()=>d,composer:()=>c.methods,reload:t=>e.reload(t),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:t=>e.submitFeedback(t),switchToBranch:t=>e.switchToBranch(t),getCopyText:()=>e.unstable_getCopyText(),part:e=>`index`in e?l.get({index:e.index}):l.get({key:`toolCallId-${e.toolCallId}`}),attachment:e=>`id`in e?u.get({key:e.id}):u.get(e),setIsCopied:i,setIsHovering:o,__internal_getRuntime:()=>e}}),tr=D(({runtime:e,id:t,threadIdRef:n})=>P(er({runtime:N(()=>e.getMessageById(t),[e,t]),threadIdRef:n}))),nr=D(({runtime:e})=>{let t=W(e),n=vt();A(()=>{let t=[];for(let r of[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`]){let i=e.unstable_on(r,()=>{let t=e.getState()?.threadId||`unknown`;n(`thread.${r}`,{threadId:t})});t.push(i)}return()=>{for(let e of t)e()}},[e,n]);let r=N(()=>({get current(){return e.getState().threadId}}),[e]),i=Ye(Zn({runtime:e.composer,threadIdRef:r})),a=H(()=>t.messages.map(t=>O(t.id,tr({runtime:e,id:t.id,threadIdRef:r}))),[t.messages,e,r]),o=N(()=>({isEmpty:a.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,voice:t.voice,composer:i.state,messages:a.state}),[t,a,i.state]);return{getState:()=>o,composer:()=>i.methods,append:e.append,startRun:e.startRun,resumeRun:e.resumeRun,unstable_resumeRun:e.resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,connectVoice:e.connectVoice,disconnectVoice:e.disconnectVoice,getVoiceVolume:e.getVoiceVolume,subscribeVoiceVolume:e.subscribeVoiceVolume,muteVoice:e.muteVoice,unmuteVoice:e.unmuteVoice,message:e=>`id`in e?a.get({key:e.id}):a.get(e),__internal_getRuntime:()=>e}}),rr=D(({runtime:e})=>{let t=W(e),n=vt();return A(()=>{let t=[];for(let r of[`switchedTo`,`switchedAway`]){let i=e.unstable_on(r,()=>{n(`threadListItem.${r}`,{threadId:e.getState().id})});t.push(i)}return()=>{for(let e of t)e()}},[e,n]),{getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}),ir=D(({runtime:e,id:t})=>P(rr({runtime:N(()=>e.getItemById(t),[e,t])}))),ar=D(({runtime:e,__internal_assistantRuntime:t})=>{let n=W(e),r=Ye(nr({runtime:e.main})),i=H(()=>Object.keys(n.threadItems).map(t=>O(t,ir({runtime:e,id:t}))),[n.threadItems,e]),a=N(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThreadId??null,isLoading:n.isLoading,threadIds:n.threadIds,archivedThreadIds:n.archivedThreadIds,threadItems:i.state,main:r.state}),[n,i.state,r.state]);return{getState:()=>a,thread:()=>r.methods,item:e=>{if(e===`main`)return i.get({key:a.mainThreadId});if(`id`in e)return i.get({key:e.id});let{index:t,archived:n=!1}=e,r=n?a.archivedThreadIds[t]:a.threadIds[t];return i.get({key:r})},switchToThread:async t=>{await e.switchToThread(t)},switchToNewThread:async()=>{await e.switchToNewThread()},getLoadThreadsPromise:()=>e.getLoadThreadsPromise(),__internal_getAssistantRuntime:()=>t}}),or=D(e=>{let t=_t();return A(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),P(ar({runtime:e.threads,__internal_assistantRuntime:e}))}),sr=(e,t)=>{e.thread??=z({source:`threads`,query:{type:`main`},get:e=>e.threads().thread(`main`)}),e.threadListItem??=z({source:`threads`,query:{type:`main`},get:e=>e.threads().item(`main`)}),e.composer??=z({source:`thread`,query:{},get:e=>e.threads().thread(`main`).composer()}),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=xn()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=hn())},cr=({runtime:e,children:t})=>(0,L.jsx)(R,{value:B({threadListItem:rr({runtime:e})}),children:t}),lr=({index:e,children:t})=>(0,L.jsx)(R,{value:B({message:z({source:`thread`,query:{type:`index`,index:e},get:t=>t.thread().message({index:e})}),composer:z({source:`message`,query:{},get:t=>t.thread().message({index:e}).composer()})}),children:t}),ur=({index:e,children:t})=>(0,L.jsx)(R,{value:B({part:z({source:`message`,query:{type:`index`,index:e},get:t=>t.message().part({index:e})})}),children:t}),dr=D(({text:e,isRunning:t})=>{let n=N(()=>({type:`text`,text:e,status:t?{type:`running`}:{type:`complete`}}),[e,t]);return{getState:()=>n,addToolResult:()=>{throw Error(`Not supported`)},resumeToolCall:()=>{throw Error(`Not supported`)}}}),fr=({text:e,isRunning:t=!1,children:n})=>(0,L.jsx)(R,{value:B({part:dr({text:e,isRunning:t})}),children:n}),pr=({startIndex:e,endIndex:t,children:n})=>{let r=V(e=>e.message.parts).slice(e,t+1),i=B();return(0,L.jsx)(R,{value:B({chainOfThought:_n({parts:r,getMessagePart:({index:t})=>{if(t<0||t>=r.length)throw Error(`ChainOfThought part index ${t} is out of bounds (0..${r.length-1})`);return i.message().part({index:e+t})}})}),children:n})},G=Symbol(`skip-update`);function mr(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(let n of Object.keys(e)){let r=e[n],i=t[n];if(!Object.is(r,i))return!1}return!0}var K=class{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){let e=[];for(let t of this._subscribers)try{t()}catch(t){e.push(t)}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e)}}},hr=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(){for(let e of this._subscriptions)e()}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},q=class extends hr{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e;let t=e.getState();if(t===G)throw Error(`Entry not available in the store`);this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return e===G||mr(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){return this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()})}},gr=class extends hr{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==G&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw Error(`Entry not available in the store`);return this._previousState};_connect(){return this.binding.subscribe(()=>{this._previousStateDirty=!0,this.notifySubscribers()})}},_r=class extends hr{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),n=t?.subscribe(e),r=this.outerSubscribe(()=>{let r=this.binding.getState();r!==t&&(t=r,n?.(),n=r?.subscribe(e),e())});return()=>{r?.(),n?.()}}},vr=class extends hr{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.config.binding.getState(),n=t?.unstable_on(this.config.event,e),r=this.outerSubscribe(()=>{let r=this.config.binding.getState();r!==t&&(t=r,n?.(),n=r?.unstable_on(this.config.event,e))});return()=>{r?.(),n?.()}}},yr=class{_contextProvider=new yn;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},br=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+
3
+ `),J=cn(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),xr=`__optimistic__`,Sr=()=>`${xr}${J()}`,Y=Symbol(`autoStatus`),Cr=Object.freeze(Object.assign({type:`running`},{[Y]:!0})),wr=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[Y]:!0})),Tr=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[Y]:!0})),Er=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[Y]:!0})),Dr=(e,t,n,r,i)=>e&&i?Object.assign({type:`incomplete`,reason:`error`,error:i},{[Y]:!0}):e&&t?Cr:n?Er:r?Tr:wr,Or=(e,t)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t}},kr=(e,t,n)=>{let{role:r,id:i,createdAt:a,attachments:o,status:s,metadata:c}=e,l={id:i??t,createdAt:a??new Date},u=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,d=({image:e,...t})=>e.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?{...t,image:e}:(console.warn(`Invalid image data format detected`),null);if(r!==`user`&&o?.length)throw Error(`attachments are only supported for user messages`);if(r!==`assistant`&&s)throw Error(`status is only supported for assistant messages`);if(r!==`assistant`&&c?.steps)throw Error(`metadata.steps is only supported for assistant messages`);switch(r){case`assistant`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`reasoning`:return e.text.trim().length===0?null:e;case`file`:case`source`:return e;case`image`:return d(e);case`data`:return e;case`tool-call`:{let{parentId:t,messages:n,...r}=e,i={...r,toolCallId:e.toolCallId??`tool-${J()}`,...t!==void 0&&{parentId:t},...n!==void 0&&{messages:n}};return e.args?{...i,args:e.args,argsText:e.argsText??JSON.stringify(e.args)}:{...i,args:qt(e.argsText??``)??{},argsText:e.argsText??``}}default:{let n=Or(t,e.data);if(n)return n;throw Error(`Unsupported assistant message part type: ${t}`)}}}).filter(e=>!!e),status:s??n,metadata:{unstable_state:c?.unstable_state??null,unstable_annotations:c?.unstable_annotations??[],unstable_data:c?.unstable_data??[],custom:c?.custom??{},steps:c?.steps??[],...c?.timing&&{timing:c.timing},...c?.submittedFeedback&&{submittedFeedback:c.submittedFeedback}}};case`user`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`image`:case`audio`:case`file`:case`data`:return e;default:{let n=Or(t,e.data);if(n)return n;throw Error(`Unsupported user message part type: ${t}`)}}}),attachments:(o??[]).map(e=>({...e,content:e.content.map(e=>Or(e.type,e.data)??e)})),metadata:{custom:c?.custom??{}}};case`system`:if(u.length!==1||u[0].type!==`text`)throw Error(`System messages must have exactly one text message part.`);return{...l,role:r,content:u,metadata:{custom:c?.custom??{}}};default:throw Error(`Unknown message role: ${r}`)}},Ar={fromArray:e=>{let t=e.map(e=>kr(e,J(),Dr(!1,!1,!1,!1,void 0)));return{messages:t.map((e,n)=>({parentId:n>0?t[n-1].id:null,message:e}))}},fromBranchableArray:(e,t)=>{let n=Dr(!1,!1,!1,!1,void 0);return{...t?.headId===void 0?void 0:{headId:t.headId},messages:e.map(({message:e,parentId:t})=>{if(!e.id)throw Error(`ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.`);return{parentId:t,message:kr(e,e.id,n)}})}}},jr=e=>e.next?jr(e.next):`current`in e?e:null,Mr=class{func;_value=null;constructor(e){this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Nr=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){e.level=t;for(let n of e.children){let e=this.messages.get(n);e&&this.updateLevels(e,t+1)}}performOp(e,t,n){let r=t.prev??this.root,i=e??this.root;if(!(n===`relink`&&r===i)){if(n!==`link`&&(r.children=r.children.filter(e=>e!==t.current.id),r.next===t)){let e=r.children.at(-1),t=e?this.messages.get(e):null;if(t===void 0)throw Error(`MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.`);r.next=t}if(n!==`cut`){for(let n=e;n;n=n.prev)if(n.current.id===t.current.id)throw Error(`MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.`);i.children=[...i.children,t.current.id],(jr(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;let n=e?e.level+1:0;this.updateLevels(t,n)}}}_messages=new Mr(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.`);let n=Array(t.level+1);for(let e=t;e;e=e.prev)n[e.level]=e.current;return n}addOrUpdateMessage(e,t){let n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw Error(`MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.`);if(n){n.current=t,this.performOp(r,n,`relink`),this._messages.dirty();return}let i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,`link`),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.`);return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let n;do n=Sr();while(this.messages.has(n));return this.addOrUpdateMessage(e,kr(t,n,{type:`running`})),n}deleteMessage(e,t){let n=this.messages.get(e);if(!n)throw Error(`MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.`);let r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw Error(`MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.`);for(let e of n.children){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.`);this.performOp(r,t,`relink`)}this.performOp(null,n,`cut`),this.messages.delete(e),this.head===n&&(this.head=jr(r??this.root)),this._messages.dirty()}getBranches(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.`);let{children:n}=t.prev??this.root;return n}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.`);let n=t.prev??this.root;n.next=t,this.head=jr(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.`);if(t.children.length>0){let e=t=>{for(let n of t.children){let t=this.messages.get(n);t&&(e(t),this.messages.delete(n))}};e(t),t.children=[],t.next=null}this.head=t;for(let e=t;e;e=e.prev)e.prev?e.prev.next=e:this.root.next=e;this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[];for(let[,t]of this.messages)e.push({message:t.current,parentId:t.prev?.current.id??null});return{headId:this.head?.current.id??null,messages:e}}import({headId:e,messages:t}){for(let{message:e,parentId:n}of t)this.addOrUpdateMessage(n,e);this.resetHead(e??t.at(-1)?.message.id??null)}};function Pr(e,t){if(t===`*`)return!0;let n=t.split(`,`).map(e=>e.trim().toLowerCase()),r=`.${e.name.split(`.`).pop().toLowerCase()}`,i=e.type.toLowerCase();for(let e of n){if(e.startsWith(`.`)&&e===r||e.includes(`/`)&&e===i)return!0;if(e.endsWith(`/*`)){let t=e.split(`/`)[0];if(i.startsWith(`${t}/`))return!0}}return!1}var Fr=e=>e.status.type===`complete`,Ir=class extends K{isEditing=!0;get attachmentAccept(){return this.getAttachmentAdapter()?.accept??`*`}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text=``;get text(){return this._text}_role=`user`;get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){if(this._text!==e){if(this._text=e,this._dictation){this._dictationBaseText=e,this._currentInterimText=``;let{status:t,inputDisabled:n}=this._dictation;this._dictation=n?{status:t,inputDisabled:n}:{status:t}}this._notifySubscribers()}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text=``,this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();if(e){let t=this._attachments.filter(e=>!Fr(e));await Promise.all(t.map(t=>e.remove(t)))}}async reset(){if(this._attachments.length===0&&this._text===``&&this._role===`user`&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role=`user`,this._runConfig={},this._quote=void 0;let e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){let e=this._onClearAttachments();this.setAttachments([]),await e}async send(e){if(this.isEmpty)return;this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());let t=this.getAttachmentAdapter(),n=this.attachments.length>0?Promise.all(this.attachments.map(async e=>{if(Fr(e))return e;if(!t)throw Error(`Attachments are not supported`);return await t.send(e)})):[],r=this.text,i=this._quote;this._quote=void 0,this._emptyTextAndAttachments();let a={createdAt:new Date,role:this.role,content:r?[{type:`text`,text:r}]:[],attachments:await n,runConfig:this.runConfig,metadata:{custom:{...i?{quote:i}:{}}}};this.handleSend(a,e),this._notifyEventSubscribers(`send`)}cancel(){this.handleCancel()}async addAttachment(e){if(!(e instanceof File)){let t={id:e.id??J(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,t],this._notifyEventSubscribers(`attachmentAdd`),this._notifySubscribers();return}let t=this.getAttachmentAdapter();if(!t)throw Error(`Attachments are not supported`);if(!Pr({name:e.name,type:e.type},t.accept))throw Error(`File type ${e.type||`unknown`} is not accepted. Accepted types: ${t.accept}`);let n=e=>{let t=this._attachments.findIndex(t=>t.id===e.id);t===-1?this._attachments=[...this._attachments,e]:this._attachments=[...this._attachments.slice(0,t),e,...this._attachments.slice(t+1)],this._notifySubscribers()},r;try{let i=t.add({file:e});if(Symbol.asyncIterator in i)for await(let e of i)r=e,n(e);else r=await i,n(r)}catch(e){r&&n({...r,status:{type:`incomplete`,reason:`error`}});try{this._notifyEventSubscribers(`attachmentAddError`)}catch{}throw e}let i=r?.status.type===`incomplete`&&r.status.reason===`error`;this._notifyEventSubscribers(i?`attachmentAddError`:`attachmentAdd`)}async removeAttachment(e){let t=this._attachments.findIndex(t=>t.id===e);if(t===-1)throw Error(`Attachment not found`);let n=this._attachments[t];if(!Fr(n)){let e=this.getAttachmentAdapter();if(!e)throw Error(`Attachments are not supported`);await e.remove(n)}this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText=``;_currentInterimText=``;_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error(`Dictation adapter not configured`);if(this._dictationSession){for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}let t=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText=``;let n=e.listen();this._dictationSession=n;let r=++this._dictationSessionIdCounter;this._activeDictationSessionId=r,this._dictation={status:n.status,inputDisabled:t},this._notifySubscribers();let i=n.onSpeech(e=>{if(!this._isActiveSession(r,n))return;let t=e.isFinal!==!1,i=this._dictationBaseText&&!this._dictationBaseText.endsWith(` `)&&e.transcript?` `:``;if(t){if(this._dictationBaseText=this._dictationBaseText+i+e.transcript,this._currentInterimText=``,this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=i+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&={...this._dictation,transcript:e.transcript},this._notifySubscribers()});this._dictationUnsubscribes.push(i);let a=n.onSpeechStart(()=>{this._isActiveSession(r,n)&&(this._dictation={status:{type:`running`},inputDisabled:t,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(a);let o=n.onSpeechEnd(()=>{this._cleanupDictation({sessionId:r})});this._dictationUnsubscribes.push(o);let s=setInterval(()=>{this._isActiveSession(r,n)&&n.status.type===`ended`&&this._cleanupDictation({sessionId:r})},100);this._dictationUnsubscribes.push(()=>clearInterval(s))}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;e.stop().finally(()=>{this._cleanupDictation({sessionId:t})})}_cleanupDictation(e){if(!(e?.sessionId!==void 0&&e.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)){this._isCleaningDictation=!0;try{for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText=``,this._currentInterimText=``,this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_eventSubscribers=new Map;_notifyEventSubscribers(e){let t=this._eventSubscribers.get(e);if(t)for(let e of t)e()}unstable_on(e,t){let n=this._eventSubscribers.get(e);return n?n.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{let n=this._eventSubscribers.get(e);n&&n.delete(t)}}},Lr=class extends Ir{runtime;_canCancel=!1;get canCancel(){return this._canCancel}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}constructor(e){super(),this.runtime=e,this.connect()}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e,t){this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun})}async handleCancel(){this.runtime.cancelRun()}},Rr=class extends Ir{runtime;endEditCallback;get canCancel(){return!0}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_nonTextParts;_previousText;_parentId;_sourceId;constructor(e,t,{parentId:n,message:r}){super(),this.runtime=e,this.endEditCallback=t,this._parentId=n,this._sourceId=r.id,this._previousText=br(r),this.setText(this._previousText),this.setRole(r.role),this.setAttachments(r.attachments??[]),this._nonTextParts=r.content.filter(e=>e.type!==`text`),this.setRunConfig({...e.composer.runConfig})}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(e,t){(br(e)!==this._previousText||t?.startRun)&&this.runtime.append({...e,content:[...e.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId,startRun:t?.startRun}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},zr=class{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new Nr;_voiceMessages=[];_voiceGeneration=0;_cachedMergedMessages=null;_cachedVoiceGeneration=-1;_cachedMergedBase=null;_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();let e=this._getBaseMessages();return(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e)&&(this._cachedMergedMessages=[...e,...this._voiceMessages],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e),this._cachedMergedMessages}get state(){let e;for(let t of this.messages)t.role===`assistant`&&(e=t);return e?.metadata.unstable_state??null}composer=new Lr(this);constructor(e){this._contextProvider=e}getModelContext(){return this._contextProvider.getModelContext()}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw Error(`Edit already in progress`);this._editComposers.set(e,new Rr(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{let t=this.repository.getMessages(),n=this._voiceMessages.findIndex(t=>t.id===e);return n===-1?void 0:{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(let e of this._subscriptions)e()}_notifyEventSubscribers(e){let t=this._eventSubscribers.get(e);if(t)for(let e of t)e()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){let n=this.adapters?.feedback;if(!n)throw Error(`Feedback adapter not configured`);let{message:r,parentId:i}=this.repository.getMessage(e);if(n.submit({message:r,type:t}),r.role===`assistant`){let e={...r,metadata:{...r.metadata,submittedFeedback:{type:t}}};this.repository.addOrUpdateMessage(i,e)}this._notifySubscribers()}_stopSpeaking;speech;speak(e){let t=this.adapters?.speech;if(!t)throw Error(`Speech adapter not configured`);let{message:n}=this.repository.getMessage(e);this._stopSpeaking?.();let r=t.speak(br(n)),i=r.subscribe(()=>{r.status.type===`ended`?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:r.status},this._notifySubscribers()});this.speech={messageId:e,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),i(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw Error(`No message is being spoken`);this._stopSpeaking(),this._notifySubscribers()}_voiceSession;_voiceUnsubs=[];voice;_voiceVolume=0;_voiceVolumeSubscribers=new Set;getVoiceVolume=()=>this._voiceVolume;subscribeVoiceVolume=e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e));connectVoice(){let e=this.adapters?.voice;if(!e)throw Error(`Voice adapter not configured`);this.disconnectVoice();let t=e.connect({});this._voiceSession=t;let n=[],r=`listening`;this.voice={status:t.status,isMuted:t.isMuted,mode:r},this._voiceVolume=0,this._notifySubscribers(),n.push(t.onStatusChange(e=>{e.type===`ended`?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0):this.voice={status:e,isMuted:t.isMuted,mode:r},this._notifySubscribers()})),n.push(t.onModeChange(e=>{r=e,this.voice&&(this.voice={...this.voice,mode:e},this._notifySubscribers())})),n.push(t.onVolumeChange(e=>{this._voiceVolume=e;for(let e of this._voiceVolumeSubscribers)e()})),n.push(t.onTranscript(e=>{this._handleVoiceTranscript(e)})),this._voiceUnsubs=n}_currentAssistantMsg=null;_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role===`user`)this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal&&(this._voiceMessages.push({id:J(),role:`user`,content:[{type:`text`,text:e.text}],metadata:{custom:{}},createdAt:new Date,status:{type:`complete`,reason:`unknown`},attachments:[]}),this._markVoiceMessagesDirty(),this._notifySubscribers());else{if(!this._currentAssistantMsg)this._currentAssistantMsg={id:J(),role:`assistant`,content:[{type:`text`,text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},status:{type:`running`},createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{let t=this._voiceMessages.indexOf(this._currentAssistantMsg);if(t===-1)return;let n={...this._currentAssistantMsg,content:[{type:`text`,text:e.text}],...e.isFinal?{status:{type:`complete`,reason:`stop`}}:{}};this._voiceMessages[t]=n,this._currentAssistantMsg=n}e.isFinal&&(this._currentAssistantMsg=null),this._markVoiceMessagesDirty(),this._notifySubscribers()}}_finishVoiceAssistantMessage(){let e=this._voiceMessages.at(-1);if(e?.role===`assistant`&&e.status.type===`running`){let t=this._voiceMessages.length-1;this._voiceMessages[t]={...e,status:{type:`complete`,reason:`stop`}},this._markVoiceMessagesDirty(),this._notifySubscribers()}}disconnectVoice(){this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null;for(let e of this._voiceUnsubs)e();this._voiceUnsubs=[],this._voiceSession?.disconnect(),this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;for(let e of this._voiceVolumeSubscribers)e();this._voiceMessages=[],this._markVoiceMessagesDirty(),this._notifySubscribers()}muteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers(`initialize`))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Ar.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){if(e===`modelContextUpdate`)return this._contextProvider.subscribe?.(t)??(()=>{});let n=this._eventSubscribers.get(e);return n?n.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},Br=class{_core;_threadListBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){let e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){let e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,o=i.id;n===a&&r===o||(n=a,r=o,!(e===`switchedTo`&&!a)&&(e===`switchedAway`&&a||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}},Vr=Symbol(`innerMessage`),Hr=class{_core;get path(){return this._core.path}constructor(e){this._core=e,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Ur=class extends Hr{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error(`Composer is not available`);return e.removeAttachment(this.getState().id)}},Wr=class extends Ur{get source(){return`thread-composer`}},Gr=class extends Ur{get source(){return`edit-composer`}},Kr=class extends Hr{get source(){return`message`}constructor(e){super(e)}remove(){throw Error(`Message attachments cannot be removed`)}},qr=Object.freeze([]),Jr=Object.freeze({}),Yr=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??qr,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??Jr,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,value:e?.text??``}),Xr=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??qr,runConfig:e?.runConfig??Jr,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),Zr=class{_core;get path(){return this._core.path}constructor(e){this._core=e}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.clearAttachments()}send(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.send(e)}cancel(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.cancel()}setRole(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new vr({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Qr=class extends Zr{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new gr({path:e.path,getState:()=>Yr(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new Wr(new q({path:{...this.path,attachmentSource:`thread-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`thread-composer`}:G},subscribe:e=>this._core.subscribe(e)}),this._core)}},$r=class extends Zr{_beginEdit;get path(){return this._core.path}get type(){return`edit`}_getState;constructor(e,t){let n=new gr({path:e.path,getState:()=>Xr(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>n.subscribe(e)}),this._beginEdit=t,this._getState=n.getState.bind(n),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new Gr(new q({path:{...this.path,attachmentSource:`edit-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`edit-composer`}:G},subscribe:e=>this._core.subscribe(e)}),this._core)}},ei=class{contentBinding;messageApi;threadApi;get path(){return this.contentBinding.path}constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to add tool result to non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=t.toolName,i=t.toolCallId,a=qn.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:a.result,artifact:a.artifact,isError:a.isError})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to resume tool call on non-tool message part`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},ti=Object.freeze({type:`complete`}),ni=(e,t,n)=>{if(e.role!==`assistant`)return ti;if(n.type===`tool-call`)return n.result?ti:e.status;let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?ti:r?e.status:ti},ri=(e,t)=>{let n=e.content[t];if(!n)return G;let r=ni(e,t,n);return Object.freeze({...n,[Vr]:n[Vr],status:r})},ii=class{_core;_threadBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new $r(new _r({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:`edit`},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}reload(e={}){let t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:i=r.runConfig}=e,a=this._core.getState();if(a.role!==`assistant`)throw Error(`Can only reload assistant messages`);this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error(`Message is not being spoken`)}submitFeedback({type:e}){let t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){let n=this._core.getState();if(t&&e)throw Error(`May not specify both branchId and position`);if(!t&&!e)throw Error(`Must specify either branchId or position`);let r=this._threadBinding.getState().getBranches(n.id),i=t;if(e===`previous`?i=r[n.branchNumber-2]:e===`next`&&(i=r[n.branchNumber]),!i)throw Error(`Branch not found`);this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return br(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new ei(new q({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>ri(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new ei(new q({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:`toolCallId`,toolCallId:e}},getState:()=>{let t=this._core.getState(),n=t.content.findIndex(t=>t.type===`tool-call`&&t.toolCallId===e);return n===-1?G:ri(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new Kr(new q({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:`message`,attachmentSelector:{type:`index`,index:e}},getState:()=>{let t=this.getState().attachments?.[e];return t?{...t,source:`message`}:G},subscribe:e=>this._core.subscribe(e)}))}},ai=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),oi=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),si=(e,t)=>typeof t==`string`?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:`user`,content:[{type:`text`,text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??`user`,content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},ci=(e,t)=>{let n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:n?.role===`assistant`?n.status.type===`running`:!1,messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice})},li=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(e,t){let n=new q({path:e.path,getState:()=>ci(e.getState(),t.getState()),subscribe:n=>{let r=e.subscribe(n),i=t.subscribe(n);return()=>{r(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new Qr(new _r({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`thread`},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.resumeRun=this.resumeRun.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(si(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){let t=e===null||typeof e==`string`?{parentId:e}:e;return this._threadBinding.getState().startRun(oi(t))}resumeRun(e){return this._threadBinding.getState().resumeRun(ai(e))}unstable_resumeRun(e){return this.resumeRun(e)}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw Error(`Message index must be >= 0`);return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:`index`,index:e}},()=>{let t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:`messageId`,messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new ii(new q({path:e,getState:()=>{let{message:e,parentId:n,index:r}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||n===void 0||r===void 0)return G;let o=this._threadBinding.getState().getBranches(e.id),s=e.metadata.submittedFeedback;return{...e,[Vr]:e[Vr],index:r,isLast:i.at(-1)?.id===e.id,parentId:n,branchNumber:o.indexOf(e.id)+1,branchCount:o.length,speech:a?.messageId===e.id?a:void 0,submittedFeedback:s}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new vr({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},ui=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadItems}),di=(e,t)=>{if(t===void 0)return G;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:G},fi=class{_core;_runtimeFactory;_getState;constructor(e,t=li){this._core=e,this._runtimeFactory=t;let n=new gr({path:{},getState:()=>ui(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new Br(new q({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>di(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new _r({path:{ref:`threads.main`,threadSelector:{type:`main`}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new _r({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(e){return new Br(new q({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>di(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new Br(new q({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>di(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new Br(new q({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>di(this._core,e),subscribe:e=>this._core.subscribe(e)}),this._core)}},pi=class{_core;threads;get threadList(){return this.threads}_thread;constructor(e){this._core=e,this.threads=new fi(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(Ar.fromArray(e??[]))}},mi=D(e=>P(or(e)));st(mi,(e,t)=>{sr(e,t),!e.tools&&t.tools.source===null&&(e.tools=Sn({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=Cn())});var hi=(0,E.createContext)(null),gi=({adapters:e,children:t})=>{let n=(0,E.useContext)(hi);return(0,L.jsx)(hi.Provider,{value:{...n,...e},children:t})},_i=()=>(0,E.useContext)(hi);function vi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yi(e,t=0){return t>100?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(e=>yi(e,t+1)):vi(e)?Object.entries(e).every(([e,n])=>typeof e==`string`&&yi(n,t+1)):!1}var bi=(e,t)=>t===void 0?e.status?.type===`requires-action`&&e.status.reason===`tool-calls`&&e.content.every(e=>e.type!==`tool-call`||!!e.result):e.status?.type===`requires-action`&&e.status.reason===`tool-calls`&&e.content.every(e=>e.type!==`tool-call`||!!e.result||!t.includes(e.toolName)),xi=class extends Error{name=`AbortError`;detach;constructor(e,t){super(t),this.detach=e}},Si=class extends zr{capabilities={switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1};abortController=null;isDisabled=!1;_isLoading=!1;get isLoading(){return this._isLoading}_suggestions=[];_suggestionsController=null;get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}constructor(e,t){super(e),this.__internal_setOptions(t)}_options;_lastRunConfig={};_getThreadId;__internal_setGetThreadId(e){this._getThreadId=e}_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}get extras(){}__internal_setOptions(e){if(this._options===e)return;this._options=e;let t=!1,n=e.adapters?.speech!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,t=!0);let r=e.adapters?.dictation!==void 0;this.capabilities.dictation!==r&&(this.capabilities.dictation=r,t=!0);let i=e.adapters?.voice!==void 0;this.capabilities.voice!==i&&(this.capabilities.voice=i,t=!0);let a=e.adapters?.attachments!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,t=!0);let o=e.adapters?.feedback!==void 0;this.capabilities.feedback!==o&&(this.capabilities.feedback=o,t=!0),t&&this._notifySubscribers()}_loadPromise;__internal_load(){if(this._loadPromise)return this._loadPromise;let e=this.adapters.history?.load()??Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=e.then(e=>{if(!e)return;this.repository.import(e),e.messages.length>0&&this.ensureInitialized(),this._notifySubscribers();let t=this.adapters.history?.resume?.bind(this.adapters.history);e.unstable_resume&&t&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},t).catch(()=>{})}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}async append(e){this.ensureInitialized();let t=this._getInitializePromise?.();t&&await t;let n=kr(e,J(),{type:`complete`,reason:`unknown`});this.repository.addOrUpdateMessage(e.parentId,n),this._options.adapters.history?.append({parentId:e.parentId,message:n,...e.runConfig!==void 0&&{runConfig:e.runConfig}}),e.startRun??e.role===`user`?await this.startRun({parentId:n.id,sourceId:e.sourceId,runConfig:e.runConfig??{}}):(this.repository.resetHead(n.id),this._notifySubscribers())}resumeRun({stream:e,...t}){if(!e)throw Error(`You must pass a stream parameter to resume runs.`);return this.startRun(t,e)}exportExternalState(){throw Error(`Runtime does not support exporting external states.`)}importExternalState(){throw Error(`Runtime does not support importing external states.`)}unstable_loadExternalState(){throw Error(`Runtime does not support importing external states.`)}async startRun({parentId:e,runConfig:t},n){this.ensureInitialized();let r={id:J(),role:`assistant`,status:{type:`running`},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers(`runStart`);try{this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do r=await this.performRoundtrip(e,r,t,n),n=void 0;while(bi(r,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers(`runEnd`)}this._suggestionsController=new AbortController;let i=this._suggestionsController.signal;if(this.adapters.suggestion&&r.status?.type!==`requires-action`){let e=this.adapters.suggestion?.generate({messages:this.messages});if(Symbol.asyncIterator in e)for await(let t of e){if(i.aborted)break;this._suggestions=t,this._notifySubscribers()}else{let t=await e;if(i.aborted)return;this._suggestions=t,this._notifySubscribers()}}}async performRoundtrip(e,t,n,r){let i=e?this.repository.getMessages(e):[];this.abortController?.abort(),this.abortController=new AbortController;let a=t.content,o=t.metadata?.unstable_annotations,s=t.metadata?.unstable_data,c=t.metadata?.steps,l=t.metadata?.custom,u=n=>{let r=n.metadata?.steps,i=r?[...c??[],...r]:void 0,u=n.metadata?.unstable_annotations,d=n.metadata?.unstable_data,f=u?[...o??[],...u]:void 0,p=d?[...s??[],...d]:void 0;t={...t,...n.content?{content:[...a,...n.content??[]]}:void 0,status:n.status??t.status,...n.metadata?{metadata:{...t.metadata,...n.metadata.unstable_state?{unstable_state:n.metadata.unstable_state}:void 0,...f?{unstable_annotations:f}:void 0,...p?{unstable_data:p}:void 0,...i?{steps:i}:void 0,...n.metadata?.timing?{timing:n.metadata.timing}:void 0,...n.metadata?.custom?{custom:{...l??{},...n.metadata.custom}}:void 0}}:void 0},this.repository.addOrUpdateMessage(e,t),this._notifySubscribers()},d=this._options.maxSteps??2;if((t.metadata?.steps?.length??0)>=d)return u({status:{type:`incomplete`,reason:`tool-calls`}}),t;u({status:{type:`running`}}),this.repository.resetHead(t.id),this._notifySubscribers();try{this._lastRunConfig=n??{};let a=this.getModelContext();r??=this.adapters.chatModel.run.bind(this.adapters.chatModel);let o=this.abortController.signal,s=this._getThreadId?.(),c=r({messages:i,runConfig:this._lastRunConfig,abortSignal:o,context:a,config:a,unstable_assistantMessageId:t.id,unstable_threadId:s,unstable_parentId:e,unstable_getMessage(){return t}});if(Symbol.asyncIterator in c)for await(let e of c){if(o.aborted){u({status:{type:`incomplete`,reason:`cancelled`}});break}u(e)}else u(await c);t.status.type===`running`&&u({status:{type:`complete`,reason:`unknown`}})}catch(e){if(e instanceof xi)u({status:{type:`incomplete`,reason:`cancelled`}});else if(e instanceof Error&&e.name===`AbortError`)u({status:{type:`incomplete`,reason:`cancelled`}});else throw u({status:{type:`incomplete`,reason:`error`,error:e instanceof Error?e.message:`[${typeof e}] ${new String(e).toString()}`}}),e}finally{this.abortController=null,(t.status.type===`complete`||t.status.type===`incomplete`)&&await this._options.adapters.history?.append({parentId:e,message:t,runConfig:this._lastRunConfig})}return t}detach(){let e=new xi(!0);this.abortController?.abort(e),this.abortController=null}cancelRun(){let e=new xi(!1);this.abortController?.abort(e),this.abortController=null}addToolResult({messageId:e,toolCallId:t,result:n,isError:r,artifact:i}){let a=this.repository.getMessage(e),{parentId:o}=a,{message:s}=a;if(s.role!==`assistant`)throw Error(`Tried to add tool result to non-assistant message`);let c=!1,l=!1,u=s.content.map(e=>e.type!==`tool-call`||e.toolCallId!==t?e:(l=!0,e.result||(c=!0),{...e,result:n,artifact:i,isError:r}));if(!l)throw Error(`Tried to add tool result to non-existing tool call`);s={...s,content:u},this.repository.addOrUpdateMessage(o,s),c&&bi(s,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,s,this._lastRunConfig).catch(()=>{})}resumeToolCall(e){throw Error(`Local runtime does not support resuming tool calls.`)}},Ci=Object.freeze([]),wi=`__DEFAULT_ID__`,Ti=Object.freeze({[wi]:{id:wi,remoteId:void 0,externalId:void 0,status:`regular`,title:void 0}}),Ei=class extends K{_mainThread;constructor(e){super(),this._mainThread=e()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){}get threadIds(){return Ci}get archivedThreadIds(){return Ci}get mainThreadId(){return wi}get threadItems(){return Ti}getThreadRuntimeCore(){throw Error(`Method not implemented.`)}getLoadThreadsPromise(){return Promise.resolve()}getItemById(e){if(e===this.mainThreadId)return{status:`regular`,id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw Error(`Method not implemented`)}async switchToThread(){throw Error(`Method not implemented.`)}switchToNewThread(){throw Error(`Method not implemented.`)}rename(){throw Error(`Method not implemented.`)}archive(){throw Error(`Method not implemented.`)}detach(){throw Error(`Method not implemented.`)}unarchive(){throw Error(`Method not implemented.`)}delete(){throw Error(`Method not implemented.`)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw Error(`Method not implemented.`)}},Di=class extends yr{threads;Provider=void 0;_options;constructor(e,t){super(),this._options=e,this.threads=new Ei(()=>new Si(this._contextProvider,this._options)),t&&this.threads.getMainThreadRuntimeCore().import(Ar.fromArray(t))}},Oi=(e,t,n)=>n.reduce((e,n)=>n?.(e,t)??e,e),ki=class extends K{_pendingTransforms=[];_completedOptimistics=[];_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){this._cachedValue=this._pendingTransforms.reduce((e,t)=>Oi(e,t.task,[t.loading,t.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(e){this._baseValue=e,this._updateState()}async optimisticUpdate(e){let t=e.execute(),n={...e,task:t};try{this._pendingTransforms.push(n),this._updateState();let r=await t;this._baseValue=Oi(this._baseValue,r,[e.optimistic,e.then]);for(let e of this._completedOptimistics)this._baseValue=e(this._baseValue);return e.optimistic&&this._completedOptimistics.push(e.optimistic),r}finally{let e=this._pendingTransforms.indexOf(n);e>-1&&this._pendingTransforms.splice(e,1),this._pendingTransforms.length===0&&(this._completedOptimistics.length=0),this._updateState()}}},X=Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Ai={getMessageById(){},getBranches(){return[]},switchToBranch(){throw X},append(){throw X},startRun(){throw X},resumeRun(){throw X},cancelRun(){throw X},addToolResult(){throw X},resumeToolCall(){throw X},speak(){throw X},stopSpeaking(){throw X},connectVoice(){throw X},disconnectVoice(){throw X},getVoiceVolume:()=>0,subscribeVoiceVolume:()=>()=>{},muteVoice(){throw X},unmuteVoice(){throw X},submitFeedback(){throw X},getModelContext(){return{}},exportExternalState(){throw X},importExternalState(){throw X},unstable_loadExternalState(){throw X},composer:{attachments:[],attachmentAccept:`*`,async addAttachment(){throw X},async removeAttachment(){throw X},isEditing:!0,canCancel:!1,isEmpty:!0,text:``,setText(){throw X},role:`user`,setRole(){throw X},runConfig:{},setRunConfig(){throw X},async reset(){},async clearAttachments(){},send(){throw X},cancel(){},dictation:void 0,startDictation(){throw X},stopDictation(){},quote:void 0,setQuote(){throw X},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw X},speech:void 0,voice:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1},isDisabled:!1,isLoading:!0,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw X},export(){return{messages:[]}},reset(){throw X},unstable_on(){return()=>{}}};function ji(e){return e}var Mi=(e,t)=>{let n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},Ni=(e,t,n)=>{let r=Mi(e,t);if(!r)return e;let{id:i,remoteId:a,status:o}=r;if(o===n)return e;let s={...e};switch(o){case`new`:s.newThreadId=void 0;break;case`regular`:s.threadIds=s.threadIds.filter(e=>e!==i);break;case`archived`:s.archivedThreadIds=s.archivedThreadIds.filter(e=>e!==i);break;default:throw Error(`Unsupported state: ${o}`)}switch(n){case`regular`:s.threadIds=[i,...s.threadIds];break;case`archived`:s.archivedThreadIds=[i,...s.archivedThreadIds];break;case`deleted`:s.threadData=Object.fromEntries(Object.entries(s.threadData).filter(([e])=>e!==i)),s.threadIdMap=Object.fromEntries(Object.entries(s.threadIdMap).filter(([e])=>e!==i&&e!==a));break;default:throw Error(`Unsupported state: ${n}`)}return n!==`deleted`&&(s.threadData={...s.threadData,[i]:{...r,status:n}}),s},Pi=class extends K{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=U(()=>({}));parent;constructor(e,t){super(),this.parent=t,this.useRuntimeHook=U(()=>({useRuntime:e}))}startThreadRuntime(e){return this.instances.has(e)||(this.instances.set(e,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((t,n)=>{let r=()=>{let r=this.instances.get(e);if(!r)i(),n(Error(`Thread was deleted before runtime was started`));else if(r.runtime)i(),t(r.runtime);else return},i=this.subscribe(r);r()})}getThreadRuntimeCore(e){let t=this.instances.get(e);if(t)return t.runtime}stopThreadRuntime(e){this.instances.delete(e),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(e){this.useRuntimeHook.getState().useRuntime!==e&&this.useRuntimeHook.setState({useRuntime:e},!0)}_InnerActiveThreadProvider=({threadId:e})=>{let{useRuntime:t}=this.useRuntimeHook(),n=t(),r=n.thread.__internal_threadBinding,i=(0,E.useCallback)(()=>{let t=this.instances.get(e);if(!t)throw Error(`Thread not found. This is a bug in assistant-ui.`);t.runtime=r.getState(),this._notifySubscribers()},[e,r]),a=(0,E.useRef)(!1);a.current||i(),(0,E.useEffect)(()=>(a.current=!0,i(),r.outerSubscribe(i)),[r,i]);let o=B(),s=(0,E.useRef)(void 0);return(0,E.useEffect)(()=>{let e=r.getState(),t=e.__internal_setGetInitializePromise;typeof t==`function`&&t.call(e,()=>s.current)},[r]),(0,E.useEffect)(()=>n.threads.main.unstable_on(`initialize`,()=>{if(o.threadListItem().getState().status===`new`){s.current=o.threadListItem().initialize();let e=n.thread.unstable_on(`runEnd`,()=>{e(),o.threadListItem().generateTitle()})}}),[n,o]),null};_OuterActiveThreadProvider=(0,E.memo)(({threadId:e,provider:t})=>(0,L.jsx)(cr,{runtime:(0,E.useMemo)(()=>new fi(this.parent).getItemById(e),[e]),children:(0,L.jsx)(t,{children:(0,L.jsx)(this._InnerActiveThreadProvider,{threadId:e})})}));__internal_RenderThreadRuntimes=({provider:e})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(t=>(0,L.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},t)))},Fi=class extends K{_options;_hookManager;_loadThreadsPromise;_mainThreadId;_state=new ki({isLoading:!0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:e=>({...e,isLoading:!0}),then:(e,t)=>{let n=[],r=[],i={},a={};for(let e of t.threads){switch(e.status){case`regular`:n.push(e.remoteId);break;case`archived`:r.push(e.remoteId);break;default:{let t=e.status;throw Error(`Unsupported state: ${t}`)}}let t=ji(e.remoteId);i[e.remoteId]=t,a[t]={id:e.remoteId,remoteId:e.remoteId,externalId:e.externalId,status:e.status,title:e.title,initializeTask:Promise.resolve({remoteId:e.remoteId,externalId:e.externalId})}}return{...e,isLoading:!1,threadIds:n,archivedThreadIds:r,threadIdMap:{...e.threadIdMap,...i},threadData:{...e.threadData,...a}}}}).catch(()=>{this._loadThreadsPromise=void 0,this._state.update({...this._state.baseValue,isLoading:!1})}).then(()=>{}),this._loadThreadsPromise}contextProvider;constructor(e,t){super(),this.contextProvider=t,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Pi(e.runtimeHook,this),this.useProvider=U(()=>({Provider:e.adapter.unstable_Provider??E.Fragment})),this.__internal_setOptions(e),this.switchToNewThread()}_initialThreadLoaded=!1;useProvider;__internal_setOptions(e){if(this._options===e)return;this._options=e;let t=e.adapter.unstable_Provider??E.Fragment;t!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:t},!0),this._hookManager.setRuntimeHook(e.runtimeHook)}__internal_load(){this.getLoadThreadsPromise();let e=this._options.threadId??this._options.initialThreadId;!this._initialThreadLoaded&&e&&(this._initialThreadLoaded=!0,this.switchToThread(e).catch(()=>{}))}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._hookManager.getThreadRuntimeCore(this._mainThreadId)||Ai}getThreadRuntimeCore(e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);let n=this._hookManager.getThreadRuntimeCore(t.id);if(!n)throw Error(`Thread not found`);return n}getItemById(e){return Mi(this._state.value,e)}async switchToThread(e){let t=this.getItemById(e);if(!t){let n=await this._options.adapter.fetch(e),r=this._state.value,i=ji(n.remoteId),a={...r.threadData,[i]:{id:i,initializeTask:Promise.resolve({remoteId:n.remoteId,externalId:n.externalId}),remoteId:n.remoteId,externalId:n.externalId,status:n.status,title:n.title}},o={...r.threadIdMap,[n.remoteId]:i},s=n.status===`regular`?[...r.threadIds,n.remoteId]:r.threadIds,c=n.status===`archived`?[...r.archivedThreadIds,n.remoteId]:r.archivedThreadIds;this._state.update({...r,threadIds:s,archivedThreadIds:c,threadIdMap:o,threadData:a}),t=this.getItemById(e)}if(!t)throw Error(`Thread not found`);if(this._mainThreadId===t.id)return;let n=this._hookManager.startThreadRuntime(t.id);this.mainThreadId===void 0?n.then(()=>this._notifySubscribers()):await n,t.status===`archived`&&await this.unarchive(t.id),this._mainThreadId=t.id,this._notifySubscribers()}async switchToNewThread(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)await this._state.waitForUpdate();let e=this._state.value,t=this._state.value.newThreadId;if(t===void 0){do t=`__LOCALID_${J()}`;while(e.threadIdMap[t]);let n=ji(t);this._state.update({...e,newThreadId:t,threadIdMap:{...e.threadIdMap,[t]:n},threadData:{...e.threadData,[n]:{status:`new`,id:t,remoteId:void 0,externalId:void 0,title:void 0}}})}return this.switchToThread(t)}initialize=async e=>{if(this._state.value.newThreadId!==e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status===`new`)throw Error(`Unexpected new state`);return t.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(e),optimistic:t=>Ni(t,e,`regular`),loading:(t,n)=>{let r=ji(e);return{...t,threadData:{...t.threadData,[r]:{...t.threadData[r],initializeTask:n}}}},then:(t,{remoteId:n,externalId:r})=>{let i=Mi(t,e);if(!i)return t;let a=ji(e);return{...t,threadIdMap:{...t.threadIdMap,[n]:a},threadData:{...t.threadData,[a]:{...i,initializeTask:Promise.resolve({remoteId:n,externalId:r}),remoteId:n,externalId:r}}}}})};generateTitle=async e=>{let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status===`new`)throw Error(`Thread is not yet initialized`);let{remoteId:n}=await t.initializeTask,r=this._hookManager.getThreadRuntimeCore(t.id);if(!r)return;let i=r.messages,a=await this._options.adapter.generateTitle(n,i),o=Gn.fromAssistantStream(a);for await(let e of o){let n=e.parts.filter(e=>e.type===`text`)[0]?.text,r=this._state.baseValue,i=Mi(r,t.id);i&&this._state.update({...r,threadData:{...r.threadData,[i.id]:{...i,title:n}}})}};rename(e,t){let n=this.getItemById(e);if(!n)throw Error(`Thread not found`);if(n.status===`new`)throw Error(`Thread is not yet initialized`);return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await n.initializeTask;return this._options.adapter.rename(e,t)},optimistic:n=>{let r=Mi(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,title:t}}}:n}})}async _ensureThreadIsNotMain(e){if(e===this.newThreadId)throw Error(`Cannot ensure new thread is not main`);e===this._mainThreadId&&await this.switchToNewThread()}async archive(e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status!==`regular`)throw Error(`Thread is not yet initialized or already archived`);return await this._ensureThreadIsNotMain(t.id),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await t.initializeTask;return this._options.adapter.archive(e)},optimistic:e=>Ni(e,t.id,`archived`)})}unarchive(e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status!==`archived`)throw Error(`Thread is not archived`);return this._state.optimisticUpdate({execute:async()=>{try{let{remoteId:e}=await t.initializeTask;return await this._options.adapter.unarchive(e)}catch(e){throw await this._ensureThreadIsNotMain(t.id),e}},optimistic:e=>Ni(e,t.id,`regular`)})}async delete(e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status!==`regular`&&t.status!==`archived`)throw Error(`Thread is not yet initialized`);return await this._ensureThreadIsNotMain(t.id),this._hookManager.stopThreadRuntime(t.id),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await t.initializeTask;return await this._options.adapter.delete(e)},optimistic:e=>Ni(e,t.id,`deleted`)})}async detach(e){let t=this.getItemById(e);if(!t)throw Error(`Thread not found`);if(t.status!==`regular`&&t.status!==`archived`)throw Error(`Thread is not yet initialized`);await this._ensureThreadIsNotMain(t.id),this._hookManager.stopThreadRuntime(t.id)}useBoundIds=U(()=>[]);__internal_RenderComponent=()=>{let e=(0,E.useId)();(0,E.useEffect)(()=>(this.useBoundIds.setState(t=>[...t,e],!0),()=>{this.useBoundIds.setState(t=>t.filter(t=>t!==e),!0)}),[e]);let t=this.useBoundIds(),{Provider:n}=this.useProvider(),r={modelContext:this.contextProvider};return(t.length===0||t[0]===e)&&(0,L.jsx)(gi,{adapters:r,children:(0,L.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})}},Ii=class extends yr{threads;constructor(e){super(),this.threads=new Fi(e,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Li=e=>{let[t]=(0,E.useState)(()=>new Ii(e));return(0,E.useEffect)(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),(0,E.useMemo)(()=>new pi(t),[t])},Ri=e=>{let t=(0,E.useRef)(e.runtimeHook);t.current=e.runtimeHook;let n=(0,E.useRef)(e.threadId??e.initialThreadId),r=(0,E.useCallback)(()=>t.current(),[]),i=(0,E.useMemo)(()=>({adapter:e.adapter,allowNesting:e.allowNesting,initialThreadId:n.current,runtimeHook:r}),[e.adapter,e.allowNesting,r]);if(B().threadListItem.source!==null){if(!i.allowNesting)throw Error(`useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).`);return r()}let a=Li(i),o=(0,E.useRef)(e.threadId);return(0,E.useEffect)(()=>{e.threadId!==o.current&&(o.current=e.threadId,e.threadId?a.threads.switchToThread(e.threadId).catch(()=>{}):a.threads.switchToNewThread().catch(()=>{}))},[a,e.threadId]),a},zi=e=>{try{let t=e.split(`.`)[1];if(!t)throw Error(`Invalid JWT format`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`);for(;n.length%4!=0;)n+=`=`;let r=atob(n),i=JSON.parse(r).exp;if(!i||typeof i!=`number`)throw Error(`JWT does not contain a valid "exp" field`);return i*1e3}catch(e){throw Error(`Unable to determine the token expiry: ${e}`)}},Bi=class{strategy=`jwt`;cachedToken=null;tokenExpiry=null;#e;constructor(e){this.#e=e}async getAuthHeaders(){let e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};let t=await this.#e();return t?(this.cachedToken=t,this.tokenExpiry=zi(t),{Authorization:`Bearer ${t}`}):!1}readAuthHeaders(e){let t=e.get(`Authorization`);if(!t)return;let[n,r]=t.split(` `);if(n!==`Bearer`||!r)throw Error(`Invalid auth header received`);this.cachedToken=r,this.tokenExpiry=zi(r)}},Vi=class{strategy=`api-key`;#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async getAuthHeaders(){return{Authorization:`Bearer ${this.#e}`,"Aui-User-Id":this.#t,"Aui-Workspace-Id":this.#n}}readAuthHeaders(){}},Hi=`aui:refresh_token`,Ui=class{strategy=`anon`;baseUrl;jwtStrategy;constructor(e){this.baseUrl=e,this.jwtStrategy=new Bi(async()=>{let e=Date.now(),t=localStorage.getItem(Hi),n=t?JSON.parse(t):void 0;if(n)if(new Date(n.expires_at).getTime()-e>30*1e3){let e=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refresh_token:n.token})});if(e.ok){let{access_token:t,refresh_token:n}=await e.json();return n&&localStorage.setItem(Hi,JSON.stringify(n)),t}}else localStorage.removeItem(Hi);let r=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:`POST`});if(!r.ok)return null;let{access_token:i,refresh_token:a}=await r.json();return!i||!a?null:(localStorage.setItem(Hi,JSON.stringify(a)),i)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Wi=class extends Error{constructor(e){super(e),this.name=`APIError`}},Gi=class{_auth;_baseUrl;constructor(e){if(`authToken`in e)this._baseUrl=e.baseUrl,this._auth=new Bi(e.authToken);else if(`apiKey`in e)this._baseUrl=`https://backend.assistant-api.com`,this._auth=new Vi(e.apiKey,e.userId,e.workspaceId);else if(`anonymous`in e)this._baseUrl=e.baseUrl,this._auth=new Ui(e.baseUrl);else throw Error(`Invalid configuration: Must provide authToken, apiKey, or anonymous configuration`)}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(e,t={}){let n=await this._auth.getAuthHeaders();if(!n)throw Error(`Authorization failed`);let r={...n,...t.headers,"Content-Type":`application/json`},i=new URLSearchParams;if(t.query)for(let[e,n]of Object.entries(t.query))n!==!1&&(n===!0?i.set(e,`true`):i.set(e,n.toString()));let a=new URL(`${this._baseUrl}/v1${e}`);a.search=i.toString();let o=await fetch(a,{method:t.method??`GET`,headers:r,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){let e=await o.text();try{throw new Wi(JSON.parse(e).message)}catch(t){throw t instanceof Wi?t:Error(`Request failed with status ${o.status}, ${e}`)}}return o}async makeRequest(e,t={}){return(await this.makeRawRequest(e,t)).json()}},Ki=class{cloud;constructor(e){this.cloud=e}async create(){return this.cloud.makeRequest(`/auth/tokens`,{method:`POST`})}},qi=class{cloud;constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:async()=>{let e=await this.cloud._auth.getAuthHeaders();if(!e)throw Error(`Authorization failed`);return{...e,Accept:`text/plain`}},body:{assistant_id:e,response_format:`vercel-ai-data-stream/v1`,thread_id:`unstable_todo`}}}async stream(e){let t=await this.cloud.makeRawRequest(`/runs/stream`,{method:`POST`,headers:{Accept:`text/plain`},body:e});return Jt.fromResponse(t,new Wn)}async report(e){return this.cloud.makeRequest(`/runs`,{method:`POST`,body:e})}},Ji=class{cloud;constructor(e){this.cloud=e}async list(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})}async create(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:`POST`,body:t})}async update(e,t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`,{method:`PUT`,body:n})}},Yi=class{cloud;messages;constructor(e){this.cloud=e,this.messages=new Ji(e)}async list(e){return this.cloud.makeRequest(`/threads`,{query:e})}async get(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)}async create(e){return this.cloud.makeRequest(`/threads`,{method:`POST`,body:e})}async update(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:`PUT`,body:t})}async delete(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:`DELETE`})}},Xi=class{cloud;constructor(e){this.cloud=e}async pdfToImages(e){return this.cloud.makeRequest(`/files/pdf-to-images`,{method:`POST`,body:e})}async generatePresignedUploadUrl(e){return this.cloud.makeRequest(`/files/attachments/generate-presigned-upload-url`,{method:`POST`,body:e})}},Zi=class{threads;auth;runs;files;telemetry;constructor(e){let t=new Gi(e);this.threads=new Yi(t),this.auth={tokens:new Ki(t)},this.runs=new qi(t),this.files=new Xi(t);let n=e.telemetry;this.telemetry=n===!1?{enabled:!1}:n===!0||n===void 0?{enabled:!0}:{enabled:n.enabled!==!1,...n}}},Qi=class{cloud;idMapping={};constructor(e){this.cloud=e}async append(e,t,n,r,i){let a=n?await this.idMapping[n]??n:null,o=this.cloud.threads.messages.create(e,{parent_id:a,format:r,content:i}).then(({message_id:e})=>(this.idMapping[t]=e,e)).catch(e=>{throw this.idMapping[t]===o&&delete this.idMapping[t],e});return this.idMapping[t]=o,o.then(()=>{})}async update(e,t,n,r){let i=await this.getRemoteId(t);i&&await this.cloud.threads.messages.update(e,i,{content:r})}isPersisted(e){return e in this.idMapping}async getRemoteId(e){let t=this.idMapping[e];if(t)return t}async load(e,t){let{messages:n}=await this.cloud.threads.messages.list(e,t?{format:t}:void 0);for(let e of n)this.idMapping[e.id]=e.id;return n}reset(){this.idMapping={}}},$i=(e,t)=>({append:async(n,r)=>{let i=t.getId(r.message),a=t.encode(r);return e.append(n,i,r.parentId,t.format,a)},update:e.update?async(n,r,i)=>{let a=t.encode(r);return e.update(n,i,t.format,a)}:void 0,load:async n=>({messages:(await e.load(n,t.format)).filter(e=>e.format===t.format).map(e=>t.decode({id:e.id,parent_id:e.parent_id,format:e.format,content:e.content})).reverse()}),isPersisted:t=>e.isPersisted(t)}),ea=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(Error(`Thread not found`))}};function ta(e){let t=e.status?.type===`running`?{type:`incomplete`,reason:`cancelled`}:e.status;return{role:e.role,content:e.content.map(e=>{let t=e.type;switch(t){case`text`:return{type:`text`,text:e.text};case`reasoning`:return{type:`reasoning`,text:e.text};case`source`:return{type:`source`,sourceType:e.sourceType,id:e.id,url:e.url,...e.title?{title:e.title}:void 0};case`tool-call`:return yi(e.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(e)}`),{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,...JSON.stringify(e.args)===e.argsText?{args:e.args}:{argsText:e.argsText},...e.result?{result:e.result}:void 0,...e.isError?{isError:!0}:void 0};case`image`:return{type:`image`,image:e.image};case`file`:return{type:`file`,data:e.data,mimeType:e.mimeType,...e.filename?{filename:e.filename}:void 0};default:throw Error(`Message part type not supported by aui/v0: ${t}`)}}),metadata:e.metadata,...t?{status:t}:void 0}}function na(e){let t=e.content,n=kr({id:e.id,createdAt:e.created_at,...t},e.id,{type:`complete`,reason:`unknown`});return{parentId:e.parent_id,message:n}}var ra=new WeakMap,ia=class{cloudRef;aui;constructor(e,t){this.cloudRef=e,this.aui=t}get _persistence(){let e=this.aui.threadListItem();return ra.has(e)||ra.set(e,new Qi(this.cloudRef.current)),ra.get(e)}withFormat(e){let t=this,n=$i(this._persistence,e);return{async append(e){let{remoteId:r}=await t.aui.threadListItem().initialize();await n.append(r,e)},async update(e,r){let i=t.aui.threadListItem().getState().remoteId;i&&await n.update?.(i,e,r)},reportTelemetry(n,r){let i=n.map(t=>e.encode(t));t._reportRunTelemetry(e.format,i,r)},async load(){let e=t.aui.threadListItem().getState().remoteId;return e?n.load(e):{messages:[]}}}}async append({parentId:e,message:t}){let{remoteId:n}=await this.aui.threadListItem().initialize(),r=ta(t);await this._persistence.append(n,t.id,e,`aui/v0`,r),this.cloudRef.current.telemetry.enabled&&this._maybeReportRun(n,`aui/v0`,r)}async load(){let e=this.aui.threadListItem().getState().remoteId;return e?{messages:(await this._persistence.load(e,`aui/v0`)).filter(e=>e.format===`aui/v0`).map(na).reverse()}:{messages:[]}}_reportRunTelemetry(e,t,n){if(!this.cloudRef.current.telemetry.enabled)return;let r=this.aui.threadListItem().getState().remoteId;if(!r)return;let i=pa(e,t);i&&this._sendReport(r,i,n?.durationMs,n?.stepTimestamps)}_maybeReportRun(e,t,n){let r=fa(t,n);r&&this._sendReport(e,r)}_sendReport(e,t,n,r){let i=da(t.steps,r),a={thread_id:e,status:t.status,...t.totalSteps==null?void 0:{total_steps:t.totalSteps},...t.toolCalls?{tool_calls:t.toolCalls}:void 0,...i?{steps:i}:void 0,...t.inputTokens==null?void 0:{input_tokens:t.inputTokens},...t.outputTokens==null?void 0:{output_tokens:t.outputTokens},...t.reasoningTokens==null?void 0:{reasoning_tokens:t.reasoningTokens},...t.cachedInputTokens==null?void 0:{cached_input_tokens:t.cachedInputTokens},...n==null?void 0:{duration_ms:n},...t.outputText==null?void 0:{output_text:t.outputText},...t.metadata?{metadata:t.metadata}:void 0,...t.modelId?{model_id:t.modelId}:void 0},{beforeReport:o}=this.cloudRef.current.telemetry,s=o?o(a):a;s&&this.cloudRef.current.runs.report(s).catch(()=>{})}},aa=5e4;function oa(e){return e.length<=aa?e:e.slice(0,aa)}function sa(e){if(e!=null)try{return oa(JSON.stringify(e))}catch{return}}var ca=/^[A-Za-z0-9+/]{100,}={0,2}$/;function la(e){if(e!=null){try{let t=typeof e==`string`?JSON.parse(e):e;if(Array.isArray(t)){let e=t.map(e=>{if(e&&typeof e==`object`&&e.type&&(e.type===`image`||e.type===`audio`)&&typeof e.data==`string`&&ca.test(e.data.slice(0,200))){let t=(e.data.length*3/4/1024).toFixed(1);return{...e,data:`[${e.type}: ${t}KB]`}}return e});return oa(JSON.stringify(e))}}catch{}return sa(e)}}function ua(e,t,n,r,i,a){let o={tool_name:e,tool_call_id:t},s=i??sa(n);s!==void 0&&(o.tool_args=s);let c=a===`mcp`?la(r):sa(r);return c!==void 0&&(o.tool_result=c),a&&(o.tool_source=a),o}function da(e,t){if(!t)return e;if(!e)return t.map(e=>({...e}));let n=Math.min(e.length,t.length);return e.map((e,r)=>({...e,...r<n?t[r]:void 0}))}function fa(e,t){switch(e){case`aui/v0`:return ha(t);case`ai-sdk/v6`:return wa(t);default:return null}}function pa(e,t){if(e===`ai-sdk/v6`)return Ta(t);for(let n=t.length-1;n>=0;n--){let r=fa(e,t[n]);if(r)return r}return null}var ma={error:`error`,incomplete:`incomplete`};function ha(e){let t=e;if(t.role!==`assistant`)return null;let n=t.content?.filter(e=>e.type===`tool-call`&&e.toolName&&e.toolCallId).map(e=>ua(e.toolName,e.toolCallId,e.args,e.result,e.argsText)),r=t.content?.filter(e=>e.type===`text`&&e.text),i=r&&r.length>0?oa(r.map(e=>e.text).join(``)):void 0,a=t.metadata?.steps,o,s,c,l;if(a&&a.length>0){let e=0,t=0,n=0,r=0,i=!1,u=!1,d=!1,f=!1;for(let o of a)o.usage?.inputTokens!=null&&(e+=o.usage.inputTokens,i=!0),o.usage?.outputTokens!=null&&(t+=o.usage.outputTokens,u=!0),o.usage?.reasoningTokens!=null&&(n+=o.usage.reasoningTokens,d=!0),o.usage?.cachedInputTokens!=null&&(r+=o.usage.cachedInputTokens,f=!0);o=i?e:void 0,s=u?t:void 0,c=d?n:void 0,l=f?r:void 0}let u=t.status?.type,d=u&&ma[u]||`completed`,f=t.metadata?.custom,p=t.metadata?.modelId??(typeof t.metadata?.custom?.modelId==`string`?t.metadata.custom.modelId:void 0),m=a&&a.length>1?a.map(e=>({...e.usage?.inputTokens==null?void 0:{input_tokens:e.usage.inputTokens},...e.usage?.outputTokens==null?void 0:{output_tokens:e.usage.outputTokens},...e.usage?.reasoningTokens==null?void 0:{reasoning_tokens:e.usage.reasoningTokens},...e.usage?.cachedInputTokens==null?void 0:{cached_input_tokens:e.usage.cachedInputTokens}})):void 0;return{status:d,...n&&n.length>0?{toolCalls:n}:void 0,...a?.length?{totalSteps:a.length}:void 0,...o==null?void 0:{inputTokens:o},...s==null?void 0:{outputTokens:s},...c==null?void 0:{reasoningTokens:c},...l==null?void 0:{cachedInputTokens:l},...i==null?void 0:{outputText:i},...f?{metadata:f}:void 0,...m?{steps:m}:void 0,...p?{modelId:p}:void 0}}function ga(e){return e.toolCallId?e.type===`tool-call`||e.type===`dynamic-tool`?!!e.toolName:e.type.startsWith(`tool-`)||e.type.startsWith(`dynamic-tool-`):!1}function _a(e){return e.type===`dynamic-tool`||e.type.startsWith(`dynamic-tool-`)}function va(e){let t=_a(e)?`mcp`:void 0;return ua(e.toolName??e.type.slice(5),e.toolCallId,e.args??e.input,e.result??e.output,void 0,t)}function ya(e){let t=[],n=[],r=[],i=null;for(let a of e)if(a.type===`step-start`)i!==null&&r.push({tool_calls:i}),i=[];else if(a.type===`text`&&a.text)t.push(a.text);else if(ga(a)){let e=va(a);n.push(e),i!==null&&i.push(e)}return i!==null&&r.push({tool_calls:i}),{textParts:t,toolCalls:n,stepsData:r}}function ba(e){if(!e)return;if(typeof e.modelId==`string`)return e.modelId;let t=e.custom;if(typeof t?.modelId==`string`)return t.modelId}function xa(e,t,n,r,i,a){let o=e.length>0,s=o?oa(e.join(``)):void 0,c=ba(r),l=i&&i.length>1?i.map(e=>({...e.tool_calls.length>0?{tool_calls:e.tool_calls}:void 0})):void 0;return{status:o?`completed`:`incomplete`,...t.length>0?{toolCalls:t}:void 0,...n>0?{totalSteps:n}:void 0,...a?.inputTokens==null?void 0:{inputTokens:a.inputTokens},...a?.outputTokens==null?void 0:{outputTokens:a.outputTokens},...a?.reasoningTokens==null?void 0:{reasoningTokens:a.reasoningTokens},...a?.cachedInputTokens==null?void 0:{cachedInputTokens:a.cachedInputTokens},...s==null?void 0:{outputText:s},...r?{metadata:r}:void 0,...l?{steps:l}:void 0,...c?{modelId:c}:void 0}}function Sa(e){let t=e.inputTokens??e.promptTokens,n=e.outputTokens??e.completionTokens;if(!(t==null&&n==null&&e.reasoningTokens==null&&e.cachedInputTokens==null))return{...t==null?void 0:{inputTokens:t},...n==null?void 0:{outputTokens:n},...e.reasoningTokens==null?void 0:{reasoningTokens:e.reasoningTokens},...e.cachedInputTokens==null?void 0:{cachedInputTokens:e.cachedInputTokens}}}function Ca(e){let t=e?.usage;if(t){let e=Sa(t);if(e)return e}let n=e?.steps;if(n&&n.length>0){let e=0,t=0,r=0,i=0,a=!1,o=!1,s=!1,c=!1,l=!1;for(let u of n){if(!u.usage)continue;let n=Sa(u.usage);n&&(n.inputTokens!=null&&(e+=n.inputTokens,a=!0),n.outputTokens!=null&&(t+=n.outputTokens,o=!0),n.reasoningTokens!=null&&(r+=n.reasoningTokens,s=!0),n.cachedInputTokens!=null&&(i+=n.cachedInputTokens,c=!0),l=!0)}if(l)return{...a?{inputTokens:e}:void 0,...o?{outputTokens:t}:void 0,...s?{reasoningTokens:r}:void 0,...c?{cachedInputTokens:i}:void 0}}}function wa(e){let t=e;if(t.role!==`assistant`)return null;let{textParts:n,toolCalls:r,stepsData:i}=ya(t.parts??[]);return xa(n,r,i.length,t.metadata,i,Ca(t.metadata))}function Ta(e){let t=[],n=[],r=[],i=!1,a,o=0,s=0,c=0,l=0,u=!1,d=!1,f=!1,p=!1;for(let m of e){let e=m;if(e.role!==`assistant`)continue;i=!0;let{textParts:h,toolCalls:ee,stepsData:te}=ya(e.parts??[]);t.push(...h),n.push(...ee),r.push(...te),e.metadata&&(a=e.metadata);let g=Ca(e.metadata);g&&(g.inputTokens!=null&&(o+=g.inputTokens,u=!0),g.outputTokens!=null&&(s+=g.outputTokens,d=!0),g.reasoningTokens!=null&&(c+=g.reasoningTokens,f=!0),g.cachedInputTokens!=null&&(l+=g.cachedInputTokens,p=!0))}return i?xa(t,n,r.length,a,r,{...u?{inputTokens:o}:void 0,...d?{outputTokens:s}:void 0,...f?{reasoningTokens:c}:void 0,...p?{cachedInputTokens:l}:void 0}):null}function Ea(e){let t=B(),[n]=(0,E.useState)(()=>new ia(e,t));return n}var Da=e=>e.startsWith(`image/`)?`image`:e.startsWith(`text/`)?`document`:`file`,Oa=class{cloud;accept=`*`;constructor(e){this.cloud=e}uploadedUrls=new Map;async*add({file:e}){let t=crypto.randomUUID(),n={id:t,type:Da(e.type),name:e.name,contentType:e.type,file:e,status:{type:`running`,reason:`uploading`,progress:0}};yield n;try{let{signedUrl:r,publicUrl:i}=await this.cloud.files.generatePresignedUploadUrl({filename:e.name});await fetch(r,{method:`PUT`,body:e,headers:{"Content-Type":e.type},mode:`cors`}),this.uploadedUrls.set(t,i),n={...n,status:{type:`requires-action`,reason:`composer-send`}},yield n}catch{n={...n,status:{type:`incomplete`,reason:`error`}},yield n}}async remove(e){this.uploadedUrls.delete(e.id)}async send(e){let t=this.uploadedUrls.get(e.id);if(!t)throw Error(`Attachment not uploaded`);this.uploadedUrls.delete(e.id);let n;return n=e.type===`image`?[{type:`image`,image:t,filename:e.name}]:[{type:`file`,data:t,mimeType:e.contentType??``,filename:e.name}],{...e,status:{type:`complete`},content:n}}},ka=typeof process<`u`&&{}?.NEXT_PUBLIC_ASSISTANT_BASE_URL,Aa=ka?new Zi({baseUrl:ka,anonymous:!0}):void 0,ja=e=>{let t=(0,E.useRef)(e);(0,E.useEffect)(()=>{t.current=e},[e]);let n=(0,E.useCallback)(function({children:e}){let n=Ea({get current(){return t.current.cloud??Aa}}),r=t.current.cloud??Aa,i=(0,E.useMemo)(()=>new Oa(r),[r]);return(0,L.jsx)(gi,{adapters:(0,E.useMemo)(()=>({history:n,attachments:i}),[n,i]),children:e})},[]),r=e.cloud??Aa;if(!r){let e=t,n=new ea;return n.initialize=async t=>({remoteId:t,externalId:(await e.current.create?.())?.externalId}),n}return{list:async()=>{let{threads:e}=await r.threads.list();return{threads:e.map(e=>({status:e.is_archived?`archived`:`regular`,remoteId:e.id,title:e.title,externalId:e.external_id??void 0}))}},initialize:async()=>{let t=await(e.create?.()??Promise.resolve()),n=t?t.externalId:void 0,{thread_id:i}=await r.threads.create({last_message_at:new Date,external_id:n});return{externalId:n,remoteId:i}},rename:async(e,t)=>r.threads.update(e,{title:t}),archive:async e=>r.threads.update(e,{is_archived:!0}),unarchive:async e=>r.threads.update(e,{is_archived:!1}),delete:async t=>(await e.delete?.(t),r.threads.delete(t)),generateTitle:async(e,t)=>{let n=t.map(e=>({...e,content:e.content.filter(e=>e.type===`text`||e.type===`tool-call`)}));return r.runs.stream({thread_id:e,assistant_id:`system/thread_title`,messages:n})},fetch:async e=>{let t=await r.threads.get(e);return{status:t.is_archived?`archived`:`regular`,remoteId:t.id,title:t.title,externalId:t.external_id??void 0}},unstable_Provider:n}},Ma=e=>e._core?.RenderComponent,Na=(0,E.memo)(({runtime:e,aui:t=null,children:n})=>{let r=B({threads:mi(e)},{parent:t}),i=Ma(e);return(0,L.jsxs)(R,{value:r,children:[i&&(0,L.jsx)(i,{}),n]})}),Pa=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,Fa=()=>null,Ia=(e,t,n)=>{switch(t){case`user`:return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case`assistant`:return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case`system`:return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??e.Message??Fa;default:throw Error(`Unknown message role: ${t}`)}},La=({components:e})=>(0,L.jsx)(Ia(e,V(e=>e.message.role),V(e=>e.message.composer.isEditing)),{}),Ra=(0,E.memo)(({index:e,components:t})=>(0,L.jsx)(lr,{index:e,children:(0,L.jsx)(La,{components:t})}),(e,t)=>e.index===t.index&&Pa(e.components,t.components));Ra.displayName=`ThreadPrimitive.MessageByIndex`;var za=({children:e})=>{let t=V(e=>e.thread.messages.length);return(0,E.useMemo)(()=>t===0?null:Array.from({length:t},(t,n)=>(0,L.jsx)(lr,{index:n,children:(0,L.jsx)(Ft,{getItemState:e=>e.thread().message({index:n}).getState(),children:t=>e({get message(){return t()}})})},n)),[t,e])},Ba=({components:e,children:t})=>e?(0,L.jsx)(za,{children:()=>(0,L.jsx)(La,{components:e})}):(0,L.jsx)(za,{children:t});Ba.displayName=`ThreadPrimitive.Messages`;var Va=(0,E.memo)(Ba,(e,t)=>e.children||t.children?e.children===t.children:Pa(e.components,t.components)),Ha=e=>{let t=e.message.metadata;if(!(!t||typeof t!=`object`))return t.custom?.quote},Ua=e=>Symbol.iterator in e,Wa=e=>`entries`in e,Ga=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},Ka=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function qa(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Ua(e)&&Ua(t)?Wa(e)&&Wa(t)?Ga(e,t):Ka(e,t):Ga({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ja(e){let t=E.useRef(void 0);return n=>{let r=e(n);return qa(t.current,r)?t.current:t.current=r}}var Ya=e=>{let t=-1;return{startGroup:e=>{t===-1&&(t=e)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},Xa=(e,t)=>{let n=[];if(t){let t=Ya(`chainOfThoughtGroup`);for(let r=0;r<e.length;r++){let i=e[r];i===`tool-call`||i===`reasoning`?t.startGroup(r):(t.endGroup(r-1,n),n.push({type:`single`,index:r}))}t.finalize(e.length-1,n)}else{let t=Ya(`toolGroup`),r=Ya(`reasoningGroup`);for(let i=0;i<e.length;i++){let a=e[i];a===`tool-call`?(r.endGroup(i-1,n),t.startGroup(i)):a===`reasoning`?(t.endGroup(i-1,n),r.startGroup(i)):(t.endGroup(i-1,n),r.endGroup(i-1,n),n.push({type:`single`,index:i}))}t.finalize(e.length-1,n),r.finalize(e.length-1,n)}return n},Za=e=>{let t=V(Ja(e=>e.message.parts.map(e=>e.type)));return(0,E.useMemo)(()=>t.length===0?[]:Xa(t,e),[t,e])},Qa=({Fallback:e,...t})=>{let n=V(n=>{let r=n.tools.tools[t.toolName]??e;return Array.isArray(r)?r[0]??e:r});return n?(0,L.jsx)(n,{...t}):null},$a=({Fallback:e,...t})=>{let n=V(n=>{let r=n.dataRenderers.renderers[t.name]??e;return Array.isArray(r)?r[0]??e:r});return n?(0,L.jsx)(n,{...t}):null},Z={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},eo=({components:{Text:e=Z.Text,Reasoning:t=Z.Reasoning,Image:n=Z.Image,Source:r=Z.Source,File:i=Z.File,Unstable_Audio:a=Z.Unstable_Audio,tools:o={},data:s}={}})=>{let c=B(),l=V(e=>e.part),u=l.type;if(u===`tool-call`){let e=c.part().addToolResult,t=c.part().resumeToolCall;if(`Override`in o)return(0,L.jsx)(o.Override,{...l,addResult:e,resume:t});let n=o.by_name?.[l.toolName]??o.Fallback;return(0,L.jsx)(Qa,{...l,Fallback:n,addResult:e,resume:t})}if(l.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(u){case`text`:return(0,L.jsx)(e,{...l});case`reasoning`:return(0,L.jsx)(t,{...l});case`source`:return(0,L.jsx)(r,{...l});case`image`:return(0,L.jsx)(n,{...l});case`file`:return(0,L.jsx)(i,{...l});case`audio`:return(0,L.jsx)(a,{...l});case`data`:{let e=s?.by_name?.[l.name]??s?.Fallback;return(0,L.jsx)($a,{...l,Fallback:e})}default:return console.warn(`Unknown message part type: ${u}`),null}},to=(0,E.memo)(({index:e,components:t})=>(0,L.jsx)(ur,{index:e,children:(0,L.jsx)(eo,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);to.displayName=`MessagePrimitive.PartByIndex`;var no=({status:e,component:t})=>(0,L.jsx)(fr,{text:``,isRunning:e.type===`running`,children:(0,L.jsx)(t,{type:`text`,text:``,status:e})}),ro=Object.freeze({type:`complete`}),io=(0,E.memo)(({components:e})=>{let t=V(e=>e.message.status??ro);return e?.Empty?(0,L.jsx)(e.Empty,{status:t}):t.type===`running`?(0,L.jsx)(no,{status:t,component:e?.Text??Z.Text}):null},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),ao=(0,E.memo)(({components:e,enabled:t})=>V(e=>{if(!t||e.message.parts.length===0)return!1;let n=e.message.parts[e.message.parts.length-1];return n?.type!==`text`&&n?.type!==`reasoning`})?(0,L.jsx)(io,{components:e}):null,(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),oo=(0,E.memo)(({Quote:e})=>{let t=V(Ha);return t?(0,L.jsx)(e,{text:t.text,messageId:t.messageId}):null}),so=()=>{let e=B(),t=V(e=>e.part),n=V(e=>{if(e.part.type!==`tool-call`)return null;let t=e.tools.tools[e.part.toolName];return Array.isArray(t)?t[0]??null:t??null});return!n||t.type!==`tool-call`?null:(0,L.jsx)(n,{...t,addResult:e.part().addToolResult,resume:e.part().resumeToolCall})},co=()=>{let e=V(e=>e.part),t=V(e=>{if(e.part.type!==`data`)return null;let t=e.dataRenderers.renderers[e.part.name];return Array.isArray(t)?t[0]??null:t??null});return!t||e.type!==`data`?null:(0,L.jsx)(t,{...e})},lo=()=>{let e=V(e=>e.part.type);return e===`tool-call`?(0,L.jsx)(so,{}):e===`data`?(0,L.jsx)(co,{}):null},uo=({children:e})=>{let t=B(),n=V(e=>e.message.parts.length);return(0,E.useMemo)(()=>Array.from({length:n},(n,r)=>(0,L.jsx)(ur,{index:r,children:(0,L.jsx)(Ft,{getItemState:e=>e.message().part({index:r}).getState(),children:n=>{let i=e({get part(){let e=n();if(e.type===`tool-call`){let n=t.tools().getState().tools[e.toolName],i=Array.isArray(n)?!!n[0]:!!n,a=t.message().part({index:r});return{...e,toolUI:i?(0,L.jsx)(so,{}):null,addResult:a.addToolResult,resume:a.resumeToolCall}}if(e.type===`data`){let n=t.dataRenderers().getState().renderers[e.name],r=Array.isArray(n)?!!n[0]:!!n;return{...e,dataRendererUI:r?(0,L.jsx)(co,{}):null}}return e}});return i===null?(0,L.jsx)(lo,{}):i}})},r)),[n,e])},fo=({components:e,unstable_showEmptyOnNonTextEnd:t=!0,children:n})=>n?(0,L.jsx)(uo,{children:n}):(0,L.jsx)(po,{components:e,unstable_showEmptyOnNonTextEnd:t});fo.displayName=`MessagePrimitive.Parts`;var po=({components:e,unstable_showEmptyOnNonTextEnd:t})=>{let n=V(e=>e.message.parts.length),r=Za(!!e?.ChainOfThought),i=(0,E.useMemo)(()=>n===0?(0,L.jsx)(io,{components:e}):r.map(t=>{if(t.type===`single`)return(0,L.jsx)(to,{index:t.index,components:e},t.index);if(t.type===`chainOfThoughtGroup`){let n=e?.ChainOfThought;return n?(0,L.jsx)(pr,{startIndex:t.startIndex,endIndex:t.endIndex,children:(0,L.jsx)(n,{})},`chainOfThought-${t.startIndex}`):null}else if(t.type===`toolGroup`)return(0,L.jsx)(e?.ToolGroup??Z.ToolGroup,{startIndex:t.startIndex,endIndex:t.endIndex,children:Array.from({length:t.endIndex-t.startIndex+1},(n,r)=>(0,L.jsx)(to,{index:t.startIndex+r,components:e},r))},`tool-${t.startIndex}`);else return(0,L.jsx)(e?.ReasoningGroup??Z.ReasoningGroup,{startIndex:t.startIndex,endIndex:t.endIndex,children:Array.from({length:t.endIndex-t.startIndex+1},(n,r)=>(0,L.jsx)(to,{index:t.startIndex+r,components:e},r))},`reasoning-${t.startIndex}`)}),[r,e,n]);return(0,L.jsxs)(L.Fragment,{children:[e?.Quote&&(0,L.jsx)(oo,{Quote:e.Quote}),i,(0,L.jsx)(ao,{components:e,enabled:t})]})},mo=()=>{let e=B(),t=V(e=>e.thread.isRunning&&!e.thread.capabilities.queue||!e.composer.isEditing||e.composer.isEmpty);return{send:(0,E.useCallback)(t=>{e.composer().send(t)},[e]),disabled:t}},ho=({prompt:e,send:t,clearComposer:n=!0})=>{let r=B(),i=V(e=>e.thread.isDisabled),a=t??!1;return{trigger:(0,E.useCallback)(()=>{let t=r.thread().getState().isRunning;if(a&&!t)r.thread().append({content:[{type:`text`,text:e}],runConfig:r.composer().getState().runConfig}),n&&r.composer().setText(``);else if(n)r.composer().setText(e);else{let t=r.composer().getState().text;r.composer().setText(t.trim()?`${t} ${e}`:e)}},[r,a,n,e]),disabled:i}},go=(e,{initialMessages:t,...n})=>{let{modelContext:r,...i}=_i()??{},a={...n,adapters:{...i,...n.adapters,chatModel:e}},[o]=(0,E.useState)(()=>new Di(a,t)),s=(0,E.useRef)(void 0);return s.current=V(e=>e.threadListItem.remoteId),(0,E.useEffect)(()=>{o.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>s.current)},[o]),(0,E.useEffect)(()=>()=>{o.threads.getMainThreadRuntimeCore().detach()},[o]),(0,E.useEffect)(()=>{o.threads.getMainThreadRuntimeCore().__internal_setOptions(a),o.threads.getMainThreadRuntimeCore().__internal_load()}),(0,E.useEffect)(()=>{if(r)return o.registerModelContextProvider(r)},[r,o]),(0,E.useMemo)(()=>new pi(o),[o])},_o=(e,{cloud:t,...n}={})=>Ri({runtimeHook:function(){return go(e,n)},adapter:ja({cloud:t}),allowNesting:!0}),vo=e=>{let t=new Map,n=()=>{let n=0;for(let e of t.values())n+=e;e(n)};return{register:()=>{let e=Symbol();return t.set(e,0),{setHeight:r=>{t.get(e)!==r&&(t.set(e,r),n())},unregister:()=>{t.delete(e),n()}}}}},yo=(e={})=>{let t=new Set,n=vo(e=>{a.setState({height:{...a.getState().height,viewport:e}})}),r=vo(e=>{a.setState({height:{...a.getState().height,inset:e}})}),i=vo(e=>{a.setState({height:{...a.getState().height,userMessage:e}})}),a=U(()=>({isAtBottom:!0,scrollToBottom:({behavior:e=`auto`}={})=>{for(let n of t)n({behavior:e})},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)}),turnAnchor:e.turnAnchor??`bottom`,height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:r.register,registerUserMessageHeight:i.register}));return a};function bo(e,t){function n(n){let r=(0,E.useContext)(e);if(!n?.optional&&!r)throw Error(`This component must be used within ${t}.`);return r}return n}function xo(e,t){function n(n){let r=e(n);return r?r[t]:null}function r(e){let t=!1,r;typeof e==`function`?r=e:e&&typeof e==`object`&&(t=!!e.optional,r=e.selector);let i=n({optional:t});return i?r?i(r):i():null}return{[t]:r,[`${t}Store`]:n}}var So=(0,E.createContext)(null),{useThreadViewport:Co,useThreadViewportStore:wo}=xo(bo(So,`ThreadPrimitive.Viewport`),`useThreadViewport`),To=e=>e,Eo=e=>{let t=wo({optional:!0}),[n]=(0,E.useState)(()=>yo(e));return(0,E.useEffect)(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),(0,E.useEffect)(()=>{if(t)return n.subscribe(e=>{t.getState().isAtBottom!==e.isAtBottom&&To(t).setState({isAtBottom:e.isAtBottom})})},[n,t]),(0,E.useEffect)(()=>{let t={turnAnchor:e.turnAnchor??`bottom`};n.getState().turnAnchor!==t.turnAnchor&&To(n).setState(t)},[n,e.turnAnchor]),n},Do=({children:e,options:t={}})=>{let n=Eo(t),[r]=(0,E.useState)(()=>({useThreadViewport:n}));return(0,L.jsx)(So.Provider,{value:r,children:e})},Oo=()=>((0,E.useEffect)(()=>{},[B()]),null),ko=(0,E.memo)(({children:e,aui:t,runtime:n})=>(0,L.jsxs)(Na,{runtime:n,aui:t??null,children:[(0,L.jsx)(Oo,{}),(0,L.jsx)(Do,{children:e})]})),Ao=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`];function jo(e){let t=d[e],n=(0,E.forwardRef)(({render:e,asChild:n,children:r,...i},a)=>{if(e&&(0,E.isValidElement)(e)){let n=r===void 0?e.props.children:r;return(0,L.jsx)(t,{asChild:!0,...i,ref:a,children:(0,E.cloneElement)(e,void 0,n)})}return(0,L.jsx)(t,{asChild:n,...i,ref:a,children:r})});return n.displayName=`Primitive.${e}`,n}var Q=Ao.reduce((e,t)=>(e[t]=jo(t),e),{}),Mo=(e,t,n=[])=>{let r=(0,E.forwardRef)((e,r)=>{let i={},a={};Object.keys(e).forEach(t=>{n.includes(t)?i[t]=e[t]:a[t]=e[t]});let o=t(i)??void 0;return(0,L.jsx)(Q.button,{...a,type:`button`,ref:r,disabled:a.disabled||!o,onClick:m(a.onClick,o)})});return r.displayName=e,r},No=()=>{let{disabled:e,send:t}=mo(),n=(0,E.useCallback)(()=>t(),[t]);return e?null:n},Po=Mo(`ComposerPrimitive.Send`,No),Fo=(0,E.forwardRef)(({onSubmit:e,...t},n)=>{let r=No(),i=e=>{e.preventDefault(),r&&r()};return(0,L.jsx)(Q.form,{...t,ref:n,onSubmit:m(e,i)})});Fo.displayName=`ComposerPrimitive.Root`;function Io(){return Io=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Io.apply(null,arguments)}function Lo(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Ro=E.useLayoutEffect,zo=function(e){var t=E.useRef(e);return Ro(function(){t.current=e}),t},Bo=function(e,t){if(typeof e==`function`){e(t);return}e.current=t},Vo=function(e,t){var n=E.useRef();return E.useCallback(function(r){e.current=r,n.current&&Bo(n.current,null),n.current=t,t&&Bo(t,r)},[t])},Ho={"min-height":`0`,"max-height":`none`,height:`0`,visibility:`hidden`,overflow:`hidden`,position:`absolute`,"z-index":`-1000`,top:`0`,right:`0`,display:`block`},Uo=function(e){Object.keys(Ho).forEach(function(t){e.style.setProperty(t,Ho[t],`important`)})},$=null,Wo=function(e,t){var n=e.scrollHeight;return t.sizingStyle.boxSizing===`border-box`?n+t.borderSize:n-t.paddingSize};function Go(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),$||($=document.createElement(`textarea`),$.setAttribute(`tabindex`,`-1`),$.setAttribute(`aria-hidden`,`true`),Uo($)),$.parentNode===null&&document.body.appendChild($);var i=e.paddingSize,a=e.borderSize,o=e.sizingStyle,s=o.boxSizing;Object.keys(o).forEach(function(e){var t=e;$.style[t]=o[t]}),Uo($),$.value=t;var c=Wo($,e);$.value=t,c=Wo($,e),$.value=`x`;var l=$.scrollHeight-i,u=l*n;s===`border-box`&&(u=u+i+a),c=Math.max(u,c);var d=l*r;return s===`border-box`&&(d=d+i+a),c=Math.min(d,c),[c,l]}var Ko=function(){},qo=function(e,t){return e.reduce(function(e,n){return e[n]=t[n],e},{})},Jo=[`borderBottomWidth`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`boxSizing`,`fontFamily`,`fontSize`,`fontStyle`,`fontWeight`,`letterSpacing`,`lineHeight`,`paddingBottom`,`paddingLeft`,`paddingRight`,`paddingTop`,`tabSize`,`textIndent`,`textRendering`,`textTransform`,`width`,`wordBreak`,`wordSpacing`,`scrollbarGutter`],Yo=!!document.documentElement.currentStyle,Xo=function(e){var t=window.getComputedStyle(e);if(t===null)return null;var n=qo(Jo,t),r=n.boxSizing;return r===``?null:(Yo&&r===`border-box`&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+`px`),{sizingStyle:n,paddingSize:parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),borderSize:parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth)})};function Zo(e,t,n){var r=zo(n);E.useLayoutEffect(function(){var n=function(e){return r.current(e)};if(e)return e.addEventListener(t,n),function(){return e.removeEventListener(t,n)}},[])}var Qo=function(e,t){Zo(document.body,`reset`,function(n){e.current.form===n.target&&t(n)})},$o=function(e){Zo(window,`resize`,e)},es=function(e){Zo(document.fonts,`loadingdone`,e)},ts=[`cacheMeasurements`,`maxRows`,`minRows`,`onChange`,`onHeightChange`],ns=E.forwardRef(function(e,t){var n=e.cacheMeasurements,r=e.maxRows,i=e.minRows,a=e.onChange,o=a===void 0?Ko:a,s=e.onHeightChange,c=s===void 0?Ko:s,l=Lo(e,ts),u=l.value!==void 0,d=E.useRef(null),f=Vo(d,t),p=E.useRef(0),m=E.useRef(),h=function(){var e=d.current,t=n&&m.current?m.current:Xo(e);if(t){m.current=t;var a=Go(t,e.value||e.placeholder||`x`,i,r),o=a[0],s=a[1];p.current!==o&&(p.current=o,e.style.setProperty(`height`,o+`px`,`important`),c(o,{rowHeight:s}))}};return E.useLayoutEffect(h),Qo(d,function(){if(!u){var e=d.current.value;requestAnimationFrame(function(){var t=d.current;t&&e!==t.value&&h()})}}),$o(h),es(h),E.createElement(`textarea`,Io({},l,{onChange:function(e){u||h(),o(e)},ref:f}))}),rs=e=>{let t=l(e),n=Co(e=>e.onScrollToBottom);(0,E.useEffect)(()=>n(t),[n,t])},is=(0,E.createContext)(null),as=()=>(0,E.useContext)(is),os=(0,E.forwardRef)(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:i,onKeyDown:a,onPaste:s,onSelect:c,submitOnEnter:l,submitMode:u,cancelOnEscape:d=!0,unstable_focusOnRunStart:h=!0,unstable_focusOnScrollToBottom:ee=!0,unstable_focusOnThreadSwitched:te=!0,addAttachmentOnPaste:g=!0,..._},ne)=>{let v=B(),y=as(),re=u??(l===!1?`none`:`enter`),ie=V(e=>e.composer.isEditing?e.composer.text:``),b=V(e=>e.thread.isDisabled||e.composer.dictation?.inputDisabled)||r,x=(0,E.useRef)(null),S=f(ne,x);p(e=>{if(!x.current?.contains(e.target))return;if(y){for(let t of y.getPlugins())if(t.handleKeyDown(e))return}if(!d)return;let t=v.composer();t.getState().canCancel&&(t.cancel(),e.preventDefault())});let C=e=>{if(!b&&!e.nativeEvent.isComposing){if(y){for(let t of y.getPlugins())if(t.handleKeyDown(e))return}if(e.key===`Enter`){let t=v.thread().getState(),n=t.capabilities.queue;if(e.shiftKey&&(e.ctrlKey||e.metaKey)&&n&&re!==`none`&&!v.composer().getState().isEmpty){e.preventDefault(),v.composer().send({steer:!0});return}if(e.shiftKey||t.isRunning&&!n)return;let r=!1;re===`ctrlEnter`?r=e.ctrlKey||e.metaKey:re===`enter`&&(r=!0),r&&(e.preventDefault(),x.current?.closest(`form`)?.requestSubmit())}}},ae=async e=>{if(!g)return;let t=v.thread().getState().capabilities,n=Array.from(e.clipboardData?.files||[]);if(t.attachments&&n.length>0)try{e.preventDefault(),await Promise.all(n.map(e=>v.composer().addAttachment(e)))}catch(e){console.error(`Error adding attachment:`,e)}},w=e&&!b,T=(0,E.useCallback)(()=>{let e=x.current;!e||!w||(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[w]);(0,E.useEffect)(()=>T(),[T]),rs(()=>{v.composer().getState().type===`thread`&&ee&&T()}),(0,E.useEffect)(()=>{if(!(v.composer().getState().type!==`thread`||!h))return v.on(`thread.runStart`,T)},[h,T,v]),(0,E.useEffect)(()=>{if(!(v.composer().getState().type!==`thread`||!te))return v.on(`threadListItem.switchedTo`,T)},[te,T,v]);let oe={name:`input`,value:ie,..._,ref:S,disabled:b,onChange:m(i,e=>{if(!v.composer().getState().isEditing)return;Oe(()=>{v.composer().setText(e.target.value)});let t=e.target.selectionStart??e.target.value.length;if(y)for(let e of y.getPlugins())e.setCursorPosition(t)}),onKeyDown:m(a,C),onSelect:m(c,e=>{let t=e.target,n=t.selectionStart??t.value.length;if(y)for(let e of y.getPlugins())e.setCursorPosition(n)}),onPaste:m(s,ae)};if(n&&(0,E.isValidElement)(n)){let e=_.children===void 0?n.props.children:_.children;return(0,L.jsx)(o,{...oe,children:(0,E.cloneElement)(n,void 0,e)})}return(0,L.jsx)(t?o:ns,{...oe})});os.displayName=`ComposerPrimitive.Input`;var ss=()=>V(e=>{if(e.part.type!==`text`&&e.part.type!==`reasoning`)throw Error(`MessagePartText can only be used inside text or reasoning message parts.`);return e.part}),cs=(0,E.createContext)(null);function ls(e){let t=(0,E.useContext)(cs);if(!e?.optional&&!t)throw Error(`This component must be used within a SmoothContextProvider.`);return t}var{useSmoothStatus:us,useSmoothStatusStore:ds}=xo(ls,`useSmoothStatus`),fs=class{currentText;setText;animationFrameId=null;lastUpdateTime=Date.now();targetText=``;constructor(e,t){this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{let e=Date.now(),t=e-this.lastUpdateTime,n=this.targetText.length-this.currentText.length,r=Math.min(5,250/n),i=0;for(;t>=r&&i<n;)i++,t-=r;i===n?this.animationFrameId=null:this.animationFrameId=requestAnimationFrame(this.animate),i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-t,this.setText(this.currentText))}},ps=Object.freeze({type:`running`}),ms=(e,t=!1)=>{let{text:n}=e,r=V(e=>e.message.id),i=(0,E.useRef)(r),[a,o]=(0,E.useState)(e.status.type===`running`?``:n),s=ds({optional:!0}),c=l(t=>{if(o(t),s){let n=a!==t||e.status.type===`running`?ps:e.status;To(s).setState(n,!0)}});(0,E.useEffect)(()=>{if(s){let r=t&&(a!==n||e.status.type===`running`)?ps:e.status;To(s).setState(r,!0)}},[s,t,n,a,e.status]);let[u]=(0,E.useState)(new fs(a,c));return(0,E.useEffect)(()=>{if(!t){u.stop();return}if(i.current!==r||!n.startsWith(u.targetText)){i.current=r,e.status.type===`running`?(c(``),u.currentText=``,u.targetText=n,u.start()):(c(n),u.currentText=n,u.targetText=n,u.stop());return}u.targetText=n,u.start()},[c,u,r,t,n,e.status.type]),(0,E.useEffect)(()=>()=>{u.stop()},[u]),(0,E.useMemo)(()=>t?{type:`text`,text:a,status:n===a?e.status:ps}:e,[t,a,e,n])},hs=(0,E.forwardRef)(({smooth:e=!0,component:t=`span`,...n},r)=>{let{text:i,status:a}=ms(ss(),e);return(0,L.jsx)(t,{"data-status":a.type,...n,ref:r,children:i})});hs.displayName=`MessagePartPrimitive.Text`;var gs=()=>V(e=>{if(e.part.type!==`image`)throw Error(`MessagePartImage can only be used inside image message parts.`);return e.part}),_s=(0,E.forwardRef)((e,t)=>{let{image:n}=gs();return(0,L.jsx)(Q.img,{src:n,...e,ref:t})});_s.displayName=`MessagePartPrimitive.Image`;var vs=({children:e})=>V(e=>e.part.status.type===`running`)?e:null;vs.displayName=`MessagePartPrimitive.InProgress`;var ys=e=>{let t=(0,E.useRef)(void 0);return(0,E.useCallback)(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},bs=(e,t)=>ys((0,E.useCallback)(n=>{if(!e)return;let r=e(),i=()=>{let e=t?t(n):n.offsetHeight;r.setHeight(e)},a=new ResizeObserver(i);return a.observe(n),i(),()=>{a.disconnect(),r.unregister()}},[e,t])),xs=(0,E.createContext)(!1),Ss=(e,t)=>{let n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;let r=parseFloat(n[1]),i=n[2];return i===`px`?r:i===`em`?r*(parseFloat(getComputedStyle(t).fontSize)||16):i===`rem`?r*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):0},Cs=({children:e,fillClampThreshold:t=`10em`,fillClampOffset:n=`6em`})=>{let r=V(e=>e.message.isLast&&e.message.role===`assistant`&&e.message.index>=1&&e.thread.messages.at(e.message.index-1)?.role===`user`),i=wo({optional:!0}),a=(0,E.useContext)(xs),s=ys((0,E.useCallback)(e=>{if(!i||a)return;let o=()=>{let a=i.getState();if(a.turnAnchor===`top`&&r){let{viewport:r,inset:i,userMessage:o}=a.height,s=Ss(t,e),c=Ss(n,e),l=o<=s?o:c,u=Math.max(0,r-i-l);e.style.minHeight=`${u}px`,e.style.flexShrink=`0`,e.style.transition=`min-height 0s`}else e.style.minHeight=``,e.style.flexShrink=``,e.style.transition=``};return o(),i.subscribe(o)},[i,r,a,t,n]));return(0,L.jsx)(xs.Provider,{value:!0,children:(0,L.jsx)(o,{ref:s,children:e})})};Cs.displayName=`ThreadPrimitive.ViewportSlack`;var ws=()=>{let e=B(),t=V(()=>e.message());return ys((0,E.useCallback)(e=>{let n=()=>{t.setIsHovering(!0)},r=()=>{t.setIsHovering(!1)};return e.addEventListener(`mouseenter`,n),e.addEventListener(`mouseleave`,r),e.matches(`:hover`)&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{e.removeEventListener(`mouseenter`,n),e.removeEventListener(`mouseleave`,r),t.setIsHovering(!1)}},[t]))},Ts=()=>{let e=Co(e=>e.turnAnchor),t=Co(e=>e.registerUserMessageHeight),n=V(t=>e===`top`&&t.message.role===`user`&&t.message.index===t.thread.messages.length-2&&t.thread.messages.at(-1)?.role===`assistant`),r=(0,E.useCallback)(e=>e.offsetHeight,[]);return bs(n?t:null,r)},Es=(0,E.forwardRef)(({fillClampThreshold:e,fillClampOffset:t,...n},r)=>{let i=f(r,ws(),Ts()),a=V(e=>e.message.id);return(0,L.jsx)(Cs,{fillClampThreshold:e,fillClampOffset:t,children:(0,L.jsx)(Q.div,{...n,ref:i,"data-message-id":a})})});Es.displayName=`MessagePrimitive.Root`;var Ds={...Z,Text:()=>(0,L.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,L.jsx)(hs,{}),(0,L.jsx)(vs,{children:(0,L.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Image:()=>(0,L.jsx)(_s,{})},Os=e=>{if(`children`in e)return(0,L.jsx)(fo,{children:e.children});let{components:t,...n}=e;return(0,L.jsx)(fo,{components:t?{Text:t.Text??Ds.Text,Image:t.Image??Ds.Image,Reasoning:t.Reasoning??Z.Reasoning,Source:t.Source??Z.Source,File:t.File??Z.File,Unstable_Audio:t.Unstable_Audio??Z.Unstable_Audio,...`ChainOfThought`in t?{ChainOfThought:t.ChainOfThought}:{tools:t.tools,data:t.data,ToolGroup:t.ToolGroup??Z.ToolGroup,ReasoningGroup:t.ReasoningGroup??Z.ReasoningGroup},Empty:t.Empty,Quote:t.Quote}:Ds,...n})};Os.displayName=`MessagePrimitive.Parts`;var ks=(0,E.forwardRef)((e,t)=>(0,L.jsx)(Q.div,{...e,ref:t}));ks.displayName=`ThreadPrimitive.Root`;var As=({children:e})=>V(e=>e.thread.isEmpty)?e:null;As.displayName=`ThreadPrimitive.Empty`;var js=e=>{let t=l(e);return ys((0,E.useCallback)(e=>{let n=new ResizeObserver(()=>{t()}),r=new MutationObserver(e=>{e.some(e=>e.type!==`attributes`||e.attributeName!==`style`)&&t()});return n.observe(e),r.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{n.disconnect(),r.disconnect()}},[t]))},Ms=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{let i=(0,E.useRef)(null),a=wo();e===void 0&&(e=a.getState().turnAnchor!==`top`);let o=(0,E.useRef)(0),s=(0,E.useRef)(null),c=(0,E.useCallback)(e=>{let t=i.current;t&&(s.current=e,t.scrollTo({top:t.scrollHeight,behavior:e}))},[]),l=()=>{let e=i.current;if(!e)return;let t=a.getState().isAtBottom,n=Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<1||e.scrollHeight<=e.clientHeight;!n&&o.current<e.scrollTop||(n&&(s.current=null),(n||s.current===null)&&n!==t&&To(a).setState({isAtBottom:n})),o.current=e.scrollTop},u=js(()=>{let t=s.current;t?c(t):e&&a.getState().isAtBottom&&c(`instant`),l()}),d=ys(e=>(e.addEventListener(`scroll`,l),()=>{e.removeEventListener(`scroll`,l)}));return rs(({behavior:e})=>{c(e)}),Mt(`thread.runStart`,()=>{t&&(s.current=`auto`,requestAnimationFrame(()=>{c(`auto`)}))}),Mt(`thread.initialize`,()=>{n&&(s.current=`instant`,requestAnimationFrame(()=>{c(`instant`)}))}),Mt(`threadListItem.switchedTo`,()=>{r&&(s.current=`instant`,requestAnimationFrame(()=>{c(`instant`)}))}),f(u,d,i)},Ns=()=>bs(Co(e=>e.registerViewport),(0,E.useCallback)(e=>e.clientHeight,[])),Ps=(0,E.forwardRef)(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:i,...a},o)=>{let s=f(o,Ms({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),Ns());return(0,L.jsx)(Q.div,{...a,ref:s,children:i})});Ps.displayName=`ThreadPrimitive.ViewportScrollable`;var Fs=(0,E.forwardRef)(({turnAnchor:e,...t},n)=>(0,L.jsx)(Do,{options:{turnAnchor:e},children:(0,L.jsx)(Ps,{...t,ref:n})}));Fs.displayName=`ThreadPrimitive.Viewport`;var Is=Mo(`ThreadPrimitive.Suggestion`,({prompt:e,send:t,clearComposer:n,autoSend:r,method:i})=>{let{disabled:a,trigger:o}=ho({prompt:e,send:t??r??!1,clearComposer:n});return a?null:o},[`prompt`,`send`,`clearComposer`,`autoSend`,`method`]),Ls=`/api/strategist/stream`;function Rs(){return{async*run({messages:e,abortSignal:t}){let n=[];for(let t of e){if(t.role!==`user`&&t.role!==`assistant`)continue;let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(``);e.length!==0&&n.push({role:t.role,content:e})}let r;try{r=await fetch(Ls,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({messages:n}),signal:t})}catch(e){yield{content:[{type:`text`,text:`Error contacting strategist: ${e.message}`}]};return}if(!r.ok){let e=``;try{e=(await r.json()).error??``}catch{e=await r.text().catch(()=>``)}yield{content:[{type:`text`,text:`Error: ${e||`${r.status} ${r.statusText}`}`}]};return}let i=r.body?.getReader();if(!i){yield{content:[{type:`text`,text:`Error: no response stream`}]};return}let a=new TextDecoder,o=``,s=``;for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
4
+
5
+ `);o=n.pop()??``;for(let e of n){let t=zs(e);if(t){if(t.kind===`delta`)s+=t.text,yield{content:[{type:`text`,text:s}]};else if(t.kind===`error`)s+=`\n\nError: ${t.message}`,yield{content:[{type:`text`,text:s}]};else if(t.kind===`done`)return}}}}}}function zs(e){let t=``,n=``;for(let r of e.split(`
6
+ `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)&&(n=r.slice(6));if(!t||!n)return null;try{return JSON.parse(n)}catch{return null}}var Bs=/<!--ACTION:(enable|disable|apply-config):([^:>]+?)(?::([\s\S]*?))?-->/,Vs=/<!--ACTION:[\s\S]*$/;function Hs(e){let t=e.match(Bs);if(!t)return null;let n=t[1],r=(t[2]??``).trim();if(!r)return null;let i=t[3]??``;if(n===`apply-config`)try{let e=JSON.parse(i);return!e||typeof e!=`object`||Array.isArray(e)?null:{kind:n,trigger:r,config:e}}catch{return null}return{kind:n,trigger:r}}function Us(e){return e.replace(Bs,``).replace(Vs,``).trim()}var Ws=[`Which triggers fit my ICP?`,`Propose github-topics topics + vendors`,`Pick an accelerator-batch cohort for my ICP`,`Audit my current trigger config`];function Gs({open:e,onClose:t}){return(0,L.jsxs)(ko,{runtime:_o((0,E.useMemo)(()=>Rs(),[])),children:[e&&(0,L.jsx)(`div`,{className:`fixed inset-0 z-40 bg-ink-bg/60 backdrop-blur-sm`,onClick:t,"aria-hidden":`true`}),(0,L.jsxs)(`aside`,{className:`fixed right-0 top-0 z-50 flex h-full w-full flex-col border-l border-ink-rule bg-ink-bg-deep shadow-2xl transition-transform duration-200 sm:w-[440px] `+(e?`translate-x-0`:`translate-x-full`),"aria-hidden":!e,children:[(0,L.jsx)(Ks,{onClose:t}),(0,L.jsx)(qs,{})]})]})}function Ks({onClose:e}){return(0,L.jsxs)(`div`,{className:`flex items-center justify-between border-b border-ink-rule px-5 py-3`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(u,{size:14,className:`text-ink-cream-2`}),(0,L.jsx)(`div`,{className:`ln-eyebrow`,children:`Strategist`})]}),(0,L.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Close strategist`,className:`cursor-pointer rounded-full p-1 text-ink-faint transition-colors hover:bg-ink-surface hover:text-ink-cream`,children:(0,L.jsx)(a,{size:14})})]})}function qs(){return(0,L.jsxs)(ks,{className:`flex h-full min-h-0 flex-col`,children:[(0,L.jsx)(As,{children:(0,L.jsx)(`div`,{className:`border-b border-ink-rule/60 px-5 py-4`,children:(0,L.jsx)(`p`,{className:`text-sm text-ink-cream-2`,children:`Tell me what to set up. I'll propose configs anchored in your ICP + product and ask before applying anything. Try a chip below or ask anything.`})})}),(0,L.jsx)(Fs,{className:`flex-1 space-y-3 overflow-y-auto px-5 py-4`,children:(0,L.jsx)(Va,{components:{UserMessage:Js,AssistantMessage:Ys}})}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 border-t border-ink-rule/60 px-5 py-2`,children:Ws.map(e=>(0,L.jsx)(Is,{prompt:e,send:!0,className:`cursor-pointer rounded-full border border-ink-rule px-3 py-1 font-mono text-[10px] uppercase tracking-wider text-ink-muted transition-colors hover:border-ink-rule-2 hover:text-ink-cream-2`,children:e},e))}),(0,L.jsx)(`div`,{className:`border-t border-ink-rule px-5 py-3`,children:(0,L.jsxs)(Fo,{className:`flex items-center gap-2`,children:[(0,L.jsx)(os,{placeholder:`Ask the strategist...`,className:`flex-1 rounded-[var(--radius-sm)] border border-ink-rule bg-ink-bg px-3 py-2 font-mono text-[13px] text-ink-cream outline-none placeholder:text-ink-faint focus:border-ink-rule-2`}),(0,L.jsx)(Po,{asChild:!0,children:(0,L.jsx)(h,{size:`sm`,variant:`primary`,children:`Send`})})]})})]})}function Js(){return(0,L.jsx)(Es,{className:`flex justify-end`,children:(0,L.jsx)(`div`,{className:`max-w-[80%] rounded-[var(--radius-sm)] border border-ink-rule bg-ink-surface px-3 py-2`,children:(0,L.jsx)(Os,{components:{Text:({text:e})=>(0,L.jsx)(`p`,{className:`whitespace-pre-wrap text-sm text-ink-cream`,children:e})}})})})}function Ys(){return(0,L.jsx)(Es,{className:`flex justify-start`,children:(0,L.jsx)(`div`,{className:`max-w-[90%] rounded-[var(--radius-sm)] border border-ink-rule bg-ink-surface px-3 py-2`,children:(0,L.jsx)(Os,{components:{Text:({text:e})=>(0,L.jsx)(Xs,{text:e})}})})})}function Xs({text:e}){let t=Hs(e);return(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`p`,{className:`whitespace-pre-wrap text-sm leading-relaxed text-ink-cream-2`,children:Us(e)}),t&&(0,L.jsx)(Zs,{action:t})]})}function Zs({action:t}){let n=s(),[r,i]=(0,E.useState)(!1),[a,o]=(0,E.useState)(null),[l,u]=(0,E.useState)(null),d=(0,E.useCallback)(async()=>{i(!0),u(null);try{t.kind===`enable`?(await e.setTriggerEnabled(t.trigger,!0),o(`enabled · ${t.trigger}`),c.success(`enabled · ${t.trigger}`)):t.kind===`disable`?(await e.setTriggerEnabled(t.trigger,!1),o(`disabled · ${t.trigger}`),c.success(`disabled · ${t.trigger}`)):t.kind===`apply-config`&&t.config&&(await e.setTriggerConfig(t.trigger,t.config),o(`config saved · ${t.trigger}`),c.success(`config saved · ${t.trigger}`)),n.invalidateQueries({queryKey:[`triggers`]}),n.invalidateQueries({queryKey:[`queue`]})}catch(e){u(e.message)}finally{i(!1)}},[t,n]);if(a)return(0,L.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 rounded-[var(--radius-sm)] border border-ink-rule bg-ink-bg-deep px-2.5 py-1.5 font-mono text-[11px] text-ink-receipt-2`,children:[`✓ `,a]});let f=t.kind===`enable`?`Enable ${t.trigger}`:t.kind===`disable`?`Disable ${t.trigger}`:`Apply config to ${t.trigger}`;return(0,L.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,L.jsx)(`button`,{onClick:d,disabled:r,className:`cursor-pointer rounded-[var(--radius-sm)] border border-ink-rule bg-ink-surface px-3 py-1.5 font-mono text-[11px] text-ink-cream transition-colors hover:border-ink-rule-2 disabled:cursor-not-allowed disabled:opacity-60`,children:r?`Applying…`:f}),l&&(0,L.jsxs)(`span`,{className:`font-mono text-[11px] text-ink-blocked-2`,children:[`err: `,l]})]})}export{Gs as default};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,o as n,r,s as i,t as a,u as o}from"./cn-CS0Arupu.js";import{t as s}from"./chevron-down-CDjJN-YY.js";import{t as ee}from"./send-Bv2Dd-HU.js";import{b as te,c,v as l,y as ne}from"./index-B_nrqLlS.js";import{t as u}from"./Button-C-XcKplu.js";import{t as d}from"./Badge-B2tW85qr.js";import{t as re}from"./EmptyNote-zvLnRLPo.js";import{a as ie,i as ae,n as f,r as oe}from"./Field-BxSk5tbg.js";import{t as p}from"./Modal-CU0ZPvE2.js";import{n as se}from"./Skeleton-DNAfO8PV.js";var ce=n(`circle-stop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),m=n(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),le=n(`trophy`,[[`path`,{d:`M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978`,key:`1n3hpd`}],[`path`,{d:`M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978`,key:`rfe1zi`}],[`path`,{d:`M18 9h1.5a1 1 0 0 0 0-5H18`,key:`7xy6bh`}],[`path`,{d:`M4 22h16`,key:`57wxv0`}],[`path`,{d:`M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z`,key:`1mhfuq`}],[`path`,{d:`M6 9H4.5a1 1 0 0 1 0-5H6`,key:`tex48p`}]]),h=o(t()),g=i();function _({current:e,total:t,tone:n=`neutral`,className:r}){if(t<=0)return(0,g.jsx)(`span`,{className:a(`font-mono text-[11px] text-ink-faint`,r),children:`—`});let i=Array.from({length:t},(t,n)=>n<e),o={neutral:`var(--ink-cream-2)`,receipt:`var(--ink-receipt)`,signal:`var(--ink-signal)`,spend:`var(--ink-spend)`,blocked:`var(--ink-blocked)`}[n]??`var(--ink-cream-2)`;return(0,g.jsx)(`span`,{className:a(`inline-flex items-center gap-1`,r),"aria-label":`step ${e} of ${t}`,title:`step ${e} of ${t}`,children:i.map((e,t)=>(0,g.jsx)(`span`,{"aria-hidden":`true`,className:a(`h-[6px] w-[6px] rounded-full`),style:{background:e?o:`transparent`,border:e?`none`:`1px solid var(--ink-rule)`}},t))})}function ue(e){if(!e)return`now`;let t=new Date(e).getTime()-Date.now();if(t<=0)return`now`;let n=Math.round(t/6e4);if(n<60)return`${n}m early`;let r=Math.round(t/36e5);return r<36?`${r}h early`:`${Math.round(t/864e5)}d early`}function de(e){switch(e){case`active`:return`receipt`;case`replied`:return`signal`;case`breakup`:return`spend`;case`completed`:return`neutral`;default:return`neutral`}}var v=e=>`${e.prospectId}|${e.playName}`;function y(){let t=te(),[n,i]=(0,h.useState)(!1),[o,y]=(0,h.useState)(null),[S,fe]=(0,h.useState)(`meeting_booked`),[C,w]=(0,h.useState)(``),[T,E]=(0,h.useState)(``),D=ne({queryKey:[`cadences`,n],queryFn:()=>e.cadences(n),refetchInterval:15e3}),O=l({mutationFn:t=>e.stopCadence(t.prospectId,t.playName),onSuccess:(e,n)=>{t.invalidateQueries({queryKey:[`cadences`]}),c.success(`stopped cadence · ${n.playName}`)},onError:e=>c.error(`couldn't stop cadence: ${e.message}`)}),k=l({mutationFn:t=>e.previewCadenceNext(t.prospectId,t.playName),onSuccess:(e,n)=>{t.invalidateQueries({queryKey:[`cadences`]}),P(e=>new Set([...e,`${n.prospectId}|${n.playName}`])),c.success(`drafted next step · ${n.playName}${e.flags.length>0?` (${e.flags.length} flag(s))`:``}`)},onError:e=>c.error(`preview failed: ${e.message}`)}),A=l({mutationFn:t=>e.sendCadenceNext(t.prospectId,t.playName),onSuccess:(e,n)=>{t.invalidateQueries({queryKey:[`cadences`]}),t.invalidateQueries({queryKey:[`receipts`]}),P(e=>{let t=new Set(e);return t.delete(`${n.prospectId}|${n.playName}`),t}),V(null),c.success(`sending · ${n.playName} — refreshes when complete`)},onError:e=>c.error(`send failed: ${e.message}`)}),j=l({mutationFn:t=>e.previewCadenceBatch(t),onSuccess:e=>{t.invalidateQueries({queryKey:[`cadences`]});let n=e.results.filter(e=>e.ok),r=e.results.length-n.length;P(e=>new Set([...e,...n.map(e=>`${e.prospectId}|${e.playName}`)]));let i=r>0?` · ${r} skipped`:``;c.success(`previewed ${n.length}${i}`)},onError:e=>c.error(`bulk preview failed: ${e.message}`)}),M=l({mutationFn:t=>e.sendCadenceBatch(t),onSuccess:e=>{t.invalidateQueries({queryKey:[`cadences`]}),I(new Set),L(!1),c.success(`started send of ${e.accepted} — drafts will clear as each completes`)},onError:e=>c.error(`bulk send failed: ${e.message}`)}),[N,P]=(0,h.useState)(new Set),[F,I]=(0,h.useState)(new Set),[pe,L]=(0,h.useState)(!1),R=e=>P(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),z=e=>I(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[B,V]=(0,h.useState)(null),H=k.isPending&&k.variables?`${k.variables.prospectId}|${k.variables.playName}`:null,U=A.isPending&&A.variables?`${A.variables.prospectId}|${A.variables.playName}`:null,W=l({mutationFn:async()=>{if(!o)throw Error(`no modal open`);let t={email:o.email,outcome:S,playName:o.playName,...C?{amountUsd:Number.parseFloat(C)}:{},...T?{notes:T}:{}};return await e.recordOutcome(t)},onSuccess:()=>{y(null),w(``),E(``),t.invalidateQueries({queryKey:[`measure`]}),c.success(`outcome logged · ${S}`)},onError:e=>c.error(`couldn't log outcome: ${e.message}`)}),G=(0,h.useMemo)(()=>D.data?.cadences??[],[D.data]),K=(0,h.useMemo)(()=>x(G,n),[G,n]),q=new Date().toISOString(),J=(0,h.useMemo)(()=>G.filter(e=>e.status===`active`),[G]),Y=J.length>0&&J.every(e=>F.has(v(e))),me=J.some(e=>F.has(v(e)))&&!Y,X=(0,h.useMemo)(()=>G.filter(e=>F.has(v(e))&&e.status===`active`),[G,F]),Z=(0,h.useMemo)(()=>X.filter(e=>e.nextStepDraft!=null&&e.nextStepDraft.flags.length===0&&!e.isSending),[X]),Q=Z.filter(e=>e.nextDueAt!=null&&e.nextDueAt>q).length,$=Z.filter(e=>e.nextStepIsBreakup).length;return(0,g.jsxs)(`div`,{className:`-mx-6 -my-6 flex flex-col`,children:[(0,g.jsxs)(`section`,{className:`flex items-end justify-between gap-4 border-b border-ink-rule px-6 pb-5 pt-6`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`div`,{className:`ln-eyebrow`,children:`The Ledger · Cadences`}),(0,g.jsx)(`h1`,{className:`mt-1 text-ink-cream`,style:{fontFamily:`var(--font-display)`,fontSize:44,fontWeight:600,letterSpacing:`-0.025em`,lineHeight:.98},children:`Prospects, in flight.`})]}),(0,g.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,g.jsx)(u,{variant:n?`secondary`:`primary`,size:`sm`,onClick:()=>i(!1),children:`Active`}),(0,g.jsx)(u,{variant:n?`primary`:`secondary`,size:`sm`,onClick:()=>i(!0),children:`All`})]})]}),(0,g.jsxs)(`section`,{className:`grid grid-cols-2 divide-x divide-ink-rule border-b border-ink-rule md:grid-cols-4`,children:[(0,g.jsx)(b,{label:`Active`,value:K.active,caption:K.overdue>0?`${K.overdue} overdue`:`awaiting reply`,tone:K.overdue>0?`spend`:`receipt`}),(0,g.jsx)(b,{label:`Replied`,value:K.replied,caption:`signal over noise`,tone:`signal`}),(0,g.jsx)(b,{label:`Breakup`,value:K.breakup,caption:`final touch sent`,tone:`spend`}),(0,g.jsx)(b,{label:`Completed`,value:K.completed,caption:`full cadence done`})]}),(0,g.jsxs)(`section`,{className:`flex items-baseline justify-between border-b border-ink-rule px-6 py-2.5`,children:[(0,g.jsx)(`div`,{className:`ln-eyebrow`,children:D.data?(0,g.jsxs)(g.Fragment,{children:[G.length,` `,(0,g.jsx)(`span`,{className:`text-ink-faint`,children:n?`total`:`active`})]}):(0,g.jsx)(`span`,{className:`text-ink-faint`,children:`…`})}),(0,g.jsx)(`div`,{className:`font-mono text-[11px] text-ink-faint`,children:`refresh · 15s`})]}),X.length>0&&(0,g.jsxs)(`section`,{className:`flex items-center justify-between gap-3 border-b border-ink-rule bg-ink-surface/40 px-6 py-2.5`,children:[(0,g.jsxs)(`div`,{className:`font-mono text-[12px] text-ink-cream-2`,children:[(0,g.jsx)(`span`,{className:`text-ink-cream`,children:X.length}),` selected`,Z.length!==X.length&&(0,g.jsxs)(`span`,{className:`ml-2 text-[color:var(--ink-spend-2)]`,children:[`· `,Z.length,` sendable (others need preview / have flags)`]})]}),(0,g.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,g.jsx)(u,{variant:`secondary`,size:`sm`,disabled:j.isPending||M.isPending,onClick:()=>j.mutate(X.map(e=>({prospectId:e.prospectId,playName:e.playName}))),children:j.isPending?`Previewing ${X.length}…`:`Preview ${X.length}`}),(0,g.jsx)(u,{variant:`primary`,size:`sm`,disabled:Z.length===0||M.isPending,onClick:()=>L(!0),children:M.isPending?`Sending…`:`Send ${Z.length}${Z.length===X.length?``:` of ${X.length}`}`}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,onClick:()=>I(new Set),children:`Clear`})]})]}),(0,g.jsx)(`section`,{children:D.isLoading?(0,g.jsx)(`div`,{children:Array.from({length:5},(e,t)=>(0,g.jsx)(se,{},t))}):G.length===0?(0,g.jsx)(`div`,{className:`px-6 py-8`,children:(0,g.jsx)(re,{note:`No cadences in flight. The engine only runs for prospects you've already touched; send a play and they appear here.`,cli:`oneshot-gtm motion show-hn --target show-hn.json`})}):(0,g.jsxs)(`table`,{className:`w-full text-[13px]`,children:[(0,g.jsx)(`thead`,{className:`sticky top-0 z-10 bg-ink-bg`,children:(0,g.jsxs)(`tr`,{className:`border-b border-ink-rule text-[10px] uppercase tracking-[0.14em] text-ink-faint`,children:[(0,g.jsx)(`th`,{className:`px-3 py-2 text-left font-medium`,style:{width:32},children:(0,g.jsx)(`input`,{type:`checkbox`,"aria-label":Y?`deselect all active cadences`:`select all active cadences`,title:J.length===0?`no active rows to select`:Y?`deselect all active`:`select all active`,disabled:J.length===0,checked:Y,ref:e=>{e&&(e.indeterminate=me)},onChange:()=>{I(e=>{if(Y){let t=new Set(e);for(let e of J)t.delete(v(e));return t}return new Set([...e,...J.map(v)])})},className:`cursor-pointer`})}),(0,g.jsx)(`th`,{className:`px-6 py-2 text-left font-medium`,children:`prospect`}),(0,g.jsx)(`th`,{className:`py-2 text-left font-medium`,children:`play`}),(0,g.jsx)(`th`,{className:`py-2 text-left font-medium`,children:`status`}),(0,g.jsx)(`th`,{className:`py-2 text-left font-medium`,children:`step`}),(0,g.jsx)(`th`,{className:`py-2 text-right font-medium`,children:`next due`}),(0,g.jsx)(`th`,{className:`py-2 text-right font-medium`,children:`enrolled`}),(0,g.jsx)(`th`,{className:`px-6 py-2 text-right font-medium`,children:`actions`})]})}),(0,g.jsx)(`tbody`,{children:G.map((e,t)=>{let n=e.followupCount+1,i=e.status===`active`&&e.nextDueAt!==null&&e.nextDueAt<=q,o=e.priorSteps.length>0||e.nextStepDraft!=null;return(0,g.jsxs)(h.Fragment,{children:[(0,g.jsxs)(`tr`,{onClick:o?t=>{t.target.closest(`button, input, a, label, [role='button']`)||R(v(e))}:void 0,className:a(`border-b border-ink-rule/60 transition-colors duration-[var(--dur-stamp)]`,`hover:bg-ink-surface/60`,t%2==1&&`bg-ink-surface/20`,o&&`cursor-pointer`),children:[(0,g.jsx)(`td`,{className:`px-3 py-2`,style:{width:32},children:(0,g.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${e.prospectName??e.prospectEmail??`row`}`,title:e.status===`active`?`select for batch preview / send`:`only active cadences can be selected (status: ${e.status})`,disabled:e.status!==`active`,checked:F.has(v(e)),onChange:()=>z(v(e)),className:`cursor-pointer disabled:cursor-not-allowed disabled:opacity-30`})}),(0,g.jsxs)(`td`,{className:`px-6 py-2`,children:[(0,g.jsx)(`div`,{className:`text-ink-cream`,children:e.prospectName??`(unknown)`}),(0,g.jsx)(`div`,{className:`font-mono text-[11px] text-ink-faint`,children:e.prospectEmail??`—`})]}),(0,g.jsx)(`td`,{className:`py-2 text-ink-cream-2`,children:e.playName}),(0,g.jsxs)(`td`,{className:`py-2`,children:[(0,g.jsx)(d,{tone:de(e.status),children:e.status}),e.isSending&&(0,g.jsx)(d,{tone:`receipt`,className:`ml-1.5 animate-pulse`,children:`sending…`})]}),(0,g.jsx)(`td`,{className:`py-2`,children:(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsx)(_,{current:Math.min(e.currentStep+1,n),total:n,tone:e.status===`replied`?`signal`:e.status===`breakup`?`spend`:`receipt`}),(0,g.jsxs)(`span`,{className:`font-mono text-[11px] text-ink-faint`,children:[e.currentStep+1,`/`,n]})]})}),(0,g.jsxs)(`td`,{className:a(`py-2 text-right font-mono text-[12px]`,i?`text-[color:var(--ink-spend-2)]`:`text-ink-muted`),children:[r(e.nextDueAt),i&&(0,g.jsx)(`span`,{className:`ml-1 text-[10px]`,children:`· overdue`})]}),(0,g.jsx)(`td`,{className:`py-2 text-right font-mono text-[11px] text-ink-faint`,children:r(e.enrolledAt)}),(0,g.jsx)(`td`,{className:`px-6 py-2 text-right`,children:(0,g.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[e.status===`active`&&(()=>{let t=`${e.prospectId}|${e.playName}`,n=e.nextStepDraft,i=!n||n.flags.length>0||U!=null||H!=null||e.isSending;return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(u,{variant:`ghost`,size:`sm`,title:n?`re-preview next step (current preview drafted ${r(n.draftedAt)})`:`preview next step (LLM draft, no send)`,disabled:H!=null,onClick:()=>k.mutate({prospectId:e.prospectId,playName:e.playName}),children:(0,g.jsx)(m,{size:12})}),(0,g.jsx)(u,{variant:i?`ghost`:`primary`,size:`sm`,title:n?n.flags.length>0?`draft held by lint (${n.flags.length} flag(s)) — re-preview`:e.nextStepIsBreakup?`send breakup (final touch) — confirms first`:`send next step — confirms first`:`click Preview first`,disabled:i,onClick:()=>{n&&V({prospectId:e.prospectId,playName:e.playName,prospectEmail:e.prospectEmail,prospectName:e.prospectName,subject:n.subject,isBreakup:e.nextStepIsBreakup,nextDueAt:e.nextDueAt,isEarly:e.nextDueAt!=null&&e.nextDueAt>new Date().toISOString()})},children:(0,g.jsx)(ee,{size:12})}),(n||e.priorSteps.length>0)&&(0,g.jsx)(u,{variant:`ghost`,size:`sm`,title:N.has(t)?`collapse`:e.priorSteps.length>0&&n?`view ${e.priorSteps.length} sent + next-step preview`:e.priorSteps.length>0?`view ${e.priorSteps.length} sent so far`:`view next-step preview`,onClick:()=>R(t),children:(0,g.jsx)(s,{size:12,className:a(`transition-transform`,N.has(t)&&`rotate-180`)})}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,title:`stop cadence`,disabled:O.isPending,onClick:()=>O.mutate({prospectId:e.prospectId,playName:e.playName}),children:(0,g.jsx)(ce,{size:12})})]})})(),e.status!==`active`&&e.priorSteps.length>0&&(()=>{let t=`${e.prospectId}|${e.playName}`;return(0,g.jsx)(u,{variant:`ghost`,size:`sm`,title:N.has(t)?`collapse`:`view ${e.priorSteps.length} sent so far`,onClick:()=>R(t),children:(0,g.jsx)(s,{size:12,className:a(`transition-transform`,N.has(t)&&`rotate-180`)})})})(),e.prospectEmail&&(0,g.jsx)(u,{variant:`ghost`,size:`sm`,title:`log outcome`,onClick:()=>y({email:e.prospectEmail,prospectName:e.prospectName,playName:e.playName}),children:(0,g.jsx)(le,{size:12})})]})})]}),(e.priorSteps.length>0||e.nextStepDraft)&&N.has(v(e))&&(0,g.jsx)(`tr`,{className:`border-b border-ink-rule/60 bg-ink-surface/30`,children:(0,g.jsxs)(`td`,{colSpan:8,className:`px-6 py-3`,children:[e.priorSteps.length>0&&(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(`div`,{className:`ln-eyebrow mb-1`,children:[`Sent so far (`,e.priorSteps.length,`)`]}),(0,g.jsx)(`div`,{className:`flex flex-col gap-3`,children:e.priorSteps.map(e=>(0,g.jsxs)(`div`,{className:`border-l-2 border-ink-rule pl-3`,children:[(0,g.jsxs)(`div`,{className:`font-mono text-[11px] text-ink-faint`,children:[`step `,e.stepIndex,` (`,e.label,`) · sent `,r(e.sentAt)]}),(0,g.jsxs)(`div`,{className:`mt-1 font-mono text-[12px] text-ink-cream`,children:[`Subject: `,e.subject]}),e.body?(0,g.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap text-[12px] text-ink-cream-2`,children:e.body}):(0,g.jsx)(`div`,{className:`mt-1 font-mono text-[11px] italic text-ink-faint`,children:`(body not captured — sent before per-touch body persistence landed)`})]},e.stepIndex))})]}),e.nextStepDraft&&(0,g.jsxs)(`div`,{className:e.priorSteps.length>0?`mt-5`:``,children:[(0,g.jsx)(`div`,{className:`ln-eyebrow mb-1`,children:`Next-step preview`}),(0,g.jsxs)(`div`,{className:`font-mono text-[11px] text-ink-faint`,children:[`drafted `,r(e.nextStepDraft.draftedAt),e.nextStepDraft.flags.length>0&&(0,g.jsxs)(`span`,{className:`ml-2 text-[color:var(--ink-spend-2)]`,children:[`· `,e.nextStepDraft.flags.length,` flag(s):`,` `,e.nextStepDraft.flags.join(`, `)]})]}),(0,g.jsxs)(`div`,{className:`mt-2 font-mono text-[12px] text-ink-cream`,children:[`Subject: `,e.nextStepDraft.subject]}),(0,g.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap text-[12px] text-ink-cream-2`,children:e.nextStepDraft.body})]})]})})]},`${e.prospectId}-${e.playName}`)})})]})}),(0,g.jsx)(p,{open:pe,onClose:()=>L(!1),title:`Send ${Z.length} cadence step${Z.length===1?``:`s`}`,footer:(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(u,{variant:`ghost`,onClick:()=>L(!1),children:`Cancel`}),(0,g.jsx)(u,{onClick:()=>M.mutate(Z.map(e=>({prospectId:e.prospectId,playName:e.playName}))),disabled:M.isPending||Z.length===0,children:M.isPending?`Sending…`:`Send ${Z.length}`})]}),children:(0,g.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[$>0&&(0,g.jsx)(`div`,{className:`rounded border border-ink-rule bg-ink-surface/40 px-3 py-2 text-[12px] text-[color:var(--ink-spend-2)]`,children:$===Z.length?`All selected steps are breakups — the final touch in their cadences. After this, no more emails will go to these prospects.`:`${$} of ${Z.length} selected steps are breakups — the final touch in their cadences. After this, no more emails will go to those prospects.`}),Q>0&&(0,g.jsx)(`div`,{className:`rounded border border-ink-rule bg-ink-surface/40 px-3 py-2 text-[12px] text-ink-cream-2`,children:Q===Z.length?`All selected steps are scheduled for a future date. Sending now fires them ahead of schedule; remaining cadence steps will recompute from today.`:`${Q} of ${Z.length} selected steps are scheduled for a future date and will fire ahead of schedule.`}),(0,g.jsxs)(`div`,{className:`ln-eyebrow text-[10px] text-ink-faint`,children:[`Targets (`,Z.length,`)`]}),(0,g.jsx)(`div`,{className:`max-h-72 overflow-auto rounded border border-ink-rule`,children:(0,g.jsxs)(`table`,{className:`w-full text-[11px]`,children:[(0,g.jsx)(`thead`,{className:`bg-ink-surface/30`,children:(0,g.jsxs)(`tr`,{className:`text-ink-faint`,children:[(0,g.jsx)(`th`,{className:`px-2 py-1 text-left font-medium`,children:`To`}),(0,g.jsx)(`th`,{className:`px-2 py-1 text-left font-medium`,children:`Play`}),(0,g.jsx)(`th`,{className:`px-2 py-1 text-left font-medium`,children:`Subject`})]})}),(0,g.jsx)(`tbody`,{children:Z.map(e=>(0,g.jsxs)(`tr`,{className:`border-t border-ink-rule/40`,children:[(0,g.jsx)(`td`,{className:`px-2 py-1 font-mono text-ink-cream-2`,children:e.prospectEmail??`(no email)`}),(0,g.jsx)(`td`,{className:`px-2 py-1 text-ink-cream-2`,children:e.playName}),(0,g.jsx)(`td`,{className:`px-2 py-1 text-ink-cream-2`,children:e.nextStepDraft?.subject??`(no subject)`})]},v(e)))})]})}),(0,g.jsx)(`div`,{className:`ln-eyebrow text-[10px] text-ink-faint`,children:`Server processes serially; ~2 min per email. The UI refreshes every 15s and rows clear their preview as each completes.`})]})}),(0,g.jsx)(p,{open:B!=null,onClose:()=>V(null),title:B?.isBreakup?`Send breakup — ${B?.prospectName??B?.prospectEmail??`(prospect)`}`:`Send next step — ${B?.prospectName??B?.prospectEmail??`(prospect)`}`,footer:(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(u,{variant:`ghost`,onClick:()=>V(null),children:`Cancel`}),(0,g.jsx)(u,{onClick:()=>{B&&A.mutate({prospectId:B.prospectId,playName:B.playName},{onSettled:()=>V(null)})},disabled:A.isPending,children:A.isPending?`Sending…`:B?.isBreakup?`Send breakup`:`Send`})]}),children:(0,g.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[B?.isEarly&&B.nextDueAt&&(0,g.jsxs)(`div`,{className:`rounded border border-ink-rule bg-ink-surface/40 px-3 py-2 text-[12px] text-ink-cream-2`,children:[`Heads up: this step isn't scheduled to fire until`,` `,(0,g.jsx)(`span`,{className:`text-ink-cream`,children:r(B.nextDueAt)}),` (`,ue(B.nextDueAt),`). Sending now fires it ahead of schedule; the remaining cadence steps will recompute their due dates from today, not the original schedule.`]}),B?.isBreakup&&(0,g.jsxs)(`div`,{className:`rounded border border-ink-rule bg-ink-surface/40 px-3 py-2 text-[12px] text-[color:var(--ink-spend-2)]`,children:[`This is the breakup — the final touch in`,` `,(0,g.jsx)(`code`,{className:`font-mono text-[11px]`,children:B.playName}),`. After this, no more emails will go to this prospect.`]}),(0,g.jsxs)(`div`,{className:`font-mono text-[12px] text-ink-muted`,children:[(0,g.jsxs)(`div`,{children:[`To:`,` `,(0,g.jsx)(`span`,{className:`text-ink-cream-2`,children:B?.prospectEmail??`(no email)`})]}),(0,g.jsxs)(`div`,{children:[`Play: `,(0,g.jsx)(`span`,{className:`text-ink-cream-2`,children:B?.playName})]}),(0,g.jsxs)(`div`,{children:[`Subject: `,(0,g.jsx)(`span`,{className:`text-ink-cream-2`,children:B?.subject})]})]}),(0,g.jsx)(`div`,{className:`ln-eyebrow text-[10px] text-ink-faint`,children:`sends the persisted preview verbatim — no LLM reroll.`})]})}),(0,g.jsx)(p,{open:o!=null,onClose:()=>y(null),title:`Log outcome${o?.prospectName?` — ${o.prospectName}`:``}`,footer:(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(u,{variant:`ghost`,onClick:()=>y(null),children:`Cancel`}),(0,g.jsx)(u,{onClick:()=>W.mutate(),disabled:W.isPending,children:W.isPending?`Saving…`:`Save outcome`})]}),children:(0,g.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,g.jsxs)(`div`,{className:`font-mono text-[12px] text-ink-muted`,children:[`Prospect: `,(0,g.jsx)(`span`,{className:`text-ink-cream-2`,children:o?.email}),(0,g.jsx)(`br`,{}),`Play: `,(0,g.jsx)(`span`,{className:`text-ink-cream-2`,children:o?.playName})]}),(0,g.jsx)(f,{label:`Outcome`,children:(0,g.jsxs)(ae,{value:S,onChange:e=>fe(e.target.value),children:[(0,g.jsx)(`option`,{value:`meeting_booked`,children:`meeting_booked`}),(0,g.jsx)(`option`,{value:`sql_qualified`,children:`sql_qualified`}),(0,g.jsx)(`option`,{value:`deal_won`,children:`deal_won`}),(0,g.jsx)(`option`,{value:`deal_lost`,children:`deal_lost`}),(0,g.jsx)(`option`,{value:`ghosted`,children:`ghosted`})]})}),S===`deal_won`&&(0,g.jsx)(f,{label:`Amount (USD)`,children:(0,g.jsx)(oe,{type:`number`,value:C,onChange:e=>w(e.target.value),placeholder:`5000`})}),(0,g.jsx)(f,{label:`Notes (optional)`,children:(0,g.jsx)(ie,{rows:3,value:T,onChange:e=>E(e.target.value)})})]})})]})}function b({label:e,value:t,caption:n,tone:r=`neutral`}){return(0,g.jsxs)(`div`,{className:`px-5 py-4`,children:[(0,g.jsx)(`div`,{className:`ln-eyebrow`,children:e}),(0,g.jsx)(`div`,{className:`mt-1 truncate text-ink-cream ln-numeral`,style:{fontSize:32,lineHeight:1},children:t}),n&&(0,g.jsx)(`div`,{className:`mt-2 truncate font-mono text-[11px]`,style:{color:r===`spend`?`var(--ink-spend-2)`:r===`receipt`?`var(--ink-receipt-2)`:r===`signal`?`var(--ink-signal-2)`:`var(--ink-faint)`},children:n})]})}function x(e,t){let n=Date.now(),r=0,i=0,a=0,o=0,s=0;for(let t of e)t.status===`active`?(r++,t.nextDueAt&&new Date(t.nextDueAt).getTime()<=n&&s++):t.status===`replied`?i++:t.status===`breakup`?a++:t.status===`completed`&&o++;return t||(i=0,a=0,o=0),{active:r,replied:i,breakup:a,completed:o,overdue:s}}export{y as component};
@@ -0,0 +1 @@
1
+ import{o as e}from"./cn-CS0Arupu.js";var t=e(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]);export{t};
@@ -0,0 +1 @@
1
+ import{o as e}from"./cn-CS0Arupu.js";var t=e(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]);export{t};