@harperfast/harper 5.1.23 → 5.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/resources/Table.js +6 -2
- package/dist/resources/Table.js.map +1 -1
- package/npm-shrinkwrap.json +38 -38
- package/package.json +2 -2
- package/resources/Table.ts +5 -1
- package/studio/web/assets/{Chat-CHWxBSOY.js → Chat-WK3X972M.js} +5 -5
- package/studio/web/assets/{Chat-CHWxBSOY.js.map → Chat-WK3X972M.js.map} +1 -1
- package/studio/web/assets/{FloatingChat-DVCy2mvk.js → FloatingChat-Bqjk6Bf4.js} +5 -5
- package/studio/web/assets/{FloatingChat-DVCy2mvk.js.map → FloatingChat-Bqjk6Bf4.js.map} +1 -1
- package/studio/web/assets/{apiToken-QLwwxtxT.js → apiToken-S_hqpnVV.js} +2 -2
- package/studio/web/assets/{apiToken-QLwwxtxT.js.map → apiToken-S_hqpnVV.js.map} +1 -1
- package/studio/web/assets/{applications-EmZVBabu.js → applications-C6zKD9Rb.js} +12 -12
- package/studio/web/assets/applications-C6zKD9Rb.js.map +1 -0
- package/studio/web/assets/{index-CndJ7kZK.js → index-BbsxXAVZ.js} +31 -31
- package/studio/web/assets/index-BbsxXAVZ.js.map +1 -0
- package/studio/web/assets/index.lazy-BPnXo1Wj.js +14 -0
- package/studio/web/assets/{index.lazy-CGmTtyPL.js.map → index.lazy-BPnXo1Wj.js.map} +1 -1
- package/studio/web/assets/jsonMode-X_blmtuO.js +2 -0
- package/studio/web/assets/jsonMode-X_blmtuO.js.map +1 -0
- package/studio/web/assets/{profile-Dgjkaqud.js → profile-CY1FwgRs.js} +2 -2
- package/studio/web/assets/{profile-Dgjkaqud.js.map → profile-CY1FwgRs.js.map} +1 -1
- package/studio/web/assets/{setComponentFile-BMFCm_Yi.js → setComponentFile-ZBQ4KXnC.js} +2 -2
- package/studio/web/assets/{setComponentFile-BMFCm_Yi.js.map → setComponentFile-ZBQ4KXnC.js.map} +1 -1
- package/studio/web/assets/setup-B_NOw8rV.js +3 -0
- package/studio/web/assets/setup-B_NOw8rV.js.map +1 -0
- package/studio/web/assets/{status-CtgqjZ6q.js → status-D7A8OktU.js} +4 -4
- package/studio/web/assets/{status-CtgqjZ6q.js.map → status-D7A8OktU.js.map} +1 -1
- package/studio/web/assets/{swagger-ui-react-BermOHTv.js → swagger-ui-react-iD3vGtu-.js} +2 -2
- package/studio/web/assets/{swagger-ui-react-BermOHTv.js.map → swagger-ui-react-iD3vGtu-.js.map} +1 -1
- package/studio/web/assets/tokenization-uOBOyHAS.js +8 -0
- package/studio/web/assets/tokenization-uOBOyHAS.js.map +1 -0
- package/studio/web/assets/{tsMode-CWC0nCN1.js → tsMode-CevZSdk5.js} +2 -2
- package/studio/web/assets/{tsMode-CWC0nCN1.js.map → tsMode-CevZSdk5.js.map} +1 -1
- package/studio/web/assets/{useEntityRestURL-DaMIzJ2I.js → useEntityRestURL-CswKSb0j.js} +2 -2
- package/studio/web/assets/{useEntityRestURL-DaMIzJ2I.js.map → useEntityRestURL-CswKSb0j.js.map} +1 -1
- package/studio/web/index.html +2 -1
- package/studio/web/assets/applications-EmZVBabu.js.map +0 -1
- package/studio/web/assets/index-CndJ7kZK.js.map +0 -1
- package/studio/web/assets/index.lazy-CGmTtyPL.js +0 -14
- package/studio/web/assets/jsonMode-DD1NLQKv.js +0 -8
- package/studio/web/assets/jsonMode-DD1NLQKv.js.map +0 -1
- package/studio/web/assets/setup-C2E-6wan.js +0 -3
- package/studio/web/assets/setup-C2E-6wan.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,g as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-CArycxS5.js";import{i as x,t as S}from"./button-Bh1J5cEt.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-hI9zAWEc.js";import{a as ae}from"./vendor-datadog-DBn-aOxh.js";import{r as oe}from"./vendor-react-B36dp27u.js";import{zt as C}from"./vendor-ui-D-BiU2GW.js";import{t as w}from"./createLucideIcon-B49W6uF4.js";import{l as se,t as ce}from"./react-SMksfEpE.js";import{a as le,i as ue,n as de,r as fe,t as pe}from"./x-Bru-nCti.js";import{c as me,f as he,g as ge,h as _e,i as ve,l as ye,m as be,p as xe,r as Se,t as Ce,u as we}from"./setComponentFile-
|
|
1
|
+
import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,g as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-CArycxS5.js";import{i as x,t as S}from"./button-Bh1J5cEt.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-hI9zAWEc.js";import{a as ae}from"./vendor-datadog-DBn-aOxh.js";import{r as oe}from"./vendor-react-B36dp27u.js";import{zt as C}from"./vendor-ui-D-BiU2GW.js";import{t as w}from"./createLucideIcon-B49W6uF4.js";import{l as se,t as ce}from"./react-SMksfEpE.js";import{a as le,i as ue,n as de,r as fe,t as pe}from"./x-Bru-nCti.js";import{c as me,f as he,g as ge,h as _e,i as ve,l as ye,m as be,p as xe,r as Se,t as Ce,u as we}from"./setComponentFile-ZBQ4KXnC.js";import{n as Te}from"./queryClient-CVMXFvkI.js";import{n as Ee,t as De}from"./localStorageKeys-dvU1YhFX.js";import{An as Oe,At as ke,Dn as Ae,Dt as je,Fn as Me,Gn as Ne,Kn as Pe,L as Fe,Mn as Ie,Mt as Le,Ot as Re,R as ze,Un as Be,Ut as Ve,Xn as He,_t as Ue,c as We,kn as Ge,kt as Ke,mn as qe,o as Je,ot as Ye,q as Xe,s as Ze,u as Qe,un as $e,ut as et,zn as tt}from"./index-BbsxXAVZ.js";import{t as nt}from"./useEntityRestURL-CswKSb0j.js";import{n as rt}from"./getAnalytics-Bmxt-5P2.js";var it=w(`between-horizontal-start`,[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]]),at=w(`book`,[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]),ot=w(`chart-area`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]]),st=w(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),ct=w(`file-pen`,[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]]),lt=w(`logs`,[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]),ut=w(`message-square-heart`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]),dt=w(`send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),ft=w(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]);async function pt(){await x.delete(`/Chat/Messages/`)}var T=e(ae(),1),E=oe();function mt({setMessages:e}){let[t,n]=(0,T.useState)(!1);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:(0,T.useCallback)(async()=>{if(!t){n(!0);try{await pt(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]),disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(de,{className:`animate-spin`,size:18}):(0,E.jsx)(Oe,{size:18}),`Clear`]})}async function ht(){let{data:e}=await x.get(`/Chat/Messages/`);return e}var gt=`vercel.ai.error`,_t=Symbol.for(gt),vt,yt,D=class e extends (yt=Error,vt=_t,yt){constructor({name:e,message:t,cause:n}){super(t),this[vt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,gt)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function bt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var xt=`AI_InvalidArgumentError`,St=`vercel.ai.error.${xt}`,Ct=Symbol.for(St),wt,Tt,Et=class extends (Tt=D,wt=Ct,Tt){constructor({message:e,cause:t,argument:n}){super({name:xt,message:e,cause:t}),this[wt]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,St)}},Dt=`AI_JSONParseError`,Ot=`vercel.ai.error.${Dt}`,kt=Symbol.for(Ot),At,jt,Mt=class extends (jt=D,At=kt,jt){constructor({text:e,cause:t}){super({name:Dt,message:`JSON parsing failed: Text: ${e}.
|
|
2
2
|
Error message: ${bt(t)}`,cause:t}),this[At]=!0,this.text=e}static isInstance(e){return D.hasMarker(e,Ot)}},Nt=`AI_TypeValidationError`,Pt=`vercel.ai.error.${Nt}`,Ft=Symbol.for(Pt),It,Lt,O=class e extends (Lt=D,It=Ft,Lt){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:Nt,message:`${r}: Value: ${JSON.stringify(e)}.
|
|
3
3
|
Error message: ${bt(t)}`,cause:t}),this[It]=!0,this.value=e,this.context=n}static isInstance(e){return D.hasMarker(e,Pt)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},Rt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},zt=10,Bt=13,k=32;function Vt(e){}function Ht(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Vt,onError:n=Vt,onRetry:r=Vt,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
4
4
|
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Rt(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
@@ -13,7 +13,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
13
13
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
14
14
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
|
|
15
15
|
`:`[${r[e]}\r
|
|
16
|
-
]`;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 Tn(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===g.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=bn(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===g.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===g.ZodBranded&&e.keyType._def.type._def.typeName===g.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ln(e.keyType._def,t);return{...n,propertyNames:i}}return n}function En(e,t){return t.mapStrategy===`record`?Tn(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function Dn(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 On(){return{not:N()}}function kn(){return{type:`null`}}var An={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function jn(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in An&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=An[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 Mn(e,t)}var Mn=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(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 Nn(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[An[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Pn(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 Fn(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=Ln(a),s=L(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=In(e,t);return a!==void 0&&(n.additionalProperties=a),n}function In(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(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 Ln(e){try{return e.isOptional()}catch{return!0}}var Rn=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},zn=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Bn(e,t){return L(e.type._def,t)}function Vn(e,t){let n={type:`array`,uniqueItems:!0,items:L(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 Hn(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Un(){return{not:N()}}function Wn(){return N()}var Gn=(e,t)=>L(e.innerType._def,t),Kn=(e,t,n)=>{switch(t){case g.ZodString:return bn(e,n);case g.ZodNumber:return Pn(e);case g.ZodObject:return Fn(e,n);case g.ZodBigInt:return sn(e);case g.ZodBoolean:return cn();case g.ZodDate:return dn(e,n);case g.ZodUndefined:return Un();case g.ZodNull:return kn();case g.ZodArray:return on(e,n);case g.ZodUnion:case g.ZodDiscriminatedUnion:return jn(e,n);case g.ZodIntersection:return _n(e,n);case g.ZodTuple:return Hn(e,n);case g.ZodRecord:return Tn(e,n);case g.ZodLiteral:return vn(e);case g.ZodEnum:return hn(e);case g.ZodNativeEnum:return Dn(e);case g.ZodNullable:return Nn(e,n);case g.ZodOptional:return Rn(e,n);case g.ZodMap:return En(e,n);case g.ZodSet:return Vn(e,n);case g.ZodLazy:return()=>e.getter()._def;case g.ZodPromise:return Bn(e,n);case g.ZodNaN:case g.ZodNever:return On();case g.ZodEffects:return mn(e,n);case g.ZodAny:return N();case g.ZodUnknown:return Wn();case g.ZodDefault:return pn(e,n);case g.ZodBranded:return ln(e,n);case g.ZodReadonly:return Gn(e,n);case g.ZodCatch:return un(e,n);case g.ZodPipeline:return zn(e,n);case g.ZodFunction:case g.ZodVoid:case g.ZodSymbol:return;default:return(e=>void 0)(t)}},qn=(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 L(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!==nn)return i}if(r&&!n){let e=Jn(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=Kn(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&Yn(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Jn=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:qn(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`),N()):t.$refStrategy===`seen`?N():void 0}},Yn=(e,t,n)=>(e.description&&(n.description=e.description),n),Xn=e=>{let t=an(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}]))}},Zn=(e,t)=>{let n=Xn(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),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},Qn=Symbol.for(`vercel.ai.schema`);function $n(e){let t;return()=>(t??=e(),t)}function er(e,{validate:t}={}){return{[Qn]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function tr(e){return typeof e==`object`&&!!e&&Qn in e&&e[Qn]===!0&&`jsonSchema`in e&&`validate`in e}function nr(e){return e==null?er({type:`object`,properties:{},additionalProperties:!1}):tr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?sr(e):rr(e):e()}function rr(e){return er(()=>tn(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 O({value:t,cause:n.issues})}}})}function ir(e,t){let n=t?.useReferences??!1;return er(()=>Zn(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 ar(e,t){let r=t?.useReferences??!1;return er(()=>tn(ee(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let r=await n(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}function or(e){return`_zod`in e}function sr(e,t){return or(e)?ar(e,t):ir(e,t)}async function cr({value:e,schema:t,context:n}){let r=await R({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function R({value:e,schema:t,context:n}){let r=nr(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:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function z({text:e,schema:t}){try{let n=en(e);return t==null?{success:!0,value:n,rawValue:n}:await R({value:n,schema:t})}catch(t){return{success:!1,error:Mt.isInstance(t)?t:new Mt({text:e,cause:t}),rawValue:void 0}}}function lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await z({text:e,schema:t}))}}))}async function B(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder,new TextDecoder;var ur=Object.defineProperty,dr=(e,t)=>{for(var n in t)ur(e,n,{get:t[n],enumerable:!0})},fr=`AI_NoObjectGeneratedError`,pr=`vercel.ai.error.${fr}`,mr=Symbol.for(pr),hr,V=class extends D{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:fr,message:e,cause:t}),this[hr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,pr)}};hr=mr;var gr=`AI_UIMessageStreamError`,_r=`vercel.ai.error.${gr}`,vr=Symbol.for(_r),yr,H=class extends D{constructor({chunkType:e,chunkId:t,message:n}){super({name:gr,message:n}),this[yr]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,_r)}};yr=vr;var U=p(()=>y([a(),o(),l(),d(),v(o(),U.optional()),s(U)])),W=v(o(),v(o(),U.optional())),br=y([o(),u(Uint8Array),u(ArrayBuffer),_(Yt,{message:`Must be a Buffer`})]),xr=v(o(),o()),Sr=i({type:f(`text`),text:o(),providerOptions:W.optional()}),Cr=i({type:f(`image`),image:y([br,u(URL),xr]),mediaType:o().optional(),providerOptions:W.optional()}),wr=c(`type`,[i({type:f(`data`),data:br}),i({type:f(`url`),url:u(URL)}),i({type:f(`reference`),reference:xr}),i({type:f(`text`),text:o()})]),Tr=c(`type`,[i({type:f(`data`),data:br}),i({type:f(`url`),url:u(URL)})]),Er=i({type:f(`file`),data:y([wr,br,u(URL),xr]),filename:o().optional(),mediaType:o(),providerOptions:W.optional()}),Dr=i({type:f(`reasoning`),text:o(),providerOptions:W.optional()}),Or=i({type:f(`custom`),kind:o().transform(e=>e),providerOptions:W.optional()}),kr=i({type:f(`reasoning-file`),data:y([Tr,br,u(URL)]),mediaType:o(),providerOptions:W.optional()}),Ar=i({type:f(`tool-call`),toolCallId:o(),toolName:o(),input:r(),providerOptions:W.optional(),providerExecuted:d().optional()}),jr=c(`type`,[i({type:f(`text`),value:o(),providerOptions:W.optional()}),i({type:f(`json`),value:U,providerOptions:W.optional()}),i({type:f(`execution-denied`),reason:o().optional(),providerOptions:W.optional()}),i({type:f(`error-text`),value:o(),providerOptions:W.optional()}),i({type:f(`error-json`),value:U,providerOptions:W.optional()}),i({type:f(`content`),value:s(y([i({type:f(`text`),text:o(),providerOptions:W.optional()}),i({type:f(`file`),data:wr,mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),i({type:f(`file-data`),data:o(),mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),i({type:f(`file-url`),url:o(),mediaType:o().optional(),providerOptions:W.optional()}),i({type:f(`file-id`),fileId:y([o(),v(o(),o())]),providerOptions:W.optional()}),i({type:f(`file-reference`),providerReference:v(o(),o()),providerOptions:W.optional()}),i({type:f(`image-data`),data:o(),mediaType:o(),providerOptions:W.optional()}),i({type:f(`image-url`),url:o(),providerOptions:W.optional()}),i({type:f(`image-file-id`),fileId:y([o(),v(o(),o())]),providerOptions:W.optional()}),i({type:f(`image-file-reference`),providerReference:v(o(),o()),providerOptions:W.optional()}),i({type:f(`custom`),providerOptions:W.optional()})]))})]),Mr=i({type:f(`tool-result`),toolCallId:o(),toolName:o(),output:jr,providerOptions:W.optional()}),Nr=i({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o()}),Pr=i({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional()});y([i({role:f(`system`),content:o(),providerOptions:W.optional()}),i({role:f(`user`),content:y([o(),s(y([Sr,Cr,Er]))]),providerOptions:W.optional()}),i({role:f(`assistant`),content:y([o(),s(y([Sr,Or,Er,Dr,kr,Ar,Mr,Nr]))]),providerOptions:W.optional()}),i({role:f(`tool`),content:s(y([Mr,Pr])),providerOptions:W.optional()})]);function Fr(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(!(r===`__proto__`||r===`constructor`||r===`prototype`)&&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]=Fr(a,i):n[r]=i}return n}dr({},{array:()=>Br,choice:()=>Vr,json:()=>Hr,object:()=>zr,text:()=>Rr});function Ir(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(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 s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;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`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Lr(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await z({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await z({text:Ir(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Rr=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),zr=({schema:e,name:t,description:n})=>{let r=nr(e);return{name:`object`,responseFormat:B(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({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 R({value:n.value,schema:r});if(!i.success)throw new V({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 Lr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Br=({element:e,name:t,description:n})=>{let r=nr(e);return{name:`array`,responseFormat:B(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 z({text:e});if(!n.success)throw new V({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 V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let a=[];for(let n of i.elements){let i=await R({value:n,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});a.push(i.value)}return a},async parsePartialOutput({text:e}){let t=await Lr(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 R({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])}})}}},Vr=({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 z({text:t});if(!r.success)throw new V({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 V({message:`No object generated: response did not match schema.`,cause:new O({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 Lr(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(){}}),Hr=({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 z({text:e});if(!n.success)throw new V({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 Lr(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(){}});new TextEncoder,new TextEncoder,A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),TransformStream;var Ur=v(o(),U.optional()),Wr=$n(()=>sr(y([b({type:f(`text-start`),id:o(),providerMetadata:W.optional()}),b({type:f(`text-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),b({type:f(`text-end`),id:o(),providerMetadata:W.optional()}),b({type:f(`error`),errorText:o()}),b({type:f(`tool-input-start`),toolCallId:o(),toolName:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),title:o().optional()}),b({type:f(`tool-input-delta`),toolCallId:o(),inputTextDelta:o()}),b({type:f(`tool-input-available`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),title:o().optional()}),b({type:f(`tool-input-error`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),errorText:o(),title:o().optional()}),b({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o(),isAutomatic:d().optional(),signature:o().optional()}),b({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional(),providerExecuted:d().optional(),providerMetadata:W.optional()}),b({type:f(`tool-output-available`),toolCallId:o(),output:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),preliminary:d().optional()}),b({type:f(`tool-output-error`),toolCallId:o(),errorText:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional()}),b({type:f(`tool-output-denied`),toolCallId:o()}),b({type:f(`reasoning-start`),id:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-end`),id:o(),providerMetadata:W.optional()}),b({type:f(`custom`),kind:o().transform(e=>e),providerMetadata:W.optional()}),b({type:f(`source-url`),sourceId:o(),url:o(),title:o().optional(),providerMetadata:W.optional()}),b({type:f(`source-document`),sourceId:o(),mediaType:o(),title:o(),filename:o().optional(),providerMetadata:W.optional()}),b({type:f(`file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),b({type:_(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:o().optional(),data:r(),transient:d().optional()}),b({type:f(`start-step`)}),b({type:f(`finish-step`)}),b({type:f(`start`),messageId:o().optional(),messageMetadata:r().optional()}),b({type:f(`finish`),finishReason:m([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:r().optional()}),b({type:f(`abort`),reason:o().optional()}),b({type:f(`message-metadata`),messageMetadata:r()})])));function Gr(e){return e.type.startsWith(`data-`)}function Kr(){return Object.create(null)}function qr(e){return e.type===`text`}function Jr(e){return e.type.startsWith(`tool-`)}function Yr(e){return e.type===`dynamic-tool`}function G(e){return Jr(e)||Yr(e)}function Xr(e){return e.type.split(`-`).slice(1).join(`-`)}function Zr(e){return Yr(e)?e.toolName:Xr(e)}function Qr({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:Kr(),activeReasoningParts:Kr(),partialToolCalls:Kr()}}function $r({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(G).find(t=>t.toolCallId===e);if(t==null)throw new H({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.filter(G).find(t=>t.approval?.id===e);if(t==null)throw new H({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function d(e){let t=r.message.parts.find(t=>Jr(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),e.toolMetadata!==void 0&&(i.toolMetadata=e.toolMetadata),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,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},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 f(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),e.toolMetadata!==void 0&&(i.toolMetadata=e.toolMetadata),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,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...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 p(e){if(e!=null){let n=r.message.metadata==null?e:Fr(r.message.metadata,e);t!=null&&await cr({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 H({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 H({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`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),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 H({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 H({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`:case`reasoning-file`:r.message.parts.push({type:e.type,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(Jr);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new H({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 Lr(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=r.message.parts.filter(G).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),c();break}case`tool-approval-request`:{let t=l(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=u(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason},...n.isAutomatic===!0?{isAutomatic:!0}:{},...n.signature==null?{}:{signature:n.signature}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),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`?f({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,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:Xr(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-output-error`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?f({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:Xr(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=Kr(),r.activeReasoningParts=Kr();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await p(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await p(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await p(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Gr(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 cr({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 ei({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()}}A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),v(o(),U.optional()),v(o(),o()),A({prefix:`call`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aiobj`,size:24});var ti=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()})}};A({prefix:`aiobj`,size:24}),A({prefix:`call`,size:24});async function ni(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 ri=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 B(this.body),r=await B(this.headers),i=await B(this.credentials),a={...j(r),...j(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:j(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 B(this.body),n=await B(this.headers),r=await B(this.credentials),i={...j(n),...j(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:j(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)}},ii=class extends ri{constructor(e={}){super(e)}processResponseStream(e){return lr({stream:e,schema:Wr}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},ai=class{constructor({generateId:e=Jt,id:t=e(),transport:n=new ii,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new ti,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 ni(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=>G(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.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=>G(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:Qr({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 ei({stream:$r({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 oi({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(G).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}function si(e){return new ii({api:be(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var ci=e(t(((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),li=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},K=(e,t,n)=>(li(e,t,`read from private field`),n?n.call(e):t.get(e)),q=(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)},J=(e,t,n,r)=>(li(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function ui(e,t){return t==null?e:(0,ci.default)(e,t)}var Y,di,fi,X,pi,Z,Q,mi,hi,gi=class{constructor(e=[]){q(this,Y,void 0),q(this,di,`ready`),q(this,fi,void 0),q(this,X,new Set),q(this,pi,new Set),q(this,Z,new Set),this.pushMessage=e=>{J(this,Y,K(this,Y).concat(e)),K(this,Q).call(this)},this.popMessage=()=>{J(this,Y,K(this,Y).slice(0,-1)),K(this,Q).call(this)},this.replaceMessage=(e,t)=>{J(this,Y,[...K(this,Y).slice(0,e),this.snapshot(t),...K(this,Y).slice(e+1)]),K(this,Q).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?ui(e,t):e;return K(this,X).add(n),()=>{K(this,X).delete(n)}},this[`~registerStatusCallback`]=e=>(K(this,pi).add(e),()=>{K(this,pi).delete(e)}),this[`~registerErrorCallback`]=e=>(K(this,Z).add(e),()=>{K(this,Z).delete(e)}),q(this,Q,()=>{K(this,X).forEach(e=>e())}),q(this,mi,()=>{K(this,pi).forEach(e=>e())}),q(this,hi,()=>{K(this,Z).forEach(e=>e())}),J(this,Y,e)}get status(){return K(this,di)}set status(e){J(this,di,e),K(this,mi).call(this)}get error(){return K(this,fi)}set error(e){J(this,fi,e),K(this,hi).call(this)}get messages(){return K(this,Y)}set messages(e){J(this,Y,[...e]),K(this,Q).call(this)}};Y=new WeakMap,di=new WeakMap,fi=new WeakMap,X=new WeakMap,pi=new WeakMap,Z=new WeakMap,Q=new WeakMap,mi=new WeakMap,hi=new WeakMap;var $,_i=class extends ai{constructor({messages:e,...t}){let n=new gi(e);super({...t,state:n}),q(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>K(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>K(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>K(this,$)[`~registerErrorCallback`](e),J(this,$,n)}};$=new WeakMap;function vi({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new ii),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=(0,T.useRef)(`chat`in r?r.chat:new _i(c));(`chat`in r&&r.chat!==l.current||`id`in r&&r.id!=null&&l.current.id!==r.id)&&(l.current=`chat`in r?r.chat:new _i(c));let u=(0,T.useSyncExternalStore)((0,T.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),()=>l.current.messages,()=>l.current.messages),d=(0,T.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),f=(0,T.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),p=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,T.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:u,setMessages:p,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:f,resumeStream:l.current.resumeStream,status:d,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function yi({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(dt,{size:18})})]})}function bi(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(de,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var xi={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:i({feedbackSummary:o().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:o().describe(`Detailed feedback from the user or agent observation.`),recap:o().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Si({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var Ci={...xi,icon:ut,execute:Si},wi={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:i({name:o().trim(),type:m(xe)})};async function Ti({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Pe(e),a=ye(he,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${he.map(e=>e.id).join(`, `)}`};let o=C.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await we({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}Ke(`ReloadApplicationRootEntries`,!0),C.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await We({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Ei={...wi,icon:ze,execute:Ti,requiresApproval:!0},Di={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:i({database:o().trim(),table:o().trim(),primaryKeys:s(o())})};async function Oi({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await et({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ki={...Di,icon:it,execute:Oi,requiresApproval:!0},Ai={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim()})};async function ji({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await me({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Mi={...Ai,icon:Ie,execute:ji,requiresApproval:!0},Ni={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:i({metricName:o().describe(`The name of the metric to retrieve.`),startTime:l().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:l().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Pi({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await rt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Fi={...Ni,icon:ot,execute:Pi},Ii={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim()})};async function Li({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await Ue({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ri={...Ii,icon:ge,execute:Li},zi={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:i({})};async function Bi({instanceClientParams:e}){try{let{rootEntries:t}=Se((await Ze(e)).entries);return{success:!0,items:ve(t).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Vi={...zi,icon:_e,execute:Bi},Hi={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:i({})};async function Ui({instanceClientParams:e}){try{return{success:!0,map:await He(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Wi={...Hi,icon:Me,execute:Ui},Gi={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim()})};async function Ki({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await tt({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var qi={...Gi,icon:Ge,execute:Ki},Ji={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:i({})};async function Yi({instanceClientParams:e,params:t}){let n=Xe();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=Je(`FileFocused/${e.entityId}`,void 0),i=Je(`FolderOpened/${e.entityId}`,[]),a=Je(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Xi={...Ji,icon:Ae,execute:Yi},Zi={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),records:s(h())})};async function Qi({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Fe({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var $i={...Zi,icon:it,execute:Qi,requiresApproval:!0},ea={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:i({metricTypes:m([`builtin`,`custom`]),customWindowMS:l().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function ta({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function na({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await ta({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var ra={...ea,icon:ot,execute:na},ia=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`vector-indexing`],aa={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
|
|
16
|
+
]`;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 Tn(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===g.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=bn(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===g.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===g.ZodBranded&&e.keyType._def.type._def.typeName===g.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ln(e.keyType._def,t);return{...n,propertyNames:i}}return n}function En(e,t){return t.mapStrategy===`record`?Tn(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function Dn(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 On(){return{not:N()}}function kn(){return{type:`null`}}var An={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function jn(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in An&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=An[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 Mn(e,t)}var Mn=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(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 Nn(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[An[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Pn(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 Fn(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=Ln(a),s=L(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=In(e,t);return a!==void 0&&(n.additionalProperties=a),n}function In(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(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 Ln(e){try{return e.isOptional()}catch{return!0}}var Rn=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},zn=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Bn(e,t){return L(e.type._def,t)}function Vn(e,t){let n={type:`array`,uniqueItems:!0,items:L(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 Hn(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Un(){return{not:N()}}function Wn(){return N()}var Gn=(e,t)=>L(e.innerType._def,t),Kn=(e,t,n)=>{switch(t){case g.ZodString:return bn(e,n);case g.ZodNumber:return Pn(e);case g.ZodObject:return Fn(e,n);case g.ZodBigInt:return sn(e);case g.ZodBoolean:return cn();case g.ZodDate:return dn(e,n);case g.ZodUndefined:return Un();case g.ZodNull:return kn();case g.ZodArray:return on(e,n);case g.ZodUnion:case g.ZodDiscriminatedUnion:return jn(e,n);case g.ZodIntersection:return _n(e,n);case g.ZodTuple:return Hn(e,n);case g.ZodRecord:return Tn(e,n);case g.ZodLiteral:return vn(e);case g.ZodEnum:return hn(e);case g.ZodNativeEnum:return Dn(e);case g.ZodNullable:return Nn(e,n);case g.ZodOptional:return Rn(e,n);case g.ZodMap:return En(e,n);case g.ZodSet:return Vn(e,n);case g.ZodLazy:return()=>e.getter()._def;case g.ZodPromise:return Bn(e,n);case g.ZodNaN:case g.ZodNever:return On();case g.ZodEffects:return mn(e,n);case g.ZodAny:return N();case g.ZodUnknown:return Wn();case g.ZodDefault:return pn(e,n);case g.ZodBranded:return ln(e,n);case g.ZodReadonly:return Gn(e,n);case g.ZodCatch:return un(e,n);case g.ZodPipeline:return zn(e,n);case g.ZodFunction:case g.ZodVoid:case g.ZodSymbol:return;default:return(e=>void 0)(t)}},qn=(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 L(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!==nn)return i}if(r&&!n){let e=Jn(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=Kn(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&Yn(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Jn=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:qn(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`),N()):t.$refStrategy===`seen`?N():void 0}},Yn=(e,t,n)=>(e.description&&(n.description=e.description),n),Xn=e=>{let t=an(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}]))}},Zn=(e,t)=>{let n=Xn(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),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},Qn=Symbol.for(`vercel.ai.schema`);function $n(e){let t;return()=>(t??=e(),t)}function er(e,{validate:t}={}){return{[Qn]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function tr(e){return typeof e==`object`&&!!e&&Qn in e&&e[Qn]===!0&&`jsonSchema`in e&&`validate`in e}function nr(e){return e==null?er({type:`object`,properties:{},additionalProperties:!1}):tr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?sr(e):rr(e):e()}function rr(e){return er(()=>tn(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 O({value:t,cause:n.issues})}}})}function ir(e,t){let n=t?.useReferences??!1;return er(()=>Zn(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 ar(e,t){let r=t?.useReferences??!1;return er(()=>tn(ee(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let r=await n(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}function or(e){return`_zod`in e}function sr(e,t){return or(e)?ar(e,t):ir(e,t)}async function cr({value:e,schema:t,context:n}){let r=await R({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function R({value:e,schema:t,context:n}){let r=nr(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:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function z({text:e,schema:t}){try{let n=en(e);return t==null?{success:!0,value:n,rawValue:n}:await R({value:n,schema:t})}catch(t){return{success:!1,error:Mt.isInstance(t)?t:new Mt({text:e,cause:t}),rawValue:void 0}}}function lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await z({text:e,schema:t}))}}))}async function B(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder,new TextDecoder;var ur=Object.defineProperty,dr=(e,t)=>{for(var n in t)ur(e,n,{get:t[n],enumerable:!0})},fr=`AI_NoObjectGeneratedError`,pr=`vercel.ai.error.${fr}`,mr=Symbol.for(pr),hr,V=class extends D{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:fr,message:e,cause:t}),this[hr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,pr)}};hr=mr;var gr=`AI_UIMessageStreamError`,_r=`vercel.ai.error.${gr}`,vr=Symbol.for(_r),yr,H=class extends D{constructor({chunkType:e,chunkId:t,message:n}){super({name:gr,message:n}),this[yr]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,_r)}};yr=vr;var U=p(()=>y([a(),o(),l(),d(),v(o(),U.optional()),s(U)])),W=v(o(),v(o(),U.optional())),br=y([o(),u(Uint8Array),u(ArrayBuffer),_(Yt,{message:`Must be a Buffer`})]),xr=v(o(),o()),Sr=i({type:f(`text`),text:o(),providerOptions:W.optional()}),Cr=i({type:f(`image`),image:y([br,u(URL),xr]),mediaType:o().optional(),providerOptions:W.optional()}),wr=c(`type`,[i({type:f(`data`),data:br}),i({type:f(`url`),url:u(URL)}),i({type:f(`reference`),reference:xr}),i({type:f(`text`),text:o()})]),Tr=c(`type`,[i({type:f(`data`),data:br}),i({type:f(`url`),url:u(URL)})]),Er=i({type:f(`file`),data:y([wr,br,u(URL),xr]),filename:o().optional(),mediaType:o(),providerOptions:W.optional()}),Dr=i({type:f(`reasoning`),text:o(),providerOptions:W.optional()}),Or=i({type:f(`custom`),kind:o().transform(e=>e),providerOptions:W.optional()}),kr=i({type:f(`reasoning-file`),data:y([Tr,br,u(URL)]),mediaType:o(),providerOptions:W.optional()}),Ar=i({type:f(`tool-call`),toolCallId:o(),toolName:o(),input:r(),providerOptions:W.optional(),providerExecuted:d().optional()}),jr=c(`type`,[i({type:f(`text`),value:o(),providerOptions:W.optional()}),i({type:f(`json`),value:U,providerOptions:W.optional()}),i({type:f(`execution-denied`),reason:o().optional(),providerOptions:W.optional()}),i({type:f(`error-text`),value:o(),providerOptions:W.optional()}),i({type:f(`error-json`),value:U,providerOptions:W.optional()}),i({type:f(`content`),value:s(y([i({type:f(`text`),text:o(),providerOptions:W.optional()}),i({type:f(`file`),data:wr,mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),i({type:f(`file-data`),data:o(),mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),i({type:f(`file-url`),url:o(),mediaType:o().optional(),providerOptions:W.optional()}),i({type:f(`file-id`),fileId:y([o(),v(o(),o())]),providerOptions:W.optional()}),i({type:f(`file-reference`),providerReference:v(o(),o()),providerOptions:W.optional()}),i({type:f(`image-data`),data:o(),mediaType:o(),providerOptions:W.optional()}),i({type:f(`image-url`),url:o(),providerOptions:W.optional()}),i({type:f(`image-file-id`),fileId:y([o(),v(o(),o())]),providerOptions:W.optional()}),i({type:f(`image-file-reference`),providerReference:v(o(),o()),providerOptions:W.optional()}),i({type:f(`custom`),providerOptions:W.optional()})]))})]),Mr=i({type:f(`tool-result`),toolCallId:o(),toolName:o(),output:jr,providerOptions:W.optional()}),Nr=i({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o()}),Pr=i({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional()});y([i({role:f(`system`),content:o(),providerOptions:W.optional()}),i({role:f(`user`),content:y([o(),s(y([Sr,Cr,Er]))]),providerOptions:W.optional()}),i({role:f(`assistant`),content:y([o(),s(y([Sr,Or,Er,Dr,kr,Ar,Mr,Nr]))]),providerOptions:W.optional()}),i({role:f(`tool`),content:s(y([Mr,Pr])),providerOptions:W.optional()})]);function Fr(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(!(r===`__proto__`||r===`constructor`||r===`prototype`)&&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]=Fr(a,i):n[r]=i}return n}dr({},{array:()=>Br,choice:()=>Vr,json:()=>Hr,object:()=>zr,text:()=>Rr});function Ir(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(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 s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;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`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Lr(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await z({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await z({text:Ir(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Rr=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),zr=({schema:e,name:t,description:n})=>{let r=nr(e);return{name:`object`,responseFormat:B(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({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 R({value:n.value,schema:r});if(!i.success)throw new V({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 Lr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Br=({element:e,name:t,description:n})=>{let r=nr(e);return{name:`array`,responseFormat:B(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 z({text:e});if(!n.success)throw new V({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 V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let a=[];for(let n of i.elements){let i=await R({value:n,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});a.push(i.value)}return a},async parsePartialOutput({text:e}){let t=await Lr(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 R({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])}})}}},Vr=({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 z({text:t});if(!r.success)throw new V({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 V({message:`No object generated: response did not match schema.`,cause:new O({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 Lr(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(){}}),Hr=({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 z({text:e});if(!n.success)throw new V({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 Lr(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(){}});new TextEncoder,new TextEncoder,A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),TransformStream;var Ur=v(o(),U.optional()),Wr=$n(()=>sr(y([b({type:f(`text-start`),id:o(),providerMetadata:W.optional()}),b({type:f(`text-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),b({type:f(`text-end`),id:o(),providerMetadata:W.optional()}),b({type:f(`error`),errorText:o()}),b({type:f(`tool-input-start`),toolCallId:o(),toolName:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),title:o().optional()}),b({type:f(`tool-input-delta`),toolCallId:o(),inputTextDelta:o()}),b({type:f(`tool-input-available`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),title:o().optional()}),b({type:f(`tool-input-error`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),errorText:o(),title:o().optional()}),b({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o(),isAutomatic:d().optional(),signature:o().optional()}),b({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional(),providerExecuted:d().optional(),providerMetadata:W.optional()}),b({type:f(`tool-output-available`),toolCallId:o(),output:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional(),preliminary:d().optional()}),b({type:f(`tool-output-error`),toolCallId:o(),errorText:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Ur.optional(),dynamic:d().optional()}),b({type:f(`tool-output-denied`),toolCallId:o()}),b({type:f(`reasoning-start`),id:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-end`),id:o(),providerMetadata:W.optional()}),b({type:f(`custom`),kind:o().transform(e=>e),providerMetadata:W.optional()}),b({type:f(`source-url`),sourceId:o(),url:o(),title:o().optional(),providerMetadata:W.optional()}),b({type:f(`source-document`),sourceId:o(),mediaType:o(),title:o(),filename:o().optional(),providerMetadata:W.optional()}),b({type:f(`file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),b({type:f(`reasoning-file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),b({type:_(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:o().optional(),data:r(),transient:d().optional()}),b({type:f(`start-step`)}),b({type:f(`finish-step`)}),b({type:f(`start`),messageId:o().optional(),messageMetadata:r().optional()}),b({type:f(`finish`),finishReason:m([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:r().optional()}),b({type:f(`abort`),reason:o().optional()}),b({type:f(`message-metadata`),messageMetadata:r()})])));function Gr(e){return e.type.startsWith(`data-`)}function Kr(){return Object.create(null)}function qr(e){return e.type===`text`}function Jr(e){return e.type.startsWith(`tool-`)}function Yr(e){return e.type===`dynamic-tool`}function G(e){return Jr(e)||Yr(e)}function Xr(e){return e.type.split(`-`).slice(1).join(`-`)}function Zr(e){return Yr(e)?e.toolName:Xr(e)}function Qr({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:Kr(),activeReasoningParts:Kr(),partialToolCalls:Kr()}}function $r({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(G).find(t=>t.toolCallId===e);if(t==null)throw new H({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.filter(G).find(t=>t.approval?.id===e);if(t==null)throw new H({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function d(e){let t=r.message.parts.find(t=>Jr(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),e.toolMetadata!==void 0&&(i.toolMetadata=e.toolMetadata),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,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},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 f(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),e.toolMetadata!==void 0&&(i.toolMetadata=e.toolMetadata),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,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...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 p(e){if(e!=null){let n=r.message.metadata==null?e:Fr(r.message.metadata,e);t!=null&&await cr({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 H({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 H({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`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),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 H({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 H({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`:case`reasoning-file`:r.message.parts.push({type:e.type,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(Jr);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new H({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 Lr(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=r.message.parts.filter(G).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?f({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):d({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),c();break}case`tool-approval-request`:{let t=l(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=u(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason},...n.isAutomatic===!0?{isAutomatic:!0}:{},...n.signature==null?{}:{signature:n.signature}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),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`?f({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,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:Xr(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-output-error`:{let t=l(e.toolCallId);t.type===`dynamic-tool`?f({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}):d({toolCallId:e.toolCallId,toolName:Xr(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=Kr(),r.activeReasoningParts=Kr();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await p(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await p(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await p(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Gr(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 cr({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 ei({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()}}A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),v(o(),U.optional()),v(o(),o()),A({prefix:`call`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aiobj`,size:24});var ti=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()})}};A({prefix:`aiobj`,size:24}),A({prefix:`call`,size:24});async function ni(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 ri=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 B(this.body),r=await B(this.headers),i=await B(this.credentials),a={...j(r),...j(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:j(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 B(this.body),n=await B(this.headers),r=await B(this.credentials),i={...j(n),...j(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:j(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)}},ii=class extends ri{constructor(e={}){super(e)}processResponseStream(e){return lr({stream:e,schema:Wr}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},ai=class{constructor({generateId:e=Jt,id:t=e(),transport:n=new ii,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new ti,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 ni(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=>G(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.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=>G(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:Qr({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 ei({stream:$r({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 oi({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(G).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}function si(e){return new ii({api:be(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var ci=e(t(((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),li=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},K=(e,t,n)=>(li(e,t,`read from private field`),n?n.call(e):t.get(e)),q=(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)},J=(e,t,n,r)=>(li(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function ui(e,t){return t==null?e:(0,ci.default)(e,t)}var Y,di,fi,X,pi,Z,Q,mi,hi,gi=class{constructor(e=[]){q(this,Y,void 0),q(this,di,`ready`),q(this,fi,void 0),q(this,X,new Set),q(this,pi,new Set),q(this,Z,new Set),this.pushMessage=e=>{J(this,Y,K(this,Y).concat(e)),K(this,Q).call(this)},this.popMessage=()=>{J(this,Y,K(this,Y).slice(0,-1)),K(this,Q).call(this)},this.replaceMessage=(e,t)=>{J(this,Y,[...K(this,Y).slice(0,e),this.snapshot(t),...K(this,Y).slice(e+1)]),K(this,Q).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?ui(e,t):e;return K(this,X).add(n),()=>{K(this,X).delete(n)}},this[`~registerStatusCallback`]=e=>(K(this,pi).add(e),()=>{K(this,pi).delete(e)}),this[`~registerErrorCallback`]=e=>(K(this,Z).add(e),()=>{K(this,Z).delete(e)}),q(this,Q,()=>{K(this,X).forEach(e=>e())}),q(this,mi,()=>{K(this,pi).forEach(e=>e())}),q(this,hi,()=>{K(this,Z).forEach(e=>e())}),J(this,Y,e)}get status(){return K(this,di)}set status(e){J(this,di,e),K(this,mi).call(this)}get error(){return K(this,fi)}set error(e){J(this,fi,e),K(this,hi).call(this)}get messages(){return K(this,Y)}set messages(e){J(this,Y,[...e]),K(this,Q).call(this)}};Y=new WeakMap,di=new WeakMap,fi=new WeakMap,X=new WeakMap,pi=new WeakMap,Z=new WeakMap,Q=new WeakMap,mi=new WeakMap,hi=new WeakMap;var $,_i=class extends ai{constructor({messages:e,...t}){let n=new gi(e);super({...t,state:n}),q(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>K(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>K(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>K(this,$)[`~registerErrorCallback`](e),J(this,$,n)}};$=new WeakMap;function vi({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new ii),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=(0,T.useRef)(`chat`in r?r.chat:new _i(c));(`chat`in r&&r.chat!==l.current||`id`in r&&r.id!=null&&l.current.id!==r.id)&&(l.current=`chat`in r?r.chat:new _i(c));let u=(0,T.useSyncExternalStore)((0,T.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),()=>l.current.messages,()=>l.current.messages),d=(0,T.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),f=(0,T.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),p=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,T.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:u,setMessages:p,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:f,resumeStream:l.current.resumeStream,status:d,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function yi({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(dt,{size:18})})]})}function bi(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(de,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var xi={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:i({feedbackSummary:o().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:o().describe(`Detailed feedback from the user or agent observation.`),recap:o().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Si({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var Ci={...xi,icon:ut,execute:Si},wi={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:i({name:o().trim(),type:m(xe)})};async function Ti({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Ve(e),a=ye(he,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${he.map(e=>e.id).join(`, `)}`};let o=C.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await we({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}Le(`ReloadApplicationRootEntries`,!0),C.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await Ue({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Ei={...wi,icon:tt,execute:Ti,requiresApproval:!0},Di={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:i({database:o().trim(),table:o().trim(),primaryKeys:s(o())})};async function Oi({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await We({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ki={...Di,icon:it,execute:Oi,requiresApproval:!0},Ai={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim()})};async function ji({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await me({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Mi={...Ai,icon:Ge,execute:ji,requiresApproval:!0},Ni={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:i({metricName:o().describe(`The name of the metric to retrieve.`),startTime:l().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:l().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Pi({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await rt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Fi={...Ni,icon:ot,execute:Pi},Ii={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim()})};async function Li({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await Qe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ri={...Ii,icon:ge,execute:Li},zi={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:i({})};async function Bi({instanceClientParams:e}){try{let{rootEntries:t}=Se((await et(e)).entries);return{success:!0,items:ve(t).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Vi={...zi,icon:_e,execute:Bi},Hi={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:i({})};async function Ui({instanceClientParams:e}){try{return{success:!0,map:await Ye(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Wi={...Hi,icon:Pe,execute:Ui},Gi={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim()})};async function Ki({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Fe({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var qi={...Gi,icon:Ie,execute:Ki},Ji={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:i({})};async function Yi({instanceClientParams:e,params:t}){let n=$e();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=ke(`FileFocused/${e.entityId}`,void 0),i=ke(`FolderOpened/${e.entityId}`,[]),a=ke(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Xi={...Ji,icon:Ae,execute:Yi},Zi={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),records:s(h())})};async function Qi({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Xe({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var $i={...Zi,icon:it,execute:Qi,requiresApproval:!0},ea={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:i({metricTypes:m([`builtin`,`custom`]),customWindowMS:l().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function ta({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function na({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await ta({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var ra={...ea,icon:ot,execute:na},ia=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`vector-indexing`],aa={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
|
|
17
17
|
name: automatic-apis
|
|
18
18
|
description: How to use Harper's automatically generated REST and WebSocket APIs.
|
|
19
19
|
metadata:
|
|
@@ -1943,7 +1943,7 @@ jsResource:
|
|
|
1943
1943
|
- No build step or transpiler is required — Harper runs \`.ts\` files directly.
|
|
1944
1944
|
- Type imports (e.g., \`import { type RequestTargetOrId }\`) from the \`harper\` package work as usual.
|
|
1945
1945
|
- Unsupported TypeScript features include: enums with runtime values, namespaces with runtime semantics, and anything requiring code transformation beyond simple type stripping.
|
|
1946
|
-
`,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","vector-indexing":'---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac\n inputHash: d90b1b74597d08a6\n---\n\n# Vector Indexing\n\nInstructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.\n\n## When to Use\n\nApply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or tuning index construction and search parameters. Use it alongside [adding-tables-with-schemas.md](adding-tables-with-schemas.md) when defining the schema that hosts the vector field.\n\n## How It Works\n\n1. **Declare the vector index on a field**: Add `@indexed(type: "HNSW")` to a `[Float]` field inside a `@table` type. This creates an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `.search()` with a `sort` descriptor that specifies the indexed `attribute` and a `target` vector. Use `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: [{ attribute: \'price\', comparator: \'lt\', value: 50 }],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. This bounds result quality rather than ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Available in both `sort`-based and threshold-based queries.\n\n ```javascript\n let results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n6. **Tune per-query search options**: Pass `distance` and `ef` directly on the `sort` descriptor to override index defaults for a single query.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector, distance: \'dotProduct\', ef: 200 },\n limit: 5,\n });\n ```\n\n - `distance` — overrides the distance function for this query: `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n - `ef` — overrides the search exploration budget. Higher values improve recall at the cost of latency.\n\n7. **Configure HNSW index parameters**: Pass parameters directly in the `@indexed` directive. Structural parameters (`distance`, `M`, `efConstruction`, `quantization`) trigger an index rebuild when changed; `efConstructionSearch` does not.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n }\n ```\n\n8. **Enable vector quantization**: Use `quantization: "int8"` to store vectors as 8-bit integers, reducing index size and memory usage. Harper re-ranks nearest-neighbor `sort` results against full-precision vectors automatically.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")\n }\n ```\n\n## Examples\n\nFull schema with custom HNSW parameters and a nearest-neighbor query with distance output:\n\n```graphql\ntype Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n}\n```\n\n```javascript\n// Nearest-neighbor search with distance scores\nlet results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n});\n\n// Distance-threshold query (no ranking)\nlet closeMatches = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n});\n```\n\n## Notes\n\n### HNSW Parameters\n\n| Parameter | Default | Description |\n| ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |\n| `distance` | `"cosine"` | Distance function: `"cosine"`, `"euclidean"`, or `"dotProduct"` |\n| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n| `mL` | computed from `M` | Normalization factor for level generation |\n| `efConstructionSearch` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size; setting it fixes the budget |\n| `quantization` | — | `"int8"` stores vectors quantized to int8 |\n\n- The `distance` option on a per-query `sort` descriptor accepts `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n- When no `ef` is passed and `efConstructionSearch` (or `efConstruction`) is not explicitly set on the index, the search budget auto-scales with index size.\n- `efConstruction` seeds the initial value of `efConstructionSearch`; setting either one fixes the search budget.\n- The correct parameter name is `efConstructionSearch` (not `efSearchConstruction`).\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- For `quantization: "int8"`, distance-threshold (`lt`/`le`) queries filter on approximate distance; `sort` queries re-rank against full-precision vectors.\n'},oa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:i({skill:m(ia)})};async function sa({input:{skill:e}}){return{success:!!aa[e],message:aa[e]||`No skill found with the name ${e}`}}var ca={...oa,icon:at,execute:sa},la={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:i({log_name:m([`hdb.log`,`system.log`]).default(`hdb.log`),limit:o().or(a()).optional(),level:m([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(a()).optional(),from:o().or(a()).optional(),until:o().or(a()).optional()})};async function ua({input:e,instanceClientParams:t}){try{return{success:!0,data:await Qe({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var da={...la,icon:lt,execute:ua},fa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),pageIndex:l().default(0),pageSize:l().default(10),primaryKey:o(),conditions:s(i({search_attribute:o(),search_type:m([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:h()})),sort:i({attribute:o(),descending:d()})})};async function pa({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await ke({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await Oe({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ma={...fa,icon:Re,execute:pa},ha={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:i({})};async function ga({instanceClientParams:e,baseURL:t}){let n=C.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await We({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var _a={...ha,icon:de,execute:ga,requiresApproval:!0},va={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim(),payload:o(),encoding:m([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function ya({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await Ce({...r,file:o,project:a,payload:n,encoding:t});return await Te.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Ke(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ba={...va,icon:ct,execute:ya,requiresApproval:!0},xa={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),records:s(h())})};async function Sa({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ye({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ca={readHarperSkill:ca,createApp:Ei,readLogs:da,getAnalytics:Fi,listAnalyticsMetrics:ra,restartHTTPService:_a,collectFeedback:Ci,getUserContext:Xi,getComponentFile:Ri,getComponents:Vi,setComponentFile:ba,dropComponentFile:Mi,getDescribeAll:Wi,getDescribeTable:qi,insertTableRecords:$i,readTableRecords:ma,updateTableRecords:{...xa,icon:it,execute:Sa,requiresApproval:!0},deleteTableRecords:ki};function wa(e){return Ca[e]}function Ta(e){return e.state===`input-available`&&!!wa(Zr(e))?.requiresApproval}function Ea(e){let t=[];for(let[n,r]of(e??[]).entries()){if(G(r)){if(Ta(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}qr(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Da({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Zr(e),u=wa(l),d=u?.icon||Be,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
|
|
1946
|
+
`,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","vector-indexing":'---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac\n inputHash: d90b1b74597d08a6\n---\n\n# Vector Indexing\n\nInstructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.\n\n## When to Use\n\nApply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or tuning index construction and search parameters. Use it alongside [adding-tables-with-schemas.md](adding-tables-with-schemas.md) when defining the schema that hosts the vector field.\n\n## How It Works\n\n1. **Declare the vector index on a field**: Add `@indexed(type: "HNSW")` to a `[Float]` field inside a `@table` type. This creates an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `.search()` with a `sort` descriptor that specifies the indexed `attribute` and a `target` vector. Use `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: [{ attribute: \'price\', comparator: \'lt\', value: 50 }],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. This bounds result quality rather than ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Available in both `sort`-based and threshold-based queries.\n\n ```javascript\n let results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n6. **Tune per-query search options**: Pass `distance` and `ef` directly on the `sort` descriptor to override index defaults for a single query.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector, distance: \'dotProduct\', ef: 200 },\n limit: 5,\n });\n ```\n\n - `distance` — overrides the distance function for this query: `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n - `ef` — overrides the search exploration budget. Higher values improve recall at the cost of latency.\n\n7. **Configure HNSW index parameters**: Pass parameters directly in the `@indexed` directive. Structural parameters (`distance`, `M`, `efConstruction`, `quantization`) trigger an index rebuild when changed; `efConstructionSearch` does not.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n }\n ```\n\n8. **Enable vector quantization**: Use `quantization: "int8"` to store vectors as 8-bit integers, reducing index size and memory usage. Harper re-ranks nearest-neighbor `sort` results against full-precision vectors automatically.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")\n }\n ```\n\n## Examples\n\nFull schema with custom HNSW parameters and a nearest-neighbor query with distance output:\n\n```graphql\ntype Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n}\n```\n\n```javascript\n// Nearest-neighbor search with distance scores\nlet results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n});\n\n// Distance-threshold query (no ranking)\nlet closeMatches = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n});\n```\n\n## Notes\n\n### HNSW Parameters\n\n| Parameter | Default | Description |\n| ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |\n| `distance` | `"cosine"` | Distance function: `"cosine"`, `"euclidean"`, or `"dotProduct"` |\n| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n| `mL` | computed from `M` | Normalization factor for level generation |\n| `efConstructionSearch` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size; setting it fixes the budget |\n| `quantization` | — | `"int8"` stores vectors quantized to int8 |\n\n- The `distance` option on a per-query `sort` descriptor accepts `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n- When no `ef` is passed and `efConstructionSearch` (or `efConstruction`) is not explicitly set on the index, the search budget auto-scales with index size.\n- `efConstruction` seeds the initial value of `efConstructionSearch`; setting either one fixes the search budget.\n- The correct parameter name is `efConstructionSearch` (not `efSearchConstruction`).\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- For `quantization: "int8"`, distance-threshold (`lt`/`le`) queries filter on approximate distance; `sort` queries re-rank against full-precision vectors.\n'},oa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:i({skill:m(ia)})};async function sa({input:{skill:e}}){return{success:!!aa[e],message:aa[e]||`No skill found with the name ${e}`}}var ca={...oa,icon:at,execute:sa},la={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:i({log_name:m([`hdb.log`,`system.log`]).default(`hdb.log`),limit:o().or(a()).optional(),level:m([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(a()).optional(),from:o().or(a()).optional(),until:o().or(a()).optional()})};async function ua({input:e,instanceClientParams:t}){try{return{success:!0,data:await Je({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var da={...la,icon:lt,execute:ua},fa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),pageIndex:l().default(0),pageSize:l().default(10),primaryKey:o(),conditions:s(i({search_attribute:o(),search_type:m([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:h()})),sort:i({attribute:o(),descending:d()})})};async function pa({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await Re({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await ze({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ma={...fa,icon:Me,execute:pa},ha={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:i({})};async function ga({instanceClientParams:e,baseURL:t}){let n=C.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Ue({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var _a={...ha,icon:de,execute:ga,requiresApproval:!0},va={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:o().trim(),payload:o(),encoding:m([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function ya({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await Ce({...r,file:o,project:a,payload:n,encoding:t});return await Te.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Le(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ba={...va,icon:ct,execute:ya,requiresApproval:!0},xa={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:i({database:o().trim(),table:o().trim(),records:s(h())})};async function Sa({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ze({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ca={readHarperSkill:ca,createApp:Ei,readLogs:da,getAnalytics:Fi,listAnalyticsMetrics:ra,restartHTTPService:_a,collectFeedback:Ci,getUserContext:Xi,getComponentFile:Ri,getComponents:Vi,setComponentFile:ba,dropComponentFile:Mi,getDescribeAll:Wi,getDescribeTable:qi,insertTableRecords:$i,readTableRecords:ma,updateTableRecords:{...xa,icon:it,execute:Sa,requiresApproval:!0},deleteTableRecords:ki};function wa(e){return Ca[e]}function Ta(e){return e.state===`input-available`&&!!wa(Zr(e))?.requiresApproval}function Ea(e){let t=[];for(let[n,r]of(e??[]).entries()){if(G(r)){if(Ta(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}qr(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Da({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Zr(e),u=wa(l),d=u?.icon||Ne,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
|
|
1947
1947
|
`).length:0}},[e.input]),h=(0,T.useMemo)(()=>{let t=JSON.stringify(e.output,null,` `);return{json:t,lines:t?t.split(`
|
|
1948
|
-
`).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(fe,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(S,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(
|
|
1949
|
-
//# sourceMappingURL=Chat-
|
|
1948
|
+
`).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(fe,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(S,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(Be,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(fe,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function Oa({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Zr(e[0]):void 0,u=l&&wa(l)?.icon||ft,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(ue,{size:14}):(0,E.jsx)(He,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(Be,{size:14,className:`animate-spin`}):c?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Da,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function ka({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>qr(e)&&e.text.length>0||G(e))?(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Ae,{size:18}):(0,E.jsx)(se,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Ea(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(Oa,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return qr(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):G(a)?(0,E.jsx)(Da,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function Aa(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?qr(n)?n.state!==`streaming`||n.text.length===0:!G(n)||n.state===`output-available`||n.state===`output-error`:!0}function ja(){return(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(se,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Ma(e){return ie({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await x.get(`/Chat/Usage/${e}`);return t}})}function Na(){let{organizationId:e}=te({strict:!1});return re(Ma(e))}function Pa(){let{data:e,isLoading:t,error:n}=Na();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Fa({autoFocus:e,closeChat:t}){let n=te({strict:!1}),{organizationId:r}=n,[i,a]=Ke(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=Ee(De.ChatAlwaysApprovedTools,[]),m=new Set(f),h=nt(),g=qe(),_=ne(),{messages:v,sendMessage:ee,status:y,addToolOutput:b,setMessages:x}=vi({transport:si(r),generateId:A(),sendAutomaticallyWhen:oi,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=wa(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});b({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),S=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=wa(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});b({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,b,n]),re=(0,T.useCallback)(e=>{let t=c[e];t&&(b({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,b]),ie=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>je([...e,t.toolName])),await S(e))},[c,p,S]);(0,T.useEffect)(()=>{(async()=>{try{let e=await ht();Array.isArray(e)&&x(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[x]);let ae=y===`streaming`||y===`submitted`,oe=(0,T.useRef)(null);return(0,T.useEffect)(()=>{oe.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(se,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Pa,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(mt,{setMessages:x}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(pe,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(bi,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(se,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(ka,{message:e,onApprove:S,onDeny:re,onAlwaysApprove:ie,approvingToolCallIds:u},e.id)),Aa(y,v.at(-1))&&(0,E.jsx)(ja,{}),(0,E.jsx)(`div`,{ref:oe})]}),(0,E.jsx)(yi,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!ae&&!o&&(ee({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Fa as Chat};
|
|
1949
|
+
//# sourceMappingURL=Chat-WK3X972M.js.map
|