@runappsai/agent 0.1.15 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- /* @runappsai/agent 0.1.15 (core) */
2
- "use strict";var RunAppsAgent=(()=>{var Oe=Object.defineProperty;var In=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var Fn=Object.prototype.hasOwnProperty;var Nn=(r,e,t)=>e in r?Oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var zn=(r,e)=>{for(var t in e)Oe(r,t,{get:e[t],enumerable:!0})},Wn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jn(e))!Fn.call(r,s)&&s!==t&&Oe(r,s,{get:()=>e[s],enumerable:!(n=In(e,s))||n.enumerable});return r};var Bn=r=>Wn(Oe({},"__esModule",{value:!0}),r);var y=(r,e,t)=>Nn(r,typeof e!="symbol"?e+"":e,t);var rs={};zn(rs,{Agent:()=>pe,ContextOverflowError:()=>G,DEFAULT_COMPACTION:()=>je,DEFAULT_SKILLS_DIR:()=>Ct,DEFAULT_USER_SKILLS_DIR:()=>$t,MCPError:()=>D,PartialReadError:()=>Q,ProviderError:()=>q,Scheduler:()=>ht,UNTITLED:()=>ce,WEB_TOOL_NAMES:()=>Rt,Workspace:()=>le,applyEdits:()=>He,askUserTool:()=>ct,buildSystemPrompt:()=>Ie,buildZip:()=>Qt,changeTask:()=>zt,checkSchedule:()=>ft,collectCompletion:()=>be,configurePdf:()=>sn,connectMCP:()=>Dn,createAgent:()=>ts,decodeText:()=>X,defineTool:()=>L,describeSchedule:()=>Ft,domUI:()=>lt,estimateTokens:()=>M,expandSlash:()=>ze,extractPdfText:()=>Ze,fileGuard:()=>ue,fileTools:()=>st,fitBudget:()=>ge,formatLocalTime:()=>ee,formatPdfText:()=>Xe,groupTurns:()=>mt,guessType:()=>V,isContextOverflow:()=>De,isPdf:()=>Ge,listTemplates:()=>Gt,listZip:()=>Ke,localSchedules:()=>Cn,makeTask:()=>Nt,memoryFS:()=>hn,memorySchedules:()=>$n,modelAccepts:()=>Le,nextRun:()=>Re,normalizeForFuzzyMatch:()=>vt,normalizePath:()=>x,normalizeResult:()=>ke,nullUI:()=>Dt,openAIProvider:()=>Kt,openWorkspace:()=>ns,parseCommandArgs:()=>kt,parseCron:()=>Me,parseFrontmatter:()=>St,parseLocalTime:()=>Ee,parseSkill:()=>Se,planCut:()=>Fe,readZipEntry:()=>se,runInSandbox:()=>Et,runappsProvider:()=>pt,sandboxTool:()=>ot,scheduleTools:()=>En,serializeConversation:()=>we,skillFoldersOf:()=>ve,skillZipFS:()=>oe,splitForSummary:()=>Ne,sseData:()=>me,subFS:()=>Te,substituteArgs:()=>xt,summaryMessage:()=>ye,summaryOf:()=>K,titleOf:()=>$e,toProvider:()=>Z,validateSchema:()=>it,webTools:()=>at});function Le(r,e){if(r){if(Array.isArray(r.input_modalities))return r.input_modalities.includes(e);if(e==="image"&&r.capability==="vision")return!0}}var q=class extends Error{constructor(t,n,s={}){super(n);y(this,"status");y(this,"code");y(this,"retryAfter");this.name="ProviderError",this.status=t,this.code=s.code,this.retryAfter=s.retryAfter}get statusCode(){return this.status}},qn={attachments:"The attachments on this message are too large for the model's context",message:"This message is too long for the model's context",tools:"The connected tools take up too much of the model's context",history:"This conversation is too long for the model's context",model:"This request does not fit the model's context"},G=class extends q{constructor(t,n,s=400){super(s,qn[t.cause],{code:"context_overflow"});y(this,"overflow");y(this,"detail");this.name="ContextOverflowError",this.overflow=t,this.detail=n}},Kn=/context[_ ]length|context[_ ]window|maximum context|(?:prompt|input|request|message)s? (?:is |are )?too (?:long|large)|too many (?:input |prompt )?tokens|prompt tokens too many|exceed\w* .{0,30}(?:context|token limit|input token)|input token count|max_input_tokens|range of input length|payload too large|entity too large/i;function De(r){if(r instanceof G)return!0;let e=Ue(r);if(e===401||e===402||e===403||e===404||e===429)return!1;if(e===413)return!0;let t=r?.code;return t==="context_length_exceeded"||t==="context_overflow"?!0:r instanceof Error&&Kn.test(r.message)}function qt(r){let e=r instanceof Error?r.message:"",n=/its ([\d,]+) max_input_tokens|maximum context length is ([\d,]+)|> ?([\d,]+) maximum|context (?:window|length) of ([\d,]+)|token limit\D{0,5}([\d,]+)|\[1, ?([\d,]+)\]/i.exec(e)?.slice(1).find(Boolean),s=n?Number(n.replace(/,/g,"")):NaN;return s>=1e3?s:void 0}function Ue(r){if(!r||typeof r!="object")return;let e=r;return typeof e.statusCode=="number"?e.statusCode:typeof e.status=="number"?e.status:void 0}function pt(r){let e=r.files;return{name:r.projectName,stream:(t,n)=>r.chat.stream(t,n),complete:r.chat.create?(t,n)=>r.chat.create(t,n):void 0,models:r.models?.list?async t=>await r.models.list(t):void 0,platformTools:r.tools,readFile:e?async(t,n)=>{let s=await e.stat(t);return n?.etag&&s.etag&&n.etag===s.etag?null:{bytes:new Uint8Array(await(await e.get(t)).arrayBuffer()),etag:s.etag}}:void 0}}function Z(r){if(typeof r.stream=="function")return r;if(typeof r.chat?.stream=="function")return pt(r);throw new Error("pass a ModelProvider (with stream()) or a RunApps client")}function Kt(r){let e=r.baseURL.replace(/\/+$/,""),t=r.fetch??((...o)=>fetch(...o)),n=()=>({"Content-Type":"application/json",...r.apiKey?{Authorization:`Bearer ${r.apiKey}`}:{},...r.headers??{}}),s=async(o,i)=>{let a;try{a=await t(`${e}/chat/completions`,{method:"POST",headers:n(),body:JSON.stringify(o),signal:i})}catch(l){throw i?.aborted?l:new q(0,`network error: ${l.message}`)}if(!a.ok)throw await Bt(a);return a};return{name:r.name,async*stream(o,i){let a={...o,stream:!0,...r.streamUsage===!1?{}:{stream_options:{include_usage:!0}}},l=await s(a,i?.signal);if(!l.body)throw new q(0,"the response has no body to stream");for await(let c of me(l.body,i?.signal)){if(c==="[DONE]")return;let u;try{u=JSON.parse(c)}catch{continue}if(u.error)throw new q(500,u.error.message??"stream error",{code:u.error.code});yield u}},async complete(o,i){return await(await s({...o,stream:!1},i?.signal)).json()},models:r.models===void 0?void 0:async()=>{if(Array.isArray(r.models))return r.models;let o=await t(`${e}/models`,{headers:n()});if(!o.ok)throw await Bt(o);return((await o.json()).data??[]).map(({id:a,is_default:l,capability:c,max_input_tokens:u,max_tokens:d,options:f})=>({id:a,is_default:l,capability:c??"text",max_input_tokens:u,max_tokens:d,options:f}))}}}async function Bt(r){let e=`HTTP ${r.status}`,t;try{let s=await r.json();typeof s.error=="string"?e=s.error:s.error?.message?(e=s.error.message,t=s.error.code??s.error.type):s.message&&(e=s.message)}catch{}let n=Number(r.headers.get("Retry-After"));return new q(r.status,e,{code:t,retryAfter:Number.isFinite(n)&&n>0?n:void 0})}async function*me(r,e){let t=r.getReader(),n=new TextDecoder,s="",o=()=>{t.cancel().catch(()=>{})};e?.addEventListener("abort",o,{once:!0});try{for(;;){let{done:a,value:l}=await t.read();if(a)break;s+=n.decode(l,{stream:!0});let c;for(;(c=s.search(/\r?\n\r?\n/))>=0;){let u=s.slice(0,c);s=s.slice(c).replace(/^\r?\n\r?\n/,"");let d=u.split(/\r?\n/).filter(f=>f.startsWith("data:")).map(f=>f.slice(5).replace(/^ /,"")).join(`
1
+ /* @runappsai/agent 0.2.1 (core) */
2
+ "use strict";var RunAppsAgent=(()=>{var Oe=Object.defineProperty;var In=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var Fn=Object.prototype.hasOwnProperty;var Nn=(r,e,t)=>e in r?Oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var zn=(r,e)=>{for(var t in e)Oe(r,t,{get:e[t],enumerable:!0})},Wn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jn(e))!Fn.call(r,s)&&s!==t&&Oe(r,s,{get:()=>e[s],enumerable:!(n=In(e,s))||n.enumerable});return r};var Bn=r=>Wn(Oe({},"__esModule",{value:!0}),r);var y=(r,e,t)=>Nn(r,typeof e!="symbol"?e+"":e,t);var rs={};zn(rs,{Agent:()=>fe,ContextOverflowError:()=>G,DEFAULT_COMPACTION:()=>je,DEFAULT_SKILLS_DIR:()=>_t,DEFAULT_USER_SKILLS_DIR:()=>Mt,MCPError:()=>U,PartialReadError:()=>ee,ProviderError:()=>q,Scheduler:()=>ft,UNTITLED:()=>ue,WEB_TOOL_NAMES:()=>Lt,Workspace:()=>ce,applyEdits:()=>He,askUserTool:()=>dt,buildSystemPrompt:()=>Ie,buildZip:()=>Qt,changeTask:()=>zt,checkSchedule:()=>mt,collectCompletion:()=>be,configurePdf:()=>sn,connectMCP:()=>Dn,createAgent:()=>ts,decodeText:()=>X,defineTool:()=>D,describeSchedule:()=>Ft,domUI:()=>ut,estimateTokens:()=>E,expandSlash:()=>ze,extractPdfText:()=>Ze,fileGuard:()=>de,fileTools:()=>st,fitBudget:()=>ge,formatLocalTime:()=>te,formatPdfText:()=>Xe,groupTurns:()=>yt,guessType:()=>Q,isContextOverflow:()=>De,isPdf:()=>Ge,listTemplates:()=>Gt,listZip:()=>Ke,localSchedules:()=>Cn,makeTask:()=>Nt,memoryFS:()=>hn,memorySchedules:()=>$n,modelAccepts:()=>Le,nextRun:()=>Re,normalizeForFuzzyMatch:()=>At,normalizePath:()=>x,normalizeResult:()=>ke,nullUI:()=>Dt,openAIProvider:()=>Kt,openWorkspace:()=>ns,parseCommandArgs:()=>vt,parseCron:()=>Me,parseFrontmatter:()=>Tt,parseLocalTime:()=>Ee,parseSkill:()=>ve,planCut:()=>Fe,readZipEntry:()=>ie,runInSandbox:()=>Ot,runappsProvider:()=>gt,sandboxTool:()=>ot,scheduleTools:()=>En,serializeConversation:()=>we,skillFoldersOf:()=>Se,skillZipFS:()=>ae,splitForSummary:()=>Ne,sseData:()=>me,subFS:()=>Te,substituteArgs:()=>St,summaryMessage:()=>ye,summaryOf:()=>K,titleOf:()=>$e,toProvider:()=>Z,validateSchema:()=>it,webTools:()=>at});function Le(r,e){if(r){if(Array.isArray(r.input_modalities))return r.input_modalities.includes(e);if(e==="image"&&r.capability==="vision")return!0}}var q=class extends Error{constructor(t,n,s={}){super(n);y(this,"status");y(this,"code");y(this,"retryAfter");this.name="ProviderError",this.status=t,this.code=s.code,this.retryAfter=s.retryAfter}get statusCode(){return this.status}},qn={attachments:"The attachments on this message are too large for the model's context",message:"This message is too long for the model's context",tools:"The connected tools take up too much of the model's context",history:"This conversation is too long for the model's context",model:"This request does not fit the model's context"},G=class extends q{constructor(t,n,s=400){super(s,qn[t.cause],{code:"context_overflow"});y(this,"overflow");y(this,"detail");this.name="ContextOverflowError",this.overflow=t,this.detail=n}},Kn=/context[_ ]length|context[_ ]window|maximum context|(?:prompt|input|request|message)s? (?:is |are )?too (?:long|large)|too many (?:input |prompt )?tokens|prompt tokens too many|exceed\w* .{0,30}(?:context|token limit|input token)|input token count|max_input_tokens|range of input length|payload too large|entity too large/i;function De(r){if(r instanceof G)return!0;let e=Ue(r);if(e===401||e===402||e===403||e===404||e===429)return!1;if(e===413)return!0;let t=r?.code;return t==="context_length_exceeded"||t==="context_overflow"?!0:r instanceof Error&&Kn.test(r.message)}function qt(r){let e=r instanceof Error?r.message:"",n=/its ([\d,]+) max_input_tokens|maximum context length is ([\d,]+)|> ?([\d,]+) maximum|context (?:window|length) of ([\d,]+)|token limit\D{0,5}([\d,]+)|\[1, ?([\d,]+)\]/i.exec(e)?.slice(1).find(Boolean),s=n?Number(n.replace(/,/g,"")):NaN;return s>=1e3?s:void 0}function Ue(r){if(!r||typeof r!="object")return;let e=r;return typeof e.statusCode=="number"?e.statusCode:typeof e.status=="number"?e.status:void 0}function gt(r){let e=r.files;return{name:r.projectName,stream:(t,n)=>r.chat.stream(t,n),complete:r.chat.create?(t,n)=>r.chat.create(t,n):void 0,models:r.models?.list?async t=>await r.models.list(t):void 0,platformTools:r.tools,readFile:e?async(t,n)=>{let s=await e.stat(t);return n?.etag&&s.etag&&n.etag===s.etag?null:{bytes:new Uint8Array(await(await e.get(t)).arrayBuffer()),etag:s.etag}}:void 0}}function Z(r){if(typeof r.stream=="function")return r;if(typeof r.chat?.stream=="function")return gt(r);throw new Error("pass a ModelProvider (with stream()) or a RunApps client")}function Kt(r){let e=r.baseURL.replace(/\/+$/,""),t=r.fetch??((...o)=>fetch(...o)),n=()=>({"Content-Type":"application/json",...r.apiKey?{Authorization:`Bearer ${r.apiKey}`}:{},...r.headers??{}}),s=async(o,i)=>{let a;try{a=await t(`${e}/chat/completions`,{method:"POST",headers:n(),body:JSON.stringify(o),signal:i})}catch(l){throw i?.aborted?l:new q(0,`network error: ${l.message}`)}if(!a.ok)throw await Bt(a);return a};return{name:r.name,async*stream(o,i){let a={...o,stream:!0,...r.streamUsage===!1?{}:{stream_options:{include_usage:!0}}},l=await s(a,i?.signal);if(!l.body)throw new q(0,"the response has no body to stream");for await(let c of me(l.body,i?.signal)){if(c==="[DONE]")return;let u;try{u=JSON.parse(c)}catch{continue}if(u.error)throw new q(500,u.error.message??"stream error",{code:u.error.code});yield u}},async complete(o,i){return await(await s({...o,stream:!1},i?.signal)).json()},models:r.models===void 0?void 0:async()=>{if(Array.isArray(r.models))return r.models;let o=await t(`${e}/models`,{headers:n()});if(!o.ok)throw await Bt(o);return((await o.json()).data??[]).map(({id:a,is_default:l,capability:c,max_input_tokens:u,max_tokens:d,options:p})=>({id:a,is_default:l,capability:c??"text",max_input_tokens:u,max_tokens:d,options:p}))}}}async function Bt(r){let e=`HTTP ${r.status}`,t;try{let s=await r.json();typeof s.error=="string"?e=s.error:s.error?.message?(e=s.error.message,t=s.error.code??s.error.type):s.message&&(e=s.message)}catch{}let n=Number(r.headers.get("Retry-After"));return new q(r.status,e,{code:t,retryAfter:Number.isFinite(n)&&n>0?n:void 0})}async function*me(r,e){let t=r.getReader(),n=new TextDecoder,s="",o=()=>{t.cancel().catch(()=>{})};e?.addEventListener("abort",o,{once:!0});try{for(;;){let{done:a,value:l}=await t.read();if(a)break;s+=n.decode(l,{stream:!0});let c;for(;(c=s.search(/\r?\n\r?\n/))>=0;){let u=s.slice(0,c);s=s.slice(c).replace(/^\r?\n\r?\n/,"");let d=u.split(/\r?\n/).filter(p=>p.startsWith("data:")).map(p=>p.slice(5).replace(/^ /,"")).join(`
3
3
  `);d&&(yield d)}}let i=s.split(/\r?\n/).filter(a=>a.startsWith("data:")).map(a=>a.slice(5).replace(/^ /,"")).join(`
4
4
  `);i&&(yield i)}finally{e?.removeEventListener("abort",o),t.releaseLock()}e?.throwIfAborted()}function Ie(r){let e=(r.now??new Date).toISOString().slice(0,10),t=[];t.push(`You are ${r.appName?`the assistant built into ${r.appName}`:"an assistant"}. Today is ${e}.`),r.instructions?.trim()&&t.push(r.instructions.trim()),r.agentsMd?.trim()&&t.push(`Project-specific instructions and guidelines:
5
5
 
@@ -31,10 +31,10 @@ There is no runtime for scripts here: a skill's scripts (Python, shell, JavaScri
31
31
  `+i.join(`
32
32
  `)),r.droppedTurns>0&&t.push(`Note: ${r.droppedTurns} earlier turn${r.droppedTurns===1?"":"s"} of this conversation ${r.droppedTurns===1?"was":"were"} removed to fit the context window. Ask the user if something seems to be missing.`),t.join(`
33
33
 
34
- `)}var Hn=1600;function M(r,e){let t=e?ne(e):0,n=0;for(let s of r){if(t+=16,typeof s.content=="string")t+=ne(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?t+=ne(o.text):n++;if(s.tool_calls)for(let o of s.tool_calls)t+=ne(o.function.name)+ne(o.function.arguments)+24;typeof s.reasoning_content=="string"&&(t+=ne(s.reasoning_content))}return Math.ceil(t/3)+n*Hn}function ne(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);e+=n<128?1:n<2048?2:n>=55296&&n<=56319?(t++,4):3}return e}function ge(r,e){let t=Math.max(1,e.keepTurns),n=e.elideAbove??400,s=mt(r),o=0,i=0,a=()=>M(s.flat(),e.system)>e.budget;if(a())for(let l=0;l<s.length-t&&a();l++)s[l]=s[l].map(c=>{if(c.role!=="tool")return c;let u=typeof c.content=="string"?c.content:Ht(c.content);return u.length<=n||u.startsWith("[result elided")?c:(o++,{...c,content:`[result elided to save context: ${u.length} characters; call the tool again if needed]`})});for(;s.length>1&&a();)s.shift(),i++;if(a()&&s.length===1){let l=s[0],c=l.map((f,h)=>f.role==="tool"?h:-1).filter(f=>f>=0);for(let f of c.slice(0,Math.max(0,c.length-(e.keepResults??3)))){if(!a())break;let h=l[f],p=typeof h.content=="string"?h.content:Ht(h.content);p.length<=n||p.startsWith("[result elided")||(l[f]={...h,content:`[result elided to save context: ${p.length} characters; call the tool again if needed]`},o++)}let u=l[0]?.role==="user"?1:0,d=f=>{let h=f+1;for(;h<l.length&&l[h].role==="tool";)h++;return h};for(;a()&&!(l.slice(u).filter(h=>h.role==="assistant").length<=1||l[u]?.role!=="assistant");)l.splice(u,d(u)-u),i++}return{messages:s.flat(),droppedTurns:i,elidedResults:o}}function mt(r){let e=[],t=[];for(let n of r)n.role==="user"&&t.length&&(e.push(t),t=[]),t.push(n);return t.length&&e.push(t),e}function Ht(r){return r?r.map(e=>e.type==="text"?e.text:"").join(""):""}var je={reserveTokens:16384,keepRecentTokens:2e4},gt=`The conversation history before this point was compacted into the following summary:
34
+ `)}var Hn=1600;function E(r,e){let t=e?re(e):0,n=0;for(let s of r){if(t+=16,typeof s.content=="string")t+=re(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?t+=re(o.text):n++;if(s.tool_calls)for(let o of s.tool_calls)t+=re(o.function.name)+re(o.function.arguments)+24;typeof s.reasoning_content=="string"&&(t+=re(s.reasoning_content))}return Math.ceil(t/3)+n*Hn}function re(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);e+=n<128?1:n<2048?2:n>=55296&&n<=56319?(t++,4):3}return e}function ge(r,e){let t=Math.max(1,e.keepTurns),n=e.elideAbove??400,s=yt(r),o=0,i=0,a=()=>E(s.flat(),e.system)>e.budget;if(a())for(let l=0;l<s.length-t&&a();l++)s[l]=s[l].map(c=>{if(c.role!=="tool")return c;let u=typeof c.content=="string"?c.content:Ht(c.content);return u.length<=n||u.startsWith("[result elided")?c:(o++,{...c,content:`[result elided to save context: ${u.length} characters; call the tool again if needed]`})});for(;s.length>1&&a();)s.shift(),i++;if(a()&&s.length===1){let l=s[0],c=l.map((p,h)=>p.role==="tool"?h:-1).filter(p=>p>=0);for(let p of c.slice(0,Math.max(0,c.length-(e.keepResults??3)))){if(!a())break;let h=l[p],f=typeof h.content=="string"?h.content:Ht(h.content);f.length<=n||f.startsWith("[result elided")||(l[p]={...h,content:`[result elided to save context: ${f.length} characters; call the tool again if needed]`},o++)}let u=l[0]?.role==="user"?1:0,d=p=>{let h=p+1;for(;h<l.length&&l[h].role==="tool";)h++;return h};for(;a()&&!(l.slice(u).filter(h=>h.role==="assistant").length<=1||l[u]?.role!=="assistant");)l.splice(u,d(u)-u),i++}return{messages:s.flat(),droppedTurns:i,elidedResults:o}}function yt(r){let e=[],t=[];for(let n of r)n.role==="user"&&t.length&&(e.push(t),t=[]),t.push(n);return t.length&&e.push(t),e}function Ht(r){return r?r.map(e=>e.type==="text"?e.text:"").join(""):""}var je={reserveTokens:16384,keepRecentTokens:2e4},wt=`The conversation history before this point was compacted into the following summary:
35
35
 
36
36
  <summary>
37
- `,yt=`
37
+ `,bt=`
38
38
  </summary>`,Jn=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
39
39
 
40
40
  Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,Gn=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
@@ -105,7 +105,7 @@ Use this EXACT format:
105
105
  ## Critical Context
106
106
  - [Preserve important context, add new if needed]
107
107
 
108
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,Xn=2e3;function K(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(gt)||!r.content.endsWith(yt)?null:r.content.slice(gt.length,r.content.length-yt.length)}function ye(r){return{role:"user",content:gt+r+yt}}function re(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??je.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??je.keepRecentTokens,Math.floor(r*.4))}}function wt(r,e,t){return r>e-t.reserveTokens}function Fe(r,e){if(r.length<2)return null;let t=0,n=-1;for(let i=r.length-1;i>=1;i--){t+=M([r[i]]);let a=r[i].role;if((a==="user"||a==="assistant")&&(n=i,t>=e))break}if(n<=0)return null;let s,o=[];for(let i of r.slice(0,n)){let a=K(i);a!==null&&s===void 0?s=a:o.push(i)}return o.length?{toSummarize:o,previousSummary:s,kept:r.slice(n)}:null}function we(r){let e=[];for(let t of r){let n=typeof t.content=="string"?t.content:(t.content??[]).map(s=>s.type==="text"?s.text:`[${s.type}]`).join(`
108
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`,Xn=2e3;function K(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(wt)||!r.content.endsWith(bt)?null:r.content.slice(wt.length,r.content.length-bt.length)}function ye(r){return{role:"user",content:wt+r+bt}}function se(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??je.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??je.keepRecentTokens,Math.floor(r*.4))}}function kt(r,e,t){return r>e-t.reserveTokens}function Fe(r,e){if(r.length<2)return null;let t=0,n=-1;for(let i=r.length-1;i>=1;i--){t+=E([r[i]]);let a=r[i].role;if((a==="user"||a==="assistant")&&(n=i,t>=e))break}if(n<=0)return null;let s,o=[];for(let i of r.slice(0,n)){let a=K(i);a!==null&&s===void 0?s=a:o.push(i)}return o.length?{toSummarize:o,previousSummary:s,kept:r.slice(n)}:null}function we(r){let e=[];for(let t of r){let n=typeof t.content=="string"?t.content:(t.content??[]).map(s=>s.type==="text"?s.text:`[${s.type}]`).join(`
109
109
  `);t.role==="user"?n&&e.push(`[User]: ${n}`):t.role==="assistant"?(n&&e.push(`[Assistant]: ${n}`),t.tool_calls?.length&&e.push(`[Assistant tool calls]: ${t.tool_calls.map(s=>`${s.function.name}(${s.function.arguments})`).join("; ")}`)):t.role==="tool"&&n&&e.push(`[Tool result]: ${Yn(n,Xn)}`)}return e.join(`
110
110
 
111
111
  `)}function Yn(r,e){return r.length<=e?r:`${r.slice(0,e)}
@@ -122,55 +122,55 @@ ${e}
122
122
 
123
123
  `),n+=e?Zn:Gn,t?.trim()&&(n+=`
124
124
 
125
- The user asked this summary to focus on: ${t.trim()}`),[{role:"system",content:Jn},{role:"user",content:n}]}async function be(r,e,t={}){let n=t.maxChars??8e5,s="",o="",i=0,a,l,c=new Map;for await(let h of r(e,{signal:t.signal}))if(t.signal?.throwIfAborted(),h.usage&&(l=h.usage),!!Array.isArray(h.choices))for(let p of h.choices){if((p.index??0)!==0)continue;p.finish_reason&&(a=p.finish_reason);let m=p.delta;if(!m)continue;typeof m.content=="string"&&m.content&&(s+=m.content,i+=m.content.length,t.onText?.(m.content,s));let b=m.reasoning_content??m.reasoning??m.thinking;if(typeof b=="string"&&b&&(o+=b,i+=b.length,t.onReasoning?.(b,o)),m.tool_calls){if(!Array.isArray(m.tool_calls))throw new Error("Malformed streamed tool_calls");for(let S of m.tool_calls){let g=typeof S.index=="number"?S.index:c.size;if(!Number.isInteger(g)||g<0||g>=64)throw new Error("Malformed streamed tool call index");let w=c.get(g);w||(w={index:g,id:"",type:"function",function:{name:"",arguments:""}},c.set(g,w)),S.id&&(w.id=S.id),S.type&&(w.type=S.type),S.function&&(S.function.name&&(w.function.name+=S.function.name),S.function.arguments&&(w.function.arguments+=S.function.arguments,i+=S.function.arguments.length)),t.onToolCall?.({index:g,id:w.id??"",name:w.function.name,arguments:w.function.arguments},S.function?.arguments??"")}}if(i>n)throw new Error("The model's reply exceeded the size limit")}if(t.signal?.throwIfAborted(),!a)throw new Error("The stream ended before the reply was complete");let u=[...c.keys()].sort((h,p)=>h-p);if(u.some((h,p)=>h!==p))throw new Error("Streamed tool calls arrived incomplete");let d=u.map(h=>{let p=c.get(h),{index:m,...b}=p;return b.id||(b.id=`call_${Math.random().toString(36).slice(2,10)}`),b}),f={role:"assistant",content:s.length?s:null};return d.length&&(f.tool_calls=d),{message:f,finishReason:a,usage:l,reasoning:o}}var bt="/prompts";function kt(r){let e=[],t="",n=!1,s=null;for(let o=0;o<r.length;o++){let i=r[o];s?i===s?s=null:t+=i:i==='"'||i==="'"?(s=i,n=!0):/\s/.test(i)?n&&(e.push(t),t="",n=!1):(t+=i,n=!0)}return n&&e.push(t),e}function xt(r,e){let t=e.join(" ");return r.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(n,s,o,i,a,l)=>{if(s){let c=s==="@"||s==="ARGUMENTS"?t:e[parseInt(s,10)-1];return c||o}if(i){let c=parseInt(i,10)-1;return c<0&&(c=0),a?e.slice(c,c+parseInt(a,10)).join(" "):e.slice(c).join(" ")}return l==="ARGUMENTS"||l==="@"?t:e[parseInt(l,10)-1]??""})}async function Gt(r){let e=[];for(let t of await r.list(bt)){if(!t.path.endsWith(".md"))continue;let n=t.path.slice(bt.length+1,-3);if(n.includes("/"))continue;let s;try{s=await r.readText(t.path)}catch{continue}let{fm:o,body:i}=Zt(s),a=o.description||Vn(i);e.push({name:n,description:a,argumentHint:o["argument-hint"],path:t.path})}return e.sort((t,n)=>t.name.localeCompare(n.name))}async function ze(r,e){let t=/^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(e);if(!t||!r)return e;let n=t[1],s=(t[2]??"").trim();if(n.startsWith("skill:")){let l=n.slice(6),u=(await r.skills()).find(h=>h.name===l);if(!u)return e;let{body:d}=await r.skillBody(l),f=`<skill name="${u.name}" location="${u.path}">
125
+ The user asked this summary to focus on: ${t.trim()}`),[{role:"system",content:Jn},{role:"user",content:n}]}async function be(r,e,t={}){let n=t.maxChars??8e5,s="",o="",i=0,a,l,c=new Map;for await(let h of r(e,{signal:t.signal}))if(t.signal?.throwIfAborted(),h.usage&&(l=h.usage),!!Array.isArray(h.choices))for(let f of h.choices){if((f.index??0)!==0)continue;f.finish_reason&&(a=f.finish_reason);let m=f.delta;if(!m)continue;typeof m.content=="string"&&m.content&&(s+=m.content,i+=m.content.length,t.onText?.(m.content,s));let b=m.reasoning_content??m.reasoning??m.thinking;if(typeof b=="string"&&b&&(o+=b,i+=b.length,t.onReasoning?.(b,o)),m.tool_calls){if(!Array.isArray(m.tool_calls))throw new Error("Malformed streamed tool_calls");for(let v of m.tool_calls){let g=typeof v.index=="number"?v.index:c.size;if(!Number.isInteger(g)||g<0||g>=64)throw new Error("Malformed streamed tool call index");let w=c.get(g);w||(w={index:g,id:"",type:"function",function:{name:"",arguments:""}},c.set(g,w)),v.id&&(w.id=v.id),v.type&&(w.type=v.type),v.function&&(v.function.name&&(w.function.name+=v.function.name),v.function.arguments&&(w.function.arguments+=v.function.arguments,i+=v.function.arguments.length)),t.onToolCall?.({index:g,id:w.id??"",name:w.function.name,arguments:w.function.arguments},v.function?.arguments??"")}}if(i>n)throw new Error("The model's reply exceeded the size limit")}if(t.signal?.throwIfAborted(),!a)throw new Error("The stream ended before the reply was complete");let u=[...c.keys()].sort((h,f)=>h-f);if(u.some((h,f)=>h!==f))throw new Error("Streamed tool calls arrived incomplete");let d=u.map(h=>{let f=c.get(h),{index:m,...b}=f;return b.id||(b.id=`call_${Math.random().toString(36).slice(2,10)}`),b}),p={role:"assistant",content:s.length?s:null};return d.length&&(p.tool_calls=d),{message:p,finishReason:a,usage:l,reasoning:o}}var xt="/prompts";function vt(r){let e=[],t="",n=!1,s=null;for(let o=0;o<r.length;o++){let i=r[o];s?i===s?s=null:t+=i:i==='"'||i==="'"?(s=i,n=!0):/\s/.test(i)?n&&(e.push(t),t="",n=!1):(t+=i,n=!0)}return n&&e.push(t),e}function St(r,e){let t=e.join(" ");return r.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(n,s,o,i,a,l)=>{if(s){let c=s==="@"||s==="ARGUMENTS"?t:e[parseInt(s,10)-1];return c||o}if(i){let c=parseInt(i,10)-1;return c<0&&(c=0),a?e.slice(c,c+parseInt(a,10)).join(" "):e.slice(c).join(" ")}return l==="ARGUMENTS"||l==="@"?t:e[parseInt(l,10)-1]??""})}async function Gt(r){let e=[];for(let t of await r.list(xt)){if(!t.path.endsWith(".md"))continue;let n=t.path.slice(xt.length+1,-3);if(n.includes("/"))continue;let s;try{s=await r.readText(t.path)}catch{continue}let{fm:o,body:i}=Zt(s),a=o.description||Vn(i);e.push({name:n,description:a,argumentHint:o["argument-hint"],path:t.path})}return e.sort((t,n)=>t.name.localeCompare(n.name))}async function ze(r,e){let t=/^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(e);if(!t||!r)return e;let n=t[1],s=(t[2]??"").trim();if(n.startsWith("skill:")){let l=n.slice(6),u=(await r.skills()).find(h=>h.name===l);if(!u)return e;let{body:d}=await r.skillBody(l),p=`<skill name="${u.name}" location="${u.path}">
126
126
  References are relative to ${u.dir}.
127
127
 
128
128
  ${d}
129
- </skill>`;return s?`${f}
129
+ </skill>`;return s?`${p}
130
130
 
131
- ${s}`:f}let o=`${bt}/${n}.md`,i;try{i=await r.readText(o)}catch{return e}let{body:a}=Zt(i);return xt(a,kt(s))}function Zt(r){let e=r.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
131
+ ${s}`:p}let o=`${xt}/${n}.md`,i;try{i=await r.readText(o)}catch{return e}let{body:a}=Zt(i);return St(a,vt(s))}function Zt(r){let e=r.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
132
132
  `),t=/^---\n([\s\S]*?)\n---\n?/.exec(e);if(!t)return{fm:{},body:e.trim()};let n={};for(let s of(t[1]??"").split(`
133
133
  `)){let o=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(s.trim());o&&(n[o[1]]=o[2].replace(/^["']|["']$/g,""))}return{fm:n,body:e.slice(t[0].length).trim()}}function Vn(r){let e=r.split(`
134
- `).find(t=>t.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var Xt=/^[A-Za-z0-9_-]{1,64}$/;function L(r){if(!Xt.test(r.name))throw new Error(`tool name "${r.name}" must match ${Xt}`);if(!r.description||!r.description.trim())throw new Error(`tool "${r.name}" needs a description`);let e=r.parameters??{type:"object",properties:{},additionalProperties:!1};return{...r,parameters:e}}function Be(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parameters}}}function ke(r,e=32e3){let t,n;r==null?t="OK":typeof r=="string"?t=r.length?r:"OK":Array.isArray(r)&&r.every(Yt)?t=r:Qn(r)?(t=r.content,n=r.details,typeof t=="string"&&!t.length&&(t="OK")):t=JSON.stringify(r);let s=!1;if(typeof t=="string"){let o=We(t,e);s=o.truncated,t=o.text}else t=t.map(o=>{if(o.type!=="text")return o;let i=We(o.text,e);return i.truncated&&(s=!0),{type:"text",text:i.text}});return{content:t,text:typeof t=="string"?t:xe(t),details:n,truncated:s}}function Yt(r){return!!r&&typeof r=="object"&&typeof r.type=="string"&&["text","image_url","video_url","audio_url"].includes(r.type)}function Qn(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r.content,t=Object.keys(r);return(typeof e=="string"||Array.isArray(e)&&e.every(Yt))&&t.every(n=>n==="content"||n==="details")}function We(r,e){if(r.length<=e)return{text:r,truncated:!1};let t=r.slice(0,Math.max(0,e-120)),n=r.length-t.length;return{text:`${t}
134
+ `).find(t=>t.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var Xt=/^[A-Za-z0-9_-]{1,64}$/;function D(r){if(!Xt.test(r.name))throw new Error(`tool name "${r.name}" must match ${Xt}`);if(!r.description||!r.description.trim())throw new Error(`tool "${r.name}" needs a description`);let e=r.parameters??{type:"object",properties:{},additionalProperties:!1};return{...r,parameters:e}}function Be(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parameters}}}function ke(r,e=32e3){let t,n;r==null?t="OK":typeof r=="string"?t=r.length?r:"OK":Array.isArray(r)&&r.every(Yt)?t=r:Qn(r)?(t=r.content,n=r.details,typeof t=="string"&&!t.length&&(t="OK")):t=JSON.stringify(r);let s=!1;if(typeof t=="string"){let o=We(t,e);s=o.truncated,t=o.text}else t=t.map(o=>{if(o.type!=="text")return o;let i=We(o.text,e);return i.truncated&&(s=!0),{type:"text",text:i.text}});return{content:t,text:typeof t=="string"?t:xe(t),details:n,truncated:s}}function Yt(r){return!!r&&typeof r=="object"&&typeof r.type=="string"&&["text","image_url","video_url","audio_url"].includes(r.type)}function Qn(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r.content,t=Object.keys(r);return(typeof e=="string"||Array.isArray(e)&&e.every(Yt))&&t.every(n=>n==="content"||n==="details")}function We(r,e){if(r.length<=e)return{text:r,truncated:!1};let t=r.slice(0,Math.max(0,e-120)),n=r.length-t.length;return{text:`${t}
135
135
 
136
136
  [... ${n} more characters not shown. Ask for a narrower range or a smaller result.]`,truncated:!0}}function xe(r){return r?typeof r=="string"?r:r.map(e=>e.type==="text"?e.text:`[${e.type}]`).join(`
137
- `):""}function Ke(r){if(r.byteLength>52428800)throw new Error("zip larger than 52428800 bytes");let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=-1;for(let u=r.byteLength-22;u>=Math.max(0,r.byteLength-22-65535);u--)if(e.getUint32(u,!0)===101010256){t=u;break}if(t<0)throw new Error("not a zip file");if(t>=20&&e.getUint32(t-20,!0)===117853008)throw new Error("zip64 archives are not supported");let n=e.getUint16(t+10,!0),s=e.getUint32(t+12,!0),o=e.getUint32(t+16,!0);if(n===65535||s===4294967295||o===4294967295)throw new Error("zip64 archives are not supported");let i=[],a=o,l=new TextDecoder("utf-8"),c=new TextDecoder("latin1");for(let u=0;u<n;u++){if(a+46>r.byteLength||e.getUint32(a,!0)!==33639248)throw new Error("zip central directory is damaged");let d=e.getUint16(a+8,!0),f=e.getUint16(a+10,!0),h=e.getUint32(a+20,!0),p=e.getUint32(a+24,!0),m=e.getUint16(a+28,!0),b=e.getUint16(a+30,!0),S=e.getUint16(a+32,!0),g=e.getUint32(a+42,!0);if(h===4294967295||p===4294967295||g===4294967295)throw new Error("zip64 archives are not supported");let w=r.subarray(a+46,a+46+m),_=(d&2048?l:c).decode(w).replace(/\\/g,"/");i.push({name:_,size:p,compressedSize:h,method:f,isDir:_.endsWith("/"),offset:g,crc:e.getUint32(a+16,!0)}),a+=46+m+b+S}return i}async function se(r,e,t){let n=new DataView(r.buffer,r.byteOffset,r.byteLength),s=e.offset;if(s+30>r.byteLength||n.getUint32(s,!0)!==67324752)throw new Error(`zip entry "${e.name}" is damaged`);let o=n.getUint16(s+26,!0),i=n.getUint16(s+28,!0),a=s+30+o+i;if(a+e.compressedSize>r.byteLength)throw new Error(`zip entry "${e.name}" is damaged`);let l=r.subarray(a,a+e.compressedSize);if(e.method===0){if(l.byteLength!==e.size||e.crc!==void 0&&Vt(l)!==e.crc)throw new Error(`zip entry "${e.name}" is damaged`);return l}if(e.method!==8)throw new Error(`zip entry "${e.name}" uses an unsupported compression method (${e.method})`);let c=await(t?t(l):er(l));if(c.byteLength!==e.size)throw new Error(`zip entry "${e.name}" inflated to the wrong size`);return c}async function er(r){let e=globalThis.DecompressionStream;if(!e)throw new Error("this runtime has no DecompressionStream; pass an `inflate` function (e.g. zlib.inflateRawSync)");let t=new Blob([r]).stream().pipeThrough(new e("deflate-raw")),n=await new Response(t).arrayBuffer();return new Uint8Array(n)}var qe=null;function Vt(r){if(!qe){qe=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let s=0;s<8;s++)n=n&1?3988292384^n>>>1:n>>>1;qe[t]=n>>>0}}let e=4294967295;for(let t=0;t<r.length;t++)e=qe[(e^r[t])&255]^e>>>8;return(e^4294967295)>>>0}async function tr(r){if(typeof CompressionStream>"u"||r.length<64)return{bytes:r,method:0};try{let e=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate-raw")),t=new Uint8Array(await new Response(e).arrayBuffer());return t.length<r.length?{bytes:t,method:8}:{bytes:r,method:0}}catch{return{bytes:r,method:0}}}function nr(r){let e=new Date(r),t=Math.max(1980,e.getFullYear())-1980<<9|e.getMonth()+1<<5|e.getDate(),n=e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1;return{date:t,time:n}}async function Qt(r){if(r.length>65534)throw new Error(`too many files for one zip (${r.length}; at most 65534)`);let e=new TextEncoder,t=[],n=[],s=0;for(let u of r){let d=e.encode(u.path.replace(/^\/+/,"")),f=typeof u.data=="string"?e.encode(u.data):u.data,h=Vt(f),{bytes:p,method:m}=await tr(f),{date:b,time:S}=nr(u.mtime??Date.now()),g=new DataView(new ArrayBuffer(30));g.setUint32(0,67324752,!0),g.setUint16(4,20,!0),g.setUint16(6,2048,!0),g.setUint16(8,m,!0),g.setUint16(10,S,!0),g.setUint16(12,b,!0),g.setUint32(14,h,!0),g.setUint32(18,p.length,!0),g.setUint32(22,f.length,!0),g.setUint16(26,d.length,!0),g.setUint16(28,0,!0);let w=new DataView(new ArrayBuffer(46));w.setUint32(0,33639248,!0),w.setUint16(4,20,!0),w.setUint16(6,20,!0),w.setUint16(8,2048,!0),w.setUint16(10,m,!0),w.setUint16(12,S,!0),w.setUint16(14,b,!0),w.setUint32(16,h,!0),w.setUint32(20,p.length,!0),w.setUint32(24,f.length,!0),w.setUint16(28,d.length,!0),w.setUint16(30,0,!0),w.setUint16(32,0,!0),w.setUint16(34,0,!0),w.setUint16(36,0,!0),w.setUint32(38,0,!0),w.setUint32(42,s,!0),t.push(new Uint8Array(g.buffer),d,p),n.push(new Uint8Array(w.buffer),d),s+=30+d.length+p.length}let o=n.reduce((u,d)=>u+d.length,0),i=new DataView(new ArrayBuffer(22));i.setUint32(0,101010256,!0),i.setUint16(4,0,!0),i.setUint16(6,0,!0),i.setUint16(8,r.length,!0),i.setUint16(10,r.length,!0),i.setUint32(12,o,!0),i.setUint32(16,s,!0),i.setUint16(20,0,!0);let a=[...t,...n,new Uint8Array(i.buffer)],l=new Uint8Array(a.reduce((u,d)=>u+d.length,0)),c=0;for(let u of a)l.set(u,c),c+=u.length;return l}var en=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Se(r,e){let t=r.replace(/^/,"").replace(/\r\n?/g,`
138
- `),n=e.replace(/\/[^/]*$/,"")||"/",s=n.split("/").filter(Boolean).pop()??"skill",o=[],i={},a=t,l=/^---\n([\s\S]*?)\n---\n?/.exec(t);l&&(i=St(l[1]??""),a=t.slice(l[0].length));let c=(i.description??"").trim();if(!c)return null;let u=(i.name??"").trim()||s;(!en.test(u)||u.length>64)&&(o.push(`skill name "${u}" is not lowercase-hyphenated (\u226464); using the folder name`),u=en.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let d={name:u,description:c.length>1024?c.slice(0,1024):c,path:e,dir:n};c.length>1024&&o.push(`description of "${u}" cut to 1024 characters`),/^(true|yes)$/i.test(i["disable-model-invocation"]??"")&&(d.disableModelInvocation=!0),i.license&&(d.license=i.license),i.compatibility&&(d.compatibility=i.compatibility),i["allowed-tools"]&&(d.allowedTools=i["allowed-tools"].split(/[\s,]+/).filter(Boolean));let f={};for(let[h,p]of Object.entries(i))h.startsWith("metadata.")&&(f[h.slice(9)]=p);return Object.keys(f).length&&(d.metadata=f),{skill:d,body:a.trim(),warnings:o}}function St(r){let e={},t=r.split(`
139
- `),n=0,s="";for(;n<t.length;){let o=t[n]??"";if(n++,!o.trim()||o.trimStart().startsWith("#"))continue;let i=o.length-o.trimStart().length,a=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(o.trim());if(!a)continue;let l=i>0&&s?`${s}.${a[1]}`:a[1];i===0&&(s="");let c=a[2]??"";if(c===""){let u=t[n]??"";if(u.length-u.trimStart().length>i&&u.trim()){s=a[1];continue}}else if(c===">"||c==="|"||c===">-"||c==="|-"){let u=c.startsWith(">"),d=[];for(;n<t.length;){let f=t[n]??"";if(f.trim()&&f.length-f.trimStart().length<=i)break;d.push(f.trim()),n++}c=u?d.join(" ").trim():d.join(`
137
+ `):""}function Ke(r){if(r.byteLength>52428800)throw new Error("zip larger than 52428800 bytes");let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=-1;for(let u=r.byteLength-22;u>=Math.max(0,r.byteLength-22-65535);u--)if(e.getUint32(u,!0)===101010256){t=u;break}if(t<0)throw new Error("not a zip file");if(t>=20&&e.getUint32(t-20,!0)===117853008)throw new Error("zip64 archives are not supported");let n=e.getUint16(t+10,!0),s=e.getUint32(t+12,!0),o=e.getUint32(t+16,!0);if(n===65535||s===4294967295||o===4294967295)throw new Error("zip64 archives are not supported");let i=[],a=o,l=new TextDecoder("utf-8"),c=new TextDecoder("latin1");for(let u=0;u<n;u++){if(a+46>r.byteLength||e.getUint32(a,!0)!==33639248)throw new Error("zip central directory is damaged");let d=e.getUint16(a+8,!0),p=e.getUint16(a+10,!0),h=e.getUint32(a+20,!0),f=e.getUint32(a+24,!0),m=e.getUint16(a+28,!0),b=e.getUint16(a+30,!0),v=e.getUint16(a+32,!0),g=e.getUint32(a+42,!0);if(h===4294967295||f===4294967295||g===4294967295)throw new Error("zip64 archives are not supported");let w=r.subarray(a+46,a+46+m),M=(d&2048?l:c).decode(w).replace(/\\/g,"/");i.push({name:M,size:f,compressedSize:h,method:p,isDir:M.endsWith("/"),offset:g,crc:e.getUint32(a+16,!0)}),a+=46+m+b+v}return i}async function ie(r,e,t){let n=new DataView(r.buffer,r.byteOffset,r.byteLength),s=e.offset;if(s+30>r.byteLength||n.getUint32(s,!0)!==67324752)throw new Error(`zip entry "${e.name}" is damaged`);let o=n.getUint16(s+26,!0),i=n.getUint16(s+28,!0),a=s+30+o+i;if(a+e.compressedSize>r.byteLength)throw new Error(`zip entry "${e.name}" is damaged`);let l=r.subarray(a,a+e.compressedSize);if(e.method===0){if(l.byteLength!==e.size||e.crc!==void 0&&Vt(l)!==e.crc)throw new Error(`zip entry "${e.name}" is damaged`);return l}if(e.method!==8)throw new Error(`zip entry "${e.name}" uses an unsupported compression method (${e.method})`);let c=await(t?t(l):er(l));if(c.byteLength!==e.size)throw new Error(`zip entry "${e.name}" inflated to the wrong size`);return c}async function er(r){let e=globalThis.DecompressionStream;if(!e)throw new Error("this runtime has no DecompressionStream; pass an `inflate` function (e.g. zlib.inflateRawSync)");let t=new Blob([r]).stream().pipeThrough(new e("deflate-raw")),n=await new Response(t).arrayBuffer();return new Uint8Array(n)}var qe=null;function Vt(r){if(!qe){qe=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let s=0;s<8;s++)n=n&1?3988292384^n>>>1:n>>>1;qe[t]=n>>>0}}let e=4294967295;for(let t=0;t<r.length;t++)e=qe[(e^r[t])&255]^e>>>8;return(e^4294967295)>>>0}async function tr(r){if(typeof CompressionStream>"u"||r.length<64)return{bytes:r,method:0};try{let e=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate-raw")),t=new Uint8Array(await new Response(e).arrayBuffer());return t.length<r.length?{bytes:t,method:8}:{bytes:r,method:0}}catch{return{bytes:r,method:0}}}function nr(r){let e=new Date(r),t=Math.max(1980,e.getFullYear())-1980<<9|e.getMonth()+1<<5|e.getDate(),n=e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1;return{date:t,time:n}}async function Qt(r){if(r.length>65534)throw new Error(`too many files for one zip (${r.length}; at most 65534)`);let e=new TextEncoder,t=[],n=[],s=0;for(let u of r){let d=e.encode(u.path.replace(/^\/+/,"")),p=typeof u.data=="string"?e.encode(u.data):u.data,h=Vt(p),{bytes:f,method:m}=await tr(p),{date:b,time:v}=nr(u.mtime??Date.now()),g=new DataView(new ArrayBuffer(30));g.setUint32(0,67324752,!0),g.setUint16(4,20,!0),g.setUint16(6,2048,!0),g.setUint16(8,m,!0),g.setUint16(10,v,!0),g.setUint16(12,b,!0),g.setUint32(14,h,!0),g.setUint32(18,f.length,!0),g.setUint32(22,p.length,!0),g.setUint16(26,d.length,!0),g.setUint16(28,0,!0);let w=new DataView(new ArrayBuffer(46));w.setUint32(0,33639248,!0),w.setUint16(4,20,!0),w.setUint16(6,20,!0),w.setUint16(8,2048,!0),w.setUint16(10,m,!0),w.setUint16(12,v,!0),w.setUint16(14,b,!0),w.setUint32(16,h,!0),w.setUint32(20,f.length,!0),w.setUint32(24,p.length,!0),w.setUint16(28,d.length,!0),w.setUint16(30,0,!0),w.setUint16(32,0,!0),w.setUint16(34,0,!0),w.setUint16(36,0,!0),w.setUint32(38,0,!0),w.setUint32(42,s,!0),t.push(new Uint8Array(g.buffer),d,f),n.push(new Uint8Array(w.buffer),d),s+=30+d.length+f.length}let o=n.reduce((u,d)=>u+d.length,0),i=new DataView(new ArrayBuffer(22));i.setUint32(0,101010256,!0),i.setUint16(4,0,!0),i.setUint16(6,0,!0),i.setUint16(8,r.length,!0),i.setUint16(10,r.length,!0),i.setUint32(12,o,!0),i.setUint32(16,s,!0),i.setUint16(20,0,!0);let a=[...t,...n,new Uint8Array(i.buffer)],l=new Uint8Array(a.reduce((u,d)=>u+d.length,0)),c=0;for(let u of a)l.set(u,c),c+=u.length;return l}var en=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ve(r,e){let t=r.replace(/^/,"").replace(/\r\n?/g,`
138
+ `),n=e.replace(/\/[^/]*$/,"")||"/",s=n.split("/").filter(Boolean).pop()??"skill",o=[],i={},a=t,l=/^---\n([\s\S]*?)\n---\n?/.exec(t);l&&(i=Tt(l[1]??""),a=t.slice(l[0].length));let c=(i.description??"").trim();if(!c)return null;let u=(i.name??"").trim()||s;(!en.test(u)||u.length>64)&&(o.push(`skill name "${u}" is not lowercase-hyphenated (\u226464); using the folder name`),u=en.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let d={name:u,description:c.length>1024?c.slice(0,1024):c,path:e,dir:n};c.length>1024&&o.push(`description of "${u}" cut to 1024 characters`),/^(true|yes)$/i.test(i["disable-model-invocation"]??"")&&(d.disableModelInvocation=!0),i.license&&(d.license=i.license),i.compatibility&&(d.compatibility=i.compatibility),i["allowed-tools"]&&(d.allowedTools=i["allowed-tools"].split(/[\s,]+/).filter(Boolean));let p={};for(let[h,f]of Object.entries(i))h.startsWith("metadata.")&&(p[h.slice(9)]=f);return Object.keys(p).length&&(d.metadata=p),{skill:d,body:a.trim(),warnings:o}}function Tt(r){let e={},t=r.split(`
139
+ `),n=0,s="";for(;n<t.length;){let o=t[n]??"";if(n++,!o.trim()||o.trimStart().startsWith("#"))continue;let i=o.length-o.trimStart().length,a=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(o.trim());if(!a)continue;let l=i>0&&s?`${s}.${a[1]}`:a[1];i===0&&(s="");let c=a[2]??"";if(c===""){let u=t[n]??"";if(u.length-u.trimStart().length>i&&u.trim()){s=a[1];continue}}else if(c===">"||c==="|"||c===">-"||c==="|-"){let u=c.startsWith(">"),d=[];for(;n<t.length;){let p=t[n]??"";if(p.trim()&&p.length-p.trimStart().length<=i)break;d.push(p.trim()),n++}c=u?d.join(" ").trim():d.join(`
140
140
  `).trim()}else c=rr(c);e[l]=c}return e}function rr(r){let e=r.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).replace(/\\"/g,'"').replace(/''/g,"'"):e.replace(/\s+#.*$/,"")}function sr(r){return r.normalize("NFKC").replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function tn(r){let e="",t=[],n=[],s=0,o=r.split(`
141
- `);return o.forEach((i,a)=>{let l=i.trimEnd(),c=0;for(let u of l){let d=sr(u);for(let f=0;f<d.length;f++)t.push(s+c),n.push(s+c+u.length);e+=d,c+=u.length}s+=i.length,a<o.length-1&&(e+=`
142
- `,t.push(s),n.push(s+1),s+=1)}),{text:e,start:t,end:n}}function vt(r){return tn(r).text}function ir(r,e){let t=0,n=0;for(;(n=r.indexOf(e,n))!==-1;)t++,n+=e.length;return t}function He(r,e,t){if(!t.length)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");let n=t.length>1,s=e.startsWith("\uFEFF")?"\uFEFF":"",o=/\r\n/.test(e),i=e.slice(s.length).replace(/\r\n/g,`
141
+ `);return o.forEach((i,a)=>{let l=i.trimEnd(),c=0;for(let u of l){let d=sr(u);for(let p=0;p<d.length;p++)t.push(s+c),n.push(s+c+u.length);e+=d,c+=u.length}s+=i.length,a<o.length-1&&(e+=`
142
+ `,t.push(s),n.push(s+1),s+=1)}),{text:e,start:t,end:n}}function At(r){return tn(r).text}function ir(r,e){let t=0,n=0;for(;(n=r.indexOf(e,n))!==-1;)t++,n+=e.length;return t}function He(r,e,t){if(!t.length)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");let n=t.length>1,s=e.startsWith("\uFEFF")?"\uFEFF":"",o=/\r\n/.test(e),i=e.slice(s.length).replace(/\r\n/g,`
143
143
  `),a=i,l=null,c=!1;for(let h of t)if(h.oldText&&!i.includes(h.oldText.replace(/\r\n/g,`
144
- `))){c=!0;break}if(c){let h=tn(i);a=h.text,l=h}let u=[];t.forEach((h,p)=>{let m=h.oldText.replace(/\r\n/g,`
145
- `);if(!m)throw new Error(n?`edits[${p}].oldText must not be empty in ${r}.`:`oldText must not be empty in ${r}.`);let b=c?vt(m):m,S=ir(a,b);if(S===0)throw new Error(n?`Could not find edits[${p}] in ${r}. The oldText must match exactly including all whitespace and newlines.`:`Could not find the exact text in ${r}. The old text must match exactly including all whitespace and newlines.`);if(S>1)throw new Error(n?`Found ${S} occurrences of edits[${p}] in ${r}. Each oldText must be unique. Please provide more context to make it unique.`:`Found ${S} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`);let g=a.indexOf(b),w=l?l.start[g]:g,_=l?l.end[g+b.length-1]:g+b.length;u.push({start:w,end:_,newText:h.newText.replace(/\r\n/g,`
146
- `),i:p})}),u.sort((h,p)=>h.start-p.start);for(let h=1;h<u.length;h++)if(u[h].start<u[h-1].end)throw new Error(`edits[${u[h-1].i}] and edits[${u[h].i}] overlap in ${r}. Merge them into one edit or target disjoint regions.`);let d="",f=0;for(let h of u)d+=i.slice(f,h.start)+h.newText,f=h.end;if(d+=i.slice(f),d===i)throw new Error(n?`No changes made to ${r}. The replacements produced identical content.`:`No changes made to ${r}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);return s+(o?d.replace(/\n/g,`\r
147
- `):d)}var ie=new Map,or=64;function ar(r){if(r.endsWith("/")||r.includes("__MACOSX/")||/(^|\/)\.DS_Store$/.test(r))return null;let e=r.replace(/^\.?\/+/,"").replace(/\/{2,}/g,"/");return!e||e.split("/").some(t=>t==="..")?null:e}function ve(r,e){let t=[...r],n=new Map;if(t.includes("SKILL.md"))return n.set(e,""),n;for(let s of t){let o=/^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(s);if(!o)continue;let i=o[1],a=s.slice(0,-8);(!n.has(i)||a.length<n.get(i).length)&&n.set(i,a)}return n}function Tt(r){let e=new Map;for(let t of Ke(r)){let n=ar(t.name);n&&e.set(n,t)}return e}function nn(r){return ie.get(r)}function Je(r,e,t){let n=ie.get(t);if(n&&n.bytes.byteLength===e.byteLength)return n;let s=Tt(e),o={entries:s,folders:ve(s.keys(),r),bytes:e,cache:new Map};return ie.size>=or&&ie.delete(ie.keys().next().value),ie.set(t,o),o}var lr=new TextDecoder("utf-8",{fatal:!0}),cr=r=>{try{return lr.decode(r)}catch{return null}};function oe(r,e,t,n){let s=new Map;for(let i of r.entries.keys())i.startsWith(e)&&s.set("/"+i.slice(e.length),i);let o=i=>{let a=s.get(i);return a?{path:i,size:r.entries.get(a).size,mtime:t}:null};return{async list(i){let a=i==="/"?"/":i.replace(/\/+$/,"")+"/",l=[];for(let c of s.keys())(a==="/"||c.startsWith(a)||c===i)&&l.push(o(c));return l},async stat(i){return o(i)},async read(i){let a=s.get(i);if(!a)throw new Error(`No such file: ${i}`);let l=r.cache.get(a);if(l!==void 0)return l;let c=await se(r.bytes,r.entries.get(a),n),u=cr(c)??c;return r.cache.set(a,u),u}}}function Te(r,e){return{async list(t){let n=[];for(let s of await r.list(t==="/"?e:e+t)){let o=s.path.startsWith(e+"/")?s.path.slice(e.length):null;o&&n.push({...s,path:o})}return n},async stat(t){let n=r.stat?await r.stat(e+t):null;return n?{...n,path:t}:null},read:t=>r.read(e+t)}}var rn="6.4.299",Y={url:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${rn}/build/pdf.min.mjs`,workerUrl:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${rn}/build/pdf.worker.min.mjs`},ae=null;function sn(r){Object.assign(Y,r),ae=null}var ur=r=>import(r);function dr(){return ae||(ae=(async()=>{let r=Y.load?await Y.load():await ur(Y.url),e=r.default?.getDocument?r.default:r;if(!Y.load&&typeof Worker<"u"&&typeof Blob<"u")try{let t=new Blob([`import ${JSON.stringify(Y.workerUrl)};`],{type:"text/javascript"});e.GlobalWorkerOptions.workerPort=new Worker(URL.createObjectURL(t),{type:"module"})}catch{e.GlobalWorkerOptions.workerSrc=Y.workerUrl}return e})(),ae.catch(()=>{ae=null})),ae}function Ge(r,e,t){return/\.pdf$/i.test(r)||e==="application/pdf"?!0:t instanceof Uint8Array&&t.length>4&&t[0]===37&&t[1]===80&&t[2]===68&&t[3]===70}async function Ze(r,e={}){let n=(await dr()).getDocument({data:r.slice(),isEvalSupported:!1}),s=await n.promise;try{let o=[],i=Math.min(s.numPages,e.maxPages??500);for(let a=1;a<=i;a++){let l=await s.getPage(a),c=await l.getTextContent();o.push(c.items.map(u=>(u.str??"")+(u.hasEOL?`
144
+ `))){c=!0;break}if(c){let h=tn(i);a=h.text,l=h}let u=[];t.forEach((h,f)=>{let m=h.oldText.replace(/\r\n/g,`
145
+ `);if(!m)throw new Error(n?`edits[${f}].oldText must not be empty in ${r}.`:`oldText must not be empty in ${r}.`);let b=c?At(m):m,v=ir(a,b);if(v===0)throw new Error(n?`Could not find edits[${f}] in ${r}. The oldText must match exactly including all whitespace and newlines.`:`Could not find the exact text in ${r}. The old text must match exactly including all whitespace and newlines.`);if(v>1)throw new Error(n?`Found ${v} occurrences of edits[${f}] in ${r}. Each oldText must be unique. Please provide more context to make it unique.`:`Found ${v} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`);let g=a.indexOf(b),w=l?l.start[g]:g,M=l?l.end[g+b.length-1]:g+b.length;u.push({start:w,end:M,newText:h.newText.replace(/\r\n/g,`
146
+ `),i:f})}),u.sort((h,f)=>h.start-f.start);for(let h=1;h<u.length;h++)if(u[h].start<u[h-1].end)throw new Error(`edits[${u[h-1].i}] and edits[${u[h].i}] overlap in ${r}. Merge them into one edit or target disjoint regions.`);let d="",p=0;for(let h of u)d+=i.slice(p,h.start)+h.newText,p=h.end;if(d+=i.slice(p),d===i)throw new Error(n?`No changes made to ${r}. The replacements produced identical content.`:`No changes made to ${r}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);return s+(o?d.replace(/\n/g,`\r
147
+ `):d)}var oe=new Map,or=64;function ar(r){if(r.endsWith("/")||r.includes("__MACOSX/")||/(^|\/)\.DS_Store$/.test(r))return null;let e=r.replace(/^\.?\/+/,"").replace(/\/{2,}/g,"/");return!e||e.split("/").some(t=>t==="..")?null:e}function Se(r,e){let t=[...r],n=new Map;if(t.includes("SKILL.md"))return n.set(e,""),n;for(let s of t){let o=/^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(s);if(!o)continue;let i=o[1],a=s.slice(0,-8);(!n.has(i)||a.length<n.get(i).length)&&n.set(i,a)}return n}function Pt(r){let e=new Map;for(let t of Ke(r)){let n=ar(t.name);n&&e.set(n,t)}return e}function nn(r){return oe.get(r)}function Je(r,e,t){let n=oe.get(t);if(n&&n.bytes.byteLength===e.byteLength)return n;let s=Pt(e),o={entries:s,folders:Se(s.keys(),r),bytes:e,cache:new Map};return oe.size>=or&&oe.delete(oe.keys().next().value),oe.set(t,o),o}var lr=new TextDecoder("utf-8",{fatal:!0}),cr=r=>{try{return lr.decode(r)}catch{return null}};function ae(r,e,t,n){let s=new Map;for(let i of r.entries.keys())i.startsWith(e)&&s.set("/"+i.slice(e.length),i);let o=i=>{let a=s.get(i);return a?{path:i,size:r.entries.get(a).size,mtime:t}:null};return{async list(i){let a=i==="/"?"/":i.replace(/\/+$/,"")+"/",l=[];for(let c of s.keys())(a==="/"||c.startsWith(a)||c===i)&&l.push(o(c));return l},async stat(i){return o(i)},async read(i){let a=s.get(i);if(!a)throw new Error(`No such file: ${i}`);let l=r.cache.get(a);if(l!==void 0)return l;let c=await ie(r.bytes,r.entries.get(a),n),u=cr(c)??c;return r.cache.set(a,u),u}}}function Te(r,e){return{async list(t){let n=[];for(let s of await r.list(t==="/"?e:e+t)){let o=s.path.startsWith(e+"/")?s.path.slice(e.length):null;o&&n.push({...s,path:o})}return n},async stat(t){let n=r.stat?await r.stat(e+t):null;return n?{...n,path:t}:null},read:t=>r.read(e+t)}}var rn="6.4.299",V={url:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${rn}/build/pdf.min.mjs`,workerUrl:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${rn}/build/pdf.worker.min.mjs`},le=null;function sn(r){Object.assign(V,r),le=null}var ur=r=>import(r);function dr(){return le||(le=(async()=>{let r=V.load?await V.load():await ur(V.url),e=r.default?.getDocument?r.default:r;if(!V.load&&typeof Worker<"u"&&typeof Blob<"u")try{let t=new Blob([`import ${JSON.stringify(V.workerUrl)};`],{type:"text/javascript"});e.GlobalWorkerOptions.workerPort=new Worker(URL.createObjectURL(t),{type:"module"})}catch{e.GlobalWorkerOptions.workerSrc=V.workerUrl}return e})(),le.catch(()=>{le=null})),le}function Ge(r,e,t){return/\.pdf$/i.test(r)||e==="application/pdf"?!0:t instanceof Uint8Array&&t.length>4&&t[0]===37&&t[1]===80&&t[2]===68&&t[3]===70}async function Ze(r,e={}){let n=(await dr()).getDocument({data:r.slice(),isEvalSupported:!1}),s=await n.promise;try{let o=[],i=Math.min(s.numPages,e.maxPages??500);for(let a=1;a<=i;a++){let l=await s.getPage(a),c=await l.getTextContent();o.push(c.items.map(u=>(u.str??"")+(u.hasEOL?`
148
148
  `:"")).join("").replace(/[ \t]+\n/g,`
149
149
  `).trim()),l.cleanup?.()}return{pages:o,numPages:s.numPages}}finally{await(n.destroy?n.destroy():s.destroy?.())}}function Xe(r,e){let t=`[PDF ${r}: ${e.numPages} page${e.numPages===1?"":"s"}${e.pages.length<e.numPages?`, text of the first ${e.pages.length}`:""}]`;return e.pages.some(n=>n.trim())?[t,...e.pages.map((n,s)=>`--- page ${s+1} ---
150
150
  ${n}`)].join(`
151
151
 
152
152
  `):`${t}
153
- This PDF has no text layer (it is probably scanned images), so there is no text to read. Tell the user; the pages would need to be read as pictures.`}var Ct="/.agent/skills";var hr="__runapps_agent_ws",$t="/skills",fr="\0skills",At=r=>typeof r=="object"&&!(r instanceof Uint8Array)&&typeof r.load=="function",Pe=new WeakMap,Ye=new Map,on=new WeakMap,pr=1,Pt=r=>{let e=on.get(r);return e||(e=pr++,on.set(r,e)),e},Ce=async(r,e)=>r.listStats?r.listStats(e):(await r.list(e)).map(dn),an=async(r,e)=>{if(r.stat)return r.stat(e);let t=await r.get(e);return t?dn(t):null},le=class r{constructor(e,t={}){y(this,"id");y(this,"dbName");y(this,"skillsDir");y(this,"userSkillsDir");y(this,"root");y(this,"store");y(this,"lib");y(this,"mounts",new Map);y(this,"skillViews",new Map);y(this,"builtins",[]);y(this,"lazySkills",[]);y(this,"resolvedSources",[]);y(this,"changeListeners",new Set);y(this,"channel");y(this,"sources");y(this,"provider");y(this,"inflate");y(this,"fetchFn");y(this,"fetchKey");y(this,"idb");y(this,"storeFactory");y(this,"skillCache",null);y(this,"opened",null);y(this,"sessions",{list:async()=>(await this.ready(),(await this.store.listSessions()).map(e=>({id:e.id??"",title:e.title&&!et(e.title)?e.title:$e(e),model:e.model,messages:e.messages.length,createdAt:e.createdAt??e.savedAt,savedAt:e.savedAt,workspace:e.space})).sort((e,t)=>t.savedAt-e.savedAt)),get:async e=>(await this.ready(),await this.store.getSession(this.id,e)??(e!==this.id?await this.store.getSession(e,e):void 0)??null),save:async e=>{if(await this.ready(),!e.id)throw new Error("a session needs an id to be saved");await this.store.putSession({...e,space:this.id})},delete:async(e,t)=>{await this.ready();let n=t??(await this.store.getSession(this.id,e)?this.id:await this.store.getSession(e,e)?e:(await this.store.listSessions()).find(s=>s.id===e)?.space??this.id);await this.store.deleteSession(n,e),n===e&&e!==this.id&&await this.store.clear(e)},clear:async()=>{await this.ready();for(let e of await this.store.listSessions())e.id&&await this.sessions.delete(e.id,e.space??this.id)}});if(this.provider=e?Z(e):null,this.id=t.id||"default",this.dbName=`${hr}:${t.project||this.provider?.name||"app"}`,this.sources=typeof t.skills=="function"?t.skills:t.skills?[].concat(t.skills):[],this.skillsDir=x(t.skillsDir||Ct),this.skillsDir==="/")throw new Error("skillsDir cannot be /");this.userSkillsDir=t.userSkills===!1||t.userSkillsDir===!1?null:x(t.userSkillsDir||$t);let n=(s,o)=>s===o||s.startsWith(o+"/")||o.startsWith(s+"/");if(this.userSkillsDir==="/"||this.userSkillsDir&&n(this.userSkillsDir,this.skillsDir))throw new Error("userSkillsDir must be its own folder, apart from skillsDir");this.root=t.dir??null,this.inflate=t.inflate,this.fetchFn=t.fetch??((...s)=>fetch(...s)),this.fetchKey=t.fetch?`f${Pt(t.fetch)}`:"",this.idb=t.indexedDB!==void 0?t.indexedDB:typeof indexedDB<"u"?indexedDB:null,this.storeFactory=t.store??null}static async open(e,t={}){let n=new r(e,t);return await n.ready(),n}ready(){if(!this.opened){let e=(async()=>{let t=n=>this.storeFactory?this.storeFactory.open(this.dbName,n):this.idb?wr(this.idb,this.dbName,n):Promise.resolve(br(this.dbName,n));this.store=await t(this.id),this.lib=await t(fr),this.openChannel(),await kr(`${this.dbName}:skills-migrate`,()=>this.migrateSkills()),this.builtins=await this.loadBuiltins(),this.mounts.set(this.skillsDir,this.skillsFS()),this.userSkillsDir&&this.mounts.set(this.userSkillsDir,this.userFS()),await this.rebuildSkills()})();this.opened=e,e.catch(()=>{this.opened===e&&(this.opened=null)})}return this.opened}close(){try{this.channel?.close()}catch{}if(this.channel=void 0,this.opened){let e=this.opened;this.opened=null,e.then(()=>{this.store.close(),this.lib.close()},()=>{})}}mount(e,t){let n=x(e);if(n==="/")throw new Error("cannot mount at / (open the workspace with `dir` instead)");this.mounts.set(n,t)}unmount(e){this.mounts.delete(x(e))}onChange(e){return this.changeListeners.add(e),this.openChannel(),()=>{this.changeListeners.delete(e)}}openChannel(){if(this.channel===void 0){if(typeof BroadcastChannel>"u"){this.channel=null;return}try{let e=new BroadcastChannel(`${this.dbName}:changes`);e.onmessage=t=>{let n=t.data;if(n?.userSkills){if(this.lib&&this.userSkillsDir&&typeof n.path=="string"&&(n.kind==="write"||n.kind==="delete")){let s=this.userSkillsDir+n.path,o=n.kind;this.rebuildSkills().then(()=>{this.emitChange(s,o,!0),this.emitChange(this.skillsDir,"write",!0)}).catch(()=>{})}return}n&&n.space===this.id&&typeof n.path=="string"&&(n.kind==="write"||n.kind==="delete")&&this.emitChange(n.path,n.kind,!0)},e.unref?.(),this.channel=e}catch{this.channel=null}}}emitChange(e,t,n=!1){if(n&&(e==="/"||this.inSkills(e))&&(this.skillCache=null),!n){this.openChannel();try{this.channel?.postMessage({space:this.id,path:e,kind:t})}catch{}}if(!this.changeListeners.size)return;let s={path:e,kind:t,remote:n};for(let o of this.changeListeners)try{o(s)}catch(i){console.warn("agent: onChange listener failed",i)}}describe(){let e=[this.root?`/ \u2014 ${this.root.description||"the working directory"}${this.root.write?"":" (read-only)"}.`:"/ \u2014 the working directory; it persists between conversations.",`${this.skillsDir}/ \u2014 skills, one folder per skill with a SKILL.md (read-only, generated from the app's skills${this.userSkillsDir?` and ${this.userSkillsDir}`:""}).`];this.userSkillsDir&&e.push(`${this.userSkillsDir}/ \u2014 the user's skills, shared by every conversation: skill zips and skill folders. To add a skill, write ${this.userSkillsDir}/<name>/SKILL.md (frontmatter with name and description); it appears under ${this.skillsDir}/ at once.`);for(let[t,n]of this.mounts)t!==this.skillsDir&&t!==this.userSkillsDir&&e.push(`${t}/ \u2014 ${n.description||"app files"}${n.write?"":" (read-only)"}.`);return e.join(`
154
- `)}route(e){let t=null;for(let n of this.mounts.keys())(e===n||e.startsWith(n+"/"))&&(!t||n.length>t.length)&&(t=n);return t?{fs:this.mounts.get(t),rel:e.slice(t.length)||"/",prefix:t}:this.root?{fs:this.root,rel:e,prefix:""}:null}inSkills(e){return e===this.skillsDir||e.startsWith(this.skillsDir+"/")}async putFile(e,t,n,s,o){if(this.inSkills(e)&&(this.skillCache=null),this.root){if(!this.root.write)throw new Error("/ is read-only");await this.root.write(e,t,n??V(e,t)),this.emitChange(e,"write");return}await this.store.put({path:e,data:t,contentType:n??V(e,t),mtime:Date.now(),layer:s,source:o}),this.emitChange(e,"write")}async rmFile(e){if(this.inSkills(e)&&(this.skillCache=null),this.root){if(!this.root.delete)throw new Error("/ is read-only");await this.root.delete(e),this.emitChange(e,"delete");return}await this.store.delete(e),this.emitChange(e,"delete")}async list(e="/"){await this.ready();let t=x(e),n=[],s=this.route(t);if(s&&s.prefix){for(let i of await s.fs.list(s.rel))n.push({...i,path:s.prefix+x(i.path)});return n.sort((i,a)=>i.path.localeCompare(a.path))}let o=this.root?(await this.root.list(t)).map(i=>({...i,path:x(i.path)})):await Ce(this.store,t==="/"?"/":t+"/");for(let i of o)this.route(i.path)?.prefix||n.push(i);for(let[i,a]of this.mounts)if(t==="/"||i.startsWith(t+"/"))for(let l of await a.list("/"))n.push({...l,path:i+x(l.path)});return n.sort((i,a)=>i.path.localeCompare(a.path))}async stat(e){await this.ready();let t=x(e),n=this.route(t);if(n){if(n.fs.stat){let o=await n.fs.stat(n.rel);return o?{...o,path:t}:null}let s=(await n.fs.list(n.rel)).find(o=>x(o.path)===x(n.rel));return s?{...s,path:t}:null}return an(this.store,t)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let t=x(e),n=this.route(t);if(n)try{let o=await n.fs.read(n.rel);return{data:o,size:Qe(o),contentType:V(t,o)}}catch(o){throw new Error(await this.missing(t,o))}let s=await this.store.get(t);if(!s)throw new Error(await this.missing(t));return{data:s.data,size:Qe(s.data),contentType:s.contentType}}async isFolder(e){let t=x(e);return t==="/"||this.mounts.has(t)?!0:(await this.list(t)).some(n=>n.path!==t)}async missing(e,t){if(await this.isFolder(e))return`${e} is a folder, not a file; use list_files to see what it holds`;let n=t instanceof Error?t.message:"";return/no such file/i.test(n)||!n?`No such file: ${e}`:`${e}: ${n}`}async readText(e){let{data:t}=await this.read(e);if(typeof t=="string")return t;let n=X(t);if(n===null)throw new Error(`${x(e)} is a binary file (${t.byteLength} bytes)`);return n}async readAsText(e){let t=x(e),{data:n,size:s,contentType:o}=await this.read(t);if(typeof n=="string")return{text:n,kind:"text"};if(Ge(t,o,n)){let a=await this.stat(t),l=`pdftext:${t}`,c=await this.getData(l).catch(()=>{});if(c&&c.size===s&&c.mtime===a?.mtime)return{text:c.text,kind:"pdf"};let u=Xe(t,await Ze(n));return await this.putData(l,{size:s,mtime:a?.mtime,text:u}).catch(()=>{}),{text:u,kind:"pdf"}}let i=X(n);return i===null?null:{text:i,kind:"text"}}async write(e,t,n){await this.ready();let s=x(e);if(s==="/")throw new Error("Cannot write to /");let o=this.route(s);if(o&&o.prefix){if(!o.fs.write)throw new Error(`${o.prefix} is read-only`);await o.fs.write(o.rel,t,n),this.emitChange(s,"write");return}await this.putFile(s,t,n,"work")}async edit(e,t){await this.ready();let n=x(e),s=this.route(n);if(s?.fs.edit){await s.fs.edit(s.rel,t),this.emitChange(n,"write");return}if(s&&!s.fs.write)throw new Error(`${s.prefix||"/"} is read-only`);await this.write(n,He(n,await this.readText(n),t))}async delete(e){await this.ready();let t=x(e),n=this.route(t);if(n&&n.prefix){if(!n.fs.delete)throw new Error(`${n.prefix} is read-only`);await n.fs.delete(n.rel),this.emitChange(t,"delete");return}if(!await this.stat(t))throw new Error(`No such file: ${t}`);await this.rmFile(t)}mountOf(e){return this.route(x(e))?.prefix||null}isReadOnly(e){let t=this.route(x(e));return t?!t.fs.write:!1}isSkillPath(e){let t=x(e);return this.inSkills(t)||!!this.userSkillsDir&&(t===this.userSkillsDir||t.startsWith(this.userSkillsDir+"/"))}async getData(e){await this.ready();let t=await this.store.getMeta("data:"+e);return t===null?void 0:t}async putData(e,t){await this.ready(),t==null?await this.store.deleteMeta("data:"+e):await this.store.putMeta("data:"+e,t)}async deleteData(e){await this.ready(),await this.store.deleteMeta("data:"+e)}async clearWork(){await this.ready();for(let e of await this.list("/"))this.inSkills(e.path)||this.route(e.path)?.prefix||await this.rmFile(e.path)}async skills(){if(await this.ready(),this.skillCache)return this.skillCache;let e=[],t=new Set;for(let[n,s]of this.skillViews){if(s.lazy){if(t.has(s.lazy.name))continue;t.add(s.lazy.name);let a=`${this.skillsDir}/${n}`;e.push({name:s.lazy.name,description:s.lazy.description,path:`${a}/SKILL.md`,dir:a,builtin:!0,lazy:!0,...s.lazy.disableModelInvocation?{disableModelInvocation:!0}:{}});continue}let o;try{let a=await s.fs.read("/SKILL.md");o=typeof a=="string"?a:X(a)}catch{continue}if(o===null)continue;let i=Se(o,`${this.skillsDir}/${n}/SKILL.md`);!i||t.has(i.skill.name)||(t.add(i.skill.name),e.push({...i.skill,...s.builtin?{builtin:!0}:{},...s.from?{from:s.from}:{}}))}return this.skillCache=e.sort((n,s)=>n.name.localeCompare(s.name)),this.skillCache}async installSkill(e,t={}){if(await this.ready(),!this.userSkillsDir)throw new Error("this workspace has no userSkillsDir to install skills into");let n,s;if(typeof e=="string"){let u=await this.fetchSource(e);if(!u)throw new Error("nothing fetched");n=u.bytes,s=t.name??e}else n=e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer()),s=t.name??(e.name||"skill");if(n.byteLength>52428800)throw new Error("skills zip too large");let o=Ve(s),i=Tt(n),a=ve(i.keys(),o);if(!a.size)throw new Error(`${o}.zip has no SKILL.md (at its root, or one per folder)`);let l=Date.now();if(t.unpack){for(let[u,d]of a){for(let f of await Ce(this.lib,`/${u}/`))await this.lib.delete(f.path);for(let[f,h]of i){if(!f.startsWith(d))continue;let p=await se(n,h,this.inflate),m=X(p),b=x(`/${u}/${f.slice(d.length)}`);await this.lib.put({path:b,data:m??p,contentType:V(b,m??p),mtime:l,layer:"work"})}}await this.userSkillsChanged(`/${[...a.keys()][0]}`,"write")}else await this.lib.put({path:`/${o}.zip`,data:n,contentType:"application/zip",mtime:l,layer:"work"}),await this.userSkillsChanged(`/${o}.zip`,"write");let c=new Set([...a.keys()].map(u=>`${this.skillsDir}/${u}`));return(await this.skills()).filter(u=>c.has(u.dir))}async removeSkill(e){let t=(await this.skills()).find(s=>s.name===e);if(!t)return!1;if(t.builtin)throw new Error(`"${e}" comes with the app and cannot be removed`);if(!t.from||!this.userSkillsDir||!t.from.startsWith(this.userSkillsDir+"/"))return!1;let n=t.from.slice(this.userSkillsDir.length);if(/\.zip$/i.test(n))await this.lib.delete(n);else for(let s of await Ce(this.lib,n+"/"))await this.lib.delete(s.path);return await this.userSkillsChanged(n,"delete"),!0}async skillBody(e){let t=(await this.skills()).find(s=>s.name===e);if(!t)throw new Error(`No skill named "${e}"`);let n=Se(await this.readText(t.path),t.path);return{skill:t,body:n?.body??""}}async refreshSkills(){await this.ready();for(let e of this.resolvedSources){if(At(e)){Pe.delete(e);continue}let t=typeof e=="string"?e:!(e instanceof Uint8Array)&&!cn(e)&&typeof e.data=="string"?e.data:null;t&&Ye.delete(`${this.dbName}|${this.fetchKey}|${t}`)}this.builtins=await this.loadBuiltins(),await this.rebuildSkills(),this.emitChange(this.skillsDir,"write")}async loadBuiltins(){let e=[],t=[];try{t=typeof this.sources=="function"?[].concat(await this.sources()):this.sources}catch(n){console.warn("[agent] the skills list failed:",n)}this.resolvedSources=t,this.lazySkills=t.filter(At);for(let n of t)if(!At(n))try{let s=typeof n=="object"&&!(n instanceof Uint8Array)&&!cn(n)?n:null,o=s?s.data:n,i,a,l=0;if(typeof o=="string"){let u=`${this.dbName}|${this.fetchKey}|${o}`,d=Ye.get(u);d||(d=this.fetchSource(o).then(f=>{if(!f)throw new Error("nothing fetched");return{bytes:f.bytes,at:Date.now()}}),Ye.set(u,d),d.catch(()=>Ye.delete(u))),{bytes:i,at:l}=await d,a=`app:${u}@${l}`}else i=o instanceof Uint8Array?o:new Uint8Array(await o.arrayBuffer()),a=`app:${this.dbName}|obj${Pt(o)}`;if(i.byteLength>52428800)throw new Error("skills zip too large");let c=Ve(s?.name??(typeof o=="string"?o:o.name||"skills"));e.push({name:c,bytes:i,key:a,at:l})}catch(s){console.warn("[agent] skills source failed:",s)}return e}async rebuildSkills(){let e=new Map;for(let t of this.builtins)try{let n=Je(t.name,t.bytes,t.key);for(let[s,o]of n.folders)e.has(s)||e.set(s,{fs:oe(n,o,t.at,this.inflate),builtin:!0})}catch(n){console.warn(`[agent] skills zip "${t.name}":`,n)}for(let t of this.lazySkills){let n=/^[A-Za-z0-9][\w.-]*$/.test(t.name)?t.name:Ve(t.name);e.has(n)||e.set(n,{fs:this.lazyFS(t,n),builtin:!0,lazy:t})}if(this.root)for(let t of await this.root.list(this.skillsDir).catch(()=>[])){let n=new RegExp("^"+gr(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(x(t.path));n&&e.set(n[1],{fs:Te(this.root,`${this.skillsDir}/${n[1]}`),builtin:!1,from:`${this.skillsDir}/${n[1]}`})}if(this.userSkillsDir){let t=await Ce(this.lib,"/");for(let s of t){let o=/^\/([^/]+)\.zip$/i.exec(s.path);if(o)try{let i=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,a=s.mtime!==void 0?nn(i):void 0;if(!a){let l=await this.lib.get(s.path);if(!l||!(l.data instanceof Uint8Array))continue;a=Je(Ve(o[1]),l.data,i)}for(let[l,c]of a.folders)e.set(l,{fs:oe(a,c,s.mtime??0,this.inflate),builtin:!1,from:this.userSkillsDir+s.path})}catch(i){console.warn(`[agent] skills zip "${s.path}":`,i)}}let n=this.userFS();for(let s of t){let o=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);o&&e.set(o[1],{fs:Te(n,`/${o[1]}`),builtin:!1,from:`${this.userSkillsDir}/${o[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,t){let n=null,s=async()=>{if(n)return n;let i=Pe.get(e);i||(i=(async()=>{let u=await e.load();if(typeof u=="string"){let d=await this.fetchSource(u);if(!d)throw new Error("nothing fetched");return d.bytes}return u instanceof Uint8Array?u:u instanceof ArrayBuffer?new Uint8Array(u):new Uint8Array(await u.arrayBuffer())})(),Pe.set(e,i),i.catch(()=>{Pe.get(e)===i&&Pe.delete(e)}));let a;try{a=await i}catch(u){throw new Error(`the skill "${e.name}" could not be loaded: ${u.message}`)}if(a.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let l=Je(t,a,`lazy:${Pt(e)}:${a.byteLength}`),c=l.folders.get(t)??[...l.folders.values()][0];if(c===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return n=oe(l,c,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${t}`,"write"),n},o=i=>i==="/"||i==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async i=>n?n.list(i):o(i),stat:async i=>{if(!n&&i==="/SKILL.md")return{path:i,size:0};let a=await s();return a.stat?a.stat(i):null},read:async i=>(await s()).read(i)}}skillsFS(){let e=t=>{let n=/^\/([^/]+)(\/.*)?$/.exec(t);return n?{name:n[1],rest:n[2]||"/"}:null};return{description:"skills (generated, read-only)",list:async t=>{let n=[],s=e(t);for(let[o,i]of this.skillViews)if(!(s&&s.name!==o))for(let a of await i.fs.list(s?s.rest:"/"))n.push({...a,path:`/${o}${x(a.path)}`});return n},stat:async t=>{let n=e(t),s=n&&this.skillViews.get(n.name);if(!s||!n)return null;let o=s.fs.stat?await s.fs.stat(n.rest):(await s.fs.list(n.rest)).find(i=>x(i.path)===n.rest)??null;return o?{...o,path:t}:null},read:async t=>{let n=e(t),s=n&&this.skillViews.get(n.name);if(!s||!n)throw new Error(`No such file: ${t}`);return s.fs.read(n.rest)}}}userFS(){return{description:"the user's skills, shared by every conversation",list:async e=>Ce(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>an(this.lib,e),read:async e=>{let t=await this.lib.get(e);if(!t)throw new Error(`No such file: ${e}`);return t.data},write:async(e,t,n)=>{await this.lib.put({path:e,data:t,contentType:n??V(e,t),mtime:Date.now(),layer:"work"}),await this.userSkillsChanged(e,"write")},delete:async e=>{await this.lib.delete(e),await this.userSkillsChanged(e,"delete")}}}async userSkillsChanged(e,t){await this.rebuildSkills(),this.openChannel();try{this.channel?.postMessage({userSkills:!0,path:e,kind:t})}catch{}this.emitChange(this.skillsDir,"write")}async migrateSkills(){if(!await this.lib.getMeta("migrated:2")){for(let t of await this.lib.listMeta("zip:"))t.source==="upload"&&!await this.lib.get(`/${t.name}.zip`)&&await this.lib.put({path:`/${t.name}.zip`,data:t.bytes,contentType:"application/zip",mtime:t.at||Date.now(),layer:"work"});for(let t of["zip:","removed:"])for(let n of await this.lib.listMetaKeys(t))await this.lib.deleteMeta(n);await this.lib.putMeta("migrated:2",!0)}if(this.root||await this.store.getMeta("skills-migrated:2"))return;let e=await this.store.list(this.skillsDir+"/");if(e.length){let t=new Set;for(let n of await this.store.listMetaKeys("skills:")){let s=await this.store.getMeta(n);if(!n.startsWith("skills:upload:"))for(let o of s?.files??[])t.add(o);await this.store.deleteMeta(n)}for(let n of e){let s=n.path.slice(this.skillsDir.length);!t.has(n.path)&&this.userSkillsDir&&!await this.lib.get(s)&&await this.lib.put({...n,path:s,layer:"work"}),await this.store.delete(n.path)}}await this.store.putMeta("skills-migrated:2",!0)}async fetchSource(e,t){if(e.startsWith("files:")){if(!this.provider?.readFile)throw new Error("a files: skills source needs a provider that reads files (RunApps)");let i=await this.provider.readFile(e.slice(6),{etag:t?.etag});if(!i)return null;if(i.bytes.byteLength>52428800)throw new Error("skills zip too large");return i}let n={};t?.etag?n["If-None-Match"]=t.etag:t?.lastModified&&(n["If-Modified-Since"]=t.lastModified);let s=await this.fetchFn(e,{headers:n,cache:"no-cache"});if(s.status===304)return null;if(!s.ok)throw new Error(`HTTP ${s.status}`);let o=await s.arrayBuffer();if(o.byteLength>52428800)throw new Error("skills zip too large");return{bytes:new Uint8Array(o),etag:s.headers.get("ETag")??void 0,lastModified:s.headers.get("Last-Modified")??void 0}}async destroy(){await this.ready(),await this.store.clear(),this.emitChange("/","delete"),this.close(),this.skillCache=null}};function x(r){let e=[];for(let t of String(r??"").replace(/\\/g,"/").split("/"))if(!(!t||t===".")){if(t===".."){e.pop();continue}e.push(t)}return"/"+e.join("/")}function dn(r){return{path:r.path,size:Qe(r.data),contentType:r.contentType,mtime:r.mtime}}function Qe(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var mr=new Set(["md","txt","json","js","mjs","cjs","ts","tsx","jsx","css","html","htm","xml","svg","yaml","yml","toml","csv","tsv","py","sh","sql","ini","cfg","conf","log","drawio","env","gitignore"]),ln={md:"text/markdown",txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/typescript",css:"text/css",html:"text/html",xml:"application/xml",svg:"image/svg+xml",yaml:"application/yaml",yml:"application/yaml",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf",zip:"application/zip",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",py:"text/x-python",sh:"text/x-shellscript"};function V(r,e){let t=r.split(".").pop()?.toLowerCase()??"";return ln[t]?ln[t]:typeof e=="string"||mr.has(t)?"text/plain":"application/octet-stream"}function X(r){let e=r.subarray(0,8192);for(let t=0;t<e.length;t++)if(e[t]===0)return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return null}}var cn=r=>typeof Blob<"u"&&r instanceof Blob,gr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Ve(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var yr=4;function wr(r,e,t){return new Promise((n,s)=>{let o=r.open(e,yr);o.onupgradeneeded=i=>{let a=o.result,l=o.transaction,c=i.oldVersion,u=()=>a.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(c<3){for(let d of["files","meta","sessions"])a.objectStoreNames.contains(d)&&a.deleteObjectStore(d);a.createObjectStore("files",{keyPath:["space","path"]}),a.createObjectStore("meta",{keyPath:["space","key"]}),u();return}if(c<4){let d=l.objectStore("sessions").getAll();d.onsuccess=()=>{let f=d.result;a.deleteObjectStore("sessions"),u();let h=l.objectStore("sessions");for(let p of f)p.id&&h.put({...p,space:p.space??"default"})}}},o.onerror=()=>s(o.error??new Error("indexedDB open failed")),o.onblocked=()=>console.warn(`agent: ${e} is waiting for another tab to release the database`),o.onsuccess=()=>{let i=o.result;i.onversionchange=()=>i.close();let a=(c,u,d)=>new Promise((f,h)=>{let p=i.transaction(c,u),m=d(p.objectStore(c)),b;m.onsuccess=()=>{b=m.result,u==="readonly"&&f(b)},m.onerror=()=>h(m.error??new Error("indexedDB request failed")),p.oncomplete=()=>f(b),p.onabort=()=>h(p.error??new Error("indexedDB transaction aborted"))}),l=(c,u)=>IDBKeyRange.bound([c,u],[c,u+"\uFFFF"],!1,!1);n({get:c=>a("files","readonly",u=>u.get([t,c])),put:async c=>{await a("files","readwrite",u=>u.put({...c,space:t}))},delete:async c=>{await a("files","readwrite",u=>u.delete([t,c]))},list:c=>a("files","readonly",u=>u.getAll(l(t,c))),getMeta:async c=>(await a("meta","readonly",u=>u.get([t,c])))?.value,putMeta:async(c,u)=>{await a("meta","readwrite",d=>d.put({space:t,key:c,value:u}))},deleteMeta:async c=>{await a("meta","readwrite",u=>u.delete([t,c]))},listMeta:async c=>(await a("meta","readonly",u=>u.getAll(l(t,c)))).map(u=>u.value),listMetaKeys:async c=>(await a("meta","readonly",u=>u.getAll(l(t,c)))).map(u=>u.key),getSession:(c,u)=>a("sessions","readonly",d=>d.get([c,u])),putSession:async c=>{await a("sessions","readwrite",u=>u.put(c))},deleteSession:async(c,u)=>{await a("sessions","readwrite",d=>d.delete([c,u]))},listSessions:()=>a("sessions","readonly",c=>c.getAll()),clear:async(c=t)=>{await a("files","readwrite",u=>u.delete(l(c,"/"))),await a("meta","readwrite",u=>u.delete(l(c,""))),await a("sessions","readwrite",u=>u.delete(l(c,"")))},close:()=>i.close()})}})}var un=new Map;function br(r,e){let t=un.get(r);t||(t={files:new Map,meta:new Map,sessions:new Map},un.set(r,t));let n=t,s=()=>{let i=n.files.get(e);return i||(i=new Map,n.files.set(e,i)),i},o=()=>{let i=n.meta.get(e);return i||(i=new Map,n.meta.set(e,i)),i};return{get:async i=>s().get(i),put:async i=>{s().set(i.path,{...i,space:e})},delete:async i=>{s().delete(i)},list:async i=>[...s().values()].filter(a=>i==="/"||a.path.startsWith(i)),getMeta:async i=>o().get(i),putMeta:async(i,a)=>{o().set(i,a)},deleteMeta:async i=>{o().delete(i)},listMeta:async i=>[...o()].filter(([a])=>a.startsWith(i)).map(([,a])=>a),listMetaKeys:async i=>[...o().keys()].filter(a=>a.startsWith(i)),getSession:async(i,a)=>n.sessions.get(`${i}\0${a}`),putSession:async i=>{n.sessions.set(`${i.space??e}\0${i.id}`,i)},deleteSession:async(i,a)=>{n.sessions.delete(`${i}\0${a}`)},listSessions:async()=>[...n.sessions.values()],clear:async(i=e)=>{n.files.delete(i),n.meta.delete(i);for(let[a,l]of n.sessions)l.space===i&&n.sessions.delete(a)},close:()=>{}}}var ce="Untitled";function $e(r){for(let e of r.messages){if(e.role!=="user"||K(e)!==null)continue;let t=e.typed,s=(typeof t=="string"?t:typeof e.content=="string"?e.content:(e.content??[]).find(o=>o.type==="text")?.text??"").replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim();if(!(!s||et(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return ce}function et(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function kr(r,e){let t=typeof navigator<"u"?navigator.locks:void 0;return t&&typeof t.request=="function"?t.request(r,e):e()}function hn(r={},e={}){let t=new Map;for(let[s,o]of Object.entries(r))t.set(x(s),o);let n={files:t,description:e.description,async list(s){let o=x(s);return[...t.entries()].filter(([i])=>o==="/"||i===o||i.startsWith(o+"/")).map(([i,a])=>({path:i,size:Qe(a)}))},async read(s){let o=t.get(x(s));if(o===void 0)throw new Error(`No such file: ${x(s)}`);return o}};return e.readonly||(n.write=async(s,o)=>{t.set(x(s),o)},n.delete=async s=>{if(!t.delete(x(s)))throw new Error(`No such file: ${x(s)}`)}),n}var xr=4*1024*1024;function Sr(r){let e=typeof r=="string"?r:X(r),t=2166136261;if(e!==null)for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);else for(let n of r)t^=n,t=Math.imul(t,16777619);return(t>>>0).toString(36)}function vr(r,e,t){if(t<e)return!1;let n=r.some(([o,i])=>o<=e&&i>=t);r.push([e,t]),r.sort((o,i)=>o[0]-i[0]);let s=[];for(let o of r){let i=s[s.length-1];i&&o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):s.push([o[0],o[1]])}return r.splice(0,r.length,...s),!n}var Q=class extends Error{constructor(t,n,s){super(t);y(this,"path",n);y(this,"coveredTo",s);this.name="PartialReadError"}};function ue(r,e={}){let t=e.enabled!==!1,n=new Map,s=async(o,i)=>{let a=await r.stat(o);if(!a)return null;let l=a.size>xr?"":Sr(i??(await r.read(o)).data);return`${a.mtime??""}:${a.size}:${l}`};return{enabled:t,async saw(o,i={}){if(!t)return;let a=await s(o,i.text).catch(()=>null);if(!a)return n.delete(o),!0;let l=i.start??1,c=i.end??1/0,u=i.total??1/0,d=n.get(o),f=!!d&&d.version===a,h=f&&l<=d.coveredTo+1?Math.max(d.coveredTo,c):l<=1?c:0,p=f?d.ranges:[],m=vr(p,l,c)||!f;return n.set(o,{version:a,coveredTo:h,total:u,ranges:p}),m},async wrote(o){if(!t)return;let i=await s(o).catch(()=>null);i?n.set(o,{version:i,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):n.delete(o)},async copied(o,i){if(!t)return;let a=n.get(o),l=a?await s(i).catch(()=>null):null;a&&l?n.set(i,{...a,version:l,ranges:a.ranges.map(([c,u])=>[c,u])}):n.delete(i)},async edited(o){if(!t)return;let i=n.get(o),a=await s(o).catch(()=>null);a&&i?n.set(o,{...i,version:a,total:1/0,ranges:[]}):n.delete(o)},async check(o,i){if(!t)return;let a=await s(o);if(a===null)return;let l=n.get(o);if(!l){if(i==="delete")return;throw new Error(`${o} already exists and you have not read it in this conversation: read it with read_file first, then ${i} it.`)}if(l.version!==a)throw new Error(`${o} has changed since you last read it (the user or another process edited it): read it again with read_file, then ${i==="delete"?"decide whether to delete it":"make your change on the current content"}.`);if(i==="overwrite"&&l.coveredTo<l.total)throw new Q(`You have read only lines 1-${l.coveredTo} of ${o}: read the rest (read_file with offset=${l.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,o,l.coveredTo)},async known(o){let i=n.get(o);return!i||await s(o).catch(()=>null)!==i.version?"none":i.coveredTo>=i.total?"all":i.coveredTo>0?"part":"none"},forget(o){n.delete(o)},retain(o){let i=new Set(o);for(let a of[...n.keys()])i.has(a)||n.delete(a)},clear(){n.clear()}}}var _t=500,tt=2e3,nt=50*1024,rt=100,fn=5*1024*1024,Tr={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},Ar={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function Pr(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e)}function st(r,e={}){let t=e.guard??ue(r,{enabled:e.readBeforeWrite!==!1}),n=t.enabled;return[L({name:"list_files",description:`List the files under a folder of the workspace (recursive), one per line with the size in bytes. Output is truncated to 500 entries. Start at / to see everything; ${r.skillsDir} holds the skills.`,readOnly:!0,parameters:{type:"object",properties:{path:{type:"string",description:"Folder to list. Default /"}},additionalProperties:!1},async execute({path:s},o){let i=await r.list(s||"/");if(!i.length)return`No files under ${x(s||"/")}.`;let a=o?.parentId?1/0:_t,l=i.slice(0,a).map(c=>`${c.path} (${c.size} B)`);return i.length>a&&l.push(`
155
- [${_t} entries limit reached (${i.length} in all). List a sub-folder.]`),l.join(`
156
- `)}}),L({name:"read_file",description:"Read the contents of a text file in the workspace; a PDF is read as the text of its pages, each under a `--- page N ---` line; a picture (PNG, JPEG, GIF, WebP) is shown to you when the model can see pictures. Output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files; when you need the full file, continue with offset until complete. Reading a folder lists it.",readOnly:!0,parameters:{type:"object",properties:{path:{type:"string",description:"Absolute path in the workspace"},offset:{type:"integer",minimum:1,description:"Line number to start reading from (1-indexed)"},limit:{type:"integer",minimum:1,description:"Maximum number of lines to read"}},required:["path"],additionalProperties:!1},async execute({path:s,offset:o,limit:i},a){if(await r.isFolder(s)){let T=await r.list(s);return`${x(s)} is a folder with ${T.length} file${T.length===1?"":"s"}:
157
- `+T.slice(0,_t).map(C=>`${C.path} (${C.size} B)`).join(`
158
- `)}let l=await r.stat(s),c=l&&Tr[(l.contentType??"").split(";")[0].trim()]?l.contentType.split(";")[0].trim():Ar[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(l&&c&&await a.agent?.accepts("image")===!0){if(l.size>fn)return`${x(s)} is a picture of ${l.size} bytes, more than the ${fn/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:T}=await r.read(s),C=typeof T=="string"?new TextEncoder().encode(T):T;return await t.saw(x(s)),[{type:"text",text:`${x(s)} (${c}, ${C.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${c};base64,${Pr(C)}`}}]}let u;try{u=await r.readAsText(s)}catch(T){if(await r.stat(s)&&/\.pdf$/i.test(s))return`Could not read the PDF ${x(s)}: ${T.message}`;throw T}if(!u){await t.saw(x(s));let T=await r.stat(s),C=c&&await a.agent?.accepts("image")===!1?" The model in use cannot view pictures.":"";return`${x(s)} is a binary file (${T?.contentType??"unknown type"}, ${T?.size??0} bytes).${C}`}let d=u.text,f=d.split(`
159
- `),h=f.length,p=Math.max(1,o??1);if(p>h)return await t.saw(x(s),{start:h+1,end:h,total:h}),`Offset ${p} is beyond end of file (${h} lines total)`;let m=!!a?.parentId,b=m?i??1/0:i!==void 0?Math.min(i,tt):tt,S=[],g=0,w=p-1;for(let T=p-1;T<h&&S.length<b;T++){let C=new TextEncoder().encode(f[T]).byteLength+1;if(!m&&g+C>nt&&S.length>0)break;S.push(f[T]),g+=C,w=T+1}let _=await t.saw(x(s),{start:p,end:w,total:h,text:u.kind==="text"?d:void 0});_!==void 0&&a.progress?.(_);let k="";if(w<h){let T=w+1;g>=nt||i===void 0&&S.length>=tt?k=`
153
+ This PDF has no text layer (it is probably scanned images), so there is no text to read. Tell the user; the pages would need to be read as pictures.`}var _t="/.agent/skills";var hr="__runapps_agent_ws",Mt="/skills",pr="\0skills",Ct=r=>typeof r=="object"&&!(r instanceof Uint8Array)&&typeof r.load=="function",Pe=new WeakMap,Ye=new Map,on=new WeakMap,fr=1,$t=r=>{let e=on.get(r);return e||(e=fr++,on.set(r,e)),e},Ce=async(r,e)=>r.listStats?r.listStats(e):(await r.list(e)).map(dn),an=async(r,e)=>{if(r.stat)return r.stat(e);let t=await r.get(e);return t?dn(t):null},ce=class r{constructor(e,t={}){y(this,"id");y(this,"dbName");y(this,"skillsDir");y(this,"userSkillsDir");y(this,"root");y(this,"store");y(this,"lib");y(this,"mounts",new Map);y(this,"skillViews",new Map);y(this,"builtins",[]);y(this,"lazySkills",[]);y(this,"resolvedSources",[]);y(this,"changeListeners",new Set);y(this,"channel");y(this,"sources");y(this,"provider");y(this,"inflate");y(this,"fetchFn");y(this,"fetchKey");y(this,"idb");y(this,"storeFactory");y(this,"skillCache",null);y(this,"opened",null);y(this,"sessions",{list:async()=>(await this.ready(),(await this.store.listSessions()).map(e=>({id:e.id??"",title:e.title&&!et(e.title)?e.title:$e(e),model:e.model,messages:e.messages.length,createdAt:e.createdAt??e.savedAt,savedAt:e.savedAt,workspace:e.space})).sort((e,t)=>t.savedAt-e.savedAt)),get:async e=>(await this.ready(),await this.store.getSession(this.id,e)??(e!==this.id?await this.store.getSession(e,e):void 0)??null),save:async e=>{if(await this.ready(),!e.id)throw new Error("a session needs an id to be saved");await this.store.putSession({...e,space:this.id})},delete:async(e,t)=>{await this.ready();let n=t??(await this.store.getSession(this.id,e)?this.id:await this.store.getSession(e,e)?e:(await this.store.listSessions()).find(s=>s.id===e)?.space??this.id);await this.store.deleteSession(n,e),n===e&&e!==this.id&&await this.store.clear(e)},clear:async()=>{await this.ready();for(let e of await this.store.listSessions())e.id&&await this.sessions.delete(e.id,e.space??this.id)}});if(this.provider=e?Z(e):null,this.id=t.id||"default",this.dbName=`${hr}:${t.project||this.provider?.name||"app"}`,this.sources=typeof t.skills=="function"?t.skills:t.skills?[].concat(t.skills):[],this.skillsDir=x(t.skillsDir||_t),this.skillsDir==="/")throw new Error("skillsDir cannot be /");this.userSkillsDir=t.userSkills===!1||t.userSkillsDir===!1?null:x(t.userSkillsDir||Mt);let n=(s,o)=>s===o||s.startsWith(o+"/")||o.startsWith(s+"/");if(this.userSkillsDir==="/"||this.userSkillsDir&&n(this.userSkillsDir,this.skillsDir))throw new Error("userSkillsDir must be its own folder, apart from skillsDir");this.root=t.dir??null,this.inflate=t.inflate,this.fetchFn=t.fetch??((...s)=>fetch(...s)),this.fetchKey=t.fetch?`f${$t(t.fetch)}`:"",this.idb=t.indexedDB!==void 0?t.indexedDB:typeof indexedDB<"u"?indexedDB:null,this.storeFactory=t.store??null}static async open(e,t={}){let n=new r(e,t);return await n.ready(),n}ready(){if(!this.opened){let e=(async()=>{let t=n=>this.storeFactory?this.storeFactory.open(this.dbName,n):this.idb?wr(this.idb,this.dbName,n):Promise.resolve(br(this.dbName,n));this.store=await t(this.id),this.lib=await t(pr),this.openChannel(),await kr(`${this.dbName}:skills-migrate`,()=>this.migrateSkills()),this.builtins=await this.loadBuiltins(),this.mounts.set(this.skillsDir,this.skillsFS()),this.userSkillsDir&&this.mounts.set(this.userSkillsDir,this.userFS()),await this.rebuildSkills()})();this.opened=e,e.catch(()=>{this.opened===e&&(this.opened=null)})}return this.opened}close(){try{this.channel?.close()}catch{}if(this.channel=void 0,this.opened){let e=this.opened;this.opened=null,e.then(()=>{this.store.close(),this.lib.close()},()=>{})}}mount(e,t){let n=x(e);if(n==="/")throw new Error("cannot mount at / (open the workspace with `dir` instead)");this.mounts.set(n,t)}unmount(e){this.mounts.delete(x(e))}onChange(e){return this.changeListeners.add(e),this.openChannel(),()=>{this.changeListeners.delete(e)}}openChannel(){if(this.channel===void 0){if(typeof BroadcastChannel>"u"){this.channel=null;return}try{let e=new BroadcastChannel(`${this.dbName}:changes`);e.onmessage=t=>{let n=t.data;if(n?.userSkills){if(this.lib&&this.userSkillsDir&&typeof n.path=="string"&&(n.kind==="write"||n.kind==="delete")){let s=this.userSkillsDir+n.path,o=n.kind;this.rebuildSkills().then(()=>{this.emitChange(s,o,!0),this.emitChange(this.skillsDir,"write",!0)}).catch(()=>{})}return}n&&n.space===this.id&&typeof n.path=="string"&&(n.kind==="write"||n.kind==="delete")&&this.emitChange(n.path,n.kind,!0)},e.unref?.(),this.channel=e}catch{this.channel=null}}}emitChange(e,t,n=!1){if(n&&(e==="/"||this.inSkills(e))&&(this.skillCache=null),!n){this.openChannel();try{this.channel?.postMessage({space:this.id,path:e,kind:t})}catch{}}if(!this.changeListeners.size)return;let s={path:e,kind:t,remote:n};for(let o of this.changeListeners)try{o(s)}catch(i){console.warn("agent: onChange listener failed",i)}}describe(){let e=[this.root?`/ \u2014 ${this.root.description||"the working directory"}${this.root.write?"":" (read-only)"}.`:"/ \u2014 the working directory; it persists between conversations.",`${this.skillsDir}/ \u2014 skills, one folder per skill with a SKILL.md (read-only, generated from the app's skills${this.userSkillsDir?` and ${this.userSkillsDir}`:""}).`];this.userSkillsDir&&e.push(`${this.userSkillsDir}/ \u2014 the user's skills, shared by every conversation: skill zips and skill folders. To add a skill, write ${this.userSkillsDir}/<name>/SKILL.md (frontmatter with name and description); it appears under ${this.skillsDir}/ at once.`);for(let[t,n]of this.mounts)t!==this.skillsDir&&t!==this.userSkillsDir&&e.push(`${t}/ \u2014 ${n.description||"app files"}${n.write?"":" (read-only)"}.`);return e.join(`
154
+ `)}route(e){let t=null;for(let n of this.mounts.keys())(e===n||e.startsWith(n+"/"))&&(!t||n.length>t.length)&&(t=n);return t?{fs:this.mounts.get(t),rel:e.slice(t.length)||"/",prefix:t}:this.root?{fs:this.root,rel:e,prefix:""}:null}inSkills(e){return e===this.skillsDir||e.startsWith(this.skillsDir+"/")}async putFile(e,t,n,s,o){if(this.inSkills(e)&&(this.skillCache=null),this.root){if(!this.root.write)throw new Error("/ is read-only");await this.root.write(e,t,n??Q(e,t)),this.emitChange(e,"write");return}await this.store.put({path:e,data:t,contentType:n??Q(e,t),mtime:Date.now(),layer:s,source:o}),this.emitChange(e,"write")}async rmFile(e){if(this.inSkills(e)&&(this.skillCache=null),this.root){if(!this.root.delete)throw new Error("/ is read-only");await this.root.delete(e),this.emitChange(e,"delete");return}await this.store.delete(e),this.emitChange(e,"delete")}async list(e="/"){await this.ready();let t=x(e),n=[],s=this.route(t);if(s&&s.prefix){for(let i of await s.fs.list(s.rel))n.push({...i,path:s.prefix+x(i.path)});return n.sort((i,a)=>i.path.localeCompare(a.path))}let o=this.root?(await this.root.list(t)).map(i=>({...i,path:x(i.path)})):await Ce(this.store,t==="/"?"/":t+"/");for(let i of o)this.route(i.path)?.prefix||n.push(i);for(let[i,a]of this.mounts)if(t==="/"||i.startsWith(t+"/"))for(let l of await a.list("/"))n.push({...l,path:i+x(l.path)});return n.sort((i,a)=>i.path.localeCompare(a.path))}async stat(e){await this.ready();let t=x(e),n=this.route(t);if(n){if(n.fs.stat){let o=await n.fs.stat(n.rel);return o?{...o,path:t}:null}let s=(await n.fs.list(n.rel)).find(o=>x(o.path)===x(n.rel));return s?{...s,path:t}:null}return an(this.store,t)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let t=x(e),n=this.route(t);if(n)try{let o=await n.fs.read(n.rel);return{data:o,size:Qe(o),contentType:Q(t,o)}}catch(o){throw new Error(await this.missing(t,o))}let s=await this.store.get(t);if(!s)throw new Error(await this.missing(t));return{data:s.data,size:Qe(s.data),contentType:s.contentType}}async isFolder(e){let t=x(e);return t==="/"||this.mounts.has(t)?!0:(await this.list(t)).some(n=>n.path!==t)}async missing(e,t){if(await this.isFolder(e))return`${e} is a folder, not a file; use list_files to see what it holds`;let n=t instanceof Error?t.message:"";return/no such file/i.test(n)||!n?`No such file: ${e}`:`${e}: ${n}`}async readText(e){let{data:t}=await this.read(e);if(typeof t=="string")return t;let n=X(t);if(n===null)throw new Error(`${x(e)} is a binary file (${t.byteLength} bytes)`);return n}async readAsText(e){let t=x(e),{data:n,size:s,contentType:o}=await this.read(t);if(typeof n=="string")return{text:n,kind:"text"};if(Ge(t,o,n)){let a=await this.stat(t),l=`pdftext:${t}`,c=await this.getData(l).catch(()=>{});if(c&&c.size===s&&c.mtime===a?.mtime)return{text:c.text,kind:"pdf"};let u=Xe(t,await Ze(n));return await this.putData(l,{size:s,mtime:a?.mtime,text:u}).catch(()=>{}),{text:u,kind:"pdf"}}let i=X(n);return i===null?null:{text:i,kind:"text"}}async write(e,t,n){await this.ready();let s=x(e);if(s==="/")throw new Error("Cannot write to /");let o=this.route(s);if(o&&o.prefix){if(!o.fs.write)throw new Error(`${o.prefix} is read-only`);await o.fs.write(o.rel,t,n),this.emitChange(s,"write");return}await this.putFile(s,t,n,"work")}async edit(e,t){await this.ready();let n=x(e),s=this.route(n);if(s?.fs.edit){await s.fs.edit(s.rel,t),this.emitChange(n,"write");return}if(s&&!s.fs.write)throw new Error(`${s.prefix||"/"} is read-only`);await this.write(n,He(n,await this.readText(n),t))}async delete(e){await this.ready();let t=x(e),n=this.route(t);if(n&&n.prefix){if(!n.fs.delete)throw new Error(`${n.prefix} is read-only`);await n.fs.delete(n.rel),this.emitChange(t,"delete");return}if(!await this.stat(t))throw new Error(`No such file: ${t}`);await this.rmFile(t)}mountOf(e){return this.route(x(e))?.prefix||null}isReadOnly(e){let t=this.route(x(e));return t?!t.fs.write:!1}isSkillPath(e){let t=x(e);return this.inSkills(t)||!!this.userSkillsDir&&(t===this.userSkillsDir||t.startsWith(this.userSkillsDir+"/"))}async getData(e){await this.ready();let t=await this.store.getMeta("data:"+e);return t===null?void 0:t}async putData(e,t){await this.ready(),t==null?await this.store.deleteMeta("data:"+e):await this.store.putMeta("data:"+e,t)}async deleteData(e){await this.ready(),await this.store.deleteMeta("data:"+e)}async clearWork(){await this.ready();for(let e of await this.list("/"))this.inSkills(e.path)||this.route(e.path)?.prefix||await this.rmFile(e.path)}async skills(){if(await this.ready(),this.skillCache)return this.skillCache;let e=[],t=new Set;for(let[n,s]of this.skillViews){if(s.lazy){if(t.has(s.lazy.name))continue;t.add(s.lazy.name);let a=`${this.skillsDir}/${n}`;e.push({name:s.lazy.name,description:s.lazy.description,path:`${a}/SKILL.md`,dir:a,builtin:!0,lazy:!0,...s.lazy.disableModelInvocation?{disableModelInvocation:!0}:{}});continue}let o;try{let a=await s.fs.read("/SKILL.md");o=typeof a=="string"?a:X(a)}catch{continue}if(o===null)continue;let i=ve(o,`${this.skillsDir}/${n}/SKILL.md`);!i||t.has(i.skill.name)||(t.add(i.skill.name),e.push({...i.skill,...s.builtin?{builtin:!0}:{},...s.from?{from:s.from}:{}}))}return this.skillCache=e.sort((n,s)=>n.name.localeCompare(s.name)),this.skillCache}async installSkill(e,t={}){if(await this.ready(),!this.userSkillsDir)throw new Error("this workspace has no userSkillsDir to install skills into");let n,s;if(typeof e=="string"){let u=await this.fetchSource(e);if(!u)throw new Error("nothing fetched");n=u.bytes,s=t.name??e}else n=e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer()),s=t.name??(e.name||"skill");if(n.byteLength>52428800)throw new Error("skills zip too large");let o=Ve(s),i=Pt(n),a=Se(i.keys(),o);if(!a.size)throw new Error(`${o}.zip has no SKILL.md (at its root, or one per folder)`);let l=Date.now();if(t.unpack){for(let[u,d]of a){for(let p of await Ce(this.lib,`/${u}/`))await this.lib.delete(p.path);for(let[p,h]of i){if(!p.startsWith(d))continue;let f=await ie(n,h,this.inflate),m=X(f),b=x(`/${u}/${p.slice(d.length)}`);await this.lib.put({path:b,data:m??f,contentType:Q(b,m??f),mtime:l,layer:"work"})}}await this.userSkillsChanged(`/${[...a.keys()][0]}`,"write")}else await this.lib.put({path:`/${o}.zip`,data:n,contentType:"application/zip",mtime:l,layer:"work"}),await this.userSkillsChanged(`/${o}.zip`,"write");let c=new Set([...a.keys()].map(u=>`${this.skillsDir}/${u}`));return(await this.skills()).filter(u=>c.has(u.dir))}async removeSkill(e){let t=(await this.skills()).find(s=>s.name===e);if(!t)return!1;if(t.builtin)throw new Error(`"${e}" comes with the app and cannot be removed`);if(!t.from||!this.userSkillsDir||!t.from.startsWith(this.userSkillsDir+"/"))return!1;let n=t.from.slice(this.userSkillsDir.length);if(/\.zip$/i.test(n))await this.lib.delete(n);else for(let s of await Ce(this.lib,n+"/"))await this.lib.delete(s.path);return await this.userSkillsChanged(n,"delete"),!0}async skillBody(e){let t=(await this.skills()).find(s=>s.name===e);if(!t)throw new Error(`No skill named "${e}"`);let n=ve(await this.readText(t.path),t.path);return{skill:t,body:n?.body??""}}async refreshSkills(){await this.ready();for(let e of this.resolvedSources){if(Ct(e)){Pe.delete(e);continue}let t=typeof e=="string"?e:!(e instanceof Uint8Array)&&!cn(e)&&typeof e.data=="string"?e.data:null;t&&Ye.delete(`${this.dbName}|${this.fetchKey}|${t}`)}this.builtins=await this.loadBuiltins(),await this.rebuildSkills(),this.emitChange(this.skillsDir,"write")}async loadBuiltins(){let e=[],t=[];try{t=typeof this.sources=="function"?[].concat(await this.sources()):this.sources}catch(n){console.warn("[agent] the skills list failed:",n)}this.resolvedSources=t,this.lazySkills=t.filter(Ct);for(let n of t)if(!Ct(n))try{let s=typeof n=="object"&&!(n instanceof Uint8Array)&&!cn(n)?n:null,o=s?s.data:n,i,a,l=0;if(typeof o=="string"){let u=`${this.dbName}|${this.fetchKey}|${o}`,d=Ye.get(u);d||(d=this.fetchSource(o).then(p=>{if(!p)throw new Error("nothing fetched");return{bytes:p.bytes,at:Date.now()}}),Ye.set(u,d),d.catch(()=>Ye.delete(u))),{bytes:i,at:l}=await d,a=`app:${u}@${l}`}else i=o instanceof Uint8Array?o:new Uint8Array(await o.arrayBuffer()),a=`app:${this.dbName}|obj${$t(o)}`;if(i.byteLength>52428800)throw new Error("skills zip too large");let c=Ve(s?.name??(typeof o=="string"?o:o.name||"skills"));e.push({name:c,bytes:i,key:a,at:l})}catch(s){console.warn("[agent] skills source failed:",s)}return e}async rebuildSkills(){let e=new Map;for(let t of this.builtins)try{let n=Je(t.name,t.bytes,t.key);for(let[s,o]of n.folders)e.has(s)||e.set(s,{fs:ae(n,o,t.at,this.inflate),builtin:!0})}catch(n){console.warn(`[agent] skills zip "${t.name}":`,n)}for(let t of this.lazySkills){let n=/^[A-Za-z0-9][\w.-]*$/.test(t.name)?t.name:Ve(t.name);e.has(n)||e.set(n,{fs:this.lazyFS(t,n),builtin:!0,lazy:t})}if(this.root)for(let t of await this.root.list(this.skillsDir).catch(()=>[])){let n=new RegExp("^"+gr(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(x(t.path));n&&e.set(n[1],{fs:Te(this.root,`${this.skillsDir}/${n[1]}`),builtin:!1,from:`${this.skillsDir}/${n[1]}`})}if(this.userSkillsDir){let t=await Ce(this.lib,"/");for(let s of t){let o=/^\/([^/]+)\.zip$/i.exec(s.path);if(o)try{let i=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,a=s.mtime!==void 0?nn(i):void 0;if(!a){let l=await this.lib.get(s.path);if(!l||!(l.data instanceof Uint8Array))continue;a=Je(Ve(o[1]),l.data,i)}for(let[l,c]of a.folders)e.set(l,{fs:ae(a,c,s.mtime??0,this.inflate),builtin:!1,from:this.userSkillsDir+s.path})}catch(i){console.warn(`[agent] skills zip "${s.path}":`,i)}}let n=this.userFS();for(let s of t){let o=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);o&&e.set(o[1],{fs:Te(n,`/${o[1]}`),builtin:!1,from:`${this.userSkillsDir}/${o[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,t){let n=null,s=async()=>{if(n)return n;let i=Pe.get(e);i||(i=(async()=>{let u=await e.load();if(typeof u=="string"){let d=await this.fetchSource(u);if(!d)throw new Error("nothing fetched");return d.bytes}return u instanceof Uint8Array?u:u instanceof ArrayBuffer?new Uint8Array(u):new Uint8Array(await u.arrayBuffer())})(),Pe.set(e,i),i.catch(()=>{Pe.get(e)===i&&Pe.delete(e)}));let a;try{a=await i}catch(u){throw new Error(`the skill "${e.name}" could not be loaded: ${u.message}`)}if(a.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let l=Je(t,a,`lazy:${$t(e)}:${a.byteLength}`),c=l.folders.get(t)??[...l.folders.values()][0];if(c===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return n=ae(l,c,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${t}`,"write"),n},o=i=>i==="/"||i==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async i=>n?n.list(i):o(i),stat:async i=>{if(!n&&i==="/SKILL.md")return{path:i,size:0};let a=await s();return a.stat?a.stat(i):null},read:async i=>(await s()).read(i)}}skillsFS(){let e=t=>{let n=/^\/([^/]+)(\/.*)?$/.exec(t);return n?{name:n[1],rest:n[2]||"/"}:null};return{description:"skills (generated, read-only)",list:async t=>{let n=[],s=e(t);for(let[o,i]of this.skillViews)if(!(s&&s.name!==o))for(let a of await i.fs.list(s?s.rest:"/"))n.push({...a,path:`/${o}${x(a.path)}`});return n},stat:async t=>{let n=e(t),s=n&&this.skillViews.get(n.name);if(!s||!n)return null;let o=s.fs.stat?await s.fs.stat(n.rest):(await s.fs.list(n.rest)).find(i=>x(i.path)===n.rest)??null;return o?{...o,path:t}:null},read:async t=>{let n=e(t),s=n&&this.skillViews.get(n.name);if(!s||!n)throw new Error(`No such file: ${t}`);return s.fs.read(n.rest)}}}userFS(){return{description:"the user's skills, shared by every conversation",list:async e=>Ce(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>an(this.lib,e),read:async e=>{let t=await this.lib.get(e);if(!t)throw new Error(`No such file: ${e}`);return t.data},write:async(e,t,n)=>{await this.lib.put({path:e,data:t,contentType:n??Q(e,t),mtime:Date.now(),layer:"work"}),await this.userSkillsChanged(e,"write")},delete:async e=>{await this.lib.delete(e),await this.userSkillsChanged(e,"delete")}}}async userSkillsChanged(e,t){await this.rebuildSkills(),this.openChannel();try{this.channel?.postMessage({userSkills:!0,path:e,kind:t})}catch{}this.emitChange(this.skillsDir,"write")}async migrateSkills(){if(!await this.lib.getMeta("migrated:2")){for(let t of await this.lib.listMeta("zip:"))t.source==="upload"&&!await this.lib.get(`/${t.name}.zip`)&&await this.lib.put({path:`/${t.name}.zip`,data:t.bytes,contentType:"application/zip",mtime:t.at||Date.now(),layer:"work"});for(let t of["zip:","removed:"])for(let n of await this.lib.listMetaKeys(t))await this.lib.deleteMeta(n);await this.lib.putMeta("migrated:2",!0)}if(this.root||await this.store.getMeta("skills-migrated:2"))return;let e=await this.store.list(this.skillsDir+"/");if(e.length){let t=new Set;for(let n of await this.store.listMetaKeys("skills:")){let s=await this.store.getMeta(n);if(!n.startsWith("skills:upload:"))for(let o of s?.files??[])t.add(o);await this.store.deleteMeta(n)}for(let n of e){let s=n.path.slice(this.skillsDir.length);!t.has(n.path)&&this.userSkillsDir&&!await this.lib.get(s)&&await this.lib.put({...n,path:s,layer:"work"}),await this.store.delete(n.path)}}await this.store.putMeta("skills-migrated:2",!0)}async fetchSource(e,t){if(e.startsWith("files:")){if(!this.provider?.readFile)throw new Error("a files: skills source needs a provider that reads files (RunApps)");let i=await this.provider.readFile(e.slice(6),{etag:t?.etag});if(!i)return null;if(i.bytes.byteLength>52428800)throw new Error("skills zip too large");return i}let n={};t?.etag?n["If-None-Match"]=t.etag:t?.lastModified&&(n["If-Modified-Since"]=t.lastModified);let s=await this.fetchFn(e,{headers:n,cache:"no-cache"});if(s.status===304)return null;if(!s.ok)throw new Error(`HTTP ${s.status}`);let o=await s.arrayBuffer();if(o.byteLength>52428800)throw new Error("skills zip too large");return{bytes:new Uint8Array(o),etag:s.headers.get("ETag")??void 0,lastModified:s.headers.get("Last-Modified")??void 0}}async destroy(){await this.ready(),await this.store.clear(),this.emitChange("/","delete"),this.close(),this.skillCache=null}};function x(r){let e=[];for(let t of String(r??"").replace(/\\/g,"/").split("/"))if(!(!t||t===".")){if(t===".."){e.pop();continue}e.push(t)}return"/"+e.join("/")}function dn(r){return{path:r.path,size:Qe(r.data),contentType:r.contentType,mtime:r.mtime}}function Qe(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var mr=new Set(["md","txt","json","js","mjs","cjs","ts","tsx","jsx","css","html","htm","xml","svg","yaml","yml","toml","csv","tsv","py","sh","sql","ini","cfg","conf","log","drawio","env","gitignore"]),ln={md:"text/markdown",txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/typescript",css:"text/css",html:"text/html",xml:"application/xml",svg:"image/svg+xml",yaml:"application/yaml",yml:"application/yaml",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf",zip:"application/zip",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",py:"text/x-python",sh:"text/x-shellscript"};function Q(r,e){let t=r.split(".").pop()?.toLowerCase()??"";return ln[t]?ln[t]:typeof e=="string"||mr.has(t)?"text/plain":"application/octet-stream"}function X(r){let e=r.subarray(0,8192);for(let t=0;t<e.length;t++)if(e[t]===0)return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return null}}var cn=r=>typeof Blob<"u"&&r instanceof Blob,gr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Ve(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var yr=4;function wr(r,e,t){return new Promise((n,s)=>{let o=r.open(e,yr);o.onupgradeneeded=i=>{let a=o.result,l=o.transaction,c=i.oldVersion,u=()=>a.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(c<3){for(let d of["files","meta","sessions"])a.objectStoreNames.contains(d)&&a.deleteObjectStore(d);a.createObjectStore("files",{keyPath:["space","path"]}),a.createObjectStore("meta",{keyPath:["space","key"]}),u();return}if(c<4){let d=l.objectStore("sessions").getAll();d.onsuccess=()=>{let p=d.result;a.deleteObjectStore("sessions"),u();let h=l.objectStore("sessions");for(let f of p)f.id&&h.put({...f,space:f.space??"default"})}}},o.onerror=()=>s(o.error??new Error("indexedDB open failed")),o.onblocked=()=>console.warn(`agent: ${e} is waiting for another tab to release the database`),o.onsuccess=()=>{let i=o.result;i.onversionchange=()=>i.close();let a=(c,u,d)=>new Promise((p,h)=>{let f=i.transaction(c,u),m=d(f.objectStore(c)),b;m.onsuccess=()=>{b=m.result,u==="readonly"&&p(b)},m.onerror=()=>h(m.error??new Error("indexedDB request failed")),f.oncomplete=()=>p(b),f.onabort=()=>h(f.error??new Error("indexedDB transaction aborted"))}),l=(c,u)=>IDBKeyRange.bound([c,u],[c,u+"\uFFFF"],!1,!1);n({get:c=>a("files","readonly",u=>u.get([t,c])),put:async c=>{await a("files","readwrite",u=>u.put({...c,space:t}))},delete:async c=>{await a("files","readwrite",u=>u.delete([t,c]))},list:c=>a("files","readonly",u=>u.getAll(l(t,c))),getMeta:async c=>(await a("meta","readonly",u=>u.get([t,c])))?.value,putMeta:async(c,u)=>{await a("meta","readwrite",d=>d.put({space:t,key:c,value:u}))},deleteMeta:async c=>{await a("meta","readwrite",u=>u.delete([t,c]))},listMeta:async c=>(await a("meta","readonly",u=>u.getAll(l(t,c)))).map(u=>u.value),listMetaKeys:async c=>(await a("meta","readonly",u=>u.getAll(l(t,c)))).map(u=>u.key),getSession:(c,u)=>a("sessions","readonly",d=>d.get([c,u])),putSession:async c=>{await a("sessions","readwrite",u=>u.put(c))},deleteSession:async(c,u)=>{await a("sessions","readwrite",d=>d.delete([c,u]))},listSessions:()=>a("sessions","readonly",c=>c.getAll()),clear:async(c=t)=>{await a("files","readwrite",u=>u.delete(l(c,"/"))),await a("meta","readwrite",u=>u.delete(l(c,""))),await a("sessions","readwrite",u=>u.delete(l(c,"")))},close:()=>i.close()})}})}var un=new Map;function br(r,e){let t=un.get(r);t||(t={files:new Map,meta:new Map,sessions:new Map},un.set(r,t));let n=t,s=()=>{let i=n.files.get(e);return i||(i=new Map,n.files.set(e,i)),i},o=()=>{let i=n.meta.get(e);return i||(i=new Map,n.meta.set(e,i)),i};return{get:async i=>s().get(i),put:async i=>{s().set(i.path,{...i,space:e})},delete:async i=>{s().delete(i)},list:async i=>[...s().values()].filter(a=>i==="/"||a.path.startsWith(i)),getMeta:async i=>o().get(i),putMeta:async(i,a)=>{o().set(i,a)},deleteMeta:async i=>{o().delete(i)},listMeta:async i=>[...o()].filter(([a])=>a.startsWith(i)).map(([,a])=>a),listMetaKeys:async i=>[...o().keys()].filter(a=>a.startsWith(i)),getSession:async(i,a)=>n.sessions.get(`${i}\0${a}`),putSession:async i=>{n.sessions.set(`${i.space??e}\0${i.id}`,i)},deleteSession:async(i,a)=>{n.sessions.delete(`${i}\0${a}`)},listSessions:async()=>[...n.sessions.values()],clear:async(i=e)=>{n.files.delete(i),n.meta.delete(i);for(let[a,l]of n.sessions)l.space===i&&n.sessions.delete(a)},close:()=>{}}}var ue="Untitled";function $e(r){for(let e of r.messages){if(e.role!=="user"||K(e)!==null)continue;let t=e.typed,s=(typeof t=="string"?t:typeof e.content=="string"?e.content:(e.content??[]).find(o=>o.type==="text")?.text??"").replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim();if(!(!s||et(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return ue}function et(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function kr(r,e){let t=typeof navigator<"u"?navigator.locks:void 0;return t&&typeof t.request=="function"?t.request(r,e):e()}function hn(r={},e={}){let t=new Map;for(let[s,o]of Object.entries(r))t.set(x(s),o);let n={files:t,description:e.description,async list(s){let o=x(s);return[...t.entries()].filter(([i])=>o==="/"||i===o||i.startsWith(o+"/")).map(([i,a])=>({path:i,size:Qe(a)}))},async read(s){let o=t.get(x(s));if(o===void 0)throw new Error(`No such file: ${x(s)}`);return o}};return e.readonly||(n.write=async(s,o)=>{t.set(x(s),o)},n.delete=async s=>{if(!t.delete(x(s)))throw new Error(`No such file: ${x(s)}`)}),n}var xr=4*1024*1024;function vr(r){let e=typeof r=="string"?r:X(r),t=2166136261;if(e!==null)for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);else for(let n of r)t^=n,t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Sr(r,e,t){if(t<e)return!1;let n=r.some(([o,i])=>o<=e&&i>=t);r.push([e,t]),r.sort((o,i)=>o[0]-i[0]);let s=[];for(let o of r){let i=s[s.length-1];i&&o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):s.push([o[0],o[1]])}return r.splice(0,r.length,...s),!n}var ee=class extends Error{constructor(t,n,s){super(t);y(this,"path",n);y(this,"coveredTo",s);this.name="PartialReadError"}};function de(r,e={}){let t=e.enabled!==!1,n=new Map,s=async(o,i)=>{let a=await r.stat(o);if(!a)return null;let l=a.size>xr?"":vr(i??(await r.read(o)).data);return`${a.mtime??""}:${a.size}:${l}`};return{enabled:t,async saw(o,i={}){if(!t)return;let a=await s(o,i.text).catch(()=>null);if(!a)return n.delete(o),!0;let l=i.start??1,c=i.end??1/0,u=i.total??1/0,d=n.get(o),p=!!d&&d.version===a,h=p&&l<=d.coveredTo+1?Math.max(d.coveredTo,c):l<=1?c:0,f=p?d.ranges:[],m=Sr(f,l,c)||!p;return n.set(o,{version:a,coveredTo:h,total:u,ranges:f}),m},async wrote(o){if(!t)return;let i=await s(o).catch(()=>null);i?n.set(o,{version:i,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):n.delete(o)},async copied(o,i){if(!t)return;let a=n.get(o),l=a?await s(i).catch(()=>null):null;a&&l?n.set(i,{...a,version:l,ranges:a.ranges.map(([c,u])=>[c,u])}):n.delete(i)},async edited(o){if(!t)return;let i=n.get(o),a=await s(o).catch(()=>null);a&&i?n.set(o,{...i,version:a,total:1/0,ranges:[]}):n.delete(o)},async check(o,i){if(!t)return;let a=await s(o);if(a===null)return;let l=n.get(o);if(!l){if(i==="delete")return;throw new Error(`${o} already exists and you have not read it in this conversation: read it with read_file first, then ${i} it.`)}if(l.version!==a)throw new Error(`${o} has changed since you last read it (the user or another process edited it): read it again with read_file, then ${i==="delete"?"decide whether to delete it":"make your change on the current content"}.`);if(i==="overwrite"&&l.coveredTo<l.total)throw new ee(`You have read only lines 1-${l.coveredTo} of ${o}: read the rest (read_file with offset=${l.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,o,l.coveredTo)},async known(o){let i=n.get(o);return!i||await s(o).catch(()=>null)!==i.version?"none":i.coveredTo>=i.total?"all":i.coveredTo>0?"part":"none"},forget(o){n.delete(o)},retain(o){let i=new Set(o);for(let a of[...n.keys()])i.has(a)||n.delete(a)},clear(){n.clear()}}}var Et=500,tt=2e3,nt=50*1024,rt=100,pn=5*1024*1024,Tr={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},Ar={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function Pr(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e)}function st(r,e={}){let t=e.guard??de(r,{enabled:e.readBeforeWrite!==!1}),n=t.enabled;return[D({name:"list_files",description:`List the files under a folder of the workspace (recursive), one per line with the size in bytes. Output is truncated to 500 entries. Start at / to see everything; ${r.skillsDir} holds the skills.`,readOnly:!0,parameters:{type:"object",properties:{path:{type:"string",description:"Folder to list. Default /"}},additionalProperties:!1},async execute({path:s},o){let i=await r.list(s||"/");if(!i.length)return`No files under ${x(s||"/")}.`;let a=o?.parentId?1/0:Et,l=i.slice(0,a).map(c=>`${c.path} (${c.size} B)`);return i.length>a&&l.push(`
155
+ [${Et} entries limit reached (${i.length} in all). List a sub-folder.]`),l.join(`
156
+ `)}}),D({name:"read_file",description:"Read the contents of a text file in the workspace; a PDF is read as the text of its pages, each under a `--- page N ---` line; a picture (PNG, JPEG, GIF, WebP) is shown to you when the model can see pictures. Output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files; when you need the full file, continue with offset until complete. Reading a folder lists it.",readOnly:!0,parameters:{type:"object",properties:{path:{type:"string",description:"Absolute path in the workspace"},offset:{type:"integer",minimum:1,description:"Line number to start reading from (1-indexed)"},limit:{type:"integer",minimum:1,description:"Maximum number of lines to read"}},required:["path"],additionalProperties:!1},async execute({path:s,offset:o,limit:i},a){if(await r.isFolder(s)){let T=await r.list(s);return`${x(s)} is a folder with ${T.length} file${T.length===1?"":"s"}:
157
+ `+T.slice(0,Et).map(C=>`${C.path} (${C.size} B)`).join(`
158
+ `)}let l=await r.stat(s),c=l&&Tr[(l.contentType??"").split(";")[0].trim()]?l.contentType.split(";")[0].trim():Ar[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(l&&c&&await a.agent?.accepts("image")===!0){if(l.size>pn)return`${x(s)} is a picture of ${l.size} bytes, more than the ${pn/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:T}=await r.read(s),C=typeof T=="string"?new TextEncoder().encode(T):T;return await t.saw(x(s)),[{type:"text",text:`${x(s)} (${c}, ${C.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${c};base64,${Pr(C)}`}}]}let u;try{u=await r.readAsText(s)}catch(T){if(await r.stat(s)&&/\.pdf$/i.test(s))return`Could not read the PDF ${x(s)}: ${T.message}`;throw T}if(!u){await t.saw(x(s));let T=await r.stat(s),C=c&&await a.agent?.accepts("image")===!1?" The model in use cannot view pictures.":"";return`${x(s)} is a binary file (${T?.contentType??"unknown type"}, ${T?.size??0} bytes).${C}`}let d=u.text,p=d.split(`
159
+ `),h=p.length,f=Math.max(1,o??1);if(f>h)return await t.saw(x(s),{start:h+1,end:h,total:h}),`Offset ${f} is beyond end of file (${h} lines total)`;let m=!!a?.parentId,b=m?i??1/0:i!==void 0?Math.min(i,tt):tt,v=[],g=0,w=f-1;for(let T=f-1;T<h&&v.length<b;T++){let C=new TextEncoder().encode(p[T]).byteLength+1;if(!m&&g+C>nt&&v.length>0)break;v.push(p[T]),g+=C,w=T+1}let M=await t.saw(x(s),{start:f,end:w,total:h,text:u.kind==="text"?d:void 0});M!==void 0&&a.progress?.(M);let k="";if(w<h){let T=w+1;g>=nt||i===void 0&&v.length>=tt?k=`
160
160
 
161
- [Showing lines ${p}-${w} of ${h}${g>=nt?" (50.0KB limit)":""}. Use offset=${T} to continue.]`:k=`
161
+ [Showing lines ${f}-${w} of ${h}${g>=nt?" (50.0KB limit)":""}. Use offset=${T} to continue.]`:k=`
162
162
 
163
- [${h-w} more lines in file. Use offset=${T} to continue.]`}return S.join(`
164
- `)+k}}),L({name:"write_file",description:"Create or overwrite a text file in the workspace with the given content. Folders are implied by the path. Prefer edit_file for small changes to an existing file."+(n?" To overwrite an existing file, read it with read_file first; if it changed since you read it, read it again. Only when the user asked for the file to be rewritten from scratch, keeping nothing of it, pass replace: true to overwrite it without reading it.":""),parameters:{type:"object",properties:{path:{type:"string"},content:{type:"string"},...n?{replace:{type:"boolean",description:"Overwrite an existing file without reading it first. Only when the user asked to rewrite it from scratch and keep nothing of it; never to skip reading a file whose content you are changing."}}:{}},required:["path","content"],additionalProperties:!1},async execute({path:s,content:o,replace:i},a){let l=x(s),c=await r.exists(l),u="";if(c&&i===!0&&n){let d=await t.known(l);if(d!=="all"){let f=await r.readAsText(l).catch(()=>null),h=f?.kind==="text"?f.text.split(`
165
- `).length:0,p=h?` (${h} line${h===1?"":"s"})`:"";u=d==="part"?` Its previous content${p} was replaced, including the part you had not read.`:` Its previous content${p} was replaced without being read.`}}else if(c)try{await t.check(l,"overwrite")}catch(d){if(!(d instanceof Q))throw d;let f=await r.readAsText(l).catch(()=>null);if(f?.kind!=="text")throw d;let h=f.text.split(`
166
- `),p=h.length,m=d.coveredTo+1,b=[],S=0,g=d.coveredTo;for(let k=m-1;k<p&&b.length<tt;k++){let T=new TextEncoder().encode(h[k]).byteLength+1;if(S+T>nt&&b.length>0)break;b.push(h[k]),S+=T,g=k+1}let w=await t.saw(l,{start:m,end:g,total:p,text:f.text});w!==void 0&&a.progress?.(w);let _=g<p?` Lines ${g+1}-${p} are still unread: read them with read_file offset=${g+1} before overwriting.`:"";throw new Error(`${l} was not overwritten: you had read only lines 1-${d.coveredTo} of its ${p}. Here are lines ${m}-${g}, which now count as read.${_} Make sure your new content keeps what it should, then call write_file again, or change the file with edit_file.
163
+ [${h-w} more lines in file. Use offset=${T} to continue.]`}return v.join(`
164
+ `)+k}}),D({name:"write_file",description:"Create or overwrite a text file in the workspace with the given content. Folders are implied by the path. Prefer edit_file for small changes to an existing file."+(n?" To overwrite an existing file, read it with read_file first; if it changed since you read it, read it again. Only when the user asked for the file to be rewritten from scratch, keeping nothing of it, pass replace: true to overwrite it without reading it.":""),parameters:{type:"object",properties:{path:{type:"string"},content:{type:"string"},...n?{replace:{type:"boolean",description:"Overwrite an existing file without reading it first. Only when the user asked to rewrite it from scratch and keep nothing of it; never to skip reading a file whose content you are changing."}}:{}},required:["path","content"],additionalProperties:!1},async execute({path:s,content:o,replace:i},a){let l=x(s),c=await r.exists(l),u="";if(c&&i===!0&&n){let d=await t.known(l);if(d!=="all"){let p=await r.readAsText(l).catch(()=>null),h=p?.kind==="text"?p.text.split(`
165
+ `).length:0,f=h?` (${h} line${h===1?"":"s"})`:"";u=d==="part"?` Its previous content${f} was replaced, including the part you had not read.`:` Its previous content${f} was replaced without being read.`}}else if(c)try{await t.check(l,"overwrite")}catch(d){if(!(d instanceof ee))throw d;let p=await r.readAsText(l).catch(()=>null);if(p?.kind!=="text")throw d;let h=p.text.split(`
166
+ `),f=h.length,m=d.coveredTo+1,b=[],v=0,g=d.coveredTo;for(let k=m-1;k<f&&b.length<tt;k++){let T=new TextEncoder().encode(h[k]).byteLength+1;if(v+T>nt&&b.length>0)break;b.push(h[k]),v+=T,g=k+1}let w=await t.saw(l,{start:m,end:g,total:f,text:p.text});w!==void 0&&a.progress?.(w);let M=g<f?` Lines ${g+1}-${f} are still unread: read them with read_file offset=${g+1} before overwriting.`:"";throw new Error(`${l} was not overwritten: you had read only lines 1-${d.coveredTo} of its ${f}. Here are lines ${m}-${g}, which now count as read.${M} Make sure your new content keeps what it should, then call write_file again, or change the file with edit_file.
167
167
 
168
168
  ${b.join(`
169
- `)}`)}return await r.write(l,o),await t.wrote(l),`${c?u?"Replaced":"Updated":"Created"} ${l} (${new TextEncoder().encode(o).byteLength} bytes).${u}`}}),L({name:"edit_file",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes."+(n?" Read the file with read_file before editing it; if it changed since you read it (the user may edit files while you work), read it again.":""),parameters:{type:"object",properties:{path:{type:"string",description:"Absolute path in the workspace"},edits:{type:"array",minItems:1,description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits.",items:{type:"object",properties:{oldText:{type:"string",description:"Exact text for one targeted replacement. It must be unique in the original file."},newText:{type:"string",description:"Replacement text for this targeted edit."}},required:["oldText","newText"],additionalProperties:!1}},oldText:{type:"string",description:"Shorthand for a single edit"},newText:{type:"string"}},required:["path"],additionalProperties:!1},guidelines:["Use edit_file for precise changes (oldText must match exactly); when changing several places in one file, use one edit_file call with several entries in edits[].","Keep oldText as small as possible while still being unique in the file."],async execute(s){let o=x(s.path),i=Array.isArray(s.edits)?[...s.edits]:[];return s.oldText!==void 0&&i.push({oldText:s.oldText,newText:s.newText??""}),await t.check(o,"edit"),await r.edit(o,i),await t.edited(o),`Successfully replaced ${i.length} block(s) in ${o}.`}}),L({name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1},destructive:!0,confirm:({path:s})=>`Delete ${x(s)}?`,async execute({path:s}){let o=x(s);return await t.check(o,"delete"),await r.delete(o),t.forget(o),`Deleted ${o}.`}}),...["move_file","copy_file"].map(s=>L({name:s,description:s==="move_file"?"Move or rename a file. The destination must not exist yet. References to the old path in other files are not changed: update them with edit_file.":"Copy a file to a new path. The destination must not exist yet.",parameters:{type:"object",properties:{from:{type:"string",description:"Existing file"},to:{type:"string",description:"New path"}},required:["from","to"],additionalProperties:!1},async execute({from:o,to:i}){let a=x(o),l=x(i);if(a===l)throw new Error("The source and the destination are the same path.");if(!await r.exists(a)||await r.isFolder(a))throw new Error(`No such file: ${a}`);if(await r.exists(l))throw new Error(`${l} already exists. Choose another path, or delete it first.`);if(s==="move_file"&&r.isReadOnly(a))throw new Error(`${a} is read-only.`);s==="move_file"&&await t.check(a,"delete");let{data:c,contentType:u}=await r.read(a);return await r.write(l,c,u),await t.copied(a,l),s==="move_file"&&(await r.delete(a),t.forget(a)),`${s==="move_file"?"Moved":"Copied"} ${a} to ${l}.`}})),L({name:"search_files",description:"Search the text files of the workspace for a pattern (a literal string, or a regular expression with regex: true). Returns matching lines as path:line: text, at most 100; long lines are cut to 200 chars.",readOnly:!0,parameters:{type:"object",properties:{query:{type:"string",minLength:1},path:{type:"string",description:"Folder to search. Default /"},regex:{type:"boolean"}},required:["query"],additionalProperties:!1},async execute({query:s,path:o,regex:i},a){let l;try{l=i?new RegExp(s,"i"):new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i")}catch(d){throw new Error(`Invalid regular expression: ${d.message}`)}let c=[],u=0;for(let d of await r.list(o||"/")){if(a.signal.throwIfAborted(),d.size>2e6)continue;let f;try{f=await r.readText(d.path)}catch{continue}u++;let h=f.split(`
170
- `);for(let p=0;p<h.length&&c.length<rt;p++)l.test(h[p])&&c.push(`${d.path}:${p+1}: ${h[p].trim().slice(0,200)}`);if(c.length>=rt)break}return c.length?c.join(`
169
+ `)}`)}return await r.write(l,o),await t.wrote(l),`${c?u?"Replaced":"Updated":"Created"} ${l} (${new TextEncoder().encode(o).byteLength} bytes).${u}`}}),D({name:"edit_file",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes."+(n?" Read the file with read_file before editing it; if it changed since you read it (the user may edit files while you work), read it again.":""),parameters:{type:"object",properties:{path:{type:"string",description:"Absolute path in the workspace"},edits:{type:"array",minItems:1,description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits.",items:{type:"object",properties:{oldText:{type:"string",description:"Exact text for one targeted replacement. It must be unique in the original file."},newText:{type:"string",description:"Replacement text for this targeted edit."}},required:["oldText","newText"],additionalProperties:!1}},oldText:{type:"string",description:"Shorthand for a single edit"},newText:{type:"string"}},required:["path"],additionalProperties:!1},guidelines:["Use edit_file for precise changes (oldText must match exactly); when changing several places in one file, use one edit_file call with several entries in edits[].","Keep oldText as small as possible while still being unique in the file."],async execute(s){let o=x(s.path),i=Array.isArray(s.edits)?[...s.edits]:[];return s.oldText!==void 0&&i.push({oldText:s.oldText,newText:s.newText??""}),await t.check(o,"edit"),await r.edit(o,i),await t.edited(o),`Successfully replaced ${i.length} block(s) in ${o}.`}}),D({name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1},destructive:!0,confirm:({path:s})=>`Delete ${x(s)}?`,async execute({path:s}){let o=x(s);return await t.check(o,"delete"),await r.delete(o),t.forget(o),`Deleted ${o}.`}}),...["move_file","copy_file"].map(s=>D({name:s,description:s==="move_file"?"Move or rename a file. The destination must not exist yet. References to the old path in other files are not changed: update them with edit_file.":"Copy a file to a new path. The destination must not exist yet.",parameters:{type:"object",properties:{from:{type:"string",description:"Existing file"},to:{type:"string",description:"New path"}},required:["from","to"],additionalProperties:!1},async execute({from:o,to:i}){let a=x(o),l=x(i);if(a===l)throw new Error("The source and the destination are the same path.");if(!await r.exists(a)||await r.isFolder(a))throw new Error(`No such file: ${a}`);if(await r.exists(l))throw new Error(`${l} already exists. Choose another path, or delete it first.`);if(s==="move_file"&&r.isReadOnly(a))throw new Error(`${a} is read-only.`);s==="move_file"&&await t.check(a,"delete");let{data:c,contentType:u}=await r.read(a);return await r.write(l,c,u),await t.copied(a,l),s==="move_file"&&(await r.delete(a),t.forget(a)),`${s==="move_file"?"Moved":"Copied"} ${a} to ${l}.`}})),D({name:"search_files",description:"Search the text files of the workspace for a pattern (a literal string, or a regular expression with regex: true). Returns matching lines as path:line: text, at most 100; long lines are cut to 200 chars.",readOnly:!0,parameters:{type:"object",properties:{query:{type:"string",minLength:1},path:{type:"string",description:"Folder to search. Default /"},regex:{type:"boolean"}},required:["query"],additionalProperties:!1},async execute({query:s,path:o,regex:i},a){let l;try{l=i?new RegExp(s,"i"):new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i")}catch(d){throw new Error(`Invalid regular expression: ${d.message}`)}let c=[],u=0;for(let d of await r.list(o||"/")){if(a.signal.throwIfAborted(),d.size>2e6)continue;let p;try{p=await r.readText(d.path)}catch{continue}u++;let h=p.split(`
170
+ `);for(let f=0;f<h.length&&c.length<rt;f++)l.test(h[f])&&c.push(`${d.path}:${f+1}: ${h[f].trim().slice(0,200)}`);if(c.length>=rt)break}return c.length?c.join(`
171
171
  `)+(c.length>=rt?`
172
172
 
173
- [${rt} matches limit reached. Refine the pattern or search a sub-folder.]`:""):`No matches found (${u} text files searched).`}})]}function it(r,e){if(!r)return[];let t=[];return de(r,e,"",t,0),t}function pn(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r}function Cr(r,e){let t=pn(e);return r==="number"?t==="number"||t==="integer":r==="integer"?t==="integer":r===t}function de(r,e,t,n,s){if(s>32)return;let o=t||"arguments";for(let i of["anyOf","oneOf"]){let a=r[i];if(Array.isArray(a)&&a.length){let l=a.filter(c=>{let u=[];return de(c,e,t,u,s+1),u.length===0}).length;if(l===0){n.push(`${o}: does not match any allowed form`);return}if(i==="oneOf"&&l>1){n.push(`${o}: matches more than one of the allowed forms`);return}}}if(Array.isArray(r.allOf))for(let i of r.allOf)de(i,e,t,n,s+1);if(r.type!==void 0){let i=Array.isArray(r.type)?r.type:[r.type];if(!i.some(a=>Cr(a,e))){n.push(`${o}: expected ${i.join(" or ")}, got ${pn(e)}`);return}}if(Array.isArray(r.enum)&&!r.enum.some(i=>Mt(i,e))){n.push(`${o}: must be one of ${r.enum.map(i=>JSON.stringify(i)).join(", ")}`);return}if("const"in r&&!Mt(r.const,e)){n.push(`${o}: must be ${JSON.stringify(r.const)}`);return}if(typeof e=="string"){if(typeof r.minLength=="number"&&e.length<r.minLength&&n.push(`${o}: shorter than ${r.minLength} characters`),typeof r.maxLength=="number"&&e.length>r.maxLength&&n.push(`${o}: longer than ${r.maxLength} characters`),typeof r.pattern=="string")try{new RegExp(r.pattern,"u").test(e)||n.push(`${o}: does not match pattern ${r.pattern}`)}catch{}}else if(typeof e=="number")typeof r.minimum=="number"&&e<r.minimum&&n.push(`${o}: below minimum ${r.minimum}`),typeof r.maximum=="number"&&e>r.maximum&&n.push(`${o}: above maximum ${r.maximum}`),typeof r.exclusiveMinimum=="number"&&e<=r.exclusiveMinimum&&n.push(`${o}: must be greater than ${r.exclusiveMinimum}`),typeof r.exclusiveMaximum=="number"&&e>=r.exclusiveMaximum&&n.push(`${o}: must be less than ${r.exclusiveMaximum}`);else if(Array.isArray(e))typeof r.minItems=="number"&&e.length<r.minItems&&n.push(`${o}: needs at least ${r.minItems} items`),typeof r.maxItems=="number"&&e.length>r.maxItems&&n.push(`${o}: at most ${r.maxItems} items`),r.items&&typeof r.items=="object"&&!Array.isArray(r.items)&&e.forEach((i,a)=>de(r.items,i,`${t}[${a}]`,n,s+1));else if(e&&typeof e=="object"){let i=e,a=r.properties&&typeof r.properties=="object"?r.properties:{};if(Array.isArray(r.required))for(let l of r.required)(!(l in i)||i[l]===void 0)&&n.push(`${o}: missing required "${l}"`);for(let[l,c]of Object.entries(i)){let u=a[l];if(u)de(u,c,t?`${t}.${l}`:l,n,s+1);else if(r.additionalProperties===!1){let d=Object.keys(a);n.push(`${o}: unknown field "${l}"${d.length?` (allowed: ${d.join(", ")})`:""}`)}else r.additionalProperties&&typeof r.additionalProperties=="object"&&de(r.additionalProperties,c,t?`${t}.${l}`:l,n,s+1)}}}function Mt(r,e){if(r===e)return!0;if(typeof r!=typeof e||r===null||e===null||typeof r!="object"||Array.isArray(r)!==Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>Mt(r[s],e[s]))}var mn=`
173
+ [${rt} matches limit reached. Refine the pattern or search a sub-folder.]`:""):`No matches found (${u} text files searched).`}})]}function it(r,e){if(!r)return[];let t=[];return he(r,e,"",t,0),t}function fn(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r}function Cr(r,e){let t=fn(e);return r==="number"?t==="number"||t==="integer":r==="integer"?t==="integer":r===t}function he(r,e,t,n,s){if(s>32)return;let o=t||"arguments";for(let i of["anyOf","oneOf"]){let a=r[i];if(Array.isArray(a)&&a.length){let l=a.filter(c=>{let u=[];return he(c,e,t,u,s+1),u.length===0}).length;if(l===0){n.push(`${o}: does not match any allowed form`);return}if(i==="oneOf"&&l>1){n.push(`${o}: matches more than one of the allowed forms`);return}}}if(Array.isArray(r.allOf))for(let i of r.allOf)he(i,e,t,n,s+1);if(r.type!==void 0){let i=Array.isArray(r.type)?r.type:[r.type];if(!i.some(a=>Cr(a,e))){n.push(`${o}: expected ${i.join(" or ")}, got ${fn(e)}`);return}}if(Array.isArray(r.enum)&&!r.enum.some(i=>Rt(i,e))){n.push(`${o}: must be one of ${r.enum.map(i=>JSON.stringify(i)).join(", ")}`);return}if("const"in r&&!Rt(r.const,e)){n.push(`${o}: must be ${JSON.stringify(r.const)}`);return}if(typeof e=="string"){if(typeof r.minLength=="number"&&e.length<r.minLength&&n.push(`${o}: shorter than ${r.minLength} characters`),typeof r.maxLength=="number"&&e.length>r.maxLength&&n.push(`${o}: longer than ${r.maxLength} characters`),typeof r.pattern=="string")try{new RegExp(r.pattern,"u").test(e)||n.push(`${o}: does not match pattern ${r.pattern}`)}catch{}}else if(typeof e=="number")typeof r.minimum=="number"&&e<r.minimum&&n.push(`${o}: below minimum ${r.minimum}`),typeof r.maximum=="number"&&e>r.maximum&&n.push(`${o}: above maximum ${r.maximum}`),typeof r.exclusiveMinimum=="number"&&e<=r.exclusiveMinimum&&n.push(`${o}: must be greater than ${r.exclusiveMinimum}`),typeof r.exclusiveMaximum=="number"&&e>=r.exclusiveMaximum&&n.push(`${o}: must be less than ${r.exclusiveMaximum}`);else if(Array.isArray(e))typeof r.minItems=="number"&&e.length<r.minItems&&n.push(`${o}: needs at least ${r.minItems} items`),typeof r.maxItems=="number"&&e.length>r.maxItems&&n.push(`${o}: at most ${r.maxItems} items`),r.items&&typeof r.items=="object"&&!Array.isArray(r.items)&&e.forEach((i,a)=>he(r.items,i,`${t}[${a}]`,n,s+1));else if(e&&typeof e=="object"){let i=e,a=r.properties&&typeof r.properties=="object"?r.properties:{};if(Array.isArray(r.required))for(let l of r.required)(!(l in i)||i[l]===void 0)&&n.push(`${o}: missing required "${l}"`);for(let[l,c]of Object.entries(i)){let u=a[l];if(u)he(u,c,t?`${t}.${l}`:l,n,s+1);else if(r.additionalProperties===!1){let d=Object.keys(a);n.push(`${o}: unknown field "${l}"${d.length?` (allowed: ${d.join(", ")})`:""}`)}else r.additionalProperties&&typeof r.additionalProperties=="object"&&he(r.additionalProperties,c,t?`${t}.${l}`:l,n,s+1)}}}function Rt(r,e){if(r===e)return!0;if(typeof r!=typeof e||r===null||e===null||typeof r!="object"||Array.isArray(r)!==Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>Rt(r[s],e[s]))}var mn=`
174
174
  "use strict";
175
175
  var isNode = typeof self === "undefined";
176
176
  var port, send;
@@ -254,24 +254,24 @@ function onMessage(m) {
254
254
  }
255
255
  }
256
256
  if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
257
- `;async function $r(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let n=URL.createObjectURL(new Blob([mn],{type:"text/javascript"})),s=new Worker(n);return URL.revokeObjectURL(n),{post:o=>s.postMessage(o),onMessage:o=>{s.onmessage=i=>o(i.data)},onFail:o=>{s.onerror=i=>{i.preventDefault(),o(i.message||"The sandbox worker could not run; the page's Content-Security-Policy may block it.")}},terminate:()=>s.terminate()}}let r=new Function("m","return import(m)"),{Worker:e}=await r("node:worker_threads"),t=new e(mn,{eval:!0});return{post:n=>t.postMessage(n),onMessage:n=>t.on("message",s=>n(s)),onFail:n=>{t.on("error",s=>n(s instanceof Error?s.message:String(s))),t.on("exit",()=>n("The sandbox worker exited before the code finished."))},terminate:()=>t.terminate()}}async function Et(r,e,t={}){let n=Math.min(6e4,Math.max(100,t.timeoutMs??1e4)),s=await $r(),o=Date.now(),i=t.bridge;return new Promise(a=>{let l=!1,c=new AbortController,u=k=>{l||(l=!0,clearTimeout(p),t.signal?.removeEventListener("abort",S),s.terminate(),c.abort(),a(k))},d=n,f=0,h=0,p,m=()=>{f=Date.now(),p=setTimeout(()=>u({ok:!1,logs:"",error:`Timed out after ${n} ms`,durationMs:Date.now()-o}),Math.max(0,d))},b=async k=>{h++===0&&(clearTimeout(p),d-=Date.now()-f);try{return await k()}finally{--h===0&&!l&&m()}};m();let S=()=>u({ok:!1,logs:"",error:"Aborted",durationMs:Date.now()-o});if(t.signal?.addEventListener("abort",S,{once:!0}),t.signal?.aborted)return S();s.onFail(k=>u({ok:!1,logs:"",error:k,durationMs:Date.now()-o}));let g=0,w=Promise.resolve(),_=(k,T)=>{if(!i?.names.includes(k))throw new Error(`there is no tool named "${k}"`);let C=i.max??50;if(++g>C)throw new Error(`this run has used its ${C} tool calls; return what you have and continue in another run_js`);let P=w.then(()=>{if(l)throw new Error("the code has finished");return i.call(k,T,c.signal)});return w=P.catch(()=>{}),P};s.onMessage(async k=>{k.type==="done"?u({ok:!0,result:k.result,logs:k.logs??"",durationMs:k.durationMs??Date.now()-o}):k.type==="error"?u({ok:!1,error:String(k.error),logs:k.logs??"",durationMs:k.durationMs??Date.now()-o}):k.type==="tool"&&b(async()=>{try{s.post({type:"toolResult",id:k.id,ok:!0,value:await _(String(k.name),k.args)})}catch(T){s.post({type:"toolResult",id:k.id,ok:!1,error:T.message})}})}),s.post({type:"run",code:r,input:e,network:!!t.network,maxLogChars:t.maxLogChars,tools:i?.names})})}function ot(r={}){let e=r.maxCodeChars??2e4;return L({name:"run_js",description:`Run JavaScript in a sandbox (no DOM, no network) and get back what it returns plus its console output. Use it for arithmetic, dates, parsing, data transformation and to run a skill's scripts instead of working them out by hand. The code is the body of an async function: use \`return\` for the result (JSON), \`console.log\` for notes. Available: \`input\` (the input argument), and \`tools\` \u2014 \`await tools.<name>(args)\` calls any of your other tools with the same arguments and rules, one at a time, and resolves with its full text result (it throws when the call fails or the user declines; do not work around a decline). A tool that cannot be called from code says so when called. Up to ${r.maxToolCalls??50} calls per run and ${e} characters of code; time spent waiting for a tool does not count against the time limit.`,guidelines:"A large result you only need to compute over (logs, orders, a long list): fetch it inside run_js with `tools` and return the numbers, so the data never passes through this conversation. Parse a tool's text there rather than assuming a shape: try one call and look at it first.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript, the body of an async function"},input:{description:"Any JSON value made available as `input`"},timeout_ms:{type:"integer",minimum:100,maximum:6e4}},required:["code"],additionalProperties:!1},maxResultChars:24e3,async execute({code:t,input:n,timeout_ms:s},o){if(t.length>e)throw new Error(`the code is ${t.length} characters; the limit is ${e}. Do less in one run.`);let i={names:o.agent.tools.filter(c=>c.name!=="run_js"&&!c.endsRun&&!c.vision&&!c.display?.hidden&&c.callableFromCode!==!1).map(c=>c.name),max:r.maxToolCalls,call:async(c,u,d)=>{let f=await o.callTool(c,u,{signal:d});if(f.status!=="ok")throw new Error(f.text.replace(/^Error:\s*/,""));return f.text}},a=await Et(t,n,{...r,timeoutMs:s??r.timeoutMs,signal:o.signal,bridge:i}),l=[];return a.logs&&l.push(`console:
257
+ `;async function $r(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let n=URL.createObjectURL(new Blob([mn],{type:"text/javascript"})),s=new Worker(n);return URL.revokeObjectURL(n),{post:o=>s.postMessage(o),onMessage:o=>{s.onmessage=i=>o(i.data)},onFail:o=>{s.onerror=i=>{i.preventDefault(),o(i.message||"The sandbox worker could not run; the page's Content-Security-Policy may block it.")}},terminate:()=>s.terminate()}}let r=new Function("m","return import(m)"),{Worker:e}=await r("node:worker_threads"),t=new e(mn,{eval:!0});return{post:n=>t.postMessage(n),onMessage:n=>t.on("message",s=>n(s)),onFail:n=>{t.on("error",s=>n(s instanceof Error?s.message:String(s))),t.on("exit",()=>n("The sandbox worker exited before the code finished."))},terminate:()=>t.terminate()}}async function Ot(r,e,t={}){let n=Math.min(6e4,Math.max(100,t.timeoutMs??1e4)),s=await $r(),o=Date.now(),i=t.bridge;return new Promise(a=>{let l=!1,c=new AbortController,u=k=>{l||(l=!0,clearTimeout(f),t.signal?.removeEventListener("abort",v),s.terminate(),c.abort(),a(k))},d=n,p=0,h=0,f,m=()=>{p=Date.now(),f=setTimeout(()=>u({ok:!1,logs:"",error:`Timed out after ${n} ms`,durationMs:Date.now()-o}),Math.max(0,d))},b=async k=>{h++===0&&(clearTimeout(f),d-=Date.now()-p);try{return await k()}finally{--h===0&&!l&&m()}};m();let v=()=>u({ok:!1,logs:"",error:"Aborted",durationMs:Date.now()-o});if(t.signal?.addEventListener("abort",v,{once:!0}),t.signal?.aborted)return v();s.onFail(k=>u({ok:!1,logs:"",error:k,durationMs:Date.now()-o}));let g=0,w=Promise.resolve(),M=(k,T)=>{if(!i?.names.includes(k))throw new Error(`there is no tool named "${k}"`);let C=i.max??50;if(++g>C)throw new Error(`this run has used its ${C} tool calls; return what you have and continue in another run_js`);let P=w.then(()=>{if(l)throw new Error("the code has finished");return i.call(k,T,c.signal)});return w=P.catch(()=>{}),P};s.onMessage(async k=>{k.type==="done"?u({ok:!0,result:k.result,logs:k.logs??"",durationMs:k.durationMs??Date.now()-o}):k.type==="error"?u({ok:!1,error:String(k.error),logs:k.logs??"",durationMs:k.durationMs??Date.now()-o}):k.type==="tool"&&b(async()=>{try{s.post({type:"toolResult",id:k.id,ok:!0,value:await M(String(k.name),k.args)})}catch(T){s.post({type:"toolResult",id:k.id,ok:!1,error:T.message})}})}),s.post({type:"run",code:r,input:e,network:!!t.network,maxLogChars:t.maxLogChars,tools:i?.names})})}function ot(r={}){let e=r.maxCodeChars??2e4;return D({name:"run_js",description:`Run JavaScript in a sandbox (no DOM, no network) and get back what it returns plus its console output. Use it for arithmetic, dates, parsing, data transformation and to run a skill's scripts instead of working them out by hand. The code is the body of an async function: use \`return\` for the result (JSON), \`console.log\` for notes. Available: \`input\` (the input argument), and \`tools\` \u2014 \`await tools.<name>(args)\` calls any of your other tools with the same arguments and rules, one at a time, and resolves with its full text result (it throws when the call fails or the user declines; do not work around a decline). A tool that cannot be called from code says so when called. Up to ${r.maxToolCalls??50} calls per run and ${e} characters of code; time spent waiting for a tool does not count against the time limit.`,guidelines:"A large result you only need to compute over (logs, orders, a long list): fetch it inside run_js with `tools` and return the numbers, so the data never passes through this conversation. Parse a tool's text there rather than assuming a shape: try one call and look at it first.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript, the body of an async function"},input:{description:"Any JSON value made available as `input`"},timeout_ms:{type:"integer",minimum:100,maximum:6e4}},required:["code"],additionalProperties:!1},maxResultChars:24e3,async execute({code:t,input:n,timeout_ms:s},o){if(t.length>e)throw new Error(`the code is ${t.length} characters; the limit is ${e}. Do less in one run.`);let i={names:o.agent.tools.filter(c=>c.name!=="run_js"&&!c.endsRun&&!c.vision&&!c.display?.hidden&&c.callableFromCode!==!1).map(c=>c.name),max:r.maxToolCalls,call:async(c,u,d)=>{let p=await o.callTool(c,u,{signal:d});if(p.status!=="ok")throw new Error(p.text.replace(/^Error:\s*/,""));return p.text}},a=await Ot(t,n,{...r,timeoutMs:s??r.timeoutMs,signal:o.signal,bridge:i}),l=[];return a.logs&&l.push(`console:
258
258
  ${a.logs}`),a.ok?l.push(a.result===void 0?"Returned: undefined":`Returned: ${a.result}`):l.push(/^\w*Error\b/.test(a.error??"")?String(a.error):`Error: ${a.error}`),l.push(`(${a.durationMs} ms)`),{content:l.join(`
259
259
 
260
- `),details:a}}})}var Rt=["web_search","web_fetch"],gn=r=>`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${r}</svg>`,_r=gn('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),Mr=gn('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),Er=["web_search finds pages and web_fetch reads one: use them for facts you can't know or that change (news, prices, releases, people, places, a work's details, a reference the user names), not for what the conversation or your own knowledge already answers.","Read the most relevant results with web_fetch before relying on them; a snippet is not the page. Say where an answer came from, with the link.","Each call costs the user a little: search with a precise query, and stop when you have enough."];function Rr(r){if(typeof r!="string")return"";try{let e=new URL(r.includes("://")?r:`https://${r}`),t=e.pathname==="/"?"":e.pathname;return e.host+(t.length>32?t.slice(0,31)+"\u2026":t)}catch{return r.slice(0,48)}}async function at(r,e={}){let t=await r.list(e.signal?{signal:e.signal}:void 0),n=[];for(let s of Rt){let o=t.find(a=>a.name===s);if(!o)continue;let i=s==="web_search";n.push({name:s,description:o.description,parameters:o.parameters??{type:"object",properties:{}},readOnly:!0,maxResultChars:i?16e3:42e3,...i?{guidelines:Er}:{},display:{icon:i?Mr:_r,outcome:({details:a})=>{if(i){let c=a?.results?.length;return typeof c=="number"?String(c):void 0}let l=a?.title;return l?l.slice(0,40):void 0}},async execute(a,l){!i&&typeof a.url=="string"&&l.update(Rr(a.url));let c=await r.call(s,a,{signal:l.signal}),u=c.usage?.total_cost;return typeof u=="number"&&u>0&&e.onCost?.(u),{content:c.content,details:c.data}}})}return n}function Ot(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var Or=["border:1px solid rgba(127,127,127,.3)","border-radius:12px","padding:18px 18px 14px","width:min(420px,calc(100vw - 32px))","font:14px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color-scheme:light dark","color:CanvasText","background:Canvas","box-shadow:0 12px 40px rgba(0,0,0,.25)"].join(";");function I(r,e,t){let n=document.createElement(r);return e&&n.setAttribute("style",e),t!==void 0&&(n.textContent=t),n}function he(r,e,t,n){let s=I("button");return s.type="button",s.textContent=r,s.setAttribute("style","font:inherit;padding:6px 14px;border-radius:8px;cursor:pointer;"+(e?`border:0;background:${t?"#dc2626":"#2563eb"};color:#fff`:"border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit")),s.addEventListener("click",n),s}function Lt(r,e,t=null){let n=I("dialog",Or),s=t,o=i=>{s=i,n.close()};return r(n,o),e?.aborted?Promise.resolve(t):(document.body.append(n),new Promise(i=>{let a=()=>o(t);e?.addEventListener("abort",a,{once:!0}),n.addEventListener("close",()=>{e?.removeEventListener("abort",a),n.remove(),i(s)},{once:!0}),n.showModal()}))}function lt(){return typeof document>"u"||typeof HTMLDialogElement>"u"?Dt():{async confirm(r,e,t={}){let n=Ot();return await Lt((o,i)=>{if(o.append(I("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&o.append(I("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word",e)),t.body)try{o.append(t.body())}catch(l){console.warn("agent: confirm body failed",l)}let a=I("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");a.append(he(t.cancel??(n?"\u53D6\u6D88":"Cancel"),!1,!1,()=>i(!1)),he(t.ok??(n?"\u786E\u5B9A":"OK"),!0,!!t.danger,()=>i(!0))),o.append(a),queueMicrotask(()=>a.lastElementChild.focus())},t.signal,!1)===!0},async select(r,e,t={}){let n=Ot(),s=await Lt((o,i)=>{o.append(I("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),t.message&&o.append(I("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",t.message));let a=I("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),l="ra_sel_"+Math.random().toString(36).slice(2,8),c=[],u=h=>{let p=I("label","display:flex;gap:8px;align-items:flex-start;padding:8px 10px;border:1px solid rgba(127,127,127,.3);border-radius:8px;cursor:pointer"),m=I("input");m.type=t.multi?"checkbox":"radio",m.name=l,m.value=h.value,m.setAttribute("style","margin-top:3px"),c.push(m);let b=I("div");b.append(I("div","",h.label??h.value)),h.description&&b.append(I("div","opacity:.7;font-size:12px",h.description)),p.append(m,b),a.append(p)};e.forEach(u);let d=null;t.allowOther&&(u({value:"__other__",label:n?"\u5176\u4ED6\u2026":"Other\u2026"}),d=I("input","font:inherit;padding:6px 8px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin-top:-4px"),d.placeholder=n?"\u8BF7\u8F93\u5165":"Type your answer",d.addEventListener("focus",()=>{let h=c.find(p=>p.value==="__other__");h&&(h.checked=!0)}),a.append(d)),o.append(a);let f=I("div","display:flex;justify-content:flex-end;gap:8px");f.append(he(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),he(n?"\u786E\u5B9A":"OK",!0,!1,()=>{let h=c.filter(p=>p.checked).map(p=>p.value==="__other__"?d?.value.trim()||"":p.value).filter(Boolean);h.length&&i(h)})),o.append(f),queueMicrotask(()=>c[0]?.focus())},t.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let t=Ot(),n=await Lt((s,o)=>{s.append(I("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(I("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let i=I(e.multiline?"textarea":"input","font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin:6px 0 12px"+(e.multiline?";min-height:96px;resize:vertical":""));e.placeholder&&(i.placeholder=e.placeholder),e.initial&&(i.value=e.initial),e.multiline||i.addEventListener("keydown",l=>{let c=l;c.key==="Enter"&&!c.isComposing&&c.keyCode!==229&&o(i.value)}),s.append(i);let a=I("div","display:flex;justify-content:flex-end;gap:8px");a.append(he(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>o(null)),he(t?"\u786E\u5B9A":"OK",!0,!1,()=>o(i.value))),s.append(a),queueMicrotask(()=>i.focus())},e.signal,null);return typeof n=="string"?n:null},notify(r,e="info"){let t=I("div",["position:fixed","right:16px","bottom:16px","z-index:2147483647","max-width:min(360px,calc(100vw - 32px))","padding:10px 14px","border-radius:10px","font:13px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#fff",`background:${e==="error"?"#dc2626":e==="warning"?"#d97706":"#111827"}`,"box-shadow:0 8px 24px rgba(0,0,0,.25)","white-space:pre-wrap","word-break:break-word"].join(";"),r);document.body.append(t),setTimeout(()=>t.remove(),e==="error"?8e3:4e3)}}}function Dt(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function ct(){return L({name:"ask_user",callableFromCode:!1,description:"Ask the user one to three questions when the request is genuinely ambiguous and the answer changes what you would do. Give 2\u20135 short options when there are natural choices (allow_other adds a free-text choice); leave options out for a free-text answer. Do not ask what you can reasonably decide yourself.",parameters:{type:"object",properties:{questions:{type:"array",minItems:1,maxItems:3,items:{type:"object",properties:{question:{type:"string",minLength:1},options:{type:"array",minItems:2,maxItems:5,items:{type:"object",properties:{label:{type:"string",minLength:1},description:{type:"string"}},required:["label"],additionalProperties:!1}},allow_other:{type:"boolean"},multi:{type:"boolean"}},required:["question"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},async execute({questions:r},e){let t=[];for(let s of r){e.signal.throwIfAborted();let o;if(s.options&&s.options.length){let i=await e.ui.select(s.question,s.options.map(a=>({value:a.label,label:a.label,description:a.description})),{multi:!!s.multi,allowOther:s.allow_other!==!1,signal:e.signal});o=i===null?null:s.multi?i:i[0]??null}else o=await e.ui.input(s.question,{multiline:!0,signal:e.signal});if(t.push({question:s.question,answer:o}),o===null)break}return{content:t.some(s=>s.answer===null)||t.length<r.length?"The user dismissed the question without answering. Proceed with a reasonable default and say which you chose, or stop if you cannot.":t.map(s=>`Q: ${s.question}
260
+ `),details:a}}})}var Lt=["web_search","web_fetch"],gn=r=>`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${r}</svg>`,_r=gn('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),Mr=gn('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),Er=["web_search finds pages and web_fetch reads one: use them for facts you can't know or that change (news, prices, releases, people, places, a work's details, a reference the user names), not for what the conversation or your own knowledge already answers.","Read the most relevant results with web_fetch before relying on them; a snippet is not the page. Say where an answer came from, with the link.","Each call costs the user a little: search with a precise query, and stop when you have enough."];function Rr(r){if(typeof r!="string")return"";try{let e=new URL(r.includes("://")?r:`https://${r}`),t=e.pathname==="/"?"":e.pathname;return e.host+(t.length>32?t.slice(0,31)+"\u2026":t)}catch{return r.slice(0,48)}}async function at(r,e={}){let t=await r.list(e.signal?{signal:e.signal}:void 0),n=[];for(let s of Lt){let o=t.find(a=>a.name===s);if(!o)continue;let i=s==="web_search";n.push({name:s,description:o.description,parameters:o.parameters??{type:"object",properties:{}},readOnly:!0,maxResultChars:i?16e3:42e3,...i?{guidelines:Er}:{},display:{icon:i?Mr:_r,outcome:({details:a})=>{if(i){let c=a?.results?.length;return typeof c=="number"?String(c):void 0}let l=a?.title;return l?l.slice(0,40):void 0}},async execute(a,l){!i&&typeof a.url=="string"&&l.update(Rr(a.url));let c=await r.call(s,a,{signal:l.signal}),u=c.usage?.total_cost;return typeof u=="number"&&u>0&&e.onCost?.(u),{content:c.content,details:c.data}}})}return n}function lt(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var Or=["border:1px solid rgba(127,127,127,.3)","border-radius:12px","padding:18px 18px 14px","width:min(420px,calc(100vw - 32px))","font:14px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color-scheme:light dark","color:CanvasText","background:Canvas","box-shadow:0 12px 40px rgba(0,0,0,.25)"].join(";");function _(r,e,t){let n=document.createElement(r);return e&&n.setAttribute("style",e),t!==void 0&&(n.textContent=t),n}function Y(r,e,t,n){let s=_("button");return s.type="button",s.textContent=r,s.setAttribute("style","font:inherit;padding:6px 14px;border-radius:8px;cursor:pointer;"+(e?`border:0;background:${t?"#dc2626":"#2563eb"};color:#fff`:"border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit")),s.addEventListener("click",n),s}function ct(r,e,t=null){let n=_("dialog",Or),s=t,o=i=>{s=i,n.close()};return r(n,o),e?.aborted?Promise.resolve(t):(document.body.append(n),new Promise(i=>{let a=()=>o(t);e?.addEventListener("abort",a,{once:!0}),n.addEventListener("close",()=>{e?.removeEventListener("abort",a),n.remove(),i(s)},{once:!0}),n.showModal()}))}function ut(){return typeof document>"u"||typeof HTMLDialogElement>"u"?Dt():{async confirm(r,e,t={}){let n=lt();return await ct((o,i)=>{if(o.append(_("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&o.append(_("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word",e)),t.body)try{o.append(t.body())}catch(l){console.warn("agent: confirm body failed",l)}let a=_("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");a.append(Y(t.cancel??(n?"\u53D6\u6D88":"Cancel"),!1,!1,()=>i(!1)),Y(t.ok??(n?"\u786E\u5B9A":"OK"),!0,!!t.danger,()=>i(!0))),o.append(a),queueMicrotask(()=>a.lastElementChild.focus())},t.signal,!1)===!0},async select(r,e,t={}){let n=lt(),s=await ct((o,i)=>{o.append(_("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),t.message&&o.append(_("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",t.message));let a=_("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),l="ra_sel_"+Math.random().toString(36).slice(2,8),c=[],u=h=>{let f=_("label","display:flex;gap:8px;align-items:flex-start;padding:8px 10px;border:1px solid rgba(127,127,127,.3);border-radius:8px;cursor:pointer"),m=_("input");m.type=t.multi?"checkbox":"radio",m.name=l,m.value=h.value,m.setAttribute("style","margin-top:3px"),c.push(m);let b=_("div");b.append(_("div","",h.label??h.value)),h.description&&b.append(_("div","opacity:.7;font-size:12px",h.description)),f.append(m,b),a.append(f)};e.forEach(u);let d=null;t.allowOther&&(u({value:"__other__",label:n?"\u5176\u4ED6\u2026":"Other\u2026"}),d=_("input","font:inherit;padding:6px 8px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin-top:-4px"),d.placeholder=n?"\u8BF7\u8F93\u5165":"Type your answer",d.addEventListener("focus",()=>{let h=c.find(f=>f.value==="__other__");h&&(h.checked=!0)}),a.append(d)),o.append(a);let p=_("div","display:flex;justify-content:flex-end;gap:8px");p.append(Y(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),Y(n?"\u786E\u5B9A":"OK",!0,!1,()=>{let h=c.filter(b=>b.checked).map(b=>b.value==="__other__"?d?.value.trim()||"":b.value).filter(Boolean),f=t.multi?t.min??1:1,m=t.multi?t.max:void 0;h.length<f||m!==void 0&&h.length>m||i(h)})),o.append(p),queueMicrotask(()=>c[0]?.focus())},t.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let t=lt(),n=await ct((s,o)=>{s.append(_("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(_("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let i=_(e.multiline?"textarea":"input","font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin:6px 0 12px"+(e.multiline?";min-height:96px;resize:vertical":""));e.placeholder&&(i.placeholder=e.placeholder),e.initial&&(i.value=e.initial),e.multiline||i.addEventListener("keydown",l=>{let c=l;c.key==="Enter"&&!c.isComposing&&c.keyCode!==229&&o(i.value)}),s.append(i);let a=_("div","display:flex;justify-content:flex-end;gap:8px");a.append(Y(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>o(null)),Y(t?"\u786E\u5B9A":"OK",!0,!1,()=>o(i.value))),s.append(a),queueMicrotask(()=>i.focus())},e.signal,null);return typeof n=="string"?n:null},async form(r,e,t={}){let n=lt(),s=await ct((o,i)=>{o.append(_("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),t.message&&o.append(_("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",t.message));let a=e.map(u=>{let d=_("label","display:block;font-size:13px;margin:8px 0");d.append(_("div","opacity:.8;margin-bottom:4px",(u.label??u.name)+(u.required?" *":"")));let p=_("input","font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box");return p.type=u.type==="number"?"number":"text",u.type==="number"&&(p.step="any"),u.placeholder&&(p.placeholder=u.placeholder),u.initial!==void 0&&(p.value=String(u.initial)),d.append(p),o.append(d),{f:u,input:p}}),l=()=>{let u={};for(let{f:d,input:p}of a){let h=p.value.trim();if(!h&&d.required||h&&d.type==="number"&&!Number.isFinite(Number(h))){p.focus();return}h&&(u[d.name]=d.type==="number"?Number(h):h)}i(u)},c=_("div","display:flex;justify-content:flex-end;gap:8px;margin-top:12px");c.append(Y(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),Y(t.ok??(n?"\u786E\u5B9A":"OK"),!0,!1,l)),o.append(c),queueMicrotask(()=>a[0]?.input.focus())},t.signal,null);return s&&typeof s=="object"&&!Array.isArray(s)?s:null},notify(r,e="info"){let t=_("div",["position:fixed","right:16px","bottom:16px","z-index:2147483647","max-width:min(360px,calc(100vw - 32px))","padding:10px 14px","border-radius:10px","font:13px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#fff",`background:${e==="error"?"#dc2626":e==="warning"?"#d97706":"#111827"}`,"box-shadow:0 8px 24px rgba(0,0,0,.25)","white-space:pre-wrap","word-break:break-word"].join(";"),r);document.body.append(t),setTimeout(()=>t.remove(),e==="error"?8e3:4e3)}}}function Dt(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function dt(){return D({name:"ask_user",callableFromCode:!1,description:"Ask the user one to three questions when the request is genuinely ambiguous and the answer changes what you would do. Give 2\u20135 short options when there are natural choices (allow_other adds a free-text choice); leave options out for a free-text answer. Do not ask what you can reasonably decide yourself.",parameters:{type:"object",properties:{questions:{type:"array",minItems:1,maxItems:3,items:{type:"object",properties:{question:{type:"string",minLength:1},options:{type:"array",minItems:2,maxItems:5,items:{type:"object",properties:{label:{type:"string",minLength:1},description:{type:"string"}},required:["label"],additionalProperties:!1}},allow_other:{type:"boolean"},multi:{type:"boolean"}},required:["question"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},async execute({questions:r},e){let t=[];for(let s of r){e.signal.throwIfAborted();let o;if(s.options&&s.options.length){let i=await e.ui.select(s.question,s.options.map(a=>({value:a.label,label:a.label,description:a.description})),{multi:!!s.multi,allowOther:s.allow_other!==!1,signal:e.signal});o=i===null?null:s.multi?i:i[0]??null}else o=await e.ui.input(s.question,{multiline:!0,signal:e.signal});if(t.push({question:s.question,answer:o}),o===null)break}return{content:t.some(s=>s.answer===null)||t.length<r.length?"The user dismissed the question without answering. Proceed with a reasonable default and say which you chose, or stop if you cannot.":t.map(s=>`Q: ${s.question}
261
261
  A: ${Array.isArray(s.answer)?s.answer.join(", "):s.answer}`).join(`
262
262
 
263
- `),details:{answers:t}}}})}var yn=100,Dr=8192,Ur=128e3,wn="/memory/notes.md",bn="/AGENTS.md",Ir=6e3,jr=3,kn=2e6,Fr=3,Nr=6;function zr(r,e){let t="ts"in r||"typed"in r||"runUsage"in r,n=e&&r.role==="assistant"&&r.reasoning_content!==void 0;if(!t&&!n)return r;let{ts:s,typed:o,runUsage:i,...a}=r;return n&&delete a.reasoning_content,a}function Wr(r){let e=c=>c.role==="tool"&&Array.isArray(c.content)&&c.content.some(u=>u.type!=="text");if(!r.some(e))return r;let t=[],n=-1,s=!1;r.forEach((c,u)=>{if(c.role!=="tool"){n=-1;return}n<0&&(n=u,s=!1),!s&&e(c)&&(t.push(n),s=!0)});let o=t.length>xn?t[t.length-xn]:0,i=[],a=[],l=()=>{a.length&&i.push({role:"user",content:a}),a=[]};for(let[c,u]of r.entries()){if(u.role!=="tool"&&l(),e(u)){let d=u.content,f=d.filter(m=>m.type!=="text"),h=d.filter(m=>m.type==="text").map(m=>m.text).join(`
264
- `),p=`${f.length} attachment${f.length===1?"":"s"}`;if(c<o){i.push({...u,content:`${h}${h?`
265
- `:""}[${p} no longer shown; call the tool again to see the current state]`});continue}i.push({...u,content:`${h}${h?`
266
- `:""}[${p} follow${f.length===1?"s":""} in the next message]`}),a.push({type:"text",text:`Attachments from tool call ${u.tool_call_id??""}:`.trim()},...f);continue}i.push(u)}return l(),i}var xn=2,Sn={image:"image_url",video:"video_url",audio:"audio_url"},vn={image:"picture",video:"video",audio:"audio clip"};function Br(r,e,t){let n=Object.keys(Sn).filter(o=>e[o]===!1);if(!n.length)return r;let s=o=>n.find(i=>Sn[i]===o.type);return r.map(o=>{if(!Array.isArray(o.content)||!o.content.some(a=>s(a)))return o;let i=o.content.map(a=>{let l=s(a);return l?{type:"text",text:`[A ${vn[l]} was attached here; the model in use${t?` (${t})`:""} does not take ${vn[l]}s, so it is not shown. Say so if it matters.]`}:a});return{...o,content:i}})}var It=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),_e=()=>({runId:"",reason:"aborted",text:"",usage:It()}),fe="Skipped: the user stopped the run.",qr=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),Tn=()=>new q(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function ut(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(e.reason??new Error("aborted"))):new Promise((t,n)=>{let s=()=>n(e.reason??new Error("aborted"));e.addEventListener("abort",s,{once:!0}),r.then(o=>{e.removeEventListener("abort",s),t(o)},o=>{e.removeEventListener("abort",s),n(o)})})}var pe=class{constructor(e,t={}){y(this,"id");y(this,"provider");y(this,"ui");y(this,"workspace");y(this,"tools");y(this,"opts");y(this,"web");y(this,"compactSummaries");y(this,"compactThresholds");y(this,"webCache",null);y(this,"history",[]);y(this,"committed",0);y(this,"droppedTurns",0);y(this,"_usage",It());y(this,"handlers",new Map);y(this,"anyHandlers",new Set);y(this,"queue",[]);y(this,"current",null);y(this,"chain",Promise.resolve());y(this,"pendingSkills",[]);y(this,"catalogue",null);y(this,"loop",{seen:new Set,idle:0,warned:!1});y(this,"turnNow",0);y(this,"loaded");y(this,"createdAt",Date.now());y(this,"fixedTitle");y(this,"_ended",null);y(this,"persist");this.provider=Z(e),this.opts=t,this.compactSummaries=t.compaction!==!1,this.compactThresholds=typeof t.compaction=="object"?{...t.compaction}:{},this.id=t.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=t.ui??lt(),this.workspace=t.workspace??null;let n=[...t.tools??[]],s=this.workspace?ue(this.workspace,{enabled:t.readBeforeWrite!==!1}):void 0;if(s){let i=()=>s.retain(this.filesInView());this.on("compaction",i),this.on("rewind",i)}if(this.workspace&&t.fileTools!==!1){let i=Array.isArray(t.fileTools)?new Set(t.fileTools):null;n.push(...st(this.workspace,{guard:s}).filter(a=>!i||i.has(a.name)))}t.askUser!==!1&&n.push(ct()),t.sandbox!==!1&&n.push(ot(typeof t.sandbox=="object"?t.sandbox:{}));let o=new Set;for(let i of n){if(o.has(i.name))throw new Error(`two tools are named "${i.name}"`);o.add(i.name)}if(this.tools=n,this.web=t.webTools??!1,t.serverTools?.length&&(t.tools?.length||this.workspace||t.sandbox!==!1||t.askUser!==!1))throw new Error("serverTools work only for an agent with no tools of its own (tools: [], workspace: null, sandbox: false, askUser: false) \u2014 the gateway runs that loop");this.persist=!!this.workspace&&t.persist!==!1,t.restore?(this.applySession(t.restore),this.loaded=Promise.resolve()):this.persist&&t.id?this.loaded=this.workspace.sessions.get(t.id).then(i=>{i&&this.applySession(i)}).catch(i=>{this.persist=!1,console.warn(`agent: could not load session ${t.id}; it will not be saved over`,i)}):this.loaded=Promise.resolve()}get title(){return this.fixedTitle}setTitle(e){this.fixedTitle=e.trim()||void 0}applySession(e){if(e.v!==1&&e.v!==2)throw new Error("unknown session format");this.history=e.messages.slice(),this.committed=this.history.length,this.droppedTurns=e.droppedTurns??0,this._usage={...e.usage},this.createdAt=e.createdAt??e.savedAt??Date.now(),this._ended=e.ended??null,this.fixedTitle=e.title&&!et(e.title)?e.title:void 0,e.model&&!this.opts.model&&(this.opts.model=e.model,this.catalogue=null)}ready(){return this.loaded}async saveSession(){if(!(!this.persist||!this.workspace))try{await this.workspace.sessions.save(this.export()),this.emit("session_saved",{id:this.id})}catch(e){console.warn("[agent] could not save the session:",e)}}on(e,t){if(e==="*")return this.anyHandlers.add(t),()=>{this.anyHandlers.delete(t)};let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>{this.handlers.get(e)?.delete(t)}}emit(e,t){for(let n of this.handlers.get(e)??[])try{n(t)}catch(s){console.error("[agent] listener for",e,"threw:",s)}for(let n of this.anyHandlers)try{n(e,t)}catch(s){console.error("[agent] listener threw:",s)}}get messages(){return this.history.slice()}get usage(){return{...this._usage}}get lastEnd(){return this._ended}get busy(){return this.current!==null}get model(){return this.opts.model}set model(e){this.opts.model=e,this.catalogue=null}get settings(){let e=this.opts.permissions??"ask",t=this.opts.extra?.reasoning_effort;return{model:this.opts.model,maxTurns:this.opts.maxTurns??yn,maxTokens:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:"auto",permissions:typeof e=="function"?"custom":e,reasoningEffort:typeof t=="string"?t:void 0,compaction:{summarize:this.compactSummaries,...this.compactThresholds}}}configure(e){if(e.compaction){let t=e.compaction;typeof t.summarize=="boolean"&&(this.compactSummaries=t.summarize);for(let n of["reserveTokens","keepRecentTokens"]){if(!(n in t))continue;let s=t[n];typeof s=="number"&&Number.isFinite(s)&&s>0?this.compactThresholds[n]=Math.floor(s):delete this.compactThresholds[n]}}if("model"in e&&(this.model=e.model||void 0),typeof e.webTools=="boolean"&&(this.web=e.webTools),"reasoningEffort"in e){let t={...this.opts.extra??{}};e.reasoningEffort?t.reasoning_effort=e.reasoningEffort:delete t.reasoning_effort,this.opts.extra=t}typeof e.maxTurns=="number"&&e.maxTurns>0&&(this.opts.maxTurns=Math.floor(e.maxTurns)),e.maxTokens!==void 0&&(this.opts.maxTokens=e.maxTokens),e.permissions!==void 0&&(this.opts.permissions=e.permissions)}compactionFor(e){return{summarize:this.compactSummaries,...re(e,this.compactThresholds)}}export(){let e=this.history.slice(0,this.committed),t={v:2,id:this.id,model:this.opts.model,messages:e,usage:{...this._usage},droppedTurns:this.droppedTurns,createdAt:this.createdAt,savedAt:Date.now(),...this._ended?{ended:this._ended}:{}};if(!this.fixedTitle){let n=$e(t);n!==ce&&(this.fixedTitle=n)}return t.title=this.fixedTitle??ce,t}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.fixedTitle=void 0,this._ended=null,this.committed=0,this.droppedTurns=0,this.resetLoop()}useSkill(e){if(!this.workspace)throw new Error("useSkill needs a workspace");this.pendingSkills.push(e)}prompt(e,t={}){let n=this.userMessage(e);return this.current?this.enqueue("followUp",n):this.start(n,t.signal)}steer(e){let t=this.userMessage(e);if(!this.current)return this.start(t);this.queue.push({kind:"steer",message:t}),this.emit("queued",{kind:"steer",message:t})}followUp(e){let t=this.userMessage(e);return this.current?this.enqueue("followUp",t):this.start(t)}get queued(){return this.queue.map(e=>({kind:e.kind,message:e.message}))}dequeue(e){let t=this.queue.find(n=>n.message===e);return t?(this.queue=this.queue.filter(n=>n!==t),t.resolve?.(_e()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let t of e)t.resolve?.(_e())}async abort(){this.clearQueue();let e=this.current;e&&(e.controller.abort(),await e.promise.catch(()=>{}))}enqueue(e,t){return new Promise(n=>{this.queue.push({kind:e,message:t,resolve:n}),this.emit("queued",{kind:e,message:t})})}userMessage(e){let t=typeof e=="string"?[{type:"text",text:e}]:e.slice();return{role:"user",content:t.length===1&&t[0].type==="text"?t[0].text:t,ts:Date.now()}}async rewind(e){if(await this.loaded,this.current)throw new Error("cannot rewind while a run is active; abort() first");if(!Number.isInteger(e)||e<0||e>this.history.length)throw new Error(`no message at ${e}`);this.clearQueue(),this.history=this.history.slice(0,e),this.committed=this.history.length,this._ended=null,this.resetLoop(),await this.saveSession(),this.emit("rewind",{index:e})}async remove(e,t=this.history.length){if(await this.loaded,this.current)throw new Error("Cannot delete messages while a run is active; abort() first");if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t>this.history.length||e>=t)throw new Error(`No messages ${e}\u2013${t}`);this.clearQueue(),this.history.splice(e,t-e),this.committed=this.history.length,this._ended=null,this.resetLoop(),await this.saveSession(),this.emit("rewind",{index:e})}async clear(){await this.loaded,await this.abort(),this.reset(),this._usage=It(),await this.saveSession(),this.emit("rewind",{index:0})}async continue(){if(await this.loaded,this.current)throw new Error("cannot continue while a run is active");if(!this.history.length)throw new Error("nothing to continue");return this.start(null)}start(e,t){let n=new AbortController;t&&(t.aborted?n.abort():t.addEventListener("abort",()=>n.abort(),{once:!0}));let s=this.chain.then(()=>this.run(e,n)).finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()});return this.current={controller:n,promise:s},this.chain=s.catch(()=>{}),s}drainFollowUps(){let e=this.queue.find(t=>t.kind==="followUp");e&&(this.queue=this.queue.filter(t=>t!==e),this.start(e.message).then(t=>e.resolve?.(t),t=>e.resolve?.({..._e(),reason:"error",error:t instanceof Error?t:new Error(String(t))})))}async run(e,t){await this.loaded;let n=`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,s=t.signal,o="done",i,a="",l=0,c={...this._usage},u=this.history.length;this.applySteering(n);let d=null,f;if(e){try{d=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(k){d=e,f=k instanceof Error?k:new Error(String(k))}this.history.push(d)}this._ended=null,this.emit("run_start",{runId:n,message:d});let h=this.opts.maxTurns??yn,{output:p,input:m}=await this.limits(),b=m,S=re(b,this.compactThresholds),g=0;try{if(f)throw f;for(let k=1;;k++){if(s.aborted){o="aborted";break}if(k>h){o="max_turns";break}this.turnNow=k,this.emit("turn_start",{runId:n,turn:k}),this.applySteering(n);let T=await this.systemPrompt(),C=this.fixedText(T),P=M(this.history,C);if(wt(P,b,S)){let v=this.compactSummaries?await this.compactWith(S,n,s):!1,N=M(this.history,C);if(!v||wt(N,b,S)){let z=this.history.length&&K(this.history[0])!==null?[this.history[0]]:[],J=this.history.slice(z.length),O=ge(J,{budget:b-S.reserveTokens-M(z),keepTurns:this.opts.keepTurns??4,system:C});(O.droppedTurns||O.elidedResults)&&(this.history=[...z,...O.messages],this.droppedTurns+=O.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:n,summary:!1,tokensBefore:N,tokensAfter:M(this.history,C),droppedTurns:O.droppedTurns,elidedResults:O.elidedResults}))}}let E=await this.activeTools(),$={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:T},...this.toWireHistory(await this.mediaSupport())],max_tokens:p};$.model||delete $.model,E.length&&($.tools=E.map(v=>Be(v))),this.opts.serverTools?.length&&($.server_tools=this.opts.serverTools),this.opts.prompt&&($.prompt=this.opts.prompt),this.opts.temperature!==void 0&&($.temperature=this.opts.temperature),this.opts.top_p!==void 0&&($.top_p=this.opts.top_p),this.emit("request",{runId:n,turn:k,params:$});let F=Date.now(),U;try{if(M(this.history,C)>b*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new q(413,"the request is far larger than the model's context");U=await this.callModel($,n,s)}catch(v){if(this.emit("response",{runId:n,turn:k,durationMs:Date.now()-F,error:v instanceof Error?v.message:String(v)}),s.aborted||!De(v))throw v;let N=qt(v);N!==void 0&&N<b&&(b=N,S=re(b,this.compactThresholds));let z=!1;for(;!z&&g<2;)z=await this.squeeze(b,g++,S,C,n,s);if(z){k--;continue}throw new G({cause:this.overflowCause(b,C),used:M(this.history,C),window:b},v instanceof Error?v.message:String(v),Ue(v)??400)}this.emit("response",{runId:n,turn:k,durationMs:Date.now()-F,finishReason:U.finishReason,usage:U.usage,message:U.message}),U.usage&&this.addUsage(U.usage);let A={role:"assistant",content:U.message.content,ts:Date.now()};U.message.tool_calls?.length&&(A.tool_calls=U.message.tool_calls),U.reasoning&&(A.reasoning_content=U.reasoning),this.history.push(A),typeof A.content=="string"&&A.content&&(a=A.content);let R=U.finishReason==="length";this.emit("message_end",{runId:n,message:A,truncated:R}),this.emit("turn_end",{runId:n,turn:k,usage:U.usage});let B=A.tool_calls??[];if(!B.length){if(this.committed=this.history.length,await this.saveSession(),R&&this.balanceLimited(U.usage,p)){o="error",i=Tn();break}if(!s.aborted&&this.queue.some(v=>v.kind==="steer"))continue;break}let te=await this.runBatch(B,n,s,R);if(this.committed=this.history.length,await this.saveSession(),s.aborted){o="aborted";break}if(!R&&xe(A.content).trim()&&B.every(v=>this.tools.find(N=>N.name===v.function.name)?.endsRun)){if(this.queue.some(v=>v.kind==="steer"))continue;break}if(R){if(l++,this.balanceLimited(U.usage,p)){o="error",i=Tn();break}if(l>=2){o="error",i=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let H=this.checkLoop(te);if(H==="stop"){o="error",i=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}H==="warn"&&this.history.push({role:"user",content:"[environment] The last rounds of tool calls brought nothing new: the same results, the same errors, or parts of files you had already read. Do not repeat them. Use what you have already read (it is above), read only what is still missing, take a different approach, or explain the blocker and finish."})}}catch(k){s.aborted?o="aborted":(o="error",i=k instanceof Error?k:new Error(String(k)))}o==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(u,c),this.committed=this.history.length,this.resetLoop();let w=i instanceof G?{code:i.code,overflow:i.overflow}:{};this._ended=o==="done"?null:{reason:o,...i?{error:i.message}:{},...w,at:Date.now()},await this.saveSession();let _={runId:n,reason:o,text:a,usage:this.usage,...i?{error:i}:{}};return this.emit("run_end",_),_}applySteering(e){let t=this.queue.filter(n=>n.kind==="steer").map(n=>n.message);t.length&&(this.queue=this.queue.filter(n=>n.kind!=="steer"),this.history.push(...t),this.loop.idle=0,this.loop.warned=!1,this.emit("steered",{runId:e,messages:t}))}toWireHistory(e={}){let t=-1;for(let n=this.history.length-1;n>=0;n--)if(this.history[n].role==="user"){t=n;break}return Br(Wr(this.history.map((n,s)=>zr(n,s<t))),e,this.opts.model)}async mediaSupport(){let[e,t,n]=await Promise.all([this.accepts("image"),this.accepts("video"),this.accepts("audio")]);return{image:e,video:t,audio:n}}get webTools(){return this.webToolsAvailable&&(typeof this.web=="function"?!!this.web():this.web)}get webToolsAvailable(){return!!this.provider.platformTools}async activeTools(){let e=this.tools;if(e.some(t=>t.vision)){let t=await this.accepts("image");e=e.filter(n=>!n.vision||t===!0)}if(this.webTools){let t=await this.loadWeb(),n=new Set(e.map(o=>o.name)),s=t.filter(o=>!n.has(o.name));s.length&&(e=[...e,...s])}return e}loadWeb(){let e=this.provider.platformTools;return e?(this.webCache??(this.webCache=at(e,{onCost:t=>this.addToolCost(t)}).catch(t=>(this.webCache=null,console.warn("[agent] could not load the web tools:",t),[]))),this.webCache):Promise.resolve([])}async systemPrompt(){let e=this.workspace,t=async(s,o)=>{if(e)try{let i=await e.readText(s);return i.length>o?i.slice(i.length-o):i}catch{return}},n=await this.activeTools();return Ie({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:n,workspaceDescription:e&&n.some(s=>qr.has(s.name))?e.describe():void 0,skills:e?await e.skills():[],hasSandbox:n.some(s=>s.name==="run_js"),hasAskUser:n.some(s=>s.name==="ask_user"),canWrite:n.some(s=>s.name==="write_file"||s.name==="edit_file"),agentsMd:this.opts.instructionsFile===!1?void 0:await t(this.opts.instructionsFile??bn,2e4),agentsPath:this.opts.instructionsFile||bn,memory:this.opts.memoryFile===!1?void 0:await t(this.opts.memoryFile??wn,Ir),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??wn,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async t=>{let n=await this.contextTokens(),s=this.squeezed(re(n,this.compactThresholds)),o=await this.compactWith(s,void 0,t,e);return o&&await this.saveSession(),o})}summarize(e){return this.exclusive("summarize",async t=>{let n=this.history.filter(l=>l!==e),s=n[0]?K(n[0]):null,o=s===null?n:n.slice(1);if(!o.length)return s;let i=await this.contextTokens(),a=re(i,this.compactThresholds);this.emit("compaction_start",{});try{return await this.writeSummary({toSummarize:o,previousSummary:s??void 0,kept:[]},a,void 0,t)}catch(l){if(t.aborted)throw l;return console.warn("[agent] summary failed:",l),null}})}async seed(e){if(await this.loaded,this.current)throw new Error("cannot seed while a run is active");if(this.history.length)throw new Error("seed needs an empty conversation");this.history=[ye(e)],this.committed=1,this._ended=null,await this.saveSession()}exclusive(e,t){if(this.current)return Promise.reject(new Error(`cannot ${e} while a run is active`));let n=new AbortController,s=this.chain.then(async()=>(await this.loaded,t(n.signal))),o=s.then(()=>({..._e(),reason:"done"}),()=>_e());return this.current={controller:n,promise:o},this.chain=o,o.finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()}),s}squeezed(e){let t=this.history,n=t.length-1;for(;n>0&&!(t[n].role==="user"&&K(t[n])===null);)n--;let s=n>0?t.slice(n).reduce((o,i)=>o+M([i]),0):Math.floor(M(t)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,t,n,s,o,i){let a=M(this.history,s);t===0&&this.compactSummaries&&await this.compactWith(this.squeezed(n),o,i);let l=this.history.length&&K(this.history[0])!==null?[this.history[0]]:[],c=this.history.slice(l.length),u=Math.floor(e*(t===0?.7:.4))-M(l),d=ge(c,{budget:u,keepTurns:1,system:s,keepResults:t===0?3:0});return(d.droppedTurns||d.elidedResults)&&(this.history=[...l,...d.messages],this.droppedTurns+=d.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:o,summary:!1,tokensBefore:a,tokensAfter:M(this.history,s),droppedTurns:d.droppedTurns,elidedResults:d.elidedResults})),M(this.history,s)<a}overflowCause(e,t){let n=this.tools.length?M([],JSON.stringify(this.tools.map(l=>Be(l)))):0,s=[...this.history].reverse().find(l=>l.role==="user"&&K(l)===null),o=s?M([s]):0,i=M(this.history)-o,a=Math.max(n,o,i);return a*2<e?"model":a===o?(Array.isArray(s.content)?s.content.length>1:/(^|\n)\[attachments\]/.test(String(s.content??"")))?"attachments":"message":a===n?"tools":"history"}async writeSummary(e,t,n,s){if(typeof this.opts.compaction=="function")return this.opts.compaction(e,this);let o=await this.limits(),i=Math.min(o.output,Math.max(1024,Math.floor(t.reserveTokens*.8))),a=Math.max(6e3,(o.input-i-1500)*3),l=e.previousSummary;for(let c of Ne(we(e.toSummarize),a)){let u={model:this.opts.model??"",messages:Jt(c,l,e.focus),max_tokens:i};u.model||delete u.model;let d={runId:n??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...d,params:u}),s.throwIfAborted();let f=Date.now(),h;try{h=this.provider.complete?await this.provider.complete(u,{signal:s}):await be((m,b)=>this.provider.stream(m,b),u,{signal:s}).then(m=>({choices:[{message:{...m.message,content:typeof m.message.content=="string"?m.message.content:null},finish_reason:m.finishReason}],usage:m.usage}))}catch(m){throw this.emit("response",{...d,durationMs:Date.now()-f,error:m instanceof Error?m.message:String(m)}),m}h.usage&&this.addUsage(h.usage);let p=h.choices[0];if(this.emit("response",{...d,durationMs:Date.now()-f,finishReason:p?.finish_reason??void 0,usage:h.usage??void 0,message:p?.message}),!p||p.finish_reason==="length")throw new Error("the summary is incomplete");if(p.message.tool_calls?.length)throw new Error("the summariser attempted to call a tool");if(l=(p.message.content??"").trim(),!l)throw new Error("empty summary")}return l}async compactWith(e,t,n,s){let o=Fe(this.history,e.keepRecentTokens);if(!o)return!1;s?.trim()&&(o.focus=s.trim()),this.emit("compaction_start",{runId:t});let i=M(this.history),a;try{a=await this.writeSummary(o,e,t,n)}catch(l){if(n.aborted)throw l;return console.warn("[agent] compaction summary failed, falling back to trimming:",l),!1}return this.history=[ye(a),...o.kept],this.committed=this.history.length,this.emit("compaction",{runId:t,summary:!0,tokensBefore:i,tokensAfter:M(this.history),droppedTurns:0,elidedResults:0}),!0}async expandSlashes(e){if(!this.workspace)return e;let t=Array.isArray(e.content)?e.content:null,n=t?.[0],s=typeof e.content=="string"?e.content:n?.type==="text"?n.text:"";if(!s.startsWith("/"))return e;let o=await ze(this.workspace,s);if(o===s)return e;let i=t?[{type:"text",text:o},...t.slice(1)]:o;return{...e,content:i,typed:s}}async callModel(e,t,n){let s="",o="",i=!1;for(let a=1;;a++){s="",o="",n.throwIfAborted();try{return await be((l,c)=>this.provider.stream(l,c),e,{signal:n,onText:(l,c)=>{i=!0,s=c,this.emit("text_delta",{runId:t,delta:l,text:c})},onReasoning:(l,c)=>{i=!0,o=c,this.emit("reasoning_delta",{runId:t,delta:l,text:c})},onToolCall:(l,c)=>{i=!0,this.emit("tool_call_delta",{runId:t,index:l.index,id:l.id,name:l.name,delta:c,arguments:l.arguments})}})}catch(l){if(n.aborted||a>=jr||!Kr(l))throw l;let c=Hr(l,a);i&&this.emit("message_reset",{runId:t,reason:l.message}),i=!1,await Jr(c,n)}}}async runBatch(e,t,n,s){let o=a=>this.runTool(a,t,n,s),i=this.opts.parallelTools?await Promise.all(e.map(a=>o(a))):await(async()=>{let a=[],l=!1;for(let c of e){if(l){a.push(this.skipTool(c,t,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}a.push(await o(c)),this.queue.some(u=>u.kind==="steer")&&(l=!0)}return a})();for(let a of i)this.history.push(a.message);return i}skipTool(e,t,n){let s=e.id??"",o=e.function.name;return this.emit("tool_start",{runId:t,id:s,name:o,args:e.function.arguments}),this.emit("tool_end",{runId:t,id:s,name:o,status:"skipped",result:n,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:n},key:"",changed:!1,progress:!0,status:"skipped"}}async runTool(e,t,n,s,o){let i=e.id??"",a=o?{parentId:o}:{},l=e.function.name,c=Date.now(),u,d,f=(g,w,_)=>{let k=xe(w);return this.emit("tool_end",{runId:t,id:i,name:l,status:g,result:o?We(k,32e3).text:k,details:_,durationMs:Date.now()-c,...a,...typeof w=="string"?{}:{content:w}}),{status:g,details:_,message:{role:"tool",tool_call_id:i,content:w},key:d?.readOnly?`${l}|${g}|${k.slice(0,4e3)}`:`${l}|${e.function.arguments.slice(0,4e3)}|${g}|${k.slice(0,2e3)}`,changed:g==="ok"&&!!d&&!d.readOnly,progress:g==="declined"||g==="skipped"?!0:g==="ok"?u:void 0}};if(n.aborted)return f("skipped",fe);if(s)return this.emit("tool_start",{runId:t,id:i,name:l,args:e.function.arguments,...a}),f("error",`Tool call "${l}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);let h=await this.activeTools();d=h.find(g=>g.name===l);let p;try{p=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:t,id:i,name:l,args:e.function.arguments,...a}),f("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:t,id:i,name:l,args:p,...a}),!d)return f("error",`Error: there is no tool named "${l}". Available tools: ${h.map(g=>g.name).join(", ")}.`);if(p===null||typeof p!="object"||Array.isArray(p))return f("error","Error: the arguments must be a JSON object.");let m=it(d.parameters,p);if(m.length)return f("error",`Error: invalid arguments for ${l}:
263
+ `),details:{answers:t}}}})}var yn=100,Dr=8192,Ur=128e3,wn="/memory/notes.md",bn="/AGENTS.md",Ir=6e3,jr=3,kn=2e6,Fr=3,Nr=6;function zr(r,e){let t="ts"in r||"typed"in r||"runUsage"in r,n=e&&r.role==="assistant"&&r.reasoning_content!==void 0;if(!t&&!n)return r;let{ts:s,typed:o,runUsage:i,...a}=r;return n&&delete a.reasoning_content,a}function Wr(r){let e=c=>c.role==="tool"&&Array.isArray(c.content)&&c.content.some(u=>u.type!=="text");if(!r.some(e))return r;let t=[],n=-1,s=!1;r.forEach((c,u)=>{if(c.role!=="tool"){n=-1;return}n<0&&(n=u,s=!1),!s&&e(c)&&(t.push(n),s=!0)});let o=t.length>xn?t[t.length-xn]:0,i=[],a=[],l=()=>{a.length&&i.push({role:"user",content:a}),a=[]};for(let[c,u]of r.entries()){if(u.role!=="tool"&&l(),e(u)){let d=u.content,p=d.filter(m=>m.type!=="text"),h=d.filter(m=>m.type==="text").map(m=>m.text).join(`
264
+ `),f=`${p.length} attachment${p.length===1?"":"s"}`;if(c<o){i.push({...u,content:`${h}${h?`
265
+ `:""}[${f} no longer shown; call the tool again to see the current state]`});continue}i.push({...u,content:`${h}${h?`
266
+ `:""}[${f} follow${p.length===1?"s":""} in the next message]`}),a.push({type:"text",text:`Attachments from tool call ${u.tool_call_id??""}:`.trim()},...p);continue}i.push(u)}return l(),i}var xn=2,vn={image:"image_url",video:"video_url",audio:"audio_url"},Sn={image:"picture",video:"video",audio:"audio clip"};function Br(r,e,t){let n=Object.keys(vn).filter(o=>e[o]===!1);if(!n.length)return r;let s=o=>n.find(i=>vn[i]===o.type);return r.map(o=>{if(!Array.isArray(o.content)||!o.content.some(a=>s(a)))return o;let i=o.content.map(a=>{let l=s(a);return l?{type:"text",text:`[A ${Sn[l]} was attached here; the model in use${t?` (${t})`:""} does not take ${Sn[l]}s, so it is not shown. Say so if it matters.]`}:a});return{...o,content:i}})}var It=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),_e=()=>({runId:"",reason:"aborted",text:"",usage:It()}),pe="Skipped: the user stopped the run.",qr=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),Tn=()=>new q(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function ht(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(e.reason??new Error("aborted"))):new Promise((t,n)=>{let s=()=>n(e.reason??new Error("aborted"));e.addEventListener("abort",s,{once:!0}),r.then(o=>{e.removeEventListener("abort",s),t(o)},o=>{e.removeEventListener("abort",s),n(o)})})}var fe=class{constructor(e,t={}){y(this,"id");y(this,"provider");y(this,"ui");y(this,"workspace");y(this,"tools");y(this,"opts");y(this,"web");y(this,"compactSummaries");y(this,"compactThresholds");y(this,"webCache",null);y(this,"history",[]);y(this,"committed",0);y(this,"droppedTurns",0);y(this,"_usage",It());y(this,"handlers",new Map);y(this,"anyHandlers",new Set);y(this,"queue",[]);y(this,"current",null);y(this,"chain",Promise.resolve());y(this,"pendingSkills",[]);y(this,"catalogue",null);y(this,"loop",{seen:new Set,idle:0,warned:!1});y(this,"turnNow",0);y(this,"loaded");y(this,"createdAt",Date.now());y(this,"fixedTitle");y(this,"_ended",null);y(this,"persist");this.provider=Z(e),this.opts=t,this.compactSummaries=t.compaction!==!1,this.compactThresholds=typeof t.compaction=="object"?{...t.compaction}:{},this.id=t.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=t.ui??ut(),this.workspace=t.workspace??null;let n=[...t.tools??[]],s=this.workspace?de(this.workspace,{enabled:t.readBeforeWrite!==!1}):void 0;if(s){let i=()=>s.retain(this.filesInView());this.on("compaction",i),this.on("rewind",i)}if(this.workspace&&t.fileTools!==!1){let i=Array.isArray(t.fileTools)?new Set(t.fileTools):null;n.push(...st(this.workspace,{guard:s}).filter(a=>!i||i.has(a.name)))}t.askUser!==!1&&n.push(dt()),t.sandbox!==!1&&n.push(ot(typeof t.sandbox=="object"?t.sandbox:{}));let o=new Set;for(let i of n){if(o.has(i.name))throw new Error(`two tools are named "${i.name}"`);o.add(i.name)}if(this.tools=n,this.web=t.webTools??!1,t.serverTools?.length&&(t.tools?.length||this.workspace||t.sandbox!==!1||t.askUser!==!1))throw new Error("serverTools work only for an agent with no tools of its own (tools: [], workspace: null, sandbox: false, askUser: false) \u2014 the gateway runs that loop");this.persist=!!this.workspace&&t.persist!==!1,t.restore?(this.applySession(t.restore),this.loaded=Promise.resolve()):this.persist&&t.id?this.loaded=this.workspace.sessions.get(t.id).then(i=>{i&&this.applySession(i)}).catch(i=>{this.persist=!1,console.warn(`agent: could not load session ${t.id}; it will not be saved over`,i)}):this.loaded=Promise.resolve()}get title(){return this.fixedTitle}setTitle(e){this.fixedTitle=e.trim()||void 0}applySession(e){if(e.v!==1&&e.v!==2)throw new Error("unknown session format");this.history=e.messages.slice(),this.committed=this.history.length,this.droppedTurns=e.droppedTurns??0,this._usage={...e.usage},this.createdAt=e.createdAt??e.savedAt??Date.now(),this._ended=e.ended??null,this.fixedTitle=e.title&&!et(e.title)?e.title:void 0,e.model&&!this.opts.model&&(this.opts.model=e.model,this.catalogue=null)}ready(){return this.loaded}async saveSession(){if(!(!this.persist||!this.workspace))try{await this.workspace.sessions.save(this.export()),this.emit("session_saved",{id:this.id})}catch(e){console.warn("[agent] could not save the session:",e)}}on(e,t){if(e==="*")return this.anyHandlers.add(t),()=>{this.anyHandlers.delete(t)};let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>{this.handlers.get(e)?.delete(t)}}emit(e,t){for(let n of this.handlers.get(e)??[])try{n(t)}catch(s){console.error("[agent] listener for",e,"threw:",s)}for(let n of this.anyHandlers)try{n(e,t)}catch(s){console.error("[agent] listener threw:",s)}}get messages(){return this.history.slice()}get usage(){return{...this._usage}}get lastEnd(){return this._ended}get busy(){return this.current!==null}get model(){return this.opts.model}set model(e){this.opts.model=e,this.catalogue=null}get settings(){let e=this.opts.permissions??"ask",t=this.opts.extra?.reasoning_effort;return{model:this.opts.model,maxTurns:this.opts.maxTurns??yn,maxTokens:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:"auto",permissions:typeof e=="function"?"custom":e,reasoningEffort:typeof t=="string"?t:void 0,compaction:{summarize:this.compactSummaries,...this.compactThresholds}}}configure(e){if(e.compaction){let t=e.compaction;typeof t.summarize=="boolean"&&(this.compactSummaries=t.summarize);for(let n of["reserveTokens","keepRecentTokens"]){if(!(n in t))continue;let s=t[n];typeof s=="number"&&Number.isFinite(s)&&s>0?this.compactThresholds[n]=Math.floor(s):delete this.compactThresholds[n]}}if("model"in e&&(this.model=e.model||void 0),typeof e.webTools=="boolean"&&(this.web=e.webTools),"reasoningEffort"in e){let t={...this.opts.extra??{}};e.reasoningEffort?t.reasoning_effort=e.reasoningEffort:delete t.reasoning_effort,this.opts.extra=t}typeof e.maxTurns=="number"&&e.maxTurns>0&&(this.opts.maxTurns=Math.floor(e.maxTurns)),e.maxTokens!==void 0&&(this.opts.maxTokens=e.maxTokens),e.permissions!==void 0&&(this.opts.permissions=e.permissions)}compactionFor(e){return{summarize:this.compactSummaries,...se(e,this.compactThresholds)}}export(){let e=this.history.slice(0,this.committed),t={v:2,id:this.id,model:this.opts.model,messages:e,usage:{...this._usage},droppedTurns:this.droppedTurns,createdAt:this.createdAt,savedAt:Date.now(),...this._ended?{ended:this._ended}:{}};if(!this.fixedTitle){let n=$e(t);n!==ue&&(this.fixedTitle=n)}return t.title=this.fixedTitle??ue,t}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.fixedTitle=void 0,this._ended=null,this.committed=0,this.droppedTurns=0,this.resetLoop()}useSkill(e){if(!this.workspace)throw new Error("useSkill needs a workspace");this.pendingSkills.push(e)}prompt(e,t={}){let n=this.userMessage(e);return this.current?this.enqueue("followUp",n):this.start(n,t.signal)}steer(e){let t=this.userMessage(e);if(!this.current)return this.start(t);this.queue.push({kind:"steer",message:t}),this.emit("queued",{kind:"steer",message:t})}followUp(e){let t=this.userMessage(e);return this.current?this.enqueue("followUp",t):this.start(t)}get queued(){return this.queue.map(e=>({kind:e.kind,message:e.message}))}dequeue(e){let t=this.queue.find(n=>n.message===e);return t?(this.queue=this.queue.filter(n=>n!==t),t.resolve?.(_e()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let t of e)t.resolve?.(_e())}async abort(){this.clearQueue();let e=this.current;e&&(e.controller.abort(),await e.promise.catch(()=>{}))}enqueue(e,t){return new Promise(n=>{this.queue.push({kind:e,message:t,resolve:n}),this.emit("queued",{kind:e,message:t})})}userMessage(e){let t=typeof e=="string"?[{type:"text",text:e}]:e.slice();return{role:"user",content:t.length===1&&t[0].type==="text"?t[0].text:t,ts:Date.now()}}async rewind(e){if(await this.loaded,this.current)throw new Error("cannot rewind while a run is active; abort() first");if(!Number.isInteger(e)||e<0||e>this.history.length)throw new Error(`no message at ${e}`);this.clearQueue(),this.history=this.history.slice(0,e),this.committed=this.history.length,this._ended=null,this.resetLoop(),await this.saveSession(),this.emit("rewind",{index:e})}async remove(e,t=this.history.length){if(await this.loaded,this.current)throw new Error("Cannot delete messages while a run is active; abort() first");if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t>this.history.length||e>=t)throw new Error(`No messages ${e}\u2013${t}`);this.clearQueue(),this.history.splice(e,t-e),this.committed=this.history.length,this._ended=null,this.resetLoop(),await this.saveSession(),this.emit("rewind",{index:e})}async clear(){await this.loaded,await this.abort(),this.reset(),this._usage=It(),await this.saveSession(),this.emit("rewind",{index:0})}async continue(){if(await this.loaded,this.current)throw new Error("cannot continue while a run is active");if(!this.history.length)throw new Error("nothing to continue");return this.start(null)}start(e,t){let n=new AbortController;t&&(t.aborted?n.abort():t.addEventListener("abort",()=>n.abort(),{once:!0}));let s=this.chain.then(()=>this.run(e,n)).finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()});return this.current={controller:n,promise:s},this.chain=s.catch(()=>{}),s}drainFollowUps(){let e=this.queue.find(t=>t.kind==="followUp");e&&(this.queue=this.queue.filter(t=>t!==e),this.start(e.message).then(t=>e.resolve?.(t),t=>e.resolve?.({..._e(),reason:"error",error:t instanceof Error?t:new Error(String(t))})))}async run(e,t){await this.loaded;let n=`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,s=t.signal,o="done",i,a="",l=0,c={...this._usage},u=this.history.length;this.applySteering(n);let d=null,p;if(e){try{d=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(k){d=e,p=k instanceof Error?k:new Error(String(k))}this.history.push(d)}this._ended=null,this.emit("run_start",{runId:n,message:d});let h=this.opts.maxTurns??yn,{output:f,input:m}=await this.limits(),b=m,v=se(b,this.compactThresholds),g=0;try{if(p)throw p;for(let k=1;;k++){if(s.aborted){o="aborted";break}if(k>h){o="max_turns";break}this.turnNow=k,this.emit("turn_start",{runId:n,turn:k}),this.applySteering(n);let T=await this.systemPrompt(),C=this.fixedText(T),P=E(this.history,C);if(kt(P,b,v)){let S=this.compactSummaries?await this.compactWith(v,n,s):!1,N=E(this.history,C);if(!S||kt(N,b,v)){let z=this.history.length&&K(this.history[0])!==null?[this.history[0]]:[],J=this.history.slice(z.length),L=ge(J,{budget:b-v.reserveTokens-E(z),keepTurns:this.opts.keepTurns??4,system:C});(L.droppedTurns||L.elidedResults)&&(this.history=[...z,...L.messages],this.droppedTurns+=L.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:n,summary:!1,tokensBefore:N,tokensAfter:E(this.history,C),droppedTurns:L.droppedTurns,elidedResults:L.elidedResults}))}}let R=await this.activeTools(),$={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:T},...this.toWireHistory(await this.mediaSupport())],max_tokens:f};$.model||delete $.model,R.length&&($.tools=R.map(S=>Be(S))),this.opts.serverTools?.length&&($.server_tools=this.opts.serverTools),this.opts.prompt&&($.prompt=this.opts.prompt),this.opts.temperature!==void 0&&($.temperature=this.opts.temperature),this.opts.top_p!==void 0&&($.top_p=this.opts.top_p),this.emit("request",{runId:n,turn:k,params:$});let F=Date.now(),I;try{if(E(this.history,C)>b*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new q(413,"the request is far larger than the model's context");I=await this.callModel($,n,s)}catch(S){if(this.emit("response",{runId:n,turn:k,durationMs:Date.now()-F,error:S instanceof Error?S.message:String(S)}),s.aborted||!De(S))throw S;let N=qt(S);N!==void 0&&N<b&&(b=N,v=se(b,this.compactThresholds));let z=!1;for(;!z&&g<2;)z=await this.squeeze(b,g++,v,C,n,s);if(z){k--;continue}throw new G({cause:this.overflowCause(b,C),used:E(this.history,C),window:b},S instanceof Error?S.message:String(S),Ue(S)??400)}this.emit("response",{runId:n,turn:k,durationMs:Date.now()-F,finishReason:I.finishReason,usage:I.usage,message:I.message}),I.usage&&this.addUsage(I.usage);let A={role:"assistant",content:I.message.content,ts:Date.now()};I.message.tool_calls?.length&&(A.tool_calls=I.message.tool_calls),I.reasoning&&(A.reasoning_content=I.reasoning),this.history.push(A),typeof A.content=="string"&&A.content&&(a=A.content);let O=I.finishReason==="length";this.emit("message_end",{runId:n,message:A,truncated:O}),this.emit("turn_end",{runId:n,turn:k,usage:I.usage});let B=A.tool_calls??[];if(!B.length){if(this.committed=this.history.length,await this.saveSession(),O&&this.balanceLimited(I.usage,f)){o="error",i=Tn();break}if(!s.aborted&&this.queue.some(S=>S.kind==="steer"))continue;break}let ne=await this.runBatch(B,n,s,O);if(this.committed=this.history.length,await this.saveSession(),s.aborted){o="aborted";break}if(!O&&xe(A.content).trim()&&B.every(S=>this.tools.find(N=>N.name===S.function.name)?.endsRun)){if(this.queue.some(S=>S.kind==="steer"))continue;break}if(O){if(l++,this.balanceLimited(I.usage,f)){o="error",i=Tn();break}if(l>=2){o="error",i=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let H=this.checkLoop(ne);if(H==="stop"){o="error",i=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}H==="warn"&&this.history.push({role:"user",content:"[environment] The last rounds of tool calls brought nothing new: the same results, the same errors, or parts of files you had already read. Do not repeat them. Use what you have already read (it is above), read only what is still missing, take a different approach, or explain the blocker and finish."})}}catch(k){s.aborted?o="aborted":(o="error",i=k instanceof Error?k:new Error(String(k)))}o==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(u,c),this.committed=this.history.length,this.resetLoop();let w=i instanceof G?{code:i.code,overflow:i.overflow}:{};this._ended=o==="done"?null:{reason:o,...i?{error:i.message}:{},...w,at:Date.now()},await this.saveSession();let M={runId:n,reason:o,text:a,usage:this.usage,...i?{error:i}:{}};return this.emit("run_end",M),M}applySteering(e){let t=this.queue.filter(n=>n.kind==="steer").map(n=>n.message);t.length&&(this.queue=this.queue.filter(n=>n.kind!=="steer"),this.history.push(...t),this.loop.idle=0,this.loop.warned=!1,this.emit("steered",{runId:e,messages:t}))}toWireHistory(e={}){let t=-1;for(let n=this.history.length-1;n>=0;n--)if(this.history[n].role==="user"){t=n;break}return Br(Wr(this.history.map((n,s)=>zr(n,s<t))),e,this.opts.model)}async mediaSupport(){let[e,t,n]=await Promise.all([this.accepts("image"),this.accepts("video"),this.accepts("audio")]);return{image:e,video:t,audio:n}}get webTools(){return this.webToolsAvailable&&(typeof this.web=="function"?!!this.web():this.web)}get webToolsAvailable(){return!!this.provider.platformTools}async activeTools(){let e=this.tools;if(e.some(t=>t.vision)){let t=await this.accepts("image");e=e.filter(n=>!n.vision||t===!0)}if(this.webTools){let t=await this.loadWeb(),n=new Set(e.map(o=>o.name)),s=t.filter(o=>!n.has(o.name));s.length&&(e=[...e,...s])}return e}loadWeb(){let e=this.provider.platformTools;return e?(this.webCache??(this.webCache=at(e,{onCost:t=>this.addToolCost(t)}).catch(t=>(this.webCache=null,console.warn("[agent] could not load the web tools:",t),[]))),this.webCache):Promise.resolve([])}async systemPrompt(){let e=this.workspace,t=async(s,o)=>{if(e)try{let i=await e.readText(s);return i.length>o?i.slice(i.length-o):i}catch{return}},n=await this.activeTools();return Ie({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:n,workspaceDescription:e&&n.some(s=>qr.has(s.name))?e.describe():void 0,skills:e?await e.skills():[],hasSandbox:n.some(s=>s.name==="run_js"),hasAskUser:n.some(s=>s.name==="ask_user"),canWrite:n.some(s=>s.name==="write_file"||s.name==="edit_file"),agentsMd:this.opts.instructionsFile===!1?void 0:await t(this.opts.instructionsFile??bn,2e4),agentsPath:this.opts.instructionsFile||bn,memory:this.opts.memoryFile===!1?void 0:await t(this.opts.memoryFile??wn,Ir),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??wn,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async t=>{let n=await this.contextTokens(),s=this.squeezed(se(n,this.compactThresholds)),o=await this.compactWith(s,void 0,t,e);return o&&await this.saveSession(),o})}summarize(e){return this.exclusive("summarize",async t=>{let n=this.history.filter(l=>l!==e),s=n[0]?K(n[0]):null,o=s===null?n:n.slice(1);if(!o.length)return s;let i=await this.contextTokens(),a=se(i,this.compactThresholds);this.emit("compaction_start",{});try{return await this.writeSummary({toSummarize:o,previousSummary:s??void 0,kept:[]},a,void 0,t)}catch(l){if(t.aborted)throw l;return console.warn("[agent] summary failed:",l),null}})}async seed(e){if(await this.loaded,this.current)throw new Error("cannot seed while a run is active");if(this.history.length)throw new Error("seed needs an empty conversation");this.history=[ye(e)],this.committed=1,this._ended=null,await this.saveSession()}exclusive(e,t){if(this.current)return Promise.reject(new Error(`cannot ${e} while a run is active`));let n=new AbortController,s=this.chain.then(async()=>(await this.loaded,t(n.signal))),o=s.then(()=>({..._e(),reason:"done"}),()=>_e());return this.current={controller:n,promise:o},this.chain=o,o.finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()}),s}squeezed(e){let t=this.history,n=t.length-1;for(;n>0&&!(t[n].role==="user"&&K(t[n])===null);)n--;let s=n>0?t.slice(n).reduce((o,i)=>o+E([i]),0):Math.floor(E(t)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,t,n,s,o,i){let a=E(this.history,s);t===0&&this.compactSummaries&&await this.compactWith(this.squeezed(n),o,i);let l=this.history.length&&K(this.history[0])!==null?[this.history[0]]:[],c=this.history.slice(l.length),u=Math.floor(e*(t===0?.7:.4))-E(l),d=ge(c,{budget:u,keepTurns:1,system:s,keepResults:t===0?3:0});return(d.droppedTurns||d.elidedResults)&&(this.history=[...l,...d.messages],this.droppedTurns+=d.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:o,summary:!1,tokensBefore:a,tokensAfter:E(this.history,s),droppedTurns:d.droppedTurns,elidedResults:d.elidedResults})),E(this.history,s)<a}overflowCause(e,t){let n=this.tools.length?E([],JSON.stringify(this.tools.map(l=>Be(l)))):0,s=[...this.history].reverse().find(l=>l.role==="user"&&K(l)===null),o=s?E([s]):0,i=E(this.history)-o,a=Math.max(n,o,i);return a*2<e?"model":a===o?(Array.isArray(s.content)?s.content.length>1:/(^|\n)\[attachments\]/.test(String(s.content??"")))?"attachments":"message":a===n?"tools":"history"}async writeSummary(e,t,n,s){if(typeof this.opts.compaction=="function")return this.opts.compaction(e,this);let o=await this.limits(),i=Math.min(o.output,Math.max(1024,Math.floor(t.reserveTokens*.8))),a=Math.max(6e3,(o.input-i-1500)*3),l=e.previousSummary;for(let c of Ne(we(e.toSummarize),a)){let u={model:this.opts.model??"",messages:Jt(c,l,e.focus),max_tokens:i};u.model||delete u.model;let d={runId:n??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...d,params:u}),s.throwIfAborted();let p=Date.now(),h;try{h=this.provider.complete?await this.provider.complete(u,{signal:s}):await be((m,b)=>this.provider.stream(m,b),u,{signal:s}).then(m=>({choices:[{message:{...m.message,content:typeof m.message.content=="string"?m.message.content:null},finish_reason:m.finishReason}],usage:m.usage}))}catch(m){throw this.emit("response",{...d,durationMs:Date.now()-p,error:m instanceof Error?m.message:String(m)}),m}h.usage&&this.addUsage(h.usage);let f=h.choices[0];if(this.emit("response",{...d,durationMs:Date.now()-p,finishReason:f?.finish_reason??void 0,usage:h.usage??void 0,message:f?.message}),!f||f.finish_reason==="length")throw new Error("the summary is incomplete");if(f.message.tool_calls?.length)throw new Error("the summariser attempted to call a tool");if(l=(f.message.content??"").trim(),!l)throw new Error("empty summary")}return l}async compactWith(e,t,n,s){let o=Fe(this.history,e.keepRecentTokens);if(!o)return!1;s?.trim()&&(o.focus=s.trim()),this.emit("compaction_start",{runId:t});let i=E(this.history),a;try{a=await this.writeSummary(o,e,t,n)}catch(l){if(n.aborted)throw l;return console.warn("[agent] compaction summary failed, falling back to trimming:",l),!1}return this.history=[ye(a),...o.kept],this.committed=this.history.length,this.emit("compaction",{runId:t,summary:!0,tokensBefore:i,tokensAfter:E(this.history),droppedTurns:0,elidedResults:0}),!0}async expandSlashes(e){if(!this.workspace)return e;let t=Array.isArray(e.content)?e.content:null,n=t?.[0],s=typeof e.content=="string"?e.content:n?.type==="text"?n.text:"";if(!s.startsWith("/"))return e;let o=await ze(this.workspace,s);if(o===s)return e;let i=t?[{type:"text",text:o},...t.slice(1)]:o;return{...e,content:i,typed:s}}async callModel(e,t,n){let s="",o="",i=!1;for(let a=1;;a++){s="",o="",n.throwIfAborted();try{return await be((l,c)=>this.provider.stream(l,c),e,{signal:n,onText:(l,c)=>{i=!0,s=c,this.emit("text_delta",{runId:t,delta:l,text:c})},onReasoning:(l,c)=>{i=!0,o=c,this.emit("reasoning_delta",{runId:t,delta:l,text:c})},onToolCall:(l,c)=>{i=!0,this.emit("tool_call_delta",{runId:t,index:l.index,id:l.id,name:l.name,delta:c,arguments:l.arguments})}})}catch(l){if(n.aborted||a>=jr||!Kr(l))throw l;let c=Hr(l,a);i&&this.emit("message_reset",{runId:t,reason:l.message}),i=!1,await Jr(c,n)}}}async runBatch(e,t,n,s){let o=a=>this.runTool(a,t,n,s),i=this.opts.parallelTools?await Promise.all(e.map(a=>o(a))):await(async()=>{let a=[],l=!1;for(let c of e){if(l){a.push(this.skipTool(c,t,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}a.push(await o(c)),this.queue.some(u=>u.kind==="steer")&&(l=!0)}return a})();for(let a of i)this.history.push(a.message);return i}skipTool(e,t,n){let s=e.id??"",o=e.function.name;return this.emit("tool_start",{runId:t,id:s,name:o,args:e.function.arguments}),this.emit("tool_end",{runId:t,id:s,name:o,status:"skipped",result:n,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:n},key:"",changed:!1,progress:!0,status:"skipped"}}async runTool(e,t,n,s,o){let i=e.id??"",a=o?{parentId:o}:{},l=e.function.name,c=Date.now(),u,d,p=(g,w,M)=>{let k=xe(w);return this.emit("tool_end",{runId:t,id:i,name:l,status:g,result:o?We(k,32e3).text:k,details:M,durationMs:Date.now()-c,...a,...typeof w=="string"?{}:{content:w}}),{status:g,details:M,message:{role:"tool",tool_call_id:i,content:w},key:d?.readOnly?`${l}|${g}|${k.slice(0,4e3)}`:`${l}|${e.function.arguments.slice(0,4e3)}|${g}|${k.slice(0,2e3)}`,changed:g==="ok"&&!!d&&!d.readOnly,progress:g==="declined"||g==="skipped"?!0:g==="ok"?u:void 0}};if(n.aborted)return p("skipped",pe);if(s)return this.emit("tool_start",{runId:t,id:i,name:l,args:e.function.arguments,...a}),p("error",`Tool call "${l}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);let h=await this.activeTools();d=h.find(g=>g.name===l);let f;try{f=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:t,id:i,name:l,args:e.function.arguments,...a}),p("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:t,id:i,name:l,args:f,...a}),!d)return p("error",`Error: there is no tool named "${l}". Available tools: ${h.map(g=>g.name).join(", ")}.`);if(f===null||typeof f!="object"||Array.isArray(f))return p("error","Error: the arguments must be a JSON object.");let m=it(d.parameters,f);if(m.length)return p("error",`Error: invalid arguments for ${l}:
267
267
  - ${m.join(`
268
268
  - `)}
269
- Fix the call and try again.`);if(d.validate){let g;try{g=await ut(Promise.resolve(d.validate(p)),n)}catch(w){g=w instanceof Error?w.message:String(w)}if(n.aborted)return f("skipped",fe);if(g)return f("error",g.startsWith("Error:")?g:`Error: ${g}`)}try{let g=await ut(Promise.resolve(this.opts.onToolCall?.({id:i,name:l,args:p,tool:d})),n);if(g&&g.block)return f("blocked",`${g.reason??"This action was not allowed."} Do not retry it another way; say what you would have done.`);if(!await ut(this.permitted(d,p,n),n))return f("declined","The user declined this action. Do not retry it another way; say what you would have done.")}catch(g){return n.aborted?f("skipped",fe):f("error",`Error: ${g.message}`)}if(n.aborted)return f("skipped",fe);let b=()=>{try{let g=d.whenStopped?.(p);if(g!==void 0){let w=ke(g,o?kn:d.maxResultChars);return f("skipped",w.content,w.details)}}catch{}return f("skipped",fe)},S=0;try{let g=await ut(Promise.resolve(d.execute(p,{signal:n,ui:this.ui,workspace:this.workspace,agent:this,callId:i,parentId:o,update:_=>this.emit("tool_update",{runId:t,id:i,name:l,content:_,...a}),progress:_=>{u=_},callTool:async(_,k,T)=>{let C=await this.runTool({id:`${i}.${++S}`,type:"function",function:{name:_,arguments:JSON.stringify(k??{})}},t,T?.signal??n,!1,i);return{status:C.status,text:xe(C.message.content),details:C.details}}})),n);if(n.aborted)return b();let w=ke(g,o?kn:d.maxResultChars);return f("ok",w.content,w.details)}catch(g){if(n.aborted)return b();let w=g instanceof Error?g.message:String(g);return f("error",w.startsWith("Error:")?w:`Error: ${w}`)}}async permitted(e,t,n){let s=this.opts.permissions??"ask";if(typeof s=="function")return s({name:e.name,args:t,tool:e});if(s==="auto")return!0;let o=!1;if(e.confirm?o=await e.confirm(t):e.destructive&&(o=`Allow ${e.name}?`),o===!1)return!0;let{title:i,message:a,always:l,ok:c,body:u}=typeof o=="string"?{title:o,message:void 0,always:void 0,ok:void 0,body:void 0}:o;return this.ui.confirm(i,a,{danger:!!e.destructive,signal:n,always:l,permission:!0,...c?{ok:c}:{},...u?{body:u}:{}})}closeOpenToolCalls(){if(!this.history[this.history.length-1])return;let t=this.history.length-1;for(;t>=0&&this.history[t].role==="tool";)t--;let n=this.history[t];if(!n||n.role!=="assistant"||!n.tool_calls?.length)return;let s=new Set(this.history.slice(t+1).map(o=>o.tool_call_id));for(let o of n.tool_calls)o.id&&!s.has(o.id)&&this.history.push({role:"tool",tool_call_id:o.id,content:fe})}checkLoop(e){let t=this.opts.loopGuard;if(t===!1)return"ok";let n=t?.warn??Fr,s=t?.stop??Nr,o=this.loop,i=e.map(c=>c.key!==""&&!o.seen.has(c.key)),a=e.some((c,u)=>c.changed&&i[u]);a&&o.seen.clear();for(let c of e)c.key&&o.seen.add(c.key);let l=a||e.some((c,u)=>c.progress??i[u]);return o.seen.size>512&&o.seen.delete(o.seen.values().next().value),l?(o.idle=0,o.warned=!1,"ok"):(o.idle++,o.idle>=s?"stop":o.idle>=n&&!o.warned?(o.warned=!0,"warn"):"ok")}resetLoop(){this.loop={seen:new Set,idle:0,warned:!1}}balanceLimited(e,t){let n=e?.completion_tokens;return typeof n=="number"&&n>0&&n<t*.9}markRunUsage(e,t){let n=this._usage;if(n.calls!==t.calls)for(let s=this.history.length-1;s>=Math.min(e,this.history.length);s--){let o=this.history[s];if(o.role==="assistant"){o.runUsage={total_cost:Ut(n.total_cost-t.total_cost),prompt_tokens:n.prompt_tokens-t.prompt_tokens,completion_tokens:n.completion_tokens-t.completion_tokens,calls:n.calls-t.calls};return}}}addToolCost(e){this._usage.total_cost=Ut(this._usage.total_cost+e)}addUsage(e){this._usage.total_cost=Ut(this._usage.total_cost+(e.total_cost??0)),this._usage.prompt_tokens+=e.prompt_tokens??0,this._usage.completion_tokens+=e.completion_tokens??0,this._usage.calls++}async context(){let[e,t]=await Promise.all([this.contextTokens(),this.systemPrompt().catch(()=>"")]);return{used:M(this.history,this.fixedText(t)),window:e}}filesInView(){let e=new Set(this.history.filter(n=>n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("[result elided")).map(n=>n.tool_call_id)),t=[];for(let n of this.history)for(let s of n.role==="assistant"?n.tool_calls??[]:[]){if(e.has(s.id))continue;let o;try{o=JSON.parse(s.function.arguments)}catch{continue}let i=["read_file","write_file","edit_file"].includes(s.function.name)?o.path:["move_file","copy_file"].includes(s.function.name)?o.to:void 0;typeof i=="string"&&t.push(x(i))}return t}fixedText(e){return this.tools.length?`${e}
269
+ Fix the call and try again.`);if(d.validate){let g;try{g=await ht(Promise.resolve(d.validate(f)),n)}catch(w){g=w instanceof Error?w.message:String(w)}if(n.aborted)return p("skipped",pe);if(g)return p("error",g.startsWith("Error:")?g:`Error: ${g}`)}try{let g=await ht(Promise.resolve(this.opts.onToolCall?.({id:i,name:l,args:f,tool:d})),n);if(g&&g.block)return p("blocked",`${g.reason??"This action was not allowed."} Do not retry it another way; say what you would have done.`);if(!await ht(this.permitted(d,f,n),n))return p("declined","The user declined this action. Do not retry it another way; say what you would have done.")}catch(g){return n.aborted?p("skipped",pe):p("error",`Error: ${g.message}`)}if(n.aborted)return p("skipped",pe);let b=()=>{try{let g=d.whenStopped?.(f);if(g!==void 0){let w=ke(g,o?kn:d.maxResultChars);return p("skipped",w.content,w.details)}}catch{}return p("skipped",pe)},v=0;try{let g=await ht(Promise.resolve(d.execute(f,{signal:n,ui:this.ui,workspace:this.workspace,agent:this,callId:i,parentId:o,update:M=>this.emit("tool_update",{runId:t,id:i,name:l,content:M,...a}),progress:M=>{u=M},callTool:async(M,k,T)=>{let C=await this.runTool({id:`${i}.${++v}`,type:"function",function:{name:M,arguments:JSON.stringify(k??{})}},t,T?.signal??n,!1,i);return{status:C.status,text:xe(C.message.content),details:C.details}}})),n);if(n.aborted)return b();let w=ke(g,o?kn:d.maxResultChars);return p("ok",w.content,w.details)}catch(g){if(n.aborted)return b();let w=g instanceof Error?g.message:String(g);return p("error",w.startsWith("Error:")?w:`Error: ${w}`)}}async permitted(e,t,n){let s=this.opts.permissions??"ask";if(typeof s=="function")return s({name:e.name,args:t,tool:e});if(s==="auto")return!0;let o=!1;if(e.confirm?o=await e.confirm(t):e.destructive&&(o=`Allow ${e.name}?`),o===!1)return!0;let{title:i,message:a,always:l,ok:c,body:u}=typeof o=="string"?{title:o,message:void 0,always:void 0,ok:void 0,body:void 0}:o;return this.ui.confirm(i,a,{danger:!!e.destructive,signal:n,always:l,permission:!0,...c?{ok:c}:{},...u?{body:u}:{}})}closeOpenToolCalls(){if(!this.history[this.history.length-1])return;let t=this.history.length-1;for(;t>=0&&this.history[t].role==="tool";)t--;let n=this.history[t];if(!n||n.role!=="assistant"||!n.tool_calls?.length)return;let s=new Set(this.history.slice(t+1).map(o=>o.tool_call_id));for(let o of n.tool_calls)o.id&&!s.has(o.id)&&this.history.push({role:"tool",tool_call_id:o.id,content:pe})}checkLoop(e){let t=this.opts.loopGuard;if(t===!1)return"ok";let n=t?.warn??Fr,s=t?.stop??Nr,o=this.loop,i=e.map(c=>c.key!==""&&!o.seen.has(c.key)),a=e.some((c,u)=>c.changed&&i[u]);a&&o.seen.clear();for(let c of e)c.key&&o.seen.add(c.key);let l=a||e.some((c,u)=>c.progress??i[u]);return o.seen.size>512&&o.seen.delete(o.seen.values().next().value),l?(o.idle=0,o.warned=!1,"ok"):(o.idle++,o.idle>=s?"stop":o.idle>=n&&!o.warned?(o.warned=!0,"warn"):"ok")}resetLoop(){this.loop={seen:new Set,idle:0,warned:!1}}balanceLimited(e,t){let n=e?.completion_tokens;return typeof n=="number"&&n>0&&n<t*.9}markRunUsage(e,t){let n=this._usage;if(n.calls!==t.calls)for(let s=this.history.length-1;s>=Math.min(e,this.history.length);s--){let o=this.history[s];if(o.role==="assistant"){o.runUsage={total_cost:Ut(n.total_cost-t.total_cost),prompt_tokens:n.prompt_tokens-t.prompt_tokens,completion_tokens:n.completion_tokens-t.completion_tokens,calls:n.calls-t.calls};return}}}addToolCost(e){this._usage.total_cost=Ut(this._usage.total_cost+e)}addUsage(e){this._usage.total_cost=Ut(this._usage.total_cost+(e.total_cost??0)),this._usage.prompt_tokens+=e.prompt_tokens??0,this._usage.completion_tokens+=e.completion_tokens??0,this._usage.calls++}async context(){let[e,t]=await Promise.all([this.contextTokens(),this.systemPrompt().catch(()=>"")]);return{used:E(this.history,this.fixedText(t)),window:e}}filesInView(){let e=new Set(this.history.filter(n=>n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("[result elided")).map(n=>n.tool_call_id)),t=[];for(let n of this.history)for(let s of n.role==="assistant"?n.tool_calls??[]:[]){if(e.has(s.id))continue;let o;try{o=JSON.parse(s.function.arguments)}catch{continue}let i=["read_file","write_file","edit_file"].includes(s.function.name)?o.path:["move_file","copy_file"].includes(s.function.name)?o.to:void 0;typeof i=="string"&&t.push(x(i))}return t}fixedText(e){return this.tools.length?`${e}
270
270
  ${JSON.stringify(this.tools.map(t=>Be(t)))}`:e}async limits(){let e=await this.catalogueLimits(),t=typeof(await this.modelInfo())?.max_input_tokens=="number",n=this.opts.maxInputTokens;return{input:typeof n=="number"?t?Math.min(n,e.input):n:e.input,output:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:e.output}}contextTokens(){return this.limits().then(e=>e.input)}async catalogueLimits(){let e=await this.modelInfo(),t=typeof e?.max_input_tokens=="number"&&e.max_input_tokens>0?e.max_input_tokens:Ur,n=typeof e?.max_tokens=="number"&&e.max_tokens>0?e.max_tokens:Dr;return{input:t,output:n}}modelInfo(){return this.catalogue||(this.catalogue=(async()=>{try{if(!this.provider.models)return;let e=await this.provider.models(),t=this.opts.model?.toLowerCase();return t?e.find(n=>n.id.toLowerCase()===t):e.find(n=>n.is_default&&(!n.capability||n.capability==="text"||n.capability==="vision"))}catch{queueMicrotask(()=>{this.catalogue=null});return}})()),this.catalogue}async accepts(e){return e==="image"&&typeof this.opts.vision=="boolean"?this.opts.vision:Le(await this.modelInfo(),e)}async withSkillPrefaces(e){if(!this.pendingSkills.length||!this.workspace)return e;let t=this.pendingSkills.splice(0),n=[];for(let i of t){let{skill:a,body:l}=await this.workspace.skillBody(i);n.push({type:"text",text:`[The user invoked the skill "${a.name}" (${a.path}). Follow these instructions for the request below.]
271
271
 
272
- ${l}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content??[],o=e.typed??(typeof e.content=="string"?e.content:void 0);return{...e,role:"user",content:[...n,...s],...o!==void 0?{typed:o}:{}}}estimateContext(){return M(this.history)}contextWindow(){return this.contextTokens()}};function Kr(r){let e=Ue(r);return e!==void 0?e===408||e===429||e>=500||e===0:r instanceof Error?/network|fetch failed|ECONNRESET|socket|stream ended before/i.test(r.message)||r.name==="TypeError":!1}function Hr(r,e){let t=r&&typeof r=="object"?r.retryAfter:void 0;return typeof t=="number"&&t>0?Math.min(3e4,t*1e3):Math.min(8e3,800*2**(e-1))+Math.random()*300}function Jr(r,e){return new Promise((t,n)=>{let s=()=>{clearTimeout(o),n(e.reason??new Error("aborted"))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.addEventListener("abort",s,{once:!0})})}function Ut(r){return Math.round(r*1e6)/1e6}function Cn(r){let e=()=>{try{let s=JSON.parse(localStorage.getItem(r)||"[]");return Array.isArray(s)?s:[]}catch{return[]}},t=s=>{try{s.length?localStorage.setItem(r,JSON.stringify(s)):localStorage.removeItem(r)}catch{}},n=s=>Gr(`${r}:write`,async()=>{t(s(e()))});return{list:async()=>e(),get:async s=>e().find(o=>o.id===s),put:s=>n(o=>{let i=o.findIndex(a=>a.id===s.id);return i>=0?o[i]=s:o.push(s),o}),delete:s=>n(o=>o.filter(i=>i.id!==s)),subscribe(s){if(typeof window>"u")return()=>{};let o=i=>{i.key===r&&s()};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)}}}function $n(r=[]){let e=new Map(r.map(t=>[t.id,structuredClone(t)]));return{list:async()=>[...e.values()].map(t=>structuredClone(t)),get:async t=>{let n=e.get(t);return n&&structuredClone(n)},put:async t=>{e.set(t.id,structuredClone(t))},delete:async t=>{e.delete(t)}}}var _n=()=>typeof navigator<"u"?navigator.locks:void 0;function Gr(r,e){let t=_n();return t?t.request(r,{},e):e()}async function Zr(r,e){let t=_n();if(!t)return await e(),!0;let n=!1;return await t.request(r,{ifAvailable:!0},async s=>{s&&(n=!0,await e())}),n}var Mn=/^([01]?\d|2[0-3]):([0-5]\d)$/;function Ee(r){let e=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(r.trim());return e?new Date(+e[1],+e[2]-1,+e[3],+e[4],+e[5],+(e[6]??0)).getTime():/[zZ]|[+-]\d{2}:?\d{2}$/.test(r)?Date.parse(r):NaN}function ee(r){let e=new Date(r),t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}var Xr={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6,jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function Me(r){let e=r.trim().split(/\s+/);if(e.length!==5)throw new Error(`cron needs five fields (minute hour day month weekday), got "${r}"`);let t=(n,s,o,i)=>{let a=new Set;for(let l of n.toLowerCase().split(",")){let[c,u]=l.split("/"),d=u===void 0?1:Number(u);if(!Number.isInteger(d)||d<1)throw new Error(`cron ${i}: bad step in "${l}"`);let f=m=>{let b=Xr[m]??Number(m);if(!Number.isInteger(b))throw new Error(`cron ${i}: "${m}" is not a number`);return b},h,p;if(c==="*")h=s,p=o;else if(c.includes("-")){let[m,b]=c.split("-");h=f(m),p=f(b)}else h=f(c),p=u===void 0?h:o;if(i==="weekday"&&(h===7&&(h=0),p===7&&h!==0&&(p=6,a.add(0))),h<s||p>o||h>p)throw new Error(`cron ${i}: "${l}" is outside ${s}-${o}`);for(let m=h;m<=p;m+=d)a.add(m)}return a};return{min:t(e[0],0,59,"minute"),hour:t(e[1],0,23,"hour"),dom:t(e[2],1,31,"day"),mon:t(e[3],1,12,"month"),dow:t(e[4],0,7,"weekday"),domAny:e[2]==="*",dowAny:e[4]==="*"}}function dt(r,e){let t=new Date(e);t.setSeconds(0,0),t.setMinutes(t.getMinutes()+1);let n=[...r.hour].sort((o,i)=>o-i),s=[...r.min].sort((o,i)=>o-i);for(let o=0;o<366*5;o++){let i=new Date(t.getFullYear(),t.getMonth(),t.getDate()+o);if(!r.mon.has(i.getMonth()+1))continue;let a=r.dom.has(i.getDate()),l=r.dow.has(i.getDay());if(r.domAny&&r.dowAny||(r.domAny?l:r.dowAny?a:a||l))for(let c of n)for(let u of s){let d=new Date(i.getFullYear(),i.getMonth(),i.getDate(),c,u).getTime();if(d>=t.getTime())return d}}return null}function ft(r,e=1){switch(r?.type){case"once":return Number.isFinite(Ee(r.at))?void 0:`"at" must be a local time like 2026-11-28 09:00, got "${r.at}"`;case"every":return Number.isFinite(r.minutes)&&r.minutes>=e?void 0:`"minutes" must be at least ${e}`;case"daily":return Mn.test(r.time??"")?r.days&&(!r.days.length||r.days.some(t=>!Number.isInteger(t)||t<0||t>6))?'"days" must be weekday numbers 0 (Sunday) to 6':void 0:`"time" must be HH:mm, got "${r.time}"`;case"cron":{try{let t=Me(r.cron);if(dt(t,Date.now())===null)return"this cron never runs"}catch(t){return t.message}if(e>1){let t=Me(r.cron),n=dt(t,Date.now()),s=dt(t,n);if(s!==null&&s-n<e*6e4)return`runs more often than every ${e} minutes`}return}default:return'"type" must be once, every, daily or cron'}}function Re(r,e,t=e){switch(r.type){case"once":{let n=Ee(r.at);return Number.isFinite(n)&&n>e?n:null}case"every":{let n=r.minutes*6e4,s=t+n;return s<=e&&(s=e+n),s}case"daily":{let n=Mn.exec(r.time);if(!n)return null;let s=new Date(e);for(let o=0;o<8;o++){let i=new Date(s.getFullYear(),s.getMonth(),s.getDate()+o,+n[1],+n[2]);if(i.getTime()>e&&(!r.days?.length||r.days.includes(i.getDay())))return i.getTime()}return null}case"cron":try{return dt(Me(r.cron),e)}catch{return null}}}var Yr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Vr=["\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"];function Ft(r,e="en"){let t=e==="zh";switch(r.type){case"once":{let n=Ee(r.at);return(t?"\u4E00\u6B21 \xB7 ":"Once \xB7 ")+(Number.isFinite(n)?ee(n):r.at)}case"every":{let n=r.minutes,s=n%1440===0?t?`${n/1440} \u5929`:`${n/1440} d`:n%60===0?t?`${n/60} \u5C0F\u65F6`:`${n/60} h`:t?`${n} \u5206\u949F`:`${n} min`;return t?`\u6BCF ${s}`:`Every ${s}`}case"daily":{let n=[...new Set(r.days??[])].sort((s,o)=>s-o);return!n.length||n.length===7?(t?"\u6BCF\u5929 ":"Daily ")+r.time:n.join()==="1,2,3,4,5"?(t?"\u5DE5\u4F5C\u65E5 ":"Weekdays ")+r.time:n.join()==="0,6"?(t?"\u5468\u672B ":"Weekends ")+r.time:(t?"\u6BCF\u5468"+n.map(s=>Vr[s]).join("\u3001")+" ":n.map(s=>Yr[s]).join(", ")+" ")+r.time}case"cron":return`cron ${r.cron}`}}var Qr=()=>`t_${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`;function Nt(r,e={},t=Date.now()){let n=r.name?.trim(),s=r.prompt?.trim();if(!n)throw new Error("a task needs a name");if(!s)throw new Error("a task needs a prompt");let o=ft(r.schedule,e.minMinutes??5);if(o)throw new Error(o);let i=r.enabled??!0,a=i?Re(r.schedule,t):null;if(i&&a===null)throw new Error("that time has already passed");return{id:Qr(),name:n,prompt:s,schedule:r.schedule,enabled:i,next:a,by:r.by,created:t,updated:t,runs:0}}function zt(r,e,t={},n=Date.now()){let s={...r,updated:n};if(e.name!==void 0){if(!e.name.trim())throw new Error("a task needs a name");s.name=e.name.trim()}if(e.prompt!==void 0){if(!e.prompt.trim())throw new Error("a task needs a prompt");s.prompt=e.prompt.trim()}if(e.schedule){let o=ft(e.schedule,t.minMinutes??5);if(o)throw new Error(o);s.schedule=e.schedule}if(e.enabled!==void 0&&(s.enabled=e.enabled),(e.schedule||e.enabled!==void 0)&&(s.next=s.enabled?Re(s.schedule,n):null,s.enabled&&s.next===null))throw new Error("that time has already passed");return s}var An={type:"object",description:`When it runs, in the user's local time. type "once": at ("YYYY-MM-DD HH:mm") or in_minutes (from now). type "every": minutes. type "daily": time ("HH:mm") and optional days (0 = Sunday \u2026 6 = Saturday; [1,2,3,4,5] for weekdays). type "cron": cron (five fields, local time).`,properties:{type:{type:"string",enum:["once","every","daily","cron"]},at:{type:"string"},in_minutes:{type:"number"},minutes:{type:"number"},time:{type:"string"},days:{type:"array",items:{type:"integer",minimum:0,maximum:6}},cron:{type:"string"}},required:["type"],additionalProperties:!1};function Pn(r,e){switch(r.type){case"once":return{type:"once",at:r.at??(r.in_minutes!==void 0?ee(e+Math.max(1,Math.round(r.in_minutes))*6e4):"")};case"every":return{type:"every",minutes:Math.round(r.minutes??0)};case"daily":return{type:"daily",time:r.time??"",...r.days?.length?{days:r.days}:{}};case"cron":return{type:"cron",cron:r.cron??""}}}function jt(r,e=Date.now()){return{id:r.id,name:r.name,prompt:r.prompt,schedule:Ft(r.schedule),enabled:r.enabled,next:r.next?ee(r.next):null,runs:r.runs,...r.last?{last_run:`${ee(r.last.at)} ${r.last.status}${r.last.note?": "+r.last.note:""}`}:{},...r.next&&r.next<e?{overdue:!0}:{}}}function En(r,e={}){let t=e.now??Date.now,n=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"local"}})(),s=()=>{try{e.onChange?.()}catch{}},o=()=>`Now: ${ee(t())} (${n}).`;return[L({name:"schedule_list",description:"Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",readOnly:!0,display:{label:()=>"Scheduled tasks"},execute:async()=>{let i=await r.list();return`${o()}
273
- ${i.length?JSON.stringify(i.map(a=>jt(a,t())),null,1):"No scheduled tasks."}`}}),L({name:"schedule_add",description:`Adds a scheduled task: at the set times the agent is given \`prompt\` in a conversation of the task's own and works on it unattended (the user may not be watching; questions wait for them). Runs only while the app is open in a browser; a run missed while it was closed happens once when it is next opened. Repeats at most every ${e.minMinutes??5} minutes. Write the prompt so it stands alone: the run does not see this conversation.`,parameters:{type:"object",properties:{name:{type:"string",description:'Short name the user sees, e.g. "Morning news digest".'},prompt:{type:"string",description:"The instruction for each run, complete on its own."},schedule:An,enabled:{type:"boolean",description:"Default true."}},required:["name","prompt","schedule"],additionalProperties:!1},display:{label:i=>`Schedule \u201C${i.name??""}\u201D`},execute:async i=>{let a=await r.list();if(a.length>=(e.maxTasks??20))throw new Error(`there are already ${a.length} tasks, the most allowed; remove one first`);let l=Nt({name:i.name,prompt:i.prompt,schedule:Pn(i.schedule,t()),enabled:i.enabled,by:"agent"},e,t());return await r.put(l),s(),`${o()}
274
- Added: ${JSON.stringify(jt(l,t()))}`}}),L({name:"schedule_update",description:"Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",parameters:{type:"object",properties:{id:{type:"string"},name:{type:"string"},prompt:{type:"string"},schedule:An,enabled:{type:"boolean"}},required:["id"],additionalProperties:!1},display:{label:i=>`Update scheduled task ${i.id??""}`},execute:async i=>{let a=await r.get(i.id);if(!a)throw new Error(`no task with id ${i.id}; schedule_list shows them`);let l=zt(a,{name:i.name,prompt:i.prompt,schedule:i.schedule?Pn(i.schedule,t()):void 0,enabled:i.enabled},e,t());return await r.put(l),s(),`${o()}
275
- Updated: ${JSON.stringify(jt(l,t()))}`}}),L({name:"schedule_remove",description:"Removes a scheduled task (by id). Its conversation stays.",parameters:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},display:{label:i=>`Remove scheduled task ${i.id??""}`},execute:async i=>{let a=await r.get(i.id);if(!a)throw new Error(`no task with id ${i.id}`);return await r.delete(i.id),s(),`Removed \u201C${a.name}\u201D.`}})]}var ht=class{constructor(e){y(this,"opts",e);y(this,"timer",null);y(this,"busy",!1);y(this,"unsub",null);y(this,"running",new Set);y(this,"poke",()=>{this.tick()})}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.opts.interval??2e4),this.unsub=this.opts.store.subscribe?.(()=>this.opts.onChange?.())??null,typeof window<"u"&&window.addEventListener("focus",this.poke),this.tick())}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.unsub?.(),this.unsub=null,typeof window<"u"&&window.removeEventListener("focus",this.poke)}async tick(){if(this.busy||!this.opts.idle())return;let e=(this.opts.now??Date.now)(),t=(await this.opts.store.list()).filter(n=>n.enabled&&n.next!==null&&n.next<=e).sort((n,s)=>n.next-s.next);for(let n of t)if(this.busy||!this.opts.idle()||await this.fire(n.id,!1))return}runNow(e){return this.fire(e,!0)}async fire(e,t){if(this.busy)return!1;this.busy=!0;let n=!1;try{return await Zr(`${this.opts.lockPrefix}:task:${e}`,async()=>{let s=this.opts.store,o=this.opts.now??Date.now,i=await s.get(e),a=o();if(!i||!t&&(!i.enabled||i.next===null||i.next>a))return;let l=i.enabled?Re(i.schedule,a,a):i.next;await s.put({...i,next:i.schedule.type==="once"&&!t?null:l,...i.schedule.type==="once"&&!t?{enabled:!1}:{}}),n=!0,this.running.add(e),this.opts.onChange?.();let c;try{c=await this.opts.run(i)}catch(d){c={status:"error",note:d.message}}this.running.delete(e);let u=await s.get(e);u&&await s.put({...u,runs:u.runs+1,last:{at:a,...c}}),this.opts.onChange?.()}),n}finally{this.busy=!1}}};var Rn="2025-06-18",D=class extends Error{constructor(t,n,s){super(t);y(this,"status",n);y(this,"code",s);this.name="MCPError"}};async function Dn(r,e={}){e.signal?.throwIfAborted();let t=new URL(r);if(t.protocol!=="https:"&&t.protocol!=="http:")throw new D("An MCP endpoint is an http(s) URL.");let n=e.fetch??globalThis.fetch.bind(globalThis),s=e.timeoutMs??6e4,o,i,a=1,l=!1,c=e.signal,u=P=>({...e.headers??{},...P?{"Content-Type":"application/json",Accept:"application/json, text/event-stream"}:{},...e.token?{Authorization:`Bearer ${e.token}`}:{},...o?{"Mcp-Session-Id":o}:{},...i?{"MCP-Protocol-Version":i}:{}}),d=(P,E)=>n(t,{method:"POST",headers:u(!0),body:JSON.stringify(P),signal:E,redirect:"error",credentials:"omit"}),f=P=>{let E=P.method==="ping"?{jsonrpc:"2.0",id:P.id,result:{}}:{jsonrpc:"2.0",id:P.id,error:{code:-32601,message:`${P.method} is not supported by this client`}};d(E,AbortSignal.timeout(s)).then($=>$.body?.cancel()).catch(()=>{})},h=async(P,E,$,F,U=!1)=>{if(l)throw new D("The MCP connection is closed.");let A=a++,R=AbortSignal.timeout(s),B=Ln([R,...$?[$]:[],...c?[c]:[]]),te={jsonrpc:"2.0",id:A,method:P,...E?{params:F?{...E,_meta:{progressToken:A}}:E}:{}},H=()=>{P!=="initialize"&&d({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:"The user stopped it."}},AbortSignal.timeout(5e3)).then(v=>v.body?.cancel()).catch(()=>{})};$?.addEventListener("abort",H,{once:!0});try{let v;try{v=await d(te,B)}catch(j){throw $?.throwIfAborted(),R.aborted?new D(`${P} timed out after ${Math.round(s/1e3)} s.`):new D(`Could not reach the MCP server (${j.message}). Check the address, its CORS settings and your network.`)}if(v.status===404&&o&&!U&&P!=="initialize")return await v.body?.cancel(),o=void 0,await S($),h(P,E,$,F,!0);if(!v.ok)throw await v.body?.cancel(),new D(`The MCP server answered ${P} with HTTP ${v.status}${v.status===401||v.status===403?" (check the token)":""}.`,v.status);let N=v.headers.get("mcp-session-id");N&&(o=N);let z=j=>{if(j.id===A&&(j.result||j.error)){if(j.error)throw new D(`${P}: ${j.error.message}`,void 0,j.error.code);return j.result??{}}if(j.method&&j.id!==void 0)f(j);else if(j.method==="notifications/progress"&&j.params?.progressToken===A&&F){let W=j.params;F(W.message??(W.total?`${W.progress??0} / ${W.total}`:String(W.progress??"")))}};if((v.headers.get("content-type")??"").includes("text/event-stream")&&v.body){for await(let j of me(v.body,B)){let W;try{W=JSON.parse(j)}catch{continue}for(let Un of Array.isArray(W)?W:[W]){let Wt=z(Un);if(Wt)return v.body.cancel().catch(()=>{}),Wt}}throw $?.throwIfAborted(),R.aborted?new D(`${P} timed out after ${Math.round(s/1e3)} s.`):new D(`The MCP server ended the stream without answering ${P}.`)}let O;try{O=await v.json()}catch{throw new D(`The MCP server's answer to ${P} is not JSON.`)}for(let j of Array.isArray(O)?O:[O]){let W=z(j);if(W)return W}throw new D(`The MCP server did not answer ${P}.`)}finally{$?.removeEventListener("abort",H)}},p=async P=>{await(await d({jsonrpc:"2.0",method:P},Ln([AbortSignal.timeout(s),...c?[c]:[]]))).body?.cancel()},m={name:"mcp"},b,S=async P=>{i=void 0;let E=await h("initialize",{protocolVersion:Rn,capabilities:{},clientInfo:{name:e.clientName??"runapps-agent",version:"1"}},P);i=typeof E.protocolVersion=="string"?E.protocolVersion:Rn;let $=E.serverInfo;$?.name&&(m={name:$.name,version:$.version,title:$.title}),typeof E.instructions=="string"&&(b=E.instructions),await p("notifications/initialized")};await S(e.signal);let g=[],w=[],_=On(e.prefix??m.name).slice(0,24)||"mcp",k=e.name||m.title||m.name,T=async P=>{let E=[],$=new Set,F;do{let A=await h("tools/list",F?{cursor:F}:{},P);if(!Array.isArray(A.tools))throw new D("The MCP server's tool list is malformed.");for(let R of A.tools){if(!R||typeof R.name!="string"||!R.name)throw new D("The MCP server listed a tool without a name.");let B=R.inputSchema&&typeof R.inputSchema=="object"?R.inputSchema:{type:"object"};E.push({...R,inputSchema:{type:"object",properties:{},...B}})}if(E.length>(e.maxTools??64))throw new D(`The MCP server has more than ${e.maxTools??64} tools (maxTools).`);if(F=typeof A.nextCursor=="string"&&A.nextCursor?A.nextCursor:void 0,F){if($.has(F))throw new D("The MCP server's tool list repeats a page.");$.add(F)}}while(F);g=E;let U=new Set;return w=E.map(A=>{let R=`${_}__${On(A.name)}`.slice(0,64);for(let v=2;U.has(R);v++)R=`${R.slice(0,60)}_${v}`;U.add(R);let B=A.annotations?.readOnlyHint===!0,te=e.confirm==="never"?!1:e.confirm==="unless-read-only"?!B:!0,H=A.title??A.annotations?.title??A.name;return L({name:R,description:`[${k} \u2014 MCP server] ${H!==A.name?`${H}. `:""}${A.description??""}`.trim().slice(0,4e3),parameters:A.inputSchema,readOnly:B,destructive:A.annotations?.destructiveHint===!0||!B&&te,maxResultChars:e.maxResultChars,confirm:te?v=>({title:`Run ${k} / ${A.name}?`,message:JSON.stringify(v,null,2).slice(0,4e3)}):()=>!1,async execute(v,N){let z;try{z=await h("tools/call",{name:A.name,arguments:v},N.signal,O=>O&&N.update(O))}catch(O){throw N.signal.throwIfAborted(),O instanceof D&&O.code!==void 0?O:new D(`${O.message} Whether ${A.name} took effect on the server is unknown; do not repeat it without checking.`)}let J=es(z,e.images===!0);if(z.isError===!0)throw new D(J.map(O=>O.type==="text"?O.text:"").join(`
272
+ ${l}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content??[],o=e.typed??(typeof e.content=="string"?e.content:void 0);return{...e,role:"user",content:[...n,...s],...o!==void 0?{typed:o}:{}}}estimateContext(){return E(this.history)}contextWindow(){return this.contextTokens()}};function Kr(r){let e=Ue(r);return e!==void 0?e===408||e===429||e>=500||e===0:r instanceof Error?/network|fetch failed|ECONNRESET|socket|stream ended before/i.test(r.message)||r.name==="TypeError":!1}function Hr(r,e){let t=r&&typeof r=="object"?r.retryAfter:void 0;return typeof t=="number"&&t>0?Math.min(3e4,t*1e3):Math.min(8e3,800*2**(e-1))+Math.random()*300}function Jr(r,e){return new Promise((t,n)=>{let s=()=>{clearTimeout(o),n(e.reason??new Error("aborted"))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.addEventListener("abort",s,{once:!0})})}function Ut(r){return Math.round(r*1e6)/1e6}function Cn(r){let e=()=>{try{let s=JSON.parse(localStorage.getItem(r)||"[]");return Array.isArray(s)?s:[]}catch{return[]}},t=s=>{try{s.length?localStorage.setItem(r,JSON.stringify(s)):localStorage.removeItem(r)}catch{}},n=s=>Gr(`${r}:write`,async()=>{t(s(e()))});return{list:async()=>e(),get:async s=>e().find(o=>o.id===s),put:s=>n(o=>{let i=o.findIndex(a=>a.id===s.id);return i>=0?o[i]=s:o.push(s),o}),delete:s=>n(o=>o.filter(i=>i.id!==s)),subscribe(s){if(typeof window>"u")return()=>{};let o=i=>{i.key===r&&s()};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)}}}function $n(r=[]){let e=new Map(r.map(t=>[t.id,structuredClone(t)]));return{list:async()=>[...e.values()].map(t=>structuredClone(t)),get:async t=>{let n=e.get(t);return n&&structuredClone(n)},put:async t=>{e.set(t.id,structuredClone(t))},delete:async t=>{e.delete(t)}}}var _n=()=>typeof navigator<"u"?navigator.locks:void 0;function Gr(r,e){let t=_n();return t?t.request(r,{},e):e()}async function Zr(r,e){let t=_n();if(!t)return await e(),!0;let n=!1;return await t.request(r,{ifAvailable:!0},async s=>{s&&(n=!0,await e())}),n}var Mn=/^([01]?\d|2[0-3]):([0-5]\d)$/;function Ee(r){let e=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(r.trim());return e?new Date(+e[1],+e[2]-1,+e[3],+e[4],+e[5],+(e[6]??0)).getTime():/[zZ]|[+-]\d{2}:?\d{2}$/.test(r)?Date.parse(r):NaN}function te(r){let e=new Date(r),t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}var Xr={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6,jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function Me(r){let e=r.trim().split(/\s+/);if(e.length!==5)throw new Error(`cron needs five fields (minute hour day month weekday), got "${r}"`);let t=(n,s,o,i)=>{let a=new Set;for(let l of n.toLowerCase().split(",")){let[c,u]=l.split("/"),d=u===void 0?1:Number(u);if(!Number.isInteger(d)||d<1)throw new Error(`cron ${i}: bad step in "${l}"`);let p=m=>{let b=Xr[m]??Number(m);if(!Number.isInteger(b))throw new Error(`cron ${i}: "${m}" is not a number`);return b},h,f;if(c==="*")h=s,f=o;else if(c.includes("-")){let[m,b]=c.split("-");h=p(m),f=p(b)}else h=p(c),f=u===void 0?h:o;if(i==="weekday"&&(h===7&&(h=0),f===7&&h!==0&&(f=6,a.add(0))),h<s||f>o||h>f)throw new Error(`cron ${i}: "${l}" is outside ${s}-${o}`);for(let m=h;m<=f;m+=d)a.add(m)}return a};return{min:t(e[0],0,59,"minute"),hour:t(e[1],0,23,"hour"),dom:t(e[2],1,31,"day"),mon:t(e[3],1,12,"month"),dow:t(e[4],0,7,"weekday"),domAny:e[2]==="*",dowAny:e[4]==="*"}}function pt(r,e){let t=new Date(e);t.setSeconds(0,0),t.setMinutes(t.getMinutes()+1);let n=[...r.hour].sort((o,i)=>o-i),s=[...r.min].sort((o,i)=>o-i);for(let o=0;o<366*5;o++){let i=new Date(t.getFullYear(),t.getMonth(),t.getDate()+o);if(!r.mon.has(i.getMonth()+1))continue;let a=r.dom.has(i.getDate()),l=r.dow.has(i.getDay());if(r.domAny&&r.dowAny||(r.domAny?l:r.dowAny?a:a||l))for(let c of n)for(let u of s){let d=new Date(i.getFullYear(),i.getMonth(),i.getDate(),c,u).getTime();if(d>=t.getTime())return d}}return null}function mt(r,e=1){switch(r?.type){case"once":return Number.isFinite(Ee(r.at))?void 0:`"at" must be a local time like 2026-11-28 09:00, got "${r.at}"`;case"every":return Number.isFinite(r.minutes)&&r.minutes>=e?void 0:`"minutes" must be at least ${e}`;case"daily":return Mn.test(r.time??"")?r.days&&(!r.days.length||r.days.some(t=>!Number.isInteger(t)||t<0||t>6))?'"days" must be weekday numbers 0 (Sunday) to 6':void 0:`"time" must be HH:mm, got "${r.time}"`;case"cron":{try{let t=Me(r.cron);if(pt(t,Date.now())===null)return"this cron never runs"}catch(t){return t.message}if(e>1){let t=Me(r.cron),n=pt(t,Date.now()),s=pt(t,n);if(s!==null&&s-n<e*6e4)return`runs more often than every ${e} minutes`}return}default:return'"type" must be once, every, daily or cron'}}function Re(r,e,t=e){switch(r.type){case"once":{let n=Ee(r.at);return Number.isFinite(n)&&n>e?n:null}case"every":{let n=r.minutes*6e4,s=t+n;return s<=e&&(s=e+n),s}case"daily":{let n=Mn.exec(r.time);if(!n)return null;let s=new Date(e);for(let o=0;o<8;o++){let i=new Date(s.getFullYear(),s.getMonth(),s.getDate()+o,+n[1],+n[2]);if(i.getTime()>e&&(!r.days?.length||r.days.includes(i.getDay())))return i.getTime()}return null}case"cron":try{return pt(Me(r.cron),e)}catch{return null}}}var Yr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Vr=["\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"];function Ft(r,e="en"){let t=e==="zh";switch(r.type){case"once":{let n=Ee(r.at);return(t?"\u4E00\u6B21 \xB7 ":"Once \xB7 ")+(Number.isFinite(n)?te(n):r.at)}case"every":{let n=r.minutes,s=n%1440===0?t?`${n/1440} \u5929`:`${n/1440} d`:n%60===0?t?`${n/60} \u5C0F\u65F6`:`${n/60} h`:t?`${n} \u5206\u949F`:`${n} min`;return t?`\u6BCF ${s}`:`Every ${s}`}case"daily":{let n=[...new Set(r.days??[])].sort((s,o)=>s-o);return!n.length||n.length===7?(t?"\u6BCF\u5929 ":"Daily ")+r.time:n.join()==="1,2,3,4,5"?(t?"\u5DE5\u4F5C\u65E5 ":"Weekdays ")+r.time:n.join()==="0,6"?(t?"\u5468\u672B ":"Weekends ")+r.time:(t?"\u6BCF\u5468"+n.map(s=>Vr[s]).join("\u3001")+" ":n.map(s=>Yr[s]).join(", ")+" ")+r.time}case"cron":return`cron ${r.cron}`}}var Qr=()=>`t_${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`;function Nt(r,e={},t=Date.now()){let n=r.name?.trim(),s=r.prompt?.trim();if(!n)throw new Error("a task needs a name");if(!s)throw new Error("a task needs a prompt");let o=mt(r.schedule,e.minMinutes??5);if(o)throw new Error(o);let i=r.enabled??!0,a=i?Re(r.schedule,t):null;if(i&&a===null)throw new Error("that time has already passed");return{id:Qr(),name:n,prompt:s,schedule:r.schedule,enabled:i,next:a,by:r.by,created:t,updated:t,runs:0}}function zt(r,e,t={},n=Date.now()){let s={...r,updated:n};if(e.name!==void 0){if(!e.name.trim())throw new Error("a task needs a name");s.name=e.name.trim()}if(e.prompt!==void 0){if(!e.prompt.trim())throw new Error("a task needs a prompt");s.prompt=e.prompt.trim()}if(e.schedule){let o=mt(e.schedule,t.minMinutes??5);if(o)throw new Error(o);s.schedule=e.schedule}if(e.enabled!==void 0&&(s.enabled=e.enabled),(e.schedule||e.enabled!==void 0)&&(s.next=s.enabled?Re(s.schedule,n):null,s.enabled&&s.next===null))throw new Error("that time has already passed");return s}var An={type:"object",description:`When it runs, in the user's local time. type "once": at ("YYYY-MM-DD HH:mm") or in_minutes (from now). type "every": minutes. type "daily": time ("HH:mm") and optional days (0 = Sunday \u2026 6 = Saturday; [1,2,3,4,5] for weekdays). type "cron": cron (five fields, local time).`,properties:{type:{type:"string",enum:["once","every","daily","cron"]},at:{type:"string"},in_minutes:{type:"number"},minutes:{type:"number"},time:{type:"string"},days:{type:"array",items:{type:"integer",minimum:0,maximum:6}},cron:{type:"string"}},required:["type"],additionalProperties:!1};function Pn(r,e){switch(r.type){case"once":return{type:"once",at:r.at??(r.in_minutes!==void 0?te(e+Math.max(1,Math.round(r.in_minutes))*6e4):"")};case"every":return{type:"every",minutes:Math.round(r.minutes??0)};case"daily":return{type:"daily",time:r.time??"",...r.days?.length?{days:r.days}:{}};case"cron":return{type:"cron",cron:r.cron??""}}}function jt(r,e=Date.now()){return{id:r.id,name:r.name,prompt:r.prompt,schedule:Ft(r.schedule),enabled:r.enabled,next:r.next?te(r.next):null,runs:r.runs,...r.last?{last_run:`${te(r.last.at)} ${r.last.status}${r.last.note?": "+r.last.note:""}`}:{},...r.next&&r.next<e?{overdue:!0}:{}}}function En(r,e={}){let t=e.now??Date.now,n=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"local"}})(),s=()=>{try{e.onChange?.()}catch{}},o=()=>`Now: ${te(t())} (${n}).`;return[D({name:"schedule_list",description:"Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",readOnly:!0,display:{label:()=>"Scheduled tasks"},execute:async()=>{let i=await r.list();return`${o()}
273
+ ${i.length?JSON.stringify(i.map(a=>jt(a,t())),null,1):"No scheduled tasks."}`}}),D({name:"schedule_add",description:`Adds a scheduled task: at the set times the agent is given \`prompt\` in a conversation of the task's own and works on it unattended (the user may not be watching; questions wait for them). Runs only while the app is open in a browser; a run missed while it was closed happens once when it is next opened. Repeats at most every ${e.minMinutes??5} minutes. Write the prompt so it stands alone: the run does not see this conversation.`,parameters:{type:"object",properties:{name:{type:"string",description:'Short name the user sees, e.g. "Morning news digest".'},prompt:{type:"string",description:"The instruction for each run, complete on its own."},schedule:An,enabled:{type:"boolean",description:"Default true."}},required:["name","prompt","schedule"],additionalProperties:!1},display:{label:i=>`Schedule \u201C${i.name??""}\u201D`},execute:async i=>{let a=await r.list();if(a.length>=(e.maxTasks??20))throw new Error(`there are already ${a.length} tasks, the most allowed; remove one first`);let l=Nt({name:i.name,prompt:i.prompt,schedule:Pn(i.schedule,t()),enabled:i.enabled,by:"agent"},e,t());return await r.put(l),s(),`${o()}
274
+ Added: ${JSON.stringify(jt(l,t()))}`}}),D({name:"schedule_update",description:"Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",parameters:{type:"object",properties:{id:{type:"string"},name:{type:"string"},prompt:{type:"string"},schedule:An,enabled:{type:"boolean"}},required:["id"],additionalProperties:!1},display:{label:i=>`Update scheduled task ${i.id??""}`},execute:async i=>{let a=await r.get(i.id);if(!a)throw new Error(`no task with id ${i.id}; schedule_list shows them`);let l=zt(a,{name:i.name,prompt:i.prompt,schedule:i.schedule?Pn(i.schedule,t()):void 0,enabled:i.enabled},e,t());return await r.put(l),s(),`${o()}
275
+ Updated: ${JSON.stringify(jt(l,t()))}`}}),D({name:"schedule_remove",description:"Removes a scheduled task (by id). Its conversation stays.",parameters:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},display:{label:i=>`Remove scheduled task ${i.id??""}`},execute:async i=>{let a=await r.get(i.id);if(!a)throw new Error(`no task with id ${i.id}`);return await r.delete(i.id),s(),`Removed \u201C${a.name}\u201D.`}})]}var ft=class{constructor(e){y(this,"opts",e);y(this,"timer",null);y(this,"busy",!1);y(this,"unsub",null);y(this,"running",new Set);y(this,"poke",()=>{this.tick()})}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.opts.interval??2e4),this.unsub=this.opts.store.subscribe?.(()=>this.opts.onChange?.())??null,typeof window<"u"&&window.addEventListener("focus",this.poke),this.tick())}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.unsub?.(),this.unsub=null,typeof window<"u"&&window.removeEventListener("focus",this.poke)}async tick(){if(this.busy||!this.opts.idle())return;let e=(this.opts.now??Date.now)(),t=(await this.opts.store.list()).filter(n=>n.enabled&&n.next!==null&&n.next<=e).sort((n,s)=>n.next-s.next);for(let n of t)if(this.busy||!this.opts.idle()||await this.fire(n.id,!1))return}runNow(e){return this.fire(e,!0)}async fire(e,t){if(this.busy)return!1;this.busy=!0;let n=!1;try{return await Zr(`${this.opts.lockPrefix}:task:${e}`,async()=>{let s=this.opts.store,o=this.opts.now??Date.now,i=await s.get(e),a=o();if(!i||!t&&(!i.enabled||i.next===null||i.next>a))return;let l=i.enabled?Re(i.schedule,a,a):i.next;await s.put({...i,next:i.schedule.type==="once"&&!t?null:l,...i.schedule.type==="once"&&!t?{enabled:!1}:{}}),n=!0,this.running.add(e),this.opts.onChange?.();let c;try{c=await this.opts.run(i)}catch(d){c={status:"error",note:d.message}}this.running.delete(e);let u=await s.get(e);u&&await s.put({...u,runs:u.runs+1,last:{at:a,...c}}),this.opts.onChange?.()}),n}finally{this.busy=!1}}};var Rn="2025-06-18",U=class extends Error{constructor(t,n,s){super(t);y(this,"status",n);y(this,"code",s);this.name="MCPError"}};async function Dn(r,e={}){e.signal?.throwIfAborted();let t=new URL(r);if(t.protocol!=="https:"&&t.protocol!=="http:")throw new U("An MCP endpoint is an http(s) URL.");let n=e.fetch??globalThis.fetch.bind(globalThis),s=e.timeoutMs??6e4,o,i,a=1,l=!1,c=e.signal,u=P=>({...e.headers??{},...P?{"Content-Type":"application/json",Accept:"application/json, text/event-stream"}:{},...e.token?{Authorization:`Bearer ${e.token}`}:{},...o?{"Mcp-Session-Id":o}:{},...i?{"MCP-Protocol-Version":i}:{}}),d=(P,R)=>n(t,{method:"POST",headers:u(!0),body:JSON.stringify(P),signal:R,redirect:"error",credentials:"omit"}),p=P=>{let R=P.method==="ping"?{jsonrpc:"2.0",id:P.id,result:{}}:{jsonrpc:"2.0",id:P.id,error:{code:-32601,message:`${P.method} is not supported by this client`}};d(R,AbortSignal.timeout(s)).then($=>$.body?.cancel()).catch(()=>{})},h=async(P,R,$,F,I=!1)=>{if(l)throw new U("The MCP connection is closed.");let A=a++,O=AbortSignal.timeout(s),B=Ln([O,...$?[$]:[],...c?[c]:[]]),ne={jsonrpc:"2.0",id:A,method:P,...R?{params:F?{...R,_meta:{progressToken:A}}:R}:{}},H=()=>{P!=="initialize"&&d({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:"The user stopped it."}},AbortSignal.timeout(5e3)).then(S=>S.body?.cancel()).catch(()=>{})};$?.addEventListener("abort",H,{once:!0});try{let S;try{S=await d(ne,B)}catch(j){throw $?.throwIfAborted(),O.aborted?new U(`${P} timed out after ${Math.round(s/1e3)} s.`):new U(`Could not reach the MCP server (${j.message}). Check the address, its CORS settings and your network.`)}if(S.status===404&&o&&!I&&P!=="initialize")return await S.body?.cancel(),o=void 0,await v($),h(P,R,$,F,!0);if(!S.ok)throw await S.body?.cancel(),new U(`The MCP server answered ${P} with HTTP ${S.status}${S.status===401||S.status===403?" (check the token)":""}.`,S.status);let N=S.headers.get("mcp-session-id");N&&(o=N);let z=j=>{if(j.id===A&&(j.result||j.error)){if(j.error)throw new U(`${P}: ${j.error.message}`,void 0,j.error.code);return j.result??{}}if(j.method&&j.id!==void 0)p(j);else if(j.method==="notifications/progress"&&j.params?.progressToken===A&&F){let W=j.params;F(W.message??(W.total?`${W.progress??0} / ${W.total}`:String(W.progress??"")))}};if((S.headers.get("content-type")??"").includes("text/event-stream")&&S.body){for await(let j of me(S.body,B)){let W;try{W=JSON.parse(j)}catch{continue}for(let Un of Array.isArray(W)?W:[W]){let Wt=z(Un);if(Wt)return S.body.cancel().catch(()=>{}),Wt}}throw $?.throwIfAborted(),O.aborted?new U(`${P} timed out after ${Math.round(s/1e3)} s.`):new U(`The MCP server ended the stream without answering ${P}.`)}let L;try{L=await S.json()}catch{throw new U(`The MCP server's answer to ${P} is not JSON.`)}for(let j of Array.isArray(L)?L:[L]){let W=z(j);if(W)return W}throw new U(`The MCP server did not answer ${P}.`)}finally{$?.removeEventListener("abort",H)}},f=async P=>{await(await d({jsonrpc:"2.0",method:P},Ln([AbortSignal.timeout(s),...c?[c]:[]]))).body?.cancel()},m={name:"mcp"},b,v=async P=>{i=void 0;let R=await h("initialize",{protocolVersion:Rn,capabilities:{},clientInfo:{name:e.clientName??"runapps-agent",version:"1"}},P);i=typeof R.protocolVersion=="string"?R.protocolVersion:Rn;let $=R.serverInfo;$?.name&&(m={name:$.name,version:$.version,title:$.title}),typeof R.instructions=="string"&&(b=R.instructions),await f("notifications/initialized")};await v(e.signal);let g=[],w=[],M=On(e.prefix??m.name).slice(0,24)||"mcp",k=e.name||m.title||m.name,T=async P=>{let R=[],$=new Set,F;do{let A=await h("tools/list",F?{cursor:F}:{},P);if(!Array.isArray(A.tools))throw new U("The MCP server's tool list is malformed.");for(let O of A.tools){if(!O||typeof O.name!="string"||!O.name)throw new U("The MCP server listed a tool without a name.");let B=O.inputSchema&&typeof O.inputSchema=="object"?O.inputSchema:{type:"object"};R.push({...O,inputSchema:{type:"object",properties:{},...B}})}if(R.length>(e.maxTools??64))throw new U(`The MCP server has more than ${e.maxTools??64} tools (maxTools).`);if(F=typeof A.nextCursor=="string"&&A.nextCursor?A.nextCursor:void 0,F){if($.has(F))throw new U("The MCP server's tool list repeats a page.");$.add(F)}}while(F);g=R;let I=new Set;return w=R.map(A=>{let O=`${M}__${On(A.name)}`.slice(0,64);for(let S=2;I.has(O);S++)O=`${O.slice(0,60)}_${S}`;I.add(O);let B=A.annotations?.readOnlyHint===!0,ne=e.confirm==="never"?!1:e.confirm==="unless-read-only"?!B:!0,H=A.title??A.annotations?.title??A.name;return D({name:O,description:`[${k} \u2014 MCP server] ${H!==A.name?`${H}. `:""}${A.description??""}`.trim().slice(0,4e3),parameters:A.inputSchema,readOnly:B,destructive:A.annotations?.destructiveHint===!0||!B&&ne,maxResultChars:e.maxResultChars,confirm:ne?S=>({title:`Run ${k} / ${A.name}?`,message:JSON.stringify(S,null,2).slice(0,4e3)}):()=>!1,async execute(S,N){let z;try{z=await h("tools/call",{name:A.name,arguments:S},N.signal,L=>L&&N.update(L))}catch(L){throw N.signal.throwIfAborted(),L instanceof U&&L.code!==void 0?L:new U(`${L.message} Whether ${A.name} took effect on the server is unknown; do not repeat it without checking.`)}let J=es(z,e.images===!0);if(z.isError===!0)throw new U(J.map(L=>L.type==="text"?L.text:"").join(`
276
276
  `).trim()||`${A.name} reported an error.`);return J.length===1&&J[0].type==="text"?J[0].text:J}})}),w};try{await T(e.signal)}catch(P){throw await C(),P}c=void 0;async function C(){if(!l&&(l=!0,!!o))try{await(await n(t,{method:"DELETE",headers:u(!1),redirect:"error",credentials:"omit",signal:AbortSignal.timeout(5e3)})).body?.cancel()}catch{}}return{get tools(){return w},get serverTools(){return g},server:m,instructions:b,refresh:T,close:C}}function es(r,e){let t=Array.isArray(r.content)?r.content:[],n=[];for(let s of t)if(!(!s||typeof s!="object"))if(s.type==="text"&&typeof s.text=="string")n.push({type:"text",text:s.text});else if(s.type==="image"&&typeof s.data=="string"){let o=typeof s.mimeType=="string"?s.mimeType:"image/png";e?n.push({type:"image_url",image_url:{url:`data:${o};base64,${s.data}`}}):n.push({type:"text",text:`[A picture (${o}, ${Math.round(s.data.length*3/4)} bytes) was returned; it is not shown here.]`})}else if(s.type==="audio")n.push({type:"text",text:`[Audio (${String(s.mimeType??"audio")}) was returned; it is not shown here.]`});else if(s.type==="resource"&&s.resource&&typeof s.resource=="object"){let o=s.resource;n.push({type:"text",text:typeof o.text=="string"?`${o.uri?`${o.uri}:
277
- `:""}${o.text}`:`[Resource ${o.uri??""} (${o.mimeType??"binary"}); its content is not shown here.]`})}else s.type==="resource_link"&&n.push({type:"text",text:`[Link: ${String(s.name??"")} ${String(s.uri??"")}]`.replace(/\s+\]/,"]")});return!n.length&&r.structuredContent!==void 0&&n.push({type:"text",text:JSON.stringify(r.structuredContent)}),n.length||n.push({type:"text",text:"OK"}),n}function On(r){return r.replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")}function Ln(r){let e=AbortSignal.any;if(e)return e(r);let t=new AbortController;for(let n of r){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}function ts(r,e={}){return new pe(r,e)}function ns(r,e={}){let t=r?Z(r):null;return le.open(t,{...e,project:e.project??t?.name??void 0})}return Bn(rs);})();
277
+ `:""}${o.text}`:`[Resource ${o.uri??""} (${o.mimeType??"binary"}); its content is not shown here.]`})}else s.type==="resource_link"&&n.push({type:"text",text:`[Link: ${String(s.name??"")} ${String(s.uri??"")}]`.replace(/\s+\]/,"]")});return!n.length&&r.structuredContent!==void 0&&n.push({type:"text",text:JSON.stringify(r.structuredContent)}),n.length||n.push({type:"text",text:"OK"}),n}function On(r){return r.replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")}function Ln(r){let e=AbortSignal.any;if(e)return e(r);let t=new AbortController;for(let n of r){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}function ts(r,e={}){return new fe(r,e)}function ns(r,e={}){let t=r?Z(r):null;return ce.open(t,{...e,project:e.project??t?.name??void 0})}return Bn(rs);})();