@on-panda/serve 0.6.1 → 0.6.2

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.
@@ -1,4 +1,4 @@
1
- import{s as qa,C as Aa,P as Da,a as za,G as Va,M,E as z,b as Fa,L as Ha,c as La,i as ut,d as Ua,e as as,f as Ka,R as Ae,g as Ga,h as er,j as Ja,k as Qa,l as Wa,T as ns,m as Cs,n as Ba,o as Ya,p as Za,q as Xa,I as xa,S as en,r as lt,t as tn,u as rn,v as sn,w as an,x as nn,y as on,z as cn,A as un,B as ln,D as dn,F as fn,H as hn,J as mn}from"./types-JPNfEfAJ.js";import{i as js}from"./index-VDofnkb1.js";function Rt(t){return!!t._zod}function ke(t,e){return Rt(t)?qa(t,e):t.safeParse(e)}function Ms(t){var r,s;if(!t)return;let e;if(Rt(t)?e=(s=(r=t._zod)==null?void 0:r.def)==null?void 0:s.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function pn(t){var a;if(Rt(t)){const o=(a=t._zod)==null?void 0:a.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const s=t.value;if(s!==void 0)return s}function Re(t){return t==="completed"||t==="failed"||t==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function os(t){const e=Ms(t),r=e==null?void 0:e.method;if(!r)throw new Error("Schema is missing a method literal");const s=pn(r);if(typeof s!="string")throw new Error("Schema method literal must be a string");return s}function is(t,e){const r=ke(t,e);if(!r.success)throw r.error;return r.data}const yn=6e4;class _n{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Aa,r=>{this._oncancel(r)}),this.setNotificationHandler(Da,r=>{this._onprogress(r)}),this.setRequestHandler(za,r=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Va,async(r,s)=>{const a=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!a)throw new M(z.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Fa,async(r,s)=>{const a=async()=>{var u;const n=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(n,s.sessionId);){if(c.type==="response"||c.type==="error"){const l=c.message,d=l.id,h=this._requestResolvers.get(d);if(h)if(this._requestResolvers.delete(d),c.type==="response")h(l);else{const g=l,b=new M(g.error.code,g.error.message,g.error.data);h(b)}else{const g=c.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${d}`))}continue}await((u=this._transport)==null?void 0:u.send(c.message,{relatedRequestId:s.requestId}))}}const o=await this._taskStore.getTask(n,s.sessionId);if(!o)throw new M(z.InvalidParams,`Task not found: ${n}`);if(!Re(o.status))return await this._waitForTaskUpdate(n,s.signal),await a();if(Re(o.status)){const c=await this._taskStore.getTaskResult(n,s.sessionId);return this._clearTaskQueue(n),{...c,_meta:{...c._meta,[Ae]:{taskId:n}}}}return await a()};return await a()}),this.setRequestHandler(Ha,async(r,s)=>{var a;try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks((a=r.params)==null?void 0:a.cursor,s.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new M(z.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(La,async(r,s)=>{try{const a=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!a)throw new M(z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Re(a.status))throw new M(z.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",s.sessionId),this._clearTaskQueue(r.params.taskId);const n=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!n)throw new M(z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...n}}catch(a){throw a instanceof M?a:new M(z.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const r=this._requestHandlerAbortControllers.get(e.params.requestId);r==null||r.abort(e.params.reason)}_setupTimeout(e,r,s,a,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:s,resetTimeoutOnProgress:n,onTimeout:a})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const s=Date.now()-r.startTime;if(r.maxTotalTimeout&&s>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),M.fromError(z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:s});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var n,o,u;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const r=(n=this.transport)==null?void 0:n.onclose;this._transport.onclose=()=>{r==null||r(),this._onclose()};const s=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=c=>{s==null||s(c),this._onerror(c)};const a=(u=this._transport)==null?void 0:u.onmessage;this._transport.onmessage=(c,l)=>{a==null||a(c,l),ut(c)||Ua(c)?this._onresponse(c):as(c)?this._onrequest(c,l):Ka(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var s;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const a of this._requestHandlerAbortControllers.values())a.abort();this._requestHandlerAbortControllers.clear();const r=M.fromError(z.ConnectionClosed,"Connection closed");this._transport=void 0,(s=this.onclose)==null||s.call(this);for(const a of e.values())a(r)}_onerror(e){var r;(r=this.onerror)==null||r.call(this,e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var d,h,g,b;const s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,a=this._transport,n=(g=(h=(d=e.params)==null?void 0:d._meta)==null?void 0:h[Ae])==null?void 0:g.taskId;if(s===void 0){const y={jsonrpc:"2.0",id:e.id,error:{code:z.MethodNotFound,message:"Method not found"}};n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:y,timestamp:Date.now()},a==null?void 0:a.sessionId).catch($=>this._onerror(new Error(`Failed to enqueue error response: ${$}`))):a==null||a.send(y).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const u=Ga(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,a==null?void 0:a.sessionId):void 0,l={signal:o.signal,sessionId:a==null?void 0:a.sessionId,_meta:(b=e.params)==null?void 0:b._meta,sendNotification:async y=>{if(o.signal.aborted)return;const $={relatedRequestId:e.id};n&&($.relatedTask={taskId:n}),await this.notification(y,$)},sendRequest:async(y,$,p)=>{var E;if(o.signal.aborted)throw new M(z.ConnectionClosed,"Request was cancelled");const f={...p,relatedRequestId:e.id};n&&!f.relatedTask&&(f.relatedTask={taskId:n});const v=((E=f.relatedTask)==null?void 0:E.taskId)??n;return v&&c&&await c.updateTaskStatus(v,"input_required"),await this.request(y,$,f)},authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:u==null?void 0:u.ttl,closeSSEStream:r==null?void 0:r.closeSSEStream,closeStandaloneSSEStream:r==null?void 0:r.closeStandaloneSSEStream};Promise.resolve().then(()=>{u&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,l)).then(async y=>{if(o.signal.aborted)return;const $={result:y,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:$,timestamp:Date.now()},a==null?void 0:a.sessionId):await(a==null?void 0:a.send($))},async y=>{if(o.signal.aborted)return;const $={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(y.code)?y.code:z.InternalError,message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:$,timestamp:Date.now()},a==null?void 0:a.sessionId):await(a==null?void 0:a.send($))}).catch(y=>this._onerror(new Error(`Failed to send response: ${y}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...s}=e.params,a=Number(r),n=this._progressHandlers.get(a);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(a),u=this._timeoutInfo.get(a);if(u&&o&&u.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(c){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),o(c);return}n(s)}_onresponse(e){const r=Number(e.id),s=this._requestResolvers.get(r);if(s){if(this._requestResolvers.delete(r),ut(e))s(e);else{const o=new M(e.error.code,e.error.message,e.error.data);s(o)}return}const a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let n=!1;if(ut(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const u=o.task;typeof u.taskId=="string"&&(n=!0,this._taskProgressTokens.set(u.taskId,r))}}if(n||this._progressHandlers.delete(r),ut(e))a(e);else{const o=M.fromError(e.error.code,e.error.message,e.error.data);a(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,r,s){var o,u;const{task:a}=s??{};if(!a){try{yield{type:"result",result:await this.request(e,r,s)}}catch(c){yield{type:"error",error:c instanceof M?c:new M(z.InternalError,String(c))}}return}let n;try{const c=await this.request(e,er,s);if(c.task)n=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new M(z.InternalError,"Task creation did not return a task");for(;;){const l=await this.getTask({taskId:n},s);if(yield{type:"taskStatus",task:l},Re(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:n},r,s)}:l.status==="failed"?yield{type:"error",error:new M(z.InternalError,`Task ${n} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new M(z.InternalError,`Task ${n} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:n},r,s)};return}const d=l.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(h=>setTimeout(h,d)),(u=s==null?void 0:s.signal)==null||u.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof M?c:new M(z.InternalError,String(c))}}}request(e,r,s){const{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o,task:u,relatedTask:c}=s??{};return new Promise((l,d)=>{var v,E,P,R,U;const h=A=>{d(A)};if(!this._transport){h(new Error("Not connected"));return}if(((v=this._options)==null?void 0:v.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),u&&this.assertTaskCapability(e.method)}catch(A){h(A);return}(E=s==null?void 0:s.signal)==null||E.throwIfAborted();const g=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:g};s!=null&&s.onprogress&&(this._progressHandlers.set(g,s.onprogress),b.params={...e.params,_meta:{...((P=e.params)==null?void 0:P._meta)||{},progressToken:g}}),u&&(b.params={...b.params,task:u}),c&&(b.params={...b.params,_meta:{...((R=b.params)==null?void 0:R._meta)||{},[Ae]:c}});const y=A=>{var B;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(B=this._transport)==null||B.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(A)}},{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o}).catch(ce=>this._onerror(new Error(`Failed to send cancellation: ${ce}`)));const Y=A instanceof M?A:new M(z.RequestTimeout,String(A));d(Y)};this._responseHandlers.set(g,A=>{var Y;if(!((Y=s==null?void 0:s.signal)!=null&&Y.aborted)){if(A instanceof Error)return d(A);try{const B=ke(r,A.result);B.success?l(B.data):d(B.error)}catch(B){d(B)}}}),(U=s==null?void 0:s.signal)==null||U.addEventListener("abort",()=>{var A;y((A=s==null?void 0:s.signal)==null?void 0:A.reason)});const $=(s==null?void 0:s.timeout)??yn,p=()=>y(M.fromError(z.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(g,$,s==null?void 0:s.maxTotalTimeout,p,(s==null?void 0:s.resetTimeoutOnProgress)??!1);const f=c==null?void 0:c.taskId;if(f){const A=Y=>{const B=this._responseHandlers.get(g);B?B(Y):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,A),this._enqueueTaskMessage(f,{type:"request",message:b,timestamp:Date.now()}).catch(Y=>{this._cleanupTimeout(g),d(Y)})}else this._transport.send(b,{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o}).catch(A=>{this._cleanupTimeout(g),d(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ja,r)}async getTaskResult(e,r,s){return this.request({method:"tasks/result",params:e},r,s)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Qa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Wa,r)}async notification(e,r){var u,c,l,d;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const s=(u=r==null?void 0:r.relatedTask)==null?void 0:u.taskId;if(s){const h={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((c=e.params)==null?void 0:c._meta)||{},[Ae]:r.relatedTask}}};await this._enqueueTaskMessage(s,{type:"notification",message:h,timestamp:Date.now()});return}if((((l=this._options)==null?void 0:l.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)&&!(r!=null&&r.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var g,b;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let h={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(h={...h,params:{...h.params,_meta:{...((g=h.params)==null?void 0:g._meta)||{},[Ae]:r.relatedTask}}}),(b=this._transport)==null||b.send(h,r).catch(y=>this._onerror(y))});return}let o={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(o={...o,params:{...o.params,_meta:{...((d=o.params)==null?void 0:d._meta)||{},[Ae]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){const s=os(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(a,n)=>{const o=is(e,a);return Promise.resolve(r(o,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const s=os(e);this._notificationHandlers.set(s,a=>{const n=is(e,a);return Promise.resolve(r(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,s){var n;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const a=(n=this._options)==null?void 0:n.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,s,a)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const s=await this._taskMessageQueue.dequeueAll(e,r);for(const a of s)if(a.type==="request"&&as(a.message)){const n=a.message.id,o=this._requestResolvers.get(n);o?(o(new M(z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var a,n;let s=((a=this._options)==null?void 0:a.defaultTaskPollInterval)??1e3;try{const o=await((n=this._taskStore)==null?void 0:n.getTask(e));o!=null&&o.pollInterval&&(s=o.pollInterval)}catch{}return new Promise((o,u)=>{if(r.aborted){u(new M(z.InvalidRequest,"Request cancelled"));return}const c=setTimeout(o,s);r.addEventListener("abort",()=>{clearTimeout(c),u(new M(z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const s=this._taskStore;if(!s)throw new Error("No task store configured");return{createTask:async a=>{if(!e)throw new Error("No request provided");return await s.createTask(a,e.id,{method:e.method,params:e.params},r)},getTask:async a=>{const n=await s.getTask(a,r);if(!n)throw new M(z.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(a,n,o)=>{await s.storeTaskResult(a,n,o,r);const u=await s.getTask(a,r);if(u){const c=ns.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Re(u.status)&&this._cleanupTaskProgressHandler(a)}},getTaskResult:a=>s.getTaskResult(a,r),updateTaskStatus:async(a,n,o)=>{const u=await s.getTask(a,r);if(!u)throw new M(z.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Re(u.status))throw new M(z.InvalidParams,`Cannot update task "${a}" from terminal status "${u.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(a,n,o,r);const c=await s.getTask(a,r);if(c){const l=ns.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Re(c.status)&&this._cleanupTaskProgressHandler(a)}},listTasks:a=>s.listTasks(a,r)}}}function cs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gn(t,e){const r={...t};for(const s in e){const a=s,n=e[a];if(n===void 0)continue;const o=r[a];cs(o)&&cs(n)?r[a]={...o,...n}:r[a]=n}return r}var tr={exports:{}},qs={},fe={},Ue={},ot={},V={},nt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class s extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((E,P)=>`${E}${P}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,P)=>(P instanceof r&&(E[P.str]=(E[P.str]||0)+1),E),{})}}t._Code=s,t.nil=new s("");function a(f,...v){const E=[f[0]];let P=0;for(;P<v.length;)u(E,v[P]),E.push(f[++P]);return new s(E)}t._=a;const n=new s("+");function o(f,...v){const E=[b(f[0])];let P=0;for(;P<v.length;)E.push(n),u(E,v[P]),E.push(n,b(f[++P]));return c(E),new s(E)}t.str=o;function u(f,v){v instanceof s?f.push(...v._items):v instanceof r?f.push(v):f.push(h(v))}t.addCodeArg=u;function c(f){let v=1;for(;v<f.length-1;){if(f[v]===n){const E=l(f[v-1],f[v+1]);if(E!==void 0){f.splice(v-1,3,E);continue}f[v++]="+"}v++}}function l(f,v){if(v==='""')return f;if(f==='""')return v;if(typeof f=="string")return v instanceof r||f[f.length-1]!=='"'?void 0:typeof v!="string"?`${f.slice(0,-1)}${v}"`:v[0]==='"'?f.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(f instanceof r))return`"${f}${v.slice(1)}`}function d(f,v){return v.emptyStr()?f:f.emptyStr()?v:o`${f}${v}`}t.strConcat=d;function h(f){return typeof f=="number"||typeof f=="boolean"||f===null?f:b(Array.isArray(f)?f.join(","):f)}function g(f){return new s(b(f))}t.stringify=g;function b(f){return JSON.stringify(f).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=b;function y(f){return typeof f=="string"&&t.IDENTIFIER.test(f)?new s(`.${f}`):a`[${f}]`}t.getProperty=y;function $(f){if(typeof f=="string"&&t.IDENTIFIER.test(f))return new s(`${f}`);throw new Error(`CodeGen: invalid export name: ${f}, use explicit $id name mapping`)}t.getEsmExportName=$;function p(f){return new s(f.toString())}t.regexpCode=p})(nt);var rr={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=nt;class r extends Error{constructor(l){super(`CodeGen: "code" for ${l} not defined`),this.value=l.value}}var s;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(s||(t.UsedValueState=s={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class a{constructor({prefixes:l,parent:d}={}){this._names={},this._prefixes=l,this._parent=d}toName(l){return l instanceof e.Name?l:this.name(l)}name(l){return new e.Name(this._newName(l))}_newName(l){const d=this._names[l]||this._nameGroup(l);return`${l}${d.index++}`}_nameGroup(l){var d,h;if(!((h=(d=this._parent)===null||d===void 0?void 0:d._prefixes)===null||h===void 0)&&h.has(l)||this._prefixes&&!this._prefixes.has(l))throw new Error(`CodeGen: prefix "${l}" is not allowed in this scope`);return this._names[l]={prefix:l,index:0}}}t.Scope=a;class n extends e.Name{constructor(l,d){super(d),this.prefix=l}setValue(l,{property:d,itemIndex:h}){this.value=l,this.scopePath=(0,e._)`.${new e.Name(d)}[${h}]`}}t.ValueScopeName=n;const o=(0,e._)`\n`;class u extends a{constructor(l){super(l),this._values={},this._scope=l.scope,this.opts={...l,_n:l.lines?o:e.nil}}get(){return this._scope}name(l){return new n(l,this._newName(l))}value(l,d){var h;if(d.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const g=this.toName(l),{prefix:b}=g,y=(h=d.key)!==null&&h!==void 0?h:d.ref;let $=this._values[b];if($){const v=$.get(y);if(v)return v}else $=this._values[b]=new Map;$.set(y,g);const p=this._scope[b]||(this._scope[b]=[]),f=p.length;return p[f]=d.ref,g.setValue(d,{property:b,itemIndex:f}),g}getValue(l,d){const h=this._values[l];if(h)return h.get(d)}scopeRefs(l,d=this._values){return this._reduceValues(d,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${l}${h.scopePath}`})}scopeCode(l=this._values,d,h){return this._reduceValues(l,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},d,h)}_reduceValues(l,d,h={},g){let b=e.nil;for(const y in l){const $=l[y];if(!$)continue;const p=h[y]=h[y]||new Map;$.forEach(f=>{if(p.has(f))return;p.set(f,s.Started);let v=d(f);if(v){const E=this.opts.es5?t.varKinds.var:t.varKinds.const;b=(0,e._)`${b}${E} ${f} = ${v};${this.opts._n}`}else if(v=g==null?void 0:g(f))b=(0,e._)`${b}${v}${this.opts._n}`;else throw new r(f);p.set(f,s.Completed)})}return b}}t.ValueScope=u})(rr);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=nt,r=rr;var s=nt;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return s.Name}});var a=rr;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class n{optimizeNodes(){return this}optimizeNames(i,m){return this}}class o extends n{constructor(i,m,S){super(),this.varKind=i,this.name=m,this.rhs=S}render({es5:i,_n:m}){const S=i?r.varKinds.var:this.varKind,O=this.rhs===void 0?"":` = ${this.rhs}`;return`${S} ${this.name}${O};`+m}optimizeNames(i,m){if(i[this.name.str])return this.rhs&&(this.rhs=L(this.rhs,i,m)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class u extends n{constructor(i,m,S){super(),this.lhs=i,this.rhs=m,this.sideEffects=S}render({_n:i}){return`${this.lhs} = ${this.rhs};`+i}optimizeNames(i,m){if(!(this.lhs instanceof e.Name&&!i[this.lhs.str]&&!this.sideEffects))return this.rhs=L(this.rhs,i,m),this}get names(){const i=this.lhs instanceof e.Name?{}:{...this.lhs.names};return W(i,this.rhs)}}class c extends u{constructor(i,m,S,O){super(i,S,O),this.op=m}render({_n:i}){return`${this.lhs} ${this.op}= ${this.rhs};`+i}}class l extends n{constructor(i){super(),this.label=i,this.names={}}render({_n:i}){return`${this.label}:`+i}}class d extends n{constructor(i){super(),this.label=i,this.names={}}render({_n:i}){return`break${this.label?` ${this.label}`:""};`+i}}class h extends n{constructor(i){super(),this.error=i}render({_n:i}){return`throw ${this.error};`+i}get names(){return this.error.names}}class g extends n{constructor(i){super(),this.code=i}render({_n:i}){return`${this.code};`+i}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(i,m){return this.code=L(this.code,i,m),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class b extends n{constructor(i=[]){super(),this.nodes=i}render(i){return this.nodes.reduce((m,S)=>m+S.render(i),"")}optimizeNodes(){const{nodes:i}=this;let m=i.length;for(;m--;){const S=i[m].optimizeNodes();Array.isArray(S)?i.splice(m,1,...S):S?i[m]=S:i.splice(m,1)}return i.length>0?this:void 0}optimizeNames(i,m){const{nodes:S}=this;let O=S.length;for(;O--;){const C=S[O];C.optimizeNames(i,m)||(ee(i,C.names),S.splice(O,1))}return S.length>0?this:void 0}get names(){return this.nodes.reduce((i,m)=>F(i,m.names),{})}}class y extends b{render(i){return"{"+i._n+super.render(i)+"}"+i._n}}class $ extends b{}class p extends y{}p.kind="else";class f extends y{constructor(i,m){super(m),this.condition=i}render(i){let m=`if(${this.condition})`+super.render(i);return this.else&&(m+="else "+this.else.render(i)),m}optimizeNodes(){super.optimizeNodes();const i=this.condition;if(i===!0)return this.nodes;let m=this.else;if(m){const S=m.optimizeNodes();m=this.else=Array.isArray(S)?new p(S):S}if(m)return i===!1?m instanceof f?m:m.nodes:this.nodes.length?this:new f(_e(i),m instanceof f?[m]:m.nodes);if(!(i===!1||!this.nodes.length))return this}optimizeNames(i,m){var S;if(this.else=(S=this.else)===null||S===void 0?void 0:S.optimizeNames(i,m),!!(super.optimizeNames(i,m)||this.else))return this.condition=L(this.condition,i,m),this}get names(){const i=super.names;return W(i,this.condition),this.else&&F(i,this.else.names),i}}f.kind="if";class v extends y{}v.kind="for";class E extends v{constructor(i){super(),this.iteration=i}render(i){return`for(${this.iteration})`+super.render(i)}optimizeNames(i,m){if(super.optimizeNames(i,m))return this.iteration=L(this.iteration,i,m),this}get names(){return F(super.names,this.iteration.names)}}class P extends v{constructor(i,m,S,O){super(),this.varKind=i,this.name=m,this.from=S,this.to=O}render(i){const m=i.es5?r.varKinds.var:this.varKind,{name:S,from:O,to:C}=this;return`for(${m} ${S}=${O}; ${S}<${C}; ${S}++)`+super.render(i)}get names(){const i=W(super.names,this.from);return W(i,this.to)}}class R extends v{constructor(i,m,S,O){super(),this.loop=i,this.varKind=m,this.name=S,this.iterable=O}render(i){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(i)}optimizeNames(i,m){if(super.optimizeNames(i,m))return this.iterable=L(this.iterable,i,m),this}get names(){return F(super.names,this.iterable.names)}}class U extends y{constructor(i,m,S){super(),this.name=i,this.args=m,this.async=S}render(i){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(i)}}U.kind="func";class A extends b{render(i){return"return "+super.render(i)}}A.kind="return";class Y extends y{render(i){let m="try"+super.render(i);return this.catch&&(m+=this.catch.render(i)),this.finally&&(m+=this.finally.render(i)),m}optimizeNodes(){var i,m;return super.optimizeNodes(),(i=this.catch)===null||i===void 0||i.optimizeNodes(),(m=this.finally)===null||m===void 0||m.optimizeNodes(),this}optimizeNames(i,m){var S,O;return super.optimizeNames(i,m),(S=this.catch)===null||S===void 0||S.optimizeNames(i,m),(O=this.finally)===null||O===void 0||O.optimizeNames(i,m),this}get names(){const i=super.names;return this.catch&&F(i,this.catch.names),this.finally&&F(i,this.finally.names),i}}class B extends y{constructor(i){super(),this.error=i}render(i){return`catch(${this.error})`+super.render(i)}}B.kind="catch";class ce extends y{render(i){return"finally"+super.render(i)}}ce.kind="finally";class j{constructor(i,m={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...m,_n:m.lines?`
1
+ import{s as qa,C as Aa,P as Da,a as za,G as Va,M,E as z,b as Fa,L as Ha,c as La,i as ut,d as Ua,e as as,f as Ka,R as Ae,g as Ga,h as er,j as Ja,k as Qa,l as Wa,T as ns,m as Cs,n as Ba,o as Ya,p as Za,q as Xa,I as xa,S as en,r as lt,t as tn,u as rn,v as sn,w as an,x as nn,y as on,z as cn,A as un,B as ln,D as dn,F as fn,H as hn,J as mn}from"./types-JPNfEfAJ.js";import{i as js}from"./index-CSSh_R5o.js";function Rt(t){return!!t._zod}function ke(t,e){return Rt(t)?qa(t,e):t.safeParse(e)}function Ms(t){var r,s;if(!t)return;let e;if(Rt(t)?e=(s=(r=t._zod)==null?void 0:r.def)==null?void 0:s.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function pn(t){var a;if(Rt(t)){const o=(a=t._zod)==null?void 0:a.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const s=t.value;if(s!==void 0)return s}function Re(t){return t==="completed"||t==="failed"||t==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function os(t){const e=Ms(t),r=e==null?void 0:e.method;if(!r)throw new Error("Schema is missing a method literal");const s=pn(r);if(typeof s!="string")throw new Error("Schema method literal must be a string");return s}function is(t,e){const r=ke(t,e);if(!r.success)throw r.error;return r.data}const yn=6e4;class _n{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Aa,r=>{this._oncancel(r)}),this.setNotificationHandler(Da,r=>{this._onprogress(r)}),this.setRequestHandler(za,r=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Va,async(r,s)=>{const a=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!a)throw new M(z.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Fa,async(r,s)=>{const a=async()=>{var u;const n=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(n,s.sessionId);){if(c.type==="response"||c.type==="error"){const l=c.message,d=l.id,h=this._requestResolvers.get(d);if(h)if(this._requestResolvers.delete(d),c.type==="response")h(l);else{const g=l,b=new M(g.error.code,g.error.message,g.error.data);h(b)}else{const g=c.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${d}`))}continue}await((u=this._transport)==null?void 0:u.send(c.message,{relatedRequestId:s.requestId}))}}const o=await this._taskStore.getTask(n,s.sessionId);if(!o)throw new M(z.InvalidParams,`Task not found: ${n}`);if(!Re(o.status))return await this._waitForTaskUpdate(n,s.signal),await a();if(Re(o.status)){const c=await this._taskStore.getTaskResult(n,s.sessionId);return this._clearTaskQueue(n),{...c,_meta:{...c._meta,[Ae]:{taskId:n}}}}return await a()};return await a()}),this.setRequestHandler(Ha,async(r,s)=>{var a;try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks((a=r.params)==null?void 0:a.cursor,s.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new M(z.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(La,async(r,s)=>{try{const a=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!a)throw new M(z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Re(a.status))throw new M(z.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",s.sessionId),this._clearTaskQueue(r.params.taskId);const n=await this._taskStore.getTask(r.params.taskId,s.sessionId);if(!n)throw new M(z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...n}}catch(a){throw a instanceof M?a:new M(z.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const r=this._requestHandlerAbortControllers.get(e.params.requestId);r==null||r.abort(e.params.reason)}_setupTimeout(e,r,s,a,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:s,resetTimeoutOnProgress:n,onTimeout:a})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const s=Date.now()-r.startTime;if(r.maxTotalTimeout&&s>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),M.fromError(z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:s});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var n,o,u;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const r=(n=this.transport)==null?void 0:n.onclose;this._transport.onclose=()=>{r==null||r(),this._onclose()};const s=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=c=>{s==null||s(c),this._onerror(c)};const a=(u=this._transport)==null?void 0:u.onmessage;this._transport.onmessage=(c,l)=>{a==null||a(c,l),ut(c)||Ua(c)?this._onresponse(c):as(c)?this._onrequest(c,l):Ka(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var s;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const a of this._requestHandlerAbortControllers.values())a.abort();this._requestHandlerAbortControllers.clear();const r=M.fromError(z.ConnectionClosed,"Connection closed");this._transport=void 0,(s=this.onclose)==null||s.call(this);for(const a of e.values())a(r)}_onerror(e){var r;(r=this.onerror)==null||r.call(this,e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var d,h,g,b;const s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,a=this._transport,n=(g=(h=(d=e.params)==null?void 0:d._meta)==null?void 0:h[Ae])==null?void 0:g.taskId;if(s===void 0){const y={jsonrpc:"2.0",id:e.id,error:{code:z.MethodNotFound,message:"Method not found"}};n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:y,timestamp:Date.now()},a==null?void 0:a.sessionId).catch($=>this._onerror(new Error(`Failed to enqueue error response: ${$}`))):a==null||a.send(y).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const u=Ga(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,a==null?void 0:a.sessionId):void 0,l={signal:o.signal,sessionId:a==null?void 0:a.sessionId,_meta:(b=e.params)==null?void 0:b._meta,sendNotification:async y=>{if(o.signal.aborted)return;const $={relatedRequestId:e.id};n&&($.relatedTask={taskId:n}),await this.notification(y,$)},sendRequest:async(y,$,p)=>{var E;if(o.signal.aborted)throw new M(z.ConnectionClosed,"Request was cancelled");const f={...p,relatedRequestId:e.id};n&&!f.relatedTask&&(f.relatedTask={taskId:n});const v=((E=f.relatedTask)==null?void 0:E.taskId)??n;return v&&c&&await c.updateTaskStatus(v,"input_required"),await this.request(y,$,f)},authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:u==null?void 0:u.ttl,closeSSEStream:r==null?void 0:r.closeSSEStream,closeStandaloneSSEStream:r==null?void 0:r.closeStandaloneSSEStream};Promise.resolve().then(()=>{u&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,l)).then(async y=>{if(o.signal.aborted)return;const $={result:y,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:$,timestamp:Date.now()},a==null?void 0:a.sessionId):await(a==null?void 0:a.send($))},async y=>{if(o.signal.aborted)return;const $={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(y.code)?y.code:z.InternalError,message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:$,timestamp:Date.now()},a==null?void 0:a.sessionId):await(a==null?void 0:a.send($))}).catch(y=>this._onerror(new Error(`Failed to send response: ${y}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...s}=e.params,a=Number(r),n=this._progressHandlers.get(a);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(a),u=this._timeoutInfo.get(a);if(u&&o&&u.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(c){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),o(c);return}n(s)}_onresponse(e){const r=Number(e.id),s=this._requestResolvers.get(r);if(s){if(this._requestResolvers.delete(r),ut(e))s(e);else{const o=new M(e.error.code,e.error.message,e.error.data);s(o)}return}const a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let n=!1;if(ut(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const u=o.task;typeof u.taskId=="string"&&(n=!0,this._taskProgressTokens.set(u.taskId,r))}}if(n||this._progressHandlers.delete(r),ut(e))a(e);else{const o=M.fromError(e.error.code,e.error.message,e.error.data);a(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,r,s){var o,u;const{task:a}=s??{};if(!a){try{yield{type:"result",result:await this.request(e,r,s)}}catch(c){yield{type:"error",error:c instanceof M?c:new M(z.InternalError,String(c))}}return}let n;try{const c=await this.request(e,er,s);if(c.task)n=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new M(z.InternalError,"Task creation did not return a task");for(;;){const l=await this.getTask({taskId:n},s);if(yield{type:"taskStatus",task:l},Re(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:n},r,s)}:l.status==="failed"?yield{type:"error",error:new M(z.InternalError,`Task ${n} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new M(z.InternalError,`Task ${n} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:n},r,s)};return}const d=l.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(h=>setTimeout(h,d)),(u=s==null?void 0:s.signal)==null||u.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof M?c:new M(z.InternalError,String(c))}}}request(e,r,s){const{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o,task:u,relatedTask:c}=s??{};return new Promise((l,d)=>{var v,E,P,R,U;const h=A=>{d(A)};if(!this._transport){h(new Error("Not connected"));return}if(((v=this._options)==null?void 0:v.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),u&&this.assertTaskCapability(e.method)}catch(A){h(A);return}(E=s==null?void 0:s.signal)==null||E.throwIfAborted();const g=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:g};s!=null&&s.onprogress&&(this._progressHandlers.set(g,s.onprogress),b.params={...e.params,_meta:{...((P=e.params)==null?void 0:P._meta)||{},progressToken:g}}),u&&(b.params={...b.params,task:u}),c&&(b.params={...b.params,_meta:{...((R=b.params)==null?void 0:R._meta)||{},[Ae]:c}});const y=A=>{var B;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(B=this._transport)==null||B.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(A)}},{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o}).catch(ce=>this._onerror(new Error(`Failed to send cancellation: ${ce}`)));const Y=A instanceof M?A:new M(z.RequestTimeout,String(A));d(Y)};this._responseHandlers.set(g,A=>{var Y;if(!((Y=s==null?void 0:s.signal)!=null&&Y.aborted)){if(A instanceof Error)return d(A);try{const B=ke(r,A.result);B.success?l(B.data):d(B.error)}catch(B){d(B)}}}),(U=s==null?void 0:s.signal)==null||U.addEventListener("abort",()=>{var A;y((A=s==null?void 0:s.signal)==null?void 0:A.reason)});const $=(s==null?void 0:s.timeout)??yn,p=()=>y(M.fromError(z.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(g,$,s==null?void 0:s.maxTotalTimeout,p,(s==null?void 0:s.resetTimeoutOnProgress)??!1);const f=c==null?void 0:c.taskId;if(f){const A=Y=>{const B=this._responseHandlers.get(g);B?B(Y):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,A),this._enqueueTaskMessage(f,{type:"request",message:b,timestamp:Date.now()}).catch(Y=>{this._cleanupTimeout(g),d(Y)})}else this._transport.send(b,{relatedRequestId:a,resumptionToken:n,onresumptiontoken:o}).catch(A=>{this._cleanupTimeout(g),d(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ja,r)}async getTaskResult(e,r,s){return this.request({method:"tasks/result",params:e},r,s)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Qa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Wa,r)}async notification(e,r){var u,c,l,d;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const s=(u=r==null?void 0:r.relatedTask)==null?void 0:u.taskId;if(s){const h={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((c=e.params)==null?void 0:c._meta)||{},[Ae]:r.relatedTask}}};await this._enqueueTaskMessage(s,{type:"notification",message:h,timestamp:Date.now()});return}if((((l=this._options)==null?void 0:l.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)&&!(r!=null&&r.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var g,b;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let h={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(h={...h,params:{...h.params,_meta:{...((g=h.params)==null?void 0:g._meta)||{},[Ae]:r.relatedTask}}}),(b=this._transport)==null||b.send(h,r).catch(y=>this._onerror(y))});return}let o={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(o={...o,params:{...o.params,_meta:{...((d=o.params)==null?void 0:d._meta)||{},[Ae]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){const s=os(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(a,n)=>{const o=is(e,a);return Promise.resolve(r(o,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const s=os(e);this._notificationHandlers.set(s,a=>{const n=is(e,a);return Promise.resolve(r(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,s){var n;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const a=(n=this._options)==null?void 0:n.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,s,a)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const s=await this._taskMessageQueue.dequeueAll(e,r);for(const a of s)if(a.type==="request"&&as(a.message)){const n=a.message.id,o=this._requestResolvers.get(n);o?(o(new M(z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var a,n;let s=((a=this._options)==null?void 0:a.defaultTaskPollInterval)??1e3;try{const o=await((n=this._taskStore)==null?void 0:n.getTask(e));o!=null&&o.pollInterval&&(s=o.pollInterval)}catch{}return new Promise((o,u)=>{if(r.aborted){u(new M(z.InvalidRequest,"Request cancelled"));return}const c=setTimeout(o,s);r.addEventListener("abort",()=>{clearTimeout(c),u(new M(z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const s=this._taskStore;if(!s)throw new Error("No task store configured");return{createTask:async a=>{if(!e)throw new Error("No request provided");return await s.createTask(a,e.id,{method:e.method,params:e.params},r)},getTask:async a=>{const n=await s.getTask(a,r);if(!n)throw new M(z.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(a,n,o)=>{await s.storeTaskResult(a,n,o,r);const u=await s.getTask(a,r);if(u){const c=ns.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Re(u.status)&&this._cleanupTaskProgressHandler(a)}},getTaskResult:a=>s.getTaskResult(a,r),updateTaskStatus:async(a,n,o)=>{const u=await s.getTask(a,r);if(!u)throw new M(z.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Re(u.status))throw new M(z.InvalidParams,`Cannot update task "${a}" from terminal status "${u.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(a,n,o,r);const c=await s.getTask(a,r);if(c){const l=ns.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Re(c.status)&&this._cleanupTaskProgressHandler(a)}},listTasks:a=>s.listTasks(a,r)}}}function cs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gn(t,e){const r={...t};for(const s in e){const a=s,n=e[a];if(n===void 0)continue;const o=r[a];cs(o)&&cs(n)?r[a]={...o,...n}:r[a]=n}return r}var tr={exports:{}},qs={},fe={},Ue={},ot={},V={},nt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class s extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((E,P)=>`${E}${P}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,P)=>(P instanceof r&&(E[P.str]=(E[P.str]||0)+1),E),{})}}t._Code=s,t.nil=new s("");function a(f,...v){const E=[f[0]];let P=0;for(;P<v.length;)u(E,v[P]),E.push(f[++P]);return new s(E)}t._=a;const n=new s("+");function o(f,...v){const E=[b(f[0])];let P=0;for(;P<v.length;)E.push(n),u(E,v[P]),E.push(n,b(f[++P]));return c(E),new s(E)}t.str=o;function u(f,v){v instanceof s?f.push(...v._items):v instanceof r?f.push(v):f.push(h(v))}t.addCodeArg=u;function c(f){let v=1;for(;v<f.length-1;){if(f[v]===n){const E=l(f[v-1],f[v+1]);if(E!==void 0){f.splice(v-1,3,E);continue}f[v++]="+"}v++}}function l(f,v){if(v==='""')return f;if(f==='""')return v;if(typeof f=="string")return v instanceof r||f[f.length-1]!=='"'?void 0:typeof v!="string"?`${f.slice(0,-1)}${v}"`:v[0]==='"'?f.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(f instanceof r))return`"${f}${v.slice(1)}`}function d(f,v){return v.emptyStr()?f:f.emptyStr()?v:o`${f}${v}`}t.strConcat=d;function h(f){return typeof f=="number"||typeof f=="boolean"||f===null?f:b(Array.isArray(f)?f.join(","):f)}function g(f){return new s(b(f))}t.stringify=g;function b(f){return JSON.stringify(f).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=b;function y(f){return typeof f=="string"&&t.IDENTIFIER.test(f)?new s(`.${f}`):a`[${f}]`}t.getProperty=y;function $(f){if(typeof f=="string"&&t.IDENTIFIER.test(f))return new s(`${f}`);throw new Error(`CodeGen: invalid export name: ${f}, use explicit $id name mapping`)}t.getEsmExportName=$;function p(f){return new s(f.toString())}t.regexpCode=p})(nt);var rr={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=nt;class r extends Error{constructor(l){super(`CodeGen: "code" for ${l} not defined`),this.value=l.value}}var s;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(s||(t.UsedValueState=s={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class a{constructor({prefixes:l,parent:d}={}){this._names={},this._prefixes=l,this._parent=d}toName(l){return l instanceof e.Name?l:this.name(l)}name(l){return new e.Name(this._newName(l))}_newName(l){const d=this._names[l]||this._nameGroup(l);return`${l}${d.index++}`}_nameGroup(l){var d,h;if(!((h=(d=this._parent)===null||d===void 0?void 0:d._prefixes)===null||h===void 0)&&h.has(l)||this._prefixes&&!this._prefixes.has(l))throw new Error(`CodeGen: prefix "${l}" is not allowed in this scope`);return this._names[l]={prefix:l,index:0}}}t.Scope=a;class n extends e.Name{constructor(l,d){super(d),this.prefix=l}setValue(l,{property:d,itemIndex:h}){this.value=l,this.scopePath=(0,e._)`.${new e.Name(d)}[${h}]`}}t.ValueScopeName=n;const o=(0,e._)`\n`;class u extends a{constructor(l){super(l),this._values={},this._scope=l.scope,this.opts={...l,_n:l.lines?o:e.nil}}get(){return this._scope}name(l){return new n(l,this._newName(l))}value(l,d){var h;if(d.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const g=this.toName(l),{prefix:b}=g,y=(h=d.key)!==null&&h!==void 0?h:d.ref;let $=this._values[b];if($){const v=$.get(y);if(v)return v}else $=this._values[b]=new Map;$.set(y,g);const p=this._scope[b]||(this._scope[b]=[]),f=p.length;return p[f]=d.ref,g.setValue(d,{property:b,itemIndex:f}),g}getValue(l,d){const h=this._values[l];if(h)return h.get(d)}scopeRefs(l,d=this._values){return this._reduceValues(d,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${l}${h.scopePath}`})}scopeCode(l=this._values,d,h){return this._reduceValues(l,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},d,h)}_reduceValues(l,d,h={},g){let b=e.nil;for(const y in l){const $=l[y];if(!$)continue;const p=h[y]=h[y]||new Map;$.forEach(f=>{if(p.has(f))return;p.set(f,s.Started);let v=d(f);if(v){const E=this.opts.es5?t.varKinds.var:t.varKinds.const;b=(0,e._)`${b}${E} ${f} = ${v};${this.opts._n}`}else if(v=g==null?void 0:g(f))b=(0,e._)`${b}${v}${this.opts._n}`;else throw new r(f);p.set(f,s.Completed)})}return b}}t.ValueScope=u})(rr);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=nt,r=rr;var s=nt;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return s.Name}});var a=rr;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class n{optimizeNodes(){return this}optimizeNames(i,m){return this}}class o extends n{constructor(i,m,S){super(),this.varKind=i,this.name=m,this.rhs=S}render({es5:i,_n:m}){const S=i?r.varKinds.var:this.varKind,O=this.rhs===void 0?"":` = ${this.rhs}`;return`${S} ${this.name}${O};`+m}optimizeNames(i,m){if(i[this.name.str])return this.rhs&&(this.rhs=L(this.rhs,i,m)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class u extends n{constructor(i,m,S){super(),this.lhs=i,this.rhs=m,this.sideEffects=S}render({_n:i}){return`${this.lhs} = ${this.rhs};`+i}optimizeNames(i,m){if(!(this.lhs instanceof e.Name&&!i[this.lhs.str]&&!this.sideEffects))return this.rhs=L(this.rhs,i,m),this}get names(){const i=this.lhs instanceof e.Name?{}:{...this.lhs.names};return W(i,this.rhs)}}class c extends u{constructor(i,m,S,O){super(i,S,O),this.op=m}render({_n:i}){return`${this.lhs} ${this.op}= ${this.rhs};`+i}}class l extends n{constructor(i){super(),this.label=i,this.names={}}render({_n:i}){return`${this.label}:`+i}}class d extends n{constructor(i){super(),this.label=i,this.names={}}render({_n:i}){return`break${this.label?` ${this.label}`:""};`+i}}class h extends n{constructor(i){super(),this.error=i}render({_n:i}){return`throw ${this.error};`+i}get names(){return this.error.names}}class g extends n{constructor(i){super(),this.code=i}render({_n:i}){return`${this.code};`+i}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(i,m){return this.code=L(this.code,i,m),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class b extends n{constructor(i=[]){super(),this.nodes=i}render(i){return this.nodes.reduce((m,S)=>m+S.render(i),"")}optimizeNodes(){const{nodes:i}=this;let m=i.length;for(;m--;){const S=i[m].optimizeNodes();Array.isArray(S)?i.splice(m,1,...S):S?i[m]=S:i.splice(m,1)}return i.length>0?this:void 0}optimizeNames(i,m){const{nodes:S}=this;let O=S.length;for(;O--;){const C=S[O];C.optimizeNames(i,m)||(ee(i,C.names),S.splice(O,1))}return S.length>0?this:void 0}get names(){return this.nodes.reduce((i,m)=>F(i,m.names),{})}}class y extends b{render(i){return"{"+i._n+super.render(i)+"}"+i._n}}class $ extends b{}class p extends y{}p.kind="else";class f extends y{constructor(i,m){super(m),this.condition=i}render(i){let m=`if(${this.condition})`+super.render(i);return this.else&&(m+="else "+this.else.render(i)),m}optimizeNodes(){super.optimizeNodes();const i=this.condition;if(i===!0)return this.nodes;let m=this.else;if(m){const S=m.optimizeNodes();m=this.else=Array.isArray(S)?new p(S):S}if(m)return i===!1?m instanceof f?m:m.nodes:this.nodes.length?this:new f(_e(i),m instanceof f?[m]:m.nodes);if(!(i===!1||!this.nodes.length))return this}optimizeNames(i,m){var S;if(this.else=(S=this.else)===null||S===void 0?void 0:S.optimizeNames(i,m),!!(super.optimizeNames(i,m)||this.else))return this.condition=L(this.condition,i,m),this}get names(){const i=super.names;return W(i,this.condition),this.else&&F(i,this.else.names),i}}f.kind="if";class v extends y{}v.kind="for";class E extends v{constructor(i){super(),this.iteration=i}render(i){return`for(${this.iteration})`+super.render(i)}optimizeNames(i,m){if(super.optimizeNames(i,m))return this.iteration=L(this.iteration,i,m),this}get names(){return F(super.names,this.iteration.names)}}class P extends v{constructor(i,m,S,O){super(),this.varKind=i,this.name=m,this.from=S,this.to=O}render(i){const m=i.es5?r.varKinds.var:this.varKind,{name:S,from:O,to:C}=this;return`for(${m} ${S}=${O}; ${S}<${C}; ${S}++)`+super.render(i)}get names(){const i=W(super.names,this.from);return W(i,this.to)}}class R extends v{constructor(i,m,S,O){super(),this.loop=i,this.varKind=m,this.name=S,this.iterable=O}render(i){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(i)}optimizeNames(i,m){if(super.optimizeNames(i,m))return this.iterable=L(this.iterable,i,m),this}get names(){return F(super.names,this.iterable.names)}}class U extends y{constructor(i,m,S){super(),this.name=i,this.args=m,this.async=S}render(i){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(i)}}U.kind="func";class A extends b{render(i){return"return "+super.render(i)}}A.kind="return";class Y extends y{render(i){let m="try"+super.render(i);return this.catch&&(m+=this.catch.render(i)),this.finally&&(m+=this.finally.render(i)),m}optimizeNodes(){var i,m;return super.optimizeNodes(),(i=this.catch)===null||i===void 0||i.optimizeNodes(),(m=this.finally)===null||m===void 0||m.optimizeNodes(),this}optimizeNames(i,m){var S,O;return super.optimizeNames(i,m),(S=this.catch)===null||S===void 0||S.optimizeNames(i,m),(O=this.finally)===null||O===void 0||O.optimizeNames(i,m),this}get names(){const i=super.names;return this.catch&&F(i,this.catch.names),this.finally&&F(i,this.finally.names),i}}class B extends y{constructor(i){super(),this.error=i}render(i){return`catch(${this.error})`+super.render(i)}}B.kind="catch";class ce extends y{render(i){return"finally"+super.render(i)}}ce.kind="finally";class j{constructor(i,m={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...m,_n:m.lines?`
2
2
  `:""},this._extScope=i,this._scope=new r.Scope({parent:i}),this._nodes=[new $]}toString(){return this._root.render(this.opts)}name(i){return this._scope.name(i)}scopeName(i){return this._extScope.name(i)}scopeValue(i,m){const S=this._extScope.value(i,m);return(this._values[S.prefix]||(this._values[S.prefix]=new Set)).add(S),S}getScopeValue(i,m){return this._extScope.getValue(i,m)}scopeRefs(i){return this._extScope.scopeRefs(i,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(i,m,S,O){const C=this._scope.toName(m);return S!==void 0&&O&&(this._constants[C.str]=S),this._leafNode(new o(i,C,S)),C}const(i,m,S){return this._def(r.varKinds.const,i,m,S)}let(i,m,S){return this._def(r.varKinds.let,i,m,S)}var(i,m,S){return this._def(r.varKinds.var,i,m,S)}assign(i,m,S){return this._leafNode(new u(i,m,S))}add(i,m){return this._leafNode(new c(i,t.operators.ADD,m))}code(i){return typeof i=="function"?i():i!==e.nil&&this._leafNode(new g(i)),this}object(...i){const m=["{"];for(const[S,O]of i)m.length>1&&m.push(","),m.push(S),(S!==O||this.opts.es5)&&(m.push(":"),(0,e.addCodeArg)(m,O));return m.push("}"),new e._Code(m)}if(i,m,S){if(this._blockNode(new f(i)),m&&S)this.code(m).else().code(S).endIf();else if(m)this.code(m).endIf();else if(S)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(i){return this._elseNode(new f(i))}else(){return this._elseNode(new p)}endIf(){return this._endBlockNode(f,p)}_for(i,m){return this._blockNode(i),m&&this.code(m).endFor(),this}for(i,m){return this._for(new E(i),m)}forRange(i,m,S,O,C=this.opts.es5?r.varKinds.var:r.varKinds.let){const G=this._scope.toName(i);return this._for(new P(C,G,m,S),()=>O(G))}forOf(i,m,S,O=r.varKinds.const){const C=this._scope.toName(i);if(this.opts.es5){const G=m instanceof e.Name?m:this.var("_arr",m);return this.forRange("_i",0,(0,e._)`${G}.length`,K=>{this.var(C,(0,e._)`${G}[${K}]`),S(C)})}return this._for(new R("of",O,C,m),()=>S(C))}forIn(i,m,S,O=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(i,(0,e._)`Object.keys(${m})`,S);const C=this._scope.toName(i);return this._for(new R("in",O,C,m),()=>S(C))}endFor(){return this._endBlockNode(v)}label(i){return this._leafNode(new l(i))}break(i){return this._leafNode(new d(i))}return(i){const m=new A;if(this._blockNode(m),this.code(i),m.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(A)}try(i,m,S){if(!m&&!S)throw new Error('CodeGen: "try" without "catch" and "finally"');const O=new Y;if(this._blockNode(O),this.code(i),m){const C=this.name("e");this._currNode=O.catch=new B(C),m(C)}return S&&(this._currNode=O.finally=new ce,this.code(S)),this._endBlockNode(B,ce)}throw(i){return this._leafNode(new h(i))}block(i,m){return this._blockStarts.push(this._nodes.length),i&&this.code(i).endBlock(m),this}endBlock(i){const m=this._blockStarts.pop();if(m===void 0)throw new Error("CodeGen: not in self-balancing block");const S=this._nodes.length-m;if(S<0||i!==void 0&&S!==i)throw new Error(`CodeGen: wrong number of nodes: ${S} vs ${i} expected`);return this._nodes.length=m,this}func(i,m=e.nil,S,O){return this._blockNode(new U(i,m,S)),O&&this.code(O).endFunc(),this}endFunc(){return this._endBlockNode(U)}optimize(i=1){for(;i-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(i){return this._currNode.nodes.push(i),this}_blockNode(i){this._currNode.nodes.push(i),this._nodes.push(i)}_endBlockNode(i,m){const S=this._currNode;if(S instanceof i||m&&S instanceof m)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${m?`${i.kind}/${m.kind}`:i.kind}"`)}_elseNode(i){const m=this._currNode;if(!(m instanceof f))throw new Error('CodeGen: "else" without "if"');return this._currNode=m.else=i,this}get _root(){return this._nodes[0]}get _currNode(){const i=this._nodes;return i[i.length-1]}set _currNode(i){const m=this._nodes;m[m.length-1]=i}}t.CodeGen=j;function F(w,i){for(const m in i)w[m]=(w[m]||0)+(i[m]||0);return w}function W(w,i){return i instanceof e._CodeOrName?F(w,i.names):w}function L(w,i,m){if(w instanceof e.Name)return S(w);if(!O(w))return w;return new e._Code(w._items.reduce((C,G)=>(G instanceof e.Name&&(G=S(G)),G instanceof e._Code?C.push(...G._items):C.push(G),C),[]));function S(C){const G=m[C.str];return G===void 0||i[C.str]!==1?C:(delete i[C.str],G)}function O(C){return C instanceof e._Code&&C._items.some(G=>G instanceof e.Name&&i[G.str]===1&&m[G.str]!==void 0)}}function ee(w,i){for(const m in i)w[m]=(w[m]||0)-(i[m]||0)}function _e(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:(0,e._)`!${k(w)}`}t.not=_e;const ge=_(t.operators.AND);function We(...w){return w.reduce(ge)}t.and=We;const Te=_(t.operators.OR);function T(...w){return w.reduce(Te)}t.or=T;function _(w){return(i,m)=>i===e.nil?m:m===e.nil?i:(0,e._)`${k(i)} ${w} ${k(m)}`}function k(w){return w instanceof e.Name?w:(0,e._)`(${w})`}})(V);var I={};Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;const J=V,$n=nt;function vn(t){const e={};for(const r of t)e[r]=!0;return e}I.toHash=vn;function wn(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(As(t,e),!Ds(e,t.self.RULES.all))}I.alwaysValidSchema=wn;function As(t,e=t.schema){const{opts:r,self:s}=t;if(!r.strictSchema||typeof e=="boolean")return;const a=s.RULES.keywords;for(const n in e)a[n]||Fs(t,`unknown keyword: "${n}"`)}I.checkUnknownRules=As;function Ds(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}I.schemaHasRules=Ds;function bn(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}I.schemaHasRulesButRef=bn;function Sn({topSchemaRef:t,schemaPath:e},r,s,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,J._)`${r}`}return(0,J._)`${t}${e}${(0,J.getProperty)(s)}`}I.schemaRefOrVal=Sn;function kn(t){return zs(decodeURIComponent(t))}I.unescapeFragment=kn;function En(t){return encodeURIComponent(lr(t))}I.escapeFragment=En;function lr(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=lr;function zs(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=zs;function Pn(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}I.eachItem=Pn;function us({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:s}){return(a,n,o,u)=>{const c=o===void 0?n:o instanceof J.Name?(n instanceof J.Name?t(a,n,o):e(a,n,o),o):n instanceof J.Name?(e(a,o,n),n):r(n,o);return u===J.Name&&!(c instanceof J.Name)?s(a,c):c}}I.mergeEvaluated={props:us({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,J._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,J._)`${r} || {}`).code((0,J._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,J._)`${r} || {}`),dr(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Vs}),items:us({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,J._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,J._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Vs(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,J._)`{}`);return e!==void 0&&dr(t,r,e),r}I.evaluatedPropsToName=Vs;function dr(t,e,r){Object.keys(r).forEach(s=>t.assign((0,J._)`${e}${(0,J.getProperty)(s)}`,!0))}I.setEvaluated=dr;const ls={};function Tn(t,e){return t.scopeValue("func",{ref:e,code:ls[e.code]||(ls[e.code]=new $n._Code(e.code))})}I.useFunc=Tn;var sr;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(sr||(I.Type=sr={}));function Rn(t,e,r){if(t instanceof J.Name){const s=e===sr.Num;return r?s?(0,J._)`"[" + ${t} + "]"`:(0,J._)`"['" + ${t} + "']"`:s?(0,J._)`"/" + ${t}`:(0,J._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,J.getProperty)(t).toString():"/"+lr(t)}I.getErrorPath=Rn;function Fs(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Fs;var ye={};Object.defineProperty(ye,"__esModule",{value:!0});const se=V,In={data:new se.Name("data"),valCxt:new se.Name("valCxt"),instancePath:new se.Name("instancePath"),parentData:new se.Name("parentData"),parentDataProperty:new se.Name("parentDataProperty"),rootData:new se.Name("rootData"),dynamicAnchors:new se.Name("dynamicAnchors"),vErrors:new se.Name("vErrors"),errors:new se.Name("errors"),this:new se.Name("this"),self:new se.Name("self"),scope:new se.Name("scope"),json:new se.Name("json"),jsonPos:new se.Name("jsonPos"),jsonLen:new se.Name("jsonLen"),jsonPart:new se.Name("jsonPart")};ye.default=In;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=V,r=I,s=ye;t.keywordError={message:({keyword:p})=>(0,e.str)`must pass "${p}" keyword validation`},t.keyword$DataError={message:({keyword:p,schemaType:f})=>f?(0,e.str)`"${p}" keyword must be ${f} ($data)`:(0,e.str)`"${p}" keyword is invalid ($data)`};function a(p,f=t.keywordError,v,E){const{it:P}=p,{gen:R,compositeRule:U,allErrors:A}=P,Y=h(p,f,v);E??(U||A)?c(R,Y):l(P,(0,e._)`[${Y}]`)}t.reportError=a;function n(p,f=t.keywordError,v){const{it:E}=p,{gen:P,compositeRule:R,allErrors:U}=E,A=h(p,f,v);c(P,A),R||U||l(E,s.default.vErrors)}t.reportExtraError=n;function o(p,f){p.assign(s.default.errors,f),p.if((0,e._)`${s.default.vErrors} !== null`,()=>p.if(f,()=>p.assign((0,e._)`${s.default.vErrors}.length`,f),()=>p.assign(s.default.vErrors,null)))}t.resetErrorsCount=o;function u({gen:p,keyword:f,schemaValue:v,data:E,errsCount:P,it:R}){if(P===void 0)throw new Error("ajv implementation error");const U=p.name("err");p.forRange("i",P,s.default.errors,A=>{p.const(U,(0,e._)`${s.default.vErrors}[${A}]`),p.if((0,e._)`${U}.instancePath === undefined`,()=>p.assign((0,e._)`${U}.instancePath`,(0,e.strConcat)(s.default.instancePath,R.errorPath))),p.assign((0,e._)`${U}.schemaPath`,(0,e.str)`${R.errSchemaPath}/${f}`),R.opts.verbose&&(p.assign((0,e._)`${U}.schema`,v),p.assign((0,e._)`${U}.data`,E))})}t.extendErrors=u;function c(p,f){const v=p.const("err",f);p.if((0,e._)`${s.default.vErrors} === null`,()=>p.assign(s.default.vErrors,(0,e._)`[${v}]`),(0,e._)`${s.default.vErrors}.push(${v})`),p.code((0,e._)`${s.default.errors}++`)}function l(p,f){const{gen:v,validateName:E,schemaEnv:P}=p;P.$async?v.throw((0,e._)`new ${p.ValidationError}(${f})`):(v.assign((0,e._)`${E}.errors`,f),v.return(!1))}const d={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function h(p,f,v){const{createErrors:E}=p.it;return E===!1?(0,e._)`{}`:g(p,f,v)}function g(p,f,v={}){const{gen:E,it:P}=p,R=[b(P,v),y(p,v)];return $(p,f,R),E.object(...R)}function b({errorPath:p},{instancePath:f}){const v=f?(0,e.str)`${p}${(0,r.getErrorPath)(f,r.Type.Str)}`:p;return[s.default.instancePath,(0,e.strConcat)(s.default.instancePath,v)]}function y({keyword:p,it:{errSchemaPath:f}},{schemaPath:v,parentSchema:E}){let P=E?f:(0,e.str)`${f}/${p}`;return v&&(P=(0,e.str)`${P}${(0,r.getErrorPath)(v,r.Type.Str)}`),[d.schemaPath,P]}function $(p,{params:f,message:v},E){const{keyword:P,data:R,schemaValue:U,it:A}=p,{opts:Y,propertyName:B,topSchemaRef:ce,schemaPath:j}=A;E.push([d.keyword,P],[d.params,typeof f=="function"?f(p):f||(0,e._)`{}`]),Y.messages&&E.push([d.message,typeof v=="function"?v(p):v]),Y.verbose&&E.push([d.schema,U],[d.parentSchema,(0,e._)`${ce}${j}`],[s.default.data,R]),B&&E.push([d.propertyName,B])}})(ot);Object.defineProperty(Ue,"__esModule",{value:!0});Ue.boolOrEmptySchema=Ue.topBoolOrEmptySchema=void 0;const Nn=ot,On=V,Cn=ye,jn={message:"boolean schema is false"};function Mn(t){const{gen:e,schema:r,validateName:s}=t;r===!1?Hs(t,!1):typeof r=="object"&&r.$async===!0?e.return(Cn.default.data):(e.assign((0,On._)`${s}.errors`,null),e.return(!0))}Ue.topBoolOrEmptySchema=Mn;function qn(t,e){const{gen:r,schema:s}=t;s===!1?(r.var(e,!1),Hs(t)):r.var(e,!0)}Ue.boolOrEmptySchema=qn;function Hs(t,e){const{gen:r,data:s}=t,a={gen:r,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Nn.reportError)(a,jn,void 0,e)}var X={},je={};Object.defineProperty(je,"__esModule",{value:!0});je.getRules=je.isJSONType=void 0;const An=["string","number","integer","boolean","null","object","array"],Dn=new Set(An);function zn(t){return typeof t=="string"&&Dn.has(t)}je.isJSONType=zn;function Vn(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}je.getRules=Vn;var $e={};Object.defineProperty($e,"__esModule",{value:!0});$e.shouldUseRule=$e.shouldUseGroup=$e.schemaHasRulesForType=void 0;function Fn({schema:t,self:e},r){const s=e.RULES.types[r];return s&&s!==!0&&Ls(t,s)}$e.schemaHasRulesForType=Fn;function Ls(t,e){return e.rules.some(r=>Us(t,r))}$e.shouldUseGroup=Ls;function Us(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(s=>t[s]!==void 0))}$e.shouldUseRule=Us;Object.defineProperty(X,"__esModule",{value:!0});X.reportTypeError=X.checkDataTypes=X.checkDataType=X.coerceAndCheckDataType=X.getJSONTypes=X.getSchemaTypes=X.DataType=void 0;const Hn=je,Ln=$e,Un=ot,D=V,Ks=I;var He;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(He||(X.DataType=He={}));function Kn(t){const e=Gs(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}X.getSchemaTypes=Kn;function Gs(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(Hn.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}X.getJSONTypes=Gs;function Gn(t,e){const{gen:r,data:s,opts:a}=t,n=Jn(e,a.coerceTypes),o=e.length>0&&!(n.length===0&&e.length===1&&(0,Ln.schemaHasRulesForType)(t,e[0]));if(o){const u=fr(e,s,a.strictNumbers,He.Wrong);r.if(u,()=>{n.length?Qn(t,e,n):hr(t)})}return o}X.coerceAndCheckDataType=Gn;const Js=new Set(["string","number","integer","boolean","null"]);function Jn(t,e){return e?t.filter(r=>Js.has(r)||e==="array"&&r==="array"):[]}function Qn(t,e,r){const{gen:s,data:a,opts:n}=t,o=s.let("dataType",(0,D._)`typeof ${a}`),u=s.let("coerced",(0,D._)`undefined`);n.coerceTypes==="array"&&s.if((0,D._)`${o} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>s.assign(a,(0,D._)`${a}[0]`).assign(o,(0,D._)`typeof ${a}`).if(fr(e,a,n.strictNumbers),()=>s.assign(u,a))),s.if((0,D._)`${u} !== undefined`);for(const l of r)(Js.has(l)||l==="array"&&n.coerceTypes==="array")&&c(l);s.else(),hr(t),s.endIf(),s.if((0,D._)`${u} !== undefined`,()=>{s.assign(a,u),Wn(t,u)});function c(l){switch(l){case"string":s.elseIf((0,D._)`${o} == "number" || ${o} == "boolean"`).assign(u,(0,D._)`"" + ${a}`).elseIf((0,D._)`${a} === null`).assign(u,(0,D._)`""`);return;case"number":s.elseIf((0,D._)`${o} == "boolean" || ${a} === null
3
3
  || (${o} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,D._)`+${a}`);return;case"integer":s.elseIf((0,D._)`${o} === "boolean" || ${a} === null
4
4
  || (${o} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(u,(0,D._)`+${a}`);return;case"boolean":s.elseIf((0,D._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(u,!1).elseIf((0,D._)`${a} === "true" || ${a} === 1`).assign(u,!0);return;case"null":s.elseIf((0,D._)`${a} === "" || ${a} === 0 || ${a} === false`),s.assign(u,null);return;case"array":s.elseIf((0,D._)`${o} === "string" || ${o} === "number"
package/web/index.html CHANGED
@@ -13,8 +13,8 @@
13
13
  <meta name="twitter:title" content="onPanda: Steer LLMs and Agents at the Token Level">
14
14
  <meta name="twitter:description" content="An interactive tool for token visualization &amp; control, model inspection, data annotation, and more.">
15
15
  <meta name="twitter:image" content="https://on-panda.github.io/img/video-cover.jpg">
16
- <script type="module" crossorigin src="/assets/index-VDofnkb1.js"></script>
17
- <link rel="stylesheet" crossorigin href="/assets/index-6pA5bJ5o.css">
16
+ <script type="module" crossorigin src="/assets/index-CSSh_R5o.js"></script>
17
+ <link rel="stylesheet" crossorigin href="/assets/index-CmJzwRhj.css">
18
18
  </head>
19
19
  <body>
20
20
  <div id="app"></div>
@@ -1,35 +0,0 @@
1
- const M=Object.getPrototypeOf(async function(){}).constructor,R=256*1024,g=200,w=6e4,j={"image/png":"image","image/jpeg":"image","image/gif":"image","image/webp":"image","audio/wav":"audio","audio/mp3":"audio","audio/mpeg":"audio","video/mp4":"video","video/webm":"video","video/quicktime":"video"},x={name:"run_browser_js",description:"Run JavaScript in the current browser runtime and return logs from `console.log`. `console.log` accepts `Blob` arguments of MCP-supported image, audio, and video types, returned as inline media in your context. Each tool call uses a fresh local scope, so local variables do not persist across calls, but shared globals like window and document do persist. Your JavaScript local scope includes a `browserAgent` variable. For content that should be reused across tool calls, prefer storing it on the `browserAgent.local` object. You can access the internet under CORS restrictions. Do not refresh or switch the current webpage, as this will reset the JavaScript runtime and your context lost.",inputSchema:{type:"object",properties:{code:{type:"string",description:"If your code starts any async work, such as fetch, promises, or async functions, await it with top-level await or await the returned promise; otherwise the tool may return before later logs run. Do not rely on un-awaited .then() callbacks for console.log output."}}}},$={name:"render_svg",description:"Render an SVG string into a bitmap PNG image. The tool uses the SVG width/height, or falls back to viewBox.",inputSchema:{type:"object",properties:{svg:{type:"string",description:"SVG markup to render. It must start with `<svg` and end with `</svg>`."}}}};function O(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=r.result;t(o.slice(o.indexOf(",")+1))},r.onerror=n,r.readAsDataURL(e)})}function y(e=""){return`<|js_error_start|>
2
- ${e}
3
- <|js_error_end|>`}function v(e="",t=R){if(e.length<=t)return e;const n=Math.ceil(t/2),r=t-n,o=e.length-t;return`(Total length: ${e.length} characters. Showing ${t} characters after truncating the middle.)
4
- ${e.slice(0,n)}
5
- <|truncate_long_text|>
6
- {Output exceeded ${t} characters. Omitted ${o} characters from the middle.} ......
7
- <|truncate_long_text|>
8
- ${e.slice(e.length-r)}`}async function E(){return await(await(await(await(await(await navigator.storage.getDirectory()).getDirectoryHandle("browser-agent",{create:!0})).getDirectoryHandle("memory",{create:!0})).getFileHandle("MEMORY.md",{create:!0})).getFile()).text()}function A(e=""){const t=e.split(`
9
- `),n=[];let r=t.length>g?t.slice(0,g).join(`
10
- `):e;return t.length>g&&n.push(`original ${t.length} lines exceeded ${g} lines`),e.length>w&&n.push(`original ${e.length} characters exceeded ${w} characters`),r.length>w&&(r=r.slice(0,w)),{text:r,truncationReason:n.length?`Truncated: ${n.join("; ")}. So, find an opportunity to organize the memory: clean up or archive outdated or unimportant information, move less important content out of the MEMORY.md into other files or folders under \`browser-agent/memory/\`, and keep only brief descriptions and references in the MEMORY.md so you can read the archived content later when needed.`:""}}async function B(){const e=`## Persistent memory
11
- Persistent memory is stored in files or folders under \`browser-agent/memory/\` in the current origin's OPFS. Use \`run_browser_js\` and \`navigator.storage.getDirectory()\` to record, modify, and query memory when needed. \`browser-agent/memory/MEMORY.md\` is always loaded into your conversation context. Keep it concise; it is truncated after ${g} lines or ${w} characters.`,t=await E();if(!t.trim())return`${e}
12
- The current \`browser-agent/memory/MEMORY.md\` is empty.`;const{text:n,truncationReason:r}=A(t);return`${e}
13
- ### the MEMORY.md
14
- <|browser_agent_memory_start|>
15
- ${n}
16
- <|browser_agent_memory_end|>${r?`
17
- ${r}`:""}`}async function U(e="",t){const n=[],r=[],o=performance.now(),s={...console,log(...i){const a=i.map(c=>{const f=c instanceof Blob?j[c.type]:null;if(f){const b={type:f,mimeType:c.type,data:""};return r.push(O(c).then(S=>{b.data=S})),b}return String(c)});n.push({kind:"log",row:a}),console.log("[run_browser_js.log]:",...i)},error(...i){const a=i.map(c=>String(c)).join(" ");n.push({kind:"error",text:y(a)}),console.log("[run_browser_js.error]:",a)}},p=t({callScope:{console:s}});try{await new M("console","browserAgent",e)(s,p)}catch(i){const a=String(i);n.push({kind:"error",text:y(a)}),console.log("[run_browser_js.error]:",a)}await Promise.all(r);const h=[{type:"text",text:`<|execution_info_start|>
18
- Code execution time: ${Math.round(performance.now()-o)} ms
19
- <|execution_info_end|>`}];n.some(i=>i.kind==="log")||h.push({type:"text",text:"<|no_js_log|>"});let l="";const u=()=>{l&&(h.push({type:"text",text:v(l)}),l="")};return n.forEach(i=>{i.kind==="log"?i.row.forEach((a,c)=>{typeof a=="string"?(l&&(l+=c===0?`
20
- `:" "),l+=a):(u(),h.push(a))}):(u(),h.push({type:"text",text:v(i.text)}))}),u(),h}async function F(e=""){const t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml"}));try{const n=await new Promise((h,l)=>{const u=new Image;u.onload=()=>h(u),u.onerror=l,u.src=t}),r=new DOMParser().parseFromString(e,"image/svg+xml").documentElement,o=Number.parseFloat(r.getAttribute("width")),s=Number.parseFloat(r.getAttribute("height")),p=(r.getAttribute("viewBox")||"").trim().split(/[\s,]+/).map(Number),d=document.createElement("canvas");return d.width=Number.isFinite(o)&&Number.isFinite(s)?o:p.length===4?p[2]:n.naturalWidth,d.height=Number.isFinite(o)&&Number.isFinite(s)?s:p.length===4?p[3]:n.naturalHeight,d.getContext("2d").drawImage(n,0,0,d.width,d.height),d.toDataURL("image/png").slice(22)}finally{URL.revokeObjectURL(t)}}function k(e,t={}){return new Response(JSON.stringify(e),{status:200,headers:{"content-type":"application/json"},...t})}function m(e,t){return k({jsonrpc:"2.0",id:e,result:t})}function _(e,t,n){return k({jsonrpc:"2.0",id:e,error:{code:t,message:n}})}async function I({message:e={},instructions:t="",buildBrowserAgent:n}={}){var r,o;if(e.method==="initialize")return m(e.id,{protocolVersion:e.params.protocolVersion,capabilities:{tools:{}},serverInfo:{name:"browser-agent-mcp",version:"0.1.0"},instructions:t});if(e.method==="ping")return m(e.id,{});if(e.method==="tools/list")return m(e.id,{tools:[x,$]});if(e.method==="tools/call"){if(e.params.name==="run_browser_js"){const s=await U(((r=e.params.arguments)==null?void 0:r.code)||"",n);return m(e.id,{content:s})}if(e.params.name==="render_svg"){const s=await F(((o=e.params.arguments)==null?void 0:o.svg)||"");return m(e.id,{content:[{type:"image",mimeType:"image/png",data:s}]})}return _(e.id,-32601,`Tool not found: ${e.params.name}`)}return e.id==null?new Response(null,{status:204}):_(e.id,-32601,`Method not found: ${e.method}`)}async function T({proxyPath:e=""}={}){return`You are an agent running in a browser. You are operating in the JavaScript runtime of the current webpage, where the user interacts with you. Please make the appropriate adjustments for this browser JavaScript environment.
21
-
22
- ## Skills
23
- A skill is a set of instructions to follow that is stored in a \`SKILL.md\` file. Below is the list of skills that can be used. Each entry includes a name, description, and skillUrl so you can open the source for full instructions when using a specific skill.
24
- ### Available skills
25
- - \`cors-internet\`: Skill for web search and information retrieval under CORS. Use when you need to access the internet. ([skillUrl](https://raw.githubusercontent.com/on-panda/browser-agent-skills/main/skills/cors-internet/SKILL.md))${e?`
26
- - Fallback: for critical resources that even cors-internet cannot reach, use the server-side proxy at \`${e}/{url}\`.`:""}
27
- - \`interactive-webpage\`: Use when you need to create webpages or interactive artifacts, or modify the current UI. ([skillUrl](https://raw.githubusercontent.com/on-panda/browser-agent-skills/main/skills/interactive-webpage/SKILL.md))
28
- - \`user-local-files\`: Use when the user shares local files, indicated by \`<|user_local_files\` in the context. Includes local filesystem read/write guidelines and common tools. ([skillUrl](https://raw.githubusercontent.com/on-panda/browser-agent-skills/main/skills/user-local-files/SKILL.md))
29
- ### How to load skills
30
- If the task clearly matches a skill's description shown above, using tool "run_browser_js" with this pattern code to load the skill:
31
- \`\`\`js
32
- await fetch(skillUrl).then(res => res.text()).then(console.log)
33
- \`\`\`
34
-
35
- ${await B()}`}function L({buildBrowserAgent:e,proxyPath:t=""}={}){return{localFetch:async function(r,o={}){if((o.method||"GET")!=="POST")return new Response(null,{status:405});const s=JSON.parse(o.body||"{}");return await I({message:s,instructions:s.method==="initialize"?await T({proxyPath:t}):"",buildBrowserAgent:e})}}}export{L as BrowserAgentMcpClosure};