@artooi/ag-ui-web-component 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@ Patch operations: ${JSON.stringify(h,null,2)}
8
8
  Error: ${x}`)}}return u()}case b.MESSAGES_SNAPSHOT:{let p=await ne(r,s,a,(h,g,x)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let{messages:h}=m,g=h.map(v=>{if(v.subagentRunId!==null)return v;let A={...v};return delete A.subagentRunId,A}),x=new Map(g.map(v=>[v.id,v])),T=g.some(v=>v.role==="activity"),S=g.some(v=>v.role==="reasoning"),L=v=>v.role==="activity"&&!T||v.role==="reasoning"&&!S;s=s.filter(v=>L(v)||x.has(v.id)).map(v=>L(v)?v:x.get(v.id));let z=new Set(s.map(v=>v.id));for(let v of g)z.has(v.id)||s.push(v);c({messages:s})}return u()}case b.ACTIVITY_SNAPSHOT:{let p=m,h=s.findIndex(L=>L.id===p.messageId),g=h>=0?s[h]:void 0,x=g?.role==="activity"?g:void 0,T=p.replace??!0,S=await ne(r,s,a,(L,z,v)=>L.onActivitySnapshotEvent?.({event:p,messages:z,state:v,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(S),S.stopPropagation!==!0){let L={id:p.messageId,role:"activity",activityType:p.activityType,content:J(p.content),...p.subagentRunId!=null&&{subagentRunId:p.subagentRunId}},z,v;h===-1?(s.push(L),z=L,v=L):x?(T&&(s[h]={...x,activityType:p.activityType,content:J(p.content),subagentRunId:p.subagentRunId},p.subagentRunId??delete s[h].subagentRunId),v=s[h]):T&&(s[h]=L,z=L,v=L),Fe(v,p),c({messages:s}),z&&await Promise.all(r.map(A=>A.onNewMessage?.({message:z,messages:s,state:a,agent:n,input:t})))}return u()}case b.ACTIVITY_DELTA:{let p=m,h=s.findIndex(S=>S.id===p.messageId);if(h===-1)return u();let g=s[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${p.messageId}' is not an activity message`),u();let x=g,T=await ne(r,s,a,(S,L,z)=>S.onActivityDeltaEvent?.({event:p,messages:L,state:z,agent:n,input:t,activityMessage:x}));if(c(T),T.stopPropagation!==!0)try{Fe(x,p)&&c({messages:s});let S=J(x.content??{}),L=Oo.applyPatch(S,p.patch??[],!0,!1).newDocument;s[h]={...x,content:J(L),activityType:p.activityType},c({messages:s})}catch(S){let L=S instanceof Error?S.message:String(S);console.warn(`Failed to apply activity patch for '${p.messageId}': ${L}`)}return u()}case b.RAW:return c(await ne(r,s,a,(p,h,g)=>p.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.CUSTOM:return c(await ne(r,s,a,(p,h,g)=>p.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.RUN_STARTED:{let p=await ne(r,s,a,(h,g,x)=>h.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages){let x=g;if(g.subagentRunId===null){let T={...g};delete T.subagentRunId,x=T}s.find(T=>T.id===x.id)||s.push(x)}c({messages:s})}}return u()}case b.RUN_FINISHED:{let p=m,h=p.outcome?.type==="interrupt"?{event:p,outcome:"interrupt",interrupts:p.outcome.interrupts}:{event:p,outcome:"success",result:p.result},g=await ne(r,s,a,(x,T,S)=>x.onRunFinishedEvent?.({...h,messages:T,state:S,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?h.interrupts.map(x=>{if(x.subagentRunId!==null)return x;let T={...x};return delete T.subagentRunId,T}):[]),u()}case b.RUN_ERROR:return c(await ne(r,s,a,(p,h,g)=>p.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.STEP_STARTED:return c(await ne(r,s,a,(p,h,g)=>p.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.STEP_FINISHED:return c(await ne(r,s,a,(p,h,g)=>p.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be transformed before being applied");case b.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be transformed before being applied");case b.THINKING_START:return u();case b.THINKING_END:return u();case b.THINKING_TEXT_MESSAGE_START:return u();case b.THINKING_TEXT_MESSAGE_CONTENT:return u();case b.THINKING_TEXT_MESSAGE_END:return u();case b.REASONING_START:return c(await ne(r,s,a,(p,h,g)=>p.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.REASONING_MESSAGE_START:{let p=await ne(r,s,a,(h,g,x)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let{messageId:h,subagentRunId:g}=m,x=s.find(L=>L.id===h),T=x;if(!T){let L={id:h,role:"reasoning",content:"",...g!=null&&{subagentRunId:g}};s.push(L),T=L}let S=Fe(T,m);(!x||S)&&c({messages:s})}return u()}case b.REASONING_MESSAGE_CONTENT:{let{messageId:p,delta:h}=m,g=s.find(T=>T.id===p);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${p}'`),u();let x=await ne(r,s,a,(T,S,L)=>T.onReasoningMessageContentEvent?.({event:m,messages:S,state:L,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,Fe(g,m),c({messages:s})),u()}case b.REASONING_MESSAGE_END:{let{messageId:p}=m,h=s.find(x=>x.id===p);if(!h)return console.warn(`REASONING_MESSAGE_END: No message found with ID '${p}'`),u();let g=await ne(r,s,a,(x,T,S)=>x.onReasoningMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}));return c(g),g.stopPropagation!==!0&&Fe(h,m)&&c({messages:s}),await Promise.all(r.map(x=>{x.onNewMessage?.({message:h,messages:s,state:a,agent:n,input:t})})),u()}case b.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case b.REASONING_END:return c(await ne(r,s,a,(p,h,g)=>p.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.REASONING_ENCRYPTED_VALUE:{let{subtype:p,entityId:h,encryptedValue:g}=m,x=await ne(r,s,a,(T,S,L)=>T.onReasoningEncryptedValueEvent?.({event:m,messages:S,state:L,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let T=!1;if(p==="tool-call"){for(let S of s)if(S.role==="assistant"&&S.toolCalls){let L=S.toolCalls.find(z=>z.id===h);if(L){L.encryptedValue=g,T=!0;break}}}else{let S=s.find(L=>L.id===h);S?.role!=="activity"&&S&&(S.encryptedValue=g,T=!0)}T&&(l.messages=s)}return u()}case b.SUBAGENT_STARTED:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.SUBAGENT_FINISHED:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.SUBAGENT_ERROR:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u()}return m.type,u()}),xa(),r.length>0?_a({}):m=>m)},Fa=t=>e=>{let n=Ar(t),r=new Set,o=new Set,i=new Set,s={message:new Map,toolCall:new Map,activity:new Map,reasoning:new Map},a=!1,l=!1,c=!1,u=new Map,m=v=>{let A=u.get(v);return A||(A=new Map,u.set(v,A)),A},w=()=>{for(let v of u.values())if(v.size>0)return!0;return!1},p=new Map,h=new Set,g=!1,x=!1,T=!1,S=()=>{r.clear(),o.clear(),i.clear(),s.message.clear(),s.toolCall.clear(),s.activity.clear(),s.reasoning.clear(),u.clear(),p.clear(),h.clear(),g=!1,x=!1,a=!1,l=!1,T=!0},L=(v,A)=>{let E=v??[];if(Array.isArray(E))for(let R of E){if(!R||typeof R.id!="string")continue;if(R.subagentRunId===null)return new j(`Cannot send a message (id '${R.id}') with 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`);let B=R.role==="reasoning"?s.reasoning:R.role==="activity"?s.activity:s.message;(A||!B.has(R.id))&&B.set(R.id,{subagentRunId:R.subagentRunId});for(let le of R.toolCalls??[])le&&typeof le.id=="string"&&(A||!s.toolCall.has(le.id))&&s.toolCall.set(le.id,{subagentRunId:R.subagentRunId??void 0})}},z=(v,A,E,R,B)=>{if(A!==void 0&&E&&E.subagentRunId!==A)return new j(`Cannot send '${v}': subagentRunId '${A}' does not match the ${R} '${B}' opener's subagent '${E.subagentRunId??"(the parent agent)"}'.`)};return e.pipe(Ue(v=>{let A=v.type;if(n?.event("VERIFY","Event:",v,{type:v.type}),l&&A!==b.RUN_STARTED)return G(()=>new j(`Cannot send event type '${A}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(a&&A!==b.RUN_ERROR&&A!==b.RUN_STARTED)return G(()=>new j(`Cannot send event type '${A}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(c){if(A===b.RUN_STARTED){if(T&&!a&&!l)return G(()=>new j("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));(a||l)&&S()}}else if(c=!0,A!==b.RUN_STARTED&&A!==b.RUN_ERROR)return G(()=>new j("First event must be 'RUN_STARTED'"));if(v.subagentRunId===null)return G(()=>new j(`Cannot send '${A}' with 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`));if(A===b.SUBAGENT_STARTED||A===b.SUBAGENT_FINISHED||A===b.SUBAGENT_ERROR){let E=A===b.SUBAGENT_STARTED?["description","parentSubagentRunId","parentToolCallId","parentMessageId"]:A===b.SUBAGENT_FINISHED?["outcome"]:["code"];for(let B of E)if(v[B]===null)return G(()=>new j(`Cannot send '${A}' with '${B}: null'. The field is optional \u2014 omit it entirely.`));let R=v.outcome;if(R!=null&&R.type!=="success"&&R.type!=="suspended")return G(()=>new j(`Cannot send '${A}' with outcome type '${String(R.type)}'. The outcome is either { type: "success" } or { type: "suspended" }.`));if(R&&R.interruptIds===null)return G(()=>new j(`Cannot send '${A}' with 'outcome.interruptIds: null'. The field is optional \u2014 omit it entirely.`));if(R&&Array.isArray(R.interruptIds)&&R.interruptIds.some(B=>typeof B!="string"))return G(()=>new j(`Cannot send '${A}' with a non-string entry in 'outcome.interruptIds'. Interrupt ids are strings.`))}if(A===b.RUN_FINISHED){let E=v.outcome;if(E?.type==="interrupt"&&Array.isArray(E.interrupts)){for(let R of E.interrupts)if(R&&R.subagentRunId===null)return G(()=>new j(`Cannot send 'RUN_FINISHED' with an interrupt (id '${R.id}') carrying 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`))}}switch(A){case b.TEXT_MESSAGE_START:{let E=v.messageId;if(r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${E}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`));let R=s.message.get(E);if(R){let B=z(A,v.subagentRunId,R,"message",E);if(B)return G(()=>B)}return r.add(E),R||s.message.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.TEXT_MESSAGE_CONTENT:{let E=v.messageId;if(!r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${E}'. Start a text message with 'TEXT_MESSAGE_START' first.`));let R=z(A,v.subagentRunId,s.message.get(E),"message",E);return R?G(()=>R):te(v)}case b.TEXT_MESSAGE_END:{let E=v.messageId;if(!r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${E}'. A 'TEXT_MESSAGE_START' event must be sent first.`));let R=z(A,v.subagentRunId,s.message.get(E),"message",E);return R?G(()=>R):(r.delete(E),te(v))}case b.TOOL_CALL_START:{let E=v.toolCallId;if(o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${E}' is already in progress. Complete it with 'TOOL_CALL_END' first.`));let R=v.parentMessageId,B=v.subagentRunId,le;if(R!==void 0){let je=s.message.get(R);if(je){if(B!==void 0&&B!==je.subagentRunId)return G(()=>new j(`Cannot send 'TOOL_CALL_START': subagentRunId '${B}' does not match its parent message '${R}' owner '${je.subagentRunId??"(the parent agent)"}'. A tool call belongs to the message that carries it.`));le=je}}let we=s.toolCall.get(E);if(we){let je=z(A,B,we,"tool call",E);if(je)return G(()=>je);if(B===void 0&&le&&le.subagentRunId!==we.subagentRunId)return G(()=>new j(`Cannot send 'TOOL_CALL_START': tool call '${E}' is owned by '${we.subagentRunId??"(the parent agent)"}' but its parent message '${R}' is owned by '${le.subagentRunId??"(the parent agent)"}'. A tool call belongs to the message that carries it.`))}return o.add(E),we||s.toolCall.set(E,B===void 0?le??{subagentRunId:void 0}:{subagentRunId:B}),te(v)}case b.TOOL_CALL_ARGS:{let E=v.toolCallId;if(!o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${E}'. Start a tool call with 'TOOL_CALL_START' first.`));let R=z(A,v.subagentRunId,s.toolCall.get(E),"tool call",E);return R?G(()=>R):te(v)}case b.TOOL_CALL_END:{let E=v.toolCallId;if(!o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${E}'. A 'TOOL_CALL_START' event must be sent first.`));let R=z(A,v.subagentRunId,s.toolCall.get(E),"tool call",E);return R?G(()=>R):(o.delete(E),te(v))}case b.STEP_STARTED:{let E=v.stepName,R=v.subagentRunId;return m(R).has(E)?G(()=>new j(`Step "${E}" is already active for 'STEP_STARTED'${R===void 0?"":` in subagent '${R}'`}`)):(m(R).set(E,!0),te(v))}case b.STEP_FINISHED:{let E=v.stepName,R=v.subagentRunId;if(!m(R).has(E)){let B,le=!1;for(let[we,je]of u)if(we!==R&&je.has(E)){B=we,le=!0;break}return G(le?()=>new j(`Cannot send 'STEP_FINISHED' for step "${E}" attributed to ${R===void 0?"the parent agent":`subagent '${R}'`}: that step is open under ${B===void 0?"the parent agent":`subagent '${B}'`}. A step must be finished by whoever started it.`):()=>new j(`Cannot send 'STEP_FINISHED' for step "${E}" that was not started`))}return m(R).delete(E),te(v)}case b.ACTIVITY_SNAPSHOT:{let E=v.messageId;return(!s.activity.has(E)||v.replace!==!1)&&s.activity.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.TOOL_CALL_RESULT:{let E=v.messageId;return typeof E=="string"&&s.message.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.REASONING_START:case b.REASONING_MESSAGE_START:{let E=v.messageId,R=s.reasoning.get(E);if(R){let B=z(A,v.subagentRunId,R,"reasoning message",E);if(B)return G(()=>B)}return i.add(E),R||s.reasoning.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:{let E=v.messageId,R=z(A,v.subagentRunId,s.reasoning.get(E),"reasoning message",E);return R?G(()=>R):(A===b.REASONING_END&&i.delete(E),te(v))}case b.REASONING_ENCRYPTED_VALUE:{let E=v.entityId,R=v.subtype,B=R==="tool-call"?s.toolCall.get(E):R==="message"?s.message.get(E)??s.reasoning.get(E):s.reasoning.get(E),le=R==="tool-call"?"tool call":R==="message"?"message":"reasoning message",we=z(A,v.subagentRunId,B,le,E);return we?G(()=>we):te(v)}case b.ACTIVITY_DELTA:{let E=v.messageId,R=z(A,v.subagentRunId,s.activity.get(E),"activity",E);return R?G(()=>R):te(v)}case b.SUBAGENT_STARTED:{if(typeof v.subagentRunId!="string")return G(()=>new j("Cannot send 'SUBAGENT_STARTED' without a 'subagentRunId'."));if(typeof v.name!="string")return G(()=>new j("Cannot send 'SUBAGENT_STARTED' without a 'name'."));let E=v.subagentRunId,R=v.parentSubagentRunId;return p.has(E)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': subagent '${E}' is already active. Finish it with 'SUBAGENT_FINISHED' first.`)):h.has(E)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': subagent '${E}' has already finished in this run. Subagent IDs are per-invocation and cannot be reused.`)):R!==void 0&&!p.has(R)&&!h.has(R)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': parentSubagentRunId '${R}' has not been started in this run.`)):(p.set(E,!0),te(v))}case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{if(typeof v.subagentRunId!="string")return G(()=>new j(`Cannot send '${A}' without a 'subagentRunId'.`));if(A===b.SUBAGENT_ERROR&&typeof v.message!="string")return G(()=>new j("Cannot send 'SUBAGENT_ERROR' without a 'message'."));let E=v.subagentRunId;return p.has(E)?(p.delete(E),h.add(E),te(v)):G(()=>new j(`Cannot send '${A}': no active subagent found with ID '${E}'. A 'SUBAGENT_STARTED' event must be sent first.`))}case b.MESSAGES_SNAPSHOT:{let E=L(v.messages,!0);if(E)return G(()=>E)}return te(v);case b.RUN_STARTED:T=!0;{let E=L((v.input??{}).messages,!1);if(E)return G(()=>E)}return te(v);case b.RUN_FINISHED:if(w()){let E=[];for(let[B,le]of u)for(let we of le.keys())E.push(B===void 0?we:`${we} (subagent '${B}')`);let R=E.join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while steps are still active: ${R}`))}if(r.size>0){let E=Array.from(r.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while text messages are still active: ${E}`))}if(o.size>0){let E=Array.from(o.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${E}`))}if(p.size>0){let E=Array.from(p.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while subagents are still active: ${E}`))}return a=!0,te(v);case b.RUN_ERROR:return l=!0,te(v);case b.CUSTOM:return te(v);case b.THINKING_TEXT_MESSAGE_START:return g?x?G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(x=!0,te(v)):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case b.THINKING_TEXT_MESSAGE_CONTENT:return x?te(v):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case b.THINKING_TEXT_MESSAGE_END:return x?(x=!1,te(v)):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case b.THINKING_START:return g?G(()=>new j("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(g=!0,te(v));case b.THINKING_END:return g?(g=!1,te(v)):G(()=>new j("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(v)}}))},fn=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),Fb=t=>ti(()=>un(t())).pipe(Ta(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return un(e.text()).pipe(Ue(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,G(()=>a)}))}let n={type:fn.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new ce(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:fn.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):G(()=>Error("Failed to getReader() from response"))})),$b=(t,e)=>{let n=Ar(e),r=new ft,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==fn.HEADERS&&a.type===fn.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let c=i.split(/\n\n/);i=c.pop()||"";for(let u of c)s(u)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
9
9
  `),c=[];for(let u of l)u.startsWith("data:")&&c.push(u.slice(5).replace(/^ /,""));if(c.length>0)try{let u=c.join(`
10
10
  `),m=JSON.parse(u);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(u){r.error(u)}}return r.asObservable()},Bb=t=>{let e=new ft,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==fn.HEADERS&&o.type===fn.DATA&&o.data){let i=new Uint8Array(n.length+o.data.length);i.set(n,0),i.set(o.data,n.length),n=i,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let i=n.slice(4,o),s=Gu(i);e.next(s),n=n.slice(o)}catch(i){let s=i instanceof Error?i.message:String(i);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Vb=(t,e)=>{let n=Ar(e),r=new ft,o=new zo,i=!1;return t.subscribe({next:s=>{if(o.next(s),s.type===fn.HEADERS&&!i){i=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Ua?"protobuf":"sse"}),a===Ua?Bb(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):$b(o,n).subscribe({next:l=>{try{let c=To.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:b.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else i||r.error(Error("No headers event received before data events"))},error:s=>{o.error(s),r.error(s)},complete:()=>{o.complete()}}),r.asObservable()},se=d.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),jb=d.enum(["LangGraphInterruptEvent","PredictState","Exit"]),qb=d.object({type:d.literal(se.enum.TextMessageStart),messageId:d.string(),parentMessageId:d.string().optional(),role:d.string().optional()}),Wb=d.object({type:d.literal(se.enum.TextMessageContent),messageId:d.string(),content:d.string()}),Xb=d.object({type:d.literal(se.enum.TextMessageEnd),messageId:d.string()}),Yb=d.object({type:d.literal(se.enum.ActionExecutionStart),actionExecutionId:d.string(),actionName:d.string(),parentMessageId:d.string().optional()}),Kb=d.object({type:d.literal(se.enum.ActionExecutionArgs),actionExecutionId:d.string(),args:d.string()}),Zb=d.object({type:d.literal(se.enum.ActionExecutionEnd),actionExecutionId:d.string()}),Qb=d.object({type:d.literal(se.enum.ActionExecutionResult),actionName:d.string(),actionExecutionId:d.string(),result:d.string()}),Jb=d.object({type:d.literal(se.enum.AgentStateMessage),threadId:d.string(),agentName:d.string(),nodeName:d.string(),runId:d.string(),active:d.boolean(),role:d.string(),state:d.string(),running:d.boolean()}),ev=d.object({type:d.literal(se.enum.MetaEvent),name:jb,value:d.any()}),tv=d.object({type:d.literal(se.enum.RunError),message:d.string(),code:d.string().optional()});d.discriminatedUnion("type",[qb,Wb,Xb,Yb,Kb,Zb,Qb,Jb,ev,tv]),d.object({id:d.string(),role:d.string(),content:d.string(),parentMessageId:d.string().optional()}),d.object({id:d.string(),name:d.string(),arguments:d.any(),parentMessageId:d.string().optional()}),d.object({id:d.string(),result:d.any(),actionExecutionId:d.string(),actionName:d.string()});var nv=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
11
- `)},rv=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,u=[],m={},w=p=>{typeof p=="object"&&p&&("messages"in p&&delete p.messages,o=p)};return r.pipe(Ue(p=>{switch(p.type){case b.TEXT_MESSAGE_START:{let h=p;return[{type:se.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case b.TEXT_MESSAGE_CONTENT:{let h=p;return[{type:se.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case b.TEXT_MESSAGE_END:{let h=p;return[{type:se.enum.TextMessageEnd,messageId:h.messageId}]}case b.TOOL_CALL_START:{let h=p;return u.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),s=!0,m[h.toolCallId]=h.toolCallName,[{type:se.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case b.TOOL_CALL_ARGS:{let h=p,g=u.find(T=>T.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let x=!1;if(c){let T=c.find(S=>S.tool==g.function.name);if(T)try{let S=JSON.parse(ii(g.function.arguments));T.tool_argument&&T.tool_argument in S?(w({...o,[T.state_key]:S[T.tool_argument]}),x=!0):T.tool_argument||(w({...o,[T.state_key]:S}),x=!0)}catch{}}return[{type:se.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...x?[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case b.TOOL_CALL_END:{let h=p;return[{type:se.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case b.TOOL_CALL_RESULT:{let h=p;return[{type:se.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case b.RAW:return[];case b.CUSTOM:{let h=p;switch(h.name){case"Exit":i=!1;break;case"PredictState":c=h.value;break}return[{type:se.enum.MetaEvent,name:h.name,value:h.value}]}case b.STATE_SNAPSHOT:return w(p.snapshot),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case b.STATE_DELTA:{let h=p,g=Oo.applyPatch(o,h.delta,!0,!1);return g?(w(g.newDocument),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case b.MESSAGES_SNAPSHOT:return l=p.messages,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case b.RUN_STARTED:return[];case b.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:ov(l)}:{}}),active:!1}];case b.RUN_ERROR:{let h=p;return[{type:se.enum.RunError,message:h.message,code:h.code}]}case b.STEP_STARTED:return a=p.stepName,u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case b.STEP_FINISHED:return u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function ov(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=nv(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var iv=t=>t.kind==="tool"?t.fields.toolCallId:t.fields.messageId,sv=t=>t==="tool"?"toolCallId":"messageId",Qn=(t,e)=>e.metadata===void 0?t:{...t,metadata:e.metadata},Bi=t=>e=>{let n=Ar(t),r=new Map,o=l=>{let c=r.get(l);if(!c)return[];switch(r.delete(l),c.kind){case"text":{let u={type:b.TEXT_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TEXT_MESSAGE_END",u,{messageId:u.messageId}),[u]}case"tool":{let u={type:b.TOOL_CALL_END,toolCallId:c.fields.toolCallId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TOOL_CALL_END",u,{toolCallId:u.toolCallId}),[u]}case"reasoning":{let u={type:b.REASONING_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","REASONING_MESSAGE_END",u,{messageId:u.messageId}),[u]}}},i=()=>[...r.keys()].flatMap(l=>o(l)),s=(l,c)=>{for(let[u,m]of r)if(m.kind===l&&iv(m)===c)return{owner:u}},a=(l,c,u,m,w)=>{if(c!==void 0){let h=s(l,c);if(h){if(u!==void 0&&u!==h.owner)throw Error(`Cannot continue ${w} '${c}': chunk subagentRunId '${u}' does not match the open stream's subagent '${h.owner??"(the parent agent)"}'.`);return h.owner}return u}if(u!==void 0)return u;if(r.get(void 0)?.kind===l)return;let p=[...r.entries()].filter(([,h])=>h.kind===l);if(p.length===1)return p[0][0];if(p.length>1)throw Error(`Ambiguous ${m}: it carries neither a ${sv(l)} nor a subagentRunId, but ${p.length} lanes have an open ${w}. Attribute the chunk to the subagent it belongs to.`)};return e.pipe(Ue(l=>{switch(l.type){case b.TEXT_MESSAGE_START:case b.TEXT_MESSAGE_CONTENT:case b.TEXT_MESSAGE_END:case b.TOOL_CALL_START:case b.TOOL_CALL_ARGS:case b.TOOL_CALL_END:case b.TOOL_CALL_RESULT:case b.STATE_SNAPSHOT:case b.STATE_DELTA:case b.CUSTOM:case b.STEP_STARTED:case b.STEP_FINISHED:case b.THINKING_START:case b.THINKING_END:case b.THINKING_TEXT_MESSAGE_START:case b.THINKING_TEXT_MESSAGE_CONTENT:case b.THINKING_TEXT_MESSAGE_END:case b.REASONING_START:case b.REASONING_MESSAGE_START:case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:return[...o(l.subagentRunId??void 0),l];case b.RUN_STARTED:case b.RUN_FINISHED:case b.RUN_ERROR:case b.MESSAGES_SNAPSHOT:return[...i(),l];case b.RAW:case b.ACTIVITY_SNAPSHOT:case b.ACTIVITY_DELTA:case b.REASONING_ENCRYPTED_VALUE:case b.SUBAGENT_STARTED:return[l];case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{let c=l.subagentRunId;return c==null?[l]:[...o(c),l]}case b.TEXT_MESSAGE_CHUNK:{let c=l,u=a("text",c.messageId,c.subagentRunId??void 0,"TEXT_MESSAGE_CHUNK","text message"),m=r.get(u),w=[],p;if(m?.kind==="text"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,name:c.name,subagentRunId:c.subagentRunId},r.set(u,{kind:"text",fields:p});let h=Qn({type:b.TEXT_MESSAGE_START,messageId:c.messageId,role:c.role||"assistant",...c.name!==void 0&&{name:c.name},...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TEXT_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.TOOL_CALL_CHUNK:{let c=l,u=a("tool",c.toolCallId,c.subagentRunId??void 0,"TOOL_CALL_CHUNK","tool call"),m=r.get(u),w=[],p;if(m?.kind==="tool"&&(c.toolCallId===void 0||c.toolCallId===m.fields.toolCallId))p=m.fields;else{if(w.push(...o(u)),c.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(c.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");p={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"tool",fields:p});let h=Qn({type:b.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TOOL_CALL_START",h,{toolCallId:c.toolCallId,toolCallName:c.toolCallName})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TOOL_CALL_ARGS",g,{toolCallId:p.toolCallId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.REASONING_MESSAGE_CHUNK:{let c=l,u=a("reasoning",c.messageId,c.subagentRunId??void 0,"REASONING_MESSAGE_CHUNK","reasoning message"),m=r.get(u),w=[],p;if(m?.kind==="reasoning"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"reasoning",fields:p});let h=Qn({type:b.REASONING_MESSAGE_START,messageId:c.messageId,role:"reasoning",...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","REASONING_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}}return l.type,[]}),hn(()=>{i()}))};function av(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function eh(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.join(", ")}`);return t.map(s=>{let a=e[s.id],l={interruptId:s.id,status:a.status};return a.status==="resolved"&&a.payload!==void 0&&(l.payload=a.payload),a.metadata!==void 0&&(l.metadata=a.metadata),l})}var kr=class{runNext(t,e){return e.run(t).pipe(Bi(!1))}runNextWithState(t,e){let n=J(t.messages||[]),r=J(t.state||{}),o=new zo;return Ju(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(ni(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:J(n),state:J(r)})))}},lv=class extends kr{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function cv(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var dv=class extends kr{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(cv)};return this.runNext(o,e)}},Vu="THINKING_START",ju="THINKING_END",qu="THINKING_TEXT_MESSAGE_START",Wu="THINKING_TEXT_MESSAGE_CONTENT",Xu="THINKING_TEXT_MESSAGE_END",uv=class extends kr{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Lt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Vu:{this.currentReasoningId=Ie();let{title:e,...n}=t;return this.warnAboutTransformation(Vu,b.REASONING_START),{...n,type:b.REASONING_START,messageId:this.currentReasoningId}}case qu:return this.currentMessageId=Ie(),this.warnAboutTransformation(qu,b.REASONING_MESSAGE_START),{...t,type:b.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Wu:{let{delta:e,...n}=t;return this.warnAboutTransformation(Wu,b.REASONING_MESSAGE_CONTENT),{...n,type:b.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ie(),delta:e}}case Xu:{let e=this.currentMessageId??Ie();return this.warnAboutTransformation(Xu,b.REASONING_MESSAGE_END),{...t,type:b.REASONING_MESSAGE_END,messageId:e}}case ju:{let e=this.currentReasoningId??Ie();return this.warnAboutTransformation(ju,b.REASONING_END),{...t,type:b.REASONING_END,messageId:e}}default:return t}}};function hv(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pv(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function fv(t){let e=hv(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function mv(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pv(r)?fv(r):r);return{...t,content:n}}var gv=class extends kr{run(t,e){let n={...t,messages:t.messages.map(mv)};return this.runNext(n,e)}},Yu="SUBAGENT_STARTED",Ku="SUBAGENT_FINISHED",Zu="SUBAGENT_ERROR";function Vi(t){if(t&&typeof t=="object"&&"subagentRunId"in t){let{subagentRunId:e,...n}=t;return n}return t}function Qu(t){return t.map(e=>Vi(e))}var bv=class extends kr{warnDroppedLifecycleEvent(t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${t} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){let n={...t,messages:(t.messages??[]).map(r=>Vi(r))};return this.runNext(n,e).pipe(oi(r=>{let o=r.type;(o===Yu||o===Ku||o===Zu)&&this.warnDroppedLifecycleEvent(o)}),Ea(r=>{let o=r.type;return o!==Yu&&o!==Ku&&o!==Zu}),Lt(r=>{let o=Vi(r);if(o.type===b.MESSAGES_SNAPSHOT){let i=o;if(Array.isArray(i.messages))return{...i,messages:Qu(i.messages)}}if(o.type===b.RUN_FINISHED){let i=o;if(i.outcome&&Array.isArray(i.outcome.interrupts))return{...i,outcome:{...i.outcome,interrupts:i.outcome.interrupts.map(s=>Vi(s))}}}if(o.type===b.RUN_STARTED){let i=o;if(i.input&&Array.isArray(i.input.messages))return{...i,input:{...i.input,messages:Qu(i.input.messages)}}}return o}))}},vv="0.0.59",yv=class{get maxVersion(){return vv}get debug(){return this._debug}set debug(t){this._debug=$i(t),this._debugLogger=za(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?za($i(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??Rt(),this.messages=J(r??[]),this.state=J(o??{}),this._debug=$i(i),this._debugLogger=za(this._debug),Zn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new dv),Zn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new uv),Zn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new gv),Zn(this.maxVersion,"0.0.57")<=0&&this.middlewares.unshift(new bv)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new lv(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:u=>c.run(u,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),hn(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new la}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>ti(()=>this.connect(n)),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.isRunning=!1,l instanceof la?Fo:this.onError(n,l,i))),hn(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Ju(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=J(this.messages);for(let r of e)r.subagentRunId===null&&delete r.subagentRunId;let n=e.filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Rt(),tools:J(t?.tools??[]),context:J(t?.context??[]),forwardedProps:J(t?.forwardedProps??{}),state:J(this.state),messages:n,...t?.resume===void 0?{}:{resume:J(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new j(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(av(i))throw new j(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let r of n.messages)r.subagentRunId===null&&delete r.subagentRunId;t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})}n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}}onError(t,e,n){return un(ne(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Lt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=J(this.messages),t.state=J(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=J(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=J(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=J(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Rt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Bi(this.debugLogger),Fa(this.debugLogger),rv(this.threadId,e.runId,this.agentId),n=>n.pipe(Lt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}};function wv(t){if(!Array.isArray(t.messages))return t;let e=!1,n=t.messages.map(r=>{if(r.subagentRunId===null){e=!0;let o={...r};return delete o.subagentRunId,o}return r});return e?{...t,messages:n}:t}var th=class extends yv{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(wv(t)),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=J(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Vb(Fb(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=J(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var xv=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function nh(t,e){let n=[];return{text:t.replace(xv,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Ev(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function Va(t){return Array.isArray(t)?t.filter(Ev):[]}var ji=["top-left","top-right","bottom-left","bottom-right"];function rh(t){return ji.includes(t)}function ja(t){return[{name:"read_chat_surface",description:"Describe the chat panel you are speaking from: its placement, whether it is collapsed, whether it can be moved, and the box it occupies. Read this before moving or minimising yourself, since a full-screen panel has nowhere to move to. Read-only.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the chat's own position"},handler:()=>t.describeSurface()},{name:"move_chat",description:"Move your own panel to a corner, to uncover something the user needs to see. `corner` is top-left, top-right, bottom-left or bottom-right. Answers `moved: false` with a reason when the placement owns its position or the panel fills the screen; check `read_chat_surface` first, and prefer minimise_chat when there is nowhere to move to.",parameters:{type:"object",properties:{corner:{type:"string",enum:[...ji]}},required:["corner"],[xe]:"Move the chat out of the way"},handler:e=>{let n=String(e.corner??""),r=t.describeSurface();return rh(n)?r.movable?{moved:t.moveTo(n,{announce:!0}),corner:n}:{moved:!1,reason:r.fullBleed?"the panel fills the screen, so there is nowhere to move it to":r.draggable===!1?"this page has turned off moving the panel":`the "${r.placement??""}" placement owns the panel's position`,suggestion:r.collapsible?"minimise_chat":null}:{moved:!1,reason:`"${n}" is not a corner; use one of ${ji.join(", ")}`}}},{name:"minimise_chat",description:"Collapse your own panel to its launcher, so the user can see the whole page. The launcher stays visible and reopens it. Answers `minimised: false` when the placement has no collapsed state, which is the case for a full-page chat.",parameters:{type:"object",properties:{},required:[],[xe]:"Minimise the chat"},handler:()=>t.describeSurface().collapsible?(t.setCollapsed(!0,{announce:!0}),{minimised:!0}):{minimised:!1,reason:"this placement has no collapsed state, so there is no launcher to return to"}},{name:"restore_chat",description:"Open your own panel again after minimising it.",parameters:{type:"object",properties:{},required:[],[xe]:"Restore the chat"},handler:()=>(t.setCollapsed(!1),{restored:!0})}]}var Ir=class{#t=new Map;register(e){this.#t.set(e.name,e)}has(e){return this.#t.has(e)}get(e){let n=this.#t.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#t.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function qa(t){return t[hr]===!0}function qi(t){return t[pr]===!0}var _v="#4f46e5";function Jn(t,e,n){let r=window.getComputedStyle(t).getPropertyValue(e).trim();return r===""?n:r}var Tv=4;function Wa(t,e={}){let n=document.createElement("div");n.setAttribute("data-ag-ui-highlight",""),n.setAttribute("aria-hidden","true"),n.style.cssText=["position: fixed","inset: 0","pointer-events: none",`z-index: ${Jn(t,"--ag-ui-highlight-z-index",String(Yc))}`].join(";");let r=document.createElement("div"),o=document.createElement("div");n.className="ag-ui-highlight",r.className="ag-ui-highlight-scrim",o.className="ag-ui-highlight-ring",e.scrim===!0&&n.append(r),n.append(o);let i=e.ringWidth??Number.parseFloat(Jn(t,"--ag-ui-highlight-ring-width","3")),s=e.flowMs??Number.parseFloat(Jn(t,"--ag-ui-highlight-flow-ms","2400")),a=()=>{let u=t.getBoundingClientRect(),m=e.padding??Tv,w=e.radius??Number.parseFloat(getComputedStyle(t).borderRadius),p=u.left-m,h=u.top-m,g=u.width+m*2,x=u.height+m*2;e.scrim===!0&&(r.style.cssText=["position: absolute","inset: 0",`background: ${Jn(t,"--ag-ui-highlight-scrim","rgba(15, 15, 25, 0.45)")}`,`clip-path: path(evenodd, '${kv(p,h,g,x,w+m)}')`].join(";")),o.style.cssText=["position: absolute",`left: ${p}px`,`top: ${h}px`,`width: ${g}px`,`height: ${x}px`,`border-radius: ${w+m}px`,`border: ${i}px solid transparent`,"box-sizing: border-box",Av(t,e)].join(";")};a();let l=null;e.gradient===!0&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(l=o.animate([{backgroundPosition:"100% 0"},{backgroundPosition:"-100% 0"}],{duration:s,iterations:Number.POSITIVE_INFINITY,easing:"linear"}));let c={capture:!0,passive:!0};return window.addEventListener("scroll",a,c),window.addEventListener("resize",a,c),document.body.appendChild(n),()=>{window.removeEventListener("scroll",a,c),window.removeEventListener("resize",a,c),l?.cancel(),n.remove()}}function Sv(t){return t===void 0?null:CSS.supports("color",t)?t:null}function Av(t,e){let n=Sv(e.color)??Jn(t,"--ag-ui-accent",_v);if(e.gradient!==!0)return`border-color: ${n}`;let r=Jn(t,"--ag-ui-highlight-gradient",`linear-gradient(115deg, transparent 20%, ${n} 50%, transparent 80%)`),o="linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)";return[`background-image: ${r}`,"background-origin: border-box","background-size: 300% 100%",`-webkit-mask: ${o}`,`mask: ${o}`,"-webkit-mask-composite: xor","mask-composite: exclude","background-position: 50% 0"].join(";")}function kv(t,e,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2)),s=t+n,a=e+r,l=`M 0 0 H ${window.innerWidth} V ${window.innerHeight} H 0 Z`,c=[`M ${t+i} ${e}`,`H ${s-i}`,`A ${i} ${i} 0 0 1 ${s} ${e+i}`,`V ${a-i}`,`A ${i} ${i} 0 0 1 ${s-i} ${a}`,`H ${t+i}`,`A ${i} ${i} 0 0 1 ${t} ${a-i}`,`V ${e+i}`,`A ${i} ${i} 0 0 1 ${t+i} ${e}`,"Z"].join(" ");return`${l} ${c}`}function Wi(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Iv=Wi(HTMLInputElement.prototype,"value"),Rv=Wi(HTMLTextAreaElement.prototype,"value"),Cv=Wi(HTMLSelectElement.prototype,"value"),Nv=Wi(HTMLInputElement.prototype,"checked");function mn(t,e){t instanceof HTMLTextAreaElement?Rv.call(t,e):t instanceof HTMLSelectElement?Cv.call(t,e):Iv.call(t,e)}function Rr(t,e){Nv.call(t,e)}var Xa="#4f46e5",Ov="rgba(79, 70, 229, 0.4)",Mv="--ag-ui-accent";function er(t){return new Promise(e=>{setTimeout(e,t)})}function Xi(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ya(t){return t<=0||Xi()?Promise.resolve():er(t)}function Yi(t,e){let n=window.getComputedStyle(t).getPropertyValue(Mv).trim();return n===""?e:n}function oh(t){return`0 0 0 3px ${Yi(t,Ov)}`}async function Ka(t,e,n={}){let r=n.charDelayMs??35;mn(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)mn(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await er(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Za(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await er(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var Lv=600,Pv=100;function _t(t,e={}){let n=Xi();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??Lv)};o=setTimeout(i,Pv),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var Dv=1200,Uv=1/3;async function ih(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??Dv;if(r<=0)return;if(e.scrim===!0||e.gradient===!0){let c=Wa(t,{scrim:e.scrim===!0,gradient:e.gradient===!0,...e.color===void 0?{}:{color:e.color},...e.ringPadding===void 0?{}:{padding:e.ringPadding}});await er(r),c();return}let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Yi(t,Xa);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Xi()?0:Math.round(r*Uv);await er(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await er(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function Hv(t,e={}){return ih(t,e,!1)}function Qa(t,e={}){return ih(t,e,!0)}async function Ja(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=oh(t),await Ya(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Gv(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function el(t,e,n={}){let r=Gv(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await Ya(o),mn(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function tl(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=oh(t),await Ya(r),Rr(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var Nr={SCROLL:"scroll",DRAG:"drag",CHAT:"chat"};function nl(t,e){let n=[];return t.has(Nr.SCROLL)&&n.push(zv(e)),t.has(Nr.DRAG)&&n.push(Fv(e)),n}function zv(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[xe]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return _t(r),{scrolled:!0,target:n}}}}function Fv(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[xe]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return $v(o,i),{dragged:!0,from:n,to:r}}}}function $v(t,e){let n=new DataTransfer;Cr(t,"dragstart",n),Cr(e,"dragenter",n),Cr(e,"dragover",n),Cr(e,"drop",n),Cr(t,"dragend",n)}function Cr(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function rl(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ki(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[xe]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[hr]:!0,[xe]:`Update ${t.name}`},handler:r=>n(r)}),e}var Bv=Ki;function ol(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary,s=r.description;typeof o=="string"&&typeof i=="string"&&(e[o]=typeof s=="string"?{name:o,summary:i,description:s}:{name:o,summary:i})}return e}var sh=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Vv(t){return[...t.matchAll(sh)].map(e=>e[0].slice(1))}function jv(t,e,n){let r={...n};return{path:e.replace(sh,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function qv(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function il(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[xe]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Vv(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[pr]:!0,[xe]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(u=>u.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=jv(o.id,o.path,i),l=qv(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ae={title:"Assistant",chatHistory:"Chat history",closeHistory:"Close history",searchConversations:"Search conversations",queued:"Waiting to send",removeQueued:'Do not send "{text}"',noMatches:"No conversations match that.",chatMoved:"Moved this panel out of the way",chatMinimised:"Minimised this panel",undo:"Undo",newChat:"New chat",collapse:"Collapse",expand:"Expand",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",jumpToLatest:"Jump to latest",announceResponding:"Assistant is responding",announceAnswerReady:"Assistant answered",announceAwaitingDecision:"{count} action is waiting for your approval",announceStopped:"Response stopped",announceFailed:"The response failed",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",historyReplaced:"The server replaced this conversation's history. Reload to see the updated transcript.",chartUndrawable:"A chart could not be drawn from the data sent, so it was removed.",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",runInterrupted:"The previous response didn\u2019t finish \u2014 the page changed before it arrived.",pageMoved:"The page changed since you last looked at it. Call read_page to see the current page, then retry.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",recordingLimit:"Stopped at the {n}-minute limit \u2014 transcribing what was recorded.",toolRunning:"running\u2026",toolDeferred:"waiting for you",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",subAgentWorking:"Working\u2026",subAgentDelegatedTo:"Delegated to {agent}",subAgentFinished:"{agent} finished",subAgentFailed:"The sub-agent failed",subAgentSteps:"Steps the sub-agent took",approvalEditArgs:"Edit the arguments before approving",approvalArgsInvalid:"That is not valid JSON, so nothing was sent.",approvalArgsNotAnObject:"Arguments have to be a JSON object.",suggestions:"Suggested follow-ups",messageActions:"Message actions",quoteSelection:"Quote",copyMessage:"Copy message",retryMessage:"Try again",feedbackUp:"Good answer",feedbackDown:"Poor answer",confirmAction:"Confirm action",confirmAlways:"Always allow",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function sl(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function ah(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function al(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=Wv(e,n,r),l=document.createElement("div");l.className="approval-actions",l.setAttribute("part","approval-actions");let c=ah("deny",r.deny),u=ah("approve",r.approve),m=!1,w=p=>{m||(m=!0,c.disabled=!0,u.disabled=!0,i.setAttribute("data-resolved",p?"approved":"denied"),o(p))};if(c.addEventListener("click",()=>w(!1)),u.addEventListener("click",()=>{a!==null&&!a.commit()||w(!0)}),n.signal?.addEventListener("abort",()=>w(!1),{once:!0}),l.append(c,u),i.append(s,...a===null?[]:[a.root],l),t.appendChild(i),n.signal?.aborted===!0){w(!1);return}u.focus()})}function Wv(t,e,n){let{onEdit:r}=e;if(r===void 0||t.args===void 0)return null;let o=JSON.stringify(t.args,null,2),i=document.createElement("div");i.className="approval-edit",i.setAttribute("part","approval-edit");let s=document.createElement("textarea");s.className="approval-args",s.setAttribute("part","approval-args"),s.setAttribute("aria-label",n.approvalEditArgs),s.rows=Math.min(10,o.split(`
11
+ `)},rv=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,u=[],m={},w=p=>{typeof p=="object"&&p&&("messages"in p&&delete p.messages,o=p)};return r.pipe(Ue(p=>{switch(p.type){case b.TEXT_MESSAGE_START:{let h=p;return[{type:se.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case b.TEXT_MESSAGE_CONTENT:{let h=p;return[{type:se.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case b.TEXT_MESSAGE_END:{let h=p;return[{type:se.enum.TextMessageEnd,messageId:h.messageId}]}case b.TOOL_CALL_START:{let h=p;return u.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),s=!0,m[h.toolCallId]=h.toolCallName,[{type:se.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case b.TOOL_CALL_ARGS:{let h=p,g=u.find(T=>T.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let x=!1;if(c){let T=c.find(S=>S.tool==g.function.name);if(T)try{let S=JSON.parse(ii(g.function.arguments));T.tool_argument&&T.tool_argument in S?(w({...o,[T.state_key]:S[T.tool_argument]}),x=!0):T.tool_argument||(w({...o,[T.state_key]:S}),x=!0)}catch{}}return[{type:se.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...x?[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case b.TOOL_CALL_END:{let h=p;return[{type:se.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case b.TOOL_CALL_RESULT:{let h=p;return[{type:se.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case b.RAW:return[];case b.CUSTOM:{let h=p;switch(h.name){case"Exit":i=!1;break;case"PredictState":c=h.value;break}return[{type:se.enum.MetaEvent,name:h.name,value:h.value}]}case b.STATE_SNAPSHOT:return w(p.snapshot),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case b.STATE_DELTA:{let h=p,g=Oo.applyPatch(o,h.delta,!0,!1);return g?(w(g.newDocument),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case b.MESSAGES_SNAPSHOT:return l=p.messages,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case b.RUN_STARTED:return[];case b.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:ov(l)}:{}}),active:!1}];case b.RUN_ERROR:{let h=p;return[{type:se.enum.RunError,message:h.message,code:h.code}]}case b.STEP_STARTED:return a=p.stepName,u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case b.STEP_FINISHED:return u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function ov(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=nv(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var iv=t=>t.kind==="tool"?t.fields.toolCallId:t.fields.messageId,sv=t=>t==="tool"?"toolCallId":"messageId",Qn=(t,e)=>e.metadata===void 0?t:{...t,metadata:e.metadata},Bi=t=>e=>{let n=Ar(t),r=new Map,o=l=>{let c=r.get(l);if(!c)return[];switch(r.delete(l),c.kind){case"text":{let u={type:b.TEXT_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TEXT_MESSAGE_END",u,{messageId:u.messageId}),[u]}case"tool":{let u={type:b.TOOL_CALL_END,toolCallId:c.fields.toolCallId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TOOL_CALL_END",u,{toolCallId:u.toolCallId}),[u]}case"reasoning":{let u={type:b.REASONING_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","REASONING_MESSAGE_END",u,{messageId:u.messageId}),[u]}}},i=()=>[...r.keys()].flatMap(l=>o(l)),s=(l,c)=>{for(let[u,m]of r)if(m.kind===l&&iv(m)===c)return{owner:u}},a=(l,c,u,m,w)=>{if(c!==void 0){let h=s(l,c);if(h){if(u!==void 0&&u!==h.owner)throw Error(`Cannot continue ${w} '${c}': chunk subagentRunId '${u}' does not match the open stream's subagent '${h.owner??"(the parent agent)"}'.`);return h.owner}return u}if(u!==void 0)return u;if(r.get(void 0)?.kind===l)return;let p=[...r.entries()].filter(([,h])=>h.kind===l);if(p.length===1)return p[0][0];if(p.length>1)throw Error(`Ambiguous ${m}: it carries neither a ${sv(l)} nor a subagentRunId, but ${p.length} lanes have an open ${w}. Attribute the chunk to the subagent it belongs to.`)};return e.pipe(Ue(l=>{switch(l.type){case b.TEXT_MESSAGE_START:case b.TEXT_MESSAGE_CONTENT:case b.TEXT_MESSAGE_END:case b.TOOL_CALL_START:case b.TOOL_CALL_ARGS:case b.TOOL_CALL_END:case b.TOOL_CALL_RESULT:case b.STATE_SNAPSHOT:case b.STATE_DELTA:case b.CUSTOM:case b.STEP_STARTED:case b.STEP_FINISHED:case b.THINKING_START:case b.THINKING_END:case b.THINKING_TEXT_MESSAGE_START:case b.THINKING_TEXT_MESSAGE_CONTENT:case b.THINKING_TEXT_MESSAGE_END:case b.REASONING_START:case b.REASONING_MESSAGE_START:case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:return[...o(l.subagentRunId??void 0),l];case b.RUN_STARTED:case b.RUN_FINISHED:case b.RUN_ERROR:case b.MESSAGES_SNAPSHOT:return[...i(),l];case b.RAW:case b.ACTIVITY_SNAPSHOT:case b.ACTIVITY_DELTA:case b.REASONING_ENCRYPTED_VALUE:case b.SUBAGENT_STARTED:return[l];case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{let c=l.subagentRunId;return c==null?[l]:[...o(c),l]}case b.TEXT_MESSAGE_CHUNK:{let c=l,u=a("text",c.messageId,c.subagentRunId??void 0,"TEXT_MESSAGE_CHUNK","text message"),m=r.get(u),w=[],p;if(m?.kind==="text"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,name:c.name,subagentRunId:c.subagentRunId},r.set(u,{kind:"text",fields:p});let h=Qn({type:b.TEXT_MESSAGE_START,messageId:c.messageId,role:c.role||"assistant",...c.name!==void 0&&{name:c.name},...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TEXT_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.TOOL_CALL_CHUNK:{let c=l,u=a("tool",c.toolCallId,c.subagentRunId??void 0,"TOOL_CALL_CHUNK","tool call"),m=r.get(u),w=[],p;if(m?.kind==="tool"&&(c.toolCallId===void 0||c.toolCallId===m.fields.toolCallId))p=m.fields;else{if(w.push(...o(u)),c.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(c.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");p={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"tool",fields:p});let h=Qn({type:b.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TOOL_CALL_START",h,{toolCallId:c.toolCallId,toolCallName:c.toolCallName})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TOOL_CALL_ARGS",g,{toolCallId:p.toolCallId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.REASONING_MESSAGE_CHUNK:{let c=l,u=a("reasoning",c.messageId,c.subagentRunId??void 0,"REASONING_MESSAGE_CHUNK","reasoning message"),m=r.get(u),w=[],p;if(m?.kind==="reasoning"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"reasoning",fields:p});let h=Qn({type:b.REASONING_MESSAGE_START,messageId:c.messageId,role:"reasoning",...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","REASONING_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}}return l.type,[]}),hn(()=>{i()}))};function av(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function eh(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.join(", ")}`);return t.map(s=>{let a=e[s.id],l={interruptId:s.id,status:a.status};return a.status==="resolved"&&a.payload!==void 0&&(l.payload=a.payload),a.metadata!==void 0&&(l.metadata=a.metadata),l})}var kr=class{runNext(t,e){return e.run(t).pipe(Bi(!1))}runNextWithState(t,e){let n=J(t.messages||[]),r=J(t.state||{}),o=new zo;return Ju(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(ni(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:J(n),state:J(r)})))}},lv=class extends kr{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function cv(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var dv=class extends kr{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(cv)};return this.runNext(o,e)}},Vu="THINKING_START",ju="THINKING_END",qu="THINKING_TEXT_MESSAGE_START",Wu="THINKING_TEXT_MESSAGE_CONTENT",Xu="THINKING_TEXT_MESSAGE_END",uv=class extends kr{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Lt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Vu:{this.currentReasoningId=Ie();let{title:e,...n}=t;return this.warnAboutTransformation(Vu,b.REASONING_START),{...n,type:b.REASONING_START,messageId:this.currentReasoningId}}case qu:return this.currentMessageId=Ie(),this.warnAboutTransformation(qu,b.REASONING_MESSAGE_START),{...t,type:b.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Wu:{let{delta:e,...n}=t;return this.warnAboutTransformation(Wu,b.REASONING_MESSAGE_CONTENT),{...n,type:b.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ie(),delta:e}}case Xu:{let e=this.currentMessageId??Ie();return this.warnAboutTransformation(Xu,b.REASONING_MESSAGE_END),{...t,type:b.REASONING_MESSAGE_END,messageId:e}}case ju:{let e=this.currentReasoningId??Ie();return this.warnAboutTransformation(ju,b.REASONING_END),{...t,type:b.REASONING_END,messageId:e}}default:return t}}};function hv(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pv(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function fv(t){let e=hv(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function mv(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pv(r)?fv(r):r);return{...t,content:n}}var gv=class extends kr{run(t,e){let n={...t,messages:t.messages.map(mv)};return this.runNext(n,e)}},Yu="SUBAGENT_STARTED",Ku="SUBAGENT_FINISHED",Zu="SUBAGENT_ERROR";function Vi(t){if(t&&typeof t=="object"&&"subagentRunId"in t){let{subagentRunId:e,...n}=t;return n}return t}function Qu(t){return t.map(e=>Vi(e))}var bv=class extends kr{warnDroppedLifecycleEvent(t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${t} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){let n={...t,messages:(t.messages??[]).map(r=>Vi(r))};return this.runNext(n,e).pipe(oi(r=>{let o=r.type;(o===Yu||o===Ku||o===Zu)&&this.warnDroppedLifecycleEvent(o)}),Ea(r=>{let o=r.type;return o!==Yu&&o!==Ku&&o!==Zu}),Lt(r=>{let o=Vi(r);if(o.type===b.MESSAGES_SNAPSHOT){let i=o;if(Array.isArray(i.messages))return{...i,messages:Qu(i.messages)}}if(o.type===b.RUN_FINISHED){let i=o;if(i.outcome&&Array.isArray(i.outcome.interrupts))return{...i,outcome:{...i.outcome,interrupts:i.outcome.interrupts.map(s=>Vi(s))}}}if(o.type===b.RUN_STARTED){let i=o;if(i.input&&Array.isArray(i.input.messages))return{...i,input:{...i.input,messages:Qu(i.input.messages)}}}return o}))}},vv="0.0.59",yv=class{get maxVersion(){return vv}get debug(){return this._debug}set debug(t){this._debug=$i(t),this._debugLogger=za(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?za($i(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??Rt(),this.messages=J(r??[]),this.state=J(o??{}),this._debug=$i(i),this._debugLogger=za(this._debug),Zn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new dv),Zn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new uv),Zn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new gv),Zn(this.maxVersion,"0.0.57")<=0&&this.middlewares.unshift(new bv)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new lv(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:u=>c.run(u,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),hn(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new la}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>ti(()=>this.connect(n)),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.isRunning=!1,l instanceof la?Fo:this.onError(n,l,i))),hn(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Ju(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=J(this.messages);for(let r of e)r.subagentRunId===null&&delete r.subagentRunId;let n=e.filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Rt(),tools:J(t?.tools??[]),context:J(t?.context??[]),forwardedProps:J(t?.forwardedProps??{}),state:J(this.state),messages:n,...t?.resume===void 0?{}:{resume:J(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new j(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(av(i))throw new j(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let r of n.messages)r.subagentRunId===null&&delete r.subagentRunId;t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})}n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}}onError(t,e,n){return un(ne(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Lt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=J(this.messages),t.state=J(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=J(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=J(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=J(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Rt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Bi(this.debugLogger),Fa(this.debugLogger),rv(this.threadId,e.runId,this.agentId),n=>n.pipe(Lt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}};function wv(t){if(!Array.isArray(t.messages))return t;let e=!1,n=t.messages.map(r=>{if(r.subagentRunId===null){e=!0;let o={...r};return delete o.subagentRunId,o}return r});return e?{...t,messages:n}:t}var th=class extends yv{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(wv(t)),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=J(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Vb(Fb(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=J(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var xv=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function nh(t,e){let n=[];return{text:t.replace(xv,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Ev(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function Va(t){return Array.isArray(t)?t.filter(Ev):[]}var ji=["top-left","top-right","bottom-left","bottom-right"];function rh(t){return ji.includes(t)}function ja(t){return[{name:"read_chat_surface",description:"Describe the chat panel you are speaking from: its placement, whether it is collapsed, whether it can be moved, and the box it occupies. Read this before moving or minimising yourself, since a full-screen panel has nowhere to move to. Read-only.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the chat's own position"},handler:()=>t.describeSurface()},{name:"move_chat",description:"Move your own panel to a corner, to uncover something the user needs to see. `corner` is top-left, top-right, bottom-left or bottom-right. Answers `moved: false` with a reason when the placement owns its position or the panel fills the screen; check `read_chat_surface` first, and prefer minimise_chat when there is nowhere to move to.",parameters:{type:"object",properties:{corner:{type:"string",enum:[...ji]}},required:["corner"],[xe]:"Move the chat out of the way"},handler:e=>{let n=String(e.corner??""),r=t.describeSurface();return rh(n)?r.movable?{moved:t.moveTo(n,{announce:!0}),corner:n}:{moved:!1,reason:r.fullBleed?"the panel fills the screen, so there is nowhere to move it to":r.draggable===!1?"this page has turned off moving the panel":`the "${r.placement??""}" placement owns the panel's position`,suggestion:r.collapsible?"minimise_chat":null}:{moved:!1,reason:`"${n}" is not a corner; use one of ${ji.join(", ")}`}}},{name:"minimise_chat",description:"Collapse your own panel to its launcher, so the user can see the whole page. The launcher stays visible and reopens it. Answers `minimised: false` when the placement has no collapsed state, which is the case for a full-page chat.",parameters:{type:"object",properties:{},required:[],[xe]:"Minimise the chat"},handler:()=>t.describeSurface().collapsible?(t.setCollapsed(!0,{announce:!0}),{minimised:!0}):{minimised:!1,reason:"this placement has no collapsed state, so there is no launcher to return to"}},{name:"restore_chat",description:"Open your own panel again after minimising it.",parameters:{type:"object",properties:{},required:[],[xe]:"Restore the chat"},handler:()=>(t.setCollapsed(!1),{restored:!0})}]}var Ir=class{#t=new Map;register(e){this.#t.set(e.name,e)}has(e){return this.#t.has(e)}get(e){let n=this.#t.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#t.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function qa(t){return t[hr]===!0}function qi(t){return t[pr]===!0}var _v="#4f46e5";function Jn(t,e,n){let r=window.getComputedStyle(t).getPropertyValue(e).trim();return r===""?n:r}var Tv=4;function Wa(t,e={}){let n=document.createElement("div");n.setAttribute("data-ag-ui-highlight",""),n.setAttribute("aria-hidden","true"),n.style.cssText=["position: fixed","inset: 0","pointer-events: none",`z-index: ${Jn(t,"--ag-ui-highlight-z-index",String(Yc))}`].join(";");let r=document.createElement("div"),o=document.createElement("div");n.className="ag-ui-highlight",r.className="ag-ui-highlight-scrim",o.className="ag-ui-highlight-ring",e.scrim===!0&&n.append(r),n.append(o);let i=e.ringWidth??Number.parseFloat(Jn(t,"--ag-ui-highlight-ring-width","3")),s=e.flowMs??Number.parseFloat(Jn(t,"--ag-ui-highlight-flow-ms","2400")),a=()=>{let u=t.getBoundingClientRect(),m=e.padding??Tv,w=e.radius??Number.parseFloat(getComputedStyle(t).borderRadius),p=u.left-m,h=u.top-m,g=u.width+m*2,x=u.height+m*2;e.scrim===!0&&(r.style.cssText=["position: absolute","inset: 0",`background: ${Jn(t,"--ag-ui-highlight-scrim","rgba(15, 15, 25, 0.45)")}`,`clip-path: path(evenodd, '${kv(p,h,g,x,w+m)}')`].join(";")),o.style.cssText=["position: absolute",`left: ${p}px`,`top: ${h}px`,`width: ${g}px`,`height: ${x}px`,`border-radius: ${w+m}px`,`border: ${i}px solid transparent`,"box-sizing: border-box",Av(t,e)].join(";")};a();let l=null;e.gradient===!0&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(l=o.animate([{backgroundPosition:"100% 0"},{backgroundPosition:"-100% 0"}],{duration:s,iterations:Number.POSITIVE_INFINITY,easing:"linear"}));let c={capture:!0,passive:!0};return window.addEventListener("scroll",a,c),window.addEventListener("resize",a,c),document.body.appendChild(n),()=>{window.removeEventListener("scroll",a,c),window.removeEventListener("resize",a,c),l?.cancel(),n.remove()}}function Sv(t){return t===void 0?null:CSS.supports("color",t)?t:null}function Av(t,e){let n=Sv(e.color)??Jn(t,"--ag-ui-accent",_v);if(e.gradient!==!0)return`border-color: ${n}`;let r=Jn(t,"--ag-ui-highlight-gradient",`linear-gradient(115deg, transparent 20%, ${n} 50%, transparent 80%)`),o="linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)";return[`background-image: ${r}`,"background-origin: border-box","background-size: 300% 100%",`-webkit-mask: ${o}`,`mask: ${o}`,"-webkit-mask-composite: xor","mask-composite: exclude","background-position: 50% 0"].join(";")}function kv(t,e,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2)),s=t+n,a=e+r,l=`M 0 0 H ${window.innerWidth} V ${window.innerHeight} H 0 Z`,c=[`M ${t+i} ${e}`,`H ${s-i}`,`A ${i} ${i} 0 0 1 ${s} ${e+i}`,`V ${a-i}`,`A ${i} ${i} 0 0 1 ${s-i} ${a}`,`H ${t+i}`,`A ${i} ${i} 0 0 1 ${t} ${a-i}`,`V ${e+i}`,`A ${i} ${i} 0 0 1 ${t+i} ${e}`,"Z"].join(" ");return`${l} ${c}`}function Wi(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Iv=Wi(HTMLInputElement.prototype,"value"),Rv=Wi(HTMLTextAreaElement.prototype,"value"),Cv=Wi(HTMLSelectElement.prototype,"value"),Nv=Wi(HTMLInputElement.prototype,"checked");function mn(t,e){t instanceof HTMLTextAreaElement?Rv.call(t,e):t instanceof HTMLSelectElement?Cv.call(t,e):Iv.call(t,e)}function Rr(t,e){Nv.call(t,e)}var Xa="#4f46e5",Ov="rgba(79, 70, 229, 0.4)",Mv="--ag-ui-accent";function er(t){return new Promise(e=>{setTimeout(e,t)})}function Xi(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ya(t){return t<=0||Xi()?Promise.resolve():er(t)}function Yi(t,e){let n=window.getComputedStyle(t).getPropertyValue(Mv).trim();return n===""?e:n}function oh(t){return`0 0 0 3px ${Yi(t,Ov)}`}async function Ka(t,e,n={}){let r=n.charDelayMs??35;mn(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)mn(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await er(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Za(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await er(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var Lv=600,Pv=100;function _t(t,e={}){let n=Xi();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??Lv)};o=setTimeout(i,Pv),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var Dv=1200,Uv=1/3;async function ih(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??Dv;if(r<=0)return;if(e.scrim===!0||e.gradient===!0){let c=Wa(t,{scrim:e.scrim===!0,gradient:e.gradient===!0,...e.color===void 0?{}:{color:e.color},...e.ringPadding===void 0?{}:{padding:e.ringPadding}});await er(r),c();return}let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Yi(t,Xa);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Xi()?0:Math.round(r*Uv);await er(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await er(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function Hv(t,e={}){return ih(t,e,!1)}function Qa(t,e={}){return ih(t,e,!0)}async function Ja(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=oh(t),await Ya(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Gv(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function el(t,e,n={}){let r=Gv(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await Ya(o),mn(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function tl(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=oh(t),await Ya(r),Rr(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var Nr={SCROLL:"scroll",DRAG:"drag",CHAT:"chat"};function nl(t,e){let n=[];return t.has(Nr.SCROLL)&&n.push(zv(e)),t.has(Nr.DRAG)&&n.push(Fv(e)),n}function zv(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[xe]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return _t(r),{scrolled:!0,target:n}}}}function Fv(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[xe]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return $v(o,i),{dragged:!0,from:n,to:r}}}}function $v(t,e){let n=new DataTransfer;Cr(t,"dragstart",n),Cr(e,"dragenter",n),Cr(e,"dragover",n),Cr(e,"drop",n),Cr(t,"dragend",n)}function Cr(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function rl(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ki(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[xe]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[hr]:!0,[xe]:`Update ${t.name}`},handler:r=>n(r)}),e}var Bv=Ki;function ol(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary,s=r.description;typeof o=="string"&&typeof i=="string"&&(e[o]=typeof s=="string"?{name:o,summary:i,description:s}:{name:o,summary:i})}return e}var sh=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Vv(t){return[...t.matchAll(sh)].map(e=>e[0].slice(1))}function jv(t,e,n){let r={...n};return{path:e.replace(sh,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function qv(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function il(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[xe]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Vv(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[pr]:!0,[xe]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(u=>u.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=jv(o.id,o.path,i),l=qv(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ae={title:"Assistant",chatHistory:"Chat history",closeHistory:"Close history",searchConversations:"Search conversations",queued:"Waiting to send",removeQueued:'Do not send "{text}"',noMatches:"No conversations match that.",chatMoved:"Moved this panel out of the way",chatMinimised:"Minimised this panel",undo:"Undo",newChat:"New chat",collapse:"Collapse",expand:"Expand",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",jumpToLatest:"Jump to latest",announceResponding:"Assistant is responding",announceAnswerReady:"Assistant answered",announceAwaitingDecision:"{count} action is waiting for your approval",announceStopped:"Response stopped",announceFailed:"The response failed",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",historyReplaced:"The server replaced this conversation's history. Reload to see the updated transcript.",chartUndrawable:"A chart could not be drawn from the data sent, so it was removed.",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",runInterrupted:"The previous response didn\u2019t finish \u2014 the page changed before it arrived.",pageMoved:"The page changed since you last looked at it. Call read_page to see the current page, then retry.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",notConnected:"This chat isn\u2019t connected to an agent, so the message wasn\u2019t sent.",continueNeedsTurn:"Type the next turn in the composer first, then pick a run to continue.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",recordingLimit:"Stopped at the {n}-minute limit \u2014 transcribing what was recorded.",toolRunning:"running\u2026",toolDeferred:"waiting for you",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",subAgentWorking:"Working\u2026",subAgentDelegatedTo:"Delegated to {agent}",subAgentFinished:"{agent} finished",subAgentFailed:"The sub-agent failed",subAgentSteps:"Steps the sub-agent took",approvalEditArgs:"Edit the arguments before approving",approvalArgsInvalid:"That is not valid JSON, so nothing was sent.",approvalArgsNotAnObject:"Arguments have to be a JSON object.",suggestions:"Suggested follow-ups",messageActions:"Message actions",quoteSelection:"Quote",copyMessage:"Copy message",retryMessage:"Try again",feedbackUp:"Good answer",feedbackDown:"Poor answer",confirmAction:"Confirm action",confirmAlways:"Always allow",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function sl(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function ah(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function al(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=Wv(e,n,r),l=document.createElement("div");l.className="approval-actions",l.setAttribute("part","approval-actions");let c=ah("deny",r.deny),u=ah("approve",r.approve),m=!1,w=p=>{m||(m=!0,c.disabled=!0,u.disabled=!0,i.setAttribute("data-resolved",p?"approved":"denied"),o(p))};if(c.addEventListener("click",()=>w(!1)),u.addEventListener("click",()=>{a!==null&&!a.commit()||w(!0)}),n.signal?.addEventListener("abort",()=>w(!1),{once:!0}),l.append(c,u),i.append(s,...a===null?[]:[a.root],l),t.appendChild(i),n.signal?.aborted===!0){w(!1);return}u.focus()})}function Wv(t,e,n){let{onEdit:r}=e;if(r===void 0||t.args===void 0)return null;let o=JSON.stringify(t.args,null,2),i=document.createElement("div");i.className="approval-edit",i.setAttribute("part","approval-edit");let s=document.createElement("textarea");s.className="approval-args",s.setAttribute("part","approval-args"),s.setAttribute("aria-label",n.approvalEditArgs),s.rows=Math.min(10,o.split(`
12
12
  `).length),s.value=o;let a=document.createElement("div");return a.className="approval-error",a.setAttribute("part","approval-error"),a.setAttribute("role","alert"),a.hidden=!0,i.append(s,a),{root:i,commit:()=>{if(s.value===o)return!0;let l;try{l=JSON.parse(s.value)}catch{return a.textContent=n.approvalArgsInvalid,a.hidden=!1,s.focus(),!1}return typeof l!="object"||l===null||Array.isArray(l)?(a.textContent=n.approvalArgsNotAnObject,a.hidden=!1,s.focus(),!1):(a.hidden=!0,r(l),!0)}}}function ll(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(Xv(r,e)))}}function Xv(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{Yv(n).then(o=>{Kv(r,o?e.copied:e.copyFailed,e)})}),r}async function Yv(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function Kv(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function cl(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(Zv(n));return e}function Zv(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.innerHTML=dl(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=Zi(t.size),e.append(n,r,o),e}function dl(t){return t.startsWith("image/")?jc:t==="application/pdf"?qc:t.startsWith("text/")?Wc:Vc}function Zi(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var Qi=class{element;#t;#n;#e=[];constructor(e){this.#t=e,this.#n=e.strings??ae,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Ie(),file:e,status:Ge.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#e.push(n);let r=this.#s(e);if(r!==null){n.status=Ge.ERROR,n.error=r,this.#o(),this.#t.onChange?.();return}this.#o(),this.#t.onChange?.(),this.#r(n)}readyRefs(){let e=[];for(let n of this.#e)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#e.some(e=>e.status===Ge.UPLOADING)}pendingCount(){return this.#e.filter(e=>e.status===Ge.UPLOADING).length}isEmpty(){return this.#e.length===0}clearReady(){this.#e=this.#e.filter(e=>e.status===Ge.UPLOADING),this.#o()}clear(){for(let e of this.#e)e.controller?.abort();this.#e=[],this.#o()}dispose(){for(let e of this.#e)e.controller?.abort()}#s(e){return this.#t.maxBytes>0&&e.size>this.#t.maxBytes?this.#n.tooLarge.replace("{size}",Zi(this.#t.maxBytes)):Qv(this.#t.accept,e)?null:this.#n.fileTypeNotAllowed}#r(e){let n=this.#s(e.file);if(n!==null){e.status=Ge.ERROR,e.error=n,this.#o(),this.#t.onChange?.();return}e.status=Ge.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#o(),this.#t.upload(e.file,o=>{e.progress=o,this.#o()},r.signal).then(o=>{e.status=Ge.READY,e.ref=o}).catch(o=>{e.status=Ge.ERROR,e.error=o instanceof Error?o.message:this.#n.uploadFailed}).finally(()=>{e.controller=null,this.#o(),this.#t.onChange?.()})}#i(e){e.controller?.abort(),this.#e=this.#e.filter(n=>n!==e),this.#o(),this.#t.onChange?.()}#o(){this.element.replaceChildren(),this.element.hidden=this.#e.length===0;for(let e of this.#e)this.element.appendChild(this.#u(e))}#u(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.innerHTML=dl(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===Ge.ERROR?e.error:Zi(e.file.size),n.append(r,o,i),e.status===Ge.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Ge.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#n.retry,a.setAttribute("aria-label",this.#n.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#n.remove,s.setAttribute("aria-label",this.#n.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#i(e)),n.appendChild(s),n}};function Qv(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}var Jv="http://www.w3.org/2000/svg",$e={top:20,right:12,bottom:30,left:44},ey=480,ty=220,ny=220/480,ry=160,oy=320,lh=8,iy=5.6,ch=["var(--ag-ui-chart-1, #4f7cff)","var(--ag-ui-chart-2, #21b573)","var(--ag-ui-chart-3, #e0803c)","var(--ag-ui-chart-4, #b563d8)","var(--ag-ui-chart-5, #d84f6e)","var(--ag-ui-chart-6, #3ba7c4)"];function gn(t){return ch[t%ch.length]}function dh(t){let e=Math.max(ty,t),n=Math.min(oy,Math.max(ry,Math.round(e*ny)));return{width:e,height:n,plotW:e-$e.left-$e.right,plotH:n-$e.top-$e.bottom}}function mt(t,e){let n=document.createElementNS(Jv,t);for(let[r,o]of Object.entries(e))n.setAttribute(r,String(o));return n}function uh(t,e){let n=mt("text",{"font-size":10,fill:"currentColor","fill-opacity":.65,...e});return n.textContent=t,n}function sy(t){let e=[];return t.labels.forEach((n,r)=>{let o=0;for(let i of t.series)o+=i.points[r]??0,e.push(o)}),e}function ay(t){let e=t.kind==="stacked"?sy(t):t.series.flatMap(o=>[...o.points]),n=Math.max(0,...e),r=Math.min(0,...e);return n===r?{min:r,max:n+1}:{min:r,max:n}}function bn(t,e,n,r){return $e.top+r.plotH-(t-e)/(n-e)*r.plotH}function ul(t,e,n){let r=n.plotW/e;return $e.left+r*t+r/2}function ly(t,e){let n=e.plotW/t.length,r=Math.max(...t.map(o=>o.length))*iy;return Math.max(1,Math.ceil(r/n))}function cy(t,e,n,r,o){for(let s of[r,o]){let a=bn(s,r,o,n);t.appendChild(mt("line",{x1:$e.left,y1:a,x2:n.width-$e.right,y2:a,stroke:"currentColor","stroke-opacity":s===r?.35:.12})),t.appendChild(uh(String(Math.round(s)),{x:$e.left-6,y:a+4,"text-anchor":"end"}))}let i=ly(e.labels,n);e.labels.forEach((s,a)=>{a%i===0&&t.appendChild(uh(s,{x:ul(a,e.labels.length,n),y:n.height-$e.bottom+16,"text-anchor":"middle"}))})}function dy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7/e.series.length,a=bn(r,r,o,n);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=bn(u,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15+s*c,y:w,width:s,height:Math.max(1,a-w),fill:gn(c),rx:2}))})})}function uy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7,a=e.labels.map(()=>0);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=a[m]??0,p=w+u;a[m]=p;let h=bn(p,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15,y:h,width:s,height:Math.max(1,bn(w,r,o,n)-h),fill:gn(c)}))})})}function hy(t,e,n,r,o){e.series.forEach((i,s)=>{let a=i.points.map((l,c)=>`${ul(c,e.labels.length,n)},${bn(l,r,o,n)}`).join(" ");t.appendChild(mt("polyline",{points:a,fill:"none",stroke:gn(s),"stroke-width":2,"stroke-linejoin":"round"}))})}function py(t,e,n,r,o){e.series.forEach((i,s)=>{i.points.forEach((a,l)=>{t.appendChild(mt("circle",{cx:ul(l,e.labels.length,n),cy:bn(a,r,o,n),r:4,fill:gn(s),"fill-opacity":.85}))})})}function fy(t,e,n){let r=e.reduce((l,c)=>l+c,0),o=n.width/2,i=$e.top+n.plotH/2,s=Math.min(n.plotW,n.plotH)/2;if(r===0){t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:"none",stroke:"currentColor","stroke-opacity":.3}));return}let a=-Math.PI/2;e.forEach((l,c)=>{let u=l/r*Math.PI*2,m=a+u;if(u>=Math.PI*2)t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:gn(c)}));else{let w=o+s*Math.cos(a),p=i+s*Math.sin(a),h=o+s*Math.cos(m),g=i+s*Math.sin(m),x=u>Math.PI?1:0;t.appendChild(mt("path",{d:`M ${o} ${i} L ${w} ${p} A ${s} ${s} 0 ${x} 1 ${h} ${g} Z`,fill:gn(c)}))}a=m})}function hh(t,e){let n=mt("svg",{viewBox:`0 0 ${e.width} ${e.height}`,width:"100%",role:"img"});if(n.setAttribute("aria-label",t.title??`${t.kind} chart`),t.kind==="pie"){let i=t.series[0];return fy(n,i.points.map(s=>Math.max(0,s)),e),n}let{min:r,max:o}=ay(t);return cy(n,t,e,r,o),t.kind==="bar"?dy(n,t,e,r,o):t.kind==="stacked"?uy(n,t,e,r,o):t.kind==="line"?hy(n,t,e,r,o):py(n,t,e,r,o),n}function my(t){if(t.length<2)return null;let e=document.createElement("div");return e.className="chart-legend",e.setAttribute("part","chart-legend"),t.forEach((n,r)=>{let o=document.createElement("span");o.className="chart-legend-item";let i=document.createElement("span");i.className="chart-legend-swatch",i.style.background=gn(r),o.append(i,document.createTextNode(n)),e.appendChild(o)}),e}function gy(t,e){new ResizeObserver(()=>{e(Math.round(t.clientWidth/lh)*lh)}).observe(t)}function Or(t){if(t.labels.length===0||t.series.length===0)return null;let e=document.createElement("div");if(e.className="chart-block",e.setAttribute("part","chart-block"),t.title!==void 0&&t.title!==""){let i=document.createElement("div");i.className="chart-title",i.setAttribute("part","chart-title"),i.textContent=t.title,e.appendChild(i)}let n=ey,r=hh(t,dh(n));e.appendChild(r);let o=my(t.kind==="pie"?t.labels:t.series.map(i=>i.label));return o!==null&&e.appendChild(o),gy(e,i=>{if(i===n)return;n=i;let s=hh(t,dh(n));r.replaceWith(s),r=s}),e}var by=["bar","line","pie","scatter","stacked"];function vy(t){return by.includes(t)?t:"bar"}function yy(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="number"||!Number.isFinite(n)||Math.abs(n)>1e15)return null;e.push(n)}return e}function wy(t){if(!Array.isArray(t))return null;for(let e=0;e<t.length;e+=1)if(typeof t[e]!="string")return null;return t}function tr(t){if(typeof t!="object"||t===null)return null;let e=t,n=wy(e.labels);if(n===null||!Array.isArray(e.series))return null;let r=[];for(let s of e.series){if(typeof s!="object"||s===null)return null;let a=s,l=yy(a.points);if(l===null||l.length!==n.length)return null;r.push({label:typeof a.label=="string"?a.label:"",points:l})}if(r.length===0||r.length*n.length>2e4||n.length>2e3)return null;let o=vy(e.kind),i=e.title;return typeof i=="string"?{kind:o,title:i,labels:n,series:r}:{kind:o,labels:n,series:r}}var Ji="render_chart";function xy(t){let e=tr(t);return e===null?null:Or(e)}function Ey(t){let e=tr(t);return e!==null&&e.labels.length>0&&e.series.length>0}var _y="chart not rendered: expected labels (strings) and series, each with one finite number per label";function ph(){return{name:Ji,description:"Show a chart in the conversation. Supply the data and the page draws it. Every series must have exactly one point per label.",parameters:{type:"object",properties:{kind:{type:"string",enum:["bar","line","pie","scatter","stacked"]},title:{type:"string"},labels:{type:"array",items:{type:"string"}},series:{type:"array",items:{type:"object",properties:{label:{type:"string"},points:{type:"array",items:{type:"number"}}},required:["points"]}}},required:["labels","series"],"x-summary":"Draw a chart"},handler:t=>Ey(t)?"chart rendered":_y,render:xy}}function Mr(t,e=Date.now(),n=ae){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}function fh(t){return t.preview!==void 0&&t.preview!==null&&t.preview!==""?t.preview:null}function mh(t){return t.replace(/\s+/g," ").trim()}var Lr=class{element;#t;#n;#e;#s=null;#r=null;#i;#o=[];constructor(e,n=ae){this.#t=e,this.#i=n,this.element=document.createElement("div"),this.element.className="checkpoints",this.element.setAttribute("part","checkpoints"),this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-label",n.checkpoints),this.element.tabIndex=-1,this.element.hidden=!0;let r=document.createElement("div");r.className="checkpoints-header",r.setAttribute("part","checkpoints-header"),this.#e=document.createElement("span"),this.#e.className="checkpoints-title",this.#e.setAttribute("part","checkpoints-title"),this.#e.textContent=n.checkpoints,r.append(this.#e),this.#n=document.createElement("div"),this.#n.className="checkpoints-list",this.#n.setAttribute("part","checkpoints-list"),this.element.append(r,this.#n),this.element.addEventListener("keydown",o=>this.#c(o))}setRuns(e){this.#o=e,this.#d()}setRelativeTimeFormatter(e){this.#r=e}#u(e){return this.#r!==null?this.#r(e):Mr(e,Date.now(),this.#i)}setStrings(e){this.#i=e,this.element.setAttribute("aria-label",e.checkpoints),this.#e.textContent=e.checkpoints,this.#d()}open(){this.open_||(this.#s=this.#h(),this.element.hidden=!1,(this.#l()[0]??this.element).focus())}close(){this.open_&&(this.element.hidden=!0,this.#s?.focus(),this.#s=null)}#h(){return this.element.getRootNode().activeElement}#l(){return Array.from(this.element.querySelectorAll("button, [tabindex]")).filter(e=>!e.hidden)}#c(e){if(e.key==="Escape"){e.stopPropagation(),this.close();return}if(e.key!=="Tab")return;let n=this.#l(),r=n[0],o=n[n.length-1],i=this.#h();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}get open_(){return!this.element.hidden}#d(){if(this.#n.replaceChildren(),this.#o.length===0){let n=document.createElement("div");n.className="checkpoints-empty",n.setAttribute("part","checkpoints-empty"),n.textContent=this.#i.noCheckpoints,this.#n.append(n);return}let e=this.#p();for(let n of this.#o)this.#n.append(this.#y(n,e))}#p(){let e=new Set,n=new Set;for(let r of this.#o){let o=fh(r);if(o===null)continue;let i=mh(o);e.has(i)&&n.add(i),e.add(i)}return n}#y(e,n){let r=document.createElement("div");r.className="checkpoint-row",r.setAttribute("part","checkpoint-row");let o=fh(e),i=e.started_at===null?null:this.#u(Date.parse(e.started_at)),s=document.createElement("span");if(s.className="checkpoint-label",s.setAttribute("part","checkpoint-label"),s.textContent=o??i??e.run_id,r.append(s),o!==null&&i!==null){let l=document.createElement("span");l.className="checkpoint-time",l.setAttribute("part","checkpoint-time"),l.textContent=i,r.append(l)}if((o===null?i!==null:n.has(mh(o)))&&e.run_id!==""){let l=document.createElement("span");l.className="checkpoint-id",l.setAttribute("part","checkpoint-id"),l.textContent=e.run_id.slice(0,8),l.title=e.run_id,r.append(l)}if(e.parent_run_id!==null){let l=document.createElement("span");l.className="checkpoint-branch",l.setAttribute("part","checkpoint-branch"),l.textContent=this.#i.forkedRun,l.title=e.parent_run_id,r.append(l)}return r.append(this.#m(e.run_id,"resume",this.#i.resumeRun),this.#m(e.run_id,"fork",this.#i.forkRun)),r}#m(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`checkpoint-action checkpoint-${n}`,o.setAttribute("part",`checkpoint-action checkpoint-${n}`),o.textContent=r,o.addEventListener("click",()=>{this.close(),this.#t(e,n)}),o}};function Dt(t,e,n=Je){let r=Math.min(n,Math.max(0,(e.width-t.width)/2)),o=Math.min(n,Math.max(0,(e.height-t.height)/2));return{left:Math.max(e.left+r,Math.min(t.left,e.left+e.width-t.width-r)),top:Math.max(e.top+o,Math.min(t.top,e.top+e.height-t.height-o))}}function Pr(t,e,n=Bt){let r=t.right-t.left,o=t.bottom-t.top,i=Math.max(e.left+n,Math.min(t.left,e.left+e.width-n-r)),s=Math.max(e.top+n,Math.min(t.top,e.top+e.height-n-o));return{left:i,top:s,right:i+r,bottom:s+o}}function hl(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function pl(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2),a.hidden=Object.keys(e.args).length===0;let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=hl("cancel",r.cancel),u=n.onAlwaysAllow===void 0?null:hl("always",r.confirmAlways.replace("{tool}",e.toolName)),m=hl("confirm",r.confirm),w=!1,p=h=>{w||(w=!0,i.remove(),o(h))};if(c.addEventListener("click",()=>p(!1)),m.addEventListener("click",()=>p(!0)),u?.addEventListener("click",()=>{n.onAlwaysAllow?.(),p(!0)}),n.signal?.addEventListener("abort",()=>p(!1),{once:!0}),l.append(c,...u===null?[]:[u],m),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){p(!1);return}m.focus()})}var Ty=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DD","DIV","DL","DT","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","HR","MAIN","NAV","OL","P","SECTION","UL"]);function es(t){let e=t.cloneNode(!0);for(let n of Array.from(e.querySelectorAll("button")))n.remove();return{text:ky(gh(e)),html:e.innerHTML}}function gh(t){if(t.nodeType===Node.TEXT_NODE)return t.nodeValue.replace(/\s+/g," ");if(t.nodeType!==Node.ELEMENT_NODE)return"";let e=t,n=e.tagName;if(n==="BR")return`
13
13
  `;if(n==="PRE")return`
14
14
 
@@ -3663,9 +3663,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
3663
3663
  border-right: none;
3664
3664
  box-shadow: none;
3665
3665
  }
3666
- `;var ps=class{element;get agent(){return this.#r}#t;#n;#e;#s=new Map;#r=null;constructor(e=ae){this.element=document.createElement("div"),this.element.className="subagent",this.element.setAttribute("part","subagent"),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="subagent-row",this.#t.setAttribute("part","subagent-row"),this.#t.setAttribute("aria-expanded","false"),this.#t.disabled=!0;let n=document.createElement("span");n.className="subagent-icon",n.setAttribute("part","subagent-icon"),n.setAttribute("aria-hidden","true"),this.#n=document.createElement("span"),this.#n.className="subagent-status",this.#n.setAttribute("part","subagent-status"),this.#n.textContent=e.subAgentWorking,this.#t.append(n,this.#n),this.#e=document.createElement("div"),this.#e.className="subagent-steps",this.#e.setAttribute("part","subagent-steps"),this.#e.setAttribute("role","list"),this.#e.setAttribute("aria-label",e.subAgentSteps),this.#e.hidden=!0,this.#t.addEventListener("click",()=>{this.#u(this.#t.getAttribute("aria-expanded")!=="true")}),this.element.append(this.#t,this.#e)}report(e){this.element.setAttribute("data-phase",e.phase),e.agent!==null&&(this.#r=e.agent,this.element.setAttribute("data-agent",e.agent)),e.status!==null&&(this.#n.textContent=e.status),e.tool!==null&&this.#i(e.tool)}#i(e){let n=this.#s.get(e.toolCallId)??this.#o(e);if(e.ok===null){n.removeAttribute("data-ok");return}n.setAttribute("data-ok",String(e.ok))}#o(e){let n=document.createElement("div");n.className="subagent-step",n.setAttribute("part","subagent-step"),n.setAttribute("role","listitem"),n.setAttribute("data-tool-call-id",e.toolCallId);let r=document.createElement("span");r.className="subagent-step-icon",r.setAttribute("part","subagent-step-icon"),r.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="subagent-step-name",o.setAttribute("part","subagent-step-name"),o.textContent=e.name,n.append(r,o),this.#e.appendChild(n),this.#s.set(e.toolCallId,n),this.#t.disabled=!1,n}#u(e){this.#e.hidden=!e,this.#t.setAttribute("aria-expanded",String(e))}};var Ux=Object.values(Cn);function bp(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function qr(t){return typeof t=="string"&&t!==""?t:null}function Hx(t){let e=bp(t);if(e===null)return null;let n=qr(e.toolCallId),r=qr(e.name),o=e.ok;return n===null||r===null||o!==null&&typeof o!="boolean"?null:{toolCallId:n,name:r,ok:o}}function vp(t){let e=bp(t);if(e===null)return null;let n=qr(e.delegationId),r=e.phase;return n===null||typeof r!="string"||!Ux.includes(r)?null:{delegationId:n,phase:r,agent:qr(e.agent),status:qr(e.status),tool:Hx(e.tool)}}var Gx=4,zx=120;function yp(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function fs(t,e,n){let r=yp(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let s=document.createElement("button");s.type="button",s.className="suggestion-chip",s.setAttribute("part","suggestion-chip"),s.textContent=i,s.addEventListener("click",()=>n(i)),o.appendChild(s)}return o}var ms=class{element;#t;#n;#e;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="thoughts-toggle",this.#e.setAttribute("part","thoughts-toggle"),this.#e.setAttribute("aria-expanded","true"),this.#t=document.createElement("span"),this.#t.className="thoughts-label",this.#t.setAttribute("part","thoughts-label"),this.#t.textContent=e.thinking,this.#e.append(this.#t),this.#n=document.createElement("pre"),this.#n.className="thoughts-body",this.#n.setAttribute("part","thoughts-body"),this.#e.addEventListener("click",()=>{this.#i(!this.#r)}),this.element.append(this.#e,this.#n)}stream(e){this.#n.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#t.textContent=this.#s.thoughts,this.#i(!0))}#i(e){this.#r=e,this.#n.hidden=e,this.#e.setAttribute("aria-expanded",String(!e))}};var Fx=8,gs=class{element;#t;#n;#e;#s;#r;#i=null;#o;#u=[];#h="";#l;#c;#d="";#p=!0;#y=null;constructor(e,n=ae){this.#t=e,this.#o=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#n=document.createElement("div"),this.#n.className="drawer-panel",this.#n.setAttribute("part","drawer-panel"),this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true"),this.#n.setAttribute("aria-label",n.chatHistory),this.#n.addEventListener("keydown",i=>this.#T(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#e=document.createElement("span"),this.#e.className="drawer-title",this.#e.setAttribute("part","drawer-title"),this.#e.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#t.onNew()}),this.#l=document.createElement("button"),this.#l.type="button",this.#l.className="drawer-close",this.#l.setAttribute("part","drawer-close"),this.#l.title=n.closeHistory,this.#l.setAttribute("aria-label",n.closeHistory),this.#l.append(document.createTextNode("\xD7")),this.#l.addEventListener("click",()=>this.close()),o.append(this.#e,this.#s,this.#l),this.#c=document.createElement("input"),this.#c.type="search",this.#c.className="drawer-filter",this.#c.setAttribute("part","drawer-filter"),this.#c.placeholder=n.searchConversations,this.#c.setAttribute("aria-label",n.searchConversations),this.#c.addEventListener("input",()=>{this.#d=this.#c.value.trim().toLowerCase(),this.#x()}),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#n.append(o,this.#c,this.#r),this.element.append(r,this.#n)}setRelativeTimeFormatter(e){this.#i=e}#m(e){return this.#i!==null?this.#i(e):Mr(e,void 0,this.#o)}setStrings(e){this.#o=e,this.#n.setAttribute("aria-label",e.chatHistory),this.#e.textContent=e.chats,this.#s.textContent=e.newChat,this.#l.title=e.closeHistory,this.#l.setAttribute("aria-label",e.closeHistory),this.#c.placeholder=e.searchConversations,this.#c.setAttribute("aria-label",e.searchConversations),this.#x()}setModal(e){this.#p=e,e?(this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true")):(this.#n.setAttribute("role","region"),this.#n.removeAttribute("aria-modal"))}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#y=this.#C(),this.element.hidden=!1,this.#p&&this.#s.focus(),this.#t.onVisibility?.(!0))}close(){this.isOpen()&&(this.element.hidden=!0,this.#p&&this.#y?.focus(),this.#y=null,this.#t.onVisibility?.(!1))}toggle(){this.isOpen()?this.close():this.open()}#C(){return this.element.getRootNode().activeElement}#T(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab"||!this.#p)return;let n=Array.from(this.#n.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#C();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#u=e,this.#h=n,this.#x()}#x(){this.#r.replaceChildren();let e=this.#u.length<Fx;this.#c.hidden=e,e&&this.#d!==""&&(this.#c.value="",this.#d="");let n=this.#G();if(n.length===0){let r=document.createElement("div");r.className="drawer-empty",r.setAttribute("part","drawer-empty"),r.textContent=this.#u.length===0?this.#o.noConversations:this.#o.noMatches,this.#r.appendChild(r);return}for(let r of n)this.#r.appendChild(this.#se(r))}#G(){return this.#d===""?this.#u:this.#u.filter(e=>e.title.toLowerCase().includes(this.#d)||e.preview.toLowerCase().includes(this.#d))}#se(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#h&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=this.#m(e.updatedAt);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#t.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#o.rename,a.setAttribute("aria-label",this.#o.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#z(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#o.delete,l.setAttribute("aria-label",this.#o.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#b(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#z(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#x():this.#t.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#x())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#b(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#o.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#o.delete,i.addEventListener("click",()=>this.#t.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#o.cancel,s.addEventListener("click",()=>this.#x()),r.append(o,i,s),e.replaceChildren(r)}};function Vl(t){return{[re.PENDING]:t.toolRunning,[re.DEFERRED]:t.toolDeferred,[re.DONE]:t.toolDone,[re.ERROR]:t.toolError,[re.DECLINED]:t.toolDeclined}}function $x(t){return{[re.DONE]:t.resultLabel,[re.ERROR]:t.errorLabel,[re.DECLINED]:t.declinedLabel}}function Bx(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var Wr=class{element;approvalSlot;subagentSlot;#t;#n;#e;#s;#r;#i;#o;args;#u;#h;#l=!1;constructor(e,n,r,o=ae,i={}){this.#o=o,this.args=n,this.#u=e,this.#h=i.formatPayload??null,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",re.PENDING),this.element.setAttribute("data-expanded","false");let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=r??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=Vl(o)[re.PENDING],this.#n=document.createElement("span"),this.#n.className="tool-call-decision",this.#n.setAttribute("part","tool-card-decision"),this.#n.hidden=!0,s.append(a,l,this.#t,this.#n);let c=this.#d("args",o.argumentsLabel);this.#c(c.body,{kind:"arguments",toolName:e,args:n},JSON.stringify(n,null,2)),c.root.hidden=Object.keys(n).length===0;let u=this.#d("result",o.resultLabel);this.#s=u.root,this.#r=u.label,this.#i=u.body,u.root.hidden=!0,this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="tool-call-toggle",this.#e.setAttribute("part","tool-card-toggle"),this.#e.setAttribute("aria-expanded","false"),this.#e.textContent=o.details,this.#e.addEventListener("click",()=>this.#y(!this.#p()));let m=document.createElement("div");m.className="tool-call-body",m.setAttribute("part","tool-card-body"),m.append(c.root,u.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.subagentSlot=document.createElement("div"),this.subagentSlot.className="tool-call-subagent",this.subagentSlot.setAttribute("part","tool-card-subagent"),this.element.append(s,this.subagentSlot,this.#e,m,this.approvalSlot)}mark(e){this.#l||(this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#n.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#n.hidden=!1}get settled(){return this.#l}settle(e,n){this.#l||(this.#l=!0,this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e],this.#r.textContent=$x(this.#o)[e],this.#c(this.#i,{kind:"result",toolName:this.#u,status:e,text:n},Bx(n)),this.#s.hidden=!1)}#c(e,n,r){let o=this.#h===null?null:this.#h(n);if(o===null){e.textContent=r;return}if(e.setAttribute("data-formatted","true"),typeof o=="string"){e.textContent=o;return}e.replaceChildren(o)}#d(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#p(){return this.element.getAttribute("data-expanded")==="true"}#y(e){this.element.setAttribute("data-expanded",String(e)),this.#e.setAttribute("aria-expanded",String(e))}};var wp=12e4,bs=class{element;#t;#n;#e;#s="idle";#r=null;#i=null;#o=[];#u=null;#h=!1;#l=!1;constructor(e){this.#t=e.transcribe,this.#n=e.onText,this.#e=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=Dc,this.element.append(n),this.#T("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#d();return}this.#s!=="transcribing"&&await this.#c()}async#c(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#C(this.#e.transcriptionFailed);return}this.#i=e,this.#o=[],this.#h=!1;let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#y(n.mimeType)}),this.#r=n,n.start(),this.#u=setTimeout(()=>{this.#h=!0,this.#d()},wp),this.#T("recording")}#d(){this.#p(),this.#r?.stop()}#p(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}dispose(){this.#l=!0,this.#p(),this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#m()}async#y(e){if(this.#l)return;this.#m(),this.#T("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#t(n);this.#T("idle"),this.#h&&(this.element.title=this.#e.recordingLimit.replace("{n}",String(wp/6e4))),r!==""&&this.#n(r)}catch(r){this.#C(r instanceof Error?r.message:this.#e.transcriptionFailed)}finally{this.#r=null}}#m(){for(let e of this.#i?.getTracks()??[])e.stop();this.#i=null}#C(e){this.#m(),this.#r=null,this.#T("idle"),this.element.title=e}#T(e){this.#s=e,this.element.dataset.state=e;let n=this.#x(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#x(e){return e==="recording"?this.#e.stopRecording:e==="transcribing"?this.#e.transcribing:this.#e.recordVoice}};var vs=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},sr=class{#t;#n;#e;#s;#r;#i;#o;#u=new Set;#h=new Map;#l;#c;#d=!1;constructor(e){this.#t=e.agent,this.#n=e.handlers,this.#e=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#i=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.maxToolRounds??Nn;this.#c=n>=1?Math.floor(n):Nn;let r=e.onStateChanged;r!==void 0&&this.#t.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#t.state}setState(e){this.#t.setState({...e})}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Ie(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#m(),await this.#p()}truncateToLastUser(){let e=[...this.#t.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#t.setMessages(r),this.#m(),r}async resume(){await this.#p()}addToolResult(e,n){this.#t.addMessage({id:Ie(),role:"tool",content:n,toolCallId:e}),this.#m()}cancel(){this.#d=!0,this.#t.abortRun()}async#p(){this.#d=!1;try{await this.#C(),this.#d&&this.#y()}catch(e){this.#d||Vx(e)?this.#y():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#y(){this.#m(),this.#n.onCancelled()}#m(){let e=this.#t.messages;if(this.#h.size===0){this.#o(e);return}this.#o(e.map(n=>{if(n.role!=="tool")return n;let r=this.#h.get(n.toolCallId);return r===void 0?n:{...n,outcome:r}}))}async#C(){let e;for(let n=0;n<this.#c;n+=1){if(this.#d)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#e(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#t.runAgent(i,this.#T(r,o)),e=void 0,this.#m(),this.#d)return;if(!o.terminal)throw new vs(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#i===null)return;let a=await this.#i(o.interrupts);if(this.#d)return;e=eh(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;l.outcome!==void 0&&this.#h.set(a.id,l.outcome),this.#t.addMessage({id:Ie(),role:"tool",content:l.content,toolCallId:a.id}),this.#m(),s=!0}}if(!s)return}}#T(e,n){let r=this.#n,o=this.#u,i=this.#h,s=()=>this.#d,a=new Set;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c)},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:u}){let m={id:l.toolCallId,name:c,args:u};e.push(m),r.onToolCall(m)},onToolCallResultEvent({event:l}){let c=l.outcome;typeof c=="string"&&i.set(l.toolCallId,c),r.onToolResult(l.toolCallId,l.content,c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(m=>m.id===l.messageId&&m.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){if(a.size!==0){for(let c of a){let u=l.find(m=>m.id===c);u!==void 0&&u.role==="activity"&&r.onActivityChanged(c,u.activityType,u.content)}a.clear()}},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!s()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Vx(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function jl(t){let e=t.attachments;return Array.isArray(e)?e.filter(jx):[]}function jx(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var xp="ag-ui-chat",ar="thread",ql="threads",Xr="messages:",ws="checkpoint:",Yr="minted:",qx=60,Wx=100,Xx="New conversation",Ep=!1;function bt(t,e){try{sessionStorage.setItem(t,e)}catch{if(Ep)return;Ep=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function ys(t){return t===""?xp:`${xp}@${t}`}var Ze=class t{#t;constructor(e=""){this.#t=ys(e),e!==""&&t.adopt("",e)}static adopt(e,n){let r=`${ys(e)}:`,o=`${ys(n)}:`;for(let[i,s]of _p(r)){let a=sessionStorage.getItem(i),l=o+s;a!==null&&sessionStorage.getItem(l)===null&&bt(l,a),sessionStorage.removeItem(i)}}static purge(e){for(let[n]of _p(`${ys(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#r(ar))??this.newThread()}newThread(){let e=Ie();return bt(this.#r(ar),e),bt(this.#r(Yr+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#r(Yr+e))!==null&&sessionStorage.getItem(this.#r(Xr+e))===null}loadMessages(e){return Promise.resolve(this.#i(this.#r(Xr+e)))}saveMessages(e,n){bt(this.#r(Xr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(Yr+e)),this.#n(e,n)}loadCheckpoint(e){return this.#i(this.#r(ws+e))}saveCheckpoint(e,n){let r=this.#r(ws+e);if(n===null){sessionStorage.removeItem(r);return}bt(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Xr+e)),sessionStorage.removeItem(this.#r(ws+e)),sessionStorage.removeItem(this.#r(Yr+e)),this.#s(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(ar))===e&&sessionStorage.removeItem(this.#r(ar))}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){bt(this.#r(ar),e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#n(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Kx(n),s=Date.now();o===void 0?r.push({threadId:e,title:Tp(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Tp(n))),this.#s(r)}#e(){return this.#i(this.#r(ql))??[]}#s(e){let n=this.#r(ql);if(e.length===0){sessionStorage.removeItem(n);return}bt(n,JSON.stringify(e))}#r(e){return`${this.#t}:${e}`}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function _p(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);Yx(o)&&e.push([r,o])}return e}function Yx(t){return t===ar||t===ql||t.startsWith(Xr)||t.startsWith(ws)||t.startsWith(Yr)}function Tp(t){for(let e of t)if(e.role==="user"){let n=Sp(e.content);if(n!=="")return Ap(n,qx)}return Xx}function Kx(t){for(let e of[...t].reverse()){let n=Sp(e.content);if(n!=="")return Ap(n,Wx)}return""}function Sp(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Ap(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Qe(t,e){return e===void 0?t:{...t,credentials:e}}function xs(t){if(t.newThread!==void 0)return t.newThread();let e=Ie();return t.setActiveThread(e),e}function Es(t,e,n,r){if(e.length===0)return;let o=new URL(String(t),location.href).origin;o===location.origin||n.includes(o)||r.has(o)||(r.add(o),console.warn(`<ag-ui-chat>: sending host credentials (${e.join(", ")}) to ${o}, which is not this page's origin (${location.origin}). Those headers are the page's own authentication, and whichever server answers the browser's preflight receives them \u2014 so a URL attribute built from a query parameter or from tenant-authored configuration is a channel for the token to leave on. If this destination is deliberate, name it in \`trustedOrigins\` to confirm it and silence this notice. Reported once per origin.`))}function Wl(t){let e=t.headers??{},n=new Set;return new th({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),s=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,s,t.trustedOrigins??[],n),i===void 0)return fetch(r,Qe(o,t.credentials));let a=new Headers(o?.headers);for(let[l,c]of Object.entries(i))a.set(l,c);return fetch(r,Qe({...o,headers:a},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var Kr=class{#t;#n;#e;#s;#r;#i=new Set;#o=new Map;constructor(e,n=()=>({}),r=new Ze,o=()=>{},i=!0){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r,this.#s=o,this.#r=i}threadId(){return this.#e.threadId()}setActiveThread(e){this.#e.setActiveThread(e)}newThread(){return xs(this.#e)}isUnsent(e){return this.#e.isUnsent?.(e)===!0}saveMessages(e,n){this.#e.saveMessages(e,this.#r?n:[])}loadCheckpoint(e){return this.#e.loadCheckpoint(e)}saveCheckpoint(e,n){this.#e.saveCheckpoint(e,n)}renameThread(e,n){this.#e.renameThread(e,n),this.#o.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#e.clear(e),this.#i.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#u();return e===null?this.#e.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){if(this.#e.isUnsent?.(e)===!0)return null;let n=await this.#c(`${this.#t}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#e.loadMessages(e);let r=await this.#h(n);return r===null?this.#e.loadMessages(e):r.messages??null}async#u(){let e=await this.#c(this.#t);if(e===null||!e.ok)return null;let n=await this.#h(e);return n===null?null:n.threads??[]}async#h(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Qe({headers:this.#n()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#n();try{await fetch(`${this.#t}${encodeURIComponent(e)}/`,Qe({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var Zr=class{#t;#n;#e;constructor(e,n=()=>({}),r=()=>{}){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r}async list(){try{let e=await fetch(this.#t,Qe({method:"GET",headers:{Accept:"application/json",...this.#n()}},this.#e()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#t.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};function _s(t){return t===It.FAILED?re.ERROR:t===It.DENIED?re.DECLINED:re.DONE}async function Xl(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Qe({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await Zx(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Zx(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Yl(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Qx(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Jx(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Qx(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Jx(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var eE=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],ec=["omit","same-origin","include"];function Kl(t){return ec.includes(t)}var kp="ag-ui-chat:collapsed",Ip="ag-ui-chat:size",Rp="ag-ui-chat:theme",Zl="ag-ui-chat:launcher";function tE(t){if(typeof t!="object"||t===null)return null;let{left:e,top:n}=t;return typeof e=="number"&&typeof n=="number"?{left:e,top:n}:null}var Cp=new Set([null,"","floating","bottom-left"]),nE=[{y:"top"},{y:"bottom"},{x:"left"},{x:"right"},{x:"left",y:"top"},{x:"right",y:"top"},{x:"left",y:"bottom"},{x:"right",y:"bottom"}],Ql=6,Jl=new Set,Qr=class extends HTMLElement{agentFactory=Wl;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>[...this.#At().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#r.tools()];getContext=()=>[...rl(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Ze;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#n=new Set;#e=ae;#s=new Set;#r=new Ir;#i=new Map;#o=new Map;#u=new Map;#h=new Map;#l=new Set;#c=new Map;#d=new Map;#p=new Set;#y=[];#m=new Set;#C=null;#T=new Set;#x;#G=document.createElement("div");#se=document.createElement("div");#z=document.createElement("button");#b=document.createElement("button");#je="";#ae=null;#Ie=document.createElement("div");#w;#K=null;#Re=!1;#E;#v;#a;#S;#Ce;#F;#R;#A;#qe=null;#P;#N;#O;#Ne;#$;#f;#B;#le=document.createElement("span");#Oe=0;#Z;#k=null;#_=null;#ce=[];#Q=[];#V=document.createElement("div");#J=null;#D=null;#ee=null;#te={x:"right",y:"bottom"};#xt=new Map;#de=()=>{this.#Dt(),!this.#cn()&&(this.#st(),this.#R.isOpen()&&(this.#R.setModal(!this.#dt()),this.#ut()))};#ln(e){let n=this.#M(),r=n.left+Je,o=n.top+Je,i=n.left+n.width-Je,s=n.top+n.height-Je;return{left:Math.min(Math.max(e.left,r),e.right),top:Math.min(Math.max(e.top,o),e.bottom),right:Math.max(Math.min(e.right,i),e.left),bottom:Math.max(Math.min(e.bottom,s),e.top)}}#cn(){return this.#f.hasAttribute("data-dragging")||this.#x.querySelector(".header[data-dragging]")!==null}#Me;#We=null;#ue=!1;#ne=null;#he={};#W=!1;#Xe=null;#U=null;#Le=null;#Ye=0;#Pe="";#re=null;#De=null;#j=null;#oe=null;#g="";#pe="";#Ue=null;#Ke="";#Et="";#ye=null;#Ze=0;#Qe=[];#_t=[];#Tt=[];#St=[];constructor(){super(),this.#x=this.attachShadow({mode:"open"}),this.#E=document.createElement("div"),this.#v=document.createElement("div"),this.#a=document.createElement("textarea"),this.#S=document.createElement("button"),this.#Ce=document.createElement("span"),this.#P=document.createElement("div"),this.#N=document.createElement("button"),this.#O=document.createElement("input"),this.#Ne=document.createElement("div"),this.#Me=document.createElement("span"),this.#$=document.createElement("button"),this.#f=document.createElement("button"),this.#B=document.createElement("span"),this.#Z=document.createElement("div"),this.registerActivityRenderer({type:ea,render:e=>{let n=aE(e);return n===null?null:Bl("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(n)),"compaction")}}),this.registerActivityRenderer({type:Ks,render:e=>fs(e,this.#e,n=>{this.sendMessage(n)})}),this.#F=new hs(e=>this.#Dn(e)),this.#R=new gs({onSelect:e=>{this.#Qn(e)},onNew:()=>{this.newChat(),this.#Ae()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Ae()},onDelete:e=>{this.#Jn(e)},onVisibility:()=>{this.#ut()}}),this.#A=new Lr((e,n)=>{this.#dn(e,n)})}#Je(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#qe===null&&(this.#qe=new Zr(e,()=>this.#xe(e),()=>this.#He())),this.#qe)}async#dn(e,n){let r=this.#Je();if(r===null)return;let o=this.#a.value.trim();if(o==="")return;this.#a.value="",this.#Y();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:[]});await new sr({agent:s,handlers:this.#en(),getTools:()=>this.#kt(),getContext:()=>this.#Wt(),executeTool:l=>this.#Qt(l),resolveInterrupts:l=>this.#Jt(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#un(){let e=this.#Je();this.#A.setRelativeTimeFormatter(this.formatRelativeTime),this.#A.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials","user-key",...eE]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Kl(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${ec.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#Fn(),this.#qn(),!this.#ze()&&this.collapsed&&this.setCollapsed(!1),requestAnimationFrame(()=>this.#fe());return}if(e==="title-text"){this.#Ce.textContent=r??this.#e.title,this.#le.textContent=this.#Ce.textContent;return}if(e==="user-key"){this.#ue&&(n??"")!==(r??"")&&this.#Kn(n??"",r??"");return}n===r||!this.#ue||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#r.register(e)}get sharedState(){return this.#ne?.state??this.#he}set sharedState(e){this.#he={...e},this.#ne?.setState(this.#he)}registerPageState(e){for(let n of Ki(e))this.#r.register(n)}registerStateHook(e){this.registerPageState(e)}#hn(){return this.routeMap.length===0?[]:il(()=>this.routeMap,()=>this.navigate)}#pn(){let e=this.getPageMap;return e===null?[]:[{name:Qs,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the page"},handler:()=>e()}]}#fn(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return[...nl(n,r=>this.resolvePageTarget(r)),...n.has(Nr.CHAT)?ja(this):[]]}#At(){return[...this.#hn(),...this.#pn(),...this.#fn(),...this.#mn()]}#mn(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#gn(e)}]:[]}async#gn(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#U=new AbortController;let i=this.#U.signal;this.#H();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await xl(this.#L(),r,{signal:i,strings:this.#e});return this.#U=null,this.#I(),this.#w.follow(),s}#kt(){let e=this.getTools();return this.#s=new Set(e.map(n=>n.name)),e}#et(e){let n=this.#At().find(r=>r.name===e);return n!==void 0?n:this.#r.has(e)?this.#r.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Kl(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Kl(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${ec.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#we(){return{...this.headers,...this.getHeaders?.()}}#xe(e){let n=this.#we();return Es(e,Object.keys(n),this.trustedOrigins,this.#n),n}#He(){return this.credentials??void 0}#Ge(){let e=this.#He();return e===void 0?{}:{credentials:e}}#It(e){return Qe({headers:this.#xe(e)},this.#He())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===On.INLINE||e===On.MINIMAL||e===On.COMPACT?e:On.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#pe=this.#Yn(),this.#ot(this.#$t()),requestAnimationFrame(()=>{this.#st(),this.#fe()}),this.#e=sl({...this.#vn(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#lt(Rp);e!==null&&this.setAttribute("theme",e)}if(this.#or(),this.#R.setStrings(this.#e),this.#A.setStrings(this.#e),this.#ze()&&this.#Hn()&&this.setAttribute("collapsed",""),this.#Kt(),this.#Ln(),this.conversationStore instanceof Ze){let e=this.#at();this.#ye=e===""?this.conversationStore:new Ze(e),this.conversationStore=this.#ye}window.addEventListener("resize",this.#de),window.visualViewport?.addEventListener("resize",this.#de),window.visualViewport?.addEventListener("scroll",this.#de),this.#Dt(),this.#Nt(),this.#yn(),this.#xn(),this.#g=this.conversationStore.threadId(),queueMicrotask(()=>this.#bn()),this.#Fe(),this.#ue=!0}#bn(){this.#ue&&(this.#Ot(),this.#Mt())}async reload(){this.#X(),this.#Se(),this.#ie(!1),await Promise.all([this.#Ot(),this.#Mt(),this.#Fe()])}disconnectedCallback(){this.#ue=!1,window.removeEventListener("resize",this.#de),window.visualViewport?.removeEventListener("resize",this.#de),window.visualViewport?.removeEventListener("scroll",this.#de),this.#Ue!==null&&(Jl.delete(this.#Ue),this.#Ue=null),this.#X(),this.#ae?.detach(),this.#ae=null,this.#k?.dispose(),this.#We?.dispose(),this.#w.dispose(),this.#K!==null&&(clearTimeout(this.#K),this.#K=null)}#Rt(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#vn(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#yn(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#wn(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new Qi({upload:n,maxBytes:this.#In(),accept:r,strings:this.#e,onChange:()=>this.#pr(o)});this.#k=o,this.#Ne.appendChild(this.#k.element),this.#O.accept=r,this.#N.hidden=!1,this.#Cn(),this.#Mn(o)}#wn(e){return e===null?null:(n,r,o)=>Yl(n,{url:e,headers:this.#xe(e),...this.#Ge(),onProgress:r,signal:o})}#xn(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#En(e);n!==null&&(this.#We=new bs({transcribe:n,onText:r=>this.#_n(r),strings:this.#e}),this.#Me.appendChild(this.#We.element))}#En(e){return e===null?null:n=>Xl(n,{url:e,headers:this.#xe(e),...this.#Ge()})}#_n(e){let n=this.#a.value.trim();this.#a.value=n===""?e:`${n} ${e}`,this.#Zt(),this.#a.focus()}quote(e){let n=bl(e);if(n==="")return;let r=this.#a.value.replace(/\s+$/,"");this.#a.value=r===""?n:`${r}
3666
+ `;var ps=class{element;get agent(){return this.#r}#t;#n;#e;#s=new Map;#r=null;constructor(e=ae){this.element=document.createElement("div"),this.element.className="subagent",this.element.setAttribute("part","subagent"),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="subagent-row",this.#t.setAttribute("part","subagent-row"),this.#t.setAttribute("aria-expanded","false"),this.#t.disabled=!0;let n=document.createElement("span");n.className="subagent-icon",n.setAttribute("part","subagent-icon"),n.setAttribute("aria-hidden","true"),this.#n=document.createElement("span"),this.#n.className="subagent-status",this.#n.setAttribute("part","subagent-status"),this.#n.textContent=e.subAgentWorking,this.#t.append(n,this.#n),this.#e=document.createElement("div"),this.#e.className="subagent-steps",this.#e.setAttribute("part","subagent-steps"),this.#e.setAttribute("role","list"),this.#e.setAttribute("aria-label",e.subAgentSteps),this.#e.hidden=!0,this.#t.addEventListener("click",()=>{this.#u(this.#t.getAttribute("aria-expanded")!=="true")}),this.element.append(this.#t,this.#e)}report(e){this.element.setAttribute("data-phase",e.phase),e.agent!==null&&(this.#r=e.agent,this.element.setAttribute("data-agent",e.agent)),e.status!==null&&(this.#n.textContent=e.status),e.tool!==null&&this.#i(e.tool)}#i(e){let n=this.#s.get(e.toolCallId)??this.#o(e);if(e.ok===null){n.removeAttribute("data-ok");return}n.setAttribute("data-ok",String(e.ok))}#o(e){let n=document.createElement("div");n.className="subagent-step",n.setAttribute("part","subagent-step"),n.setAttribute("role","listitem"),n.setAttribute("data-tool-call-id",e.toolCallId);let r=document.createElement("span");r.className="subagent-step-icon",r.setAttribute("part","subagent-step-icon"),r.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="subagent-step-name",o.setAttribute("part","subagent-step-name"),o.textContent=e.name,n.append(r,o),this.#e.appendChild(n),this.#s.set(e.toolCallId,n),this.#t.disabled=!1,n}#u(e){this.#e.hidden=!e,this.#t.setAttribute("aria-expanded",String(e))}};var Ux=Object.values(Cn);function bp(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function qr(t){return typeof t=="string"&&t!==""?t:null}function Hx(t){let e=bp(t);if(e===null)return null;let n=qr(e.toolCallId),r=qr(e.name),o=e.ok;return n===null||r===null||o!==null&&typeof o!="boolean"?null:{toolCallId:n,name:r,ok:o}}function vp(t){let e=bp(t);if(e===null)return null;let n=qr(e.delegationId),r=e.phase;return n===null||typeof r!="string"||!Ux.includes(r)?null:{delegationId:n,phase:r,agent:qr(e.agent),status:qr(e.status),tool:Hx(e.tool)}}var Gx=4,zx=120;function yp(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function fs(t,e,n){let r=yp(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let s=document.createElement("button");s.type="button",s.className="suggestion-chip",s.setAttribute("part","suggestion-chip"),s.textContent=i,s.addEventListener("click",()=>n(i)),o.appendChild(s)}return o}var ms=class{element;#t;#n;#e;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="thoughts-toggle",this.#e.setAttribute("part","thoughts-toggle"),this.#e.setAttribute("aria-expanded","true"),this.#t=document.createElement("span"),this.#t.className="thoughts-label",this.#t.setAttribute("part","thoughts-label"),this.#t.textContent=e.thinking,this.#e.append(this.#t),this.#n=document.createElement("pre"),this.#n.className="thoughts-body",this.#n.setAttribute("part","thoughts-body"),this.#e.addEventListener("click",()=>{this.#i(!this.#r)}),this.element.append(this.#e,this.#n)}stream(e){this.#n.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#t.textContent=this.#s.thoughts,this.#i(!0))}#i(e){this.#r=e,this.#n.hidden=e,this.#e.setAttribute("aria-expanded",String(!e))}};var Fx=8,gs=class{element;#t;#n;#e;#s;#r;#i=null;#o;#u=[];#h="";#l;#c;#d="";#p=!0;#y=null;constructor(e,n=ae){this.#t=e,this.#o=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#n=document.createElement("div"),this.#n.className="drawer-panel",this.#n.setAttribute("part","drawer-panel"),this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true"),this.#n.setAttribute("aria-label",n.chatHistory),this.#n.addEventListener("keydown",i=>this.#T(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#e=document.createElement("span"),this.#e.className="drawer-title",this.#e.setAttribute("part","drawer-title"),this.#e.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#t.onNew()}),this.#l=document.createElement("button"),this.#l.type="button",this.#l.className="drawer-close",this.#l.setAttribute("part","drawer-close"),this.#l.title=n.closeHistory,this.#l.setAttribute("aria-label",n.closeHistory),this.#l.append(document.createTextNode("\xD7")),this.#l.addEventListener("click",()=>this.close()),o.append(this.#e,this.#s,this.#l),this.#c=document.createElement("input"),this.#c.type="search",this.#c.className="drawer-filter",this.#c.setAttribute("part","drawer-filter"),this.#c.placeholder=n.searchConversations,this.#c.setAttribute("aria-label",n.searchConversations),this.#c.addEventListener("input",()=>{this.#d=this.#c.value.trim().toLowerCase(),this.#x()}),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#n.append(o,this.#c,this.#r),this.element.append(r,this.#n)}setRelativeTimeFormatter(e){this.#i=e}#m(e){return this.#i!==null?this.#i(e):Mr(e,void 0,this.#o)}setStrings(e){this.#o=e,this.#n.setAttribute("aria-label",e.chatHistory),this.#e.textContent=e.chats,this.#s.textContent=e.newChat,this.#l.title=e.closeHistory,this.#l.setAttribute("aria-label",e.closeHistory),this.#c.placeholder=e.searchConversations,this.#c.setAttribute("aria-label",e.searchConversations),this.#x()}setModal(e){this.#p=e,e?(this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true")):(this.#n.setAttribute("role","region"),this.#n.removeAttribute("aria-modal"))}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#y=this.#N(),this.element.hidden=!1,this.#p&&this.#s.focus(),this.#t.onVisibility?.(!0))}close(){this.isOpen()&&(this.element.hidden=!0,this.#p&&this.#y?.focus(),this.#y=null,this.#t.onVisibility?.(!1))}toggle(){this.isOpen()?this.close():this.open()}#N(){return this.element.getRootNode().activeElement}#T(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab"||!this.#p)return;let n=Array.from(this.#n.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#N();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#u=e,this.#h=n,this.#x()}#x(){this.#r.replaceChildren();let e=this.#u.length<Fx;this.#c.hidden=e,e&&this.#d!==""&&(this.#c.value="",this.#d="");let n=this.#G();if(n.length===0){let r=document.createElement("div");r.className="drawer-empty",r.setAttribute("part","drawer-empty"),r.textContent=this.#u.length===0?this.#o.noConversations:this.#o.noMatches,this.#r.appendChild(r);return}for(let r of n)this.#r.appendChild(this.#ae(r))}#G(){return this.#d===""?this.#u:this.#u.filter(e=>e.title.toLowerCase().includes(this.#d)||e.preview.toLowerCase().includes(this.#d))}#ae(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#h&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=this.#m(e.updatedAt);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#t.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#o.rename,a.setAttribute("aria-label",this.#o.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#z(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#o.delete,l.setAttribute("aria-label",this.#o.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#b(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#z(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#x():this.#t.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#x())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#b(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#o.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#o.delete,i.addEventListener("click",()=>this.#t.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#o.cancel,s.addEventListener("click",()=>this.#x()),r.append(o,i,s),e.replaceChildren(r)}};function Vl(t){return{[re.PENDING]:t.toolRunning,[re.DEFERRED]:t.toolDeferred,[re.DONE]:t.toolDone,[re.ERROR]:t.toolError,[re.DECLINED]:t.toolDeclined}}function $x(t){return{[re.DONE]:t.resultLabel,[re.ERROR]:t.errorLabel,[re.DECLINED]:t.declinedLabel}}function Bx(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var Wr=class{element;approvalSlot;subagentSlot;#t;#n;#e;#s;#r;#i;#o;args;#u;#h;#l=!1;constructor(e,n,r,o=ae,i={}){this.#o=o,this.args=n,this.#u=e,this.#h=i.formatPayload??null,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",re.PENDING),this.element.setAttribute("data-expanded","false");let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=r??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=Vl(o)[re.PENDING],this.#n=document.createElement("span"),this.#n.className="tool-call-decision",this.#n.setAttribute("part","tool-card-decision"),this.#n.hidden=!0,s.append(a,l,this.#t,this.#n);let c=this.#d("args",o.argumentsLabel);this.#c(c.body,{kind:"arguments",toolName:e,args:n},JSON.stringify(n,null,2)),c.root.hidden=Object.keys(n).length===0;let u=this.#d("result",o.resultLabel);this.#s=u.root,this.#r=u.label,this.#i=u.body,u.root.hidden=!0,this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="tool-call-toggle",this.#e.setAttribute("part","tool-card-toggle"),this.#e.setAttribute("aria-expanded","false"),this.#e.textContent=o.details,this.#e.addEventListener("click",()=>this.#y(!this.#p()));let m=document.createElement("div");m.className="tool-call-body",m.setAttribute("part","tool-card-body"),m.append(c.root,u.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.subagentSlot=document.createElement("div"),this.subagentSlot.className="tool-call-subagent",this.subagentSlot.setAttribute("part","tool-card-subagent"),this.element.append(s,this.subagentSlot,this.#e,m,this.approvalSlot)}mark(e){this.#l||(this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#n.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#n.hidden=!1}get settled(){return this.#l}settle(e,n){this.#l||(this.#l=!0,this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e],this.#r.textContent=$x(this.#o)[e],this.#c(this.#i,{kind:"result",toolName:this.#u,status:e,text:n},Bx(n)),this.#s.hidden=!1)}#c(e,n,r){let o=this.#h===null?null:this.#h(n);if(o===null){e.textContent=r;return}if(e.setAttribute("data-formatted","true"),typeof o=="string"){e.textContent=o;return}e.replaceChildren(o)}#d(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#p(){return this.element.getAttribute("data-expanded")==="true"}#y(e){this.element.setAttribute("data-expanded",String(e)),this.#e.setAttribute("aria-expanded",String(e))}};var wp=12e4,bs=class{element;#t;#n;#e;#s="idle";#r=null;#i=null;#o=[];#u=null;#h=!1;#l=!1;constructor(e){this.#t=e.transcribe,this.#n=e.onText,this.#e=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=Dc,this.element.append(n),this.#T("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#d();return}this.#s!=="transcribing"&&await this.#c()}async#c(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#N(this.#e.transcriptionFailed);return}this.#i=e,this.#o=[],this.#h=!1;let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#y(n.mimeType)}),this.#r=n,n.start(),this.#u=setTimeout(()=>{this.#h=!0,this.#d()},wp),this.#T("recording")}#d(){this.#p(),this.#r?.stop()}#p(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}dispose(){this.#l=!0,this.#p(),this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#m()}async#y(e){if(this.#l)return;this.#m(),this.#T("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#t(n);this.#T("idle"),this.#h&&(this.element.title=this.#e.recordingLimit.replace("{n}",String(wp/6e4))),r!==""&&this.#n(r)}catch(r){this.#N(r instanceof Error?r.message:this.#e.transcriptionFailed)}finally{this.#r=null}}#m(){for(let e of this.#i?.getTracks()??[])e.stop();this.#i=null}#N(e){this.#m(),this.#r=null,this.#T("idle"),this.element.title=e}#T(e){this.#s=e,this.element.dataset.state=e;let n=this.#x(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#x(e){return e==="recording"?this.#e.stopRecording:e==="transcribing"?this.#e.transcribing:this.#e.recordVoice}};var vs=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},sr=class{#t;#n;#e;#s;#r;#i;#o;#u=new Set;#h=new Map;#l;#c;#d=!1;constructor(e){this.#t=e.agent,this.#n=e.handlers,this.#e=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#i=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.maxToolRounds??Nn;this.#c=n>=1?Math.floor(n):Nn;let r=e.onStateChanged;r!==void 0&&this.#t.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#t.state}setState(e){this.#t.setState({...e})}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Ie(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#m(),await this.#p()}truncateToLastUser(){let e=[...this.#t.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#t.setMessages(r),this.#m(),r}async resume(){await this.#p()}addToolResult(e,n){this.#t.addMessage({id:Ie(),role:"tool",content:n,toolCallId:e}),this.#m()}cancel(){this.#d=!0,this.#t.abortRun()}async#p(){this.#d=!1;try{await this.#N(),this.#d&&this.#y()}catch(e){this.#d||Vx(e)?this.#y():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#y(){this.#m(),this.#n.onCancelled()}#m(){let e=this.#t.messages;if(this.#h.size===0){this.#o(e);return}this.#o(e.map(n=>{if(n.role!=="tool")return n;let r=this.#h.get(n.toolCallId);return r===void 0?n:{...n,outcome:r}}))}async#N(){let e;for(let n=0;n<this.#c;n+=1){if(this.#d)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#e(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#t.runAgent(i,this.#T(r,o)),e=void 0,this.#m(),this.#d)return;if(!o.terminal)throw new vs(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#i===null)return;let a=await this.#i(o.interrupts);if(this.#d)return;e=eh(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;l.outcome!==void 0&&this.#h.set(a.id,l.outcome),this.#t.addMessage({id:Ie(),role:"tool",content:l.content,toolCallId:a.id}),this.#m(),s=!0}}if(!s)return}}#T(e,n){let r=this.#n,o=this.#u,i=this.#h,s=()=>this.#d,a=new Set;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c)},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:u}){let m={id:l.toolCallId,name:c,args:u};e.push(m),r.onToolCall(m)},onToolCallResultEvent({event:l}){let c=l.outcome;typeof c=="string"&&i.set(l.toolCallId,c),r.onToolResult(l.toolCallId,l.content,c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(m=>m.id===l.messageId&&m.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){if(a.size!==0){for(let c of a){let u=l.find(m=>m.id===c);u!==void 0&&u.role==="activity"&&r.onActivityChanged(c,u.activityType,u.content)}a.clear()}},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!s()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Vx(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function jl(t){let e=t.attachments;return Array.isArray(e)?e.filter(jx):[]}function jx(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var xp="ag-ui-chat",ar="thread",ql="threads",Xr="messages:",ws="checkpoint:",Yr="minted:",qx=60,Wx=100,Xx="New conversation",Ep=!1;function bt(t,e){try{sessionStorage.setItem(t,e)}catch{if(Ep)return;Ep=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function ys(t){return t===""?xp:`${xp}@${t}`}var Ze=class t{#t;constructor(e=""){this.#t=ys(e),e!==""&&t.adopt("",e)}static adopt(e,n){let r=`${ys(e)}:`,o=`${ys(n)}:`;for(let[i,s]of _p(r)){let a=sessionStorage.getItem(i),l=o+s;a!==null&&sessionStorage.getItem(l)===null&&bt(l,a),sessionStorage.removeItem(i)}}static purge(e){for(let[n]of _p(`${ys(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#r(ar))??this.newThread()}newThread(){let e=Ie();return bt(this.#r(ar),e),bt(this.#r(Yr+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#r(Yr+e))!==null&&sessionStorage.getItem(this.#r(Xr+e))===null}loadMessages(e){return Promise.resolve(this.#i(this.#r(Xr+e)))}saveMessages(e,n){bt(this.#r(Xr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(Yr+e)),this.#n(e,n)}loadCheckpoint(e){return this.#i(this.#r(ws+e))}saveCheckpoint(e,n){let r=this.#r(ws+e);if(n===null){sessionStorage.removeItem(r);return}bt(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Xr+e)),sessionStorage.removeItem(this.#r(ws+e)),sessionStorage.removeItem(this.#r(Yr+e)),this.#s(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(ar))===e&&sessionStorage.removeItem(this.#r(ar))}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){bt(this.#r(ar),e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#n(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Kx(n),s=Date.now();o===void 0?r.push({threadId:e,title:Tp(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Tp(n))),this.#s(r)}#e(){return this.#i(this.#r(ql))??[]}#s(e){let n=this.#r(ql);if(e.length===0){sessionStorage.removeItem(n);return}bt(n,JSON.stringify(e))}#r(e){return`${this.#t}:${e}`}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function _p(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);Yx(o)&&e.push([r,o])}return e}function Yx(t){return t===ar||t===ql||t.startsWith(Xr)||t.startsWith(ws)||t.startsWith(Yr)}function Tp(t){for(let e of t)if(e.role==="user"){let n=Sp(e.content);if(n!=="")return Ap(n,qx)}return Xx}function Kx(t){for(let e of[...t].reverse()){let n=Sp(e.content);if(n!=="")return Ap(n,Wx)}return""}function Sp(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Ap(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Qe(t,e){return e===void 0?t:{...t,credentials:e}}function xs(t){if(t.newThread!==void 0)return t.newThread();let e=Ie();return t.setActiveThread(e),e}function Es(t,e,n,r){if(e.length===0)return;let o=new URL(String(t),location.href).origin;o===location.origin||n.includes(o)||r.has(o)||(r.add(o),console.warn(`<ag-ui-chat>: sending host credentials (${e.join(", ")}) to ${o}, which is not this page's origin (${location.origin}). Those headers are the page's own authentication, and whichever server answers the browser's preflight receives them \u2014 so a URL attribute built from a query parameter or from tenant-authored configuration is a channel for the token to leave on. If this destination is deliberate, name it in \`trustedOrigins\` to confirm it and silence this notice. Reported once per origin.`))}function Wl(t){let e=t.headers??{},n=new Set;return new th({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),s=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,s,t.trustedOrigins??[],n),i===void 0)return fetch(r,Qe(o,t.credentials));let a=new Headers(o?.headers);for(let[l,c]of Object.entries(i))a.set(l,c);return fetch(r,Qe({...o,headers:a},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var Kr=class{#t;#n;#e;#s;#r;#i=new Set;#o=new Map;constructor(e,n=()=>({}),r=new Ze,o=()=>{},i=!0){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r,this.#s=o,this.#r=i}threadId(){return this.#e.threadId()}setActiveThread(e){this.#e.setActiveThread(e)}newThread(){return xs(this.#e)}isUnsent(e){return this.#e.isUnsent?.(e)===!0}saveMessages(e,n){this.#e.saveMessages(e,this.#r?n:[])}loadCheckpoint(e){return this.#e.loadCheckpoint(e)}saveCheckpoint(e,n){this.#e.saveCheckpoint(e,n)}renameThread(e,n){this.#e.renameThread(e,n),this.#o.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#e.clear(e),this.#i.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#u();return e===null?this.#e.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){if(this.#e.isUnsent?.(e)===!0)return null;let n=await this.#c(`${this.#t}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#e.loadMessages(e);let r=await this.#h(n);return r===null?this.#e.loadMessages(e):r.messages??null}async#u(){let e=await this.#c(this.#t);if(e===null||!e.ok)return null;let n=await this.#h(e);return n===null?null:n.threads??[]}async#h(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Qe({headers:this.#n()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#n();try{await fetch(`${this.#t}${encodeURIComponent(e)}/`,Qe({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var Zr=class{#t;#n;#e;constructor(e,n=()=>({}),r=()=>{}){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r}async list(){try{let e=await fetch(this.#t,Qe({method:"GET",headers:{Accept:"application/json",...this.#n()}},this.#e()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#t.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};function _s(t){return t===It.FAILED?re.ERROR:t===It.DENIED?re.DECLINED:re.DONE}async function Xl(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Qe({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await Zx(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Zx(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Yl(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Qx(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Jx(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Qx(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Jx(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var eE=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],ec=["omit","same-origin","include"];function Kl(t){return ec.includes(t)}var kp="ag-ui-chat:collapsed",Ip="ag-ui-chat:size",Rp="ag-ui-chat:theme",Zl="ag-ui-chat:launcher";function tE(t){if(typeof t!="object"||t===null)return null;let{left:e,top:n}=t;return typeof e=="number"&&typeof n=="number"?{left:e,top:n}:null}var Cp=new Set([null,"","floating","bottom-left"]),nE=[{y:"top"},{y:"bottom"},{x:"left"},{x:"right"},{x:"left",y:"top"},{x:"right",y:"top"},{x:"left",y:"bottom"},{x:"right",y:"bottom"}],Ql=6,Jl=new Set,Qr=class extends HTMLElement{agentFactory=Wl;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>[...this.#At().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#r.tools()];getContext=()=>[...rl(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Ze;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#n=new Set;#e=ae;#s=new Set;#r=new Ir;#i=new Map;#o=new Map;#u=new Map;#h=new Map;#l=new Set;#c=new Map;#d=new Map;#p=new Set;#y=[];#m=new Set;#N=null;#T=new Set;#x;#G=document.createElement("div");#ae=document.createElement("div");#z=document.createElement("button");#b=document.createElement("button");#je="";#le=null;#Ie=document.createElement("div");#w;#K=null;#Re=!1;#E;#v;#a;#S;#Ce;#F;#R;#A;#qe=null;#C;#O;#M;#Ne;#$;#f;#B;#ce=document.createElement("span");#Oe=0;#Z;#k=null;#_=null;#de=[];#Q=[];#V=document.createElement("div");#J=null;#D=null;#ee=null;#te={x:"right",y:"bottom"};#xt=new Map;#ue=()=>{this.#Ut(),!this.#dn()&&(this.#st(),this.#R.isOpen()&&(this.#R.setModal(!this.#dt()),this.#ut()))};#cn(e){let n=this.#L(),r=n.left+Je,o=n.top+Je,i=n.left+n.width-Je,s=n.top+n.height-Je;return{left:Math.min(Math.max(e.left,r),e.right),top:Math.min(Math.max(e.top,o),e.bottom),right:Math.max(Math.min(e.right,i),e.left),bottom:Math.max(Math.min(e.bottom,s),e.top)}}#dn(){return this.#f.hasAttribute("data-dragging")||this.#x.querySelector(".header[data-dragging]")!==null}#Me;#We=null;#he=!1;#ne=null;#pe={};#W=!1;#Xe=null;#U=null;#Le=null;#Ye=0;#Pe="";#re=null;#De=null;#j=null;#oe=null;#g="";#fe="";#Ue=null;#Ke="";#Et="";#ye=null;#Ze=0;#Qe=[];#_t=[];#Tt=[];#St=[];constructor(){super(),this.#x=this.attachShadow({mode:"open"}),this.#E=document.createElement("div"),this.#v=document.createElement("div"),this.#a=document.createElement("textarea"),this.#S=document.createElement("button"),this.#Ce=document.createElement("span"),this.#C=document.createElement("div"),this.#O=document.createElement("button"),this.#M=document.createElement("input"),this.#Ne=document.createElement("div"),this.#Me=document.createElement("span"),this.#$=document.createElement("button"),this.#f=document.createElement("button"),this.#B=document.createElement("span"),this.#Z=document.createElement("div"),this.registerActivityRenderer({type:ea,render:e=>{let n=aE(e);return n===null?null:Bl("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(n)),"compaction")}}),this.registerActivityRenderer({type:Ks,render:e=>fs(e,this.#e,n=>{this.sendMessage(n)})}),this.#F=new hs(e=>this.#Un(e)),this.#R=new gs({onSelect:e=>{this.#Jn(e)},onNew:()=>{this.newChat(),this.#Ae()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Ae()},onDelete:e=>{this.#er(e)},onVisibility:()=>{this.#ut()}}),this.#A=new Lr((e,n)=>{this.#un(e,n)})}#Je(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#qe===null&&(this.#qe=new Zr(e,()=>this.#xe(e),()=>this.#He())),this.#qe)}async#un(e,n){let r=this.#Je();if(r===null)return;let o=this.#a.value.trim();if(o===""){this.#C.textContent=this.#e.continueNeedsTurn,this.#C.hidden=!1,this.#a.focus();return}this.#a.value="",this.#Y();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:[]});await new sr({agent:s,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:l=>this.#Jt(l),resolveInterrupts:l=>this.#en(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#hn(){let e=this.#Je();this.#A.setRelativeTimeFormatter(this.formatRelativeTime),this.#A.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials","user-key",...eE]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Kl(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${ec.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#$n(),this.#Wn(),!this.#ze()&&this.collapsed&&this.setCollapsed(!1),requestAnimationFrame(()=>this.#me());return}if(e==="title-text"){this.#Ce.textContent=r??this.#e.title,this.#ce.textContent=this.#Ce.textContent;return}if(e==="user-key"){this.#he&&(n??"")!==(r??"")&&this.#Zn(n??"",r??"");return}n===r||!this.#he||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#r.register(e)}get sharedState(){return this.#ne?.state??this.#pe}set sharedState(e){this.#pe={...e},this.#ne?.setState(this.#pe)}registerPageState(e){for(let n of Ki(e))this.#r.register(n)}registerStateHook(e){this.registerPageState(e)}#pn(){return this.routeMap.length===0?[]:il(()=>this.routeMap,()=>this.navigate)}#fn(){let e=this.getPageMap;return e===null?[]:[{name:Qs,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the page"},handler:()=>e()}]}#mn(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return[...nl(n,r=>this.resolvePageTarget(r)),...n.has(Nr.CHAT)?ja(this):[]]}#At(){return[...this.#pn(),...this.#fn(),...this.#mn(),...this.#gn()]}#gn(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#bn(e)}]:[]}async#bn(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#U=new AbortController;let i=this.#U.signal;this.#H();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await xl(this.#P(),r,{signal:i,strings:this.#e});return this.#U=null,this.#I(),this.#w.follow(),s}#kt(){let e=this.getTools();return this.#s=new Set(e.map(n=>n.name)),e}#et(e){let n=this.#At().find(r=>r.name===e);return n!==void 0?n:this.#r.has(e)?this.#r.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Kl(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Kl(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${ec.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#we(){return{...this.headers,...this.getHeaders?.()}}#xe(e){let n=this.#we();return Es(e,Object.keys(n),this.trustedOrigins,this.#n),n}#He(){return this.credentials??void 0}#Ge(){let e=this.#He();return e===void 0?{}:{credentials:e}}#It(e){return Qe({headers:this.#xe(e)},this.#He())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===On.INLINE||e===On.MINIMAL||e===On.COMPACT?e:On.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#fe=this.#Kn(),this.#ot(this.#Bt()),requestAnimationFrame(()=>{this.#st(),this.#me()}),this.#e=sl({...this.#yn(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#lt(Rp);e!==null&&this.setAttribute("theme",e)}if(this.#ir(),this.#R.setStrings(this.#e),this.#A.setStrings(this.#e),this.#ze()&&this.#Gn()&&this.setAttribute("collapsed",""),this.#Zt(),this.#Pn(),this.conversationStore instanceof Ze){let e=this.#at();this.#ye=e===""?this.conversationStore:new Ze(e),this.conversationStore=this.#ye}window.addEventListener("resize",this.#ue),window.visualViewport?.addEventListener("resize",this.#ue),window.visualViewport?.addEventListener("scroll",this.#ue),this.#Ut(),this.#Ot(),this.#wn(),this.#En(),this.#g=this.conversationStore.threadId(),queueMicrotask(()=>this.#vn()),this.#Fe(),this.#he=!0}#vn(){this.#he&&(this.#Mt(),this.#Lt())}async reload(){this.#X(),this.#Se(),this.#ie(!1),await Promise.all([this.#Mt(),this.#Lt(),this.#Fe()])}disconnectedCallback(){this.#he=!1,window.removeEventListener("resize",this.#ue),window.visualViewport?.removeEventListener("resize",this.#ue),window.visualViewport?.removeEventListener("scroll",this.#ue),this.#Ue!==null&&(Jl.delete(this.#Ue),this.#Ue=null),this.#X(),this.#le?.detach(),this.#le=null,this.#k?.dispose(),this.#We?.dispose(),this.#w.dispose(),this.#K!==null&&(clearTimeout(this.#K),this.#K=null)}#Rt(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Ct(e){let n=this.getAttribute(e);if(n===null)return null;try{return JSON.parse(n)}catch{return console.warn(`<ag-ui-chat>: ${e} is not valid JSON, so it was ignored entirely and the built-in default is being used. Check the quoting -- JSON inside an HTML attribute needs single quotes around the attribute value, or its own double quotes escaped.`),null}}#yn(){let e=this.#Ct("data-strings");return typeof e=="object"&&e!==null?e:{}}#wn(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#xn(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new Qi({upload:n,maxBytes:this.#Rn(),accept:r,strings:this.#e,onChange:()=>this.#fr(o)});this.#k=o,this.#Ne.appendChild(this.#k.element),this.#M.accept=r,this.#O.hidden=!1,this.#Nn(),this.#Ln(o)}#xn(e){return e===null?null:(n,r,o)=>Yl(n,{url:e,headers:this.#xe(e),...this.#Ge(),onProgress:r,signal:o})}#En(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#_n(e);n!==null&&(this.#We=new bs({transcribe:n,onText:r=>this.#Tn(r),strings:this.#e}),this.#Me.appendChild(this.#We.element))}#_n(e){return e===null?null:n=>Xl(n,{url:e,headers:this.#xe(e),...this.#Ge()})}#Tn(e){let n=this.#a.value.trim();this.#a.value=n===""?e:`${n} ${e}`,this.#Qt(),this.#a.focus()}quote(e){let n=bl(e);if(n==="")return;let r=this.#a.value.replace(/\s+$/,"");this.#a.value=r===""?n:`${r}
3667
3667
 
3668
- ${n}`,this.#Y(),this.#a.focus();let o=this.#a.value.length;this.#a.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#ae?.detach();let n=yl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#ae=n,()=>{n.detach(),this.#ae===n&&(this.#ae=null)}}#Tn(){return this.getAttribute("data-quote-selection")!=="false"}#Ct(e){if(!this.#Tn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Ur(this.#v,[this.#x],n);if(r===null){this.#tt();return}this.#je=r.text,this.#Sn(r.rect)}#Sn(e){this.#b.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Ql+this.#b.offsetHeight;this.#b.dataset.below=String(o),this.#b.style.top=`${o?e.bottom-n.top+Ql:r-Ql}px`;let i=this.#b.offsetWidth/2,s=e.left+e.width/2-n.left;this.#b.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#b.hidden=!0,this.#je=""}#An(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Nn:Number.parseInt(e,10)}#kn(){let e=this.getAttribute("data-message-actions");return e===null?new Set([$t.COPY,$t.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#In(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Js;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Js}#Rn(){let e=this.#O.files;if(e!==null)for(let n of Array.from(e))this.#k?.add(n);this.#O.value=""}#Cn(){this.#E.addEventListener("dragover",e=>{e.preventDefault(),this.#E.classList.add("chat--dragover")}),this.#E.addEventListener("dragleave",()=>{this.#E.classList.remove("chat--dragover")}),this.#E.addEventListener("drop",e=>{e.preventDefault(),this.#E.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#k?.add(r)})}#Nn(e,n,r){let o=this.#On(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#On(){let e=this.getAttribute("data-paste-attach");if(e===null)return go;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${go} is used.`),go):n}#Mn(e){this.#E.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#Nn(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#k?.add(iE(i))})}#Nt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Kr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Ot(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=ol(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Ln(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Pn(),this.#nt()}#Pn(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Va(JSON.parse(e))}catch{return[]}}async#Mt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=Va(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Dn(e){if(e.prompt===void 0){this.#P.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=nh(e.prompt,this.skillContext());if(r.length>0){this.#P.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#P.hidden=!1,this.#a.value=n,this.#Y(),this.#a.focus(),this.#Un(n);return}if(this.#P.hidden=!0,this.#a.value=n,this.#Y(),e.sendImmediately===!1){this.#a.focus();return}this.#ft()}#Un(e){let n=e.indexOf("{");this.#a.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#in(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(kp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent($s,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Hn(){let e=this.#Vt(kp);return e!==null?e==="1":Cp.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#M(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#Gn():null,o=this.#M(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+Bt,c=o.top+Bt,u=a==="left"?l:Math.max(l,o.left+o.width-Bt-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-Bt-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#in(this.#e.chatMoved,r),!0}#Gn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#_,i=this.#D,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#_=o,this.#D=i,this.#ee=s,o===null?this.#Zn(Zl):this.#_e(),this.#fe()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(Rp,e),this.#jt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#zn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Lt(e,-1),i=o.x===null||o.y===null?this.#Lt(e,1):o;return this.#Pt("--ag-ui-width",n),this.#Pt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Lt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#fe(){if(!this.#ue)return;let e=this.#ee??this.#zn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#Ft()}#Pt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#Fn(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Cp.has(this.getAttribute("placement"))}#M(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#se),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Dt(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#me(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#_;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ut(e){if(!this.#q())return;this.#_=e,this.#D=null;let n=this.getBoundingClientRect(),r=fl(this.#me(),{width:n.width,height:n.height},this.#M(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#fe()}#Ht(e,n){this.#Ut({left:e,top:n})}#$n(e,n){this.#Ht(e,n),this.#_e()}#Gt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#_===null){let c=this.#me();this.#_={left:c.left,top:c.top}}let r=this.#_,o=Pr(e,this.#M(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#D={left:o.left,top:o.top};let a={...this.#me(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Dt(a,this.#M())};return this.style.setProperty("--ag-ui-launcher-inset",Dr(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Bn(e,n){let{held:r,launcher:o}=this.#Gt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#M(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=fl(n,i,r,o),a=Dr(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#_={left:n.left,top:n.top},this.#D={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#fe()}#Vn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Pr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#M(),Je),o=this.#me(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Dt(i,this.#M())})}#_e(){let e=this.#_;if(e===null)return;let n=this.#D;this.#ct(Zl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#jn(),n=this.#_??e;if(n===null)return;let r=this.#D??e?.panel??null;if(r!==null){this.#_={left:n.left,top:n.top},this.#Vn(r);return}let o=this.#me();this.#Ut(Dt({...o,left:n.left,top:n.top},this.#M()))}#jn(){let e=this.#lt(Zl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=tE(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#qn(){this.#q()||(this.#_=null,this.#D=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#zt(e,n){if(n=this.#ln(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#_!==null){let s=this.#f.offsetWidth;this.#_={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#D!==null&&(this.#D={left:n.left,top:n.top}),n}#Wn(e,n){let r=this.#zt(e,n);this.#Xn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#fe()}#Ft(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Xn(e){let n={...this.#$t(),...e};this.#ct(Ip,JSON.stringify(n))}#$t(){let e=this.#lt(Ip);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Yn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Jl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Jl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#pe:`${this.#pe}#${e}`}#Kn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Bt(o);return}Ze.purge(r),this.#Bt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#g=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Bt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Nt())}#Te(e){return this.#pe===""?e:`${e}:${this.#pe}`}#Vt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#pe===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#Vt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Zn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#jt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Hc:Uc,null))}openThreads(){this.#A.close(),this.#Ae(),this.#R.setModal(!this.#dt()),this.#R.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Kc}#ut(){this.#R.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#R.close(),this.#un(),this.#A.open()}closeThreads(){this.#R.close()}closeCheckpoints(){this.#A.close()}toggleCheckpoints(){if(this.#A.open_){this.#A.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#g)===!0&&this.conversationStore.clear(this.#g),this.#Se(),this.#g=xs(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#qt(),this.#Qe=[],this.#ce.length=0,this.#J=null}#qt(){this.#be(),this.#j=null,this.#oe=null,this.#H(),this.#i.clear(),this.#o.clear(),this.#u.clear(),this.#p.clear(),this.#c.clear(),this.#d.clear(),this.#C=null,this.#k?.clear(),this.#v.replaceChildren(this.#Z),this.#I()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#qt();for(let r of n)this.#Xt(r);return await e.resume(),!0}async#Qn(e){e!==this.#g&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#g=e,this.#ie(!1),await this.#Fe())}#Jn(e){let n=e===this.#g;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#g=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#R.setRelativeTimeFormatter(this.formatRelativeTime),this.#R.setThreads(await this.conversationStore.listThreads(),this.#g)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#g);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Xt(o)}let r=this.conversationStore.loadCheckpoint(this.#g);if(r!==null){await this.#rr(r);return}this.#tr(n)}#Wt(){return this.#Xe=window.location.href,this.getContext()}#er(){return this.#Xe!==null&&this.#Xe!==window.location.href}#tr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#ve("\u26A0",this.#e.runInterrupted,"interrupted")}#Xt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=jl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(cl(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of oE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#nr(r.function.arguments)};if(this.#on(o))continue;this.#c.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#sn(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(_s(e.outcome),e.content)}}#nr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Yt(e){this.getAttribute("data-text-animation")==="word"&&fp(e)}async#rr(e){this.conversationStore.saveCheckpoint(this.#g,null);let n=this.#mt();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===qe.ASSISTANT?(r.innerHTML=ds(n,{allowImages:this.allowImages}),ll(r,this.#e),this.#L().appendChild(r)):(this.#j=null,r.textContent=n,this.#v.appendChild(r)),this.#I(),e===qe.USER?this.#w.jump():this.#w.follow(),r}#L(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#v.appendChild(e),this.#I()}return this.#j}#or(){this.#E.className="chat",this.#E.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#jt(),o.append(this.#$)),o.append(l),e.append(n,r,o),Th(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)}),this.#v.className="messages",this.#v.setAttribute("part","messages"),this.#v.setAttribute("role","log"),this.#v.setAttribute("aria-live","off"),this.#v.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#w.jump()}),this.#b.className="quote-selection",this.#b.type="button",this.#b.setAttribute("part","quote-selection"),this.#b.textContent=this.#e.quoteSelection,this.#b.hidden=!0,this.#b.addEventListener("mousedown",g=>{g.preventDefault()}),this.#b.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#v.addEventListener("mouseup",g=>this.#Ct(g)),this.#v.addEventListener("keyup",()=>this.#Ct()),this.#v.addEventListener("mousedown",()=>this.#tt()),this.#w=mp({viewport:this.#v,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#cr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#v.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#a.className="input",this.#a.setAttribute("part","input"),this.#a.setAttribute("aria-label",this.#e.message),this.#a.rows=1,this.#a.placeholder=this.#e.inputPlaceholder,this.#a.addEventListener("keydown",g=>this.#dr(g)),this.#a.addEventListener("input",()=>this.#Zt()),this.#S.className="send",this.#S.type="button",this.#S.setAttribute("part","send"),this.#S.append(this.#ht("icon-send","send-send",Mc),this.#ht("icon-stop","send-stop",Lc)),this.#S.title=this.#e.send,this.#S.setAttribute("aria-label",this.#e.send),this.#S.dataset.state="idle",this.#S.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#P.className="skill-hint",this.#P.setAttribute("part","skill-hint"),this.#P.hidden=!0,this.#N.className="attach-btn",this.#N.type="button",this.#N.setAttribute("part","attach-button"),this.#N.append(this.#ht("icon-attach","attach-glyph",Pc)),this.#N.title=this.#e.attachFiles,this.#N.setAttribute("aria-label",this.#e.attachFiles),this.#N.hidden=!0,this.#N.addEventListener("click",()=>this.#O.click()),this.#O.className="attach-input",this.#O.type="file",this.#O.multiple=!0,this.#O.hidden=!0,this.#O.addEventListener("change",()=>this.#Rn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#N,this.#Me,this.#S),w.append(this.#a,p),m.append(w,this.#O),this.#Ie.className="messages-wrap",this.#Ie.append(this.#v,this.#z,this.#b),this.#E.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#P,this.#V,this.#Ne,m,h,this.#R.element,this.#A.element),this.#E.addEventListener("pointerdown",g=>{if(!this.#A.open_)return;let x=g.composedPath();x.includes(this.#A.element)||x.includes(s)||this.#A.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#le.className="rail-label",this.#le.setAttribute("part","rail-label"),this.#le.setAttribute("aria-hidden","true"),this.#le.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Gc,this.#sr()),this.#le,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),yh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#me(),viewport:()=>this.#M(),apply:(g,x)=>this.#Ht(g,x),commit:(g,x)=>this.#$n(g,x)});for(let g of nE){let x=hp(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#zt(g,T),commit:T=>this.#Wn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(us(g),x),this.#E.appendChild(x)}this.#Ft(),this.#ir(),this.#se.className="viewport-probe",this.#se.setAttribute("aria-hidden","true"),this.#x.append(this.#se,this.#G,this.#E,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},Xc)}#ir(){let e=new CSSStyleSheet;e.replaceSync(gp),this.#x.adoptedStyleSheets=[e]}#$e(e,n,r){let o=document.createElement("button");o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#sr(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Kt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#ar();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#ar(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Kt(),this.dispatchEvent(new CustomEvent(Bs,{detail:{unread:e},bubbles:!0,composed:!0}))}#lr(){this.collapsed&&this.#Be(this.#Oe+1)}#cr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return fs({prompts:n},this.#e,r=>{this.sendMessage(r)})}#I(){this.#Z.hidden=this.#v.childElementCount>1}#Zt(){this.#F.onInput(this.#a.value),this.#P.hidden=!0,this.#Y(),this.#J=null}#dr(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#ur(e)}#ur(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#ce;if(r.length===0||this.#J===null&&(!n||this.#a.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#a.value=o<0?"":r[o],this.#a.setSelectionRange(this.#a.value.length,this.#a.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#ce[0]!==e&&this.#ce.unshift(e);this.#Q.length=0,this.#Ve(),this.#U?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#S.title=r,this.#S.setAttribute("aria-label",r),this.#S.dataset.state=e?"running":"idle",n&&this.#hr()}#hr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#a.style.height="auto",this.#a.style.height=`${this.#a.scrollHeight}px`}async#ft(){let e=this.#a.value.trim(),n=this.#k?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#a.value="",this.#Y());return}e!==""&&this.#ce[0]!==e&&this.#ce.unshift(e),this.#J=null,this.#a.value="",this.#Y(),this.#k?.hasPending()===!0&&this.#ve("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#k.pendingCount())),"attachment-pending"),this.#k?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(cl(n)),this.dispatchEvent(new CustomEvent(Fs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#fr(e,n)}attachFile(e){return this.#k===null?!1:(this.#k.add(e),!0)}#pr(e){this.dispatchEvent(new CustomEvent(js,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#fr(e,n){this.endpoint!==""&&await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:this.#Qe,initialState:this.#he});this.#ne=new sr({agent:e,handlers:this.#en(),getTools:()=>this.#kt(),getContext:()=>this.#Wt(),executeTool:n=>this.#Qt(n),resolveInterrupts:n=>this.#Jt(n),onPersist:n=>this.conversationStore.saveMessages(this.#g,n),onStateChanged:n=>this.#mr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#An()})}return this.#ne}#mr(e){this.#he={...e},this.dispatchEvent(new CustomEvent(Vs,{detail:{state:this.#he},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#kn(),o=r.has($t.COPY),i=n.rateable!==!1&&r.has($t.FEEDBACK);(o||i)&&gl(e,{strings:this.#e,...o?{text:()=>es(e).text,html:()=>es(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ys,{detail:{content:es(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has($t.RETRY)&&this.#gr(ts(e,this.#e))}#gr(e){this.#C?.querySelector(".message-action--retry")?.remove();let n=ns("retry",this.#e.retryMessage,Fc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#C=e}async#br(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#m.has(e.name)?null:qa(n.parameters)?"destructive":null}async#Qt(e){if(Np(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#c.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(re.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Qs&&!qi(r.parameters)&&this.#er()){let s=this.#e.pageMoved;return n.settle(re.ERROR,s),this.#ge(),{content:`Error: ${s}`,error:s,outcome:It.FAILED}}let o=await this.#br(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[fo];typeof a=="string"&&(s.message=a),this.#U=new AbortController;let l=pl(this.#L(),s,{signal:this.#U.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#m.add(e.name)}:{}});this.#I(),this.#w.follow();let c=await l;if(this.#U=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(re.DECLINED,u),this.#ge(),{content:u,outcome:It.DENIED}}}let i=qi(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#g,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#sn(r.render,e),i)return n.settle(re.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(re.DONE,a),this.#ge(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#g,null);let a=s instanceof Error?s.message:String(s);return n.settle(re.ERROR,a),this.#ge(),{content:`Error: ${a}`,error:a,outcome:It.FAILED}}}async#Jt(e){this.#U=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#H();let n=this.#U.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=rE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(re.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await al(s?.approvalSlot??this.#L(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(re.PENDING):s?.settle(re.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#I(),this.#w.follow(),this.#U=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#en(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#L(),this.#ge()},onReasoningStart:()=>{this.#H(),this.#nn()},onReasoningDelta:e=>{this.#nn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#H(),this.#oe?.collapse(),this.#_r(e),this.#Ye+=1},onTextEnd:e=>{let n=this.#vt(e);this.#Ye<=1&&this.#Yt(n),ll(n,this.#e),this.#gt(n),this.#be(),this.#lr()},onToolCall:e=>{this.#H(),!this.#on(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Zs){this.#yr(n);return}if(e===Oc){this.#wr(n);return}this.dispatchEvent(new CustomEvent(Ws,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#u.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Cn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#tn(e,Cn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#tn(e,Cn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#ve("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n,r)=>{let o=this.#i.get(e);o!==void 0&&(o.settle(_s(r),n),this.#p.add(e),this.#ge())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#H(),this.#be()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#H();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Yt(n),this.#be()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#H(),this.#Er(),this.#be()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#H(),this.#ie(!1),this.#be();for(let e of this.#i.values())e.settled||e.settle(re.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#I()),this.#j=null,this.#oe=null,this.#vr()}}}#vr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#T];this.#T=new Set,this.dispatchEvent(new CustomEvent(qs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#yr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#T.add(o);this.dispatchEvent(new CustomEvent(Xs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#wr(e){let n=vp(e);n!==null&&this.#bt(n)}#tn(e,n,r){let o=this.#u.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#xr(i):r,tool:null})}#xr(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new ps(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#w.follow()}#Er(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#L().appendChild(e),this.#I(),this.#w.follow()}#ge(){if(this.#De!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#De=e,this.#L().appendChild(e),this.#I(),this.#w.follow()}#H(){this.#De?.remove(),this.#De=null}#nn(){if(this.#oe===null){this.#oe=new ms(this.#e);let e=this.#L();e.insertBefore(this.#oe.element,e.firstChild),this.#I(),this.#w.follow()}return this.#oe}#rn(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#_r(e){this.#Pe=e,this.#rn(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#rn();return n.innerHTML=ds(e,{allowImages:this.allowImages}),this.#w.follow(),n}#be(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#on(e){let n=Np(e);return n===null?!1:(this.#ve("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#ve(e,n,r,o){this.#L().appendChild(Bl(e,n,r,o)),this.#I(),this.#w.follow()}#in(e,n){this.#ve("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(mo)&&!this.#r.has(Ji);e.includes("activity")&&this.registerActivityRenderer({type:mo,render:r=>{let o=tr(r);return o===null?null:Or(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(ph()),n&&this.isConnected&&this.reload()}#sn(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#c.get(n.id)?.after(r),this.#an())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#l.delete(e.type)}get unhandledActivityTypes(){return[...this.#l]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#l.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Tr(e,n,o.removedNotice,r);return}let s=this.#d.get(e);s===void 0?this.#L().appendChild(i):s.replaceWith(i),this.#d.set(e,i),this.#an()}#Tr(e,n,r,o){let i=this.#d.has(e);this.#d.get(e)?.remove(),this.#d.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#ve("\u{1F4C9}",r,"chart-undrawable")}#an(){this.#I(),this.#w.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??wl(e.name),i=new Wr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#L().appendChild(i.element),this.#I(),this.#w.follow(),i}};function rE(t){let e=t.metadata?.[fo];return typeof e=="string"&&e.trim()!==""?e:void 0}function oE(t){return Array.isArray(t)?t.filter(sE):[]}function iE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function sE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Np(t){if(t.name!==ta)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function aE(t){let e=t?.removed;return typeof e=="number"?e:null}function lE(){customElements.get(po)===void 0&&customElements.define(po,Qr)}async function cE(t,e,n={}){await _t(t),await Qa(t,{...n,flashMs:n.flashMs??0}),await Ka(t,e,n)}async function dE(t,e={}){await _t(t),await Za(t,e)}async function uE(t,e={}){await _t(t),await Ja(t,e)}async function hE(t,e,n={}){await _t(t),await el(t,e,n)}async function pE(t,e,n={}){await _t(t),await tl(t,e,n)}function fE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Rr(t,!!e):mn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var mE="0.36.0";export{js as ATTACHMENT_EVENT,Qr as AgUiChat,sr as AgUiClient,mo as CHART_ACTIVITY_TYPE,Ji as CHART_TOOL_NAME,ji as CHAT_CORNERS,ea as COMPACTION_ACTIVITY_TYPE,Ws as CUSTOM_AGENT_EVENT,Lr as CheckpointMenu,Ir as ClientToolRegistry,vs as ConnectionLostError,ae as DEFAULT_UI_STRINGS,po as ELEMENT_TAG,Ys as FEEDBACK_EVENT,Zs as INVALIDATE_CUSTOM_NAME,Xs as INVALIDATE_EVENT,ta as LOAD_CAPABILITY_TOOL,Py as MAX_QUOTE_CHARS,Gx as MAX_SUGGESTIONS,zx as MAX_SUGGESTION_CHARS,Nn as MAX_TOOL_ROUNDS,$t as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Nr as PAGE_ACTIONS,qs as RUN_FINISHED_EVENT,Kr as RemoteConversationStore,Zr as RunIndex,Vs as STATE_EVENT,Fs as SUBMIT_EVENT,Ks as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,$s as TOGGLE_EVENT,re as TOOL_CALL_STATUS,On as TOOL_DISPLAY,It as TOOL_OUTCOME,Wr as ToolCallCard,Bs as UNREAD_EVENT,mE as VERSION,fo as X_CONFIRM_KEY,hr as X_DESTRUCTIVE_KEY,pr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,bl as asQuote,gl as attachMessageActions,yl as attachQuoteOffer,tr as chartSpecFrom,dE as clickElement,ja as createChatSurfaceTools,Wl as createHttpAgent,nl as createPageActionTools,rl as createPageMapContext,Ki as createPageStateTools,il as createRouteTools,Bv as createStateHookTools,lE as defineAgUiChat,cE as fillField,Hv as flash,Qa as focusWithFlash,Za as highlightThenClick,rh as isChatCorner,qa as isDestructive,qi as isNavigates,sl as mergeUiStrings,ts as messageActionBar,jl as messageAttachments,ol as parseToolCatalog,Xi as prefersReducedMotion,uE as pressButton,Ja as pressThenClick,wl as prettifyToolName,Ur as quotableSelection,Mr as relativeTime,Or as renderChart,ds as renderMarkdown,fs as renderSuggestionChips,al as requestApproval,pl as requestConfirmation,xl as requestQuestion,_t as scrollIntoCenterView,hE as selectControl,el as selectOption,fE as setControlValue,Rr as setNativeChecked,mn as setNativeValue,Wa as showHighlightOverlay,yp as suggestionPrompts,pE as toggleCheckbox,tl as toggleControl,_s as toolStatusFromOutcome,Xl as transcribeAudio,Ka as typeInto,Yl as uploadAttachment};
3668
+ ${n}`,this.#Y(),this.#a.focus();let o=this.#a.value.length;this.#a.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#le?.detach();let n=yl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#le=n,()=>{n.detach(),this.#le===n&&(this.#le=null)}}#Sn(){return this.getAttribute("data-quote-selection")!=="false"}#Nt(e){if(!this.#Sn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Ur(this.#v,[this.#x],n);if(r===null){this.#tt();return}this.#je=r.text,this.#An(r.rect)}#An(e){this.#b.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Ql+this.#b.offsetHeight;this.#b.dataset.below=String(o),this.#b.style.top=`${o?e.bottom-n.top+Ql:r-Ql}px`;let i=this.#b.offsetWidth/2,s=e.left+e.width/2-n.left;this.#b.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#b.hidden=!0,this.#je=""}#kn(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Nn:Number.parseInt(e,10)}#In(){let e=this.getAttribute("data-message-actions");return e===null?new Set([$t.COPY,$t.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#Rn(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Js;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Js}#Cn(){let e=this.#M.files;if(e!==null)for(let n of Array.from(e))this.#k?.add(n);this.#M.value=""}#Nn(){this.#E.addEventListener("dragover",e=>{e.preventDefault(),this.#E.classList.add("chat--dragover")}),this.#E.addEventListener("dragleave",()=>{this.#E.classList.remove("chat--dragover")}),this.#E.addEventListener("drop",e=>{e.preventDefault(),this.#E.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#k?.add(r)})}#On(e,n,r){let o=this.#Mn(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#Mn(){let e=this.getAttribute("data-paste-attach");if(e===null)return go;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${go} is used.`),go):n}#Ln(e){this.#E.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#On(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#k?.add(iE(i))})}#Ot(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Kr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Mt(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=ol(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Pn(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Dn(),this.#nt()}#Dn(){return Va(this.#Ct("data-skills"))}async#Lt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=Va(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Un(e){if(e.prompt===void 0){this.#C.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=nh(e.prompt,this.skillContext());if(r.length>0){this.#C.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#C.hidden=!1,this.#a.value=n,this.#Y(),this.#a.focus(),this.#Hn(n);return}if(this.#C.hidden=!0,this.#a.value=n,this.#Y(),e.sendImmediately===!1){this.#a.focus();return}this.#ft()}#Hn(e){let n=e.indexOf("{");this.#a.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#sn(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(kp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent($s,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Gn(){let e=this.#jt(kp);return e!==null?e==="1":Cp.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#L(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#zn():null,o=this.#L(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+Bt,c=o.top+Bt,u=a==="left"?l:Math.max(l,o.left+o.width-Bt-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-Bt-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#sn(this.#e.chatMoved,r),!0}#zn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#_,i=this.#D,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#_=o,this.#D=i,this.#ee=s,o===null?this.#Qn(Zl):this.#_e(),this.#me()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(Rp,e),this.#qt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#Fn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Pt(e,-1),i=o.x===null||o.y===null?this.#Pt(e,1):o;return this.#Dt("--ag-ui-width",n),this.#Dt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Pt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#me(){if(!this.#he)return;let e=this.#ee??this.#Fn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#$t()}#Dt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#$n(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Cp.has(this.getAttribute("placement"))}#L(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#ae),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Ut(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#ge(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#_;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ht(e){if(!this.#q())return;this.#_=e,this.#D=null;let n=this.getBoundingClientRect(),r=fl(this.#ge(),{width:n.width,height:n.height},this.#L(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#me()}#Gt(e,n){this.#Ht({left:e,top:n})}#Bn(e,n){this.#Gt(e,n),this.#_e()}#zt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#_===null){let c=this.#ge();this.#_={left:c.left,top:c.top}}let r=this.#_,o=Pr(e,this.#L(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#D={left:o.left,top:o.top};let a={...this.#ge(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Dt(a,this.#L())};return this.style.setProperty("--ag-ui-launcher-inset",Dr(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Vn(e,n){let{held:r,launcher:o}=this.#zt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#L(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=fl(n,i,r,o),a=Dr(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#_={left:n.left,top:n.top},this.#D={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#me()}#jn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Pr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#L(),Je),o=this.#ge(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Dt(i,this.#L())})}#_e(){let e=this.#_;if(e===null)return;let n=this.#D;this.#ct(Zl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#qn(),n=this.#_??e;if(n===null)return;let r=this.#D??e?.panel??null;if(r!==null){this.#_={left:n.left,top:n.top},this.#jn(r);return}let o=this.#ge();this.#Ht(Dt({...o,left:n.left,top:n.top},this.#L()))}#qn(){let e=this.#lt(Zl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=tE(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#Wn(){this.#q()||(this.#_=null,this.#D=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#Ft(e,n){if(n=this.#cn(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#_!==null){let s=this.#f.offsetWidth;this.#_={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#D!==null&&(this.#D={left:n.left,top:n.top}),n}#Xn(e,n){let r=this.#Ft(e,n);this.#Yn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#me()}#$t(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Yn(e){let n={...this.#Bt(),...e};this.#ct(Ip,JSON.stringify(n))}#Bt(){let e=this.#lt(Ip);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Kn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Jl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Jl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#fe:`${this.#fe}#${e}`}#Zn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Vt(o);return}Ze.purge(r),this.#Vt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#g=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Vt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Ot())}#Te(e){return this.#fe===""?e:`${e}:${this.#fe}`}#jt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#fe===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#jt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Qn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#qt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Hc:Uc,null))}openThreads(){this.#A.close(),this.#Ae(),this.#R.setModal(!this.#dt()),this.#R.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Kc}#ut(){this.#R.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#R.close(),this.#hn(),this.#A.open()}closeThreads(){this.#R.close()}closeCheckpoints(){this.#A.close()}toggleCheckpoints(){if(this.#A.open_){this.#A.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#g)===!0&&this.conversationStore.clear(this.#g),this.#Se(),this.#g=xs(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#Wt(),this.#Qe=[],this.#de.length=0,this.#J=null}#Wt(){this.#ve(),this.#j=null,this.#oe=null,this.#H(),this.#i.clear(),this.#o.clear(),this.#u.clear(),this.#p.clear(),this.#c.clear(),this.#d.clear(),this.#N=null,this.#k?.clear(),this.#v.replaceChildren(this.#Z),this.#I()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#Wt();for(let r of n)this.#Yt(r);return await e.resume(),!0}async#Jn(e){e!==this.#g&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#g=e,this.#ie(!1),await this.#Fe())}#er(e){let n=e===this.#g;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#g=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#R.setRelativeTimeFormatter(this.formatRelativeTime),this.#R.setThreads(await this.conversationStore.listThreads(),this.#g)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#g);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Yt(o)}let r=this.conversationStore.loadCheckpoint(this.#g);if(r!==null){await this.#or(r);return}this.#nr(n)}#Xt(){return this.#Xe=window.location.href,this.getContext()}#tr(){return this.#Xe!==null&&this.#Xe!==window.location.href}#nr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#se("\u26A0",this.#e.runInterrupted,"interrupted")}#Yt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=jl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(cl(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of oE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#rr(r.function.arguments)};if(this.#in(o))continue;this.#c.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#an(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(_s(e.outcome),e.content)}}#rr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Kt(e){this.getAttribute("data-text-animation")==="word"&&fp(e)}async#or(e){this.conversationStore.saveCheckpoint(this.#g,null);let n=this.#mt();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===qe.ASSISTANT?(r.innerHTML=ds(n,{allowImages:this.allowImages}),ll(r,this.#e),this.#P().appendChild(r)):(this.#j=null,r.textContent=n,this.#v.appendChild(r)),this.#I(),e===qe.USER?this.#w.jump():this.#w.follow(),r}#P(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#v.appendChild(e),this.#I()}return this.#j}#ir(){this.#E.className="chat",this.#E.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#qt(),o.append(this.#$)),o.append(l),e.append(n,r,o),Th(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#zt(g,x),commit:(g,x)=>this.#Vn(g,x)}),this.#v.className="messages",this.#v.setAttribute("part","messages"),this.#v.setAttribute("role","log"),this.#v.setAttribute("aria-live","off"),this.#v.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#w.jump()}),this.#b.className="quote-selection",this.#b.type="button",this.#b.setAttribute("part","quote-selection"),this.#b.textContent=this.#e.quoteSelection,this.#b.hidden=!0,this.#b.addEventListener("mousedown",g=>{g.preventDefault()}),this.#b.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#v.addEventListener("mouseup",g=>this.#Nt(g)),this.#v.addEventListener("keyup",()=>this.#Nt()),this.#v.addEventListener("mousedown",()=>this.#tt()),this.#w=mp({viewport:this.#v,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#dr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#v.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#a.className="input",this.#a.setAttribute("part","input"),this.#a.setAttribute("aria-label",this.#e.message),this.#a.rows=1,this.#a.placeholder=this.#e.inputPlaceholder,this.#a.addEventListener("keydown",g=>this.#ur(g)),this.#a.addEventListener("input",()=>this.#Qt()),this.#S.className="send",this.#S.type="button",this.#S.setAttribute("part","send"),this.#S.append(this.#ht("icon-send","send-send",Mc),this.#ht("icon-stop","send-stop",Lc)),this.#S.title=this.#e.send,this.#S.setAttribute("aria-label",this.#e.send),this.#S.dataset.state="idle",this.#S.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#C.className="skill-hint",this.#C.setAttribute("part","skill-hint"),this.#C.hidden=!0,this.#O.className="attach-btn",this.#O.type="button",this.#O.setAttribute("part","attach-button"),this.#O.append(this.#ht("icon-attach","attach-glyph",Pc)),this.#O.title=this.#e.attachFiles,this.#O.setAttribute("aria-label",this.#e.attachFiles),this.#O.hidden=!0,this.#O.addEventListener("click",()=>this.#M.click()),this.#M.className="attach-input",this.#M.type="file",this.#M.multiple=!0,this.#M.hidden=!0,this.#M.addEventListener("change",()=>this.#Cn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#O,this.#Me,this.#S),w.append(this.#a,p),m.append(w,this.#M),this.#Ie.className="messages-wrap",this.#Ie.append(this.#v,this.#z,this.#b),this.#E.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#C,this.#V,this.#Ne,m,h,this.#R.element,this.#A.element),this.#E.addEventListener("pointerdown",g=>{if(!this.#A.open_)return;let x=g.composedPath();x.includes(this.#A.element)||x.includes(s)||this.#A.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#ce.className="rail-label",this.#ce.setAttribute("part","rail-label"),this.#ce.setAttribute("aria-hidden","true"),this.#ce.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Gc,this.#ar()),this.#ce,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),yh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#ge(),viewport:()=>this.#L(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)});for(let g of nE){let x=hp(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#Ft(g,T),commit:T=>this.#Xn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(us(g),x),this.#E.appendChild(x)}this.#$t(),this.#sr(),this.#ae.className="viewport-probe",this.#ae.setAttribute("aria-hidden","true"),this.#x.append(this.#ae,this.#G,this.#E,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},Xc)}#sr(){let e=new CSSStyleSheet;e.replaceSync(gp),this.#x.adoptedStyleSheets=[e]}#$e(e,n,r){let o=document.createElement("button");o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#ar(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Zt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#lr();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#lr(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Zt(),this.dispatchEvent(new CustomEvent(Bs,{detail:{unread:e},bubbles:!0,composed:!0}))}#cr(){this.collapsed&&this.#Be(this.#Oe+1)}#dr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return fs({prompts:n},this.#e,r=>{this.sendMessage(r)})}#I(){this.#Z.hidden=this.#v.childElementCount>1}#Qt(){this.#F.onInput(this.#a.value),this.#C.hidden=!0,this.#Y(),this.#J=null}#ur(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#hr(e)}#hr(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#de;if(r.length===0||this.#J===null&&(!n||this.#a.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#a.value=o<0?"":r[o],this.#a.setSelectionRange(this.#a.value.length,this.#a.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#de[0]!==e&&this.#de.unshift(e);this.#Q.length=0,this.#Ve(),this.#U?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#S.title=r,this.#S.setAttribute("aria-label",r),this.#S.dataset.state=e?"running":"idle",n&&this.#pr()}#pr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#a.style.height="auto",this.#a.style.height=`${this.#a.scrollHeight}px`}async#ft(){let e=this.#a.value.trim(),n=this.#k?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#a.value="",this.#Y());return}e!==""&&this.#de[0]!==e&&this.#de.unshift(e),this.#J=null,this.#a.value="",this.#Y(),this.#k?.hasPending()===!0&&this.#se("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#k.pendingCount())),"attachment-pending"),this.#k?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(cl(n)),this.dispatchEvent(new CustomEvent(Fs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#mr(e,n)}attachFile(e){return this.#k===null?!1:(this.#k.add(e),!0)}#fr(e){this.dispatchEvent(new CustomEvent(js,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#mr(e,n){if(this.endpoint===""){console.error('<ag-ui-chat>: no endpoint is set, so this message was not sent and no request was made. Point the element at your AG-UI mount with the endpoint attribute (endpoint="/agent/"), or assign chat.endpoint before sending.'),this.#se("\u26A0",this.#e.notConnected,"not-connected");return}await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:this.#Qe,initialState:this.#pe});this.#ne=new sr({agent:e,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:n=>this.#Jt(n),resolveInterrupts:n=>this.#en(n),onPersist:n=>this.conversationStore.saveMessages(this.#g,n),onStateChanged:n=>this.#gr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#kn()})}return this.#ne}#gr(e){this.#pe={...e},this.dispatchEvent(new CustomEvent(Vs,{detail:{state:this.#pe},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#In(),o=r.has($t.COPY),i=n.rateable!==!1&&r.has($t.FEEDBACK);(o||i)&&gl(e,{strings:this.#e,...o?{text:()=>es(e).text,html:()=>es(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ys,{detail:{content:es(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has($t.RETRY)&&this.#br(ts(e,this.#e))}#br(e){this.#N?.querySelector(".message-action--retry")?.remove();let n=ns("retry",this.#e.retryMessage,Fc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#N=e}async#vr(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#m.has(e.name)?null:qa(n.parameters)?"destructive":null}async#Jt(e){if(Np(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#c.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(re.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Qs&&!qi(r.parameters)&&this.#tr()){let s=this.#e.pageMoved;return n.settle(re.ERROR,s),this.#be(),{content:`Error: ${s}`,error:s,outcome:It.FAILED}}let o=await this.#vr(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[fo];typeof a=="string"&&(s.message=a),this.#U=new AbortController;let l=pl(this.#P(),s,{signal:this.#U.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#m.add(e.name)}:{}});this.#I(),this.#w.follow();let c=await l;if(this.#U=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(re.DECLINED,u),this.#be(),{content:u,outcome:It.DENIED}}}let i=qi(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#g,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#an(r.render,e),i)return n.settle(re.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(re.DONE,a),this.#be(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#g,null);let a=s instanceof Error?s.message:String(s);return n.settle(re.ERROR,a),this.#be(),{content:`Error: ${a}`,error:a,outcome:It.FAILED}}}async#en(e){this.#U=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#H();let n=this.#U.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=rE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(re.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await al(s?.approvalSlot??this.#P(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(re.PENDING):s?.settle(re.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#I(),this.#w.follow(),this.#U=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#tn(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#P(),this.#be()},onReasoningStart:()=>{this.#H(),this.#rn()},onReasoningDelta:e=>{this.#rn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#H(),this.#oe?.collapse(),this.#Tr(e),this.#Ye+=1},onTextEnd:e=>{let n=this.#vt(e);this.#Ye<=1&&this.#Kt(n),ll(n,this.#e),this.#gt(n),this.#ve(),this.#cr()},onToolCall:e=>{this.#H(),!this.#in(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Zs){this.#wr(n);return}if(e===Oc){this.#xr(n);return}this.dispatchEvent(new CustomEvent(Ws,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#u.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Cn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#nn(e,Cn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#nn(e,Cn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#se("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n,r)=>{let o=this.#i.get(e);o!==void 0&&(o.settle(_s(r),n),this.#p.add(e),this.#be())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#H(),this.#ve()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#H();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Kt(n),this.#ve()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#H(),this.#_r(),this.#ve()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#H(),this.#ie(!1),this.#ve();for(let e of this.#i.values())e.settled||e.settle(re.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#I()),this.#j=null,this.#oe=null,this.#yr()}}}#yr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#T];this.#T=new Set,this.dispatchEvent(new CustomEvent(qs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#wr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#T.add(o);this.dispatchEvent(new CustomEvent(Xs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#xr(e){let n=vp(e);n!==null&&this.#bt(n)}#nn(e,n,r){let o=this.#u.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#Er(i):r,tool:null})}#Er(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new ps(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#w.follow()}#_r(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#P().appendChild(e),this.#I(),this.#w.follow()}#be(){if(this.#De!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#De=e,this.#P().appendChild(e),this.#I(),this.#w.follow()}#H(){this.#De?.remove(),this.#De=null}#rn(){if(this.#oe===null){this.#oe=new ms(this.#e);let e=this.#P();e.insertBefore(this.#oe.element,e.firstChild),this.#I(),this.#w.follow()}return this.#oe}#on(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#Tr(e){this.#Pe=e,this.#on(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#on();return n.innerHTML=ds(e,{allowImages:this.allowImages}),this.#w.follow(),n}#ve(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#in(e){let n=Np(e);return n===null?!1:(this.#se("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#se(e,n,r,o){this.#P().appendChild(Bl(e,n,r,o)),this.#I(),this.#w.follow()}#sn(e,n){this.#se("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(mo)&&!this.#r.has(Ji);e.includes("activity")&&this.registerActivityRenderer({type:mo,render:r=>{let o=tr(r);return o===null?null:Or(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(ph()),n&&this.isConnected&&this.reload()}#an(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#c.get(n.id)?.after(r),this.#ln())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#l.delete(e.type)}get unhandledActivityTypes(){return[...this.#l]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#l.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Sr(e,n,o.removedNotice,r);return}let s=this.#d.get(e);s===void 0?this.#P().appendChild(i):s.replaceWith(i),this.#d.set(e,i),this.#ln()}#Sr(e,n,r,o){let i=this.#d.has(e);this.#d.get(e)?.remove(),this.#d.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#se("\u{1F4C9}",r,"chart-undrawable")}#ln(){this.#I(),this.#w.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??wl(e.name),i=new Wr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#P().appendChild(i.element),this.#I(),this.#w.follow(),i}};function rE(t){let e=t.metadata?.[fo];return typeof e=="string"&&e.trim()!==""?e:void 0}function oE(t){return Array.isArray(t)?t.filter(sE):[]}function iE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function sE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Np(t){if(t.name!==ta)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function aE(t){let e=t?.removed;return typeof e=="number"?e:null}function lE(){customElements.get(po)===void 0&&customElements.define(po,Qr)}async function cE(t,e,n={}){await _t(t),await Qa(t,{...n,flashMs:n.flashMs??0}),await Ka(t,e,n)}async function dE(t,e={}){await _t(t),await Za(t,e)}async function uE(t,e={}){await _t(t),await Ja(t,e)}async function hE(t,e,n={}){await _t(t),await el(t,e,n)}async function pE(t,e,n={}){await _t(t),await tl(t,e,n)}function fE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Rr(t,!!e):mn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var mE="0.37.0";export{js as ATTACHMENT_EVENT,Qr as AgUiChat,sr as AgUiClient,mo as CHART_ACTIVITY_TYPE,Ji as CHART_TOOL_NAME,ji as CHAT_CORNERS,ea as COMPACTION_ACTIVITY_TYPE,Ws as CUSTOM_AGENT_EVENT,Lr as CheckpointMenu,Ir as ClientToolRegistry,vs as ConnectionLostError,ae as DEFAULT_UI_STRINGS,po as ELEMENT_TAG,Ys as FEEDBACK_EVENT,Zs as INVALIDATE_CUSTOM_NAME,Xs as INVALIDATE_EVENT,ta as LOAD_CAPABILITY_TOOL,Py as MAX_QUOTE_CHARS,Gx as MAX_SUGGESTIONS,zx as MAX_SUGGESTION_CHARS,Nn as MAX_TOOL_ROUNDS,$t as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Nr as PAGE_ACTIONS,qs as RUN_FINISHED_EVENT,Kr as RemoteConversationStore,Zr as RunIndex,Vs as STATE_EVENT,Fs as SUBMIT_EVENT,Ks as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,$s as TOGGLE_EVENT,re as TOOL_CALL_STATUS,On as TOOL_DISPLAY,It as TOOL_OUTCOME,Wr as ToolCallCard,Bs as UNREAD_EVENT,mE as VERSION,fo as X_CONFIRM_KEY,hr as X_DESTRUCTIVE_KEY,pr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,bl as asQuote,gl as attachMessageActions,yl as attachQuoteOffer,tr as chartSpecFrom,dE as clickElement,ja as createChatSurfaceTools,Wl as createHttpAgent,nl as createPageActionTools,rl as createPageMapContext,Ki as createPageStateTools,il as createRouteTools,Bv as createStateHookTools,lE as defineAgUiChat,cE as fillField,Hv as flash,Qa as focusWithFlash,Za as highlightThenClick,rh as isChatCorner,qa as isDestructive,qi as isNavigates,sl as mergeUiStrings,ts as messageActionBar,jl as messageAttachments,ol as parseToolCatalog,Xi as prefersReducedMotion,uE as pressButton,Ja as pressThenClick,wl as prettifyToolName,Ur as quotableSelection,Mr as relativeTime,Or as renderChart,ds as renderMarkdown,fs as renderSuggestionChips,al as requestApproval,pl as requestConfirmation,xl as requestQuestion,_t as scrollIntoCenterView,hE as selectControl,el as selectOption,fE as setControlValue,Rr as setNativeChecked,mn as setNativeValue,Wa as showHighlightOverlay,yp as suggestionPrompts,pE as toggleCheckbox,tl as toggleControl,_s as toolStatusFromOutcome,Xl as transcribeAudio,Ka as typeInto,Yl as uploadAttachment};
3669
3669
  /*! Bundled license information:
3670
3670
 
3671
3671
  fast-json-patch/module/helpers.mjs: