@ag-ui/aws-strands 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{randomUUID as e}from"crypto";import{Agent as t,DocumentBlock as n,ImageBlock as r,InterruptResponseContent as i,Message as a,SessionManager as o,TextBlock as s,ToolResultBlock as c,VideoBlock as l}from"@strands-agents/sdk";import{EventType as u}from"@ag-ui/core";import{HttpAgent as d}from"@ag-ui/client";function f(e){return{state_key:e.stateKey,tool:e.tool,tool_argument:e.toolArgument}}const p=new Set([`__proto__`,`constructor`,`prototype`]);function m(e){return typeof e==`object`&&!!e&&`stateKey`in e&&`tool`in e&&`toolArgument`in e}function h(e){let t=Object.create(null),n=e.context;if(Array.isArray(n))for(let e of n){if(!e||typeof e!=`object`)continue;let n=e;typeof n.description!=`string`||n.description.length===0||p.has(n.description)||(t[n.description]=typeof n.value==`string`?n.value:String(n.value??``))}let r=e.forwardedProps;return{context:t,forwardedProps:r&&typeof r==`object`&&!Array.isArray(r)?r:{}}}async function g(e){return await Promise.resolve(e)}function _(e){return e===void 0?[]:m(e)?[e]:Array.from(e)}const v={debug(){},warn:(e,...t)=>console.warn(e,...t),error:(e,...t)=>console.error(e,...t)};function y(e){return e??v}const b=`[@ag-ui/aws-strands]`,x=Symbol.for(`@ag-ui/aws-strands.proxyTool`);function S(e){let t=e.description&&e.description.length>0?e.description:`Client-side tool: ${e.name}`,n={name:e.name,description:t,inputSchema:e.parameters??{type:`object`,properties:{}}};return{name:n.name,description:t,toolSpec:n,[x]:!0,async*stream(e){return new c({toolUseId:e.toolUse.toolUseId,status:`success`,content:[new s(`Forwarded to client`)]})}}}function C(e){return typeof e==`object`&&!!e&&e[x]===!0}function w(e,t,n,r=v){let i=new Set;for(let e of t)e.name&&i.add(e.name);for(let t of n){if(i.has(t))continue;let n=e.get(t);n&&C(n)&&(e.remove(t),r.debug(`${b} Removed stale proxy tool: ${t}`))}let a=new Set;for(let n of t){if(!n.name)continue;let t=e.get(n.name);if(t&&!C(t)){r.warn(`${b} Native tool "${n.name}" shadows client-declared tool with the same name; client tool will not be registered`);continue}t&&e.remove(n.name),e.add(S(n)),a.add(n.name),r.debug(`${b} Registered proxy tool: ${n.name}`)}return a}const T=`[@ag-ui/aws-strands]`,E=new Set([`png`,`jpeg`,`gif`,`webp`]),D=new Set([`pdf`,`csv`,`doc`,`docx`,`xls`,`xlsx`,`html`,`txt`,`md`]),O=new Set([`flv`,`mkv`,`mov`,`mpeg`,`mpg`,`mp4`,`three_gp`,`webm`,`wmv`]);function k(e,t,n){if(!e)return n.warn(`${T} No MIME type provided, cannot determine format`),null;let r=e.split(`/`).pop()?.toLowerCase()??``;return t.has(r)?r:(n.warn(`${T} Unsupported MIME type '${e}' (parsed format '${r}' not in ${JSON.stringify([...t].sort())})`),null)}async function A(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),3e4);try{let r=await fetch(e,{signal:n.signal});if(!r.ok)return t.warn(`${T} Failed to fetch URL ${e}: HTTP ${r.status}`),null;let i=await r.arrayBuffer();return new Uint8Array(i)}catch(n){return t.warn(`${T} Failed to fetch URL ${e}:`,n),null}finally{clearTimeout(r)}}function j(e,t){try{let t=globalThis.atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){return t.warn(`${T} Failed to decode base64 content:`,e),null}}async function M(e,t){return e.type===`data`?j(e.value,t):e.type===`url`?await A(e.value,t):(t.warn(`${T} Unknown content source type: ${e.type}, cannot resolve bytes`),null)}async function N(e,t=v){let i=[];for(let a of e){if(a.type===`text`){i.push(new s(a.text));continue}if(a.type===`image`){let e=a,n=await M(e.source,t);if(!n)continue;let o=k(e.source.mimeType,E,t);if(!o)continue;i.push(new r({format:o,source:{bytes:n}}));continue}if(a.type===`document`){let e=a,r=await M(e.source,t);if(!r)continue;let o=k(e.source.mimeType,D,t);if(!o)continue;i.push(new n({format:o,name:`document`,source:{bytes:r}}));continue}if(a.type===`video`){let e=a,n=await M(e.source,t);if(!n)continue;let r=k(e.source.mimeType,O,t);if(!r)continue;i.push(new l({format:r,source:{bytes:n}}));continue}if(a.type===`audio`){t.warn(`${T} Skipping audio content: Strands has no audio support`);continue}if(a.type===`binary`){let e=a,n=null;if(e.data?n=j(e.data,t):e.url&&(n=await A(e.url,t)),!n){t.warn(`${T} Skipping binary content: could not resolve bytes`);continue}let o=k(e.mimeType,E,t);if(!o){t.warn(`${T} Skipping binary content: unsupported MIME type '${e.mimeType}'`);continue}i.push(new r({format:o,source:{bytes:n}}));continue}t.warn(`${T} Skipping unknown content type: ${a.type}`)}return i}function P(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e)){let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.type===`text`&&typeof e.text==`string`&&t.push(e.text),e.type===`textBlock`&&typeof e.text==`string`&&t.push(e.text)}return t.join(` `)}return``}const F=`[@ag-ui/aws-strands]`,I=()=>e();function L(e){let t={model:e.model,tools:e.tools.slice()};e.systemPrompt!==void 0&&(t.systemPrompt=e.systemPrompt),e.name!==void 0&&(t.name=e.name),e.id!==void 0&&(t.id=e.id),e.description!==void 0&&(t.description=e.description);let n=e.appState?.getAll?.();n&&Object.keys(n).length>0&&(t.appState=n);let r=e.modelState?.getAll?.();r&&Object.keys(r).length>0&&(t.modelState=r);let i=e;return i.traceAttributes!==void 0&&(t.traceAttributes=i.traceAttributes),i.structuredOutputSchema!==void 0&&(t.structuredOutputSchema=i.structuredOutputSchema),i.toolExecutor!==void 0&&(t.toolExecutor=i.toolExecutor),t}function R(e){return typeof e==`string`?e:e==null?``:Array.isArray(e)?P(e):String(e)}function z(e){let t=R(e),n=t.trim();if(n.length===0)return{text:t};let r=n[0];if(r!==`{`&&r!==`[`)return{text:t};try{let e=JSON.parse(n);if(typeof e==`object`&&e)return{json:e}}catch{}return{text:t}}function B(e){return typeof e==`string`&&e.length>0?e:I()}function V(e){return e instanceof Error?e.message:String(e)}function H(e,t,n){for(let[n,r]of e)if(r.strandsToolId===t)return n;return n?I():t||I()}function U(e){let t=[];for(let n of e??[]){let e=n.role;if(e!==`user`&&e!==`assistant`&&e!==`tool`)continue;let r=B(n.id);if(e===`user`)t.push({id:r,role:`user`,content:R(n.content)});else if(e===`assistant`){let e=n.toolCalls,i;e&&e.length>0&&(i=e.map(e=>{let t=e.function;return{id:B(e.id),type:`function`,function:{name:t?.name??`unknown`,arguments:t?.arguments??`{}`}}}));let a={id:r,role:`assistant`,content:R(n.content)};i&&(a.toolCalls=i),t.push(a)}else{let e=n.toolCallId??``;t.push({id:r,role:`tool`,content:R(n.content),toolCallId:e})}}return t}async function W(e,t){let n=[];for(let r of e??[]){let e=r.role;if(e===`user`){let e=[],i=r.content;if(Array.isArray(i))if(i.some(e=>[`image`,`audio`,`video`,`document`].includes(e.type??``))){try{let n=await N(i,t);for(let t of n)if(t instanceof s)e.push({text:t.text});else{let n=typeof t.toJSON==`function`?t.toJSON():t;e.push(n)}}catch(e){t.warn(`${F} history replay multimodal conversion failed; falling back to text`,e)}e.length===0&&e.push({text:P(i)||``})}else e.push({text:P(i)});else e.push({text:R(i)});n.push({role:`user`,content:e})}else if(e===`assistant`){let e=[],i=R(r.content);i&&e.push({text:i});let a=r.toolCalls??[];for(let n of a){let r=n.function,i=r?.name||`unknown`,a=r?.arguments||`{}`,o;try{o=JSON.parse(a)}catch(e){t.warn(`${F} history tool args JSON parse failed for ${i}; falling back to {}`,e),o={}}(typeof o!=`object`||!o||Array.isArray(o))&&(o={}),e.push({toolUse:{toolUseId:n.id,name:i,input:o}})}e.length===0&&e.push({text:``}),n.push({role:`assistant`,content:e})}else if(e===`tool`){let e=r.toolCallId||``;n.push({role:`user`,content:[{toolResult:{toolUseId:e,content:[z(r.content)],status:`success`}}]})}}return n}var G=class{constructor(e){this._agentsByThread=new Map,this._proxyToolNamesByThread=new Map,this._threadInitLock=new K,this._activeRunsByThread=new Set,this._pendingInterruptsByThread=new Map;let{agent:t,name:n,description:r=``,config:i={},plugins:a}=e,o=t.model===void 0||t.model===null;if(this.name=n,this.description=r,this.config=i,this._log=y(i.logger),o){this._orchestrator=t,this._templateFields={model:void 0,tools:[]},this._plugins=[];return}this._orchestrator=null;let s=t;this._templateFields=L(s),this._plugins=a?[...a]:[],s.sessionManager&&!this.config.sessionManagerProvider&&this._log.warn(`${F} sessionManager was set on the template Agent but will be ignored: forwarding it would cause every AG-UI thread to share the same session_id. Construct per-thread session managers via StrandsAgentConfig.sessionManagerProvider instead.`);for(let e of this._templateFields.tools??[])e!=null&&typeof e.connect==`function`&&typeof e.name!=`string`&&this._log.warn(`${F} an entry in the template Agent's \`tools\` looks like an unconnected McpClient — its tools will not be available to the model. Call \`await client.connect()\` and spread the resolved tool list into \`tools: [...]\` before constructing the Agent.`)}async*run(e){let t=e.threadId||`default`;if(Array.isArray(e.resume)&&e.resume.length>0){let n=this._pendingInterruptsByThread.get(t),r=e.resume.map(e=>e.interruptId).filter(e=>!n?.has(e));if(r.length>0){yield q(e),yield J(`This agent did not issue any interrupts to resume: ${r.slice(0,4).join(`, `)}. Resume entries must reference an outstanding interruptId.`,`UNKNOWN_INTERRUPT`);return}}else this._pendingInterruptsByThread.delete(t);let n=this._runRaw(e);if(this.config.emitChunkEvents){yield*ne(n);return}yield*n}async*_runRaw(e){let t=e.threadId||`default`;if(this._activeRunsByThread.has(t)){yield q(e),yield J(`Another run is already in progress on thread "${t}". Wait for RUN_FINISHED before starting a new run on the same thread.`,`THREAD_BUSY`);return}this._activeRunsByThread.add(t);try{this._orchestrator===null?yield*this._runSingleAgent(e,t):yield*this._runOrchestrator(e)}finally{this._activeRunsByThread.delete(t)}}async*_runSingleAgent(e,n){yield q(e);let r=this._agentsByThread.get(n);if(!r){let i;if(!this.config.sessionManagerProvider)try{i=await Q(e.messages??[],this._log)}catch(e){this._log.error(`${F} buildStrandsSeed failed for thread ${n}: ${V(e)}`,e),yield J(`Failed to build conversation seed: `+V(e),`SEED_BUILD_ERROR`);return}let a=await this._threadInitLock.acquire();try{if(r=this._agentsByThread.get(n),!r){let a;if(this.config.sessionManagerProvider){try{a=await g(this.config.sessionManagerProvider(e))}catch(e){let t=V(e);this._log.error(`${F} sessionManagerProvider failed: ${t}`,e),yield J(`Failed to initialize session manager: ${t}`,`SESSION_MANAGER_ERROR`);return}if(a!=null&&!(a instanceof o)){let e=a?.constructor?.name??typeof a;this._log.error(`${F} sessionManagerProvider returned ${e}; expected a SessionManager instance.`),yield J(`sessionManagerProvider returned ${e}; expected a SessionManager instance`,`SESSION_MANAGER_INVALID_TYPE`);return}a||this._log.warn(`${F} sessionManagerProvider returned null/undefined for threadId=${n}; agent will run without session persistence`)}let s=a?void 0:i;r=new t(this._buildThreadAgentConfig(a??void 0,s)),this._agentsByThread.set(n,r)}}finally{a()}}if(e.tools&&e.tools.length>0){let t=w(r.toolRegistry,e.tools,this._proxyToolNamesByThread.get(n)??new Set,this._log);this._proxyToolNamesByThread.set(n,t)}else{let e=this._proxyToolNamesByThread.get(n);e&&e.size>0&&(w(r.toolRegistry,[],e,this._log),this._proxyToolNamesByThread.set(n,new Set))}try{let t=this.config.emitMessagesSnapshot!==!1,o=t?U(e.messages??[]):[];if(e.state&&typeof e.state==`object`){let t={};for(let[n,r]of Object.entries(e.state))n!==`messages`&&(t[n]=r);yield{type:u.STATE_SNAPSHOT,snapshot:t}}t&&o.length>0&&(yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()});let c=new Set;for(let t of e.tools??[])t.name&&c.add(t.name);let l=new Set;if(e.messages){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if(n.role===`tool`){let e=n.toolCallId;e&&l.add(e)}else break}l.size>0&&this._log.debug(`${F} Has pending tool results detected: toolCallIds=${JSON.stringify([...l])}, threadId=${e.threadId}`)}let d=new Map;for(let t of e.messages??[]){if(t.role!==`assistant`)continue;let e=t.toolCalls;if(e)for(let t of e){let e=t.function;t.id&&e?.name&&d.set(t.id,e.name)}}let p=`Hello`;if(l.size>0&&e.messages)for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if(n.role===`tool`){let e=n.toolCallId;if(e){let t=d.get(e);t&&c.has(t)&&(p=`${t} executed successfully with no return value.`)}break}}else if(e.messages)for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if((n.role===`user`||n.role===`tool`)&&n.content!=null){if(Array.isArray(n.content))if(n.content.some(e=>[`image`,`audio`,`video`,`document`].includes(e.type??``))){let e=await N(n.content,this._log);if(e.length>0)p=e;else{let e=P(n.content);if(e)p=e,this._log.warn(`${F} all media content blocks failed conversion; falling back to text`);else{yield J(`All media content blocks failed conversion and no text fallback is available`,`MEDIA_RESOLUTION_FAILED`);return}}}else p=P(n.content);else p=n.content;break}}if(this.config.stateContextBuilder)try{let t=Array.isArray(p)?P(p):p,n=this.config.stateContextBuilder(e,t,h(e));Array.isArray(p)||(p=n)}catch(e){this._log.error(`${F} stateContextBuilder failed:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateContextBuilder`,tool:`__prompt__`,error:V(e)}}}let m=I(),v=!1,y=``,b=new Map,x={...e.state??{}},S=!1,C=!1,w=!1,T=!1,E,D=null,O=this.config.replayHistoryIntoStrands!==!1&&!r.sessionManager,k=p,A=Y(e);if(A.length>0&&(k=A.map(e=>new i({interruptId:e.interruptId,response:ee(e)})),this._pendingInterruptsByThread.delete(n)),O&&A.length===0){let t=await W(e.messages??[],this._log);if(t.length>0){if(this.config.stateContextBuilder)for(let n=t.length-1;n>=0;n--){let r=t[n];if(!r||r.role!==`user`)continue;let i=r.content[0];if(i&&typeof i.text==`string`){try{let t=this.config.stateContextBuilder(e,i.text,h(e));typeof t==`string`&&(i.text=t)}catch(e){this._log.error(`${F} stateContextBuilder failed:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateContextBuilder`,tool:`__prompt__`,error:V(e)}}}break}}r.messages=t.map(e=>a.fromMessageData({role:e.role,content:e.content})),k=void 0}}this._log.debug(`${F} Starting agent run: threadId=${e.threadId}, runId=${e.runId}, pendingToolResultIds=${JSON.stringify([...l])}, messageCount=${e.messages?.length??0}`);let j=new AbortController,M=r.stream(k,{cancelSignal:j.signal}),L;try{for(;;){let n;try{n=await M.next()}catch(e){if(w||C){if(e instanceof TypeError||e instanceof ReferenceError)throw e;C=!0;break}throw e}if(n.done){L=n.value;break}if(C)continue;let r=Z(n.value),i=X(r);if(i===`modelContentBlockDeltaEvent`){let n=r.delta;if(n.type===`textDelta`&&n.text){if(S)continue;v||=(yield{type:u.TEXT_MESSAGE_START,messageId:m,role:`assistant`},!0),y+=n.text,yield{type:u.TEXT_MESSAGE_CONTENT,messageId:m,delta:n.text};continue}if(n.type===`reasoningContentDelta`){n.text?(T||=(E=I(),yield{type:u.REASONING_START,messageId:E},yield{type:u.REASONING_MESSAGE_START,messageId:E,role:`reasoning`},!0),yield{type:u.REASONING_MESSAGE_CONTENT,messageId:E,delta:n.text}):n.redactedContent&&(T||=(E=I(),yield{type:u.REASONING_START,messageId:E},yield{type:u.REASONING_MESSAGE_START,messageId:E,role:`reasoning`},!0),yield{type:u.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:E,encryptedValue:Buffer.from(n.redactedContent).toString(`base64`)});continue}if(n.type===`toolUseInputDelta`&&D){D.inputChunks.push(n.input);let{name:r,toolUseId:i}=D,a=c.has(r),s=H(b,i,a),d=b.get(s);if(!d){let n=l.has(s),c=this.config.toolBehaviors?.[r];this._log.debug(`${F} Tool call event received: toolName=${r}, toolUseId=${s}, strandsId=${i}, isFrontend=${a}, threadId=${e.threadId}`);let p=!n&&!c?.argsStreamer;if(d={name:r,args:``,input:{},raw:``,emitted:!1,startEmitted:!1,endEmitted:!1,lastEmittedRawLen:0,isPending:n,isFrontend:a,useStreaming:p,strandsToolId:i},b.set(s,d),p){if(v&&(yield{type:u.TEXT_MESSAGE_END,messageId:m},t&&y&&(o.push({id:m,role:`assistant`,content:y}),y=``,yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()}),v=!1,m=I()),c){let e=_(c.predictState).map(f);e.length>0&&(yield{type:u.CUSTOM,name:`PredictState`,value:e})}yield{type:u.TOOL_CALL_START,toolCallId:s,toolCallName:r,parentMessageId:m},d.startEmitted=!0}}let p=D.inputChunks.join(``);d.raw=p;try{d.input=JSON.parse(p)}catch{d.input=p}if(d.args=typeof d.input==`string`?d.input:JSON.stringify(d.input),d.startEmitted&&d.useStreaming){let e=d.lastEmittedRawLen??0;p.length>e&&(yield{type:u.TOOL_CALL_ARGS,toolCallId:s,delta:p.slice(e)},d.lastEmittedRawLen=p.length)}}continue}if(i===`reasoningSignatureEvent`)continue;if(i===`modelContentBlockStartEvent`){let e=r.start;e?.type===`toolUseStart`&&e.name&&(D={name:e.name,toolUseId:e.toolUseId??I(),inputChunks:[]});continue}if(i===`modelContentBlockStopEvent`){if(T&&(yield{type:u.REASONING_MESSAGE_END,messageId:E},yield{type:u.REASONING_END,messageId:E},T=!1,E=void 0),D){let{name:n,toolUseId:r,inputChunks:i}=D;D=null;let a=i.join(``),s={};if(a)try{s=JSON.parse(a)}catch(e){this._log.warn(`${F} tool args JSON parse failed for ${n}; using raw string`,e),s=a}let d=c.has(n),f=H(b,r,d),p=typeof s==`string`?s:JSON.stringify(s);if(!b.has(f))b.set(f,{name:n,args:p,input:s,emitted:!1,strandsToolId:r,raw:a});else{let e=b.get(f);e.args=p,e.input=s,e.raw=a}let _=b.get(f),S=this.config.toolBehaviors?.[n];if(this._log.debug(`${F} contentBlockStop close: toolName=${n}, toolUseId=${f}, isFrontendTool=${d}, isPending=${_.isPending??!1}, useStreaming=${_.useStreaming??!1}, threadId=${e.threadId}`),_.startEmitted&&_.useStreaming){let r=_.lastEmittedRawLen??0;if(a.length>r&&(yield{type:u.TOOL_CALL_ARGS,toolCallId:f,delta:a.slice(r)},_.lastEmittedRawLen=a.length),S?.stateFromArgs){let t={inputData:e,toolName:n,toolUseId:f,toolInput:s,argsStr:p,...h(e)};try{let e=await g(S.stateFromArgs(t));e&&(Object.assign(x,e),yield{type:u.STATE_SNAPSHOT,snapshot:e})}catch(e){this._log.error(`${F} stateFromArgs failed for ${n}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:V(e)}}}}yield{type:u.TOOL_CALL_END,toolCallId:f},_.endEmitted=!0,_.emitted=!0,t&&!S?.skipMessagesSnapshot&&(o.push({id:m,role:`assistant`,content:``,toolCalls:[{id:f,type:`function`,function:{name:n||`unknown`,arguments:p||`{}`}}]}),yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()},m=I()),d&&!S?.continueAfterFrontendCall&&(this._log.debug(`${F} Deferring halt after frontend tool call: toolName=${n}, toolCallId=${f}, threadId=${e.threadId}`),w=!0)}else yield*this._emitToolCall({inputData:e,toolUseId:f,isFrontendTool:d,pendingToolResultIds:l,getMessageId:()=>m,setMessageId:e=>{m=e},getMessageStarted:()=>v,setMessageStarted:e=>{v=e},getAccumulatedText:()=>y,setAccumulatedText:e=>{y=e},snapshotMessages:o,emitMessagesSnapshot:t,toolCallsSeen:b,currentState:x,onPendingHalt:()=>{w=!0}})}continue}if(i===`toolUseBlock`){let n=r,i=c.has(n.name),a=H(b,n.toolUseId,i),s=typeof n.input==`string`?n.input:JSON.stringify(n.input);if(!b.has(a))b.set(a,{name:n.name,args:s,input:n.input,emitted:!1,strandsToolId:n.toolUseId});else{let e=b.get(a);e.args=s,e.input=n.input}yield*this._emitToolCall({inputData:e,toolUseId:a,isFrontendTool:i,pendingToolResultIds:l,getMessageId:()=>m,setMessageId:e=>{m=e},getMessageStarted:()=>v,setMessageStarted:e=>{v=e},getAccumulatedText:()=>y,setAccumulatedText:e=>{y=e},snapshotMessages:o,emitMessagesSnapshot:t,toolCallsSeen:b,currentState:x,onPendingHalt:()=>{w=!0}});continue}if(i===`afterToolCallEvent`){if(w){C=!0;try{j.abort()}catch{}break}let n=r,i=n.toolUse.toolUseId,a=n.toolUse.name;if(c.has(a))continue;let l=null,d=n.result?.content;if(Array.isArray(d))for(let e of d){if(e instanceof s){try{l=JSON.parse(e.text)}catch{try{l=JSON.parse(e.text.replace(/'/g,`"`))}catch(t){this._log.warn(`${F} tool result JSON parse failed for ${a}; using raw text`,t),l=e.text}}break}let t=e.json;if(t!==void 0){l=t;break}}if(!i)continue;let f=b.get(i),p=f?.args,_=f?.input,T=this.config.toolBehaviors?.[a];this._log.debug(`${F} Processing tool result: toolName=${a}, resultToolId=${i}, threadId=${e.threadId}`);let E=I(),D=l==null?``:JSON.stringify(l);yield{type:u.TOOL_CALL_RESULT,toolCallId:i,messageId:E,content:D},t&&!T?.skipMessagesSnapshot&&(o.push({id:E,role:`tool`,content:D,toolCallId:i}),yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()});let O={inputData:e,toolName:a,toolUseId:i,toolInput:_,argsStr:p??`{}`,resultData:l,messageId:m,...h(e)};if(T?.stateFromResult)try{let e=await g(T.stateFromResult(O));e&&(Object.assign(x,e),yield{type:u.STATE_SNAPSHOT,snapshot:e})}catch(e){this._log.error(`${F} stateFromResult failed for ${a}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateFromResult`,tool:a,error:V(e)}}}if(T?.customResultHandler)try{for await(let e of T.customResultHandler(O))e&&(yield e)}catch(e){this._log.error(`${F} customResultHandler failed for ${a}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`customResultHandler`,tool:a,error:V(e)}}}if(T?.stopStreamingAfterResult){S=!0,v&&(yield{type:u.TEXT_MESSAGE_END,messageId:m},v=!1,t&&y&&(o.push({id:m,role:`assistant`,content:y}),y=``,yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()})),this._log.debug(`${F} Breaking event stream: stopStreamingAfterResult behavior triggered (threadId=${e.threadId}, toolName=${a})`),C=!0;break}continue}if(i===`toolStreamEvent`){let e=r.data;e&&typeof e==`object`&&`state`in e&&(yield{type:u.STATE_SNAPSHOT,snapshot:e.state});continue}let a=r;if(a?.type===`beforeNodeCallEvent`){yield{type:u.STEP_STARTED,stepName:`${a.nodeType??`agent`}:${a.nodeId??`unknown`}`};continue}if(a?.type===`afterNodeCallEvent`){yield{type:u.STEP_FINISHED,stepName:`${a.nodeType??`agent`}:${a.nodeId??`unknown`}`};continue}if(a?.type===`multiAgentHandoffEvent`){let e=a.message;yield{type:u.CUSTOM,name:`MultiAgentHandoff`,value:{from_nodes:a.source?[a.source]:[],to_nodes:a.targets??[],message:e}};continue}}}finally{try{j.abort()}catch{}try{await M.return(void 0)}catch{}}if(T&&(yield{type:u.REASONING_MESSAGE_END,messageId:E},yield{type:u.REASONING_END,messageId:E}),v&&(yield{type:u.TEXT_MESSAGE_END,messageId:m},t&&y&&(o.push({id:m,role:`assistant`,content:y}),y=``,yield{type:u.MESSAGES_SNAPSHOT,messages:o.slice()})),yield{type:u.STATE_SNAPSHOT,snapshot:x},L?.stopReason===`interrupt`){let t=L.interrupts??[];if(t.length>0){let r=t.map(e=>e.id);this._pendingInterruptsByThread.set(n,new Set(r)),yield{type:u.RUN_FINISHED,threadId:e.threadId,runId:e.runId,outcome:{type:`interrupt`,interrupts:t.map(te)}};return}}yield{type:u.RUN_FINISHED,threadId:e.threadId,runId:e.runId}}catch(e){let t=e instanceof TypeError||e instanceof ReferenceError?`ADAPTER_BUG`:`STRANDS_ERROR`;this._log.error(`${F} _runSingleAgent failed:`,e),yield J(V(e),t)}}async*_emitToolCall(e){let t=e.toolCallsSeen.get(e.toolUseId);if(!t||t.emitted)return;t.emitted=!0;let n=t.name,r=t.args,i=t.input,a=this.config.toolBehaviors?.[n],o=e.pendingToolResultIds.has(e.toolUseId),s={inputData:e.inputData,toolName:n,toolUseId:e.toolUseId,toolInput:i,argsStr:r,...h(e.inputData)};if(o){if(a?.stateFromArgs)try{let t=await g(a.stateFromArgs(s));t&&(Object.assign(e.currentState,t),yield{type:u.STATE_SNAPSHOT,snapshot:t})}catch(e){this._log.error(`${F} stateFromArgs failed for ${n}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:V(e)}}}return}if(a?.stateFromArgs)try{let t=await g(a.stateFromArgs(s));t&&(Object.assign(e.currentState,t),yield{type:u.STATE_SNAPSHOT,snapshot:t})}catch(e){this._log.error(`${F} stateFromArgs failed for ${n}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:V(e)}}}if(a){let e=_(a.predictState).map(f);e.length>0&&(yield{type:u.CUSTOM,name:`PredictState`,value:e})}if(e.getMessageStarted()){yield{type:u.TEXT_MESSAGE_END,messageId:e.getMessageId()};let t=e.getAccumulatedText();e.emitMessagesSnapshot&&t&&(e.snapshotMessages.push({id:e.getMessageId(),role:`assistant`,content:t}),e.setAccumulatedText(``),yield{type:u.MESSAGES_SNAPSHOT,messages:e.snapshotMessages.slice()}),e.setMessageStarted(!1),e.setMessageId(I())}yield{type:u.TOOL_CALL_START,toolCallId:e.toolUseId,toolCallName:n,parentMessageId:e.getMessageId()};let c=!1;if(a?.argsStreamer)try{for await(let t of a.argsStreamer(s))t!=null&&(yield{type:u.TOOL_CALL_ARGS,toolCallId:e.toolUseId,delta:String(t)})}catch(e){c=!0,this._log.error(`${F} argsStreamer failed for ${n}:`,e),yield{type:u.CUSTOM,name:`hook_error`,value:{hook:`argsStreamer`,tool:n,error:V(e)}}}else yield{type:u.TOOL_CALL_ARGS,toolCallId:e.toolUseId,delta:r};if(c){yield{type:u.TOOL_CALL_END,toolCallId:e.toolUseId};return}yield{type:u.TOOL_CALL_END,toolCallId:e.toolUseId},e.emitMessagesSnapshot&&!a?.skipMessagesSnapshot&&(e.snapshotMessages.push({id:e.getMessageId(),role:`assistant`,content:``,toolCalls:[{id:e.toolUseId,type:`function`,function:{name:n||`unknown`,arguments:r||`{}`}}]}),yield{type:u.MESSAGES_SNAPSHOT,messages:e.snapshotMessages.slice()},e.setMessageId(I())),e.isFrontendTool&&!a?.continueAfterFrontendCall&&(this._log.debug(`${F} Deferring halt after frontend tool call: toolName=${n}, toolCallId=${e.toolUseId}, threadId=${e.inputData.threadId}`),e.onPendingHalt())}async*_runOrchestrator(e){yield q(e);try{if(e.state&&typeof e.state==`object`){let t={};for(let[n,r]of Object.entries(e.state))n!==`messages`&&(t[n]=r);yield{type:u.STATE_SNAPSHOT,snapshot:t}}let t=`Hello`;if(e.messages)for(let n=e.messages.length-1;n>=0;n--){let r=e.messages[n];if(!r)break;if((r.role===`user`||r.role===`tool`)&&r.content!=null){t=typeof r.content==`string`?r.content:P(r.content);break}}let n=I(),r=!1,i=!1,a,o=this._orchestrator.stream(t);try{for await(let e of o){let t=Z(e),o=X(t);if(o===`beforeNodeCallEvent`){let e=t;yield{type:u.STEP_STARTED,stepName:`${e.nodeType??`agent`}:${e.nodeId??`unknown`}`};continue}if(o===`afterNodeCallEvent`){let e=t;r&&(yield{type:u.TEXT_MESSAGE_END,messageId:n},r=!1,n=I()),i&&(yield{type:u.REASONING_MESSAGE_END,messageId:a},yield{type:u.REASONING_END,messageId:a},i=!1,a=void 0),yield{type:u.STEP_FINISHED,stepName:`${e.nodeType??`agent`}:${e.nodeId??`unknown`}`};continue}if(o===`multiAgentHandoffEvent`){let e=t;yield{type:u.CUSTOM,name:`MultiAgentHandoff`,value:{from_nodes:e.source?[e.source]:[],to_nodes:e.targets??[],message:e.message}};continue}if(o===`nodeStreamUpdateEvent`){let e=t,o=e.inner?.event?Z(e.inner.event):void 0;if(X(o)===`modelContentBlockDeltaEvent`){let e=o.delta;e?.type===`textDelta`&&e.text?(r||=(yield{type:u.TEXT_MESSAGE_START,messageId:n,role:`assistant`},!0),yield{type:u.TEXT_MESSAGE_CONTENT,messageId:n,delta:e.text}):e?.type===`reasoningContentDelta`&&e.text&&(i||=(a=I(),yield{type:u.REASONING_START,messageId:a},yield{type:u.REASONING_MESSAGE_START,messageId:a,role:`reasoning`},!0),yield{type:u.REASONING_MESSAGE_CONTENT,messageId:a,delta:e.text})}continue}}}finally{try{await o.return(void 0)}catch{}}r&&(yield{type:u.TEXT_MESSAGE_END,messageId:n}),i&&(yield{type:u.REASONING_MESSAGE_END,messageId:a},yield{type:u.REASONING_END,messageId:a}),yield{type:u.STATE_SNAPSHOT,snapshot:{}},yield{type:u.RUN_FINISHED,threadId:e.threadId,runId:e.runId}}catch(e){let t=e instanceof TypeError||e instanceof ReferenceError?`ADAPTER_BUG`:`STRANDS_ERROR`;this._log.error(`${F} _runOrchestrator failed:`,e),yield J(V(e),t)}}_buildThreadAgentConfig(e,t){let n=this._templateFields,r={model:n.model,tools:n.tools.slice(),printer:!1};return n.systemPrompt!==void 0&&(r.systemPrompt=n.systemPrompt),n.name!==void 0&&(r.name=n.name),n.description!==void 0&&(r.description=n.description),n.id!==void 0&&(r.id=n.id),n.appState!==void 0&&(r.appState=n.appState),n.modelState!==void 0&&(r.modelState=n.modelState),n.traceAttributes!==void 0&&(r.traceAttributes=n.traceAttributes),n.structuredOutputSchema!==void 0&&(r.structuredOutputSchema=n.structuredOutputSchema),n.toolExecutor!==void 0&&(r.toolExecutor=n.toolExecutor),e&&(r.sessionManager=e),t&&t.length>0&&(r.messages=t),this._plugins.length>0&&(r.plugins=[...this._plugins]),r}},K=class{constructor(){this._tail=Promise.resolve()}async acquire(){let e,t=new Promise(t=>{e=t}),n=this._tail;return this._tail=t,await n,e}};function q(e){return{type:u.RUN_STARTED,threadId:e.threadId,runId:e.runId}}function J(e,t){return{type:u.RUN_ERROR,message:e,code:t}}function Y(e){let t=e.resume;return Array.isArray(t)&&t.length>0?t:[]}function ee(e){return e.status===`cancelled`?{status:`cancelled`}:e.payload}function te(e){let t=e.reason,n=typeof t==`string`&&t.length>0?t:`confirmation`,r={id:e.id,reason:n};if(typeof t==`string`&&t.length>0)r.message=t;else if(t!=null)try{r.message=JSON.stringify(t)}catch{}return r.metadata={strandsName:e.name},r}function X(e){if(e&&typeof e==`object`&&`type`in e){let t=e.type;return typeof t==`string`?t:void 0}}function Z(e){if(!e||typeof e!=`object`)return e;let t=e.type;return t===`modelStreamUpdateEvent`&&`event`in e||t===`toolStreamUpdateEvent`&&`event`in e?e.event:t===`contentBlockEvent`&&`contentBlock`in e?e.contentBlock:e}async function*ne(e){for await(let t of e)switch(t.type){case u.TEXT_MESSAGE_START:{let e=t;yield{type:u.TEXT_MESSAGE_CHUNK,messageId:e.messageId,role:e.role};break}case u.TEXT_MESSAGE_CONTENT:{let e=t;yield{type:u.TEXT_MESSAGE_CHUNK,messageId:e.messageId,delta:e.delta};break}case u.TEXT_MESSAGE_END:break;case u.TOOL_CALL_START:{let e=t;yield{type:u.TOOL_CALL_CHUNK,toolCallId:e.toolCallId,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId};break}case u.TOOL_CALL_ARGS:{let e=t;yield{type:u.TOOL_CALL_CHUNK,toolCallId:e.toolCallId,delta:e.delta};break}case u.TOOL_CALL_END:break;case u.REASONING_MESSAGE_START:{let e=t;yield{type:u.REASONING_MESSAGE_CHUNK,messageId:e.messageId};break}case u.REASONING_MESSAGE_CONTENT:{let e=t;yield{type:u.REASONING_MESSAGE_CHUNK,messageId:e.messageId,delta:e.delta};break}case u.REASONING_MESSAGE_END:break;default:yield t}}async function Q(e,t){if(e.length===0)return;let n=e.length;if(e[e.length-1]?.role===`user`&&(n=e.length-1),n<=0)return;let r=await $(e.slice(0,n),t);if(r.length!==0){for(;r.length>0&&r[0]?.role!==`user`;)r.shift();if(r.length!==0)return r}}async function $(e,t){let n=[],r=null,i=null,a=()=>{i&&i.length>0&&n.push({role:`user`,content:i}),i=null,r=null};for(let o of e){let e=o.role;if(e===`system`||e===`developer`)continue;if(e===`assistant`){a();let e=o.toolCalls,i=[];if(typeof o.content==`string`&&o.content.length>0)i.push({text:o.content});else if(Array.isArray(o.content))for(let e of o.content)e&&typeof e==`object`&&`text`in e&&i.push({text:e.text});if(e&&e.length>0){r=new Map;for(let n of e){if(!n?.id||!n.function?.name)continue;let e={};try{e=n.function.arguments?JSON.parse(n.function.arguments):{}}catch(r){t?.warn(`${F} seed tool args JSON parse failed for ${n.function.name}; using raw string`,r),e=n.function.arguments??{}}i.push({toolUse:{name:n.function.name,toolUseId:n.id,input:e}}),r.set(n.id,n.function.name)}}if(i.length===0)continue;n.push({role:`assistant`,content:i});continue}if(e===`tool`){let e=o.toolCallId;if(!e||!r||!r.has(e))continue;let t=o.content,n=typeof t==`string`?t:Array.isArray(t)?t.map(e=>e&&typeof e==`object`&&`text`in e?e.text??``:``).join(``):``;i??=[],i.push({toolResult:{toolUseId:e,status:`success`,content:[{text:n}]}});continue}a();let c=[],l=o.content;if(typeof l==`string`)l.length>0&&c.push({text:l});else if(Array.isArray(l))if(l.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e.type;return t===`image`||t===`audio`||t===`video`||t===`document`}))try{let e=await N(l,t);for(let t of e)if(t instanceof s)c.push({text:t.text});else{let e=typeof t.toJSON==`function`?t.toJSON():t;c.push(e)}}catch(e){(t??v).warn(`${F} seed multimodal conversion failed; dropping attachments for this turn`,e);let n=P(l);n.length>0&&c.push({text:n})}else for(let e of l)e&&typeof e==`object`&&`text`in e&&c.push({text:e.text});c.length!==0&&n.push({role:`user`,content:c})}return a(),n}var re=class extends d{};export{re as AWSStrandsAgent,G as StrandsAgent,h as buildContextExtras,U as buildSnapshotMessages,Q as buildStrandsSeed,N as convertAguiContentToStrands,$ as convertMessagesForStrandsSeed,S as createProxyTool,P as flattenContentToText,C as isProxyTool,w as syncProxyTools};
1
+ import{randomUUID as e}from"crypto";import{Agent as t,DocumentBlock as n,ImageBlock as r,InterruptResponseContent as i,Message as a,SessionManager as o,TextBlock as s,ToolResultBlock as c,ToolStreamEvent as l,VideoBlock as u}from"@strands-agents/sdk";import{EventType as d}from"@ag-ui/core";import{A2UI_OPERATIONS_KEY as f,GENERATE_A2UI_ARG_DESCRIPTIONS as p,GENERATE_A2UI_TOOL_NAME as m,RENDER_A2UI_TOOL_DEF as h,buildA2UIEnvelope as g,prepareA2UIRequest as _,resolveA2UIToolParams as v,runA2UIGenerationWithRecovery as y,wrapErrorEnvelope as b}from"@ag-ui/a2ui-toolkit";import{HttpAgent as x}from"@ag-ui/client";function S(e){return{state_key:e.stateKey,tool:e.tool,tool_argument:e.toolArgument}}const C=new Set([`__proto__`,`constructor`,`prototype`]);function w(e){return typeof e==`object`&&!!e&&`stateKey`in e&&`tool`in e&&`toolArgument`in e}function T(e){let t=Object.create(null),n=e.context;if(Array.isArray(n))for(let e of n){if(!e||typeof e!=`object`)continue;let n=e;typeof n.description!=`string`||n.description.length===0||C.has(n.description)||(t[n.description]=typeof n.value==`string`?n.value:String(n.value??``))}let r=e.forwardedProps;return{context:t,forwardedProps:r&&typeof r==`object`&&!Array.isArray(r)?r:{}}}async function E(e){return await Promise.resolve(e)}function D(e){return e===void 0?[]:w(e)?[e]:Array.from(e)}const O={debug(){},warn:(e,...t)=>console.warn(e,...t),error:(e,...t)=>console.error(e,...t)};function k(e){return e??O}const A=`[@ag-ui/aws-strands]`,j=Symbol.for(`@ag-ui/aws-strands.proxyTool`);function M(e){let t=e.description&&e.description.length>0?e.description:`Client-side tool: ${e.name}`,n={name:e.name,description:t,inputSchema:e.parameters??{type:`object`,properties:{}}};return{name:n.name,description:t,toolSpec:n,[j]:!0,async*stream(e){return new c({toolUseId:e.toolUse.toolUseId,status:`success`,content:[new s(`Forwarded to client`)]})}}}function N(e){return typeof e==`object`&&!!e&&e[j]===!0}function P(e,t,n,r=O){let i=new Set;for(let e of t)e.name&&i.add(e.name);for(let t of n){if(i.has(t))continue;let n=e.get(t);n&&N(n)&&(e.remove(t),r.debug(`${A} Removed stale proxy tool: ${t}`))}let a=new Set;for(let n of t){if(!n.name)continue;let t=e.get(n.name);if(t&&!N(t)){r.warn(`${A} Native tool "${n.name}" shadows client-declared tool with the same name; client tool will not be registered`);continue}t&&e.remove(n.name),e.add(M(n)),a.add(n.name),r.debug(`${A} Registered proxy tool: ${n.name}`)}return a}const F=`[@ag-ui/aws-strands]`,I=new Set([`png`,`jpeg`,`gif`,`webp`]),ee=new Set([`pdf`,`csv`,`doc`,`docx`,`xls`,`xlsx`,`html`,`txt`,`md`]),te=new Set([`flv`,`mkv`,`mov`,`mpeg`,`mpg`,`mp4`,`three_gp`,`webm`,`wmv`]);function L(e,t,n){if(!e)return n.warn(`${F} No MIME type provided, cannot determine format`),null;let r=e.split(`/`).pop()?.toLowerCase()??``;return t.has(r)?r:(n.warn(`${F} Unsupported MIME type '${e}' (parsed format '${r}' not in ${JSON.stringify([...t].sort())})`),null)}async function ne(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),3e4);try{let r=await fetch(e,{signal:n.signal});if(!r.ok)return t.warn(`${F} Failed to fetch URL ${e}: HTTP ${r.status}`),null;let i=await r.arrayBuffer();return new Uint8Array(i)}catch(n){return t.warn(`${F} Failed to fetch URL ${e}:`,n),null}finally{clearTimeout(r)}}function re(e,t){try{let t=globalThis.atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){return t.warn(`${F} Failed to decode base64 content:`,e),null}}async function R(e,t){return e.type===`data`?re(e.value,t):e.type===`url`?await ne(e.value,t):(t.warn(`${F} Unknown content source type: ${e.type}, cannot resolve bytes`),null)}async function z(e,t=O){let i=[];for(let a of e){if(a.type===`text`){i.push(new s(a.text));continue}if(a.type===`image`){let e=a,n=await R(e.source,t);if(!n)continue;let o=L(e.source.mimeType,I,t);if(!o)continue;i.push(new r({format:o,source:{bytes:n}}));continue}if(a.type===`document`){let e=a,r=await R(e.source,t);if(!r)continue;let o=L(e.source.mimeType,ee,t);if(!o)continue;i.push(new n({format:o,name:`document`,source:{bytes:r}}));continue}if(a.type===`video`){let e=a,n=await R(e.source,t);if(!n)continue;let r=L(e.source.mimeType,te,t);if(!r)continue;i.push(new u({format:r,source:{bytes:n}}));continue}if(a.type===`audio`){t.warn(`${F} Skipping audio content: Strands has no audio support`);continue}if(a.type===`binary`){let e=a,n=null;if(e.data?n=re(e.data,t):e.url&&(n=await ne(e.url,t)),!n){t.warn(`${F} Skipping binary content: could not resolve bytes`);continue}let o=L(e.mimeType,I,t);if(!o){t.warn(`${F} Skipping binary content: unsupported MIME type '${e.mimeType}'`);continue}i.push(new r({format:o,source:{bytes:n}}));continue}t.warn(`${F} Skipping unknown content type: ${a.type}`)}return i}function B(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e)){let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.type===`text`&&typeof e.text==`string`&&t.push(e.text),e.type===`textBlock`&&typeof e.text==`string`&&t.push(e.text)}return t.join(` `)}return``}const V=h.function.name,H=Symbol.for(`@ag-ui/aws-strands.a2uiAutoInjected`),U=`__a2uiRenderStream`;let W=0;function ie(e,t={}){if(e?.model==null)throw Error(`getA2UITools requires a 'model' (the Strands model instance the render sub-agent runs on).`);let{model:n,guidelines:r,defaultSurfaceId:i,defaultCatalogId:a,toolName:o,toolDescription:u,catalog:d,recovery:f,onA2UIAttempt:m}=v(e),h=n;return{name:o,description:u,toolSpec:{name:o,description:u,inputSchema:{type:`object`,properties:{intent:{type:`string`,enum:[`create`,`update`],description:p.intent},target_surface_id:{type:`string`,description:p.target_surface_id},changes:{type:`string`,description:p.changes}}}},async*stream(e){let n=e.toolUse.input??{},u=ue(e.agent.messages??[],o),p=[...t.aguiMessages??[],...fe(u)],v=_({intent:n.intent,targetSurfaceId:n.target_surface_id,changes:n.changes,messages:p,state:t.state&&typeof t.state==`object`&&!Array.isArray(t.state)?t.state:{},guidelines:r}),x=[],S=null,C=e=>{x.push(e),S?.(),S=null};v.error&&O.warn(`[@ag-ui/aws-strands] A2UI request prep failed: ${v.error}`);let w=!1,T=v.error?Promise.resolve(b(v.error)):y({basePrompt:v.prompt,catalog:d,config:f,onAttempt:m,invokeSubagent:t=>{if(w){let e=Error(`consumer disconnected; abandoning A2UI recovery`);throw e.name=`CancelledError`,e}return oe(h,t,u,{cancelSignal:e.agent.cancelSignal,onStreamEvent:C})},buildEnvelope:e=>g({args:e,isUpdate:v.isUpdate,targetSurfaceId:n.target_surface_id,prior:v.prior,defaultSurfaceId:i,defaultCatalogId:a})}).then(e=>e.envelope),E=!1,D=T.then(()=>{E=!0},()=>{E=!0});try{for(;!E||x.length>0;){for(;x.length>0;)yield new l({data:{[U]:x.shift()}});if(E)break;await Promise.race([D,new Promise(e=>{S=e})])}}finally{E||(w=!0,T.catch(e=>{let t=e?.name;t===`CancelledError`||t===`AbortError`||O.warn(`[@ag-ui/aws-strands] A2UI recovery loop failed after the consumer disconnected: ${e instanceof Error?e.message:String(e)}`)}))}let k=await T;return new c({toolUseId:e.toolUse.toolUseId,status:`success`,content:[new s(k)]})}}}function ae(e,t){let n=e?.name;return t||n===`AbortError`||n===`CancelledError`?`rethrow`:e instanceof TypeError?e.message===`fetch failed`?`recoverable`:`rethrow`:e instanceof ReferenceError?`rethrow`:`recoverable`}async function oe(e,n,r,i={}){let a=null,o=new t({model:e,tools:[{name:V,description:h.function.description,toolSpec:{name:V,description:h.function.description,inputSchema:h.function.parameters},async*stream(e){return a=e.toolUse.input??{},new c({toolUseId:e.toolUse.toolUseId,status:`success`,content:[new s(`ok`)]})}}],systemPrompt:n}),l=i.onStreamEvent,u=null,d=!1;try{let e=o.stream(r,i.cancelSignal?{cancelSignal:i.cancelSignal}:void 0);for await(let t of e){if(!l)continue;let e=t&&typeof t==`object`&&t.type===`modelStreamUpdateEvent`&&`event`in t?t.event:t;if(e?.type===`modelContentBlockStartEvent`&&e.start?.type===`toolUseStart`){if(u&&=(l({kind:`end`,toolCallId:u}),null),e.start.name!==V)continue;u=e.start.toolUseId||`a2ui-render-${++W}`,d=!0,l({kind:`start`,toolCallId:u,toolCallName:V})}else u&&e?.type===`modelContentBlockDeltaEvent`&&e.delta?.type===`toolUseInputDelta`&&typeof e.delta.input==`string`?l({kind:`args`,toolCallId:u,delta:e.delta.input}):u&&e?.type===`modelContentBlockStopEvent`&&(l({kind:`end`,toolCallId:u}),u=null)}}catch(e){if(l&&u&&(l({kind:`end`,toolCallId:u}),u=null),ae(e,!!i.cancelSignal?.aborted)===`rethrow`)throw e;return O.warn(`[@ag-ui/aws-strands] A2UI sub-agent invoke failed; treating as a failed attempt: ${e instanceof Error?e.message:String(e)}`),null}if(l){if(u)l({kind:`end`,toolCallId:u}),u=null;else if(!d&&a!==null){let e=`a2ui-render-${++W}`;l({kind:`start`,toolCallId:e,toolCallName:V}),l({kind:`args`,toolCallId:e,delta:JSON.stringify(a)}),l({kind:`end`,toolCallId:e})}}return a}function se(e){let t=e;return t?.type===`toolUseBlock`?{name:t.name}:t?.toolUse?{name:t.toolUse.name}:null}function ce(e){let t=e;return t?.type===`toolResultBlock`?{toolUseId:t.toolUseId,content:t.content}:t?.toolResult?t.toolResult:null}function le(e,t){let n=e?.content;return Array.isArray(n)?n.some(e=>se(e)?.name===t):!1}function ue(e,t){let n=e[e.length-1];return n&&n.role===`assistant`&&le(n,t)?e.slice(0,-1):e.slice()}function de(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return B(e);let t=[];for(let n of e){let e=n;typeof e?.text==`string`?t.push(e.text):e?.json!==void 0&&t.push(JSON.stringify(e.json))}return t.join(``)}function fe(e){let t=[],n=0;for(let r of e){let e=r?.content;if(Array.isArray(e))for(let r of e){let e=ce(r);if(!e)continue;let i=de(e.content);if(!i||!i.includes(f))continue;let a=e.toolUseId||`a2ui-prior-${n++}`;t.push({id:a,role:`tool`,toolCallId:a,content:i})}}return t}function pe(e){let{input:t,existingToolNames:n,config:r,log:i=O}=e,a=t.forwardedProps?.injectA2UITool??r?.injectA2UITool;if(!a)return null;let o=m;if(n.includes(o))return null;if(e.model==null)return i.warn("[@ag-ui/aws-strands] A2UI tool injection requested but no model could be inferred from the agent (multi-agent orchestrators like Graph/Swarm have no `.model`). Skipping auto-injection — wire getA2UITools() explicitly."),null;let s=typeof a==`string`?a:V,c=r?.catalog??he(t),l=ie({model:e.model,toolName:o,catalog:c,defaultCatalogId:r?.defaultCatalogId,guidelines:r?.guidelines,recovery:r?.recovery},{aguiMessages:t.messages,state:t.state});return l[H]=!0,{tool:l,toolName:o,dropToolNames:[s],catalog:c}}function me(e){return typeof e==`object`&&!!e&&e[H]===!0}function he(e){for(let t of e.context??[]){if(t.description!==`A2UI Component Schema — available components for generating UI surfaces. Use these component names and properties when creating A2UI operations.`)continue;if(!t.value){O.warn(`[@ag-ui/aws-strands] A2UI schema context entry has an empty value; catalog-aware recovery disabled.`);continue}let e;try{e=JSON.parse(t.value)}catch(e){O.warn(`[@ag-ui/aws-strands] A2UI schema context entry present but unparseable; catalog-aware recovery disabled: ${String(e)}`);continue}if(typeof e==`object`&&e&&!Array.isArray(e))return e;O.warn(`[@ag-ui/aws-strands] A2UI schema context entry is valid JSON but not an object; catalog-aware recovery disabled.`)}}const G=`[@ag-ui/aws-strands]`,K=()=>e();function ge(e){let t={model:e.model,tools:e.tools.slice()};e.systemPrompt!==void 0&&(t.systemPrompt=e.systemPrompt),e.name!==void 0&&(t.name=e.name),e.id!==void 0&&(t.id=e.id),e.description!==void 0&&(t.description=e.description);let n=e.appState?.getAll?.();n&&Object.keys(n).length>0&&(t.appState=n);let r=e.modelState?.getAll?.();r&&Object.keys(r).length>0&&(t.modelState=r);let i=e;return i.traceAttributes!==void 0&&(t.traceAttributes=i.traceAttributes),i.structuredOutputSchema!==void 0&&(t.structuredOutputSchema=i.structuredOutputSchema),i.toolExecutor!==void 0&&(t.toolExecutor=i.toolExecutor),t}function q(e){return typeof e==`string`?e:e==null?``:Array.isArray(e)?B(e):String(e)}function _e(e){let t=q(e),n=t.trim();if(n.length===0)return{text:t};let r=n[0];if(r!==`{`&&r!==`[`)return{text:t};try{let e=JSON.parse(n);if(typeof e==`object`&&e)return{json:e}}catch{}return{text:t}}function ve(e){return typeof e==`string`&&e.length>0?e:K()}function J(e){return e instanceof Error?e.message:String(e)}function Y(e,t,n){for(let[n,r]of e)if(r.strandsToolId===t)return n;return n?K():t||K()}function ye(e){let t=[];for(let n of e??[]){let e=n.role;if(e!==`user`&&e!==`assistant`&&e!==`tool`)continue;let r=ve(n.id);if(e===`user`)t.push({id:r,role:`user`,content:q(n.content)});else if(e===`assistant`){let e=n.toolCalls,i;e&&e.length>0&&(i=e.map(e=>{let t=e.function;return{id:ve(e.id),type:`function`,function:{name:t?.name??`unknown`,arguments:t?.arguments??`{}`}}}));let a={id:r,role:`assistant`,content:q(n.content)};i&&(a.toolCalls=i),t.push(a)}else{let e=n.toolCallId??``;t.push({id:r,role:`tool`,content:q(n.content),toolCallId:e})}}return t}async function be(e,t){let n=[];for(let r of e??[]){let e=r.role;if(e===`user`){let e=[],i=r.content;if(Array.isArray(i))if(i.some(e=>[`image`,`audio`,`video`,`document`].includes(e.type??``))){try{let n=await z(i,t);for(let t of n)if(t instanceof s)e.push({text:t.text});else{let n=typeof t.toJSON==`function`?t.toJSON():t;e.push(n)}}catch(e){t.warn(`${G} history replay multimodal conversion failed; falling back to text`,e)}e.length===0&&e.push({text:B(i)||``})}else e.push({text:B(i)});else e.push({text:q(i)});n.push({role:`user`,content:e})}else if(e===`assistant`){let e=[],i=q(r.content);i&&e.push({text:i});let a=r.toolCalls??[];for(let n of a){let r=n.function,i=r?.name||`unknown`,a=r?.arguments||`{}`,o;try{o=JSON.parse(a)}catch(e){t.warn(`${G} history tool args JSON parse failed for ${i}; falling back to {}`,e),o={}}(typeof o!=`object`||!o||Array.isArray(o))&&(o={}),e.push({toolUse:{toolUseId:n.id,name:i,input:o}})}e.length===0&&e.push({text:``}),n.push({role:`assistant`,content:e})}else if(e===`tool`){let e=r.toolCallId||``;n.push({role:`user`,content:[{toolResult:{toolUseId:e,content:[_e(r.content)],status:`success`}}]})}}return n}var xe=class{constructor(e){this._agentsByThread=new Map,this._proxyToolNamesByThread=new Map,this._threadInitLock=new Se,this._activeRunsByThread=new Set,this._pendingInterruptsByThread=new Map;let{agent:t,name:n,description:r=``,config:i={},plugins:a}=e,o=t.model===void 0||t.model===null;if(this.name=n,this.description=r,this.config=i,this._log=k(i.logger),o){this._orchestrator=t,this._templateFields={model:void 0,tools:[]},this._plugins=[];return}this._orchestrator=null;let s=t;this._templateFields=ge(s),this._plugins=a?[...a]:[],s.sessionManager&&!this.config.sessionManagerProvider&&this._log.warn(`${G} sessionManager was set on the template Agent but will be ignored: forwarding it would cause every AG-UI thread to share the same session_id. Construct per-thread session managers via StrandsAgentConfig.sessionManagerProvider instead.`);for(let e of this._templateFields.tools??[])e!=null&&typeof e.connect==`function`&&typeof e.name!=`string`&&this._log.warn(`${G} an entry in the template Agent's \`tools\` looks like an unconnected McpClient — its tools will not be available to the model. Call \`await client.connect()\` and spread the resolved tool list into \`tools: [...]\` before constructing the Agent.`)}async*run(e){let t=e.threadId||`default`;if(Array.isArray(e.resume)&&e.resume.length>0){let n=this._pendingInterruptsByThread.get(t),r=e.resume.map(e=>e.interruptId).filter(e=>!n?.has(e));if(r.length>0){yield X(e),yield Z(`This agent did not issue any interrupts to resume: ${r.slice(0,4).join(`, `)}. Resume entries must reference an outstanding interruptId.`,`UNKNOWN_INTERRUPT`);return}}else this._pendingInterruptsByThread.delete(t);let n=this._runRaw(e);if(this.config.emitChunkEvents){yield*Ee(n);return}yield*n}async*_runRaw(e){let t=e.threadId||`default`;if(this._activeRunsByThread.has(t)){yield X(e),yield Z(`Another run is already in progress on thread "${t}". Wait for RUN_FINISHED before starting a new run on the same thread.`,`THREAD_BUSY`);return}this._activeRunsByThread.add(t);try{this._orchestrator===null?yield*this._runSingleAgent(e,t):yield*this._runOrchestrator(e)}finally{this._activeRunsByThread.delete(t)}}async*_runSingleAgent(e,n){yield X(e);let r=this._agentsByThread.get(n);if(!r){let i;if(!this.config.sessionManagerProvider)try{i=await De(e.messages??[],this._log)}catch(e){this._log.error(`${G} buildStrandsSeed failed for thread ${n}: ${J(e)}`,e),yield Z(`Failed to build conversation seed: `+J(e),`SEED_BUILD_ERROR`);return}let a=await this._threadInitLock.acquire();try{if(r=this._agentsByThread.get(n),!r){let a;if(this.config.sessionManagerProvider){try{a=await E(this.config.sessionManagerProvider(e))}catch(e){let t=J(e);this._log.error(`${G} sessionManagerProvider failed: ${t}`,e),yield Z(`Failed to initialize session manager: ${t}`,`SESSION_MANAGER_ERROR`);return}if(a!=null&&!(a instanceof o)){let e=a?.constructor?.name??typeof a;this._log.error(`${G} sessionManagerProvider returned ${e}; expected a SessionManager instance.`),yield Z(`sessionManagerProvider returned ${e}; expected a SessionManager instance`,`SESSION_MANAGER_INVALID_TYPE`);return}a||this._log.warn(`${G} sessionManagerProvider returned null/undefined for threadId=${n}; agent will run without session persistence`)}let s=a?void 0:i;r=new t(this._buildThreadAgentConfig(a??void 0,s)),this._agentsByThread.set(n,r)}}finally{a()}}if(e.tools&&e.tools.length>0){let t=P(r.toolRegistry,e.tools,this._proxyToolNamesByThread.get(n)??new Set,this._log);this._proxyToolNamesByThread.set(n,t)}else{let e=this._proxyToolNamesByThread.get(n);e&&e.size>0&&(P(r.toolRegistry,[],e,this._log),this._proxyToolNamesByThread.set(n,new Set))}try{let t=r.toolRegistry;if(typeof t.list!=`function`)(e.forwardedProps?.injectA2UITool??this.config.a2ui?.injectA2UITool)&&this._log.warn(`[@ag-ui/aws-strands] A2UI tool injection requested but toolRegistry.list() is unavailable; skipping auto-injection for this run.`);else{for(let e of t.list())me(e)&&t.remove(e.name);let n=t.list().map(e=>e.name),i=pe({model:r.model??null,input:e,existingToolNames:n,config:this.config.a2ui,log:this._log});if(i){for(let e of i.dropToolNames)t.remove(e);t.add(i.tool)}}}catch(e){this._log.warn(`[@ag-ui/aws-strands] A2UI auto-injection failed; running without A2UI for this turn: ${e instanceof Error?e.message:String(e)}`)}try{let t=this.config.emitMessagesSnapshot!==!1,o=t?ye(e.messages??[]):[];if(e.state&&typeof e.state==`object`){let t={};for(let[n,r]of Object.entries(e.state))n!==`messages`&&(t[n]=r);yield{type:d.STATE_SNAPSHOT,snapshot:t}}t&&o.length>0&&(yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()});let c=new Set;for(let t of e.tools??[])t.name&&c.add(t.name);let l=new Set;if(e.messages){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if(n.role===`tool`){let e=n.toolCallId;e&&l.add(e)}else break}l.size>0&&this._log.debug(`${G} Has pending tool results detected: toolCallIds=${JSON.stringify([...l])}, threadId=${e.threadId}`)}let u=new Map;for(let t of e.messages??[]){if(t.role!==`assistant`)continue;let e=t.toolCalls;if(e)for(let t of e){let e=t.function;t.id&&e?.name&&u.set(t.id,e.name)}}let f=`Hello`;if(l.size>0&&e.messages)for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if(n.role===`tool`){let e=n.toolCallId;if(e){let t=u.get(e);t&&c.has(t)&&(f=`${t} executed successfully with no return value.`)}break}}else if(e.messages)for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(!n)break;if((n.role===`user`||n.role===`tool`)&&n.content!=null){if(Array.isArray(n.content))if(n.content.some(e=>[`image`,`audio`,`video`,`document`].includes(e.type??``))){let e=await z(n.content,this._log);if(e.length>0)f=e;else{let e=B(n.content);if(e)f=e,this._log.warn(`${G} all media content blocks failed conversion; falling back to text`);else{yield Z(`All media content blocks failed conversion and no text fallback is available`,`MEDIA_RESOLUTION_FAILED`);return}}}else f=B(n.content);else f=n.content;break}}if(this.config.stateContextBuilder)try{let t=Array.isArray(f)?B(f):f,n=this.config.stateContextBuilder(e,t,T(e));Array.isArray(f)||(f=n)}catch(e){this._log.error(`${G} stateContextBuilder failed:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateContextBuilder`,tool:`__prompt__`,error:J(e)}}}let p=K(),m=!1,h=``,g=new Map,_={...e.state??{}},v=!1,y=!1,b=!1,x=!1,C,w=null,O=this.config.replayHistoryIntoStrands!==!1&&!r.sessionManager,k=f,A=Ce(e);if(A.length>0&&(k=A.map(e=>new i({interruptId:e.interruptId,response:we(e)})),this._pendingInterruptsByThread.delete(n)),O&&A.length===0){let t=await be(e.messages??[],this._log);if(t.length>0){if(this.config.stateContextBuilder)for(let n=t.length-1;n>=0;n--){let r=t[n];if(!r||r.role!==`user`)continue;let i=r.content[0];if(i&&typeof i.text==`string`){try{let t=this.config.stateContextBuilder(e,i.text,T(e));typeof t==`string`&&(i.text=t)}catch(e){this._log.error(`${G} stateContextBuilder failed:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateContextBuilder`,tool:`__prompt__`,error:J(e)}}}break}}r.messages=t.map(e=>a.fromMessageData({role:e.role,content:e.content})),k=void 0}}this._log.debug(`${G} Starting agent run: threadId=${e.threadId}, runId=${e.runId}, pendingToolResultIds=${JSON.stringify([...l])}, messageCount=${e.messages?.length??0}`);let j=new AbortController,M=r.stream(k,{cancelSignal:j.signal}),N;try{for(;;){let n;try{n=await M.next()}catch(e){if(b||y){if(e instanceof TypeError||e instanceof ReferenceError)throw e;y=!0;break}throw e}if(n.done){N=n.value;break}if(y)continue;let r=$(n.value),i=Q(r);if(i===`modelContentBlockDeltaEvent`){let n=r.delta;if(n.type===`textDelta`&&n.text){if(v)continue;m||=(yield{type:d.TEXT_MESSAGE_START,messageId:p,role:`assistant`},!0),h+=n.text,yield{type:d.TEXT_MESSAGE_CONTENT,messageId:p,delta:n.text};continue}if(n.type===`reasoningContentDelta`){n.text?(x||=(C=K(),yield{type:d.REASONING_START,messageId:C},yield{type:d.REASONING_MESSAGE_START,messageId:C,role:`reasoning`},!0),yield{type:d.REASONING_MESSAGE_CONTENT,messageId:C,delta:n.text}):n.redactedContent&&(x||=(C=K(),yield{type:d.REASONING_START,messageId:C},yield{type:d.REASONING_MESSAGE_START,messageId:C,role:`reasoning`},!0),yield{type:d.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:C,encryptedValue:Buffer.from(n.redactedContent).toString(`base64`)});continue}if(n.type===`toolUseInputDelta`&&w){w.inputChunks.push(n.input);let{name:r,toolUseId:i}=w,a=c.has(r),s=Y(g,i,a),u=g.get(s);if(!u){let n=l.has(s),c=this.config.toolBehaviors?.[r];this._log.debug(`${G} Tool call event received: toolName=${r}, toolUseId=${s}, strandsId=${i}, isFrontend=${a}, threadId=${e.threadId}`);let f=!n&&!c?.argsStreamer;if(u={name:r,args:``,input:{},raw:``,emitted:!1,startEmitted:!1,endEmitted:!1,lastEmittedRawLen:0,isPending:n,isFrontend:a,useStreaming:f,strandsToolId:i},g.set(s,u),f){if(m&&(yield{type:d.TEXT_MESSAGE_END,messageId:p},t&&h&&(o.push({id:p,role:`assistant`,content:h}),h=``,yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()}),m=!1,p=K()),c){let e=D(c.predictState).map(S);e.length>0&&(yield{type:d.CUSTOM,name:`PredictState`,value:e})}yield{type:d.TOOL_CALL_START,toolCallId:s,toolCallName:r,parentMessageId:p},u.startEmitted=!0}}let f=w.inputChunks.join(``);u.raw=f;try{u.input=JSON.parse(f)}catch{u.input=f}if(u.args=typeof u.input==`string`?u.input:JSON.stringify(u.input),u.startEmitted&&u.useStreaming){let e=u.lastEmittedRawLen??0;f.length>e&&(yield{type:d.TOOL_CALL_ARGS,toolCallId:s,delta:f.slice(e)},u.lastEmittedRawLen=f.length)}}continue}if(i===`reasoningSignatureEvent`)continue;if(i===`modelContentBlockStartEvent`){let e=r.start;e?.type===`toolUseStart`&&e.name&&(w={name:e.name,toolUseId:e.toolUseId??K(),inputChunks:[]});continue}if(i===`modelContentBlockStopEvent`){if(x&&(yield{type:d.REASONING_MESSAGE_END,messageId:C},yield{type:d.REASONING_END,messageId:C},x=!1,C=void 0),w){let{name:n,toolUseId:r,inputChunks:i}=w;w=null;let a=i.join(``),s={};if(a)try{s=JSON.parse(a)}catch(e){this._log.warn(`${G} tool args JSON parse failed for ${n}; using raw string`,e),s=a}let u=c.has(n),f=Y(g,r,u),v=typeof s==`string`?s:JSON.stringify(s);if(!g.has(f))g.set(f,{name:n,args:v,input:s,emitted:!1,strandsToolId:r,raw:a});else{let e=g.get(f);e.args=v,e.input=s,e.raw=a}let y=g.get(f),x=this.config.toolBehaviors?.[n];if(this._log.debug(`${G} contentBlockStop close: toolName=${n}, toolUseId=${f}, isFrontendTool=${u}, isPending=${y.isPending??!1}, useStreaming=${y.useStreaming??!1}, threadId=${e.threadId}`),y.startEmitted&&y.useStreaming){let r=y.lastEmittedRawLen??0;if(a.length>r&&(yield{type:d.TOOL_CALL_ARGS,toolCallId:f,delta:a.slice(r)},y.lastEmittedRawLen=a.length),x?.stateFromArgs){let t={inputData:e,toolName:n,toolUseId:f,toolInput:s,argsStr:v,...T(e)};try{let e=await E(x.stateFromArgs(t));e&&(Object.assign(_,e),yield{type:d.STATE_SNAPSHOT,snapshot:e})}catch(e){this._log.error(`${G} stateFromArgs failed for ${n}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:J(e)}}}}yield{type:d.TOOL_CALL_END,toolCallId:f},y.endEmitted=!0,y.emitted=!0,t&&!x?.skipMessagesSnapshot&&(o.push({id:p,role:`assistant`,content:``,toolCalls:[{id:f,type:`function`,function:{name:n||`unknown`,arguments:v||`{}`}}]}),yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()},p=K()),u&&!x?.continueAfterFrontendCall&&(this._log.debug(`${G} Deferring halt after frontend tool call: toolName=${n}, toolCallId=${f}, threadId=${e.threadId}`),b=!0)}else yield*this._emitToolCall({inputData:e,toolUseId:f,isFrontendTool:u,pendingToolResultIds:l,getMessageId:()=>p,setMessageId:e=>{p=e},getMessageStarted:()=>m,setMessageStarted:e=>{m=e},getAccumulatedText:()=>h,setAccumulatedText:e=>{h=e},snapshotMessages:o,emitMessagesSnapshot:t,toolCallsSeen:g,currentState:_,onPendingHalt:()=>{b=!0}})}continue}if(i===`toolUseBlock`){let n=r,i=c.has(n.name),a=Y(g,n.toolUseId,i),s=typeof n.input==`string`?n.input:JSON.stringify(n.input);if(!g.has(a))g.set(a,{name:n.name,args:s,input:n.input,emitted:!1,strandsToolId:n.toolUseId});else{let e=g.get(a);e.args=s,e.input=n.input}yield*this._emitToolCall({inputData:e,toolUseId:a,isFrontendTool:i,pendingToolResultIds:l,getMessageId:()=>p,setMessageId:e=>{p=e},getMessageStarted:()=>m,setMessageStarted:e=>{m=e},getAccumulatedText:()=>h,setAccumulatedText:e=>{h=e},snapshotMessages:o,emitMessagesSnapshot:t,toolCallsSeen:g,currentState:_,onPendingHalt:()=>{b=!0}});continue}if(i===`afterToolCallEvent`){if(b){y=!0;try{j.abort()}catch{}break}let n=r,i=n.toolUse.toolUseId,a=n.toolUse.name;if(c.has(a))continue;let l=null,u=n.result?.content;if(Array.isArray(u))for(let e of u){if(e instanceof s){try{l=JSON.parse(e.text)}catch{try{l=JSON.parse(e.text.replace(/'/g,`"`))}catch(t){this._log.warn(`${G} tool result JSON parse failed for ${a}; using raw text`,t),l=e.text}}break}let t=e.json;if(t!==void 0){l=t;break}}if(!i)continue;let f=g.get(i),x=f?.args,S=f?.input,C=this.config.toolBehaviors?.[a];this._log.debug(`${G} Processing tool result: toolName=${a}, resultToolId=${i}, threadId=${e.threadId}`);let w=K(),D=l==null?``:JSON.stringify(l);yield{type:d.TOOL_CALL_RESULT,toolCallId:i,messageId:w,content:D},t&&!C?.skipMessagesSnapshot&&(o.push({id:w,role:`tool`,content:D,toolCallId:i}),yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()});let O={inputData:e,toolName:a,toolUseId:i,toolInput:S,argsStr:x??`{}`,resultData:l,messageId:p,...T(e)};if(C?.stateFromResult)try{let e=await E(C.stateFromResult(O));e&&(Object.assign(_,e),yield{type:d.STATE_SNAPSHOT,snapshot:e})}catch(e){this._log.error(`${G} stateFromResult failed for ${a}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateFromResult`,tool:a,error:J(e)}}}if(C?.customResultHandler)try{for await(let e of C.customResultHandler(O))e&&(yield e)}catch(e){this._log.error(`${G} customResultHandler failed for ${a}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`customResultHandler`,tool:a,error:J(e)}}}if(C?.stopStreamingAfterResult){v=!0,m&&(yield{type:d.TEXT_MESSAGE_END,messageId:p},m=!1,t&&h&&(o.push({id:p,role:`assistant`,content:h}),h=``,yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()})),this._log.debug(`${G} Breaking event stream: stopStreamingAfterResult behavior triggered (threadId=${e.threadId}, toolName=${a})`),y=!0;break}continue}if(i===`toolStreamEvent`){let e=r.data;if(e&&typeof e==`object`&&`state`in e)yield{type:d.STATE_SNAPSHOT,snapshot:e.state};else if(e&&typeof e==`object`&&U in e){let t=e[U];t.kind===`start`?yield{type:d.TOOL_CALL_START,toolCallId:t.toolCallId,toolCallName:t.toolCallName??`render_a2ui`}:t.kind===`args`&&t.delta?yield{type:d.TOOL_CALL_ARGS,toolCallId:t.toolCallId,delta:t.delta}:t.kind===`end`&&(yield{type:d.TOOL_CALL_END,toolCallId:t.toolCallId})}continue}let a=r;if(a?.type===`beforeNodeCallEvent`){yield{type:d.STEP_STARTED,stepName:`${a.nodeType??`agent`}:${a.nodeId??`unknown`}`};continue}if(a?.type===`afterNodeCallEvent`){yield{type:d.STEP_FINISHED,stepName:`${a.nodeType??`agent`}:${a.nodeId??`unknown`}`};continue}if(a?.type===`multiAgentHandoffEvent`){let e=a.message;yield{type:d.CUSTOM,name:`MultiAgentHandoff`,value:{from_nodes:a.source?[a.source]:[],to_nodes:a.targets??[],message:e}};continue}}}finally{try{j.abort()}catch{}try{await M.return(void 0)}catch{}}if(x&&(yield{type:d.REASONING_MESSAGE_END,messageId:C},yield{type:d.REASONING_END,messageId:C}),m&&(yield{type:d.TEXT_MESSAGE_END,messageId:p},t&&h&&(o.push({id:p,role:`assistant`,content:h}),h=``,yield{type:d.MESSAGES_SNAPSHOT,messages:o.slice()})),yield{type:d.STATE_SNAPSHOT,snapshot:_},N?.stopReason===`interrupt`){let t=N.interrupts??[];if(t.length>0){let r=t.map(e=>e.id);this._pendingInterruptsByThread.set(n,new Set(r)),yield{type:d.RUN_FINISHED,threadId:e.threadId,runId:e.runId,outcome:{type:`interrupt`,interrupts:t.map(Te)}};return}}yield{type:d.RUN_FINISHED,threadId:e.threadId,runId:e.runId}}catch(e){let t=e instanceof TypeError||e instanceof ReferenceError?`ADAPTER_BUG`:`STRANDS_ERROR`;this._log.error(`${G} _runSingleAgent failed:`,e),yield Z(J(e),t)}}async*_emitToolCall(e){let t=e.toolCallsSeen.get(e.toolUseId);if(!t||t.emitted)return;t.emitted=!0;let n=t.name,r=t.args,i=t.input,a=this.config.toolBehaviors?.[n],o=e.pendingToolResultIds.has(e.toolUseId),s={inputData:e.inputData,toolName:n,toolUseId:e.toolUseId,toolInput:i,argsStr:r,...T(e.inputData)};if(o){if(a?.stateFromArgs)try{let t=await E(a.stateFromArgs(s));t&&(Object.assign(e.currentState,t),yield{type:d.STATE_SNAPSHOT,snapshot:t})}catch(e){this._log.error(`${G} stateFromArgs failed for ${n}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:J(e)}}}return}if(a?.stateFromArgs)try{let t=await E(a.stateFromArgs(s));t&&(Object.assign(e.currentState,t),yield{type:d.STATE_SNAPSHOT,snapshot:t})}catch(e){this._log.error(`${G} stateFromArgs failed for ${n}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`stateFromArgs`,tool:n,error:J(e)}}}if(a){let e=D(a.predictState).map(S);e.length>0&&(yield{type:d.CUSTOM,name:`PredictState`,value:e})}if(e.getMessageStarted()){yield{type:d.TEXT_MESSAGE_END,messageId:e.getMessageId()};let t=e.getAccumulatedText();e.emitMessagesSnapshot&&t&&(e.snapshotMessages.push({id:e.getMessageId(),role:`assistant`,content:t}),e.setAccumulatedText(``),yield{type:d.MESSAGES_SNAPSHOT,messages:e.snapshotMessages.slice()}),e.setMessageStarted(!1),e.setMessageId(K())}yield{type:d.TOOL_CALL_START,toolCallId:e.toolUseId,toolCallName:n,parentMessageId:e.getMessageId()};let c=!1;if(a?.argsStreamer)try{for await(let t of a.argsStreamer(s))t!=null&&(yield{type:d.TOOL_CALL_ARGS,toolCallId:e.toolUseId,delta:String(t)})}catch(e){c=!0,this._log.error(`${G} argsStreamer failed for ${n}:`,e),yield{type:d.CUSTOM,name:`hook_error`,value:{hook:`argsStreamer`,tool:n,error:J(e)}}}else yield{type:d.TOOL_CALL_ARGS,toolCallId:e.toolUseId,delta:r};if(c){yield{type:d.TOOL_CALL_END,toolCallId:e.toolUseId};return}yield{type:d.TOOL_CALL_END,toolCallId:e.toolUseId},e.emitMessagesSnapshot&&!a?.skipMessagesSnapshot&&(e.snapshotMessages.push({id:e.getMessageId(),role:`assistant`,content:``,toolCalls:[{id:e.toolUseId,type:`function`,function:{name:n||`unknown`,arguments:r||`{}`}}]}),yield{type:d.MESSAGES_SNAPSHOT,messages:e.snapshotMessages.slice()},e.setMessageId(K())),e.isFrontendTool&&!a?.continueAfterFrontendCall&&(this._log.debug(`${G} Deferring halt after frontend tool call: toolName=${n}, toolCallId=${e.toolUseId}, threadId=${e.inputData.threadId}`),e.onPendingHalt())}async*_runOrchestrator(e){yield X(e);try{if(e.state&&typeof e.state==`object`){let t={};for(let[n,r]of Object.entries(e.state))n!==`messages`&&(t[n]=r);yield{type:d.STATE_SNAPSHOT,snapshot:t}}let t=`Hello`;if(e.messages)for(let n=e.messages.length-1;n>=0;n--){let r=e.messages[n];if(!r)break;if((r.role===`user`||r.role===`tool`)&&r.content!=null){t=typeof r.content==`string`?r.content:B(r.content);break}}let n=K(),r=!1,i=!1,a,o=this._orchestrator.stream(t);try{for await(let e of o){let t=$(e),o=Q(t);if(o===`beforeNodeCallEvent`){let e=t;yield{type:d.STEP_STARTED,stepName:`${e.nodeType??`agent`}:${e.nodeId??`unknown`}`};continue}if(o===`afterNodeCallEvent`){let e=t;r&&(yield{type:d.TEXT_MESSAGE_END,messageId:n},r=!1,n=K()),i&&(yield{type:d.REASONING_MESSAGE_END,messageId:a},yield{type:d.REASONING_END,messageId:a},i=!1,a=void 0),yield{type:d.STEP_FINISHED,stepName:`${e.nodeType??`agent`}:${e.nodeId??`unknown`}`};continue}if(o===`multiAgentHandoffEvent`){let e=t;yield{type:d.CUSTOM,name:`MultiAgentHandoff`,value:{from_nodes:e.source?[e.source]:[],to_nodes:e.targets??[],message:e.message}};continue}if(o===`nodeStreamUpdateEvent`){let e=t,o=e.inner?.event?$(e.inner.event):void 0;if(Q(o)===`modelContentBlockDeltaEvent`){let e=o.delta;e?.type===`textDelta`&&e.text?(r||=(yield{type:d.TEXT_MESSAGE_START,messageId:n,role:`assistant`},!0),yield{type:d.TEXT_MESSAGE_CONTENT,messageId:n,delta:e.text}):e?.type===`reasoningContentDelta`&&e.text&&(i||=(a=K(),yield{type:d.REASONING_START,messageId:a},yield{type:d.REASONING_MESSAGE_START,messageId:a,role:`reasoning`},!0),yield{type:d.REASONING_MESSAGE_CONTENT,messageId:a,delta:e.text})}continue}}}finally{try{await o.return(void 0)}catch{}}r&&(yield{type:d.TEXT_MESSAGE_END,messageId:n}),i&&(yield{type:d.REASONING_MESSAGE_END,messageId:a},yield{type:d.REASONING_END,messageId:a}),yield{type:d.STATE_SNAPSHOT,snapshot:{}},yield{type:d.RUN_FINISHED,threadId:e.threadId,runId:e.runId}}catch(e){let t=e instanceof TypeError||e instanceof ReferenceError?`ADAPTER_BUG`:`STRANDS_ERROR`;this._log.error(`${G} _runOrchestrator failed:`,e),yield Z(J(e),t)}}_buildThreadAgentConfig(e,t){let n=this._templateFields,r={model:n.model,tools:n.tools.slice(),printer:!1};return n.systemPrompt!==void 0&&(r.systemPrompt=n.systemPrompt),n.name!==void 0&&(r.name=n.name),n.description!==void 0&&(r.description=n.description),n.id!==void 0&&(r.id=n.id),n.appState!==void 0&&(r.appState=n.appState),n.modelState!==void 0&&(r.modelState=n.modelState),n.traceAttributes!==void 0&&(r.traceAttributes=n.traceAttributes),n.structuredOutputSchema!==void 0&&(r.structuredOutputSchema=n.structuredOutputSchema),n.toolExecutor!==void 0&&(r.toolExecutor=n.toolExecutor),e&&(r.sessionManager=e),t&&t.length>0&&(r.messages=t),this._plugins.length>0&&(r.plugins=[...this._plugins]),r}},Se=class{constructor(){this._tail=Promise.resolve()}async acquire(){let e,t=new Promise(t=>{e=t}),n=this._tail;return this._tail=t,await n,e}};function X(e){return{type:d.RUN_STARTED,threadId:e.threadId,runId:e.runId}}function Z(e,t){return{type:d.RUN_ERROR,message:e,code:t}}function Ce(e){let t=e.resume;return Array.isArray(t)&&t.length>0?t:[]}function we(e){return e.status===`cancelled`?{status:`cancelled`}:e.payload}function Te(e){let t=e.reason,n=typeof t==`string`&&t.length>0?t:`confirmation`,r={id:e.id,reason:n};if(typeof t==`string`&&t.length>0)r.message=t;else if(t!=null)try{r.message=JSON.stringify(t)}catch{}return r.metadata={strandsName:e.name},r}function Q(e){if(e&&typeof e==`object`&&`type`in e){let t=e.type;return typeof t==`string`?t:void 0}}function $(e){if(!e||typeof e!=`object`)return e;let t=e.type;return t===`modelStreamUpdateEvent`&&`event`in e||t===`toolStreamUpdateEvent`&&`event`in e?e.event:t===`contentBlockEvent`&&`contentBlock`in e?e.contentBlock:e}async function*Ee(e){for await(let t of e)switch(t.type){case d.TEXT_MESSAGE_START:{let e=t;yield{type:d.TEXT_MESSAGE_CHUNK,messageId:e.messageId,role:e.role};break}case d.TEXT_MESSAGE_CONTENT:{let e=t;yield{type:d.TEXT_MESSAGE_CHUNK,messageId:e.messageId,delta:e.delta};break}case d.TEXT_MESSAGE_END:break;case d.TOOL_CALL_START:{let e=t;yield{type:d.TOOL_CALL_CHUNK,toolCallId:e.toolCallId,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId};break}case d.TOOL_CALL_ARGS:{let e=t;yield{type:d.TOOL_CALL_CHUNK,toolCallId:e.toolCallId,delta:e.delta};break}case d.TOOL_CALL_END:break;case d.REASONING_MESSAGE_START:{let e=t;yield{type:d.REASONING_MESSAGE_CHUNK,messageId:e.messageId};break}case d.REASONING_MESSAGE_CONTENT:{let e=t;yield{type:d.REASONING_MESSAGE_CHUNK,messageId:e.messageId,delta:e.delta};break}case d.REASONING_MESSAGE_END:break;default:yield t}}async function De(e,t){if(e.length===0)return;let n=e.length;if(e[e.length-1]?.role===`user`&&(n=e.length-1),n<=0)return;let r=await Oe(e.slice(0,n),t);if(r.length!==0){for(;r.length>0&&r[0]?.role!==`user`;)r.shift();if(r.length!==0)return r}}async function Oe(e,t){let n=[],r=null,i=null,a=()=>{i&&i.length>0&&n.push({role:`user`,content:i}),i=null,r=null};for(let o of e){let e=o.role;if(e===`system`||e===`developer`)continue;if(e===`assistant`){a();let e=o.toolCalls,i=[];if(typeof o.content==`string`&&o.content.length>0)i.push({text:o.content});else if(Array.isArray(o.content))for(let e of o.content)e&&typeof e==`object`&&`text`in e&&i.push({text:e.text});if(e&&e.length>0){r=new Map;for(let n of e){if(!n?.id||!n.function?.name)continue;let e={};try{e=n.function.arguments?JSON.parse(n.function.arguments):{}}catch(r){t?.warn(`${G} seed tool args JSON parse failed for ${n.function.name}; using raw string`,r),e=n.function.arguments??{}}i.push({toolUse:{name:n.function.name,toolUseId:n.id,input:e}}),r.set(n.id,n.function.name)}}if(i.length===0)continue;n.push({role:`assistant`,content:i});continue}if(e===`tool`){let e=o.toolCallId;if(!e||!r||!r.has(e))continue;let t=o.content,n=typeof t==`string`?t:Array.isArray(t)?t.map(e=>e&&typeof e==`object`&&`text`in e?e.text??``:``).join(``):``;i??=[],i.push({toolResult:{toolUseId:e,status:`success`,content:[{text:n}]}});continue}a();let c=[],l=o.content;if(typeof l==`string`)l.length>0&&c.push({text:l});else if(Array.isArray(l))if(l.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e.type;return t===`image`||t===`audio`||t===`video`||t===`document`}))try{let e=await z(l,t);for(let t of e)if(t instanceof s)c.push({text:t.text});else{let e=typeof t.toJSON==`function`?t.toJSON():t;c.push(e)}}catch(e){(t??O).warn(`${G} seed multimodal conversion failed; dropping attachments for this turn`,e);let n=B(l);n.length>0&&c.push({text:n})}else for(let e of l)e&&typeof e==`object`&&`text`in e&&c.push({text:e.text});c.length!==0&&n.push({role:`user`,content:c})}return a(),n}var ke=class extends x{};export{U as A2UI_STREAM_KEY,ke as AWSStrandsAgent,xe as StrandsAgent,T as buildContextExtras,ye as buildSnapshotMessages,De as buildStrandsSeed,z as convertAguiContentToStrands,Oe as convertMessagesForStrandsSeed,M as createProxyTool,B as flattenContentToText,ie as getA2UITools,me as isAutoInjectedA2UITool,N as isProxyTool,pe as planA2UIInjection,P as syncProxyTools};
2
2
  //# sourceMappingURL=index.mjs.map