@runtypelabs/persona 4.27.0 → 4.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/dist/{approval-ui-QAKWNFNM.js → approval-ui-OBBI62ES.js} +1 -1
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +20 -5
- package/dist/approval-ui.d.ts +20 -5
- package/dist/approval-ui.js +2 -2
- package/dist/artifacts-ui.d.cts +20 -5
- package/dist/artifacts-ui.d.ts +20 -5
- package/dist/{chunk-NQLDCJAP.js → chunk-D4TDKCT5.js} +2 -2
- package/dist/chunk-FNXK3VTC.js +1 -0
- package/dist/{client-history-HTRKHBAF.js → client-history-QGAFMCBE.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/{client-stream-N22JHTLE.js → client-stream-WXD2FL23.js} +1 -1
- package/dist/client-stream.js +3 -3
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +5 -5
- package/dist/context-mentions.d.cts +20 -5
- package/dist/context-mentions.d.ts +20 -5
- package/dist/event-stream-view.d.cts +20 -5
- package/dist/event-stream-view.d.ts +20 -5
- package/dist/forms-ui.d.cts +26 -5
- package/dist/forms-ui.d.ts +26 -5
- package/dist/index.cjs +41 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -30
- package/dist/index.d.ts +59 -30
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +41 -41
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +20 -5
- package/dist/session-reconnect.d.ts +20 -5
- package/dist/smart-dom-reader.d.cts +20 -5
- package/dist/smart-dom-reader.d.ts +20 -5
- package/dist/theme-editor-preview.cjs +63 -63
- package/dist/theme-editor-preview.d.cts +20 -5
- package/dist/theme-editor-preview.d.ts +20 -5
- package/dist/theme-editor-preview.js +6 -6
- package/dist/theme-editor.d.cts +21 -6
- package/dist/theme-editor.d.ts +21 -6
- package/dist/voice-runtime-TWFJ4UUS.js +17 -0
- package/dist/voice-runtime.cjs +8 -8
- package/dist/voice-runtime.d.cts +31 -5
- package/dist/voice-runtime.d.ts +31 -5
- package/dist/voice-runtime.js +8 -8
- package/dist/webmcp-runtime-5Q3IHAHP.js +6 -0
- package/dist/webmcp-runtime.cjs +2 -2
- package/dist/webmcp-runtime.d.cts +22 -26
- package/dist/webmcp-runtime.d.ts +22 -26
- package/dist/webmcp-runtime.js +2 -2
- package/package.json +5 -2
- package/src/client.interrupt.test.ts +18 -0
- package/src/client.ts +7 -0
- package/src/generated/runtype-openapi-contract.ts +3 -0
- package/src/session.ts +11 -3
- package/src/session.voice.test.ts +140 -0
- package/src/theme-editor/webmcp/types.ts +1 -1
- package/src/types.ts +26 -5
- package/src/voice/runtype-voice-provider.ts +93 -11
- package/src/voice/voice-clause-buffer.test.ts +143 -0
- package/src/voice/voice-clause-buffer.ts +187 -0
- package/src/voice/voice-delegation.ts +85 -3
- package/src/voice/voice.test.ts +257 -2
- package/src/webmcp-bridge.test.ts +87 -21
- package/src/webmcp-bridge.ts +21 -26
- package/src/webmcp-polyfill.integration.test.ts +339 -0
- package/src/webmcp-polyfill.ts +7 -4
- package/src/webmcp-runtime-bundle.test.ts +1 -1
- package/src/webmcp-runtime-entry.ts +34 -19
- package/dist/chunk-3255TNY7.js +0 -1
- package/dist/voice-runtime-RHRX4F3T.js +0 -17
- package/dist/webmcp-runtime-V6ZWW3PI.js +0 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
var c="webmcp:",u=new Map,w=t=>{u.clear();for(let r of t){let e=r.title?.trim();e&&u.set(r.name,e)}},_=t=>u.get(h(t)),g=null;function D(t){if(t.length===0)return"0:empty";let r=t.map(e=>[e.name,e.description??"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",e.origin??"",e.annotations?JSON.stringify(e.annotations):""].join("")).sort();return`${t.length}:${m(r.join(""))}`}function p(t,r){let e=3735928559^r,n=1103547991^r;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);e=Math.imul(e^s,2654435761),n=Math.imul(n^s,1597334677)}return e=Math.imul(e^e>>>16,2246822507),e^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(e^e>>>13,3266489909),4294967296*(2097151&n)+(e>>>0)}function m(t){let r=p(t,0).toString(36),e=p(t,2654435761).toString(36);return`${r}.${e}`}var h=t=>t.startsWith(c)?t.slice(c.length):t,E=t=>t.startsWith(c),k=()=>g?g():import("@mcp-b/webmcp-polyfill");import{parse as T,STR as M,OBJ as y}from"partial-json";var d=t=>t.replace(/\\n/g,`
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),J=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},W=t=>{let r=t.completedAt??Date.now(),e=t.startedAt??r,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,r-e))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},I=t=>t.status==="complete"?W(t):t.status==="pending"?"Waiting":"",b=15e3,P=1200,N=(t,r)=>{let e=r?.durationMs??b,n=r?.chars??P;return typeof t.durationMs=="number"?t.durationMs<e:(t.chunks??[]).join("").length<n},S=t=>{let e=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return e<.1?"Used tool for <0.1 seconds":`Used tool for ${e>=10?Math.round(e).toString():e.toFixed(1).replace(/\.0$/,"")} seconds`};var O=t=>t.status==="complete"?S(t):"Using tool...",x=t=>{let r=t/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},A=t=>{let r=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return x(r)},$=t=>{let r=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return x(r)},L=(t,r,e)=>{if(!r)return e;let n=t.name?.trim()||"tool",o=A(t);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},H=(t,r)=>{let e=t.replace(/\{toolName\}/g,r),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=o.exec(e))!==null;)i.index>s&&l(n,e.slice(s,i.index),[]),i[1]!==void 0?l(n,i[1],["bold"]):i[2]!==void 0?l(n,i[2],["italic"]):i[3]!==void 0&&l(n,i[3],["dim"]),s=i.index+i[0].length;return s<e.length&&l(n,e.slice(s),[]),n},l=(t,r,e)=>{let n=r.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&t.push({text:n[o],styles:e}),o<n.length-1&&t.push({text:"{duration}",styles:e,isDuration:!0})},R=()=>{let t=null,r=0,e=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=n.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=r)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=e(n);return s!==null&&(t=s),r=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=r)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=e(n);return s!==null&&(t=s),r=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},j=t=>{try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},U=()=>{let t={processChunk:r=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},B=()=>{let t=R();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},K=()=>{let t=null,r=0;return{getExtractedText:()=>t,processChunk:e=>{let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(e.length<=r)return t!==null||t===""?{text:t||"",raw:e}:null;try{let o=T(e,M|y);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?d(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=d(o.text)))}catch{}return r=e.length,t!==null?{text:t,raw:e}:null},close:()=>{}}};var X=()=>{let t=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(t=n[1],{text:t,raw:r}):null},getExtractedText:()=>t}};export{c as a,w as b,_ as c,D as d,E as e,k as f,J as g,I as h,N as i,O as j,x as k,A as l,$ as m,L as n,H as o,j as p,U as q,B as r,K as s,X as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t="4.28.1";var n=t;export{n as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as g}from"./chunk-
|
|
1
|
+
import{a as g}from"./chunk-FNXK3VTC.js";var H=32768,c=49152,p=t=>{let e=t??{},i=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:i,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},v="The identity proof was not admitted; account history is unavailable",m="The identity proof was rejected",C="The request carried no visitor credential",w="The stored visitor belongs to a different signed-in user";function E(t,e,i){let r=new URLSearchParams;for(let[n,s]of Object.entries(i))s===void 0||s===""||r.set(n,String(s));let o=r.toString();return`${t.clientApiBase()}/v1/client/${e}${o?`?${o}`:""}`}function b(t,e){if(e)return e;let i=t.config.features?.history?.scope;return i||(t.config.getIdentityProof?"verified-user":"browser")}async function T(t,e,i){let r=t.config.getIdentityProof;if(!r)return i&&t.setHistoryIdentityStatus(t.browserOnlyStatus()),null;i&&t.setHistoryIdentityStatus({state:"verifying"});let o;try{o=await r()??null}catch{throw i&&t.setHistoryIdentityStatus({state:"identity_provider_failed"}),new t.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(o)return o;if(e.visitor?.endUserId!=null)throw i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return i&&t.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function P(t,e,i,r){if(e.visitor?.endUserId!=null)return e;let o=await t.reinitWithProof(i);if(!(o.visitor?.identityStatus==="admitted"&&o.visitor?.endUserId!=null))throw r&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);return o}async function _(t,e){let i=await e.json().catch(()=>({}));return typeof i.error=="string"?i.error:typeof i.message=="string"?i.message:""}async function A(t,e,i,r){let o=e.toLowerCase();if(o.includes("invalid_identity_proof"))throw r&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",m);if(o.includes("visitor token required"))throw new t.HistoryClientError("visitor_token_missing",C);if(o.includes("visitor_identity_mismatch")){if(!i)throw r&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("visitor_identity_mismatch",w);return t.reinitWithProof(i)}if(o.includes("expired")||o.includes("not found"))return t.clearClientSession(),t.initSession();throw new t.HistoryClientError("unauthorized",e||"History request was not authorized")}async function h(t,e,i){let r=await _(t,e);if(e.status===404)return new t.HistoryClientError("not_found","Conversation not found");if(e.status===429){let o=Number.parseInt(e.headers.get("Retry-After")??"",10);return new t.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(o)?{retryAfterSeconds:o}:{}})}if(e.status===503&&r.includes("identity_proof_not_admitted"))return i&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);if(e.status===401){let o=r.toLowerCase();return o.includes("invalid_identity_proof")?(i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",m)):o.includes("visitor token required")?new t.HistoryClientError("visitor_token_missing",C):o.includes("visitor_identity_mismatch")?new t.HistoryClientError("visitor_identity_mismatch",w):new t.HistoryClientError("unauthorized",r||"History request was not authorized")}return new t.HistoryClientError("request_failed",r||`History request failed (${e.status})`)}function R(t,e,i,r){let o=e?.toLowerCase()??null;if(i){if(o==="admitted"){r&&t.setHistoryIdentityStatus({state:"verified"});return}throw r&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),o==="ignored"?new t.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new t.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(o==="admitted")throw new t.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");r&&t.setHistoryIdentityStatus(t.browserOnlyStatus())}async function y(t,e,i){f(t);let r=i.trackIdentity!==!1,o=await t.initSession(),n=null;b(t,i.scope)==="verified-user"&&(n=await T(t,o,r),n&&(o=await P(t,o,n,r)));let s=t.historyInternals.visitorStore,a=!1;for(;;){let u=s?.revision()??0,d=await t.readVisitorToken();if(!d&&!i.visitorTokenOptional)throw new t.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let l=await fetch(E(t,e,{...i.query,sessionId:o.sessionId}),{method:i.method,headers:{"X-Persona-Version":g,...d?{"X-Visitor-Token":d}:{},...n?{"X-Identity-Proof":n}:{},...i.body!==void 0?{"Content-Type":"application/json"}:{}},...i.body!==void 0?{body:JSON.stringify(i.body)}:{},...i.keepalive?{keepalive:!0}:{}});if(l.status===401&&!a){a=!0,o=await A(t,await _(t,l),n,r);continue}if(!l.ok)throw await h(t,l,r);let S=l.headers.get("X-History-Identity-Status"),I=await l.json().catch(()=>{});if(s&&s.revision()!==u)throw new t.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return R(t,S,n!==null,r),I}}function f(t){if(!t.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!t.isHistoryCapable())throw new t.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function O(t,e){let i=await y(t,"conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(i?.data)?i.data:[]).map(p),nextCursor:typeof i?.nextCursor=="string"?i.nextCursor:null}}async function x(t,e,i){let r=await y(t,`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...i?.messageCursor?{messageCursor:i.messageCursor}:{}},...i?.scope?{scope:i.scope}:{}});return{summary:p(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor=="string"?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision=="string"?r.conversationRevision:null}}async function q(t,e,i){f(t);let r=0;for(let u of i){let d=u.displayContent.length;if(d>H)throw new t.HistoryClientError("payload_too_large",`displayContent exceeds the ${H} character limit`);r+=d}if(r>c)throw new t.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${c} character limit`);await t.initSession();let o=t.historyInternals.visitorStore,n=o?.revision()??0,s=await y(t,`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:i},scope:"browser",keepalive:r<=c,trackIdentity:!1}),a=typeof s?.conversationRevision=="string"?s.conversationRevision:null;return a&&t.clientSession?.conversationId===e&&(o?.revision()??0)===n&&t.historyInternals.setStoredConversationRevision?.(a),{conversationRevision:a}}async function D(t,e,i){let r=await y(t,`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...i?.scope?{scope:i.scope}:{}});return{deleted:typeof r?.deleted=="number"?r.deleted:0}}async function M(t,e){let i=await y(t,"conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof i?.deleted=="number"?i.deleted:0}}async function N(t){f(t),t.setHistoryIdentityStatus({state:"resetting"});try{await y(t,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await t.historyInternals.visitorStore?.clear(),t.setHistoryIdentityStatus(t.derivedBrowserOnly())}return{reset:!0}}export{M as deleteAllConversations,D as deleteConversation,q as finalizeDisplayProjections,x as getConversation,h as historyErrorFor,O as listConversations,_ as readErrorCode,A as recoverFromUnauthorized,N as resetVisitor};
|
package/dist/client-history.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var y="4.
|
|
1
|
+
var y="4.28.1";var f=y;var g=32768,p=49152,b=t=>{let e=t??{},i=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:i,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},v="The identity proof was not admitted; account history is unavailable",w="The identity proof was rejected",H="The request carried no visitor credential",C="The stored visitor belongs to a different signed-in user";function j(t,e,i){let s=new URLSearchParams;for(let[r,o]of Object.entries(i))o===void 0||o===""||s.set(r,String(o));let n=s.toString();return`${t.clientApiBase()}/v1/client/${e}${n?`?${n}`:""}`}function I(t,e){if(e)return e;let i=t.config.features?.history?.scope;return i||(t.config.getIdentityProof?"verified-user":"browser")}async function E(t,e,i){let s=t.config.getIdentityProof;if(!s)return i&&t.setHistoryIdentityStatus(t.browserOnlyStatus()),null;i&&t.setHistoryIdentityStatus({state:"verifying"});let n;try{n=await s()??null}catch{throw i&&t.setHistoryIdentityStatus({state:"identity_provider_failed"}),new t.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(n)return n;if(e.visitor?.endUserId!=null)throw i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return i&&t.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function k(t,e,i,s){if(e.visitor?.endUserId!=null)return e;let n=await t.reinitWithProof(i);if(!(n.visitor?.identityStatus==="admitted"&&n.visitor?.endUserId!=null))throw s&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);return n}async function h(t,e){let i=await e.json().catch(()=>({}));return typeof i.error=="string"?i.error:typeof i.message=="string"?i.message:""}async function T(t,e,i,s){let n=e.toLowerCase();if(n.includes("invalid_identity_proof"))throw s&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",w);if(n.includes("visitor token required"))throw new t.HistoryClientError("visitor_token_missing",H);if(n.includes("visitor_identity_mismatch")){if(!i)throw s&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("visitor_identity_mismatch",C);return t.reinitWithProof(i)}if(n.includes("expired")||n.includes("not found"))return t.clearClientSession(),t.initSession();throw new t.HistoryClientError("unauthorized",e||"History request was not authorized")}async function q(t,e,i){let s=await h(t,e);if(e.status===404)return new t.HistoryClientError("not_found","Conversation not found");if(e.status===429){let n=Number.parseInt(e.headers.get("Retry-After")??"",10);return new t.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(e.status===503&&s.includes("identity_proof_not_admitted"))return i&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);if(e.status===401){let n=s.toLowerCase();return n.includes("invalid_identity_proof")?(i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",w)):n.includes("visitor token required")?new t.HistoryClientError("visitor_token_missing",H):n.includes("visitor_identity_mismatch")?new t.HistoryClientError("visitor_identity_mismatch",C):new t.HistoryClientError("unauthorized",s||"History request was not authorized")}return new t.HistoryClientError("request_failed",s||`History request failed (${e.status})`)}function P(t,e,i,s){let n=e?.toLowerCase()??null;if(i){if(n==="admitted"){s&&t.setHistoryIdentityStatus({state:"verified"});return}throw s&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),n==="ignored"?new t.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new t.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(n==="admitted")throw new t.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");s&&t.setHistoryIdentityStatus(t.browserOnlyStatus())}async function l(t,e,i){m(t);let s=i.trackIdentity!==!1,n=await t.initSession(),r=null;I(t,i.scope)==="verified-user"&&(r=await E(t,n,s),r&&(n=await k(t,n,r,s)));let o=t.historyInternals.visitorStore,a=!1;for(;;){let c=o?.revision()??0,d=await t.readVisitorToken();if(!d&&!i.visitorTokenOptional)throw new t.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(j(t,e,{...i.query,sessionId:n.sessionId}),{method:i.method,headers:{"X-Persona-Version":f,...d?{"X-Visitor-Token":d}:{},...r?{"X-Identity-Proof":r}:{},...i.body!==void 0?{"Content-Type":"application/json"}:{}},...i.body!==void 0?{body:JSON.stringify(i.body)}:{},...i.keepalive?{keepalive:!0}:{}});if(u.status===401&&!a){a=!0,n=await T(t,await h(t,u),r,s);continue}if(!u.ok)throw await q(t,u,s);let x=u.headers.get("X-History-Identity-Status"),_=await u.json().catch(()=>{});if(o&&o.revision()!==c)throw new t.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return P(t,x,r!==null,s),_}}function m(t){if(!t.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!t.isHistoryCapable())throw new t.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function z(t,e){let i=await l(t,"conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(i?.data)?i.data:[]).map(b),nextCursor:typeof i?.nextCursor=="string"?i.nextCursor:null}}async function M(t,e,i){let s=await l(t,`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...i?.messageCursor?{messageCursor:i.messageCursor}:{}},...i?.scope?{scope:i.scope}:{}});return{summary:b(s),messages:Array.isArray(s?.messages)?s.messages:[],nextMessageCursor:typeof s?.nextMessageCursor=="string"?s.nextMessageCursor:null,conversationRevision:typeof s?.conversationRevision=="string"?s.conversationRevision:null}}async function N(t,e,i){m(t);let s=0;for(let c of i){let d=c.displayContent.length;if(d>g)throw new t.HistoryClientError("payload_too_large",`displayContent exceeds the ${g} character limit`);s+=d}if(s>p)throw new t.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${p} character limit`);await t.initSession();let n=t.historyInternals.visitorStore,r=n?.revision()??0,o=await l(t,`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:i},scope:"browser",keepalive:s<=p,trackIdentity:!1}),a=typeof o?.conversationRevision=="string"?o.conversationRevision:null;return a&&t.clientSession?.conversationId===e&&(n?.revision()??0)===r&&t.historyInternals.setStoredConversationRevision?.(a),{conversationRevision:a}}async function L(t,e,i){let s=await l(t,`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...i?.scope?{scope:i.scope}:{}});return{deleted:typeof s?.deleted=="number"?s.deleted:0}}async function U(t,e){let i=await l(t,"conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof i?.deleted=="number"?i.deleted:0}}async function $(t){m(t),t.setHistoryIdentityStatus({state:"resetting"});try{await l(t,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await t.historyInternals.visitorStore?.clear(),t.setHistoryIdentityStatus(t.derivedBrowserOnly())}return{reset:!0}}export{U as deleteAllConversations,L as deleteConversation,N as finalizeDisplayProjections,M as getConversation,q as historyErrorFor,z as listConversations,h as readErrorCode,T as recoverFromUnauthorized,$ as resetVisitor};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as me,d as ye,e as Ie}from"./chunk-K6HKIP5K.js";import"./chunk-K7NA7G7J.js";import{d as we}from"./chunk-2ANTRKTV.js";import"./chunk-TR2H475E.js";import{e as de,p as z}from"./chunk-NQLDCJAP.js";import"./chunk-76IELU7F.js";async function Te(d,h,m){let g={"Content-Type":"application/json",...d.headers};d.getHeaders&&Object.assign(g,await d.getHeaders());let M={executionId:h.executionId,approvalId:h.approvalId,decision:m,streamResponse:!0},x=(k,p)=>fetch(`${d.clientApiBase()}${k}`,{method:"POST",headers:g,body:JSON.stringify({...p,...M})}),A=`/v1/agents/${h.agentId}/approve`;if(!d.isClientTokenMode())return x(A);let{sessionId:y}=await d.initSession(),S=await x("/v1/client/approve",{sessionId:y});if(S.status===404){let k=await S.clone().json().catch(()=>null);if(!k||k.error==="Not Found")return x(A)}return S}async function Se(d,h,m,g){let M=d.isClientTokenMode(),x=M?d.getClientApiUrl("resume"):`${d.config.apiUrl?.replace(/\/+$/,"")||we}/resume`,A,y=null;if(M){let p=await d.initSession();A=p.sessionId,p.durableRecovery?.enabled===!0&&(y=await d.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...d.headers};d.getHeaders&&Object.assign(S,await d.getHeaders());let k={executionId:h,toolOutputs:m,streamResponse:g?.streamResponse??!0,...g?.after?{after:g.after}:{}};if(A&&(k.sessionId=A),M&&A){let p=[...Ie(d.config),...await(await d.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:D,commit:ee}=await d.sendWithClientToolsDiff(A,p,l=>{let f={...k,...l};return d.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(x,{method:"POST",headers:S,body:JSON.stringify(f),signal:g?.signal})},{emptyMeansReplace:!0});return D.ok&&ee(),D}return fetch(x,{method:"POST",headers:S,body:JSON.stringify(k),signal:g?.signal})}function ke(d){let h=d.toLowerCase(),g={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[h];if(g)return`attachment.${g}`;let M=h.indexOf("/");if(M>0){let x=h.slice(M+1).split(";")[0]?.trim()??"";if(x&&x!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(x))return`attachment.${x}`}return"attachment"}var he=d=>d.startsWith("{")||d.startsWith("[")||d.startsWith("<");function We(d,h){if(!d)return h;let m=d.trim(),g=h.trim();if(m.length===0)return h;if(g.length===0)return d;let M=he(m);if(!he(g))return d;if(!M||g===m||g.startsWith(m))return h;let A=z(d);return z(h)!==null&&A===null?h:d}async function be(d,h,m,g,M,x,A){if(!d.parseSSEEvent)return!1;try{let y=await d.parseSSEEvent(h);if(y===null)return!1;let S=p=>{let D={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:x(),...p!==void 0&&{partId:p}};return g.current=D,M(D),D},k=p=>g.current?g.current:S(p);if(y.text!==void 0){y.partId!==void 0&&A.current!==null&&y.partId!==A.current&&(g.current&&(g.current.streaming=!1,M(g.current)),S(y.partId)),y.partId!==void 0&&(A.current=y.partId);let p=k(y.partId);y.partId!==void 0&&!p.partId&&(p.partId=y.partId),p.content+=y.text,M(p)}return y.done&&(g.current&&(g.current.streaming=!1,M(g.current)),A.current=null,m({type:"status",status:"idle"})),y.error&&(A.current=null,m({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function Ee(d,h,m,g,M){let x=h.getReader(),A=new TextDecoder,y="",S=Date.now(),k=0,p=()=>S+k++,D=n=>{let e=n.reasoning?{...n.reasoning,chunks:[...n.reasoning.chunks]}:void 0,t=n.toolCall?{...n.toolCall,chunks:n.toolCall.chunks?[...n.toolCall.chunks]:void 0}:void 0,o=n.tools?n.tools.map(s=>({...s,chunks:s.chunks?[...s.chunks]:void 0})):void 0;return{...n,reasoning:e,toolCall:t,tools:o}},ee=n=>{if(n.role!=="assistant"||n.variant)return!0;let e=Array.isArray(n.contentParts)&&n.contentParts.length>0,t=typeof n.rawContent=="string"&&n.rawContent.trim()!=="";return typeof n.content=="string"&&n.content.trim()!==""||e||t||!!n.stopReason},l=n=>{ee(n)&&m({type:"message",message:D(n)})},f=null,U=null,O={current:null},Ce={current:null},F=null,E="",$=new Map,v=new Map,te=new Map,Q=new Map,ne=new Map,X=g,ce=!1,oe=()=>{if(f)return f;let n,e="",t=F;return!ce&&X?(n=X,ce=!0,e=M??""):X&&t?n=`${X}_${t}`:n=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:n,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},l(f),f},se=n=>{let e=Q.get(n);if(e)return e;let t={id:`reason-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:n,status:"streaming",chunks:[]}};return Q.set(n,t),l(t),t},H=new Set,re=new Map,ue=new Set,J=new Map,Ae=n=>{if(!n)return!1;let e=n.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},L=n=>{let e=ne.get(n);if(e)return e;let t={id:`tool-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:n,status:"pending"}};return ne.set(n,t),l(t),t},ge=n=>{if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let e=Number(n);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(n);if(!Number.isNaN(t))return t}return Date.now()},ie=n=>{if(typeof n=="string")return n;if(n==null)return"";try{return JSON.stringify(n)}catch{return String(n)}},T=new Map,W=new Map,Me=(n,e)=>{let t=ie(e),o=W.get(n.id),s=We(o,t);n.rawContent=s;let r=T.get(n.id),i=I=>{let u=n.content??"";I.trim()!==""&&(u.trim().length===0||I.startsWith(u)||I.trimStart().startsWith(u.trim()))&&(n.content=I)},c=()=>{if(r){let I=r.close?.();I instanceof Promise&&I.catch(()=>{})}T.delete(n.id),W.delete(n.id),n.streaming=!1,l(n)};if(!r){i(t),c();return}let a=z(s);if(a!==null&&a.trim()!==""){i(a),c();return}let w=I=>{let u=typeof I=="string"?I:I?.text??null;if(u!==null&&u.trim()!=="")return u;let N=r.getExtractedText();return N!==null&&N.trim()!==""?N:t},C;try{C=r.processChunk(s)}catch{i(t),c();return}if(C instanceof Promise){C.then(I=>{i(w(I)),c()}).catch(()=>{i(t),c()});return}i(w(C)),c()},K=null,ae=(n,e,t,o)=>{n.rawContent=e,T.has(n.id)||T.set(n.id,d.createStreamParser());let s=T.get(n.id),r=e.trim().startsWith("{")||e.trim().startsWith("[");if(r&&W.set(n.id,e),s.__isPlainTextParser===!0){n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n);return}let c=s.processChunk(e);if(c instanceof Promise)c.then(a=>{let w=typeof a=="string"?a:a?.text??null;w!==null&&w.trim()!==""?(n.content=w,l(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n))}).catch(()=>{n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n)});else{let a=typeof c=="string"?c:c?.text??null;a!==null&&a.trim()!==""?(n.content=a,l(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n))}},V=(n,e)=>{let t=e??n.content;if(t==null||t===""){n.streaming=!1,l(n);return}let s=W.get(n.id)??ie(t);n.rawContent=s;let r=T.get(n.id),i=null,c=!1;if(r&&(i=r.getExtractedText(),i===null&&(i=z(s)),i===null)){let a=r.processChunk(s);a instanceof Promise?(c=!0,a.then(w=>{let C=typeof w=="string"?w:w?.text??null;C!==null&&(n.content=C,n.streaming=!1,T.delete(n.id),W.delete(n.id),l(n))}).catch(()=>{})):i=typeof a=="string"?a:a?.text??null}if(!c){i!==null&&i.trim()!==""?n.content=i:W.has(n.id)||(n.content=ie(t));let a=T.get(n.id);if(a){let w=a.close?.();w instanceof Promise&&w.catch(()=>{}),T.delete(n.id)}W.delete(n.id),n.streaming=!1,l(n)}},pe=(n,e,t)=>{let o=v.get(n);if(o)return o;let s={id:`nested-${e}-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:n,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(n,s),l(s),s},G=[],le,Y=new Map,_=0,B="agent",fe=!1,Z=null,j=null,xe=d.config().iterationDisplay??"separate";for(le=()=>{for(let n=0;n<G.length;n++){let e=G[n];if(!fe&&B!=="flow"&&typeof e.stepType=="string"&&(B="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o),pe(t,o,"reasoning");continue}let s=e.id,r=se(s);r.reasoning=r.reasoning??{id:s,status:"streaming",chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),r.streaming=!0,r.reasoning.status="streaming",l(r)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let r=v.get(t),i=e.delta;i&&r.reasoning&&(r.reasoning.chunks.push(String(i)),l(r));continue}let o=e.id,s=se(o);s.reasoning=s.reasoning??{id:o,status:"streaming",chunks:[]},s.reasoning.startedAt=s.reasoning.startedAt??Date.now(),e.delta&&s.reasoning.chunks.push(e.delta),s.reasoning.status="streaming",s.streaming=!0,l(s)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let i=v.get(t);if(i.reasoning){let c=typeof e.text=="string"?e.text:"";c&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(c),i.reasoning.status="complete",i.streaming=!1,l(i)}$.delete(t),v.delete(t);continue}let o=e.id,s=typeof e.text=="string"?e.text:"";!Q.get(o)&&(s||e.scope==="loop")&&se(o);let r=Q.get(o);if(r?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),s&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(s),r.reasoning.status="complete",r.reasoning.completedAt=Date.now();let i=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-i),r.streaming=!1,l(r)}}else if(e.type==="tool_start"){f&&(f.streaming=!1,l(f),f=null),typeof e.iteration=="number"&&(_=e.iteration);let t=e.toolCallId,o=e.toolName;if(Ae(o)){H.add(t);continue}let s=L(t),r=s.toolCall??{id:t,status:"pending"};r.name=o??r.name,r.status="running",r.success=void 0,r.error=void 0,r.duration=void 0,e.parameters!==void 0&&(r.args=e.parameters),r.startedAt=r.startedAt??ge(e.startedAt),r.completedAt=void 0,r.durationMs=void 0,s.toolCall=r,s.streaming=!0,e.executionId&&(s.agentMetadata={executionId:e.executionId,iteration:e.iteration}),l(s)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(H.has(t))continue;let o=L(t),s=o.toolCall??{id:t,status:"running"};s.startedAt=s.startedAt??Date.now();let r=e.delta;r&&(s.chunks=s.chunks??[],s.chunks.push(String(r))),s.status="running",o.toolCall=s,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:_}),l(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(H.has(t)){H.delete(t);continue}let o=L(t),s=o.toolCall??{id:t,status:"running"};s.status="complete",e.result!==void 0&&(s.result=e.result),s.name=e.toolName??s.name,s.success=e.success,s.error=e.error,s.completedAt=Date.now();let r=e.executionTime;if(typeof r=="number")s.durationMs=r,s.duration=r;else{let i=s.startedAt??Date.now();s.durationMs=Math.max(0,(s.completedAt??Date.now())-i)}o.toolCall=s,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??_}),l(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${p()}`,s=L(o),r=e.toolName,i=e.origin==="webmcp"&&!de(r)?`webmcp:${r}`:r,c=de(i),a=s.toolCall??{id:o,status:"pending"};a.name=i,a.args=e.parameters,a.status=c?"running":"complete",a.chunks=a.chunks??[],a.startedAt=a.startedAt??ge(e.awaitedAt),c?(a.completedAt=void 0,a.duration=void 0,a.durationMs=void 0):a.completedAt=a.completedAt??a.startedAt,s.toolCall=a,s.streaming=!1,s.agentMetadata={...s.agentMetadata,executionId:e.executionId??s.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},l(s)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o);continue}let s=f;s&&(B==="flow"?(V(s),K=s):(s.streaming=!1,l(s)),f=null),F=typeof e.id=="string"?e.id:F,E=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?$.get(t):void 0;if(t&&o){let i=typeof e.delta=="string"?e.delta:"",c=(te.get(t)??"")+i;if(te.set(t,c),c.trim()==="")continue;let a=pe(t,o);a.agentMetadata={...a.agentMetadata,executionId:e.executionId,parentToolId:o},ae(a,c,i,void 0);continue}if(F=typeof e.id=="string"?e.id:F,B==="flow"){let i=typeof e.delta=="string"?e.delta:"";if(E+=i,E.trim()==="")continue;let c=oe();c.agentMetadata={executionId:e.executionId,iteration:_},ae(c,E,i,void 0),U=c;continue}let s=typeof e.delta=="string"?e.delta:"";E+=s;let r=oe();r.agentMetadata={executionId:e.executionId,iteration:_,turnId:Z??void 0,agentName:j?.agentName},ae(r,E,s,void 0),U=r}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)){let s=v.get(t);s&&V(s),$.delete(t),te.delete(t),v.delete(t);continue}let o=f;o&&(B==="flow"?(V(o),K=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,l(o)),f=null),F=null,E=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,l(o)),m({type:"status",status:"idle"});continue}{let t=K;K=null;let o=e.stopReason,r=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),r!=null?Me(t,r):t.streaming!==!1&&(T.delete(t.id),W.delete(t.id),t.streaming=!1,l(t));else{let i=r!=null&&r!=="";if(i||!!o&&o!=="end_turn"&&o!=="unknown"){let a=oe();o&&(a.stopReason=o),i?V(a,r):(a.streaming=!1,l(a))}}continue}}else if(e.type==="execution_start")B=e.kind==="flow"?"flow":"agent",fe=!0,B==="agent"&&(j={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:_;if(t!==_){if(xe==="separate"&&t>1){let o=f;o&&(o.streaming=!1,l(o),f=null)}_=t}Z=typeof e.id=="string"?e.id:null,U=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ne.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),l(o))}}else if(e.type==="tool_input_complete"){if(H.has(e.toolCallId))continue;let t=L(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,l(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=f??U;if(t&&o!==null){let s=e.id;(!s||o.agentMetadata?.turnId===s)&&(o.stopReason=t,l(o))}Z===e.id&&(Z=null)}else if(e.type==="media_start"){let t=String(e.id);Y.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=Y.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=Y.get(t);Y.delete(t);let s=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",r=typeof e.data=="string"?e.data:void 0,i=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,c=null;if(r)c={type:"media",data:r,mediaType:s};else if(i){let I=s.toLowerCase();c={type:I==="image"||I.startsWith("image/")?"image-url":"file-url",url:i,mediaType:s}}let a=e.toolCallId??o?.toolCallId,w=c?[c]:[],C=[];for(let I of w){if(!I||typeof I!="object")continue;let u=I,N=typeof u.type=="string"?u.type:void 0,q=typeof u.mediaType=="string"?u.mediaType.toLowerCase():"",b=null,P="";if(N==="media"){let R=typeof u.data=="string"?u.data:void 0;if(!R)continue;P=q.length>0?q:"application/octet-stream",b=`data:${P};base64,${R}`}else if(N==="image-url"){let R=typeof u.url=="string"?u.url:void 0;if(!R)continue;P=q,b=R}else if(N==="file-url"){let R=typeof u.url=="string"?u.url:void 0;if(!R)continue;P=q,b=R}else continue;if(b)if(N==="image-url"||P.startsWith("image/"))C.push({type:"image",image:b,...P.includes("/")?{mimeType:P}:{}});else if(P.startsWith("audio/"))C.push({type:"audio",audio:b,mimeType:P});else if(P.startsWith("video/"))C.push({type:"video",video:b,mimeType:P});else{let R=P||"application/octet-stream";C.push({type:"file",data:b,mimeType:R,filename:ke(R)})}}if(C.length>0){let I=p(),u=a,q={id:`agent-media-${typeof u=="string"&&u.length>0?`${u}-${I}`:String(I)}`,role:"assistant",content:"",contentParts:C,createdAt:new Date().toISOString(),streaming:!1,sequence:I,agentMetadata:{executionId:e.executionId,iteration:_}};l(q);let b=f;b&&(b.streaming=!1,l(b)),f=null,O.current=null}}else if(e.type==="execution_complete"){let t=f;t&&(e.kind==="flow"&&t.streaming!==!1?V(t):(t.streaming=!1,l(t)),f=null),F=null,E="",K=null,m({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";m({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${p()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:"pending",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};l(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let s={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:e.decision??"approved",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};l(s)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),s=typeof e.title=="string"?e.title:void 0,r=e.file,i;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.path=="string"&&typeof r.mimeType=="string"&&(i={path:r.path,mimeType:r.mimeType,...typeof r.language=="string"?{language:r.language}:{}}),m({type:"artifact_start",id:o,artifactType:t,title:s,component:typeof e.component=="string"?e.component:void 0,...i?{file:i}:{}}),J.set(o,{markdown:"",title:s,file:i}),!ue.has(o)){ue.add(o);let c=me(d.config().features?.artifacts,{artifactType:t,...i?{file:i}:{}}),a=typeof e.component=="string"?e.component:void 0,w={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:ye(c,{artifactId:o,title:s,artifactType:t,status:"streaming",...i?{file:i}:{},...a?{component:a}:{}})};re.set(o,w),l(w)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");m({type:"artifact_delta",id:t,artDelta:o});let s=J.get(t);s&&(s.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};m({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=J.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);m({type:"artifact_complete",id:t});let o=re.get(t);if(o){o.streaming=!1;try{let s=JSON.parse(o.rawContent??"{}");if(s.props){s.props.status="complete";let r=J.get(t);r?.markdown&&(s.props.markdown=r.markdown),r?.file&&(s.props.file=r.file),s.component==="PersonaArtifactInline"&&r?.props&&Object.keys(r.props).length>0&&(s.props.componentProps=r.props)}o.rawContent=JSON.stringify(s)}catch{}J.delete(t),l(o),re.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,l(o)),m({type:"status",status:"idle"})}}}G.length=0};;){let{done:n,value:e}=await x.read();if(n)break;y+=A.decode(e,{stream:!0});let t=y.split(`
|
|
1
|
+
import{c as me,d as ye,e as Ie}from"./chunk-K6HKIP5K.js";import"./chunk-K7NA7G7J.js";import{d as we}from"./chunk-2ANTRKTV.js";import"./chunk-TR2H475E.js";import{e as de,p as z}from"./chunk-D4TDKCT5.js";import"./chunk-76IELU7F.js";async function Te(d,h,m){let g={"Content-Type":"application/json",...d.headers};d.getHeaders&&Object.assign(g,await d.getHeaders());let M={executionId:h.executionId,approvalId:h.approvalId,decision:m,streamResponse:!0},x=(k,p)=>fetch(`${d.clientApiBase()}${k}`,{method:"POST",headers:g,body:JSON.stringify({...p,...M})}),A=`/v1/agents/${h.agentId}/approve`;if(!d.isClientTokenMode())return x(A);let{sessionId:y}=await d.initSession(),S=await x("/v1/client/approve",{sessionId:y});if(S.status===404){let k=await S.clone().json().catch(()=>null);if(!k||k.error==="Not Found")return x(A)}return S}async function Se(d,h,m,g){let M=d.isClientTokenMode(),x=M?d.getClientApiUrl("resume"):`${d.config.apiUrl?.replace(/\/+$/,"")||we}/resume`,A,y=null;if(M){let p=await d.initSession();A=p.sessionId,p.durableRecovery?.enabled===!0&&(y=await d.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...d.headers};d.getHeaders&&Object.assign(S,await d.getHeaders());let k={executionId:h,toolOutputs:m,streamResponse:g?.streamResponse??!0,...g?.after?{after:g.after}:{}};if(A&&(k.sessionId=A),M&&A){let p=[...Ie(d.config),...await(await d.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:D,commit:ee}=await d.sendWithClientToolsDiff(A,p,l=>{let f={...k,...l};return d.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(x,{method:"POST",headers:S,body:JSON.stringify(f),signal:g?.signal})},{emptyMeansReplace:!0});return D.ok&&ee(),D}return fetch(x,{method:"POST",headers:S,body:JSON.stringify(k),signal:g?.signal})}function ke(d){let h=d.toLowerCase(),g={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[h];if(g)return`attachment.${g}`;let M=h.indexOf("/");if(M>0){let x=h.slice(M+1).split(";")[0]?.trim()??"";if(x&&x!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(x))return`attachment.${x}`}return"attachment"}var he=d=>d.startsWith("{")||d.startsWith("[")||d.startsWith("<");function We(d,h){if(!d)return h;let m=d.trim(),g=h.trim();if(m.length===0)return h;if(g.length===0)return d;let M=he(m);if(!he(g))return d;if(!M||g===m||g.startsWith(m))return h;let A=z(d);return z(h)!==null&&A===null?h:d}async function be(d,h,m,g,M,x,A){if(!d.parseSSEEvent)return!1;try{let y=await d.parseSSEEvent(h);if(y===null)return!1;let S=p=>{let D={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:x(),...p!==void 0&&{partId:p}};return g.current=D,M(D),D},k=p=>g.current?g.current:S(p);if(y.text!==void 0){y.partId!==void 0&&A.current!==null&&y.partId!==A.current&&(g.current&&(g.current.streaming=!1,M(g.current)),S(y.partId)),y.partId!==void 0&&(A.current=y.partId);let p=k(y.partId);y.partId!==void 0&&!p.partId&&(p.partId=y.partId),p.content+=y.text,M(p)}return y.done&&(g.current&&(g.current.streaming=!1,M(g.current)),A.current=null,m({type:"status",status:"idle"})),y.error&&(A.current=null,m({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function Ee(d,h,m,g,M){let x=h.getReader(),A=new TextDecoder,y="",S=Date.now(),k=0,p=()=>S+k++,D=n=>{let e=n.reasoning?{...n.reasoning,chunks:[...n.reasoning.chunks]}:void 0,t=n.toolCall?{...n.toolCall,chunks:n.toolCall.chunks?[...n.toolCall.chunks]:void 0}:void 0,o=n.tools?n.tools.map(s=>({...s,chunks:s.chunks?[...s.chunks]:void 0})):void 0;return{...n,reasoning:e,toolCall:t,tools:o}},ee=n=>{if(n.role!=="assistant"||n.variant)return!0;let e=Array.isArray(n.contentParts)&&n.contentParts.length>0,t=typeof n.rawContent=="string"&&n.rawContent.trim()!=="";return typeof n.content=="string"&&n.content.trim()!==""||e||t||!!n.stopReason},l=n=>{ee(n)&&m({type:"message",message:D(n)})},f=null,U=null,O={current:null},Ce={current:null},F=null,E="",$=new Map,v=new Map,te=new Map,Q=new Map,ne=new Map,X=g,ce=!1,oe=()=>{if(f)return f;let n,e="",t=F;return!ce&&X?(n=X,ce=!0,e=M??""):X&&t?n=`${X}_${t}`:n=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:n,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},l(f),f},se=n=>{let e=Q.get(n);if(e)return e;let t={id:`reason-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:n,status:"streaming",chunks:[]}};return Q.set(n,t),l(t),t},H=new Set,re=new Map,ue=new Set,J=new Map,Ae=n=>{if(!n)return!1;let e=n.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},L=n=>{let e=ne.get(n);if(e)return e;let t={id:`tool-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:n,status:"pending"}};return ne.set(n,t),l(t),t},ge=n=>{if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let e=Number(n);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(n);if(!Number.isNaN(t))return t}return Date.now()},ie=n=>{if(typeof n=="string")return n;if(n==null)return"";try{return JSON.stringify(n)}catch{return String(n)}},T=new Map,W=new Map,Me=(n,e)=>{let t=ie(e),o=W.get(n.id),s=We(o,t);n.rawContent=s;let r=T.get(n.id),i=I=>{let u=n.content??"";I.trim()!==""&&(u.trim().length===0||I.startsWith(u)||I.trimStart().startsWith(u.trim()))&&(n.content=I)},c=()=>{if(r){let I=r.close?.();I instanceof Promise&&I.catch(()=>{})}T.delete(n.id),W.delete(n.id),n.streaming=!1,l(n)};if(!r){i(t),c();return}let a=z(s);if(a!==null&&a.trim()!==""){i(a),c();return}let w=I=>{let u=typeof I=="string"?I:I?.text??null;if(u!==null&&u.trim()!=="")return u;let N=r.getExtractedText();return N!==null&&N.trim()!==""?N:t},C;try{C=r.processChunk(s)}catch{i(t),c();return}if(C instanceof Promise){C.then(I=>{i(w(I)),c()}).catch(()=>{i(t),c()});return}i(w(C)),c()},K=null,ae=(n,e,t,o)=>{n.rawContent=e,T.has(n.id)||T.set(n.id,d.createStreamParser());let s=T.get(n.id),r=e.trim().startsWith("{")||e.trim().startsWith("[");if(r&&W.set(n.id,e),s.__isPlainTextParser===!0){n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n);return}let c=s.processChunk(e);if(c instanceof Promise)c.then(a=>{let w=typeof a=="string"?a:a?.text??null;w!==null&&w.trim()!==""?(n.content=w,l(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n))}).catch(()=>{n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n)});else{let a=typeof c=="string"?c:c?.text??null;a!==null&&a.trim()!==""?(n.content=a,l(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,l(n))}},V=(n,e)=>{let t=e??n.content;if(t==null||t===""){n.streaming=!1,l(n);return}let s=W.get(n.id)??ie(t);n.rawContent=s;let r=T.get(n.id),i=null,c=!1;if(r&&(i=r.getExtractedText(),i===null&&(i=z(s)),i===null)){let a=r.processChunk(s);a instanceof Promise?(c=!0,a.then(w=>{let C=typeof w=="string"?w:w?.text??null;C!==null&&(n.content=C,n.streaming=!1,T.delete(n.id),W.delete(n.id),l(n))}).catch(()=>{})):i=typeof a=="string"?a:a?.text??null}if(!c){i!==null&&i.trim()!==""?n.content=i:W.has(n.id)||(n.content=ie(t));let a=T.get(n.id);if(a){let w=a.close?.();w instanceof Promise&&w.catch(()=>{}),T.delete(n.id)}W.delete(n.id),n.streaming=!1,l(n)}},pe=(n,e,t)=>{let o=v.get(n);if(o)return o;let s={id:`nested-${e}-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:n,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(n,s),l(s),s},G=[],le,Y=new Map,_=0,B="agent",fe=!1,Z=null,j=null,xe=d.config().iterationDisplay??"separate";for(le=()=>{for(let n=0;n<G.length;n++){let e=G[n];if(!fe&&B!=="flow"&&typeof e.stepType=="string"&&(B="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o),pe(t,o,"reasoning");continue}let s=e.id,r=se(s);r.reasoning=r.reasoning??{id:s,status:"streaming",chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),r.streaming=!0,r.reasoning.status="streaming",l(r)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let r=v.get(t),i=e.delta;i&&r.reasoning&&(r.reasoning.chunks.push(String(i)),l(r));continue}let o=e.id,s=se(o);s.reasoning=s.reasoning??{id:o,status:"streaming",chunks:[]},s.reasoning.startedAt=s.reasoning.startedAt??Date.now(),e.delta&&s.reasoning.chunks.push(e.delta),s.reasoning.status="streaming",s.streaming=!0,l(s)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let i=v.get(t);if(i.reasoning){let c=typeof e.text=="string"?e.text:"";c&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(c),i.reasoning.status="complete",i.streaming=!1,l(i)}$.delete(t),v.delete(t);continue}let o=e.id,s=typeof e.text=="string"?e.text:"";!Q.get(o)&&(s||e.scope==="loop")&&se(o);let r=Q.get(o);if(r?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),s&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(s),r.reasoning.status="complete",r.reasoning.completedAt=Date.now();let i=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-i),r.streaming=!1,l(r)}}else if(e.type==="tool_start"){f&&(f.streaming=!1,l(f),f=null),typeof e.iteration=="number"&&(_=e.iteration);let t=e.toolCallId,o=e.toolName;if(Ae(o)){H.add(t);continue}let s=L(t),r=s.toolCall??{id:t,status:"pending"};r.name=o??r.name,r.status="running",r.success=void 0,r.error=void 0,r.duration=void 0,e.parameters!==void 0&&(r.args=e.parameters),r.startedAt=r.startedAt??ge(e.startedAt),r.completedAt=void 0,r.durationMs=void 0,s.toolCall=r,s.streaming=!0,e.executionId&&(s.agentMetadata={executionId:e.executionId,iteration:e.iteration}),l(s)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(H.has(t))continue;let o=L(t),s=o.toolCall??{id:t,status:"running"};s.startedAt=s.startedAt??Date.now();let r=e.delta;r&&(s.chunks=s.chunks??[],s.chunks.push(String(r))),s.status="running",o.toolCall=s,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:_}),l(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(H.has(t)){H.delete(t);continue}let o=L(t),s=o.toolCall??{id:t,status:"running"};s.status="complete",e.result!==void 0&&(s.result=e.result),s.name=e.toolName??s.name,s.success=e.success,s.error=e.error,s.completedAt=Date.now();let r=e.executionTime;if(typeof r=="number")s.durationMs=r,s.duration=r;else{let i=s.startedAt??Date.now();s.durationMs=Math.max(0,(s.completedAt??Date.now())-i)}o.toolCall=s,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??_}),l(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${p()}`,s=L(o),r=e.toolName,i=e.origin==="webmcp"&&!de(r)?`webmcp:${r}`:r,c=de(i),a=s.toolCall??{id:o,status:"pending"};a.name=i,a.args=e.parameters,a.status=c?"running":"complete",a.chunks=a.chunks??[],a.startedAt=a.startedAt??ge(e.awaitedAt),c?(a.completedAt=void 0,a.duration=void 0,a.durationMs=void 0):a.completedAt=a.completedAt??a.startedAt,s.toolCall=a,s.streaming=!1,s.agentMetadata={...s.agentMetadata,executionId:e.executionId??s.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},l(s)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o);continue}let s=f;s&&(B==="flow"?(V(s),K=s):(s.streaming=!1,l(s)),f=null),F=typeof e.id=="string"?e.id:F,E=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?$.get(t):void 0;if(t&&o){let i=typeof e.delta=="string"?e.delta:"",c=(te.get(t)??"")+i;if(te.set(t,c),c.trim()==="")continue;let a=pe(t,o);a.agentMetadata={...a.agentMetadata,executionId:e.executionId,parentToolId:o},ae(a,c,i,void 0);continue}if(F=typeof e.id=="string"?e.id:F,B==="flow"){let i=typeof e.delta=="string"?e.delta:"";if(E+=i,E.trim()==="")continue;let c=oe();c.agentMetadata={executionId:e.executionId,iteration:_},ae(c,E,i,void 0),U=c;continue}let s=typeof e.delta=="string"?e.delta:"";E+=s;let r=oe();r.agentMetadata={executionId:e.executionId,iteration:_,turnId:Z??void 0,agentName:j?.agentName},ae(r,E,s,void 0),U=r}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)){let s=v.get(t);s&&V(s),$.delete(t),te.delete(t),v.delete(t);continue}let o=f;o&&(B==="flow"?(V(o),K=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,l(o)),f=null),F=null,E=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,l(o)),m({type:"status",status:"idle"});continue}{let t=K;K=null;let o=e.stopReason,r=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),r!=null?Me(t,r):t.streaming!==!1&&(T.delete(t.id),W.delete(t.id),t.streaming=!1,l(t));else{let i=r!=null&&r!=="";if(i||!!o&&o!=="end_turn"&&o!=="unknown"){let a=oe();o&&(a.stopReason=o),i?V(a,r):(a.streaming=!1,l(a))}}continue}}else if(e.type==="execution_start")B=e.kind==="flow"?"flow":"agent",fe=!0,B==="agent"&&(j={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:_;if(t!==_){if(xe==="separate"&&t>1){let o=f;o&&(o.streaming=!1,l(o),f=null)}_=t}Z=typeof e.id=="string"?e.id:null,U=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ne.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),l(o))}}else if(e.type==="tool_input_complete"){if(H.has(e.toolCallId))continue;let t=L(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,l(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=f??U;if(t&&o!==null){let s=e.id;(!s||o.agentMetadata?.turnId===s)&&(o.stopReason=t,l(o))}Z===e.id&&(Z=null)}else if(e.type==="media_start"){let t=String(e.id);Y.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=Y.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=Y.get(t);Y.delete(t);let s=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",r=typeof e.data=="string"?e.data:void 0,i=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,c=null;if(r)c={type:"media",data:r,mediaType:s};else if(i){let I=s.toLowerCase();c={type:I==="image"||I.startsWith("image/")?"image-url":"file-url",url:i,mediaType:s}}let a=e.toolCallId??o?.toolCallId,w=c?[c]:[],C=[];for(let I of w){if(!I||typeof I!="object")continue;let u=I,N=typeof u.type=="string"?u.type:void 0,q=typeof u.mediaType=="string"?u.mediaType.toLowerCase():"",b=null,P="";if(N==="media"){let R=typeof u.data=="string"?u.data:void 0;if(!R)continue;P=q.length>0?q:"application/octet-stream",b=`data:${P};base64,${R}`}else if(N==="image-url"){let R=typeof u.url=="string"?u.url:void 0;if(!R)continue;P=q,b=R}else if(N==="file-url"){let R=typeof u.url=="string"?u.url:void 0;if(!R)continue;P=q,b=R}else continue;if(b)if(N==="image-url"||P.startsWith("image/"))C.push({type:"image",image:b,...P.includes("/")?{mimeType:P}:{}});else if(P.startsWith("audio/"))C.push({type:"audio",audio:b,mimeType:P});else if(P.startsWith("video/"))C.push({type:"video",video:b,mimeType:P});else{let R=P||"application/octet-stream";C.push({type:"file",data:b,mimeType:R,filename:ke(R)})}}if(C.length>0){let I=p(),u=a,q={id:`agent-media-${typeof u=="string"&&u.length>0?`${u}-${I}`:String(I)}`,role:"assistant",content:"",contentParts:C,createdAt:new Date().toISOString(),streaming:!1,sequence:I,agentMetadata:{executionId:e.executionId,iteration:_}};l(q);let b=f;b&&(b.streaming=!1,l(b)),f=null,O.current=null}}else if(e.type==="execution_complete"){let t=f;t&&(e.kind==="flow"&&t.streaming!==!1?V(t):(t.streaming=!1,l(t)),f=null),F=null,E="",K=null,m({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";m({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${p()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:"pending",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};l(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let s={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:e.decision??"approved",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};l(s)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),s=typeof e.title=="string"?e.title:void 0,r=e.file,i;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.path=="string"&&typeof r.mimeType=="string"&&(i={path:r.path,mimeType:r.mimeType,...typeof r.language=="string"?{language:r.language}:{}}),m({type:"artifact_start",id:o,artifactType:t,title:s,component:typeof e.component=="string"?e.component:void 0,...i?{file:i}:{}}),J.set(o,{markdown:"",title:s,file:i}),!ue.has(o)){ue.add(o);let c=me(d.config().features?.artifacts,{artifactType:t,...i?{file:i}:{}}),a=typeof e.component=="string"?e.component:void 0,w={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:ye(c,{artifactId:o,title:s,artifactType:t,status:"streaming",...i?{file:i}:{},...a?{component:a}:{}})};re.set(o,w),l(w)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");m({type:"artifact_delta",id:t,artDelta:o});let s=J.get(t);s&&(s.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};m({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=J.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);m({type:"artifact_complete",id:t});let o=re.get(t);if(o){o.streaming=!1;try{let s=JSON.parse(o.rawContent??"{}");if(s.props){s.props.status="complete";let r=J.get(t);r?.markdown&&(s.props.markdown=r.markdown),r?.file&&(s.props.file=r.file),s.component==="PersonaArtifactInline"&&r?.props&&Object.keys(r.props).length>0&&(s.props.componentProps=r.props)}o.rawContent=JSON.stringify(s)}catch{}J.delete(t),l(o),re.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,l(o)),m({type:"status",status:"idle"})}}}G.length=0};;){let{done:n,value:e}=await x.read();if(n)break;y+=A.decode(e,{stream:!0});let t=y.split(`
|
|
2
2
|
|
|
3
3
|
`);y=t.pop()??"";for(let o of t){let s=o.split(`
|
|
4
4
|
`),r="message",i="",c=null;for(let u of s)u.startsWith("event:")?r=u.replace("event:","").trim():u.startsWith("data:")?i+=u.replace("data:","").trim():u.startsWith("id:")&&(c=u.slice(3).trim());let a=()=>{c!==null&&c!==""&&m({type:"cursor",id:c})};if(!i){a();continue}let w;try{w=JSON.parse(i)}catch(u){m({type:"error",error:u instanceof Error?u:new Error("Failed to parse chat stream payload")});continue}let C=w!==null&&typeof w=="object"&&!Array.isArray(w)?w:null,I=r!=="message"?r:typeof C?.type=="string"?C.type:"message";if(d.onSSEEvent?.(I,w),d.parseSSEEvent){O.current=f;let u=await be(d,w,m,O,l,p,Ce);if(O.current&&O.current!==f&&(f=O.current),u){a();continue}}C&&(G.push({...C,type:I}),le()),a()}}le()}export{We as preferFinalStructuredContent,Te as resolveApproval,Se as resumeFlow,Ee as streamResponse};
|
package/dist/client-stream.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Je=Object.create;var Ie=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ce=(n,a)=>()=>(a||n((a={exports:{}}).exports,a),a.exports);var Ve=(n,a,c,r)=>{if(a&&typeof a=="object"||typeof a=="function")for(let f of Ke(a))!Xe.call(n,f)&&f!==c&&Ie(n,f,{get:()=>a[f],enumerable:!(r=Qe(a,f))||r.enumerable});return n};var Ee=(n,a,c)=>(c=n!=null?Je(Ge(n)):{},Ve(a||!n||!n.__esModule?Ie(c,"default",{value:n,enumerable:!0}):c,n));var xe=Ce(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.Allow=u.ALL=u.COLLECTION=u.ATOM=u.SPECIAL=u.INF=u._INFINITY=u.INFINITY=u.NAN=u.BOOL=u.NULL=u.OBJ=u.ARR=u.NUM=u.STR=void 0;u.STR=1;u.NUM=2;u.ARR=4;u.OBJ=8;u.NULL=16;u.BOOL=32;u.NAN=64;u.INFINITY=128;u._INFINITY=256;u.INF=u.INFINITY|u._INFINITY;u.SPECIAL=u.NULL|u.BOOL|u.INF|u.NAN;u.ATOM=u.STR|u.NUM|u.SPECIAL;u.COLLECTION=u.ARR|u.OBJ;u.ALL=u.ATOM|u.COLLECTION;u.Allow={STR:u.STR,NUM:u.NUM,ARR:u.ARR,OBJ:u.OBJ,NULL:u.NULL,BOOL:u.BOOL,NAN:u.NAN,INFINITY:u.INFINITY,_INFINITY:u._INFINITY,INF:u.INF,SPECIAL:u.SPECIAL,ATOM:u.ATOM,COLLECTION:u.COLLECTION,ALL:u.ALL};u.default=u.Allow});var he=Ce(C=>{"use strict";var Ze=C&&C.__createBinding||(Object.create?(function(n,a,c,r){r===void 0&&(r=c);var f=Object.getOwnPropertyDescriptor(a,c);(!f||("get"in f?!a.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return a[c]}}),Object.defineProperty(n,r,f)}):(function(n,a,c,r){r===void 0&&(r=c),n[r]=a[c]})),et=C&&C.__exportStar||function(n,a){for(var c in n)c!=="default"&&!Object.prototype.hasOwnProperty.call(a,c)&&Ze(a,n,c)};Object.defineProperty(C,"__esModule",{value:!0});C.Allow=C.MalformedJSON=C.PartialJSON=C.parseJSON=C.parse=void 0;var P=xe();Object.defineProperty(C,"Allow",{enumerable:!0,get:function(){return P.Allow}});et(xe(),C);var ie=class extends Error{};C.PartialJSON=ie;var ae=class extends Error{};C.MalformedJSON=ae;function Ne(n,a=P.Allow.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return tt(n.trim(),a)}C.parseJSON=Ne;var tt=(n,a)=>{let c=n.length,r=0,f=
|
|
2
|
-
\r `.includes(n[r]);)r++};return T()},nt=Ne;C.parse=nt});var Ye="webmcp:";var Ae=n=>n.startsWith(Ye);function H(n){return n==="card"?"collapsed":n}function oe(n){return n.split(";",1)[0].trim().toLowerCase()}function ze(n,a){if(!n)return;let c=Object.entries(n);for(let[f,h]of c)if(oe(f)===a)return{mode:H(h),selector:oe(f)};let r=`${a.split("/",1)[0]}/*`;for(let[f,h]of c)if(oe(f)===r)return{mode:H(h),selector:r}}function je(n,a){let c=n?.display,r=typeof c=="string"?{default:c}:c??{};if(a.file&&r.files){if(typeof r.files=="string")return{mode:H(r.files),matchedBy:{type:"files"}};let y=a.file.mimeType?oe(a.file.mimeType):void 0,S=y?ze(r.files.byMediaType,y):void 0;if(y&&S)return{mode:S.mode,matchedBy:{type:"mediaType",mediaType:y,selector:S.selector}};if(r.files.default)return{mode:H(r.files.default),matchedBy:{type:"files"}}}let f=r.byKind?.[a.artifactType];if(f)return{mode:H(f),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byKind"}};let h=r.byType?.[a.artifactType];if(h)return{mode:H(h),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byType"}};let T=a.presentation?.preferredMode;return T?{mode:H(T),matchedBy:{type:"preferredMode"}}:r.default?{mode:H(r.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Pe(n,a){return je(n,a).mode}function Le(n,a){return JSON.stringify({component:n==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:a.artifactId,title:a.title,artifactType:a.artifactType,status:a.status,...a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{},...n==="inline"&&a.component?{component:a.component}:{},...n==="inline"&&a.componentProps?{componentProps:a.componentProps}:{},...a.markdown!==void 0?{markdown:a.markdown}:{}}})}var be=Ee(he(),1);var j=n=>{try{let a=JSON.parse(n);if(a&&typeof a=="object"&&typeof a.text=="string")return a.text}catch{return null}return null};var le=Ee(he(),1);var _e="ask_user_question",We=8;var rt="suggest_replies";var st={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Oe={name:rt,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:st,origin:"sdk",annotations:{readOnlyHint:!0}};var Re=new Set,ot=(n,a,c)=>{let r=`${n}:${a}:${c}`;Re.has(r)||(Re.add(r),console.warn(`[persona] suggestions.followUps.${n} and features.suggestReplies.${n} disagree; suggestions.followUps.${n} wins.`))},ve=n=>{let a=n?.suggestions?.followUps,c=n?.features?.suggestReplies,r=T=>{let y=a?.[T],S=c?.[T];y===void 0||S===void 0||y!==S&&ot(T,S,y)};n&&(r("enabled"),r("expose"));let f=a?.enabled??c?.enabled??!0,h=f?a?.expose??c?.expose??!1:!1;return{enabled:f,expose:h}};var it={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:We,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},at={name:_e,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:it,origin:"sdk",annotations:{readOnlyHint:!0}},Ue=n=>{let a=[],c=n?.features?.askUserQuestion;return c?.expose===!0&&c.enabled!==!1&&a.push(at),ve(n).expose&&a.push(Oe),a};var lt=1e5,Et=lt+1,Fe="https://api.runtype.com";async function ct(n,a,c){let r={"Content-Type":"application/json",...n.headers};n.getHeaders&&Object.assign(r,await n.getHeaders());let f={executionId:a.executionId,approvalId:a.approvalId,decision:c,streamResponse:!0},h=(L,b)=>fetch(`${n.clientApiBase()}${L}`,{method:"POST",headers:r,body:JSON.stringify({...b,...f})}),T=`/v1/agents/${a.agentId}/approve`;if(!n.isClientTokenMode())return h(T);let{sessionId:y}=await n.initSession(),S=await h("/v1/client/approve",{sessionId:y});if(S.status===404){let L=await S.clone().json().catch(()=>null);if(!L||L.error==="Not Found")return h(T)}return S}async function ut(n,a,c,r){let f=n.isClientTokenMode(),h=f?n.getClientApiUrl("resume"):`${n.config.apiUrl?.replace(/\/+$/,"")||Fe}/resume`,T,y=null;if(f){let b=await n.initSession();T=b.sessionId,b.durableRecovery?.enabled===!0&&(y=await n.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...n.headers};n.getHeaders&&Object.assign(S,await n.getHeaders());let L={executionId:a,toolOutputs:c,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(T&&(L.sessionId=T),f&&T){let b=[...Ue(n.config),...await(await n.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:E,commit:w}=await n.sendWithClientToolsDiff(T,b,p=>{let A={...L,...p};return n.debug&&console.debug("[AgentWidgetClient] client token resume",A),fetch(h,{method:"POST",headers:S,body:JSON.stringify(A),signal:r?.signal})},{emptyMeansReplace:!0});return E.ok&&w(),E}return fetch(h,{method:"POST",headers:S,body:JSON.stringify(L),signal:r?.signal})}function dt(n){let a=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[a];if(r)return`attachment.${r}`;let f=a.indexOf("/");if(f>0){let h=a.slice(f+1).split(";")[0]?.trim()??"";if(h&&h!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(h))return`attachment.${h}`}return"attachment"}var De=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function pt(n,a){if(!n)return a;let c=n.trim(),r=a.trim();if(c.length===0)return a;if(r.length===0)return n;let f=De(c);if(!De(r))return n;if(!f||r===c||r.startsWith(c))return a;let T=j(n);return j(a)!==null&&T===null?a:n}async function gt(n,a,c,r,f,h,T){if(!n.parseSSEEvent)return!1;try{let y=await n.parseSSEEvent(a);if(y===null)return!1;let S=b=>{let E={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:h(),...b!==void 0&&{partId:b}};return r.current=E,f(E),E},L=b=>r.current?r.current:S(b);if(y.text!==void 0){y.partId!==void 0&&T.current!==null&&y.partId!==T.current&&(r.current&&(r.current.streaming=!1,f(r.current)),S(y.partId)),y.partId!==void 0&&(T.current=y.partId);let b=L(y.partId);y.partId!==void 0&&!b.partId&&(b.partId=y.partId),b.content+=y.text,f(b)}return y.done&&(r.current&&(r.current.streaming=!1,f(r.current)),T.current=null,c({type:"status",status:"idle"})),y.error&&(T.current=null,c({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function vt(n,a,c,r,f){let h=a.getReader(),T=new TextDecoder,y="",S=Date.now(),L=0,b=()=>S+L++,E=s=>{let e=s.reasoning?{...s.reasoning,chunks:[...s.reasoning.chunks]}:void 0,t=s.toolCall?{...s.toolCall,chunks:s.toolCall.chunks?[...s.toolCall.chunks]:void 0}:void 0,o=s.tools?s.tools.map(i=>({...i,chunks:i.chunks?[...i.chunks]:void 0})):void 0;return{...s,reasoning:e,toolCall:t,tools:o}},w=s=>{if(s.role!=="assistant"||s.variant)return!0;let e=Array.isArray(s.contentParts)&&s.contentParts.length>0,t=typeof s.rawContent=="string"&&s.rawContent.trim()!=="";return typeof s.content=="string"&&s.content.trim()!==""||e||t||!!s.stopReason},p=s=>{w(s)&&c({type:"message",message:E(s)})},A=null,Z=null,J={current:null},Be={current:null},q=null,D="",B=new Map,v=new Map,ce=new Map,ee=new Map,ue=new Map,te=r,Te=!1,de=()=>{if(A)return A;let s,e="",t=q;return!Te&&te?(s=te,Te=!0,e=f??""):te&&t?s=`${te}_${t}`:s=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,A={id:s,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:b()},p(A),A},pe=s=>{let e=ee.get(s);if(e)return e;let t={id:`reason-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:b(),reasoning:{id:s,status:"streaming",chunks:[]}};return ee.set(s,t),p(t),t},G=new Set,ge=new Map,Me=new Set,X=new Map,He=s=>{if(!s)return!1;let e=s.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},V=s=>{let e=ue.get(s);if(e)return e;let t={id:`tool-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:b(),toolCall:{id:s,status:"pending"}};return ue.set(s,t),p(t),t},ke=s=>{if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"){let e=Number(s);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(s);if(!Number.isNaN(t))return t}return Date.now()},fe=s=>{if(typeof s=="string")return s;if(s==null)return"";try{return JSON.stringify(s)}catch{return String(s)}},N=new Map,_=new Map,qe=(s,e)=>{let t=fe(e),o=_.get(s.id),i=pt(o,t);s.rawContent=i;let l=N.get(s.id),d=M=>{let x=s.content??"";M.trim()!==""&&(x.trim().length===0||M.startsWith(x)||M.trimStart().startsWith(x.trim()))&&(s.content=M)},m=()=>{if(l){let M=l.close?.();M instanceof Promise&&M.catch(()=>{})}N.delete(s.id),_.delete(s.id),s.streaming=!1,p(s)};if(!l){d(t),m();return}let g=j(i);if(g!==null&&g.trim()!==""){d(g),m();return}let k=M=>{let x=typeof M=="string"?M:M?.text??null;if(x!==null&&x.trim()!=="")return x;let F=l.getExtractedText();return F!==null&&F.trim()!==""?F:t},I;try{I=l.processChunk(i)}catch{d(t),m();return}if(I instanceof Promise){I.then(M=>{d(k(M)),m()}).catch(()=>{d(t),m()});return}d(k(I)),m()},Y=null,me=(s,e,t,o)=>{s.rawContent=e,N.has(s.id)||N.set(s.id,n.createStreamParser());let i=N.get(s.id),l=e.trim().startsWith("{")||e.trim().startsWith("[");if(l&&_.set(s.id,e),i.__isPlainTextParser===!0){s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s);return}let m=i.processChunk(e);if(m instanceof Promise)m.then(g=>{let k=typeof g=="string"?g:g?.text??null;k!==null&&k.trim()!==""?(s.content=k,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}).catch(()=>{s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s)});else{let g=typeof m=="string"?m:m?.text??null;g!==null&&g.trim()!==""?(s.content=g,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}},z=(s,e)=>{let t=e??s.content;if(t==null||t===""){s.streaming=!1,p(s);return}let i=_.get(s.id)??fe(t);s.rawContent=i;let l=N.get(s.id),d=null,m=!1;if(l&&(d=l.getExtractedText(),d===null&&(d=j(i)),d===null)){let g=l.processChunk(i);g instanceof Promise?(m=!0,g.then(k=>{let I=typeof k=="string"?k:k?.text??null;I!==null&&(s.content=I,s.streaming=!1,N.delete(s.id),_.delete(s.id),p(s))}).catch(()=>{})):d=typeof g=="string"?g:g?.text??null}if(!m){d!==null&&d.trim()!==""?s.content=d:_.has(s.id)||(s.content=fe(t));let g=N.get(s.id);if(g){let k=g.close?.();k instanceof Promise&&k.catch(()=>{}),N.delete(s.id)}_.delete(s.id),s.streaming=!1,p(s)}},we=(s,e,t)=>{let o=v.get(s);if(o)return o;let i={id:`nested-${e}-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:s,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(s,i),p(i),i},ne=[],ye,re=new Map,U=0,$="agent",Se=!1,se=null,Q=null,$e=n.config().iterationDisplay??"separate";for(ye=()=>{for(let s=0;s<ne.length;s++){let e=ne[s];if(!Se&&$!=="flow"&&typeof e.stepType=="string"&&($="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o),we(t,o,"reasoning");continue}let i=e.id,l=pe(i);l.reasoning=l.reasoning??{id:i,status:"streaming",chunks:[]},l.reasoning.startedAt=l.reasoning.startedAt??Date.now(),l.reasoning.completedAt=void 0,l.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),l.streaming=!0,l.reasoning.status="streaming",p(l)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let l=v.get(t),d=e.delta;d&&l.reasoning&&(l.reasoning.chunks.push(String(d)),p(l));continue}let o=e.id,i=pe(o);i.reasoning=i.reasoning??{id:o,status:"streaming",chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),e.delta&&i.reasoning.chunks.push(e.delta),i.reasoning.status="streaming",i.streaming=!0,p(i)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let d=v.get(t);if(d.reasoning){let m=typeof e.text=="string"?e.text:"";m&&d.reasoning.chunks.length===0&&d.reasoning.chunks.push(m),d.reasoning.status="complete",d.streaming=!1,p(d)}B.delete(t),v.delete(t);continue}let o=e.id,i=typeof e.text=="string"?e.text:"";!ee.get(o)&&(i||e.scope==="loop")&&pe(o);let l=ee.get(o);if(l?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),i&&l.reasoning.chunks.length===0&&l.reasoning.chunks.push(i),l.reasoning.status="complete",l.reasoning.completedAt=Date.now();let d=l.reasoning.startedAt??Date.now();l.reasoning.durationMs=Math.max(0,(l.reasoning.completedAt??Date.now())-d),l.streaming=!1,p(l)}}else if(e.type==="tool_start"){A&&(A.streaming=!1,p(A),A=null),typeof e.iteration=="number"&&(U=e.iteration);let t=e.toolCallId,o=e.toolName;if(He(o)){G.add(t);continue}let i=V(t),l=i.toolCall??{id:t,status:"pending"};l.name=o??l.name,l.status="running",l.success=void 0,l.error=void 0,l.duration=void 0,e.parameters!==void 0&&(l.args=e.parameters),l.startedAt=l.startedAt??ke(e.startedAt),l.completedAt=void 0,l.durationMs=void 0,i.toolCall=l,i.streaming=!0,e.executionId&&(i.agentMetadata={executionId:e.executionId,iteration:e.iteration}),p(i)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(G.has(t))continue;let o=V(t),i=o.toolCall??{id:t,status:"running"};i.startedAt=i.startedAt??Date.now();let l=e.delta;l&&(i.chunks=i.chunks??[],i.chunks.push(String(l))),i.status="running",o.toolCall=i,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:U}),p(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(G.has(t)){G.delete(t);continue}let o=V(t),i=o.toolCall??{id:t,status:"running"};i.status="complete",e.result!==void 0&&(i.result=e.result),i.name=e.toolName??i.name,i.success=e.success,i.error=e.error,i.completedAt=Date.now();let l=e.executionTime;if(typeof l=="number")i.durationMs=l,i.duration=l;else{let d=i.startedAt??Date.now();i.durationMs=Math.max(0,(i.completedAt??Date.now())-d)}o.toolCall=i,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??U}),p(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${b()}`,i=V(o),l=e.toolName,d=e.origin==="webmcp"&&!Ae(l)?`webmcp:${l}`:l,m=Ae(d),g=i.toolCall??{id:o,status:"pending"};g.name=d,g.args=e.parameters,g.status=m?"running":"complete",g.chunks=g.chunks??[],g.startedAt=g.startedAt??ke(e.awaitedAt),m?(g.completedAt=void 0,g.duration=void 0,g.durationMs=void 0):g.completedAt=g.completedAt??g.startedAt,i.toolCall=g,i.streaming=!1,i.agentMetadata={...i.agentMetadata,executionId:e.executionId??i.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},p(i)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o);continue}let i=A;i&&($==="flow"?(z(i),Y=i):(i.streaming=!1,p(i)),A=null),q=typeof e.id=="string"?e.id:q,D=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?B.get(t):void 0;if(t&&o){let d=typeof e.delta=="string"?e.delta:"",m=(ce.get(t)??"")+d;if(ce.set(t,m),m.trim()==="")continue;let g=we(t,o);g.agentMetadata={...g.agentMetadata,executionId:e.executionId,parentToolId:o},me(g,m,d,void 0);continue}if(q=typeof e.id=="string"?e.id:q,$==="flow"){let d=typeof e.delta=="string"?e.delta:"";if(D+=d,D.trim()==="")continue;let m=de();m.agentMetadata={executionId:e.executionId,iteration:U},me(m,D,d,void 0),Z=m;continue}let i=typeof e.delta=="string"?e.delta:"";D+=i;let l=de();l.agentMetadata={executionId:e.executionId,iteration:U,turnId:se??void 0,agentName:Q?.agentName},me(l,D,i,void 0),Z=l}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)){let i=v.get(t);i&&z(i),B.delete(t),ce.delete(t),v.delete(t);continue}let o=A;o&&($==="flow"?(z(o),Y=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,p(o)),A=null),q=null,D=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"});continue}{let t=Y;Y=null;let o=e.stopReason,l=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),l!=null?qe(t,l):t.streaming!==!1&&(N.delete(t.id),_.delete(t.id),t.streaming=!1,p(t));else{let d=l!=null&&l!=="";if(d||!!o&&o!=="end_turn"&&o!=="unknown"){let g=de();o&&(g.stopReason=o),d?z(g,l):(g.streaming=!1,p(g))}}continue}}else if(e.type==="execution_start")$=e.kind==="flow"?"flow":"agent",Se=!0,$==="agent"&&(Q={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:U;if(t!==U){if($e==="separate"&&t>1){let o=A;o&&(o.streaming=!1,p(o),A=null)}U=t}se=typeof e.id=="string"?e.id:null,Z=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ue.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),p(o))}}else if(e.type==="tool_input_complete"){if(G.has(e.toolCallId))continue;let t=V(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,p(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=A??Z;if(t&&o!==null){let i=e.id;(!i||o.agentMetadata?.turnId===i)&&(o.stopReason=t,p(o))}se===e.id&&(se=null)}else if(e.type==="media_start"){let t=String(e.id);re.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=re.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=re.get(t);re.delete(t);let i=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",l=typeof e.data=="string"?e.data:void 0,d=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,m=null;if(l)m={type:"media",data:l,mediaType:i};else if(d){let M=i.toLowerCase();m={type:M==="image"||M.startsWith("image/")?"image-url":"file-url",url:d,mediaType:i}}let g=e.toolCallId??o?.toolCallId,k=m?[m]:[],I=[];for(let M of k){if(!M||typeof M!="object")continue;let x=M,F=typeof x.type=="string"?x.type:void 0,K=typeof x.mediaType=="string"?x.mediaType.toLowerCase():"",W=null,R="";if(F==="media"){let O=typeof x.data=="string"?x.data:void 0;if(!O)continue;R=K.length>0?K:"application/octet-stream",W=`data:${R};base64,${O}`}else if(F==="image-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,W=O}else if(F==="file-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,W=O}else continue;if(W)if(F==="image-url"||R.startsWith("image/"))I.push({type:"image",image:W,...R.includes("/")?{mimeType:R}:{}});else if(R.startsWith("audio/"))I.push({type:"audio",audio:W,mimeType:R});else if(R.startsWith("video/"))I.push({type:"video",video:W,mimeType:R});else{let O=R||"application/octet-stream";I.push({type:"file",data:W,mimeType:O,filename:dt(O)})}}if(I.length>0){let M=b(),x=g,K={id:`agent-media-${typeof x=="string"&&x.length>0?`${x}-${M}`:String(M)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:M,agentMetadata:{executionId:e.executionId,iteration:U}};p(K);let W=A;W&&(W.streaming=!1,p(W)),A=null,J.current=null}}else if(e.type==="execution_complete"){let t=A;t&&(e.kind==="flow"&&t.streaming!==!1?z(t):(t.streaming=!1,p(t)),A=null),q=null,D="",Y=null,c({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";c({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${b()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:"pending",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};p(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let i={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:e.decision??"approved",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};p(i)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),i=typeof e.title=="string"?e.title:void 0,l=e.file,d;if(l&&typeof l=="object"&&!Array.isArray(l)&&typeof l.path=="string"&&typeof l.mimeType=="string"&&(d={path:l.path,mimeType:l.mimeType,...typeof l.language=="string"?{language:l.language}:{}}),c({type:"artifact_start",id:o,artifactType:t,title:i,component:typeof e.component=="string"?e.component:void 0,...d?{file:d}:{}}),X.set(o,{markdown:"",title:i,file:d}),!Me.has(o)){Me.add(o);let m=Pe(n.config().features?.artifacts,{artifactType:t,...d?{file:d}:{}}),g=typeof e.component=="string"?e.component:void 0,k={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),rawContent:Le(m,{artifactId:o,title:i,artifactType:t,status:"streaming",...d?{file:d}:{},...g?{component:g}:{}})};ge.set(o,k),p(k)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");c({type:"artifact_delta",id:t,artDelta:o});let i=X.get(t);i&&(i.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};c({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=X.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);c({type:"artifact_complete",id:t});let o=ge.get(t);if(o){o.streaming=!1;try{let i=JSON.parse(o.rawContent??"{}");if(i.props){i.props.status="complete";let l=X.get(t);l?.markdown&&(i.props.markdown=l.markdown),l?.file&&(i.props.file=l.file),i.component==="PersonaArtifactInline"&&l?.props&&Object.keys(l.props).length>0&&(i.props.componentProps=l.props)}o.rawContent=JSON.stringify(i)}catch{}X.delete(t),p(o),ge.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"})}}}ne.length=0};;){let{done:s,value:e}=await h.read();if(s)break;y+=T.decode(e,{stream:!0});let t=y.split(`
|
|
1
|
+
var Je=Object.create;var Ie=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ce=(n,a)=>()=>(a||n((a={exports:{}}).exports,a),a.exports);var Ve=(n,a,c,r)=>{if(a&&typeof a=="object"||typeof a=="function")for(let f of Ke(a))!Xe.call(n,f)&&f!==c&&Ie(n,f,{get:()=>a[f],enumerable:!(r=Qe(a,f))||r.enumerable});return n};var Ee=(n,a,c)=>(c=n!=null?Je(Ge(n)):{},Ve(a||!n||!n.__esModule?Ie(c,"default",{value:n,enumerable:!0}):c,n));var xe=Ce(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.Allow=u.ALL=u.COLLECTION=u.ATOM=u.SPECIAL=u.INF=u._INFINITY=u.INFINITY=u.NAN=u.BOOL=u.NULL=u.OBJ=u.ARR=u.NUM=u.STR=void 0;u.STR=1;u.NUM=2;u.ARR=4;u.OBJ=8;u.NULL=16;u.BOOL=32;u.NAN=64;u.INFINITY=128;u._INFINITY=256;u.INF=u.INFINITY|u._INFINITY;u.SPECIAL=u.NULL|u.BOOL|u.INF|u.NAN;u.ATOM=u.STR|u.NUM|u.SPECIAL;u.COLLECTION=u.ARR|u.OBJ;u.ALL=u.ATOM|u.COLLECTION;u.Allow={STR:u.STR,NUM:u.NUM,ARR:u.ARR,OBJ:u.OBJ,NULL:u.NULL,BOOL:u.BOOL,NAN:u.NAN,INFINITY:u.INFINITY,_INFINITY:u._INFINITY,INF:u.INF,SPECIAL:u.SPECIAL,ATOM:u.ATOM,COLLECTION:u.COLLECTION,ALL:u.ALL};u.default=u.Allow});var he=Ce(C=>{"use strict";var Ze=C&&C.__createBinding||(Object.create?(function(n,a,c,r){r===void 0&&(r=c);var f=Object.getOwnPropertyDescriptor(a,c);(!f||("get"in f?!a.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return a[c]}}),Object.defineProperty(n,r,f)}):(function(n,a,c,r){r===void 0&&(r=c),n[r]=a[c]})),et=C&&C.__exportStar||function(n,a){for(var c in n)c!=="default"&&!Object.prototype.hasOwnProperty.call(a,c)&&Ze(a,n,c)};Object.defineProperty(C,"__esModule",{value:!0});C.Allow=C.MalformedJSON=C.PartialJSON=C.parseJSON=C.parse=void 0;var P=xe();Object.defineProperty(C,"Allow",{enumerable:!0,get:function(){return P.Allow}});et(xe(),C);var ie=class extends Error{};C.PartialJSON=ie;var ae=class extends Error{};C.MalformedJSON=ae;function Ne(n,a=P.Allow.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return tt(n.trim(),a)}C.parseJSON=Ne;var tt=(n,a)=>{let c=n.length,r=0,f=k=>{throw new ie(`${k} at position ${r}`)},h=k=>{throw new ae(`${k} at position ${r}`)},T=()=>(E(),r>=c&&f("Unexpected end of input"),n[r]==='"'?y():n[r]==="{"?S():n[r]==="["?L():n.substring(r,r+4)==="null"||P.Allow.NULL&a&&c-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||P.Allow.BOOL&a&&c-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||P.Allow.BOOL&a&&c-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||P.Allow.INFINITY&a&&c-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||P.Allow._INFINITY&a&&1<c-r&&c-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||P.Allow.NAN&a&&c-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):b()),y=()=>{let k=r,p=!1;for(r++;r<c&&(n[r]!=='"'||p&&n[r-1]==="\\");)p=n[r]==="\\"?!p:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(k,++r-Number(p)))}catch(A){h(String(A))}else if(P.Allow.STR&a)try{return JSON.parse(n.substring(k,r-Number(p))+'"')}catch{return JSON.parse(n.substring(k,n.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},S=()=>{r++,E();let k={};try{for(;n[r]!=="}";){if(E(),r>=c&&P.Allow.OBJ&a)return k;let p=y();E(),r++;try{let A=T();k[p]=A}catch(A){if(P.Allow.OBJ&a)return k;throw A}E(),n[r]===","&&r++}}catch{if(P.Allow.OBJ&a)return k;f("Expected '}' at end of object")}return r++,k},L=()=>{r++;let k=[];try{for(;n[r]!=="]";)k.push(T()),E(),n[r]===","&&r++}catch{if(P.Allow.ARR&a)return k;f("Expected ']' at end of array")}return r++,k},b=()=>{if(r===0){n==="-"&&h("Not sure what '-' is");try{return JSON.parse(n)}catch(p){if(P.Allow.NUM&a)try{return JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}h(String(p))}}let k=r;for(n[r]==="-"&&r++;n[r]&&",]}".indexOf(n[r])===-1;)r++;r==c&&!(P.Allow.NUM&a)&&f("Unterminated number literal");try{return JSON.parse(n.substring(k,r))}catch{n.substring(k,r)==="-"&&f("Not sure what '-' is");try{return JSON.parse(n.substring(k,n.lastIndexOf("e")))}catch(A){h(String(A))}}},E=()=>{for(;r<c&&`
|
|
2
|
+
\r `.includes(n[r]);)r++};return T()},nt=Ne;C.parse=nt});var Ye="webmcp:";var Ae=n=>n.startsWith(Ye);function H(n){return n==="card"?"collapsed":n}function oe(n){return n.split(";",1)[0].trim().toLowerCase()}function je(n,a){if(!n)return;let c=Object.entries(n);for(let[f,h]of c)if(oe(f)===a)return{mode:H(h),selector:oe(f)};let r=`${a.split("/",1)[0]}/*`;for(let[f,h]of c)if(oe(f)===r)return{mode:H(h),selector:r}}function ze(n,a){let c=n?.display,r=typeof c=="string"?{default:c}:c??{};if(a.file&&r.files){if(typeof r.files=="string")return{mode:H(r.files),matchedBy:{type:"files"}};let y=a.file.mimeType?oe(a.file.mimeType):void 0,S=y?je(r.files.byMediaType,y):void 0;if(y&&S)return{mode:S.mode,matchedBy:{type:"mediaType",mediaType:y,selector:S.selector}};if(r.files.default)return{mode:H(r.files.default),matchedBy:{type:"files"}}}let f=r.byKind?.[a.artifactType];if(f)return{mode:H(f),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byKind"}};let h=r.byType?.[a.artifactType];if(h)return{mode:H(h),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byType"}};let T=a.presentation?.preferredMode;return T?{mode:H(T),matchedBy:{type:"preferredMode"}}:r.default?{mode:H(r.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Pe(n,a){return ze(n,a).mode}function Le(n,a){return JSON.stringify({component:n==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:a.artifactId,title:a.title,artifactType:a.artifactType,status:a.status,...a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{},...n==="inline"&&a.component?{component:a.component}:{},...n==="inline"&&a.componentProps?{componentProps:a.componentProps}:{},...a.markdown!==void 0?{markdown:a.markdown}:{}}})}var be=Ee(he(),1);var z=n=>{try{let a=JSON.parse(n);if(a&&typeof a=="object"&&typeof a.text=="string")return a.text}catch{return null}return null};var le=Ee(he(),1);var We="ask_user_question",_e=8;var rt="suggest_replies";var st={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Oe={name:rt,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:st,origin:"sdk",annotations:{readOnlyHint:!0}};var Re=new Set,ot=(n,a,c)=>{let r=`${n}:${a}:${c}`;Re.has(r)||(Re.add(r),console.warn(`[persona] suggestions.followUps.${n} and features.suggestReplies.${n} disagree; suggestions.followUps.${n} wins.`))},ve=n=>{let a=n?.suggestions?.followUps,c=n?.features?.suggestReplies,r=T=>{let y=a?.[T],S=c?.[T];y===void 0||S===void 0||y!==S&&ot(T,S,y)};n&&(r("enabled"),r("expose"));let f=a?.enabled??c?.enabled??!0,h=f?a?.expose??c?.expose??!1:!1;return{enabled:f,expose:h}};var it={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:_e,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},at={name:We,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:it,origin:"sdk",annotations:{readOnlyHint:!0}},Ue=n=>{let a=[],c=n?.features?.askUserQuestion;return c?.expose===!0&&c.enabled!==!1&&a.push(at),ve(n).expose&&a.push(Oe),a};var lt=1e5,Et=lt+1,Fe="https://api.runtype.com";async function ct(n,a,c){let r={"Content-Type":"application/json",...n.headers};n.getHeaders&&Object.assign(r,await n.getHeaders());let f={executionId:a.executionId,approvalId:a.approvalId,decision:c,streamResponse:!0},h=(L,b)=>fetch(`${n.clientApiBase()}${L}`,{method:"POST",headers:r,body:JSON.stringify({...b,...f})}),T=`/v1/agents/${a.agentId}/approve`;if(!n.isClientTokenMode())return h(T);let{sessionId:y}=await n.initSession(),S=await h("/v1/client/approve",{sessionId:y});if(S.status===404){let L=await S.clone().json().catch(()=>null);if(!L||L.error==="Not Found")return h(T)}return S}async function ut(n,a,c,r){let f=n.isClientTokenMode(),h=f?n.getClientApiUrl("resume"):`${n.config.apiUrl?.replace(/\/+$/,"")||Fe}/resume`,T,y=null;if(f){let b=await n.initSession();T=b.sessionId,b.durableRecovery?.enabled===!0&&(y=await n.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...n.headers};n.getHeaders&&Object.assign(S,await n.getHeaders());let L={executionId:a,toolOutputs:c,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(T&&(L.sessionId=T),f&&T){let b=[...Ue(n.config),...await(await n.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:E,commit:k}=await n.sendWithClientToolsDiff(T,b,p=>{let A={...L,...p};return n.debug&&console.debug("[AgentWidgetClient] client token resume",A),fetch(h,{method:"POST",headers:S,body:JSON.stringify(A),signal:r?.signal})},{emptyMeansReplace:!0});return E.ok&&k(),E}return fetch(h,{method:"POST",headers:S,body:JSON.stringify(L),signal:r?.signal})}function dt(n){let a=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[a];if(r)return`attachment.${r}`;let f=a.indexOf("/");if(f>0){let h=a.slice(f+1).split(";")[0]?.trim()??"";if(h&&h!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(h))return`attachment.${h}`}return"attachment"}var De=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function pt(n,a){if(!n)return a;let c=n.trim(),r=a.trim();if(c.length===0)return a;if(r.length===0)return n;let f=De(c);if(!De(r))return n;if(!f||r===c||r.startsWith(c))return a;let T=z(n);return z(a)!==null&&T===null?a:n}async function gt(n,a,c,r,f,h,T){if(!n.parseSSEEvent)return!1;try{let y=await n.parseSSEEvent(a);if(y===null)return!1;let S=b=>{let E={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:h(),...b!==void 0&&{partId:b}};return r.current=E,f(E),E},L=b=>r.current?r.current:S(b);if(y.text!==void 0){y.partId!==void 0&&T.current!==null&&y.partId!==T.current&&(r.current&&(r.current.streaming=!1,f(r.current)),S(y.partId)),y.partId!==void 0&&(T.current=y.partId);let b=L(y.partId);y.partId!==void 0&&!b.partId&&(b.partId=y.partId),b.content+=y.text,f(b)}return y.done&&(r.current&&(r.current.streaming=!1,f(r.current)),T.current=null,c({type:"status",status:"idle"})),y.error&&(T.current=null,c({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function vt(n,a,c,r,f){let h=a.getReader(),T=new TextDecoder,y="",S=Date.now(),L=0,b=()=>S+L++,E=s=>{let e=s.reasoning?{...s.reasoning,chunks:[...s.reasoning.chunks]}:void 0,t=s.toolCall?{...s.toolCall,chunks:s.toolCall.chunks?[...s.toolCall.chunks]:void 0}:void 0,o=s.tools?s.tools.map(i=>({...i,chunks:i.chunks?[...i.chunks]:void 0})):void 0;return{...s,reasoning:e,toolCall:t,tools:o}},k=s=>{if(s.role!=="assistant"||s.variant)return!0;let e=Array.isArray(s.contentParts)&&s.contentParts.length>0,t=typeof s.rawContent=="string"&&s.rawContent.trim()!=="";return typeof s.content=="string"&&s.content.trim()!==""||e||t||!!s.stopReason},p=s=>{k(s)&&c({type:"message",message:E(s)})},A=null,Z=null,J={current:null},Be={current:null},q=null,D="",B=new Map,v=new Map,ce=new Map,ee=new Map,ue=new Map,te=r,Te=!1,de=()=>{if(A)return A;let s,e="",t=q;return!Te&&te?(s=te,Te=!0,e=f??""):te&&t?s=`${te}_${t}`:s=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,A={id:s,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:b()},p(A),A},pe=s=>{let e=ee.get(s);if(e)return e;let t={id:`reason-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:b(),reasoning:{id:s,status:"streaming",chunks:[]}};return ee.set(s,t),p(t),t},G=new Set,ge=new Map,Me=new Set,X=new Map,He=s=>{if(!s)return!1;let e=s.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},V=s=>{let e=ue.get(s);if(e)return e;let t={id:`tool-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:b(),toolCall:{id:s,status:"pending"}};return ue.set(s,t),p(t),t},we=s=>{if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"){let e=Number(s);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(s);if(!Number.isNaN(t))return t}return Date.now()},fe=s=>{if(typeof s=="string")return s;if(s==null)return"";try{return JSON.stringify(s)}catch{return String(s)}},N=new Map,W=new Map,qe=(s,e)=>{let t=fe(e),o=W.get(s.id),i=pt(o,t);s.rawContent=i;let l=N.get(s.id),d=M=>{let x=s.content??"";M.trim()!==""&&(x.trim().length===0||M.startsWith(x)||M.trimStart().startsWith(x.trim()))&&(s.content=M)},m=()=>{if(l){let M=l.close?.();M instanceof Promise&&M.catch(()=>{})}N.delete(s.id),W.delete(s.id),s.streaming=!1,p(s)};if(!l){d(t),m();return}let g=z(i);if(g!==null&&g.trim()!==""){d(g),m();return}let w=M=>{let x=typeof M=="string"?M:M?.text??null;if(x!==null&&x.trim()!=="")return x;let F=l.getExtractedText();return F!==null&&F.trim()!==""?F:t},I;try{I=l.processChunk(i)}catch{d(t),m();return}if(I instanceof Promise){I.then(M=>{d(w(M)),m()}).catch(()=>{d(t),m()});return}d(w(I)),m()},Y=null,me=(s,e,t,o)=>{s.rawContent=e,N.has(s.id)||N.set(s.id,n.createStreamParser());let i=N.get(s.id),l=e.trim().startsWith("{")||e.trim().startsWith("[");if(l&&W.set(s.id,e),i.__isPlainTextParser===!0){s.content=o!==void 0?e:s.content+t,W.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s);return}let m=i.processChunk(e);if(m instanceof Promise)m.then(g=>{let w=typeof g=="string"?g:g?.text??null;w!==null&&w.trim()!==""?(s.content=w,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,W.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}).catch(()=>{s.content=o!==void 0?e:s.content+t,W.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s)});else{let g=typeof m=="string"?m:m?.text??null;g!==null&&g.trim()!==""?(s.content=g,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,W.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}},j=(s,e)=>{let t=e??s.content;if(t==null||t===""){s.streaming=!1,p(s);return}let i=W.get(s.id)??fe(t);s.rawContent=i;let l=N.get(s.id),d=null,m=!1;if(l&&(d=l.getExtractedText(),d===null&&(d=z(i)),d===null)){let g=l.processChunk(i);g instanceof Promise?(m=!0,g.then(w=>{let I=typeof w=="string"?w:w?.text??null;I!==null&&(s.content=I,s.streaming=!1,N.delete(s.id),W.delete(s.id),p(s))}).catch(()=>{})):d=typeof g=="string"?g:g?.text??null}if(!m){d!==null&&d.trim()!==""?s.content=d:W.has(s.id)||(s.content=fe(t));let g=N.get(s.id);if(g){let w=g.close?.();w instanceof Promise&&w.catch(()=>{}),N.delete(s.id)}W.delete(s.id),s.streaming=!1,p(s)}},ke=(s,e,t)=>{let o=v.get(s);if(o)return o;let i={id:`nested-${e}-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:s,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(s,i),p(i),i},ne=[],ye,re=new Map,U=0,$="agent",Se=!1,se=null,Q=null,$e=n.config().iterationDisplay??"separate";for(ye=()=>{for(let s=0;s<ne.length;s++){let e=ne[s];if(!Se&&$!=="flow"&&typeof e.stepType=="string"&&($="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o),ke(t,o,"reasoning");continue}let i=e.id,l=pe(i);l.reasoning=l.reasoning??{id:i,status:"streaming",chunks:[]},l.reasoning.startedAt=l.reasoning.startedAt??Date.now(),l.reasoning.completedAt=void 0,l.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),l.streaming=!0,l.reasoning.status="streaming",p(l)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let l=v.get(t),d=e.delta;d&&l.reasoning&&(l.reasoning.chunks.push(String(d)),p(l));continue}let o=e.id,i=pe(o);i.reasoning=i.reasoning??{id:o,status:"streaming",chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),e.delta&&i.reasoning.chunks.push(e.delta),i.reasoning.status="streaming",i.streaming=!0,p(i)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let d=v.get(t);if(d.reasoning){let m=typeof e.text=="string"?e.text:"";m&&d.reasoning.chunks.length===0&&d.reasoning.chunks.push(m),d.reasoning.status="complete",d.streaming=!1,p(d)}B.delete(t),v.delete(t);continue}let o=e.id,i=typeof e.text=="string"?e.text:"";!ee.get(o)&&(i||e.scope==="loop")&&pe(o);let l=ee.get(o);if(l?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),i&&l.reasoning.chunks.length===0&&l.reasoning.chunks.push(i),l.reasoning.status="complete",l.reasoning.completedAt=Date.now();let d=l.reasoning.startedAt??Date.now();l.reasoning.durationMs=Math.max(0,(l.reasoning.completedAt??Date.now())-d),l.streaming=!1,p(l)}}else if(e.type==="tool_start"){A&&(A.streaming=!1,p(A),A=null),typeof e.iteration=="number"&&(U=e.iteration);let t=e.toolCallId,o=e.toolName;if(He(o)){G.add(t);continue}let i=V(t),l=i.toolCall??{id:t,status:"pending"};l.name=o??l.name,l.status="running",l.success=void 0,l.error=void 0,l.duration=void 0,e.parameters!==void 0&&(l.args=e.parameters),l.startedAt=l.startedAt??we(e.startedAt),l.completedAt=void 0,l.durationMs=void 0,i.toolCall=l,i.streaming=!0,e.executionId&&(i.agentMetadata={executionId:e.executionId,iteration:e.iteration}),p(i)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(G.has(t))continue;let o=V(t),i=o.toolCall??{id:t,status:"running"};i.startedAt=i.startedAt??Date.now();let l=e.delta;l&&(i.chunks=i.chunks??[],i.chunks.push(String(l))),i.status="running",o.toolCall=i,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:U}),p(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(G.has(t)){G.delete(t);continue}let o=V(t),i=o.toolCall??{id:t,status:"running"};i.status="complete",e.result!==void 0&&(i.result=e.result),i.name=e.toolName??i.name,i.success=e.success,i.error=e.error,i.completedAt=Date.now();let l=e.executionTime;if(typeof l=="number")i.durationMs=l,i.duration=l;else{let d=i.startedAt??Date.now();i.durationMs=Math.max(0,(i.completedAt??Date.now())-d)}o.toolCall=i,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??U}),p(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${b()}`,i=V(o),l=e.toolName,d=e.origin==="webmcp"&&!Ae(l)?`webmcp:${l}`:l,m=Ae(d),g=i.toolCall??{id:o,status:"pending"};g.name=d,g.args=e.parameters,g.status=m?"running":"complete",g.chunks=g.chunks??[],g.startedAt=g.startedAt??we(e.awaitedAt),m?(g.completedAt=void 0,g.duration=void 0,g.durationMs=void 0):g.completedAt=g.completedAt??g.startedAt,i.toolCall=g,i.streaming=!1,i.agentMetadata={...i.agentMetadata,executionId:e.executionId??i.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},p(i)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o);continue}let i=A;i&&($==="flow"?(j(i),Y=i):(i.streaming=!1,p(i)),A=null),q=typeof e.id=="string"?e.id:q,D=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?B.get(t):void 0;if(t&&o){let d=typeof e.delta=="string"?e.delta:"",m=(ce.get(t)??"")+d;if(ce.set(t,m),m.trim()==="")continue;let g=ke(t,o);g.agentMetadata={...g.agentMetadata,executionId:e.executionId,parentToolId:o},me(g,m,d,void 0);continue}if(q=typeof e.id=="string"?e.id:q,$==="flow"){let d=typeof e.delta=="string"?e.delta:"";if(D+=d,D.trim()==="")continue;let m=de();m.agentMetadata={executionId:e.executionId,iteration:U},me(m,D,d,void 0),Z=m;continue}let i=typeof e.delta=="string"?e.delta:"";D+=i;let l=de();l.agentMetadata={executionId:e.executionId,iteration:U,turnId:se??void 0,agentName:Q?.agentName},me(l,D,i,void 0),Z=l}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)){let i=v.get(t);i&&j(i),B.delete(t),ce.delete(t),v.delete(t);continue}let o=A;o&&($==="flow"?(j(o),Y=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,p(o)),A=null),q=null,D=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"});continue}{let t=Y;Y=null;let o=e.stopReason,l=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),l!=null?qe(t,l):t.streaming!==!1&&(N.delete(t.id),W.delete(t.id),t.streaming=!1,p(t));else{let d=l!=null&&l!=="";if(d||!!o&&o!=="end_turn"&&o!=="unknown"){let g=de();o&&(g.stopReason=o),d?j(g,l):(g.streaming=!1,p(g))}}continue}}else if(e.type==="execution_start")$=e.kind==="flow"?"flow":"agent",Se=!0,$==="agent"&&(Q={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:U;if(t!==U){if($e==="separate"&&t>1){let o=A;o&&(o.streaming=!1,p(o),A=null)}U=t}se=typeof e.id=="string"?e.id:null,Z=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ue.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),p(o))}}else if(e.type==="tool_input_complete"){if(G.has(e.toolCallId))continue;let t=V(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,p(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=A??Z;if(t&&o!==null){let i=e.id;(!i||o.agentMetadata?.turnId===i)&&(o.stopReason=t,p(o))}se===e.id&&(se=null)}else if(e.type==="media_start"){let t=String(e.id);re.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=re.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=re.get(t);re.delete(t);let i=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",l=typeof e.data=="string"?e.data:void 0,d=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,m=null;if(l)m={type:"media",data:l,mediaType:i};else if(d){let M=i.toLowerCase();m={type:M==="image"||M.startsWith("image/")?"image-url":"file-url",url:d,mediaType:i}}let g=e.toolCallId??o?.toolCallId,w=m?[m]:[],I=[];for(let M of w){if(!M||typeof M!="object")continue;let x=M,F=typeof x.type=="string"?x.type:void 0,K=typeof x.mediaType=="string"?x.mediaType.toLowerCase():"",_=null,R="";if(F==="media"){let O=typeof x.data=="string"?x.data:void 0;if(!O)continue;R=K.length>0?K:"application/octet-stream",_=`data:${R};base64,${O}`}else if(F==="image-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,_=O}else if(F==="file-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,_=O}else continue;if(_)if(F==="image-url"||R.startsWith("image/"))I.push({type:"image",image:_,...R.includes("/")?{mimeType:R}:{}});else if(R.startsWith("audio/"))I.push({type:"audio",audio:_,mimeType:R});else if(R.startsWith("video/"))I.push({type:"video",video:_,mimeType:R});else{let O=R||"application/octet-stream";I.push({type:"file",data:_,mimeType:O,filename:dt(O)})}}if(I.length>0){let M=b(),x=g,K={id:`agent-media-${typeof x=="string"&&x.length>0?`${x}-${M}`:String(M)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:M,agentMetadata:{executionId:e.executionId,iteration:U}};p(K);let _=A;_&&(_.streaming=!1,p(_)),A=null,J.current=null}}else if(e.type==="execution_complete"){let t=A;t&&(e.kind==="flow"&&t.streaming!==!1?j(t):(t.streaming=!1,p(t)),A=null),q=null,D="",Y=null,c({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";c({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${b()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:"pending",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};p(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let i={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:e.decision??"approved",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};p(i)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),i=typeof e.title=="string"?e.title:void 0,l=e.file,d;if(l&&typeof l=="object"&&!Array.isArray(l)&&typeof l.path=="string"&&typeof l.mimeType=="string"&&(d={path:l.path,mimeType:l.mimeType,...typeof l.language=="string"?{language:l.language}:{}}),c({type:"artifact_start",id:o,artifactType:t,title:i,component:typeof e.component=="string"?e.component:void 0,...d?{file:d}:{}}),X.set(o,{markdown:"",title:i,file:d}),!Me.has(o)){Me.add(o);let m=Pe(n.config().features?.artifacts,{artifactType:t,...d?{file:d}:{}}),g=typeof e.component=="string"?e.component:void 0,w={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),rawContent:Le(m,{artifactId:o,title:i,artifactType:t,status:"streaming",...d?{file:d}:{},...g?{component:g}:{}})};ge.set(o,w),p(w)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");c({type:"artifact_delta",id:t,artDelta:o});let i=X.get(t);i&&(i.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};c({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=X.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);c({type:"artifact_complete",id:t});let o=ge.get(t);if(o){o.streaming=!1;try{let i=JSON.parse(o.rawContent??"{}");if(i.props){i.props.status="complete";let l=X.get(t);l?.markdown&&(i.props.markdown=l.markdown),l?.file&&(i.props.file=l.file),i.component==="PersonaArtifactInline"&&l?.props&&Object.keys(l.props).length>0&&(i.props.componentProps=l.props)}o.rawContent=JSON.stringify(i)}catch{}X.delete(t),p(o),ge.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"})}}}ne.length=0};;){let{done:s,value:e}=await h.read();if(s)break;y+=T.decode(e,{stream:!0});let t=y.split(`
|
|
3
3
|
|
|
4
4
|
`);y=t.pop()??"";for(let o of t){let i=o.split(`
|
|
5
|
-
`),l="message",d="",m=null;for(let x of i)x.startsWith("event:")?l=x.replace("event:","").trim():x.startsWith("data:")?d+=x.replace("data:","").trim():x.startsWith("id:")&&(m=x.slice(3).trim());let g=()=>{m!==null&&m!==""&&c({type:"cursor",id:m})};if(!d){g();continue}let
|
|
5
|
+
`),l="message",d="",m=null;for(let x of i)x.startsWith("event:")?l=x.replace("event:","").trim():x.startsWith("data:")?d+=x.replace("data:","").trim():x.startsWith("id:")&&(m=x.slice(3).trim());let g=()=>{m!==null&&m!==""&&c({type:"cursor",id:m})};if(!d){g();continue}let w;try{w=JSON.parse(d)}catch(x){c({type:"error",error:x instanceof Error?x:new Error("Failed to parse chat stream payload")});continue}let I=w!==null&&typeof w=="object"&&!Array.isArray(w)?w:null,M=l!=="message"?l:typeof I?.type=="string"?I.type:"message";if(n.onSSEEvent?.(M,w),n.parseSSEEvent){J.current=A;let x=await gt(n,w,c,J,p,b,Be);if(J.current&&J.current!==A&&(A=J.current),x){g();continue}}I&&(ne.push({...I,type:M}),ye()),g()}}ye()}export{pt as preferFinalStructuredContent,ct as resolveApproval,ut as resumeFlow,vt as streamResponse};
|