@ably/ai-transport 0.2.0 → 0.3.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/README.md +10 -19
- package/dist/ably-ai-transport.js +1790 -1091
- package/dist/ably-ai-transport.js.map +1 -1
- package/dist/ably-ai-transport.umd.cjs +1 -1
- package/dist/ably-ai-transport.umd.cjs.map +1 -1
- package/dist/constants.d.ts +2 -2
- package/dist/core/agent.d.ts +20 -5
- package/dist/core/channel-options.d.ts +57 -0
- package/dist/core/codec/codec-event.d.ts +9 -0
- package/dist/core/codec/decoder.d.ts +4 -1
- package/dist/core/codec/define-codec.d.ts +100 -0
- package/dist/core/codec/encoder.d.ts +2 -7
- package/dist/core/codec/field-bag.d.ts +85 -0
- package/dist/core/codec/fields.d.ts +141 -0
- package/dist/core/codec/index.d.ts +8 -1
- package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
- package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
- package/dist/core/codec/input-descriptors.d.ts +281 -0
- package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
- package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
- package/dist/core/codec/output-descriptors.d.ts +237 -0
- package/dist/core/codec/types.d.ts +95 -36
- package/dist/core/codec/well-known-inputs.d.ts +52 -0
- package/dist/core/transport/agent-view.d.ts +296 -0
- package/dist/core/transport/decode-fold.d.ts +40 -32
- package/dist/core/transport/headers.d.ts +30 -1
- package/dist/core/transport/index.d.ts +1 -1
- package/dist/core/transport/invocation.d.ts +1 -1
- package/dist/core/transport/load-history-pages.d.ts +71 -0
- package/dist/core/transport/load-history.d.ts +21 -16
- package/dist/core/transport/run-manager.d.ts +9 -11
- package/dist/core/transport/session-support.d.ts +55 -0
- package/dist/core/transport/tree.d.ts +165 -15
- package/dist/core/transport/types/agent.d.ts +120 -98
- package/dist/core/transport/types/client.d.ts +45 -12
- package/dist/core/transport/types/tree.d.ts +52 -10
- package/dist/core/transport/types/view.d.ts +55 -28
- package/dist/core/transport/view.d.ts +176 -58
- package/dist/core/transport/wire-log.d.ts +102 -0
- package/dist/errors.d.ts +10 -4
- package/dist/index.d.ts +6 -5
- package/dist/react/ably-ai-transport-react.js +784 -415
- package/dist/react/ably-ai-transport-react.js.map +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
- package/dist/react/contexts/client-session-context.d.ts +2 -1
- package/dist/react/contexts/client-session-provider.d.ts +3 -0
- package/dist/react/index.d.ts +2 -1
- package/dist/react/internal/skipped-session.d.ts +8 -0
- package/dist/react/use-view.d.ts +3 -3
- package/dist/utils.d.ts +22 -54
- package/dist/vercel/ably-ai-transport-vercel.js +2297 -2026
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
- package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
- package/dist/vercel/codec/events.d.ts +1 -2
- package/dist/vercel/codec/fields.d.ts +44 -0
- package/dist/vercel/codec/fold-content.d.ts +16 -0
- package/dist/vercel/codec/fold-data.d.ts +16 -0
- package/dist/vercel/codec/fold-input.d.ts +67 -0
- package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
- package/dist/vercel/codec/fold-text.d.ts +16 -0
- package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
- package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
- package/dist/vercel/codec/index.d.ts +5 -30
- package/dist/vercel/codec/inputs.d.ts +11 -0
- package/dist/vercel/codec/outputs.d.ts +11 -0
- package/dist/vercel/codec/reducer-state.d.ts +121 -0
- package/dist/vercel/codec/reducer.d.ts +20 -102
- package/dist/vercel/codec/tool-transitions.d.ts +0 -6
- package/dist/vercel/codec/wire-data.d.ts +34 -0
- package/dist/vercel/index.d.ts +1 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +2013 -9500
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -70
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +2 -1
- package/dist/vercel/run-end-reason.d.ts +66 -11
- package/dist/vercel/tool-part.d.ts +21 -0
- package/dist/vercel/transport/chat-transport.d.ts +0 -2
- package/dist/vercel/transport/index.d.ts +1 -1
- package/dist/vercel/transport/run-output-stream.d.ts +6 -8
- package/dist/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/constants.ts +2 -2
- package/src/core/agent.ts +43 -19
- package/src/core/channel-options.ts +89 -0
- package/src/core/codec/codec-event.ts +27 -0
- package/src/core/codec/decoder.ts +145 -21
- package/src/core/codec/define-codec.ts +432 -0
- package/src/core/codec/encoder.ts +13 -54
- package/src/core/codec/field-bag.ts +142 -0
- package/src/core/codec/fields.ts +193 -0
- package/src/core/codec/index.ts +43 -0
- package/src/core/codec/input-descriptor-decoder.ts +97 -0
- package/src/core/codec/input-descriptor-encoder.ts +150 -0
- package/src/core/codec/input-descriptors.ts +373 -0
- package/src/core/codec/output-descriptor-decoder.ts +139 -0
- package/src/core/codec/output-descriptor-encoder.ts +101 -0
- package/src/core/codec/output-descriptors.ts +307 -0
- package/src/core/codec/types.ts +99 -36
- package/src/core/codec/well-known-inputs.ts +96 -0
- package/src/core/transport/agent-session.ts +330 -589
- package/src/core/transport/agent-view.ts +738 -0
- package/src/core/transport/client-session.ts +74 -69
- package/src/core/transport/decode-fold.ts +57 -47
- package/src/core/transport/headers.ts +57 -4
- package/src/core/transport/index.ts +2 -1
- package/src/core/transport/invocation.ts +1 -1
- package/src/core/transport/load-history-pages.ts +220 -0
- package/src/core/transport/load-history.ts +63 -61
- package/src/core/transport/pipe-stream.ts +10 -1
- package/src/core/transport/run-manager.ts +25 -31
- package/src/core/transport/session-support.ts +96 -0
- package/src/core/transport/tree.ts +414 -47
- package/src/core/transport/types/agent.ts +129 -102
- package/src/core/transport/types/client.ts +49 -13
- package/src/core/transport/types/tree.ts +61 -12
- package/src/core/transport/types/view.ts +57 -28
- package/src/core/transport/view.ts +520 -172
- package/src/core/transport/wire-log.ts +189 -0
- package/src/errors.ts +10 -3
- package/src/index.ts +44 -11
- package/src/react/contexts/client-session-context.ts +1 -1
- package/src/react/contexts/client-session-provider.tsx +38 -2
- package/src/react/index.ts +2 -1
- package/src/react/internal/skipped-session.ts +62 -0
- package/src/react/use-client-session.ts +7 -30
- package/src/react/use-view.ts +3 -3
- package/src/utils.ts +31 -97
- package/src/vercel/codec/decode-lifecycle.ts +70 -0
- package/src/vercel/codec/events.ts +1 -3
- package/src/vercel/codec/fields.ts +58 -0
- package/src/vercel/codec/fold-content.ts +54 -0
- package/src/vercel/codec/fold-data.ts +46 -0
- package/src/vercel/codec/fold-input.ts +255 -0
- package/src/vercel/codec/fold-lifecycle.ts +85 -0
- package/src/vercel/codec/fold-text.ts +55 -0
- package/src/vercel/codec/fold-tool-input.ts +86 -0
- package/src/vercel/codec/fold-tool-output.ts +79 -0
- package/src/vercel/codec/index.ts +23 -63
- package/src/vercel/codec/inputs.ts +116 -0
- package/src/vercel/codec/outputs.ts +207 -0
- package/src/vercel/codec/reducer-state.ts +169 -0
- package/src/vercel/codec/reducer.ts +52 -838
- package/src/vercel/codec/tool-transitions.ts +1 -12
- package/src/vercel/codec/wire-data.ts +64 -0
- package/src/vercel/index.ts +1 -0
- package/src/vercel/react/contexts/chat-transport-context.ts +1 -1
- package/src/vercel/react/use-chat-transport.ts +8 -28
- package/src/vercel/react/use-message-sync.ts +5 -10
- package/src/vercel/run-end-reason.ts +95 -16
- package/src/vercel/tool-part.ts +25 -0
- package/src/vercel/transport/chat-transport.ts +10 -22
- package/src/vercel/transport/index.ts +1 -1
- package/src/vercel/transport/run-output-stream.ts +7 -8
- package/src/version.ts +1 -1
- package/dist/core/transport/branch-chain.d.ts +0 -43
- package/dist/core/transport/load-conversation.d.ts +0 -128
- package/dist/vercel/codec/decoder.d.ts +0 -9
- package/dist/vercel/codec/encoder.d.ts +0 -11
- package/src/core/transport/branch-chain.ts +0 -58
- package/src/core/transport/load-conversation.ts +0 -355
- package/src/vercel/codec/decoder.ts +0 -696
- package/src/vercel/codec/encoder.ts +0 -548
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`ably`),require(`ai`)):typeof define==`function`&&define.amd?define([`exports`,`ably`,`ai`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportVercel={},e.Ably,e.AI))})(this,function(e,t,n){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var s=o(t),l=0,u=s.length,d;l<u;l++)d=s[l],!c.call(e,d)&&d!==n&&i(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=a(t,d))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:r(s(e)),l(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);var u=`stream`,d=`status`,f=`stream-id`,p=`discrete`,m=`run-id`,h=`invocation-id`,g=`event-id`,_=`codec-message-id`,v=`run-client-id`,y=`input-client-id`,b=`role`,x=`parent`,S=`fork-of`,C=`msg-regenerate`,w=`run-reason`,T=`input-codec-message-id`,E=`error-code`,D=`ai-cancel`,O=`ai-run-start`,ee=`ai-run-suspend`,te=`ai-run-resume`,k=`ai-run-end`,A=`ai-output`,j=`ai-input`,M=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},N=e=>M(e,`transport`),P=e=>M(e,`codec`),F=e=>{if(e!==void 0)try{return JSON.parse(e)}catch{return}},I=(e,t)=>({...e,...t}),L=e=>{if(e!==void 0)return e===`true`},R=(e,t)=>e.serial===void 0&&t.serial===void 0?0:e.serial===void 0?1:t.serial===void 0||e.serial<t.serial?-1:+(e.serial>t.serial),z=(e,t)=>e[t],B=e=>{let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==void 0&&(t[n]=e[n]);return t},V=e=>({str:t=>z(e,t),strOr:(t,n)=>z(e,t)??n,bool:t=>L(z(e,t)),json:t=>F(z(e,t))}),H=()=>{let e={},t={str:(n,r)=>(r!==void 0&&(e[n]=r),t),bool:(n,r)=>(r!==void 0&&(e[n]=String(r)),t),json:(n,r)=>(r!=null&&(e[n]=JSON.stringify(r)),t),build:()=>e};return t},U=class{constructor(e,t={}){this._serialState=new Map,this._hooks=e,this._onStreamUpdate=t.onStreamUpdate,this._onStreamDelete=t.onStreamDelete,this._logger=t.logger?.withContext({component:`DecoderCore`})}decode(e){let t=e.action;switch(this._logger?.trace(`DefaultDecoderCore.decode();`,{action:t,serial:e.serial,name:e.name}),t){case`message.create`:{let t=this._toPayload(e);return t.transportHeaders?.stream===`true`?this._decodeStreamedCreate(t,e.serial):this._hooks.decodeDiscrete(t)}case`message.append`:return this._decodeAppend(e);case`message.update`:return this._decodeUpdate(e);case`message.delete`:return this._decodeDelete(e);default:return[]}}_toPayload(e){return{name:e.name??``,data:e.data,transportHeaders:N(e),codecHeaders:P(e)}}_stringData(e){return typeof e.data==`string`?e.data:``}_invokeOnStreamUpdate(e){if(this._onStreamUpdate)try{this._onStreamUpdate(e)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamUpdate(); callback threw`,{error:e})}}_invokeOnStreamDelete(e,t){if(this._onStreamDelete)try{this._onStreamDelete(e,t)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamDelete(); callback threw`,{error:e})}}_decodeStreamedCreate(e,t){if(!t)return[];let n=e.transportHeaders?.[`stream-id`]??``,r={name:e.name,streamId:n,accumulated:``,codecHeaders:{...e.codecHeaders},transportHeaders:{...e.transportHeaders},closed:!1};return this._serialState.set(t,r),this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); new stream`,{name:e.name,streamId:n,serial:t}),this._hooks.buildStartEvents(r)}_decodeAppend(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);if(!n)return this._decodeUpdate(e);let r=N(e),i=P(e),a=typeof e.data==`string`?e.data:``,o=r[d],s=[];return a.length>0&&(n.accumulated+=a,s.push(...this._hooks.buildDeltaEvents(n,a))),o===`complete`&&!n.closed?(n.closed=!0,s.push(...this._hooks.buildEndEvents(n,i)),this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream complete`,{streamId:n.streamId})):o===`cancelled`&&!n.closed&&(n.closed=!0,this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream cancelled`,{streamId:n.streamId})),s}_decodeUpdate(e){let t=e.serial;if(!t)return[];let n=this._toPayload(e),r=n.transportHeaders??{},i=n.codecHeaders??{},a=r[u]===`true`,o=r[d],s=this._serialState.get(t);if(!s)return this._decodeFirstContact(n,a,o,t);let c=this._stringData(e);if(c.startsWith(s.accumulated)){let e=c.slice(s.accumulated.length),t=[];return e.length>0&&(s.accumulated=c,t.push(...this._hooks.buildDeltaEvents(s,e))),o===`complete`&&!s.closed?(s.closed=!0,t.push(...this._hooks.buildEndEvents(s,i))):o===`cancelled`&&!s.closed&&(s.closed=!0),t}return s.accumulated=c,s.codecHeaders={...i},s.transportHeaders={...r},this._invokeOnStreamUpdate(s),[]}_decodeFirstContact(e,t,n,r){if(!t)return this._hooks.decodeDiscrete(e);let i=e.transportHeaders?.[`stream-id`]??``,a=e.codecHeaders??{},o=typeof e.data==`string`?e.data:``;this._logger?.debug(`DefaultDecoderCore._decodeFirstContact(); first-contact stream`,{name:e.name,streamId:i,serial:r});let s={name:e.name,streamId:i,accumulated:o,codecHeaders:{...a},transportHeaders:{...e.transportHeaders},closed:n===`complete`||n===`cancelled`};this._serialState.set(r,s);let c=this._hooks.buildStartEvents(s);return o.length>0&&c.push(...this._hooks.buildDeltaEvents(s,o)),n===`complete`&&c.push(...this._hooks.buildEndEvents(s,a)),c}_decodeDelete(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);return this._invokeOnStreamDelete(t,n),n&&(n.accumulated=``,n.closed=!0),this._logger?.debug(`DefaultDecoderCore._decodeDelete();`,{serial:t}),[]}},ne=(e,t={})=>new U(e,t),re=class{constructor(e){this._emitted=new Map,this._phases=e}ensurePhases(e,t){let n=this._getOrCreate(e),r=[];for(let e of this._phases)n.has(e.key)||(n.add(e.key),r.push(...e.build(t)));return r}markEmitted(e,t){this._getOrCreate(e).add(t)}resetPhase(e,t){this._emitted.get(e)?.delete(t)}clearScope(e){this._emitted.delete(e)}_getOrCreate(e){let t=this._emitted.get(e);return t||(t=new Set,this._emitted.set(e,t)),t}},ie=e=>new re(e),W=e=>{let t=V(e);return{...t,providerMetadata:()=>t.json(`providerMetadata`)}},ae=(e,t)=>e===`stop`||e===`length`||e===`content-filter`||e===`tool-calls`||e===`error`||e===`other`?e:t,oe=e=>e.startsWith(`data-`),se=e=>{if(e)try{return JSON.parse(e)}catch{return e}},ce=e=>W(e.codecHeaders).strOr(`type`,``),le=e=>{let t=W(e.codecHeaders);switch(ce(e)){case`text`:return B({type:`text-start`,id:e.streamId,providerMetadata:t.providerMetadata()});case`reasoning`:return B({type:`reasoning-start`,id:e.streamId,providerMetadata:t.providerMetadata()});case`tool-input`:return B({type:`tool-input-start`,toolCallId:e.streamId,toolName:t.strOr(`toolName`,``),dynamic:t.bool(`dynamic`),title:t.str(`title`),providerExecuted:t.bool(`providerExecuted`),providerMetadata:t.providerMetadata()});default:return{type:`text-start`,id:e.streamId}}},ue=(e,t)=>{switch(ce(e)){case`text`:return{type:`text-delta`,id:e.streamId,delta:t};case`reasoning`:return{type:`reasoning-delta`,id:e.streamId,delta:t};case`tool-input`:return{type:`tool-input-delta`,toolCallId:e.streamId,inputTextDelta:t};default:return{type:`text-delta`,id:e.streamId,delta:t}}},de=(e,t)=>{let n=W(t);switch(ce(e)){case`text`:return B({type:`text-end`,id:e.streamId,providerMetadata:n.providerMetadata()});case`reasoning`:return B({type:`reasoning-end`,id:e.streamId,providerMetadata:n.providerMetadata()});case`tool-input`:return B({type:`tool-input-available`,toolCallId:e.streamId,toolName:n.strOr(`toolName`,W(e.codecHeaders).strOr(`toolName`,``)),input:se(e.accumulated),providerMetadata:n.providerMetadata()});default:return{type:`text-end`,id:e.streamId}}},fe=()=>ie([{key:`start`,build:e=>[B({type:`start`,messageId:e.messageId})]},{key:`start-step`,build:()=>[{type:`start-step`}]}]),pe=(e,t,n)=>(n.markEmitted(t,`start`),[B({type:`start`,messageId:e.str(`messageId`),messageMetadata:e.json(`messageMetadata`)})]),me=(e,t)=>(t.markEmitted(e,`start-step`),[{type:`start-step`}]),he=(e,t)=>(t.resetPhase(e,`start-step`),[{type:`finish-step`}]),ge=(e,t,n)=>(n.clearScope(t),[B({type:`finish`,finishReason:ae(e.str(`finishReason`),`stop`),messageMetadata:e.json(`messageMetadata`)})]),_e=(e,t,n)=>(n.clearScope(t),[{type:`error`,errorText:typeof e==`string`?e:``}]),ve=(e,t,n)=>(n.clearScope(t),[B({type:`abort`,reason:typeof e==`string`&&e?e:void 0})]),ye=e=>[{type:`message-metadata`,messageMetadata:e.json(`messageMetadata`)}],be=(e,t)=>[B({type:`file`,url:typeof t==`string`?t:``,mediaType:e.strOr(`mediaType`,``),providerMetadata:e.providerMetadata()})],xe=(e,t)=>[B({type:`source-url`,sourceId:e.strOr(`sourceId`,``),url:typeof t==`string`?t:``,title:e.str(`title`),providerMetadata:e.providerMetadata()})],Se=e=>[B({type:`source-document`,sourceId:e.strOr(`sourceId`,``),mediaType:e.strOr(`mediaType`,``),title:e.strOr(`title`,``),filename:e.str(`filename`),providerMetadata:e.providerMetadata()})],Ce=(e,t)=>{let n=t;return[B({type:`tool-input-error`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),errorText:n?.errorText??``,input:n?.input,dynamic:e.bool(`dynamic`),title:e.str(`title`),providerExecuted:e.bool(`providerExecuted`),providerMetadata:e.providerMetadata()})]},we=(e,t)=>{let n=t;return[B({type:`tool-output-available`,toolCallId:e.strOr(`toolCallId`,``),output:n?.output,dynamic:e.bool(`dynamic`),providerExecuted:e.bool(`providerExecuted`),preliminary:e.bool(`preliminary`)})]},Te=(e,t)=>{let n=t;return[B({type:`tool-output-error`,toolCallId:e.strOr(`toolCallId`,``),errorText:n?.errorText??``,dynamic:e.bool(`dynamic`),providerExecuted:e.bool(`providerExecuted`)})]},Ee=e=>[{type:`tool-approval-request`,toolCallId:e.strOr(`toolCallId`,``),approvalId:e.strOr(`approvalId`,``)}],De=e=>[{type:`tool-output-denied`,toolCallId:e.strOr(`toolCallId`,``)}],Oe=(e,t,n)=>[B({type:e,data:n,id:t.str(`id`),transient:t.bool(`transient`)})],ke=(e,t,n,r)=>[...r.ensurePhases(n,{messageId:e.str(`messageId`)}),B({type:`tool-input-start`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),dynamic:e.bool(`dynamic`),title:e.str(`title`),providerExecuted:e.bool(`providerExecuted`),providerMetadata:e.providerMetadata()}),B({type:`tool-input-available`,toolCallId:e.strOr(`toolCallId`,``),toolName:e.strOr(`toolName`,``),input:t,providerMetadata:e.providerMetadata()})],Ae=e=>{let t=W(e.codecHeaders??{}),n=e.transportHeaders?.role??`user`,r=t.str(`messageId`)??``,i=t.strOr(`type`,``),a;switch(i){case`text`:a={type:`text`,text:typeof e.data==`string`?e.data:``};break;case`file`:a={type:`file`,mediaType:t.strOr(`mediaType`,``),url:typeof e.data==`string`?e.data:``};break;default:oe(i)&&(a=B({type:i,id:t.str(`id`),data:e.data}));break}return a?[{kind:`user-message`,message:{id:r,role:n,parts:[a]}}]:[]},je=(e,t)=>(e===`text`||e===`file`||oe(e))&&`discrete`in t,Me=(e,t,n)=>{let r=n;return[{kind:`tool-result`,codecMessageId:e,payload:{toolCallId:t.strOr(`toolCallId`,``),output:r?.output}}]},Ne=(e,t,n)=>{let r=n;return[{kind:`tool-result-error`,codecMessageId:e,payload:{toolCallId:t.strOr(`toolCallId`,``),message:r?.message??``}}]},Pe=(e,t)=>[{kind:`tool-approval-response`,codecMessageId:e,payload:B({toolCallId:t.strOr(`toolCallId`,``),approved:t.bool(`approved`)??!1,reason:t.str(`reason`)})}],Fe=(e,t,n,r,i)=>{switch(e){case`start`:return pe(t,r,i);case`start-step`:return me(r,i);case`finish-step`:return he(r,i);case`finish`:return ge(t,r,i);case`error`:return _e(n,r,i);case`abort`:return ve(n,r,i);case`message-metadata`:return ye(t);case`file`:return be(t,n);case`source-url`:return xe(t,n);case`source-document`:return Se(t);case`tool-input`:return ke(t,n,r,i);case`tool-input-error`:return Ce(t,n);case`tool-output-available`:return we(t,n);case`tool-output-error`:return Te(t,n);case`tool-approval-request`:return Ee(t);case`tool-output-denied`:return De(t);default:return oe(e)?Oe(e,t,n):[]}},Ie=(e,t,n)=>{if(je(e,t.transportHeaders??{}))return Ae(t);let r=t.transportHeaders?.[`codec-message-id`]??``;switch(e){case`tool-result`:return Me(r,n,t.data);case`tool-result-error`:return Ne(r,n,t.data);case`tool-approval-response`:return Pe(r,n);case`regenerate`:return[];default:return[]}},Le=(e,t)=>{let n=W(e.codecHeaders??{}),r=e.transportHeaders?.[`run-id`]??``,i=n.strOr(`type`,``);return e.name===`ai-input`?Ie(i,e,n):e.name===`ai-output`?Fe(i,n,e.data,r,t):[]},Re=e=>({buildStartEvents:t=>{let n=t.transportHeaders[`run-id`]??``,r=W(t.codecHeaders).str(`messageId`);return[...e.ensurePhases(n,{messageId:r}),le(t)]},buildDeltaEvents:(e,t)=>[ue(e,t)],buildEndEvents:(e,t)=>[de(e,t)],decodeDiscrete:t=>Le(t,e)}),ze=e=>`kind`in e,Be=class{constructor(e={}){this._core=ne(Re(fe()),e)}decode(e){let t=this._core.decode(e),n=[],r=[];for(let e of t)ze(e)?n.push(e):r.push(e);return{inputs:n,outputs:r}}},Ve=(e={})=>new Be(e),G=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e}({}),He=(e,t)=>e.code===t,Ue=class{constructor(e,t={}){this._trackers=new Map,this._pending=[],this._closed=!1,this._writer=e,this._defaultClientId=t.clientId,this._defaultExtras=t.extras,this._onMessageHook=t.onMessage??(()=>{}),this._logger=t.logger?.withContext({component:`EncoderCore`})}async publishDiscrete(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscrete();`,{name:e.name});let n=this._buildDiscreteMessage(e,t);return this._writer.publish(n)}async publishDiscreteBatch(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscreteBatch();`,{count:e.length});let n=e.map(e=>this._buildDiscreteMessage(e,t,!0));return this._writer.publish(n)}async startStream(e,n,r){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.startStream();`,{name:n.name,streamId:e});let i=this._buildTransport(n.transportHeaders,r);i[u]=`true`,i[d]=`streaming`,i[f]=e;let a=n.codecHeaders??{},o=this._resolveClientId(r),s={name:n.name,data:n.data,extras:{ai:this._aiExtras(i,a)},...o?{clientId:o}:{}};this._invokeOnMessage(s);let c=(await this._writer.publish(s)).serials[0];if(!c)throw new t.ErrorInfo(`unable to start stream; no serial returned for stream '${n.name}' (streamId: ${e})`,G.BadRequest,400);this._trackers.set(e,{serial:c,name:n.name,streamId:e,accumulated:n.data,persistentTransport:i,persistentCodec:a,cancelled:!1}),this._logger?.debug(`DefaultEncoderCore.startStream(); stream started`,{name:n.name,streamId:e,serial:c})}appendStream(e,n){this._assertNotClosed();let r=this._trackers.get(e);if(!r)throw new t.ErrorInfo(`unable to append to stream; no active stream for streamId '${e}'`,G.InvalidArgument,400);r.accumulated+=n;let i={serial:r.serial,data:n,extras:{ai:this._aiExtras({...r.persistentTransport},{...r.persistentCodec})}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:e})}async closeStream(e,n){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.closeStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new t.ErrorInfo(`unable to close stream; no active stream for streamId '${e}'`,G.InvalidArgument,400);r.accumulated+=n.data;let{transport:i,codec:a}=this._buildClosing(r,n);i[d]=`complete`;let o={serial:r.serial,data:n.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.closeStream(); stream closed`,{streamId:e})}async cancelStream(e,n){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new t.ErrorInfo(`unable to cancel stream; no active stream for streamId '${e}'`,G.InvalidArgument,400);r.cancelled=!0;let{transport:i,codec:a}=this._buildClosing(r,void 0,n);i[d]=`cancelled`;let o={serial:r.serial,data:``,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.cancelStream(); stream cancelled`,{streamId:e})}async cancelAllStreams(e){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelAllStreams();`,{streamCount:this._trackers.size});for(let t of this._trackers.values()){t.cancelled=!0;let{transport:n,codec:r}=this._buildClosing(t,void 0,e);n[d]=`cancelled`;let i={serial:t.serial,data:``,extras:{ai:this._aiExtras(n,r)}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:t.streamId})}await this._flushPending()}async _flushPending(){if(this._flushPromise)return this._flushPromise;let e=this._pending;if(this._pending=[],e.length!==0){this._logger?.trace(`DefaultEncoderCore._flushPending();`,{count:e.length}),this._flushPromise=this._doFlush(e);try{await this._flushPromise}finally{this._flushPromise=void 0}}}async _doFlush(e){let n=await Promise.allSettled(e.map(async e=>e.promise)),r=new Set;for(let[t,i]of n.entries()){let n=e[t];n&&i.status===`rejected`&&r.add(n.streamId)}if(r.size===0){this._logger?.debug(`DefaultEncoderCore._flushPending(); all appends succeeded`);return}this._logger?.warn(`DefaultEncoderCore._flushPending(); recovering failed appends`,{failedStreams:[...r]});let i=[];for(let e of r){let t=this._trackers.get(e);if(!t)continue;let n=t.cancelled?`cancelled`:`complete`,r={serial:t.serial,data:t.accumulated,extras:{ai:this._aiExtras({...t.persistentTransport,[d]:n},{...t.persistentCodec})}};try{await this._writer.updateMessage(r)}catch(t){i.push({streamId:e,error:t})}}if(i.length>0){let e=i.map(e=>e.streamId).join(`, `);throw this._logger?.error(`DefaultEncoderCore._flushPending(); recovery failed`,{failedStreams:e}),new t.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${e}`,G.EncoderRecoveryFailed,500)}}async close(){if(!this._closed){this._logger?.trace(`DefaultEncoderCore.close();`),this._closed=!0;try{await this._flushPending()}finally{this._trackers.clear()}this._logger?.debug(`DefaultEncoderCore.close(); encoder closed`)}}_invokeOnMessage(e){try{this._onMessageHook(e)}catch(e){this._logger?.error(`DefaultEncoderCore._invokeOnMessage(); hook threw`,{error:e})}}_assertNotClosed(){if(this._closed)throw new t.ErrorInfo(`unable to write to encoder; encoder has been closed`,G.InvalidArgument,400)}_resolveClientId(e){return e?.clientId??this._defaultClientId}_buildTransport(e,t){let n={...I(this._defaultExtras?.headers,t?.extras?.headers),...e};return t?.messageId!==void 0&&(n[_]=t.messageId),n}_aiExtras(e,t){return Object.keys(t).length>0?{transport:e,codec:t}:{transport:e}}_buildDiscreteMessage(e,t,n=!1){let r=this._buildTransport(e.transportHeaders,t);r[u]=`false`,n&&(r[p]=`true`);let i=this._resolveClientId(t),a={name:e.name,data:e.data,extras:{ai:this._aiExtras(r,e.codecHeaders??{}),...e.ephemeral?{ephemeral:!0}:{}},...i?{clientId:i}:{}};return this._invokeOnMessage(a),a}_buildClosing(e,t,n){let r=I(this._defaultExtras?.headers,n?.extras?.headers);return{transport:{...e.persistentTransport,...r,...t?.transportHeaders},codec:{...e.persistentCodec,...t?.codecHeaders}}}},We=(e,t={})=>new Ue(e,t),Ge=class{constructor(e,t={}){this._cancelled=!1,this._core=We(e,t),this._messageId=t.messageId}async publishInput(e,t){switch(e.kind){case`user-message`:await this._publishUserMessage(e,t);return;case`regenerate`:await this._publishRegenerate(t);return;case`tool-result`:await this._publishToolResult(e,t);return;case`tool-result-error`:await this._publishToolResultError(e,t);return;case`tool-approval-response`:await this._publishToolApprovalResponse(e,t);return}}async publishOutput(e,t){await this._publishChunk(e,t)}async cancel(e){this._cancelled||(this._cancelled=!0,await this._core.cancelAllStreams(),await this._core.publishDiscrete({name:A,data:e??``,codecHeaders:H().str(`type`,`abort`).build(),transportHeaders:{[d]:`cancelled`}}))}async close(){await this._core.close()}async _publishChunk(e,n){switch(e.type){case`text-start`:{let t=H().str(`type`,`text`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.id,{name:A,data:``,codecHeaders:t},n);return}case`reasoning-start`:{let t=H().str(`type`,`reasoning`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.id,{name:A,data:``,codecHeaders:t},n);return}case`tool-input-start`:{let t=H().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.startStream(e.toolCallId,{name:A,data:``,codecHeaders:t},n);return}case`text-delta`:this._core.appendStream(e.id,e.delta);return;case`reasoning-delta`:this._core.appendStream(e.id,e.delta);return;case`tool-input-delta`:this._core.appendStream(e.toolCallId,e.inputTextDelta);return;case`text-end`:{let t=H().str(`type`,`text`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.id,{name:A,data:``,codecHeaders:t});return}case`reasoning-end`:{let t=H().str(`type`,`reasoning`).str(`id`,e.id).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.id,{name:A,data:``,codecHeaders:t});return}case`tool-input-available`:try{let t=H().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).json(`providerMetadata`,e.providerMetadata).build();await this._core.closeStream(e.toolCallId,{name:A,data:``,codecHeaders:t})}catch(n){if(!(n instanceof t.ErrorInfo&&He(n,G.InvalidArgument)))throw n;let r=H().str(`type`,`tool-input`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:A,data:e.input,codecHeaders:r})}return;case`start`:{let t=H().str(`type`,`start`).str(`messageId`,e.messageId??this._messageId).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:t},n);return}case`start-step`:{let e=H().str(`type`,`start-step`).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:e},n);return}case`finish-step`:{let e=H().str(`type`,`finish-step`).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:e},n);return}case`finish`:{let t=H().str(`type`,`finish`).str(`finishReason`,e.finishReason).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:t},n);return}case`error`:{let t=H().str(`type`,`error`).build();await this._core.publishDiscrete({name:A,data:e.errorText,codecHeaders:t},n);return}case`abort`:this._cancelled=!0,await this._core.cancelAllStreams(n),await this._core.publishDiscrete({name:A,data:e.reason??``,codecHeaders:H().str(`type`,`abort`).build(),transportHeaders:{[d]:`cancelled`}},n);return;case`message-metadata`:{let t=H().str(`type`,`message-metadata`).json(`messageMetadata`,e.messageMetadata).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:t},n);return}case`tool-input-error`:{let t=H().str(`type`,`tool-input-error`).str(`toolCallId`,e.toolCallId).str(`toolName`,e.toolName).bool(`dynamic`,e.dynamic).str(`title`,e.title).bool(`providerExecuted`,e.providerExecuted).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:A,data:{errorText:e.errorText,input:e.input},codecHeaders:t},n);return}case`tool-output-available`:case`tool-output-error`:case`tool-approval-request`:case`tool-output-denied`:await this._core.publishDiscrete(Ke(e),n);return;case`file`:{let t=H().str(`type`,`file`).str(`mediaType`,e.mediaType).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:A,data:e.url,codecHeaders:t},n);return}case`source-url`:{let t=H().str(`type`,`source-url`).str(`sourceId`,e.sourceId).str(`title`,e.title).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:A,data:e.url,codecHeaders:t},n);return}case`source-document`:{let t=H().str(`type`,`source-document`).str(`sourceId`,e.sourceId).str(`mediaType`,e.mediaType).str(`title`,e.title).str(`filename`,e.filename).json(`providerMetadata`,e.providerMetadata).build();await this._core.publishDiscrete({name:A,data:``,codecHeaders:t},n);return}default:if(e.type.startsWith(`data-`)){let t=e,r=H().str(`type`,t.type).str(`id`,t.id).bool(`transient`,t.transient).build(),i=t.transient===!0;await this._core.publishDiscrete({name:A,data:t.data,codecHeaders:r,ephemeral:i},n);return}throw new t.ErrorInfo(`unable to publish output; unsupported chunk type '${e.type}'`,G.InvalidArgument,400)}}async _publishUserMessage(e,t){let n=qe(e.message);for(let e of n)e.transportHeaders={...e.transportHeaders,[b]:`user`};await this._core.publishDiscreteBatch(n,t)}async _publishRegenerate(e){let t=H().str(`type`,`regenerate`).build();await this._core.publishDiscrete({name:j,data:``,codecHeaders:t},e)}async _publishToolResult(e,t){let n=H().str(`type`,`tool-result`).str(`toolCallId`,e.payload.toolCallId).build();await this._core.publishDiscrete({name:j,data:{output:e.payload.output},codecHeaders:n},t)}async _publishToolResultError(e,t){let n=H().str(`type`,`tool-result-error`).str(`toolCallId`,e.payload.toolCallId).build();await this._core.publishDiscrete({name:j,data:{message:e.payload.message},codecHeaders:n},t)}async _publishToolApprovalResponse(e,t){let n=H().str(`type`,`tool-approval-response`).str(`toolCallId`,e.payload.toolCallId).bool(`approved`,e.payload.approved).str(`reason`,e.payload.reason).build();await this._core.publishDiscrete({name:j,data:``,codecHeaders:n},t)}},Ke=e=>{switch(e.type){case`tool-output-available`:{let t=H().str(`type`,`tool-output-available`).str(`toolCallId`,e.toolCallId).bool(`dynamic`,e.dynamic).bool(`providerExecuted`,e.providerExecuted).bool(`preliminary`,e.preliminary).build();return{name:A,data:{output:e.output},codecHeaders:t}}case`tool-output-error`:{let t=H().str(`type`,`tool-output-error`).str(`toolCallId`,e.toolCallId).bool(`dynamic`,e.dynamic).bool(`providerExecuted`,e.providerExecuted).build();return{name:A,data:{errorText:e.errorText},codecHeaders:t}}case`tool-approval-request`:return{name:A,data:``,codecHeaders:H().str(`type`,`tool-approval-request`).str(`toolCallId`,e.toolCallId).str(`approvalId`,e.approvalId).build()};case`tool-output-denied`:return{name:A,data:``,codecHeaders:H().str(`type`,`tool-output-denied`).str(`toolCallId`,e.toolCallId).build()}}},qe=e=>{let t=e.id,r=[];for(let i of e.parts)switch(i.type){case`text`:r.push({name:j,data:i.text,codecHeaders:H().str(`type`,`text`).str(`messageId`,t).build()});break;case`file`:r.push({name:j,data:i.url,codecHeaders:H().str(`type`,`file`).str(`messageId`,t).str(`mediaType`,i.mediaType).build()});break;default:(0,n.isDataUIPart)(i)&&r.push({name:j,data:i.data,codecHeaders:H().str(`type`,i.type).str(`messageId`,t).str(`id`,i.id).build()});break}return r.length===0&&r.push({name:j,data:``,codecHeaders:H().str(`type`,`text`).str(`messageId`,t).build()}),r},Je=(e,t={})=>new Ge(e,t),K=e=>B({type:`dynamic-tool`,toolCallId:e.toolCallId,toolName:e.toolName,title:e.title,providerExecuted:e.providerExecuted}),q=(e,t)=>{let n=K(e);switch(t.type){case`tool-output-available`:return B({...n,state:`output-available`,input:e.input,output:t.output,preliminary:t.preliminary});case`tool-output-error`:return{...n,state:`output-error`,input:e.input,errorText:t.errorText};case`tool-output-denied`:return{...n,state:`output-denied`,input:e.input,approval:{id:``,approved:!1}};case`tool-approval-request`:return{...n,state:`approval-requested`,input:e.input,approval:{id:t.approvalId}}}},Ye=()=>({messages:[],conflictSerials:new Map,trackers:new Map,pendingToolResolutions:[]}),Xe=(e,t,n)=>{if(n.serial){let r=Qe(t,n);if(r!==void 0){let t=e.conflictSerials.get(r);if(t!==void 0&&n.serial<=t)return e;e.conflictSerials.set(r,n.serial)}}if(Ze(t))switch(t.kind){case`user-message`:$e(e,t.message,n);break;case`regenerate`:break;case`tool-result`:et(e,t,n);break;case`tool-result-error`:tt(e,t,n);break;case`tool-approval-response`:nt(e,t,n);break}else ot(e,t,n);return e.pendingToolResolutions.length>0&&at(e),e},Ze=e=>`kind`in e,Qe=(e,t)=>{if(Ze(e))switch(e.kind){case`user-message`:return t.messageId===void 0?void 0:`user-msg:${t.messageId}`;case`tool-approval-response`:return`tool-approval:${e.payload.toolCallId}`;case`tool-result`:case`tool-result-error`:return`tool-output:${e.payload.toolCallId}`;case`regenerate`:return}switch(e.type){case`tool-input-start`:case`tool-input-available`:case`tool-input-error`:return`${e.type}:${e.toolCallId}`;case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return`tool-output:${e.toolCallId}`;case`text-start`:case`text-end`:case`reasoning-start`:case`reasoning-end`:return`${e.type}:${t.messageId??``}:${e.id}`;case`finish`:case`message-metadata`:return`${e.type}:${t.messageId??``}`;default:return}},$e=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e.messages.push({codecMessageId:t.id,message:t}),e;let i=e.messages.findIndex(e=>e.codecMessageId===r);return i===-1?e.messages.push({codecMessageId:r,message:t}):e.messages[i]={codecMessageId:r,message:t},e},et=(e,t,n)=>{let{toolCallId:r,output:i}=t.payload,a=J(e,t.codecMessageId,r);return a?(a.message.parts[a.tracker.partIndex]=q(a.part,{type:`tool-output-available`,toolCallId:r,output:i}),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-result`,output:i}}),e)},tt=(e,t,n)=>{let{toolCallId:r,message:i}=t.payload,a=J(e,t.codecMessageId,r);return a?(a.message.parts[a.tracker.partIndex]=q(a.part,{type:`tool-output-error`,toolCallId:r,errorText:i}),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-result-error`,message:i}}),e)},nt=(e,t,n)=>{let{toolCallId:r,approved:i,reason:a}=t.payload,o=J(e,t.codecMessageId,r);return o?(o.message.parts[o.tracker.partIndex]=it(o.part,i,a),e):(e.pendingToolResolutions.push({targetCodecMessageId:t.codecMessageId,toolCallId:r,serial:n.serial,resolution:{kind:`tool-approval-response`,approved:i,...a===void 0?{}:{reason:a}}}),e)},J=(e,t,n)=>{let r=e.messages.find(e=>e.codecMessageId===t);if(!r)return;let i=X(e,t),a=Z(r.message,i,n);if(a)return{message:r.message,tracker:a.tracker,part:a.part}},rt=(e,t)=>{for(let n of e.messages){let r=e.trackers.get(n.codecMessageId);if(!r)continue;let i=Z(n.message,r,t);if(i)return{message:n.message,tracker:i.tracker,part:i.part}}},it=(e,t,n)=>t?{...K(e),state:`approval-responded`,input:`input`in e?e.input:void 0,approval:{id:`approval`in e&&e.approval?e.approval.id:``,approved:!0,...n===void 0?{}:{reason:n}}}:q(e,{type:`tool-output-denied`,toolCallId:e.toolCallId,...n===void 0?{}:{reason:n}}),at=e=>{let t=[];for(let n of e.pendingToolResolutions){let r=J(e,n.targetCodecMessageId,n.toolCallId);if(!r){t.push(n);continue}switch(n.resolution.kind){case`tool-result`:r.message.parts[r.tracker.partIndex]=q(r.part,{type:`tool-output-available`,toolCallId:n.toolCallId,output:n.resolution.output});break;case`tool-result-error`:r.message.parts[r.tracker.partIndex]=q(r.part,{type:`tool-output-error`,toolCallId:n.toolCallId,errorText:n.resolution.message});break;case`tool-approval-response`:r.message.parts[r.tracker.partIndex]=it(r.part,n.resolution.approved,n.resolution.reason);break}}e.pendingToolResolutions=t},ot=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e;switch(t.type){case`start`:case`start-step`:case`finish-step`:case`finish`:case`abort`:case`error`:case`message-metadata`:return st(e,t,r);case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:return ct(e,t,r);case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:return lt(e,t,r);case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return ut(e,t,r);case`file`:case`source-url`:case`source-document`:return dt(e,t,r);default:return t.type.startsWith(`data-`)?ft(e,t,r):e}},Y=(e,t)=>{let n=e.messages.find(e=>e.codecMessageId===t);return n||(n={codecMessageId:t,message:{id:t,role:`assistant`,parts:[]}},e.messages.push(n)),n.message},X=(e,t)=>{let n=e.trackers.get(t);return n||(n={text:new Map,reasoning:new Map,tools:new Map},e.trackers.set(t,n)),n},Z=(e,t,n)=>{let r=t.tools.get(n);if(!r)return;let i=e.parts[r.partIndex];if(i?.type===`dynamic-tool`)return{tracker:r,part:i}},st=(e,t,n)=>{switch(t.type){case`start`:{let r=Y(e,n);return t.messageId!==void 0&&(r.id=t.messageId),t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`start-step`:return Y(e,n).parts.push({type:`step-start`}),e;case`finish-step`:{let t=e.trackers.get(n);return t&&(t.text.clear(),t.reasoning.clear()),e}case`finish`:{let r=e.messages.find(e=>e.codecMessageId===n)?.message;return r&&t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`abort`:case`error`:return e;case`message-metadata`:{let r=e.messages.find(e=>e.codecMessageId===n)?.message;return r&&t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}}},ct=(e,t,n)=>{let r=Y(e,n),i=X(e,n),a=t.type.startsWith(`text-`),o=a?`text`:`reasoning`,s=a?i.text:i.reasoning;switch(t.type){case`text-start`:case`reasoning-start`:return s.set(t.id,r.parts.length),r.parts.push({type:o,text:``}),e;case`text-delta`:case`reasoning-delta`:{let n=s.get(t.id);if(n===void 0)return e;let i=r.parts[n];return i?.type===o&&(i.text+=t.delta),e}case`text-end`:case`reasoning-end`:return s.delete(t.id),e}},lt=(e,t,n)=>{let r=Y(e,n),i=X(e,n);switch(t.type){case`tool-input-start`:{let n=r.parts.length;return r.parts.push({...K(t),state:`input-streaming`,input:void 0}),i.tools.set(t.toolCallId,{partIndex:n,inputText:``}),e}case`tool-input-delta`:{let n=i.tools.get(t.toolCallId);if(!n)return e;n.inputText+=t.inputTextDelta;let a;try{a=JSON.parse(n.inputText)}catch{a=void 0}let o=Z(r,i,t.toolCallId);return o&&(r.parts[o.tracker.partIndex]={...K(o.part),state:`input-streaming`,input:a}),e}case`tool-input-available`:{let n=Z(r,i,t.toolCallId);return n&&(r.parts[n.tracker.partIndex]={...K(n.part),state:`input-available`,input:t.input}),e}case`tool-input-error`:{let n=Z(r,i,t.toolCallId);if(n)r.parts[n.tracker.partIndex]={...K(n.part),state:`output-error`,input:t.input,errorText:t.errorText};else{let e=r.parts.length;r.parts.push({...K(t),state:`output-error`,input:t.input,errorText:t.errorText}),i.tools.set(t.toolCallId,{partIndex:e,inputText:``})}return e}}},ut=(e,t,n)=>{if(t.type===`tool-output-available`||t.type===`tool-output-error`){let n=rt(e,t.toolCallId);return n&&(n.message.parts[n.tracker.partIndex]=q(n.part,t)),e}let r=Y(e,n),i=Z(r,X(e,n),t.toolCallId);return i&&(r.parts[i.tracker.partIndex]=q(i.part,t)),e},dt=(e,t,n)=>{let r=Y(e,n);switch(t.type){case`file`:return r.parts.push({type:`file`,mediaType:t.mediaType,url:t.url}),e;case`source-url`:return r.parts.push(B({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title})),e;case`source-document`:return r.parts.push(B({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename})),e}},ft=(e,t,n)=>{if(t.transient)return e;let r=Y(e,n),i=B({type:t.type,id:t.id,data:t.data});if(t.id!==void 0){let n=r.parts.findIndex(e=>e.type===t.type&&`id`in e&&e.id===t.id);if(n!==-1)return r.parts[n]=i,e}return r.parts.push(i),e},Q={adapterTag:`vercel-ai-sdk-ui-message`,init:Ye,fold:Xe,createEncoder:Je,createDecoder:Ve,getMessages:e=>e.messages,createUserMessage:e=>({kind:`user-message`,message:e}),createRegenerate:(e,t)=>({kind:`regenerate`,target:e,parent:t}),createToolResult:(e,t)=>({kind:`tool-result`,codecMessageId:e,payload:t}),createToolResultError:(e,t)=>({kind:`tool-result-error`,codecMessageId:e,payload:t}),createToolApprovalResponse:(e,t)=>({kind:`tool-approval-response`,codecMessageId:e,payload:t})},pt=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),mt=t.Realtime.EventEmitter,ht=class extends mt{constructor(e){super(pt(e))}},gt=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),_t=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},vt=e=>new bt(e.logHandler??_t,e.logLevel),yt=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),bt=class e{constructor(e,n,r){this._handler=e,this._context=r;let i=yt.get(n);if(i===void 0)throw new t.ErrorInfo(`unable to create logger; invalid log level: ${n}`,G.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...yt.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},xt=e=>e.type===`finish`||e.type===`error`||e.type===`abort`,St=(e,n,r)=>{let i={},a=[],o=new ReadableStream({start:e=>{i.controller=e},cancel:()=>{u()}}),{controller:s}=i;if(!s)throw new t.ErrorInfo(`unable to create run stream; ReadableStream start() was not called synchronously`,G.SessionSubscriptionError,500);let c;n.then(e=>{c=e},()=>{});let l=!1,u=()=>{for(let e of a)e();a.length=0},d=e=>{if(!l){l=!0;try{e()}catch{}u()}},f=()=>{d(()=>{s.close()})},p=e=>{d(()=>{s.error(e)})};return a.push(e.tree.on(`output`,e=>{if(e.inputCodecMessageId===r)for(let t of e.events){try{s.enqueue(t)}catch{f();return}if(xt(t)){f();return}}}),e.tree.on(`run`,e=>{e.type===`end`&&c!==void 0&&e.runId===c&&f()}),e.on(`error`,e=>{p(e)})),{stream:o,close:f,error:p}},Ct=e=>{let t,n=new Promise(e=>{t=e}),r=new TransformStream({flush:()=>{t()}}),i=new AbortController;return e.pipeTo(r.writable,{signal:i.signal,preventCancel:!0}).catch(()=>{t()}),{stream:r.readable,done:n,fail:e=>{i.abort(e)}}},wt=e=>(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`toolCallId`in e&&`state`in e,Tt=e=>e.role===`assistant`&&e.parts.some(e=>wt(e)&&(e.state===`input-streaming`||e.state===`input-available`||e.state===`approval-requested`)),Et=new Set([`input-streaming`,`input-available`,`approval-requested`]),Dt=(e,t)=>{let n=[];for(let r of t){if(r.role!==`assistant`)continue;let t=e.find(e=>e.message.id===r.id);if(!t)continue;let{codecMessageId:i,message:a}=t;for(let e of r.parts){if(!wt(e))continue;let t=a.parts.find(t=>wt(t)&&t.toolCallId===e.toolCallId);if(e.state===`approval-responded`&&(!t||t.state===`approval-requested`)){n.push(Q.createToolApprovalResponse(i,{toolCallId:e.toolCallId,approved:e.approval.approved,...e.approval.reason===void 0?{}:{reason:e.approval.reason}}));continue}e.state!==`output-available`&&e.state!==`output-error`||t&&!Et.has(t.state)||(e.state===`output-available`?n.push(Q.createToolResult(i,{toolCallId:e.toolCallId,output:e.output})):n.push(Q.createToolResultError(i,{toolCallId:e.toolCallId,message:e.errorText})))}}return n},Ot=(e,t)=>{let n=e.findIndex(e=>e.message.id===t);if(!(n<=0))return e[n-1]?.codecMessageId},kt=(e,n)=>{let r=n?.api??`/api/chat`,i=n?.fetch??globalThis.fetch.bind(globalThis),a=n?.credentials,o=!1,s=new ht(vt({logLevel:gt.Silent})),c=e=>{o=e,s.emit(`streaming`,e)};return{sendMessages:async o=>{let{messages:s,abortSignal:l,trigger:u,messageId:d}=o,f=e.view.getMessages(),p=new Map(f.map(e=>[e.message.id,e.codecMessageId])),m=e=>p.get(e),h=s.at(-1),g=!!h&&p.has(h.id),_=u===`submit-message`&&h?.role===`assistant`&&g,v=u===`submit-message`&&!d&&h?.role===`user`?s.at(-2):void 0,y=v&&Tt(v)&&p.has(v.id)?v.id:void 0,b,x;if(u===`regenerate-message`||_)b=[],x=s;else{if(s.length===0)throw new t.ErrorInfo(`unable to send messages; messages array is empty for submit-message trigger`,G.InvalidArgument,400);b=[s.at(-1)],x=y?s.slice(0,-2):s.slice(0,-1)}let S,C;u===`submit-message`&&d&&!_?(S=m(d),C=Ot(f,d)):y&&(S=m(y),C=Ot(f,y));let w,T;if(n?.prepareSendMessagesRequest){let e=n.prepareSendMessagesRequest({chatId:o.chatId,trigger:u,messageId:d,history:x,messages:b,forkOf:S,parent:C});w=e.body??{},T=e.headers}else w={},T=void 0;let E={};if(S!==void 0&&(E.forkOf=S),C!==void 0&&(E.parent=C),_){let t=m(h.id),n=t===void 0?void 0:e.view.runOf(t);n&&(E.runId=n.runId)}let D;if(_){let t=Dt(f,s);D=await e.view.send(t,E)}else if(u===`regenerate-message`){if(d===void 0)throw new t.ErrorInfo(`unable to regenerate; regenerate-message trigger fired without messageId`,G.InvalidArgument,400);let n=m(d);if(n===void 0)throw new t.ErrorInfo(`unable to regenerate; message not visible: ${d}`,G.InvalidArgument,400);D=await e.view.regenerate(n,E)}else{let t=b.map(e=>Q.createUserMessage(e));D=await e.view.send(t,E)}let O=St(e,D.runId,D.inputCodecMessageId);if(l){let e=()=>{D.cancel(),O.close()};l.aborted?e():l.addEventListener(`abort`,e,{once:!0})}let{stream:ee,done:te,fail:k}=Ct(O.stream);c(!0),te.then(()=>{c(!1)});let A={...w,...D.toInvocation().toJSON()};return i(r,{method:`POST`,headers:{"Content-Type":`application/json`,...T},body:JSON.stringify(A),...a?{credentials:a}:{}}).then(e=>{e.ok||k(new t.ErrorInfo(`unable to send; HTTP POST to ${r} returned ${String(e.status)} ${e.statusText}`,G.SessionSendFailed,e.status))}).catch(e=>{let n=e instanceof t.ErrorInfo?e:void 0;k(new t.ErrorInfo(`unable to send; HTTP POST to ${r} failed: ${e instanceof Error?e.message:String(e)}`,G.SessionSendFailed,500,n))}),ee},reconnectToStream:()=>Promise.resolve(null),close:async()=>e.close(),get streaming(){return o},onStreamingChange:e=>(s.on(`streaming`,e),()=>{s.off(`streaming`,e)})}},At=`0.2.0`,jt=`ai-transport-js`,Mt=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:Object.entries(t).map(([e,t])=>`${e}/${t}`).join(` `)}}},Nt=(e,t)=>{let n=t?.adapterTag,r={[jt]:At};return n&&(r[n]=At),Mt(e,r)},Pt=e=>{let t={[b]:e.role,[_]:e.codecMessageId};return e.runId!==void 0&&(t[m]=e.runId),e.runClientId!==void 0&&(t[v]=e.runClientId),e.parent&&(t[x]=e.parent),e.forkOf&&(t[S]=e.forkOf),e.regenerates&&(t[C]=e.regenerates),e.invocationId&&(t[h]=e.invocationId),e.inputClientId!==void 0&&(t[y]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[T]=e.inputCodecMessageId),e.inputEventId&&(t[g]=e.inputEventId),t},Ft=e=>{let t={[m]:e.runId,[v]:e.runClientId};return e.reason!==void 0&&(t[w]=e.reason),e.parent!==void 0&&(t[x]=e.parent),e.forkOf!==void 0&&(t[S]=e.forkOf),e.regenerates!==void 0&&(t[C]=e.regenerates),e.invocationId!==void 0&&(t[h]=e.invocationId),e.inputClientId!==void 0&&(t[y]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[T]=e.inputCodecMessageId),t},It=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,Lt=(e,t,n)=>{let r=t[m];if(!r)return;let i=t[`run-client-id`]??``;if(e===`ai-run-start`){let e=t[x],a=t[S],o=t[C];return{type:`start`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,...e!==void 0&&{parent:e},...a!==void 0&&{forkOf:a},...o!==void 0&&{regenerates:o}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-resume`)return{type:`resume`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`;return{type:`end`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,reason:e}}},Rt=(e,t,n)=>{if(e.has(t)||e.size<n)return;let r=e.keys().next().value;if(r!==void 0)return e.delete(r),r},zt=(e,t)=>{let n=[],r=new Set,i=t;for(;i!==void 0&&!r.has(i);)r.add(i),n.push(i),i=e.get(i)?.parentCodecMessageId;return n.toReversed()},Bt=(e,t,n)=>{let r=N(n),i=n.serial;if(It(n.name)){let t=Lt(n.name,r,i);return t&&e.applyRunLifecycle(t),t}let{inputs:a,outputs:o}=t.decode(n);(a.length>0||o.length>0||r[`run-id`])&&e.applyMessage({inputs:a,outputs:o},r,i)},Vt=(e,t,n,r,i)=>{let{inputs:a,outputs:o}=t.decode(r),s=n;for(let t of[...a,...o])s=e.fold(s,t,{serial:r.serial??``,messageId:i});return s},Ht=(e,t)=>{let n=new Set,r=[];for(let t of e)t.serial!==void 0&&!n.has(t.serial)&&(n.add(t.serial),r.push(t));if(t!==void 0)for(let e of t)e.serial!==void 0&&!n.has(e.serial)&&(n.add(e.serial),r.push(e));return r.toSorted(R)},Ut=async(e,t,n)=>{let r=[],i=await e.history({limit:t});for(r.push(...i.items);i.hasNext()&&r.length<n;){let e=await i.next();if(!e)break;r.push(...e.items),i=e}return r},Wt=(e,t,n,r)=>{let i=e.createDecoder(),a=e.init(),o=0;for(let s of t){let t=N(s);if(t[`run-id`]!==n||It(s.name))continue;let c=t[_];if(r!==void 0&&c===r)break;a=Vt(e,i,a,s,c??``),o++}return{projection:a,folded:o}},Gt=(e,t,n)=>{let r=e.createDecoder(),i=e.init();for(let a of t){let t=N(a);t[`run-id`]===void 0&&t[`codec-message-id`]===n&&(i=Vt(e,r,i,a,n))}return i},Kt=async e=>{let{channel:n,codec:r,runId:i,signal:a,logger:o,liveMessages:s}=e;if(a.aborted)throw new t.ErrorInfo(`unable to load run projection; run ${i} was cancelled`,G.InvalidArgument,400);await n.attach();let{projection:c,folded:l}=Wt(r,Ht(await Ut(n,200,2e3),s),i);return o?.debug(`loadRunProjection(); folded run events`,{runId:i,folded:l}),c},qt=async e=>{let{channel:n,codec:r,runId:i,signal:a,logger:o,liveMessages:s,assistantParentFallback:c,pageLimit:l,maxMessages:u}=e;if(a.aborted)throw new t.ErrorInfo(`unable to load conversation; run ${i} was cancelled`,G.InvalidArgument,400);let d=Ht(await Ut(n,l,u),s),f=new Map,p=new Map;for(let e of d){if(It(e.name))continue;let t=N(e),n=t[_];if(n===void 0)continue;let r=t[m];r!==void 0&&p.set(r,n),f.has(n)||f.set(n,{runId:r,parentCodecMessageId:t[x]})}for(let e of d){if(e.name!==`ai-run-start`)continue;let t=N(e),n=t[m];if(n===void 0)continue;let r=p.get(n);if(r===void 0)continue;let i=f.get(r);i&&i.parentCodecMessageId===void 0&&(i.parentCodecMessageId=t[x])}let h=[],g=0;if(c!==void 0){let e=zt(f,c);g=e.length;for(let t of e){let e=f.get(t);if(e?.runId===i)continue;let n=e?.runId===void 0?Gt(r,d,t):Wt(r,d,e.runId).projection;h.push(...r.getMessages(n).map(e=>e.message))}}let{projection:v,folded:y}=Wt(r,d,i);return h.push(...r.getMessages(v).map(e=>e.message)),o?.debug(`loadConversation(); built`,{runId:i,chainLength:g,totalMessages:h.length,folded:y}),{messages:h,projection:v}},Jt=e=>{let t;return{promise:e===void 0?new Promise(()=>{}):e.aborted?Promise.resolve():new Promise(n=>{t=()=>{n()},e.addEventListener(`abort`,t,{once:!0})}),cleanup:()=>{t&&e&&e.removeEventListener(`abort`,t)}}},Yt=async(e,t,n,r,i,a)=>{a?.trace(`pipeStream();`);let o=e.getReader(),s=Jt(n),c=`complete`,l;try{for(;;){let e=await Promise.race([o.read(),s.promise.then(()=>`cancelled`)]);if(e===`cancelled`){c=`cancelled`,a?.debug(`pipeStream(); stream cancelled by AbortSignal`),r&&await r(async e=>t.publishOutput(e)),await t.cancel(`cancelled`);break}let{done:n,value:l}=e;if(n){await t.close(),a?.debug(`pipeStream(); stream completed`);break}await t.publishOutput(l,i?.(l))}}catch(e){c=`error`,l=e instanceof Error?e:Error(String(e)),a?.error(`pipeStream(); stream error`,{error:l.message});try{await t.close()}catch{}}finally{s.cleanup(),o.releaseLock()}return{reason:c,error:l}},Xt=class{constructor(e,t){this._activeRuns=new Map,this._channel=e,this._logger=t?.withContext({component:`RunManager`})}async startRun(e,t,n,r){this._logger?.trace(`DefaultRunManager.startRun();`,{runId:e,clientId:t});let i=n??new AbortController,a=t??``;this._activeRuns.set(e,{controller:i,clientId:a});let o=r?.continuation===!0,s=Ft({runId:e,runClientId:a,parent:o?void 0:r?.parent,forkOf:o?void 0:r?.forkOf,regenerates:o?void 0:r?.regenerates,invocationId:r?.invocationId,inputClientId:r?.inputClientId,inputCodecMessageId:r?.inputCodecMessageId});return await this._channel.publish({name:o?te:O,extras:{ai:{transport:s}}}),this._logger?.debug(`DefaultRunManager.startRun(); run started`,{runId:e}),i.signal}async suspendRun(e,t,n,r){this._logger?.trace(`DefaultRunManager.suspendRun();`,{runId:e}),await this._publishTerminal(ee,e,{invocationId:t,inputClientId:n,inputCodecMessageId:r}),this._logger?.debug(`DefaultRunManager.suspendRun(); run suspended`,{runId:e})}async endRun(e,t,n,r,i){this._logger?.trace(`DefaultRunManager.endRun();`,{runId:e,reason:t}),await this._publishTerminal(k,e,{reason:t,invocationId:n,inputClientId:r,inputCodecMessageId:i}),this._logger?.debug(`DefaultRunManager.endRun(); run ended`,{runId:e,reason:t})}async _publishTerminal(e,t,n){let r=Ft({runId:t,runClientId:this._activeRuns.get(t)?.clientId??``,...n});await this._channel.publish({name:e,extras:{ai:{transport:r}}}),this._activeRuns.delete(t)}getSignal(e){return this._activeRuns.get(e)?.controller.signal}getClientId(e){return this._activeRuns.get(e)?.clientId}cancel(e){this._logger?.debug(`DefaultRunManager.cancel();`,{runId:e}),this._activeRuns.get(e)?.controller.abort()}getActiveRunIds(){return[...this._activeRuns.keys()]}close(){this._logger?.trace(`DefaultRunManager.close();`,{activeRuns:this._activeRuns.size});for(let e of this._activeRuns.values())e.controller.abort();this._activeRuns.clear()}},Zt=(e,t)=>new Xt(e,t),Qt=async e=>{let{register:n,codec:r,invocationId:i,runId:a,expectedInputEventIds:o,timeoutMs:s,signal:c,logger:l}=e,u=new Set(o),d=u.size,f=[],p=[],m=new Set,h,_,v=e=>{let t=r.createDecoder(),n=N(e),i=n[`codec-message-id`]??``,{inputs:a,outputs:o}=t.decode(e),s=[...a,...o],c=r.init();for(let t of s)c=r.fold(c,t,{serial:e.serial??``,messageId:i});return r.getMessages(c).map(({message:t})=>({kind:`message`,message:t,codecMessageId:i,parentId:n[x],forkOf:n[S],headers:n,serial:e.serial}))};return new Promise((e,r)=>{let o=!1,y=new Set,b=()=>{},x,S=()=>{b(),x!==void 0&&clearTimeout(x),c.removeEventListener(`abort`,C)},C=()=>{o||(o=!0,S(),r(new t.ErrorInfo(`unable to look up input event; run ${a} was cancelled`,G.InvalidArgument,400)))};if(c.addEventListener(`abort`,C,{once:!0}),!o){if(b=n(n=>{if(o||n.serial!==void 0&&y.has(n.serial))return;n.serial!==void 0&&y.add(n.serial);let s=N(n),c=s[g];if(!c||!u.has(c)||m.has(c))return;m.add(c),h===void 0&&(h=s,_=n.clientId);let b;try{b=v(n)}catch(e){o=!0,S();let n=e instanceof t.ErrorInfo?e:void 0;r(new t.ErrorInfo(`unable to look up input event; decode failed for invocation ${i}: ${e instanceof Error?e.message:String(e)}`,G.InputEventNotFound,504,n));return}for(let e of b)f.push(e);p.push(n),!(m.size<d)&&(o=!0,S(),f.sort(R),l?.debug(`lookupInputEvents(); collected input events`,{runId:a,invocationId:i,count:f.length}),e({nodes:f,firstHeaders:h,firstClientId:_,rawMessages:p}))}),o){b();return}x=setTimeout(()=>{o||(o=!0,S(),r(new t.ErrorInfo(`unable to look up input event; received ${String(f.length)} of ${String(d)} input events for invocation ${i} within ${String(s)}ms`,G.InputEventNotFound,504)))},s)}})},$t=class{constructor(e){this._registeredRuns=new Map,this._runIdByInputCodecMessageId=new Map,this._deferredCancels=new Map,this._pendingInputEventLookups=new Map,this._inputEventBuffer=new Map,this._state=`ready`,this._codec=e.codec;let t={params:{...Nt(e.client,e.codec).params,rewind:e.rewindWindow??`2m`}};this._channel=e.client.channels.get(e.channelName,t),this._logger=e.logger?.withContext({component:`AgentSession`}),this._onError=e.onError,this._runManager=Zt(this._channel,this._logger),this._inputEventLookupTimeoutMs=e.inputEventLookupTimeoutMs??3e4,this._inputEventBufferLimit=e.inputEventBufferLimit??200,this._channelListener=e=>{this._handleChannelMessage(e)},this._hasAttachedOnce=this._channel.state===`attached`,this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange),this._logger?.debug(`DefaultAgentSession(); session created`)}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,G.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger?.trace(`DefaultAgentSession.connect();`),this._connectPromise=this._channel.subscribe(this._channelListener).then(()=>{this._logger?.debug(`DefaultAgentSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${e instanceof Error?e.message:String(e)}`,G.SessionSubscriptionError,500,e instanceof t.ErrorInfo?e:void 0);throw this._logger?.error(`DefaultAgentSession.connect(); subscribe failed`),this._onError?.(n),n}),this._connectPromise)}_registerInputEventListener(e,t){for(let n of e)this._pendingInputEventLookups.set(n,t);for(let n of e){let e=this._inputEventBuffer.get(n);if(e){this._inputEventBuffer.delete(n);for(let n of e)t(n)}}return()=>{for(let n of e)this._pendingInputEventLookups.get(n)===t&&this._pendingInputEventLookups.delete(n)}}createRun(e,t){return this._logger?.trace(`DefaultAgentSession.createRun();`,{inputEventId:e.inputEventId}),this._createRun(e,t??{})}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger?.trace(`DefaultAgentSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._channelListener),this._channel.off(this._onChannelStateChange);for(let e of this._registeredRuns.values())e.controller.abort();if(this._registeredRuns.clear(),this._runIdByInputCodecMessageId.clear(),this._deferredCancels.clear(),this._pendingInputEventLookups.clear(),this._inputEventBuffer.clear(),this._runManager.close(),this._connectPromise)try{await this._channel.detach()}catch(e){this._logger?.debug(`DefaultAgentSession.close(); channel detach failed`,{error:e})}this._logger?.debug(`DefaultAgentSession.close(); session closed`)}}async _handleCancelMessage(e){let t=N(e),n=t[m],r=t[T];if(!n&&!r){this._logger?.warn(`DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id`,{serial:e.serial});return}let i=n??(r?this._runIdByInputCodecMessageId.get(r):void 0),a=i?this._registeredRuns.get(i):void 0;if(!a){r!==void 0&&this._bufferDeferredCancel(r,e);return}await this._cancelRegistration(a,e)}_bufferDeferredCancel(e,t){let n=Rt(this._deferredCancels,e,this._inputEventBufferLimit);n!==void 0&&this._logger?.warn(`DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest`,{evictedInputCodecMessageId:n,limit:this._inputEventBufferLimit}),this._deferredCancels.set(e,t),this._logger?.debug(`DefaultAgentSession._bufferDeferredCancel(); buffered early cancel`,{inputCodecMessageId:e,serial:t.serial})}async _pullDeferredCancel(e,t){let n=this._deferredCancels.get(t);n!==void 0&&(this._deferredCancels.delete(t),this._logger?.debug(`DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel`,{runId:e.runId,inputCodecMessageId:t}),await this._cancelRegistration(e,n))}async _cancelRegistration(e,n){let{runId:r}=e;this._logger?.debug(`DefaultAgentSession._cancelRegistration(); matched run`,{runId:r});let i={message:n,runId:r};try{if(e.onCancel&&!await e.onCancel(i)){this._logger?.debug(`DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel`,{runId:r});return}e.controller.abort(),this._logger?.debug(`DefaultAgentSession._cancelRegistration(); run cancelled`,{runId:r})}catch(n){let i=new t.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${n instanceof Error?n.message:String(n)}`,G.CancelListenerError,500,n instanceof t.ErrorInfo?n:void 0);this._logger?.error(`DefaultAgentSession._cancelRegistration(); onCancel threw`,{runId:r}),(e.onError??this._onError)?.(i)}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:n,resumed:r}=e;if(n===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!(n===`failed`||n===`suspended`||n===`detached`||n===`attached`&&!r))return;this._logger?.error(`DefaultAgentSession._handleChannelStateChange(); channel continuity lost`,{current:n,resumed:r,previous:e.previous});let i=new t.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n===`attached`?`, resumed: false`:``})`,G.ChannelContinuityLost,500,e.reason);this._onError?.(i)}_handleChannelMessage(e){try{if(e.name===`ai-cancel`){this._handleCancelMessage(e).catch(e=>{let n=new t.ErrorInfo(`unable to route cancel message; ${e instanceof Error?e.message:String(e)}`,G.CancelListenerError,500,e instanceof t.ErrorInfo?e:void 0);this._logger?.error(`DefaultAgentSession._handleChannelMessage(); cancel routing error`),this._onError?.(n)});return}let n=N(e)[g];if(n!==void 0){let t=this._pendingInputEventLookups.get(n);if(t)t(e);else{let t=this._inputEventBuffer.get(n);if(t)t.push(e);else{let t=Rt(this._inputEventBuffer,n,this._inputEventBufferLimit);t!==void 0&&this._logger?.warn(`DefaultAgentSession._handleChannelMessage(); input-event buffer full, dropping oldest entry`,{evictedEventId:t,limit:this._inputEventBufferLimit}),this._inputEventBuffer.set(n,[e])}}}}catch(e){let n=new t.ErrorInfo(`unable to process channel message; ${e instanceof Error?e.message:String(e)}`,G.SessionSubscriptionError,500,e instanceof t.ErrorInfo?e:void 0);this._logger?.error(`DefaultAgentSession._handleChannelMessage(); subscription error`),this._onError?.(n)}}async _requireConnected(e){if(!this._connectPromise)throw new t.ErrorInfo(`unable to ${e}; connect() must be called before ${e}()`,G.InvalidArgument,400);return this._connectPromise}_createRun(e,n){let r=n.runId??crypto.randomUUID(),i=n.invocationId??crypto.randomUUID(),a=this._inputEventLookupTimeoutMs,{onMessage:o,onCancelled:s,onCancel:c,onError:l,signal:u}=n,d=new AbortController,f=`initialized`,p=u?AbortSignal.any([d.signal,u]):d.signal,h={runId:r,invocationId:i,controller:d,signal:p,onCancel:c,onError:l};this._registeredRuns.set(r,h);let g=this._logger,y=this._runManager,b=this._codec,w=this._channel,T=this._registeredRuns,E=this._runIdByInputCodecMessageId,D=this._deferredCancels,O=this._requireConnected.bind(this),ee=this._registerInputEventListener.bind(this),te=this._pullDeferredCancel.bind(this),k=e.inputEventId,A=[],j={get messages(){return A}},M,N,P,F,I,L,R=!1,z,B,V,H=()=>{T.delete(r),L!==void 0&&(E.delete(L),D.delete(L))},U,ne;return{get runId(){return r},get invocationId(){return i},get abortSignal(){return p},get view(){return j},get messages(){return ne===void 0?U===void 0?A.map(e=>e.message):b.getMessages(U).map(e=>e.message):[...ne]},start:async()=>{if(g?.trace(`Run.start();`,{runId:r,inputEventId:k}),await O(`start`),p.aborted)throw new t.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`,G.InvalidArgument,400);if(f!==`initialized`)return;if(f=`started`,k&&a>0)try{let e=await Qt({register:e=>ee([k],e),codec:b,invocationId:i,runId:r,expectedInputEventIds:[k],timeoutMs:a,signal:p,logger:g});for(let t of e.nodes)A.push(t);e.firstHeaders!==void 0&&(z=e.firstHeaders),e.firstClientId!==void 0&&(N=e.firstClientId),V=e.rawMessages}catch(e){let n=e instanceof t.ErrorInfo?e:new t.ErrorInfo(`unable to look up input event; ${e instanceof Error?e.message:String(e)}`,G.InputEventNotFound,504);throw H(),g?.error(`Run.start(); input-event lookup failed`,{runId:r,invocationId:i}),n}let e=z??A[0]?.headers;if(e){M=e[v],P=e[x],F=e[S],I=e[C],L=e[_];let t=e[m];R=t!==void 0,t!==void 0&&t!==r&&(T.delete(r),r=t,h.runId=r,T.set(r,h))}B=A.at(-1)?.codecMessageId??P,L!==void 0&&(E.set(L,r),await te(h,L));try{await y.startRun(r,M,d,{parent:B,forkOf:F,regenerates:I,invocationId:i,inputClientId:N,inputCodecMessageId:L,continuation:R})}catch(e){let n=new t.ErrorInfo(`unable to publish run-start for run ${r}; ${e instanceof Error?e.message:String(e)}`,G.RunLifecycleError,500,e instanceof t.ErrorInfo?e:void 0);throw g?.error(`Run.start(); failed to publish run-start`,{runId:r}),n}g?.debug(`Run.start(); run started`,{runId:r,inputEventId:k})},addEvents:async e=>{if(g?.trace(`Run.addEvents();`,{runId:r,count:e.length}),await O(`addEvents`),f===`initialized`)throw new t.ErrorInfo(`unable to add events; start() must be called before addEvents() (run ${r})`,G.InvalidArgument,400);let n=y.getClientId(r);try{for(let t of e){let e=Pt({role:`assistant`,runId:r,codecMessageId:t.codecMessageId,runClientId:n,invocationId:i,inputClientId:N,inputCodecMessageId:L}),a=b.createEncoder(w,{extras:{headers:e},onMessage:o});for(let e of t.events)await a.publishOutput(e);await a.close()}}catch(e){let n=new t.ErrorInfo(`unable to publish events for run ${r}; ${e instanceof Error?e.message:String(e)}`,G.RunLifecycleError,500,e instanceof t.ErrorInfo?e:void 0);throw g?.error(`Run.addEvents(); publish failed`,{runId:r}),n}g?.debug(`Run.addEvents(); events published`,{runId:r,count:e.length})},loadProjection:async()=>{g?.trace(`Run.loadProjection();`,{runId:r}),await O(`loadProjection`);let e=await Kt({channel:w,codec:b,runId:r,signal:p,logger:g,liveMessages:V});return U=e,e},loadConversation:async e=>{g?.trace(`Run.loadConversation();`,{runId:r}),await O(`loadConversation`);let{messages:t,projection:n}=await qt({channel:w,codec:b,runId:r,signal:p,logger:g,liveMessages:V,assistantParentFallback:B,pageLimit:e?.pageLimit??200,maxMessages:e?.maxMessages??2e3});return U=n,ne=t,t},pipe:async(e,n)=>{if(g?.trace(`Run.pipe();`,{runId:r}),await O(`pipe`),f===`initialized`)throw new t.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`,G.InvalidArgument,400);let a=y.getClientId(r),c=n?.parent??B,u=n?.forkOf??F,d=I,m=crypto.randomUUID(),h=Pt({role:`assistant`,runId:r,codecMessageId:m,runClientId:a,parent:c,forkOf:u,invocationId:i,inputClientId:N,inputCodecMessageId:L,regenerates:d}),_=await Yt(e,b.createEncoder(w,{extras:{headers:h},onMessage:o,messageId:m}),p,s,n?.resolveWriteOptions,g);if(_.error){let e=new t.ErrorInfo(`unable to pipe response for run ${r}; ${_.error.message}`,G.StreamError,500,_.error instanceof t.ErrorInfo?_.error:void 0);g?.error(`Run.pipe(); stream error`,{runId:r}),l?.(e)}return g?.debug(`Run.pipe(); stream finished`,{runId:r,reason:_.reason}),_},suspend:async()=>{if(g?.trace(`Run.suspend();`,{runId:r}),await O(`suspend`),f===`initialized`)throw new t.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`,G.InvalidArgument,400);if(f!==`ended`){f=`ended`;try{await y.suspendRun(r,i,N,L)}catch(e){let n=new t.ErrorInfo(`unable to publish run-suspend for run ${r}; ${e instanceof Error?e.message:String(e)}`,G.RunLifecycleError,500,e instanceof t.ErrorInfo?e:void 0);throw g?.error(`Run.suspend(); failed to publish run-suspend`,{runId:r}),n}finally{H()}g?.debug(`Run.suspend(); run suspended`,{runId:r})}},end:async e=>{if(g?.trace(`Run.end();`,{runId:r,reason:e}),await O(`end`),f===`initialized`)throw new t.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`,G.InvalidArgument,400);if(f!==`ended`){f=`ended`;try{await y.endRun(r,e,i,N,L)}catch(e){let n=new t.ErrorInfo(`unable to publish run-end for run ${r}; ${e instanceof Error?e.message:String(e)}`,G.RunLifecycleError,500,e instanceof t.ErrorInfo?e:void 0);throw g?.error(`Run.end(); failed to publish run-end`,{runId:r}),n}finally{H()}g?.debug(`Run.end(); run ended`,{runId:r,reason:e})}}}}},en=e=>new $t(e),tn=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},$=e=>e.kind===`run`?e.runId:e.codecMessageId,nn=e=>e.kind===`run`?e.startSerial:e.serial,rn=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},an=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},on=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._codec=e,this._logger=t,this._emitter=new ht(t)}_compareNodes(e,t){let n=nn(e.node),r=nn(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(nn(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:$(e.node),messageId:r,err:t})}}_addToParentIndex(e,t){rn(this._parentIndex,e,t)}_removeFromParentIndex(e,t){an(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([$(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add($(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set($(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=$(t);if($(e)===n)return!0;let r=e,i=new Set([$(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add($(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return $(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?$(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=$(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>$(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=$(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n){let r=t[m],i=t[_],a=r===void 0&&i!==void 0&&t.role===`user`&&e.inputs.length>0?i:void 0;if(r===void 0&&a===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let o=[...e.inputs,...e.outputs],s=a??r;if(o.length===0&&s!==void 0&&!this._nodeIndex.has(s))return;let c=this._structuralVersion;a===void 0?r!==void 0&&this._applyRunMessage(r,e,t,n):this._applyInputMessage(a,t,n,o),this._structuralVersion!==c&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r){let i=this._nodeIndex.get(e);i?i.node.kind===`input`&&n&&!i.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),i.node.serial=n,this._promoteSerial(i)):(i=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,i,i.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._foldInto(i,r,n,e),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r){let i=n[_],a=n[T],o=[...t.inputs,...t.outputs],s=t.outputs,c=this._nodeIndex.get(e);if(!c&&i!==void 0){let e=this._codecMessageIdToNodeKey.get(i),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(c=t)}c?r&&c.node.kind===`run`&&!c.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),c.node.startSerial=r,this._promoteSerial(c)):(c=this._createRunFromHeaders(e,n,r),this._insertNode(e,c,c.node.parentCodecMessageId),this._indexReplyRun(c.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let l=$(c.node);i&&this._codecMessageIdToNodeKey.set(i,l),this._foldInto(c,o,r,i),this._emitter.emit(`output`,{runId:l,inputCodecMessageId:a,codecMessageId:i,serial:r,events:s})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&rn(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.status!==`active`&&(n.status=`active`),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=`suspended`,t.node.endSerial=e.serial)}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.status===`suspended`&&(t.node.status=`active`)}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=e.reason,t.node.endSerial=e.serial)}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&an(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[S];return this._buildRunNode({runId:e,parentCodecMessageId:t[x],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[C],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n})}_buildRunNode(e){return{node:{kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,status:`active`,projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0},insertSeq:this._seqCounter++}}_createInputNodeFromHeaders(e,t,n){let r=t[S];return{node:{kind:`input`,codecMessageId:e,parentCodecMessageId:t[x],forkOf:r,projection:this._codec.init(),serial:n},insertSeq:this._seqCounter++}}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`),this._emitter.emit(`ably-message`,e)}},sn=(e,t)=>new on(e,t),cn=(e,t)=>{for(let n of t){let t=N(n),r=t[_];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[d],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},ln=async(e,t,n)=>{e.rawMessages.push(...t.items),e.lastAblyPage=t,cn(e,t.items);let r=e.returnedCount+n;for(;e.completedCodecMessageIds.size<r&&t.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); fetching next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let n=await t.next();if(!n)break;t=n,e.rawMessages.push(...n.items),e.lastAblyPage=n,cn(e,n.items)}},un=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.lastAblyPage?.hasNext()??!1,o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return un(e,t);if(!a||!e.lastAblyPage)return;let n=await e.lastAblyPage.next();if(n)return await ln(e,n,t),un(e,t)}}},dn=async(e,t,n)=>{let r=t?.limit??100,i={rawMessages:[],returnedCount:0,returnedRawCount:0,lastAblyPage:void 0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};n.trace(`loadHistory();`,{limit:r});let a=r*10;return await e.attach(),await ln(i,await e.history({untilAttach:!0,limit:a}),r),un(i,r)},fn=e=>Array.isArray(e)?e:[e],pn=3,mn=e=>({runId:e.runId,clientId:e.clientId,status:e.status,invocationId:e.invocationId}),hn=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new ht(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>mn(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has($(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_extractMessages(e){let t=[];for(let n of e)for(let e of this._codec.getMessages(n.projection))t.push(e);return t}hasOlder(){return this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=100){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._withheldBuffer.length>0){let t=this._withheldBuffer.splice(-e,e);this._releaseWithheld(t);return}if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return mn(t);let n=this._selectedReplyRun(t.codecMessageId);return n?mn(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?mn(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.siblings.flatMap(e=>{let t=this._codec.getMessages(e.projection).at(0);return t?[t.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.siblings.length-1)),i=n.siblings[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:$(i)}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:$(i)})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:$(i)}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:$(i),groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.siblings.length-1;let n=e.siblings.findIndex(e=>$(e)===t.selectedKey);return n===-1?e.siblings.length-1:n}let t=this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.siblings.length-1;let n=e.siblings.findIndex(e=>$(e)===t.selectedRunId);return n===-1?e.siblings.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),siblings:e}:void 0}let n=this._tree.getSiblingNodes(t.runId);if(n.length>1&&this._codec.getMessages(t.projection).at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),siblings:n}}async send(e,n){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new t.ErrorInfo(`unable to send; view is closed`,G.InvalidArgument,400);let r=fn(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,n,i);return this._applyForkAutoSelect(a,n),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,n){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to regenerate; view is closed`,G.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new t.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,G.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new t.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,G.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...n,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,n,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to edit; view is closed`,G.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new t.ErrorInfo(`unable to edit; message not found in tree: ${e}`,G.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(n,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._onClose?.()}}async _loadFirstPage(e){let t=e*pn,n=await dn(this._channel,{limit:t},this._logger);this._closed||await this._revealFromPage(n,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>$(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){if(e[i]?.kind===`run`){if(n===t)break;n++}r=i}let i=e.slice(r),a=e.slice(0,r);for(let e of a)this._withheldRunIds.add($(e));this._withheldBuffer.push(...a),this._releaseWithheld(i)}_processHistoryPage(e){this._processingHistory=!0;try{let t=this._codec.createDecoder();for(let n of e.rawMessages)Bt(this._tree,t,n);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())t.kind===`run`&&!n.has($(t))&&e++;return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has($(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete($(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>$(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_onTreeAblyMessage(e){let t=N(e),n=t[_],r=t[m];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has($(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if($(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},gn=e=>new hn(e),_n=()=>{},vn=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=Nt(e.client,e.codec);if(this._channel=e.client.channels.get(e.channelName,t),this._codec=e.codec,this._clientId=e.clientId,this._logger=(e.logger??vt({logLevel:gt.Silent})).withContext({component:`ClientSession`}),this._emitter=new ht(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=sn(this._codec,this._logger),this._view=gn({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._decoder=this._codec.createDecoder(),this._encoder=this._codec.createEncoder(this._channel,this._clientId===void 0?void 0:{clientId:this._clientId}),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[_]:e,[b]:`user`};t&&(r[x]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,G.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${e instanceof Error?e.message:String(e)}`,G.SessionSubscriptionError,500,e instanceof t.ErrorInfo?e:void 0);throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,n),n}),this._connectPromise)}async _requireConnected(e){if(!this._connectPromise)throw new t.ErrorInfo(`unable to ${e}; connect() must be called before ${e}()`,G.InvalidArgument,400);return this._connectPromise}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let n=N(e);if((n[`run-reason`]??`complete`)===`error`){let e=n[E],r=e===void 0?NaN:Number(e),i=Number.isFinite(r)?r:G.SessionSubscriptionError,a=n[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500,s=new t.ErrorInfo(a,i,o);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:n[m],invocationId:n[h],code:i}),this._emitter.emit(`error`,s)}}let n=Bt(this._tree,this._decoder,e);if(n&&(n.type===`start`||n.type===`resume`)){let t=N(e)[T];if(t!==void 0){let e=this._pendingRunStarts.get(t);e&&(this._pendingRunStarts.delete(t),e.resolve(n.runId))}}this._tree.emitAblyMessage(e)}catch(e){let n=e instanceof t.ErrorInfo?e:void 0;this._emitter.emit(`error`,new t.ErrorInfo(`unable to process channel message; ${e instanceof Error?e.message:String(e)}`,G.SessionSubscriptionError,500,n))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:n,resumed:r}=e;if(n===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!(n===`failed`||n===`suspended`||n===`detached`||n===`attached`&&!r))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:n,resumed:r,previous:e.previous});let i=new t.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n===`attached`?`, resumed: false`:``})`,G.ChannelContinuityLost,500,e.reason);this._emitter.emit(`error`,i)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new t.ErrorInfo(`unable to create view; session is closed`,G.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=gn({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,n,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new t.ErrorInfo(`unable to send; session is closed`,G.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new t.ErrorInfo(`unable to send; channel is ${i}`,G.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=n?.runId!==void 0,o=n?.runId,s;n?.parent===void 0&&!n?.forkOf&&(s=r);let c=new Set,l=[];for(let t of e){let e=crypto.randomUUID(),r=t.codecMessageId??crypto.randomUUID();c.add(r);let i=t.kind!==`user-message`&&(t.kind===`regenerate`||t.codecMessageId!==void 0),a=t.parent??(n?.parent===void 0?s:n.parent),u=n?.forkOf,d=t.kind===`regenerate`?t.target:void 0,f=Pt({role:`user`,runId:o,codecMessageId:r,runClientId:this._clientId,...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[t],outputs:[]},f),l.push({input:t,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&n?.parent===void 0&&!n?.forkOf&&t.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new t.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,G.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId,...this._clientId!==void 0&&{clientId:this._clientId}})}catch(e){let n=e instanceof t.ErrorInfo?e:void 0,r=n?.statusCode===401||n?.statusCode===403,i=new t.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${e instanceof Error?e.message:String(e)}`,r?G.InsufficientCapability:G.SessionSendFailed,r?401:500,n);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>tn.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[g]:crypto.randomUUID()};e.runId!==void 0&&(t[m]=e.runId),e.inputCodecMessageId!==void 0&&(t[T]=e.inputCodecMessageId),await this._channel.publish({name:D,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return _n;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new t.ErrorInfo(`unable to await run-start; session closed`,G.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}if(this._connectPromise)try{await this._channel.detach()}catch(e){this._logger.debug(`ClientSession.close(); channel detach failed`,{error:e})}}}},yn=e=>new vn(e),bn=e=>yn({...e,codec:Q}),xn=e=>en({...e,codec:Q}),Sn=async(e,t)=>{if(e.reason!==`complete`)return Promise.resolve(t).catch(()=>{}),e.reason;try{return await t===`tool-calls`?`suspend`:`complete`}catch(e){return Cn(e)?`cancelled`:`error`}},Cn=e=>typeof e!=`object`||!e?!1:e.name===`AbortError`;e.UIMessageCodec=Q,e.createAgentSession=xn,e.createChatTransport=kt,e.createClientSession=bn,e.vercelRunOutcome=Sn});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`ably`)):typeof define==`function`&&define.amd?define([`exports`,`ably`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportVercel={},e.Ably))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e};t=((e,t,i)=>(i=e==null?{}:n(o(e)),c(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)))(t,1);var l=`stream`,u=`status`,d=`stream-id`,f=`discrete`,p=`run-id`,m=`invocation-id`,h=`event-id`,g=`codec-message-id`,_=`run-client-id`,v=`input-client-id`,y=`role`,b=`parent`,x=`fork-of`,S=`msg-regenerate`,C=`run-reason`,w=`input-codec-message-id`,T=`error-code`,E=`error-message`,D=`ai-cancel`,ee=`ai-run-start`,O=`ai-run-suspend`,k=`ai-run-resume`,te=`ai-run-end`,A=`ai-output`,ne=`ai-input`,j=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e[e.HistoryFetchFailed=104011]=`HistoryFetchFailed`,e}({}),M=(e,t)=>e.code===t,N=e=>e instanceof Error?e.message:String(e),P=e=>e instanceof t.ErrorInfo?e:void 0,re=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},F=e=>re(e,`transport`),I=e=>re(e,`codec`),L=e=>{if(e!==void 0)try{return JSON.parse(e)}catch{return}},R=e=>{if(e)try{return JSON.parse(e)}catch{return e}},ie=(e,t)=>({...e,...t}),ae=e=>{if(e!==void 0)return e===`true`},oe=(e,t)=>e.serial===void 0&&t.serial===void 0?0:e.serial===void 0?1:t.serial===void 0||e.serial<t.serial?-1:+(e.serial>t.serial),z=e=>{let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==void 0&&(t[n]=e[n]);return t},se=class{constructor(e,t={}){this._trackers=new Map,this._pending=[],this._closed=!1,this._writer=e,this._defaultExtras=t.extras,this._onMessageHook=t.onMessage??(()=>{}),this._logger=t.logger?.withContext({component:`EncoderCore`})}async publishDiscrete(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscrete();`,{name:e.name});let n=this._buildDiscreteMessage(e,t);return this._writer.publish(n)}async publishDiscreteBatch(e,t){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.publishDiscreteBatch();`,{count:e.length});let n=e.map(e=>this._buildDiscreteMessage(e,t,!0));return this._writer.publish(n)}async startStream(e,n,r){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.startStream();`,{name:n.name,streamId:e});let i=this._buildTransport(n.transportHeaders,r);i[l]=`true`,i[u]=`streaming`,i[d]=e;let a=n.codecHeaders??{},o={name:n.name,data:n.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=(await this._writer.publish(o)).serials[0];if(!s)throw new t.ErrorInfo(`unable to start stream; no serial returned for stream '${n.name}' (streamId: ${e})`,j.BadRequest,400);this._trackers.set(e,{serial:s,name:n.name,streamId:e,accumulated:n.data,persistentTransport:i,persistentCodec:a,cancelled:!1,completed:!1}),this._logger?.debug(`DefaultEncoderCore.startStream(); stream started`,{name:n.name,streamId:e,serial:s})}appendStream(e,n){this._assertNotClosed();let r=this._trackers.get(e);if(!r)throw new t.ErrorInfo(`unable to append to stream; no active stream for streamId '${e}'`,j.InvalidArgument,400);r.accumulated+=n;let i={serial:r.serial,data:n,extras:{ai:this._aiExtras({...r.persistentTransport},{...r.persistentCodec})}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:e})}async closeStream(e,n){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.closeStream();`,{streamId:e});let r=this._trackers.get(e);if(!r)throw new t.ErrorInfo(`unable to close stream; no active stream for streamId '${e}'`,j.InvalidArgument,400);r.accumulated+=n.data,r.completed=!0;let{transport:i,codec:a}=this._buildClosing(r,n);i[u]=`complete`;let o={serial:r.serial,data:n.data,extras:{ai:this._aiExtras(i,a)}};this._invokeOnMessage(o);let s=this._writer.appendMessage(o);this._pending.push({promise:s,streamId:e}),await this._flushPending(),this._logger?.debug(`DefaultEncoderCore.closeStream(); stream closed`,{streamId:e})}async cancelAllStreams(e){this._assertNotClosed(),this._logger?.trace(`DefaultEncoderCore.cancelAllStreams();`,{streamCount:this._trackers.size});for(let t of this._trackers.values()){if(t.cancelled||t.completed)continue;t.cancelled=!0;let{transport:n,codec:r}=this._buildClosing(t,void 0,e);n[u]=`cancelled`;let i={serial:t.serial,data:``,extras:{ai:this._aiExtras(n,r)}};this._invokeOnMessage(i);let a=this._writer.appendMessage(i);this._pending.push({promise:a,streamId:t.streamId})}await this._flushPending()}async _flushPending(){if(this._flushPromise)return this._flushPromise;let e=this._pending;if(this._pending=[],e.length!==0){this._logger?.trace(`DefaultEncoderCore._flushPending();`,{count:e.length}),this._flushPromise=this._doFlush(e);try{await this._flushPromise}finally{this._flushPromise=void 0}}}async _doFlush(e){let n=await Promise.allSettled(e.map(async e=>e.promise)),r=new Set;for(let[t,i]of n.entries()){let n=e[t];n&&i.status===`rejected`&&r.add(n.streamId)}if(r.size===0){this._logger?.debug(`DefaultEncoderCore._flushPending(); all appends succeeded`);return}this._logger?.warn(`DefaultEncoderCore._flushPending(); recovering failed appends`,{failedStreams:[...r]});let i=[];for(let e of r){let t=this._trackers.get(e);if(!t)continue;let n=t.cancelled?`cancelled`:`complete`,r={serial:t.serial,data:t.accumulated,extras:{ai:this._aiExtras({...t.persistentTransport,[u]:n},{...t.persistentCodec})}};try{await this._writer.updateMessage(r)}catch(t){i.push({streamId:e,error:t})}}if(i.length>0){let e=i.map(e=>e.streamId).join(`, `);throw this._logger?.error(`DefaultEncoderCore._flushPending(); recovery failed`,{failedStreams:e}),new t.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${e}`,j.EncoderRecoveryFailed,500)}}async close(){if(!this._closed){this._logger?.trace(`DefaultEncoderCore.close();`),this._closed=!0;try{await this._flushPending()}finally{this._trackers.clear()}this._logger?.debug(`DefaultEncoderCore.close(); encoder closed`)}}_invokeOnMessage(e){try{this._onMessageHook(e)}catch(e){this._logger?.error(`DefaultEncoderCore._invokeOnMessage(); hook threw`,{error:e})}}_assertNotClosed(){if(this._closed)throw new t.ErrorInfo(`unable to write to encoder; encoder has been closed`,j.InvalidArgument,400)}_buildTransport(e,t){let n={...ie(this._defaultExtras?.headers,t?.extras?.headers),...e};return t?.messageId!==void 0&&(n[g]=t.messageId),n}_aiExtras(e,t){return Object.keys(t).length>0?{transport:e,codec:t}:{transport:e}}_buildDiscreteMessage(e,t,n=!1){let r=this._buildTransport(e.transportHeaders,t);r[l]=`false`,n&&(r[f]=`true`);let i={name:e.name,data:e.data,extras:{ai:this._aiExtras(r,e.codecHeaders??{}),...e.ephemeral?{ephemeral:!0}:{}}};return this._invokeOnMessage(i),i}_buildClosing(e,t,n){let r=ie(this._defaultExtras?.headers,n?.extras?.headers);return{transport:{...e.persistentTransport,...r,...t?.transportHeaders},codec:{...e.persistentCodec,...t?.codecHeaders}}}},ce=(e,t={})=>new se(e,t),le=class{constructor(e,t={}){this._serialState=new Map,this._hooks=e,this._onStreamUpdate=t.onStreamUpdate,this._onStreamDelete=t.onStreamDelete,this._logger=t.logger?.withContext({component:`DecoderCore`})}decode(e){let t=e.action;switch(this._logger?.trace(`DefaultDecoderCore.decode();`,{action:t,serial:e.serial,name:e.name}),t){case`message.create`:{let t=this._toPayload(e);return t.transportHeaders?.stream===`true`?this._decodeStreamedCreate(t,e.serial,e.version.serial):this._hooks.decodeDiscrete(t)}case`message.append`:return this._decodeAppend(e);case`message.update`:return this._decodeUpdate(e);case`message.delete`:return this._decodeDelete(e);default:return[]}}_toPayload(e){return{name:e.name??``,data:e.data,transportHeaders:F(e),codecHeaders:I(e)}}_stringData(e){return typeof e.data==`string`?e.data:``}_invokeOnStreamUpdate(e){if(this._onStreamUpdate)try{this._onStreamUpdate(e)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamUpdate(); callback threw`,{error:e})}}_invokeOnStreamDelete(e,t){if(this._onStreamDelete)try{this._onStreamDelete(e,t)}catch(e){this._logger?.error(`DefaultDecoderCore._invokeOnStreamDelete(); callback threw`,{error:e})}}_alreadyIncorporated(e,t,n,r){return r!==void 0&&r<=n.version?(this._logger?.debug(`DefaultDecoderCore.${e}(); delivery already incorporated`,{serial:t,version:r,trackerVersion:n.version}),!0):n.closed?(this._logger?.debug(`DefaultDecoderCore.${e}(); stream closed, dropping delivery`,{serial:t,version:r}),!0):(r!==void 0&&(n.version=r),!1)}_closeTracker(e){e.closed=!0,e.accumulated=``}_applyTerminalStatus(e,t,n,r){return t===`complete`?(r.push(...this._hooks.buildEndEvents(e,n)),this._closeTracker(e),!0):t===`cancelled`?(this._closeTracker(e),!0):!1}_decodeStreamedCreate(e,t,n){if(!t)return[];if(this._serialState.get(t))return this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); duplicate create for tracked stream`,{serial:t}),[];let r=e.transportHeaders?.[`stream-id`]??``,i={name:e.name,streamId:r,accumulated:``,codecHeaders:{...e.codecHeaders},transportHeaders:{...e.transportHeaders},version:n??t,closed:!1};return this._serialState.set(t,i),this._logger?.debug(`DefaultDecoderCore._decodeStreamedCreate(); new stream`,{name:e.name,streamId:r,serial:t}),this._hooks.buildStartEvents(i)}_decodeAppend(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);if(!n)return this._logger?.warn(`DefaultDecoderCore._decodeAppend(); append with no tracker, treating as first contact`,{serial:t}),this._decodeUpdate(e);if(this._alreadyIncorporated(`_decodeAppend`,t,n,e.version.serial))return[];let r=F(e),i=I(e),a=typeof e.data==`string`?e.data:``,o=r[u],s=[];return a.length>0&&(n.accumulated+=a,s.push(...this._hooks.buildDeltaEvents(n,a))),this._applyTerminalStatus(n,o,i,s)&&this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream ${o===`complete`?`complete`:`cancelled`}`,{streamId:n.streamId}),s}_decodeUpdate(e){let t=e.serial;if(!t)return[];let n=this._toPayload(e),r=n.transportHeaders??{},i=n.codecHeaders??{},a=r[l]===`true`,o=r[u],s=this._serialState.get(t);if(!s)return this._decodeFirstContact(n,a,o,t,e.version.serial);if(this._alreadyIncorporated(`_decodeUpdate`,t,s,e.version.serial))return[];let c=this._stringData(e);if(c.startsWith(s.accumulated)){let e=c.slice(s.accumulated.length),t=[];return e.length>0&&(s.accumulated=c,t.push(...this._hooks.buildDeltaEvents(s,e))),this._applyTerminalStatus(s,o,i,t),t}return s.accumulated=c,s.codecHeaders={...i},s.transportHeaders={...r},this._invokeOnStreamUpdate(s),[]}_decodeFirstContact(e,t,n,r,i){if(!t)return this._hooks.decodeDiscrete(e);let a=e.transportHeaders?.[`stream-id`]??``,o=e.codecHeaders??{},s=typeof e.data==`string`?e.data:``;this._logger?.debug(`DefaultDecoderCore._decodeFirstContact(); first-contact stream`,{name:e.name,streamId:a,serial:r});let c={name:e.name,streamId:a,accumulated:s,codecHeaders:{...o},transportHeaders:{...e.transportHeaders},version:i??r,closed:!1};this._serialState.set(r,c);let l=this._hooks.buildStartEvents(c);return s.length>0&&l.push(...this._hooks.buildDeltaEvents(c,s)),n===`complete`&&l.push(...this._hooks.buildEndEvents(c,o)),(n===`complete`||n===`cancelled`)&&this._closeTracker(c),l}_decodeDelete(e){let t=e.serial;if(!t)return[];let n=this._serialState.get(t);return this._invokeOnStreamDelete(t,n),n&&this._closeTracker(n),this._logger?.debug(`DefaultDecoderCore._decodeDelete();`,{serial:t}),[]}},ue=(e,t={})=>new le(e,t),de=class{constructor(e){this._emitted=new Map,this._phases=e}ensurePhases(e,t){let n=this._getOrCreate(e),r=[];for(let e of this._phases)n.has(e.key)||(n.add(e.key),r.push(...e.build(t)));return r}markEmitted(e,t){this._getOrCreate(e).add(t)}resetPhase(e,t){this._emitted.get(e)?.delete(t)}clearScope(e){this._emitted.delete(e)}_getOrCreate(e){let t=this._emitted.get(e);return t||(t=new Set,this._emitted.set(e,t)),t}},fe=e=>new de(e);function B(e,t){return{key:e,read:n=>n[e]??t,write:(t,n)=>{typeof n==`string`&&(t[e]=n)}}}function V(e,t){return{key:e,read:n=>ae(n[e])??t,write:(t,n)=>{typeof n==`boolean`&&(t[e]=String(n))}}}var pe=e=>({key:e,read:t=>L(t[e]),write:(t,n)=>{n!=null&&(t[e]=JSON.stringify(n))}}),me=(e,t,n)=>({key:e,read:r=>{let i=r[e];return t.find(e=>e===i)??n},write:(t,n)=>{typeof n==`string`&&(t[e]=n)}}),he=`kind`,ge=`-*`,_e=e=>e.endsWith(ge)?t=>t.startsWith(e.slice(0,-1)):void 0,ve=`partType`,ye=(e,t)=>e[t],be=(e,t,n,r)=>{let i={[he]:t};for(let t of e)r&&!r.includes(t.key)||t.write(i,ye(n,t.key));return i},xe=(e,t)=>e.find(e=>!e.match&&e.partType===t)??e.find(e=>e.match?.(t)),Se=e=>{let t=new Map,n=[];for(let r of e)r.construct===`event`&&(r.match?n.push(r):t.set(r.type,r));return{discreteByType:t,wildcards:n}},H=(e,t)=>{let n={};for(let r of e){let e=r.read(t);e!==void 0&&(n[r.key]=e)}return n},Ce=e=>{let t=new Map;for(let n of e)t.set(n.kind,n);let n=(e,t)=>{if(e.wireOnly)return[];let n=H(e.fields,t.codecHeaders);e.data&&Object.assign(n,e.data.decode(t.data));let r=t.transportHeaders[`codec-message-id`]??``;return[{kind:e.kind,codecMessageId:r,payload:z(n)}]},r=(e,t)=>{let n=t.codecHeaders.partType??``,r=xe(e.parts,n);if(!r)return[];let i=H(r.fields,t.codecHeaders);r.data&&Object.assign(i,r.data.decode(t.data)),i.type=n;let a=e.assemble(z(i),{codecHeaders:t.codecHeaders,transportHeaders:t.transportHeaders});return[{kind:e.kind,...a}]};return{decode:e=>{let i=t.get(e.codecKind);return i?i.construct===`event`?n(i,e):r(i,e):[]}}},we=(e,t)=>t?.transportHeaders===void 0?e:{...e,transportHeaders:{...e.transportHeaders,...t.transportHeaders}},Te=(e,n)=>{let r=new Map;for(let t of e)r.set(t.kind,t);let i=async(e,r,i,a)=>{if(e.wireOnly){await i.publishDiscrete({name:n,data:``,codecHeaders:{[he]:e.kind}},a.opts);return}let o=ye(r,`payload`);if(typeof o!=`object`||!o)throw new t.ErrorInfo(`unable to encode input; event '${e.kind}' carries no payload object — declare it wireOnly or use an encode escape hatch`,j.InvalidArgument,400);let s=be(e.fields,e.kind,o),c=e.data?e.data.encode(o):``;await i.publishDiscrete({name:n,data:c,codecHeaders:s},a.opts)},a=async(e,t,r,i)=>{let a=e.messageHeaders?.(t),o=[];for(let r of e.explode(t)){let t=e.partTypeOf(r),i=xe(e.parts,t);if(!i)continue;let s=r,c={...be(i.fields,e.kind,s),...a?.codecHeaders,[ve]:t},l=i.data?i.data.encode(r):``;o.push(we({name:n,data:l,codecHeaders:c},a))}o.length===0&&o.push(we({name:n,data:``,codecHeaders:{[he]:e.kind,...a?.codecHeaders}},a)),await r.publishDiscreteBatch(o,i.opts)};return{encode:async(e,n,o)=>{let s=r.get(e.kind);if(!s)throw new t.ErrorInfo(`unable to publish; unsupported input kind '${e.kind}'`,j.InvalidArgument,400);await(s.construct===`event`?i(s,e,n,o):a(s,e,n,o))}}},Ee=()=>{let e=(e,t)=>{let n=_e(e);return{partType:e,...n?{match:n}:{},fields:t.fields??[],data:t.data}};return{event:(e,t)=>{let n=t;return{construct:`event`,kind:e,fields:n?.fields??[],data:n?.data,wireOnly:n?.wireOnly??!1}},batch:(t,n)=>{let r=n.parts(e);return{construct:`batch`,kind:t,explode:n.explode,partTypeOf:n.partTypeOf,parts:r,messageHeaders:n.messageHeaders,assemble:n.assemble}}}},De=`type`,Oe=e=>{let{discreteByType:t,wildcards:n}=Se(e),r=new Map;for(let t of e)t.construct===`stream`&&r.set(t.kind,t);let i=(e,t)=>(t[De]=e,z(t)),a=(e,t,n)=>{let r=H(e.fields,n.codecHeaders);return e.data&&Object.assign(r,e.data.decode(n.data)),[i(t,r)]},o=e=>r.get(e.codecHeaders.kind??``);return{buildStart:e=>{let t=o(e);if(!t)return[];let n=H(t.fields,e.codecHeaders);return n[t.idField]=e.streamId,[i(t.start,n)]},buildDelta:(e,t)=>{let n=o(e);if(!n)return[];let r={[n.idField]:e.streamId,[n.deltaField]:t};return[i(n.delta,r)]},buildEnd:(e,t)=>{let n=o(e);if(!n)return[];if(n.decodeEnd)return n.decodeEnd({streamId:e.streamId,accumulated:e.accumulated,codecHeaders:e.codecHeaders,closingCodecHeaders:t});let r=H(n.fields,t);return r[n.idField]=e.streamId,[i(n.end,r)]},decodeDiscrete:(e,i,o,s)=>{let c={codecKind:e,codecHeaders:i,transportHeaders:o,data:s},l=t.get(e);if(l)return a(l,e,c);let u=r.get(e);if(u?.decodeDiscrete)return u.decodeDiscrete(c);let d=n.find(t=>t.match?.(e));return d?a(d,e,c):[]}}},ke=(e,n)=>{let{discreteByType:r,wildcards:i}=Se(e),a=new Map;for(let t of e)t.construct===`stream`&&(a.set(t.start,{descriptor:t,phase:`start`}),a.set(t.delta,{descriptor:t,phase:`delta`}),a.set(t.end,{descriptor:t,phase:`end`}));return{encode:async(e,o,s)=>{let{type:c}=e,l=a.get(c);if(l){let{descriptor:t,phase:r}=l,i=(e,n)=>be(t.fields,t.kind,e,n),a=ye(e,t.idField);r===`start`?await o.startStream(a,{name:n,data:``,codecHeaders:i(e)},s.opts):r===`delta`?o.appendStream(a,ye(e,t.deltaField)):t.onEnd?await t.onEnd(e,o,{h:i,name:n,messageId:s.messageId,opts:s.opts}):await o.closeStream(a,{name:n,data:``,codecHeaders:i(e)});return}let u=r.get(c)??i.find(e=>e.match?.(c));if(!u)throw new t.ErrorInfo(`unable to publish; unsupported event type '${c}'`,j.InvalidArgument,400);let d=(e,t)=>be(u.fields,e.type,e,t);if(u.encode){await u.encode(e,o,{h:d,name:n,messageId:s.messageId,opts:s.opts});return}let f=u.data?u.data.encode(e):``;await o.publishDiscrete({name:n,data:f,codecHeaders:d(e),ephemeral:u.ephemeral?.(e)},s.opts)}}},Ae=()=>({event:(e,t)=>({construct:`event`,type:e,fields:t?.fields??[],data:t?.data,ephemeral:t?.ephemeral,match:_e(e),encode:t?.encode}),stream:(e,t)=>({construct:`stream`,kind:e,...t})}),je=()=>({createUserMessage:e=>({kind:`user-message`,message:e}),createRegenerate:(e,t)=>({kind:`regenerate`,target:e,parent:t}),createToolResult:(e,t)=>({kind:`tool-result`,codecMessageId:e,payload:t}),createToolResultError:(e,t)=>({kind:`tool-result-error`,codecMessageId:e,payload:t}),createToolApprovalResponse:(e,t)=>({kind:`tool-approval-response`,codecMessageId:e,payload:t})}),Me=class{constructor(e,t,n,r){this._core=ce(e,t),this._messageId=t.messageId,this._outputEncoder=n,this._inputEncoder=r}async publishInput(e,t){await this._inputEncoder.encode(e,this._core,{opts:t})}async publishOutput(e,t){await this._outputEncoder.encode(e,this._core,{messageId:this._messageId,opts:t})}async cancelStreams(){await this._core.cancelAllStreams()}async close(){await this._core.close()}},Ne=(e,t,n,r)=>{let i=e.codecHeaders??{},a=e.transportHeaders??{},o=i.kind??``;if(e.name===`ai-input`)return n.decode({codecKind:o,data:e.data,codecHeaders:i,transportHeaders:a});if(e.name===`ai-output`){let n=a[`run-id`]??``,s=r?.onDiscrete;return[...(s!==void 0&&Object.hasOwn(s,o)?s[o]:void 0)?.(n,{codecHeaders:i})??[],...t.decodeDiscrete(o,i,a,e.data)]}return[]},Pe=e=>e.name===A,Fe=(e,t,n)=>({buildStartEvents:t=>{if(!Pe(t))return[];let r=t.transportHeaders[`run-id`]??``;return[...n?.onStreamStart?.(r,t)??[],...e.buildStart(t)]},buildDeltaEvents:(t,n)=>Pe(t)?e.buildDelta(t,n):[],buildEndEvents:(t,n)=>Pe(t)?e.buildEnd(t,n):[],decodeDiscrete:r=>Ne(r,e,t,n)}),Ie=class{constructor(e){this._core=e}decode(e){let t=this._core.decode(e);return e.name===`ai-input`?{inputs:t,outputs:[]}:{inputs:[],outputs:t}}},U=(e,n,r)=>{let i=e.get(n);if(i!==void 0)throw new t.ErrorInfo(`unable to define codec; dispatch literal '${n}' is declared by both ${i} and ${r}`,j.InvalidArgument,400);e.set(n,r)},Le=(e,n)=>{for(let r of e)if(r.key===`kind`||r.key===`partType`)throw new t.ErrorInfo(`unable to define codec; ${n} binds the driver-reserved header key '${r.key}'`,j.InvalidArgument,400)},Re=(e,t)=>{let n=new Map,r=new Map;for(let t of e)if(t.construct===`event`){let e=`output event '${t.type}'`;U(n,t.type,e),U(r,t.type,e),Le(t.fields,e)}else{let e=`output stream '${t.kind}'`;U(r,t.kind,e);for(let r of[t.start,t.delta,t.end])U(n,r,e);Le(t.fields,e)}let i=new Map;for(let e of t){let t=`input ${e.construct} '${e.kind}'`;if(U(i,e.kind,t),e.construct===`event`)Le(e.fields,t);else{let n=new Map;for(let r of e.parts){let e=`${t} part '${r.partType}'`;U(n,r.partType,e),Le(r.fields,e)}}}},ze=()=>e=>{let{reducer:t,decodeLifecycle:n}=e,r=e.output(Ae()),i=e.input(Ee());Re(r,i);let a=ke(r,A),o=Te(i,ne),s=Oe(r),c=Ce(i);return{...e.adapterTag===void 0?{}:{adapterTag:e.adapterTag},init:t.init,fold:t.fold,getMessages:t.getMessages,createEncoder:(e,t={})=>new Me(e,t,a,o),createDecoder:()=>new Ie(ue(Fe(s,c,n?.()),{})),...je()}},Be=B(`id`),W=pe(`providerMetadata`),G=B(`toolCallId`,``),K=B(`toolName`,``),q=V(`dynamic`),Ve=B(`title`),J=V(`providerExecuted`),He=B(`mediaType`,``),Ue=B(`sourceId`,``),We=B(`messageId`),Ge=V(`approved`,!1),Ke=B(`reason`),qe=me(`finishReason`,[`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`],`stop`),Je=()=>fe([{key:`start`,build:e=>[z({type:`start`,messageId:e.messageId})]},{key:`start-step`,build:()=>[{type:`start-step`}]}]),Ye=()=>{let e=Je();return{onDiscrete:{start:t=>(e.markEmitted(t,`start`),[]),"start-step":t=>(e.markEmitted(t,`start-step`),[]),"finish-step":t=>(e.resetPhase(t,`start-step`),[]),finish:t=>(e.clearScope(t),[]),error:t=>(e.clearScope(t),[]),abort:t=>(e.clearScope(t),[]),"tool-input":(t,n)=>e.ensurePhases(t,{messageId:We.read(n.codecHeaders)})},onStreamStart:(t,n)=>e.ensurePhases(t,{messageId:We.read(n.codecHeaders)})}},Xe=e=>typeof e==`object`&&!!e,Ze=(e,t)=>Xe(e)&&(e[t]===void 0||typeof e[t]==`string`),Qe=e=>typeof e==`string`?e:``,$e=e=>Ze(e,`errorText`),et=e=>Xe(e),tt=e=>Ze(e,`errorText`),nt=e=>Ze(e,`message`),rt=[{type:`text`,text:``}],it=e=>e.type===`text`||e.type===`file`||e.type.startsWith(`data-`),at=({event:e,batch:t})=>[e(`tool-result`,{fields:[G],data:{encode:e=>({output:e.output}),decode:e=>({output:et(e)?e.output:void 0})}}),e(`tool-result-error`,{fields:[G],data:{encode:e=>({message:e.message}),decode:e=>({message:nt(e)?e.message??``:``})}}),e(`tool-approval-response`,{fields:[G,Ge,Ke]}),e(`regenerate`,{wireOnly:!0}),t(`user-message`,{explode:e=>{let t=e.message.parts.filter(e=>it(e));return t.length>0?t:rt},partTypeOf:e=>e.type,parts:e=>[e(`text`,{data:{encode:e=>e.text,decode:e=>({text:Qe(e)})}}),e(`file`,{fields:[He],data:{encode:e=>e.url,decode:e=>({url:Qe(e)})}}),e(`data-*`,{fields:[Be],data:{encode:e=>e.data,decode:e=>({data:e})}})],messageHeaders:e=>{let t={};return We.write(t,e.message.id),{codecHeaders:t,transportHeaders:{[y]:e.message.role}}},assemble:(e,{codecHeaders:t,transportHeaders:n})=>{let r=n.role??`user`;return{message:{id:We.read(t)??``,role:r,parts:[e]}}}})],ot=({event:e,stream:n})=>[n(`text`,{start:`text-start`,delta:`text-delta`,end:`text-end`,idField:`id`,deltaField:`delta`,fields:[Be,W]}),n(`reasoning`,{start:`reasoning-start`,delta:`reasoning-delta`,end:`reasoning-end`,idField:`id`,deltaField:`delta`,fields:[Be,W]}),n(`tool-input`,{start:`tool-input-start`,delta:`tool-input-delta`,end:`tool-input-available`,idField:`toolCallId`,deltaField:`inputTextDelta`,fields:[G,K,q,Ve,J,W],onEnd:async(e,n,{h:r,name:i})=>{try{await n.closeStream(e.toolCallId,{name:i,data:``,codecHeaders:r(e,[`toolCallId`,`toolName`,`providerMetadata`])})}catch(a){if(!(a instanceof t.ErrorInfo&&M(a,j.InvalidArgument)))throw a;await n.publishDiscrete({name:i,data:e.input,codecHeaders:r(e)})}},decodeEnd:({streamId:e,accumulated:t,codecHeaders:n,closingCodecHeaders:r})=>[z({type:`tool-input-available`,toolCallId:e,toolName:K.read(r)||K.read(n),input:R(t),providerMetadata:W.read(r)})],decodeDiscrete:({codecHeaders:e,data:t})=>[z({type:`tool-input-start`,toolCallId:G.read(e),toolName:K.read(e),dynamic:q.read(e),title:Ve.read(e),providerExecuted:J.read(e),providerMetadata:W.read(e)}),z({type:`tool-input-available`,toolCallId:G.read(e),toolName:K.read(e),input:t,providerMetadata:W.read(e)})]}),e(`start`,{fields:[We,pe(`messageMetadata`)],encode:async(e,t,{h:n,name:r,messageId:i,opts:a})=>{await t.publishDiscrete({name:r,data:``,codecHeaders:n({...e,messageId:e.messageId??i})},a)}}),e(`start-step`),e(`finish-step`),e(`finish`,{fields:[qe,pe(`messageMetadata`)]}),e(`message-metadata`,{fields:[pe(`messageMetadata`)]}),e(`error`,{data:{encode:e=>e.errorText,decode:e=>({errorText:Qe(e)})}}),e(`abort`,{data:{encode:e=>e.reason??``,decode:e=>typeof e==`string`&&e?{reason:e}:{}}}),e(`file`,{fields:[He,W],data:{encode:e=>e.url,decode:e=>({url:Qe(e)})}}),e(`source-url`,{fields:[Ue,Ve,W],data:{encode:e=>e.url,decode:e=>({url:Qe(e)})}}),e(`source-document`,{fields:[Ue,He,B(`title`,``),B(`filename`),W]}),e(`tool-input-error`,{fields:[G,K,q,Ve,J,W],data:{encode:e=>({errorText:e.errorText,input:e.input}),decode:e=>$e(e)?{errorText:e.errorText??``,input:e.input}:{errorText:``}}}),e(`tool-output-available`,{fields:[G,q,J,V(`preliminary`)],data:{encode:e=>({output:e.output}),decode:e=>et(e)?{output:e.output}:{}}}),e(`tool-output-error`,{fields:[G,q,J],data:{encode:e=>({errorText:e.errorText}),decode:e=>({errorText:tt(e)?e.errorText??``:``})}}),e(`tool-approval-request`,{fields:[G,B(`approvalId`,``)]}),e(`tool-output-denied`,{fields:[G]}),e(`data-*`,{fields:[Be,V(`transient`)],ephemeral:e=>e.transient===!0,data:{encode:e=>e.data,decode:e=>({data:e})}})],st=()=>({messages:[],trackers:new Map,pendingToolResolutions:[]}),Y=(e,t)=>{let n=e.messages.find(e=>e.codecMessageId===t);return n||(n={codecMessageId:t,message:{id:t,role:`assistant`,parts:[]}},e.messages.push(n)),n.message},ct=(e,t)=>{let n=e.trackers.get(t);return n||(n={text:new Map,reasoning:new Map,tools:new Map},e.trackers.set(t,n)),n},X=(e,t,n)=>{let r=t.tools.get(n);if(!r)return;let i=e.parts[r.partIndex];if(i?.type===`dynamic-tool`)return{tracker:r,part:i}},lt=(e,t,n)=>{let r=Y(e,n);switch(t.type){case`file`:return r.parts.push({type:`file`,mediaType:t.mediaType,url:t.url}),e;case`source-url`:return r.parts.push(z({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title})),e;case`source-document`:return r.parts.push(z({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename})),e}},ut=(e,t,n)=>{if(t.transient)return e;let r=Y(e,n),i=z({type:t.type,id:t.id,data:t.data});if(t.id!==void 0){let n=r.parts.findIndex(e=>e.type===t.type&&`id`in e&&e.id===t.id);if(n!==-1)return r.parts[n]=i,e}return r.parts.push(i),e},Z=e=>z({type:`dynamic-tool`,toolCallId:e.toolCallId,toolName:e.toolName,title:e.title,providerExecuted:e.providerExecuted}),dt=(e,t)=>{let n=Z(e);switch(t.type){case`tool-output-available`:return z({...n,state:`output-available`,input:e.input,output:t.output,preliminary:t.preliminary});case`tool-output-error`:return{...n,state:`output-error`,input:e.input,errorText:t.errorText};case`tool-output-denied`:return{...n,state:`output-denied`,input:e.input,approval:{id:``,approved:!1}};case`tool-approval-request`:return{...n,state:`approval-requested`,input:e.input,approval:{id:t.approvalId}}}},ft=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e.messages.push({codecMessageId:t.id,message:t}),e;let i=e.messages.find(e=>e.codecMessageId===r);return i===void 0?e.messages.push({codecMessageId:r,message:t}):i.message.parts.push(...t.parts),e},pt=(e,t)=>{let{toolCallId:n,output:r}=t.payload;return gt(e,t.codecMessageId,n,{kind:`tool-result`,output:r})},mt=(e,t)=>{let{toolCallId:n,message:r}=t.payload;return gt(e,t.codecMessageId,n,{kind:`tool-result-error`,message:r})},ht=(e,t)=>{let{toolCallId:n,approved:r,reason:i}=t.payload;return gt(e,t.codecMessageId,n,{kind:`tool-approval-response`,approved:r,...i===void 0?{}:{reason:i}})},gt=(e,t,n,r)=>{let i=yt(e,t,n);return i?_t(i,n,r):e.pendingToolResolutions.push({targetCodecMessageId:t,toolCallId:n,resolution:r}),e},_t=(e,t,n)=>{switch(n.kind){case`tool-result`:e.message.parts[e.tracker.partIndex]=dt(e.part,{type:`tool-output-available`,toolCallId:t,output:n.output});break;case`tool-result-error`:e.message.parts[e.tracker.partIndex]=dt(e.part,{type:`tool-output-error`,toolCallId:t,errorText:n.message});break;case`tool-approval-response`:e.message.parts[e.tracker.partIndex]=bt(e.part,n.approved,n.reason);break}},vt=e=>{let t=[];for(let n of e.pendingToolResolutions){let r=yt(e,n.targetCodecMessageId,n.toolCallId);if(!r){t.push(n);continue}_t(r,n.toolCallId,n.resolution)}e.pendingToolResolutions=t},yt=(e,t,n)=>{let r=e.messages.find(e=>e.codecMessageId===t);if(!r)return;let i=ct(e,t),a=X(r.message,i,n);if(a)return{message:r.message,tracker:a.tracker,part:a.part}},bt=(e,t,n)=>t?{...Z(e),state:`approval-responded`,input:`input`in e?e.input:void 0,approval:{id:`approval`in e&&e.approval?e.approval.id:``,approved:!0,...n===void 0?{}:{reason:n}}}:dt(e,{type:`tool-output-denied`,toolCallId:e.toolCallId,...n===void 0?{}:{reason:n}}),xt=(e,t,n)=>{if(n===void 0)return;let r=e.messages.find(e=>e.codecMessageId===t)?.message;r&&(r.metadata=n)},St=(e,t,n)=>{switch(t.type){case`start`:{let r=Y(e,n);return t.messageId!==void 0&&(r.id=t.messageId),t.messageMetadata!==void 0&&(r.metadata=t.messageMetadata),e}case`start-step`:return Y(e,n).parts.push({type:`step-start`}),e;case`finish-step`:{let t=e.trackers.get(n);return t&&(t.text.clear(),t.reasoning.clear()),e}case`finish`:return xt(e,n,t.messageMetadata),e;case`abort`:case`error`:return e;case`message-metadata`:return xt(e,n,t.messageMetadata),e}},Ct=(e,t,n)=>{let r=Y(e,n),i=ct(e,n),a=t.type.startsWith(`text-`),o=a?`text`:`reasoning`,s=a?i.text:i.reasoning;switch(t.type){case`text-start`:case`reasoning-start`:return s.set(t.id,r.parts.length),r.parts.push({type:o,text:``}),e;case`text-delta`:case`reasoning-delta`:{let n=s.get(t.id);if(n===void 0)return e;let i=r.parts[n];return i?.type===o&&(i.text+=t.delta),e}case`text-end`:case`reasoning-end`:return s.delete(t.id),e}},wt=(e,t,n)=>{let r=Y(e,n),i=ct(e,n);switch(t.type){case`tool-input-start`:{let n=r.parts.length;return r.parts.push({...Z(t),state:`input-streaming`,input:void 0}),i.tools.set(t.toolCallId,{partIndex:n,inputText:``}),e}case`tool-input-delta`:{let n=i.tools.get(t.toolCallId);if(!n)return e;n.inputText+=t.inputTextDelta;let a=L(n.inputText),o=X(r,i,t.toolCallId);return o&&(r.parts[o.tracker.partIndex]={...Z(o.part),state:`input-streaming`,input:a}),e}case`tool-input-available`:{let n=X(r,i,t.toolCallId);return n&&(r.parts[n.tracker.partIndex]={...Z(n.part),state:`input-available`,input:t.input}),e}case`tool-input-error`:{let n=X(r,i,t.toolCallId);if(n)r.parts[n.tracker.partIndex]={...Z(n.part),state:`output-error`,input:t.input,errorText:t.errorText};else{let e=r.parts.length;r.parts.push({...Z(t),state:`output-error`,input:t.input,errorText:t.errorText}),i.tools.set(t.toolCallId,{partIndex:e,inputText:``})}return e}}},Tt=(e,t)=>{for(let n of e.messages){let r=e.trackers.get(n.codecMessageId);if(!r)continue;let i=X(n.message,r,t);if(i)return{message:n.message,tracker:i.tracker,part:i.part}}},Et=(e,t,n)=>{if(t.type===`tool-output-available`||t.type===`tool-output-error`){let n=Tt(e,t.toolCallId);return n&&(n.message.parts[n.tracker.partIndex]=dt(n.part,t)),e}let r=Y(e,n),i=X(r,ct(e,n),t.toolCallId);return i&&(r.parts[i.tracker.partIndex]=dt(i.part,t)),e},Dt=(e,t,n)=>{if(t.direction===`input`){let r=t.event;switch(r.kind){case`user-message`:ft(e,r.message,n);break;case`regenerate`:break;case`tool-result`:pt(e,r);break;case`tool-result-error`:mt(e,r);break;case`tool-approval-response`:ht(e,r);break}}else Ot(e,t.event,n);return e.pendingToolResolutions.length>0&&vt(e),e},Ot=(e,t,n)=>{let r=n.messageId;if(r===void 0)return e;switch(t.type){case`start`:case`start-step`:case`finish-step`:case`finish`:case`abort`:case`error`:case`message-metadata`:return St(e,t,r);case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:return Ct(e,t,r);case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:return wt(e,t,r);case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:return Et(e,t,r);case`file`:case`source-url`:case`source-document`:return lt(e,t,r);default:return t.type.startsWith(`data-`)?ut(e,t,r):e}},Q=ze()({adapterTag:`vercel-ai-sdk-ui-message`,reducer:{init:st,fold:Dt,getMessages:e=>e.messages},output:ot,input:at,decodeLifecycle:Ye}),kt=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),At=t.Realtime.EventEmitter,jt=class extends At{constructor(e){super(kt(e))}},Mt=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),Nt=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},Pt=e=>new It(e.logHandler??Nt,e.logLevel),Ft=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),It=class e{constructor(e,n,r){this._handler=e,this._context=r;let i=Ft.get(n);if(i===void 0)throw new t.ErrorInfo(`unable to create logger; invalid log level: ${n}`,j.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...Ft.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},Lt=e=>(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`toolCallId`in e&&`state`in e,Rt=e=>e.type===`finish`||e.type===`error`||e.type===`abort`,zt=(e,n,r)=>{let i={},a=[],o=new ReadableStream({start:e=>{i.controller=e},cancel:()=>{u()}}),{controller:s}=i;if(!s)throw new t.ErrorInfo(`unable to create run stream; ReadableStream start() was not called synchronously`,j.SessionSubscriptionError,500);let c;n.then(e=>{c=e},()=>{});let l=!1,u=()=>{for(let e of a)e();a.length=0},d=e=>{if(!l){l=!0;try{e()}catch{}u()}},f=()=>{d(()=>{s.close()})},p=e=>{d(()=>{s.error(e)})};return a.push(e.tree.on(`output`,e=>{if(e.inputCodecMessageId===r)for(let t of e.events){try{s.enqueue(t)}catch{f();return}if(Rt(t)){f();return}}}),e.tree.on(`run`,e=>{e.type===`end`&&c!==void 0&&e.runId===c&&f()}),e.on(`error`,e=>{p(e)})),{stream:o,close:f}},Bt=`/api/chat`,Vt=e=>{let t,n=new Promise(e=>{t=e}),r=new TransformStream({flush:()=>{t()}}),i=new AbortController;return e.pipeTo(r.writable,{signal:i.signal,preventCancel:!0}).catch(()=>{t()}),{stream:r.readable,done:n,fail:e=>{i.abort(e)}}},Ht=e=>e.role===`assistant`&&e.parts.some(e=>Lt(e)&&(e.state===`input-streaming`||e.state===`input-available`||e.state===`approval-requested`)),Ut=new Set([`input-streaming`,`input-available`,`approval-requested`]),Wt=(e,t)=>{let n=[];for(let r of t){if(r.role!==`assistant`)continue;let t=e.find(e=>e.message.id===r.id);if(!t)continue;let{codecMessageId:i,message:a}=t;for(let e of r.parts){if(!Lt(e))continue;let t=a.parts.find(t=>Lt(t)&&t.toolCallId===e.toolCallId);if(e.state===`approval-responded`&&(!t||t.state===`approval-requested`)){n.push(Q.createToolApprovalResponse(i,{toolCallId:e.toolCallId,approved:e.approval.approved,...e.approval.reason===void 0?{}:{reason:e.approval.reason}}));continue}e.state!==`output-available`&&e.state!==`output-error`||t&&!Ut.has(t.state)||(e.state===`output-available`?n.push(Q.createToolResult(i,{toolCallId:e.toolCallId,output:e.output})):n.push(Q.createToolResultError(i,{toolCallId:e.toolCallId,message:e.errorText})))}}return n},Gt=(e,t)=>{let n=e.findIndex(e=>e.message.id===t);if(!(n<=0))return e[n-1]?.codecMessageId},Kt=(e,n)=>{let r=n?.api??Bt,i=n?.fetch??globalThis.fetch.bind(globalThis),a=n?.credentials,o=!1,s=new jt(Pt({logLevel:Mt.Silent})),c=e=>{o=e,s.emit(`streaming`,e)};return{sendMessages:async o=>{let{messages:s,abortSignal:l,trigger:u,messageId:d}=o,f=e.view.getMessages(),p=new Map(f.map(e=>[e.message.id,e.codecMessageId])),m=e=>p.get(e),h=s.at(-1),g=!!h&&p.has(h.id),_=u===`submit-message`&&h?.role===`assistant`&&g,v=u===`submit-message`&&!d&&h?.role===`user`?s.at(-2):void 0,y=v&&Ht(v)&&p.has(v.id)?v.id:void 0,b,x;if(u===`regenerate-message`||_)b=[],x=s;else{if(s.length===0)throw new t.ErrorInfo(`unable to send messages; messages array is empty for submit-message trigger`,j.InvalidArgument,400);b=[s.at(-1)],x=y?s.slice(0,-2):s.slice(0,-1)}let S,C;u===`submit-message`&&d&&!_?(S=m(d),C=Gt(f,d)):y&&(S=m(y),C=Gt(f,y));let w,T;if(n?.prepareSendMessagesRequest){let e=n.prepareSendMessagesRequest({chatId:o.chatId,trigger:u,messageId:d,history:x,messages:b,forkOf:S,parent:C});w=e.body??{},T=e.headers}else w={},T=void 0;let E={};if(S!==void 0&&(E.forkOf=S),C!==void 0&&(E.parent=C),_){let t=m(h.id),n=t===void 0?void 0:e.view.runOf(t);n&&(E.runId=n.runId)}let D;if(_){let t=Wt(f,s);D=await e.view.send(t,E)}else if(u===`regenerate-message`){if(d===void 0)throw new t.ErrorInfo(`unable to regenerate; regenerate-message trigger fired without messageId`,j.InvalidArgument,400);let n=m(d);if(n===void 0)throw new t.ErrorInfo(`unable to regenerate; message not visible: ${d}`,j.InvalidArgument,400);D=await e.view.regenerate(n,E)}else{let t=b.map(e=>Q.createUserMessage(e));D=await e.view.send(t,E)}let ee=zt(e,D.runId,D.inputCodecMessageId);if(l){let e=()=>{D.cancel(),ee.close()};l.aborted?e():l.addEventListener(`abort`,e,{once:!0})}let{stream:O,done:k,fail:te}=Vt(ee.stream);c(!0),k.then(()=>{c(!1)});let A={...w,...D.toInvocation().toJSON()};return i(r,{method:`POST`,headers:{"Content-Type":`application/json`,...T},body:JSON.stringify(A),...a?{credentials:a}:{}}).then(e=>{e.ok||te(new t.ErrorInfo(`unable to send; HTTP POST to ${r} returned ${String(e.status)} ${e.statusText}`,j.SessionSendFailed,e.status))}).catch(e=>{te(new t.ErrorInfo(`unable to send; HTTP POST to ${r} failed: ${N(e)}`,j.SessionSendFailed,500,P(e)))}),O},reconnectToStream:()=>Promise.resolve(null),close:async()=>e.close(),get streaming(){return o},onStreamingChange:e=>(s.on(`streaming`,e),()=>{s.off(`streaming`,e)})}},qt=`0.3.0`,Jt=`ai-transport-js`,Yt=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:Zt(t)}}},Xt=e=>{let t=e?.adapterTag,n={[Jt]:qt};return t&&(n[t]=qt),n},Zt=e=>Object.entries(e).map(([e,t])=>`${e}/${t}`).join(` `),Qt=(e,t)=>Yt(e,Xt(t)),$t=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`ANNOTATION_PUBLISH`],en=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`OBJECT_PUBLISH`,`OBJECT_SUBSCRIBE`,`ANNOTATION_PUBLISH`,`ANNOTATION_SUBSCRIBE`],tn=e=>{if(e===void 0||e.length===0)return;let t=new Set([...$t,...e]),n=en.filter(e=>t.has(e)),r=[...t].filter(e=>!en.includes(e)).toSorted();return[...n,...r]},nn=(e,n)=>new Promise((r,i)=>{if(n?.aborted){i(new t.ErrorInfo(`unable to wait; signal aborted`,j.InvalidArgument,400));return}let a=setTimeout(()=>{n?.removeEventListener(`abort`,o),r()},e);typeof a==`object`&&a.unref();let o=()=>{clearTimeout(a),i(new t.ErrorInfo(`unable to wait; signal aborted`,j.InvalidArgument,400))};n?.addEventListener(`abort`,o,{once:!0})}),rn=async(e,n,r,i,a)=>{let o;for(let s=0;s<=n;s++){if(i?.aborted)throw new t.ErrorInfo(`unable to fetch history page; signal aborted`,j.InvalidArgument,400,P(o));try{return await e()}catch(e){if(o=e,s===n)break;let t=r*2**s;a?.debug(`loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying`,{attempt:s+1,maxRetries:n,backoff:t}),await nn(t,i)}}throw new t.ErrorInfo(`unable to fetch history page; ${N(o)}`,j.HistoryFetchFailed,500,P(o))},an=async(e,n)=>{let{pageLimit:r,untilAttach:i=!0,signal:a,maxRetries:o=3,retryBackoffMs:s=100,logger:c}=n;if(a?.aborted)throw new t.ErrorInfo(`unable to load history; signal aborted`,j.InvalidArgument,400);await e.attach();let l={limit:r,untilAttach:i},u=await rn(()=>e.history(l),o,s,a,c),d=!1;return{hasNext:()=>u===void 0||a?.aborted?!1:d?u.hasNext():!0,next:async()=>{if(u===void 0)return;if(a?.aborted)throw new t.ErrorInfo(`unable to load history; signal aborted`,j.InvalidArgument,400);if(!d)return d=!0,u.items;if(!u.hasNext()){u=void 0;return}let e=await rn(async()=>await u?.next()??void 0,o,s,a,c);if(!e){u=void 0;return}return u=e,e.items}}},on=(e,t,n,r)=>{if(t===void 0)return[];let i=[],a=e.getNodeByCodecMessageId(t),o=new Set,s=0;for(;a!==void 0;){let t=a.kind===`run`?a.runId:a.codecMessageId;if(o.has(t))break;if(a.kind===`run`&&a.runId!==r){if(n!==void 0&&s>=n)break;s+=1}o.add(t),i.unshift(a);let c=a.parentCodecMessageId;if(c===void 0)break;a=e.getNodeByCodecMessageId(c)}return i},sn=(e,t)=>{let n=0;for(let r of e)r.kind===`run`&&r.runId!==t&&n++;return n},cn=(e,n)=>{let r=P(n);return new t.ErrorInfo(`unable to ${e}; ${N(n)}`,r?.code??j.HistoryFetchFailed,r?.statusCode??500,r)},ln=class{constructor(e){this._historyExhausted=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._applier=e.applier,this._inputEventLookbackMs=e.inputEventLookbackMs,this._logger=e.logger?.withContext({component:`AgentView`})}_foldWire(e){this._applier.apply(e),this._tree.emitAblyMessage(e)}findInputEvent(e){let{invocationId:n,runId:r,expectedEventIds:i,timeoutMs:a,signal:o}=e,s=this._logger,c=new Set(i),l=c.size,u=new Map,d=new AbortController;return new Promise((e,f)=>{let p=!1,m,g,_,v=()=>{g&&g(),_!==void 0&&clearTimeout(_),d.abort(),o.removeEventListener(`abort`,y)},y=()=>{p||(p=!0,v(),f(new t.ErrorInfo(`unable to look up input event; run ${r} was cancelled`,j.InvalidArgument,400)))},b=()=>{if(p)return;p=!0,v();let t=[...u.values()].toSorted(oe),i,a;for(let e of t)if(i===void 0){i=F(e),a=e.clientId;break}s?.debug(`AgentView.findInputEvent(); collected input events`,{runId:r,invocationId:n,count:t.length}),e({rawMessages:t,firstHeaders:i,firstClientId:a})},x=e=>{if(p)return!1;let t=F(e)[h];return!t||!c.has(t)||u.has(t)?!1:(u.set(t,e),u.size>=l)};if(o.addEventListener(`abort`,y,{once:!0}),o.aborted){y();return}for(let e of i){let t=this._tree.findAblyMessageByEventId(e);if(t&&x(t)&&!p){b();return}}g=this._tree.on(`ably-message`,e=>{x(e)&&!p&&b()}),this._driveHistoryChain(()=>p,d.signal,this._inputEventLookbackMs,`scan history for input event`).catch(e=>{p||(m=e instanceof t.ErrorInfo?e:cn(`scan history for input event`,e),s?.warn(`AgentView.findInputEvent(); history scan failed (continuing on live path)`,{error:N(e)}))}),_=setTimeout(()=>{p||(p=!0,v(),f(new t.ErrorInfo(`unable to look up input event; received ${String(u.size)} of ${String(l)} input events for invocation ${n} within ${String(a)}ms`,j.InputEventNotFound,504,m)))},a),typeof _==`object`&&_.unref()})}async loadConversation(e,n,r,i,a,o){if(r.aborted)throw new t.ErrorInfo(`unable to load conversation; run ${e} was cancelled`,j.InvalidArgument,400);return await this._hydrateAncestors(e,n,r,i,a),this._collectConversation(e,n,i,o)}_collectConversation(e,t,n,r){let i=this._tree,a=on(i,t,n,e),o=i.getRunNode(e),s=[];for(let e of a)for(let t of this._codec.getMessages(e.projection)){if(r!==void 0&&t.codecMessageId===r)return{messages:s,projection:o?.projection??this._codec.init()};s.push(t.message)}if(o!==void 0&&!a.some(t=>t.kind===`run`&&t.runId===e))for(let e of this._codec.getMessages(o.projection))s.push(e.message);return{messages:s,projection:o?.projection??this._codec.init()}}messages(e,t,n){return this._collectConversation(e,t,void 0,n).messages}async _driveHistoryChain(e,t,n,r){let i=!1,a,o=this._hydrationMutex??Promise.resolve(),s=(async()=>{if(await o.catch(()=>{}),!(this._historyExhausted||t.aborted||e()))try{i=await this._walkSharedHistory(e,t,n)}catch(e){a=cn(r,e)}})();if(this._hydrationMutex=s,await s,a!==void 0)throw a;return{exhausted:i}}async _walkSharedHistory(e,t,n){this._cursor===void 0&&(this._cursor=await an(this._channel,{pageLimit:200,untilAttach:!0,logger:this._logger}));let r=this._cursor;for(;r.hasNext()&&!e();){if(t.aborted)return!1;let e=await r.next();if(!e)break;for(let t of e.toReversed())this._foldWire(t);if(n!==void 0){let t=e.at(-1);if(t?.timestamp!==void 0&&t.timestamp<Date.now()-n)break}}return!r.hasNext()&&!t.aborted}async _hydrateAncestors(e,n,r,i,a){let o=()=>{let t=this._tree;if(a&&t.getRunNode(e)?.startSerial===void 0)return!0;if(n===void 0)return!1;if(t.getNodeByCodecMessageId(n)===void 0)return!0;let r=on(t,n,i,e),o=r[0],s=o!==void 0&&o.parentCodecMessageId===void 0,c=i!==void 0&&sn(r,e)>=i&&o!==void 0&&(o.kind!==`run`||o.runId===e);return!s&&!c};if(!o()||this._historyExhausted)return;let s;try{({exhausted:s}=await this._driveHistoryChain(()=>!o(),r,void 0,`hydrate ancestors`))}catch(t){throw this._logger?.error(`AgentView._hydrateAncestors(); history fetch failed`,{runId:e,error:N(t)}),t}if(s&&(this._historyExhausted=!0),r.aborted&&o())throw new t.ErrorInfo(`unable to hydrate ancestors; signal aborted`,j.InvalidArgument,400)}},un=e=>new ln(e),dn=e=>{let t={[y]:e.role,[g]:e.codecMessageId};return e.runId!==void 0&&(t[p]=e.runId),e.runClientId!==void 0&&(t[_]=e.runClientId),e.parent&&(t[b]=e.parent),e.forkOf&&(t[x]=e.forkOf),e.regenerates&&(t[S]=e.regenerates),e.invocationId&&(t[m]=e.invocationId),e.inputClientId!==void 0&&(t[v]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[w]=e.inputCodecMessageId),e.inputEventId&&(t[h]=e.inputEventId),t},fn=e=>{let t={[p]:e.runId,[_]:e.runClientId};return e.reason!==void 0&&(t[C]=e.reason),e.parent!==void 0&&(t[b]=e.parent),e.forkOf!==void 0&&(t[x]=e.forkOf),e.regenerates!==void 0&&(t[S]=e.regenerates),e.invocationId!==void 0&&(t[m]=e.invocationId),e.inputClientId!==void 0&&(t[v]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[w]=e.inputCodecMessageId),e.errorCode!==void 0&&(t[T]=String(e.errorCode)),e.errorMessage!==void 0&&(t[E]=e.errorMessage),t},pn=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,mn=e=>{let n=e[T],r=n===void 0?NaN:Number(n),i=Number.isFinite(r)?r:j.SessionSubscriptionError,a=e[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500;return new t.ErrorInfo(a,i,o)},hn=(e,t,n,r)=>{let i=t[p];if(!i)return;let a=t[`run-client-id`]??``,o=r===void 0?{}:{timestamp:r};if(e===`ai-run-start`){let e=t[b],r=t[x],s=t[S];return{type:`start`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o,...e!==void 0&&{parent:e},...r!==void 0&&{forkOf:r},...s!==void 0&&{regenerates:s}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-resume`)return{type:`resume`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`,r=t[`invocation-id`]??``;return e===`error`?{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o,error:mn(t)}:{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o}}},gn=(e,t,n)=>{let r=F(n),i=n.serial,a=n.timestamp;if(pn(n.name)){let t=hn(n.name,r,i,a);return t&&e.applyRunLifecycle(t),t}let{inputs:o,outputs:s}=t.decode(n);(o.length>0||s.length>0||r[`run-id`])&&e.applyMessage({inputs:o,outputs:s},r,i,a,n.version.serial)},_n=(e,t)=>({apply:n=>gn(e,t,n)}),vn=(e,t,n)=>{if(e.has(t)||e.size<n)return;let r=e.keys().next().value;if(r!==void 0)return e.delete(r),r},yn=e=>{let t;return{promise:e===void 0?new Promise(()=>{}):e.aborted?Promise.resolve():new Promise(n=>{t=()=>{n()},e.addEventListener(`abort`,t,{once:!0})}),cleanup:()=>{t&&e&&e.removeEventListener(`abort`,t)}}},bn=async(e,t,n,r,i,a)=>{a?.trace(`pipeStream();`);let o=e.getReader(),s=yn(n),c=`complete`,l;try{for(;;){let e=await Promise.race([o.read(),s.promise.then(()=>`cancelled`)]);if(e===`cancelled`){c=`cancelled`,a?.debug(`pipeStream(); stream cancelled by AbortSignal`),r&&await r(async e=>t.publishOutput(e)),await t.cancelStreams();break}let{done:n,value:l}=e;if(n){await t.cancelStreams(),await t.close(),a?.debug(`pipeStream(); stream completed`);break}await t.publishOutput(l,i?.(l))}}catch(e){c=`error`,l=e instanceof Error?e:Error(String(e)),a?.error(`pipeStream(); stream error`,{error:l.message});try{await t.close()}catch{}}finally{s.cleanup(),o.releaseLock()}return{reason:c,error:l}},xn=class{constructor(e,t){this._activeRuns=new Map,this._channel=e,this._logger=t?.withContext({component:`RunManager`})}async startRun(e,t,n,r){this._logger?.trace(`DefaultRunManager.startRun();`,{runId:e,clientId:t});let i=n??new AbortController,a=t??``;this._activeRuns.set(e,{controller:i,clientId:a});let o=r?.continuation===!0,s=fn({runId:e,runClientId:a,parent:o?void 0:r?.parent,forkOf:o?void 0:r?.forkOf,regenerates:o?void 0:r?.regenerates,invocationId:r?.invocationId,inputClientId:r?.inputClientId,inputCodecMessageId:r?.inputCodecMessageId});await this._channel.publish({name:o?k:ee,extras:{ai:{transport:s}}}),this._logger?.debug(`DefaultRunManager.startRun(); run started`,{runId:e})}async suspendRun(e,t,n,r){this._logger?.trace(`DefaultRunManager.suspendRun();`,{runId:e}),await this._publishTerminal(O,e,{invocationId:t,inputClientId:n,inputCodecMessageId:r}),this._logger?.debug(`DefaultRunManager.suspendRun(); run suspended`,{runId:e})}async endRun(e,t,n,r,i,a){this._logger?.trace(`DefaultRunManager.endRun();`,{runId:e,reason:t});let o=t===`error`&&a?{errorCode:a.code,errorMessage:a.message}:{};await this._publishTerminal(te,e,{reason:t,invocationId:n,inputClientId:r,inputCodecMessageId:i,...o}),this._logger?.debug(`DefaultRunManager.endRun(); run ended`,{runId:e,reason:t})}async _publishTerminal(e,t,n){let r=fn({runId:t,runClientId:this._activeRuns.get(t)?.clientId??``,...n});await this._channel.publish({name:e,extras:{ai:{transport:r}}}),this._activeRuns.delete(t)}getClientId(e){return this._activeRuns.get(e)?.clientId}close(){this._logger?.trace(`DefaultRunManager.close();`,{activeRuns:this._activeRuns.size});for(let e of this._activeRuns.values())e.controller.abort();this._activeRuns.clear()}},Sn=(e,t)=>new xn(e,t),Cn=async(e,n)=>{if(!e)throw new t.ErrorInfo(`unable to ${n}; connect() must be called before ${n}()`,j.InvalidArgument,400);return e},wn=async(e,t,n,r)=>{if(t!==void 0)try{await e.detach()}catch(e){n?.debug(`${r}.close(); channel detach failed`,{error:e})}},Tn=e=>{let{current:t,resumed:n}=e;return t===`failed`||t===`suspended`||t===`detached`||t===`attached`&&!n},En=(e,n)=>{let{current:r}=e;return new t.ErrorInfo(`unable to ${n}; channel continuity lost (${r}${r===`attached`?`, resumed: false`:``})`,j.ChannelContinuityLost,500,e.reason)},Dn=e=>[...e.inputs.map(e=>({direction:`input`,event:e})),...e.outputs.map(e=>({direction:`output`,event:e}))],On=class{constructor(){this._entries=[],this._swept=!1}get swept(){return this._swept}record(e,t,n,r,i){let a=this._recordEntry(e,t,this._swept?[]:n,r,i);return a===void 0?`dropped`:this._swept||a===this._entries.length-1?`incremental`:`refold`}replay(e){for(let t of this._entries)for(let n of t.events)e(n,t.serial,t.messageId)}sweep(){this._swept=!0;for(let e of this._entries)e.events.length=0}_recordEntry(e,t,n,r,i){for(let a=this._entries.length-1;a>=0;a--){let o=this._entries[a];if(!o)break;if(o.serial===e)return r!==void 0&&(r<=o.decodedThrough||!i)?void 0:(o.events.push(...n),r!==void 0&&(o.decodedThrough=r),a);if(o.serial<e)return this._entries.splice(a+1,0,{serial:e,messageId:t,events:[...n],decodedThrough:r??e}),a+1}return this._entries.unshift({serial:e,messageId:t,events:[...n],decodedThrough:r??e}),0}},$=e=>e.kind===`run`?e.runId:e.codecMessageId,kn=e=>e.kind===`run`?e.startSerial:e.serial,An=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},jn=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},Mn=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._eventIdIndex=new Map,this._clock=0,this._sweepQueue=[],this._codec=e,this._logger=t,this._emitter=new jt(t)}_compareNodes(e,t){let n=kn(e.node),r=kn(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(kn(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:$(e.node),messageId:r,err:t})}}_recordAndFold(e,t,n,r,i,a){if(n===void 0||t.length===0){n===void 0&&t.length>0&&(e.optimistic=!0),this._foldInto(e,t,n,r);return}let o=e.log.record(n,r,t,i,a);if(o===`dropped`){this._logger.debug(`Tree._recordAndFold(); version guard dropped re-delivered wire`,{key:$(e.node),serial:n,version:i,swept:e.log.swept});return}if(e.optimistic&&!e.log.swept){e.optimistic=!1,this._refold(e);return}if(o===`refold`){this._refold(e);return}e.log.swept&&this._logger.warn(`Tree._recordAndFold(); late wire after log retention window; folding in arrival order`,{key:$(e.node),serial:n}),this._foldInto(e,t,n,r)}_refold(e){let t=this._codec.init();e.log.replay((n,r,i)=>{try{t=this._codec.fold(t,n,{serial:r,messageId:i})}catch(t){this._logger.error(`Tree._refold(); fold threw`,{key:$(e.node),messageId:i,err:t})}}),e.node.projection=t}_recordActivity(e,t){t!==void 0&&(t>e.lastActivityTs&&(e.lastActivityTs=t),t>this._clock&&(this._clock=t,this._drainSweepQueue()))}_maybeQueueSweep(e){let t=e.node;t.kind===`run`&&(e.log.swept||e.sweepQueued||e.runStartSeen&&(t.state.status===`active`||t.state.status===`suspended`||(e.sweepQueued=!0,this._sweepQueue.push(t.runId))))}_drainSweepQueue(){for(;this._sweepQueue.length>0;){let e=this._sweepQueue[0],t=e===void 0?void 0:this._nodeIndex.get(e);if(!t||t.log.swept){this._sweepQueue.shift();continue}if(t.lastActivityTs+12e4>=this._clock)return;this._sweepQueue.shift(),t.sweepQueued=!1,t.log.sweep(),this._logger.debug(`Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys`,{key:e,lastActivityTs:t.lastActivityTs})}}_addToParentIndex(e,t){An(this._parentIndex,e,t)}_removeFromParentIndex(e,t){jn(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([$(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add($(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set($(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=$(t);if($(e)===n)return!0;let r=e,i=new Set([$(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add($(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return $(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?$(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=$(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>$(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=$(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n,r,i){let a=t[p],o=t[g],s=a===void 0&&o!==void 0&&t.role===`user`&&e.inputs.length>0?o:void 0;if(a===void 0&&s===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let c=Dn(e),l=s??a;if(c.length===0&&l!==void 0&&!this._nodeIndex.has(l))return;let u=this._structuralVersion;s===void 0?a!==void 0&&this._applyRunMessage(a,e,t,n,r,i):this._applyInputMessage(s,t,n,r,i,c),this._structuralVersion!==u&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r,i,a){let o=this._nodeIndex.get(e);o?o.node.kind===`input`&&n&&!o.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),o.node.serial=n,this._promoteSerial(o)):(o=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,o,o.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._recordActivity(o,r),this._recordAndFold(o,a,n,e,i,t[l]===`true`),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r,i,a){let o=n[g],s=n[w],c=Dn(t),u=t.outputs,d=this._nodeIndex.get(e);if(!d&&o!==void 0){let e=this._codecMessageIdToNodeKey.get(o),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(d=t)}d?r&&d.node.kind===`run`&&!d.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),d.node.startSerial=r,this._promoteSerial(d)):(d=this._createRunFromHeaders(e,n,r),this._insertNode(e,d,d.node.parentCodecMessageId),this._indexReplyRun(d.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let f=$(d.node);o&&this._codecMessageIdToNodeKey.set(o,f),this._recordActivity(d,i),this._recordAndFold(d,c,r,o,a,n[l]===`true`),this._emitter.emit(`output`,{runId:f,inputCodecMessageId:s,codecMessageId:o,serial:r,events:u})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&An(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.state.status===`suspended`&&(n.state={status:`active`}),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId),t.runStartSeen=!0,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId),this._recordActivity(t,e.timestamp)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state={status:`suspended`},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp))}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.state.status===`suspended`&&(t.node.state={status:`active`},this._recordActivity(t,e.timestamp))}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state=e.reason===`error`?{status:`error`,error:e.error}:{status:e.reason},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t))}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&jn(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[x];return this._buildRunNode({runId:e,parentCodecMessageId:t[b],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[S],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n,runStartSeen:!1})}_wrapNode(e,t=!1){return{node:e,insertSeq:this._seqCounter++,log:new On,lastActivityTs:0,runStartSeen:t,sweepQueued:!1,optimistic:!1}}_buildRunNode(e){let t={kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,state:{status:`active`},projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0};return this._wrapNode(t,e.runStartSeen)}_createInputNodeFromHeaders(e,t,n){let r=t[x],i={kind:`input`,codecMessageId:e,parentCodecMessageId:t[b],forkOf:r,projection:this._codec.init(),serial:n};return this._wrapNode(i)}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial,runStartSeen:!0})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`);let t=F(e)[h];t!==void 0&&!this._eventIdIndex.has(t)&&this._eventIdIndex.set(t,e),this._emitter.emit(`ably-message`,e)}findAblyMessageByEventId(e){return this._eventIdIndex.get(e)}},Nn=(e,t)=>new Mn(e,t),Pn=200,Fn=class{constructor(e){this._registeredRuns=new Map,this._runIdByInputCodecMessageId=new Map,this._deferredCancels=new Map,this._state=`ready`,this._codec=e.codec;let t={...Qt(e.client,e.codec)},n=tn(e.channelModes);n&&(t.modes=n),this._channel=e.client.channels.get(e.channelName,t),this._logger=e.logger?.withContext({component:`AgentSession`}),this._onError=e.onError,this._runManager=Sn(this._channel,this._logger),this._inputEventLookupTimeoutMs=e.inputEventLookupTimeoutMs??3e4,this._inputEventLookbackMs=e.inputEventLookbackMs??12e4,this._tree=Nn(this._codec,this._logger??Pt({logLevel:Mt.Silent})),this._applier=_n(this._tree,this._codec.createDecoder()),this._agentView=this._createAgentView(),this._channelListener=e=>{this._handleChannelMessage(e)},this._hasAttachedOnce=this._channel.state===`attached`,this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange),this._logger?.debug(`DefaultAgentSession(); session created`)}_createAgentView(){return un({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,logger:this._logger,inputEventLookbackMs:this._inputEventLookbackMs})}get presence(){return this._channel.presence}get object(){return this._channel.object}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,j.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger?.trace(`DefaultAgentSession.connect();`),this._connectPromise=this._channel.subscribe(this._channelListener).then(()=>{this._logger?.debug(`DefaultAgentSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${N(e)}`,j.SessionSubscriptionError,500,P(e));throw this._logger?.error(`DefaultAgentSession.connect(); subscribe failed`),this._onError?.(n),n}),this._connectPromise)}get tree(){return this._tree}createRun(e,t){return this._logger?.trace(`DefaultAgentSession.createRun();`,{inputEventId:e.inputEventId}),this._createRun(e,t??{})}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger?.trace(`DefaultAgentSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._channelListener),this._channel.off(this._onChannelStateChange);for(let e of this._registeredRuns.values())e.controller.abort();this._registeredRuns.clear(),this._runIdByInputCodecMessageId.clear(),this._deferredCancels.clear(),this._runManager.close(),await wn(this._channel,this._connectPromise,this._logger,`DefaultAgentSession`),this._logger?.debug(`DefaultAgentSession.close(); session closed`)}}async _handleCancelMessage(e){let t=F(e),n=t[p],r=t[w];if(!n&&!r){this._logger?.warn(`DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id`,{serial:e.serial});return}let i=n??(r?this._runIdByInputCodecMessageId.get(r):void 0),a=i?this._registeredRuns.get(i):void 0;if(!a){r!==void 0&&this._bufferDeferredCancel(r,e);return}await this._cancelRegistration(a,e)}_bufferDeferredCancel(e,t){let n=vn(this._deferredCancels,e,Pn);n!==void 0&&this._logger?.warn(`DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest`,{evictedInputCodecMessageId:n,limit:Pn}),this._deferredCancels.set(e,t),this._logger?.debug(`DefaultAgentSession._bufferDeferredCancel(); buffered early cancel`,{inputCodecMessageId:e,serial:t.serial})}async _pullDeferredCancel(e,t){let n=this._deferredCancels.get(t);n!==void 0&&(this._deferredCancels.delete(t),this._logger?.debug(`DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel`,{runId:e.runId,inputCodecMessageId:t}),await this._cancelRegistration(e,n))}async _cancelRegistration(e,n){let{runId:r}=e;this._logger?.debug(`DefaultAgentSession._cancelRegistration(); matched run`,{runId:r});let i={message:n,runId:r};try{if(e.onCancel&&!await e.onCancel(i)){this._logger?.debug(`DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel`,{runId:r});return}e.controller.abort(),this._logger?.debug(`DefaultAgentSession._cancelRegistration(); run cancelled`,{runId:r})}catch(n){let i=new t.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${N(n)}`,j.CancelListenerError,500,P(n));this._logger?.error(`DefaultAgentSession._cancelRegistration(); onCancel threw`,{runId:r}),(e.onError??this._onError)?.(i)}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:t,resumed:n}=e;if(t===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!Tn(e))return;this._logger?.error(`DefaultAgentSession._handleChannelStateChange(); channel continuity lost`,{current:t,resumed:n,previous:e.previous});let r=En(e,`continue`);for(let e of this._registeredRuns.values())e.controller.abort();this._tree=Nn(this._codec,this._logger??Pt({logLevel:Mt.Silent})),this._applier=_n(this._tree,this._codec.createDecoder()),this._agentView=this._createAgentView(),this._onError?.(r)}_foldWire(e){this._applier.apply(e),this._tree.emitAblyMessage(e)}_handleChannelMessage(e){try{if(this._foldWire(e),e.name===`ai-cancel`){this._handleCancelMessage(e).catch(e=>{let n=new t.ErrorInfo(`unable to route cancel message; ${N(e)}`,j.CancelListenerError,500,P(e));this._logger?.error(`DefaultAgentSession._handleChannelMessage(); cancel routing error`),this._onError?.(n)});return}}catch(e){let n=new t.ErrorInfo(`unable to process channel message; ${N(e)}`,j.SessionSubscriptionError,500,P(e));this._logger?.error(`DefaultAgentSession._handleChannelMessage(); subscription error`),this._onError?.(n)}}async _requireConnected(e){return Cn(this._connectPromise,e)}_createRun(e,n){let r=n.runId??crypto.randomUUID(),i=n.runId!==void 0,a=n.invocationId??crypto.randomUUID(),o=this._inputEventLookupTimeoutMs,{onMessage:s,onCancelled:c,onCancel:l,onError:u,signal:d}=n,f=new AbortController,m=`initialized`,h=d?AbortSignal.any([f.signal,d]):f.signal,v={runId:r,invocationId:a,controller:f,signal:h,onCancel:l,onError:u};this._registeredRuns.set(r,v);let y=this._logger,C=this._runManager,w=this._codec,T=this._channel,E=this._registeredRuns,D=this._runIdByInputCodecMessageId,ee=this._deferredCancels,O=this._requireConnected.bind(this),k=()=>this._agentView,te=this._pullDeferredCancel.bind(this),A=e.inputEventId,ne,M,re,F,I,L,R=!1,ie,ae=()=>this._tree,oe={get messages(){if(L===void 0)return[];let e=ae().getNodeByCodecMessageId(L);if(!e)return[];let t=e.kind===`input`?e.serial:e.startSerial,n=e.kind===`input`?e.forkOf:void 0;return w.getMessages(e.projection).map(r=>({kind:`message`,message:r.message,codecMessageId:r.codecMessageId,parentId:e.parentCodecMessageId,forkOf:n,headers:{},serial:t}))}},z,se=()=>{E.delete(r),L!==void 0&&(D.delete(L),ee.delete(L))},ce=async(e,n,i)=>{try{await i()}catch(i){let a=new t.ErrorInfo(`unable to publish ${e} for run ${r}; ${N(i)}`,j.RunLifecycleError,500,P(i));throw y?.error(`Run.${n}(); failed to publish ${e}`,{runId:r}),a}},le={get runId(){return r},get invocationId(){return a},get abortSignal(){return h},get view(){return oe},get messages(){return k().messages(r,z,I)},start:async()=>{if(y?.trace(`Run.start();`,{runId:r,inputEventId:A}),await O(`start`),h.aborted)throw new t.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`,j.InvalidArgument,400);if(m!==`initialized`)return;if(m=`started`,A&&o>0)try{let e=await k().findInputEvent({invocationId:a,runId:r,expectedEventIds:[A],timeoutMs:o,signal:h});e.firstHeaders!==void 0&&(ie=e.firstHeaders),e.firstClientId!==void 0&&(M=e.firstClientId)}catch(e){let n=e instanceof t.ErrorInfo?e:new t.ErrorInfo(`unable to look up input event; ${N(e)}`,j.InputEventNotFound,504);throw se(),y?.error(`Run.start(); input-event lookup failed`,{runId:r,invocationId:a}),n}let e=ie;if(e){ne=e[_],re=e[b],F=e[x],I=e[S],L=e[g];let t=e[p];R=t!==void 0,t!==void 0&&t!==r&&(E.delete(r),r=t,v.runId=r,E.set(r,v))}z=L!==void 0&&this._tree.getNodeByCodecMessageId(L)!==void 0?L:re,L!==void 0&&(D.set(L,r),await te(v,L)),await ce(`run-start`,`start`,async()=>C.startRun(r,ne,f,{parent:z,forkOf:F,regenerates:I,invocationId:a,inputClientId:M,inputCodecMessageId:L,continuation:R})),R||ae().applyRunLifecycle({type:`start`,runId:r,clientId:ne??``,serial:void 0,invocationId:a,...z!==void 0&&{parent:z},...F!==void 0&&{forkOf:F},...I!==void 0&&{regenerates:I}}),y?.debug(`Run.start(); run started`,{runId:r,inputEventId:A})},loadConversation:async e=>{y?.trace(`Run.loadConversation();`,{runId:r}),await O(`loadConversation`);let{messages:t}=await k().loadConversation(r,z,h,e?.maxRuns,i||R,I);return t},pipe:async(e,n)=>{if(y?.trace(`Run.pipe();`,{runId:r}),await O(`pipe`),m===`initialized`)throw new t.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`,j.InvalidArgument,400);let i=C.getClientId(r),o=n?.parent??z,l=n?.forkOf??F,d=I,f=crypto.randomUUID(),p=dn({role:`assistant`,runId:r,codecMessageId:f,runClientId:i,parent:o,forkOf:l,invocationId:a,inputClientId:M,inputCodecMessageId:L,regenerates:d}),g=await bn(e,w.createEncoder(T,{extras:{headers:p},onMessage:s,messageId:f}),h,c,n?.resolveWriteOptions,y);if(g.error){let e=new t.ErrorInfo(`unable to pipe response for run ${r}; ${g.error.message}`,j.StreamError,500,P(g.error));y?.error(`Run.pipe(); stream error`,{runId:r}),u?.(e)}if(g.reason===`cancelled`)try{await le.end({reason:`cancelled`})}catch{y?.error(`Run.pipe(); run-end on cancel failed`,{runId:r})}return y?.debug(`Run.pipe(); stream finished`,{runId:r,reason:g.reason}),g},suspend:async()=>{if(y?.trace(`Run.suspend();`,{runId:r}),await O(`suspend`),m===`initialized`)throw new t.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`,j.InvalidArgument,400);if(m!==`ended`){m=`ended`;try{await ce(`run-suspend`,`suspend`,async()=>C.suspendRun(r,a,M,L))}finally{se()}y?.debug(`Run.suspend(); run suspended`,{runId:r})}},end:async e=>{let{reason:n}=e,i=e.reason===`error`?e.error:void 0;if(y?.trace(`Run.end();`,{runId:r,reason:n}),await O(`end`),m===`initialized`)throw new t.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`,j.InvalidArgument,400);if(m!==`ended`){m=`ended`;try{await ce(`run-end`,`end`,async()=>C.endRun(r,n,a,M,L,i))}finally{se()}y?.debug(`Run.end(); run ended`,{runId:r,reason:n})}}};return le}},In=e=>new Fn(e),Ln=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},Rn=(e,t)=>{for(let n of t){let t=F(n),r=t[g];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[u],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},zn=async(e,t)=>{let n=e.returnedCount+t;for(;e.completedCodecMessageIds.size<n&&e.cursor.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); pulling next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let t=await e.cursor.next();if(!t)break;e.rawMessages.push(...t),Rn(e,t)}},Bn=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.cursor.hasNext(),o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return Bn(e,t);if(a)return await zn(e,t),Bn(e,t)}}},Vn=async(e,t,n)=>{let r=t?.limit??100;n.trace(`loadHistory();`,{limit:r});let i={cursor:await an(e,{pageLimit:r*10,untilAttach:!0,logger:n}),rawMessages:[],returnedCount:0,returnedRawCount:0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};return await zn(i,r),Bn(i,r)},Hn=e=>Array.isArray(e)?e:[e],Un=e=>({runId:e.runId,clientId:e.clientId,invocationId:e.invocationId,...e.state}),Wn=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._nonHeadRegenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._hiddenMessageCount=0,this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._applier=e.applier,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new jt(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes).slice(this._hiddenMessageCount),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>Un(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has($(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_nonHeadRegenerators(e,t){return this._tree.getReplyRuns(t).filter(t=>t.regeneratesCodecMessageId===e).toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``))}_selectedNonHeadMember(e,t,n){let r=this._nonHeadRegenSelections.get(e);return r&&r.kind!==`pending`&&[t,...n.map(e=>e.runId)].includes(r.selectedRunId)?r.selectedRunId:n.at(-1)?.runId??t}_extractMessages(e){let t=[],n=new Set;for(let r of e)r.kind===`run`&&n.has(r.runId)||this._emitNodeMessages(r,t,n);return t}_emitNodeMessages(e,t,n){let r=this._codec.getMessages(e.projection);if(e.kind!==`run`){t.push(...r);return}for(let i=0;i<r.length;i++){let a=r[i];if(!a)continue;let o=i>0?r[i-1]?.codecMessageId:void 0;if(o!==void 0){let r=this._nonHeadRegenerators(a.codecMessageId,o);if(r.length>0){for(let e of r)n.add(e.runId);let i=this._selectedNonHeadMember(a.codecMessageId,e.runId,r);if(i!==e.runId){let e=r.find(e=>e.runId===i);if(e){this._emitNodeMessages(e,t,n);return}}}}t.push(a)}}hasOlder(){return this._hiddenMessageCount>0||this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=10){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._hiddenMessageCount>=e){this._hiddenMessageCount-=e,this._recomputeAndEmit();return}let t=e-this._hiddenMessageCount,n=this._extractMessages(this._computeFlatNodes()).length,r=()=>this._extractMessages(this._computeFlatNodes()).length-n;if(this._withheldBuffer.length>0){let e=this._messageTailSplitIndex(this._withheldBuffer,t),n=this._withheldBuffer.splice(e);this._releaseWithheld(n)}if(r()<t&&(await this._fetchOlder(t-r()),this._closed))return;let i=this._extractMessages(this._computeFlatNodes()).length;this._hiddenMessageCount=Math.max(0,this._hiddenMessageCount+(i-n)-e),this._recomputeAndEmit()}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}async _fetchOlder(e){if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}_messageTailSplitIndex(e,t){let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];if(i&&(n+=this._codec.getMessages(i.projection).length,n>=t))return r}return 0}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return Un(t);let n=this._selectedReplyRun(t.codecMessageId);return n?Un(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?Un(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.members.flatMap(e=>{let t=this._tree.getNodeByCodecMessageId(e.representativeCodecMessageId);if(!t)return[];let n=this._codec.getMessages(t.projection).find(t=>t.codecMessageId===e.representativeCodecMessageId);return n?[n.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.members.length-1)),i=n.members[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:i.memberNodeKey})):n.kind===`non-head-regen`?(this._nonHeadRegenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); non-head-regen`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,anchor:n.groupRoot})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedKey);return n===-1?e.members.length-1:n}let t=e.kind===`non-head-regen`?this._nonHeadRegenSelections.get(e.groupRoot):this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedRunId);return n===-1?e.members.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),members:this._nodeHeadMembers(e)}:void 0}let n=this._codec.getMessages(t.projection),r=this._resolveNonHeadBranchPoint(t,n,e);if(r)return r;let i=this._tree.getSiblingNodes(t.runId);if(i.length>1&&n.at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),members:this._nodeHeadMembers(i)}}_resolveNonHeadBranchPoint(e,t,n){if(t.at(0)?.codecMessageId===n&&e.regeneratesCodecMessageId!==void 0){let t=e.regeneratesCodecMessageId,n=this._runByCodecMessageId(t);if(n){let e=this._codec.getMessages(n.projection),r=e.findIndex(e=>e.codecMessageId===t),i=r>0?e[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(t,n.runId,i)}return}let r=t.findIndex(e=>e.codecMessageId===n),i=r>0?t[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(n,e.runId,i)}_buildNonHeadGroup(e,t,n){let r=this._nonHeadRegenerators(e,n);if(r.length===0)return;let i=[{memberNodeKey:t,representativeCodecMessageId:e}];for(let e of r){let t=this._codec.getMessages(e.projection).at(0);t&&i.push({memberNodeKey:e.runId,representativeCodecMessageId:t.codecMessageId})}return{kind:`non-head-regen`,groupRoot:e,members:i}}_nodeHeadMembers(e){let t=[];for(let n of e){let e=this._codec.getMessages(n.projection).at(0);e&&t.push({memberNodeKey:$(n),representativeCodecMessageId:e.codecMessageId})}return t}async send(e,n){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new t.ErrorInfo(`unable to send; view is closed`,j.InvalidArgument,400);let r=Hn(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,n,i);return this._applyForkAutoSelect(a,n),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;if(this._codec.getMessages(n.projection).at(0)?.codecMessageId!==t){this._nonHeadRegenSelections.set(t,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection`,{anchorCodecMessageId:t,carrier:e.inputCodecMessageId}),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged();return}let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,n){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to regenerate; view is closed`,j.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new t.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,j.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new t.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,j.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...n,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,n,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to edit; view is closed`,j.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new t.ErrorInfo(`unable to edit; message not found in tree: ${e}`,j.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(n,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._nonHeadRegenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._hiddenMessageCount=0,this._onClose?.()}}async _loadFirstPage(e){let t=await Vn(this._channel,{limit:e},this._logger);this._closed||await this._revealFromPage(t,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>$(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=this._messageTailSplitIndex(e,t),r=e.slice(n),i=e.slice(0,n);for(let e of i)this._withheldRunIds.add($(e));this._withheldBuffer.push(...i),this._releaseWithheld(r)}_processHistoryPage(e){this._processingHistory=!0;try{for(let t of e.rawMessages)this._applier.apply(t);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())n.has($(t))||(e+=this._codec.getMessages(t.projection).length);return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has($(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete($(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>$(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t).slice(this._hiddenMessageCount)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_resolvePendingNonHeadRegenSelections(){for(let[e,t]of this._nonHeadRegenSelections){if(t.kind===`user`)continue;let n=this._runByCodecMessageId(e);if(!n)continue;let r=this._codec.getMessages(n.projection),i=r.findIndex(t=>t.codecMessageId===e),a=i>0?r[i-1]?.codecMessageId:void 0;if(a===void 0)continue;let o=this._nonHeadRegenerators(e,a).at(-1);o&&this._nonHeadRegenSelections.set(e,{kind:`auto`,selectedRunId:o.runId})}}_onTreeAblyMessage(e){let t=F(e),n=t[g],r=t[p];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has($(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if($(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},Gn=e=>new Wn(e),Kn=()=>{},qn=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=Qt(e.client,e.codec),n=tn(e.channelModes);if(n&&(t.modes=n),this._channel=e.client.channels.get(e.channelName,t),this._client=e.client,this._codec=e.codec,this._logger=(e.logger??Pt({logLevel:Mt.Silent})).withContext({component:`ClientSession`}),this._emitter=new jt(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=Nn(this._codec,this._logger),this._applier=_n(this._tree,this._codec.createDecoder()),this._view=Gn({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._encoder=this._codec.createEncoder(this._channel),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[g]:e,[y]:`user`};t&&(r[b]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}get presence(){return this._channel.presence}get object(){return this._channel.object}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,j.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${N(e)}`,j.SessionSubscriptionError,500,P(e));throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,n),n}),this._connectPromise)}_resolveClientId(){let e=this._client.auth.clientId;return e&&e!==`*`?e:void 0}async _requireConnected(e){return Cn(this._connectPromise,e)}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let t=F(e);if((t[`run-reason`]??`complete`)===`error`){let e=mn(t);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:t[p],invocationId:t[m],code:e.code}),this._emitter.emit(`error`,e)}}let t=this._applier.apply(e);if(t&&(t.type===`start`||t.type===`resume`)){let n=F(e)[w];if(n!==void 0){let e=this._pendingRunStarts.get(n);e&&(this._pendingRunStarts.delete(n),e.resolve(t.runId))}}this._tree.emitAblyMessage(e)}catch(e){this._emitter.emit(`error`,new t.ErrorInfo(`unable to process channel message; ${N(e)}`,j.SessionSubscriptionError,500,P(e)))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:t,resumed:n}=e;if(t===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!Tn(e))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:t,resumed:n,previous:e.previous});let r=En(e,`deliver events`);this._emitter.emit(`error`,r)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new t.ErrorInfo(`unable to create view; session is closed`,j.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=Gn({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,n,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new t.ErrorInfo(`unable to send; session is closed`,j.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new t.ErrorInfo(`unable to send; channel is ${i}`,j.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=n?.runId!==void 0,o=n?.runId,s;n?.parent===void 0&&!n?.forkOf&&(s=r);let c=new Set,l=[];for(let t of e){let e=crypto.randomUUID(),r=t.codecMessageId??crypto.randomUUID();c.add(r);let i=t.kind!==`user-message`&&(t.kind===`regenerate`||t.codecMessageId!==void 0),a=t.parent??(n?.parent===void 0?s:n.parent),u=n?.forkOf,d=t.kind===`regenerate`?t.target:void 0,f=dn({role:`user`,runId:o,codecMessageId:r,runClientId:this._resolveClientId(),...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[t],outputs:[]},f),l.push({input:t,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&n?.parent===void 0&&!n?.forkOf&&t.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new t.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,j.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId})}catch(e){let n=P(e),r=n?.statusCode===401||n?.statusCode===403,i=new t.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${N(e)}`,r?j.InsufficientCapability:j.SessionSendFailed,r?401:500,n);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>Ln.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[h]:crypto.randomUUID()};e.runId!==void 0&&(t[p]=e.runId),e.inputCodecMessageId!==void 0&&(t[w]=e.inputCodecMessageId),await this._channel.publish({name:D,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return Kn;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new t.ErrorInfo(`unable to await run-start; session closed`,j.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}await wn(this._channel,this._connectPromise,this._logger,`ClientSession`)}}},Jn=e=>new qn(e),Yn=e=>Jn({...e,codec:Q}),Xn=e=>In({...e,codec:Q}),Zn=async(e,t)=>{if(e.reason!==`complete`)return Promise.resolve(t).catch(()=>{}),e.reason===`error`?{reason:`error`,error:Qn(e.error)}:{reason:e.reason};try{return await t===`tool-calls`?{reason:`suspend`}:{reason:`complete`}}catch(e){return $n(e)?{reason:`cancelled`}:{reason:`error`,error:Qn(e)}}},Qn=e=>{if(e instanceof t.ErrorInfo)return e;let n=e instanceof Error?e.message:String(e);return new t.ErrorInfo(`unable to complete run; ${n}`,j.StreamError,500)},$n=e=>typeof e!=`object`||!e?!1:e.name===`AbortError`;e.UIMessageCodec=Q,e.createAgentSession=Xn,e.createChatTransport=Kt,e.createClientSession=Yn,e.vercelRunOutcome=Zn});
|
|
2
2
|
//# sourceMappingURL=ably-ai-transport-vercel.umd.cjs.map
|