@economic/agents-playground 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -235,7 +235,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
235
235
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
236
236
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
|
|
237
237
|
`:`[${r[e]}\r
|
|
238
|
-
]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function G$(e,t){let n={type:`object`,additionalProperties:m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=R$(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=E$(e.keyType._def,t);return{...n,propertyNames:i}}return n}function K$(e,t){return t.mapStrategy===`record`?G$(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[m1(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||S$(),m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||S$()],minItems:2,maxItems:2}}}function q$(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function J$(){return{not:S$()}}function Y$(){return{type:`null`}}var X$={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Z$(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in X$&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=X$[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Q$(e,t)}var Q$=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function $$(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[X$[e.innerType._def.typeName],`null`]};let n=m1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function e1(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function t1(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=r1(a),s=m1(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=n1(e,t);return a!==void 0&&(n.additionalProperties=a),n}function n1(e,t){if(e.catchall._def.typeName!==`ZodNever`)return m1(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function r1(e){try{return e.isOptional()}catch{return!0}}var i1=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return m1(e.innerType._def,t);let n=m1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:S$()},n]}:S$()},a1=(e,t)=>{if(t.pipeStrategy===`input`)return m1(e.in._def,t);if(t.pipeStrategy===`output`)return m1(e.out._def,t);let n=m1(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,m1(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function o1(e,t){return m1(e.type._def,t)}function s1(e,t){let n={type:`array`,uniqueItems:!0,items:m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function c1(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:m1(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function l1(){return{not:S$()}}function u1(){return S$()}var d1=(e,t)=>m1(e.innerType._def,t),f1=(e,t,n)=>{switch(t){case $.ZodString:return R$(e,n);case $.ZodNumber:return e1(e);case $.ZodObject:return t1(e,n);case $.ZodBigInt:return w$(e);case $.ZodBoolean:return T$();case $.ZodDate:return O$(e,n);case $.ZodUndefined:return l1();case $.ZodNull:return Y$();case $.ZodArray:return C$(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Z$(e,n);case $.ZodIntersection:return P$(e,n);case $.ZodTuple:return c1(e,n);case $.ZodRecord:return G$(e,n);case $.ZodLiteral:return F$(e);case $.ZodEnum:return M$(e);case $.ZodNativeEnum:return q$(e);case $.ZodNullable:return $$(e,n);case $.ZodOptional:return i1(e,n);case $.ZodMap:return K$(e,n);case $.ZodSet:return s1(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return o1(e,n);case $.ZodNaN:case $.ZodNever:return J$();case $.ZodEffects:return j$(e,n);case $.ZodAny:return S$();case $.ZodUnknown:return u1();case $.ZodDefault:return A$(e,n);case $.ZodBranded:return E$(e,n);case $.ZodReadonly:return d1(e,n);case $.ZodCatch:return D$(e,n);case $.ZodPipeline:return a1(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}},p1=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function m1(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==y$)return i}if(r&&!n){let e=h1(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=f1(e,e.typeName,t),o=typeof a==`function`?m1(a(),t):a;if(o&&g1(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var h1=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:p1(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),S$()):t.$refStrategy===`seen`?S$():void 0}},g1=(e,t,n)=>(e.description&&(n.description=e.description),n),_1=e=>{let t=x$(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},v1=(e,t)=>{let n=_1(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:m1(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??S$()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=m1(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??S$(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},y1=Symbol.for(`vercel.ai.schema`);function b1(e){let t;return()=>(t??=e(),t)}function x1(e,{validate:t}={}){return{[y1]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function S1(e){return typeof e==`object`&&!!e&&y1 in e&&e[y1]===!0&&`jsonSchema`in e&&`validate`in e}function C1(e){return e==null?x1({properties:{},additionalProperties:!1}):S1(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?O1(e):w1(e):e()}function w1(e){return x1(()=>_$(e[`~standard`].jsonSchema.input({target:`draft-07`})),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new pW({value:t,cause:n.issues})}}})}function T1(e,t){let n=t?.useReferences??!1;return x1(()=>v1(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function E1(e,t){let n=t?.useReferences??!1;return x1(()=>_$(jY(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await GY(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function D1(e){return`_zod`in e}function O1(e,t){return D1(e)?E1(e,t):T1(e,t)}async function k1({value:e,schema:t,context:n}){let r=await A1({value:e,schema:t,context:n});if(!r.success)throw pW.wrap({value:e,cause:r.error,context:n});return r.value}async function A1({value:e,schema:t,context:n}){let r=C1(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:pW.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:pW.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function j1({text:e,schema:t}){try{let n=g$(e);return t==null?{success:!0,value:n,rawValue:n}:await A1({value:n,schema:t})}catch(t){return{success:!1,error:sW.isInstance(t)?t:new sW({text:e,cause:t}),rawValue:void 0}}}function M1({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new o$).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await j1({text:e,schema:t}))}}))}async function N1(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var P1=Object.defineProperty,F1=(e,t)=>{for(var n in t)P1(e,n,{get:t[n],enumerable:!0})},I1=`AI_NoObjectGeneratedError`,L1=`vercel.ai.error.${I1}`,R1=Symbol.for(L1),z1,B1=class extends JU{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:I1,message:e,cause:t}),this[z1]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return JU.hasMarker(e,L1)}};z1=R1;var V1=`AI_UIMessageStreamError`,H1=`vercel.ai.error.${V1}`,U1=Symbol.for(H1),W1,G1=class extends JU{constructor({chunkType:e,chunkId:t,message:n}){super({name:V1,message:n}),this[W1]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return JU.hasMarker(e,H1)}};W1=U1;var K1=VX([J(),wZ(Uint8Array),wZ(ArrayBuffer),xZ(e=>globalThis.Buffer?.isBuffer(e)??!1,{message:`Must be a Buffer`})]),q1=yZ(()=>VX([AX(),J(),wX(),OX(),qX(J(),q1.optional()),IX(q1)])),J1=qX(J(),qX(J(),q1.optional())),Y1=RX({type:ZX(`text`),text:J(),providerOptions:J1.optional()}),X1=RX({type:ZX(`image`),image:VX([K1,wZ(URL)]),mediaType:J().optional(),providerOptions:J1.optional()}),Z1=RX({type:ZX(`file`),data:VX([K1,wZ(URL)]),filename:J().optional(),mediaType:J(),providerOptions:J1.optional()}),Q1=RX({type:ZX(`reasoning`),text:J(),providerOptions:J1.optional()}),$1=RX({type:ZX(`tool-call`),toolCallId:J(),toolName:J(),input:MX(),providerOptions:J1.optional(),providerExecuted:OX().optional()}),e0=UX(`type`,[RX({type:ZX(`text`),value:J(),providerOptions:J1.optional()}),RX({type:ZX(`json`),value:q1,providerOptions:J1.optional()}),RX({type:ZX(`execution-denied`),reason:J().optional(),providerOptions:J1.optional()}),RX({type:ZX(`error-text`),value:J(),providerOptions:J1.optional()}),RX({type:ZX(`error-json`),value:q1,providerOptions:J1.optional()}),RX({type:ZX(`content`),value:IX(VX([RX({type:ZX(`text`),text:J(),providerOptions:J1.optional()}),RX({type:ZX(`media`),data:J(),mediaType:J()}),RX({type:ZX(`file-data`),data:J(),mediaType:J(),filename:J().optional(),providerOptions:J1.optional()}),RX({type:ZX(`file-url`),url:J(),providerOptions:J1.optional()}),RX({type:ZX(`file-id`),fileId:VX([J(),qX(J(),J())]),providerOptions:J1.optional()}),RX({type:ZX(`image-data`),data:J(),mediaType:J(),providerOptions:J1.optional()}),RX({type:ZX(`image-url`),url:J(),providerOptions:J1.optional()}),RX({type:ZX(`image-file-id`),fileId:VX([J(),qX(J(),J())]),providerOptions:J1.optional()}),RX({type:ZX(`custom`),providerOptions:J1.optional()})]))})]),t0=RX({type:ZX(`tool-result`),toolCallId:J(),toolName:J(),output:e0,providerOptions:J1.optional()}),n0=RX({type:ZX(`tool-approval-request`),approvalId:J(),toolCallId:J()}),r0=RX({type:ZX(`tool-approval-response`),approvalId:J(),approved:OX(),reason:J().optional()});VX([RX({role:ZX(`system`),content:J(),providerOptions:J1.optional()}),RX({role:ZX(`user`),content:VX([J(),IX(VX([Y1,X1,Z1]))]),providerOptions:J1.optional()}),RX({role:ZX(`assistant`),content:VX([J(),IX(VX([Y1,Z1,Q1,$1,t0,n0]))]),providerOptions:J1.optional()}),RX({role:ZX(`tool`),content:IX(VX([t0,r0])),providerOptions:J1.optional()})]);function i0(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=i0(a,i):n[r]=i}return n}F1({},{array:()=>l0,choice:()=>u0,json:()=>d0,object:()=>c0,text:()=>s0});function a0(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s];switch(t[t.length-1]){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(c){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(c){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;break;case`INSIDE_NUMBER`:switch(c){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:s+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}return s}async function o0(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await j1({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await j1({text:a0(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var s0=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),c0=({schema:e,name:t,description:n})=>{let r=C1(e);return{name:`object`,responseFormat:N1(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await A1({value:n.value,schema:r});if(!i.success)throw new B1({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},l0=({element:e,name:t,description:n})=>{let r=C1(e);return{name:`array`,responseFormat:N1(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new B1({message:`No object generated: response did not match schema.`,cause:new pW({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let n of i.elements){let i=await A1({value:n,schema:r});if(!i.success)throw new B1({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return i.elements},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await A1({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},u0=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await j1({text:t});if(!r.success)throw new B1({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new B1({message:`No object generated: response did not match schema.`,cause:new pW({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await o0(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),d0=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});l$({prefix:`aitxt`,size:24}),TransformStream;var f0=b1(()=>O1(VX([zX({type:ZX(`text-start`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`text-delta`),id:J(),delta:J(),providerMetadata:J1.optional()}),zX({type:ZX(`text-end`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`error`),errorText:J()}),zX({type:ZX(`tool-input-start`),toolCallId:J(),toolName:J(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),title:J().optional()}),zX({type:ZX(`tool-input-delta`),toolCallId:J(),inputTextDelta:J()}),zX({type:ZX(`tool-input-available`),toolCallId:J(),toolName:J(),input:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),title:J().optional()}),zX({type:ZX(`tool-input-error`),toolCallId:J(),toolName:J(),input:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),errorText:J(),title:J().optional()}),zX({type:ZX(`tool-approval-request`),approvalId:J(),toolCallId:J()}),zX({type:ZX(`tool-output-available`),toolCallId:J(),output:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),preliminary:OX().optional()}),zX({type:ZX(`tool-output-error`),toolCallId:J(),errorText:J(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional()}),zX({type:ZX(`tool-output-denied`),toolCallId:J()}),zX({type:ZX(`reasoning-start`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`reasoning-delta`),id:J(),delta:J(),providerMetadata:J1.optional()}),zX({type:ZX(`reasoning-end`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`source-url`),sourceId:J(),url:J(),title:J().optional(),providerMetadata:J1.optional()}),zX({type:ZX(`source-document`),sourceId:J(),mediaType:J(),title:J(),filename:J().optional(),providerMetadata:J1.optional()}),zX({type:ZX(`file`),url:J(),mediaType:J(),providerMetadata:J1.optional()}),zX({type:xZ(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:J().optional(),data:MX(),transient:OX().optional()}),zX({type:ZX(`start-step`)}),zX({type:ZX(`finish-step`)}),zX({type:ZX(`start`),messageId:J().optional(),messageMetadata:MX().optional()}),zX({type:ZX(`finish`),finishReason:YX([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:MX().optional()}),zX({type:ZX(`abort`),reason:J().optional()}),zX({type:ZX(`message-metadata`),messageMetadata:MX()})])));function p0(e){return e.type.startsWith(`data-`)}function m0(e){return e.type===`text`}function h0(e){return e.type===`reasoning`}function g0(e){return e.type.startsWith(`tool-`)}function _0(e){return e.type===`dynamic-tool`}function v0(e){return g0(e)||_0(e)}function y0(e){return e.type.split(`-`).slice(1).join(`-`)}function b0(e){return _0(e)?e.toolName:y0(e)}function x0({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function S0({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(e){let t=r.message.parts.filter(v0).find(t=>t.toolCallId===e);if(t==null)throw new G1({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function u(e){let t=r.message.parts.find(t=>g0(t)&&t.toolCallId===e.toolCallId),n=e,i=t;if(t!=null){t.state=e.state,i.input=n.input,i.output=n.output,i.errorText=n.errorText,i.rawInput=n.rawInput,i.preliminary=n.preliminary,e.title!==void 0&&(i.title=e.title),i.providerExecuted=n.providerExecuted??t.providerExecuted;let r=n.providerMetadata;if(r!=null)if(e.state===`output-available`||e.state===`output-error`){let e=t;e.resultProviderMetadata=r}else t.callProviderMetadata=r}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,input:n.input,output:n.output,rawInput:n.rawInput,errorText:n.errorText,providerExecuted:n.providerExecuted,preliminary:n.preliminary,...n.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:n.providerMetadata}:{},...n.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:n.providerMetadata}:{}})}function d(e){let t=r.message.parts.find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),n=e,i=t;if(t!=null){t.state=e.state,i.toolName=e.toolName,i.input=n.input,i.output=n.output,i.errorText=n.errorText,i.rawInput=n.rawInput??i.rawInput,i.preliminary=n.preliminary,e.title!==void 0&&(i.title=e.title),i.providerExecuted=n.providerExecuted??t.providerExecuted;let r=n.providerMetadata;if(r!=null)if(e.state===`output-available`||e.state===`output-error`){let e=t;e.resultProviderMetadata=r}else t.callProviderMetadata=r}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:n.input,output:n.output,errorText:n.errorText,preliminary:n.preliminary,providerExecuted:n.providerExecuted,title:e.title,...n.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:n.providerMetadata}:{},...n.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:n.providerMetadata}:{}})}async function f(e){if(e!=null){let n=r.message.metadata==null?e:i0(r.message.metadata,e);t!=null&&await k1({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new G1({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new G1({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new G1({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new G1({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:r.message.parts.push({type:`file`,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=r.message.parts.filter(g0);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title},e.dynamic?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new G1({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await o0(t.text);t.dynamic?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title}):u({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title}),c();break}case`tool-input-available`:e.dynamic?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=r.message.parts.filter(v0).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c();break}case`tool-approval-request`:{let t=l(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId},c();break}case`tool-output-denied`:{let t=l(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}):u({toolCallId:e.toolCallId,toolName:y0(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title}),c();break}case`tool-output-error`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}):u({toolCallId:e.toolCallId,toolName:y0(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts={},r.activeReasoningParts={};break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await f(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await f(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await f(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(p0(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await k1({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function C0({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}l$({prefix:`aitxt`,size:24}),l$({prefix:`aiobj`,size:24});var w0=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};l$({prefix:`aiobj`,size:24});async function T0(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error(`FileList is not supported in the current environment`);return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}var E0=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await N1(this.body),r=await N1(this.headers),i=await N1(this.credentials),a={...d$(r),...d$(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:d$(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"Content-Type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw Error(await d.text()??`Failed to fetch the chat response.`);if(!d.body)throw Error(`The response body is empty.`);return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await N1(this.body),n=await N1(this.headers),r=await N1(this.credentials),i={...d$(n),...d$(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??`${this.api}/${e.chatId}/stream`,s=a?.headers===void 0?i:d$(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c});if(l.status===204)return null;if(!l.ok)throw Error(await l.text()??`Failed to fetch the chat response.`);if(!l.body)throw Error(`The response body is empty.`);return this.processResponseStream(l.body)}},D0=class extends E0{constructor(e={}){super(e)}processResponseStream(e){return M1({stream:e,schema:f0}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},O0=class{constructor({generateId:e=u$,id:t=e(),transport:n=new D0,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new w0,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(n=`text`in e||`files`in e?{parts:[...Array.isArray(e.files)?e.files:await T0(e.files),...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}:e,e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw Error(`message with id ${e.messageId} not found`);if(this.state.messages[t].role!==`user`)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...n,id:e.messageId,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>v0(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>v0(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{this.status!==`streaming`&&this.status!==`submitted`||this.activeResponse?.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a;let o;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(e==null)return;o=e}catch(e){this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e});return}this.setStatus({status:`submitted`,error:void 0});let s=this.lastMessage,c=!1,l=!1,u=!1;try{let a={state:x0({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};a.abortController.signal.addEventListener(`abort`,()=>{c=!0}),this.activeResponse=a;let l;l=e===`resume-stream`?o:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await C0({stream:S0({stream:l,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>e({state:a.state,write:()=>{this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message)}})),onError:e=>{throw e}}),onError:e=>{throw e}}),this.setStatus({status:`ready`})}catch(e){if(c||e.name===`AbortError`)return c=!0,this.setStatus({status:`ready`}),null;u=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(l=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{(a=this.onFinish)==null||a.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:this.activeResponse?.state.finishReason})}catch(e){console.error(e)}this.activeResponse=void 0}!u&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function k0(e,t){switch(t.type){case`text-start`:return e.push({type:`text`,text:``,state:`streaming`}),!0;case`text-delta`:{let n=A0(e,`text`);return n&&n.type===`text`?n.text+=t.delta??``:e.push({type:`text`,text:t.delta??``,state:`streaming`}),!0}case`text-end`:{let t=A0(e,`text`);return t&&`state`in t&&(t.state=`done`),!0}case`reasoning-start`:return e.push({type:`reasoning`,text:``,state:`streaming`}),!0;case`reasoning-delta`:{let n=A0(e,`reasoning`);return n&&n.type===`reasoning`?n.text+=t.delta??``:e.push({type:`reasoning`,text:t.delta??``,state:`streaming`}),!0}case`reasoning-end`:{let t=A0(e,`reasoning`);return t&&`state`in t&&(t.state=`done`),!0}case`file`:return e.push({type:`file`,mediaType:t.mediaType,url:t.url}),!0;case`source-url`:return e.push({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title,providerMetadata:t.providerMetadata}),!0;case`source-document`:return e.push({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename,providerMetadata:t.providerMetadata}),!0;case`tool-input-start`:return e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`input-streaming`,input:void 0,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata},...t.title==null?{}:{title:t.title}}),!0;case`tool-input-delta`:{let n=j0(e,t.toolCallId);return n&&(n.input=t.input),!0}case`tool-input-available`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`input-available`,e.input=t.input,t.providerExecuted!=null&&(e.providerExecuted=t.providerExecuted),t.providerMetadata!=null&&(e.callProviderMetadata=t.providerMetadata),t.title!=null&&(e.title=t.title)}else e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`input-available`,input:t.input,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata},...t.title==null?{}:{title:t.title}});return!0}case`tool-input-error`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-error`,e.errorText=t.errorText,e.input=t.input,t.providerExecuted!=null&&(e.providerExecuted=t.providerExecuted),t.providerMetadata!=null&&(e.callProviderMetadata=t.providerMetadata)}else e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:t.errorText,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata}});return!0}case`tool-approval-request`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`approval-requested`,e.approval={id:t.approvalId}}return!0}case`tool-output-denied`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-denied`}return!0}case`tool-output-available`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-available`,e.output=t.output,t.preliminary!==void 0&&(e.preliminary=t.preliminary)}return!0}case`tool-output-error`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-error`,e.errorText=t.errorText}return!0}case`step-start`:case`start-step`:return e.push({type:`step-start`}),!0;default:if(t.type.startsWith(`data-`)){if(t.transient)return!0;if(t.id!=null){let n=M0(e,t.type,t.id);if(n)return n.data=t.data,!0}return e.push({type:t.type,...t.id!=null&&{id:t.id},data:t.data}),!0}return!1}}function A0(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].type===t)return e[n]}function j0(e,t){if(t)for(let n=e.length-1;n>=0;n--){let r=e[n];if(`toolCallId`in r&&r.toolCallId===t)return r}}function M0(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.type===t&&`id`in i&&i.id===n)return i}}new TextEncoder;function N0(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}var P0=class{constructor(e){this.messageId=e.messageId,this._isContinuation=e.continuation??!1,this.parts=e.existingParts?[...e.existingParts]:[],this.metadata=e.existingMetadata?{...e.existingMetadata}:void 0}applyChunk(e){let t=k0(this.parts,e);if(e.type===`tool-approval-request`&&e.toolCallId)return{handled:t,action:{type:`tool-approval-request`,toolCallId:e.toolCallId}};if((e.type===`tool-output-available`||e.type===`tool-output-error`)&&e.toolCallId&&!this.parts.some(t=>`toolCallId`in t&&t.toolCallId===e.toolCallId))return{handled:t,action:{type:`cross-message-tool-update`,updateType:e.type===`tool-output-available`?`output-available`:`output-error`,toolCallId:e.toolCallId,output:e.output,errorText:e.errorText,preliminary:e.preliminary}};if(!t)switch(e.type){case`start`:{e.messageId!=null&&!this._isContinuation&&(this.messageId=e.messageId);let t=N0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`start`,messageId:e.messageId,metadata:t}}}case`finish`:{let t=N0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`finish`,finishReason:`finishReason`in e?e.finishReason:void 0,metadata:t}}}case`message-metadata`:{let t=N0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`message-metadata`,metadata:t??{}}}}case`finish-step`:return{handled:!0};case`error`:return{handled:!0,action:{type:`error`,error:e.errorText??JSON.stringify(e)}}}return{handled:t}}toMessage(){return{id:this.messageId,role:`assistant`,parts:[...this.parts],...this.metadata!=null&&{metadata:this.metadata}}}mergeInto(e){let t=e.findIndex(e=>e.id===this.messageId);if(t<0&&this._isContinuation){for(let n=e.length-1;n>=0;n--)if(e[n].role===`assistant`){t=n;break}}let n={id:t>=0?e[t].id:this.messageId,role:`assistant`,parts:[...this.parts],...this.metadata!=null&&{metadata:this.metadata}};if(t>=0){let r=[...e];return r[t]=n,r}return[...e,n]}};function F0(e,t){switch(t.type){case`clear`:return{state:{status:`idle`},isStreaming:!1};case`resume-fallback`:{let e=new P0({messageId:t.messageId});return{state:{status:`observing`,streamId:t.streamId,accumulator:e},isStreaming:!0}}case`response`:{let n;if(e.status===`idle`||e.streamId!==t.streamId){let e=t.messageId,r,i;if(t.continuation&&t.currentMessages){for(let n=t.currentMessages.length-1;n>=0;n--)if(t.currentMessages[n].role===`assistant`){e=t.currentMessages[n].id,r=[...t.currentMessages[n].parts],t.currentMessages[n].metadata!=null&&(i={...t.currentMessages[n].metadata});break}}n=new P0({messageId:e,continuation:t.continuation,existingParts:r,existingMetadata:i})}else n=e.accumulator;t.chunkData&&n.applyChunk(t.chunkData);let r;return t.done?(r=e=>n.mergeInto(e),{state:{status:`idle`},messagesUpdate:r,isStreaming:!1}):((t.chunkData&&!t.replay||t.replayComplete)&&(r=e=>n.mergeInto(e)),{state:{status:`observing`,streamId:t.streamId,accumulator:n},messagesUpdate:r,isStreaming:!0})}}}var I0={CHAT_MESSAGES:`cf_agent_chat_messages`,USE_CHAT_REQUEST:`cf_agent_use_chat_request`,USE_CHAT_RESPONSE:`cf_agent_use_chat_response`,CHAT_CLEAR:`cf_agent_chat_clear`,CHAT_REQUEST_CANCEL:`cf_agent_chat_request_cancel`,STREAM_RESUMING:`cf_agent_stream_resuming`,STREAM_RESUME_ACK:`cf_agent_stream_resume_ack`,STREAM_RESUME_REQUEST:`cf_agent_stream_resume_request`,STREAM_RESUME_NONE:`cf_agent_stream_resume_none`,TOOL_RESULT:`cf_agent_tool_result`,TOOL_APPROVAL:`cf_agent_tool_approval`,MESSAGE_UPDATED:`cf_agent_message_updated`},L0=10,R0=100,z0=600*1e3,B0=1440*60*1e3,V0=new TextEncoder,H0=class e{constructor(e){this.sql=e,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0,this._isLive=!1,this._chunkBuffer=[],this._isFlushingChunks=!1,this._lastCleanupTime=0,this.sql`create table if not exists cf_ai_chat_stream_chunks (
|
|
238
|
+
]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function G$(e,t){let n={type:`object`,additionalProperties:m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=R$(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=E$(e.keyType._def,t);return{...n,propertyNames:i}}return n}function K$(e,t){return t.mapStrategy===`record`?G$(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[m1(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||S$(),m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||S$()],minItems:2,maxItems:2}}}function q$(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function J$(){return{not:S$()}}function Y$(){return{type:`null`}}var X$={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Z$(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in X$&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=X$[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Q$(e,t)}var Q$=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function $$(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[X$[e.innerType._def.typeName],`null`]};let n=m1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function e1(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function t1(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=r1(a),s=m1(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=n1(e,t);return a!==void 0&&(n.additionalProperties=a),n}function n1(e,t){if(e.catchall._def.typeName!==`ZodNever`)return m1(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function r1(e){try{return e.isOptional()}catch{return!0}}var i1=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return m1(e.innerType._def,t);let n=m1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:S$()},n]}:S$()},a1=(e,t)=>{if(t.pipeStrategy===`input`)return m1(e.in._def,t);if(t.pipeStrategy===`output`)return m1(e.out._def,t);let n=m1(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,m1(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function o1(e,t){return m1(e.type._def,t)}function s1(e,t){let n={type:`array`,uniqueItems:!0,items:m1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function c1(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:m1(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>m1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function l1(){return{not:S$()}}function u1(){return S$()}var d1=(e,t)=>m1(e.innerType._def,t),f1=(e,t,n)=>{switch(t){case $.ZodString:return R$(e,n);case $.ZodNumber:return e1(e);case $.ZodObject:return t1(e,n);case $.ZodBigInt:return w$(e);case $.ZodBoolean:return T$();case $.ZodDate:return O$(e,n);case $.ZodUndefined:return l1();case $.ZodNull:return Y$();case $.ZodArray:return C$(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Z$(e,n);case $.ZodIntersection:return P$(e,n);case $.ZodTuple:return c1(e,n);case $.ZodRecord:return G$(e,n);case $.ZodLiteral:return F$(e);case $.ZodEnum:return M$(e);case $.ZodNativeEnum:return q$(e);case $.ZodNullable:return $$(e,n);case $.ZodOptional:return i1(e,n);case $.ZodMap:return K$(e,n);case $.ZodSet:return s1(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return o1(e,n);case $.ZodNaN:case $.ZodNever:return J$();case $.ZodEffects:return j$(e,n);case $.ZodAny:return S$();case $.ZodUnknown:return u1();case $.ZodDefault:return A$(e,n);case $.ZodBranded:return E$(e,n);case $.ZodReadonly:return d1(e,n);case $.ZodCatch:return D$(e,n);case $.ZodPipeline:return a1(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}},p1=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function m1(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==y$)return i}if(r&&!n){let e=h1(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=f1(e,e.typeName,t),o=typeof a==`function`?m1(a(),t):a;if(o&&g1(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var h1=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:p1(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),S$()):t.$refStrategy===`seen`?S$():void 0}},g1=(e,t,n)=>(e.description&&(n.description=e.description),n),_1=e=>{let t=x$(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},v1=(e,t)=>{let n=_1(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:m1(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??S$()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=m1(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??S$(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},y1=Symbol.for(`vercel.ai.schema`);function b1(e){let t;return()=>(t??=e(),t)}function x1(e,{validate:t}={}){return{[y1]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function S1(e){return typeof e==`object`&&!!e&&y1 in e&&e[y1]===!0&&`jsonSchema`in e&&`validate`in e}function C1(e){return e==null?x1({properties:{},additionalProperties:!1}):S1(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?O1(e):w1(e):e()}function w1(e){return x1(()=>_$(e[`~standard`].jsonSchema.input({target:`draft-07`})),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new pW({value:t,cause:n.issues})}}})}function T1(e,t){let n=t?.useReferences??!1;return x1(()=>v1(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function E1(e,t){let n=t?.useReferences??!1;return x1(()=>_$(jY(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await GY(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function D1(e){return`_zod`in e}function O1(e,t){return D1(e)?E1(e,t):T1(e,t)}async function k1({value:e,schema:t,context:n}){let r=await A1({value:e,schema:t,context:n});if(!r.success)throw pW.wrap({value:e,cause:r.error,context:n});return r.value}async function A1({value:e,schema:t,context:n}){let r=C1(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:pW.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:pW.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function j1({text:e,schema:t}){try{let n=g$(e);return t==null?{success:!0,value:n,rawValue:n}:await A1({value:n,schema:t})}catch(t){return{success:!1,error:sW.isInstance(t)?t:new sW({text:e,cause:t}),rawValue:void 0}}}function M1({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new o$).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await j1({text:e,schema:t}))}}))}async function N1(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var P1=Object.defineProperty,F1=(e,t)=>{for(var n in t)P1(e,n,{get:t[n],enumerable:!0})},I1=`AI_NoObjectGeneratedError`,L1=`vercel.ai.error.${I1}`,R1=Symbol.for(L1),z1,B1=class extends JU{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:I1,message:e,cause:t}),this[z1]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return JU.hasMarker(e,L1)}};z1=R1;var V1=`AI_UIMessageStreamError`,H1=`vercel.ai.error.${V1}`,U1=Symbol.for(H1),W1,G1=class extends JU{constructor({chunkType:e,chunkId:t,message:n}){super({name:V1,message:n}),this[W1]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return JU.hasMarker(e,H1)}};W1=U1;var K1=VX([J(),wZ(Uint8Array),wZ(ArrayBuffer),xZ(e=>globalThis.Buffer?.isBuffer(e)??!1,{message:`Must be a Buffer`})]),q1=yZ(()=>VX([AX(),J(),wX(),OX(),qX(J(),q1.optional()),IX(q1)])),J1=qX(J(),qX(J(),q1.optional())),Y1=RX({type:ZX(`text`),text:J(),providerOptions:J1.optional()}),X1=RX({type:ZX(`image`),image:VX([K1,wZ(URL)]),mediaType:J().optional(),providerOptions:J1.optional()}),Z1=RX({type:ZX(`file`),data:VX([K1,wZ(URL)]),filename:J().optional(),mediaType:J(),providerOptions:J1.optional()}),Q1=RX({type:ZX(`reasoning`),text:J(),providerOptions:J1.optional()}),$1=RX({type:ZX(`tool-call`),toolCallId:J(),toolName:J(),input:MX(),providerOptions:J1.optional(),providerExecuted:OX().optional()}),e0=UX(`type`,[RX({type:ZX(`text`),value:J(),providerOptions:J1.optional()}),RX({type:ZX(`json`),value:q1,providerOptions:J1.optional()}),RX({type:ZX(`execution-denied`),reason:J().optional(),providerOptions:J1.optional()}),RX({type:ZX(`error-text`),value:J(),providerOptions:J1.optional()}),RX({type:ZX(`error-json`),value:q1,providerOptions:J1.optional()}),RX({type:ZX(`content`),value:IX(VX([RX({type:ZX(`text`),text:J(),providerOptions:J1.optional()}),RX({type:ZX(`media`),data:J(),mediaType:J()}),RX({type:ZX(`file-data`),data:J(),mediaType:J(),filename:J().optional(),providerOptions:J1.optional()}),RX({type:ZX(`file-url`),url:J(),providerOptions:J1.optional()}),RX({type:ZX(`file-id`),fileId:VX([J(),qX(J(),J())]),providerOptions:J1.optional()}),RX({type:ZX(`image-data`),data:J(),mediaType:J(),providerOptions:J1.optional()}),RX({type:ZX(`image-url`),url:J(),providerOptions:J1.optional()}),RX({type:ZX(`image-file-id`),fileId:VX([J(),qX(J(),J())]),providerOptions:J1.optional()}),RX({type:ZX(`custom`),providerOptions:J1.optional()})]))})]),t0=RX({type:ZX(`tool-result`),toolCallId:J(),toolName:J(),output:e0,providerOptions:J1.optional()}),n0=RX({type:ZX(`tool-approval-request`),approvalId:J(),toolCallId:J()}),r0=RX({type:ZX(`tool-approval-response`),approvalId:J(),approved:OX(),reason:J().optional()});VX([RX({role:ZX(`system`),content:J(),providerOptions:J1.optional()}),RX({role:ZX(`user`),content:VX([J(),IX(VX([Y1,X1,Z1]))]),providerOptions:J1.optional()}),RX({role:ZX(`assistant`),content:VX([J(),IX(VX([Y1,Z1,Q1,$1,t0,n0]))]),providerOptions:J1.optional()}),RX({role:ZX(`tool`),content:IX(VX([t0,r0])),providerOptions:J1.optional()})]);function i0(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=i0(a,i):n[r]=i}return n}F1({},{array:()=>l0,choice:()=>u0,json:()=>d0,object:()=>c0,text:()=>s0});function a0(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s];switch(t[t.length-1]){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(c){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(c){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;break;case`INSIDE_NUMBER`:switch(c){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:s+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}return s}async function o0(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await j1({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await j1({text:a0(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var s0=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),c0=({schema:e,name:t,description:n})=>{let r=C1(e);return{name:`object`,responseFormat:N1(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await A1({value:n.value,schema:r});if(!i.success)throw new B1({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},l0=({element:e,name:t,description:n})=>{let r=C1(e);return{name:`array`,responseFormat:N1(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new B1({message:`No object generated: response did not match schema.`,cause:new pW({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let n of i.elements){let i=await A1({value:n,schema:r});if(!i.success)throw new B1({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return i.elements},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await A1({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},u0=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await j1({text:t});if(!r.success)throw new B1({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new B1({message:`No object generated: response did not match schema.`,cause:new pW({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await o0(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),d0=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await j1({text:e});if(!n.success)throw new B1({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await o0(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});l$({prefix:`aitxt`,size:24}),TransformStream;var f0=b1(()=>O1(VX([zX({type:ZX(`text-start`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`text-delta`),id:J(),delta:J(),providerMetadata:J1.optional()}),zX({type:ZX(`text-end`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`error`),errorText:J()}),zX({type:ZX(`tool-input-start`),toolCallId:J(),toolName:J(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),title:J().optional()}),zX({type:ZX(`tool-input-delta`),toolCallId:J(),inputTextDelta:J()}),zX({type:ZX(`tool-input-available`),toolCallId:J(),toolName:J(),input:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),title:J().optional()}),zX({type:ZX(`tool-input-error`),toolCallId:J(),toolName:J(),input:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),errorText:J(),title:J().optional()}),zX({type:ZX(`tool-approval-request`),approvalId:J(),toolCallId:J()}),zX({type:ZX(`tool-output-available`),toolCallId:J(),output:MX(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional(),preliminary:OX().optional()}),zX({type:ZX(`tool-output-error`),toolCallId:J(),errorText:J(),providerExecuted:OX().optional(),providerMetadata:J1.optional(),dynamic:OX().optional()}),zX({type:ZX(`tool-output-denied`),toolCallId:J()}),zX({type:ZX(`reasoning-start`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`reasoning-delta`),id:J(),delta:J(),providerMetadata:J1.optional()}),zX({type:ZX(`reasoning-end`),id:J(),providerMetadata:J1.optional()}),zX({type:ZX(`source-url`),sourceId:J(),url:J(),title:J().optional(),providerMetadata:J1.optional()}),zX({type:ZX(`source-document`),sourceId:J(),mediaType:J(),title:J(),filename:J().optional(),providerMetadata:J1.optional()}),zX({type:ZX(`file`),url:J(),mediaType:J(),providerMetadata:J1.optional()}),zX({type:xZ(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:J().optional(),data:MX(),transient:OX().optional()}),zX({type:ZX(`start-step`)}),zX({type:ZX(`finish-step`)}),zX({type:ZX(`start`),messageId:J().optional(),messageMetadata:MX().optional()}),zX({type:ZX(`finish`),finishReason:YX([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:MX().optional()}),zX({type:ZX(`abort`),reason:J().optional()}),zX({type:ZX(`message-metadata`),messageMetadata:MX()})])));function p0(e){return e.type.startsWith(`data-`)}function m0(e){return e.type===`text`}function h0(e){return e.type===`reasoning`}function g0(e){return e.type.startsWith(`tool-`)}function _0(e){return e.type===`dynamic-tool`}function v0(e){return g0(e)||_0(e)}function y0(e){return e.type.split(`-`).slice(1).join(`-`)}function b0(e){return _0(e)?e.toolName:y0(e)}function x0({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function S0({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(e){let t=r.message.parts.filter(v0).find(t=>t.toolCallId===e);if(t==null)throw new G1({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function u(e){let t=r.message.parts.find(t=>g0(t)&&t.toolCallId===e.toolCallId),n=e,i=t;if(t!=null){t.state=e.state,i.input=n.input,i.output=n.output,i.errorText=n.errorText,i.rawInput=n.rawInput,i.preliminary=n.preliminary,e.title!==void 0&&(i.title=e.title),i.providerExecuted=n.providerExecuted??t.providerExecuted;let r=n.providerMetadata;if(r!=null)if(e.state===`output-available`||e.state===`output-error`){let e=t;e.resultProviderMetadata=r}else t.callProviderMetadata=r}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,input:n.input,output:n.output,rawInput:n.rawInput,errorText:n.errorText,providerExecuted:n.providerExecuted,preliminary:n.preliminary,...n.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:n.providerMetadata}:{},...n.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:n.providerMetadata}:{}})}function d(e){let t=r.message.parts.find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),n=e,i=t;if(t!=null){t.state=e.state,i.toolName=e.toolName,i.input=n.input,i.output=n.output,i.errorText=n.errorText,i.rawInput=n.rawInput??i.rawInput,i.preliminary=n.preliminary,e.title!==void 0&&(i.title=e.title),i.providerExecuted=n.providerExecuted??t.providerExecuted;let r=n.providerMetadata;if(r!=null)if(e.state===`output-available`||e.state===`output-error`){let e=t;e.resultProviderMetadata=r}else t.callProviderMetadata=r}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:n.input,output:n.output,errorText:n.errorText,preliminary:n.preliminary,providerExecuted:n.providerExecuted,title:e.title,...n.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:n.providerMetadata}:{},...n.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:n.providerMetadata}:{}})}async function f(e){if(e!=null){let n=r.message.metadata==null?e:i0(r.message.metadata,e);t!=null&&await k1({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new G1({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new G1({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new G1({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new G1({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:r.message.parts.push({type:`file`,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=r.message.parts.filter(g0);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title},e.dynamic?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new G1({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await o0(t.text);t.dynamic?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title}):u({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title}),c();break}case`tool-input-available`:e.dynamic?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=r.message.parts.filter(v0).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?d({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}):u({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c();break}case`tool-approval-request`:{let t=l(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId},c();break}case`tool-output-denied`:{let t=l(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}):u({toolCallId:e.toolCallId,toolName:y0(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title}),c();break}case`tool-output-error`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?d({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}):u({toolCallId:e.toolCallId,toolName:y0(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title}),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts={},r.activeReasoningParts={};break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await f(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await f(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await f(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(p0(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await k1({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function C0({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}l$({prefix:`aitxt`,size:24}),l$({prefix:`aiobj`,size:24});var w0=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};l$({prefix:`aiobj`,size:24});async function T0(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error(`FileList is not supported in the current environment`);return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}var E0=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await N1(this.body),r=await N1(this.headers),i=await N1(this.credentials),a={...d$(r),...d$(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:d$(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"Content-Type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw Error(await d.text()??`Failed to fetch the chat response.`);if(!d.body)throw Error(`The response body is empty.`);return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await N1(this.body),n=await N1(this.headers),r=await N1(this.credentials),i={...d$(n),...d$(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??`${this.api}/${e.chatId}/stream`,s=a?.headers===void 0?i:d$(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c});if(l.status===204)return null;if(!l.ok)throw Error(await l.text()??`Failed to fetch the chat response.`);if(!l.body)throw Error(`The response body is empty.`);return this.processResponseStream(l.body)}},D0=class extends E0{constructor(e={}){super(e)}processResponseStream(e){return M1({stream:e,schema:f0}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},O0=class{constructor({generateId:e=u$,id:t=e(),transport:n=new D0,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new w0,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(n=`text`in e||`files`in e?{parts:[...Array.isArray(e.files)?e.files:await T0(e.files),...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}:e,e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw Error(`message with id ${e.messageId} not found`);if(this.state.messages[t].role!==`user`)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...n,id:e.messageId,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>v0(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>v0(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{this.status!==`streaming`&&this.status!==`submitted`||this.activeResponse?.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a;let o;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(e==null)return;o=e}catch(e){this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e});return}this.setStatus({status:`submitted`,error:void 0});let s=this.lastMessage,c=!1,l=!1,u=!1;try{let a={state:x0({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};a.abortController.signal.addEventListener(`abort`,()=>{c=!0}),this.activeResponse=a;let l;l=e===`resume-stream`?o:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await C0({stream:S0({stream:l,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>e({state:a.state,write:()=>{this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message)}})),onError:e=>{throw e}}),onError:e=>{throw e}}),this.setStatus({status:`ready`})}catch(e){if(c||e.name===`AbortError`)return c=!0,this.setStatus({status:`ready`}),null;u=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(l=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{(a=this.onFinish)==null||a.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:this.activeResponse?.state.finishReason})}catch(e){console.error(e)}this.activeResponse=void 0}!u&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function k0(e,t){switch(t.type){case`text-start`:return e.push({type:`text`,text:``,state:`streaming`}),!0;case`text-delta`:{let n=A0(e,`text`);return n&&n.type===`text`?n.text+=t.delta??``:e.push({type:`text`,text:t.delta??``,state:`streaming`}),!0}case`text-end`:{let t=A0(e,`text`);return t&&`state`in t&&(t.state=`done`),!0}case`reasoning-start`:return e.push({type:`reasoning`,text:``,state:`streaming`}),!0;case`reasoning-delta`:{let n=A0(e,`reasoning`);return n&&n.type===`reasoning`?(n.text+=t.delta??``,M0(n,t.providerMetadata)):e.push({type:`reasoning`,text:t.delta??``,state:`streaming`,...t.providerMetadata==null?{}:{providerMetadata:t.providerMetadata}}),!0}case`reasoning-end`:{let n=A0(e,`reasoning`);return n&&`state`in n&&(n.state=`done`,M0(n,t.providerMetadata)),!0}case`file`:return e.push({type:`file`,mediaType:t.mediaType,url:t.url}),!0;case`source-url`:return e.push({type:`source-url`,sourceId:t.sourceId,url:t.url,title:t.title,providerMetadata:t.providerMetadata}),!0;case`source-document`:return e.push({type:`source-document`,sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename,providerMetadata:t.providerMetadata}),!0;case`tool-input-start`:return e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`input-streaming`,input:void 0,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata},...t.title==null?{}:{title:t.title}}),!0;case`tool-input-delta`:{let n=j0(e,t.toolCallId);return n&&(n.input=t.input),!0}case`tool-input-available`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`input-available`,e.input=t.input,t.providerExecuted!=null&&(e.providerExecuted=t.providerExecuted),t.providerMetadata!=null&&(e.callProviderMetadata=t.providerMetadata),t.title!=null&&(e.title=t.title)}else e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`input-available`,input:t.input,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata},...t.title==null?{}:{title:t.title}});return!0}case`tool-input-error`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-error`,e.errorText=t.errorText,e.input=t.input,t.providerExecuted!=null&&(e.providerExecuted=t.providerExecuted),t.providerMetadata!=null&&(e.callProviderMetadata=t.providerMetadata)}else e.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:t.errorText,...t.providerExecuted==null?{}:{providerExecuted:t.providerExecuted},...t.providerMetadata==null?{}:{callProviderMetadata:t.providerMetadata}});return!0}case`tool-approval-request`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`approval-requested`,e.approval={id:t.approvalId}}return!0}case`tool-output-denied`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-denied`}return!0}case`tool-output-available`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-available`,e.output=t.output,t.preliminary!==void 0&&(e.preliminary=t.preliminary)}return!0}case`tool-output-error`:{let n=j0(e,t.toolCallId);if(n){let e=n;e.state=`output-error`,e.errorText=t.errorText}return!0}case`step-start`:case`start-step`:return e.push({type:`step-start`}),!0;default:if(t.type.startsWith(`data-`)){if(t.transient)return!0;if(t.id!=null){let n=N0(e,t.type,t.id);if(n)return n.data=t.data,!0}return e.push({type:t.type,...t.id!=null&&{id:t.id},data:t.data}),!0}return!1}}function A0(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].type===t)return e[n]}function j0(e,t){if(t)for(let n=e.length-1;n>=0;n--){let r=e[n];if(`toolCallId`in r&&r.toolCallId===t)return r}}function M0(e,t){if(t==null)return;let n=e;n.providerMetadata={...n.providerMetadata,...t}}function N0(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.type===t&&`id`in i&&i.id===n)return i}}new TextEncoder;function P0(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}var F0=class{constructor(e){this.messageId=e.messageId,this._isContinuation=e.continuation??!1,this.parts=e.existingParts?[...e.existingParts]:[],this.metadata=e.existingMetadata?{...e.existingMetadata}:void 0}applyChunk(e){let t=k0(this.parts,e);if(e.type===`tool-approval-request`&&e.toolCallId)return{handled:t,action:{type:`tool-approval-request`,toolCallId:e.toolCallId}};if((e.type===`tool-output-available`||e.type===`tool-output-error`)&&e.toolCallId&&!this.parts.some(t=>`toolCallId`in t&&t.toolCallId===e.toolCallId))return{handled:t,action:{type:`cross-message-tool-update`,updateType:e.type===`tool-output-available`?`output-available`:`output-error`,toolCallId:e.toolCallId,output:e.output,errorText:e.errorText,preliminary:e.preliminary}};if(!t)switch(e.type){case`start`:{e.messageId!=null&&!this._isContinuation&&(this.messageId=e.messageId);let t=P0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`start`,messageId:e.messageId,metadata:t}}}case`finish`:{let t=P0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`finish`,finishReason:`finishReason`in e?e.finishReason:void 0,metadata:t}}}case`message-metadata`:{let t=P0(e.messageMetadata);return t&&(this.metadata=this.metadata?{...this.metadata,...t}:{...t}),{handled:!0,action:{type:`message-metadata`,metadata:t??{}}}}case`finish-step`:return{handled:!0};case`error`:return{handled:!0,action:{type:`error`,error:e.errorText??JSON.stringify(e)}}}return{handled:t}}toMessage(){return{id:this.messageId,role:`assistant`,parts:[...this.parts],...this.metadata!=null&&{metadata:this.metadata}}}mergeInto(e){let t=e.findIndex(e=>e.id===this.messageId);if(t<0&&this._isContinuation){for(let n=e.length-1;n>=0;n--)if(e[n].role===`assistant`){t=n;break}}let n={id:t>=0?e[t].id:this.messageId,role:`assistant`,parts:[...this.parts],...this.metadata!=null&&{metadata:this.metadata}};if(t>=0){let r=[...e];return r[t]=n,r}return[...e,n]}};function I0(e,t){switch(t.type){case`clear`:return{state:{status:`idle`},isStreaming:!1};case`resume-fallback`:{let e=new F0({messageId:t.messageId});return{state:{status:`observing`,streamId:t.streamId,accumulator:e},isStreaming:!0}}case`response`:{let n;if(e.status===`idle`||e.streamId!==t.streamId){let e=t.messageId,r,i;if(t.continuation&&t.currentMessages){for(let n=t.currentMessages.length-1;n>=0;n--)if(t.currentMessages[n].role===`assistant`){e=t.currentMessages[n].id,r=[...t.currentMessages[n].parts],t.currentMessages[n].metadata!=null&&(i={...t.currentMessages[n].metadata});break}}n=new F0({messageId:e,continuation:t.continuation,existingParts:r,existingMetadata:i})}else n=e.accumulator;t.chunkData&&n.applyChunk(t.chunkData);let r;return t.done?(r=e=>n.mergeInto(e),{state:{status:`idle`},messagesUpdate:r,isStreaming:!1}):((t.chunkData&&!t.replay||t.replayComplete)&&(r=e=>n.mergeInto(e)),{state:{status:`observing`,streamId:t.streamId,accumulator:n},messagesUpdate:r,isStreaming:!0})}}}var L0={CHAT_MESSAGES:`cf_agent_chat_messages`,USE_CHAT_REQUEST:`cf_agent_use_chat_request`,USE_CHAT_RESPONSE:`cf_agent_use_chat_response`,CHAT_CLEAR:`cf_agent_chat_clear`,CHAT_REQUEST_CANCEL:`cf_agent_chat_request_cancel`,STREAM_RESUMING:`cf_agent_stream_resuming`,STREAM_RESUME_ACK:`cf_agent_stream_resume_ack`,STREAM_RESUME_REQUEST:`cf_agent_stream_resume_request`,STREAM_RESUME_NONE:`cf_agent_stream_resume_none`,TOOL_RESULT:`cf_agent_tool_result`,TOOL_APPROVAL:`cf_agent_tool_approval`,MESSAGE_UPDATED:`cf_agent_message_updated`},R0=10,z0=100,B0=600*1e3,V0=1440*60*1e3,H0=new TextEncoder,U0=class e{constructor(e){this.sql=e,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0,this._isLive=!1,this._chunkBuffer=[],this._isFlushingChunks=!1,this._lastCleanupTime=0,this.sql`create table if not exists cf_ai_chat_stream_chunks (
|
|
239
239
|
id text primary key,
|
|
240
240
|
stream_id text not null,
|
|
241
241
|
body text not null,
|
|
@@ -259,14 +259,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
259
259
|
update cf_ai_chat_stream_metadata
|
|
260
260
|
set status = 'error', completed_at = ${Date.now()}
|
|
261
261
|
where id = ${e}
|
|
262
|
-
`,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0,this._isLive=!1}storeChunk(t,n){let r=
|
|
262
|
+
`,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0,this._isLive=!1}storeChunk(t,n){let r=H0.encode(n).byteLength;if(r>e.CHUNK_MAX_BYTES){console.warn(`[ResumableStream] Skipping oversized chunk (${r} bytes) to prevent SQLite row limit crash. Live clients still receive it.`);return}this._chunkBuffer.length>=z0&&this.flushBuffer(),this._chunkBuffer.push({id:UU(),streamId:t,body:n,index:this._streamChunkIndex}),this._streamChunkIndex++,this._chunkBuffer.length>=R0&&this.flushBuffer()}flushBuffer(){if(!(this._isFlushingChunks||this._chunkBuffer.length===0)){this._isFlushingChunks=!0;try{let e=this._chunkBuffer;this._chunkBuffer=[];let t=Date.now();for(let n of e)this.sql`
|
|
263
263
|
insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
|
|
264
264
|
values (${n.id}, ${n.streamId}, ${n.body}, ${n.index}, ${t})
|
|
265
265
|
`}finally{this._isFlushingChunks=!1}}}replayChunks(e,t){let n=this._activeStreamId;if(!n)return null;this.flushBuffer();let r=this.sql`
|
|
266
266
|
select * from cf_ai_chat_stream_chunks
|
|
267
267
|
where stream_id = ${n}
|
|
268
268
|
order by chunk_index asc
|
|
269
|
-
`;for(let n of r||[])e.send(JSON.stringify({body:n.body,done:!1,id:t,type:
|
|
269
|
+
`;for(let n of r||[])e.send(JSON.stringify({body:n.body,done:!1,id:t,type:L0.USE_CHAT_RESPONSE,replay:!0}));return this._activeStreamId===n?this._isLive?(e.send(JSON.stringify({body:``,done:!1,id:t,type:L0.USE_CHAT_RESPONSE,replay:!0,replayComplete:!0})),null):(e.send(JSON.stringify({body:``,done:!0,id:t,type:L0.USE_CHAT_RESPONSE,replay:!0})),this.complete(n),n):(e.send(JSON.stringify({body:``,done:!0,id:t,type:L0.USE_CHAT_RESPONSE,replay:!0})),null)}restore(){let e=this.sql`
|
|
270
270
|
select * from cf_ai_chat_stream_metadata
|
|
271
271
|
where status = 'streaming'
|
|
272
272
|
order by created_at desc
|
|
@@ -275,7 +275,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
275
275
|
select max(chunk_index) as max_index
|
|
276
276
|
from cf_ai_chat_stream_chunks
|
|
277
277
|
where stream_id = ${this._activeStreamId}
|
|
278
|
-
`;this._streamChunkIndex=n&&n[0]?.max_index!=null?n[0].max_index+1:0}}clearAll(){this._chunkBuffer=[],this.sql`delete from cf_ai_chat_stream_chunks`,this.sql`delete from cf_ai_chat_stream_metadata`,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0}destroy(){this.flushBuffer(),this.sql`drop table if exists cf_ai_chat_stream_chunks`,this.sql`drop table if exists cf_ai_chat_stream_metadata`,this._activeStreamId=null,this._activeRequestId=null}_maybeCleanupOldStreams(){let e=Date.now();if(e-this._lastCleanupTime<
|
|
278
|
+
`;this._streamChunkIndex=n&&n[0]?.max_index!=null?n[0].max_index+1:0}}clearAll(){this._chunkBuffer=[],this.sql`delete from cf_ai_chat_stream_chunks`,this.sql`delete from cf_ai_chat_stream_metadata`,this._activeStreamId=null,this._activeRequestId=null,this._streamChunkIndex=0}destroy(){this.flushBuffer(),this.sql`drop table if exists cf_ai_chat_stream_chunks`,this.sql`drop table if exists cf_ai_chat_stream_metadata`,this._activeStreamId=null,this._activeRequestId=null}_maybeCleanupOldStreams(){let e=Date.now();if(e-this._lastCleanupTime<B0)return;this._lastCleanupTime=e;let t=e-V0;this.sql`
|
|
279
279
|
delete from cf_ai_chat_stream_chunks
|
|
280
280
|
where stream_id in (
|
|
281
281
|
select id from cf_ai_chat_stream_metadata
|
|
@@ -303,7 +303,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
303
303
|
`;return t&&t.length>0?t[0]:null}getAllStreamMetadata(){return this.sql`select id, status, request_id, created_at from cf_ai_chat_stream_metadata`||[]}insertStaleStream(e,t,n){let r=Date.now()-n;this.sql`
|
|
304
304
|
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
305
305
|
values (${e}, ${t}, 'streaming', ${r})
|
|
306
|
-
`}};H0.CHUNK_MAX_BYTES=18e5,I0.STREAM_RESUME_NONE;var U0=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+=`-`:e+=`_`,e),``),W0=n(i(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),G0=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},K0=(e,t,n)=>(G0(e,t,`read from private field`),n?n.call(e):t.get(e)),q0=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},J0=(e,t,n,r)=>(G0(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function Y0(e,t){return t==null?e:(0,W0.default)(e,t)}var X0,Z0,Q0,$0,e2,t2,n2,r2,i2,a2=class{constructor(e=[]){q0(this,X0,void 0),q0(this,Z0,`ready`),q0(this,Q0,void 0),q0(this,$0,new Set),q0(this,e2,new Set),q0(this,t2,new Set),this.pushMessage=e=>{J0(this,X0,K0(this,X0).concat(e)),K0(this,n2).call(this)},this.popMessage=()=>{J0(this,X0,K0(this,X0).slice(0,-1)),K0(this,n2).call(this)},this.replaceMessage=(e,t)=>{J0(this,X0,[...K0(this,X0).slice(0,e),this.snapshot(t),...K0(this,X0).slice(e+1)]),K0(this,n2).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?Y0(e,t):e;return K0(this,$0).add(n),()=>{K0(this,$0).delete(n)}},this[`~registerStatusCallback`]=e=>(K0(this,e2).add(e),()=>{K0(this,e2).delete(e)}),this[`~registerErrorCallback`]=e=>(K0(this,t2).add(e),()=>{K0(this,t2).delete(e)}),q0(this,n2,()=>{K0(this,$0).forEach(e=>e())}),q0(this,r2,()=>{K0(this,e2).forEach(e=>e())}),q0(this,i2,()=>{K0(this,t2).forEach(e=>e())}),J0(this,X0,e)}get status(){return K0(this,Z0)}set status(e){J0(this,Z0,e),K0(this,r2).call(this)}get error(){return K0(this,Q0)}set error(e){J0(this,Q0,e),K0(this,i2).call(this)}get messages(){return K0(this,X0)}set messages(e){J0(this,X0,[...e]),K0(this,n2).call(this)}};X0=new WeakMap,Z0=new WeakMap,Q0=new WeakMap,$0=new WeakMap,e2=new WeakMap,t2=new WeakMap,n2=new WeakMap,r2=new WeakMap,i2=new WeakMap;var o2,s2=class extends O0{constructor({messages:e,...t}){let n=new a2(e);super({...t,state:n}),q0(this,o2,void 0),this[`~registerMessagesCallback`]=(e,t)=>K0(this,o2)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>K0(this,o2)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>K0(this,o2)[`~registerErrorCallback`](e),J0(this,o2,n)}};o2=new WeakMap;function c2({experimental_throttle:e,resume:t=!1,...n}={}){let r=(0,B.useRef)(`chat`in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});`chat`in n||(r.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});let i={...n,onToolCall:e=>{var t;return(t=r.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=r.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=r.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=r.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=r.current).sendAutomaticallyWhen?.call(t,e)??!1}},a=(0,B.useRef)(`chat`in n?n.chat:new s2(i));(`chat`in n&&n.chat!==a.current||`id`in n&&a.current.id!==n.id)&&(a.current=`chat`in n?n.chat:new s2(i));let o=(0,B.useSyncExternalStore)((0,B.useCallback)(t=>a.current[`~registerMessagesCallback`](t,e),[e,a.current.id]),()=>a.current.messages,()=>a.current.messages),s=(0,B.useSyncExternalStore)(a.current[`~registerStatusCallback`],()=>a.current.status,()=>a.current.status),c=(0,B.useSyncExternalStore)(a.current[`~registerErrorCallback`],()=>a.current.error,()=>a.current.error),l=(0,B.useCallback)(e=>{typeof e==`function`&&(e=e(a.current.messages)),a.current.messages=e},[a]);return(0,B.useEffect)(()=>{t&&a.current.resumeStream()},[t,a]),{id:a.current.id,messages:o,setMessages:l,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:c,resumeStream:a.current.resumeStream,status:s,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}var l2=class{constructor(e){this._resumeResolver=null,this._resumeNoneResolver=null,this._expectToolContinuation=!1,this._abortToolContinuation=null,this.agent=e.agent,this.prepareBody=e.prepareBody,this.activeRequestIds=e.activeRequestIds}expectToolContinuation(){this._expectToolContinuation=!0}abortActiveToolContinuation(){return this._abortToolContinuation?.()??!1}isAwaitingResume(){return this._resumeResolver!==null||this._resumeNoneResolver!==null}handleStreamResuming(e){return this._resumeResolver?(this._resumeResolver(e),!0):!1}handleStreamResumeNone(){return this._resumeNoneResolver?(this._resumeNoneResolver(),!0):!1}async sendMessages(e){let t=U0(8),n=new AbortController,r=!1,i={};this.prepareBody&&(i=await this.prepareBody({messages:e.messages,trigger:e.trigger,messageId:e.messageId})),e.body&&(i={...i,...e.body});let a=JSON.stringify({messages:e.messages,trigger:e.trigger,...i});this.activeRequestIds?.add(t);let o=this.agent,s=this.activeRequestIds,c=(e,i=!1)=>{if(!r){r=!0;try{e()}catch{}i||s?.delete(t),n.abort()}},l=Error(`Aborted`);l.name=`AbortError`;let u=()=>{if(!r){try{o.send(JSON.stringify({id:t,type:VU.CF_AGENT_CHAT_REQUEST_CANCEL}))}catch{}c(()=>d.error(l),!0)}},d,f=new ReadableStream({start(e){d=e,o.addEventListener(`message`,n=>{try{let r=JSON.parse(n.data);if(r.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||r.id!==t)return;if(r.error){c(()=>e.error(Error(r.body||`Stream error`)));return}if(r.body?.trim())try{let t=JSON.parse(r.body);e.enqueue(t)}catch{}r.done&&c(()=>e.close())}catch{}},{signal:n.signal})},cancel(){u()}});return e.abortSignal&&(e.abortSignal.addEventListener(`abort`,u,{once:!0}),e.abortSignal.aborted&&u()),o.send(JSON.stringify({id:t,init:{method:`POST`,body:a},type:VU.CF_AGENT_USE_CHAT_REQUEST})),f}async reconnectToStream(e){if(this._expectToolContinuation)return this._expectToolContinuation=!1,this._createToolContinuationStream();let t=this.activeRequestIds;return new Promise(e=>{let n=!1,r,i=t=>{n||(n=!0,this._resumeResolver=null,this._resumeNoneResolver=null,r&&clearTimeout(r),e(t))};this._resumeNoneResolver=()=>i(null),this._resumeResolver=e=>{let n=e.id;t?.add(n),this.agent.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:n})),i(this._createResumeStream(n))};try{this.agent.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_REQUEST}))}catch{}r=setTimeout(()=>i(null),5e3)})}_createToolContinuationStream(){let e=this.agent,t=this.activeRequestIds,n=new AbortController,r=Error(`Aborted`);r.name=`AbortError`;let i=!1,a=null,o,s=null,c=null,l=(e,t)=>{if(e===void 0&&t===void 0){this._resumeResolver=null,this._resumeNoneResolver=null;return}e&&this._resumeResolver===e&&(this._resumeResolver=null),t&&this._resumeNoneResolver===t&&(this._resumeNoneResolver=null)},u=(e,r,o,s=!1)=>{if(!i){i=!0,this._abortToolContinuation=null,l(r,o);try{e()}catch{}a&&!s&&t?.delete(a),n.abort()}};this._abortToolContinuation=()=>{if(i)return!1;if(a===null)return u(()=>o.error(r),s,c),!0;try{e.send(JSON.stringify({type:VU.CF_AGENT_CHAT_REQUEST_CANCEL,id:a}))}catch{}return u(()=>o.error(r),s,c,!0),!0};let d=this;return new ReadableStream({start(r){o=r;let i,f=()=>{i&&clearTimeout(i),u(()=>r.close(),p,f)},p=n=>{a||(a=n.id,t?.add(a),l(p,f),i&&clearTimeout(i),e.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:a})))};s=p,c=f,i=setTimeout(()=>u(()=>r.close(),p,f),5e3),d._resumeResolver=p,d._resumeNoneResolver=f,e.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(t.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||a==null||t.id!==a)return;if(t.error){u(()=>r.error(Error(t.body||`Stream error`)),p,f);return}if(t.body?.trim())try{let e=JSON.parse(t.body);r.enqueue(e)}catch{}t.done&&u(()=>r.close(),p,f)}catch{}},{signal:n.signal});try{e.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_REQUEST}))}catch{u(()=>r.close())}},cancel(){u(()=>{})}})}_createResumeStream(e){let t=this.agent,n=this.activeRequestIds,r=new AbortController,i=!1,a=t=>{if(!i){i=!0;try{t()}catch{}n?.delete(e),r.abort()}};return new ReadableStream({start(n){t.addEventListener(`message`,t=>{try{let r=JSON.parse(t.data);if(r.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||r.id!==e)return;if(r.error){a(()=>n.error(Error(r.body||`Stream error`)));return}if(r.body?.trim())try{let e=JSON.parse(r.body);n.enqueue(e)}catch{}r.done&&a(()=>n.close())}catch{}},{signal:r.signal})},cancel(){a(()=>{})}})}},u2=new Set;function d2(e,t){u2.has(e)||(u2.add(e),console.warn(`[@cloudflare/ai-chat] Deprecated: ${t}`))}function f2(e){if(!e)return;let t=Object.entries(e).filter(([e,t])=>t.execute).map(([e,t])=>(t.inputSchema&&!t.parameters&&console.warn(`[useAgentChat] Tool "${e}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`),{name:e,description:t.description,parameters:t.parameters??t.inputSchema}));return t.length>0?t:void 0}var p2=new Map;function m2(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`assistant`)return{index:t,message:n}}return null}function h2(e,t){let n=e.findIndex(e=>e.id===t);if(n<0||n===e.length-1)return e;let r=[...e],[i]=r.splice(n,1);return i?(r.push(i),r):e}function g2(e){let{agent:t,getInitialMessages:n,messages:r,onToolCall:i,onData:a,experimental_automaticToolResolution:o,tools:s,toolsRequiringConfirmation:c,autoContinueAfterToolResult:l=!0,autoSendAfterAllConfirmationsResolved:u=!0,resume:d=!0,body:f,prepareSendMessagesRequest:p,...m}=e;c&&d2(`useAgentChat.toolsRequiringConfirmation`,`The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.`),o&&d2(`useAgentChat.experimental_automaticToolResolution`,`The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.`),e.autoSendAfterAllConfirmationsResolved!==void 0&&d2(`useAgentChat.autoSendAfterAllConfirmationsResolved`,`The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.`);let h=(0,B.useMemo)(()=>c||(s?Object.entries(s).filter(([e,t])=>!t.execute).map(([e])=>e):[]),[c,s]),g=(0,B.useRef)(i);g.current=i;let _=(0,B.useRef)(a);_.current=a;let v=new URL(t.getHttpUrl());v.searchParams.delete(`_pk`);let y=v.toString(),b=`${v.origin}${v.pathname}|${t.agent??``}|${t.name??``}`,x=(0,B.useRef)(t);x.current=t;async function S({url:t}){let n=new URL(t);n.pathname+=`/get-messages`;let r=await fetch(n.toString(),{credentials:e.credentials,headers:e.headers});if(!r.ok)return console.warn(`Failed to fetch initial messages: ${r.status} ${r.statusText}`),[];let i=await r.text();if(!i.trim())return[];try{return JSON.parse(i)}catch(e){return console.warn(`Failed to parse initial messages JSON:`,e),[]}}let C=n||S;function w(e,t){if(p2.has(t))return p2.get(t);let n=C(e);return p2.set(t,n),n}let T=n===null?null:w({agent:t.agent,name:t.name,url:y},b),E=T?(0,B.use)(T):r??[];(0,B.useEffect)(()=>{if(T)return p2.set(b,T),()=>{p2.get(b)===T&&p2.delete(b)}},[b,T]);let D=(0,B.useRef)(s);D.current=s;let O=(0,B.useRef)(p);O.current=p;let k=(0,B.useRef)(f);k.current=f;let A=(0,B.useRef)(new Set),j=(0,B.useRef)(null);j.current===null&&(j.current=new l2({agent:x.current,activeRequestIds:A.current,prepareBody:async({messages:e,trigger:t,messageId:n})=>{let r={},i=k.current;if(i&&(r={...typeof i==`function`?await i():i}),D.current){let e=f2(D.current);e&&(r.clientTools=e)}if(O.current){let i=await O.current({id:x.current._pk,messages:e,trigger:t,messageId:n});i.body&&Object.assign(r,i.body)}return r}})),j.current.agent=x.current;let M=j.current,N=c2({...m,onData:a,messages:E,transport:M,id:b,resume:d}),{messages:P,setMessages:F,addToolResult:I,addToolApprovalResponse:ee,sendMessage:L,resumeStream:te,status:R,stop:ne}=N,re=(0,B.useRef)(R);re.current=R;let ie=(0,B.useRef)(!1),z=(0,B.useCallback)(()=>{!l||ie.current||(ie.current=!0,M.expectToolContinuation(),te().finally(()=>{ie.current=!1}))},[l,M,te]),ae=(0,B.useCallback)(async()=>{try{await ne()}finally{M.abortActiveToolContinuation()}},[ne,M]),oe=(0,B.useRef)(new Set),se=(0,B.useRef)(!1),[ce,le]=(0,B.useState)(0),[ue,de]=(0,B.useState)(new Map),fe=(0,B.useRef)(P);fe.current=P;let pe=(0,B.useRef)(new Map),me=(0,B.useRef)(null),he=(0,B.useCallback)(e=>{let t=me.current;if(!t)return e;let n=fe.current.find(e=>e.id===t.assistantId)??e.find(e=>e.id===t.assistantId);return n?[...e.filter(e=>e.id!==t.assistantId),n]:e},[]),ge=(0,B.useCallback)(()=>{if(re.current!==`streaming`)return;let e=m2(fe.current);e&&(me.current?.assistantId!==e.message.id&&(me.current={assistantId:e.message.id,anchorMessageId:fe.current[e.index-1]?.id??null}),F(e=>{let t=me.current;return t?h2(e,t.assistantId):e}))},[F]),_e=(0,B.useCallback)(e=>{let t=me.current;!t||e!==void 0&&t.assistantId!==e||(me.current=null,F(e=>{let n=e.findIndex(e=>e.id===t.assistantId);if(n<0)return e;let r=[...e],[i]=r.splice(n,1);if(!i)return e;if(t.anchorMessageId===null)r.unshift(i);else{let e=r.findIndex(e=>e.id===t.anchorMessageId);r.splice(e>=0?e+1:n,0,i)}return r}))},[F]),ve=(0,B.useCallback)(async(e,t)=>{let n=L(e,t);return e!==void 0&&!(typeof e==`object`&&e&&`messageId`in e&&e.messageId!=null)&&ge(),n},[L,ge]),ye=P[P.length-1],be=(()=>{if(!ye||ye.role!==`assistant`)return{messageId:void 0,toolCallIds:new Set};let e=new Set;for(let t of ye.parts??[])v0(t)&&t.state===`input-available`&&h.includes(b0(t))&&e.add(t.toolCallId);return{messageId:ye.id,toolCallIds:e}})(),xe=(0,B.useRef)(be);xe.current=be,(0,B.useEffect)(()=>{if(!o||se.current)return;let e=P[P.length-1];if(!e||e.role!==`assistant`)return;let t=e.parts.filter(e=>v0(e)&&e.state===`input-available`&&!oe.current.has(e.toolCallId));if(t.length>0){let e=D.current,n=t.filter(t=>v0(t)&&!h.includes(b0(t))&&e?.[b0(t)]?.execute);n.length>0&&(se.current=!0,(async()=>{try{let t=[];for(let r of n)if(v0(r)){let n=null,i=b0(r),a=e?.[i];if(a?.execute&&r.input!==void 0)try{n=await a.execute(r.input)}catch(e){n=`Error executing tool: ${e instanceof Error?e.message:String(e)}`}oe.current.add(r.toolCallId),t.push({toolCallId:r.toolCallId,toolName:i,output:n})}if(t.length>0){let n=f2(e);for(let e of t)x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,autoContinue:l,clientTools:n}));await Promise.all(t.map(e=>I({tool:e.toolName,toolCallId:e.toolCallId,output:e.output}))),de(e=>{let n=new Map(e);for(let e of t)n.set(e.toolCallId,e.output);return n}),z()}}finally{se.current=!1,le(e=>e+1)}})())}},[P,o,I,h,l,z,ce]);let Se=(0,B.useCallback)((e,t,n,r,i)=>{let a=r===`output-error`?!1:l;x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:e,toolName:t,output:n,...r?{state:r}:{},...i===void 0?{}:{errorText:i},autoContinue:a,clientTools:D.current?f2(D.current):void 0})),r!==`output-error`&&de(t=>new Map(t).set(e,n)),a&&z()},[l,z]),Ce=(0,B.useCallback)((e,t)=>{x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_APPROVAL,toolCallId:e,approved:t,autoContinue:l})),l&&z()},[l,z]);(0,B.useEffect)(()=>{let e=g.current;if(!e)return;let t=P[P.length-1];if(!t||t.role!==`assistant`)return;let n=t.parts.filter(e=>v0(e)&&e.state===`input-available`&&!oe.current.has(e.toolCallId));for(let t of n)if(v0(t)){let n=t.toolCallId,r=b0(t);oe.current.add(n),e({toolCall:{toolCallId:n,toolName:r,input:t.input},addToolOutput:e=>{Se(e.toolCallId,r,e.output,e.state,e.errorText),I({tool:r,toolCallId:e.toolCallId,output:e.state===`output-error`?e.errorText??`Tool execution denied by user`:e.output})}})}},[P,Se,I]);let we=(0,B.useRef)({status:`idle`}),[Te,Ee]=(0,B.useState)(!1);(0,B.useEffect)(()=>{let e=pe.current;function n(t){if(typeof t.data!=`string`)return;let n;try{n=JSON.parse(t.data)}catch{return}switch(n.type){case VU.CF_AGENT_CHAT_CLEAR:e.clear(),me.current=null,we.current=F0(we.current,{type:`clear`}).state,Ee(!1),F([]);break;case VU.CF_AGENT_CHAT_MESSAGES:F(he(n.messages));break;case VU.CF_AGENT_MESSAGE_UPDATED:F(e=>{let t=n.message,r=e.findIndex(e=>e.id===t.id);if(r<0){let n=new Set(t.parts.filter(e=>`toolCallId`in e&&e.toolCallId).map(e=>e.toolCallId));n.size>0&&(r=e.findIndex(e=>e.parts.some(e=>`toolCallId`in e&&n.has(e.toolCallId))))}if(r>=0){let n=[...e];return n[r]={...t,id:e[r].id},n}return e});break;case VU.CF_AGENT_STREAM_RESUME_NONE:M.handleStreamResumeNone();break;case VU.CF_AGENT_STREAM_RESUMING:if(!d&&!M.isAwaitingResume()||M.handleStreamResuming(n)||A.current.has(n.id))return;we.current=F0(we.current,{type:`resume-fallback`,streamId:n.id,messageId:U0()}).state,Ee(!0),x.current.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:n.id}));break;case VU.CF_AGENT_USE_CHAT_RESPONSE:{if(A.current.has(n.id)){if(n.body?.trim())try{let t=JSON.parse(n.body);t.type===`start`&&typeof t.messageId==`string`&&e.set(n.id,t.messageId)}catch{}n.done&&(_e(e.get(n.id)),e.delete(n.id),A.current.delete(n.id));return}let t;if(n.body?.trim())try{t=JSON.parse(n.body),typeof t.type==`string`&&t.type.startsWith(`data-`)&&_.current&&_.current(t)}catch(e){console.warn(`[useAgentChat] Failed to parse stream chunk:`,e instanceof Error?e.message:e,`body:`,n.body?.slice(0,100))}let r=F0(we.current,{type:`response`,streamId:n.id,messageId:U0(),chunkData:t,done:n.done,error:n.error,replay:n.replay,replayComplete:n.replayComplete,continuation:n.continuation,currentMessages:n.continuation?fe.current:void 0});we.current=r.state,r.messagesUpdate&&F(r.messagesUpdate),Ee(r.isStreaming);break}}}return t.addEventListener(`message`,n),()=>{t.removeEventListener(`message`,n),we.current={status:`idle`},Ee(!1),me.current=null,e.clear()}},[t,F,d,M,he,_e]);let De=async e=>{let{toolCallId:t}=e,n=`tool`in e?e.tool:``,r=`output`in e?e.output:void 0;if(x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:t,toolName:n,output:r,autoContinue:l,clientTools:D.current?f2(D.current):void 0})),de(e=>new Map(e).set(t,r)),I(e),l&&z(),!l){if(!u){L();return}let e=xe.current?.toolCallIds;if(!e){L();return}let n=e.size===1&&e.has(t);e.has(t)&&e.delete(t),(n||e.size===0)&&L()}},Oe=e=>{let{id:t,approved:n}=e,r;for(let e of fe.current){for(let n of e.parts)if(`toolCallId`in n&&`approval`in n&&n.approval?.id===t){r=n.toolCallId;break}if(r)break}r?Ce(r,n):console.warn(`[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID "${t}". Server will not be notified, which may cause duplicate messages.`),ee(e)},ke=(0,B.useMemo)(()=>ue.size===0?P:P.map(e=>({...e,parts:e.parts.map(e=>!(`toolCallId`in e)||!(`state`in e)||e.state!==`input-available`||!ue.has(e.toolCallId)?e:{...e,state:`output-available`,output:ue.get(e.toolCallId)})})),[P,ue]);(0,B.useEffect)(()=>{let e=new Set;for(let t of P)for(let n of t.parts)`toolCallId`in n&&n.toolCallId&&e.add(n.toolCallId);de(t=>{if(t.size===0)return t;let n=!1;for(let r of t.keys())if(!e.has(r)){n=!0;break}if(!n)return t;let r=new Map;for(let[n,i]of t)e.has(n)&&r.set(n,i);return r});for(let t of oe.current)e.has(t)||oe.current.delete(t)},[P]);let Ae=(0,B.useCallback)(e=>{let t=e.toolName??``;Se(e.toolCallId,t,e.output,e.state,e.errorText),I({tool:t,toolCallId:e.toolCallId,output:e.state===`output-error`?e.errorText??`Tool execution denied by user`:e.output})},[Se,I]),je=R===`streaming`||Te;return{...N,messages:ke,isServerStreaming:Te,isStreaming:je,sendMessage:ve,stop:ae,addToolOutput:Ae,addToolResult:De,addToolApprovalResponse:Oe,clearHistory:()=>{F([]),de(new Map),ie.current=!1,oe.current.clear(),pe.current.clear(),me.current=null,t.send(JSON.stringify({type:VU.CF_AGENT_CHAT_CLEAR}))},setMessages:e=>{let n;n=typeof e==`function`?e(fe.current):e,F(n),t.send(JSON.stringify({messages:n,type:VU.CF_AGENT_CHAT_MESSAGES}))}}}var _2=function(e){return e.CF_AGENT_MCP_SERVERS=`cf_agent_mcp_servers`,e.CF_MCP_AGENT_EVENT=`cf_mcp_agent_event`,e.CF_AGENT_STATE=`cf_agent_state`,e.CF_AGENT_STATE_ERROR=`cf_agent_state_error`,e.CF_AGENT_IDENTITY=`cf_agent_identity`,e.CF_AGENT_SESSION=`cf_agent_session`,e.CF_AGENT_SESSION_ERROR=`cf_agent_session_error`,e.RPC=`rpc`,e}({});function v2(e){if(e===e.toUpperCase()&&e!==e.toLowerCase())return e.toLowerCase().replace(/_/g,`-`);let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t=t.startsWith(`-`)?t.slice(1):t,t.replace(/_/g,`-`).replace(/-$/,``)}(!globalThis.EventTarget||!globalThis.Event)&&console.error(`
|
|
306
|
+
`}};U0.CHUNK_MAX_BYTES=18e5,L0.STREAM_RESUME_NONE;var W0=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+=`-`:e+=`_`,e),``),G0=n(i(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),K0=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},q0=(e,t,n)=>(K0(e,t,`read from private field`),n?n.call(e):t.get(e)),J0=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},Y0=(e,t,n,r)=>(K0(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function X0(e,t){return t==null?e:(0,G0.default)(e,t)}var Z0,Q0,$0,e2,t2,n2,r2,i2,a2,o2=class{constructor(e=[]){J0(this,Z0,void 0),J0(this,Q0,`ready`),J0(this,$0,void 0),J0(this,e2,new Set),J0(this,t2,new Set),J0(this,n2,new Set),this.pushMessage=e=>{Y0(this,Z0,q0(this,Z0).concat(e)),q0(this,r2).call(this)},this.popMessage=()=>{Y0(this,Z0,q0(this,Z0).slice(0,-1)),q0(this,r2).call(this)},this.replaceMessage=(e,t)=>{Y0(this,Z0,[...q0(this,Z0).slice(0,e),this.snapshot(t),...q0(this,Z0).slice(e+1)]),q0(this,r2).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?X0(e,t):e;return q0(this,e2).add(n),()=>{q0(this,e2).delete(n)}},this[`~registerStatusCallback`]=e=>(q0(this,t2).add(e),()=>{q0(this,t2).delete(e)}),this[`~registerErrorCallback`]=e=>(q0(this,n2).add(e),()=>{q0(this,n2).delete(e)}),J0(this,r2,()=>{q0(this,e2).forEach(e=>e())}),J0(this,i2,()=>{q0(this,t2).forEach(e=>e())}),J0(this,a2,()=>{q0(this,n2).forEach(e=>e())}),Y0(this,Z0,e)}get status(){return q0(this,Q0)}set status(e){Y0(this,Q0,e),q0(this,i2).call(this)}get error(){return q0(this,$0)}set error(e){Y0(this,$0,e),q0(this,a2).call(this)}get messages(){return q0(this,Z0)}set messages(e){Y0(this,Z0,[...e]),q0(this,r2).call(this)}};Z0=new WeakMap,Q0=new WeakMap,$0=new WeakMap,e2=new WeakMap,t2=new WeakMap,n2=new WeakMap,r2=new WeakMap,i2=new WeakMap,a2=new WeakMap;var s2,c2=class extends O0{constructor({messages:e,...t}){let n=new o2(e);super({...t,state:n}),J0(this,s2,void 0),this[`~registerMessagesCallback`]=(e,t)=>q0(this,s2)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>q0(this,s2)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>q0(this,s2)[`~registerErrorCallback`](e),Y0(this,s2,n)}};s2=new WeakMap;function l2({experimental_throttle:e,resume:t=!1,...n}={}){let r=(0,B.useRef)(`chat`in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});`chat`in n||(r.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});let i={...n,onToolCall:e=>{var t;return(t=r.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=r.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=r.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=r.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=r.current).sendAutomaticallyWhen?.call(t,e)??!1}},a=(0,B.useRef)(`chat`in n?n.chat:new c2(i));(`chat`in n&&n.chat!==a.current||`id`in n&&a.current.id!==n.id)&&(a.current=`chat`in n?n.chat:new c2(i));let o=(0,B.useSyncExternalStore)((0,B.useCallback)(t=>a.current[`~registerMessagesCallback`](t,e),[e,a.current.id]),()=>a.current.messages,()=>a.current.messages),s=(0,B.useSyncExternalStore)(a.current[`~registerStatusCallback`],()=>a.current.status,()=>a.current.status),c=(0,B.useSyncExternalStore)(a.current[`~registerErrorCallback`],()=>a.current.error,()=>a.current.error),l=(0,B.useCallback)(e=>{typeof e==`function`&&(e=e(a.current.messages)),a.current.messages=e},[a]);return(0,B.useEffect)(()=>{t&&a.current.resumeStream()},[t,a]),{id:a.current.id,messages:o,setMessages:l,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:c,resumeStream:a.current.resumeStream,status:s,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}var u2=class{constructor(e){this._resumeResolver=null,this._resumeNoneResolver=null,this._expectToolContinuation=!1,this._abortToolContinuation=null,this.agent=e.agent,this.prepareBody=e.prepareBody,this.activeRequestIds=e.activeRequestIds}expectToolContinuation(){this._expectToolContinuation=!0}abortActiveToolContinuation(){return this._abortToolContinuation?.()??!1}isAwaitingResume(){return this._resumeResolver!==null||this._resumeNoneResolver!==null}handleStreamResuming(e){return this._resumeResolver?(this._resumeResolver(e),!0):!1}handleStreamResumeNone(){return this._resumeNoneResolver?(this._resumeNoneResolver(),!0):!1}async sendMessages(e){let t=W0(8),n=new AbortController,r=!1,i={};this.prepareBody&&(i=await this.prepareBody({messages:e.messages,trigger:e.trigger,messageId:e.messageId})),e.body&&(i={...i,...e.body});let a=JSON.stringify({messages:e.messages,trigger:e.trigger,...i});this.activeRequestIds?.add(t);let o=this.agent,s=this.activeRequestIds,c=(e,i=!1)=>{if(!r){r=!0;try{e()}catch{}i||s?.delete(t),n.abort()}},l=Error(`Aborted`);l.name=`AbortError`;let u=()=>{if(!r){try{o.send(JSON.stringify({id:t,type:VU.CF_AGENT_CHAT_REQUEST_CANCEL}))}catch{}c(()=>d.error(l),!0)}},d,f=new ReadableStream({start(e){d=e,o.addEventListener(`message`,n=>{try{let r=JSON.parse(n.data);if(r.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||r.id!==t)return;if(r.error){c(()=>e.error(Error(r.body||`Stream error`)));return}if(r.body?.trim())try{let t=JSON.parse(r.body);e.enqueue(t)}catch{}r.done&&c(()=>e.close())}catch{}},{signal:n.signal})},cancel(){u()}});return e.abortSignal&&(e.abortSignal.addEventListener(`abort`,u,{once:!0}),e.abortSignal.aborted&&u()),o.send(JSON.stringify({id:t,init:{method:`POST`,body:a},type:VU.CF_AGENT_USE_CHAT_REQUEST})),f}async reconnectToStream(e){if(this._expectToolContinuation)return this._expectToolContinuation=!1,this._createToolContinuationStream();let t=this.activeRequestIds;return new Promise(e=>{let n=!1,r,i=t=>{n||(n=!0,this._resumeResolver=null,this._resumeNoneResolver=null,r&&clearTimeout(r),e(t))};this._resumeNoneResolver=()=>i(null),this._resumeResolver=e=>{let n=e.id;t?.add(n),this.agent.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:n})),i(this._createResumeStream(n))};try{this.agent.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_REQUEST}))}catch{}r=setTimeout(()=>i(null),5e3)})}_createToolContinuationStream(){let e=this.agent,t=this.activeRequestIds,n=new AbortController,r=Error(`Aborted`);r.name=`AbortError`;let i=!1,a=null,o,s=null,c=null,l=(e,t)=>{if(e===void 0&&t===void 0){this._resumeResolver=null,this._resumeNoneResolver=null;return}e&&this._resumeResolver===e&&(this._resumeResolver=null),t&&this._resumeNoneResolver===t&&(this._resumeNoneResolver=null)},u=(e,r,o,s=!1)=>{if(!i){i=!0,this._abortToolContinuation=null,l(r,o);try{e()}catch{}a&&!s&&t?.delete(a),n.abort()}};this._abortToolContinuation=()=>{if(i)return!1;if(a===null)return u(()=>o.error(r),s,c),!0;try{e.send(JSON.stringify({type:VU.CF_AGENT_CHAT_REQUEST_CANCEL,id:a}))}catch{}return u(()=>o.error(r),s,c,!0),!0};let d=this;return new ReadableStream({start(r){o=r;let i,f=()=>{i&&clearTimeout(i),u(()=>r.close(),p,f)},p=n=>{a||(a=n.id,t?.add(a),l(p,f),i&&clearTimeout(i),e.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:a})))};s=p,c=f,i=setTimeout(()=>u(()=>r.close(),p,f),5e3),d._resumeResolver=p,d._resumeNoneResolver=f,e.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(t.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||a==null||t.id!==a)return;if(t.error){u(()=>r.error(Error(t.body||`Stream error`)),p,f);return}if(t.body?.trim())try{let e=JSON.parse(t.body);r.enqueue(e)}catch{}t.done&&u(()=>r.close(),p,f)}catch{}},{signal:n.signal});try{e.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_REQUEST}))}catch{u(()=>r.close())}},cancel(){u(()=>{})}})}_createResumeStream(e){let t=this.agent,n=this.activeRequestIds,r=new AbortController,i=!1,a=t=>{if(!i){i=!0;try{t()}catch{}n?.delete(e),r.abort()}};return new ReadableStream({start(n){t.addEventListener(`message`,t=>{try{let r=JSON.parse(t.data);if(r.type!==VU.CF_AGENT_USE_CHAT_RESPONSE||r.id!==e)return;if(r.error){a(()=>n.error(Error(r.body||`Stream error`)));return}if(r.body?.trim())try{let e=JSON.parse(r.body);n.enqueue(e)}catch{}r.done&&a(()=>n.close())}catch{}},{signal:r.signal})},cancel(){a(()=>{})}})}},d2=new Set;function f2(e,t){d2.has(e)||(d2.add(e),console.warn(`[@cloudflare/ai-chat] Deprecated: ${t}`))}function p2(e){if(!e)return;let t=Object.entries(e).filter(([e,t])=>t.execute).map(([e,t])=>(t.inputSchema&&!t.parameters&&console.warn(`[useAgentChat] Tool "${e}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`),{name:e,description:t.description,parameters:t.parameters??t.inputSchema}));return t.length>0?t:void 0}var m2=new Map;function h2(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`assistant`)return{index:t,message:n}}return null}function g2(e,t){let n=e.findIndex(e=>e.id===t);if(n<0||n===e.length-1)return e;let r=[...e],[i]=r.splice(n,1);return i?(r.push(i),r):e}function _2(e){let{agent:t,getInitialMessages:n,messages:r,onToolCall:i,onData:a,experimental_automaticToolResolution:o,tools:s,toolsRequiringConfirmation:c,autoContinueAfterToolResult:l=!0,autoSendAfterAllConfirmationsResolved:u=!0,resume:d=!0,body:f,prepareSendMessagesRequest:p,...m}=e;c&&f2(`useAgentChat.toolsRequiringConfirmation`,`The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.`),o&&f2(`useAgentChat.experimental_automaticToolResolution`,`The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.`),e.autoSendAfterAllConfirmationsResolved!==void 0&&f2(`useAgentChat.autoSendAfterAllConfirmationsResolved`,`The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.`);let h=(0,B.useMemo)(()=>c||(s?Object.entries(s).filter(([e,t])=>!t.execute).map(([e])=>e):[]),[c,s]),g=(0,B.useRef)(i);g.current=i;let _=(0,B.useRef)(a);_.current=a;let v=new URL(t.getHttpUrl());v.searchParams.delete(`_pk`);let y=v.toString(),b=`${v.origin}${v.pathname}|${t.agent??``}|${t.name??``}`,x=(0,B.useRef)(t);x.current=t;async function S({url:t}){let n=new URL(t);n.pathname+=`/get-messages`;let r=await fetch(n.toString(),{credentials:e.credentials,headers:e.headers});if(!r.ok)return console.warn(`Failed to fetch initial messages: ${r.status} ${r.statusText}`),[];let i=await r.text();if(!i.trim())return[];try{return JSON.parse(i)}catch(e){return console.warn(`Failed to parse initial messages JSON:`,e),[]}}let C=n||S;function w(e,t){if(m2.has(t))return m2.get(t);let n=C(e);return m2.set(t,n),n}let T=n===null?null:w({agent:t.agent,name:t.name,url:y},b),E=T?(0,B.use)(T):r??[];(0,B.useEffect)(()=>{if(T)return m2.set(b,T),()=>{m2.get(b)===T&&m2.delete(b)}},[b,T]);let D=(0,B.useRef)(s);D.current=s;let O=(0,B.useRef)(p);O.current=p;let k=(0,B.useRef)(f);k.current=f;let A=(0,B.useRef)(new Set),j=(0,B.useRef)(null);j.current===null&&(j.current=new u2({agent:x.current,activeRequestIds:A.current,prepareBody:async({messages:e,trigger:t,messageId:n})=>{let r={},i=k.current;if(i&&(r={...typeof i==`function`?await i():i}),D.current){let e=p2(D.current);e&&(r.clientTools=e)}if(O.current){let i=await O.current({id:x.current._pk,messages:e,trigger:t,messageId:n});i.body&&Object.assign(r,i.body)}return r}})),j.current.agent=x.current;let M=j.current,N=l2({...m,onData:a,messages:E,transport:M,id:b,resume:d}),{messages:P,setMessages:F,addToolResult:I,addToolApprovalResponse:ee,sendMessage:L,resumeStream:te,status:R,stop:ne}=N,re=(0,B.useRef)(R);re.current=R;let ie=(0,B.useRef)(!1),z=(0,B.useCallback)(()=>{!l||ie.current||(ie.current=!0,M.expectToolContinuation(),te().finally(()=>{ie.current=!1}))},[l,M,te]),ae=(0,B.useCallback)(async()=>{try{await ne()}finally{M.abortActiveToolContinuation()}},[ne,M]),oe=(0,B.useRef)(new Set),se=(0,B.useRef)(!1),[ce,le]=(0,B.useState)(0),[ue,de]=(0,B.useState)(new Map),fe=(0,B.useRef)(P);fe.current=P;let pe=(0,B.useRef)(new Map),me=(0,B.useRef)(null),he=(0,B.useCallback)(e=>{let t=me.current;if(!t)return e;let n=fe.current.find(e=>e.id===t.assistantId)??e.find(e=>e.id===t.assistantId);return n?[...e.filter(e=>e.id!==t.assistantId),n]:e},[]),ge=(0,B.useCallback)(()=>{if(re.current!==`streaming`)return;let e=h2(fe.current);e&&(me.current?.assistantId!==e.message.id&&(me.current={assistantId:e.message.id,anchorMessageId:fe.current[e.index-1]?.id??null}),F(e=>{let t=me.current;return t?g2(e,t.assistantId):e}))},[F]),_e=(0,B.useCallback)(e=>{let t=me.current;!t||e!==void 0&&t.assistantId!==e||(me.current=null,F(e=>{let n=e.findIndex(e=>e.id===t.assistantId);if(n<0)return e;let r=[...e],[i]=r.splice(n,1);if(!i)return e;if(t.anchorMessageId===null)r.unshift(i);else{let e=r.findIndex(e=>e.id===t.anchorMessageId);r.splice(e>=0?e+1:n,0,i)}return r}))},[F]),ve=(0,B.useCallback)(async(e,t)=>{let n=L(e,t);return e!==void 0&&!(typeof e==`object`&&e&&`messageId`in e&&e.messageId!=null)&&ge(),n},[L,ge]),ye=P[P.length-1],be=(()=>{if(!ye||ye.role!==`assistant`)return{messageId:void 0,toolCallIds:new Set};let e=new Set;for(let t of ye.parts??[])v0(t)&&t.state===`input-available`&&h.includes(b0(t))&&e.add(t.toolCallId);return{messageId:ye.id,toolCallIds:e}})(),xe=(0,B.useRef)(be);xe.current=be,(0,B.useEffect)(()=>{if(!o||se.current)return;let e=P[P.length-1];if(!e||e.role!==`assistant`)return;let t=e.parts.filter(e=>v0(e)&&e.state===`input-available`&&!oe.current.has(e.toolCallId));if(t.length>0){let e=D.current,n=t.filter(t=>v0(t)&&!h.includes(b0(t))&&e?.[b0(t)]?.execute);n.length>0&&(se.current=!0,(async()=>{try{let t=[];for(let r of n)if(v0(r)){let n=null,i=b0(r),a=e?.[i];if(a?.execute&&r.input!==void 0)try{n=await a.execute(r.input)}catch(e){n=`Error executing tool: ${e instanceof Error?e.message:String(e)}`}oe.current.add(r.toolCallId),t.push({toolCallId:r.toolCallId,toolName:i,output:n})}if(t.length>0){let n=p2(e);for(let e of t)x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,autoContinue:l,clientTools:n}));await Promise.all(t.map(e=>I({tool:e.toolName,toolCallId:e.toolCallId,output:e.output}))),de(e=>{let n=new Map(e);for(let e of t)n.set(e.toolCallId,e.output);return n}),z()}}finally{se.current=!1,le(e=>e+1)}})())}},[P,o,I,h,l,z,ce]);let Se=(0,B.useCallback)((e,t,n,r,i)=>{let a=r===`output-error`?!1:l;x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:e,toolName:t,output:n,...r?{state:r}:{},...i===void 0?{}:{errorText:i},autoContinue:a,clientTools:D.current?p2(D.current):void 0})),r!==`output-error`&&de(t=>new Map(t).set(e,n)),a&&z()},[l,z]),Ce=(0,B.useCallback)((e,t)=>{x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_APPROVAL,toolCallId:e,approved:t,autoContinue:l})),l&&z()},[l,z]);(0,B.useEffect)(()=>{let e=g.current;if(!e)return;let t=P[P.length-1];if(!t||t.role!==`assistant`)return;let n=t.parts.filter(e=>v0(e)&&e.state===`input-available`&&!oe.current.has(e.toolCallId));for(let t of n)if(v0(t)){let n=t.toolCallId,r=b0(t);oe.current.add(n),e({toolCall:{toolCallId:n,toolName:r,input:t.input},addToolOutput:e=>{Se(e.toolCallId,r,e.output,e.state,e.errorText),I({tool:r,toolCallId:e.toolCallId,output:e.state===`output-error`?e.errorText??`Tool execution denied by user`:e.output})}})}},[P,Se,I]);let we=(0,B.useRef)({status:`idle`}),[Te,Ee]=(0,B.useState)(!1);(0,B.useEffect)(()=>{let e=pe.current;function n(t){if(typeof t.data!=`string`)return;let n;try{n=JSON.parse(t.data)}catch{return}switch(n.type){case VU.CF_AGENT_CHAT_CLEAR:e.clear(),me.current=null,we.current=I0(we.current,{type:`clear`}).state,Ee(!1),F([]);break;case VU.CF_AGENT_CHAT_MESSAGES:F(he(n.messages));break;case VU.CF_AGENT_MESSAGE_UPDATED:F(e=>{let t=n.message,r=e.findIndex(e=>e.id===t.id);if(r<0){let n=new Set(t.parts.filter(e=>`toolCallId`in e&&e.toolCallId).map(e=>e.toolCallId));n.size>0&&(r=e.findIndex(e=>e.parts.some(e=>`toolCallId`in e&&n.has(e.toolCallId))))}if(r>=0){let n=[...e];return n[r]={...t,id:e[r].id},n}return e});break;case VU.CF_AGENT_STREAM_RESUME_NONE:M.handleStreamResumeNone();break;case VU.CF_AGENT_STREAM_RESUMING:if(!d&&!M.isAwaitingResume()||M.handleStreamResuming(n)||A.current.has(n.id))return;we.current=I0(we.current,{type:`resume-fallback`,streamId:n.id,messageId:W0()}).state,Ee(!0),x.current.send(JSON.stringify({type:VU.CF_AGENT_STREAM_RESUME_ACK,id:n.id}));break;case VU.CF_AGENT_USE_CHAT_RESPONSE:{if(A.current.has(n.id)){if(n.body?.trim())try{let t=JSON.parse(n.body);t.type===`start`&&typeof t.messageId==`string`&&e.set(n.id,t.messageId)}catch{}n.done&&(_e(e.get(n.id)),e.delete(n.id),A.current.delete(n.id));return}let t;if(n.body?.trim())try{t=JSON.parse(n.body),typeof t.type==`string`&&t.type.startsWith(`data-`)&&_.current&&_.current(t)}catch(e){console.warn(`[useAgentChat] Failed to parse stream chunk:`,e instanceof Error?e.message:e,`body:`,n.body?.slice(0,100))}let r=I0(we.current,{type:`response`,streamId:n.id,messageId:W0(),chunkData:t,done:n.done,error:n.error,replay:n.replay,replayComplete:n.replayComplete,continuation:n.continuation,currentMessages:n.continuation?fe.current:void 0});we.current=r.state,r.messagesUpdate&&F(r.messagesUpdate),Ee(r.isStreaming);break}}}return t.addEventListener(`message`,n),()=>{t.removeEventListener(`message`,n),we.current={status:`idle`},Ee(!1),me.current=null,e.clear()}},[t,F,d,M,he,_e]);let De=async e=>{let{toolCallId:t}=e,n=`tool`in e?e.tool:``,r=`output`in e?e.output:void 0;if(x.current.send(JSON.stringify({type:VU.CF_AGENT_TOOL_RESULT,toolCallId:t,toolName:n,output:r,autoContinue:l,clientTools:D.current?p2(D.current):void 0})),de(e=>new Map(e).set(t,r)),I(e),l&&z(),!l){if(!u){L();return}let e=xe.current?.toolCallIds;if(!e){L();return}let n=e.size===1&&e.has(t);e.has(t)&&e.delete(t),(n||e.size===0)&&L()}},Oe=e=>{let{id:t,approved:n}=e,r;for(let e of fe.current){for(let n of e.parts)if(`toolCallId`in n&&`approval`in n&&n.approval?.id===t){r=n.toolCallId;break}if(r)break}r?Ce(r,n):console.warn(`[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID "${t}". Server will not be notified, which may cause duplicate messages.`),ee(e)},ke=(0,B.useMemo)(()=>ue.size===0?P:P.map(e=>({...e,parts:e.parts.map(e=>!(`toolCallId`in e)||!(`state`in e)||e.state!==`input-available`||!ue.has(e.toolCallId)?e:{...e,state:`output-available`,output:ue.get(e.toolCallId)})})),[P,ue]);(0,B.useEffect)(()=>{let e=new Set;for(let t of P)for(let n of t.parts)`toolCallId`in n&&n.toolCallId&&e.add(n.toolCallId);de(t=>{if(t.size===0)return t;let n=!1;for(let r of t.keys())if(!e.has(r)){n=!0;break}if(!n)return t;let r=new Map;for(let[n,i]of t)e.has(n)&&r.set(n,i);return r});for(let t of oe.current)e.has(t)||oe.current.delete(t)},[P]);let Ae=(0,B.useCallback)(e=>{let t=e.toolName??``;Se(e.toolCallId,t,e.output,e.state,e.errorText),I({tool:t,toolCallId:e.toolCallId,output:e.state===`output-error`?e.errorText??`Tool execution denied by user`:e.output})},[Se,I]),je=R===`streaming`||Te;return{...N,messages:ke,isServerStreaming:Te,isStreaming:je,sendMessage:ve,stop:ae,addToolOutput:Ae,addToolResult:De,addToolApprovalResponse:Oe,clearHistory:()=>{F([]),de(new Map),ie.current=!1,oe.current.clear(),pe.current.clear(),me.current=null,t.send(JSON.stringify({type:VU.CF_AGENT_CHAT_CLEAR}))},setMessages:e=>{let n;n=typeof e==`function`?e(fe.current):e,F(n),t.send(JSON.stringify({messages:n,type:VU.CF_AGENT_CHAT_MESSAGES}))}}}var v2=function(e){return e.CF_AGENT_MCP_SERVERS=`cf_agent_mcp_servers`,e.CF_MCP_AGENT_EVENT=`cf_mcp_agent_event`,e.CF_AGENT_STATE=`cf_agent_state`,e.CF_AGENT_STATE_ERROR=`cf_agent_state_error`,e.CF_AGENT_IDENTITY=`cf_agent_identity`,e.CF_AGENT_SESSION=`cf_agent_session`,e.CF_AGENT_SESSION_ERROR=`cf_agent_session_error`,e.RPC=`rpc`,e}({});function y2(e){if(e===e.toUpperCase()&&e!==e.toLowerCase())return e.toLowerCase().replace(/_/g,`-`);let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t=t.startsWith(`-`)?t.slice(1):t,t.replace(/_/g,`-`).replace(/-$/,``)}(!globalThis.EventTarget||!globalThis.Event)&&console.error(`
|
|
307
307
|
PartySocket requires a global 'EventTarget' class to be available!
|
|
308
308
|
You can polyfill this global by adding this to your code before any partysocket imports:
|
|
309
309
|
|
|
@@ -311,7 +311,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
311
311
|
import 'partysocket/event-target-polyfill';
|
|
312
312
|
\`\`\`
|
|
313
313
|
Please file an issue at https://github.com/partykit/partykit if you're still having trouble.
|
|
314
|
-
`);var
|
|
314
|
+
`);var b2=class extends Event{message;error;constructor(e,t){super(`error`,t),this.message=e.message,this.error=e}},x2=class extends Event{code;reason;wasClean=!0;constructor(e=1e3,t=``,n){super(`close`,n),this.code=e,this.reason=t}},S2={Event,ErrorEvent:b2,CloseEvent:x2};function C2(e,t){if(!e)throw Error(t)}function w2(e){return new e.constructor(e.type,e)}function T2(e){return`data`in e?new MessageEvent(e.type,e):`code`in e||`reason`in e?new x2(e.code||1999,e.reason||`unknown reason`,e):`error`in e?new b2(e.error,e):new Event(e.type,e)}var E2=typeof process<`u`&&process.versions?.node!==void 0,D2=typeof navigator<`u`&&navigator.product===`ReactNative`,O2=E2||D2?T2:w2,k2={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},A2=!1,j2=class e extends EventTarget{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType=`blob`;_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(e,t,n={}){super(),this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return e.CONNECTING}get OPEN(){return e.OPEN}get CLOSING(){return e.CLOSING}get CLOSED(){return e.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((e,t)=>(typeof t==`string`?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:``}get protocol(){return this._ws?this._ws.protocol:``}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING}get url(){return this._ws?this._ws.url:``}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(e=1e3,t){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug(`close enqueued: no ws instance`);return}if(this._ws.readyState===this.CLOSED){this._debug(`close: already closed`);return}this._ws.close(e,t)}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED||this._disconnect(e,t),this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug(`send`,e),this._ws.send(e);else{let{maxEnqueuedMessages:t=k2.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&(this._debug(`enqueue`,e),this._messageQueue.push(e))}}_debug(...e){this._options.debug&&this._debugLogger(`RWS>`,...e)}_getNextDelay(){let{reconnectionDelayGrowFactor:e=k2.reconnectionDelayGrowFactor,minReconnectionDelay:t=k2.minReconnectionDelay,maxReconnectionDelay:n=k2.maxReconnectionDelay}=this._options,r=0;return this._retryCount>0&&(r=t*e**(this._retryCount-1),r>n&&(r=n)),this._debug(`next delay`,r),r}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_getNextProtocols(e){if(!e)return Promise.resolve(null);if(typeof e==`string`||Array.isArray(e))return Promise.resolve(e);if(typeof e==`function`){let t=e();if(!t)return Promise.resolve(null);if(typeof t==`string`||Array.isArray(t))return Promise.resolve(t);if(t.then)return t}throw Error(`Invalid protocols`)}_getNextUrl(e){if(typeof e==`string`)return Promise.resolve(e);if(typeof e==`function`){let t=e();if(typeof t==`string`)return Promise.resolve(t);if(t.then)return t}throw Error(`Invalid URL`)}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;let{maxRetries:e=k2.maxRetries,connectionTimeout:t=k2.connectionTimeout}=this._options;if(this._retryCount>=e){this._debug(`max retries reached`,this._retryCount,`>=`,e),this._connectLock=!1;return}this._retryCount++,this._debug(`connect`,this._retryCount),this._removeListeners(),this._wait().then(()=>Promise.all([this._getNextUrl(this._url),this._getNextProtocols(this._protocols||null)])).then(([e,n])=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>`u`&&!A2&&(console.error(`‼️ No WebSocket implementation available. You should define options.WebSocket.
|
|
315
315
|
|
|
316
316
|
For example, if you're using node.js, run \`npm install ws\`, and then in your code:
|
|
317
317
|
|
|
@@ -324,11 +324,11 @@ const partysocket = new PartySocket({
|
|
|
324
324
|
WebSocket: WS
|
|
325
325
|
});
|
|
326
326
|
|
|
327
|
-
`),k2=!0);let r=this._options.WebSocket||WebSocket;this._debug(`connect`,{url:e,protocols:n}),this._ws=n?new r(e,n):new r(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),t)}).catch(e=>{this._connectLock=!1,this._handleError(new x2.ErrorEvent(Error(e.message),this))})}_handleTimeout(){this._debug(`timeout event`),this._handleError(new x2.ErrorEvent(Error(`TIMEOUT`),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(e,t),this._handleClose(new x2.CloseEvent(e,t,this))}catch{}}}_acceptOpen(){this._debug(`accept open`),this._retryCount=0}_handleOpen=e=>{this._debug(`open event`);let{minUptime:t=O2.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),t),S2(this._ws,`WebSocket is not defined`),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(e=>{this._ws?.send(e)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(D2(e))};_handleMessage=e=>{this._debug(`message event`),this.onmessage&&this.onmessage(e),this.dispatchEvent(D2(e))};_handleError=e=>{this._debug(`error event`,e.message),this._disconnect(void 0,e.message===`TIMEOUT`?`timeout`:void 0),this.onerror&&this.onerror(e),this._debug(`exec error listeners`),this.dispatchEvent(D2(e)),this._connect()};_handleClose=e=>{this._debug(`close event`),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(D2(e))};_removeListeners(){this._ws&&(this._debug(`removeListeners`),this._ws.removeEventListener(`open`,this._handleOpen),this._ws.removeEventListener(`close`,this._handleClose),this._ws.removeEventListener(`message`,this._handleMessage),this._ws.removeEventListener(`error`,this._handleError))}_addListeners(){this._ws&&(this._debug(`addListeners`),this._ws.addEventListener(`open`,this._handleOpen),this._ws.addEventListener(`close`,this._handleClose),this._ws.addEventListener(`message`,this._handleMessage),this._ws.addEventListener(`error`,this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}},j2=e=>e[1]!==null&&e[1]!==void 0;function M2(){if(crypto?.randomUUID)return crypto.randomUUID();let e=Date.now(),t=performance?.now&&performance.now()*1e3||0;return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(n){let r=Math.random()*16;return e>0?(r=(e+r)%16|0,e=Math.floor(e/16)):(r=(t+r)%16|0,t=Math.floor(t/16)),(n===`x`?r:r&3|8).toString(16)})}function N2(e,t,n={}){let{host:r,path:i,protocol:a,room:o,party:s,basePath:c,prefix:l,query:u}=e,d=r.replace(/^(http|https|ws|wss):\/\//,``);if(d.endsWith(`/`)&&(d=d.slice(0,-1)),i?.startsWith(`/`))throw Error(`path must not start with a slash`);let f=s??`main`,p=i?`/${i}`:``,m=a||(d.startsWith(`localhost:`)||d.startsWith(`127.0.0.1:`)||d.startsWith(`192.168.`)||d.startsWith(`10.`)||d.startsWith(`172.`)&&d.split(`.`)[1]>=`16`&&d.split(`.`)[1]<=`31`||d.startsWith(`[::ffff:7f00:1]:`)?t:`${t}s`),h=`${m}://${d}/${c||`${l||`parties`}/${f}/${o}`}${p}`,g=(e={})=>`${h}?${new URLSearchParams([...Object.entries(n),...Object.entries(e).filter(j2)])}`,_=typeof u==`function`?async()=>g(await u()):g(u);return{host:d,path:p,room:o,name:f,protocol:m,partyUrl:h,urlProvider:_}}var P2=class extends A2{_pk;_pkurl;name;room;host;path;basePath;constructor(e){let t=F2(e);if(super(t.urlProvider,t.protocols,t.socketOptions),this.partySocketOptions=e,this.setWSProperties(t),!e.startClosed&&!this.room&&!this.basePath)throw this.close(),Error(`Either room or basePath must be provided to connect. Use startClosed: true to create a socket and set them via updateProperties before calling reconnect().`);e.disableNameValidation||(e.party?.includes(`/`)&&console.warn(`PartySocket: party name "${e.party}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`),e.room?.includes(`/`)&&console.warn(`PartySocket: room name "${e.room}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`))}updateProperties(e){let t=F2({...this.partySocketOptions,...e,host:e.host??this.host,room:e.room??this.room,path:e.path??this.path,basePath:e.basePath??this.basePath});this._url=t.urlProvider,this._protocols=t.protocols,this._options=t.socketOptions,this.setWSProperties(t)}setWSProperties(e){let{_pk:t,_pkurl:n,name:r,room:i,host:a,path:o,basePath:s}=e;this._pk=t,this._pkurl=n,this.name=r,this.room=i,this.host=a,this.path=o,this.basePath=s}reconnect(e,t){if(!this.host)throw Error("The host must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");if(!this.room&&!this.basePath)throw Error("The room (or basePath) must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");super.reconnect(e,t)}get id(){return this._pk}get roomUrl(){return this._pkurl}static async fetch(e,t){let n=N2(e,`http`),r=typeof n.urlProvider==`string`?n.urlProvider:await n.urlProvider();return(e.fetch??fetch)(r,t)}};function F2(e){let{id:t,host:n,path:r,party:i,room:a,protocol:o,query:s,protocols:c,...l}=e,u=t||M2(),d=N2(e,`ws`,{_pk:u});return{_pk:u,_pkurl:d.partyUrl,name:d.name,room:d.room,host:d.host,path:d.path,basePath:e.basePath,protocols:c,socketOptions:l,urlProvider:d.urlProvider}}function I2(e){return new Proxy({},{get:(t,n)=>{if(!(typeof n==`symbol`||n===`toJSON`||n===`then`||n===`catch`||n===`finally`||n===`valueOf`||n===`toString`||n===`constructor`||n===`prototype`||n===`$$typeof`||n===`@@toStringTag`||n===`asymmetricMatch`||n===`nodeType`))return(...t)=>e(n,t)}})}var L2=(e,t)=>{let n=(0,B.useRef)(t);n.current=t,(0,B.useEffect)(()=>{let t=e=>n.current?.onOpen?.(e),r=e=>n.current?.onMessage?.(e),i=e=>n.current?.onClose?.(e),a=e=>n.current?.onError?.(e);return e.addEventListener(`open`,t),e.addEventListener(`close`,i),e.addEventListener(`error`,a),e.addEventListener(`message`,r),()=>{e.removeEventListener(`open`,t),e.removeEventListener(`close`,i),e.removeEventListener(`error`,a),e.removeEventListener(`message`,r)}},[e])},R2=e=>[e.startClosed,e.minUptime,e.maxRetries,e.connectionTimeout,e.maxEnqueuedMessages,e.maxReconnectionDelay,e.minReconnectionDelay,e.reconnectionDelayGrowFactor,e.debug];function z2({options:e,createSocket:t,createSocketMemoKey:n}){let{enabled:r=!0}=e,i=(0,B.useMemo)(()=>e,[n(e)]),[a,o]=(0,B.useState)(()=>t({...i,startClosed:!0})),s=(0,B.useRef)(null),c=(0,B.useRef)(t);c.current=t;let l=(0,B.useRef)(r),u=(0,B.useRef)(i),d=(0,B.useRef)(!1);return(0,B.useEffect)(()=>{let e=u.current!==i;if(u.current=i,!r)return a.close(),l.current=r,e&&(d.current=!0),()=>{a.close()};if(!l.current&&r){l.current=r;let t=e||d.current;if(d.current=!1,!t)return a.reconnect(),()=>{a.close()};let n=c.current({...i,startClosed:!0});return o(n),()=>{n.close()}}if(l.current=r,s.current===a)if(e){let e=c.current({...i,startClosed:!0});return o(e),()=>{e.close()}}else return i.startClosed!==!0&&a.reconnect(),()=>{a.close()};else return s.current?s.current!==a&&a.reconnect():i.startClosed!==!0&&a.reconnect(),s.current=a,()=>{a.close()}},[a,i,r]),a}function B2(e){let{host:t,...n}=e,r=z2({options:{host:t||(typeof window<`u`?window.location.host:`dummy-domain.com`),...n},createSocket:e=>new P2(e),createSocketMemoKey:e=>JSON.stringify([e.query,e.id,e.host,e.room,e.party,e.path,e.protocol,e.protocols,e.basePath,e.prefix,...R2(e)])});return L2(r,e),r}var V2=new Map;function H2(e,t,n){return JSON.stringify([e,t||`default`,...n])}function U2(e){let t=V2.get(e);if(t){if(Date.now()>=t.expiresAt){V2.delete(e);return}return t}}function W2(e,t,n){let r={promise:t,expiresAt:Date.now()+n};return V2.set(e,r),r}function G2(e){V2.delete(e)}function K2(e){let t=v2(e.agent),{query:n,queryDeps:r,cacheTtl:i,...a}=e,o=(0,B.useRef)(new Map),s=(0,B.useMemo)(()=>H2(t,e.name,r||[]),[t,e.name,r]),c=(0,B.useRef)(s);c.current=s;let l=i??300*1e3,[u,d]=(0,B.useState)(0),f=n&&typeof n==`function`,[p,m]=(0,B.useState)(!1),h=(0,B.useMemo)(()=>{if(!n||typeof n!=`function`)return null;let t=U2(s);if(t)return t.promise;let r=n().catch(t=>{throw console.error(`[useAgent] Query failed for agent "${e.agent}":`,t),G2(s),t});return W2(s,r,l),r},[s,n,e.agent,l,u]);(0,B.useEffect)(()=>{if(!h||l<=0)return;let e=U2(s);if(!e)return;let t=e.expiresAt-Date.now(),n=setTimeout(()=>{G2(s),d(Date.now())},Math.max(0,t));return()=>clearTimeout(n)},[s,h,l]);let g;if(n)if(typeof n==`function`){let e=(0,B.use)(h);if(e){for(let[t,n]of Object.entries(e))n!=null&&typeof n!=`string`&&typeof n!=`number`&&typeof n!=`boolean`&&console.warn(`[useAgent] Query parameter "${t}" is an object and will be converted to "[object Object]". Query parameters should be string, number, boolean, or null.`);g=e}}else g=n;(0,B.useEffect)(()=>{p&&g!==void 0&&m(!1)},[p,g]);let[_,v]=(0,B.useState)(void 0),[y,b]=(0,B.useState)({name:e.name||`default`,agent:t,identified:!1}),x=(0,B.useRef)({name:null,agent:null}),S=(0,B.useRef)(void 0),C=()=>{let e;S.current={promise:new Promise(t=>{e=t}),resolve:e}};S.current||C();let w=e.basePath?{basePath:e.basePath,path:e.path,query:g,...a}:{party:t,prefix:`agents`,room:e.name||`default`,path:e.path,query:g,...a},T=!p&&(a.enabled??!0),E=B2({...w,enabled:T,onMessage:t=>{if(typeof t.data==`string`){let n;try{n=JSON.parse(t.data)}catch{return e.onMessage?.(t)}if(n.type===_2.CF_AGENT_IDENTITY){let t=x.current.name,r=x.current.agent,i=n.name,a=n.agent;if(b({name:i,agent:a,identified:!0}),S.current?.resolve(),t!==null&&r!==null&&(t!==i||r!==a))if(e.onIdentityChange)e.onIdentityChange(t,i,r,a);else{let e=r!==a,n=t!==i,o=``;o=e&&n?`agent "${r}" → "${a}", instance "${t}" → "${i}"`:e?`agent "${r}" → "${a}"`:`instance "${t}" → "${i}"`,console.warn(`[agents] Identity changed on reconnect: ${o}. This can happen with server-side routing (e.g., basePath with getAgentByName) where the instance is determined by auth/session. Provide onIdentityChange callback to handle this explicitly, or ignore if this is expected for your routing pattern.`)}x.current={name:i,agent:a},e.onIdentity?.(i,a);return}if(n.type===_2.CF_AGENT_STATE){v(n.state),e.onStateUpdate?.(n.state,`server`);return}if(n.type===_2.CF_AGENT_STATE_ERROR){e.onStateUpdateError?.(n.error);return}if(n.type===_2.CF_AGENT_MCP_SERVERS){e.onMcpUpdate?.(n.mcp);return}if(n.type===_2.RPC){let e=n,t=o.current.get(e.id);if(!t)return;if(!e.success){t.reject(Error(e.error)),o.current.delete(e.id),t.stream?.onError?.(e.error);return}`done`in e?e.done?(t.resolve(e.result),o.current.delete(e.id),t.stream?.onDone?.(e.result)):t.stream?.onChunk?.(e.result):(t.resolve(e.result),o.current.delete(e.id));return}}e.onMessage?.(t)},onClose:t=>{C(),b(e=>({...e,identified:!1})),f&&m(!0),G2(c.current),d(Date.now());let n=Error(`Connection closed`);for(let e of o.current.values())e.reject(n),e.stream?.onError?.(`Connection closed`);o.current.clear(),e.onClose?.(t)}}),D=(0,B.useCallback)((e,t=[],n)=>new Promise((r,i)=>{let a=crypto.randomUUID();o.current.set(a,{reject:i,resolve:r,stream:n});let s={args:t,id:a,method:e,type:_2.RPC};E.send(JSON.stringify(s))}),[E]);return E.setState=t=>{E.send(JSON.stringify({state:t,type:_2.CF_AGENT_STATE})),v(t),e.onStateUpdate?.(t,`client`)},E.call=D,E.agent=y.agent,E.name=y.name,E.identified=y.identified,E.ready=S.current.promise,E.state=_,E.stub=(0,B.useMemo)(()=>I2(D),[D]),E.getHttpUrl=()=>(E._url||E._pkurl||``).replace(`ws://`,`http://`).replace(`wss://`,`https://`),y.agent!==y.agent.toLowerCase()&&console.warn(`Agent name: `+y.agent+` should probably be in lowercase. Received: `+y.agent),E}function q2(e){let{agent:t,host:n,basePath:r,chatId:i,authToken:a,toolContext:o,connectionParams:s,welcomeMessage:c,onConnectionStatusChange:l,onOpen:u,onClose:d,onError:f}=e,[p,m]=B.useState(`connecting`),h=B.useCallback(e=>{m(e),l?.(e)},[l]),g={};a&&(g.Authorization=`Bearer ${a}`,[].push(`bearer`,a));let _=K2({agent:t,host:n,basePath:r,name:i,query:s??{},queryDeps:Object.keys(s??{}),onOpen:e=>{h(`connected`),u?.(e)},onClose:e=>{if(e.code>=3e3){h(`unauthorized`),_.close(),d?.(e);return}h(`disconnected`),d?.(e)},onError:f}),v=g2({agent:_,body:o??{}}),y=B.useRef(!1);return B.useEffect(()=>{c&&p===`connected`&&v.messages.length===0&&!y.current&&(y.current=!0,v.sendMessage({role:`assistant`,parts:[{type:`text`,text:c}]}))},[p,v.messages.length,c]),{agent:_,chat:v,connectionStatus:p}}function J2({part:e,partIndex:t,userMode:n}){if(m0(e))return(0,U.jsx)(jE,{children:e.text},t);if(v0(e)){if(n)return null;let r=b0(e);return(0,U.jsxs)(NU,{defaultOpen:e.state===`output-error`,children:[e.type===`dynamic-tool`?(0,U.jsx)(LU,{state:e.state,title:r,toolName:r,type:`dynamic-tool`}):(0,U.jsx)(LU,{state:e.state,title:r,type:e.type}),(0,U.jsxs)(RU,{children:[(0,U.jsx)(zU,{input:e.input}),(0,U.jsx)(BU,{errorText:e.errorText,output:e.output})]})]},t)}return e.type===`source-url`?(0,U.jsx)(VB,{href:e.url,title:e.title??e.url},t):e.type===`source-document`?(0,U.jsx)(VB,{href:`#${e.sourceId}`,title:e.title},t):null}function Y2({message:e,isStreaming:t,userMode:n}){let r=e.parts.filter(e=>e.type===`source-url`||e.type===`source-document`),i=e.parts.filter(e=>e.type!==`source-url`&&e.type!==`source-document`),a=i.filter(h0),o=i.filter(e=>!h0(e)),s=a.map(e=>e.text).join(`
|
|
327
|
+
`),A2=!0);let r=this._options.WebSocket||WebSocket;this._debug(`connect`,{url:e,protocols:n}),this._ws=n?new r(e,n):new r(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),t)}).catch(e=>{this._connectLock=!1,this._handleError(new S2.ErrorEvent(Error(e.message),this))})}_handleTimeout(){this._debug(`timeout event`),this._handleError(new S2.ErrorEvent(Error(`TIMEOUT`),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(e,t),this._handleClose(new S2.CloseEvent(e,t,this))}catch{}}}_acceptOpen(){this._debug(`accept open`),this._retryCount=0}_handleOpen=e=>{this._debug(`open event`);let{minUptime:t=k2.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),t),C2(this._ws,`WebSocket is not defined`),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(e=>{this._ws?.send(e)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(O2(e))};_handleMessage=e=>{this._debug(`message event`),this.onmessage&&this.onmessage(e),this.dispatchEvent(O2(e))};_handleError=e=>{this._debug(`error event`,e.message),this._disconnect(void 0,e.message===`TIMEOUT`?`timeout`:void 0),this.onerror&&this.onerror(e),this._debug(`exec error listeners`),this.dispatchEvent(O2(e)),this._connect()};_handleClose=e=>{this._debug(`close event`),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(O2(e))};_removeListeners(){this._ws&&(this._debug(`removeListeners`),this._ws.removeEventListener(`open`,this._handleOpen),this._ws.removeEventListener(`close`,this._handleClose),this._ws.removeEventListener(`message`,this._handleMessage),this._ws.removeEventListener(`error`,this._handleError))}_addListeners(){this._ws&&(this._debug(`addListeners`),this._ws.addEventListener(`open`,this._handleOpen),this._ws.addEventListener(`close`,this._handleClose),this._ws.addEventListener(`message`,this._handleMessage),this._ws.addEventListener(`error`,this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}},M2=e=>e[1]!==null&&e[1]!==void 0;function N2(){if(crypto?.randomUUID)return crypto.randomUUID();let e=Date.now(),t=performance?.now&&performance.now()*1e3||0;return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(n){let r=Math.random()*16;return e>0?(r=(e+r)%16|0,e=Math.floor(e/16)):(r=(t+r)%16|0,t=Math.floor(t/16)),(n===`x`?r:r&3|8).toString(16)})}function P2(e,t,n={}){let{host:r,path:i,protocol:a,room:o,party:s,basePath:c,prefix:l,query:u}=e,d=r.replace(/^(http|https|ws|wss):\/\//,``);if(d.endsWith(`/`)&&(d=d.slice(0,-1)),i?.startsWith(`/`))throw Error(`path must not start with a slash`);let f=s??`main`,p=i?`/${i}`:``,m=a||(d.startsWith(`localhost:`)||d.startsWith(`127.0.0.1:`)||d.startsWith(`192.168.`)||d.startsWith(`10.`)||d.startsWith(`172.`)&&d.split(`.`)[1]>=`16`&&d.split(`.`)[1]<=`31`||d.startsWith(`[::ffff:7f00:1]:`)?t:`${t}s`),h=`${m}://${d}/${c||`${l||`parties`}/${f}/${o}`}${p}`,g=(e={})=>`${h}?${new URLSearchParams([...Object.entries(n),...Object.entries(e).filter(M2)])}`,_=typeof u==`function`?async()=>g(await u()):g(u);return{host:d,path:p,room:o,name:f,protocol:m,partyUrl:h,urlProvider:_}}var F2=class extends j2{_pk;_pkurl;name;room;host;path;basePath;constructor(e){let t=I2(e);if(super(t.urlProvider,t.protocols,t.socketOptions),this.partySocketOptions=e,this.setWSProperties(t),!e.startClosed&&!this.room&&!this.basePath)throw this.close(),Error(`Either room or basePath must be provided to connect. Use startClosed: true to create a socket and set them via updateProperties before calling reconnect().`);e.disableNameValidation||(e.party?.includes(`/`)&&console.warn(`PartySocket: party name "${e.party}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`),e.room?.includes(`/`)&&console.warn(`PartySocket: room name "${e.room}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`))}updateProperties(e){let t=I2({...this.partySocketOptions,...e,host:e.host??this.host,room:e.room??this.room,path:e.path??this.path,basePath:e.basePath??this.basePath});this._url=t.urlProvider,this._protocols=t.protocols,this._options=t.socketOptions,this.setWSProperties(t)}setWSProperties(e){let{_pk:t,_pkurl:n,name:r,room:i,host:a,path:o,basePath:s}=e;this._pk=t,this._pkurl=n,this.name=r,this.room=i,this.host=a,this.path=o,this.basePath=s}reconnect(e,t){if(!this.host)throw Error("The host must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");if(!this.room&&!this.basePath)throw Error("The room (or basePath) must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");super.reconnect(e,t)}get id(){return this._pk}get roomUrl(){return this._pkurl}static async fetch(e,t){let n=P2(e,`http`),r=typeof n.urlProvider==`string`?n.urlProvider:await n.urlProvider();return(e.fetch??fetch)(r,t)}};function I2(e){let{id:t,host:n,path:r,party:i,room:a,protocol:o,query:s,protocols:c,...l}=e,u=t||N2(),d=P2(e,`ws`,{_pk:u});return{_pk:u,_pkurl:d.partyUrl,name:d.name,room:d.room,host:d.host,path:d.path,basePath:e.basePath,protocols:c,socketOptions:l,urlProvider:d.urlProvider}}function L2(e){return new Proxy({},{get:(t,n)=>{if(!(typeof n==`symbol`||n===`toJSON`||n===`then`||n===`catch`||n===`finally`||n===`valueOf`||n===`toString`||n===`constructor`||n===`prototype`||n===`$$typeof`||n===`@@toStringTag`||n===`asymmetricMatch`||n===`nodeType`))return(...t)=>e(n,t)}})}var R2=(e,t)=>{let n=(0,B.useRef)(t);n.current=t,(0,B.useEffect)(()=>{let t=e=>n.current?.onOpen?.(e),r=e=>n.current?.onMessage?.(e),i=e=>n.current?.onClose?.(e),a=e=>n.current?.onError?.(e);return e.addEventListener(`open`,t),e.addEventListener(`close`,i),e.addEventListener(`error`,a),e.addEventListener(`message`,r),()=>{e.removeEventListener(`open`,t),e.removeEventListener(`close`,i),e.removeEventListener(`error`,a),e.removeEventListener(`message`,r)}},[e])},z2=e=>[e.startClosed,e.minUptime,e.maxRetries,e.connectionTimeout,e.maxEnqueuedMessages,e.maxReconnectionDelay,e.minReconnectionDelay,e.reconnectionDelayGrowFactor,e.debug];function B2({options:e,createSocket:t,createSocketMemoKey:n}){let{enabled:r=!0}=e,i=(0,B.useMemo)(()=>e,[n(e)]),[a,o]=(0,B.useState)(()=>t({...i,startClosed:!0})),s=(0,B.useRef)(null),c=(0,B.useRef)(t);c.current=t;let l=(0,B.useRef)(r),u=(0,B.useRef)(i),d=(0,B.useRef)(!1);return(0,B.useEffect)(()=>{let e=u.current!==i;if(u.current=i,!r)return a.close(),l.current=r,e&&(d.current=!0),()=>{a.close()};if(!l.current&&r){l.current=r;let t=e||d.current;if(d.current=!1,!t)return a.reconnect(),()=>{a.close()};let n=c.current({...i,startClosed:!0});return o(n),()=>{n.close()}}if(l.current=r,s.current===a)if(e){let e=c.current({...i,startClosed:!0});return o(e),()=>{e.close()}}else return i.startClosed!==!0&&a.reconnect(),()=>{a.close()};else return s.current?s.current!==a&&a.reconnect():i.startClosed!==!0&&a.reconnect(),s.current=a,()=>{a.close()}},[a,i,r]),a}function V2(e){let{host:t,...n}=e,r=B2({options:{host:t||(typeof window<`u`?window.location.host:`dummy-domain.com`),...n},createSocket:e=>new F2(e),createSocketMemoKey:e=>JSON.stringify([e.query,e.id,e.host,e.room,e.party,e.path,e.protocol,e.protocols,e.basePath,e.prefix,...z2(e)])});return R2(r,e),r}var H2=new Map;function U2(e,t,n){return JSON.stringify([e,t||`default`,...n])}function W2(e){let t=H2.get(e);if(t){if(Date.now()>=t.expiresAt){H2.delete(e);return}return t}}function G2(e,t,n){let r={promise:t,expiresAt:Date.now()+n};return H2.set(e,r),r}function K2(e){H2.delete(e)}function q2(e){let t=y2(e.agent),{query:n,queryDeps:r,cacheTtl:i,...a}=e,o=(0,B.useRef)(new Map),s=(0,B.useMemo)(()=>U2(t,e.name,r||[]),[t,e.name,r]),c=(0,B.useRef)(s);c.current=s;let l=i??300*1e3,[u,d]=(0,B.useState)(0),f=n&&typeof n==`function`,[p,m]=(0,B.useState)(!1),h=(0,B.useMemo)(()=>{if(!n||typeof n!=`function`)return null;let t=W2(s);if(t)return t.promise;let r=n().catch(t=>{throw console.error(`[useAgent] Query failed for agent "${e.agent}":`,t),K2(s),t});return G2(s,r,l),r},[s,n,e.agent,l,u]);(0,B.useEffect)(()=>{if(!h||l<=0)return;let e=W2(s);if(!e)return;let t=e.expiresAt-Date.now(),n=setTimeout(()=>{K2(s),d(Date.now())},Math.max(0,t));return()=>clearTimeout(n)},[s,h,l]);let g;if(n)if(typeof n==`function`){let e=(0,B.use)(h);if(e){for(let[t,n]of Object.entries(e))n!=null&&typeof n!=`string`&&typeof n!=`number`&&typeof n!=`boolean`&&console.warn(`[useAgent] Query parameter "${t}" is an object and will be converted to "[object Object]". Query parameters should be string, number, boolean, or null.`);g=e}}else g=n;(0,B.useEffect)(()=>{p&&g!==void 0&&m(!1)},[p,g]);let[_,v]=(0,B.useState)(void 0),[y,b]=(0,B.useState)({name:e.name||`default`,agent:t,identified:!1}),x=(0,B.useRef)({name:null,agent:null}),S=(0,B.useRef)(void 0),C=()=>{let e;S.current={promise:new Promise(t=>{e=t}),resolve:e}};S.current||C();let w=e.basePath?{basePath:e.basePath,path:e.path,query:g,...a}:{party:t,prefix:`agents`,room:e.name||`default`,path:e.path,query:g,...a},T=!p&&(a.enabled??!0),E=V2({...w,enabled:T,onMessage:t=>{if(typeof t.data==`string`){let n;try{n=JSON.parse(t.data)}catch{return e.onMessage?.(t)}if(n.type===v2.CF_AGENT_IDENTITY){let t=x.current.name,r=x.current.agent,i=n.name,a=n.agent;if(b({name:i,agent:a,identified:!0}),S.current?.resolve(),t!==null&&r!==null&&(t!==i||r!==a))if(e.onIdentityChange)e.onIdentityChange(t,i,r,a);else{let e=r!==a,n=t!==i,o=``;o=e&&n?`agent "${r}" → "${a}", instance "${t}" → "${i}"`:e?`agent "${r}" → "${a}"`:`instance "${t}" → "${i}"`,console.warn(`[agents] Identity changed on reconnect: ${o}. This can happen with server-side routing (e.g., basePath with getAgentByName) where the instance is determined by auth/session. Provide onIdentityChange callback to handle this explicitly, or ignore if this is expected for your routing pattern.`)}x.current={name:i,agent:a},e.onIdentity?.(i,a);return}if(n.type===v2.CF_AGENT_STATE){v(n.state),e.onStateUpdate?.(n.state,`server`);return}if(n.type===v2.CF_AGENT_STATE_ERROR){e.onStateUpdateError?.(n.error);return}if(n.type===v2.CF_AGENT_MCP_SERVERS){e.onMcpUpdate?.(n.mcp);return}if(n.type===v2.RPC){let e=n,t=o.current.get(e.id);if(!t)return;if(!e.success){t.reject(Error(e.error)),o.current.delete(e.id),t.stream?.onError?.(e.error);return}`done`in e?e.done?(t.resolve(e.result),o.current.delete(e.id),t.stream?.onDone?.(e.result)):t.stream?.onChunk?.(e.result):(t.resolve(e.result),o.current.delete(e.id));return}}e.onMessage?.(t)},onClose:t=>{C(),b(e=>({...e,identified:!1})),f&&m(!0),K2(c.current),d(Date.now());let n=Error(`Connection closed`);for(let e of o.current.values())e.reject(n),e.stream?.onError?.(`Connection closed`);o.current.clear(),e.onClose?.(t)}}),D=(0,B.useCallback)((e,t=[],n)=>new Promise((r,i)=>{let a=crypto.randomUUID();o.current.set(a,{reject:i,resolve:r,stream:n});let s={args:t,id:a,method:e,type:v2.RPC};E.send(JSON.stringify(s))}),[E]);return E.setState=t=>{E.send(JSON.stringify({state:t,type:v2.CF_AGENT_STATE})),v(t),e.onStateUpdate?.(t,`client`)},E.call=D,E.agent=y.agent,E.name=y.name,E.identified=y.identified,E.ready=S.current.promise,E.state=_,E.stub=(0,B.useMemo)(()=>L2(D),[D]),E.getHttpUrl=()=>(E._url||E._pkurl||``).replace(`ws://`,`http://`).replace(`wss://`,`https://`),y.agent!==y.agent.toLowerCase()&&console.warn(`Agent name: `+y.agent+` should probably be in lowercase. Received: `+y.agent),E}function J2(e){let{agent:t,host:n,basePath:r,chatId:i,authToken:a,toolContext:o,connectionParams:s,welcomeMessage:c,onConnectionStatusChange:l,onOpen:u,onClose:d,onError:f}=e,[p,m]=B.useState(`connecting`),h=B.useCallback(e=>{m(e),l?.(e)},[l]),g={},_=[];a&&(g.Authorization=`Bearer ${a}`,_.push(`bearer`,a));let v=q2({agent:t,host:n,basePath:r,name:i,query:s??{},queryDeps:Object.keys(s??{}),onOpen:e=>{h(`connected`),u?.(e)},onClose:e=>{if(e.code>=3e3){h(`unauthorized`),v.close(),d?.(e);return}h(`disconnected`),d?.(e)},onError:f,protocols:_}),y=_2({agent:v,body:o??{},headers:g}),b=B.useRef(!1);return B.useEffect(()=>{c&&p===`connected`&&y.messages.length===0&&!b.current&&(b.current=!0,y.setMessages([{id:`welcome-message`,role:`assistant`,parts:[{type:`text`,text:c}]}]))},[p,y.messages.length,c]),{agent:v,chat:y,connectionStatus:p}}function Y2({part:e,partIndex:t,userMode:n}){if(m0(e))return(0,U.jsx)(jE,{children:e.text},t);if(v0(e)){if(n)return null;let r=b0(e);return(0,U.jsxs)(NU,{defaultOpen:e.state===`output-error`,children:[e.type===`dynamic-tool`?(0,U.jsx)(LU,{state:e.state,title:r,toolName:r,type:`dynamic-tool`}):(0,U.jsx)(LU,{state:e.state,title:r,type:e.type}),(0,U.jsxs)(RU,{children:[(0,U.jsx)(zU,{input:e.input}),(0,U.jsx)(BU,{errorText:e.errorText,output:e.output})]})]},t)}return e.type===`source-url`?(0,U.jsx)(VB,{href:e.url,title:e.title??e.url},t):e.type===`source-document`?(0,U.jsx)(VB,{href:`#${e.sourceId}`,title:e.title},t):null}function X2({message:e,isStreaming:t,userMode:n}){let r=e.parts.filter(e=>e.type===`source-url`||e.type===`source-document`),i=e.parts.filter(e=>e.type!==`source-url`&&e.type!==`source-document`),a=i.filter(h0),o=i.filter(e=>!h0(e)),s=a.map(e=>e.text).join(`
|
|
328
328
|
|
|
329
329
|
---
|
|
330
330
|
|
|
331
|
-
`),c=o.some(m0),l=!t&&!c&&a.length>0;return(0,U.jsx)(wE,{from:e.role,children:(0,U.jsxs)(`div`,{children:[r.length>0&&(0,U.jsxs)(RB,{children:[(0,U.jsx)(zB,{count:r.length}),(0,U.jsx)(BB,{children:r.map((e,t)=>e.type===`source-url`?(0,U.jsx)(VB,{href:e.url,title:e.title??e.url},t):(0,U.jsx)(VB,{href:`#${e.sourceId}`,title:e.title},t))})]}),(0,U.jsx)(TE,{children:l?(0,U.jsx)(jE,{children:s}):(0,U.jsxs)(U.Fragment,{children:[s&&!n&&(0,U.jsxs)(NB,{defaultOpen:!1,isStreaming:t,children:[(0,U.jsx)(FB,{}),(0,U.jsx)(LB,{children:s})]}),o.map((e,r)=>(0,U.jsx)(J2,{isStreaming:t,part:e,partIndex:r,userMode:n},r))]})})]})})}var X2=({attachment:e,onRemove:t})=>(0,U.jsxs)(td,{data:e,onRemove:(0,B.useCallback)(()=>{t(e.id)},[t,e.id]),children:[(0,U.jsx)(nd,{}),(0,U.jsx)(rd,{})]}),Z2=()=>{let e=dk(),t=(0,B.useCallback)(t=>{e.remove(t)},[e]);return e.files.length===0?null:(0,U.jsx)(ed,{variant:`inline`,children:e.files.map(e=>(0,U.jsx)(X2,{attachment:e,onRemove:t},e.id))})},Q2=({chatId:e,host:t,agentName:n,agentUrl:r,authToken:i,body:a,query:o,welcomeMessage:s,onAgentChange:c,onConnectionStatusChange:l,onRetry:u,onUnauthorized:d,userMode:f})=>{let[p,m]=(0,B.useState)(``),[h,g]=(0,B.useState)(!1),{agent:_,chat:v,connectionStatus:y}=q2({agent:n,host:t,chatId:e,authToken:i,toolContext:a??{},connectionParams:o??{},onConnectionStatusChange:l,welcomeMessage:s,onClose:e=>{e.code>=3e3&&d?.(e.reason??``)}});(0,B.useEffect)(()=>(c?.(_),()=>{c?.(null)}),[_,c]);let{messages:b,sendMessage:x,status:S,stop:C}=v,w=(0,B.useMemo)(()=>b.filter(e=>e.role!==`system`),[b]),T=(0,B.useCallback)(e=>{let t=!!e.text?.trim(),n=!!e.files?.length;if(!(t||n))return;let r=[];if(e.text?.trim()&&r.push({type:`text`,text:e.text.trim()}),e.files?.length)for(let t of e.files)r.push({type:`text`,text:`[Attachment: ${t.filename??`file`}]`});x({role:`user`,parts:r}),m(``),e.files?.length&&nt.success(`Files attached`,{description:`${e.files.length} file(s) attached to message`})},[x]),E=(0,B.useCallback)(e=>{m(t=>t?`${t} ${e}`:e)},[]),D=(0,B.useCallback)(e=>{m(e.target.value)},[]),O=(0,B.useCallback)(()=>{g(e=>!e)},[]),k=(0,B.useMemo)(()=>String(S)===`idle`||String(S)===`ready`?`ready`:S===`submitted`||S===`streaming`||S===`error`?S:`ready`,[S]),A=(0,B.useMemo)(()=>{if(k!==`submitted`&&k!==`streaming`)return!1;let e=w.at(-1);if(!e||e.role===`user`)return!0;if(e.role===`assistant`){let t=e.parts?.some(e=>e.type===`text`),n=e.parts?.some(e=>e.type===`reasoning`);return!t&&!n}return!1},[k,w]),j=(0,B.useMemo)(()=>!p.trim()||k===`streaming`||k===`submitted`,[p,k]);return y===`connecting`?(0,U.jsxs)(`div`,{className:`flex size-full flex-col items-center justify-center gap-3 text-muted-foreground`,children:[(0,U.jsx)(`div`,{className:`h-6 w-6 rounded-full border-2 border-zinc-300 border-t-zinc-600 animate-spin`}),(0,U.jsx)(`p`,{className:`text-sm`,children:`Connecting to agent...`})]}):y===`disconnected`?(0,U.jsxs)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4`,children:[(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Unable to connect`}),r&&(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground max-w-xs`,children:[`Could not reach `,(0,U.jsx)(`span`,{className:`font-mono`,children:r}),`. Check the URL and make sure the agent is running.`]})]}),u&&(0,U.jsx)(`button`,{className:`text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground transition-colors`,onClick:u,children:`Try again`})]}):(0,U.jsxs)(`div`,{className:`relative flex size-full flex-col divide-y overflow-hidden`,children:[(0,U.jsxs)(_d,{children:[(0,U.jsxs)(vd,{children:[w.map((e,t)=>(0,U.jsx)(OE,{defaultBranch:0,children:(0,U.jsx)(kE,{children:(0,U.jsx)(Y2,{isStreaming:k===`streaming`&&t===w.length-1,message:e,userMode:f})})},e.id)),A&&(0,U.jsx)(wE,{from:`assistant`,children:(0,U.jsx)(TE,{children:(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground text-sm`,children:[(0,U.jsx)(nk,{className:`size-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:`Thinking...`})]})})})]}),(0,U.jsx)(yd,{})]}),(0,U.jsx)(`div`,{className:`grid shrink-0 gap-4 pt-4`,children:(0,U.jsx)(`div`,{className:`w-full px-4 pb-4`,children:(0,U.jsxs)(mk,{globalDrop:!0,multiple:!0,onSubmit:T,children:[(0,U.jsx)(_k,{children:(0,U.jsx)(Z2,{})}),(0,U.jsx)(hk,{children:(0,U.jsx)(gk,{onChange:D,value:p})}),(0,U.jsxs)(vk,{children:[(0,U.jsxs)(yk,{children:[(0,U.jsxs)(xk,{children:[(0,U.jsx)(Sk,{}),(0,U.jsx)(Ck,{children:(0,U.jsx)(pk,{})})]}),(0,U.jsx)(UB,{className:`shrink-0`,onTranscriptionChange:E,size:`icon-sm`,variant:`ghost`}),(0,U.jsxs)(bk,{onClick:O,variant:h?`default`:`ghost`,children:[(0,U.jsx)(Au,{size:16}),(0,U.jsx)(`span`,{children:`Search`})]})]}),(0,U.jsx)(wk,{disabled:j,onStop:C,status:k})]})]})})})]})};function $2({className:e,size:t=`default`,...n}){return(0,U.jsx)(`div`,{"data-slot":`card`,"data-size":t,className:H(`group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl`,e),...n})}function e4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-header`,className:H(`group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3`,e),...t})}function t4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-title`,className:H(`text-base leading-snug font-medium group-data-[size=sm]/card:text-sm`,e),...t})}function n4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-description`,className:H(`text-sm text-muted-foreground`,e),...t})}function r4({...e}){return(0,U.jsx)(SD,{"data-slot":`sheet`,...e})}function i4({...e}){return(0,U.jsx)(wD,{"data-slot":`sheet-trigger`,...e})}function a4({...e}){return(0,U.jsx)(aD,{"data-slot":`sheet-portal`,...e})}function o4({className:e,children:t,side:n=`right`,showCloseButton:r=!0,...i}){return(0,U.jsx)(a4,{children:(0,U.jsxs)(rD,{"data-slot":`sheet-content`,"data-side":n,className:H(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm`,e),...i,children:[t,r&&(0,U.jsx)(VE,{"data-slot":`sheet-close`,render:(0,U.jsxs)(Yn,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,U.jsx)(Ku,{}),(0,U.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})]})})}function s4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`sheet-header`,className:H(`flex flex-col gap-0.5 p-4`,e),...t})}function c4({className:e,...t}){return(0,U.jsx)(CD,{"data-slot":`sheet-title`,className:H(`cn-font-heading text-base font-medium text-foreground`,e),...t})}function l4({className:e,...t}){return(0,U.jsx)(HE,{"data-slot":`sheet-description`,className:H(`text-sm text-muted-foreground`,e),...t})}function u4(e){return!e||typeof e!=`object`?!1:`durable_object_name`in e||`title`in e||`summary`in e||`created_at`in e||`updated_at`in e}function d4(e){return Array.isArray(e)?{rows:e.filter(u4),supported:!0}:{rows:[],supported:!1}}function f4(e){if(e==null||e===``)return`Unknown time`;let t=new Date(e);return Number.isNaN(t.getTime())?`Unknown time`:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function p4(e){let t=e?.trim();return t?t.length>180?`${t.slice(0,177)}...`:t:`No summary available yet.`}function m4(e){return e.title?.trim()||`Untitled conversation`}function h4(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function g4({agent:e,connectionStatus:t,currentChatId:n,onConversationClick:r}){let[i,a]=(0,B.useState)(!1),[o,s]=(0,B.useState)([]),[c,l]=(0,B.useState)(`disconnected`),[u,d]=(0,B.useState)(null),[f,p]=(0,B.useState)(null),m=(0,B.useMemo)(()=>t===`unauthorized`?{title:`Unauthorized`,description:`Reconnect with valid credentials to load conversations.`}:{title:`Disconnected`,description:`Connect to the agent to load conversations for the active identity.`},[t]),h=(0,B.useCallback)(async()=>{if(!e){l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null);return}if(t!==`connected`){l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null);return}l(`loading`),d(null);try{let{rows:t,supported:n}=d4(await e.call(`getConversations`));s(t),p(new Date().toISOString()),l(n?t.length>0?`ready`:`empty`:`unsupported`)}catch(e){d(e instanceof Error?e.message:String(e)),l(`error`)}},[e,t]);return(0,B.useEffect)(()=>{if(t===`connected`&&e&&!i){h();return}if(i){if(t===`connected`&&e){h();return}l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null)}},[i,t,h]),(0,U.jsxs)(r4,{open:i,onOpenChange:a,children:[(0,U.jsx)(i4,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsx)(Yn,{"aria-label":`Conversation history`,title:`Conversation history`,size:`icon-sm`,variant:`outline`,className:`relative`,children:(0,U.jsx)(Fu,{className:`size-4`})})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Conversation history`})})]})}),(0,U.jsxs)(o4,{className:`gap-0`,children:[(0,U.jsxs)(s4,{children:[(0,U.jsxs)(c4,{children:[`Conversation history`,(0,U.jsx)(Yn,{"aria-label":`Refresh conversations`,className:`absolute top-3 right-10`,onClick:()=>void h(),size:`icon-sm`,variant:`ghost`,children:(0,U.jsx)(Bu,{className:`size-4`})})]}),(0,U.jsx)(l4,{children:`Recent conversations for the connected identity.`})]}),(0,U.jsx)(`div`,{className:`border-b px-4 pb-3 text-xs text-muted-foreground`,children:f?(0,U.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,U.jsx)(wu,{className:`size-3.5`}),`Last refreshed`,` `,new Intl.DateTimeFormat(void 0,{timeStyle:`short`}).format(new Date(f))]}):(0,U.jsx)(`span`,{children:`Open the panel to load conversations from the current session.`})}),(0,U.jsxs)(`div`,{className:`overflow-y-auto`,children:[c===`loading`&&(0,U.jsx)(`div`,{className:`flex h-full items-center justify-center px-4`,children:(0,U.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,U.jsx)(nk,{className:`size-4`}),`Loading conversations...`]})}),c===`unauthorized`||c===`disconnected`?(0,U.jsx)(`div`,{className:`flex h-full items-center justify-center px-4`,children:(0,U.jsx)($2,{size:`sm`,className:`w-full border-dashed`,children:(0,U.jsxs)(e4,{children:[(0,U.jsx)(t4,{className:`text-sm`,children:m.title}),(0,U.jsx)(n4,{children:m.description})]})})}):null,c===`error`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{className:`text-red-600`,children:`Could not load conversations`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u??`An unexpected error occurred while loading the conversation list.`}),(0,U.jsx)(Yn,{onClick:()=>void h(),size:`sm`,variant:`outline`,children:`Retry`})]}):null,c===`empty`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{children:`No conversations yet`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This identity has not created any saved conversations.`})]}):null,c===`unsupported`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{children:`Conversations unavailable`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This agent does not expose saved conversations for the current identity.`})]}):null,c===`ready`?(0,U.jsx)(`div`,{className:`flex flex-col gap-3 p-4`,children:o.map((e,t)=>{let i=h4(e.durable_object_name??``);return(0,U.jsx)(`article`,{className:[`rounded-lg border bg-card p-3 shadow-sm transition-shadow hover:shadow-md cursor-pointer`,n&&i===n?`ring-2 ring-primary border-primary`:``].filter(Boolean).join(` `),onClick:()=>{a(!1),r(i)},children:(0,U.jsxs)(`div`,{className:`flex flex-col justify-between gap-2`,children:[(0,U.jsxs)(`div`,{className:`min-w-0 flex gap-x-2 items-center`,children:[(0,U.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:m4(e)}),(0,U.jsx)(`time`,{className:`shrink-0 text-[11px] text-muted-foreground ml-auto`,children:f4(e.updated_at)})]}),(0,U.jsx)(`p`,{className:`mt-1 line-clamp-3 text-xs leading-relaxed text-muted-foreground`,children:p4(e.summary)})]})},e.durable_object_name??`${e.updated_at??t}`)})}):null]})]})]})}var _4=class extends B.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}render(){return this.state.error?(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4 text-muted-foreground`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Something went wrong`}),(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:`Could not connect to the agent. Check the URL above and try again.`})]})}):this.props.children}};function v4(e){try{let t=JSON.parse(e);return typeof t==`object`&&!!t&&Object.keys(t).length>0}catch{return!1}}var y4=`{
|
|
331
|
+
`),c=o.some(m0),l=!t&&!c&&a.length>0;return(0,U.jsx)(wE,{from:e.role,children:(0,U.jsxs)(`div`,{children:[r.length>0&&(0,U.jsxs)(RB,{children:[(0,U.jsx)(zB,{count:r.length}),(0,U.jsx)(BB,{children:r.map((e,t)=>e.type===`source-url`?(0,U.jsx)(VB,{href:e.url,title:e.title??e.url},t):(0,U.jsx)(VB,{href:`#${e.sourceId}`,title:e.title},t))})]}),(0,U.jsx)(TE,{children:l?(0,U.jsx)(jE,{children:s}):(0,U.jsxs)(U.Fragment,{children:[s&&!n&&(0,U.jsxs)(NB,{defaultOpen:!1,isStreaming:t,children:[(0,U.jsx)(FB,{}),(0,U.jsx)(LB,{children:s})]}),o.map((e,r)=>(0,U.jsx)(Y2,{isStreaming:t,part:e,partIndex:r,userMode:n},r))]})})]})})}var Z2=({attachment:e,onRemove:t})=>(0,U.jsxs)(td,{data:e,onRemove:(0,B.useCallback)(()=>{t(e.id)},[t,e.id]),children:[(0,U.jsx)(nd,{}),(0,U.jsx)(rd,{})]}),Q2=()=>{let e=dk(),t=(0,B.useCallback)(t=>{e.remove(t)},[e]);return e.files.length===0?null:(0,U.jsx)(ed,{variant:`inline`,children:e.files.map(e=>(0,U.jsx)(Z2,{attachment:e,onRemove:t},e.id))})},$2=({chatId:e,host:t,agentName:n,agentUrl:r,authToken:i,body:a,query:o,welcomeMessage:s,onAgentChange:c,onConnectionStatusChange:l,onRetry:u,onUnauthorized:d,userMode:f})=>{let[p,m]=(0,B.useState)(``),[h,g]=(0,B.useState)(!1),{agent:_,chat:v,connectionStatus:y}=J2({agent:n,host:t,chatId:e,authToken:i,toolContext:a??{},connectionParams:o??{},onConnectionStatusChange:l,welcomeMessage:s,onClose:e=>{e.code>=3e3&&d?.(e.reason??``)}});(0,B.useEffect)(()=>(c?.(_),()=>{c?.(null)}),[_,c]);let{messages:b,sendMessage:x,status:S,stop:C}=v,w=(0,B.useMemo)(()=>b.filter(e=>e.role!==`system`),[b]),T=(0,B.useCallback)(e=>{let t=!!e.text?.trim(),n=!!e.files?.length;if(!(t||n))return;let r=[];if(e.text?.trim()&&r.push({type:`text`,text:e.text.trim()}),e.files?.length)for(let t of e.files)r.push({type:`text`,text:`[Attachment: ${t.filename??`file`}]`});x({role:`user`,parts:r}),m(``),e.files?.length&&nt.success(`Files attached`,{description:`${e.files.length} file(s) attached to message`})},[x]),E=(0,B.useCallback)(e=>{m(t=>t?`${t} ${e}`:e)},[]),D=(0,B.useCallback)(e=>{m(e.target.value)},[]),O=(0,B.useCallback)(()=>{g(e=>!e)},[]),k=(0,B.useMemo)(()=>String(S)===`idle`||String(S)===`ready`?`ready`:S===`submitted`||S===`streaming`||S===`error`?S:`ready`,[S]),A=(0,B.useMemo)(()=>{if(k!==`submitted`&&k!==`streaming`)return!1;let e=w.at(-1);if(!e||e.role===`user`)return!0;if(e.role===`assistant`){let t=e.parts?.some(e=>e.type===`text`),n=e.parts?.some(e=>e.type===`reasoning`);return!t&&!n}return!1},[k,w]),j=(0,B.useMemo)(()=>!p.trim()||k===`streaming`||k===`submitted`,[p,k]);return y===`connecting`?(0,U.jsxs)(`div`,{className:`flex size-full flex-col items-center justify-center gap-3 text-muted-foreground`,children:[(0,U.jsx)(`div`,{className:`h-6 w-6 rounded-full border-2 border-zinc-300 border-t-zinc-600 animate-spin`}),(0,U.jsx)(`p`,{className:`text-sm`,children:`Connecting to agent...`})]}):y===`disconnected`?(0,U.jsxs)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4`,children:[(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Unable to connect`}),r&&(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground max-w-xs`,children:[`Could not reach `,(0,U.jsx)(`span`,{className:`font-mono`,children:r}),`. Check the URL and make sure the agent is running.`]})]}),u&&(0,U.jsx)(`button`,{className:`text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground transition-colors`,onClick:u,children:`Try again`})]}):(0,U.jsxs)(`div`,{className:`relative flex size-full flex-col divide-y overflow-hidden`,children:[(0,U.jsxs)(_d,{children:[(0,U.jsxs)(vd,{children:[w.map((e,t)=>(0,U.jsx)(OE,{defaultBranch:0,children:(0,U.jsx)(kE,{children:(0,U.jsx)(X2,{isStreaming:k===`streaming`&&t===w.length-1,message:e,userMode:f})})},e.id)),A&&(0,U.jsx)(wE,{from:`assistant`,children:(0,U.jsx)(TE,{children:(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground text-sm`,children:[(0,U.jsx)(nk,{className:`size-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:`Thinking...`})]})})})]}),(0,U.jsx)(yd,{})]}),(0,U.jsx)(`div`,{className:`grid shrink-0 gap-4 pt-4`,children:(0,U.jsx)(`div`,{className:`w-full px-4 pb-4`,children:(0,U.jsxs)(mk,{globalDrop:!0,multiple:!0,onSubmit:T,children:[(0,U.jsx)(_k,{children:(0,U.jsx)(Q2,{})}),(0,U.jsx)(hk,{children:(0,U.jsx)(gk,{onChange:D,value:p})}),(0,U.jsxs)(vk,{children:[(0,U.jsxs)(yk,{children:[(0,U.jsxs)(xk,{children:[(0,U.jsx)(Sk,{}),(0,U.jsx)(Ck,{children:(0,U.jsx)(pk,{})})]}),(0,U.jsx)(UB,{className:`shrink-0`,onTranscriptionChange:E,size:`icon-sm`,variant:`ghost`}),(0,U.jsxs)(bk,{onClick:O,variant:h?`default`:`ghost`,children:[(0,U.jsx)(Au,{size:16}),(0,U.jsx)(`span`,{children:`Search`})]})]}),(0,U.jsx)(wk,{disabled:j,onStop:C,status:k})]})]})})})]})};function e4({className:e,size:t=`default`,...n}){return(0,U.jsx)(`div`,{"data-slot":`card`,"data-size":t,className:H(`group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl`,e),...n})}function t4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-header`,className:H(`group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3`,e),...t})}function n4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-title`,className:H(`text-base leading-snug font-medium group-data-[size=sm]/card:text-sm`,e),...t})}function r4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`card-description`,className:H(`text-sm text-muted-foreground`,e),...t})}function i4({...e}){return(0,U.jsx)(SD,{"data-slot":`sheet`,...e})}function a4({...e}){return(0,U.jsx)(wD,{"data-slot":`sheet-trigger`,...e})}function o4({...e}){return(0,U.jsx)(aD,{"data-slot":`sheet-portal`,...e})}function s4({className:e,children:t,side:n=`right`,showCloseButton:r=!0,...i}){return(0,U.jsx)(o4,{children:(0,U.jsxs)(rD,{"data-slot":`sheet-content`,"data-side":n,className:H(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm`,e),...i,children:[t,r&&(0,U.jsx)(VE,{"data-slot":`sheet-close`,render:(0,U.jsxs)(Yn,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,U.jsx)(Ku,{}),(0,U.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})]})})}function c4({className:e,...t}){return(0,U.jsx)(`div`,{"data-slot":`sheet-header`,className:H(`flex flex-col gap-0.5 p-4`,e),...t})}function l4({className:e,...t}){return(0,U.jsx)(CD,{"data-slot":`sheet-title`,className:H(`cn-font-heading text-base font-medium text-foreground`,e),...t})}function u4({className:e,...t}){return(0,U.jsx)(HE,{"data-slot":`sheet-description`,className:H(`text-sm text-muted-foreground`,e),...t})}function d4(e){return!e||typeof e!=`object`?!1:`durable_object_name`in e||`title`in e||`summary`in e||`created_at`in e||`updated_at`in e}function f4(e){return Array.isArray(e)?{rows:e.filter(d4),supported:!0}:{rows:[],supported:!1}}function p4(e){if(e==null||e===``)return`Unknown time`;let t=new Date(e);return Number.isNaN(t.getTime())?`Unknown time`:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(t)}function m4(e){let t=e?.trim();return t?t.length>180?`${t.slice(0,177)}...`:t:`No summary available yet.`}function h4(e){return e.title?.trim()||`Untitled conversation`}function g4(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function _4({agent:e,connectionStatus:t,currentChatId:n,onConversationClick:r}){let[i,a]=(0,B.useState)(!1),[o,s]=(0,B.useState)([]),[c,l]=(0,B.useState)(`disconnected`),[u,d]=(0,B.useState)(null),[f,p]=(0,B.useState)(null),m=(0,B.useMemo)(()=>t===`unauthorized`?{title:`Unauthorized`,description:`Reconnect with valid credentials to load conversations.`}:{title:`Disconnected`,description:`Connect to the agent to load conversations for the active identity.`},[t]),h=(0,B.useCallback)(async()=>{if(!e){l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null);return}if(t!==`connected`){l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null);return}l(`loading`),d(null);try{let{rows:t,supported:n}=f4(await e.call(`getConversations`));s(t),p(new Date().toISOString()),l(n?t.length>0?`ready`:`empty`:`unsupported`)}catch(e){d(e instanceof Error?e.message:String(e)),l(`error`)}},[e,t]);return(0,B.useEffect)(()=>{if(t===`connected`&&e&&!i){h();return}if(i){if(t===`connected`&&e){h();return}l(t===`unauthorized`?`unauthorized`:`disconnected`),d(null)}},[i,t,h]),(0,U.jsxs)(i4,{open:i,onOpenChange:a,children:[(0,U.jsx)(a4,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsx)(Yn,{"aria-label":`Conversation history`,title:`Conversation history`,size:`icon-sm`,variant:`outline`,className:`relative`,children:(0,U.jsx)(Fu,{className:`size-4`})})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Conversation history`})})]})}),(0,U.jsxs)(s4,{className:`gap-0`,children:[(0,U.jsxs)(c4,{children:[(0,U.jsxs)(l4,{children:[`Conversation history`,(0,U.jsx)(Yn,{"aria-label":`Refresh conversations`,className:`absolute top-3 right-10`,onClick:()=>void h(),size:`icon-sm`,variant:`ghost`,children:(0,U.jsx)(Bu,{className:`size-4`})})]}),(0,U.jsx)(u4,{children:`Recent conversations for the connected identity.`})]}),(0,U.jsx)(`div`,{className:`border-b px-4 pb-3 text-xs text-muted-foreground`,children:f?(0,U.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,U.jsx)(wu,{className:`size-3.5`}),`Last refreshed`,` `,new Intl.DateTimeFormat(void 0,{timeStyle:`short`}).format(new Date(f))]}):(0,U.jsx)(`span`,{children:`Open the panel to load conversations from the current session.`})}),(0,U.jsxs)(`div`,{className:`overflow-y-auto`,children:[c===`loading`&&(0,U.jsx)(`div`,{className:`flex h-full items-center justify-center px-4`,children:(0,U.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,U.jsx)(nk,{className:`size-4`}),`Loading conversations...`]})}),c===`unauthorized`||c===`disconnected`?(0,U.jsx)(`div`,{className:`flex h-full items-center justify-center px-4`,children:(0,U.jsx)(e4,{size:`sm`,className:`w-full border-dashed`,children:(0,U.jsxs)(t4,{children:[(0,U.jsx)(n4,{className:`text-sm`,children:m.title}),(0,U.jsx)(r4,{children:m.description})]})})}):null,c===`error`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{className:`text-red-600`,children:`Could not load conversations`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u??`An unexpected error occurred while loading the conversation list.`}),(0,U.jsx)(Yn,{onClick:()=>void h(),size:`sm`,variant:`outline`,children:`Retry`})]}):null,c===`empty`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{children:`No conversations yet`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This identity has not created any saved conversations.`})]}):null,c===`unsupported`?(0,U.jsxs)(`div`,{className:` items-center justify-center p-4`,children:[(0,U.jsx)(`p`,{children:`Conversations unavailable`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This agent does not expose saved conversations for the current identity.`})]}):null,c===`ready`?(0,U.jsx)(`div`,{className:`flex flex-col gap-3 p-4`,children:o.map((e,t)=>{let i=g4(e.durable_object_name??``);return(0,U.jsx)(`article`,{className:[`rounded-lg border bg-card p-3 shadow-sm transition-shadow hover:shadow-md cursor-pointer`,n&&i===n?`ring-2 ring-primary border-primary`:``].filter(Boolean).join(` `),onClick:()=>{a(!1),r(i)},children:(0,U.jsxs)(`div`,{className:`flex flex-col justify-between gap-2`,children:[(0,U.jsxs)(`div`,{className:`min-w-0 flex gap-x-2 items-center`,children:[(0,U.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:h4(e)}),(0,U.jsx)(`time`,{className:`shrink-0 text-[11px] text-muted-foreground ml-auto`,children:p4(e.updated_at)})]}),(0,U.jsx)(`p`,{className:`mt-1 line-clamp-3 text-xs leading-relaxed text-muted-foreground`,children:m4(e.summary)})]})},e.durable_object_name??`${e.updated_at??t}`)})}):null]})]})]})}var v4=class extends B.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}render(){return this.state.error?(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4 text-muted-foreground`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Something went wrong`}),(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:`Could not connect to the agent. Check the URL above and try again.`})]})}):this.props.children}};function y4(e){try{let t=JSON.parse(e);return typeof t==`object`&&!!t&&Object.keys(t).length>0}catch{return!1}}var b4=`{
|
|
332
332
|
"currentDateTime": "2026-04-13T11:57:17.858Z",
|
|
333
333
|
"tokens": {
|
|
334
334
|
"X-Economic-Token": "token_123"
|
|
@@ -337,4 +337,4 @@ const partysocket = new PartySocket({
|
|
|
337
337
|
"guid": "guid_123";
|
|
338
338
|
"agreementNumber": "agreementNumber_123";
|
|
339
339
|
}
|
|
340
|
-
}`;function b4({body:e,onChange:t}){let[n,r]=(0,B.useState)(!1),[i,a]=(0,B.useState)(e),o=(0,B.useCallback)(t=>{t&&a(e),r(t)},[e]),s=(0,B.useCallback)(()=>{let e=i.trim();if(e&&e!==`{}`)try{JSON.parse(e)}catch{nt.error(`Invalid JSON — check the syntax and try again.`);return}t(e),r(!1)},[i,t]),c=v4(e);return(0,U.jsxs)(TD,{open:n,onOpenChange:o,children:[(0,U.jsx)(ED,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsxs)(Yn,{"aria-label":`Request body`,title:`Request body — JSON merged into each chat request (tool execution context)`,size:`icon-sm`,variant:`outline`,className:`relative`,children:[(0,U.jsx)(Vu,{className:`size-4`}),c&&(0,U.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-blue-500`})]})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Request body params`})})]})}),(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Request body`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`JSON object merged into the body of every chat request. Available in tool`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:`execute`}),` functions via`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:`experimental_context`}),`.`]}),(0,U.jsx)(ZD,{className:`font-mono text-xs min-h-32 max-h-72 break-all w-full`,placeholder:y4,value:i,onChange:e=>a(e.target.value),spellCheck:!1})]}),(0,U.jsx)(jD,{showCloseButton:!0,children:(0,U.jsx)(Yn,{size:`sm`,onClick:s,children:`Save`})})]})]})}function x4(e){if(!e||e===`{}`)return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t;for(let e of Object.values(n))if(typeof e!=`string`)return null;return n}function S4(e,t){if(!t?.length)return;let n=e??{};for(let e of t)n[e]?.trim()||nt.warning(`Query param "${e}" is required for this playground session.`)}function C4(e,t,n){let r=n?.declaredQueryKeys;if(!e||e===`{}`)return S4(null,r),t(e),!0;let i=x4(e);return i===null?(nt.error(`Invalid query params — use only flat string key/value pairs.`),!1):(S4(i,r),t(e),!0)}function w4(e){let t=x4(e.trim());return!t||Object.keys(t).length===0?[{id:ik(),key:``,value:``}]:Object.entries(t).map(([e,t])=>({id:ik(),key:e,value:t}))}function T4(e){let t={},n=new Set;for(let r of e){let e=r.key.trim();if(e){if(n.has(e))return`duplicate`;n.add(e),t[e]=r.value}}return t}function E4({query:e,onChange:t,declaredQueryKeys:n,userId:r,onUserIdChange:i,token:a,onTokenChange:o,welcomeMessage:s,onWelcomeMessageChange:c}){let[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(r),[p,m]=(0,B.useState)(a),[h,g]=(0,B.useState)(s),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(()=>w4(e)),x=(0,B.useCallback)(t=>{t&&(f(r),m(a),g(s),b(w4(e))),u(t)},[e,r,a,s]),S=(0,B.useCallback)(()=>{b(e=>[...e,{id:ik(),key:``,value:``}])},[]),C=(0,B.useCallback)(e=>{b(t=>{let n=t.filter(t=>t.id!==e);return n.length>0?n:[{id:ik(),key:``,value:``}]})},[]),w=(0,B.useCallback)((e,t,n)=>{b(r=>r.map(r=>r.id===e?{...r,[t]:n}:r))},[]),T=(0,B.useCallback)(()=>{let e=d.trim();if(!e){nt.error(`User ID is required.`);return}let r=T4(y);if(r===`duplicate`){nt.error(`Duplicate parameter keys are not allowed.`);return}C4(JSON.stringify(r),e=>t(e),{declaredQueryKeys:n})&&(i(e),o(p.trim()),c(h.trim()),u(!1))},[y,t,n,d,p,h,i,o,c]),E=v4(e)||!!r||!!a;return(0,U.jsxs)(TD,{open:l,onOpenChange:x,children:[(0,U.jsx)(ED,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsxs)(Yn,{"aria-label":`Connection settings`,title:`Connection settings — user ID, auth token, and query params`,size:`icon-sm`,variant:`outline`,className:`relative`,children:[(0,U.jsx)(Mu,{className:`size-4`}),E&&(0,U.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-blue-500`})]})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Connection settings`})})]})}),(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Connection settings`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Configure your User ID, auth token, and any additional query params for the WebSocket connection. Changes take effect on the next connection after saving, such as starting a new chat or refreshing the page.`}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-user-id`,children:[`User ID `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:`params-user-id`,onChange:e=>f(e.target.value),placeholder:`e.g. user_123`,spellCheck:!1,value:d})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-token`,children:[`Auth Token `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsxs)(`div`,{className:`relative`,children:[(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs pr-10`,id:`params-token`,onChange:e=>m(e.target.value),placeholder:`Bearer token for authentication`,spellCheck:!1,type:_?`text`:`password`,value:p}),(0,U.jsx)(Yn,{className:`absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7`,onClick:()=>v(e=>!e),size:`icon-sm`,type:`button`,variant:`ghost`,children:_?(0,U.jsx)(Du,{className:`size-4`}):(0,U.jsx)(Ou,{className:`size-4`})})]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-welcome-message`,children:[`Welcome Message `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsx)(ZD,{className:`text-xs min-h-16 max-h-32`,id:`params-welcome-message`,onChange:e=>g(e.target.value),placeholder:`Hello! How can I help you today?`,spellCheck:!1,value:h})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Additional query params`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Flat string key/value pairs appended to the WebSocket URL.`}),(0,U.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] gap-2 text-xs font-medium text-muted-foreground px-0.5`,children:[(0,U.jsx)(`span`,{children:`Name`}),(0,U.jsx)(`span`,{children:`Value`}),(0,U.jsx)(`span`,{className:`sr-only`,children:`Remove`})]}),y.map(e=>(0,U.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] gap-2 items-center`,children:[(0,U.jsx)(XD,{"aria-label":`Parameter name`,className:`font-mono text-xs h-9`,onChange:t=>w(e.id,`key`,t.target.value),placeholder:`e.g. token`,spellCheck:!1,value:e.key}),(0,U.jsx)(XD,{"aria-label":`Value for ${e.key||`parameter`}`,className:`font-mono text-xs h-9`,onChange:t=>w(e.id,`value`,t.target.value),placeholder:`value`,spellCheck:!1,value:e.value}),(0,U.jsx)(Yn,{"aria-label":`Remove row`,className:`shrink-0 justify-self-end sm:justify-self-center`,onClick:()=>C(e.id),size:`icon-sm`,type:`button`,variant:`ghost`,children:(0,U.jsx)(Uu,{className:`size-4 text-muted-foreground`})})]},e.id)),(0,U.jsxs)(Yn,{className:`self-start gap-1.5`,onClick:S,size:`sm`,type:`button`,variant:`outline`,children:[(0,U.jsx)(zu,{className:`size-4`}),`Add param`]})]})]}),(0,U.jsx)(jD,{showCloseButton:!0,children:(0,U.jsx)(Yn,{size:`sm`,onClick:T,children:`Save`})})]})]})}var D4=`playground:url`,O4=`playground:body`,k4=`playground:query`,A4=`playground:userId`,j4=`playground:token`,M4=`playground:welcomeMessage`,N4=`playground:userMode`,P4=`{{agent_name}}`,F4=`http://localhost:8787/agents/${P4}`;function I4(e){if(!e?.trim())return[];let t=new Set,n=[];for(let r of e.split(`,`)){let e=r.trim();e&&(t.has(e)||(t.add(e),n.push(e)))}return n}function L4(e){return e?.length?I4(e.join(`,`)):[]}function R4(){let e=window.__PLAYGROUND_CONFIG__,t=L4(e?.queryParamKeys),n=I4(void 0),r=t.length>0?t:n;return{agentName:e?.agentName,port:e?.port,queryParamKeys:r}}function z4(e,t){if(t.length===0)return!0;let n=x4(e.trim());return n?t.every(e=>!!n[e]?.trim()):!1}function B4(e,t){return x4(e.trim())?.[t]?.trim()??``}function V4(e){return`setup-query-${e.replace(/[^a-zA-Z0-9_-]/g,`_`)}`}function H4(){return localStorage.getItem(O4)??``}function U4(){return localStorage.getItem(k4)??``}function W4(){return new URLSearchParams(window.location.search).get(`user`)??``}function G4(){return W4()||(localStorage.getItem(A4)??``)}function K4(){return localStorage.getItem(j4)??``}function q4(){return localStorage.getItem(M4)??``}function J4(e){try{let t=new URL(e.includes(`://`)?e:`http://${e}`),n=t.pathname.split(`/`).filter(Boolean);return n[0]===`agents`&&n[1]?{host:t.host,agent:n[1]}:null}catch{return null}}function Y4(e){return e?J4(e)||(nt.error(`Invalid agent URL — expected http://<host>/agents/<name>`),null):null}function X4({open:e,urlDraft:t,setUrlDraft:n,onCommitUrl:r,query:i,onPersistQuery:a,requiredParamKeys:o,userId:s,onUserIdChange:c,token:l,onTokenChange:u,welcomeMessage:d,onWelcomeMessageChange:f}){let[p,m]=(0,B.useState)(s),[h,g]=(0,B.useState)(l),[_,v]=(0,B.useState)(d),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(()=>Object.fromEntries(o.map(e=>[e,B4(i,e)])));(0,B.useEffect)(()=>{m(s)},[s]),(0,B.useEffect)(()=>{g(l)},[l]),(0,B.useEffect)(()=>{v(d)},[d]),(0,B.useEffect)(()=>{S(Object.fromEntries(o.map(e=>[e,B4(i,e)])))},[i,o]);let C=(0,B.useCallback)(()=>{let e=p.trim();if(!e){nt.error(`User ID is required.`);return}if(r()){if(o.length>0){for(let e of o)if(!x[e]?.trim()){nt.error(`"${e}" is required for this playground session (WebSocket query param).`);return}let e={...x4(i.trim())??{},...Object.fromEntries(o.map(e=>[e,x[e].trim()]))};a(JSON.stringify(e))}c(e),u(h.trim()),f(_.trim())}},[p,h,_,r,o,x,i,a,c,u,f]);return(0,U.jsx)(TD,{open:e,onOpenChange:e=>{},children:(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,showCloseButton:!1,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Initial setup`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Set your User ID, a valid agent URL, and optionally an auth token.`,` `,o.length>0?(0,U.jsxs)(U.Fragment,{children:[`This CLI session also requires query params:`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:o.join(`, `)}),`.`]}):(0,U.jsx)(U.Fragment,{children:`Additional query params can be added later via the settings icon in the header.`}),` `,`Fields are pre-filled from saved settings when possible.`]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-user-id`,children:[`User ID `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:`setup-user-id`,onChange:e=>m(e.target.value),placeholder:`e.g. user_123`,spellCheck:!1,value:p})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-token`,children:[`Auth Token `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsxs)(`div`,{className:`relative`,children:[(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs pr-10`,id:`setup-token`,onChange:e=>g(e.target.value),placeholder:`Bearer token for authentication`,spellCheck:!1,type:y?`text`:`password`,value:h}),(0,U.jsx)(Yn,{className:`absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7`,onClick:()=>b(e=>!e),size:`icon-sm`,type:`button`,variant:`ghost`,children:y?(0,U.jsx)(Du,{className:`size-4`}):(0,U.jsx)(Ou,{className:`size-4`})})]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsx)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-agent-url`,children:`Agent URL`}),(0,U.jsx)(XD,{className:`font-mono text-xs`,id:`setup-agent-url`,onChange:e=>n(e.target.value),placeholder:`http://localhost:8787/agents/my-agent`,spellCheck:!1,value:t})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-welcome-message`,children:[`Welcome Message `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsx)(ZD,{className:`text-xs min-h-16 max-h-32`,id:`setup-welcome-message`,onChange:e=>v(e.target.value),placeholder:`Hello! How can I help you today?`,spellCheck:!1,value:_})]}),o.length>0?(0,U.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,U.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Required query params`}),o.map(e=>(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:V4(e),children:[(0,U.jsx)(`code`,{className:`font-mono`,children:e}),` `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:V4(e),onChange:t=>S(n=>({...n,[e]:t.target.value})),placeholder:e,spellCheck:!1,value:x[e]??``})]},e)),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use the key icon in the header to add more key/value pairs if you need keys beyond this list.`})]}):null]}),(0,U.jsx)(jD,{children:(0,U.jsx)(Yn,{size:`sm`,onClick:C,children:`Continue`})})]})})}function Z4(){let e=R4();return e.agentName?`http://localhost:${e.port??8787}/agents/${e.agentName}`:F4}function Q4(){return localStorage.getItem(D4)??Z4()}function $4(){return new URLSearchParams(window.location.search).get(`chat`)??void 0}function e3(){return ik()}function t3(){let[e,t]=(0,B.useState)(()=>$4()??e3()),[n,r]=(0,B.useState)(G4),[i,a]=(0,B.useState)(K4),[o,s]=(0,B.useState)(q4),[c,l]=(0,B.useState)(Q4),[u,d]=(0,B.useState)(c),[f,p]=(0,B.useState)(`connecting`),[m,h]=(0,B.useState)(null),[g,_]=(0,B.useState)(H4),[v,y]=(0,B.useState)(U4),[b,x]=(0,B.useState)(null),[S,C]=(0,B.useState)(()=>localStorage.getItem(N4)===`true`),w=(0,B.useRef)(!1),T=(0,B.useMemo)(()=>R4().queryParamKeys??[],[]);(0,B.useEffect)(()=>{p(`connecting`),h(null)},[e]);let E=c.includes(P4),D=E?null:J4(c),O=!E&&D!==null,k=z4(v,T),A=!O||!k||!n;(0,B.useEffect)(()=>{let t=new URLSearchParams(window.location.search);e&&t.get(`chat`)!==e&&(t.set(`chat`,e),history.replaceState(null,``,`?${t}`))},[e]),(0,B.useEffect)(()=>{let e=new URLSearchParams(window.location.search);n&&e.get(`user`)!==n&&(e.set(`user`,n),history.replaceState(null,``,`?${e}`))},[n]);let j=(0,B.useCallback)(()=>{let e=e3(),n=new URLSearchParams(window.location.search);n.set(`chat`,e),history.pushState(null,``,`?${n}`),t(e),nt.success(`New chat started`)},[]),M=(0,B.useCallback)(()=>{let e=u.trim();return Y4(e)?(localStorage.setItem(D4,e),l(e),d(e),w.current=!0,t(e3()),!0):!1},[u]),N=(0,B.useCallback)(e=>{localStorage.setItem(A4,e),r(e)},[]),P=(0,B.useCallback)(e=>{localStorage.setItem(j4,e),a(e)},[]),F=(0,B.useCallback)(e=>{localStorage.setItem(M4,e),s(e)},[]);return(0,U.jsxs)(`div`,{className:`relative flex h-screen overflow-hidden`,children:[(0,U.jsx)(X4,{open:A,query:v,requiredParamKeys:T,setUrlDraft:d,urlDraft:u,onCommitUrl:M,onPersistQuery:(0,B.useCallback)(e=>C4(e,e=>{localStorage.setItem(k4,e),y(e)},{declaredQueryKeys:T}),[T]),userId:n,onUserIdChange:N,token:i,onTokenChange:P,welcomeMessage:o,onWelcomeMessageChange:F}),(0,U.jsxs)(`div`,{className:`flex-1 flex flex-col`,children:[(0,U.jsx)(`div`,{className:`border-b-2 border-zinc-200 flex items-center justify-between bg-zinc-50`,children:(0,U.jsxs)(`div`,{className:`h-20 flex items-center w-6xl mx-auto border-x-2 border-zinc-200/40 py-6 px-6 justify-between`,children:[(0,U.jsx)(`div`,{className:`flex items-center`,children:c?(0,U.jsx)(U.Fragment,{children:(0,U.jsxs)(`div`,{children:[(0,U.jsxs)(`h2`,{className:`text-sm font-semibold mb-0 flex items-center`,children:[(0,U.jsx)(`div`,{className:[`h-2 w-2 rounded-full mr-2`,f===`connected`&&`bg-green-500`,f===`connecting`&&`bg-amber-400 animate-pulse`,(f===`disconnected`||f===`unauthorized`)&&`bg-red-500 animate-pulse`].filter(Boolean).join(` `)}),f===`connected`&&`Connected to agent`,f===`connecting`&&`Connecting...`,f===`disconnected`&&`Unable to connect to agent`,f===`unauthorized`&&`Unauthorized to connect to agent`]}),(0,U.jsx)(`input`,{className:`-ml-1.5 text-xs text-muted-foreground mb-0 py-1 pl-2 pr-10 field-sizing-content rounded-md hover:text-foreground focus:text-foreground hover:bg-white focus:bg-white hover:outline hover:outline-zinc-200 focus:outline focus:outline-zinc-300`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`?(M(),e.currentTarget.blur()):e.key===`Escape`&&(d(c),e.currentTarget.blur())},onBlur:()=>{if(w.current){w.current=!1;return}d(c)}})]})}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`h-2 w-2 bg-muted-foreground/50 rounded-full mr-3`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground mb-0`,children:`Not Connected`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground mb-0`,children:`Enter an agent URL and click Connect`})]})]})}),(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,U.jsx)(Yn,{onClick:j,size:`icon-sm`,variant:`outline`,children:(0,U.jsx)(Pu,{className:`size-4`})}),(0,U.jsx)(g4,{agent:b,connectionStatus:f,currentChatId:e,onConversationClick:t}),(0,U.jsx)(E4,{declaredQueryKeys:T,query:v,onChange:e=>{localStorage.setItem(k4,e),y(e)},userId:n,onUserIdChange:N,token:i,onTokenChange:P,welcomeMessage:o,onWelcomeMessageChange:F}),(0,U.jsx)(b4,{body:g,onChange:e=>{localStorage.setItem(O4,e),_(e)}}),(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsx)(Yn,{"aria-label":`View chat as a user would`,title:`View chat as a user would`,onClick:()=>C(e=>{let t=!e;return localStorage.setItem(N4,String(t)),t}),size:`icon-sm`,variant:S?`default`:`outline`,children:S?(0,U.jsx)(Ou,{className:`size-4`}):(0,U.jsx)(Du,{className:`size-4`})})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`View chat as a user would`})})]})]})]})}),(0,U.jsx)(`div`,{className:`flex-1 overflow-hidden min-h-0 grow`,children:(0,U.jsxs)(`div`,{className:`max-w-6xl w-full mx-auto border-x-2 border-zinc-100 h-full`,children:[f===`unauthorized`&&O&&k&&(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4 text-muted-foreground`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Unauthorized`}),m?(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:m}):(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:`You are not authorized to connect to this agent.`})]})}),O&&k&&D?(0,U.jsx)(_4,{children:(0,U.jsx)(Q2,{agentName:D.agent,host:D.host,chatId:n?`${n}:${e}`:e,agentUrl:c,authToken:i||void 0,body:g?JSON.parse(g):void 0,query:v?x4(v.trim())??void 0:void 0,welcomeMessage:o||void 0,onAgentChange:x,onConnectionStatusChange:p,onUnauthorized:h,userMode:S},`${n}:${e}:${v}`)},`${n}:${e}:${v}`):(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-3 text-muted-foreground px-4`,children:O?(0,U.jsxs)(`p`,{className:`text-sm text-center max-w-md`,children:[`Set required WebSocket query params in the setup dialog`,T.length>0?(0,U.jsxs)(U.Fragment,{children:[`: `,(0,U.jsx)(`code`,{className:`font-mono text-xs`,children:T.join(`, `)})]}):null,`.`]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`p`,{className:`text-sm text-center`,children:`Enter an agent URL in the bar above or in the setup dialog.`}),(0,U.jsx)(`p`,{className:`text-xs font-mono text-muted-foreground/60`,children:`e.g. http://localhost:8787/agents/my-agent`})]})})]})})]})]})}(0,Be.createRoot)(document.getElementById(`app`)).render((0,U.jsx)(B.StrictMode,{children:(0,U.jsxs)(Hd,{children:[(0,U.jsx)(_t,{}),(0,U.jsx)(t3,{})]})}));
|
|
340
|
+
}`;function x4({body:e,onChange:t}){let[n,r]=(0,B.useState)(!1),[i,a]=(0,B.useState)(e),o=(0,B.useCallback)(t=>{t&&a(e),r(t)},[e]),s=(0,B.useCallback)(()=>{let e=i.trim();if(e&&e!==`{}`)try{JSON.parse(e)}catch{nt.error(`Invalid JSON — check the syntax and try again.`);return}t(e),r(!1)},[i,t]),c=y4(e);return(0,U.jsxs)(TD,{open:n,onOpenChange:o,children:[(0,U.jsx)(ED,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsxs)(Yn,{"aria-label":`Request body`,title:`Request body — JSON merged into each chat request (tool execution context)`,size:`icon-sm`,variant:`outline`,className:`relative`,children:[(0,U.jsx)(Vu,{className:`size-4`}),c&&(0,U.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-blue-500`})]})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Request body params`})})]})}),(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Request body`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`JSON object merged into the body of every chat request. Available in tool`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:`execute`}),` functions via`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:`experimental_context`}),`.`]}),(0,U.jsx)(ZD,{className:`font-mono text-xs min-h-32 max-h-72 break-all w-full`,placeholder:b4,value:i,onChange:e=>a(e.target.value),spellCheck:!1})]}),(0,U.jsx)(jD,{showCloseButton:!0,children:(0,U.jsx)(Yn,{size:`sm`,onClick:s,children:`Save`})})]})]})}function S4(e){if(!e||e===`{}`)return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t;for(let e of Object.values(n))if(typeof e!=`string`)return null;return n}function C4(e,t){if(!t?.length)return;let n=e??{};for(let e of t)n[e]?.trim()||nt.warning(`Query param "${e}" is required for this playground session.`)}function w4(e,t,n){let r=n?.declaredQueryKeys;if(!e||e===`{}`)return C4(null,r),t(e),!0;let i=S4(e);return i===null?(nt.error(`Invalid query params — use only flat string key/value pairs.`),!1):(C4(i,r),t(e),!0)}function T4(e){let t=S4(e.trim());return!t||Object.keys(t).length===0?[{id:ik(),key:``,value:``}]:Object.entries(t).map(([e,t])=>({id:ik(),key:e,value:t}))}function E4(e){let t={},n=new Set;for(let r of e){let e=r.key.trim();if(e){if(n.has(e))return`duplicate`;n.add(e),t[e]=r.value}}return t}function D4({query:e,onChange:t,declaredQueryKeys:n,userId:r,onUserIdChange:i,token:a,onTokenChange:o,welcomeMessage:s,onWelcomeMessageChange:c}){let[l,u]=(0,B.useState)(!1),[d,f]=(0,B.useState)(r),[p,m]=(0,B.useState)(a),[h,g]=(0,B.useState)(s),[_,v]=(0,B.useState)(!1),[y,b]=(0,B.useState)(()=>T4(e)),x=(0,B.useCallback)(t=>{t&&(f(r),m(a),g(s),b(T4(e))),u(t)},[e,r,a,s]),S=(0,B.useCallback)(()=>{b(e=>[...e,{id:ik(),key:``,value:``}])},[]),C=(0,B.useCallback)(e=>{b(t=>{let n=t.filter(t=>t.id!==e);return n.length>0?n:[{id:ik(),key:``,value:``}]})},[]),w=(0,B.useCallback)((e,t,n)=>{b(r=>r.map(r=>r.id===e?{...r,[t]:n}:r))},[]),T=(0,B.useCallback)(()=>{let e=d.trim();if(!e){nt.error(`User ID is required.`);return}let r=E4(y);if(r===`duplicate`){nt.error(`Duplicate parameter keys are not allowed.`);return}w4(JSON.stringify(r),e=>t(e),{declaredQueryKeys:n})&&(i(e),o(p.trim()),c(h.trim()),u(!1))},[y,t,n,d,p,h,i,o,c]),E=y4(e)||!!r||!!a;return(0,U.jsxs)(TD,{open:l,onOpenChange:x,children:[(0,U.jsx)(ED,{children:(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsxs)(Yn,{"aria-label":`Connection settings`,title:`Connection settings — user ID, auth token, and query params`,size:`icon-sm`,variant:`outline`,className:`relative`,children:[(0,U.jsx)(Mu,{className:`size-4`}),E&&(0,U.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-blue-500`})]})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`Connection settings`})})]})}),(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Connection settings`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Configure your User ID, auth token, and any additional query params for the WebSocket connection. Changes take effect on the next connection after saving, such as starting a new chat or refreshing the page.`}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-user-id`,children:[`User ID `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:`params-user-id`,onChange:e=>f(e.target.value),placeholder:`e.g. user_123`,spellCheck:!1,value:d})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-token`,children:[`Auth Token `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsxs)(`div`,{className:`relative`,children:[(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs pr-10`,id:`params-token`,onChange:e=>m(e.target.value),placeholder:`Bearer token for authentication`,spellCheck:!1,type:_?`text`:`password`,value:p}),(0,U.jsx)(Yn,{className:`absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7`,onClick:()=>v(e=>!e),size:`icon-sm`,type:`button`,variant:`ghost`,children:_?(0,U.jsx)(Du,{className:`size-4`}):(0,U.jsx)(Ou,{className:`size-4`})})]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`params-welcome-message`,children:[`Welcome Message `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsx)(ZD,{className:`text-xs min-h-16 max-h-32`,id:`params-welcome-message`,onChange:e=>g(e.target.value),placeholder:`Hello! How can I help you today?`,spellCheck:!1,value:h})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Additional query params`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Flat string key/value pairs appended to the WebSocket URL.`}),(0,U.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] gap-2 text-xs font-medium text-muted-foreground px-0.5`,children:[(0,U.jsx)(`span`,{children:`Name`}),(0,U.jsx)(`span`,{children:`Value`}),(0,U.jsx)(`span`,{className:`sr-only`,children:`Remove`})]}),y.map(e=>(0,U.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] gap-2 items-center`,children:[(0,U.jsx)(XD,{"aria-label":`Parameter name`,className:`font-mono text-xs h-9`,onChange:t=>w(e.id,`key`,t.target.value),placeholder:`e.g. token`,spellCheck:!1,value:e.key}),(0,U.jsx)(XD,{"aria-label":`Value for ${e.key||`parameter`}`,className:`font-mono text-xs h-9`,onChange:t=>w(e.id,`value`,t.target.value),placeholder:`value`,spellCheck:!1,value:e.value}),(0,U.jsx)(Yn,{"aria-label":`Remove row`,className:`shrink-0 justify-self-end sm:justify-self-center`,onClick:()=>C(e.id),size:`icon-sm`,type:`button`,variant:`ghost`,children:(0,U.jsx)(Uu,{className:`size-4 text-muted-foreground`})})]},e.id)),(0,U.jsxs)(Yn,{className:`self-start gap-1.5`,onClick:S,size:`sm`,type:`button`,variant:`outline`,children:[(0,U.jsx)(zu,{className:`size-4`}),`Add param`]})]})]}),(0,U.jsx)(jD,{showCloseButton:!0,children:(0,U.jsx)(Yn,{size:`sm`,onClick:T,children:`Save`})})]})]})}var O4=`playground:url`,k4=`playground:body`,A4=`playground:query`,j4=`playground:userId`,M4=`playground:token`,N4=`playground:welcomeMessage`,P4=`playground:userMode`,F4=`{{agent_name}}`,I4=`http://localhost:8787/agents/${F4}`;function L4(e){if(!e?.trim())return[];let t=new Set,n=[];for(let r of e.split(`,`)){let e=r.trim();e&&(t.has(e)||(t.add(e),n.push(e)))}return n}function R4(e){return e?.length?L4(e.join(`,`)):[]}function z4(){let e=window.__PLAYGROUND_CONFIG__,t=R4(e?.queryParamKeys),n=L4(void 0),r=t.length>0?t:n;return{agentName:e?.agentName,port:e?.port,queryParamKeys:r}}function B4(e,t){if(t.length===0)return!0;let n=S4(e.trim());return n?t.every(e=>!!n[e]?.trim()):!1}function V4(e,t){return S4(e.trim())?.[t]?.trim()??``}function H4(e){return`setup-query-${e.replace(/[^a-zA-Z0-9_-]/g,`_`)}`}function U4(){return localStorage.getItem(k4)??``}function W4(){return localStorage.getItem(A4)??``}function G4(){return new URLSearchParams(window.location.search).get(`user`)??``}function K4(){return G4()||(localStorage.getItem(j4)??``)}function q4(){return localStorage.getItem(M4)??``}function J4(){return localStorage.getItem(N4)??``}function Y4(e){try{let t=new URL(e.includes(`://`)?e:`http://${e}`),n=t.pathname.split(`/`).filter(Boolean);return n[0]===`agents`&&n[1]?{host:t.host,agent:n[1]}:null}catch{return null}}function X4(e){return e?Y4(e)||(nt.error(`Invalid agent URL — expected http://<host>/agents/<name>`),null):null}function Z4({open:e,urlDraft:t,setUrlDraft:n,onCommitUrl:r,query:i,onPersistQuery:a,requiredParamKeys:o,userId:s,onUserIdChange:c,token:l,onTokenChange:u,welcomeMessage:d,onWelcomeMessageChange:f}){let[p,m]=(0,B.useState)(s),[h,g]=(0,B.useState)(l),[_,v]=(0,B.useState)(d),[y,b]=(0,B.useState)(!1),[x,S]=(0,B.useState)(()=>Object.fromEntries(o.map(e=>[e,V4(i,e)])));(0,B.useEffect)(()=>{m(s)},[s]),(0,B.useEffect)(()=>{g(l)},[l]),(0,B.useEffect)(()=>{v(d)},[d]),(0,B.useEffect)(()=>{S(Object.fromEntries(o.map(e=>[e,V4(i,e)])))},[i,o]);let C=(0,B.useCallback)(()=>{let e=p.trim();if(!e){nt.error(`User ID is required.`);return}if(r()){if(o.length>0){for(let e of o)if(!x[e]?.trim()){nt.error(`"${e}" is required for this playground session (WebSocket query param).`);return}let e={...S4(i.trim())??{},...Object.fromEntries(o.map(e=>[e,x[e].trim()]))};a(JSON.stringify(e))}c(e),u(h.trim()),f(_.trim())}},[p,h,_,r,o,x,i,a,c,u,f]);return(0,U.jsx)(TD,{open:e,onOpenChange:e=>{},children:(0,U.jsxs)(kD,{className:`!w-2xl !max-w-2xl`,showCloseButton:!1,children:[(0,U.jsx)(AD,{children:(0,U.jsx)(MD,{children:`Initial setup`})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Set your User ID, a valid agent URL, and optionally an auth token.`,` `,o.length>0?(0,U.jsxs)(U.Fragment,{children:[`This CLI session also requires query params:`,` `,(0,U.jsx)(`code`,{className:`font-mono`,children:o.join(`, `)}),`.`]}):(0,U.jsx)(U.Fragment,{children:`Additional query params can be added later via the settings icon in the header.`}),` `,`Fields are pre-filled from saved settings when possible.`]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-user-id`,children:[`User ID `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:`setup-user-id`,onChange:e=>m(e.target.value),placeholder:`e.g. user_123`,spellCheck:!1,value:p})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-token`,children:[`Auth Token `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsxs)(`div`,{className:`relative`,children:[(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs pr-10`,id:`setup-token`,onChange:e=>g(e.target.value),placeholder:`Bearer token for authentication`,spellCheck:!1,type:y?`text`:`password`,value:h}),(0,U.jsx)(Yn,{className:`absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7`,onClick:()=>b(e=>!e),size:`icon-sm`,type:`button`,variant:`ghost`,children:y?(0,U.jsx)(Du,{className:`size-4`}):(0,U.jsx)(Ou,{className:`size-4`})})]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsx)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-agent-url`,children:`Agent URL`}),(0,U.jsx)(XD,{className:`font-mono text-xs`,id:`setup-agent-url`,onChange:e=>n(e.target.value),placeholder:`http://localhost:8787/agents/my-agent`,spellCheck:!1,value:t})]}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:`setup-welcome-message`,children:[`Welcome Message `,(0,U.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,U.jsx)(ZD,{className:`text-xs min-h-16 max-h-32`,id:`setup-welcome-message`,onChange:e=>v(e.target.value),placeholder:`Hello! How can I help you today?`,spellCheck:!1,value:_})]}),o.length>0?(0,U.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,U.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Required query params`}),o.map(e=>(0,U.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,htmlFor:H4(e),children:[(0,U.jsx)(`code`,{className:`font-mono`,children:e}),` `,(0,U.jsx)(`span`,{className:`text-destructive font-normal`,children:`(required)`})]}),(0,U.jsx)(XD,{autoComplete:`off`,className:`font-mono text-xs`,id:H4(e),onChange:t=>S(n=>({...n,[e]:t.target.value})),placeholder:e,spellCheck:!1,value:x[e]??``})]},e)),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use the key icon in the header to add more key/value pairs if you need keys beyond this list.`})]}):null]}),(0,U.jsx)(jD,{children:(0,U.jsx)(Yn,{size:`sm`,onClick:C,children:`Continue`})})]})})}function Q4(){let e=z4();return e.agentName?`http://localhost:${e.port??8787}/agents/${e.agentName}`:I4}function $4(){return localStorage.getItem(O4)??Q4()}function e3(){return new URLSearchParams(window.location.search).get(`chat`)??void 0}function t3(){return ik()}function n3(){let[e,t]=(0,B.useState)(()=>e3()??t3()),[n,r]=(0,B.useState)(K4),[i,a]=(0,B.useState)(q4),[o,s]=(0,B.useState)(J4),[c,l]=(0,B.useState)($4),[u,d]=(0,B.useState)(c),[f,p]=(0,B.useState)(`connecting`),[m,h]=(0,B.useState)(null),[g,_]=(0,B.useState)(U4),[v,y]=(0,B.useState)(W4),[b,x]=(0,B.useState)(null),[S,C]=(0,B.useState)(()=>localStorage.getItem(P4)===`true`),w=(0,B.useRef)(!1),T=(0,B.useMemo)(()=>z4().queryParamKeys??[],[]);(0,B.useEffect)(()=>{p(`connecting`),h(null)},[e]);let E=c.includes(F4),D=E?null:Y4(c),O=!E&&D!==null,k=B4(v,T),A=!O||!k||!n;(0,B.useEffect)(()=>{let t=new URLSearchParams(window.location.search);e&&t.get(`chat`)!==e&&(t.set(`chat`,e),history.replaceState(null,``,`?${t}`))},[e]),(0,B.useEffect)(()=>{let e=new URLSearchParams(window.location.search);n&&e.get(`user`)!==n&&(e.set(`user`,n),history.replaceState(null,``,`?${e}`))},[n]);let j=(0,B.useCallback)(()=>{let e=t3(),n=new URLSearchParams(window.location.search);n.set(`chat`,e),history.pushState(null,``,`?${n}`),t(e),nt.success(`New chat started`)},[]),M=(0,B.useCallback)(()=>{let e=u.trim();return X4(e)?(localStorage.setItem(O4,e),l(e),d(e),w.current=!0,t(t3()),!0):!1},[u]),N=(0,B.useCallback)(e=>{localStorage.setItem(j4,e),r(e)},[]),P=(0,B.useCallback)(e=>{localStorage.setItem(M4,e),a(e)},[]),F=(0,B.useCallback)(e=>{localStorage.setItem(N4,e),s(e)},[]);return(0,U.jsxs)(`div`,{className:`relative flex h-screen overflow-hidden`,children:[(0,U.jsx)(Z4,{open:A,query:v,requiredParamKeys:T,setUrlDraft:d,urlDraft:u,onCommitUrl:M,onPersistQuery:(0,B.useCallback)(e=>w4(e,e=>{localStorage.setItem(A4,e),y(e)},{declaredQueryKeys:T}),[T]),userId:n,onUserIdChange:N,token:i,onTokenChange:P,welcomeMessage:o,onWelcomeMessageChange:F}),(0,U.jsxs)(`div`,{className:`flex-1 flex flex-col`,children:[(0,U.jsx)(`div`,{className:`border-b-2 border-zinc-200 flex items-center justify-between bg-zinc-50`,children:(0,U.jsxs)(`div`,{className:`h-20 flex items-center w-6xl mx-auto border-x-2 border-zinc-200/40 py-6 px-6 justify-between`,children:[(0,U.jsx)(`div`,{className:`flex items-center`,children:c?(0,U.jsx)(U.Fragment,{children:(0,U.jsxs)(`div`,{children:[(0,U.jsxs)(`h2`,{className:`text-sm font-semibold mb-0 flex items-center`,children:[(0,U.jsx)(`div`,{className:[`h-2 w-2 rounded-full mr-2`,f===`connected`&&`bg-green-500`,f===`connecting`&&`bg-amber-400 animate-pulse`,(f===`disconnected`||f===`unauthorized`)&&`bg-red-500 animate-pulse`].filter(Boolean).join(` `)}),f===`connected`&&`Connected to agent`,f===`connecting`&&`Connecting...`,f===`disconnected`&&`Unable to connect to agent`,f===`unauthorized`&&`Unauthorized to connect to agent`]}),(0,U.jsx)(`input`,{className:`-ml-1.5 text-xs text-muted-foreground mb-0 py-1 pl-2 pr-10 field-sizing-content rounded-md hover:text-foreground focus:text-foreground hover:bg-white focus:bg-white hover:outline hover:outline-zinc-200 focus:outline focus:outline-zinc-300`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`?(M(),e.currentTarget.blur()):e.key===`Escape`&&(d(c),e.currentTarget.blur())},onBlur:()=>{if(w.current){w.current=!1;return}d(c)}})]})}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`h-2 w-2 bg-muted-foreground/50 rounded-full mr-3`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground mb-0`,children:`Not Connected`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground mb-0`,children:`Enter an agent URL and click Connect`})]})]})}),(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,U.jsx)(Yn,{onClick:j,size:`icon-sm`,variant:`outline`,children:(0,U.jsx)(Pu,{className:`size-4`})}),(0,U.jsx)(_4,{agent:b,connectionStatus:f,currentChatId:e,onConversationClick:t}),(0,U.jsx)(D4,{declaredQueryKeys:T,query:v,onChange:e=>{localStorage.setItem(A4,e),y(e)},userId:n,onUserIdChange:N,token:i,onTokenChange:P,welcomeMessage:o,onWelcomeMessageChange:F}),(0,U.jsx)(x4,{body:g,onChange:e=>{localStorage.setItem(k4,e),_(e)}}),(0,U.jsxs)(Ud,{children:[(0,U.jsx)(Wd,{children:(0,U.jsx)(Yn,{"aria-label":`View chat as a user would`,title:`View chat as a user would`,onClick:()=>C(e=>{let t=!e;return localStorage.setItem(P4,String(t)),t}),size:`icon-sm`,variant:S?`default`:`outline`,children:S?(0,U.jsx)(Ou,{className:`size-4`}):(0,U.jsx)(Du,{className:`size-4`})})}),(0,U.jsx)(Gd,{children:(0,U.jsx)(`p`,{children:`View chat as a user would`})})]})]})]})}),(0,U.jsx)(`div`,{className:`flex-1 overflow-hidden min-h-0 grow`,children:(0,U.jsxs)(`div`,{className:`max-w-6xl w-full mx-auto border-x-2 border-zinc-100 h-full`,children:[f===`unauthorized`&&O&&k&&(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-4 text-muted-foreground`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-center`,children:[(0,U.jsx)(`div`,{className:`h-10 w-10 rounded-full bg-red-50 flex items-center justify-center`,children:(0,U.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-red-400`})}),(0,U.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Unauthorized`}),m?(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:m}):(0,U.jsx)(`p`,{className:`text-xs max-w-xs`,children:`You are not authorized to connect to this agent.`})]})}),O&&k&&D?(0,U.jsx)(v4,{children:(0,U.jsx)($2,{agentName:D.agent,host:D.host,chatId:n?`${n}:${e}`:e,agentUrl:c,authToken:i||void 0,body:g?JSON.parse(g):void 0,query:v?S4(v.trim())??void 0:void 0,welcomeMessage:o||void 0,onAgentChange:x,onConnectionStatusChange:p,onUnauthorized:h,userMode:S},`${n}:${e}:${v}`)},`${n}:${e}:${v}`):(0,U.jsx)(`div`,{className:`flex size-full flex-col items-center justify-center gap-3 text-muted-foreground px-4`,children:O?(0,U.jsxs)(`p`,{className:`text-sm text-center max-w-md`,children:[`Set required WebSocket query params in the setup dialog`,T.length>0?(0,U.jsxs)(U.Fragment,{children:[`: `,(0,U.jsx)(`code`,{className:`font-mono text-xs`,children:T.join(`, `)})]}):null,`.`]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`p`,{className:`text-sm text-center`,children:`Enter an agent URL in the bar above or in the setup dialog.`}),(0,U.jsx)(`p`,{className:`text-xs font-mono text-muted-foreground/60`,children:`e.g. http://localhost:8787/agents/my-agent`})]})})]})})]})]})}(0,Be.createRoot)(document.getElementById(`app`)).render((0,U.jsx)(B.StrictMode,{children:(0,U.jsxs)(Hd,{children:[(0,U.jsx)(_t,{}),(0,U.jsx)(n3,{})]})}));
|
package/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>website</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-CNPSk-AE.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/chunk-CFjPhJqf.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/preload-helper-D4M6sveU.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/src-Bn-kKzs7.js">
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@economic/agents-playground",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "A local chat UI for testing agents built with @economic/agents.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"@streamdown/math": "^1.0.2",
|
|
31
31
|
"@streamdown/mermaid": "^1.0.2",
|
|
32
32
|
"@xyflow/react": "^12.10.2",
|
|
33
|
-
"agents": "^0.10.
|
|
33
|
+
"agents": "^0.10.2",
|
|
34
34
|
"ai": "^6.0.158",
|
|
35
35
|
"ansi-to-react": "^6.2.6",
|
|
36
36
|
"class-variance-authority": "^0.7.1",
|