@pikku/cli 0.12.29 → 0.12.31
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.
- package/console-app/assets/{index-ClGe-ul_.js → index-BkiCv5R3.js} +1 -1
- package/console-app/index.html +1 -1
- package/dist/.pikku/agent/pikku-agent-types.gen.d.ts +1 -1
- package/dist/.pikku/channel/pikku-channel-types.gen.d.ts +1 -1
- package/dist/.pikku/channel/pikku-channel-types.gen.js +1 -1
- package/dist/.pikku/cli/pikku-cli-channel.js +1 -1
- package/dist/.pikku/cli/pikku-cli-types.gen.d.ts +1 -1
- package/dist/.pikku/cli/pikku-cli-types.gen.js +1 -1
- package/dist/.pikku/cli/pikku-cli-wirings-meta.gen.js +1 -1
- package/dist/.pikku/cli/pikku-cli-wirings.gen.d.ts +1 -1
- package/dist/.pikku/cli/pikku-cli-wirings.gen.js +1 -1
- package/dist/.pikku/cli/pikku-cli.gen.d.ts +1 -1
- package/dist/.pikku/cli/pikku-cli.gen.js +1 -1
- package/dist/.pikku/console/pikku-node-types.gen.d.ts +1 -1
- package/dist/.pikku/function/pikku-function-types.gen.d.ts +1 -1
- package/dist/.pikku/function/pikku-function-types.gen.js +1 -1
- package/dist/.pikku/function/pikku-functions-meta.gen.js +1 -1
- package/dist/.pikku/function/pikku-functions-meta.gen.json +257 -257
- package/dist/.pikku/function/pikku-functions.gen.js +1 -1
- package/dist/.pikku/http/pikku-http-types.gen.d.ts +1 -1
- package/dist/.pikku/http/pikku-http-types.gen.js +1 -1
- package/dist/.pikku/http/pikku-http-wirings-meta.gen.js +1 -1
- package/dist/.pikku/http/pikku-http-wirings.gen.d.ts +1 -1
- package/dist/.pikku/http/pikku-http-wirings.gen.js +1 -1
- package/dist/.pikku/mcp/pikku-mcp-types.gen.d.ts +1 -1
- package/dist/.pikku/mcp/pikku-mcp-types.gen.js +1 -1
- package/dist/.pikku/pikku-bootstrap.gen.d.ts +1 -1
- package/dist/.pikku/pikku-bootstrap.gen.js +1 -1
- package/dist/.pikku/pikku-meta-service.gen.d.ts +1 -1
- package/dist/.pikku/pikku-meta-service.gen.js +1 -1
- package/dist/.pikku/pikku-services.gen.d.ts +1 -1
- package/dist/.pikku/pikku-types.gen.d.ts +1 -1
- package/dist/.pikku/pikku-types.gen.js +1 -1
- package/dist/.pikku/queue/pikku-queue-types.gen.d.ts +1 -1
- package/dist/.pikku/queue/pikku-queue-types.gen.js +1 -1
- package/dist/.pikku/queue/pikku-queue-workers-wirings-meta.gen.js +1 -1
- package/dist/.pikku/queue/pikku-queue-workers-wirings.gen.d.ts +1 -1
- package/dist/.pikku/queue/pikku-queue-workers-wirings.gen.js +1 -1
- package/dist/.pikku/rpc/pikku-rpc-wirings-meta.internal.gen.js +1 -1
- package/dist/.pikku/rpc/pikku-rpc-wirings-meta.internal.gen.json +5 -5
- package/dist/.pikku/scheduler/pikku-scheduler-types.gen.d.ts +1 -1
- package/dist/.pikku/scheduler/pikku-scheduler-types.gen.js +1 -1
- package/dist/.pikku/schemas/register.gen.js +15 -15
- package/dist/.pikku/secrets/pikku-secret-types.gen.d.ts +1 -1
- package/dist/.pikku/secrets/pikku-secret-types.gen.js +1 -1
- package/dist/.pikku/secrets/pikku-secrets.gen.d.ts +1 -1
- package/dist/.pikku/secrets/pikku-secrets.gen.js +1 -1
- package/dist/.pikku/trigger/pikku-trigger-types.gen.d.ts +1 -1
- package/dist/.pikku/trigger/pikku-trigger-types.gen.js +1 -1
- package/dist/.pikku/variables/pikku-variable-types.gen.d.ts +1 -1
- package/dist/.pikku/variables/pikku-variable-types.gen.js +1 -1
- package/dist/.pikku/variables/pikku-variables.gen.d.ts +1 -1
- package/dist/.pikku/variables/pikku-variables.gen.js +1 -1
- package/dist/.pikku/workflow/pikku-workflow-types.gen.d.ts +1 -1
- package/dist/.pikku/workflow/pikku-workflow-types.gen.js +1 -1
- package/dist/.pikku/workflow/pikku-workflow-wirings-meta.gen.js +1 -1
- package/dist/.pikku/workflow/pikku-workflow-wirings.gen.js +1 -1
- package/dist/bin/pikku-bin.mjs +2 -2
- package/dist/src/functions/commands/dev.js +1 -9
- package/dist/src/functions/db/db-codegen.d.ts +1 -0
- package/dist/src/functions/db/db-codegen.js +45 -0
- package/dist/src/functions/db/db-introspector.d.ts +12 -0
- package/dist/src/functions/db/local-db.d.ts +1 -0
- package/dist/src/functions/db/local-db.js +9 -2
- package/dist/src/functions/db/postgres/postgres-introspector.d.ts +3 -1
- package/dist/src/functions/db/postgres/postgres-introspector.js +43 -0
- package/dist/src/functions/db/sqlite/sqlite-introspector.d.ts +3 -1
- package/dist/src/functions/db/sqlite/sqlite-introspector.js +14 -0
- package/dist/src/functions/db/sqlite/sqlite-runtime-node.js +16 -3
- package/dist/src/functions/wirings/auth/serialize-auth-gen.js +4 -2
- package/dist/src/scaffold/rpc-remote.gen.js +1 -1
- package/package.json +1 -1
|
@@ -184,7 +184,7 @@ When calling a sub-agent, provide a short session name that describes the task.
|
|
|
184
184
|
`,type:`heading`});continue}if(r&&a===``&&(r=!1),r&&i.startsWith(` `)){let e=i.match(/^(\s{2})(\S+)(\s.*)?$/);if(e){let[,t,r,i]=e;n.push({text:t}),n.push({text:r,type:`command`}),n.push({text:(i||``)+`
|
|
185
185
|
`});continue}}let o=i.match(/^(\s+)(--?\S+(?:,\s*--?\S+)*)(.*)$/);if(o){let[,e,t,r]=o;n.push({text:e}),n.push({text:t,type:`flag`}),n.push({text:r+`
|
|
186
186
|
`});continue}n.push({text:i+(e<t.length-1?`
|
|
187
|
-
`:``)})}return n};const d1e=({programId:e,cliMeta:t,commandPath:n})=>(0,A.jsx)(j,{component:`pre`,style:{fontFamily:`var(--mantine-font-family-monospace)`,fontSize:`var(--mantine-font-size-sm)`,lineHeight:1.6,margin:0,whiteSpace:`pre-wrap`,wordBreak:`break-word`},children:(0,O.useMemo)(()=>u1e(c1e(e,t,n)),[e,t,n]).map((e,t)=>e.type===`heading`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-yellow-5)`,fontWeight:600},children:e.text},t):e.type===`command`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-blue-5)`},children:e.text},t):e.type===`flag`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-green-5)`},children:e.text},t):(0,A.jsx)(`span`,{children:e.text},t))});var f1e=({programs:e,cliRenderers:t,searchQuery:n})=>{let[r,i]=(0,O.useState)(e[0]?.wireId||``),[a,o]=(0,O.useState)([]),[s,c]=(0,O.useState)(()=>new Set(e.length>0?[e[0].wireId]:[])),l=(0,O.useMemo)(()=>e.find(e=>e.wireId===r),[e,r]),u=(0,O.useMemo)(()=>l?{programs:{[r]:{program:l.program||r,commands:l.commands,options:l.options,defaultRenderName:l.defaultRenderName}},renderers:t}:{programs:{},renderers:{}},[l,r,t]),d=e=>{c(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},f=e=>{i(e),o([]),s.has(e)||c(t=>new Set(t).add(e))},p=(e,t)=>{r!==e&&(i(e),s.has(e)||c(t=>new Set(t).add(e))),o([t])},m=a.length>0?`$ ${r} ${a.join(` `)} --help`:`$ ${r} --help`;return e.length,(0,A.jsxs)(j,{className:Qb.flexRow,children:[(0,A.jsx)(j,{className:Qb.listPaneFixed,style:{width:280,minWidth:220},children:(0,A.jsx)(Od,{style:{flex:1},children:e.map(e=>{let t=e.wireId===r,i=s.has(e.wireId),o=Object.entries(e.commands||{}),c=n.toLowerCase(),l=c?o.filter(([e,t])=>e.includes(c)||t.description?.toLowerCase().includes(c)):o;return c&&l.length===0&&!e.wireId.includes(c)?null:(0,A.jsxs)(O.Fragment,{children:[(0,A.jsxs)(kd,{onClick:()=>t?d(e.wireId):f(e.wireId),style:{display:`flex`,alignItems:`center`,gap:6,padding:`7px 12px`,fontSize:11,color:t?`var(--app-meta-value)`:`var(--app-text)`,borderLeft:t?`2px solid rgba(6,182,212,0.4)`:`2px solid transparent`,width:`100%`,opacity:t?1:.6,cursor:`pointer`},children:[i?(0,A.jsx)(Iy,{size:9,color:`var(--app-section-label)`}):(0,A.jsx)(Ly,{size:9,color:`var(--app-section-label)`}),(0,A.jsx)(N,{size:`sm`,ff:`monospace`,style:{flex:1},children:e.wireId}),(0,A.jsx)(kf,{size:`sm`,variant:`light`,color:`cyan`,ff:`monospace`,children:`cli`})]}),i&&l.map(([n,r])=>{let i=t&&a.length===1&&a[0]===n;return(0,A.jsxs)(kd,{onClick:()=>p(e.wireId,n),className:Qb.listItem,"data-active":i,style:{display:`flex`,alignItems:`center`,gap:7,padding:`5px 12px 5px 24px`},children:[(0,A.jsx)(j,{className:Qb.typeDot,style:{background:`rgba(124,58,237,0.4)`}}),(0,A.jsxs)(j,{style:{flex:1,minWidth:0},children:[(0,A.jsx)(N,{size:`sm`,ff:`monospace`,fw:i?600:400,c:i?`var(--app-meta-value)`:`var(--app-text)`,truncate:!0,children:n}),r.description&&(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:i?`var(--app-meta-label)`:`var(--app-text-muted)`,truncate:!0,style:{fontSize:9},children:r.description})]})]},n)})]},e.wireId)})})}),(0,A.jsxs)(j,{className:`${Qb.detailPane} ${Qb.flexColumn}`,style:{overflow:`hidden`},children:[(0,A.jsxs)(j,{className:Qb.gridHeader,style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,A.jsxs)(N,{size:`sm`,ff:`monospace`,c:`var(--app-text-muted)`,style:{flex:1},children:[(0,A.jsx)(N,{component:`span`,c:`violet`,ff:`monospace`,children:`$`}),` `,(0,A.jsx)(N,{component:`span`,c:`var(--app-text)`,ff:`monospace`,children:m.slice(2)})]}),(0,A.jsx)(op,{value:typeof document<`u`&&document.getElementById(`cli-terminal`)?.innerText||``,children:({copied:e,copy:t})=>(0,A.jsx)(dh,{label:e?`Copied`:`Copy`,children:(0,A.jsx)(Qd,{variant:`subtle`,color:e?`teal`:`gray`,size:`sm`,onClick:t,children:e?(0,A.jsx)(Fy,{size:12}):(0,A.jsx)(Xfe,{size:12})})})})]}),(0,A.jsx)(j,{id:`cli-terminal`,className:Qb.overflowAuto,style:{flex:1,padding:`20px 24px`,lineHeight:1.9,fontSize:11,fontFamily:`var(--mantine-font-family-monospace)`},children:l?(0,A.jsx)(d1e,{programId:r,cliMeta:u,commandPath:a}):(0,A.jsx)(N,{c:`dimmed`,ff:`monospace`,size:`sm`,children:`No CLI programs found.`})})]})]})};const rW=({searchQuery:e})=>{let{meta:t}=Xb(),n=t.cliMeta||[];return n.length===0?(0,A.jsx)(zz,{icon:vb,title:`No CLI programs found`,description:`Define CLI programs in your project to see them here.`,docsHref:`https://pikku.dev/docs/core-features/cli`}):(0,A.jsx)(sx,{children:(0,A.jsx)(f1e,{programs:n,cliRenderers:t.cliRenderers||{},searchQuery:e})})},p1e=({searchQuery:e})=>(0,A.jsx)(O.Suspense,{fallback:(0,A.jsx)(Ff,{h:`100%`,children:(0,A.jsx)(Xd,{})}),children:(0,A.jsx)(rW,{searchQuery:e})});var m1e=[{value:`http`,label:`HTTP`},{value:`channels`,label:`Channels`},{value:`mcp`,label:`MCP`},{value:`cli`,label:`CLI`}],h1e={http:`Search routes...`,channels:`Search channels...`,mcp:`Search MCP tools, resources, prompts...`,cli:`Search commands...`},g1e=({httpHero:e,channelsHero:t,mcpHero:n})=>{let[r,i]=Dy(),[a,o]=(0,O.useState)(``),s=r.get(`tab`)||`http`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`APIs`,description:`Browse HTTP routes, channels, MCP servers, and CLI surfaces`,docsHref:`https://pikku.dev/docs/wiring/http`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:h1e[s],leftSection:(0,A.jsx)(pb,{size:14}),value:a,onChange:e=>o(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:s,onChange:e=>{o(``),i({tab:e})},data:m1e})]})}),emptyPanelMessage:`Select an item to view details`,children:(()=>{switch(s){case`channels`:return(0,A.jsx)(RQe,{searchQuery:a,emptyHero:t});case`mcp`:return(0,A.jsx)(zQe,{searchQuery:a,emptyHero:n});case`cli`:return(0,A.jsx)(p1e,{searchQuery:a});default:return(0,A.jsx)(wQe,{searchQuery:a,emptyHero:e})}})()})})};const _1e=e=>(0,A.jsx)(O.Suspense,{fallback:(0,A.jsx)(Ff,{h:`100vh`,children:(0,A.jsx)(Xd,{})}),children:(0,A.jsx)(g1e,{...e})});var v1e=({schedule:e})=>(0,A.jsx)(af,{gap:3,wrap:`nowrap`,children:e.split(` `).map((e,t)=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(245,158,11,0.08)`,border:`0.5px solid rgba(245,158,11,0.18)`,color:`#fbbf24`,padding:`1px 5px`},children:e},t))}),y1e=e=>{let t=Math.floor((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`};const b1e=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),r=by(),{openScheduler:i}=ox(),{data:a={}}=Ur({queryKey:[`console:getSchedulerHistory`],queryFn:()=>r.invoke(`console:getSchedulerHistory`).then(e=>e??{}),refetchInterval:15e3}),o=(0,O.useMemo)(()=>n.schedulerMeta?Object.entries(n.schedulerMeta).map(([e,t])=>({name:e,...t})):[],[n.schedulerMeta]);return(0,A.jsx)(Bz,{title:`Schedulers`,icon:By,docsHref:`https://pikku.dev/docs/wiring/scheduled-tasks`,data:(0,O.useMemo)(()=>{if(!e)return o;let t=e.toLowerCase();return o.filter(e=>e.name?.toLowerCase().includes(t)||e.pikkuFuncId?.toLowerCase().includes(t)||e.schedule?.toLowerCase().includes(t))},[o,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.wireId||e.name}),e.pikkuFuncId&&(0,A.jsxs)(N,{size:`xs`,c:`dimmed`,ff:`monospace`,truncate:!0,children:[e.pikkuFuncId,`()`]})]})},{key:`schedule`,header:`SCHEDULE`,render:e=>e.schedule?(0,A.jsx)(v1e,{schedule:e.schedule}):null},{key:`lastRun`,header:`LAST RUN`,width:120,render:e=>{let t=a[e.wireId||e.name]?.lastRun??null;return t?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:t.status===`failed`?`var(--mantine-color-red-5)`:`var(--mantine-color-green-5)`,children:t.status}),(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:`var(--app-text-muted)`,children:y1e(t.timestamp)})]}):(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:`var(--app-meta-label)`,children:`—`})}}],[a]),getKey:e=>e.name,onRowClick:e=>i(e.wireId||e.name,e),emptyMessage:`No scheduled tasks found.`,emptyHero:t})},x1e=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),r=by(),{openQueue:i}=ox(),{data:a}=Ur({queryKey:[`console:getQueueDepths`],queryFn:()=>r.invoke(`console:getQueueDepths`).then(e=>e??{}),refetchInterval:5e3}),o=(0,O.useMemo)(()=>n.queueMeta?Object.entries(n.queueMeta).map(([e,t])=>({name:e,...t})):[],[n.queueMeta]);return(0,A.jsx)(Bz,{title:`Queues`,icon:$y,docsHref:`https://pikku.dev/docs/wiring/queues`,data:(0,O.useMemo)(()=>{if(!e)return o;let t=e.toLowerCase();return o.filter(e=>e.name?.toLowerCase().includes(t)||e.wireId?.toLowerCase().includes(t)||e.pikkuFuncId?.toLowerCase().includes(t))},[o,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.wireId||e.name}),e.pikkuFuncId&&(0,A.jsx)(N,{size:`xs`,c:`dimmed`,ff:`monospace`,truncate:!0,children:e.pikkuFuncId})]})},{key:`queued`,header:`QUEUED`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.queued?`var(--app-meta-value)`:`var(--app-meta-label)`,children:t?.queued??`—`})}},{key:`active`,header:`ACTIVE`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.active?`var(--mantine-color-green-5)`:`var(--app-meta-label)`,children:t?.active??`—`})}},{key:`failed`,header:`FAILED`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.failed?`var(--mantine-color-red-5)`:`var(--app-meta-label)`,children:t?.failed??`—`})}}],[a]),getKey:e=>e.name,onRowClick:e=>i(e.wireId||e.name,e),emptyMessage:`No queue workers found.`,emptyHero:t})};var S1e=[{key:`name`,header:`NAME`,render:e=>(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.name})},{key:`source`,header:`SOURCE`,render:e=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(124,58,237,0.08)`,border:`0.5px solid rgba(124,58,237,0.18)`,color:`#a78bfa`,maxWidth:200,overflow:`hidden`,textOverflow:`ellipsis`},children:e.source?.pikkuFuncId||`Missing`})},{key:`target`,header:`TARGET`,render:e=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(6,182,212,0.07)`,border:`0.5px solid rgba(6,182,212,0.15)`,color:`#06b6d4`,maxWidth:200,overflow:`hidden`,textOverflow:`ellipsis`},children:e.trigger?.pikkuFuncId||`Missing`})}];const iW=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),{openTrigger:r}=ox(),i=(0,O.useMemo)(()=>{let e=new Set;return n.triggerSourceMeta&&Object.keys(n.triggerSourceMeta).forEach(t=>e.add(t)),n.triggerMeta&&Object.keys(n.triggerMeta).forEach(t=>e.add(t)),Array.from(e).sort().map(e=>({name:e,source:n.triggerSourceMeta?.[e]||null,trigger:n.triggerMeta?.[e]||null}))},[n.triggerMeta,n.triggerSourceMeta]);return(0,A.jsx)(Bz,{title:`Triggers`,icon:wb,docsHref:`https://pikku.dev/docs/wiring/triggers`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.source?.pikkuFuncId?.toLowerCase().includes(t)||e.trigger?.pikkuFuncId?.toLowerCase().includes(t))},[i,e]),columns:S1e,getKey:e=>e.name,onRowClick:e=>r(e.name,e.trigger),emptyMessage:`No triggers found.`,emptyHero:t})};var C1e=[{value:`schedulers`,label:`Schedulers`},{value:`queues`,label:`Queues`},{value:`triggers`,label:`Triggers`}],w1e={schedulers:`Search scheduled tasks...`,queues:`Search queue workers...`,triggers:`Search triggers...`};const T1e=({queuesHero:e,triggersHero:t,schedulersHero:n})=>{let[r,i]=Dy(),[a,o]=(0,O.useState)(``),s=r.get(`tab`)||`schedulers`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Jobs`,description:`Scheduled tasks, queues, and triggers`,docsHref:`https://pikku.dev/docs/wiring/scheduled-tasks`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:w1e[s],leftSection:(0,A.jsx)(pb,{size:14}),value:a,onChange:e=>o(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:s,onChange:e=>{o(``),i({tab:e})},data:C1e})]})}),emptyPanelMessage:`Select an item to view details`,children:(()=>{switch(s){case`queues`:return(0,A.jsx)(x1e,{searchQuery:a,emptyHero:e});case`triggers`:return(0,A.jsx)(iW,{searchQuery:a,emptyHero:t});default:return(0,A.jsx)(b1e,{searchQuery:a,emptyHero:n})}})()})})};var E1e=[{key:`name`,header:`NAME`,render:e=>(0,A.jsx)(N,{fw:500,children:e.name})},{key:`functions`,header:`FUNCTIONS`,align:`right`,render:e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`functions`,value:e.funcCount})}];const D1e=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),r=(0,O.useMemo)(()=>{let e=new Map;return t.functions?.forEach(t=>{if(t.services?.services)for(let n of t.services.services){let r=e.get(n)||{funcCount:0,functions:[]};r.funcCount++,r.functions.push(t.pikkuFuncId),e.set(n,r)}}),Array.from(e.entries()).map(([e,t])=>({name:e,...t})).sort((e,t)=>t.funcCount-e.funcCount)},[t.functions]);return(0,A.jsx)(Bz,{title:`Services`,icon:mb,docsHref:`https://pikku.dev/docs/core-features/services`,data:(0,O.useMemo)(()=>{if(!e)return r;let t=e.toLowerCase();return r.filter(e=>e.name.toLowerCase().includes(t)||e.functions.some(e=>e.toLowerCase().includes(t)))},[r,e]),columns:E1e,getKey:e=>e.name,onRowClick:()=>{},emptyMessage:`No services found.`,loading:n})},X=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),{openMiddleware:r}=ox(),i=(0,O.useMemo)(()=>{if(!t.middlewareGroupsMeta)return[];let e=t.middlewareGroupsMeta.definitions||{},n=[];for(let[t,r]of Object.entries(e))r.exportedName!==null&&n.push({id:`middleware::def::${t}`,name:r.name||r.exportedName||t,data:{...r,_id:t}});return n},[t.middlewareGroupsMeta]);return(0,A.jsx)(Bz,{title:`Middleware`,icon:Xy,docsHref:`https://pikku.dev/docs/core-features/middleware`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.data?.description?.toLowerCase().includes(t))},[i,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.name}),e.data?.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,lineClamp:1,children:e.data.description})]})},{key:`type`,header:`TYPE`,align:`right`,render:e=>{let t=e.data?.wires?.wires??[],n=new Set([`session`,`setSession`,`clearSession`,`getSession`,`hasSessionChanged`]),r=t.some(e=>n.has(e)),i=t.filter(e=>!n.has(e));return(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[r&&(0,A.jsx)(fx,{type:`flag`,flag:`session`}),i.map(e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`wire`,value:e},e)),e.data?.factory&&(0,A.jsx)(fx,{type:`flag`,flag:`factory`})]})}}],[]),getKey:e=>e.id,onRowClick:e=>r(e.id,e.data),emptyMessage:`No middleware found.`,loading:n})},aW=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),{openPermission:r}=ox(),i=(0,O.useMemo)(()=>{if(!t.permissionsGroupsMeta)return[];let e=t.permissionsGroupsMeta.definitions||{},n=[];for(let[t,r]of Object.entries(e))r.exportedName!==null&&n.push({id:`permission::def::${t}`,name:r.name||r.exportedName||t,data:{...r,_id:t}});return n},[t.permissionsGroupsMeta]);return(0,A.jsx)(Bz,{title:`Permissions`,icon:gb,docsHref:`https://pikku.dev/docs/core-features/permission-guards`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.data?.description?.toLowerCase().includes(t))},[i,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.name}),e.data?.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,lineClamp:1,children:e.data.description})]})},{key:`type`,header:`TYPE`,align:`right`,render:e=>{let t=e.data?.wires?.wires??[],n=new Set([`session`,`setSession`,`clearSession`,`getSession`,`hasSessionChanged`]),r=t.some(e=>n.has(e)),i=t.filter(e=>!n.has(e));return(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[r&&(0,A.jsx)(fx,{type:`flag`,flag:`session`}),i.map(e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`wire`,value:e},e)),e.data?.factory&&(0,A.jsx)(fx,{type:`flag`,flag:`factory`})]})}}],[]),getKey:e=>e.id,onRowClick:e=>r(e.id,e.data),emptyMessage:`No permissions found.`,loading:n})};var O1e=[{value:`services`,label:`Services`},{value:`middleware`,label:`Middleware`},{value:`permissions`,label:`Permissions`}],k1e={services:`Search services...`,middleware:`Search middleware...`,permissions:`Search permissions...`};const A1e=()=>{let[e,t]=Dy(),[n,r]=(0,O.useState)(``),i=e.get(`tab`)||`services`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Runtime`,description:`Services, middleware, and permission guards`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:k1e[i],leftSection:(0,A.jsx)(pb,{size:14}),value:n,onChange:e=>r(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:i,onChange:e=>{r(``),t({tab:e})},data:O1e})]})}),emptyPanelMessage:`Select an item to view its details`,children:(()=>{switch(i){case`middleware`:return(0,A.jsx)(X,{searchQuery:n});case`permissions`:return(0,A.jsx)(aW,{searchQuery:n});default:return(0,A.jsx)(D1e,{searchQuery:n})}})()})})};var j1e=`https://pikku.dev/docs`;function M1e(e){return{type:`object`,properties:Object.fromEntries(e.map(e=>[e,{type:`string`,title:e}]))}}var N1e=[{key:`name`,header:`NAME`,render:e=>(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.name})},{key:`variables`,header:`VARIABLES`,width:120,render:e=>(0,A.jsx)(N,{size:`sm`,c:`dimmed`,children:e.variables.length})},{key:`locales`,header:`LOCALES`,width:280,render:e=>{let t=Object.keys(e.locales);return(0,A.jsxs)(af,{gap:4,children:[t.slice(0,5).map(e=>(0,A.jsx)(kf,{variant:`outline`,color:`gray`,size:`sm`,children:e},e)),t.length>5&&(0,A.jsxs)(kf,{variant:`outline`,color:`gray`,size:`sm`,children:[`+`,t.length-5]})]})}}],P1e=({templateNames:e,templates:t,onSelect:n})=>(0,A.jsx)(Bz,{icon:ib,title:`Email Templates`,docsHref:j1e,data:(0,O.useMemo)(()=>e.map(e=>({name:e,...t[e]})),[e,t]),columns:N1e,getKey:e=>e.name,onRowClick:e=>n(e.name),searchPlaceholder:`Search email templates...`,searchFilter:(e,t)=>e.name.toLowerCase().includes(t)||e.variables.some(e=>e.toLowerCase().includes(t)),emptyMessage:`No email templates match the current search.`});const F1e=({hero:e,headerRight:t})=>{let{meta:n,loading:r}=Xb(),[i,a]=Dy(),[o,s]=(0,O.useState)({}),[c,l]=(0,O.useState)(`desktop`),[u,d]=(0,O.useState)(!1),[f,p]=(0,O.useState)(``),m=n.emailsMeta?.templates||{},h=(0,O.useMemo)(()=>Object.keys(m).sort((e,t)=>e.localeCompare(t)),[m]),g=i.get(`template`),_=g?m[g]:null,v=(0,O.useMemo)(()=>h.map(e=>({name:e,description:`${m[e].variables.length} variable${m[e].variables.length===1?``:`s`}`})),[h,m]),y=(0,O.useMemo)(()=>Object.keys(_?.locales??{}).sort((e,t)=>e.localeCompare(t)).map(e=>({label:e,value:e})),[_]),b=i.get(`locale`),x=_?y.find(e=>e.value===b)?.value||y[0]?.value||`en`:null;(0,O.useEffect)(()=>{!g||!x||i.get(`locale`)!==x&&a({template:g,locale:x},{replace:!0})},[i,x,g,a]);let S=_Ae(g,x??void 0,o,!!g&&!!x),C=(0,O.useMemo)(()=>M1e(_?.variables??[]),[_]);if(r)return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`,lead:t}),children:(0,A.jsx)(Ff,{h:`100%`,children:(0,A.jsx)(Xd,{})})})});if(h.length===0)return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`,lead:t}),children:(0,A.jsx)(zz,{icon:ib,hero:e,title:`No email templates found`,description:`Add an email templates directory to your project, then run:`,code:`pikku emails generate`,docsHref:j1e})})});if(!g||!_||!x)return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`,lead:t}),children:(0,A.jsx)(P1e,{templateNames:h,templates:m,onSelect:e=>{s({}),a({template:e,locale:Object.keys(m[e].locales).sort((e,t)=>e.localeCompare(t))[0]??`en`})}})})});let w=(0,O.useMemo)(()=>{if(!f)return v;let e=f.toLowerCase();return v.filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[v,f]),T=e=>{d(!1),p(``),s({}),a({template:e,locale:Object.keys(m[e].locales).sort((e,t)=>e.localeCompare(t))[0]??`en`})};return(0,A.jsx)(j,{className:Qb.flexColumn,style:{height:`100vh`,padding:`var(--mantine-spacing-xl)`,gap:`var(--mantine-spacing-md)`},children:(0,A.jsxs)(j,{style:{flex:1,minHeight:0,display:`flex`,gap:`var(--mantine-spacing-md)`},children:[(0,A.jsxs)(j,{className:Qb.listSurfaceCard,style:{flex:1,minWidth:480,display:`flex`,flexDirection:`column`},children:[(0,A.jsxs)(j,{px:`md`,py:`xs`,style:{borderBottom:`1px solid var(--mantine-color-default-border)`,flexShrink:0},children:[(0,A.jsxs)(af,{gap:`sm`,justify:`space-between`,wrap:`nowrap`,children:[(0,A.jsxs)(af,{gap:`xs`,style:{minWidth:0},children:[(0,A.jsx)(ib,{size:16}),(0,A.jsx)(N,{fw:600,ff:`monospace`,truncate:!0,children:g}),S.data?.hash?(0,A.jsx)(kf,{variant:`outline`,color:`gray`,style:{flexShrink:0},children:S.data.hash.slice(0,10)}):null]}),(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,style:{flexShrink:0},children:[(0,A.jsx)(ph,{data:y,value:x,onChange:e=>{e&&(s({}),a({template:g,locale:e}))},allowDeselect:!1,size:`xs`,w:96}),(0,A.jsx)(fh,{value:c,onChange:e=>l(e),size:`xs`,data:[{label:(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[(0,A.jsx)(ab,{size:14}),(0,A.jsx)(`span`,{children:`Desktop`})]}),value:`desktop`},{label:(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[(0,A.jsx)(vpe,{size:14}),(0,A.jsx)(`span`,{children:`Mobile`})]}),value:`mobile`}]})]})]}),S.data?.subject&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,mt:4,children:S.data.subject})]}),(0,A.jsx)(j,{style:{flex:1,minHeight:0,overflow:`auto`},p:`md`,children:(0,A.jsxs)(kh,{gap:`md`,children:[S.isLoading?(0,A.jsx)(Ff,{py:`xl`,children:(0,A.jsx)(Xd,{})}):null,S.error?(0,A.jsx)(vf,{color:`red`,icon:(0,A.jsx)(bb,{size:16}),children:S.error instanceof Error?S.error.message:`Failed to render email preview`}):null,S.data?.missing?.length?(0,A.jsxs)(vf,{color:`yellow`,icon:(0,A.jsx)(bb,{size:16}),children:[`Missing source files: `,S.data.missing.join(`, `)]}):null,(0,A.jsx)(Ff,{py:`sm`,children:c===`desktop`?(0,A.jsx)(j,{style:{width:`100%`,maxWidth:960,height:720,border:`1px solid var(--app-row-border)`,borderRadius:8,overflow:`hidden`,background:`#fff`},children:(0,A.jsx)(`iframe`,{title:`Desktop email preview`,srcDoc:S.data?.html??``,style:{width:`100%`,height:`100%`,border:0,background:`#fff`}})}):(0,A.jsx)(j,{style:{width:390,maxWidth:`100%`,height:720,border:`1px solid var(--app-row-border)`,borderRadius:24,overflow:`hidden`,background:`#fff`},children:(0,A.jsx)(`iframe`,{title:`Mobile email preview`,srcDoc:S.data?.html??``,style:{width:`100%`,height:`100%`,border:0,background:`#fff`}})})}),S.data?.text?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(up,{}),(0,A.jsxs)(kh,{gap:`xs`,children:[(0,A.jsx)(N,{fw:600,children:`Text fallback`}),(0,A.jsx)(Lf,{block:!0,children:S.data.text})]})]}):null]})})]}),(0,A.jsxs)(j,{className:Qb.listSurfaceCard,style:{width:300,flexShrink:0,display:`flex`,flexDirection:`column`},children:[(0,A.jsxs)(qd,{opened:u,onChange:d,width:280,position:`bottom-start`,shadow:`md`,zIndex:1e4,children:[(0,A.jsx)(qd.Target,{children:(0,A.jsxs)(kd,{px:`sm`,py:`xs`,style:{width:`100%`,display:`flex`,alignItems:`center`,gap:4,borderBottom:`1px solid var(--mantine-color-default-border)`},onClick:()=>d(e=>!e),children:[(0,A.jsx)(N,{size:`sm`,fw:600,style:{flex:1,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:g}),(0,A.jsx)(Iy,{size:14,style:{flexShrink:0}})]})}),(0,A.jsxs)(qd.Dropdown,{p:0,children:[(0,A.jsx)(Xh,{placeholder:`Search templates...`,leftSection:(0,A.jsx)(pb,{size:14}),value:f,onChange:e=>p(e.currentTarget.value),styles:{input:{border:`none`,borderBottom:`1px solid var(--mantine-color-default-border)`,borderRadius:0}}}),(0,A.jsx)(Od.Autosize,{mah:300,children:(0,A.jsxs)(kh,{gap:0,children:[w.map(e=>(0,A.jsxs)(kd,{onClick:()=>T(e.name),py:`xs`,px:`sm`,style:{display:`flex`,alignItems:`center`,gap:8,backgroundColor:e.name===g?`var(--mantine-color-green-light)`:void 0},children:[e.name===g?(0,A.jsx)(Fy,{size:14,color:`var(--mantine-color-green-6)`}):(0,A.jsx)(j,{w:14}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(N,{size:`sm`,fw:e.name===g?500:400,children:e.name}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,children:e.description})]})]},e.name)),w.length===0&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ta:`center`,py:`md`,children:`No results`})]})})]})]}),(0,A.jsx)(j,{style:{flex:1,minHeight:0,overflow:`auto`},p:`md`,children:(0,A.jsxs)(kh,{gap:`lg`,children:[(0,A.jsx)(dk,{schema:C,submitLabel:`Render preview`,onSubmit:e=>s(e??{})},`${g}:${x}`),(0,A.jsx)(up,{}),(0,A.jsxs)(kh,{gap:`xs`,children:[(0,A.jsx)(N,{fw:600,children:`Template details`}),(0,A.jsxs)(af,{gap:`xs`,children:[(0,A.jsxs)(kf,{variant:`light`,children:[_.variables.length,` variables`]}),(0,A.jsxs)(kf,{variant:`light`,children:[Object.keys(_.locales).length,` locales`]})]}),S.data?.hash?(0,A.jsx)(Lf,{block:!0,children:S.data.hash}):null]})]})})]})]})})},I1e=({secrets:e,loading:t,installed:n=!0,emptyHero:r})=>{let{openSecret:i}=ox();return(0,A.jsx)(Bz,{title:`Secrets`,icon:Jy,docsHref:`https://pikku.dev/docs/core-features/secrets`,data:e,columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(af,{gap:`xs`,children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.displayName}),e.isOAuth2&&(0,A.jsx)(fx,{type:`label`,color:`gray`,children:`OAuth2`})]}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,children:e.description})]})},{key:`secretId`,header:`SECRET ID`,render:e=>(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ff:`monospace`,children:e.secretId})}],[]),getKey:e=>e.name,onRowClick:e=>i(e.name,{...e.rawData??e,installed:n}),emptyMessage:`No secrets found.`,loading:t,emptyHero:r})};var L1e=({emptyHero:e})=>{let{meta:t,loading:n}=Xb(),[r,i]=(0,O.useState)(``),a=(0,O.useMemo)(()=>t.secretsMeta?Object.entries(t.secretsMeta).map(([e,t])=>({name:e,displayName:t.displayName,description:t.description,secretId:t.secretId,isOAuth2:!!t.oauth2,rawData:t})):[],[t.secretsMeta]),o=(0,O.useMemo)(()=>{if(!r)return a;let e=r.toLowerCase();return a.filter(t=>t.name.toLowerCase().includes(e)||t.displayName?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.secretId?.toLowerCase().includes(e))},[a,r]);return(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Secrets`,description:`Encrypted secrets managed by pikku`,docsHref:`https://pikku.dev/docs/core-features/secrets`,filters:(0,A.jsx)(af,{gap:`sm`,wrap:`nowrap`,children:(0,A.jsx)(Xh,{placeholder:`Search secrets...`,leftSection:(0,A.jsx)(pb,{size:14}),value:r,onChange:e=>i(e.target.value),size:`xs`,style:{width:240}})})}),emptyPanelMessage:`Select a secret to view details`,children:(0,A.jsx)(I1e,{secrets:o,loading:n,emptyHero:e})})};const R1e=({emptyHero:e})=>(0,A.jsx)(sx,{children:(0,A.jsx)(L1e,{emptyHero:e})}),z1e=({variables:e,loading:t,installed:n=!0,emptyHero:r})=>{let{openVariable:i}=ox();return(0,A.jsx)(Bz,{title:`Environment Variables`,icon:hb,docsHref:`https://pikku.dev/docs/core-features/variables`,data:e,columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.displayName}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,children:e.description})]})},{key:`variableId`,header:`VARIABLE ID`,render:e=>(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ff:`monospace`,children:e.variableId})}],[]),getKey:e=>e.name,onRowClick:e=>i(e.name,{...e.rawData??e,installed:n}),emptyMessage:`No variables found.`,loading:t,emptyHero:r})};var B1e=({emptyHero:e})=>{let{meta:t,loading:n}=Xb(),[r,i]=(0,O.useState)(``),a=(0,O.useMemo)(()=>t.variablesMeta?Object.entries(t.variablesMeta).map(([e,t])=>({name:e,displayName:t.displayName,description:t.description,variableId:t.variableId,rawData:t})):[],[t.variablesMeta]),o=(0,O.useMemo)(()=>{if(!r)return a;let e=r.toLowerCase();return a.filter(t=>t.name.toLowerCase().includes(e)||t.displayName?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.variableId?.toLowerCase().includes(e))},[a,r]);return(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Variables`,description:`Runtime configuration variables for this environment`,docsHref:`https://pikku.dev/docs/core-features/variables`,filters:(0,A.jsx)(af,{gap:`sm`,wrap:`nowrap`,children:(0,A.jsx)(Xh,{placeholder:`Search variables...`,leftSection:(0,A.jsx)(pb,{size:14}),value:r,onChange:e=>i(e.target.value),size:`xs`,style:{width:240}})})}),emptyPanelMessage:`Select a variable to view details`,children:(0,A.jsx)(z1e,{variables:o,loading:n,emptyHero:e})})};const V1e=({emptyHero:e})=>(0,A.jsx)(sx,{children:(0,A.jsx)(B1e,{emptyHero:e})}),H1e=({onOpen:e,headerRight:t,emptyHero:n,metricSlot:r})=>{let i=Ty(),{meta:a,loading:o}=Xb(),[s,c]=(0,O.useState)(``),l=(0,O.useMemo)(()=>a.agentsMeta?Object.entries(a.agentsMeta).map(([e,t])=>{let n=(t.tools??[]).length,r=(t.agents??[]).length,i=t.model?[{label:t.model,tone:`neutral`}]:[],a=[];return n>0&&a.push(`${n} ${n===1?`tool`:`tools`}`),r>0&&a.push(`${r} ${r===1?`sub-agent`:`sub-agents`}`),{name:e,badges:i,meta:a,description:t.summary??t.description,tags:t.tags}}).sort((e,t)=>e.name.localeCompare(t.name)):[],[a.agentsMeta]),u=(0,O.useMemo)(()=>{let e=s.toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.badges?.some(t=>t.label.toLowerCase().includes(e))):l},[l,s]);return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Agents`,description:`AI agents and their configurations`,docsHref:`https://pikku.dev/docs/wiring/ai-agents`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:`Search agents...`,leftSection:(0,A.jsx)(pb,{size:14}),value:s,onChange:e=>c(e.target.value),size:`xs`,style:{width:240}}),t]})}),children:(0,A.jsx)(SQe,{items:u,onOpen:t=>{e?e(t):i(`/agents/playground?id=${encodeURIComponent(t)}`)},loading:o,icon:Ny,emptyHero:n,emptyTitle:`No agents found`,emptyDescription:`Define agents in your project to see them here.`,docsHref:`https://pikku.dev/docs/wiring/ai-agents`,metricSlot:r})})})};var oW=typeof process<`u`&&!1,sW=null;function U1e(e,t){e.currentIndex=0;let n=sW;sW=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{sW=n}}function cW(){if(!sW)throw Error(`No resource fiber available`);return sW}function W1e(){return sW}function G1e(e){return oW?sW?.devStrictMode?sW.isFirstRender?`child`:`root`:e?`root`:null:null}var K1e=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],dirtyCells:[]}),lW=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},uW=(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()),lW(e)}}},q1e=(e,t)=>{t.dirty||(t.dirty=!0,e.markDirty?.(),e.root.dirtyCells.push(t))},J1e=(e,t)=>{let n=cW(),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},Y1e=e=>{cW().renderContext.effectTasks.push(e)},X1e=(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 Z1e(e,t,n,r){let i=J1e(`reducer`,()=>{let t=cW(),a=r?r(n):n;return oW&&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};X1e(t,()=>t.root.dirtyCells.length===0&&!r.hasEagerState&&(r.eagerState=e(i.workInProgress,n),r.hasEagerState=!0,Object.is(i.current,r.eagerState))?null:()=>{q1e(t,i),i.queue.add(r)})}}}),a=cW(),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),oW&&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)||(q1e(a,i),i.workInProgress=e)}return[i.workInProgress,i.dispatch]}function Q1e(e,t,n){return Z1e(e,void 0,t,n)}function $1e(e,t,n,r){return Z1e(e,t,n,r)}var e0e=(e,t)=>typeof t==`function`?t(e):t,t0e=e=>typeof e==`function`?e():e;function Z(e){return Q1e(e0e,e,t0e)}function dW(e){let[t]=Z(()=>({current:e}));return t}var n0e=(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},r0e=()=>{throw Error(`Memo reducer should not be called`)},fW=(e,t)=>{let n=cW(),[r]=$1e(r0e,r=>{if(r&&n0e(r.deps,t))return r;let i=e();return oW&&n.devStrictMode&&e(),{value:i,deps:t}},null);return r.value},pW=(e,t)=>fW(()=>e,t),i0e=()=>({type:`effect`,cleanup:void 0,deps:null});function mW(e,t){let n=J1e(`effect`,i0e);if(!(t&&n.deps&&n0e(n.deps,t))){if(n.deps!==null&&!!t!=!!n.deps)throw Error(`useEffect called with and without dependencies across re-renders`);Y1e(()=>{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 a0e(e){let t=dW(e);mW(()=>{t.current=e});let n=cW();return pW(((...e)=>{if(oW&&n.renderContext)throw Error(`useEffectEvent cannot be called during render`);return t.current(...e)}),[n])}var hW=Symbol(`tap.Context`),o0e=e=>e,gW=e=>({[hW]:e}),s0e=e=>typeof e==`object`&&!!e&&hW in e,c0e=(e,t,n)=>{let r=o0e(e),i=r[hW];r[hW]=t;try{return n()}finally{r[hW]=i}},l0e=e=>o0e(e)[hW],_W=c({default:()=>O.default,use:()=>d0e,useCallback:()=>CW,useContext:()=>DW,useEffect:()=>wW,useEffectEvent:()=>EW,useLayoutEffect:()=>TW,useMemo:()=>SW,useReducer:()=>u0e,useRef:()=>xW,useState:()=>bW},1);u(_W,d(_(),1),void 0,1);var vW=()=>W1e()!==null,yW=O.default,bW=e=>vW()?Z(e):yW.useState(e),u0e=(e,t,n)=>vW()?Q1e(e,t,n):yW.useReducer(e,t,n),xW=e=>vW()?dW(e):yW.useRef(e),SW=(e,t)=>vW()?fW(e,t):yW.useMemo(e,t),CW=(e,t)=>vW()?pW(e,t):yW.useCallback(e,t),wW=(e,t)=>vW()?mW(e,t):yW.useEffect(e,t),TW=(e,t)=>vW()?mW(e,t):yW.useLayoutEffect(e,t),EW=e=>vW()?a0e(e):yW.useEffectEvent(e),d0e=e=>s0e(e)?l0e(e):yW.use(e),DW=e=>s0e(e)?l0e(e):yW.useContext(e);function OW(e,t){let n=e[kW];if(!n)throw Error(`ResourceElement.type is not a valid Resource`);return n(t)}var kW=Symbol(`fnSymbol`);function AW(e){let t=e=>({type:t,props:e});return t[kW]=e,t}function jW(e,t){return{...t,key:e}}var f0e=50,MW={schedulers:new Set([]),isScheduled:!1},p0e=class{_task;_isDirty=!1;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,MW.schedulers.add(this),m0e()}runTask(){this._isDirty=!1,this._task()}},m0e=()=>{MW.isScheduled||(MW.isScheduled=!0,NW())},h0e=()=>{try{let e=[],t=0;for(let n of MW.schedulers)if(MW.schedulers.delete(n),n.isDirty){if(t++,t>f0e)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.`);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{MW.schedulers.clear(),MW.isScheduled=!1}},NW=(()=>{if(typeof MessageChannel<`u`){let e=new MessageChannel;return e.port1.onmessage=h0e,()=>e.port2.postMessage(null)}return()=>setTimeout(h0e,0)})(),g0e=e=>{let t=MW;MW={schedulers:new Set([]),isScheduled:!0};try{let t=e();return h0e(),t}finally{MW=t}};function _0e(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 v0e(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 y0e=e=>{if(!s0e(e))throw Error("A tap resource's `use()` only accepts a resource context.");return l0e(e)},b0e=Symbol.for(`react.memo_cache_sentinel`),x0e={useState:Z,useReducer:Q1e,useRef:dW,useMemo:fW,useCallback:pW,useEffect:mW,useLayoutEffect:mW,useInsertionEffect:mW,useEffectEvent:a0e,useContext:y0e,use:y0e,useMemoCache:e=>{let t=!1,[n]=$1e(()=>[],e=>t?e:(t=!0,[...e]),e,e=>Array.from({length:e}).fill(b0e));return n}},S0e=O.default,PW=S0e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??S0e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,C0e=PW==null?null:`H`in PW?{get current(){return PW.H},set current(e){PW.H=e}}:`ReactCurrentDispatcher`in PW?{get current(){return PW.ReactCurrentDispatcher.current},set current(e){PW.ReactCurrentDispatcher.current=e}}:null;function w0e(e){if(!C0e)return e();let t=C0e.current;C0e.current=x0e;try{return e()}finally{C0e.current=t}}function FW(e,t,n=void 0,r=G1e(!1)){return{type:e,root:t,markDirty:n,devStrictMode:r,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function IW(e){if(!e.isMounted)throw Error(`Tried to unmount a fiber that is already unmounted`);e.isMounted=!1,v0e(e)}function LW(e,t){let n={effectTasks:[],props:t,output:void 0};return U1e(e,()=>{e.renderContext=n;try{n.output=w0e(()=>OW(e.type,t))}finally{e.renderContext=void 0}}),n}function RW(e,t){e.isMounted=!0,oW&&e.isNeverMounted&&e.devStrictMode===`root`&&(e.isNeverMounted=!1,_0e(t),v0e(e)),e.isNeverMounted=!1,_0e(t)}var T0e=e=>{let t=fW(()=>new p0e(()=>l(null)),[]),n=fW(()=>[],[]),r=fW(()=>(e.key,FW(e.type,K1e(e=>{!t.isDirty&&!e()||(n.push(e),t.markDirty())}))),[e.type,e.key,n,t]);uW(r.root,r.root.committedVersion);let i=LW(r,e.props),a=dW(!1),o=dW(e.props),s=dW(i.output),c=fW(()=>new Set,[]),l=a0e(e=>{if(e===null&&(uW(r.root,2),uW(r.root,1),n.forEach(e=>{oW&&r.devStrictMode&&e(),e()}),oW&&r.devStrictMode&&LW(r,o.current),e=LW(r,o.current)),t.isDirty)throw Error(`Scheduler is dirty, this should never happen`);lW(r.root),n.length=0,a.current&&RW(r,e),!(t.isDirty||s.current===e.output)&&(s.current=e.output,c.forEach(e=>e()))});return mW(()=>(a.current=!0,()=>{a.current=!1,IW(r)}),[r]),mW(()=>{o.current=i.props,lW(r.root),RW(r,i),!(t.isDirty||s.current===i.output)&&(s.current=i.output,c.forEach(e=>e()))}),fW(()=>({getValue:()=>s.current,subscribe:e=>(c.add(e),()=>c.delete(e))}),[c])};function E0e(e,t){let n=cW(),r=dW(0),i=fW(()=>(e.key,FW(e.type,n.root,()=>{r.current++,n.markDirty?.()})),[e.type,e.key,n]),a=t?fW(()=>LW(i,e.props),[i,...t,r.current]):LW(i,e.props);return mW(()=>()=>IW(i),[i]),mW(()=>{RW(i,a)},[i,a]),a.output}function D0e(e,t){let n=dW(0),r=n.current,i=fW(()=>cW(),[]),a=fW(()=>()=>{n.current++,i.markDirty?.()},[i]),o=fW(()=>new Map,[]),s=t?pW(e,t):e,c=fW(()=>{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(`useResources did not provide a key for array at index ${s}`);if(t.has(l))throw Error(`Duplicate key ${l} in useResources`);t.add(l);let u=o.get(l);if(u)if(u.fiber.type!==c.type){let e=FW(c.type,i.root,a),t=LW(e,c.props);u.next=[e,t],n.push(t.output)}else u.next=LW(u.fiber,c.props),n.push(u.next.output);else{let e=FW(c.type,i.root,a),t=LW(e,c.props);u={fiber:e,next:t},r++,o.set(l,u),n.push(t.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,i,a,o]);return mW(()=>()=>{for(let e of o.keys()){let t=o.get(e).fiber;IW(t)}},[o]),mW(()=>{for(let[e,t]of o.entries())t.next===`delete`?(t.fiber.isMounted&&IW(t.fiber),o.delete(e)):Array.isArray(t.next)?(IW(t.fiber),t.fiber=t.next[0],RW(t.fiber,t.next[1])):RW(t.fiber,t.next)},[c,o]),c}var zW=()=>{if(!oW)return null;let e=(0,O.useRef)(0),t=e.current===0;return(0,O.useState)(()=>e.current++),e.current===2?t?`child`:`root`:null},O0e=AW(function(e){return e()}),k0e=e=>{let t=(0,O.useMemo)(()=>K1e(e=>r(e)),[]),[n,r]=(0,O.useReducer)((e,n)=>(uW(t,e),e+(n()?1:0)),0);uW(t,n);let i=zW(),a=(0,O.useMemo)(()=>FW(O0e,t,void 0,i),[t,i]),o=LW(a,e);return(0,O.useLayoutEffect)(()=>()=>IW(a),[a]),(0,O.useLayoutEffect)(()=>{lW(t),RW(a,o)}),o.output},A0e=e=>((...t)=>W1e()?e(...t):k0e(()=>e(...t))),BW=A0e(E0e),VW=A0e(D0e),j0e=A0e(T0e),M0e=AW(function(){let[e,t]=bW(()=>({renderers:{},fallbacks:[]}));return{getState:()=>e,setDataUI:CW((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)??[]}}))}),[]),setFallbackDataUI:CW(e=>(t(t=>({...t,fallbacks:[...t.fallbacks,e]})),()=>{t(t=>({...t,fallbacks:t.fallbacks.filter(t=>t!==e)}))}),[])}}),HW=e=>{let t=Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)),n={};return t.reduce((e,t)=>{let r=t.priority??0;if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[i,a]of Object.entries(t.tools)){let t=e.tools?.[i];if(t&&t!==a){let o=n[i];if(o===r)throw Error(`You tried to define a tool with the name ${i}, but it already exists.`);let s=o>r?t:a,c=o>r?a:t;e.tools[i]={...c,...s},n[i]=Math.max(o,r);continue}e.tools||={},e.tools[i]=a,n[i]??=r}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),e},{})},N0e=class{_providers=new Set;getModelContext(){return HW(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)}}},UW=[],P0e={modelName:void 0,toolNames:UW},WW=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),GW=(e,t)=>{let n=e.getModelContext(),r=n.config?.modelName,i=n.tools?Object.keys(n.tools).sort():UW,a=i.length?i:UW;return r===t.modelName&&WW(a,t.toolNames)?t:{modelName:r,toolNames:a}},F0e=AW(function(){let e=SW(()=>new N0e,[]),[t,n]=bW(()=>GW(e,P0e));return wW(()=>(n(t=>GW(e,t)),e.subscribe(()=>{n(t=>GW(e,t))})),[e]),{getState:()=>GW(e,t),getModelContext:()=>e.getModelContext(),subscribe:t=>e.subscribe(t),register:t=>e.registerModelContextProvider(t)}}),I0e=e=>e.display===void 0?e.type===`human`:e.display===`standalone`,KW=(e,t)=>{if(!(t.status?.type===`running`||t.status?.type===`requires-action`)){let n=e.complete;return typeof n==`function`?n({args:t.args,result:t.result}):n??null}let n=e.running;return typeof n==`function`?n({args:t.args}):n??null},qW=e=>function(t){return KW(e,t)},L0e=Symbol(`assistant-ui.store.clientIndex`),R0e=e=>e[L0e],z0e=gW([]),B0e=()=>d0e(z0e),JW=(e,t)=>{let n=B0e();return c0e(z0e,SW(()=>[...n,e],[n,e]),t)},V0e=new Set([`$$typeof`,`nodeType`,`then`]),H0e=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!V0e.has(e))return!1}},U0e=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}},W0e=e=>{let t=AW(e);return e=>{let n=t(e);return e.key===void 0?n:jW(e.key,n)}},G0e=Symbol(`assistant-ui.store.getValue`),K0e=e=>{let t=e[G0e];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.`);return t.getState?.()},q0e=new Map;function J0e(e){let t=q0e.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[G0e];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)},q0e.set(e,t)),t}var YW=class extends U0e{outputRef;index;boundFns;cachedReceiver;constructor(e,t){super(),this.outputRef=e,this.index=t}get(e,t,n){if(t===G0e)return this.outputRef.current;if(t===L0e)return this.index;let r=H0e(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=J0e(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===G0e||t===L0e?!0:t in this.outputRef.current}},Y0e=W0e(e=>{let t=xW(null),n=B0e().length,r=SW(()=>new Proxy({},new YW(t,n)),[n]),i=JW(r,()=>BW(e));return t.current||=i,wW(()=>{t.current=i}),{methods:r,state:i.getState?.(),key:e.key}}),XW=e=>BW(Y0e(e)),ZW=Symbol(`assistant-ui.store.proxiedAssistantState`),X0e=e=>e===`on`||e===`subscribe`||typeof e==`symbol`,Z0e=e=>{class t extends U0e{get(t,n){let r=H0e(n,`AssistantState`);if(r!==!1)return r;let i=n;if(!X0e(i))return K0e(e[i]())}ownKeys(){return Object.keys(e).filter(e=>!X0e(e))}has(t,n){return!X0e(n)&&n in e}}return new Proxy({},new t)},QW=e=>e[ZW],Q0e=()=>()=>{},$W=e=>{let t=(()=>{throw Error(e)});return t.source=null,t.query=null,t},$0e=class extends U0e{get(e,t){if(t===`subscribe`||t===`on`)return Q0e;if(t===ZW)return e2e;let n=H0e(t,`DefaultAssistantClient`);return n===!1?$W(`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`):n}ownKeys(){return[`subscribe`,`on`,ZW]}has(e,t){return t===`subscribe`||t===`on`||t===ZW}},eG=new Proxy({},new $0e),e2e=Z0e(eG),t2e=()=>new Proxy({},{get(e,t){let n=H0e(t,`AssistantClient`);return n===!1?$W(`The current scope does not have a "${String(t)}" property.`):n}}),n2e=(0,_W.createContext)(eG),r2e=()=>DW(n2e),tG=({value:e,children:t})=>(0,A.jsx)(n2e.Provider,{value:e,children:t}),nG=AW(function(e){return null}),i2e=Symbol(`assistant-ui.transform-scopes`);function rG(e,t){let n=e;if(n[i2e])throw Error(`transformScopes is already attached to this resource`);n[i2e]=t}function a2e(e){return e[i2e]}var iG=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},o2e=gW(null),s2e=(e,t)=>c0e(o2e,e,t),c2e=()=>{let e=d0e(o2e);if(!e)throw Error(`AssistantTapContext is not available`);return e},l2e=()=>c2e().clientRef,u2e=()=>{let{emit:e}=c2e(),t=B0e();return EW((n,r)=>{e(n,r,t)})};function d2e(e,t){let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(e.type===nG||r.has(e.type))continue;r.add(e.type);let a=a2e(e.type);if(a){a(n,t),i=!0;break}}}let a={},o={};for(let[e,t]of Object.entries(n))t.type===nG?o[e]=t:a[e]=t;return{rootClients:a,derivedClients:o}}var aG=e=>SW(()=>e,[...Object.entries(e).flat()]),f2e=(e,t)=>{let{rootClients:n,derivedClients:r}=d2e(e,t);return{rootClients:aG(n),derivedClients:aG(r)}},p2e=AW(function(){return SW(()=>{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)}}}},[])}),oG=e=>SW(()=>e,e),m2e=AW(function({element:e,emit:t,clientRef:n}){let{methods:r,state:i}=s2e({clientRef:n,emit:t},()=>XW(e));return SW(()=>({state:i,methods:r}),[r,i])}),h2e=AW(function({element:e,notifications:t,clientRef:n,name:r}){let i=j0e(m2e({element:e,emit:t.emit,clientRef:n}));return wW(()=>i.subscribe(t.notifySubscribers),[i,t]),SW(()=>{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])}),g2e=AW(function(){return SW(()=>({clients:[],subscribe:void 0,on:void 0}),[])}),_2e=AW(function({clients:e,clientRef:t}){let n=BW(p2e());wW(()=>t.parent.subscribe(n.notifySubscribers),[t,n]);let r=oG(VW(()=>Object.keys(e).map(r=>jW(r,h2e({element:e[r],notifications:n,clientRef:t,name:r}))),[e,n,t]));return SW(()=>({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}=iG(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[R0e(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])}),v2e=AW(function({element:e,clientRef:t,name:n}){let r=xW(e.props);return r.current=e.props,SW(()=>{let e=()=>r.current.get(t.current);return Object.defineProperties(e,{source:{value:r.current.source},query:{value:r.current.query},name:{value:n,configurable:!0}}),e},[t,n])}),y2e=(e,t)=>{let n;try{let e={};for(let n of Object.keys(t.query).sort())e[n]=t.query[n];n=JSON.stringify(e)}catch{n=String(t.query)}return`${e}::${t.source}::${n}`},b2e=AW(function({clients:e,clientRef:t}){return oG(VW(()=>Object.keys(e).map(n=>{let r=n,i=e[r];return jW(y2e(r,i.props),v2e({element:i,clientRef:t,name:r}))}),[e,t]))}),x2e=AW(function({parent:e,clients:t}){let{rootClients:n,derivedClients:r}=f2e(t,e),i=xW({parent:e,current:null}).current;wW(()=>{i.current=s});let a=BW(Object.keys(n).length>0?_2e({clients:n,clientRef:i}):g2e()),o=BW(b2e({clients:r,clientRef:i})),s=SW(()=>{let t=e===eG?t2e():e,n=Object.create(t);Object.assign(n,{subscribe:a.subscribe??e.subscribe,on:a.on??e.on,[ZW]:Z0e(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 sG(e,{parent:t}={parent:r2e()}){if(e)return BW(x2e({parent:t??eG,clients:e}));if(t===null)throw Error(`received null parent, this usage is not allowed`);return t}var cG=e=>{let t=sG(),n=QW(t),r=(0,_W.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,_W.useDebugValue)(r),r},S2e=e=>{let t=sG(),n=xW(!1),r=n.current?null:e(t);return cG(()=>n.current?e(t):r),()=>(n.current=!0,e(t))},C2e=Object.freeze({});function lG({getItemState:e,children:t}){return w2e(t(S2e(e)))}var w2e=e=>{let t=typeof e==`object`&&e&&`type`in e?e:null,n=t?.type,r=t?.key;return SW(()=>t,[n,r,typeof t?.props==`object`&&t.props!=null&&Object.entries(t.props).length===0?C2e:t?.props])??e},T2e=O.createContext(!0);function uG(){throw Error(`A function wrapped in useEffectEvent can't be called during rendering.`)}var E2e=`use`in O.default?()=>{try{return O.use(T2e)}catch{return!1}}:()=>!1;function D2e(e){let t=O.useRef(uG);return O.useInsertionEffect(()=>{t.current=e},[e]),(...e)=>{E2e()&&uG();let n=t.current;return n(...e)}}var O2e=(e,t)=>{let n=sG(),r=D2e(t),{scope:i,event:a}=iG(e);wW(()=>n.on({scope:i,event:a},r),[n,i,a])},k2e=W0e(e=>{if(e.key===void 0)throw Error(`useClientResource: Element has no key`);return BW(Y0e(e))});function dG(e,t){let n=VW(()=>e().map(e=>k2e(e)),t),r=SW(()=>Object.keys(n),[n]),i=SW(()=>n.reduce((e,t,n)=>(e[t.key]=n,e),{}),[n]);return{state:SW(()=>n.map(e=>e.state),[n]),get:e=>{if(`index`in e){if(e.index<0||e.index>=r.length)throw Error(`useClientLookup: 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(`useClientLookup: Key "${e.key}" not found`);return n[t].methods}}}var A2e=AW(function({toolkit:e,mcpApp:t}){let n=VW(()=>t?[jW(`mcpApp`,t)]:[],[t])[0],[r,i]=bW(()=>({})),a=SW(()=>({toolUIs:r,mcpApp:n,tools:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.map(e=>e.render)]))}),[r,n]),o=l2e(),s=CW((e,t,n)=>{let r={render:t,standalone:n?.standalone??!1};return i(t=>({...t,[e]:[...t[e]??[],r]})),()=>{i(t=>{let n=t[e]?.filter(e=>e!==r)??[];if(n.length>0)return{...t,[e]:n};let{[e]:i,...a}=t;return a})}},[]);return wW(()=>{if(!e)return;let t=[];for(let[n,r]of Object.entries(e)){let e=`render`in r?r.render:void 0,i=`renderText`in r?r.renderText:void 0,a=e??(i?qW(i):void 0);a&&t.push(s(n,a,{standalone:I0e(r)}))}let n=Object.entries(e).reduce((e,[t,n])=>{if(n.type===`mcp`)return e;let{display:r,render:i,renderText:a,...o}=n;return e[t]=o,e},{});return t.push(o.current.modelContext().register({getModelContext:()=>({tools:n})})),()=>{t.forEach(e=>e())}},[e,s,o]),{getState:()=>a,setToolUI:s}});rG(A2e,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=F0e())});var fG=e=>{let[,t]=bW(e.getState);return wW(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},j2e=AW(function({runtime:e}){let t=fG(e);return{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}),M2e=AW(function({runtime:e,index:t}){return BW(j2e({runtime:SW(()=>e.getAttachmentByIndex(t),[e,t])}))}),N2e=AW(function({item:e,onSteer:t,onRemove:n}){return{getState:()=>e,steer:t,remove:n}}),pG=AW(function({threadIdRef:e,messageIdRef:t,runtime:n}){let r=fG(n),i=u2e();wW(()=>{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`,n=>{i(`composer.attachmentAddError`,{threadId:e.current,...t&&{messageId:t.current},...n.attachmentId&&{attachmentId:n.attachmentId},reason:n.reason,message:n.message})})),()=>{for(let e of r)e()}},[n,i,e,t]);let a=dG(()=>r.attachments.map((e,t)=>jW(e.id,M2e({runtime:n,index:t}))),[r.attachments,n]),o=r.queue,s=dG(()=>o.map(e=>jW(e.id,N2e({item:e,onSteer:()=>n.steerQueueItem(e.id),onRemove:()=>n.removeQueueItem(e.id)}))),[o,n]),c=SW(()=>({text:r.text,role:r.role,attachments:a.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,canSend:r.canSend,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:r.type??`thread`,dictation:r.dictation,quote:r.quote,queue:o}),[r,a.state,o]);return{getState:()=>c,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:e=>s.get(e),__internal_getRuntime:()=>n}}),P2e=AW(function({runtime:e}){let t=fG(e);return{getState:()=>t,addToolResult:t=>e.addToolResult(t),resumeToolCall:t=>e.resumeToolCall(t),respondToToolApproval:t=>e.respondToToolApproval(t),__internal_getRuntime:()=>e}}),F2e=AW(function({runtime:e,index:t}){return BW(j2e({runtime:SW(()=>e.getAttachmentByIndex(t),[e,t])}))}),I2e=AW(function({runtime:e,index:t}){return BW(P2e({runtime:SW(()=>e.getMessagePartByIndex(t),[e,t])}))}),mG=AW(function({runtime:e,threadIdRef:t}){let n=fG(e),[r,i]=bW(!1),[a,o]=bW(!1),s=SW(()=>({get current(){return e.getState().id}}),[e]),c=XW(pG({runtime:e.composer,threadIdRef:t,messageIdRef:s})),l=dG(()=>n.content.map((t,n)=>jW(`toolCallId`in t&&t.toolCallId!=null?`toolCallId-${t.toolCallId}`:`index-${n}`,I2e({runtime:e,index:n}))),[n.content,e]),u=dG(()=>(n.attachments??[]).map((t,n)=>jW(t.id,F2e({runtime:e,index:n}))),[n.attachments,e]),d=SW(()=>({...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}}),L2e=AW(function({runtime:e,id:t,threadIdRef:n}){return BW(mG({runtime:SW(()=>e.getMessageById(t),[e,t]),threadIdRef:n}))}),hG=AW(function({runtime:e}){let t=fG(e),n=u2e();wW(()=>{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=SW(()=>({get current(){return e.getState().threadId}}),[e]),i=XW(pG({runtime:e.composer,threadIdRef:r})),a=dG(()=>t.messages.map(t=>jW(t.id,L2e({runtime:e,id:t.id,threadIdRef:r}))),[t.messages,e,r]),o=SW(()=>({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,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}}),R2e=AW(function({runtime:e}){let t=fG(e),n=u2e();return wW(()=>{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,updateCustom:e.updateCustom,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}),gG=AW(function({runtime:e,id:t}){return BW(R2e({runtime:SW(()=>e.getItemById(t),[e,t])}))}),_G=AW(function({runtime:e,__internal_assistantRuntime:t}){let n=fG(e),r=XW(hG({runtime:e.main})),i=dG(()=>Object.keys(n.threadItems).map(t=>jW(t,gG({runtime:e,id:t}))),[n.threadItems,e]),a=SW(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThreadId??null,isLoading:n.isLoading,isLoadingMore:n.isLoadingMore,hasMore:n.hasMore,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,n)=>{await e.switchToThread(t,n)},switchToNewThread:async()=>{await e.switchToNewThread()},getLoadThreadsPromise:()=>e.getLoadThreadsPromise(),reload:()=>e.reload(),loadMore:()=>e.loadMore(),__internal_getAssistantRuntime:()=>t}}),z2e=AW(function(e){return{getState:()=>e}}),B2e=AW(function(e){let[t]=bW(()=>({suggestions:(e??[]).map(e=>typeof e==`string`?{title:e,label:``,prompt:e}:{title:e.title,label:e.label,prompt:e.prompt})})),n=dG(()=>t.suggestions.map((e,t)=>jW(t,z2e(e))),[t.suggestions]);return{getState:()=>t,suggestion:({index:e})=>n.get({index:e})}}),vG=AW(function(e){let t=l2e();return wW(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),BW(_G({runtime:e.threads,__internal_assistantRuntime:e}))}),V2e=(e,t)=>{e.thread??=nG({source:`threads`,query:{type:`main`},get:e=>e.threads().thread(`main`)}),e.threadListItem??=nG({source:`threads`,query:{type:`main`},get:e=>e.threads().item(`main`)}),e.composer??=nG({source:`thread`,query:{},get:e=>e.threads().thread(`main`).composer()}),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=F0e()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=B2e())},H2e=AW(function(e){return BW(vG(e))});rG(H2e,(e,t)=>{V2e(e,t),!e.tools&&t.tools.source===null&&(e.tools=A2e({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=M0e())});var U2e=e=>e._core?.RenderComponent,W2e=(0,_W.memo)(({runtime:e,aui:t=null,children:n})=>{let r=sG({threads:H2e(e)},{parent:t}),i=U2e(e);return(0,A.jsxs)(tG,{value:r,children:[i&&(0,A.jsx)(i,{}),n]})}),G2e=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},K2e=(e=>e?G2e(e):G2e),q2e=e=>e;function yG(e,t=q2e){let n=O.useSyncExternalStore(e.subscribe,O.useCallback(()=>t(e.getState()),[e,t]),O.useCallback(()=>t(e.getInitialState()),[e,t]));return O.useDebugValue(n),n}var J2e=e=>{let t=K2e(e),n=e=>yG(t,e);return Object.assign(n,t),n},bG=(e=>e?J2e(e):J2e),Y2e={toResponse(e,t){return new Response(Y2e.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return Y2e.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},X2e=()=>{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}},Z2e=()=>{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=X2e(),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()}}))}}},Q2e=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())}},$2e=e=>new ReadableStream({start(t){return e.start?.(new Q2e(t))},pull(t){return e.pull?.(new Q2e(t))},cancel(t){return e.cancel?.(t)}}),e4e=()=>{let e;return[$2e({start(t){e=t}}),e]},t4e=class{_controller;_isClosed=!1;_mergeTask;constructor(e){this._controller=e;let t=$2e({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.modelContent===void 0?{}:{modelContent:e.modelContent},...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())}},n4e=e=>new ReadableStream({start(t){return e.start?.(new t4e(t))},pull(t){return e.pull?.(new t4e(t))},cancel(t){return e.cancel?.(t)}}),r4e=()=>{let e;return[n4e({start(t){e=t}}),e]},i4e=class{value=-1;up(){return++this.value}},a4e=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}},xG=class extends TransformStream{constructor(e){let t=new i4e,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]})}})}},SG=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,`readable`,{value:t,writable:!1})}};let o4e=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r};var s4e=o4e(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),c4e=class e{_state;_parentId;constructor(e){this._state=e||{merger:Z2e(),contentCounter:new i4e}}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 a4e(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new xG(this._state.contentCounter)))}appendText(e){(this._state.append?.kind!==`text`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`text`,parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){(this._state.append?.kind!==`reasoning`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`reasoning`,parentId:this._parentId,controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,t]=e4e();return this._addPart(this._withParentIdOption({type:`text`}),e),t}addReasoningPart(){let[e,t]=e4e();return this._addPart(this._withParentIdOption({type:`reasoning`}),e),t}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??s4e(),[i,a]=r4e();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 l4e(e){let t=new c4e;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 u4e(){let{resolve:e,promise:t}=X2e(),n;return[l4e(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}var d4e=class extends TransformStream{constructor(e,t,n){let[r,i]=u4e(),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)}};function f4e(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 p4e=d(s(((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}))(),1),m4e=Symbol(`aui.parse-partial-json-object.meta`),CG=e=>{if(e.length===0)return{[m4e]:{state:`partial`,partialPath:[]}};try{let t=p4e.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[m4e]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=f4e(e),r=p4e.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[m4e]={state:`partial`,partialPath:n},r}catch{return}}},wG=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(t,n,r){if(n.length===0)return r(t);if(t??={},typeof t!=`object`)throw Error(`Invalid path: [${n.join(`, `)}]`);let[i,...a]=n;if(Array.isArray(t)){let o=Number(i);if(Number.isNaN(o))throw Error(`Expected array index at [${n.join(`, `)}]`);if(o>t.length||o<0)throw Error(`Insert array index out of bounds`);let s=[...t];return s[o]=e.updatePath(s[o],a,r),s}let o={...t};return o[i]=e.updatePath(o[i],a,r),o}},h4e=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}}},g4e=({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:{}}}),_4e=(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}}},v4e=(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}`)},y4e=(e,t)=>_4e(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}),b4e=(e,t)=>_4e(e,t,e=>({...e,status:{type:`complete`,reason:`unknown`}})),x4e=(e,t)=>_4e(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=CG(n)??e.args;return{...e,argsText:n,args:r}}else throw Error(`text-delta received but part is neither text nor tool-call`)}),S4e=(e,t)=>_4e(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.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}};throw Error(`Result chunk received but part is not a tool-call`)}),C4e=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=w4e(t);return{...e,status:n}},w4e=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},T4e=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),E4e=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),D4e=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),O4e=(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:s4e(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},k4e=(e,t)=>({...e,status:{type:`incomplete`,reason:`error`,error:t.error}}),A4e=(e,t)=>{let n=new wG(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},TG=(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)},j4e=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},M4e=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n}={}){let r=e??g4e(),i=new h4e,a,o=t?j4e(()=>{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=v4e(r,e),e.part.type===`tool-call`&&i.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:r=y4e(r,e);break;case`part-finish`:r=b4e(r,e);break;case`text-delta`:r=x4e(r,e),i.recordFirstToken();break;case`result`:r=S4e(r,e);break;case`message-finish`:r=C4e(r,e);break;case`annotations`:r=T4e(r,e);break;case`data`:r=E4e(r,e);break;case`step-start`:r=D4e(r,e);break;case`step-finish`:r=O4e(r,e);break;case`error`:r=k4e(r,e),n?.(e.error);break;case`update-state`:r=A4e(r,e);break;default:throw Error(`Unsupported chunk type: ${t}`)}r.status.type!==`running`&&(r={...r,metadata:{...r.metadata,timing:TG(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=C4e(r,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),r={...r,metadata:{...r.metadata,timing:TG(i,r)}},e.enqueue(r)}}})}},N4e=class extends SG{constructor(){super(e=>{let t=new d4e({transform(e,t){t.appendText(e)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},P4e=class e{readable;constructor(e){this.readable=e,this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new M4e))}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)]}},F4e=Symbol.for(`aui.tool-response`),I4e=class e{get[F4e](){return!0}artifact;result;isError;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact),this.result=e.result,this.isError=e.isError??!1,e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&F4e in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?`<no result>`:t})}},L4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({attachment:nG({source:`message`,query:{type:`index`,index:e},get:t=>t.message().attachment({index:e})})}),children:t}),R4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({attachment:nG({source:`composer`,query:{type:`index`,index:e},get:t=>t.composer().attachment({index:e})})}),children:t}),z4e=({runtime:e,children:t})=>(0,A.jsx)(tG,{value:sG({threadListItem:R2e({runtime:e})}),children:t}),EG=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({message:nG({source:`thread`,query:{type:`index`,index:e},get:t=>t.thread().message({index:e})}),composer:nG({source:`message`,query:{},get:t=>t.thread().message({index:e}).composer()})}),children:t}),B4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({part:nG({source:`message`,query:{type:`index`,index:e},get:t=>t.message().part({index:e})})}),children:t}),V4e=AW(function({text:e,isRunning:t}){let n=SW(()=>({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`)},respondToToolApproval:()=>{throw Error(`Not supported`)}}}),H4e=({text:e,isRunning:t=!1,children:n})=>(0,A.jsx)(tG,{value:sG({part:V4e({text:e,isRunning:t})}),children:n}),U4e=Object.freeze({type:`complete`}),W4e=AW(function({parts:e,getMessagePart:t}){let[n,r]=bW(!0),i=SW(()=>e[e.length-1]?.status??U4e,[e]),a=SW(()=>({parts:e,collapsed:n,status:i}),[e,n,i]);return{getState:()=>a,setCollapsed:r,part:t}}),G4e=({startIndex:e,endIndex:t,children:n})=>{let r=cG(e=>e.message.parts).slice(e,t+1),i=sG();return(0,A.jsx)(tG,{value:sG({chainOfThought:W4e({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})},DG=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({suggestion:nG({source:`suggestions`,query:{index:e},get:t=>t.suggestions().suggestion({index:e})})}),children:t}),K4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({queueItem:nG({source:`composer`,query:{index:e},get:t=>t.composer().queueItem({index:e})})}),children:t}),q4e=Symbol(`innerMessage`),OG=Symbol(`skip-update`);function J4e(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 kG=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)}}},AG=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e){for(let t of this._subscriptions)t(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()}}},jG=class extends AG{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e;let t=e.getState();if(t===OG)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===OG||J4e(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){return this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()})}},Y4e=class extends AG{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!==OG&&(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()})}},MG=class extends AG{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?.()}}},X4e=class extends AG{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=e=>{this.notifySubscribers(e)},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?.()}}},Z4e=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)}},Q4e=class extends Z4e{_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)}},NG=class extends Q4e{get source(){return`thread-composer`}},$4e=class extends Q4e{get source(){return`edit-composer`}},e3e=class extends Z4e{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},PG=Object.freeze([]),t3e=Object.freeze({}),n3e=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??PG,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??t3e,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??PG,value:e?.text??``}),r3e=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??PG,runConfig:e?.runConfig??t3e,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??PG,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),i3e=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.steerQueueItem=this.steerQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.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()}steerQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.steerQueueItem(e)}removeQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.removeQueueItem(e)}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 X4e({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},a3e=class extends i3e{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new Y4e({path:e.path,getState:()=>n3e(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 NG(new jG({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`}:OG},subscribe:e=>this._core.subscribe(e)}),this._core)}},FG=class extends i3e{_beginEdit;get path(){return this._core.path}get type(){return`edit`}_getState;constructor(e,t){let n=new Y4e({path:e.path,getState:()=>r3e(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 $4e(new jG({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`}:OG},subscribe:e=>this._core.subscribe(e)}),this._core)}},IG=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
187
|
+
`:``)})}return n};const d1e=({programId:e,cliMeta:t,commandPath:n})=>(0,A.jsx)(j,{component:`pre`,style:{fontFamily:`var(--mantine-font-family-monospace)`,fontSize:`var(--mantine-font-size-sm)`,lineHeight:1.6,margin:0,whiteSpace:`pre-wrap`,wordBreak:`break-word`},children:(0,O.useMemo)(()=>u1e(c1e(e,t,n)),[e,t,n]).map((e,t)=>e.type===`heading`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-yellow-5)`,fontWeight:600},children:e.text},t):e.type===`command`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-blue-5)`},children:e.text},t):e.type===`flag`?(0,A.jsx)(`span`,{style:{color:`var(--mantine-color-green-5)`},children:e.text},t):(0,A.jsx)(`span`,{children:e.text},t))});var f1e=({programs:e,cliRenderers:t,searchQuery:n})=>{let[r,i]=(0,O.useState)(e[0]?.wireId||``),[a,o]=(0,O.useState)([]),[s,c]=(0,O.useState)(()=>new Set(e.length>0?[e[0].wireId]:[])),l=(0,O.useMemo)(()=>e.find(e=>e.wireId===r),[e,r]),u=(0,O.useMemo)(()=>l?{programs:{[r]:{program:l.program||r,commands:l.commands,options:l.options,defaultRenderName:l.defaultRenderName}},renderers:t}:{programs:{},renderers:{}},[l,r,t]),d=e=>{c(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},f=e=>{i(e),o([]),s.has(e)||c(t=>new Set(t).add(e))},p=(e,t)=>{r!==e&&(i(e),s.has(e)||c(t=>new Set(t).add(e))),o([t])},m=a.length>0?`$ ${r} ${a.join(` `)} --help`:`$ ${r} --help`;return e.length,(0,A.jsxs)(j,{className:Qb.flexRow,children:[(0,A.jsx)(j,{className:Qb.listPaneFixed,style:{width:280,minWidth:220},children:(0,A.jsx)(Od,{style:{flex:1},children:e.map(e=>{let t=e.wireId===r,i=s.has(e.wireId),o=Object.entries(e.commands||{}),c=n.toLowerCase(),l=c?o.filter(([e,t])=>e.includes(c)||t.description?.toLowerCase().includes(c)):o;return c&&l.length===0&&!e.wireId.includes(c)?null:(0,A.jsxs)(O.Fragment,{children:[(0,A.jsxs)(kd,{onClick:()=>t?d(e.wireId):f(e.wireId),style:{display:`flex`,alignItems:`center`,gap:6,padding:`7px 12px`,fontSize:11,color:t?`var(--app-meta-value)`:`var(--app-text)`,borderLeft:t?`2px solid rgba(6,182,212,0.4)`:`2px solid transparent`,width:`100%`,opacity:t?1:.6,cursor:`pointer`},children:[i?(0,A.jsx)(Iy,{size:9,color:`var(--app-section-label)`}):(0,A.jsx)(Ly,{size:9,color:`var(--app-section-label)`}),(0,A.jsx)(N,{size:`sm`,ff:`monospace`,style:{flex:1},children:e.wireId}),(0,A.jsx)(kf,{size:`sm`,variant:`light`,color:`cyan`,ff:`monospace`,children:`cli`})]}),i&&l.map(([n,r])=>{let i=t&&a.length===1&&a[0]===n;return(0,A.jsxs)(kd,{onClick:()=>p(e.wireId,n),className:Qb.listItem,"data-active":i,style:{display:`flex`,alignItems:`center`,gap:7,padding:`5px 12px 5px 24px`},children:[(0,A.jsx)(j,{className:Qb.typeDot,style:{background:`rgba(124,58,237,0.4)`}}),(0,A.jsxs)(j,{style:{flex:1,minWidth:0},children:[(0,A.jsx)(N,{size:`sm`,ff:`monospace`,fw:i?600:400,c:i?`var(--app-meta-value)`:`var(--app-text)`,truncate:!0,children:n}),r.description&&(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:i?`var(--app-meta-label)`:`var(--app-text-muted)`,truncate:!0,style:{fontSize:9},children:r.description})]})]},n)})]},e.wireId)})})}),(0,A.jsxs)(j,{className:`${Qb.detailPane} ${Qb.flexColumn}`,style:{overflow:`hidden`},children:[(0,A.jsxs)(j,{className:Qb.gridHeader,style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,A.jsxs)(N,{size:`sm`,ff:`monospace`,c:`var(--app-text-muted)`,style:{flex:1},children:[(0,A.jsx)(N,{component:`span`,c:`violet`,ff:`monospace`,children:`$`}),` `,(0,A.jsx)(N,{component:`span`,c:`var(--app-text)`,ff:`monospace`,children:m.slice(2)})]}),(0,A.jsx)(op,{value:typeof document<`u`&&document.getElementById(`cli-terminal`)?.innerText||``,children:({copied:e,copy:t})=>(0,A.jsx)(dh,{label:e?`Copied`:`Copy`,children:(0,A.jsx)(Qd,{variant:`subtle`,color:e?`teal`:`gray`,size:`sm`,onClick:t,children:e?(0,A.jsx)(Fy,{size:12}):(0,A.jsx)(Xfe,{size:12})})})})]}),(0,A.jsx)(j,{id:`cli-terminal`,className:Qb.overflowAuto,style:{flex:1,padding:`20px 24px`,lineHeight:1.9,fontSize:11,fontFamily:`var(--mantine-font-family-monospace)`},children:l?(0,A.jsx)(d1e,{programId:r,cliMeta:u,commandPath:a}):(0,A.jsx)(N,{c:`dimmed`,ff:`monospace`,size:`sm`,children:`No CLI programs found.`})})]})]})};const rW=({searchQuery:e})=>{let{meta:t}=Xb(),n=t.cliMeta||[];return n.length===0?(0,A.jsx)(zz,{icon:vb,title:`No CLI programs found`,description:`Define CLI programs in your project to see them here.`,docsHref:`https://pikku.dev/docs/core-features/cli`}):(0,A.jsx)(sx,{children:(0,A.jsx)(f1e,{programs:n,cliRenderers:t.cliRenderers||{},searchQuery:e})})},p1e=({searchQuery:e})=>(0,A.jsx)(O.Suspense,{fallback:(0,A.jsx)(Ff,{h:`100%`,children:(0,A.jsx)(Xd,{})}),children:(0,A.jsx)(rW,{searchQuery:e})});var m1e=[{value:`http`,label:`HTTP`},{value:`channels`,label:`Channels`},{value:`mcp`,label:`MCP`},{value:`cli`,label:`CLI`}],h1e={http:`Search routes...`,channels:`Search channels...`,mcp:`Search MCP tools, resources, prompts...`,cli:`Search commands...`},g1e=({httpHero:e,channelsHero:t,mcpHero:n})=>{let[r,i]=Dy(),[a,o]=(0,O.useState)(``),s=r.get(`tab`)||`http`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`APIs`,description:`Browse HTTP routes, channels, MCP servers, and CLI surfaces`,docsHref:`https://pikku.dev/docs/wiring/http`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:h1e[s],leftSection:(0,A.jsx)(pb,{size:14}),value:a,onChange:e=>o(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:s,onChange:e=>{o(``),i({tab:e})},data:m1e})]})}),emptyPanelMessage:`Select an item to view details`,children:(()=>{switch(s){case`channels`:return(0,A.jsx)(RQe,{searchQuery:a,emptyHero:t});case`mcp`:return(0,A.jsx)(zQe,{searchQuery:a,emptyHero:n});case`cli`:return(0,A.jsx)(p1e,{searchQuery:a});default:return(0,A.jsx)(wQe,{searchQuery:a,emptyHero:e})}})()})})};const _1e=e=>(0,A.jsx)(O.Suspense,{fallback:(0,A.jsx)(Ff,{h:`100vh`,children:(0,A.jsx)(Xd,{})}),children:(0,A.jsx)(g1e,{...e})});var v1e=({schedule:e})=>(0,A.jsx)(af,{gap:3,wrap:`nowrap`,children:e.split(` `).map((e,t)=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(245,158,11,0.08)`,border:`0.5px solid rgba(245,158,11,0.18)`,color:`#fbbf24`,padding:`1px 5px`},children:e},t))}),y1e=e=>{let t=Math.floor((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`};const b1e=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),r=by(),{openScheduler:i}=ox(),{data:a={}}=Ur({queryKey:[`console:getSchedulerHistory`],queryFn:()=>r.invoke(`console:getSchedulerHistory`).then(e=>e??{}),refetchInterval:15e3}),o=(0,O.useMemo)(()=>n.schedulerMeta?Object.entries(n.schedulerMeta).map(([e,t])=>({name:e,...t})):[],[n.schedulerMeta]);return(0,A.jsx)(Bz,{title:`Schedulers`,icon:By,docsHref:`https://pikku.dev/docs/wiring/scheduled-tasks`,data:(0,O.useMemo)(()=>{if(!e)return o;let t=e.toLowerCase();return o.filter(e=>e.name?.toLowerCase().includes(t)||e.pikkuFuncId?.toLowerCase().includes(t)||e.schedule?.toLowerCase().includes(t))},[o,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.wireId||e.name}),e.pikkuFuncId&&(0,A.jsxs)(N,{size:`xs`,c:`dimmed`,ff:`monospace`,truncate:!0,children:[e.pikkuFuncId,`()`]})]})},{key:`schedule`,header:`SCHEDULE`,render:e=>e.schedule?(0,A.jsx)(v1e,{schedule:e.schedule}):null},{key:`lastRun`,header:`LAST RUN`,width:120,render:e=>{let t=a[e.wireId||e.name]?.lastRun??null;return t?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:t.status===`failed`?`var(--mantine-color-red-5)`:`var(--mantine-color-green-5)`,children:t.status}),(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:`var(--app-text-muted)`,children:y1e(t.timestamp)})]}):(0,A.jsx)(N,{size:`xs`,ff:`monospace`,c:`var(--app-meta-label)`,children:`—`})}}],[a]),getKey:e=>e.name,onRowClick:e=>i(e.wireId||e.name,e),emptyMessage:`No scheduled tasks found.`,emptyHero:t})},x1e=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),r=by(),{openQueue:i}=ox(),{data:a}=Ur({queryKey:[`console:getQueueDepths`],queryFn:()=>r.invoke(`console:getQueueDepths`).then(e=>e??{}),refetchInterval:5e3}),o=(0,O.useMemo)(()=>n.queueMeta?Object.entries(n.queueMeta).map(([e,t])=>({name:e,...t})):[],[n.queueMeta]);return(0,A.jsx)(Bz,{title:`Queues`,icon:$y,docsHref:`https://pikku.dev/docs/wiring/queues`,data:(0,O.useMemo)(()=>{if(!e)return o;let t=e.toLowerCase();return o.filter(e=>e.name?.toLowerCase().includes(t)||e.wireId?.toLowerCase().includes(t)||e.pikkuFuncId?.toLowerCase().includes(t))},[o,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.wireId||e.name}),e.pikkuFuncId&&(0,A.jsx)(N,{size:`xs`,c:`dimmed`,ff:`monospace`,truncate:!0,children:e.pikkuFuncId})]})},{key:`queued`,header:`QUEUED`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.queued?`var(--app-meta-value)`:`var(--app-meta-label)`,children:t?.queued??`—`})}},{key:`active`,header:`ACTIVE`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.active?`var(--mantine-color-green-5)`:`var(--app-meta-label)`,children:t?.active??`—`})}},{key:`failed`,header:`FAILED`,width:80,render:e=>{let t=a?.[e.wireId||e.name];return(0,A.jsx)(N,{size:`sm`,ff:`monospace`,c:t?.failed?`var(--mantine-color-red-5)`:`var(--app-meta-label)`,children:t?.failed??`—`})}}],[a]),getKey:e=>e.name,onRowClick:e=>i(e.wireId||e.name,e),emptyMessage:`No queue workers found.`,emptyHero:t})};var S1e=[{key:`name`,header:`NAME`,render:e=>(0,A.jsx)(N,{fw:500,ff:`monospace`,truncate:!0,children:e.name})},{key:`source`,header:`SOURCE`,render:e=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(124,58,237,0.08)`,border:`0.5px solid rgba(124,58,237,0.18)`,color:`#a78bfa`,maxWidth:200,overflow:`hidden`,textOverflow:`ellipsis`},children:e.source?.pikkuFuncId||`Missing`})},{key:`target`,header:`TARGET`,render:e=>(0,A.jsx)(kf,{size:`sm`,ff:`monospace`,tt:`none`,style:{background:`rgba(6,182,212,0.07)`,border:`0.5px solid rgba(6,182,212,0.15)`,color:`#06b6d4`,maxWidth:200,overflow:`hidden`,textOverflow:`ellipsis`},children:e.trigger?.pikkuFuncId||`Missing`})}];const iW=({searchQuery:e,emptyHero:t})=>{let{meta:n}=Xb(),{openTrigger:r}=ox(),i=(0,O.useMemo)(()=>{let e=new Set;return n.triggerSourceMeta&&Object.keys(n.triggerSourceMeta).forEach(t=>e.add(t)),n.triggerMeta&&Object.keys(n.triggerMeta).forEach(t=>e.add(t)),Array.from(e).sort().map(e=>({name:e,source:n.triggerSourceMeta?.[e]||null,trigger:n.triggerMeta?.[e]||null}))},[n.triggerMeta,n.triggerSourceMeta]);return(0,A.jsx)(Bz,{title:`Triggers`,icon:wb,docsHref:`https://pikku.dev/docs/wiring/triggers`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.source?.pikkuFuncId?.toLowerCase().includes(t)||e.trigger?.pikkuFuncId?.toLowerCase().includes(t))},[i,e]),columns:S1e,getKey:e=>e.name,onRowClick:e=>r(e.name,e.trigger),emptyMessage:`No triggers found.`,emptyHero:t})};var C1e=[{value:`schedulers`,label:`Schedulers`},{value:`queues`,label:`Queues`},{value:`triggers`,label:`Triggers`}],w1e={schedulers:`Search scheduled tasks...`,queues:`Search queue workers...`,triggers:`Search triggers...`};const T1e=({queuesHero:e,triggersHero:t,schedulersHero:n})=>{let[r,i]=Dy(),[a,o]=(0,O.useState)(``),s=r.get(`tab`)||`schedulers`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Jobs`,description:`Scheduled tasks, queues, and triggers`,docsHref:`https://pikku.dev/docs/wiring/scheduled-tasks`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:w1e[s],leftSection:(0,A.jsx)(pb,{size:14}),value:a,onChange:e=>o(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:s,onChange:e=>{o(``),i({tab:e})},data:C1e})]})}),emptyPanelMessage:`Select an item to view details`,children:(()=>{switch(s){case`queues`:return(0,A.jsx)(x1e,{searchQuery:a,emptyHero:e});case`triggers`:return(0,A.jsx)(iW,{searchQuery:a,emptyHero:t});default:return(0,A.jsx)(b1e,{searchQuery:a,emptyHero:n})}})()})})};var E1e=[{key:`name`,header:`NAME`,render:e=>(0,A.jsx)(N,{fw:500,children:e.name})},{key:`functions`,header:`FUNCTIONS`,align:`right`,render:e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`functions`,value:e.funcCount})}];const D1e=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),r=(0,O.useMemo)(()=>{let e=new Map;return t.functions?.forEach(t=>{if(t.services?.services)for(let n of t.services.services){let r=e.get(n)||{funcCount:0,functions:[]};r.funcCount++,r.functions.push(t.pikkuFuncId),e.set(n,r)}}),Array.from(e.entries()).map(([e,t])=>({name:e,...t})).sort((e,t)=>t.funcCount-e.funcCount)},[t.functions]);return(0,A.jsx)(Bz,{title:`Services`,icon:mb,docsHref:`https://pikku.dev/docs/core-features/services`,data:(0,O.useMemo)(()=>{if(!e)return r;let t=e.toLowerCase();return r.filter(e=>e.name.toLowerCase().includes(t)||e.functions.some(e=>e.toLowerCase().includes(t)))},[r,e]),columns:E1e,getKey:e=>e.name,onRowClick:()=>{},emptyMessage:`No services found.`,loading:n})},X=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),{openMiddleware:r}=ox(),i=(0,O.useMemo)(()=>{if(!t.middlewareGroupsMeta)return[];let e=t.middlewareGroupsMeta.definitions||{},n=[];for(let[t,r]of Object.entries(e))r.exportedName!==null&&n.push({id:`middleware::def::${t}`,name:r.name||r.exportedName||t,data:{...r,_id:t}});return n},[t.middlewareGroupsMeta]);return(0,A.jsx)(Bz,{title:`Middleware`,icon:Xy,docsHref:`https://pikku.dev/docs/core-features/middleware`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.data?.description?.toLowerCase().includes(t))},[i,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.name}),e.data?.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,lineClamp:1,children:e.data.description})]})},{key:`type`,header:`TYPE`,align:`right`,render:e=>{let t=e.data?.wires?.wires??[],n=new Set([`session`,`setSession`,`clearSession`,`getSession`,`hasSessionChanged`]),r=t.some(e=>n.has(e)),i=t.filter(e=>!n.has(e));return(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[r&&(0,A.jsx)(fx,{type:`flag`,flag:`session`}),i.map(e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`wire`,value:e},e)),e.data?.factory&&(0,A.jsx)(fx,{type:`flag`,flag:`factory`})]})}}],[]),getKey:e=>e.id,onRowClick:e=>r(e.id,e.data),emptyMessage:`No middleware found.`,loading:n})},aW=({searchQuery:e})=>{let{meta:t,loading:n}=Xb(),{openPermission:r}=ox(),i=(0,O.useMemo)(()=>{if(!t.permissionsGroupsMeta)return[];let e=t.permissionsGroupsMeta.definitions||{},n=[];for(let[t,r]of Object.entries(e))r.exportedName!==null&&n.push({id:`permission::def::${t}`,name:r.name||r.exportedName||t,data:{...r,_id:t}});return n},[t.permissionsGroupsMeta]);return(0,A.jsx)(Bz,{title:`Permissions`,icon:gb,docsHref:`https://pikku.dev/docs/core-features/permission-guards`,data:(0,O.useMemo)(()=>{if(!e)return i;let t=e.toLowerCase();return i.filter(e=>e.name.toLowerCase().includes(t)||e.data?.description?.toLowerCase().includes(t))},[i,e]),columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.name}),e.data?.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,lineClamp:1,children:e.data.description})]})},{key:`type`,header:`TYPE`,align:`right`,render:e=>{let t=e.data?.wires?.wires??[],n=new Set([`session`,`setSession`,`clearSession`,`getSession`,`hasSessionChanged`]),r=t.some(e=>n.has(e)),i=t.filter(e=>!n.has(e));return(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[r&&(0,A.jsx)(fx,{type:`flag`,flag:`session`}),i.map(e=>(0,A.jsx)(fx,{type:`dynamic`,badge:`wire`,value:e},e)),e.data?.factory&&(0,A.jsx)(fx,{type:`flag`,flag:`factory`})]})}}],[]),getKey:e=>e.id,onRowClick:e=>r(e.id,e.data),emptyMessage:`No permissions found.`,loading:n})};var O1e=[{value:`services`,label:`Services`},{value:`middleware`,label:`Middleware`},{value:`permissions`,label:`Permissions`}],k1e={services:`Search services...`,middleware:`Search middleware...`,permissions:`Search permissions...`};const A1e=()=>{let[e,t]=Dy(),[n,r]=(0,O.useState)(``),i=e.get(`tab`)||`services`;return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Runtime`,description:`Services, middleware, and permission guards`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:k1e[i],leftSection:(0,A.jsx)(pb,{size:14}),value:n,onChange:e=>r(e.target.value),size:`xs`,style:{width:240}}),(0,A.jsx)(fh,{size:`xs`,value:i,onChange:e=>{r(``),t({tab:e})},data:O1e})]})}),emptyPanelMessage:`Select an item to view its details`,children:(()=>{switch(i){case`middleware`:return(0,A.jsx)(X,{searchQuery:n});case`permissions`:return(0,A.jsx)(aW,{searchQuery:n});default:return(0,A.jsx)(D1e,{searchQuery:n})}})()})})};var j1e=`https://pikku.dev/docs`;const M1e=({templateNames:e,templates:t,onSelect:n,headerRight:r})=>{let[i,a]=(0,O.useState)(``),o=(0,O.useMemo)(()=>e.map(e=>{let n=t[e],r=(n.variables??[]).length,i=Object.keys(n.locales??{}).length,a=[];return r>0&&a.push(`${r} ${r===1?`variable`:`variables`}`),i>0&&a.push(`${i} ${i===1?`locale`:`locales`}`),{name:e,meta:a}}),[e,t]),s=(0,O.useMemo)(()=>{let e=i.toLowerCase();return e?o.filter(t=>t.name.toLowerCase().includes(e)):o},[o,i]);return(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`,docsHref:j1e,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:`Search email templates...`,leftSection:(0,A.jsx)(pb,{size:14}),value:i,onChange:e=>a(e.target.value),size:`xs`,style:{width:240}}),r]})}),children:(0,A.jsx)(SQe,{items:s,onOpen:n,icon:ib,emptyTitle:`No email templates match the current search.`,docsHref:j1e})})};var N1e=`https://pikku.dev/docs`;function P1e(e){return{type:`object`,properties:Object.fromEntries(e.map(e=>[e,{type:`string`,title:e}]))}}const F1e=({hero:e,headerRight:t})=>{let{meta:n,loading:r}=Xb(),[i,a]=Dy(),[o,s]=(0,O.useState)({}),[c,l]=(0,O.useState)(`desktop`),[u,d]=(0,O.useState)(!1),[f,p]=(0,O.useState)(``),m=n.emailsMeta?.templates||{},h=(0,O.useMemo)(()=>Object.keys(m).sort((e,t)=>e.localeCompare(t)),[m]),g=i.get(`template`),_=g?m[g]:null,v=(0,O.useMemo)(()=>h.map(e=>({name:e,description:`${m[e].variables.length} variable${m[e].variables.length===1?``:`s`}`})),[h,m]),y=(0,O.useMemo)(()=>Object.keys(_?.locales??{}).sort((e,t)=>e.localeCompare(t)).map(e=>({label:e,value:e})),[_]),b=i.get(`locale`),x=_?y.find(e=>e.value===b)?.value||y[0]?.value||`en`:null;(0,O.useEffect)(()=>{!g||!x||i.get(`locale`)!==x&&a({template:g,locale:x},{replace:!0})},[i,x,g,a]);let S=_Ae(g,x??void 0,o,!!g&&!!x),C=(0,O.useMemo)(()=>P1e(_?.variables??[]),[_]),w=(0,O.useMemo)(()=>{if(!f)return v;let e=f.toLowerCase();return v.filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e))},[v,f]);if(r)return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`}),children:(0,A.jsx)(Ff,{h:`100%`,children:(0,A.jsx)(Xd,{})})})});if(h.length===0)return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Email Templates`,description:`Preview and inspect email templates with live variable rendering`}),children:(0,A.jsx)(zz,{icon:ib,hero:e,title:`No email templates found`,description:`Add an email templates directory to your project, then run:`,code:`pikku emails generate`,docsHref:N1e})})});if(!g||!_||!x)return(0,A.jsx)(sx,{children:(0,A.jsx)(M1e,{templateNames:h,templates:m,headerRight:t,onSelect:e=>{s({}),a({template:e,locale:Object.keys(m[e]?.locales??{}).sort((e,t)=>e.localeCompare(t))[0]??`en`})}})});let T=e=>{d(!1),p(``),s({}),a({template:e,locale:Object.keys(m[e]?.locales??{}).sort((e,t)=>e.localeCompare(t))[0]??`en`})};return(0,A.jsx)(j,{className:Qb.flexColumn,style:{height:`100vh`,padding:`var(--mantine-spacing-xl)`,gap:`var(--mantine-spacing-md)`},children:(0,A.jsxs)(j,{style:{flex:1,minHeight:0,display:`flex`,gap:`var(--mantine-spacing-md)`},children:[(0,A.jsxs)(j,{className:Qb.listSurfaceCard,style:{flex:1,minWidth:0,display:`flex`,flexDirection:`column`},children:[(0,A.jsxs)(j,{px:`md`,py:`xs`,style:{borderBottom:`1px solid var(--mantine-color-default-border)`,flexShrink:0},children:[(0,A.jsxs)(af,{gap:`sm`,justify:`space-between`,wrap:`nowrap`,children:[(0,A.jsxs)(af,{gap:`xs`,style:{minWidth:0},children:[(0,A.jsx)(ib,{size:16}),(0,A.jsx)(N,{fw:600,ff:`monospace`,truncate:!0,children:g}),S.data?.hash?(0,A.jsx)(kf,{variant:`outline`,color:`gray`,style:{flexShrink:0},children:S.data.hash.slice(0,10)}):null]}),(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,style:{flexShrink:0},children:[(0,A.jsx)(ph,{data:y,value:x,onChange:e=>{e&&(s({}),a({template:g,locale:e}))},allowDeselect:!1,size:`xs`,w:96}),(0,A.jsx)(fh,{value:c,onChange:e=>l(e),size:`xs`,data:[{label:(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[(0,A.jsx)(ab,{size:14}),(0,A.jsx)(`span`,{children:`Desktop`})]}),value:`desktop`},{label:(0,A.jsxs)(af,{gap:4,wrap:`nowrap`,children:[(0,A.jsx)(vpe,{size:14}),(0,A.jsx)(`span`,{children:`Mobile`})]}),value:`mobile`}]})]})]}),S.data?.subject&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,mt:4,children:S.data.subject})]}),(0,A.jsx)(j,{style:{flex:1,minHeight:0,overflow:`auto`},p:`md`,children:(0,A.jsxs)(kh,{gap:`md`,children:[S.isLoading?(0,A.jsx)(Ff,{py:`xl`,children:(0,A.jsx)(Xd,{})}):null,S.error?(0,A.jsx)(vf,{color:`red`,icon:(0,A.jsx)(bb,{size:16}),children:S.error instanceof Error?S.error.message:`Failed to render email preview`}):null,S.data?.missing?.length?(0,A.jsxs)(vf,{color:`yellow`,icon:(0,A.jsx)(bb,{size:16}),children:[`Missing source files: `,S.data.missing.join(`, `)]}):null,(0,A.jsx)(Ff,{py:`sm`,children:c===`desktop`?(0,A.jsx)(j,{style:{width:`100%`,maxWidth:960,height:720,border:`1px solid var(--app-row-border)`,borderRadius:8,overflow:`hidden`,background:`#fff`},children:(0,A.jsx)(`iframe`,{title:`Desktop email preview`,srcDoc:S.data?.html??``,style:{width:`100%`,height:`100%`,border:0,background:`#fff`}})}):(0,A.jsx)(j,{style:{width:390,maxWidth:`100%`,height:720,border:`1px solid var(--app-row-border)`,borderRadius:24,overflow:`hidden`,background:`#fff`},children:(0,A.jsx)(`iframe`,{title:`Mobile email preview`,srcDoc:S.data?.html??``,style:{width:`100%`,height:`100%`,border:0,background:`#fff`}})})}),S.data?.text?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(up,{}),(0,A.jsxs)(kh,{gap:`xs`,children:[(0,A.jsx)(N,{fw:600,children:`Text fallback`}),(0,A.jsx)(Lf,{block:!0,children:S.data.text})]})]}):null]})})]}),(0,A.jsxs)(j,{className:Qb.listSurfaceCard,style:{width:400,flexShrink:0,display:`flex`,flexDirection:`column`},children:[(0,A.jsxs)(qd,{opened:u,onChange:d,width:280,position:`bottom-start`,shadow:`md`,zIndex:1e4,children:[(0,A.jsx)(qd.Target,{children:(0,A.jsxs)(kd,{px:`sm`,py:`xs`,style:{width:`100%`,display:`flex`,alignItems:`center`,gap:4,borderBottom:`1px solid var(--mantine-color-default-border)`},onClick:()=>d(e=>!e),children:[(0,A.jsx)(N,{size:`sm`,fw:600,style:{flex:1,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:g}),(0,A.jsx)(Iy,{size:14,style:{flexShrink:0}})]})}),(0,A.jsxs)(qd.Dropdown,{p:0,children:[(0,A.jsx)(Xh,{placeholder:`Search templates...`,leftSection:(0,A.jsx)(pb,{size:14}),value:f,onChange:e=>p(e.currentTarget.value),styles:{input:{border:`none`,borderBottom:`1px solid var(--mantine-color-default-border)`,borderRadius:0}}}),(0,A.jsx)(Od.Autosize,{mah:300,children:(0,A.jsxs)(kh,{gap:0,children:[w.map(e=>(0,A.jsxs)(kd,{onClick:()=>T(e.name),py:`xs`,px:`sm`,style:{display:`flex`,alignItems:`center`,gap:8,backgroundColor:e.name===g?`var(--mantine-color-green-light)`:void 0},children:[e.name===g?(0,A.jsx)(Fy,{size:14,color:`var(--mantine-color-green-6)`}):(0,A.jsx)(j,{w:14}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(N,{size:`sm`,fw:e.name===g?500:400,children:e.name}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,children:e.description})]})]},e.name)),w.length===0&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ta:`center`,py:`md`,children:`No results`})]})})]})]}),(0,A.jsx)(j,{style:{flex:1,minHeight:0,overflow:`auto`},p:`md`,children:(0,A.jsxs)(kh,{gap:`lg`,children:[(0,A.jsx)(dk,{schema:C,submitLabel:`Render preview`,onSubmit:e=>s(e??{})},`${g}:${x}`),(0,A.jsx)(up,{}),(0,A.jsxs)(kh,{gap:`xs`,children:[(0,A.jsx)(N,{fw:600,children:`Template details`}),(0,A.jsxs)(af,{gap:`xs`,children:[(0,A.jsxs)(kf,{variant:`light`,children:[_.variables.length,` variables`]}),(0,A.jsxs)(kf,{variant:`light`,children:[Object.keys(_.locales).length,` locales`]})]}),S.data?.hash?(0,A.jsx)(Lf,{block:!0,children:S.data.hash}):null]})]})})]})]})})},I1e=({secrets:e,loading:t,installed:n=!0,emptyHero:r})=>{let{openSecret:i}=ox();return(0,A.jsx)(Bz,{title:`Secrets`,icon:Jy,docsHref:`https://pikku.dev/docs/core-features/secrets`,data:e,columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(af,{gap:`xs`,children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.displayName}),e.isOAuth2&&(0,A.jsx)(fx,{type:`label`,color:`gray`,children:`OAuth2`})]}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,children:e.description})]})},{key:`secretId`,header:`SECRET ID`,render:e=>(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ff:`monospace`,children:e.secretId})}],[]),getKey:e=>e.name,onRowClick:e=>i(e.name,{...e.rawData??e,installed:n}),emptyMessage:`No secrets found.`,loading:t,emptyHero:r})};var L1e=({emptyHero:e})=>{let{meta:t,loading:n}=Xb(),[r,i]=(0,O.useState)(``),a=(0,O.useMemo)(()=>t.secretsMeta?Object.entries(t.secretsMeta).map(([e,t])=>({name:e,displayName:t.displayName,description:t.description,secretId:t.secretId,isOAuth2:!!t.oauth2,rawData:t})):[],[t.secretsMeta]),o=(0,O.useMemo)(()=>{if(!r)return a;let e=r.toLowerCase();return a.filter(t=>t.name.toLowerCase().includes(e)||t.displayName?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.secretId?.toLowerCase().includes(e))},[a,r]);return(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Secrets`,description:`Encrypted secrets managed by pikku`,docsHref:`https://pikku.dev/docs/core-features/secrets`,filters:(0,A.jsx)(af,{gap:`sm`,wrap:`nowrap`,children:(0,A.jsx)(Xh,{placeholder:`Search secrets...`,leftSection:(0,A.jsx)(pb,{size:14}),value:r,onChange:e=>i(e.target.value),size:`xs`,style:{width:240}})})}),emptyPanelMessage:`Select a secret to view details`,children:(0,A.jsx)(I1e,{secrets:o,loading:n,emptyHero:e})})};const R1e=({emptyHero:e})=>(0,A.jsx)(sx,{children:(0,A.jsx)(L1e,{emptyHero:e})}),z1e=({variables:e,loading:t,installed:n=!0,emptyHero:r})=>{let{openVariable:i}=ox();return(0,A.jsx)(Bz,{title:`Environment Variables`,icon:hb,docsHref:`https://pikku.dev/docs/core-features/variables`,data:e,columns:(0,O.useMemo)(()=>[{key:`name`,header:`NAME`,render:e=>(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(N,{fw:500,truncate:!0,children:e.displayName}),e.description&&(0,A.jsx)(N,{size:`sm`,c:`dimmed`,truncate:!0,children:e.description})]})},{key:`variableId`,header:`VARIABLE ID`,render:e=>(0,A.jsx)(N,{size:`sm`,c:`dimmed`,ff:`monospace`,children:e.variableId})}],[]),getKey:e=>e.name,onRowClick:e=>i(e.name,{...e.rawData??e,installed:n}),emptyMessage:`No variables found.`,loading:t,emptyHero:r})};var B1e=({emptyHero:e})=>{let{meta:t,loading:n}=Xb(),[r,i]=(0,O.useState)(``),a=(0,O.useMemo)(()=>t.variablesMeta?Object.entries(t.variablesMeta).map(([e,t])=>({name:e,displayName:t.displayName,description:t.description,variableId:t.variableId,rawData:t})):[],[t.variablesMeta]),o=(0,O.useMemo)(()=>{if(!r)return a;let e=r.toLowerCase();return a.filter(t=>t.name.toLowerCase().includes(e)||t.displayName?.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.variableId?.toLowerCase().includes(e))},[a,r]);return(0,A.jsx)(Rz,{header:(0,A.jsx)(tx,{title:`Variables`,description:`Runtime configuration variables for this environment`,docsHref:`https://pikku.dev/docs/core-features/variables`,filters:(0,A.jsx)(af,{gap:`sm`,wrap:`nowrap`,children:(0,A.jsx)(Xh,{placeholder:`Search variables...`,leftSection:(0,A.jsx)(pb,{size:14}),value:r,onChange:e=>i(e.target.value),size:`xs`,style:{width:240}})})}),emptyPanelMessage:`Select a variable to view details`,children:(0,A.jsx)(z1e,{variables:o,loading:n,emptyHero:e})})};const V1e=({emptyHero:e})=>(0,A.jsx)(sx,{children:(0,A.jsx)(B1e,{emptyHero:e})}),H1e=({onOpen:e,headerRight:t,emptyHero:n,metricSlot:r})=>{let i=Ty(),{meta:a,loading:o}=Xb(),[s,c]=(0,O.useState)(``),l=(0,O.useMemo)(()=>a.agentsMeta?Object.entries(a.agentsMeta).map(([e,t])=>{let n=(t.tools??[]).length,r=(t.agents??[]).length,i=t.model?[{label:t.model,tone:`neutral`}]:[],a=[];return n>0&&a.push(`${n} ${n===1?`tool`:`tools`}`),r>0&&a.push(`${r} ${r===1?`sub-agent`:`sub-agents`}`),{name:e,badges:i,meta:a,description:t.summary??t.description,tags:t.tags}}).sort((e,t)=>e.name.localeCompare(t.name)):[],[a.agentsMeta]),u=(0,O.useMemo)(()=>{let e=s.toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||t.description?.toLowerCase().includes(e)||t.badges?.some(t=>t.label.toLowerCase().includes(e))):l},[l,s]);return(0,A.jsx)(sx,{children:(0,A.jsx)(Rz,{hidePanel:!0,header:(0,A.jsx)(tx,{title:`Agents`,description:`AI agents and their configurations`,docsHref:`https://pikku.dev/docs/wiring/ai-agents`,filters:(0,A.jsxs)(af,{gap:`sm`,wrap:`nowrap`,children:[(0,A.jsx)(Xh,{placeholder:`Search agents...`,leftSection:(0,A.jsx)(pb,{size:14}),value:s,onChange:e=>c(e.target.value),size:`xs`,style:{width:240}}),t]})}),children:(0,A.jsx)(SQe,{items:u,onOpen:t=>{e?e(t):i(`/agents/playground?id=${encodeURIComponent(t)}`)},loading:o,icon:Ny,emptyHero:n,emptyTitle:`No agents found`,emptyDescription:`Define agents in your project to see them here.`,docsHref:`https://pikku.dev/docs/wiring/ai-agents`,metricSlot:r})})})};var oW=typeof process<`u`&&!1,sW=null;function U1e(e,t){e.currentIndex=0;let n=sW;sW=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{sW=n}}function cW(){if(!sW)throw Error(`No resource fiber available`);return sW}function W1e(){return sW}function G1e(e){return oW?sW?.devStrictMode?sW.isFirstRender?`child`:`root`:e?`root`:null:null}var K1e=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],dirtyCells:[]}),lW=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},uW=(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()),lW(e)}}},q1e=(e,t)=>{t.dirty||(t.dirty=!0,e.markDirty?.(),e.root.dirtyCells.push(t))},J1e=(e,t)=>{let n=cW(),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},Y1e=e=>{cW().renderContext.effectTasks.push(e)},X1e=(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 Z1e(e,t,n,r){let i=J1e(`reducer`,()=>{let t=cW(),a=r?r(n):n;return oW&&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};X1e(t,()=>t.root.dirtyCells.length===0&&!r.hasEagerState&&(r.eagerState=e(i.workInProgress,n),r.hasEagerState=!0,Object.is(i.current,r.eagerState))?null:()=>{q1e(t,i),i.queue.add(r)})}}}),a=cW(),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),oW&&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)||(q1e(a,i),i.workInProgress=e)}return[i.workInProgress,i.dispatch]}function Q1e(e,t,n){return Z1e(e,void 0,t,n)}function $1e(e,t,n,r){return Z1e(e,t,n,r)}var e0e=(e,t)=>typeof t==`function`?t(e):t,t0e=e=>typeof e==`function`?e():e;function Z(e){return Q1e(e0e,e,t0e)}function dW(e){let[t]=Z(()=>({current:e}));return t}var n0e=(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},r0e=()=>{throw Error(`Memo reducer should not be called`)},fW=(e,t)=>{let n=cW(),[r]=$1e(r0e,r=>{if(r&&n0e(r.deps,t))return r;let i=e();return oW&&n.devStrictMode&&e(),{value:i,deps:t}},null);return r.value},pW=(e,t)=>fW(()=>e,t),i0e=()=>({type:`effect`,cleanup:void 0,deps:null});function mW(e,t){let n=J1e(`effect`,i0e);if(!(t&&n.deps&&n0e(n.deps,t))){if(n.deps!==null&&!!t!=!!n.deps)throw Error(`useEffect called with and without dependencies across re-renders`);Y1e(()=>{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 a0e(e){let t=dW(e);mW(()=>{t.current=e});let n=cW();return pW(((...e)=>{if(oW&&n.renderContext)throw Error(`useEffectEvent cannot be called during render`);return t.current(...e)}),[n])}var hW=Symbol(`tap.Context`),o0e=e=>e,gW=e=>({[hW]:e}),s0e=e=>typeof e==`object`&&!!e&&hW in e,c0e=(e,t,n)=>{let r=o0e(e),i=r[hW];r[hW]=t;try{return n()}finally{r[hW]=i}},l0e=e=>o0e(e)[hW],_W=c({default:()=>O.default,use:()=>d0e,useCallback:()=>CW,useContext:()=>DW,useEffect:()=>wW,useEffectEvent:()=>EW,useLayoutEffect:()=>TW,useMemo:()=>SW,useReducer:()=>u0e,useRef:()=>xW,useState:()=>bW},1);u(_W,d(_(),1),void 0,1);var vW=()=>W1e()!==null,yW=O.default,bW=e=>vW()?Z(e):yW.useState(e),u0e=(e,t,n)=>vW()?Q1e(e,t,n):yW.useReducer(e,t,n),xW=e=>vW()?dW(e):yW.useRef(e),SW=(e,t)=>vW()?fW(e,t):yW.useMemo(e,t),CW=(e,t)=>vW()?pW(e,t):yW.useCallback(e,t),wW=(e,t)=>vW()?mW(e,t):yW.useEffect(e,t),TW=(e,t)=>vW()?mW(e,t):yW.useLayoutEffect(e,t),EW=e=>vW()?a0e(e):yW.useEffectEvent(e),d0e=e=>s0e(e)?l0e(e):yW.use(e),DW=e=>s0e(e)?l0e(e):yW.useContext(e);function OW(e,t){let n=e[kW];if(!n)throw Error(`ResourceElement.type is not a valid Resource`);return n(t)}var kW=Symbol(`fnSymbol`);function AW(e){let t=e=>({type:t,props:e});return t[kW]=e,t}function jW(e,t){return{...t,key:e}}var f0e=50,MW={schedulers:new Set([]),isScheduled:!1},p0e=class{_task;_isDirty=!1;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,MW.schedulers.add(this),m0e()}runTask(){this._isDirty=!1,this._task()}},m0e=()=>{MW.isScheduled||(MW.isScheduled=!0,NW())},h0e=()=>{try{let e=[],t=0;for(let n of MW.schedulers)if(MW.schedulers.delete(n),n.isDirty){if(t++,t>f0e)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.`);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{MW.schedulers.clear(),MW.isScheduled=!1}},NW=(()=>{if(typeof MessageChannel<`u`){let e=new MessageChannel;return e.port1.onmessage=h0e,()=>e.port2.postMessage(null)}return()=>setTimeout(h0e,0)})(),g0e=e=>{let t=MW;MW={schedulers:new Set([]),isScheduled:!0};try{let t=e();return h0e(),t}finally{MW=t}};function _0e(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 v0e(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 y0e=e=>{if(!s0e(e))throw Error("A tap resource's `use()` only accepts a resource context.");return l0e(e)},b0e=Symbol.for(`react.memo_cache_sentinel`),x0e={useState:Z,useReducer:Q1e,useRef:dW,useMemo:fW,useCallback:pW,useEffect:mW,useLayoutEffect:mW,useInsertionEffect:mW,useEffectEvent:a0e,useContext:y0e,use:y0e,useMemoCache:e=>{let t=!1,[n]=$1e(()=>[],e=>t?e:(t=!0,[...e]),e,e=>Array.from({length:e}).fill(b0e));return n}},S0e=O.default,PW=S0e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??S0e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,C0e=PW==null?null:`H`in PW?{get current(){return PW.H},set current(e){PW.H=e}}:`ReactCurrentDispatcher`in PW?{get current(){return PW.ReactCurrentDispatcher.current},set current(e){PW.ReactCurrentDispatcher.current=e}}:null;function w0e(e){if(!C0e)return e();let t=C0e.current;C0e.current=x0e;try{return e()}finally{C0e.current=t}}function FW(e,t,n=void 0,r=G1e(!1)){return{type:e,root:t,markDirty:n,devStrictMode:r,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function IW(e){if(!e.isMounted)throw Error(`Tried to unmount a fiber that is already unmounted`);e.isMounted=!1,v0e(e)}function LW(e,t){let n={effectTasks:[],props:t,output:void 0};return U1e(e,()=>{e.renderContext=n;try{n.output=w0e(()=>OW(e.type,t))}finally{e.renderContext=void 0}}),n}function RW(e,t){e.isMounted=!0,oW&&e.isNeverMounted&&e.devStrictMode===`root`&&(e.isNeverMounted=!1,_0e(t),v0e(e)),e.isNeverMounted=!1,_0e(t)}var T0e=e=>{let t=fW(()=>new p0e(()=>l(null)),[]),n=fW(()=>[],[]),r=fW(()=>(e.key,FW(e.type,K1e(e=>{!t.isDirty&&!e()||(n.push(e),t.markDirty())}))),[e.type,e.key,n,t]);uW(r.root,r.root.committedVersion);let i=LW(r,e.props),a=dW(!1),o=dW(e.props),s=dW(i.output),c=fW(()=>new Set,[]),l=a0e(e=>{if(e===null&&(uW(r.root,2),uW(r.root,1),n.forEach(e=>{oW&&r.devStrictMode&&e(),e()}),oW&&r.devStrictMode&&LW(r,o.current),e=LW(r,o.current)),t.isDirty)throw Error(`Scheduler is dirty, this should never happen`);lW(r.root),n.length=0,a.current&&RW(r,e),!(t.isDirty||s.current===e.output)&&(s.current=e.output,c.forEach(e=>e()))});return mW(()=>(a.current=!0,()=>{a.current=!1,IW(r)}),[r]),mW(()=>{o.current=i.props,lW(r.root),RW(r,i),!(t.isDirty||s.current===i.output)&&(s.current=i.output,c.forEach(e=>e()))}),fW(()=>({getValue:()=>s.current,subscribe:e=>(c.add(e),()=>c.delete(e))}),[c])};function E0e(e,t){let n=cW(),r=dW(0),i=fW(()=>(e.key,FW(e.type,n.root,()=>{r.current++,n.markDirty?.()})),[e.type,e.key,n]),a=t?fW(()=>LW(i,e.props),[i,...t,r.current]):LW(i,e.props);return mW(()=>()=>IW(i),[i]),mW(()=>{RW(i,a)},[i,a]),a.output}function D0e(e,t){let n=dW(0),r=n.current,i=fW(()=>cW(),[]),a=fW(()=>()=>{n.current++,i.markDirty?.()},[i]),o=fW(()=>new Map,[]),s=t?pW(e,t):e,c=fW(()=>{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(`useResources did not provide a key for array at index ${s}`);if(t.has(l))throw Error(`Duplicate key ${l} in useResources`);t.add(l);let u=o.get(l);if(u)if(u.fiber.type!==c.type){let e=FW(c.type,i.root,a),t=LW(e,c.props);u.next=[e,t],n.push(t.output)}else u.next=LW(u.fiber,c.props),n.push(u.next.output);else{let e=FW(c.type,i.root,a),t=LW(e,c.props);u={fiber:e,next:t},r++,o.set(l,u),n.push(t.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,i,a,o]);return mW(()=>()=>{for(let e of o.keys()){let t=o.get(e).fiber;IW(t)}},[o]),mW(()=>{for(let[e,t]of o.entries())t.next===`delete`?(t.fiber.isMounted&&IW(t.fiber),o.delete(e)):Array.isArray(t.next)?(IW(t.fiber),t.fiber=t.next[0],RW(t.fiber,t.next[1])):RW(t.fiber,t.next)},[c,o]),c}var zW=()=>{if(!oW)return null;let e=(0,O.useRef)(0),t=e.current===0;return(0,O.useState)(()=>e.current++),e.current===2?t?`child`:`root`:null},O0e=AW(function(e){return e()}),k0e=e=>{let t=(0,O.useMemo)(()=>K1e(e=>r(e)),[]),[n,r]=(0,O.useReducer)((e,n)=>(uW(t,e),e+(n()?1:0)),0);uW(t,n);let i=zW(),a=(0,O.useMemo)(()=>FW(O0e,t,void 0,i),[t,i]),o=LW(a,e);return(0,O.useLayoutEffect)(()=>()=>IW(a),[a]),(0,O.useLayoutEffect)(()=>{lW(t),RW(a,o)}),o.output},A0e=e=>((...t)=>W1e()?e(...t):k0e(()=>e(...t))),BW=A0e(E0e),VW=A0e(D0e),j0e=A0e(T0e),M0e=AW(function(){let[e,t]=bW(()=>({renderers:{},fallbacks:[]}));return{getState:()=>e,setDataUI:CW((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)??[]}}))}),[]),setFallbackDataUI:CW(e=>(t(t=>({...t,fallbacks:[...t.fallbacks,e]})),()=>{t(t=>({...t,fallbacks:t.fallbacks.filter(t=>t!==e)}))}),[])}}),HW=e=>{let t=Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)),n={};return t.reduce((e,t)=>{let r=t.priority??0;if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[i,a]of Object.entries(t.tools)){let t=e.tools?.[i];if(t&&t!==a){let o=n[i];if(o===r)throw Error(`You tried to define a tool with the name ${i}, but it already exists.`);let s=o>r?t:a,c=o>r?a:t;e.tools[i]={...c,...s},n[i]=Math.max(o,r);continue}e.tools||={},e.tools[i]=a,n[i]??=r}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),e},{})},N0e=class{_providers=new Set;getModelContext(){return HW(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)}}},UW=[],P0e={modelName:void 0,toolNames:UW},WW=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),GW=(e,t)=>{let n=e.getModelContext(),r=n.config?.modelName,i=n.tools?Object.keys(n.tools).sort():UW,a=i.length?i:UW;return r===t.modelName&&WW(a,t.toolNames)?t:{modelName:r,toolNames:a}},F0e=AW(function(){let e=SW(()=>new N0e,[]),[t,n]=bW(()=>GW(e,P0e));return wW(()=>(n(t=>GW(e,t)),e.subscribe(()=>{n(t=>GW(e,t))})),[e]),{getState:()=>GW(e,t),getModelContext:()=>e.getModelContext(),subscribe:t=>e.subscribe(t),register:t=>e.registerModelContextProvider(t)}}),I0e=e=>e.display===void 0?e.type===`human`:e.display===`standalone`,KW=(e,t)=>{if(!(t.status?.type===`running`||t.status?.type===`requires-action`)){let n=e.complete;return typeof n==`function`?n({args:t.args,result:t.result}):n??null}let n=e.running;return typeof n==`function`?n({args:t.args}):n??null},qW=e=>function(t){return KW(e,t)},L0e=Symbol(`assistant-ui.store.clientIndex`),R0e=e=>e[L0e],z0e=gW([]),B0e=()=>d0e(z0e),JW=(e,t)=>{let n=B0e();return c0e(z0e,SW(()=>[...n,e],[n,e]),t)},V0e=new Set([`$$typeof`,`nodeType`,`then`]),H0e=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!V0e.has(e))return!1}},U0e=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}},W0e=e=>{let t=AW(e);return e=>{let n=t(e);return e.key===void 0?n:jW(e.key,n)}},G0e=Symbol(`assistant-ui.store.getValue`),K0e=e=>{let t=e[G0e];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.`);return t.getState?.()},q0e=new Map;function J0e(e){let t=q0e.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[G0e];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)},q0e.set(e,t)),t}var YW=class extends U0e{outputRef;index;boundFns;cachedReceiver;constructor(e,t){super(),this.outputRef=e,this.index=t}get(e,t,n){if(t===G0e)return this.outputRef.current;if(t===L0e)return this.index;let r=H0e(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=J0e(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===G0e||t===L0e?!0:t in this.outputRef.current}},Y0e=W0e(e=>{let t=xW(null),n=B0e().length,r=SW(()=>new Proxy({},new YW(t,n)),[n]),i=JW(r,()=>BW(e));return t.current||=i,wW(()=>{t.current=i}),{methods:r,state:i.getState?.(),key:e.key}}),XW=e=>BW(Y0e(e)),ZW=Symbol(`assistant-ui.store.proxiedAssistantState`),X0e=e=>e===`on`||e===`subscribe`||typeof e==`symbol`,Z0e=e=>{class t extends U0e{get(t,n){let r=H0e(n,`AssistantState`);if(r!==!1)return r;let i=n;if(!X0e(i))return K0e(e[i]())}ownKeys(){return Object.keys(e).filter(e=>!X0e(e))}has(t,n){return!X0e(n)&&n in e}}return new Proxy({},new t)},QW=e=>e[ZW],Q0e=()=>()=>{},$W=e=>{let t=(()=>{throw Error(e)});return t.source=null,t.query=null,t},$0e=class extends U0e{get(e,t){if(t===`subscribe`||t===`on`)return Q0e;if(t===ZW)return e2e;let n=H0e(t,`DefaultAssistantClient`);return n===!1?$W(`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`):n}ownKeys(){return[`subscribe`,`on`,ZW]}has(e,t){return t===`subscribe`||t===`on`||t===ZW}},eG=new Proxy({},new $0e),e2e=Z0e(eG),t2e=()=>new Proxy({},{get(e,t){let n=H0e(t,`AssistantClient`);return n===!1?$W(`The current scope does not have a "${String(t)}" property.`):n}}),n2e=(0,_W.createContext)(eG),r2e=()=>DW(n2e),tG=({value:e,children:t})=>(0,A.jsx)(n2e.Provider,{value:e,children:t}),nG=AW(function(e){return null}),i2e=Symbol(`assistant-ui.transform-scopes`);function rG(e,t){let n=e;if(n[i2e])throw Error(`transformScopes is already attached to this resource`);n[i2e]=t}function a2e(e){return e[i2e]}var iG=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},o2e=gW(null),s2e=(e,t)=>c0e(o2e,e,t),c2e=()=>{let e=d0e(o2e);if(!e)throw Error(`AssistantTapContext is not available`);return e},l2e=()=>c2e().clientRef,u2e=()=>{let{emit:e}=c2e(),t=B0e();return EW((n,r)=>{e(n,r,t)})};function d2e(e,t){let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(e.type===nG||r.has(e.type))continue;r.add(e.type);let a=a2e(e.type);if(a){a(n,t),i=!0;break}}}let a={},o={};for(let[e,t]of Object.entries(n))t.type===nG?o[e]=t:a[e]=t;return{rootClients:a,derivedClients:o}}var aG=e=>SW(()=>e,[...Object.entries(e).flat()]),f2e=(e,t)=>{let{rootClients:n,derivedClients:r}=d2e(e,t);return{rootClients:aG(n),derivedClients:aG(r)}},p2e=AW(function(){return SW(()=>{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)}}}},[])}),oG=e=>SW(()=>e,e),m2e=AW(function({element:e,emit:t,clientRef:n}){let{methods:r,state:i}=s2e({clientRef:n,emit:t},()=>XW(e));return SW(()=>({state:i,methods:r}),[r,i])}),h2e=AW(function({element:e,notifications:t,clientRef:n,name:r}){let i=j0e(m2e({element:e,emit:t.emit,clientRef:n}));return wW(()=>i.subscribe(t.notifySubscribers),[i,t]),SW(()=>{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])}),g2e=AW(function(){return SW(()=>({clients:[],subscribe:void 0,on:void 0}),[])}),_2e=AW(function({clients:e,clientRef:t}){let n=BW(p2e());wW(()=>t.parent.subscribe(n.notifySubscribers),[t,n]);let r=oG(VW(()=>Object.keys(e).map(r=>jW(r,h2e({element:e[r],notifications:n,clientRef:t,name:r}))),[e,n,t]));return SW(()=>({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}=iG(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[R0e(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])}),v2e=AW(function({element:e,clientRef:t,name:n}){let r=xW(e.props);return r.current=e.props,SW(()=>{let e=()=>r.current.get(t.current);return Object.defineProperties(e,{source:{value:r.current.source},query:{value:r.current.query},name:{value:n,configurable:!0}}),e},[t,n])}),y2e=(e,t)=>{let n;try{let e={};for(let n of Object.keys(t.query).sort())e[n]=t.query[n];n=JSON.stringify(e)}catch{n=String(t.query)}return`${e}::${t.source}::${n}`},b2e=AW(function({clients:e,clientRef:t}){return oG(VW(()=>Object.keys(e).map(n=>{let r=n,i=e[r];return jW(y2e(r,i.props),v2e({element:i,clientRef:t,name:r}))}),[e,t]))}),x2e=AW(function({parent:e,clients:t}){let{rootClients:n,derivedClients:r}=f2e(t,e),i=xW({parent:e,current:null}).current;wW(()=>{i.current=s});let a=BW(Object.keys(n).length>0?_2e({clients:n,clientRef:i}):g2e()),o=BW(b2e({clients:r,clientRef:i})),s=SW(()=>{let t=e===eG?t2e():e,n=Object.create(t);Object.assign(n,{subscribe:a.subscribe??e.subscribe,on:a.on??e.on,[ZW]:Z0e(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 sG(e,{parent:t}={parent:r2e()}){if(e)return BW(x2e({parent:t??eG,clients:e}));if(t===null)throw Error(`received null parent, this usage is not allowed`);return t}var cG=e=>{let t=sG(),n=QW(t),r=(0,_W.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,_W.useDebugValue)(r),r},S2e=e=>{let t=sG(),n=xW(!1),r=n.current?null:e(t);return cG(()=>n.current?e(t):r),()=>(n.current=!0,e(t))},C2e=Object.freeze({});function lG({getItemState:e,children:t}){return w2e(t(S2e(e)))}var w2e=e=>{let t=typeof e==`object`&&e&&`type`in e?e:null,n=t?.type,r=t?.key;return SW(()=>t,[n,r,typeof t?.props==`object`&&t.props!=null&&Object.entries(t.props).length===0?C2e:t?.props])??e},T2e=O.createContext(!0);function uG(){throw Error(`A function wrapped in useEffectEvent can't be called during rendering.`)}var E2e=`use`in O.default?()=>{try{return O.use(T2e)}catch{return!1}}:()=>!1;function D2e(e){let t=O.useRef(uG);return O.useInsertionEffect(()=>{t.current=e},[e]),(...e)=>{E2e()&&uG();let n=t.current;return n(...e)}}var O2e=(e,t)=>{let n=sG(),r=D2e(t),{scope:i,event:a}=iG(e);wW(()=>n.on({scope:i,event:a},r),[n,i,a])},k2e=W0e(e=>{if(e.key===void 0)throw Error(`useClientResource: Element has no key`);return BW(Y0e(e))});function dG(e,t){let n=VW(()=>e().map(e=>k2e(e)),t),r=SW(()=>Object.keys(n),[n]),i=SW(()=>n.reduce((e,t,n)=>(e[t.key]=n,e),{}),[n]);return{state:SW(()=>n.map(e=>e.state),[n]),get:e=>{if(`index`in e){if(e.index<0||e.index>=r.length)throw Error(`useClientLookup: 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(`useClientLookup: Key "${e.key}" not found`);return n[t].methods}}}var A2e=AW(function({toolkit:e,mcpApp:t}){let n=VW(()=>t?[jW(`mcpApp`,t)]:[],[t])[0],[r,i]=bW(()=>({})),a=SW(()=>({toolUIs:r,mcpApp:n,tools:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.map(e=>e.render)]))}),[r,n]),o=l2e(),s=CW((e,t,n)=>{let r={render:t,standalone:n?.standalone??!1};return i(t=>({...t,[e]:[...t[e]??[],r]})),()=>{i(t=>{let n=t[e]?.filter(e=>e!==r)??[];if(n.length>0)return{...t,[e]:n};let{[e]:i,...a}=t;return a})}},[]);return wW(()=>{if(!e)return;let t=[];for(let[n,r]of Object.entries(e)){let e=`render`in r?r.render:void 0,i=`renderText`in r?r.renderText:void 0,a=e??(i?qW(i):void 0);a&&t.push(s(n,a,{standalone:I0e(r)}))}let n=Object.entries(e).reduce((e,[t,n])=>{if(n.type===`mcp`)return e;let{display:r,render:i,renderText:a,...o}=n;return e[t]=o,e},{});return t.push(o.current.modelContext().register({getModelContext:()=>({tools:n})})),()=>{t.forEach(e=>e())}},[e,s,o]),{getState:()=>a,setToolUI:s}});rG(A2e,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=F0e())});var fG=e=>{let[,t]=bW(e.getState);return wW(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},j2e=AW(function({runtime:e}){let t=fG(e);return{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}),M2e=AW(function({runtime:e,index:t}){return BW(j2e({runtime:SW(()=>e.getAttachmentByIndex(t),[e,t])}))}),N2e=AW(function({item:e,onSteer:t,onRemove:n}){return{getState:()=>e,steer:t,remove:n}}),pG=AW(function({threadIdRef:e,messageIdRef:t,runtime:n}){let r=fG(n),i=u2e();wW(()=>{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`,n=>{i(`composer.attachmentAddError`,{threadId:e.current,...t&&{messageId:t.current},...n.attachmentId&&{attachmentId:n.attachmentId},reason:n.reason,message:n.message})})),()=>{for(let e of r)e()}},[n,i,e,t]);let a=dG(()=>r.attachments.map((e,t)=>jW(e.id,M2e({runtime:n,index:t}))),[r.attachments,n]),o=r.queue,s=dG(()=>o.map(e=>jW(e.id,N2e({item:e,onSteer:()=>n.steerQueueItem(e.id),onRemove:()=>n.removeQueueItem(e.id)}))),[o,n]),c=SW(()=>({text:r.text,role:r.role,attachments:a.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,canSend:r.canSend,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:r.type??`thread`,dictation:r.dictation,quote:r.quote,queue:o}),[r,a.state,o]);return{getState:()=>c,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:e=>s.get(e),__internal_getRuntime:()=>n}}),P2e=AW(function({runtime:e}){let t=fG(e);return{getState:()=>t,addToolResult:t=>e.addToolResult(t),resumeToolCall:t=>e.resumeToolCall(t),respondToToolApproval:t=>e.respondToToolApproval(t),__internal_getRuntime:()=>e}}),F2e=AW(function({runtime:e,index:t}){return BW(j2e({runtime:SW(()=>e.getAttachmentByIndex(t),[e,t])}))}),I2e=AW(function({runtime:e,index:t}){return BW(P2e({runtime:SW(()=>e.getMessagePartByIndex(t),[e,t])}))}),mG=AW(function({runtime:e,threadIdRef:t}){let n=fG(e),[r,i]=bW(!1),[a,o]=bW(!1),s=SW(()=>({get current(){return e.getState().id}}),[e]),c=XW(pG({runtime:e.composer,threadIdRef:t,messageIdRef:s})),l=dG(()=>n.content.map((t,n)=>jW(`toolCallId`in t&&t.toolCallId!=null?`toolCallId-${t.toolCallId}`:`index-${n}`,I2e({runtime:e,index:n}))),[n.content,e]),u=dG(()=>(n.attachments??[]).map((t,n)=>jW(t.id,F2e({runtime:e,index:n}))),[n.attachments,e]),d=SW(()=>({...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}}),L2e=AW(function({runtime:e,id:t,threadIdRef:n}){return BW(mG({runtime:SW(()=>e.getMessageById(t),[e,t]),threadIdRef:n}))}),hG=AW(function({runtime:e}){let t=fG(e),n=u2e();wW(()=>{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=SW(()=>({get current(){return e.getState().threadId}}),[e]),i=XW(pG({runtime:e.composer,threadIdRef:r})),a=dG(()=>t.messages.map(t=>jW(t.id,L2e({runtime:e,id:t.id,threadIdRef:r}))),[t.messages,e,r]),o=SW(()=>({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,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}}),R2e=AW(function({runtime:e}){let t=fG(e),n=u2e();return wW(()=>{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,updateCustom:e.updateCustom,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}),gG=AW(function({runtime:e,id:t}){return BW(R2e({runtime:SW(()=>e.getItemById(t),[e,t])}))}),_G=AW(function({runtime:e,__internal_assistantRuntime:t}){let n=fG(e),r=XW(hG({runtime:e.main})),i=dG(()=>Object.keys(n.threadItems).map(t=>jW(t,gG({runtime:e,id:t}))),[n.threadItems,e]),a=SW(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThreadId??null,isLoading:n.isLoading,isLoadingMore:n.isLoadingMore,hasMore:n.hasMore,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,n)=>{await e.switchToThread(t,n)},switchToNewThread:async()=>{await e.switchToNewThread()},getLoadThreadsPromise:()=>e.getLoadThreadsPromise(),reload:()=>e.reload(),loadMore:()=>e.loadMore(),__internal_getAssistantRuntime:()=>t}}),z2e=AW(function(e){return{getState:()=>e}}),B2e=AW(function(e){let[t]=bW(()=>({suggestions:(e??[]).map(e=>typeof e==`string`?{title:e,label:``,prompt:e}:{title:e.title,label:e.label,prompt:e.prompt})})),n=dG(()=>t.suggestions.map((e,t)=>jW(t,z2e(e))),[t.suggestions]);return{getState:()=>t,suggestion:({index:e})=>n.get({index:e})}}),vG=AW(function(e){let t=l2e();return wW(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),BW(_G({runtime:e.threads,__internal_assistantRuntime:e}))}),V2e=(e,t)=>{e.thread??=nG({source:`threads`,query:{type:`main`},get:e=>e.threads().thread(`main`)}),e.threadListItem??=nG({source:`threads`,query:{type:`main`},get:e=>e.threads().item(`main`)}),e.composer??=nG({source:`thread`,query:{},get:e=>e.threads().thread(`main`).composer()}),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=F0e()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=B2e())},H2e=AW(function(e){return BW(vG(e))});rG(H2e,(e,t)=>{V2e(e,t),!e.tools&&t.tools.source===null&&(e.tools=A2e({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=M0e())});var U2e=e=>e._core?.RenderComponent,W2e=(0,_W.memo)(({runtime:e,aui:t=null,children:n})=>{let r=sG({threads:H2e(e)},{parent:t}),i=U2e(e);return(0,A.jsxs)(tG,{value:r,children:[i&&(0,A.jsx)(i,{}),n]})}),G2e=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},K2e=(e=>e?G2e(e):G2e),q2e=e=>e;function yG(e,t=q2e){let n=O.useSyncExternalStore(e.subscribe,O.useCallback(()=>t(e.getState()),[e,t]),O.useCallback(()=>t(e.getInitialState()),[e,t]));return O.useDebugValue(n),n}var J2e=e=>{let t=K2e(e),n=e=>yG(t,e);return Object.assign(n,t),n},bG=(e=>e?J2e(e):J2e),Y2e={toResponse(e,t){return new Response(Y2e.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return Y2e.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},X2e=()=>{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}},Z2e=()=>{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=X2e(),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()}}))}}},Q2e=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())}},$2e=e=>new ReadableStream({start(t){return e.start?.(new Q2e(t))},pull(t){return e.pull?.(new Q2e(t))},cancel(t){return e.cancel?.(t)}}),e4e=()=>{let e;return[$2e({start(t){e=t}}),e]},t4e=class{_controller;_isClosed=!1;_mergeTask;constructor(e){this._controller=e;let t=$2e({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.modelContent===void 0?{}:{modelContent:e.modelContent},...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())}},n4e=e=>new ReadableStream({start(t){return e.start?.(new t4e(t))},pull(t){return e.pull?.(new t4e(t))},cancel(t){return e.cancel?.(t)}}),r4e=()=>{let e;return[n4e({start(t){e=t}}),e]},i4e=class{value=-1;up(){return++this.value}},a4e=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}},xG=class extends TransformStream{constructor(e){let t=new i4e,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]})}})}},SG=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,`readable`,{value:t,writable:!1})}};let o4e=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r};var s4e=o4e(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),c4e=class e{_state;_parentId;constructor(e){this._state=e||{merger:Z2e(),contentCounter:new i4e}}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 a4e(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new xG(this._state.contentCounter)))}appendText(e){(this._state.append?.kind!==`text`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`text`,parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){(this._state.append?.kind!==`reasoning`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`reasoning`,parentId:this._parentId,controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,t]=e4e();return this._addPart(this._withParentIdOption({type:`text`}),e),t}addReasoningPart(){let[e,t]=e4e();return this._addPart(this._withParentIdOption({type:`reasoning`}),e),t}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??s4e(),[i,a]=r4e();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 l4e(e){let t=new c4e;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 u4e(){let{resolve:e,promise:t}=X2e(),n;return[l4e(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}var d4e=class extends TransformStream{constructor(e,t,n){let[r,i]=u4e(),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)}};function f4e(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 p4e=d(s(((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}))(),1),m4e=Symbol(`aui.parse-partial-json-object.meta`),CG=e=>{if(e.length===0)return{[m4e]:{state:`partial`,partialPath:[]}};try{let t=p4e.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[m4e]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=f4e(e),r=p4e.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[m4e]={state:`partial`,partialPath:n},r}catch{return}}},wG=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(t,n,r){if(n.length===0)return r(t);if(t??={},typeof t!=`object`)throw Error(`Invalid path: [${n.join(`, `)}]`);let[i,...a]=n;if(Array.isArray(t)){let o=Number(i);if(Number.isNaN(o))throw Error(`Expected array index at [${n.join(`, `)}]`);if(o>t.length||o<0)throw Error(`Insert array index out of bounds`);let s=[...t];return s[o]=e.updatePath(s[o],a,r),s}let o={...t};return o[i]=e.updatePath(o[i],a,r),o}},h4e=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}}},g4e=({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:{}}}),_4e=(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}}},v4e=(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}`)},y4e=(e,t)=>_4e(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}),b4e=(e,t)=>_4e(e,t,e=>({...e,status:{type:`complete`,reason:`unknown`}})),x4e=(e,t)=>_4e(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=CG(n)??e.args;return{...e,argsText:n,args:r}}else throw Error(`text-delta received but part is neither text nor tool-call`)}),S4e=(e,t)=>_4e(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.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}};throw Error(`Result chunk received but part is not a tool-call`)}),C4e=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=w4e(t);return{...e,status:n}},w4e=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},T4e=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),E4e=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),D4e=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),O4e=(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:s4e(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},k4e=(e,t)=>({...e,status:{type:`incomplete`,reason:`error`,error:t.error}}),A4e=(e,t)=>{let n=new wG(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},TG=(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)},j4e=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},M4e=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n}={}){let r=e??g4e(),i=new h4e,a,o=t?j4e(()=>{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=v4e(r,e),e.part.type===`tool-call`&&i.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:r=y4e(r,e);break;case`part-finish`:r=b4e(r,e);break;case`text-delta`:r=x4e(r,e),i.recordFirstToken();break;case`result`:r=S4e(r,e);break;case`message-finish`:r=C4e(r,e);break;case`annotations`:r=T4e(r,e);break;case`data`:r=E4e(r,e);break;case`step-start`:r=D4e(r,e);break;case`step-finish`:r=O4e(r,e);break;case`error`:r=k4e(r,e),n?.(e.error);break;case`update-state`:r=A4e(r,e);break;default:throw Error(`Unsupported chunk type: ${t}`)}r.status.type!==`running`&&(r={...r,metadata:{...r.metadata,timing:TG(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=C4e(r,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),r={...r,metadata:{...r.metadata,timing:TG(i,r)}},e.enqueue(r)}}})}},N4e=class extends SG{constructor(){super(e=>{let t=new d4e({transform(e,t){t.appendText(e)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},P4e=class e{readable;constructor(e){this.readable=e,this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new M4e))}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)]}},F4e=Symbol.for(`aui.tool-response`),I4e=class e{get[F4e](){return!0}artifact;result;isError;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact),this.result=e.result,this.isError=e.isError??!1,e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&F4e in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?`<no result>`:t})}},L4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({attachment:nG({source:`message`,query:{type:`index`,index:e},get:t=>t.message().attachment({index:e})})}),children:t}),R4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({attachment:nG({source:`composer`,query:{type:`index`,index:e},get:t=>t.composer().attachment({index:e})})}),children:t}),z4e=({runtime:e,children:t})=>(0,A.jsx)(tG,{value:sG({threadListItem:R2e({runtime:e})}),children:t}),EG=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({message:nG({source:`thread`,query:{type:`index`,index:e},get:t=>t.thread().message({index:e})}),composer:nG({source:`message`,query:{},get:t=>t.thread().message({index:e}).composer()})}),children:t}),B4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({part:nG({source:`message`,query:{type:`index`,index:e},get:t=>t.message().part({index:e})})}),children:t}),V4e=AW(function({text:e,isRunning:t}){let n=SW(()=>({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`)},respondToToolApproval:()=>{throw Error(`Not supported`)}}}),H4e=({text:e,isRunning:t=!1,children:n})=>(0,A.jsx)(tG,{value:sG({part:V4e({text:e,isRunning:t})}),children:n}),U4e=Object.freeze({type:`complete`}),W4e=AW(function({parts:e,getMessagePart:t}){let[n,r]=bW(!0),i=SW(()=>e[e.length-1]?.status??U4e,[e]),a=SW(()=>({parts:e,collapsed:n,status:i}),[e,n,i]);return{getState:()=>a,setCollapsed:r,part:t}}),G4e=({startIndex:e,endIndex:t,children:n})=>{let r=cG(e=>e.message.parts).slice(e,t+1),i=sG();return(0,A.jsx)(tG,{value:sG({chainOfThought:W4e({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})},DG=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({suggestion:nG({source:`suggestions`,query:{index:e},get:t=>t.suggestions().suggestion({index:e})})}),children:t}),K4e=({index:e,children:t})=>(0,A.jsx)(tG,{value:sG({queueItem:nG({source:`composer`,query:{index:e},get:t=>t.composer().queueItem({index:e})})}),children:t}),q4e=Symbol(`innerMessage`),OG=Symbol(`skip-update`);function J4e(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 kG=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)}}},AG=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e){for(let t of this._subscriptions)t(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()}}},jG=class extends AG{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e;let t=e.getState();if(t===OG)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===OG||J4e(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){return this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()})}},Y4e=class extends AG{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!==OG&&(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()})}},MG=class extends AG{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?.()}}},X4e=class extends AG{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=e=>{this.notifySubscribers(e)},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?.()}}},Z4e=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)}},Q4e=class extends Z4e{_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)}},NG=class extends Q4e{get source(){return`thread-composer`}},$4e=class extends Q4e{get source(){return`edit-composer`}},e3e=class extends Z4e{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},PG=Object.freeze([]),t3e=Object.freeze({}),n3e=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??PG,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??t3e,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??PG,value:e?.text??``}),r3e=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??PG,runConfig:e?.runConfig??t3e,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??PG,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),i3e=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.steerQueueItem=this.steerQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.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()}steerQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.steerQueueItem(e)}removeQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.removeQueueItem(e)}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 X4e({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},a3e=class extends i3e{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new Y4e({path:e.path,getState:()=>n3e(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 NG(new jG({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`}:OG},subscribe:e=>this._core.subscribe(e)}),this._core)}},FG=class extends i3e{_beginEdit;get path(){return this._core.path}get type(){return`edit`}_getState;constructor(e,t){let n=new Y4e({path:e.path,getState:()=>r3e(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 $4e(new jG({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`}:OG},subscribe:e=>this._core.subscribe(e)}),this._core)}},IG=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
188
188
|
|
|
189
189
|
`),o3e=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.respondToToolApproval=this.respondToToolApproval.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=I4e.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})}respondToToolApproval(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to respond to tool approval on non-tool message part`);if(!t.approval||t.approval.approved!==void 0)throw Error(`Tool call has no pending approval`);if(!this.threadApi)throw Error(`Thread API is not available`);this.threadApi.getState().respondToToolApproval({approvalId:t.approval.id,approved:e.approved,...e.reason!=null&&{reason:e.reason}})}subscribe(e){return this.contentBinding.subscribe(e)}},s3e=Object.freeze({type:`complete`}),c3e=(e,t,n)=>{if(e.role!==`assistant`)return s3e;if(n.type===`tool-call`)return n.result?s3e:e.status;let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?s3e:r?e.status:s3e},LG=(e,t)=>{let n=e.content[t];if(!n)return OG;let r=c3e(e,t,n);return Object.freeze({...n,[q4e]:n[q4e],status:r})},l3e=class{_core;_threadBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new FG(new MG({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 IG(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new o3e(new jG({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>LG(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new o3e(new jG({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?OG:LG(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new e3e(new jG({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`}:OG},subscribe:e=>this._core.subscribe(e)}))}},u3e=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),d3e=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),f3e=(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},p3e=(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:e.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})},m3e=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(e,t){let n=new jG({path:e.path,getState:()=>p3e(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 a3e(new MG({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.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.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(f3e(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(d3e(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(u3e(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(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 l3e(new jG({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 OG;let o=this._threadBinding.getState().getBranches(e.id);return{...e,[q4e]:e[q4e],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}},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 X4e({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},h3e=(0,_W.createContext)(null),g3e=({adapters:e,children:t})=>{let n=DW(h3e),r=SW(()=>({...n,...e}),[n,e]);return(0,A.jsx)(h3e.Provider,{value:r,children:t})},_3e=()=>DW(h3e),RG=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.updateCustom=this.updateCustom.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(e){let t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){let t=this._core.getState();if(!this._threadListBinding.updateCustom)throw Error(`Thread list runtime does not support updating custom metadata`);return this._threadListBinding.updateCustom(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}},v3e=Promise.resolve(),y3e=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),b3e=(e,t)=>{if(t===void 0)return OG;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,custom:n.custom,isMain:n.id===e.mainThreadId}:OG},x3e=class{_core;_runtimeFactory;_getState;constructor(e,t=m3e){this._core=e,this._runtimeFactory=t;let n=new Y4e({path:{},getState:()=>y3e(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new RG(new jG({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>b3e(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new MG({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.reload=this.reload.bind(this),this.loadMore=this.loadMore.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,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??v3e}loadMore(){return this._core.loadMore?.()??v3e}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 MG({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 RG(new jG({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>b3e(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new RG(new jG({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>b3e(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new RG(new jG({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>b3e(this._core,e),subscribe:e=>this._core.subscribe(e)}),this._core)}},S3e=class{_core;threads;_thread;constructor(e){this._core=e,this.threads=new x3e(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},C3e=class{_contextProvider=new N0e;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},zG=o4e(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),BG=Symbol(`autoStatus`),w3e=Object.freeze(Object.assign({type:`running`},{[BG]:!0})),T3e=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[BG]:!0})),E3e=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[BG]:!0})),D3e=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[BG]:!0})),O3e=(e,t,n,r,i)=>e&&i?Object.assign({type:`incomplete`,reason:`error`,error:i},{[BG]:!0}):e&&t?w3e:n?D3e:r?E3e:T3e,k3e=(e,t)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t}},VG=(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|svg\+xml);base64,(.*)$/)||/^(https:\/\/|blob:)/.test(e)?{...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`generative-ui`:return e;case`tool-call`:{let{parentId:t,messages:n,...r}=e,i={...r,toolCallId:e.toolCallId??`tool-${zG()}`,...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:CG(e.argsText??``)??{},argsText:e.argsText??``}}default:{let n=k3e(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},...c?.isOptimistic&&{isOptimistic:!0}}};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=k3e(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=>k3e(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}`)}},HG={fromArray:e=>{let t=e.map(e=>VG(e,zG(),O3e(!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=O3e(!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:VG(e,e.id,n)}})}}},UG=e=>e.next?UG(e.next):`current`in e?e:null,A3e=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}},j3e=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],(UG(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 A3e(()=>{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}}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=UG(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}evictOffBranchOptimisticMessages(e,t){if(!e)return;let n=new Set;for(let e=t;e;e=e.prev)n.add(e.current.id);let r=[];for(let t=e;t&&!n.has(t.current.id);t=t.prev)t.current.metadata?.isOptimistic&&r.push(t.current.id);for(let e of r)this.messages.has(e)&&this.deleteMessage(e)}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=this.head,r=t.prev??this.root;r.next=t,this.head=UG(t),this.evictOffBranchOptimisticMessages(n,this.head),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.`);let n=this.head;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.evictOffBranchOptimisticMessages(n,this.head),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)t.current.metadata?.isOptimistic||e.push({message:t.current,parentId:t.prev?.current.id??null});let t=this.head;for(;t?.current.metadata?.isOptimistic;)t=t.prev;return{headId:t?.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)}},WG=Object.freeze([]);function M3e(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}function N3e(e,t){return e.length===t.length?e.every((e,n)=>e.id===t[n].id):!1}function P3e(e){let t=zG();return e.type===`image`?{id:t,type:`image`,name:e.filename??`image`,content:[e],status:{type:`complete`}}:e.type===`file`?{id:t,type:`document`,name:e.filename??`document`,contentType:e.mimeType,content:[e],status:{type:`complete`}}:e.type===`audio`?{id:t,type:`audio`,name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:`complete`}}:{id:t,type:`data`,name:e.name,content:[e],status:{type:`complete`}}}function F3e(e){let t=[];for(let n of e)n.type!==`text`&&t.push(P3e(n));return t}var I3e=e=>e.status.type===`complete`,GG=class extends kG{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=>!I3e(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.canSend)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(I3e(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()}get queue(){return WG}steerQueueItem(e){}removeQueueItem(e){}async addAttachment(e){if(!(e instanceof File)){let t=this.getAttachmentAdapter();if(t&&!M3e({name:e.name,type:e.contentType??``},t.accept)){let n=`File type ${e.contentType||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r),r}let n={id:e.id??zG(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,n],this._notifySubscribers(),this._notifyEventSubscribers(`attachmentAdd`,{});return}let t=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()},n=this.getAttachmentAdapter();if(!n){let e=`Attachments are not supported`,t=Error(e);throw this._safeEmitAttachmentAddError(`no-adapter`,e,void 0,t),t}if(!M3e({name:e.name,type:e.type},n.accept)){let t=`File type ${e.type||`unknown`} is not accepted. Accepted types: ${n.accept}`,r=Error(t);throw this._safeEmitAttachmentAddError(`not-accepted`,t,void 0,r),r}let r;try{let i=n.add({file:e});if(Symbol.asyncIterator in i)for await(let e of i)r=e,t(e);else r=await i,t(r)}catch(e){throw r&&t({...r,status:{type:`incomplete`,reason:`error`}}),this._safeEmitAttachmentAddError(`adapter-error`,e instanceof Error?e.message:String(e),r?.id,e instanceof Error?e:void 0),e}r?.status.type===`incomplete`&&r.status.reason===`error`?this._safeEmitAttachmentAddError(`adapter-error`,`Attachment upload did not complete successfully.`,r?.id):this._notifyEventSubscribers(`attachmentAdd`,{})}_safeEmitAttachmentAddError(e,t,n,r){try{this._notifyEventSubscribers(`attachmentAddError`,{reason:e,message:t,...n!==void 0&&{attachmentId:n},...r!==void 0&&{error:r}})}catch(e){console.error(`[assistant-ui] attachmentAddError subscriber threw:`,e)}}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(!I3e(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,t){let n=this._eventSubscribers.get(e);if(n)for(let e of n)e(t)}unstable_on(e,t){let n=t,r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),()=>{this._eventSubscribers.get(e)?.delete(n)}}},L3e=class extends GG{runtime;_canCancel=!1;get canCancel(){return this._canCancel}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled}get queue(){return this.runtime.getQueueItems?.()??WG}steerQueueItem(e){this.runtime.steerQueueItem?.(e)}removeQueueItem(e){this.runtime.removeQueueItem?.(e)}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}constructor(e){super(),this.runtime=e,this.connect()}connect(){let e=this.runtime.isSendDisabled,t=this.queue;return this.runtime.subscribe(()=>{let n=!1;this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,n=!0),e!==this.runtime.isSendDisabled&&(e=this.runtime.isSendDisabled,n=!0),t!==this.queue&&(t=this.queue,n=!0),n&&this._notifySubscribers()})}async handleSend(e,t){this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun,steer:t?.steer})}async handleCancel(){this.runtime.cancelRun()}},R3e=class extends GG{runtime;endEditCallback;get canCancel(){return!0}get canSend(){return!this.isEmpty}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_previousText;_previousAttachments;_nonTextPassthrough;_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=IG(r),this.setText(this._previousText),this.setRole(r.role),r.role===`user`?(this._previousAttachments=[...r.attachments??[],...F3e(r.content)],this._nonTextPassthrough=[]):(this._previousAttachments=r.attachments??[],this._nonTextPassthrough=r.content.filter(e=>e.type!==`text`)),this.setAttachments(this._previousAttachments),this.setRunConfig({...e.composer.runConfig})}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(e,t){let n=IG(e),r=!N3e(e.attachments??[],this._previousAttachments);if(n!==this._previousText||r||t?.startRun){let n=this._nonTextPassthrough.length>0?[...e.content,...this._nonTextPassthrough]:e.content;this.runtime.append({...e,content:n,parentId:this._parentId,sourceId:this._sourceId,startRun:t?.startRun})}this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},z3e=class{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new j3e;_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 L3e(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 R3e(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,t){let n=this._eventSubscribers.get(e);if(n)for(let e of n)e(t)}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(IG(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:zG(),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:zG(),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(HG.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){let n=t;if(e===`modelContextUpdate`)return this._contextProvider.subscribe?.(()=>n({}))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e===`initialize`&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&n({})}),()=>{this._eventSubscribers.get(e)?.delete(n)}}};function B3e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V3e(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=>V3e(e,t+1)):B3e(e)?Object.entries(e).every(([e,n])=>typeof e==`string`&&V3e(n,t+1)):!1}var H3e=({detectorRef:e})=>(TW(()=>{e.current=!0},[e]),null),U3e=class extends kG{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=bG(()=>({}));parent;constructor(e,t){super(),this.parent=t,this.useRuntimeHook=bG(()=>({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)}_RuntimeBinder=({threadId:e,children:t})=>{let{useRuntime:n}=this.useRuntimeHook(),r=n(),i=r.thread.__internal_threadBinding,a=CW(()=>{let t=this.instances.get(e);if(!t)throw Error(`Thread not found. This is a bug in assistant-ui.`);t.runtime=i.getState(),this._notifySubscribers()},[e,i]),o=xW(!1);o.current||a(),wW(()=>(o.current=!0,a(),i.outerSubscribe(a)),[i,a]);let s=sG(),c=xW(void 0),l=xW(!1);return wW(()=>{let e=i.getState(),t=e.__internal_setGetInitializePromise;typeof t==`function`&&t.call(e,()=>c.current)},[i]),wW(()=>(l.current=!1,r.threads.main.unstable_on(`initialize`,()=>{if(l.current||s.threadListItem().getState().status!==`new`)return;l.current=!0,c.current=s.threadListItem().initialize();let e=r.thread.unstable_on(`runEnd`,()=>{e(),s.threadListItem().generateTitle()})})),[r,s]),(0,A.jsx)(A.Fragment,{children:t})};_OuterActiveThreadProvider=(0,_W.memo)(({threadId:e,provider:t})=>{let n=SW(()=>new x3e(this.parent).getItemById(e),[e]),r=xW(!1);return wW(()=>{},[t]),(0,A.jsx)(z4e,{runtime:n,children:(0,A.jsx)(t,{children:(0,A.jsx)(this._RuntimeBinder,{threadId:e,children:(0,A.jsx)(H3e,{detectorRef:r})})})})});__internal_RenderThreadRuntimes=({provider:e})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(t=>(0,A.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},t)))},KG=(e,t,n)=>n.reduce((e,n)=>n?.(e,t)??e,e),W3e=class extends kG{_pendingTransforms=[];_completedOptimistics=[];_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){this._cachedValue=this._pendingTransforms.reduce((e,t)=>KG(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=KG(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()}}},qG=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."),G3e={getMessageById(){},getBranches(){return[]},switchToBranch(){throw qG},append(){throw qG},startRun(){throw qG},resumeRun(){throw qG},cancelRun(){throw qG},addToolResult(){throw qG},resumeToolCall(){throw qG},respondToToolApproval(){throw qG},speak(){throw qG},stopSpeaking(){throw qG},connectVoice(){throw qG},disconnectVoice(){throw qG},getVoiceVolume:()=>0,subscribeVoiceVolume:()=>()=>{},muteVoice(){throw qG},unmuteVoice(){throw qG},submitFeedback(){throw qG},getModelContext(){return{}},exportExternalState(){throw qG},importExternalState(){throw qG},composer:{attachments:[],attachmentAccept:`*`,async addAttachment(){throw qG},async removeAttachment(){throw qG},isEditing:!0,canCancel:!1,canSend:!1,isEmpty:!0,text:``,setText(){throw qG},role:`user`,setRole(){throw qG},runConfig:{},setRunConfig(){throw qG},async reset(){},async clearAttachments(){},send(){throw qG},cancel(){},queue:[],steerQueueItem(){},removeQueueItem(){},dictation:void 0,startDictation(){throw qG},stopDictation(){},quote:void 0,setQuote(){throw qG},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw qG},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,isSendDisabled:!1,isLoading:!0,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw qG},export(){return{messages:[]}},reset(){throw qG},unstable_on(){return()=>{}}};function JG(e){return e}var YG=e=>e||void 0,K3e=(e,t)=>{for(let n of e){if(t.threadIdMap[n.remoteId]!==void 0)continue;switch(n.status){case`regular`:t.threadIds.push(n.remoteId);break;case`archived`:t.archivedThreadIds.push(n.remoteId);break;default:{let e=n.status;throw Error(`Unsupported state: ${e}`)}}let e=JG(n.remoteId);t.threadIdMap[n.remoteId]=e,t.threadData[e]={id:n.remoteId,remoteId:n.remoteId,externalId:n.externalId,status:n.status,title:n.title,custom:n.custom,initializeTask:Promise.resolve({remoteId:n.remoteId,externalId:n.externalId})}}return t},XG=(e,t)=>{let n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},ZG=(e,t,n)=>{let r=XG(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},q3e=class extends kG{_options;_hookManager;_loadThreadsPromise;_loadMorePromise;_loadGeneration=0;_mainThreadId;_state=new W3e({isLoading:!0,isLoadingMore:!1,cursor:void 0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){if(!this._loadThreadsPromise){let e=this._loadGeneration;this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:e=>({...e,isLoading:!0}),then:(t,n)=>{if(e!==this._loadGeneration)return t;let r=K3e(n.threads,{threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});return{...t,isLoading:!1,cursor:YG(n.nextCursor),threadIds:r.threadIds,archivedThreadIds:r.archivedThreadIds,threadIdMap:{...t.threadIdMap,...r.threadIdMap},threadData:{...t.threadData,...r.threadData}}}}).catch(t=>{e===this._loadGeneration&&(console.error(`[assistant-ui] thread list load failed:`,t),this._loadThreadsPromise=void 0,this._state.update({...this._state.baseValue,isLoading:!1}))}).then(()=>{})}return this._loadThreadsPromise}loadMore(){if(this._loadMorePromise)return this._loadMorePromise;let e=this._state.value;if(e.cursor===void 0||e.isLoading)return Promise.resolve();let t=this._loadGeneration,n=this._options.adapter,r=e.cursor,i=this._state.optimisticUpdate({execute:()=>n.list({after:r}),loading:e=>({...e,isLoadingMore:!0}),then:(e,r)=>{if(t!==this._loadGeneration||n!==this._options.adapter)return e;let i=K3e(r.threads,{threadIds:[...e.threadIds],archivedThreadIds:[...e.archivedThreadIds],threadIdMap:{...e.threadIdMap},threadData:{...e.threadData}});return{...e,isLoadingMore:!1,cursor:YG(r.nextCursor),threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadIdMap:i.threadIdMap,threadData:i.threadData}}}).catch(e=>{console.error(`[assistant-ui] thread list loadMore failed:`,e)}).then(()=>{this._loadMorePromise===i&&(this._loadMorePromise=void 0)});return this._loadMorePromise=i,i}contextProvider;constructor(e,t){super(),this.contextProvider=t,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new U3e(e.runtimeHook,this),this.useProvider=bG(()=>({Provider:e.adapter.unstable_Provider??_W.Fragment})),this.__internal_setOptions(e),this.switchToNewThread()}_initialThreadLoaded=!1;useProvider;__internal_setOptions(e){if(this._options===e)return;let t=this._options!==void 0&&this._options.adapter!==e.adapter;this._options=e;let n=e.adapter.unstable_Provider??_W.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!0),this._hookManager.setRuntimeHook(e.runtimeHook),t&&(this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}))}__internal_load(){this.getLoadThreadsPromise();let e=this._options.threadId??this._options.initialThreadId;!this._initialThreadLoaded&&e&&(this._initialThreadLoaded=!0,this.switchToThread(e).catch(()=>{}))}reload(){return this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}),this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get isLoadingMore(){return this._state.value.isLoadingMore}get hasMore(){return this._state.value.cursor!==void 0}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)||G3e}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 XG(this._state.value,e)}async switchToThread(e,t){let n=this.getItemById(e);if(!n){let t=await this._options.adapter.fetch(e),r=this._state.value,i=JG(t.remoteId),a={...r.threadData,[i]:{id:i,initializeTask:Promise.resolve({remoteId:t.remoteId,externalId:t.externalId}),remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,custom:t.custom}},o={...r.threadIdMap,[t.remoteId]:i},s=r.threadIds.filter(e=>e!==t.remoteId),c=r.archivedThreadIds.filter(e=>e!==t.remoteId),l=t.status===`regular`?[...s,t.remoteId]:s,u=t.status===`archived`?[...c,t.remoteId]:c;this._state.update({...r,threadIds:l,archivedThreadIds:u,threadIdMap:o,threadData:a}),n=this.getItemById(e)}if(!n)throw Error(`Thread not found`);if(this._mainThreadId===n.id)return;let r=this._hookManager.startThreadRuntime(n.id);this.mainThreadId===void 0?r.then(()=>this._notifySubscribers()):await r,n.status===`archived`&&t?.unarchive!==!1&&await this.unarchive(n.id),this._mainThreadId=n.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_${zG()}`;while(e.threadIdMap[t]);let n=JG(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,custom: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=>ZG(t,e,`regular`),loading:(t,n)=>{let r=JG(e);return{...t,threadData:{...t.threadData,[r]:{...t.threadData[r],initializeTask:n}}}},then:(t,{remoteId:n,externalId:r})=>{let i=XG(t,e);if(!i)return t;let a=JG(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=P4e.fromAssistantStream(a);for await(let e of o){let n=e.parts.filter(e=>e.type===`text`)[0]?.text,r=this._state.baseValue,i=XG(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=XG(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,title:t}}}:n}})}updateCustom(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`);if(!this._options.adapter.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await n.initializeTask,r=this._options.adapter;if(!r.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return r.updateCustom(e,t)},optimistic:n=>{let r=XG(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,custom: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=>ZG(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=>ZG(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=>ZG(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=bG(()=>[]);__internal_RenderComponent=()=>{let e=(0,_W.useId)();wW(()=>(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,A.jsx)(g3e,{adapters:r,children:(0,A.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})}},J3e=class extends C3e{threads;constructor(e){super(),this.threads=new q3e(e,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Y3e=e=>{let[t]=bW(()=>new J3e(e));return wW(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),SW(()=>new S3e(t),[t])},X3e=e=>{let t=xW(e.runtimeHook);t.current=e.runtimeHook;let n=xW(e.threadId??e.initialThreadId),r=CW(()=>t.current(),[]),i=SW(()=>({adapter:e.adapter,allowNesting:e.allowNesting,initialThreadId:n.current,runtimeHook:r}),[e.adapter,e.allowNesting,r]);if(sG().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=Y3e(i),o=xW(e.threadId);return wW(()=>{e.threadId!==o.current&&(o.current=e.threadId,e.threadId?a.threads.switchToThread(e.threadId).catch(()=>{}):a.threads.switchToNewThread().catch(()=>{}))},[a,e.threadId]),a};function Z3e(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 e.sourceType===`url`?{type:`source`,sourceType:`url`,id:e.id,url:e.url,...e.title==null?void 0:{title:e.title},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata}}:{type:`source`,sourceType:`document`,id:e.id,title:e.title,mediaType:e.mediaType,...e.filename==null?void 0:{filename:e.filename},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata}};case`tool-call`:return V3e(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 Q3e(e){let t=e.content,n=VG({id:e.id,createdAt:e.created_at,...t},e.id,{type:`complete`,reason:`unknown`});return{parentId:e.parent_id,message:n}}var $3e=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}`)}},QG=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=$3e(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=$3e(r)}},e6e=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(){}},t6e=`aui:refresh_token`,n6e=class{strategy=`anon`;baseUrl;jwtStrategy;constructor(e){this.baseUrl=e,this.jwtStrategy=new QG(async()=>{let e=Date.now(),t=localStorage.getItem(t6e),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(t6e,JSON.stringify(n)),t}}else localStorage.removeItem(t6e);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(t6e,JSON.stringify(a)),i)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},r6e=class extends Error{constructor(e){super(e),this.name=`APIError`}},i6e=class{_auth;_baseUrl;constructor(e){if(`authToken`in e)this._baseUrl=e.baseUrl,this._auth=new QG(e.authToken);else if(`apiKey`in e)this._baseUrl=(e.baseUrl??`https://backend.assistant-api.com`).replace(/\/$/,``),this._auth=new e6e(e.apiKey,e.userId,e.workspaceId);else if(`anonymous`in e)this._baseUrl=e.baseUrl,this._auth=new n6e(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 r6e(JSON.parse(e).message)}catch(t){throw t instanceof r6e?t:Error(`Request failed with status ${o.status}, ${e}`)}}return o}async makeRequest(e,t={}){return(await this.makeRawRequest(e,t)).json()}},a6e=class{cloud;constructor(e){this.cloud=e}async create(){return this.cloud.makeRequest(`/auth/tokens`,{method:`POST`})}},o6e=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 Y2e.fromResponse(t,new N4e)}async report(e){return this.cloud.makeRequest(`/runs`,{method:`POST`,body:e})}},s6e=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})}},$G=class{cloud;messages;constructor(e){this.cloud=e,this.messages=new s6e(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`})}},c6e=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})}},l6e=class{threads;auth;runs;files;telemetry;constructor(e){let t=new i6e(e);this.threads=new $G(t),this.auth={tokens:new a6e(t)},this.runs=new o6e(t),this.files=new c6e(t);let n=e.telemetry;this.telemetry=n===!1?{enabled:!1}:n===!0||n===void 0?{enabled:!0}:{enabled:n.enabled!==!1,...n}}},u6e=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={}}},d6e=(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)}),eK=new WeakMap,f6e=class{cloudRef;aui;constructor(e,t){this.cloudRef=e,this.aui=t}get _persistence(){let e=this.aui.threadListItem();return eK.has(e)||eK.set(e,new u6e(this.cloudRef.current)),eK.get(e)}withFormat(e){let t=this,n=d6e(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=Z3e(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(Q3e).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=x6e(e,t);i&&this._sendReport(r,i,n?.durationMs,n?.stepTimestamps)}_maybeReportRun(e,t,n){let r=b6e(t,n);r&&this._sendReport(e,r)}_sendReport(e,t,n,r){let i=y6e(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(()=>{})}},p6e=5e4;function m6e(e){return e.length<=p6e?e:e.slice(0,p6e)}function h6e(e){if(e!=null)try{return m6e(JSON.stringify(e))}catch{return}}var g6e=/^[A-Za-z0-9+/]{100,}={0,2}$/;function _6e(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`&&g6e.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 m6e(JSON.stringify(e))}}catch{}return h6e(e)}}function v6e(e,t,n,r,i,a){let o={tool_name:e,tool_call_id:t},s=i??h6e(n);s!==void 0&&(o.tool_args=s);let c=a===`mcp`?_6e(r):h6e(r);return c!==void 0&&(o.tool_result=c),a&&(o.tool_source=a),o}function y6e(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 b6e(e,t){switch(e){case`aui/v0`:return C6e(t);case`ai-sdk/v6`:return iK(t);default:return null}}function x6e(e,t){if(e===`ai-sdk/v6`)return k6e(t);for(let n=t.length-1;n>=0;n--){let r=b6e(e,t[n]);if(r)return r}return null}var S6e={error:`error`,incomplete:`incomplete`};function C6e(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=>v6e(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?m6e(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&&S6e[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 tK(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 w6e(e){return e.type===`dynamic-tool`||e.type.startsWith(`dynamic-tool-`)}function T6e(e){let t=w6e(e)?`mcp`:void 0;return v6e(e.toolName??e.type.slice(5),e.toolCallId,e.args??e.input,e.result??e.output,void 0,t)}function E6e(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(tK(a)){let e=T6e(a);n.push(e),i!==null&&i.push(e)}return i!==null&&r.push({tool_calls:i}),{textParts:t,toolCalls:n,stepsData:r}}function D6e(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 O6e(e,t,n,r,i,a){let o=e.length>0,s=o?m6e(e.join(``)):void 0,c=D6e(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 nK(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 rK(e){let t=e?.usage;if(t){let e=nK(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=nK(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 iK(e){let t=e;if(t.role!==`assistant`)return null;let{textParts:n,toolCalls:r,stepsData:i}=E6e(t.parts??[]);return O6e(n,r,i.length,t.metadata,i,rK(t.metadata))}function k6e(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:g,stepsData:_}=E6e(e.parts??[]);t.push(...h),n.push(...g),r.push(..._),e.metadata&&(a=e.metadata);let v=rK(e.metadata);v&&(v.inputTokens!=null&&(o+=v.inputTokens,u=!0),v.outputTokens!=null&&(s+=v.outputTokens,d=!0),v.reasoningTokens!=null&&(c+=v.reasoningTokens,f=!0),v.cachedInputTokens!=null&&(l+=v.cachedInputTokens,p=!0))}return i?O6e(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 A6e(e){let t=sG(),[n]=bW(()=>new f6e(e,t));return n}var j6e=e=>e.startsWith(`image/`)?`image`:e.startsWith(`text/`)?`document`:`file`,M6e=class{cloud;accept=`*`;constructor(e){this.cloud=e}uploadedUrls=new Map;async*add({file:e}){let t=crypto.randomUUID(),n={id:t,type:j6e(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}}},N6e=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}updateCustom(){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`))}},P6e=e=>B3e(e)?e:void 0,F6e=typeof process<`u`&&{}?.NEXT_PUBLIC_ASSISTANT_BASE_URL,I6e=F6e?new l6e({baseUrl:F6e,anonymous:!0}):void 0,L6e=e=>{let t=xW(e);wW(()=>{t.current=e},[e]);let n=CW(function({children:e}){let n=A6e({get current(){return t.current.cloud??I6e}}),r=t.current.cloud??I6e,i=SW(()=>new M6e(r),[r]);return(0,A.jsx)(g3e,{adapters:SW(()=>({history:n,attachments:i}),[n,i]),children:e})},[]),r=e.cloud??I6e;if(!r){let e=t,n=new N6e;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,custom:P6e(e.metadata)}))}},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}),updateCustom:async(e,t)=>r.threads.update(e,{metadata:t??null}),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,custom:P6e(t.metadata)}},unstable_Provider:n}},R6e=(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,z6e=()=>null,B6e=(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??z6e;default:throw Error(`Unknown message role: ${t}`)}},V6e=({components:e})=>(0,A.jsx)(B6e(e,cG(e=>e.message.role),cG(e=>e.message.composer.isEditing)),{}),aK=(0,_W.memo)(({index:e,components:t})=>(0,A.jsx)(EG,{index:e,children:(0,A.jsx)(V6e,{components:t})}),(e,t)=>e.index===t.index&&R6e(e.components,t.components));aK.displayName=`ThreadPrimitive.MessageByIndex`;var H6e=({children:e})=>{let t=cG(e=>e.thread.messages.length);return SW(()=>t===0?null:Array.from({length:t},(t,n)=>(0,A.jsx)(EG,{index:n,children:(0,A.jsx)(lG,{getItemState:e=>e.thread().message({index:n}).getState(),children:t=>e({get message(){return t()}})})},n)),[t,e])},oK=({components:e,children:t})=>e?(0,A.jsx)(H6e,{children:()=>(0,A.jsx)(V6e,{components:e})}):(0,A.jsx)(H6e,{children:t});oK.displayName=`ThreadPrimitive.Messages`;var U6e=(0,_W.memo)(oK,(e,t)=>e.children||t.children?e.children===t.children:R6e(e.components,t.components)),W6e=e=>{let t=e.message.metadata;if(!(!t||typeof t!=`object`))return t.custom?.quote},G6e=class extends Error{componentName;constructor(e,t=`Component "${e}" is not in the generative-ui allowlist.`){super(t),this.name=`GenerativeUIRenderError`,this.componentName=e}},K6e=e=>typeof e==`object`&&!!e,sK=(e,t,n,r)=>{if(e==null)return null;if(typeof e==`string`)return e;if(!K6e(e)||!(`component`in e))return null;let{component:i,props:a,children:o,key:s}=e,c=t[i];if(!c){if(n)return(0,A.jsx)(n,{component:i,props:a},s??r);throw new G6e(i)}let l=o?.length?o.map((e,i)=>sK(e,t,n,`${r}/${i}`)):void 0;return(0,_W.createElement)(c,{...a??{},key:s??r},...l??[])},q6e=e=>{if(!e||e.root===void 0||e.root===null)return[];let t=e.root;return Array.isArray(t)?t:[t]},cK=({spec:e,components:t,Fallback:n})=>(0,A.jsx)(A.Fragment,{children:SW(()=>q6e(e),[e]).map((e,r)=>sK(e,t,n,`${r}`))});cK.displayName=`GenerativeUIRender`;var J6e=({components:e,spec:t,Fallback:n})=>{let r=cG(e=>{let t=e.part;return t?.type===`generative-ui`?t.spec:void 0}),i=t??r;return i?(0,A.jsx)(cK,{spec:i,components:e,Fallback:n}):null};J6e.displayName=`MessagePrimitive.GenerativeUI`;var Y6e=`ui://`,X6e=e=>!!e?.startsWith(Y6e),Z6e=e=>Symbol.iterator in e,lK=e=>`entries`in e,Q6e=(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},$6e=(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 e8e(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Z6e(e)&&Z6e(t)?lK(e)&&lK(t)?Q6e(e,t):$6e(e,t):Q6e({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function t8e(e){let t=O.useRef(void 0);return n=>{let r=e(n);return e8e(t.current,r)?t.current:t.current=r}}var n8e=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})}}},uK=(e,t)=>{let n=[];if(t){let t=n8e(`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=n8e(`toolGroup`),r=n8e(`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},dK=e=>{let t=cG(t8e(e=>e.message.parts.map(e=>e.type)));return SW(()=>t.length===0?[]:uK(t,e),[t,e])},r8e=({Fallback:e,...t})=>{let n=cG(n=>n.tools.toolUIs[t.toolName]?.[0]?.render??e);return n?(0,A.jsx)(n,{...t}):null},fK=(e,t,n)=>e.renderers[t]?.[0]||(e.fallbacks[0]??n),i8e=({Fallback:e,...t})=>{let n=cG(n=>fK(n.dataRenderers,t.name,e));return n?(0,A.jsx)(n,{...t}):null},pK={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},a8e=({components:{Text:e=pK.Text,Reasoning:t=pK.Reasoning,Image:n=pK.Image,Source:r=pK.Source,File:i=pK.File,Unstable_Audio:a=pK.Unstable_Audio,tools:o={},data:s,generativeUI:c}={}})=>{let l=sG(),u=cG(e=>e.part),d=u.type;if(d===`tool-call`){let e=l.part().addToolResult,t=l.part().resumeToolCall,n=l.part().respondToToolApproval;if(`Override`in o)return(0,A.jsx)(o.Override,{...u,addResult:e,resume:t,respondToApproval:n});let r=o.by_name?.[u.toolName]??o.Fallback;return(0,A.jsx)(r8e,{...u,Fallback:r,addResult:e,resume:t,respondToApproval:n})}if(u.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(d){case`text`:return(0,A.jsx)(e,{...u});case`reasoning`:return(0,A.jsx)(t,{...u});case`source`:return(0,A.jsx)(r,{...u});case`image`:return(0,A.jsx)(n,{...u});case`file`:return(0,A.jsx)(i,{...u});case`audio`:return(0,A.jsx)(a,{...u});case`data`:{let e=s?.by_name?.[u.name]??s?.Fallback;return(0,A.jsx)(i8e,{...u,Fallback:e})}case`generative-ui`:return c?.components?(0,A.jsx)(cK,{spec:u.spec,components:c.components,Fallback:c.Fallback}):null;default:return console.warn(`Unknown message part type: ${d}`),null}},o8e=(0,_W.memo)(({index:e,components:t})=>(0,A.jsx)(B4e,{index:e,children:(0,A.jsx)(a8e,{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?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);o8e.displayName=`MessagePrimitive.PartByIndex`;var s8e=({status:e,component:t})=>(0,A.jsx)(H4e,{text:``,isRunning:e.type===`running`,children:(0,A.jsx)(t,{type:`text`,text:``,status:e})}),c8e=Object.freeze({type:`complete`}),l8e=Object.freeze({type:`running`}),mK=(0,_W.memo)(({components:e})=>{let t=cG(e=>e.message.status??c8e);return e?.Empty?(0,A.jsx)(e.Empty,{status:t}):t.type===`running`?(0,A.jsx)(s8e,{status:t,component:e?.Text??pK.Text}):null},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),u8e=(0,_W.memo)(({components:e,enabled:t})=>cG(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,A.jsx)(mK,{components:e}):null,(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),d8e=(0,_W.memo)(({Quote:e})=>{let t=cG(W6e);return t?(0,A.jsx)(e,{text:t.text,messageId:t.messageId}):null});function f8e(e,t){return(e.toolUIs[t.toolName]?.[0]?.render??null)||(X6e(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}var p8e=()=>{let e=sG(),t=cG(e=>e.part),n=cG(e=>e.part.type===`tool-call`?f8e(e.tools,e.part):null);return!n||t.type!==`tool-call`?null:(0,A.jsx)(n,{...t,addResult:e.part().addToolResult,resume:e.part().resumeToolCall,respondToApproval:e.part().respondToToolApproval})},m8e=()=>{let e=cG(e=>e.part),t=cG(e=>e.part.type===`data`?fK(e.dataRenderers,e.part.name,void 0)??null:null);return!t||e.type!==`data`?null:(0,A.jsx)(t,{...e})},h8e=()=>{let e=cG(e=>e.part.type);return e===`tool-call`?(0,A.jsx)(p8e,{}):e===`data`?(0,A.jsx)(m8e,{}):null},g8e=Object.freeze({type:`text`,text:``,status:l8e}),_8e=({index:e,children:t})=>{let n=sG(),r=cG(e=>e.dataRenderers);return(0,A.jsx)(B4e,{index:e,children:(0,A.jsx)(lG,{getItemState:t=>t.message().part({index:e}).getState(),children:i=>t({get part(){let t=i();if(t.type===`tool-call`){let r=f8e(n.tools().getState(),t)!==null,i=n.message().part({index:e});return{...t,toolUI:r?(0,A.jsx)(p8e,{}):null,addResult:i.addToolResult,resume:i.resumeToolCall,respondToApproval:i.respondToToolApproval}}if(t.type===`data`){let e=fK(r,t.name,void 0)!==void 0;return{...t,dataRendererUI:e?(0,A.jsx)(m8e,{}):null}}return t}})})})},hK=({children:e})=>{let t=cG(e=>e.message.parts.length),n=cG(e=>(e.message.status?.type??`complete`)===`running`);return t===0?t===0&&n?(0,A.jsx)(H4e,{text:``,isRunning:!0,children:e({part:g8e})}):null:(0,A.jsx)(A.Fragment,{children:Array.from({length:t},(t,n)=>(0,A.jsx)(_8e,{index:n,children:t=>e(t)??(0,A.jsx)(h8e,{})},n))})},gK=({components:e,unstable_showEmptyOnNonTextEnd:t=!0,children:n})=>n?(0,A.jsx)(hK,{children:n}):(0,A.jsx)(v8e,{components:e,unstable_showEmptyOnNonTextEnd:t});gK.displayName=`MessagePrimitive.Parts`;var v8e=({components:e,unstable_showEmptyOnNonTextEnd:t})=>{let n=cG(e=>e.message.parts.length),r=dK(!!e?.ChainOfThought),i=SW(()=>n===0?(0,A.jsx)(mK,{components:e}):r.map(t=>{if(t.type===`single`)return(0,A.jsx)(o8e,{index:t.index,components:e},t.index);if(t.type===`chainOfThoughtGroup`){let n=e?.ChainOfThought;return n?(0,A.jsx)(G4e,{startIndex:t.startIndex,endIndex:t.endIndex,children:(0,A.jsx)(n,{})},`chainOfThought-${t.startIndex}`):null}else if(t.type===`toolGroup`)return(0,A.jsx)(e?.ToolGroup??pK.ToolGroup,{startIndex:t.startIndex,endIndex:t.endIndex,children:Array.from({length:t.endIndex-t.startIndex+1},(n,r)=>{let i=t.startIndex+r;return(0,A.jsx)(o8e,{index:i,components:e},`part-${i}`)})},`tool-${t.startIndex}`);else return(0,A.jsx)(e?.ReasoningGroup??pK.ReasoningGroup,{startIndex:t.startIndex,endIndex:t.endIndex,children:Array.from({length:t.endIndex-t.startIndex+1},(n,r)=>{let i=t.startIndex+r;return(0,A.jsx)(o8e,{index:i,components:e},`part-${i}`)})},`reasoning-${t.startIndex}`)}),[r,e,n]);return(0,A.jsxs)(A.Fragment,{children:[e?.Quote&&(0,A.jsx)(d8e,{Quote:e.Quote}),i,(0,A.jsx)(u8e,{components:e,enabled:t})]})},y8e=Symbol.for(`@assistant-ui/groupBy.memoKey`),b8e=e=>{let t=e.nextChildIdx++;return e.nodeKey===``?String(t):`${e.nodeKey}.${t}`},x8e=e=>{let t={key:``,nodeKey:``,indices:[],children:[],nextChildIdx:0},n=[t],r=()=>{let e=n.pop();n[n.length-1].children.push({type:`group`,key:e.key,nodeKey:e.nodeKey,indices:e.indices,children:e.children})};for(let t=0;t<e.length;t++){let i=e[t],a=0;for(;a<n.length-1&&a<i.length&&n[a+1].key===i[a];)a++;for(;n.length-1>a;)r();for(;n.length-1<i.length;){let e=n[n.length-1];n.push({key:i[n.length-1],nodeKey:b8e(e),indices:[],children:[],nextChildIdx:0})}let o=n[n.length-1];o.children.push({type:`part`,index:t,nodeKey:b8e(o)});for(let e=1;e<n.length;e++)n[e].indices.push(t)}for(;n.length>1;)r();return t.children},S8e=Object.freeze({type:`complete`}),C8e=(e,t,n)=>{if(!n)return!1;switch(e){case`never`:return!1;case`always`:return!0;case`empty`:return t.length===0;case`no-text`:{let e=t[t.length-1];return e!==void 0&&e.type!==`text`&&e.type!==`reasoning`}}},w8e=()=>{throw Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},T8e=(e,t,n)=>{if(e.type===`part`)return(0,A.jsx)(_8e,{index:e.index,children:({part:e})=>n({part:e,children:(0,A.jsx)(w8e,{})})},`part-${e.index}`);let r=t[e.indices.at(-1)]?.status??S8e;return(0,A.jsx)(_W.Fragment,{children:n({part:{type:e.key,status:r,indices:e.indices},children:(0,A.jsx)(A.Fragment,{children:e.children.map(e=>T8e(e,t,n))})})},e.nodeKey)},E8e=({groupBy:e,indicator:t=`no-text`,children:n})=>{let r=cG(t8e(e=>e.message.parts)),i=cG(e=>e.tools.toolUIs),a=cG(e=>t===`never`?!1:e.message.status?.type===`running`);return(0,A.jsxs)(A.Fragment,{children:[SW(()=>{let t={toolUIs:i};return x8e(r.map(n=>e(n,t)??[]))},[r,e[y8e]??e,i]).map(e=>T8e(e,r,n)),C8e(t,r,a)&&n({part:{type:`indicator`},children:(0,A.jsx)(w8e,{})})]})};E8e.displayName=`MessagePrimitive.GroupedParts`;var D8e=(0,_W.memo)(({children:e})=>{let t=cG(W6e);return t?(0,A.jsx)(A.Fragment,{children:e(t)}):null});D8e.displayName=`MessagePrimitive.Quote`;var O8e=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},k8e=({components:e})=>{let t=cG(e=>e.attachment);if(!t)return null;let n=O8e(e,t);return n?(0,A.jsx)(n,{}):null},_K=(0,_W.memo)(({index:e,components:t})=>(0,A.jsx)(L4e,{index:e,children:(0,A.jsx)(k8e,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);_K.displayName=`MessagePrimitive.AttachmentByIndex`;var A8e=({children:e})=>{let t=cG(e=>e.message.role===`user`?(e.message.attachments??[]).length:0);return SW(()=>Array.from({length:t},(t,n)=>(0,A.jsx)(L4e,{index:n,children:(0,A.jsx)(lG,{getItemState:e=>e.message().attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},n)),[t,e])},j8e=({components:e,children:t})=>e?(0,A.jsx)(A8e,{children:({attachment:t})=>{let n=O8e(e,t);return n?(0,A.jsx)(n,{}):null}}):(0,A.jsx)(A8e,{children:t});j8e.displayName=`MessagePrimitive.Attachments`;var vK=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},M8e=({components:e})=>{let t=cG(e=>e.attachment);if(!t)return null;let n=vK(e,t);return n?(0,A.jsx)(n,{}):null},yK=(0,_W.memo)(({index:e,components:t})=>(0,A.jsx)(R4e,{index:e,children:(0,A.jsx)(M8e,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);yK.displayName=`ComposerPrimitive.AttachmentByIndex`;var N8e=({children:e})=>{let t=cG(e=>e.composer.attachments.length);return SW(()=>Array.from({length:t},(t,n)=>(0,A.jsx)(R4e,{index:n,children:(0,A.jsx)(lG,{getItemState:e=>e.composer().attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},n)),[t,e])},P8e=({components:e,children:t})=>e?(0,A.jsx)(N8e,{children:({attachment:t})=>{let n=vK(e,t);return n?(0,A.jsx)(n,{}):null}}):(0,A.jsx)(N8e,{children:t});P8e.displayName=`ComposerPrimitive.Attachments`;var F8e=(0,_W.memo)(({children:e})=>{let t=cG(e=>e.composer.queue.length);return SW(()=>Array.from({length:t},(t,n)=>(0,A.jsx)(K4e,{index:n,children:(0,A.jsx)(lG,{getItemState:e=>e.composer().queueItem({index:n}).getState(),children:t=>e({get queueItem(){return t()}})})},n)),[t,e])});F8e.displayName=`ComposerPrimitive.Queue`;var I8e=({children:e})=>cG(e=>e.part.status.type===`running`)?e:null;I8e.displayName=`MessagePartPrimitive.InProgress`;var L8e=({components:e})=>{let t=e.Suggestion;return(0,A.jsx)(t,{})},R8e=(0,_W.memo)(({index:e,components:t})=>(0,A.jsx)(DG,{index:e,children:(0,A.jsx)(L8e,{components:t})}),(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);R8e.displayName=`ThreadPrimitive.SuggestionByIndex`;var z8e=({children:e})=>{let t=cG(e=>e.suggestions.suggestions.length);return SW(()=>t===0?null:Array.from({length:t},(t,n)=>(0,A.jsx)(DG,{index:n,children:(0,A.jsx)(lG,{getItemState:e=>e.suggestions().suggestion({index:n}).getState(),children:t=>e({get suggestion(){return t()}})})},n)),[t,e])},B8e=({components:e,children:t})=>e?(0,A.jsx)(z8e,{children:()=>(0,A.jsx)(L8e,{components:e})}):(0,A.jsx)(z8e,{children:t});B8e.displayName=`ThreadPrimitive.Suggestions`;var V8e=(0,_W.memo)(B8e,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),H8e=e=>cG(t=>{if(e.editing===!0&&!t.composer.isEditing||e.editing===!1&&t.composer.isEditing)return!1;let n=t.composer.dictation!=null;return!(e.dictation===!0&&!n||e.dictation===!1&&n)}),U8e=({children:e,...t})=>H8e(t)?e:null;U8e.displayName=`ComposerPrimitive.If`;var bK=()=>{let e=sG(),t=cG(e=>!e.composer.canSend||e.thread.isRunning&&!e.thread.capabilities.queue);return{send:CW(t=>{e.composer().send(t)},[e]),disabled:t}},W8e=()=>{let e=sG(),t=cG(e=>!e.composer.canCancel);return{cancel:CW(()=>{e.composer().cancel()},[e]),disabled:t}},G8e=()=>{let e=sG(),t=cG(e=>e.composer.dictation!=null||!e.thread.capabilities.dictation||!e.composer.isEditing);return{startDictation:CW(()=>{e.composer().startDictation()},[e]),disabled:t}},K8e=()=>{let e=sG(),t=cG(e=>!e.composer.isEditing);return{addAttachment:CW(t=>e.composer().addAttachment(t),[e]),disabled:t}},q8e=({prompt:e,send:t,clearComposer:n=!0})=>{let r=sG(),i=cG(e=>e.thread.isDisabled),a=t??!1;return{trigger:CW(()=>{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}},J8e=()=>cG(e=>e.message.status?.type===`incomplete`&&e.message.status.reason===`error`?e.message.status.error??`An error occurred`:void 0),Y8e=e=>{let t=WG,n=new Map,r=new Set,i=!1,a=0,o=()=>{for(let e of r)e()},s=e=>{t=e,d.items=e,o()},c=()=>{if(i||t.length===0)return;let r=t[0],a=n.get(r.id);n.delete(r.id),s(t.slice(1)),a&&(i=!0,e.run(a,{steer:!1}))},l=(e,{steer:r})=>{let i=zG(),a=IG(e);n.set(i,e),s([...t,{id:i,prompt:a}]),r?u(i):c()},u=r=>{if(!n.has(r))return;if(e.cancel&&i){let o=n.get(r);n.delete(r),s(t.filter(e=>e.id!==r)),a++,e.cancel(),i=!0,e.run(o,{steer:!0});return}let o=t.find(e=>e.id===r);o&&(s([o,...t.filter(e=>e.id!==r)]),c())},d={items:t,enqueue:l,steer:u,remove:e=>{n.delete(e)&&s(t.filter(t=>t.id!==e))},clear:()=>{t.length!==0&&(n.clear(),s(WG))}};return{adapter:d,notifyBusy:()=>{i=!0},notifyIdle:()=>{if(a>0){a--;return}i=!1,c()},subscribe:e=>(r.add(e),()=>{r.delete(e)})}},X8e=(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)),xK=class extends Error{name=`AbortError`;detach;constructor(e,t){super(t),this.detach=e}},Z8e=class extends z3e{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;_queue=null;_queueRunInFlight=!1;isDisabled=!1;isSendDisabled=!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);let s=e.unstable_enableMessageQueue===!0;s&&!this._queue?(this._queue=Y8e({run:e=>{this._queueRunInFlight=!0,this._runAppend(e).finally(()=>{this._queueRunInFlight=!1,this._queue?.notifyIdle()}).catch(()=>{})}}),this._queue.subscribe(()=>this._notifySubscribers())):!s&&this._queue&&(this._queue.adapter.clear(`cancel-run`),this._queue=null),this.capabilities.queue!==s&&(this.capabilities.queue=s,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){let t=e.parentId===(this.messages.at(-1)?.id??null),n=e.startRun??e.role===`user`;if(this._queue&&n&&t){this._queue.adapter.enqueue(e,{steer:e.steer??!1});return}return this._queue&&!t&&this._queue.adapter.clear(`edit`),this._runAppend(e)}getQueueItems(){return this._queue?.adapter.items??WG}steerQueueItem(e){this._queue?.adapter.steer(e)}removeQueueItem(e){this._queue?.adapter.remove(e)}async _runAppend(e){this.ensureInitialized();let t=this._getInitializePromise?.();t&&await t;let n=VG(e,zG(),{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.`)}async startRun({parentId:e,runConfig:t},n){this.ensureInitialized();let r={id:zG(),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._queue?.notifyBusy(),this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do r=await this.performRoundtrip(e,r,t,n),n=void 0;while(X8e(r,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers(`runEnd`,{}),this._queueRunInFlight||queueMicrotask(()=>this._queue?.notifyIdle())}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,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 xK)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(){this._queue?.adapter.clear(`cancel-run`);let e=new xK(!0);this.abortController?.abort(e),this.abortController=null}cancelRun(){this._queue?.adapter.clear(`cancel-run`);let e=new xK(!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&&X8e(s,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,s,this._lastRunConfig).catch(()=>{})}resumeToolCall(e){throw Error(`Local runtime does not support resuming tool calls.`)}respondToToolApproval(e){throw Error(`Local runtime does not support tool approvals.`)}},Q8e=Object.freeze([]),SK=`__DEFAULT_ID__`,$8e=Object.freeze({[SK]:{id:SK,remoteId:void 0,externalId:void 0,status:`regular`,title:void 0}}),CK=class extends kG{_mainThread;constructor(e){super(),this._mainThread=e()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){}get threadIds(){return Q8e}get archivedThreadIds(){return Q8e}get mainThreadId(){return SK}get threadItems(){return $8e}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.`)}},e5e=class extends C3e{threads;Provider=void 0;_options;constructor(e,t){super(),this._options=e,this.threads=new CK(()=>new Z8e(this._contextProvider,this._options)),t&&this.threads.getMainThreadRuntimeCore().import(HG.fromArray(t))}},t5e=(e,{initialMessages:t,...n})=>{let{modelContext:r,...i}=_3e()??{},a={...n,adapters:{...i,...n.adapters,chatModel:e}},[o]=bW(()=>new e5e(a,t)),s=xW(void 0);return s.current=cG(e=>e.threadListItem.remoteId),wW(()=>{o.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>s.current)},[o]),wW(()=>()=>{o.threads.getMainThreadRuntimeCore().detach()},[o]),wW(()=>{o.threads.getMainThreadRuntimeCore().__internal_setOptions(a),o.threads.getMainThreadRuntimeCore().__internal_load()}),wW(()=>{if(r)return o.registerModelContextProvider(r)},[r,o]),SW(()=>new S3e(o),[o])},n5e=(e,{cloud:t,...n}={})=>X3e({runtimeHook:function(){return t5e(e,n)},adapter:L6e({cloud:t}),allowNesting:!0}),r5e=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,i5e={serialize(e){let t=e.id===e.label?``:`{name=${e.id}}`;return`:${e.type}[${e.label}]${t}`},parse(e){let t=[],n=0;for(let r of e.matchAll(r5e)){r.index>n&&t.push({kind:`text`,text:e.slice(n,r.index)});let i=r[2];t.push({kind:`mention`,type:r[1],label:i,id:r[3]??i}),n=r.index+r[0].length}return n<e.length&&t.push({kind:`text`,text:e.slice(n)}),t}};function a5e(e,t){function n(n){let r=DW(e);if(!n?.optional&&!r)throw Error(`This component must be used within ${t}.`);return r}return n}function o5e(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 s5e=(0,_W.createContext)(null),{useThreadViewport:wK,useThreadViewportStore:TK}=o5e(a5e(s5e,`ThreadPrimitive.Viewport`),`useThreadViewport`),c5e=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()}}}}},l5e=(e={})=>{let t=new Set,n=c5e(e=>{a.setState({height:{...a.getState().height,viewport:e}})}),r=c5e(e=>{a.setState({height:{...a.getState().height,inset:e}})}),i=(e,t)=>(a.setState({element:{...a.getState().element,[e]:t}}),()=>{a.getState().element[e]===t&&a.setState({element:{...a.getState().element,[e]:null}})}),a=bG(()=>({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`,topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??`10em`,visibleHeight:e.topAnchorMessageClamp?.visibleHeight??`6em`},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:n.register,registerContentInset:r.register,registerViewportElement:e=>i(`viewport`,e),registerAnchorElement:e=>i(`anchor`,e),registerAnchorTargetElement:(e,t)=>(a.setState({element:{...a.getState().element,target:e},targetConfig:e&&t?t:null}),()=>{a.getState().element.target===e&&a.setState({element:{...a.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:e=>{a.setState({topAnchorTurn:e})}}));return a},u5e=e=>e,d5e=e=>{let t=TK({optional:!0}),[n]=bW(()=>l5e(e));return wW(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),wW(()=>{if(t)return n.subscribe(e=>{t.getState().isAtBottom!==e.isAtBottom&&u5e(t).setState({isAtBottom:e.isAtBottom})})},[n,t]),n},f5e=({children:e,options:t={}})=>{let n=d5e(t),[r]=bW(()=>({useThreadViewport:n}));return(0,A.jsx)(s5e.Provider,{value:r,children:e})},p5e=()=>(wW(()=>{},[sG()]),null),m5e=(0,_W.memo)(({children:e,aui:t,runtime:n})=>(0,A.jsxs)(W2e,{runtime:n,aui:t??null,children:[(0,A.jsx)(p5e,{}),(0,A.jsx)(f5e,{children:e})]}));function h5e(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}function g5e(...e){return t=>{let n=!1,r=e.map(e=>{let r=h5e(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;t<r.length;t++){let n=r[t];typeof n==`function`?n():h5e(e[t],null)}}}}function EK(...e){return O.useCallback(g5e(...e),e)}var _5e=Object.defineProperty,v5e=(e,t)=>{let n={};for(var r in e)_5e(n,r,{get:e[r],enumerable:!0});return t||_5e(n,Symbol.toStringTag,{value:`Module`}),n};function y5e(e){let t=O.forwardRef((t,n)=>{let{children:r,...i}=t,a=null,o=!1,s=[];E5e(r)&&typeof OK==`function`&&(r=OK(r._payload)),O.Children.forEach(r,e=>{if(DK(e)){o=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;E5e(n)&&typeof OK==`function`&&(n=OK(n._payload)),a=S5e(t,n),s.push(a?.props?.children)}else s.push(e)}),a?a=O.cloneElement(a,void 0,s):!o&&O.Children.count(r)===1&&O.isValidElement(r)&&(a=r);let c=a?w5e(a):void 0,l=EK(n,c);if(!a){if(r||r===0)throw Error(o?k5e(e):O5e(e));return r}let u=C5e(i,a.props??{});return a.type!==O.Fragment&&(u.ref=n?l:c),O.cloneElement(a,u)});return t.displayName=`${e}.Slot`,t}var b5e=y5e(`Slot`),x5e=Symbol.for(`radix.slottable`),S5e=(e,t)=>{if(`child`in e.props){let t=e.props.child;return O.isValidElement(t)?O.cloneElement(t,void 0,e.props.children(t.props.children)):null}return O.isValidElement(t)?t:null};function C5e(e,t){let n={...t};for(let r in t){let i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...e)=>{let t=a(...e);return i(...e),t}:i&&(n[r]=i):r===`style`?n[r]={...i,...a}:r===`className`&&(n[r]=[i,a].filter(Boolean).join(` `))}return{...e,...n}}function w5e(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function DK(e){return O.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===x5e}var T5e=Symbol.for(`react.lazy`);function E5e(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===T5e&&`_payload`in e&&D5e(e._payload)}function D5e(e){return typeof e==`object`&&!!e&&`then`in e}var O5e=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,k5e=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,OK=O.use;x();var A5e=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=y5e(`Primitive.${t}`),r=O.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,A.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),j5e=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`];function M5e(e){let t=(0,_W.forwardRef)(({render:t,asChild:n,children:r,...i},a)=>{let o=e;if(t&&(0,_W.isValidElement)(t)){let e=r===void 0?t.props.children:r;return(0,A.jsx)(o,{...i,asChild:!0,ref:a,children:(0,_W.cloneElement)(t,void 0,e)})}return(0,A.jsx)(o,{...i,asChild:n,ref:a,children:r})});return t.displayName=typeof e==`string`?e:e.displayName??e.name??`Component`,t}function N5e(e){let t=A5e[e],n=M5e(t);return n.displayName=`Primitive.${e}`,n}var kK=j5e.reduce((e,t)=>(e[t]=N5e(t),e),{});typeof window<`u`&&window.document&&window.document.createElement;function AK(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}var jK=(e,t,n=[])=>{let r=(0,_W.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,A.jsx)(kK.button,{...a,type:`button`,ref:r,disabled:a.disabled||!o,onClick:AK(a.onClick,o)})});return r.displayName=e,r};function MK(e){let t=O.useRef(e);return O.useEffect(()=>{t.current=e}),O.useMemo(()=>((...e)=>t.current?.(...e)),[])}function P5e(e,t=globalThis?.document){let n=MK(e);O.useEffect(()=>{let e=e=>{e.key===`Escape`&&n(e)};return t.addEventListener(`keydown`,e,{capture:!0}),()=>t.removeEventListener(`keydown`,e,{capture:!0})},[n,t])}var F5e=e=>cG(t=>{let{role:n,attachments:r,parts:i,branchCount:a,isLast:o,speech:s,isCopied:c,isHovering:l}=t.message;return!(e.hasBranches===!0&&a<2||e.user&&n!==`user`||e.assistant&&n!==`assistant`||e.system&&n!==`system`||e.lastOrHover===!0&&!l&&!o||e.last!==void 0&&e.last!==o||e.copied===!0&&!c||e.copied===!1&&c||e.speaking===!0&&s==null||e.speaking===!1&&s!=null||e.hasAttachments===!0&&(n!==`user`||!r?.length)||e.hasAttachments===!1&&n===`user`&&r?.length||e.hasContent===!0&&i.length===0||e.hasContent===!1&&i.length>0||e.submittedFeedback!==void 0&&(t.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)}),NK=({children:e,...t})=>F5e(t)?e:null;NK.displayName=`MessagePrimitive.If`;var I5e=(0,_W.createContext)(null),L5e=()=>DW(I5e),R5e=({children:e})=>{let t=xW(new Map),n=xW([]),r=CW(()=>{let e=Array.from(t.current.entries());e.sort((e,t)=>t[1]-e[1]),n.current=e.map(([e])=>e)},[]),i=CW((e,n)=>{let i=n?.priority??0;return t.current.set(e,i),r(),()=>{t.current.delete(e),r()}},[r]),a=CW(()=>n.current,[]),o=SW(()=>({register:i,getPlugins:a}),[i,a]);return(0,A.jsx)(I5e.Provider,{value:o,children:e})},PK=(0,_W.createContext)(null),z5e=(0,_W.createContext)(null),FK=()=>{let e=DW(PK);if(!e)throw Error(`useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},B5e=()=>DW(PK),V5e=()=>{let e=DW(z5e);if(!e)throw Error(`useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},H5e=()=>{let e=FK();return(0,_W.useSyncExternalStore)(e.subscribe,e.getTriggers,e.getTriggers)},IK=new Map,LK=()=>()=>{},U5e=()=>IK,W5e=()=>{let e=B5e();return(0,_W.useSyncExternalStore)(e?e.subscribe:LK,e?e.getTriggers:U5e,e?e.getTriggers:U5e)},G5e=()=>null,K5e=()=>{let e=B5e();return(0,_W.useSyncExternalStore)(e?e.subscribeAria:LK,e?e.getActiveAria:G5e,e?e.getActiveAria:G5e)};function q5e(){let e=xW(new Set);return{notify:CW(()=>{for(let t of e.current)t()},[]),subscribe:CW(t=>(e.current.add(t),()=>{e.current.delete(t)}),[])}}var J5e=({children:e})=>{let t=xW(new Map),n=xW(new Set),{notify:r,subscribe:i}=q5e(),a=CW(e=>{let{char:i}=e;if(t.current.has(i))return()=>{};let a=new Map(t.current);a.set(i,e),t.current=a,r();for(let t of n.current)t.added(e);return()=>{let e=new Map(t.current);e.delete(i),t.current=e,r();for(let e of n.current)e.removed(i)}},[r]),o=CW(()=>t.current,[]),s=CW(e=>(n.current.add(e),()=>{n.current.delete(e)}),[]),c=xW(null),l=xW(null),{notify:u,subscribe:d}=q5e(),f=CW((e,t)=>{if(t===null){if(l.current!==e)return;c.current=null,l.current=null,u();return}let n=c.current;l.current===e&&n!==null&&n.popoverId===t.popoverId&&n.highlightedItemId===t.highlightedItemId||(c.current=t,l.current=e,u())},[u]),p=CW(()=>c.current,[]),m=SW(()=>({register:a,getTriggers:o,subscribe:i,subscribeLifecycle:s,getActiveAria:p,subscribeAria:d}),[a,o,i,s,p,d]),h=SW(()=>({setActiveAria:f}),[f]);return(0,A.jsx)(PK.Provider,{value:m,children:(0,A.jsx)(z5e.Provider,{value:h,children:e})})},Y5e=({children:e})=>L5e()?(0,A.jsx)(J5e,{children:e}):(0,A.jsx)(R5e,{children:(0,A.jsx)(J5e,{children:e})});Y5e.displayName=`ComposerPrimitive.TriggerPopoverRoot`;var RK=/\s/u;function X5e(e,t,n){let r=e.slice(0,n);for(let e=r.length-1;e>=0;e--){let n=r[e];if(RK.test(n))return null;if(r.startsWith(t,e)){if(e>0&&!RK.test(r[e-1]))continue;return{query:r.slice(e+t.length),offset:e}}}return null}var Z5e=AW(function({text:e,triggerChar:t}){let[n,r]=bW(e.length),i=SW(()=>X5e(e,t,Math.min(n,e.length)),[n,e,t]);return{trigger:i,query:i?.query??``,setCursorPosition:r}});function Q5e(e){return`type`in e}var zK=AW(function({navigableList:e,isSearchMode:t,activeCategoryId:n,query:r,popoverId:i,open:a,selectItem:o,selectCategory:s,goBack:c,close:l}){let[u,d]=bW(0);wW(()=>{d(0)},[e]),wW(()=>{d(0)},[t,n]);let f=EW(t=>{t<0||t>=e.length||t!==u&&d(t)}),p=EW(t=>{if(!a)return!1;switch(t.key){case`ArrowDown`:return t.preventDefault(),d(t=>{let n=e.length;return n===0?0:t<n-1?t+1:0}),!0;case`ArrowUp`:return t.preventDefault(),d(t=>{let n=e.length;return n===0?0:t>0?t-1:n-1}),!0;case`Enter`:case`Tab`:{if(t.shiftKey)return!1;t.preventDefault();let n=e[u];return n&&(Q5e(n)?o(n):s(n.id)),!0}case`Escape`:return t.preventDefault(),l(),!0;case`Backspace`:return n&&r===``?(t.preventDefault(),c(),!0):!1;default:return!1}}),m=e[u];return{highlightedIndex:u,highlightedItemId:a&&m?`${i}-option-${m.id}`:void 0,highlightIndex:f,handleKeyDown:p}});function $5e(e,t){return e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}var e7e=AW(function({adapter:e,query:t,open:n}){let[r,i]=bW(null);wW(()=>{n||i(null)},[n]);let a=SW(()=>!n||!e?[]:e.categories(),[n,e]),o=n?r:null,s=SW(()=>!o||!e?[]:e.categoryItems(o),[o,e]),c=SW(()=>{if(!n||!e||o||!t&&a.length>0)return null;if(e.search)return e.search(t);let r=[],i=t.toLowerCase();for(let t of a)for(let n of e.categoryItems(t.id))$5e(n,i)&&r.push(n);return r},[n,e,t,o,a]),l=c!==null,u=SW(()=>{if(l)return[];if(!t)return a;let e=t.toLowerCase();return a.filter(t=>t.label.toLowerCase().includes(e))},[a,t,l]),d=SW(()=>{if(l)return c??[];if(!t)return s;let e=t.toLowerCase();return s.filter(t=>$5e(t,e))},[s,t,l,c]);return{categories:u,items:d,isSearchMode:l,activeCategoryId:o,navigableList:SW(()=>l?c??[]:o?d:u,[l,c,o,d,u]),selectCategory:EW(e=>{i(e)}),goBack:EW(()=>{i(null)})}}),t7e=AW(function({behavior:e,trigger:t,aui:n,triggerChar:r,setCursorPosition:i,onSelected:a}){let o=xW(null),s=EW(e=>(o.current=e,()=>{o.current===e&&(o.current=null)}));return{selectItem:EW(i=>{if(!t||!e)return;if(o.current?.(i)){a();return}let s=n.composer().getState().text,c=s.slice(0,t.offset),l=s.slice(t.offset+r.length+t.query.length),u=()=>{let t=e.formatter.serialize(i);n.composer().setText(c+t+(l.startsWith(` `)?l:` ${l}`))};e.kind===`directive`?(u(),e.onInserted?.(i)):(e.removeOnExecute?n.composer().setText(c+(l.startsWith(` `)?l.slice(1):l)):u(),e.onExecute(i)),a()}),close:EW(()=>{a(),t&&i(t.offset)}),registerSelectItemOverride:s}}),n7e=AW(function({adapter:e,text:t,triggerChar:n,behavior:r,aui:i,popoverId:a}){let o=BW(Z5e({text:t,triggerChar:n})),s=o.trigger!==null&&e!==void 0&&r!==void 0,c=BW(e7e({adapter:e,query:o.query,open:s})),l=EW(()=>{c.goBack()}),u=BW(t7e({behavior:r,trigger:o.trigger,aui:i,triggerChar:n,setCursorPosition:o.setCursorPosition,onSelected:l})),d=BW(zK({navigableList:c.navigableList,isSearchMode:c.isSearchMode,activeCategoryId:c.activeCategoryId,query:o.query,popoverId:a,open:s,selectItem:u.selectItem,selectCategory:c.selectCategory,goBack:c.goBack,close:u.close}));return{open:s,query:o.query,activeCategoryId:c.activeCategoryId,categories:c.categories,items:c.items,highlightedIndex:d.highlightedIndex,isSearchMode:c.isSearchMode,popoverId:a,highlightedItemId:d.highlightedItemId,selectCategory:c.selectCategory,goBack:c.goBack,selectItem:u.selectItem,close:u.close,highlightIndex:d.highlightIndex,handleKeyDown:d.handleKeyDown,setCursorPosition:o.setCursorPosition,registerSelectItemOverride:u.registerSelectItemOverride}}),r7e=(0,_W.createContext)(null),BK=()=>{let e=DW(r7e);if(!e)throw Error(`useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover`);return e},i7e=()=>DW(r7e),a7e=(0,_W.createContext)(null),o7e=()=>{let e=DW(a7e);if(!e)throw Error(`TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover`);return e},s7e=(0,_W.forwardRef)(({char:e,adapter:t,"aria-label":n,children:r,...i},a)=>{let o=sG(),s=cG(e=>e.composer.text),c=(0,_W.useId)(),l=xW(null),[u,d]=bW(null),f=xW(0),p=CW(e=>(f.current+=1,l.current=e,d(e),()=>{f.current=Math.max(0,f.current-1),l.current===e&&(l.current=null,d(null))}),[e]),m=SW(()=>({register:p}),[p]),h=BW(n7e({adapter:t,text:s,triggerChar:e,behavior:u??void 0,aui:o,popoverId:c})),g=xW(h);g.current=h;let _=FK();wW(()=>_.register({char:e,...u?{behavior:u}:{},resource:g.current}),[_,e,u]);let v=L5e();wW(()=>{if(v)return v.register(g.current)},[v]);let y=u!==null&&h.open,b=V5e();return wW(()=>{if(y)return()=>{b.setActiveAria(e,null)}},[b,e,y]),wW(()=>{y&&b.setActiveAria(e,{popoverId:c,highlightedItemId:h.highlightedItemId})},[b,e,c,y,h.highlightedItemId]),(0,A.jsx)(a7e.Provider,{value:m,children:(0,A.jsx)(r7e.Provider,{value:h,children:y?(0,A.jsx)(kK.div,{role:`listbox`,id:c,"aria-label":n??`Suggestions`,"aria-activedescendant":h.highlightedItemId,"data-state":`open`,...i,ref:a,children:r}):r})})});s7e.displayName=`ComposerPrimitive.TriggerPopover`;var VK=()=>{let{disabled:e,send:t}=bK(),n=CW(()=>t(),[t]);return e?null:n},c7e=jK(`ComposerPrimitive.Send`,VK),l7e=(0,_W.forwardRef)(({onSubmit:e,...t},n)=>{let r=VK(),i=e=>{e.preventDefault(),r&&r()};return(0,A.jsx)(kK.form,{...t,ref:n,onSubmit:AK(e,i)})});l7e.displayName=`ComposerPrimitive.Root`;var u7e=e=>{let t=MK(e),n=wK(e=>e.onScrollToBottom);wW(()=>n(t),[n,t])},d7e=()=>!1,f7e=()=>{},p7e=e=>(0,_W.useSyncExternalStore)(CW(t=>{if(typeof window>`u`||e===null)return f7e;let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},[e]),CW(()=>typeof window>`u`||e===null?!1:window.matchMedia(e).matches,[e]),d7e),m7e=`(pointer: coarse) and (not (any-pointer: fine))`,HK=(0,_W.forwardRef)(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:i,onKeyDown:a,onPaste:o,onSelect:s,submitOnEnter:c,submitMode:l,cancelOnEscape:u=!0,unstable_focusOnRunStart:d=!0,unstable_focusOnScrollToBottom:f=!0,unstable_focusOnThreadSwitched:p=!0,unstable_insertNewlineOnTouchEnter:m=!1,addAttachmentOnPaste:h=!0,...g},_)=>{let v=sG(),y=L5e(),b=K5e(),x=l??(c===!1?`none`:`enter`),S=p7e(m?m7e:null),C=m&&S&&x===`enter`?`none`:x,w=cG(e=>e.composer.isEditing?e.composer.text:``),T=cG(e=>e.thread.isDisabled||e.composer.dictation?.inputDisabled)||r,E=xW(null),D=EK(_,E),O=xW(!1);P5e(e=>{if(!E.current?.contains(e.target))return;if(y){for(let t of y.getPlugins())if(t.handleKeyDown(e))return}if(!u)return;let t=v.composer();t.getState().canCancel&&(t.cancel(),e.preventDefault())});let k=e=>{if(!T&&!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&&x!==`none`&&v.composer().getState().canSend){e.preventDefault(),v.composer().send({steer:!0});return}if(e.shiftKey||t.isRunning&&!n)return;let r=!1;C===`ctrlEnter`?r=e.ctrlKey||e.metaKey:C===`enter`&&(r=!0),r&&(e.preventDefault(),E.current?.closest(`form`)?.requestSubmit())}}},ee=async e=>{if(!h)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)}},te=e&&!T,ne=CW(()=>{let e=E.current;!e||!te||(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[te]);wW(()=>ne(),[ne]),u7e(()=>{v.composer().getState().type===`thread`&&f&&ne()}),wW(()=>{if(!(v.composer().getState().type!==`thread`||!d))return v.on(`thread.runStart`,ne)},[d,ne,v]),wW(()=>{if(!(v.composer().getState().type!==`thread`||!p))return v.on(`threadListItem.switchedTo`,ne)},[p,ne,v]);let re=b?{"aria-controls":b.popoverId,"aria-expanded":!0,"aria-haspopup":`listbox`,"aria-activedescendant":b.highlightedItemId}:{},ie={name:`input`,value:w,...g,...re,ref:D,disabled:T,onChange:AK(i,e=>{if(!v.composer().getState().isEditing)return;let t=e.nativeEvent.isComposing===!0;O.current&&!t&&(O.current=!1);let n=t||O.current;if(g0e(()=>{v.composer().setText(e.target.value)}),n)return;let r=e.target.selectionStart??e.target.value.length;if(y)for(let e of y.getPlugins())e.setCursorPosition(r)}),onKeyDown:AK(a,k),onCompositionStart:AK(g.onCompositionStart,()=>{O.current=!0}),onCompositionEnd:AK(g.onCompositionEnd,e=>{if(O.current=!1,!v.composer().getState().isEditing)return;let t=e.target;g0e(()=>{v.composer().setText(t.value)});let n=t.selectionStart??t.value.length;if(y)for(let e of y.getPlugins())e.setCursorPosition(n)}),onSelect:AK(s,e=>{if(O.current)return;let t=e.target,n=t.selectionStart??t.value.length;if(y)for(let e of y.getPlugins())e.setCursorPosition(n)}),onPaste:AK(o,ee)};if(n&&(0,_W.isValidElement)(n)){let e=g.children===void 0?n.props.children:g.children;return(0,A.jsx)(b5e,{...ie,children:(0,_W.cloneElement)(n,void 0,e)})}return(0,A.jsx)(t?b5e:fse,{...ie})});HK.displayName=`ComposerPrimitive.Input`;var h7e=jK(`ComposerPrimitive.Cancel`,()=>{let{disabled:e,cancel:t}=W8e();return e?null:t}),g7e=jK(`ComposerPrimitive.AddAttachment`,({multiple:e=!0}={})=>{let{disabled:t,addAttachment:n}=K8e(),r=sG(),i=CW(()=>{let t=document.createElement(`input`);t.type=`file`,t.multiple=e,t.hidden=!0;let i=r.composer().getState().attachmentAccept;i!==`*`&&(t.accept=i),document.body.appendChild(t),t.onchange=e=>{let r=e.target.files;if(r){for(let e of r)n(e);document.body.removeChild(t)}},t.oncancel=()=>{(!t.files||t.files.length===0)&&document.body.removeChild(t)},t.click()},[r,e,n]);return t?null:i},[`multiple`]),_7e=(0,_W.forwardRef)(({disabled:e,asChild:t=!1,render:n,children:r,...i},a)=>{let[o,s]=bW(!1),c=sG(),l=CW(t=>{e||(t.preventDefault(),s(!0))},[e]),u=CW(t=>{e||(t.preventDefault(),o||s(!0))},[e,o]),d=CW(t=>{if(e)return;t.preventDefault();let n=t.relatedTarget;n&&t.currentTarget.contains(n)||s(!1)},[e]),f=CW(async t=>{if(e)return;t.preventDefault(),s(!1);let n=Array.from(t.dataTransfer.files);await Promise.all(n.map(async e=>{try{await c.composer().addAttachment(e)}catch(e){console.error(`Failed to add attachment:`,e)}}))},[e,c]),p={...o?{"data-dragging":`true`}:null,...i,onDragEnterCapture:AK(i.onDragEnterCapture,l),onDragOverCapture:AK(i.onDragOverCapture,u),onDragLeaveCapture:AK(i.onDragLeaveCapture,d),onDropCapture:AK(i.onDropCapture,f),ref:a};if(n&&(0,_W.isValidElement)(n)){let e=r===void 0?n.props.children:r;return(0,A.jsx)(b5e,{...p,children:(0,_W.cloneElement)(n,void 0,e)})}return(0,A.jsx)(t?b5e:`div`,{...p,children:r})});_7e.displayName=`ComposerPrimitive.AttachmentDropzone`;var v7e=jK(`ComposerPrimitive.Dictate`,()=>{let{disabled:e,startDictation:t}=G8e();return e?null:t}),UK=jK(`ComposerPrimitive.StopDictation`,()=>{let e=sG(),t=cG(e=>e.composer.dictation!=null),n=CW(()=>{e.composer().stopDictation()},[e]);return t?n:null}),y7e=(0,_W.forwardRef)(({children:e,...t},n)=>{let r=cG(e=>e.composer.dictation?.transcript);return r?(0,A.jsx)(kK.span,{...t,ref:n,children:e??r}):null});y7e.displayName=`ComposerPrimitive.DictationTranscript`;var b7e=(0,_W.forwardRef)((e,t)=>cG(e=>e.composer.quote)?(0,A.jsx)(kK.div,{...e,ref:t}):null);b7e.displayName=`ComposerPrimitive.Quote`;var x7e=(0,_W.forwardRef)(({children:e,...t},n)=>{let r=cG(e=>e.composer.quote?.text);return r?(0,A.jsx)(kK.span,{...t,ref:n,children:e??r}):null});x7e.displayName=`ComposerPrimitive.QuoteText`;var S7e=(0,_W.forwardRef)(({onClick:e,...t},n)=>{let r=sG(),i=CW(()=>{r.composer().setQuote(void 0)},[r]);return(0,A.jsx)(kK.button,{type:`button`,...t,ref:n,onClick:AK(e,i)})});S7e.displayName=`ComposerPrimitive.QuoteDismiss`;var WK=(0,_W.forwardRef)(({children:e,"aria-label":t,...n},r)=>{let{categories:i,activeCategoryId:a,isSearchMode:o,open:s}=BK();return!s||a||o?null:(0,A.jsx)(kK.div,{role:`group`,"aria-label":t??`Categories`,...n,ref:r,children:e(i)})});WK.displayName=`ComposerPrimitive.TriggerPopoverCategories`;var GK=(0,_W.forwardRef)(({categoryId:e,onClick:t,onMouseMove:n,...r},i)=>{let{selectCategory:a,highlightIndex:o,categories:s,highlightedIndex:c,activeCategoryId:l,isSearchMode:u,popoverId:d}=BK(),f=CW(()=>{a(e)},[a,e]),p=s.findIndex(t=>t.id===e),m=!l&&!u&&p===c,h=CW(()=>{o(p)},[o,p]);return(0,A.jsx)(kK.button,{type:`button`,role:`option`,id:`${d}-option-${e}`,"aria-selected":m,"data-highlighted":m?``:void 0,...r,ref:i,onClick:AK(t,f),onMouseMove:AK(n,h)})});GK.displayName=`ComposerPrimitive.TriggerPopoverCategoryItem`;var C7e=(0,_W.forwardRef)(({children:e,"aria-label":t,...n},r)=>{let{items:i,activeCategoryId:a,isSearchMode:o,open:s}=BK();return!s||!a&&!o?null:(0,A.jsx)(kK.div,{role:`group`,"aria-label":t??`Items`,...n,ref:r,children:e(i)})});C7e.displayName=`ComposerPrimitive.TriggerPopoverItems`;var w7e=(0,_W.forwardRef)(({item:e,index:t,onClick:n,onMouseMove:r,...i},a)=>{let{selectItem:o,highlightIndex:s,items:c,highlightedIndex:l,activeCategoryId:u,isSearchMode:d,popoverId:f}=BK(),p=CW(()=>{o(e)},[o,e]),m=t??c.findIndex(t=>t.id===e.id),h=(d||u!==null)&&m===l,g=CW(()=>{s(m)},[s,m]);return(0,A.jsx)(kK.button,{type:`button`,role:`option`,id:`${f}-option-${e.id}`,"aria-selected":h,"data-highlighted":h?``:void 0,...i,ref:a,onClick:AK(n,p),onMouseMove:AK(r,g)})});w7e.displayName=`ComposerPrimitive.TriggerPopoverItem`;var T7e=(0,_W.forwardRef)(({onClick:e,...t},n)=>{let{activeCategoryId:r,isSearchMode:i,goBack:a,open:o}=BK();return!o||!r||i?null:(0,A.jsx)(kK.button,{type:`button`,...t,ref:n,onClick:AK(e,a)})});T7e.displayName=`ComposerPrimitive.TriggerPopoverBack`;var E7e=({formatter:e,onExecute:t,removeOnExecute:n})=>{let{register:r}=o7e(),i=xW(t);return i.current=t,wW(()=>r({kind:`action`,formatter:e??i5e,onExecute:e=>i.current(e),...n===void 0?{}:{removeOnExecute:n}}),[r,e,n]),null};E7e.displayName=`ComposerPrimitive.TriggerPopoverAction`;var D7e=({formatter:e,onInserted:t})=>{let{register:n}=o7e(),r=xW(t);return r.current=t,wW(()=>n({kind:`directive`,formatter:e??i5e,onInserted:e=>r.current?.(e)}),[n,e]),null};D7e.displayName=`ComposerPrimitive.TriggerPopoverDirective`;var O7e=Object.assign(s7e,{Directive:D7e,Action:E7e}),KK=v5e({AddAttachment:()=>g7e,AttachmentByIndex:()=>yK,AttachmentDropzone:()=>_7e,Attachments:()=>P8e,Cancel:()=>h7e,Dictate:()=>v7e,DictationTranscript:()=>y7e,If:()=>U8e,Input:()=>HK,Queue:()=>F8e,Quote:()=>b7e,QuoteDismiss:()=>S7e,QuoteText:()=>x7e,Root:()=>l7e,Send:()=>c7e,StopDictation:()=>UK,Unstable_TriggerPopover:()=>O7e,Unstable_TriggerPopoverBack:()=>T7e,Unstable_TriggerPopoverCategories:()=>WK,Unstable_TriggerPopoverCategoryItem:()=>GK,Unstable_TriggerPopoverItem:()=>w7e,Unstable_TriggerPopoverItems:()=>C7e,Unstable_TriggerPopoverRoot:()=>Y5e,unstable_useTriggerPopoverRootContext:()=>FK,unstable_useTriggerPopoverRootContextOptional:()=>B5e,unstable_useTriggerPopoverScopeContext:()=>BK,unstable_useTriggerPopoverScopeContextOptional:()=>i7e,unstable_useTriggerPopoverTriggers:()=>H5e,unstable_useTriggerPopoverTriggersOptional:()=>W5e}),k7e=()=>cG(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}),qK=()=>cG(e=>{if(e.part.type!==`image`)throw Error(`MessagePartImage can only be used inside image message parts.`);return e.part}),A7e=(0,_W.createContext)(null);function j7e(e){let t=DW(A7e);if(!e?.optional&&!t)throw Error(`This component must be used within a SmoothContextProvider.`);return t}var{useSmoothStatus:M7e,useSmoothStatusStore:N7e}=o5e(j7e,`useSmoothStatus`),P7e=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))}},F7e=Object.freeze({type:`running`}),I7e=(e,t=!1)=>{let{text:n}=e,[r,i]=bW(e.status.type===`running`?``:n),a=sG(),o=cG(()=>a.part()),[s,c]=bW(o);(o!==s||!n.startsWith(r))&&(c(o),i(e.status.type===`running`?``:n));let l=N7e({optional:!0}),u=MK(t=>{if(i(t),l){let n=r!==t||e.status.type===`running`?F7e:e.status;u5e(l).setState(n,!0)}});wW(()=>{if(l){let i=t&&(r!==n||e.status.type===`running`)?F7e:e.status;u5e(l).setState(i,!0)}},[l,t,n,r,e.status]);let[d]=bW(new P7e(r,u)),f=xW(o);return wW(()=>{if(!t){d.stop();return}let r=f.current!==o;if(f.current=o,r||!n.startsWith(d.targetText)){e.status.type===`running`?(d.currentText=``,d.targetText=n,d.start()):(d.currentText=n,d.targetText=n,d.stop());return}d.targetText=n,d.start()},[d,t,n,e.status.type,o]),wW(()=>()=>{d.stop()},[d]),SW(()=>t?{type:`text`,text:r,status:n===r?e.status:F7e}:e,[t,r,e,n])},JK=(0,_W.forwardRef)(({smooth:e=!0,component:t=`span`,...n},r)=>{let{text:i,status:a}=I7e(k7e(),e);return(0,A.jsx)(t,{"data-status":a.type,...n,ref:r,children:i})});JK.displayName=`MessagePartPrimitive.Text`;var YK=(0,_W.forwardRef)((e,t)=>{let{image:n}=qK();return(0,A.jsx)(kK.img,{src:n,...e,ref:t})});YK.displayName=`MessagePartPrimitive.Image`;var XK=e=>{let t=xW(void 0);return CW(n=>{t.current&&=(t.current(),void 0),n&&(t.current=e(n))},[e])},L7e=(e,t)=>{let n=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!n)return 1/0;let r=Number(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):1/0},R7e=e=>e.dataset.messageId,z7e=()=>{let e=document.createElement(`div`);return e.dataset.auiTopAnchorReserve=``,e.style.height=`0px`,e.style.flexShrink=`0`,e.style.pointerEvents=`none`,e.setAttribute(`aria-hidden`,`true`),e},B7e=(e,t)=>{let n=`${t}px`;return e.style.height===n?!1:(e.style.height=n,!0)},V7e=e=>{let t=window.devicePixelRatio||1;return Math.round(e*t)/t},H7e=()=>{let e=sG(),t=cG(()=>e.message());return XK(CW(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]))},ZK=()=>{let e=wK(e=>e.topAnchorTurn?.anchorId);return cG(t=>t.message.role===`user`&&t.message.index>0&&t.message.index===t.thread.messages.length-2&&t.thread.messages.at(-1)?.role===`assistant`&&(t.message.id===e||t.thread.isRunning))},QK=()=>{let e=wK(e=>e.topAnchorTurn?.targetId);return cG(t=>t.message.isLast&&t.message.role===`assistant`&&t.message.index>=1&&t.thread.messages.at(t.message.index-1)?.role===`user`&&(t.message.id===e||t.thread.isRunning))},$K=(e,t)=>XK(CW(n=>{if(e)return t.getState().registerAnchorElement(n)},[e,t])),U7e=({active:e,threadViewportStore:t})=>XK(CW(n=>{if(!e)return;let r=t.getState(),i=r.topAnchorMessageClamp;return r.registerAnchorTargetElement(n,{tallerThan:L7e(i.tallerThan,n),visibleHeight:L7e(i.visibleHeight,n)})},[e,t])),W7e=({forwardedRef:e,...t})=>{let n=EK(e,H7e()),r=cG(e=>e.message.id);return(0,A.jsx)(kK.div,{...t,ref:n,"data-message-id":r})},G7e=({forwardedRef:e,threadViewportStore:t,...n})=>{let r=H7e(),i=ZK(),a=QK(),o=EK(e,r,$K(i,t),U7e({active:a,threadViewportStore:t})),s=cG(e=>e.message.id);return(0,A.jsx)(kK.div,{...n,ref:o,"data-message-id":s,"data-aui-top-anchor-user":i?``:void 0,"data-aui-top-anchor-target":a?``:void 0})},K7e=(0,_W.forwardRef)((e,t)=>{let n=TK();return n.getState().turnAnchor===`top`?(0,A.jsx)(G7e,{...e,forwardedRef:t,threadViewportStore:n}):(0,A.jsx)(W7e,{...e,forwardedRef:t})});K7e.displayName=`MessagePrimitive.Root`;var eq={...pK,Text:()=>(0,A.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,A.jsx)(JK,{}),(0,A.jsx)(I8e,{children:(0,A.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Image:()=>(0,A.jsx)(YK,{})},q7e=e=>{if(`children`in e)return(0,A.jsx)(gK,{children:e.children});let{components:t,...n}=e;return(0,A.jsx)(gK,{components:t?{Text:t.Text??eq.Text,Image:t.Image??eq.Image,Reasoning:t.Reasoning??pK.Reasoning,Source:t.Source??pK.Source,File:t.File??pK.File,Unstable_Audio:t.Unstable_Audio??pK.Unstable_Audio,...`ChainOfThought`in t?{ChainOfThought:t.ChainOfThought}:{tools:t.tools,data:t.data,ToolGroup:t.ToolGroup??pK.ToolGroup,ReasoningGroup:t.ReasoningGroup??pK.ReasoningGroup},Empty:t.Empty,Quote:t.Quote,generativeUI:t.generativeUI}:eq,...n})};q7e.displayName=`MessagePrimitive.Parts`;var tq=({children:e})=>J8e()===void 0?null:e;tq.displayName=`MessagePrimitive.Error`;var J7e=e=>{let t=new Map;for(let n=0;n<e.length;n++){let r=e[n]?.parentId??`__ungrouped_${n}`,i=t.get(r)??[];i.push(n),t.set(r,i)}let n=[];for(let[e,r]of t){let t=e.startsWith(`__ungrouped_`)?void 0:e;n.push({groupKey:t,indices:r})}return n},Y7e=e=>{let t=cG(e=>e.message.parts);return SW(()=>t.length===0?[]:e(t),[t,e])},X7e=({Fallback:e,...t})=>{let n=cG(n=>{let r=n.tools.tools[t.toolName]??e;return Array.isArray(r)?r[0]??e:r});return n?(0,A.jsx)(n,{...t}):null},nq=({Fallback:e,...t})=>{let n=cG(n=>{let r=n.dataRenderers.renderers[t.name]??e;return Array.isArray(r)?r[0]??e:r});return n?(0,A.jsx)(n,{...t}):null},rq={Text:()=>(0,A.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,A.jsx)(JK,{}),(0,A.jsx)(I8e,{children:(0,A.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>(0,A.jsx)(YK,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},Z7e=({components:{Text:e=rq.Text,Reasoning:t=rq.Reasoning,Image:n=rq.Image,Source:r=rq.Source,File:i=rq.File,Unstable_Audio:a=rq.Unstable_Audio,tools:o={},data:s}={}})=>{let c=sG(),l=cG(e=>e.part),u=l.type;if(u===`tool-call`){let e=c.part().addToolResult,t=c.part().resumeToolCall,n=c.part().respondToToolApproval;if(`Override`in o)return(0,A.jsx)(o.Override,{...l,addResult:e,resume:t,respondToApproval:n});let r=o.by_name?.[l.toolName]??o.Fallback;return(0,A.jsx)(X7e,{...l,Fallback:r,addResult:e,resume:t,respondToApproval:n})}if(l.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(u){case`text`:return(0,A.jsx)(e,{...l});case`reasoning`:return(0,A.jsx)(t,{...l});case`source`:return(0,A.jsx)(r,{...l});case`image`:return(0,A.jsx)(n,{...l});case`file`:return(0,A.jsx)(i,{...l});case`audio`:return(0,A.jsx)(a,{...l});case`data`:{let e=s?.by_name?.[l.name]??s?.Fallback;return(0,A.jsx)(nq,{...l,Fallback:e})}default:return console.warn(`Unknown message part type: ${u}`),null}},iq=(0,_W.memo)(({partIndex:e,components:t})=>(0,A.jsx)(B4e,{index:e,children:(0,A.jsx)(Z7e,{components:t})}),(e,t)=>e.partIndex===t.partIndex&&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?.Group===t.components?.Group),Q7e=({status:e,component:t})=>(0,A.jsx)(H4e,{text:``,isRunning:e.type===`running`,children:(0,A.jsx)(t,{type:`text`,text:``,status:e})}),$7e=Object.freeze({type:`complete`}),e9e=(0,_W.memo)(({components:e})=>{let t=cG(e=>e.message.status??$7e);return e?.Empty?(0,A.jsx)(e.Empty,{status:t}):(0,A.jsx)(Q7e,{status:t,component:e?.Text??rq.Text})},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),t9e=({groupingFunction:e,components:t})=>{let n=cG(e=>e.message.parts.length),r=Y7e(e);return(0,A.jsx)(A.Fragment,{children:SW(()=>n===0?(0,A.jsx)(e9e,{components:t}):r.map((e,n)=>(0,A.jsx)(t?.Group??rq.Group,{groupKey:e.groupKey,indices:e.indices,children:e.indices.map(e=>(0,A.jsx)(iq,{partIndex:e,components:t},e))},`group-${n}-${e.groupKey??`ungrouped`}`)),[r,t,n])})};t9e.displayName=`MessagePrimitive.Unstable_PartsGrouped`;var n9e=({components:e,...t})=>(0,A.jsx)(t9e,{...t,components:e,groupingFunction:J7e});n9e.displayName=`MessagePrimitive.Unstable_PartsGroupedByParentId`;var r9e=v5e({AttachmentByIndex:()=>_K,Attachments:()=>j8e,Content:()=>q7e,Error:()=>tq,GenerativeUI:()=>J6e,GroupedParts:()=>E8e,If:()=>NK,PartByIndex:()=>o8e,Parts:()=>q7e,Quote:()=>D8e,Root:()=>K7e,Unstable_PartsGrouped:()=>t9e,Unstable_PartsGroupedByParentId:()=>n9e}),i9e=e=>{let t=MK(e);return XK(CW(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]))},a9e=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{let i=xW(null),a=cG(e=>e.thread.messages.length>0),o=xW(!1),s=xW(null),c=TK();e===void 0&&(e=c.getState().turnAnchor!==`top`);let l=xW(0),u=xW(0),d=xW(0),f=xW(0),p=xW(null),m=CW(e=>{let t=i.current;t&&(p.current=e,t.scrollTo({top:t.scrollHeight,behavior:e}))},[]),h=CW(e=>{p.current=e,s.current!==null&&cancelAnimationFrame(s.current),s.current=requestAnimationFrame(()=>{s.current=null,m(e)})},[m]);TW(()=>()=>{s.current!==null&&cancelAnimationFrame(s.current)},[]);let g=CW(()=>{let e=c.getState();return e.turnAnchor===`top`&&e.element.viewport===i.current&&e.element.anchor!==null},[c]),_=()=>{let e=i.current;if(!e)return;let t=c.getState().isAtBottom,n=Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<=1||e.scrollHeight<=e.clientHeight;!n&&l.current<e.scrollTop||(n?e.scrollHeight>e.clientHeight+1&&(p.current=null):l.current>e.scrollTop&&u.current===e.scrollHeight&&(p.current=null),(n||p.current===null)&&n!==t&&u5e(c).setState({isAtBottom:n})),l.current=e.scrollTop,u.current=e.scrollHeight},v=i9e(()=>{let t=i.current;if(!t)return;let{scrollHeight:n,clientHeight:r}=t;if(n===d.current&&r===f.current)return;d.current=n,f.current=r;let a=p.current;a&&g()?p.current=null:a?m(a):e&&c.getState().isAtBottom&&m(`instant`),_()}),y=XK(e=>(e.addEventListener(`scroll`,_),()=>{e.removeEventListener(`scroll`,_)}));return TW(()=>{if(n){if(!a){o.current=!1;return}o.current||(o.current=!0,p.current===null&&h(`instant`))}},[a,h,n]),u7e(({behavior:e})=>{m(e)}),O2e(`thread.runStart`,()=>{t&&c.getState().turnAnchor!==`top`&&h(`auto`)}),O2e(`threadListItem.switchedTo`,()=>{r&&h(`instant`)}),EK(v,y,i)},o9e=(0,_W.forwardRef)((e,t)=>(0,A.jsx)(kK.div,{...e,ref:t}));o9e.displayName=`ThreadPrimitive.Root`;var s9e=({children:e})=>cG(e=>e.thread.isEmpty)?e:null;s9e.displayName=`ThreadPrimitive.Empty`;var c9e=e=>cG(t=>!(e.empty===!0&&!t.thread.isEmpty||e.empty===!1&&t.thread.isEmpty||e.running===!0&&!t.thread.isRunning||e.running===!1&&t.thread.isRunning||e.disabled===!0&&!t.thread.isDisabled||e.disabled===!1&&t.thread.isDisabled)),l9e=({children:e,...t})=>c9e(t)?e:null;l9e.displayName=`ThreadPrimitive.If`;var u9e=(e,t)=>XK(CW(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])),d9e=e=>{let t=0,n=e;for(;n;)t+=n.offsetTop,n=n.offsetParent;return t},f9e=(e,t)=>{let n=0,r=e;for(;r&&r!==t;)n+=r.offsetTop,r=r.offsetParent;return r===t?n:d9e(e)-d9e(t)},p9e=({viewport:e,anchor:t,tallerThan:n,visibleHeight:r})=>{let i=f9e(t,e),a=t.offsetHeight;return i+Math.max(0,a-(a<=n?a:r))},aq=({scrollHeight:e,...t})=>{let{viewport:n}=t,r=p9e(t)+n.clientHeight;return Math.max(0,r-e)},m9e=({viewport:e,reserve:t,...n})=>aq({viewport:e,...n,scrollHeight:e.scrollHeight-t.offsetHeight}),h9e=e=>{let t=new ResizeObserver(e),n=new MutationObserver(e),r=null,i=null,a=null,o=()=>{t.disconnect(),n.disconnect(),r=null,i=null,a=null};return{target:(e,s,c)=>{r===e&&i===s&&a===c||(o(),t.observe(e),t.observe(s),t.observe(c),n.observe(c,{childList:!0,subtree:!0,characterData:!0}),r=e,i=s,a=c)},disconnect:o}},g9e=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},_9e=e=>{let t=null,n;function r(){let r=e.getState(),{viewport:o,anchor:s,target:c}=r.element,l=r.targetConfig;if(r.turnAnchor!==`top`||!o||!s||!c||!l){a.disconnect(),t&&(B7e(t,0),t.remove());return}if(t??=z7e(),(t.parentElement!==c.parentElement||t.previousElementSibling!==c)&&c.after(t),a.target(o,s,c),B7e(t,m9e({viewport:o,anchor:s,reserve:t,...l}))){i.schedule();return}let u=R7e(s);if(u!==void 0&&n===u)return;let d=V7e(p9e({viewport:o,anchor:s,...l}));Math.abs(o.scrollTop-d)>1&&o.scrollTo({top:d,behavior:`smooth`}),u!==void 0&&(n=u)}let i=g9e(r),a=h9e(i.schedule);i.schedule();let o=e.subscribe(i.schedule);return()=>{i.cancel(),o(),a.disconnect(),t?.remove()}},v9e=e=>{let t=TK();TW(()=>{if(e)return _9e(t)},[e,t])},oq=({isRunning:e,messages:t})=>{if(!e)return null;let n=t.at(-1),r=t.at(-2);return r?.role!==`user`||n?.role!==`assistant`?null:{anchorId:r.id,targetId:n.id}},y9e=e=>oq(e)?.anchorId,b9e=e=>oq(e)?.targetId,x9e=()=>u9e(wK(e=>e.registerViewport),CW(e=>e.clientHeight,[])),S9e=()=>XK(wK(e=>e.registerViewportElement)),sq=e=>{let t=TK(),n=cG(t=>{if(e)return y9e(t.thread)}),r=cG(t=>{if(e)return b9e(t.thread)}),i=SW(()=>!n||!r?null:{anchorId:n,targetId:r},[n,r]);TW(()=>{if(!i)return;let e=t.getState(),n=e.topAnchorTurn;n?.anchorId===i.anchorId&&n.targetId===i.targetId||e.setTopAnchorTurn(i)},[i,t]);let a=CW(()=>{t.getState().setTopAnchorTurn(null)},[t]);O2e(`thread.initialize`,a),O2e(`threadListItem.switchedTo`,a)},cq=(0,_W.forwardRef)(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:i,...a},o)=>{let s=a9e({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),c=x9e(),l=S9e(),u=TK().getState().turnAnchor===`top`;sq(u),v9e(u);let d=EK(o,s,c,l);return(0,A.jsx)(kK.div,{...a,ref:d,children:i})});cq.displayName=`ThreadPrimitive.ViewportScrollable`;var lq=(0,_W.forwardRef)(({turnAnchor:e,topAnchorMessageClamp:t,...n},r)=>(0,A.jsx)(f5e,{options:{turnAnchor:e,topAnchorMessageClamp:t},children:(0,A.jsx)(cq,{...n,ref:r})}));lq.displayName=`ThreadPrimitive.Viewport`;var C9e=(0,_W.forwardRef)((e,t)=>{let n=EK(t,u9e(wK(e=>e.registerContentInset),CW(e=>{let t=parseFloat(getComputedStyle(e).marginTop)||0;return e.offsetHeight+t},[])));return(0,A.jsx)(kK.div,{...e,ref:n})});C9e.displayName=`ThreadPrimitive.ViewportFooter`;var uq=jK(`ThreadPrimitive.ScrollToBottom`,({behavior:e}={})=>{let t=wK(e=>e.isAtBottom),n=TK(),r=CW(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:r},[`behavior`]),w9e=jK(`ThreadPrimitive.Suggestion`,({prompt:e,send:t,clearComposer:n,autoSend:r,method:i})=>{let{disabled:a,trigger:o}=q8e({prompt:e,send:t??r??!1,clearComposer:n});return a?null:o},[`prompt`,`send`,`clearComposer`,`autoSend`,`method`]),dq=v5e({Empty:()=>s9e,If:()=>l9e,MessageByIndex:()=>aK,Messages:()=>U6e,Root:()=>o9e,ScrollToBottom:()=>uq,Suggestion:()=>w9e,SuggestionByIndex:()=>R8e,Suggestions:()=>V8e,Viewport:()=>lq,ViewportFooter:()=>C9e,ViewportProvider:()=>f5e});const T9e=(0,O.createContext)({pendingApprovals:[],handleApproval:()=>{}}),E9e=()=>(0,O.useContext)(T9e);async function*D9e(e){let t=new TextDecoder,n=``;for(;;){let{done:r,value:i}=await e.read();if(r)break;n+=t.decode(i,{stream:!0});let a=n.split(`
|
|
190
190
|
`);n=a.pop();for(let e of a)if(e.startsWith(`data: `)){let t=e.slice(6);if(t)try{yield JSON.parse(t)}catch{}}}}async function O9e(e,t,n,r,i,a){let o=[];for await(let s of D9e(e)){switch(s.type){case`text-delta`:t.value+=s.text;break;case`tool-call`:{let e=s.args;if(typeof s.args==`string`)try{e=JSON.parse(s.args)}catch{e={}}n.push({type:`tool-call`,toolCallId:s.toolCallId,toolName:s.toolName,args:e});break}case`tool-result`:{let e=typeof s.result==`object`?s.result:null;if(e&&`__approvalRequired`in e)break;let t=n.find(e=>e.toolCallId===s.toolCallId);t&&(t.result=typeof s.result==`string`?s.result:JSON.stringify(s.result),s.isError&&(t.isError=!0));break}case`generative-ui`:{let e={type:`generative-ui`,spec:s.spec},t=r.findIndex(e=>e.type===`generative-ui`);t===-1?r.push(e):r[t]=e;break}case`data`:{let e={type:`data`,name:s.name,data:s.data},t=r.findIndex(e=>e.type===`data`&&e.name===s.name);t===-1?r.push(e):r[t]=e;break}case`approval-request`:o.push({toolCallId:s.toolCallId,toolName:s.toolName,args:s.args,reason:s.reason,runId:s.runId,type:`approval-request`});break;case`credential-request`:o.push({toolCallId:s.toolCallId,toolName:s.toolName,args:s.args,runId:s.runId,type:`credential-request`,credentialName:s.credentialName,credentialType:s.credentialType,connectUrl:s.connectUrl});break;case`error`:t.value+=`\n\nError: ${s.message||s.errorText||`Unknown error`}`;break;case`done`:a?.();continue}i()}return o}function k9e(e){if(e==null)return!1;try{let t=typeof e==`string`?JSON.parse(e):e;return t&&typeof t==`object`&&t.approved===!1}catch{return!1}}function A9e(e){if(typeof e==`object`&&e&&e.error===`missing_credential`)return e;if(typeof e==`string`)try{let t=JSON.parse(e);if(t?.error===`missing_credential`)return t}catch{}return null}function fq(e,t){if(e.type===`running`)return{type:`running`};if(e.type===`requires-action`)return{type:`requires-action`};if(k9e(t))return{type:`denied`};let n=A9e(t);return n?{type:`missing-credential`,payload:n}:typeof t==`string`&&t.startsWith(`Error:`)?{type:`error`}:{type:`completed`}}function pq(e,t,n){let r=[];return e.value&&r.push({type:`text`,text:e.value}),r.push(...t),r.push(...n),r}function j9e(e){let t=[];if(typeof e==`string`)return e&&t.push({type:`text`,text:e}),t;if(!e||typeof e!=`object`)return t;let n=e;return typeof n.text==`string`&&n.text&&t.push({type:`text`,text:n.text}),n.ui!=null&&t.push({type:`generative-ui`,spec:n.ui}),t}function M9e(e,t,n,r,i){return{async*run({messages:a,abortSignal:o}){let s=e.current,c=t.current;if(c.length>0){let e=n.current;if(n.current=[],e.length===0)return;t.current=[],r.current([]);let a={value:``},l=[],u=[],d=[];for(let t=0;t<e.length;t++){let n=e[t],r=c.find(e=>e.toolCallId===n.toolCallId)?.runId??c[0]?.runId,f=await fetch(`${s.api}/${s.agentName}/resume`,{method:`POST`,headers:{"Content-Type":`application/json`,...s.headers},body:JSON.stringify({runId:r,toolCallId:n.toolCallId,approved:n.approved}),signal:o,credentials:s.credentials});if(!f.ok||!f.body){let e=f.body?await f.text().catch(()=>``):``;throw Error(`Resume failed: ${f.status}${e?` - ${e}`:``}`)}let p={value:``},m=[],h=[],g=await O9e(f.body.getReader(),p,m,h,()=>{},t===e.length-1?i.current??void 0:void 0);a=p,l=m,u=h,g.length>0&&(d=g)}let f=pq(a,u,l);if(d.length>0){t.current=d,r.current(d);for(let e of d){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,args:{...typeof e.args==`object`&&e.args!==null?e.args:{},...e.reason?{__approvalReason:e.reason}:{}}},n=l.findIndex(t=>t.toolCallId===e.toolCallId&&!t.result);n===-1?l.push(t):l[n]=t}yield{content:pq(a,u,l),status:{type:`requires-action`,reason:`tool-calls`}}}else f.length>0&&(yield{content:f});return}let l=[...a].reverse().find(e=>e.role===`user`);if(!l)return;let u=``;if(l.content)for(let e of l.content)`text`in e&&e.type===`text`&&(u+=e.text);let d;try{d=await fetch(`${s.api}/${s.agentName}/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...s.headers},body:JSON.stringify({agentName:s.agentName,message:u,threadId:s.threadId,resourceId:s.resourceId,model:s.model,temperature:s.temperature,...s.context?{context:s.context}:{}}),signal:o,credentials:s.credentials})}catch(e){let t=e?.message||`Unknown error`,n=`Failed to connect to the agent.`;if(t.includes(`Failed to fetch`)||t.includes(`NetworkError`)||t.includes(`CORS`))n=`Unable to reach the agent server. The deployment may be down or the URL may be incorrect.`;else if(t.includes(`abort`))return;yield{content:[{type:`text`,text:`⚠️ ${n}`}]};return}if(!d.ok||!d.body){let e=`Request failed (${d.status}).`;d.status===401||d.status===403?e=`Authentication error.`:d.status===404?e=`Agent not found — the agent may not be configured for this project.`:d.status===502||d.status===503?e=`The agent server is currently unavailable. Try again in a moment.`:d.status===429&&(e=`Rate limited — too many requests. Please wait a moment.`),yield{content:[{type:`text`,text:`⚠️ ${e}`}]};return}let f={value:``},p=[],m=[],h=null,g=await O9e(d.body.getReader(),f,p,m,()=>{let e=pq(f,m,p);e.length>0&&(h=e)},i.current??void 0);if(g.length===0){h&&(yield{content:h});return}t.current=g,r.current(g);for(let e of g){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,args:{...typeof e.args==`object`&&e.args!==null?e.args:{},...e.reason?{__approvalReason:e.reason}:{}}},n=p.findIndex(t=>t.toolCallId===e.toolCallId&&!t.result);n===-1?p.push(t):p[n]=t}let _=new Set(g.map(e=>e.toolCallId)),v=new Set(g.map(e=>e.toolName));for(let e=p.length-1;e>=0;e--)v.has(p[e].toolName)&&!_.has(p[e].toolCallId)&&p.splice(e,1);yield{content:pq(f,m,p),status:{type:`requires-action`,reason:`tool-calls`}}}}}const N9e=e=>{let t=[],n=null;for(let r of e){if(r.role===`user`){n&&=(t.push(n),null),t.push({role:`user`,content:r.content||``,id:r.id,createdAt:new Date(r.createdAt)});continue}if(r.role===`tool`&&n&&Array.isArray(r.toolResults)){let e=Array.isArray(n.content)?[...n.content]:n.content?[{type:`text`,text:n.content}]:[];for(let t of r.toolResults){let n=e.findIndex(e=>e.type===`tool-call`&&e.toolCallId===t.id);n!==-1&&(e[n]={...e[n],result:typeof t.result==`string`?t.result:JSON.stringify(t.result)})}n={role:n.role,id:n.id,createdAt:n.createdAt,status:n.status,content:e};continue}if(r.role===`tool`)continue;let e=[];if(r.content&&(Array.isArray(r.content)?e.push(...r.content):e.push({type:`text`,text:r.content})),Array.isArray(r.toolCalls))for(let t of r.toolCalls)e.push({type:`tool-call`,toolCallId:t.id,toolName:t.name,args:t.args||{}});if(n){let t=n.content,r=Array.isArray(t)?[...t]:t?[{type:`text`,text:t}]:[];n={role:n.role,id:n.id,createdAt:n.createdAt,status:n.status,content:[...r,...e]}}else n={role:`assistant`,content:e.length>0?e:``,id:r.id,createdAt:new Date(r.createdAt),status:{type:`complete`,reason:`stop`}}}return n&&t.push(n),t};function P9e(e){let[t,n]=(0,O.useState)([]),r=(0,O.useRef)(e);r.current=e;let i=(0,O.useRef)(e.onFinish);i.current=e.onFinish;let a=(0,O.useRef)([]),o=(0,O.useRef)([]),s=(0,O.useRef)(n);s.current=n;let c=n5e((0,O.useMemo)(()=>M9e(r,a,o,s,i),[]),{initialMessages:(0,O.useMemo)(()=>e.initialMessages?N9e(e.initialMessages):void 0,[e.initialMessages])}),l=(0,O.useCallback)((e,t)=>{o.current.push({toolCallId:e,approved:t})},[]);return{runtime:c,pendingApprovals:t,isAwaitingApproval:t.length>0,handleApproval:l}}function F9e(e,t,n,r,i){return{async*run({messages:a,abortSignal:o}){let s=e.current,c=t.current;if(c.length>0){let e=n.current;if(n.current=[],e.length===0)return;t.current=[],r.current([]);let a={value:``},l=[],u=[],d=[];for(let t=0;t<e.length;t++){let n=e[t],r=c.find(e=>e.toolCallId===n.toolCallId)?.runId??c[0]?.runId,f=await fetch(`${s.api}/${s.agentName}/resume`,{method:`POST`,headers:{"Content-Type":`application/json`,...s.headers},body:JSON.stringify({runId:r,toolCallId:n.toolCallId,approved:n.approved}),signal:o,credentials:s.credentials});if(!f.ok||!f.body){let e=f.body?await f.text().catch(()=>``):``;throw Error(`Resume failed: ${f.status}${e?` - ${e}`:``}`)}let p={value:``},m=[],h=[],g=await O9e(f.body.getReader(),p,m,h,()=>{},t===e.length-1?i.current??void 0:void 0);a=p,l=m,u=h,g.length>0&&(d=g)}let f=pq(a,u,l);if(d.length>0){t.current=d,r.current(d);for(let e of d){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,args:{...typeof e.args==`object`&&e.args!==null?e.args:{},...e.reason?{__approvalReason:e.reason}:{}}},n=l.findIndex(t=>t.toolCallId===e.toolCallId&&!t.result);n===-1?l.push(t):l[n]=t}yield{content:pq(a,u,l),status:{type:`requires-action`,reason:`tool-calls`}}}else f.length>0&&(yield{content:f});return}let l=[...a].reverse().find(e=>e.role===`user`);if(!l)return;let u=``;if(l.content)for(let e of l.content)`text`in e&&e.type===`text`&&(u+=e.text);let d=await fetch(`${s.api}/${s.agentName}`,{method:`POST`,headers:{"Content-Type":`application/json`,...s.headers},body:JSON.stringify({agentName:s.agentName,message:u,threadId:s.threadId,resourceId:s.resourceId,model:s.model,temperature:s.temperature,...s.context?{context:s.context}:{}}),signal:o,credentials:s.credentials});if(!d.ok)throw Error(`Agent run failed: ${d.status}`);let f=await d.json();if(f.status===`suspended`&&f.pendingApprovals?.length>0){let e=f.pendingApprovals;t.current=e,r.current(e);let n=e.map(e=>({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,args:{...typeof e.args==`object`&&e.args!==null?e.args:{},...e.reason?{__approvalReason:e.reason}:{}}})),i=[];i.push(...j9e(f.result)),i.push(...n),yield{content:i,status:{type:`requires-action`,reason:`tool-calls`}};return}i.current?.();let p=j9e(f.result);p.length>0&&(yield{content:p})}}}function I9e(e){let[t,n]=(0,O.useState)([]),r=(0,O.useRef)(e);r.current=e;let i=(0,O.useRef)(e.onFinish);i.current=e.onFinish;let a=(0,O.useRef)([]),o=(0,O.useRef)([]),s=(0,O.useRef)(n);s.current=n;let c=n5e((0,O.useMemo)(()=>F9e(r,a,o,s,i),[]),{initialMessages:(0,O.useMemo)(()=>e.initialMessages?N9e(e.initialMessages):void 0,[e.initialMessages])}),l=(0,O.useCallback)((e,t)=>{o.current.push({toolCallId:e,approved:t})},[]);return{runtime:c,pendingApprovals:t,isAwaitingApproval:t.length>0,handleApproval:l}}function mq(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var L9e=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,R9e=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,z9e={};function B9e(e,t){return((t||z9e).jsx?R9e:L9e).test(e)}var V9e=/[ \t\n\f\r]/g;function H9e(e){return typeof e==`object`?e.type===`text`?U9e(e.value):!1:U9e(e)}function U9e(e){return e.replace(V9e,``)===``}var hq=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};hq.prototype.normal={},hq.prototype.property={},hq.prototype.space=void 0;function W9e(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new hq(n,r,t)}function G9e(e){return e.toLowerCase()}var gq=class{constructor(e,t){this.attribute=t,this.property=e}};gq.prototype.attribute=``,gq.prototype.booleanish=!1,gq.prototype.boolean=!1,gq.prototype.commaOrSpaceSeparated=!1,gq.prototype.commaSeparated=!1,gq.prototype.defined=!1,gq.prototype.mustUseProperty=!1,gq.prototype.number=!1,gq.prototype.overloadedBoolean=!1,gq.prototype.property=``,gq.prototype.spaceSeparated=!1,gq.prototype.space=void 0;var _q=c({boolean:()=>vq,booleanish:()=>yq,commaOrSpaceSeparated:()=>Cq,commaSeparated:()=>Sq,number:()=>bq,overloadedBoolean:()=>q9e,spaceSeparated:()=>xq},1),K9e=0;const vq=wq(),yq=wq(),q9e=wq(),bq=wq(),xq=wq(),Sq=wq(),Cq=wq();function wq(){return 2**++K9e}var J9e=Object.keys(_q),Y9e=class extends gq{constructor(e,t,n,r){let i=-1;if(super(e,t),X9e(this,`space`,r),typeof n==`number`)for(;++i<J9e.length;){let e=J9e[i];X9e(this,J9e[i],(n&_q[e])===_q[e])}}};Y9e.prototype.defined=!0;function X9e(e,t,n){n&&(e[t]=n)}function Tq(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new Y9e(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[G9e(r)]=r,n[G9e(a.attribute)]=r}return new hq(t,n,e.space)}const Eq=Tq({properties:{ariaActiveDescendant:null,ariaAtomic:yq,ariaAutoComplete:null,ariaBusy:yq,ariaChecked:yq,ariaColCount:bq,ariaColIndex:bq,ariaColSpan:bq,ariaControls:xq,ariaCurrent:null,ariaDescribedBy:xq,ariaDetails:null,ariaDisabled:yq,ariaDropEffect:xq,ariaErrorMessage:null,ariaExpanded:yq,ariaFlowTo:xq,ariaGrabbed:yq,ariaHasPopup:null,ariaHidden:yq,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:xq,ariaLevel:bq,ariaLive:null,ariaModal:yq,ariaMultiLine:yq,ariaMultiSelectable:yq,ariaOrientation:null,ariaOwns:xq,ariaPlaceholder:null,ariaPosInSet:bq,ariaPressed:yq,ariaReadOnly:yq,ariaRelevant:null,ariaRequired:yq,ariaRoleDescription:xq,ariaRowCount:bq,ariaRowIndex:bq,ariaRowSpan:bq,ariaSelected:yq,ariaSetSize:bq,ariaSort:null,ariaValueMax:bq,ariaValueMin:bq,ariaValueNow:bq,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function Z9e(e,t){return t in e?e[t]:t}function Q9e(e,t){return Z9e(e,t.toLowerCase())}const $9e=Tq({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:Sq,acceptCharset:xq,accessKey:xq,action:null,allow:null,allowFullScreen:vq,allowPaymentRequest:vq,allowUserMedia:vq,alt:null,as:null,async:vq,autoCapitalize:null,autoComplete:xq,autoFocus:vq,autoPlay:vq,blocking:xq,capture:null,charSet:null,checked:vq,cite:null,className:xq,cols:bq,colSpan:null,content:null,contentEditable:yq,controls:vq,controlsList:xq,coords:bq|Sq,crossOrigin:null,data:null,dateTime:null,decoding:null,default:vq,defer:vq,dir:null,dirName:null,disabled:vq,download:q9e,draggable:yq,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:vq,formTarget:null,headers:xq,height:bq,hidden:q9e,high:bq,href:null,hrefLang:null,htmlFor:xq,httpEquiv:xq,id:null,imageSizes:null,imageSrcSet:null,inert:vq,inputMode:null,integrity:null,is:null,isMap:vq,itemId:null,itemProp:xq,itemRef:xq,itemScope:vq,itemType:xq,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:vq,low:bq,manifest:null,max:null,maxLength:bq,media:null,method:null,min:null,minLength:bq,multiple:vq,muted:vq,name:null,nonce:null,noModule:vq,noValidate:vq,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:vq,optimum:bq,pattern:null,ping:xq,placeholder:null,playsInline:vq,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:vq,referrerPolicy:null,rel:xq,required:vq,reversed:vq,rows:bq,rowSpan:bq,sandbox:xq,scope:null,scoped:vq,seamless:vq,selected:vq,shadowRootClonable:vq,shadowRootDelegatesFocus:vq,shadowRootMode:null,shape:null,size:bq,sizes:null,slot:null,span:bq,spellCheck:yq,src:null,srcDoc:null,srcLang:null,srcSet:null,start:bq,step:null,style:null,tabIndex:bq,target:null,title:null,translate:null,type:null,typeMustMatch:vq,useMap:null,value:yq,width:bq,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:xq,axis:null,background:null,bgColor:null,border:bq,borderColor:null,bottomMargin:bq,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:vq,declare:vq,event:null,face:null,frame:null,frameBorder:null,hSpace:bq,leftMargin:bq,link:null,longDesc:null,lowSrc:null,marginHeight:bq,marginWidth:bq,noResize:vq,noHref:vq,noShade:vq,noWrap:vq,object:null,profile:null,prompt:null,rev:null,rightMargin:bq,rules:null,scheme:null,scrolling:yq,standby:null,summary:null,text:null,topMargin:bq,valueType:null,version:null,vAlign:null,vLink:null,vSpace:bq,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:vq,disableRemotePlayback:vq,prefix:null,property:null,results:bq,security:null,unselectable:null},space:`html`,transform:Q9e}),eet=Tq({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:Cq,accentHeight:bq,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:bq,amplitude:bq,arabicForm:null,ascent:bq,attributeName:null,attributeType:null,azimuth:bq,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:bq,by:null,calcMode:null,capHeight:bq,className:xq,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:bq,diffuseConstant:bq,direction:null,display:null,dur:null,divisor:bq,dominantBaseline:null,download:vq,dx:null,dy:null,edgeMode:null,editable:null,elevation:bq,enableBackground:null,end:null,event:null,exponent:bq,externalResourcesRequired:null,fill:null,fillOpacity:bq,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Sq,g2:Sq,glyphName:Sq,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:bq,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:bq,horizOriginX:bq,horizOriginY:bq,id:null,ideographic:bq,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:bq,k:bq,k1:bq,k2:bq,k3:bq,k4:bq,kernelMatrix:Cq,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:bq,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:bq,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:bq,overlineThickness:bq,paintOrder:null,panose1:null,path:null,pathLength:bq,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:xq,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:bq,pointsAtY:bq,pointsAtZ:bq,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Cq,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Cq,rev:Cq,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Cq,requiredFeatures:Cq,requiredFonts:Cq,requiredFormats:Cq,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:bq,specularExponent:bq,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:bq,strikethroughThickness:bq,string:null,stroke:null,strokeDashArray:Cq,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:bq,strokeOpacity:bq,strokeWidth:null,style:null,surfaceScale:bq,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Cq,tabIndex:bq,tableValues:null,target:null,targetX:bq,targetY:bq,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Cq,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:bq,underlineThickness:bq,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:bq,values:null,vAlphabetic:bq,vMathematical:bq,vectorEffect:null,vHanging:bq,vIdeographic:bq,version:null,vertAdvY:bq,vertOriginX:bq,vertOriginY:bq,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:bq,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:Z9e}),tet=Tq({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),net=Tq({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:Q9e}),ret=Tq({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),Dq={classId:`classID`,dataType:`datatype`,itemId:`itemID`,strokeDashArray:`strokeDasharray`,strokeDashOffset:`strokeDashoffset`,strokeLineCap:`strokeLinecap`,strokeLineJoin:`strokeLinejoin`,strokeMiterLimit:`strokeMiterlimit`,typeOf:`typeof`,xLinkActuate:`xlinkActuate`,xLinkArcRole:`xlinkArcrole`,xLinkHref:`xlinkHref`,xLinkRole:`xlinkRole`,xLinkShow:`xlinkShow`,xLinkTitle:`xlinkTitle`,xLinkType:`xlinkType`,xmlnsXLink:`xmlnsXlink`};var iet=/[A-Z]/g,aet=/-[a-z]/g,oet=/^data[-\w.:]+$/i;function set(e,t){let n=G9e(t),r=t,i=gq;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&oet.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(aet,Oq);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!aet.test(e)){let n=e.replace(iet,cet);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=Y9e}return new i(r,t)}function cet(e){return`-`+e.toLowerCase()}function Oq(e){return e.charAt(1).toUpperCase()}const uet=W9e([Eq,$9e,tet,net,ret],`html`),det=W9e([Eq,eet,tet,net,ret],`svg`);function fet(e){return e.join(` `).trim()}var pet=s(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=`
|