@marimo-team/frontend 0.24.3-dev3 → 0.24.3-dev4
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/assets/{CellStatus-LoTwk7fR.js → CellStatus-0QNZS4By.js} +1 -1
- package/dist/assets/{JsonOutput-CzIGPEZQ.js → JsonOutput-D2ZWLZs4.js} +7 -7
- package/dist/assets/{MarimoErrorOutput-DqpoYOvw.js → MarimoErrorOutput-BlmIJ9WY.js} +2 -2
- package/dist/assets/{RenderHTML-DwhMAd9l.js → RenderHTML-DnPB4qpJ.js} +1 -1
- package/dist/assets/{RunButton-BlpbweyH.js → RunButton-C7TxE07w.js} +1 -1
- package/dist/assets/{add-cell-with-ai-R-3DS79K.js → add-cell-with-ai-OQ4sSXg4.js} +12 -12
- package/dist/assets/{add-connection-dialog-BGfpw5lC.js → add-connection-dialog-MTOC2ycO.js} +73 -73
- package/dist/assets/{agent-panel-Cgt_K0tD.js → agent-panel-BdEDIHdc.js} +4 -4
- package/dist/assets/ai-model-dropdown-CmJEEhSC.js +3 -0
- package/dist/assets/app-config-button-W8Pytgb5.js +1 -0
- package/dist/assets/{blob-B2d_dHwI.js → blob-BrVH7IJp.js} +1 -1
- package/dist/assets/{cell-editor-Dw09J9yD.js → cell-editor-C7IiingQ.js} +8 -8
- package/dist/assets/{cell-link-6burT2XF.js → cell-link-CbHXmrt8.js} +1 -1
- package/dist/assets/{cells-Cp-G34Rz.js → cells-BBhW3FXj.js} +1 -1
- package/dist/assets/{chat-display-Bu405iyc.js → chat-display-CIpYPLlF.js} +1 -1
- package/dist/assets/{chat-panel-BlUwNY5j.js → chat-panel-CK3X_KPy.js} +2 -2
- package/dist/assets/{chat-ui-DGiVDzNh.js → chat-ui-BJwtx1SR.js} +4 -4
- package/dist/assets/{column-preview-riSXbYe_.js → column-preview-Coa5PyHk.js} +1 -1
- package/dist/assets/{command-palette-CCVzJcyf.js → command-palette-_xpwMniA.js} +1 -1
- package/dist/assets/{common-CHR7w7aQ.js → common-KqtqJsml.js} +1 -1
- package/dist/assets/{components-C7mWrmXr.js → components-Cpv2z-yV.js} +1 -1
- package/dist/assets/{datasource-DrODSIs0.js → datasource-B3qF2oaW.js} +2 -2
- package/dist/assets/{dependency-graph-panel-AY5BEVH2.js → dependency-graph-panel-Av1CMZ61.js} +3 -3
- package/dist/assets/{documentation-panel-CaJF7e-j.js → documentation-panel-BEz3Hjfu.js} +1 -1
- package/dist/assets/{download-DMxOzI7b.js → download-BgO9EN-W.js} +1 -1
- package/dist/assets/edit-page-DslcxB67.js +9 -0
- package/dist/assets/error-entries-BFzSRy80.js +5 -0
- package/dist/assets/{error-panel-Bhlvt6_H.js → error-panel-BtLTJDUq.js} +1 -1
- package/dist/assets/{file-explorer-panel-s0ohSG_L.js → file-explorer-panel-DEyChgqS.js} +1 -1
- package/dist/assets/{file-icons-DdGYuADJ.js → file-icons-BhotQqrU.js} +1 -1
- package/dist/assets/{file-name-input-K4MKESI_.js → file-name-input-CH-hNP6F.js} +1 -1
- package/dist/assets/{floating-outline-DaUHnl_e.js → floating-outline-Cmk3XDJi.js} +1 -1
- package/dist/assets/{home-page-BLd6rnbk.js → home-page-CUBuu5Go.js} +1 -1
- package/dist/assets/index-C5h1aWhw.js +29 -0
- package/dist/assets/{layout-DWnrxIo2.js → layout-CsLuqwD3.js} +5 -5
- package/dist/assets/{logs-panel-BGS2v3ba.js → logs-panel-BV4VZ_uH.js} +1 -1
- package/dist/assets/{markdown-renderer-BZKlbm2Q.js → markdown-renderer-751VNlrQ.js} +1 -1
- package/dist/assets/{name-cell-input-BMCdK-el.js → name-cell-input-DexJ7ZIH.js} +1 -1
- package/dist/assets/{outline-panel-Dr5u73V6.js → outline-panel-QU3nj1VW.js} +1 -1
- package/dist/assets/packages-panel-D7oDuI6v.js +1 -0
- package/dist/assets/panel-accordion-state-Dl0VcB79.js +1 -0
- package/dist/assets/panels-nM4QKfEI.js +4 -0
- package/dist/assets/process-output-CPUOlFhp.js +1 -0
- package/dist/assets/readonly-code-display-DP7DxRA1.js +1 -0
- package/dist/assets/{readonly-python-code-DpIyjHqY.js → readonly-python-code-CAYyabaV.js} +1 -1
- package/dist/assets/{reveal-component-nZIAapoD.js → reveal-component-D9DygPds.js} +2 -2
- package/dist/assets/rotate-cw-CESctpLh.js +1 -0
- package/dist/assets/{run-page-9pl8qhQR.js → run-page-CzO-uMUn.js} +1 -1
- package/dist/assets/{scratchpad-panel-BleGt2KM.js → scratchpad-panel-7YBL6E95.js} +1 -1
- package/dist/assets/session-panel-hnFaUP0Y.js +1 -0
- package/dist/assets/share-BZW3tzEX.js +1 -0
- package/dist/assets/{skeleton-BKeh8hf3.js → skeleton-CM7HxSva.js} +1 -1
- package/dist/assets/{snippets-panel-D5yy7kj0.js → snippets-panel-AdjuR23O.js} +1 -1
- package/dist/assets/state-DOrY1Jyf.js +1 -0
- package/dist/assets/state-DQHafeTV.js +3 -0
- package/dist/assets/{tracing-DNk3gmWv.js → tracing-CUlvXr_H.js} +1 -1
- package/dist/assets/{tracing-panel-Yqazr6w_.js → tracing-panel-CjyayE-l.js} +2 -2
- package/dist/assets/{tree-actions-CG5g7aUQ.js → tree-actions-mfuAcK1x.js} +1 -1
- package/dist/assets/{useAddCell-DdB_uBif.js → useAddCell-BR8kYnb6.js} +1 -1
- package/dist/assets/{useCellActionButton-B31neI3m.js → useCellActionButton-BhREXvvn.js} +1 -1
- package/dist/assets/{useDeleteCell-Bz49_cFj.js → useDeleteCell-DwaN6KAw.js} +1 -1
- package/dist/assets/useDependencyPanelTab-I-7B78cW.js +1 -0
- package/dist/assets/useInstallPackage-IUt497GC.js +1 -0
- package/dist/assets/useNotebookActions-D5_YLR42.js +10 -0
- package/dist/assets/useRunCells-BMQuitYY.js +1 -0
- package/dist/assets/{useSplitCell-Dy2_DmJR.js → useSplitCell-B7AvHoya.js} +1 -1
- package/dist/index.html +22 -22
- package/package.json +1 -1
- package/src/__mocks__/requests.ts +7 -2
- package/src/components/editor/chrome/panels/__tests__/packages-panel.test.tsx +143 -0
- package/src/components/editor/chrome/panels/packages-panel.tsx +145 -51
- package/src/components/editor/package-alert.tsx +25 -1
- package/src/core/packages/__tests__/useInstallPackage.test.tsx +47 -1
- package/src/core/packages/toast-components.tsx +26 -0
- package/src/core/packages/useInstallPackage.ts +7 -2
- package/src/core/wasm/bridge.ts +1 -0
- package/dist/assets/ai-model-dropdown-DCmiuk7x.js +0 -3
- package/dist/assets/app-config-button-DUJC6b6x.js +0 -1
- package/dist/assets/edit-page-xlMlcLnI.js +0 -9
- package/dist/assets/error-entries-Cv2m1yhc.js +0 -5
- package/dist/assets/index-4n22QjCD.js +0 -29
- package/dist/assets/packages-panel-BdpRg9tX.js +0 -1
- package/dist/assets/panel-accordion-state-DjUTN7i5.js +0 -1
- package/dist/assets/panels-CWn0Yh1D.js +0 -4
- package/dist/assets/process-output-Ck7-P_xp.js +0 -1
- package/dist/assets/readonly-code-display--S2daDa6.js +0 -1
- package/dist/assets/session-panel-DRGPlL5J.js +0 -1
- package/dist/assets/share-CPtBiNgr.js +0 -1
- package/dist/assets/state-B6AklCzD.js +0 -1
- package/dist/assets/state-Di9TbuV9.js +0 -3
- package/dist/assets/useDependencyPanelTab-C_ps0r--.js +0 -1
- package/dist/assets/useInstallPackage-DsD08SLK.js +0 -1
- package/dist/assets/useNotebookActions-CQtbk9CB.js +0 -10
- package/dist/assets/useRunCells-CX7oW5zy.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,t}from"./rolldown-runtime-B0Z9INg1.js";import{a as n,c as r,d as i,f as a,l as o,r as s,t as c}from"./useEvent-xfs0Sn4r.js";import{t as l}from"./react-CBDbhulC.js";import{
|
|
1
|
+
import{a as e,t}from"./rolldown-runtime-B0Z9INg1.js";import{a as n,c as r,d as i,f as a,l as o,r as s,t as c}from"./useEvent-xfs0Sn4r.js";import{t as l}from"./react-CBDbhulC.js";import{$i as u,D as d,Ka as f,Mi as p,No as m,Po as h,Qa as g,So as _,To as v,Ui as y,Un as b,ai as x,b as S,ci as ee,dr as te,f as ne,fa as re,fo as ie,ga as ae,go as oe,ha as se,ir as ce,it as le,qt as ue,ta as de,wo as fe,yt as pe}from"./cells-BBhW3FXj.js";import{Cn as C,Cr as me,In as w,It as he,Jn as T,Sn as ge,Tt as E,Yn as D,bt as _e,cn as ve,jn as O,kt as k,lc as ye,ln as A,mr as be,un as j,vn as M,vt as xe,xt as Se,zt as Ce}from"./schemas-aTUejmFi.js";import{t as we}from"./compiler-runtime-CYIjoINj.js";import{n as Te}from"./utils-D5Ywm7-q.js";import{k as Ee,t as De}from"./ai-model-dropdown-CmJEEhSC.js";import{f as Oe,g as N}from"./useEventListener-92uWqz-P.js";import{o as ke}from"./config-BlNM0caL.js";import{t as Ae}from"./cn-ldLVeaqm.js";import{t as je}from"./jsx-runtime-B74pBk57.js";import{a as Me,c as Ne,p as Pe,r as Fe,t as Ie}from"./dropdown-menu-C40jM9o4.js";import{t as Le}from"./tooltip-BUtPzKB4.js";import{t as Re}from"./button-Dh8EwhsF.js";import{Gt as ze,Qt as Be,Tt as Ve,Wt as He,Zt as Ue,at as We,dt as Ge,en as Ke,qt as qe,st as Je,ut as Ye,wt as Xe}from"./dist-BtC9ym6k.js";import{t as Ze}from"./createReducer-B_XmHROl.js";import{h as Qe,n as $e,o as et,r as tt}from"./dist-DiYjQAhI.js";import{t as nt}from"./requests-C6_IaFh7.js";import{t as rt}from"./createLucideIcon-B7HeEoG2.js";import{r as it,t as at}from"./fileToBase64-NhpNrK5l.js";import{r as ot}from"./useNumberFormatter-DHJ9s6Vk.js";import{f as st,n as ct}from"./markdown-renderer-751VNlrQ.js";import{t as lt}from"./file-DF8n85RA.js";import{t as ut}from"./image-ab13yGv4.js";import{t as dt}from"./spinner-Ck-Hgfvj.js";import{i as ft,t as pt}from"./useDeleteCell-DwaN6KAw.js";import{r as mt}from"./input-DEbY281O.js";import{a as ht,c as gt,i as _t,n as vt,o as yt,s as bt,t as xt}from"./datasource-B3qF2oaW.js";import{a as St}from"./dist-Cx4BE7jC.js";import{t as Ct}from"./uuid-k9DpjH68.js";import{t as wt}from"./use-toast-DpWHUGuF.js";import{a as Tt}from"./session-Sz5nSFku.js";import{r as Et}from"./useTheme-C-ri8BtY.js";import{n as Dt}from"./useRunCells-BMQuitYY.js";import{n as Ot}from"./blob-BrVH7IJp.js";import{a as kt}from"./errors-DzO-nXy-.js";import{r as At,t as jt}from"./esm-BHMOvJzM.js";import{i as Mt}from"./cell-link-CbHXmrt8.js";import{t as Nt}from"./html-to-image-D6GUC5q6.js";import{n as Pt}from"./renderShortcut-X-CJUSM8.js";import{n as Ft}from"./icons-CjLa9BiH.js";import{t as It}from"./process-output-CPUOlFhp.js";import{i as Lt,r as Rt,t as zt}from"./error-entries-BFzSRy80.js";var Bt=rt(`circle-stop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),Vt=rt(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Ht=rt(`send-horizontal`,[[`path`,{d:`M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z`,key:`117uat`}],[`path`,{d:`M6 12h16`,key:`s4cdu5`}]]),P=we(),Ut=`vercel.ai.error`,Wt=Symbol.for(Ut),Gt,Kt,qt=class e extends (Kt=Error,Gt=Wt,Kt){constructor({name:e,message:t,cause:n}){super(t),this[Gt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ut)}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 Jt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var Yt=`AI_InvalidArgumentError`,Xt=`vercel.ai.error.${Yt}`,Zt=Symbol.for(Xt),Qt,$t,en=class extends ($t=qt,Qt=Zt,$t){constructor({message:e,cause:t,argument:n}){super({name:Yt,message:e,cause:t}),this[Qt]=!0,this.argument=n}static isInstance(e){return qt.hasMarker(e,Xt)}},tn=`AI_JSONParseError`,nn=`vercel.ai.error.${tn}`,rn=Symbol.for(nn),an,on,sn=class extends (on=qt,an=rn,on){constructor({text:e,cause:t}){super({name:tn,message:`JSON parsing failed: Text: ${e}.
|
|
2
2
|
Error message: ${Jt(t)}`,cause:t}),this[an]=!0,this.text=e}static isInstance(e){return qt.hasMarker(e,nn)}},cn=`AI_TypeValidationError`,ln=`vercel.ai.error.${cn}`,un=Symbol.for(ln),dn,fn,pn=class e extends (fn=qt,dn=un,fn){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:cn,message:`${r}: Value: ${JSON.stringify(e)}.
|
|
3
3
|
Error message: ${Jt(t)}`,cause:t}),this[dn]=!0,this.value=e,this.context=n}static isInstance(e){return qt.hasMarker(e,ln)}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})}},F;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(F||={});var mn;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(mn||={});var I=F.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),hn=e=>{switch(typeof e){case`undefined`:return I.undefined;case`string`:return I.string;case`number`:return Number.isNaN(e)?I.nan:I.number;case`boolean`:return I.boolean;case`function`:return I.function;case`bigint`:return I.bigint;case`symbol`:return I.symbol;case`object`:return Array.isArray(e)?I.array:e===null?I.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?I.promise:typeof Map<`u`&&e instanceof Map?I.map:typeof Set<`u`&&e instanceof Set?I.set:typeof Date<`u`&&e instanceof Date?I.date:I.object;default:return I.unknown}},L=F.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),gn=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};gn.create=e=>new gn(e);var _n=(e,t)=>{let n;switch(e.code){case L.invalid_type:n=e.received===I.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case L.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,F.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(e.keys,`, `)}`;break;case L.invalid_union:n=`Invalid input`;break;case L.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(e.options)}`;break;case L.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(e.options)}, received '${e.received}'`;break;case L.invalid_arguments:n=`Invalid function arguments`;break;case L.invalid_return_type:n=`Invalid function return type`;break;case L.invalid_date:n=`Invalid date`;break;case L.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:F.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case L.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case L.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case L.custom:n=`Invalid input`;break;case L.invalid_intersection_types:n=`Intersection results could not be merged`;break;case L.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case L.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,F.assertNever(e)}return{message:n}},vn=_n;function yn(){return vn}var bn=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function R(e,t){let n=yn(),r=bn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===_n?void 0:_n].filter(e=>!!e)});e.common.issues.push(r)}var z=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return B;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return B;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:`aborted`}),xn=e=>({status:`dirty`,value:e}),V=e=>({status:`valid`,value:e}),Sn=e=>e.status===`aborted`,Cn=e=>e.status===`dirty`,wn=e=>e.status===`valid`,Tn=e=>typeof Promise<`u`&&e instanceof Promise,H;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(H||={});var En=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dn=(e,t)=>{if(wn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new gn(e.common.issues);return this._error=t,this._error}}};function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var W=class{get description(){return this._def.description}_getType(e){return hn(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new z,ctx:{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Tn(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)};return Dn(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return wn(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>wn(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)},r=this._parse({data:e,path:n.path,parent:n});return Dn(n,await(Tn(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:L.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Ar({schema:this,typeName:G.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return jr.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dr.create(this)}promise(){return kr.create(this,this._def)}or(e){return mr.create([this,e],this._def)}and(e){return vr.create(this,e,this._def)}transform(e){return new Ar({...U(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new Ir({typeName:G.ZodBranded,type:this,...U(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Pr({...U(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Lr.create(this,e)}readonly(){return Rr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},On=/^c[^\s-]{8,}$/i,kn=/^[0-9a-z]+$/,An=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Mn=/^[a-z0-9_-]{21}$/i,Nn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Pn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Fn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,In=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Ln,Rn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Bn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Vn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Hn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Un=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Wn=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Gn=RegExp(`^${Wn}$`);function Kn(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function qn(e){return RegExp(`^${Kn(e)}$`)}function Jn(e){let t=`${Wn}T${Kn(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Yn(e,t){return!!((t===`v4`||!t)&&Rn.test(e)||(t===`v6`||!t)&&Bn.test(e))}function Xn(e,t){if(!Nn.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Zn(e,t){return!!((t===`v4`||!t)&&zn.test(e)||(t===`v6`||!t)&&Vn.test(e))}var Qn=class e extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.string,received:t.parsedType}),B}let t=new z,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),R(n,{code:L.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),R(n,{code:L.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?R(n,{code:L.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&R(n,{code:L.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Fn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`email`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Ln||=new RegExp(In,`u`),Ln.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`emoji`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)jn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`uuid`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Mn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`nanoid`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)On.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`cuid`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)kn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`cuid2`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)An.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`ulid`,code:L.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),R(n,{validation:`url`,code:L.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`regex`,code:L.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Jn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Gn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?qn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:L.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Pn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`duration`,code:L.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Yn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`ip`,code:L.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Xn(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`jwt`,code:L.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Zn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`cidr`,code:L.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Hn.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`base64`,code:L.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Un.test(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{validation:`base64url`,code:L.invalid_string,message:r.message}),t.dirty()):F.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:L.invalid_string,...H.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...H.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...H.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...H.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...H.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...H.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...H.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...H.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...H.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...H.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...H.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...H.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Qn.create=e=>new Qn({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...U(e)});function $n(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var er=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==I.number){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.number,received:t.parsedType}),B}let t,n=new z;for(let r of this._def.checks)r.kind===`int`?F.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),R(t,{code:L.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?$n(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),R(t,{code:L.not_finite,message:r.message}),n.dirty()):F.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:H.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:H.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:H.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:H.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&F.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};er.create=e=>new er({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...U(e)});var tr=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==I.bigint)return this._getInvalidInput(e);let t,n=new z;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),R(t,{code:L.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):F.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.bigint,received:t.parsedType}),B}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};tr.create=e=>new tr({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var nr=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.boolean,received:t.parsedType}),B}return V(e.data)}};nr.create=e=>new nr({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var rr=class e extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.date,received:t.parsedType}),B}if(Number.isNaN(e.data.getTime()))return R(this._getOrReturnCtx(e),{code:L.invalid_date}),B;let t=new z,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),R(n,{code:L.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),R(n,{code:L.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):F.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:H.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:H.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};rr.create=e=>new rr({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...U(e)});var ir=class extends W{_parse(e){if(this._getType(e)!==I.symbol){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.symbol,received:t.parsedType}),B}return V(e.data)}};ir.create=e=>new ir({typeName:G.ZodSymbol,...U(e)});var ar=class extends W{_parse(e){if(this._getType(e)!==I.undefined){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.undefined,received:t.parsedType}),B}return V(e.data)}};ar.create=e=>new ar({typeName:G.ZodUndefined,...U(e)});var or=class extends W{_parse(e){if(this._getType(e)!==I.null){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.null,received:t.parsedType}),B}return V(e.data)}};or.create=e=>new or({typeName:G.ZodNull,...U(e)});var sr=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return V(e.data)}};sr.create=e=>new sr({typeName:G.ZodAny,...U(e)});var cr=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return V(e.data)}};cr.create=e=>new cr({typeName:G.ZodUnknown,...U(e)});var lr=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.never,received:t.parsedType}),B}};lr.create=e=>new lr({typeName:G.ZodNever,...U(e)});var ur=class extends W{_parse(e){if(this._getType(e)!==I.undefined){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.void,received:t.parsedType}),B}return V(e.data)}};ur.create=e=>new ur({typeName:G.ZodVoid,...U(e)});var dr=class e extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==I.array)return R(t,{code:L.invalid_type,expected:I.array,received:t.parsedType}),B;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(R(t,{code:e?L.too_big:L.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(R(t,{code:L.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(R(t,{code:L.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new En(t,e,t.path,n)))).then(e=>z.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new En(t,e,t.path,n)));return z.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:H.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};dr.create=(e,t)=>new dr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...U(t)});function fr(e){if(e instanceof pr){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=jr.create(fr(r))}return new pr({...e._def,shape:()=>t})}return e instanceof dr?new dr({...e._def,type:fr(e.element)}):e instanceof jr?jr.create(fr(e.unwrap())):e instanceof Mr?Mr.create(fr(e.unwrap())):e instanceof yr?yr.create(e.items.map(e=>fr(e))):e}var pr=class e extends W{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=F.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==I.object){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.object,received:t.parsedType}),B}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof lr&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new En(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof lr){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(R(n,{code:L.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new En(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>z.mergeObjectSync(t,e)):z.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return H.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:H.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of F.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of F.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return fr(this)}partial(t){let n={};for(let e of F.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of F.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof jr;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Er(F.objectKeys(this.shape))}};pr.create=(e,t)=>new pr({shape:()=>e,unknownKeys:`strip`,catchall:lr.create(),typeName:G.ZodObject,...U(t)}),pr.strictCreate=(e,t)=>new pr({shape:()=>e,unknownKeys:`strict`,catchall:lr.create(),typeName:G.ZodObject,...U(t)}),pr.lazycreate=(e,t)=>new pr({shape:e,unknownKeys:`strip`,catchall:lr.create(),typeName:G.ZodObject,...U(t)});var mr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new gn(e.ctx.common.issues));return R(t,{code:L.invalid_union,unionErrors:n}),B}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new gn(e));return R(t,{code:L.invalid_union,unionErrors:i}),B}}get options(){return this._def.options}};mr.create=(e,t)=>new mr({options:e,typeName:G.ZodUnion,...U(t)});var hr=e=>e instanceof wr?hr(e.schema):e instanceof Ar?hr(e.innerType()):e instanceof Tr?[e.value]:e instanceof Dr?e.options:e instanceof Or?F.objectValues(e.enum):e instanceof Nr?hr(e._def.innerType):e instanceof ar?[void 0]:e instanceof or?[null]:e instanceof jr?[void 0,...hr(e.unwrap())]:e instanceof Mr?[null,...hr(e.unwrap())]:e instanceof Ir||e instanceof Rr?hr(e.unwrap()):e instanceof Pr?hr(e._def.innerType):[],gr=class e extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.object)return R(t,{code:L.invalid_type,expected:I.object,received:t.parsedType}),B;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(R(t,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=hr(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function _r(e,t){let n=hn(e),r=hn(t);if(e===t)return{valid:!0,data:e};if(n===I.object&&r===I.object){let n=F.objectKeys(t),r=F.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=_r(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===I.array&&r===I.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=_r(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===I.date&&r===I.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var vr=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Sn(e)||Sn(r))return B;let i=_r(e.value,r.value);return i.valid?((Cn(e)||Cn(r))&&t.dirty(),{status:t.value,value:i.data}):(R(n,{code:L.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};vr.create=(e,t,n)=>new vr({left:e,right:t,typeName:G.ZodIntersection,...U(n)});var yr=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.array)return R(n,{code:L.invalid_type,expected:I.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return R(n,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),B;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new En(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>z.mergeArray(t,e)):z.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};yr.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new yr({items:e,typeName:G.ZodTuple,rest:null,...U(t)})};var br=class e extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return R(n,{code:L.invalid_type,expected:I.object,received:n.parsedType}),B;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new En(n,e,n.path,e)),value:a._parse(new En(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?z.mergeObjectAsync(t,r):z.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof W?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...U(r)}):new e({keyType:Qn.create(),valueType:t,typeName:G.ZodRecord,...U(n)})}},xr=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.map)return R(n,{code:L.invalid_type,expected:I.map,received:n.parsedType}),B;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new En(n,e,n.path,[a,`key`])),value:i._parse(new En(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return B;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return B;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};xr.create=(e,t,n)=>new xr({valueType:t,keyType:e,typeName:G.ZodMap,...U(n)});var Sr=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.set)return R(n,{code:L.invalid_type,expected:I.set,received:n.parsedType}),B;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(R(n,{code:L.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(R(n,{code:L.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return B;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new En(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:H.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Sr.create=(e,t)=>new Sr({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...U(t)});var Cr=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.function)return R(t,{code:L.invalid_type,expected:I.function,received:t.parsedType}),B;function n(e,n){return bn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yn(),_n].filter(e=>!!e),issueData:{code:L.invalid_arguments,argumentsError:n}})}function r(e,n){return bn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yn(),_n].filter(e=>!!e),issueData:{code:L.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof kr){let e=this;return V(async function(...t){let o=new gn([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return V(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new gn([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new gn([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:yr.create(t).rest(cr.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||yr.create([]).rest(cr.create()),returns:n||cr.create(),typeName:G.ZodFunction,...U(r)})}},wr=class extends W{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};wr.create=(e,t)=>new wr({getter:e,typeName:G.ZodLazy,...U(t)});var Tr=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return R(t,{received:t.data,code:L.invalid_literal,expected:this._def.value}),B}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Tr.create=(e,t)=>new Tr({value:e,typeName:G.ZodLiteral,...U(t)});function Er(e,t){return new Dr({values:e,typeName:G.ZodEnum,...U(t)})}var Dr=class e extends W{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{expected:F.joinValues(n),received:t.parsedType,code:L.invalid_type}),B}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{received:t.data,code:L.invalid_enum_value,options:n}),B}return V(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Dr.create=Er;var Or=class extends W{_parse(e){let t=F.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.string&&n.parsedType!==I.number){let e=F.objectValues(t);return R(n,{expected:F.joinValues(e),received:n.parsedType,code:L.invalid_type}),B}if(this._cache||=new Set(F.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=F.objectValues(t);return R(n,{received:n.data,code:L.invalid_enum_value,options:e}),B}return V(e.data)}get enum(){return this._def.values}};Or.create=(e,t)=>new Or({values:e,typeName:G.ZodNativeEnum,...U(t)});var kr=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==I.promise&&t.common.async===!1?(R(t,{code:L.invalid_type,expected:I.promise,received:t.parsedType}),B):V((t.parsedType===I.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kr.create=(e,t)=>new kr({type:e,typeName:G.ZodPromise,...U(t)});var Ar=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{R(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return B;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?B:r.status===`dirty`||t.value===`dirty`?xn(r.value):r});{if(t.value===`aborted`)return B;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?B:r.status===`dirty`||t.value===`dirty`?xn(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?B:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?B:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!wn(e))return B;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>wn(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):B)}F.assertNever(r)}};Ar.create=(e,t,n)=>new Ar({schema:e,typeName:G.ZodEffects,effect:t,...U(n)}),Ar.createWithPreprocess=(e,t,n)=>new Ar({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...U(n)});var jr=class extends W{_parse(e){return this._getType(e)===I.undefined?V(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jr.create=(e,t)=>new jr({innerType:e,typeName:G.ZodOptional,...U(t)});var Mr=class extends W{_parse(e){return this._getType(e)===I.null?V(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(e,t)=>new Mr({innerType:e,typeName:G.ZodNullable,...U(t)});var Nr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===I.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Nr.create=(e,t)=>new Nr({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...U(t)});var Pr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Tn(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new gn(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new gn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Pr.create=(e,t)=>new Pr({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...U(t)});var Fr=class extends W{_parse(e){if(this._getType(e)!==I.nan){let t=this._getOrReturnCtx(e);return R(t,{code:L.invalid_type,expected:I.nan,received:t.parsedType}),B}return{status:`valid`,value:e.data}}};Fr.create=e=>new Fr({typeName:G.ZodNaN,...U(e)});var Ir=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Lr=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?B:e.status===`dirty`?(t.dirty(),xn(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?B:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:G.ZodPipeline})}},Rr=class extends W{_parse(e){let t=this._def.innerType._parse(e),n=e=>(wn(e)&&(e.value=Object.freeze(e.value)),e);return Tn(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Rr.create=(e,t)=>new Rr({innerType:e,typeName:G.ZodReadonly,...U(t)}),pr.lazycreate;var G;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(G||={}),Qn.create,er.create,Fr.create,tr.create,nr.create,rr.create,ir.create,ar.create,or.create,sr.create,cr.create,lr.create,ur.create,dr.create,pr.create,pr.strictCreate,mr.create,gr.create,vr.create,yr.create,br.create,xr.create,Sr.create,Cr.create,wr.create,Tr.create,Dr.create,Or.create,kr.create,Ar.create,jr.create,Mr.create,Ar.createWithPreprocess,Lr.create;var zr=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}},Br=10,Vr=13,Hr=32;function Ur(e){}function Wr(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=Ur,onError:n=Ur,onRetry:r=Ur,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 zr(`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(`
|
|
@@ -17,7 +17,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
17
17
|
|
|
18
18
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
19
19
|
|
|
20
|
-
`)}})}},ho={"content-type":`text/event-stream`,"cache-control":`no-cache`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`};function go({status:e,statusText:t,headers:n,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new mo);if(i){let[e,t]=a.tee();a=e,i({stream:t})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:po(n,ho)})}var _o=O(w(),Ra.optional()),vo=aa(()=>ma(T([j({type:A(`text-start`),id:w(),providerMetadata:Y.optional()}),j({type:A(`text-delta`),id:w(),delta:w(),providerMetadata:Y.optional()}),j({type:A(`text-end`),id:w(),providerMetadata:Y.optional()}),j({type:A(`error`),errorText:w()}),j({type:A(`tool-input-start`),toolCallId:w(),toolName:w(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),title:w().optional()}),j({type:A(`tool-input-delta`),toolCallId:w(),inputTextDelta:w()}),j({type:A(`tool-input-available`),toolCallId:w(),toolName:w(),input:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),title:w().optional()}),j({type:A(`tool-input-error`),toolCallId:w(),toolName:w(),input:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),errorText:w(),title:w().optional()}),j({type:A(`tool-approval-request`),approvalId:w(),toolCallId:w(),isAutomatic:k().optional(),signature:w().optional()}),j({type:A(`tool-approval-response`),approvalId:w(),approved:k(),reason:w().optional(),providerExecuted:k().optional(),providerMetadata:Y.optional()}),j({type:A(`tool-output-available`),toolCallId:w(),output:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),preliminary:k().optional()}),j({type:A(`tool-output-error`),toolCallId:w(),errorText:w(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional()}),j({type:A(`tool-output-denied`),toolCallId:w()}),j({type:A(`reasoning-start`),id:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-delta`),id:w(),delta:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-end`),id:w(),providerMetadata:Y.optional()}),j({type:A(`custom`),kind:w().transform(e=>e),providerMetadata:Y.optional()}),j({type:A(`source-url`),sourceId:w(),url:w(),title:w().optional(),providerMetadata:Y.optional()}),j({type:A(`source-document`),sourceId:w(),mediaType:w(),title:w(),filename:w().optional(),providerMetadata:Y.optional()}),j({type:A(`file`),url:w(),mediaType:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-file`),url:w(),mediaType:w(),providerMetadata:Y.optional()}),j({type:he(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:w().optional(),data:D(),transient:k().optional()}),j({type:A(`start-step`)}),j({type:A(`finish-step`)}),j({type:A(`start`),messageId:w().optional(),messageMetadata:D().optional()}),j({type:A(`finish`),finishReason:xe([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:D().optional()}),j({type:A(`abort`),reason:w().optional()}),j({type:A(`message-metadata`),messageMetadata:D()})])));function yo(e){return e.type.startsWith(`data-`)}function bo(){return Object.create(null)}function xo(e){return e.type.startsWith(`tool-`)}function So(e){return e.type===`dynamic-tool`}function Co(e){return xo(e)||So(e)}function wo(e){return e.type.split(`-`).slice(1).join(`-`)}function To({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:bo(),activeReasoningParts:bo(),partialToolCalls:bo()}}function Eo({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(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(Co)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(Co(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new Ia({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(Co).find(t=>t.approval?.id===e);if(t==null)throw new Ia({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>xo(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}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:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:La(r.message.metadata,e);t!=null&&await ha({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 Ia({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 Ia({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 Ia({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 Ia({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=l().filter(xo);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({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 Ia({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 oo(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({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?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({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=l().filter(Co).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):p({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=d(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=f(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=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({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},t):p({toolCallId:e.toolCallId,toolName:wo(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},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({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},t):p({toolCallId:e.toolCallId,toolName:wo(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},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=bo(),r.activeReasoningParts=bo();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(yo(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 ha({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 Do({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()}}Xr({prefix:`aitxt`,size:24}),Xr({prefix:`call`,size:24}),Xr({prefix:`aitxt`,size:24}),Xr({prefix:`call`,size:24});var X=O(w(),Ra.optional()),Oo=O(w(),w()),ko=aa(()=>ma(E(C({id:w(),role:xe([`system`,`user`,`assistant`]),metadata:D().optional(),parts:E(T([C({type:A(`text`),text:w(),state:xe([`streaming`,`done`]).optional(),providerMetadata:Y.optional()}),C({type:A(`reasoning`),text:w(),state:xe([`streaming`,`done`]).optional(),providerMetadata:Y.optional()}),C({type:A(`custom`),kind:w(),providerMetadata:Y.optional()}),C({type:A(`source-url`),sourceId:w(),url:w(),title:w().optional(),providerMetadata:Y.optional()}),C({type:A(`source-document`),sourceId:w(),mediaType:w(),title:w(),filename:w().optional(),providerMetadata:Y.optional()}),C({type:A(`file`),mediaType:w(),filename:w().optional(),url:w(),providerReference:Oo.optional(),providerMetadata:Y.optional()}),C({type:A(`reasoning-file`),mediaType:w(),url:w(),providerMetadata:Y.optional()}),C({type:A(`step-start`)}),C({type:w().startsWith(`data-`),id:w().optional(),data:D()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-streaming`),input:D().optional(),providerExecuted:k().optional(),callProviderMetadata:Y.optional(),output:M().optional(),errorText:M().optional(),approval:M().optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-available`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:M().optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-requested`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:M().optional(),reason:M().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-responded`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:k(),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-available`),input:D(),providerExecuted:k().optional(),output:D(),errorText:M().optional(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),preliminary:k().optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-error`),input:D().optional(),rawInput:D().optional(),providerExecuted:k().optional(),output:M().optional(),errorText:w(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-denied`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!1),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-streaming`),providerExecuted:k().optional(),callProviderMetadata:Y.optional(),input:D().optional(),output:M().optional(),errorText:M().optional(),approval:M().optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-available`),providerExecuted:k().optional(),input:D(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:M().optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-requested`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:M().optional(),reason:M().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-responded`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:k(),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-available`),providerExecuted:k().optional(),input:D(),output:D(),errorText:M().optional(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),preliminary:k().optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-error`),providerExecuted:k().optional(),input:D().optional(),rawInput:D().optional(),output:M().optional(),errorText:w(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-denied`),providerExecuted:k().optional(),input:D(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!1),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})})]))}).superRefine((e,t)=>{e.role!==`assistant`&&e.parts.length===0&&t.addIssue({origin:`array`,code:`too_small`,minimum:1,inclusive:!0,input:e.parts,path:[`parts`],message:`Message must contain at least one part`})})).nonempty(`Messages array must not be empty`)));async function Ao({messages:e,metadataSchema:t,dataSchemas:n,tools:r}){try{if(e==null)return{success:!1,error:new Ea({parameter:`messages`,value:e,message:`messages parameter must be provided`})};let i=await ha({value:e,schema:ko});if(t)for(let[e,n]of i.entries())await ha({value:n.metadata,schema:t,context:{field:`messages[${e}].metadata`,entityId:n.id}});if(n||r)for(let[e,t]of i.entries())for(let[i,a]of t.parts.entries()){if(n&&a.type.startsWith(`data-`)){let t=a,r=t.type.slice(5),o=n[r];if(!o)return{success:!1,error:new pn({value:t.data,cause:`No data schema found for data part ${r}`,context:{field:`messages[${e}].parts[${i}].data`,entityName:r,entityId:t.id}})};await ha({value:t.data,schema:o,context:{field:`messages[${e}].parts[${i}].data`,entityName:r,entityId:t.id}})}if(r&&a.type.startsWith(`tool-`)){let t=a,n=t.type.slice(5),o=io(r,n);if(!o&&(t.state===`output-available`||t.state===`output-error`||t.state===`output-denied`))continue;if(!o)return{success:!1,error:new pn({value:t.input,cause:`No tool schema found for tool part ${n}`,context:{field:`messages[${e}].parts[${i}].input`,entityName:n,entityId:t.toolCallId}})};(t.state===`input-available`||t.state===`output-available`)&&await ha({value:t.input,schema:o.inputSchema,context:{field:`messages[${e}].parts[${i}].input`,entityName:n,entityId:t.toolCallId}}),t.state===`output-available`&&o.outputSchema&&await ha({value:t.output,schema:o.outputSchema,context:{field:`messages[${e}].parts[${i}].output`,entityName:n,entityId:t.toolCallId}})}}return{success:!0,data:i}}catch(e){return{success:!1,error:e}}}Xr({prefix:`call`,size:24}),Xr({prefix:`call`,size:24}),Xr({prefix:`aiobj`,size:24});var jo=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()})}};Xr({prefix:`aiobj`,size:24}),Xr({prefix:`call`,size:24});async function Mo(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 No=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 ya(this.body),r=await ya(this.headers),i=await ya(this.credentials),a={...Qr(r),...Qr(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:Qr(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 ya(this.body),n=await ya(this.headers),r=await ya(this.credentials),i={...Qr(n),...Qr(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:Qr(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)}},Po=class extends No{constructor(e={}){super(e)}processResponseStream(e){return va({stream:e,schema:vo}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Fo=class{constructor({generateId:e=Zr,id:t=e(),transport:n=new Po,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new jo,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 Mo(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=>Co(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=>Co(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,d;try{let a={state:To({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};d=a,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 Do({stream:Eo({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{d&&((a=this.onFinish)==null||a.call(this,{message:d.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:d.state.finishReason}))}catch(e){console.error(e)}this.activeResponse===d&&(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 Io({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(Co);return r.filter(e=>e.state===`approval-responded`).length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`||e.state===`approval-responded`)}function Lo({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(Co).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}var Ro=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})),Z=e(l(),1),zo=e(Ro(),1),Q=je(),Bo=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},$=(e,t,n)=>(Bo(e,t,`read from private field`),n?n.call(e):t.get(e)),Vo=(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)},Ho=(e,t,n,r)=>(Bo(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function Uo(e,t){return t==null?e:(0,zo.default)(e,t)}var Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo,$o=class{constructor(e=[]){Vo(this,Wo,void 0),Vo(this,Go,`ready`),Vo(this,Ko,void 0),Vo(this,qo,new Set),Vo(this,Jo,new Set),Vo(this,Yo,new Set),this.pushMessage=e=>{Ho(this,Wo,$(this,Wo).concat(e)),$(this,Xo).call(this)},this.popMessage=()=>{Ho(this,Wo,$(this,Wo).slice(0,-1)),$(this,Xo).call(this)},this.replaceMessage=(e,t)=>{Ho(this,Wo,[...$(this,Wo).slice(0,e),this.snapshot(t),...$(this,Wo).slice(e+1)]),$(this,Xo).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?Uo(e,t):e;return $(this,qo).add(n),()=>{$(this,qo).delete(n)}},this[`~registerStatusCallback`]=e=>($(this,Jo).add(e),()=>{$(this,Jo).delete(e)}),this[`~registerErrorCallback`]=e=>($(this,Yo).add(e),()=>{$(this,Yo).delete(e)}),Vo(this,Xo,()=>{$(this,qo).forEach(e=>e())}),Vo(this,Zo,()=>{$(this,Jo).forEach(e=>e())}),Vo(this,Qo,()=>{$(this,Yo).forEach(e=>e())}),Ho(this,Wo,e)}get status(){return $(this,Go)}set status(e){Ho(this,Go,e),$(this,Zo).call(this)}get error(){return $(this,Ko)}set error(e){Ho(this,Ko,e),$(this,Qo).call(this)}get messages(){return $(this,Wo)}set messages(e){Ho(this,Wo,[...e]),$(this,Xo).call(this)}};Wo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,qo=new WeakMap,Jo=new WeakMap,Yo=new WeakMap,Xo=new WeakMap,Zo=new WeakMap,Qo=new WeakMap;var es,ts=class extends Fo{constructor({messages:e,...t}){let n=new $o(e);super({...t,state:n}),Vo(this,es,void 0),this[`~registerMessagesCallback`]=(e,t)=>$(this,es)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>$(this,es)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>$(this,es)[`~registerErrorCallback`](e),Ho(this,es,n)}};es=new WeakMap;function ns({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,Z.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 Po),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,Z.useRef)(`chat`in r?r.chat:new ts(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 ts(c));let u=(0,Z.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),d=(0,Z.useSyncExternalStore)(u,()=>l.current.messages,()=>l.current.messages),f=(0,Z.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),p=(0,Z.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),m=(0,Z.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,Z.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:d,setMessages:m,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:p,resumeStream:l.current.resumeStream,status:f,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function rs(e){return ze.define({combine:t=>t[0]??e})}var is=rs({}),as=Ue.define(),os=Ue.define(),ss=50,cs=Be.define({create(){return{prompts:[],navigationIndex:-1,originalText:``}},update(e,t){let n={...e};t.docChanged&&e.navigationIndex!==-1&&(t.effects.some(e=>e.is(os)||e.is(as))||(n.navigationIndex=-1,n.originalText=``));for(let r of t.effects)if(r.is(as)){let i=r.value.trim();i&&(n.prompts=[i,...e.prompts.filter(e=>e!==i)].slice(0,ss),t.state.facet(is).save?.(n.prompts)),n.navigationIndex=-1,n.originalText=``}else r.is(os)&&(n.navigationIndex=r.value.index,n.originalText=r.value.originalText);return n}}),ls=e=>{let t=e.state.field(cs),n=e.state.doc;if(t.prompts.length===0)return!1;let r,i=t.originalText;if(t.navigationIndex===-1){if(n.length>0)return!1;r=0,i=n.toString()}else if(r=Math.min(t.navigationIndex+1,t.prompts.length-1),r===t.navigationIndex)return!1;let a=t.prompts[r];return e.dispatch({changes:{from:0,to:e.state.doc.length,insert:a},effects:os.of({index:r,originalText:i})}),!0},us=e=>{let t=e.state.field(cs);if(t.navigationIndex===-1)return!1;let n,r;return t.navigationIndex===0?(n=t.originalText,r=-1):(r=t.navigationIndex-1,n=t.prompts[r]??``),e.dispatch({changes:{from:0,to:e.state.doc.length,insert:n},effects:os.of({index:r,originalText:t.originalText})}),!0},ds=e=>{let t=e.state.doc.toString();return t.trim()?(e.dispatch({effects:as.of(t)}),!0):!1};function fs(e={}){let{storage:t,defaultKeymap:n=!0}=e,r=[cs.init(()=>({prompts:t?.load?.()??[],navigationIndex:-1,originalText:``})),is.of(t??{})];return n&&r.push(Ve.of([{key:`ArrowUp`,run:ls},{key:`ArrowDown`,run:us}])),r}var ps=class extends Error{code;isRetryable;suggestedFix;meta;constructor(e,t=`TOOL_ERROR`,n=!1,r,i){super(e),this.name=`ToolExecutionError`,this.code=t,this.isRetryable=n,this.suggestedFix=r,this.meta=i}toStructuredString(){let e=JSON.stringify({message:this.message,code:this.code,is_retryable:this.isRetryable,...this.suggestedFix&&{suggested_fix:this.suggestedFix},...this.meta&&{meta:this.meta}});return`Error invoking tool ${this.name}: ${e}`}},ms=C({status:xe([`success`,`error`,`warning`]).optional(),auth_required:k().optional(),next_steps:E(w()).optional(),action_url:w().optional(),message:w().optional(),meta:O(w(),D()).optional()}),hs=`cell-completion`,gs=`notebook-cells-completion`,_s=`data-${hs}`,vs=`data-${gs}`,ys=C({code:w()}),bs=C({language:xe([`python`,`sql`,`markdown`]),code:w().min(1)}),xs=C({cells:E(bs).min(1)});function Ss(e){return e.type.startsWith(`data-`)}var Cs=a(null),ws=a(e=>e(Cs)?.status===`in_progress`),{valueAtom:Ts,useActions:Es,createActions:Ds,reducer:Os}=Ze(()=>new Map,{addStagedCell:(e,t)=>{let{cellId:n,edit:r}=t;return new Map([...e,[n,r]])},removeStagedCell:(e,t)=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}});function ks(e){let t=(0,P.c)(2),n;return t[0]===e?n=t[1]:(n=fe(Ts,t=>t.get(e),Object.is),t[0]=e,t[1]=n),o(n)}function As(e){let t=(0,P.c)(15),{addStagedCell:n,removeStagedCell:r}=Es(),{createNewCell:i,updateCellCode:a}=d(),o=pt(),s;t[0]!==n||t[1]!==i?(s=e=>{let t=g.create();return n({cellId:t,edit:{type:`add_cell`}}),i({cellId:`__end__`,code:e,before:!1,newCellId:t}),t},t[0]=n,t[1]=i,t[2]=s):s=t[2];let c=s,l;t[3]!==e||t[4]!==a?(l=t=>{let{cellId:n,code:r}=t;if(!e.get(Ts).has(n)){N.error(`Staged cell not found`,{cellId:n});return}let i=ne(n);i?de(i,r):a({cellId:n,code:r,formattingChange:!1})},t[3]=e,t[4]=a,t[5]=l):l=t[5];let u=l,f;t[6]!==o||t[7]!==r?(f=e=>{r(e),o({cellId:e})},t[6]=o,t[7]=r,t[8]=f):f=t[8];let p=f,m;return t[9]!==n||t[10]!==c||t[11]!==p||t[12]!==r||t[13]!==u?(m={createStagedCell:c,updateStagedCell:u,addStagedCell:n,removeStagedCell:r,deleteStagedCell:p},t[9]=n,t[10]=c,t[11]=p,t[12]=r,t[13]=u,t[14]=m):m=t[14],m}function js(e){let t=(0,P.c)(30),n=As(e),{createNewCell:r}=d(),i=(0,Z.useRef)(null),a;t[0]===e?a=t[1]:(a={store:e},t[0]=e,t[1]=a),o(Cs,a);let s;t[2]===e?s=t[3]:(s={store:e},t[2]=e,t[3]=s),o(Ts,s);let c;t[4]!==n||t[5]!==e?(c=t=>{let r=e.get(Ts);for(let e of t.toReversed())r.has(e)&&n.deleteStagedCell(e)},t[4]=n,t[5]=e,t[6]=c):c=t[6];let l=c,u;t[7]!==r||t[8]!==l||t[9]!==n||t[10]!==e?(u=()=>{let t=e.get(Cs);t?.status===`in_progress`&&l(t.cellIds),i.current?.reconciler.discard(e.get(Ts));let a=Symbol(`staged-cell-generation`);i.current={id:a,status:`in_progress`,reconciler:new Ms({...n,createNewCell:r})},e.set(Cs,{id:a,status:`in_progress`,cellIds:[]})},t[7]=r,t[8]=l,t[9]=n,t[10]=e,t[11]=u):u=t[11];let f=u,p;t[12]===e?p=t[13]:(p=t=>{let n=i.current;if(n?.status!==`in_progress`)return;let r=e.get(Cs),a=r?.id===n.id&&r.status===`in_progress`;if(!a||!t){n.reconciler.discard(e.get(Ts)),a&&e.set(Cs,null),i.current=null;return}n.status=`complete`,e.set(Cs,{id:n.id,status:`complete`})},t[12]=e,t[13]=p);let m=p,h;t[14]===e?h=t[15]:(h=()=>{let t=i.current,n=e.get(Cs);return t!==null&&t.status===`complete`&&n?.status===`complete`&&n.id===t.id&&t.reconciler.hasStagedCells(e.get(Ts))},t[14]=e,t[15]=h);let g=h,_;t[16]!==g||t[17]!==e?(_=()=>g()?(i.current?.reconciler.accept(),e.set(Cs,null),i.current=null,!0):!1,t[16]=g,t[17]=e,t[18]=_):_=t[18];let v=_,y;t[19]===e?y=t[20]:(y=()=>{let t=i.current,n=e.get(Cs);return t===null||n?.id!==t.id?!1:(t.reconciler.discard(e.get(Ts)),e.set(Cs,null),i.current=null,!0)},t[19]=e,t[20]=y);let b=y,x;t[21]===e?x=t[22]:(x=t=>{if(t.type!==vs)return;let n=i.current,r=e.get(Cs);if(n?.status!==`in_progress`||r?.id!==n.id||r.status!==`in_progress`)return;let a=xs.parse(t.data);n.reconciler.reconcile(a.cells),e.set(Cs,{...r,cellIds:n.reconciler.stagedCellIds()})},t[21]=e,t[22]=x);let ee=x,te;return t[23]!==v||t[24]!==f||t[25]!==b||t[26]!==m||t[27]!==g||t[28]!==ee?(te={beginStagedCellGeneration:f,finishStagedCellGeneration:m,hasOwnedStagedCells:g,acceptOwnedStagedCells:v,discardOwnedStagedCells:b,onData:ee},t[23]=v,t[24]=f,t[25]=b,t[26]=m,t[27]=g,t[28]=ee,t[29]=te):te=t[29],te}var Ms=class{createdCells=[];actions;marimoImportCellId=null;constructor(e){this.actions=e}reconcile(e){for(let[t,n]of e.entries())if(t<this.createdCells.length){let e=this.createdCells[t],r=e.code!==n.code;if(this.createdCells[t]={...e,code:n.code},!r)continue;this.actions.updateStagedCell({cellId:e.cellId,code:n.code})}else{let e=this.actions.createStagedCell(n.code);this.createdCells.push({cellId:e,code:n.code})}let t=this.createdCells.splice(e.length);for(let{cellId:e}of t.toReversed())this.actions.deleteStagedCell(e);this.syncMarimoImport(e)}discard(e){for(let{cellId:t}of this.createdCells.toReversed())e.has(t)&&this.actions.deleteStagedCell(t);this.createdCells=[],this.marimoImportCellId&&e.has(this.marimoImportCellId)&&this.actions.deleteStagedCell(this.marimoImportCellId),this.marimoImportCellId=null}accept(){for(let e of this.stagedCellIds())this.actions.removeStagedCell(e)}hasStagedCells(e){return this.stagedCellIds().some(t=>e.has(t))}stagedCellIds(){let e=this.createdCells.map(({cellId:e})=>e);return this.marimoImportCellId&&e.push(this.marimoImportCellId),e}syncMarimoImport(e){if(!e.some(e=>e.language!==`python`)){this.marimoImportCellId&&=(this.actions.deleteStagedCell(this.marimoImportCellId),null);return}if(this.marimoImportCellId)return;let t=h({autoInstantiate:!1,createNewCell:this.actions.createNewCell,fromCellId:this.createdCells[0]?.cellId,before:!0});t&&(this.actions.addStagedCell({cellId:t,edit:{type:`add_cell`}}),this.marimoImportCellId=t)}},Ns={baseDescription:`Perform editing operations on the current notebook. You should prefer to create new cells unless you need to edit existing cells. Call this tool multiple times to perform multiple edits. Separate code into logical individual cells to take advantage of the notebook's reactive execution model.`,prerequisites:[`If you are updating existing cells, you need the cellIds. If they are not known, call the lightweight_cell_map_tool to find out.`],additionalInfo:`
|
|
20
|
+
`)}})}},ho={"content-type":`text/event-stream`,"cache-control":`no-cache`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`};function go({status:e,statusText:t,headers:n,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new mo);if(i){let[e,t]=a.tee();a=e,i({stream:t})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:po(n,ho)})}var _o=O(w(),Ra.optional()),vo=aa(()=>ma(T([j({type:A(`text-start`),id:w(),providerMetadata:Y.optional()}),j({type:A(`text-delta`),id:w(),delta:w(),providerMetadata:Y.optional()}),j({type:A(`text-end`),id:w(),providerMetadata:Y.optional()}),j({type:A(`error`),errorText:w()}),j({type:A(`tool-input-start`),toolCallId:w(),toolName:w(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),title:w().optional()}),j({type:A(`tool-input-delta`),toolCallId:w(),inputTextDelta:w()}),j({type:A(`tool-input-available`),toolCallId:w(),toolName:w(),input:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),title:w().optional()}),j({type:A(`tool-input-error`),toolCallId:w(),toolName:w(),input:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),errorText:w(),title:w().optional()}),j({type:A(`tool-approval-request`),approvalId:w(),toolCallId:w(),isAutomatic:k().optional(),signature:w().optional()}),j({type:A(`tool-approval-response`),approvalId:w(),approved:k(),reason:w().optional(),providerExecuted:k().optional(),providerMetadata:Y.optional()}),j({type:A(`tool-output-available`),toolCallId:w(),output:D(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional(),preliminary:k().optional()}),j({type:A(`tool-output-error`),toolCallId:w(),errorText:w(),providerExecuted:k().optional(),providerMetadata:Y.optional(),toolMetadata:_o.optional(),dynamic:k().optional()}),j({type:A(`tool-output-denied`),toolCallId:w()}),j({type:A(`reasoning-start`),id:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-delta`),id:w(),delta:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-end`),id:w(),providerMetadata:Y.optional()}),j({type:A(`custom`),kind:w().transform(e=>e),providerMetadata:Y.optional()}),j({type:A(`source-url`),sourceId:w(),url:w(),title:w().optional(),providerMetadata:Y.optional()}),j({type:A(`source-document`),sourceId:w(),mediaType:w(),title:w(),filename:w().optional(),providerMetadata:Y.optional()}),j({type:A(`file`),url:w(),mediaType:w(),providerMetadata:Y.optional()}),j({type:A(`reasoning-file`),url:w(),mediaType:w(),providerMetadata:Y.optional()}),j({type:he(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:w().optional(),data:D(),transient:k().optional()}),j({type:A(`start-step`)}),j({type:A(`finish-step`)}),j({type:A(`start`),messageId:w().optional(),messageMetadata:D().optional()}),j({type:A(`finish`),finishReason:xe([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:D().optional()}),j({type:A(`abort`),reason:w().optional()}),j({type:A(`message-metadata`),messageMetadata:D()})])));function yo(e){return e.type.startsWith(`data-`)}function bo(){return Object.create(null)}function xo(e){return e.type.startsWith(`tool-`)}function So(e){return e.type===`dynamic-tool`}function Co(e){return xo(e)||So(e)}function wo(e){return e.type.split(`-`).slice(1).join(`-`)}function To({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:bo(),activeReasoningParts:bo(),partialToolCalls:bo()}}function Eo({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(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(Co)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(Co(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new Ia({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(Co).find(t=>t.approval?.id===e);if(t==null)throw new Ia({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>xo(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}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:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:La(r.message.metadata,e);t!=null&&await ha({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 Ia({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 Ia({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 Ia({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 Ia({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=l().filter(xo);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({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 Ia({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 oo(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({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?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({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=l().filter(Co).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):p({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=d(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=f(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=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({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},t):p({toolCallId:e.toolCallId,toolName:wo(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},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({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},t):p({toolCallId:e.toolCallId,toolName:wo(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},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=bo(),r.activeReasoningParts=bo();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(yo(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 ha({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 Do({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()}}Xr({prefix:`aitxt`,size:24}),Xr({prefix:`call`,size:24}),Xr({prefix:`aitxt`,size:24}),Xr({prefix:`call`,size:24});var X=O(w(),Ra.optional()),Oo=O(w(),w()),ko=aa(()=>ma(E(C({id:w(),role:xe([`system`,`user`,`assistant`]),metadata:D().optional(),parts:E(T([C({type:A(`text`),text:w(),state:xe([`streaming`,`done`]).optional(),providerMetadata:Y.optional()}),C({type:A(`reasoning`),text:w(),state:xe([`streaming`,`done`]).optional(),providerMetadata:Y.optional()}),C({type:A(`custom`),kind:w(),providerMetadata:Y.optional()}),C({type:A(`source-url`),sourceId:w(),url:w(),title:w().optional(),providerMetadata:Y.optional()}),C({type:A(`source-document`),sourceId:w(),mediaType:w(),title:w(),filename:w().optional(),providerMetadata:Y.optional()}),C({type:A(`file`),mediaType:w(),filename:w().optional(),url:w(),providerReference:Oo.optional(),providerMetadata:Y.optional()}),C({type:A(`reasoning-file`),mediaType:w(),url:w(),providerMetadata:Y.optional()}),C({type:A(`step-start`)}),C({type:w().startsWith(`data-`),id:w().optional(),data:D()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-streaming`),input:D().optional(),providerExecuted:k().optional(),callProviderMetadata:Y.optional(),output:M().optional(),errorText:M().optional(),approval:M().optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-available`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:M().optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-requested`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:M().optional(),reason:M().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-responded`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:k(),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-available`),input:D(),providerExecuted:k().optional(),output:D(),errorText:M().optional(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),preliminary:k().optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-error`),input:D().optional(),rawInput:D().optional(),providerExecuted:k().optional(),output:M().optional(),errorText:w(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:A(`dynamic-tool`),toolName:w(),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-denied`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!1),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-streaming`),providerExecuted:k().optional(),callProviderMetadata:Y.optional(),input:D().optional(),output:M().optional(),errorText:M().optional(),approval:M().optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`input-available`),providerExecuted:k().optional(),input:D(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:M().optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-requested`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:M().optional(),reason:M().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`approval-responded`),input:D(),providerExecuted:k().optional(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:k(),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-available`),providerExecuted:k().optional(),input:D(),output:D(),errorText:M().optional(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),preliminary:k().optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-error`),providerExecuted:k().optional(),input:D().optional(),rawInput:D().optional(),output:M().optional(),errorText:w(),callProviderMetadata:Y.optional(),resultProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!0),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()}).optional()}),C({type:w().startsWith(`tool-`),toolCallId:w(),toolMetadata:X.optional(),state:A(`output-denied`),providerExecuted:k().optional(),input:D(),output:M().optional(),errorText:M().optional(),callProviderMetadata:Y.optional(),approval:C({id:w(),approved:A(!1),reason:w().optional(),isAutomatic:k().optional(),signature:w().optional()})})]))}).superRefine((e,t)=>{e.role!==`assistant`&&e.parts.length===0&&t.addIssue({origin:`array`,code:`too_small`,minimum:1,inclusive:!0,input:e.parts,path:[`parts`],message:`Message must contain at least one part`})})).nonempty(`Messages array must not be empty`)));async function Ao({messages:e,metadataSchema:t,dataSchemas:n,tools:r}){try{if(e==null)return{success:!1,error:new Ea({parameter:`messages`,value:e,message:`messages parameter must be provided`})};let i=await ha({value:e,schema:ko});if(t)for(let[e,n]of i.entries())await ha({value:n.metadata,schema:t,context:{field:`messages[${e}].metadata`,entityId:n.id}});if(n||r)for(let[e,t]of i.entries())for(let[i,a]of t.parts.entries()){if(n&&a.type.startsWith(`data-`)){let t=a,r=t.type.slice(5),o=n[r];if(!o)return{success:!1,error:new pn({value:t.data,cause:`No data schema found for data part ${r}`,context:{field:`messages[${e}].parts[${i}].data`,entityName:r,entityId:t.id}})};await ha({value:t.data,schema:o,context:{field:`messages[${e}].parts[${i}].data`,entityName:r,entityId:t.id}})}if(r&&a.type.startsWith(`tool-`)){let t=a,n=t.type.slice(5),o=io(r,n);if(!o&&(t.state===`output-available`||t.state===`output-error`||t.state===`output-denied`))continue;if(!o)return{success:!1,error:new pn({value:t.input,cause:`No tool schema found for tool part ${n}`,context:{field:`messages[${e}].parts[${i}].input`,entityName:n,entityId:t.toolCallId}})};(t.state===`input-available`||t.state===`output-available`)&&await ha({value:t.input,schema:o.inputSchema,context:{field:`messages[${e}].parts[${i}].input`,entityName:n,entityId:t.toolCallId}}),t.state===`output-available`&&o.outputSchema&&await ha({value:t.output,schema:o.outputSchema,context:{field:`messages[${e}].parts[${i}].output`,entityName:n,entityId:t.toolCallId}})}}return{success:!0,data:i}}catch(e){return{success:!1,error:e}}}Xr({prefix:`call`,size:24}),Xr({prefix:`call`,size:24}),Xr({prefix:`aiobj`,size:24});var jo=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()})}};Xr({prefix:`aiobj`,size:24}),Xr({prefix:`call`,size:24});async function Mo(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 No=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 ya(this.body),r=await ya(this.headers),i=await ya(this.credentials),a={...Qr(r),...Qr(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:Qr(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 ya(this.body),n=await ya(this.headers),r=await ya(this.credentials),i={...Qr(n),...Qr(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:Qr(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)}},Po=class extends No{constructor(e={}){super(e)}processResponseStream(e){return va({stream:e,schema:vo}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Fo=class{constructor({generateId:e=Zr,id:t=e(),transport:n=new Po,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new jo,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 Mo(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=>Co(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=>Co(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,d;try{let a={state:To({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};d=a,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 Do({stream:Eo({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{d&&((a=this.onFinish)==null||a.call(this,{message:d.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:d.state.finishReason}))}catch(e){console.error(e)}this.activeResponse===d&&(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 Io({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(Co);return r.filter(e=>e.state===`approval-responded`).length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`||e.state===`approval-responded`)}function Lo({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(Co).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}var Ro=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})),Z=e(l(),1),zo=e(Ro(),1),Q=je(),Bo=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},$=(e,t,n)=>(Bo(e,t,`read from private field`),n?n.call(e):t.get(e)),Vo=(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)},Ho=(e,t,n,r)=>(Bo(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function Uo(e,t){return t==null?e:(0,zo.default)(e,t)}var Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo,$o=class{constructor(e=[]){Vo(this,Wo,void 0),Vo(this,Go,`ready`),Vo(this,Ko,void 0),Vo(this,qo,new Set),Vo(this,Jo,new Set),Vo(this,Yo,new Set),this.pushMessage=e=>{Ho(this,Wo,$(this,Wo).concat(e)),$(this,Xo).call(this)},this.popMessage=()=>{Ho(this,Wo,$(this,Wo).slice(0,-1)),$(this,Xo).call(this)},this.replaceMessage=(e,t)=>{Ho(this,Wo,[...$(this,Wo).slice(0,e),this.snapshot(t),...$(this,Wo).slice(e+1)]),$(this,Xo).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?Uo(e,t):e;return $(this,qo).add(n),()=>{$(this,qo).delete(n)}},this[`~registerStatusCallback`]=e=>($(this,Jo).add(e),()=>{$(this,Jo).delete(e)}),this[`~registerErrorCallback`]=e=>($(this,Yo).add(e),()=>{$(this,Yo).delete(e)}),Vo(this,Xo,()=>{$(this,qo).forEach(e=>e())}),Vo(this,Zo,()=>{$(this,Jo).forEach(e=>e())}),Vo(this,Qo,()=>{$(this,Yo).forEach(e=>e())}),Ho(this,Wo,e)}get status(){return $(this,Go)}set status(e){Ho(this,Go,e),$(this,Zo).call(this)}get error(){return $(this,Ko)}set error(e){Ho(this,Ko,e),$(this,Qo).call(this)}get messages(){return $(this,Wo)}set messages(e){Ho(this,Wo,[...e]),$(this,Xo).call(this)}};Wo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,qo=new WeakMap,Jo=new WeakMap,Yo=new WeakMap,Xo=new WeakMap,Zo=new WeakMap,Qo=new WeakMap;var es,ts=class extends Fo{constructor({messages:e,...t}){let n=new $o(e);super({...t,state:n}),Vo(this,es,void 0),this[`~registerMessagesCallback`]=(e,t)=>$(this,es)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>$(this,es)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>$(this,es)[`~registerErrorCallback`](e),Ho(this,es,n)}};es=new WeakMap;function ns({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,Z.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 Po),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,Z.useRef)(`chat`in r?r.chat:new ts(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 ts(c));let u=(0,Z.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),d=(0,Z.useSyncExternalStore)(u,()=>l.current.messages,()=>l.current.messages),f=(0,Z.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),p=(0,Z.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),m=(0,Z.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,Z.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:d,setMessages:m,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:p,resumeStream:l.current.resumeStream,status:f,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function rs(e){return ze.define({combine:t=>t[0]??e})}var is=rs({}),as=Ue.define(),os=Ue.define(),ss=50,cs=Be.define({create(){return{prompts:[],navigationIndex:-1,originalText:``}},update(e,t){let n={...e};t.docChanged&&e.navigationIndex!==-1&&(t.effects.some(e=>e.is(os)||e.is(as))||(n.navigationIndex=-1,n.originalText=``));for(let r of t.effects)if(r.is(as)){let i=r.value.trim();i&&(n.prompts=[i,...e.prompts.filter(e=>e!==i)].slice(0,ss),t.state.facet(is).save?.(n.prompts)),n.navigationIndex=-1,n.originalText=``}else r.is(os)&&(n.navigationIndex=r.value.index,n.originalText=r.value.originalText);return n}}),ls=e=>{let t=e.state.field(cs),n=e.state.doc;if(t.prompts.length===0)return!1;let r,i=t.originalText;if(t.navigationIndex===-1){if(n.length>0)return!1;r=0,i=n.toString()}else if(r=Math.min(t.navigationIndex+1,t.prompts.length-1),r===t.navigationIndex)return!1;let a=t.prompts[r];return e.dispatch({changes:{from:0,to:e.state.doc.length,insert:a},effects:os.of({index:r,originalText:i})}),!0},us=e=>{let t=e.state.field(cs);if(t.navigationIndex===-1)return!1;let n,r;return t.navigationIndex===0?(n=t.originalText,r=-1):(r=t.navigationIndex-1,n=t.prompts[r]??``),e.dispatch({changes:{from:0,to:e.state.doc.length,insert:n},effects:os.of({index:r,originalText:t.originalText})}),!0},ds=e=>{let t=e.state.doc.toString();return t.trim()?(e.dispatch({effects:as.of(t)}),!0):!1};function fs(e={}){let{storage:t,defaultKeymap:n=!0}=e,r=[cs.init(()=>({prompts:t?.load?.()??[],navigationIndex:-1,originalText:``})),is.of(t??{})];return n&&r.push(Ve.of([{key:`ArrowUp`,run:ls},{key:`ArrowDown`,run:us}])),r}var ps=class extends Error{code;isRetryable;suggestedFix;meta;constructor(e,t=`TOOL_ERROR`,n=!1,r,i){super(e),this.name=`ToolExecutionError`,this.code=t,this.isRetryable=n,this.suggestedFix=r,this.meta=i}toStructuredString(){let e=JSON.stringify({message:this.message,code:this.code,is_retryable:this.isRetryable,...this.suggestedFix&&{suggested_fix:this.suggestedFix},...this.meta&&{meta:this.meta}});return`Error invoking tool ${this.name}: ${e}`}},ms=C({status:xe([`success`,`error`,`warning`]).optional(),auth_required:k().optional(),next_steps:E(w()).optional(),action_url:w().optional(),message:w().optional(),meta:O(w(),D()).optional()}),hs=`cell-completion`,gs=`notebook-cells-completion`,_s=`data-${hs}`,vs=`data-${gs}`,ys=C({code:w()}),bs=C({language:xe([`python`,`sql`,`markdown`]),code:w().min(1)}),xs=C({cells:E(bs).min(1)});function Ss(e){return e.type.startsWith(`data-`)}var Cs=a(null),ws=a(e=>e(Cs)?.status===`in_progress`),{valueAtom:Ts,useActions:Es,createActions:Ds,reducer:Os}=Ze(()=>new Map,{addStagedCell:(e,t)=>{let{cellId:n,edit:r}=t;return new Map([...e,[n,r]])},removeStagedCell:(e,t)=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}});function ks(e){let t=(0,P.c)(2),n;return t[0]===e?n=t[1]:(n=v(Ts,t=>t.get(e),Object.is),t[0]=e,t[1]=n),o(n)}function As(e){let t=(0,P.c)(15),{addStagedCell:n,removeStagedCell:r}=Es(),{createNewCell:i,updateCellCode:a}=d(),o=pt(),s;t[0]!==n||t[1]!==i?(s=e=>{let t=m.create();return n({cellId:t,edit:{type:`add_cell`}}),i({cellId:`__end__`,code:e,before:!1,newCellId:t}),t},t[0]=n,t[1]=i,t[2]=s):s=t[2];let c=s,l;t[3]!==e||t[4]!==a?(l=t=>{let{cellId:n,code:r}=t;if(!e.get(Ts).has(n)){N.error(`Staged cell not found`,{cellId:n});return}let i=ne(n);i?pe(i,r):a({cellId:n,code:r,formattingChange:!1})},t[3]=e,t[4]=a,t[5]=l):l=t[5];let u=l,f;t[6]!==o||t[7]!==r?(f=e=>{r(e),o({cellId:e})},t[6]=o,t[7]=r,t[8]=f):f=t[8];let p=f,h;return t[9]!==n||t[10]!==c||t[11]!==p||t[12]!==r||t[13]!==u?(h={createStagedCell:c,updateStagedCell:u,addStagedCell:n,removeStagedCell:r,deleteStagedCell:p},t[9]=n,t[10]=c,t[11]=p,t[12]=r,t[13]=u,t[14]=h):h=t[14],h}function js(e){let t=(0,P.c)(30),n=As(e),{createNewCell:r}=d(),i=(0,Z.useRef)(null),a;t[0]===e?a=t[1]:(a={store:e},t[0]=e,t[1]=a),o(Cs,a);let s;t[2]===e?s=t[3]:(s={store:e},t[2]=e,t[3]=s),o(Ts,s);let c;t[4]!==n||t[5]!==e?(c=t=>{let r=e.get(Ts);for(let e of t.toReversed())r.has(e)&&n.deleteStagedCell(e)},t[4]=n,t[5]=e,t[6]=c):c=t[6];let l=c,u;t[7]!==r||t[8]!==l||t[9]!==n||t[10]!==e?(u=()=>{let t=e.get(Cs);t?.status===`in_progress`&&l(t.cellIds),i.current?.reconciler.discard(e.get(Ts));let a=Symbol(`staged-cell-generation`);i.current={id:a,status:`in_progress`,reconciler:new Ms({...n,createNewCell:r})},e.set(Cs,{id:a,status:`in_progress`,cellIds:[]})},t[7]=r,t[8]=l,t[9]=n,t[10]=e,t[11]=u):u=t[11];let f=u,p;t[12]===e?p=t[13]:(p=t=>{let n=i.current;if(n?.status!==`in_progress`)return;let r=e.get(Cs),a=r?.id===n.id&&r.status===`in_progress`;if(!a||!t){n.reconciler.discard(e.get(Ts)),a&&e.set(Cs,null),i.current=null;return}n.status=`complete`,e.set(Cs,{id:n.id,status:`complete`})},t[12]=e,t[13]=p);let m=p,h;t[14]===e?h=t[15]:(h=()=>{let t=i.current,n=e.get(Cs);return t!==null&&t.status===`complete`&&n?.status===`complete`&&n.id===t.id&&t.reconciler.hasStagedCells(e.get(Ts))},t[14]=e,t[15]=h);let g=h,_;t[16]!==g||t[17]!==e?(_=()=>g()?(i.current?.reconciler.accept(),e.set(Cs,null),i.current=null,!0):!1,t[16]=g,t[17]=e,t[18]=_):_=t[18];let v=_,y;t[19]===e?y=t[20]:(y=()=>{let t=i.current,n=e.get(Cs);return t===null||n?.id!==t.id?!1:(t.reconciler.discard(e.get(Ts)),e.set(Cs,null),i.current=null,!0)},t[19]=e,t[20]=y);let b=y,x;t[21]===e?x=t[22]:(x=t=>{if(t.type!==vs)return;let n=i.current,r=e.get(Cs);if(n?.status!==`in_progress`||r?.id!==n.id||r.status!==`in_progress`)return;let a=xs.parse(t.data);n.reconciler.reconcile(a.cells),e.set(Cs,{...r,cellIds:n.reconciler.stagedCellIds()})},t[21]=e,t[22]=x);let S=x,ee;return t[23]!==v||t[24]!==f||t[25]!==b||t[26]!==m||t[27]!==g||t[28]!==S?(ee={beginStagedCellGeneration:f,finishStagedCellGeneration:m,hasOwnedStagedCells:g,acceptOwnedStagedCells:v,discardOwnedStagedCells:b,onData:S},t[23]=v,t[24]=f,t[25]=b,t[26]=m,t[27]=g,t[28]=S,t[29]=ee):ee=t[29],ee}var Ms=class{createdCells=[];actions;marimoImportCellId=null;constructor(e){this.actions=e}reconcile(e){for(let[t,n]of e.entries())if(t<this.createdCells.length){let e=this.createdCells[t],r=e.code!==n.code;if(this.createdCells[t]={...e,code:n.code},!r)continue;this.actions.updateStagedCell({cellId:e.cellId,code:n.code})}else{let e=this.actions.createStagedCell(n.code);this.createdCells.push({cellId:e,code:n.code})}let t=this.createdCells.splice(e.length);for(let{cellId:e}of t.toReversed())this.actions.deleteStagedCell(e);this.syncMarimoImport(e)}discard(e){for(let{cellId:t}of this.createdCells.toReversed())e.has(t)&&this.actions.deleteStagedCell(t);this.createdCells=[],this.marimoImportCellId&&e.has(this.marimoImportCellId)&&this.actions.deleteStagedCell(this.marimoImportCellId),this.marimoImportCellId=null}accept(){for(let e of this.stagedCellIds())this.actions.removeStagedCell(e)}hasStagedCells(e){return this.stagedCellIds().some(t=>e.has(t))}stagedCellIds(){let e=this.createdCells.map(({cellId:e})=>e);return this.marimoImportCellId&&e.push(this.marimoImportCellId),e}syncMarimoImport(e){if(!e.some(e=>e.language!==`python`)){this.marimoImportCellId&&=(this.actions.deleteStagedCell(this.marimoImportCellId),null);return}if(this.marimoImportCellId)return;let t=ue({autoInstantiate:!1,createNewCell:this.actions.createNewCell,fromCellId:this.createdCells[0]?.cellId,before:!0});t&&(this.actions.addStagedCell({cellId:t,edit:{type:`add_cell`}}),this.marimoImportCellId=t)}},Ns={baseDescription:`Perform editing operations on the current notebook. You should prefer to create new cells unless you need to edit existing cells. Call this tool multiple times to perform multiple edits. Separate code into logical individual cells to take advantage of the notebook's reactive execution model.`,prerequisites:[`If you are updating existing cells, you need the cellIds. If they are not known, call the lightweight_cell_map_tool to find out.`],additionalInfo:`
|
|
21
21
|
Args:
|
|
22
22
|
edit (object): The editing operation to perform with the following structure:
|
|
23
23
|
- type: One of "update_cell", "add_cell", or "delete_cell"
|
|
@@ -41,21 +41,21 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
41
41
|
- SQL cells: use mo.sql(f"""{content}""") function to insert content. If a database engine is specified, use mo.sql(f"""{content}""", engine=engine) instead.
|
|
42
42
|
|
|
43
43
|
Returns:
|
|
44
|
-
- A result object containing standard tool metadata.`},Ps=C({edit:C({type:xe([`update_cell`,`add_cell`,`delete_cell`]),code:w().optional(),position:C({type:xe([`relative`,`column_end`,`notebook_end`]).optional(),cellId:w().optional(),columnIndex:ge().optional(),before:k().optional()})})}),Fs=class{name=`edit_notebook_tool`;description=Ns;schema=Ps;outputSchema=ms;mode=[`agent`];handler=async({edit:e},t)=>{let{addStagedCell:n,createNewCell:r,store:i}=t;switch(e.type){case`update_cell`:{let{position:t,code:r}=e,a=t.cellId;if(!a)throw new ps(`Cell ID is required for update_cell`,`CELL_ID_REQUIRED_FOR_UPDATE_CELL`,!0,`Provide a cell ID to update`);if(!r)throw new ps(`Code is required for update_cell`,`CODE_REQUIRED_FOR_UPDATE_CELL`,!0,`Provide the new code to update the cell`);let o=i.get(
|
|
45
|
-
`),o=this.truncateString(o,Us),d+=o.length),c.set(e,{cellOutput:a,consoleOutput:o})}if(c.size===0)return{status:`success`,message:`Stale cells have been run. No output was returned.`};let p=[`Review the output of the cells. The CellId is the key of the result object.`,l?`There are errors in the cells. Please fix them by using the edit notebook tool and the given CellIds.`:`You may edit the notebook further with the given CellIds.`];return{status:`success`,cellsToOutput:Object.fromEntries(c),message:u?`Console output represents the stdout or stderr of the cell (eg. print statements).`:void 0,next_steps:p}};outputHasErrors(e){return e.output.mimetype===`application/vnd.marimo+error`||e.output.mimetype===`application/vnd.marimo+traceback`}formatOutputString(e){let{outputType:t,processedContent:n,imageUrl:r,output:i}=e;if(t===`media`){let e=`Media Output: Contains ${i.mimetype} content`;return r?`${e}\nImage URL: ${r}`:e}if(i.mimetype===`text/html`)return`HTML Output: text/html content (${(typeof i.data==`string`?i.data.length:JSON.stringify(i.data).length).toLocaleString()} chars). Full output visible in notebook UI.`;let a=this.outputHasErrors(e)?Ws:Us,o=n;return o||=typeof i.data==`string`?i.data:JSON.stringify(i.data),`Output:\n${this.truncateString(o,a)}`}truncateString(e,t){return e.length<=t?e:`${e.slice(0,t)}\n\n[TRUNCATED: ${e.length.toLocaleString()} → ${t.toLocaleString()} chars. Full output visible in the notebook UI.]`}async waitForCellsToFinish(e,t,r,i){let a=e=>t.every(t=>{let n=e.cellRuntime[t];return n?.status!==`running`&&n?.status!==`queued`}),o=async()=>(i>0&&await new Promise(e=>setTimeout(e,i)),!0);if(a(e.get(
|
|
44
|
+
- A result object containing standard tool metadata.`},Ps=C({edit:C({type:xe([`update_cell`,`add_cell`,`delete_cell`]),code:w().optional(),position:C({type:xe([`relative`,`column_end`,`notebook_end`]).optional(),cellId:w().optional(),columnIndex:ge().optional(),before:k().optional()})})}),Fs=class{name=`edit_notebook_tool`;description=Ns;schema=Ps;outputSchema=ms;mode=[`agent`];handler=async({edit:e},t)=>{let{addStagedCell:n,createNewCell:r,store:i}=t;switch(e.type){case`update_cell`:{let{position:t,code:r}=e,a=t.cellId;if(!a)throw new ps(`Cell ID is required for update_cell`,`CELL_ID_REQUIRED_FOR_UPDATE_CELL`,!0,`Provide a cell ID to update`);if(!r)throw new ps(`Code is required for update_cell`,`CODE_REQUIRED_FOR_UPDATE_CELL`,!0,`Provide the new code to update the cell`);let o=i.get(S);this.validateCellIdExists(a,o);let s=this.getCellEditorView(a,o);Mt(a);let c=i.get(Ts).get(a);if(c?.type===`add_cell`){pe(s,r);break}let l=s.state.doc.toString(),u=c?.previousCode??l;if(r===u)break;n({cellId:a,edit:{type:`update_cell`,previousCode:u}}),pe(s,r);break}case`add_cell`:{let{position:t,code:a}=e,o=`__end__`,s=!1,c=m.create(),l=i.get(S);switch(t.type){case`relative`:{let e=t.cellId;if(!e)throw new ps(`Cell ID is required for add_cell with relative position`,`TOOL_ERROR`,!0,`Provide a cell ID to add the cell before`);if(t.before===void 0)throw new ps(`Before is required for add_cell with relative position`,`TOOL_ERROR`,!0,`Provide a boolean value for before, true to add before cell ${e}, false to add after the cell`);this.validateCellIdExists(e,l),o=e,s=t.before;break}case`column_end`:if(!t.columnIndex)throw new ps(`Column index is required for add_cell with column_end position`,`TOOL_ERROR`,!0,`Provide a column index to add the cell at the end of`);o={type:`__end__`,columnId:this.getColumnId(t.columnIndex,l)}}r({cellId:o,before:s,code:a,newCellId:c}),n({cellId:c,edit:{type:`add_cell`}}),Mt(c);break}case`delete_cell`:{let{position:t}=e,r=t.cellId;if(!r)throw new ps(`Cell ID is required for delete_cell`,`CELL_ID_REQUIRED_FOR_DELETE_CELL`,!0,`Provide a cell ID to delete`);let a=i.get(S);this.validateCellIdExists(r,a),n({cellId:r,edit:{type:`delete_cell`,previousCode:this.getCellEditorView(r,a).state.doc.toString()}}),Mt(r);break}}return{status:`success`,next_steps:[`If you need to perform more edits, call this tool again.`,`You should use the lint notebook tool to check for errors and lint issues. Fix them by editing the notebook.`,`You should use the run stale cells tool to run the cells that have been edited or newly added. This allows you to see the output of the cells and fix any errors.`]}};validateCellIdExists(e,t){if(!t.cellIds.getColumns().some(t=>t.idSet.has(e)))throw new ps(`Cell not found`,`CELL_NOT_FOUND`,!1,`Check which cells exist in the notebook`)}getColumnId(e,t){let n=t.cellIds.getColumns();if(e<0||e>=n.length)throw new ps(`Column index is out of range`,`COLUMN_INDEX_OUT_OF_RANGE`,!0,`Choose a column index between 0 and the number of columns in the notebook (0-based)`);return n[e].id}getCellEditorView(e,t){let n=t.cellHandles[e].current;if(!n?.editorView)throw new ps(`Cell editor not found`,`CELL_EDITOR_NOT_FOUND`,!1,`Internal error, ask the user to report this error`);return n.editorView}};function Is(e,t){return e?!!([`image/`,`video/`,`audio/`,`application/pdf`].some(t=>e.startsWith(t))||[`svg`,`vega`].some(t=>e.includes(t))||e===`text/html`&&[`<img`,`<video`,`<audio`,`<iframe`,`<canvas`,`<svg`,`<marimo-ui-element`].some(e=>t.includes(e))):!1}var Ls=class extends bt{title=`Cell Outputs`;mentionPrefix=`@`;contextType=`cell-output`;store;constructor(e){super(),this.store=e}getItems(){let e=this.store.get(S),t=[];for(let n of e.cellIds.inOrderIds){let r=Bs(n,e),i=r.cellOutput;if(!i)continue;let a=i.output.mimetype||`unknown`;t.push({uri:this.asURI(n),name:r.cellName,type:this.contextType,description:`Cell output (${a})`,data:{...r,cellOutput:i}})}return t}formatCompletion(e){let{cellOutput:t,cellName:n,cellCode:r}=e.data;return{label:`@${n}`,displayLabel:n,detail:`${t.outputType} output`,boost:t.outputType===`media`?_t.HIGH:_t.MEDIUM,type:this.contextType,section:ht.CELL_OUTPUT,apply:`@${n}`,info:()=>{let e=document.createElement(`div`);e.classList.add(`mo-cm-tooltip`,`docs-documentation`,`min-w-[300px]`,`max-w-[500px]`,`flex`,`flex-col`,`gap-2`);let i=document.createElement(`div`);i.classList.add(`flex`,`flex-col`,`gap-1`);let a=document.createElement(`div`);a.classList.add(`font-bold`,`text-base`),a.textContent=n,i.append(a);let o=document.createElement(`div`);if(o.classList.add(`text-sm`,`text-muted-foreground`),i.append(o),e.append(i),r){let t=document.createElement(`div`);t.classList.add(`text-xs`,`font-medium`,`text-muted-foreground`),t.textContent=`Code:`,e.append(t);let n=document.createElement(`div`);n.classList.add(`text-xs`,`font-mono`,`bg-muted`,`p-2`,`rounded`,`max-h-20`,`overflow-y-auto`),n.textContent=r.slice(0,200)+(r.length>200?`...`:``),e.append(n)}if(t.processedContent){let n=document.createElement(`div`);n.classList.add(`text-xs`,`font-medium`,`text-muted-foreground`,`mt-2`),n.textContent=`Output Preview:`,e.append(n);let r=document.createElement(`div`);r.classList.add(`text-xs`,`bg-muted`,`p-2`,`rounded`,`max-h-24`,`overflow-y-auto`,`mb-2`),r.textContent=t.processedContent.slice(0,300)+(t.processedContent.length>300?`...`:``),e.append(r)}if(t.outputType===`media`){let t=document.createElement(`div`);t.classList.add(`text-xs`,`text-muted-foreground`,`italic`,`mb-2`),t.textContent=`A screenshot of the output will be attached`,e.append(t)}return e}}}formatContext(e){let{cellOutput:t,cellName:n,cellId:r,cellCode:i}=e.data,a={name:n,cellId:r,outputType:t.outputType,mimetype:t.output.mimetype},o=`Cell Code:\n${i}\n\n`;return t.outputType===`text`&&t.processedContent?o+=`Output:\n${t.processedContent}`:t.outputType===`media`&&(o+=`Media Output: Contains ${t.output.mimetype} content`,t.imageUrl&&(o+=`\nImage URL: ${t.imageUrl}`)),yt({type:this.contextType,data:a,details:o})}async getAttachments(e){let t=e[0].data.cellId,n=e[0].data.cellName;return Rs(e.map(e=>e.data.cellOutput),t,n)}};async function Rs(e,t,n){let r=e.filter(e=>e.shouldDownloadImage&&e.outputType===`media`);if(r.length===0)return[];let i=r.flatMap(e=>{let r=document.getElementById(h.create(t));return r?{cellId:t,cellName:n,mimetype:e.output.mimetype,element:r}:(N.warn(`Output element not found for cell ${t}`),[])});try{return await Promise.all(i.map(async e=>({type:`file`,filename:`${n}-output-screenshot`,mediaType:`image/png`,url:await Nt(e.element)})))}catch(e){return N.error(`Error downloading cell output images:`,e),[]}}function zs(e){if(ct(e))return null;let t=e.mimetype,n=Is(t,String(e.data))?`media`:`text`,r=It(e),i,a=!1;return n===`media`&&(typeof e.data==`string`&&e.data.startsWith(`data:`)||typeof e.data==`string`&&e.data.startsWith(`http`)?i=e.data:a=!0),{processedContent:r,imageUrl:i,shouldDownloadImage:a,outputType:n,output:e}}function Bs(e,t,n){let{includeConsoleOutput:r=!1}=n||{},i=t.cellRuntime[e],a=t.cellData[e],o=t.cellIds.inOrderIds.indexOf(e),s=b(a.name,o),c;r&&(c=i.consoleOutputs.map(e=>zs(e)).filter(e=>e!==null));let l,u=i.output;return u&&!ct(u)&&(l=zs(u)??void 0),{cellId:e,cellName:s,cellCode:a.code,cellOutput:l,consoleOutputs:c}}var Vs=200,Hs=3e4,Us=2e3,Ws=3e3,Gs=4e4,Ks={baseDescription:`Run cells in the current notebook that are stale. Stale cells are cells that have been edited or newly added. You can run this tool after editing the notebook or when requested. The output of the ran cells will be returned alongside metadata.`},qs=C({type:A(`file`),url:w(),mediaType:w()}),Js=class{name=`run_stale_cells_tool`;description=Ks;schema=C({});outputSchema=ms.extend({cellsToOutput:O(w(),C({consoleOutput:w().optional(),cellOutput:w().optional(),consoleAttachments:E(qs).optional(),cellAttachments:E(qs).optional()}).nullable()).optional()});mode=[`agent`];postExecutionDelay;constructor(e){this.postExecutionDelay=e?.postExecutionDelay??Vs}handler=async(e,t)=>{let{prepareForRun:n,sendRun:r,store:i}=t,a=i.get(S),o=f(a);if(o.length===0)return{status:`success`,message:`No stale cells found.`};if(await Dt({cellIds:o,sendRun:r,prepareForRun:n,notebook:a}),!await this.waitForCellsToFinish(i,o,Hs,this.postExecutionDelay))return{status:`success`,message:`No output was returned because some cells have not finished executing`};let s=i.get(S),c=new Map,l=!1,u=!1,d=0;for(let e of o){let t=Bs(e,s,{includeConsoleOutput:!0}),n=t.cellOutput,r=t.consoleOutputs,i=r&&r.length>0;if((n&&this.outputHasErrors(n)||i&&r.some(e=>this.outputHasErrors(e)))&&(l=!0),!n&&!i){c.set(e,null);continue}if(d>=Gs){c.set(e,{cellOutput:`Cell executed (output omitted due to context limits).`});continue}let a,o;n&&(a=this.formatOutputString(n),d+=a.length),i&&(u=!0,o=r.map(e=>this.formatOutputString(e)).join(`
|
|
45
|
+
`),o=this.truncateString(o,Us),d+=o.length),c.set(e,{cellOutput:a,consoleOutput:o})}if(c.size===0)return{status:`success`,message:`Stale cells have been run. No output was returned.`};let p=[`Review the output of the cells. The CellId is the key of the result object.`,l?`There are errors in the cells. Please fix them by using the edit notebook tool and the given CellIds.`:`You may edit the notebook further with the given CellIds.`];return{status:`success`,cellsToOutput:Object.fromEntries(c),message:u?`Console output represents the stdout or stderr of the cell (eg. print statements).`:void 0,next_steps:p}};outputHasErrors(e){return e.output.mimetype===`application/vnd.marimo+error`||e.output.mimetype===`application/vnd.marimo+traceback`}formatOutputString(e){let{outputType:t,processedContent:n,imageUrl:r,output:i}=e;if(t===`media`){let e=`Media Output: Contains ${i.mimetype} content`;return r?`${e}\nImage URL: ${r}`:e}if(i.mimetype===`text/html`)return`HTML Output: text/html content (${(typeof i.data==`string`?i.data.length:JSON.stringify(i.data).length).toLocaleString()} chars). Full output visible in notebook UI.`;let a=this.outputHasErrors(e)?Ws:Us,o=n;return o||=typeof i.data==`string`?i.data:JSON.stringify(i.data),`Output:\n${this.truncateString(o,a)}`}truncateString(e,t){return e.length<=t?e:`${e.slice(0,t)}\n\n[TRUNCATED: ${e.length.toLocaleString()} → ${t.toLocaleString()} chars. Full output visible in the notebook UI.]`}async waitForCellsToFinish(e,t,r,i){let a=e=>t.every(t=>{let n=e.cellRuntime[t];return n?.status!==`running`&&n?.status!==`queued`}),o=async()=>(i>0&&await new Promise(e=>setTimeout(e,i)),!0);if(a(e.get(S)))return await o();try{return await Promise.race([n(S,a),new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),r))]),await o()}catch{return!1}}};function Ys(e){let t=e.baseDescription;return e.whenToUse&&(t+=`\n\n## When to use:\n- ${e.whenToUse.join(`
|
|
46
46
|
- `)}`),e.avoidIf&&(t+=`\n\n## Avoid if:\n- ${e.avoidIf.join(`
|
|
47
47
|
- `)}`),e.prerequisites&&(t+=`\n\n## Prerequisites:\n- ${e.prerequisites.join(`
|
|
48
48
|
- `)}`),e.sideEffects&&(t+=`\n\n## Side effects:\n- ${e.sideEffects.join(`
|
|
49
|
-
- `)}`),e.additionalInfo&&(t+=`\n\n## Additional info:\n- ${e.additionalInfo}`),t}var Xs=class{tools=new Map;constructor(e=[]){this.tools=new Map(e.map(e=>[e.name,e]))}has(e){return this.tools.has(e)}getToolOrThrow(e){let t=this.tools.get(e);if(!t)throw Error(`Tool ${e} not found`);return t}async invoke({toolName:e,rawArgs:t,toolContext:n}){let r=this.getToolOrThrow(e),i=r.handler,a=r.schema,o=r.outputSchema;try{let r=await a.safeParseAsync(t);if(r.error)throw new ps(`Tool ${e} returned invalid input: ${ye(r.error)}`,`INVALID_ARGUMENTS`,!0,`Please check the arguments and try again.`);let s=r.data,c=await i(s,n),l=await o.safeParseAsync(c);if(l.error){let t=ye(l.error);throw Error(`Tool ${e} returned invalid output: ${t}`)}return{tool_name:e,result:l.data,error:null}}catch(n){return n instanceof ps?{tool_name:e,result:null,error:n.toStructuredString()}:{tool_name:e,result:null,error:new ps(n instanceof Error?n.message:String(n),`TOOL_ERROR`,!1,`Check the error message and try again with valid arguments.`,{args:t,errorType:n?.constructor?.name??typeof n}).toStructuredString()}}}getToolSchemas(e){return[...this.tools.values()].filter(t=>t.mode.includes(e)).map(e=>({name:e.name,description:Ys(e.description),parameters:me(e.schema),source:`frontend`,mode:e.mode}))}};
|
|
49
|
+
- `)}`),e.additionalInfo&&(t+=`\n\n## Additional info:\n- ${e.additionalInfo}`),t}var Xs=class{tools=new Map;constructor(e=[]){this.tools=new Map(e.map(e=>[e.name,e]))}has(e){return this.tools.has(e)}getToolOrThrow(e){let t=this.tools.get(e);if(!t)throw Error(`Tool ${e} not found`);return t}async invoke({toolName:e,rawArgs:t,toolContext:n}){let r=this.getToolOrThrow(e),i=r.handler,a=r.schema,o=r.outputSchema;try{let r=await a.safeParseAsync(t);if(r.error)throw new ps(`Tool ${e} returned invalid input: ${ye(r.error)}`,`INVALID_ARGUMENTS`,!0,`Please check the arguments and try again.`);let s=r.data,c=await i(s,n),l=await o.safeParseAsync(c);if(l.error){let t=ye(l.error);throw Error(`Tool ${e} returned invalid output: ${t}`)}return{tool_name:e,result:l.data,error:null}}catch(n){return n instanceof ps?{tool_name:e,result:null,error:n.toStructuredString()}:{tool_name:e,result:null,error:new ps(n instanceof Error?n.message:String(n),`TOOL_ERROR`,!1,`Check the error message and try again with valid arguments.`,{args:t,errorType:n?.constructor?.name??typeof n}).toStructuredString()}}}getToolSchemas(e){return[...this.tools.values()].filter(t=>t.mode.includes(e)).map(e=>({name:e.name,description:Ys(e.description),parameters:me(e.schema),source:`frontend`,mode:e.mode}))}};ie([_()],Xs.prototype,`getToolSchemas`,null);var Zs=new Xs([new Fs,new Js]);function Qs(e,t){let n=[`Code:\n${e.cellCode}`];if(e.tracebackHtml&&n.push(`Traceback:\n${le(e.tracebackHtml)}`),e.errorData.length>0&&n.push(e.errorData.map(e=>Rt(e)).join(`
|
|
50
50
|
|
|
51
51
|
`)),e.errorData.some(e=>e.type===`sql-error`)){let r=vt(e.cellId,t);r&&n.push(`Database schema:\n${r}`)}return n.join(`
|
|
52
52
|
|
|
53
|
-
`)}function $s(e,t){return yt({type:`error`,data:{name:e.cellName||`Cell ${e.cellId}`,cellId:e.cellId},details:Qs(e,t)})}function ec(e){return e.errorData.length===1?zt(e.errorData[0]):e.errorData.length>1?`${e.errorData.length} errors`:e.tracebackHtml?
|
|
54
|
-
`).find(e=>e.trim())?.trim()||`traceback`:`error`}function tc(e){return`Error: ${e.cellName||`Cell ${e.cellId}`}`}var nc=new
|
|
53
|
+
`)}function $s(e,t){return yt({type:`error`,data:{name:e.cellName||`Cell ${e.cellId}`,cellId:e.cellId},details:Qs(e,t)})}function ec(e){return e.errorData.length===1?zt(e.errorData[0]):e.errorData.length>1?`${e.errorData.length} errors`:e.tracebackHtml?le(e.tracebackHtml).trim().split(`
|
|
54
|
+
`).find(e=>e.trim())?.trim()||`traceback`:`error`}function tc(e){return`Error: ${e.cellName||`Cell ${e.cellId}`}`}var nc=new p(`error`,`errors`),rc=class extends bt{title=`Errors`;mentionPrefix=`@`;contextType=`error`;store;constructor(e){super(),this.store=e}getItems(){let e=Lt(this.store);if(e.length===0)return[];let t=[{uri:this.asURI(`all`),name:`Errors`,type:this.contextType,data:{type:`all-errors`,errors:e},description:`All errors in the notebook`}];for(let n of e)t.push({uri:this.asURI(n.cellId),name:tc(n),type:this.contextType,data:{type:`cell-error`,error:n},description:ec(n)});return t}formatCompletion(e){if(e.data.type===`all-errors`){let t=e.data.errors.length;return{label:`@Errors`,displayLabel:`Errors`,detail:`${t} ${nc.pluralize(t)}`,type:`error`,apply:`@error://all`,section:ht.ERROR,info:()=>{let e=document.createElement(`div`);e.classList.add(`mo-cm-tooltip`,`docs-documentation`,`min-w-[200px]`,`flex`,`flex-col`,`gap-1`,`p-2`);let n=document.createElement(`div`);n.classList.add(`flex`,`flex-col`,`gap-1`);let r=document.createElement(`div`);r.classList.add(`font-bold`,`text-base`),r.textContent=`Errors`,n.append(r);let i=document.createElement(`div`);return i.classList.add(`text-sm`,`text-muted-foreground`),i.textContent=`${t} ${nc.pluralize(t)}`,n.append(i),e.append(n),e}}}if(e.data.type===`cell-error`){let{error:t}=e.data;return{...this.createBasicCompletion(e,{detail:ec(t),type:`error`}),section:ht.ERROR}}return{label:`Error`,displayLabel:`Error`,section:ht.ERROR}}formatContext(e){return(e.data.type===`all-errors`?e.data.errors:[e.data.error]).map(e=>$s(e,this.store)).join(`
|
|
55
55
|
|
|
56
|
-
`)}},ic=
|
|
57
|
-
`;for(let e of n){let t=` ${e.name} (${e.type})`;if(e.sample_values&&e.sample_values.length>0){let n=e.sample_values.slice(0,3).map(e=>e===null?`null`:String(e)).join(`, `);t+=` - samples: [${n}]`}l+=`${t}\n`}}return yt({type:this.contextType,data:{name:o,source:r??`unknown`},details:l.trim()})}formatCompletion(e){let t=e.data.name,n=e.data;return{label:`@${t}`,displayLabel:t,detail:n.source===`memory`?`in-memory`:n.source,boost:n.source_type===`local`?_t.LOCAL_TABLE:_t.REMOTE_TABLE,type:
|
|
58
|
-
`)}async function kc(e){let t=await vc({input:Oc(e.flatMap(e=>e.parts))});function n(e,n){return n?{...e,parts:[...e.parts,...t.attachments]}:e}return{...t.body,uiMessages:e.map((t,r)=>n(t,r===e.length-1))}}async function Ac({invokeAiTool:e,addToolOutput:t,toolCall:n,toolContext:r}){try{if(Zs.has(n.toolName)){let e=await Zs.invoke({toolName:n.toolName,rawArgs:n.input,toolContext:r});t({tool:n.toolName,toolCallId:n.toolCallId,output:e.result||e.error})}else{let r=await e({toolName:n.toolName,arguments:n.input??{}});t({tool:n.toolName,toolCallId:n.toolCallId,output:r.result||r.error})}}catch(e){N.error(`Tool call failed:`,e),t({tool:n.toolName,toolCallId:n.toolCallId,output:`Error: ${e instanceof Error?e.message:String(e)}`})}}function jc(e){let t=e.at(-1);if(!t||t.role!==`assistant`)return!1;let n=t.parts.at(-1);return!n||!Co(n)?!1:Lo({messages:e})||Io({messages:e})||n.state===`output-denied`&&!n.providerExecuted}function Mc(e){let t=e.at(-1);return!t||t.role!==`assistant`?!1:t.parts.some(e=>Co(e)&&Nc(e.state))}function Nc(e){switch(e){case`approval-requested`:case`input-streaming`:case`input-available`:return!0;case`approval-responded`:case`output-available`:case`output-error`:case`output-denied`:return!1;default:return e}}function Pc(){let e=(0,P.c)(7),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0];let[n,r]=(0,Z.useState)(t),i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=e=>{if(e.length!==0){if(e.reduce(Fc,0)>wc){wt({title:`File size exceeded`,description:`Attachments must be under 50 MB`,variant:`danger`});return}r(t=>[...t,...e])}},e[1]=i):i=e[1];let a=c(i),o;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>r([]),e[2]=o):o=e[2];let s=o,l;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(l=e=>r(t=>t.filter(t=>t!==e)),e[3]=l):l=e[3];let u=l,d;return e[4]!==a||e[5]!==n?(d={files:n,addFiles:a,clearFiles:s,removeFile:u},e[4]=a,e[5]=n,e[6]=d):d=e[6],d}function Fc(e,t){return e+t.size}function Ic(e){return e.isError?!1:e.isAbort?!0:!e.hasPendingToolCalls&&!e.hasUnresolvedToolCalls}function Lc(){let[e,t]=(0,Z.useState)([]),n=(0,Z.useRef)([]),r=(0,Z.useRef)(!1);return n.current=e,r.current=e.length>0,{messages:e,enqueue:c(e=>{t(t=>{let i=[...t,{id:Ct(),parts:e}];return n.current=i,r.current=!0,i})}),flushNext:c(e=>{let i=n.current;if(i.length===0)return;let[a,...o]=i;n.current=o,r.current=o.length>0,t(o),e(a.parts)}),clear:c(()=>{n.current=[],r.current=!1,t([])}),hasQueuedRef:r}}var Rc=e=>{let t=(0,P.c)(6),{attachment:n}=e;if(n.mediaType?.startsWith(`image/`)){let e=n.filename||`Attachment`,r;return t[0]!==n.url||t[1]!==e?(r=(0,Q.jsx)(`img`,{src:n.url,alt:e,className:`max-h-[100px] max-w-[100px] object-contain mb-1.5`}),t[0]=n.url,t[1]=e,t[2]=r):r=t[2],r}let r;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Q.jsx)(lt,{className:`h-3 w-3 mt-0.5`}),t[3]=r):r=t[3];let i=n.filename||`Attachment`,a;return t[4]===i?a=t[5]:(a=(0,Q.jsxs)(`div`,{className:`flex flex-row gap-1 items-center text-xs`,children:[r,i]}),t[4]=i,t[5]=a),a},zc=e=>{let t=(0,P.c)(12),{file:n,className:r,onRemove:i}=e,[a,o]=(0,Z.useState)(!1),s;t[0]===r?s=t[1]:(s=Ae(`py-1 px-1.5 bg-muted rounded-md cursor-pointer flex flex-row gap-1 items-center text-xs`,r),t[0]=r,t[1]=s);let c,l;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>o(!0),l=()=>o(!1),t[2]=c,t[3]=l):(c=t[2],l=t[3]);let u;t[4]!==n||t[5]!==a||t[6]!==i?(u=a?(0,Q.jsx)(ot,{className:`h-3 w-3 mt-0.5`,onClick:i}):Uc(n),t[4]=n,t[5]=a,t[6]=i,t[7]=u):u=t[7];let d;return t[8]!==n.name||t[9]!==s||t[10]!==u?(d=(0,Q.jsxs)(`div`,{className:s,onMouseEnter:c,onMouseLeave:l,children:[u,n.name]}),t[8]=n.name,t[9]=s,t[10]=u,t[11]=d):d=t[11],d},Bc=e=>{let t=(0,P.c)(12),{isLoading:n,onStop:r,onSendClick:i,isEmpty:a,showStopLabel:o}=e,s=o!==void 0&&o,c;t[0]===s?c=t[1]:(c=s?(0,Q.jsxs)(`div`,{className:`flex flex-row items-center gap-1 px-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-error`,children:`Stop`}),(0,Q.jsx)(dt,{size:`small`})]}):(0,Q.jsx)(Bt,{className:`size-4 text-error`}),t[0]=s,t[1]=c);let l=c,u=n?`Stop`:`Submit`,d=n?r:i,f=!n&&a,p;t[2]!==n||t[3]!==l?(p=n?l:(0,Q.jsx)(Ht,{className:`h-3.5 w-3.5`}),t[2]=n,t[3]=l,t[4]=p):p=t[4];let m;t[5]!==d||t[6]!==f||t[7]!==p?(m=(0,Q.jsx)(Re,{variant:`text`,size:`sm`,className:`h-6 min-w-6 p-0 hover:bg-muted/30 cursor-pointer`,onClick:d,disabled:f,children:p}),t[5]=d,t[6]=f,t[7]=p,t[8]=m):m=t[8];let h;return t[9]!==u||t[10]!==m?(h=(0,Q.jsx)(Le,{content:u,children:m}),t[9]=u,t[10]=m,t[11]=h):h=t[11],h},Vc=e=>{let t=(0,P.c)(4),{handleAddContext:n,isLoading:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Q.jsx)(it,{className:`h-3.5 w-3.5`}),t[0]=i):i=t[0];let a;return t[1]!==n||t[2]!==r?(a=(0,Q.jsx)(Le,{content:`Add context`,children:(0,Q.jsx)(Re,{variant:`text`,size:`icon`,onClick:n,disabled:r,children:i})}),t[1]=n,t[2]=r,t[3]=a):a=t[3],a},Hc=e=>{let t=(0,P.c)(15),{fileInputRef:n,isLoading:r,onAddFiles:i}=e,a;t[0]===n?a=t[1]:(a=()=>n.current?.click(),t[0]=n,t[1]=a);let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Q.jsx)(Vt,{className:`h-3.5 w-3.5`}),t[2]=o):o=t[2];let s;t[3]!==r||t[4]!==a?(s=(0,Q.jsx)(Le,{content:`Attach a file`,children:(0,Q.jsx)(Re,{variant:`text`,size:`icon`,onClick:a,disabled:r,children:o})}),t[3]=r,t[4]=a,t[5]=s):s=t[5];let c;t[6]===i?c=t[7]:(c=e=>{e.target.files&&i([...e.target.files])},t[6]=i,t[7]=c);let l;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(l=Cc.join(`,`),t[8]=l):l=t[8];let u;t[9]!==n||t[10]!==c?(u=(0,Q.jsx)(mt,{ref:n,type:`file`,multiple:!0,hidden:!0,onChange:c,accept:l}),t[9]=n,t[10]=c,t[11]=u):u=t[11];let d;return t[12]!==s||t[13]!==u?(d=(0,Q.jsxs)(Q.Fragment,{children:[s,u]}),t[12]=s,t[13]=u,t[14]=d):d=t[14],d};function Uc(e){let t=`h-3 w-3 mt-0.5`;return e.type.startsWith(`image/`)?(0,Q.jsx)(ut,{className:t}):e.type.startsWith(`text/`)?(0,Q.jsx)(v,{className:t}):(0,Q.jsx)(lt,{className:t})}var Wc=e=>{let t=(0,P.c)(15),{icon:n,title:r,subtitle:i,href:a}=e,o;t[0]===r?o=t[1]:(o=(0,Q.jsx)(`span`,{className:`truncate font-medium`,children:r}),t[0]=r,t[1]=o);let s;t[2]===i?s=t[3]:(s=i&&(0,Q.jsxs)(`span`,{className:`truncate opacity-70`,children:[`(`,i,`)`]}),t[2]=i,t[3]=s);let c;t[4]!==n||t[5]!==o||t[6]!==s?(c=(0,Q.jsxs)(Q.Fragment,{children:[n,o,s]}),t[4]=n,t[5]=o,t[6]=s,t[7]=c):c=t[7];let l=c;if(a&&Tt(a)){let e=i??r,n;return t[8]!==l||t[9]!==a||t[10]!==e?(n=(0,Q.jsx)(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer`,title:e,className:`inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/50 px-2 py-1 my-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors`,children:l}),t[8]=l,t[9]=a,t[10]=e,t[11]=n):n=t[11],n}let u=i??r,d;return t[12]!==l||t[13]!==u?(d=(0,Q.jsx)(`div`,{className:`inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/50 px-2 py-1 my-1 text-xs text-muted-foreground`,title:u,children:l}),t[12]=l,t[13]=u,t[14]=d):d=t[14],d},Gc=Ue.define(),Kc=Be.define({create(){return new Map},update(e,t){let n=!1,r=e;for(let i of t.effects)if(i.is(Gc)){n||=(r=new Map(e),!0);for(let[e,t]of i.value)r.set(e,t)}return r}}),qc=Be.define({create(){return{onResourceClick:void 0,onResourceMouseOver:void 0,onResourceMouseOut:void 0,onPromptSubmit:void 0}},update(e){return e}}),Jc=Ue.define();Be.define({create(){return new Map},update(e,t){let n=!1,r=e;for(let i of t.effects)if(i.is(Jc)){n||=(r=new Map(e),!0);for(let[e,t]of i.value)r.set(e,t)}return r}});var Yc=(e,t)=>async n=>{let r=n.matchBefore(/@(\w+)?/);if(!r||r.from===r.to&&!n.explicit)return null;let i=await e();if(i.length===0)return null;let a=Gc.of(new Map(i.map(e=>[e.uri,e])));n.view&&n.view.dispatch({effects:a});let o=i.map(e=>({label:`@${e.name}`,displayLabel:e.name,detail:e.uri,info:e.description||void 0,type:e.mimeType?`constant`:`variable`,boost:e.description?100:0,...t?.(e),apply:(t,n,r,i)=>{t.dispatch({changes:{from:r,to:i,insert:`@${e.uri} `}})}}));return{from:r.from,options:o}},Xc=/@[\w-]+:\/\/(?!\/)[^\s]+/;function Zc(e){return e.matchAll(new RegExp(Xc.source,`g`))}var Qc=class extends Ge{resource;view;constructor(e,t){super(),this.resource=e,this.view=t}eq(e){return e.resource.uri===this.resource.uri}toDOM(){let e=document.createElement(`span`);e.className=`cm-resource-widget`,e.textContent=`@${this.resource.name}`;let t=this.view.state.field(qc,!1),n=t?.onResourceClick,r=t?.onResourceMouseOver,i=t?.onResourceMouseOut;return n&&(e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(this.resource)})),r&&e.addEventListener(`mouseover`,e=>{e.preventDefault(),e.stopPropagation(),r(this.resource)}),i&&e.addEventListener(`mouseout`,e=>{e.preventDefault(),e.stopPropagation(),i(this.resource)}),e}},$c=class extends Ge{uri;view;constructor(e,t){super(),this.uri=e,this.view=t}eq(e){return e.uri===this.uri}toDOM(){let e=document.createElement(`span`);return e.className=`cm-not-found-resource-widget`,e.textContent=`@${this.uri.split(`://`)[1]??this.uri}`,e}};function el(e){let t=e.state.field(Kc),n=[];for(let{from:r,to:i}of e.visibleRanges){let a=e.state.doc.sliceString(r,i);for(let i of Zc(a)){let a=r+i.index,o=i[0].slice(1),s=t.get(o);s?n.push(We.replace({widget:new Qc(s,e)}).range(a,a+i[0].length)):n.push(We.replace({widget:new $c(o,e)}).range(a,a+i[0].length))}}return We.set(n)}var tl=Ye.fromClass(class{decorations;constructor(e){this.decorations=el(e)}update(e){(e.docChanged||e.viewportChanged||e.transactions.some(e=>e.effects.some(e=>e.is(Gc))))&&(this.decorations=el(e.view))}},{decorations:e=>e.decorations});function nl(e){let t=document.createElement(`div`);t.className=`cm-tooltip-cursor`;let n=document.createElement(`div`);if(n.className=`cm-tooltip-cursor-title`,n.textContent=`${e.name} (${e.uri})`,t.appendChild(n),e.description){let n=document.createElement(`div`);n.className=`cm-tooltip-cursor-description`,n.textContent=e.description,t.appendChild(n)}if(e.mimeType){let n=document.createElement(`div`);n.className=`cm-tooltip-cursor-mimetype`,n.textContent=e.mimeType,t.appendChild(n)}return{dom:t}}function rl(e,t,n,r=0){for(let i of Zc(e)){let e=r+i.index,a=e+i[0].length;if(t>=e&&t<=a){let t=i[0].slice(1),r=n.get(t);if(r)return{resource:r,start:e,end:a}}}return null}function il(e){return Xe((t,n)=>{let{from:r,text:i}=t.state.doc.lineAt(n),a=rl(i,n,t.state.field(Kc),r);return a?{pos:a.start,end:a.end,above:!0,create(){return(e.createTooltip??nl)(a.resource)}}:null})}function al(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));if(o.length===0)return null;for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(t===a&&n.has(o))return{from:r,to:a,uri:o}}return null}function ol(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t).to,a=r.sliceString(t,i),o=Array.from(Zc(a));if(o.length===0)return null;let s=o[0];if(!s||s.index!==0)return null;let c=t,l=t+s[0].length,u=s[0].slice(1);return n.has(u)?{from:c,to:l,uri:u}:null}function sl(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(t>r&&t<a&&n.has(o))return{from:r,to:a,uri:o}}return null}function cl(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,t),o=Array.from(Zc(a)),s=null;for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);n.has(o)&&a<=t&&(t>a?s=a:t===a&&(s=r))}return s}function ll(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(n.has(o)&&r>=t){if(t<r)return r;if(t===r)return a}}return null}var ul=He.transactionFilter.of(e=>{let t=e.annotation(Ke.userEvent);if(!t)return e;let n=e.startState.selection.main;if(!n.empty)return e;if(t===`input.type`||t.startsWith(`input`)){if(e.changes.empty)return e;let t=e.startState.field(Kc),n=e.startState.doc,r=!1,i=0,a=[];if(e.changes.iterChanges((e,o,s,c,l)=>{let u=l.toString(),d=e;if(/^\s+$/.test(u)){a.push({from:e,to:o,insert:u});return}let f=n.lineAt(d),p=n.sliceString(f.from,f.to),m=Array.from(Zc(p)),h=!1,g=!1;for(let e of m){let r=f.from+e.index,i=r+e[0].length,a=e[0].slice(1);if(t.has(a)){if(d===r){let e=d>0?n.sliceString(d-1,d):``;e!==``&&e!==` `&&e!==`
|
|
56
|
+
`)}},ic=g(),ac={maxDepth:3,maxResults:20,defaultResultsLimit:5,includeDirectories:!1},oc=class extends bt{title=`Files`;mentionPrefix=`#`;contextType=`file`;apiRequests;config;constructor(e,t=ac){super(),this.apiRequests=e,this.config=t}createCompletionSource(){return async e=>{let t=e.matchBefore(/#[^\s#]*/);if(!t)return null;let n=t.text;if(!n.startsWith(`#`))return null;let r=n.slice(1);if(r.length===0)return this.getDefaultCompletions(t);try{let e=(await this.searchFiles(r)||[]).map(e=>{let t={uri:this.asURI(e.path),name:e.name,type:this.contextType,description:e.isDirectory?`Directory`:`File`,data:{path:e.path,isDirectory:e.isDirectory}};return this.formatCompletion(t)});return{from:t.from,options:e}}catch(e){return N.error(`Failed to search files:`,e),null}}}searchFiles=async(e,t={})=>{let{maxDepth:n,maxResults:r,includeDirectories:i}={...this.config,...t};return(await this.apiRequests.sendSearchFiles({query:e,includeFiles:!0,includeDirectories:i,depth:n,limit:r})).files};async getDefaultCompletions(e){try{for(let t of[`py`,`md`,`csv`])try{let n=await this.searchFiles(t,{maxDepth:1,maxResults:5});if(n&&n.length>0){let t=n.map(e=>{let t={uri:this.asURI(e.path),name:e.name,type:this.contextType,description:e.isDirectory?`Directory`:`File`,data:{path:e.path,isDirectory:e.isDirectory}};return this.formatCompletion(t)});return{from:e.from,options:t}}}catch(e){N.error(`Failed to get default file completions:`,e)}return{from:e.from,options:[]}}catch(e){return N.error(`Failed to get default file completions:`,e),null}}getItems(){return[]}formatCompletion(e){let{data:t,name:n}=e,r=t.isDirectory?`📁`:`📄`;return{...this.createBasicCompletion(e),type:`file`,section:ht.FILE,boost:t.isDirectory?_t.MEDIUM:_t.LOW,detail:t.path,displayLabel:`${r} ${n}`,apply:async(e,r,i,a)=>{let o=e.state.facet(ic)?.addAttachment;if(!o){N.warn(`No addAttachment callback provided`);return}let s=await this.apiRequests.sendFileDetails({path:t.path}).catch(e=>(wt({title:`Failed to get file details`,description:e.message}),null));if(!s)return;let c=s.mimeType||`text/plain`,l=Ot({contents:s.contents??``,mimeType:c,isBase64:s.isBase64??!1});o(new File([l],n,{type:c})),e.dispatch({changes:{from:i,to:a,insert:``}}),et(e)},info:()=>{let e=document.createElement(`div`);e.classList.add(`flex`,`flex-col`,`gap-1`,`p-2`);let r=document.createElement(`div`);r.classList.add(`font-bold`),r.textContent=n,e.append(r);let i=document.createElement(`div`);return i.classList.add(`text-xs`,`text-muted-foreground`),i.textContent=t.path,e.append(i),e}}}formatContext(e){let{data:t,name:n}=e;return yt({type:this.contextType,data:{name:n,path:t.path,isDirectory:t.isDirectory},details:t.isDirectory?`Directory containing files and subdirectories`:`File`})}},sc=class extends bt{title=`Tables`;mentionPrefix=`@`;contextType=`data`;tablesMap;constructor(e){super(),this.tablesMap=e}getItems(){return[...this.tablesMap.entries()].map(([e,t])=>({uri:this.asURI(e),name:e,type:this.contextType,description:t.source===`memory`?`in-memory`:t.source,data:t}))}formatContext(e){let{data:t}=e,{columns:n,source:r,num_rows:i,num_columns:a,name:o,variable_name:s}=t,c=[i==null?void 0:`${i} rows`,a==null?void 0:`${a} columns`].filter(Boolean).join(`, `),l=``;if(c&&(l+=`Shape: ${c}\n`),s&&(l+=`Variable: ${s}\n`),n&&n.length>0){l+=`Columns:
|
|
57
|
+
`;for(let e of n){let t=` ${e.name} (${e.type})`;if(e.sample_values&&e.sample_values.length>0){let n=e.sample_values.slice(0,3).map(e=>e===null?`null`:String(e)).join(`, `);t+=` - samples: [${n}]`}l+=`${t}\n`}}return yt({type:this.contextType,data:{name:o,source:r??`unknown`},details:l.trim()})}formatCompletion(e){let t=e.data.name,n=e.data;return{label:`@${t}`,displayLabel:t,detail:n.source===`memory`?`in-memory`:n.source,boost:n.source_type===`local`?_t.LOCAL_TABLE:_t.REMOTE_TABLE,type:ae(n),apply:`@${t}`,section:{name:ae(n)===`dataframe`?`Dataframe`:`Table`,rank:ht.TABLE.rank},info:()=>this.createTableInfoElement(t,n)}}createTableInfoElement(e,t){let n=document.createElement(`div`);n.classList.add(`mo-cm-tooltip`,`docs-documentation`,`min-w-[200px]`,`flex`,`flex-col`,`gap-1`,`p-2`);let r=document.createElement(`div`);r.classList.add(`flex`,`flex-col`,`gap-1`);let i=document.createElement(`div`);if(i.classList.add(`font-bold`,`text-base`),i.textContent=e,r.append(i),t.source){let e=document.createElement(`div`);e.classList.add(`text-xs`,`text-muted-foreground`),e.textContent=`Source: ${t.source}`,r.append(e)}n.append(r);let a=[t.num_rows==null?void 0:`${t.num_rows} rows`,t.num_columns==null?void 0:`${t.num_columns} columns`].filter(Boolean).join(`, `);if(a){let e=document.createElement(`div`);e.classList.add(`text-xs`,`bg-muted`,`px-2`,`py-1`,`rounded`),e.textContent=a,n.append(e)}if(t.columns&&t.columns.length>0){let e=document.createElement(`div`);e.classList.add(`overflow-auto`,`max-h-60`);let r=document.createElement(`table`);r.classList.add(`w-full`,`text-xs`,`border-collapse`);let i=r.insertRow();i.classList.add(`bg-muted`);let a=i.insertCell();a.classList.add(`p-2`,`font-medium`,`text-left`),a.textContent=`Column`;let o=i.insertCell();o.classList.add(`p-2`,`font-medium`,`text-left`),o.textContent=`Type`;let s=t.columns.some(e=>this.getItemMetadata(t,e)!==void 0),c;s&&(c=i.insertCell(),c.classList.add(`p-2`,`font-medium`,`text-left`),c.textContent=`Metadata`),t.columns.forEach((e,n)=>{let i=r.insertRow();i.classList.add(n%2==0?`bg-background`:`bg-muted/30`);let a=i.insertCell();a.classList.add(`p-2`,`font-mono`),a.textContent=e.name;let o=i.insertCell();if(o.classList.add(`p-2`,`text-muted-foreground`),o.textContent=e.type,s){let n=i.insertCell();n.classList.add(`p-2`);let r=this.getItemMetadata(t,e);r&&n.append(r)}}),e.append(r),n.append(e)}return n}getItemMetadata(e,t){let n=e.primary_keys?.includes(t.name),r=e.indexes?.includes(t.name);if(n||r){let e=document.createElement(`span`);e.textContent=n?`PK`:`IDX`;let t=n?`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`:`bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200`;return e.classList.add(`text-xs`,`px-1.5`,`py-0.5`,`rounded-full`,`font-medium`,...t.split(` `)),e}}},cc=class extends bt{title=`Variables`;mentionPrefix=`@`;contextType=`variable`;variables;tablesMap;constructor(e,t){super(),this.variables=e,this.tablesMap=t}getItems(){let e=new Set(this.tablesMap.keys());return Object.entries(this.variables).flatMap(([t,n])=>e.has(t)?[]:[{uri:this.asURI(t),name:t,type:this.contextType,description:n.dataType??``,dataType:n.dataType,data:{variable:n}}])}formatCompletion(e){let{data:t}=e,{variable:n}=t;return{label:`@${n.name}`,displayLabel:n.name,detail:n.dataType??``,type:this.contextType,section:ht.VARIABLE,info:()=>te(n)}}formatContext(e){let{data:t}=e,{variable:n}=t;return yt({type:this.contextType,data:{name:n.name,dataType:n.dataType},details:n.value==null?void 0:JSON.stringify(n.value)})}};function lc(e){let t=e.get(se),n=e.get(re),r=e.get(ee);return new gt().register(new sc(n)).register(new cc(r,n)).register(new rc(e)).register(new Ls(e)).register(new xt(t.connectionsMap,n))}function uc(){return new oc(nt())}function dc({input:e}){let t=``;return e.includes(`@`)&&(t=yc(e),N.debug(`Included context`,t)),{includeOtherCode:ce(``),context:{plainText:t,schema:[],variables:[]}}}var fc=`data-marimo-context`,pc={marimo:{source:`context`}};function mc(e){return e.type===`file`&&e.providerMetadata?.marimo?.source===pc.marimo.source}function hc(e){return{...e,providerMetadata:{...e.providerMetadata,marimo:{...e.providerMetadata?.marimo,...pc.marimo}}}}async function gc(e){if(!e.includes(`@`))return{plainText:``,contextIds:[],attachments:[]};let t=lc(s),n=t.parseAllContextIds(e);if(n.length===0)return{plainText:``,contextIds:[],attachments:[]};let r=t.formatContextForAI(n),i=[];try{i=(await t.getAttachmentsForContext(n)).map(hc)}catch(e){N.error(`Error getting attachments:`,e)}return{plainText:r,contextIds:n,attachments:i}}async function _c(e){let{plainText:t,contextIds:n,attachments:r}=await gc(e),i=null;return t.trim()&&(i={type:fc,data:{plainText:t,contextIds:n.map(String)}}),{contextPart:i,attachments:r}}async function vc({input:e}){let{plainText:t,attachments:n}=await gc(e);return{body:{includeOtherCode:ce(``),context:{plainText:t,schema:[],variables:[]}},attachments:n}}function yc(e){let t=lc(s),n=t.parseAllContextIds(e);return t.formatContextForAI(n)}function bc(e,t=[]){return n=>{let r=e.map(e=>n.matchBefore(e)).find(Boolean);return!r||r&&r.from===r.to&&!n.explicit?null:{from:r?.from,options:[...t]}}}function xc(e){if(e.current?.view){let t=e.current.view.state.selection.main.from;e.current.view.dispatch({changes:{from:t,to:t,insert:`@`},selection:{anchor:t+1,head:t+1}}),e.current.view.focus(),Qe(e.current.view)}}var Sc=new Set([`openai`,`google`,`anthropic`]),Cc=[`image/*`,`text/*`],wc=52428800;function Tc(e){return e.length>50?`${e.slice(0,50)}...`:e}async function Ec(e){return await Promise.all(e.map(async e=>({type:`file`,mediaType:e.type,filename:e.name,url:await at(e,`dataUrl`)})))}function Dc(e){if(e.length===0)return!1;let t=e.at(-1);if(!t||t.role!==`assistant`||!t.parts)return!1;let n=t.parts;return n.length!==0&&n[n.length-1].type===`reasoning`}function Oc(e){return e.map(e=>e.type===`text`?e.text:``).join(`
|
|
58
|
+
`)}async function kc(e){let t=await vc({input:Oc(e.flatMap(e=>e.parts))});function n(e,n){return n?{...e,parts:[...e.parts,...t.attachments]}:e}return{...t.body,uiMessages:e.map((t,r)=>n(t,r===e.length-1))}}async function Ac({invokeAiTool:e,addToolOutput:t,toolCall:n,toolContext:r}){try{if(Zs.has(n.toolName)){let e=await Zs.invoke({toolName:n.toolName,rawArgs:n.input,toolContext:r});t({tool:n.toolName,toolCallId:n.toolCallId,output:e.result||e.error})}else{let r=await e({toolName:n.toolName,arguments:n.input??{}});t({tool:n.toolName,toolCallId:n.toolCallId,output:r.result||r.error})}}catch(e){N.error(`Tool call failed:`,e),t({tool:n.toolName,toolCallId:n.toolCallId,output:`Error: ${e instanceof Error?e.message:String(e)}`})}}function jc(e){let t=e.at(-1);if(!t||t.role!==`assistant`)return!1;let n=t.parts.at(-1);return!n||!Co(n)?!1:Lo({messages:e})||Io({messages:e})||n.state===`output-denied`&&!n.providerExecuted}function Mc(e){let t=e.at(-1);return!t||t.role!==`assistant`?!1:t.parts.some(e=>Co(e)&&Nc(e.state))}function Nc(e){switch(e){case`approval-requested`:case`input-streaming`:case`input-available`:return!0;case`approval-responded`:case`output-available`:case`output-error`:case`output-denied`:return!1;default:return e}}function Pc(){let e=(0,P.c)(7),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0];let[n,r]=(0,Z.useState)(t),i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=e=>{if(e.length!==0){if(e.reduce(Fc,0)>wc){wt({title:`File size exceeded`,description:`Attachments must be under 50 MB`,variant:`danger`});return}r(t=>[...t,...e])}},e[1]=i):i=e[1];let a=c(i),o;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>r([]),e[2]=o):o=e[2];let s=o,l;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(l=e=>r(t=>t.filter(t=>t!==e)),e[3]=l):l=e[3];let u=l,d;return e[4]!==a||e[5]!==n?(d={files:n,addFiles:a,clearFiles:s,removeFile:u},e[4]=a,e[5]=n,e[6]=d):d=e[6],d}function Fc(e,t){return e+t.size}function Ic(e){return e.isError?!1:e.isAbort?!0:!e.hasPendingToolCalls&&!e.hasUnresolvedToolCalls}function Lc(){let[e,t]=(0,Z.useState)([]),n=(0,Z.useRef)([]),r=(0,Z.useRef)(!1);return n.current=e,r.current=e.length>0,{messages:e,enqueue:c(e=>{t(t=>{let i=[...t,{id:Ct(),parts:e}];return n.current=i,r.current=!0,i})}),flushNext:c(e=>{let i=n.current;if(i.length===0)return;let[a,...o]=i;n.current=o,r.current=o.length>0,t(o),e(a.parts)}),clear:c(()=>{n.current=[],r.current=!1,t([])}),hasQueuedRef:r}}var Rc=e=>{let t=(0,P.c)(6),{attachment:n}=e;if(n.mediaType?.startsWith(`image/`)){let e=n.filename||`Attachment`,r;return t[0]!==n.url||t[1]!==e?(r=(0,Q.jsx)(`img`,{src:n.url,alt:e,className:`max-h-[100px] max-w-[100px] object-contain mb-1.5`}),t[0]=n.url,t[1]=e,t[2]=r):r=t[2],r}let r;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Q.jsx)(lt,{className:`h-3 w-3 mt-0.5`}),t[3]=r):r=t[3];let i=n.filename||`Attachment`,a;return t[4]===i?a=t[5]:(a=(0,Q.jsxs)(`div`,{className:`flex flex-row gap-1 items-center text-xs`,children:[r,i]}),t[4]=i,t[5]=a),a},zc=e=>{let t=(0,P.c)(12),{file:n,className:r,onRemove:i}=e,[a,o]=(0,Z.useState)(!1),s;t[0]===r?s=t[1]:(s=Ae(`py-1 px-1.5 bg-muted rounded-md cursor-pointer flex flex-row gap-1 items-center text-xs`,r),t[0]=r,t[1]=s);let c,l;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>o(!0),l=()=>o(!1),t[2]=c,t[3]=l):(c=t[2],l=t[3]);let u;t[4]!==n||t[5]!==a||t[6]!==i?(u=a?(0,Q.jsx)(ot,{className:`h-3 w-3 mt-0.5`,onClick:i}):Uc(n),t[4]=n,t[5]=a,t[6]=i,t[7]=u):u=t[7];let d;return t[8]!==n.name||t[9]!==s||t[10]!==u?(d=(0,Q.jsxs)(`div`,{className:s,onMouseEnter:c,onMouseLeave:l,children:[u,n.name]}),t[8]=n.name,t[9]=s,t[10]=u,t[11]=d):d=t[11],d},Bc=e=>{let t=(0,P.c)(12),{isLoading:n,onStop:r,onSendClick:i,isEmpty:a,showStopLabel:o}=e,s=o!==void 0&&o,c;t[0]===s?c=t[1]:(c=s?(0,Q.jsxs)(`div`,{className:`flex flex-row items-center gap-1 px-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-error`,children:`Stop`}),(0,Q.jsx)(dt,{size:`small`})]}):(0,Q.jsx)(Bt,{className:`size-4 text-error`}),t[0]=s,t[1]=c);let l=c,u=n?`Stop`:`Submit`,d=n?r:i,f=!n&&a,p;t[2]!==n||t[3]!==l?(p=n?l:(0,Q.jsx)(Ht,{className:`h-3.5 w-3.5`}),t[2]=n,t[3]=l,t[4]=p):p=t[4];let m;t[5]!==d||t[6]!==f||t[7]!==p?(m=(0,Q.jsx)(Re,{variant:`text`,size:`sm`,className:`h-6 min-w-6 p-0 hover:bg-muted/30 cursor-pointer`,onClick:d,disabled:f,children:p}),t[5]=d,t[6]=f,t[7]=p,t[8]=m):m=t[8];let h;return t[9]!==u||t[10]!==m?(h=(0,Q.jsx)(Le,{content:u,children:m}),t[9]=u,t[10]=m,t[11]=h):h=t[11],h},Vc=e=>{let t=(0,P.c)(4),{handleAddContext:n,isLoading:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Q.jsx)(it,{className:`h-3.5 w-3.5`}),t[0]=i):i=t[0];let a;return t[1]!==n||t[2]!==r?(a=(0,Q.jsx)(Le,{content:`Add context`,children:(0,Q.jsx)(Re,{variant:`text`,size:`icon`,onClick:n,disabled:r,children:i})}),t[1]=n,t[2]=r,t[3]=a):a=t[3],a},Hc=e=>{let t=(0,P.c)(15),{fileInputRef:n,isLoading:r,onAddFiles:i}=e,a;t[0]===n?a=t[1]:(a=()=>n.current?.click(),t[0]=n,t[1]=a);let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Q.jsx)(Vt,{className:`h-3.5 w-3.5`}),t[2]=o):o=t[2];let s;t[3]!==r||t[4]!==a?(s=(0,Q.jsx)(Le,{content:`Attach a file`,children:(0,Q.jsx)(Re,{variant:`text`,size:`icon`,onClick:a,disabled:r,children:o})}),t[3]=r,t[4]=a,t[5]=s):s=t[5];let c;t[6]===i?c=t[7]:(c=e=>{e.target.files&&i([...e.target.files])},t[6]=i,t[7]=c);let l;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(l=Cc.join(`,`),t[8]=l):l=t[8];let u;t[9]!==n||t[10]!==c?(u=(0,Q.jsx)(mt,{ref:n,type:`file`,multiple:!0,hidden:!0,onChange:c,accept:l}),t[9]=n,t[10]=c,t[11]=u):u=t[11];let d;return t[12]!==s||t[13]!==u?(d=(0,Q.jsxs)(Q.Fragment,{children:[s,u]}),t[12]=s,t[13]=u,t[14]=d):d=t[14],d};function Uc(e){let t=`h-3 w-3 mt-0.5`;return e.type.startsWith(`image/`)?(0,Q.jsx)(ut,{className:t}):e.type.startsWith(`text/`)?(0,Q.jsx)(u,{className:t}):(0,Q.jsx)(lt,{className:t})}var Wc=e=>{let t=(0,P.c)(15),{icon:n,title:r,subtitle:i,href:a}=e,o;t[0]===r?o=t[1]:(o=(0,Q.jsx)(`span`,{className:`truncate font-medium`,children:r}),t[0]=r,t[1]=o);let s;t[2]===i?s=t[3]:(s=i&&(0,Q.jsxs)(`span`,{className:`truncate opacity-70`,children:[`(`,i,`)`]}),t[2]=i,t[3]=s);let c;t[4]!==n||t[5]!==o||t[6]!==s?(c=(0,Q.jsxs)(Q.Fragment,{children:[n,o,s]}),t[4]=n,t[5]=o,t[6]=s,t[7]=c):c=t[7];let l=c;if(a&&Tt(a)){let e=i??r,n;return t[8]!==l||t[9]!==a||t[10]!==e?(n=(0,Q.jsx)(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer`,title:e,className:`inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/50 px-2 py-1 my-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors`,children:l}),t[8]=l,t[9]=a,t[10]=e,t[11]=n):n=t[11],n}let u=i??r,d;return t[12]!==l||t[13]!==u?(d=(0,Q.jsx)(`div`,{className:`inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/50 px-2 py-1 my-1 text-xs text-muted-foreground`,title:u,children:l}),t[12]=l,t[13]=u,t[14]=d):d=t[14],d},Gc=Ue.define(),Kc=Be.define({create(){return new Map},update(e,t){let n=!1,r=e;for(let i of t.effects)if(i.is(Gc)){n||=(r=new Map(e),!0);for(let[e,t]of i.value)r.set(e,t)}return r}}),qc=Be.define({create(){return{onResourceClick:void 0,onResourceMouseOver:void 0,onResourceMouseOut:void 0,onPromptSubmit:void 0}},update(e){return e}}),Jc=Ue.define();Be.define({create(){return new Map},update(e,t){let n=!1,r=e;for(let i of t.effects)if(i.is(Jc)){n||=(r=new Map(e),!0);for(let[e,t]of i.value)r.set(e,t)}return r}});var Yc=(e,t)=>async n=>{let r=n.matchBefore(/@(\w+)?/);if(!r||r.from===r.to&&!n.explicit)return null;let i=await e();if(i.length===0)return null;let a=Gc.of(new Map(i.map(e=>[e.uri,e])));n.view&&n.view.dispatch({effects:a});let o=i.map(e=>({label:`@${e.name}`,displayLabel:e.name,detail:e.uri,info:e.description||void 0,type:e.mimeType?`constant`:`variable`,boost:e.description?100:0,...t?.(e),apply:(t,n,r,i)=>{t.dispatch({changes:{from:r,to:i,insert:`@${e.uri} `}})}}));return{from:r.from,options:o}},Xc=/@[\w-]+:\/\/(?!\/)[^\s]+/;function Zc(e){return e.matchAll(new RegExp(Xc.source,`g`))}var Qc=class extends Ge{resource;view;constructor(e,t){super(),this.resource=e,this.view=t}eq(e){return e.resource.uri===this.resource.uri}toDOM(){let e=document.createElement(`span`);e.className=`cm-resource-widget`,e.textContent=`@${this.resource.name}`;let t=this.view.state.field(qc,!1),n=t?.onResourceClick,r=t?.onResourceMouseOver,i=t?.onResourceMouseOut;return n&&(e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(this.resource)})),r&&e.addEventListener(`mouseover`,e=>{e.preventDefault(),e.stopPropagation(),r(this.resource)}),i&&e.addEventListener(`mouseout`,e=>{e.preventDefault(),e.stopPropagation(),i(this.resource)}),e}},$c=class extends Ge{uri;view;constructor(e,t){super(),this.uri=e,this.view=t}eq(e){return e.uri===this.uri}toDOM(){let e=document.createElement(`span`);return e.className=`cm-not-found-resource-widget`,e.textContent=`@${this.uri.split(`://`)[1]??this.uri}`,e}};function el(e){let t=e.state.field(Kc),n=[];for(let{from:r,to:i}of e.visibleRanges){let a=e.state.doc.sliceString(r,i);for(let i of Zc(a)){let a=r+i.index,o=i[0].slice(1),s=t.get(o);s?n.push(We.replace({widget:new Qc(s,e)}).range(a,a+i[0].length)):n.push(We.replace({widget:new $c(o,e)}).range(a,a+i[0].length))}}return We.set(n)}var tl=Ye.fromClass(class{decorations;constructor(e){this.decorations=el(e)}update(e){(e.docChanged||e.viewportChanged||e.transactions.some(e=>e.effects.some(e=>e.is(Gc))))&&(this.decorations=el(e.view))}},{decorations:e=>e.decorations});function nl(e){let t=document.createElement(`div`);t.className=`cm-tooltip-cursor`;let n=document.createElement(`div`);if(n.className=`cm-tooltip-cursor-title`,n.textContent=`${e.name} (${e.uri})`,t.appendChild(n),e.description){let n=document.createElement(`div`);n.className=`cm-tooltip-cursor-description`,n.textContent=e.description,t.appendChild(n)}if(e.mimeType){let n=document.createElement(`div`);n.className=`cm-tooltip-cursor-mimetype`,n.textContent=e.mimeType,t.appendChild(n)}return{dom:t}}function rl(e,t,n,r=0){for(let i of Zc(e)){let e=r+i.index,a=e+i[0].length;if(t>=e&&t<=a){let t=i[0].slice(1),r=n.get(t);if(r)return{resource:r,start:e,end:a}}}return null}function il(e){return Xe((t,n)=>{let{from:r,text:i}=t.state.doc.lineAt(n),a=rl(i,n,t.state.field(Kc),r);return a?{pos:a.start,end:a.end,above:!0,create(){return(e.createTooltip??nl)(a.resource)}}:null})}function al(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));if(o.length===0)return null;for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(t===a&&n.has(o))return{from:r,to:a,uri:o}}return null}function ol(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t).to,a=r.sliceString(t,i),o=Array.from(Zc(a));if(o.length===0)return null;let s=o[0];if(!s||s.index!==0)return null;let c=t,l=t+s[0].length,u=s[0].slice(1);return n.has(u)?{from:c,to:l,uri:u}:null}function sl(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(t>r&&t<a&&n.has(o))return{from:r,to:a,uri:o}}return null}function cl(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,t),o=Array.from(Zc(a)),s=null;for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);n.has(o)&&a<=t&&(t>a?s=a:t===a&&(s=r))}return s}function ll(e,t){let n=e.field(Kc),r=e.doc,i=r.lineAt(t),a=r.sliceString(i.from,i.to),o=Array.from(Zc(a));for(let e of o){let r=i.from+e.index,a=r+e[0].length,o=e[0].slice(1);if(n.has(o)&&r>=t){if(t<r)return r;if(t===r)return a}}return null}var ul=He.transactionFilter.of(e=>{let t=e.annotation(Ke.userEvent);if(!t)return e;let n=e.startState.selection.main;if(!n.empty)return e;if(t===`input.type`||t.startsWith(`input`)){if(e.changes.empty)return e;let t=e.startState.field(Kc),n=e.startState.doc,r=!1,i=0,a=[];if(e.changes.iterChanges((e,o,s,c,l)=>{let u=l.toString(),d=e;if(/^\s+$/.test(u)){a.push({from:e,to:o,insert:u});return}let f=n.lineAt(d),p=n.sliceString(f.from,f.to),m=Array.from(Zc(p)),h=!1,g=!1;for(let e of m){let r=f.from+e.index,i=r+e[0].length,a=e[0].slice(1);if(t.has(a)){if(d===r){let e=d>0?n.sliceString(d-1,d):``;e!==``&&e!==` `&&e!==`
|
|
59
59
|
`&&e!==` `&&(h=!0)}if(d===i){let e=d<n.length?n.sliceString(d,d+1):``;(e===``||e!==` `&&e!==`
|
|
60
60
|
`&&e!==` `)&&(g=!0)}}}let _=u;h&&(_=` ${_}`,i+=1),g&&(_=` ${_}`,i+=1),_!==u&&(r=!0),a.push({from:e,to:o,insert:_})}),r)return[{changes:a,selection:e.selection?{anchor:e.selection.main.anchor+i,head:e.selection.main.head+i}:void 0,scrollIntoView:e.scrollIntoView}]}if(t===`delete.backward`||t===`delete.forward`){let r=null;return t===`delete.backward`?r=al(e.startState,n.head):t===`delete.forward`&&(r=ol(e.startState,n.head)),r?[{changes:{from:r.from,to:r.to,insert:``},selection:{anchor:r.from},scrollIntoView:!0}]:e}if(e.selection?.main.empty&&n.empty&&!t.startsWith(`input`)&&t!==`input.type`){let t=n.head,r=e.selection.main.head,i=null;if(r<t){let n=sl(e.startState,t);i=n&&t>n.from?n.from:cl(e.startState,t)}else if(r>t){let n=sl(e.startState,t);i=n&&t<n.to?n.to:ll(e.startState,t)}if(i!==null&&i!==r)return[{selection:{anchor:i},scrollIntoView:!0}]}return e}),dl=150;function fl(e,t){let n=new Set;for(let r of Zc(e)){let e=r[0].slice(1);t.has(e)||n.add(e)}return[...n]}function pl(e){return[...e].sort().join(`
|
|
61
61
|
`)}function ml(e){return!Zc(e).next().done}function hl(e){let t=[],n=[];return e.changes.iterChanges((r,i,a,o)=>{let s=e.startState.doc.lineAt(r),c=e.startState.doc.lineAt(i===r?r:i-1);t.push(e.startState.doc.sliceString(s.from,c.to));let l=e.state.doc.lineAt(a),u=e.state.doc.lineAt(o===a?a:o-1);n.push(e.state.doc.sliceString(l.from,u.to))}),{before:t.join(`
|
|
@@ -72,5 +72,5 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
72
72
|
border-(--green-6) border hover:shadow-xs rounded px-3 ${o}`,y;t[24]===s?y=t[25]:(y=s&&(0,Q.jsx)(Pt,{className:`ml-1 inline`,shortcut:s}),t[24]=s,t[25]=y);let b;return t[26]!==n||t[27]!==r||t[28]!==p||t[29]!==v||t[30]!==y||t[31]!==_?(b=(0,Q.jsxs)(Re,{variant:`text`,size:p,disabled:n,onClick:r,className:v,children:[_,y]}),t[26]=n,t[27]=r,t[28]=p,t[29]=v,t[30]=y,t[31]=_,t[32]=b):b=t[32],b},kl=e=>{let t=(0,P.c)(9),{onDecline:n,disabled:r,multipleCompletions:i,size:a,className:o,declineShortcut:s,borderless:c,label:l}=e,u=r!==void 0&&r,d=i!==void 0&&i,f=a===void 0?`sm`:a,p=`h-6 text-(--red-10) bg-(--red-3)/60 hover:bg-(--red-3)
|
|
73
73
|
dark:bg-(--red-4)/80 dark:hover:bg-(--red-3) rounded px-3 font-semibold
|
|
74
74
|
active:bg-(--red-5) dark:active:bg-(--red-4)
|
|
75
|
-
border-(--red-6) border hover:shadow-xs ${c!==void 0&&c&&`border-none rounded-md`} ${o}`,m=l??`Reject${d?` all`:``}`,h;t[0]===s?h=t[1]:(h=s&&(0,Q.jsx)(Pt,{className:`ml-1 inline`,shortcut:s}),t[0]=s,t[1]=h);let g;return t[2]!==u||t[3]!==n||t[4]!==f||t[5]!==p||t[6]!==m||t[7]!==h?(g=(0,Q.jsxs)(Re,{variant:`text`,size:f,disabled:u,onClick:n,className:p,children:[m,h]}),t[2]=u,t[3]=n,t[4]=f,t[5]=p,t[6]=m,t[7]=h,t[8]=g):g=t[8],g},Al=class{activeAttempt=null;cancel(){this.activeAttempt&&(this.activeAttempt.cancelled=!0)}async run({prepare:e,submit:t,onError:n}){if(this.activeAttempt!==null)return;let r={cancelled:!1};this.activeAttempt=r;try{let n=await e();if(r.cancelled)return;await t(n)}catch(e){r.cancelled||n(e)}finally{this.activeAttempt=null}}},jl=
|
|
76
|
-
`},selection:{anchor:n+1,head:n+1}}),t.preventDefault(),t.stopPropagation(),!0}return!1}}])),t[12]=h,t[13]=
|
|
75
|
+
border-(--red-6) border hover:shadow-xs ${c!==void 0&&c&&`border-none rounded-md`} ${o}`,m=l??`Reject${d?` all`:``}`,h;t[0]===s?h=t[1]:(h=s&&(0,Q.jsx)(Pt,{className:`ml-1 inline`,shortcut:s}),t[0]=s,t[1]=h);let g;return t[2]!==u||t[3]!==n||t[4]!==f||t[5]!==p||t[6]!==m||t[7]!==h?(g=(0,Q.jsxs)(Re,{variant:`text`,size:f,disabled:u,onClick:n,className:p,children:[m,h]}),t[2]=u,t[3]=n,t[4]=f,t[5]=p,t[6]=m,t[7]=h,t[8]=g):g=t[8],g},Al=class{activeAttempt=null;cancel(){this.activeAttempt&&(this.activeAttempt.cancelled=!0)}async run({prepare:e,submit:t,onError:n}){if(this.activeAttempt!==null)return;let r={cancelled:!1};this.activeAttempt=r;try{let n=await e();if(r.cancelled)return;await t(n)}catch(e){r.cancelled||n(e)}finally{this.activeAttempt=null}}},jl=fe(`marimo:ai-language`,`python`,x),Ml=`marimo:ai-prompt-history`,Nl=new oe(E(w()),()=>[]),Pl=({onClose:e})=>{let t=i(),[n,a]=(0,Z.useState)(``),{acceptOwnedStagedCells:s,beginStagedCellGeneration:l,discardOwnedStagedCells:u,finishStagedCellGeneration:d,hasOwnedStagedCells:f,onData:p}=js(t),[m,h]=r(jl),g=ke(),_=(0,Z.useRef)(null),v=(0,Z.useRef)(new Al).current,b=(0,Z.useRef)(null),{files:x,addFiles:S,removeFile:ee}=Pc(),te=o(Te),ne=(0,Z.useMemo)(()=>new Po({api:g.getAiURL(`completion`).toString(),headers:()=>g.headers(),prepareSendMessagesRequest:async e=>{let t={...await kc(e.messages),code:``,prompt:``,language:m};return{api:g.getAiURL(`completion`).toString(),body:t}}}),[m,g]),re=c(e=>{d(!1),wt({title:`Generate with AI failed`,description:kt(e)})}),{sendMessage:ie,stop:ae,status:oe}=ns({throttle:100,transport:ne,onData:p,onError:re,onFinish:({isAbort:e,isDisconnect:t,isError:n,finishReason:r})=>{d(!e&&!t&&!n&&r===`stop`)}}),se=oe===`streaming`||oe===`submitted`,ce=f(),le=c(()=>{v.cancel(),d(!1),ae()}),ue=c(()=>{v.cancel(),u(),ae()});(0,Z.useEffect)(()=>()=>{le()},[le]);let fe=te?.models?.edit_model||`openai/gpt-4o`,pe=Ee.parse(fe).providerId,C=Sc.has(pe),me=async()=>{se||await v.run({prepare:async()=>(_.current?.view&&ds(_.current.view),x?await Ec(x):void 0),submit:async e=>{l(),await ie({text:n,files:e})},onError:re})},w=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ft,{className:`size-4 mr-2`}),`Python`]}),he=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(de,{className:`size-4 mr-2`}),`SQL`]}),T=(0,Q.jsxs)(Ie,{modal:!1,children:[(0,Q.jsxs)(Pe,{className:`flex items-center justify-between h-7 text-xs px-2 py-0.5 border rounded-md hover:text-accent-foreground`,"data-testid":`language-button`,children:[m===`python`?w:he,(0,Q.jsx)(st,{className:`ml-1 h-3.5 w-3.5 text-muted-foreground/70`})]}),(0,Q.jsxs)(Fe,{align:`center`,children:[(0,Q.jsx)(`div`,{className:`px-2 py-1 text-sm text-muted-foreground`,children:`Select language`}),(0,Q.jsx)(Ne,{}),(0,Q.jsx)(Me,{onClick:()=>h(`python`),children:w}),(0,Q.jsx)(Me,{onClick:()=>h(`sql`),children:he})]})]}),ge=()=>{s()&&e()},E=()=>{ue(),_.current?.view?.focus()},D=()=>{ue(),e()},_e=(0,Q.jsxs)(`div`,{className:`flex items-center px-3`,children:[(0,Q.jsx)(y,{className:`size-4 text-(--blue-11) mr-2`}),(0,Q.jsx)(Fl,{inputRef:_,onClose:D,value:n,onChange:e=>{a(e)},onSubmit:me,onKeyDown:El({handleAcceptCompletion:ge,handleDeclineCompletion:E,isLoading:se,hasCompletion:ce})}),(0,Q.jsx)(Re,{variant:`text`,size:`sm`,className:`mb-0 px-1`,onClick:D,children:(0,Q.jsx)(ot,{className:`size-4`})})]}),ve=(0,Q.jsxs)(`div`,{className:`px-3 pt-1 flex flex-row items-center justify-between`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(De,{triggerClassName:`h-7 text-xs max-w-64`,iconSize:`small`,forRole:`edit`,showAddCustomModelDocs:!0}),T]}),(0,Q.jsxs)(`div`,{className:`flex flex-row items-center`,children:[x.length>0&&(0,Q.jsx)(`div`,{className:`flex flex-row gap-1 flex-wrap pr-1`,children:x?.map((e,t)=>(0,Q.jsx)(zc,{file:e,onRemove:()=>ee(e)},`${e.name}-${t}`))}),(0,Q.jsx)(Vc,{handleAddContext:()=>xc(_),isLoading:se}),C&&(0,Q.jsx)(Hc,{fileInputRef:b,isLoading:se,onAddFiles:S}),(0,Q.jsx)(Bc,{isLoading:se,onStop:le,onSendClick:me,isEmpty:!n.trim(),showStopLabel:!0})]})]});return(0,Q.jsxs)(`div`,{className:Ae(`flex flex-col w-full py-2`),children:[_e,ve]})},Fl=e=>{let t=(0,P.c)(35),{value:n,placeholder:r,inputRef:a,className:o,onChange:s,onSubmit:l,onKeyDown:u,onClose:d,onAddFiles:f,additionalCompletions:p,maxHeight:m}=e,h=l,g=d,_=i(),{theme:v}=Et(),y;t[0]===p?y=t[1]:(y=e=>p?bc([p.triggerCompletionRegex],p.completions)(e):null,t[0]=p,t[1]=y);let b=c(y),x,S,ee,te;if(t[2]!==b||t[3]!==f||t[4]!==_){let e=St();t[9]===Symbol.for(`react.memo_cache_sentinel`)?(x=tt({}),t[9]=x):x=t[9],S=e,ee=Cl({language:e.language,store:_,onAddFiles:f}),te=e.language.data.of({autocomplete:b}),t[2]=b,t[3]=f,t[4]=_,t[5]=x,t[6]=S,t[7]=ee,t[8]=te}else x=t[5],S=t[6],ee=t[7],te=t[8];let ne;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(ne=fs({storage:{load:Il,save:Ll}}),t[10]=ne):ne=t[10];let re;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(re=At(),t[11]=re):re=t[11];let ie;t[12]===h?ie=t[13]:(ie=qe.highest(Ve.of([{preventDefault:!0,stopPropagation:!0,any:(e,t)=>{let n=t.metaKey||t.ctrlKey||t.shiftKey;if(t.key===`Enter`&&!n)return h(t,e.state.doc.toString()),t.preventDefault(),t.stopPropagation(),!0;if(t.key===`Enter`&&t.shiftKey){let n=e.state.selection.main.from;return e.dispatch({changes:{from:n,to:n,insert:`
|
|
76
|
+
`},selection:{anchor:n+1,head:n+1}}),t.preventDefault(),t.stopPropagation(),!0}return!1}}])),t[12]=h,t[13]=ie);let ae;t[14]===g?ae=t[15]:(ae=Ve.of([{key:`Escape`,preventDefault:!0,stopPropagation:!0,run:()=>(g(),!0)}]),t[14]=g,t[15]=ae);let oe;t[16]!==x||t[17]!==S||t[18]!==ee||t[19]!==te||t[20]!==ie||t[21]!==ae?(oe=[x,S,ee,te,ne,Je.lineWrapping,re,ie,ae],t[16]=x,t[17]=S,t[18]=ee,t[19]=te,t[20]=ie,t[21]=ae,t[22]=oe):oe=t[22];let se=oe,ce;t[23]===o?ce=t[24]:(ce=Ae(`flex-1 font-sans overflow-auto my-1`,o),t[23]=o,t[24]=ce);let le=v===`dark`?`dark`:`light`,ue=r||`Generate with AI, @ to include context`,de;return t[25]!==se||t[26]!==a||t[27]!==m||t[28]!==s||t[29]!==u||t[30]!==ce||t[31]!==le||t[32]!==ue||t[33]!==n?(de=(0,Q.jsx)(jt,{ref:a,className:ce,width:`100%`,maxHeight:m,value:n,basicSetup:!1,extensions:se,onChange:s,onKeyDown:u,theme:le,placeholder:ue}),t[25]=se,t[26]=a,t[27]=m,t[28]=s,t[29]=u,t[30]=ce,t[31]=le,t[32]=ue,t[33]=n,t[34]=de):de=t[34],de};function Il(){return Nl.get(Ml)}function Ll(e){return Nl.set(Ml,e)}export{Ts as A,Po as B,Lc as C,_c as D,mc as E,_s as F,va as G,go as H,ys as I,Bt as J,Ht as K,Ss as L,ks as M,Es as N,lc as O,As as P,ds as R,Pc as S,dc as T,Ao as U,Do as V,vo as W,Ac as _,Dl as a,Dc as b,Vc as c,zc as d,Bc as f,Tc as g,Ec as h,Ol as i,ws as j,Zs as k,Hc as l,Sc as m,Fl as n,kl as o,Wc as p,Vt as q,Tl as r,El as s,Pl as t,Rc as u,jc as v,xc as w,Ic as x,Mc as y,ns as z};
|