@runappsai/agent 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-core.umd.js +1 -1
- package/dist/agent.umd.js +57 -57
- package/dist/ui.cjs +4 -3
- package/dist/vlist.js +8 -4
- package/package.json +1 -1
package/dist/agent.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* @runappsai/agent 0.1.
|
|
2
|
-
"use strict";var RunAppsAgent=(()=>{var zr=Object.defineProperty;var hl=Object.getOwnPropertyDescriptor;var gl=Object.getOwnPropertyNames;var ml=Object.prototype.hasOwnProperty;var yl=(r,e,n)=>e in r?zr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var wl=(r,e)=>{for(var n in e)zr(r,n,{get:e[n],enumerable:!0})},bl=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gl(e))!ml.call(r,s)&&s!==n&&zr(r,s,{get:()=>e[s],enumerable:!(t=hl(e,s))||t.enumerable});return r};var xl=r=>bl(zr({},"__esModule",{value:!0}),r);var z=(r,e,n)=>yl(r,typeof e!="symbol"?e+"":e,n);var td={};wl(td,{Agent:()=>Lt,CHAT_COLOR_TOKENS:()=>wa,CHAT_PALETTES:()=>us,CHAT_SHARED_TOKENS:()=>ba,DEFAULT_SKILLS_DIR:()=>di,DEFAULT_USER_SKILLS_DIR:()=>pi,MCPError:()=>Ce,PartialReadError:()=>Wt,ProviderError:()=>ct,UNTITLED:()=>$t,VirtualList:()=>wn,Workspace:()=>un,applyEdits:()=>Gr,askUserTool:()=>ls,buildSystemPrompt:()=>Ur,buildZip:()=>Vr,collectCompletion:()=>Jn,configurePdf:()=>No,connectMCP:()=>da,createAgent:()=>wc,decodeText:()=>pt,defineTool:()=>
|
|
1
|
+
/* @runappsai/agent 0.1.2 */
|
|
2
|
+
"use strict";var RunAppsAgent=(()=>{var zr=Object.defineProperty;var hl=Object.getOwnPropertyDescriptor;var gl=Object.getOwnPropertyNames;var ml=Object.prototype.hasOwnProperty;var yl=(r,e,n)=>e in r?zr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var wl=(r,e)=>{for(var n in e)zr(r,n,{get:e[n],enumerable:!0})},bl=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gl(e))!ml.call(r,s)&&s!==n&&zr(r,s,{get:()=>e[s],enumerable:!(t=hl(e,s))||t.enumerable});return r};var xl=r=>bl(zr({},"__esModule",{value:!0}),r);var z=(r,e,n)=>yl(r,typeof e!="symbol"?e+"":e,n);var td={};wl(td,{Agent:()=>Lt,CHAT_COLOR_TOKENS:()=>wa,CHAT_PALETTES:()=>us,CHAT_SHARED_TOKENS:()=>ba,DEFAULT_SKILLS_DIR:()=>di,DEFAULT_USER_SKILLS_DIR:()=>pi,MCPError:()=>Ce,PartialReadError:()=>Wt,ProviderError:()=>ct,UNTITLED:()=>$t,VirtualList:()=>wn,Workspace:()=>un,applyEdits:()=>Gr,askUserTool:()=>ls,buildSystemPrompt:()=>Ur,buildZip:()=>Vr,collectCompletion:()=>Jn,configurePdf:()=>No,connectMCP:()=>da,createAgent:()=>wc,decodeText:()=>pt,defineTool:()=>He,directoryFS:()=>za,domUI:()=>as,enhanceSelect:()=>Aa,escapeHTML:()=>xe,estimateTokens:()=>Fe,expandSlash:()=>qr,extractPdfText:()=>dn,fileGuard:()=>fn,fileTools:()=>ss,fitBudget:()=>Ir,formatPdfText:()=>pn,groupTurns:()=>Xs,guessType:()=>dt,isPdf:()=>cn,listTemplates:()=>Nr,listZip:()=>Kr,memoryFS:()=>Zo,modelAccepts:()=>Nt,normalizeForFuzzyMatch:()=>oi,normalizePath:()=>V,normalizeResult:()=>Yn,nullUI:()=>mi,openAIProvider:()=>$o,openWorkspace:()=>bc,parseCommandArgs:()=>ni,parseFrontmatter:()=>ii,parseSkill:()=>Qn,planCut:()=>Hr,readZipEntry:()=>sn,renderChat:()=>Da,renderInline:()=>bt,renderMarkdown:()=>yn,runInSandbox:()=>fi,runappsProvider:()=>Zs,sandboxTool:()=>os,selectBox:()=>ar,serializeConversation:()=>Xn,skillFoldersOf:()=>er,skillZipFS:()=>an,splitForSummary:()=>jr,sseData:()=>Zn,subFS:()=>tr,substituteArgs:()=>ri,summaryMessage:()=>Fr,summaryOf:()=>Ze,titleOf:()=>Bt,toProvider:()=>tt,validateSchema:()=>is});function Nt(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 ct=class extends Error{constructor(n,t,s={}){super(t);z(this,"status");z(this,"code");z(this,"retryAfter");this.name="ProviderError",this.status=n,this.code=s.code,this.retryAfter=s.retryAfter}get statusCode(){return this.status}};function Ao(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 Zs(r){let e=r.files;return{name:r.projectName,stream:(n,t)=>r.chat.stream(n,t),complete:r.chat.create?(n,t)=>r.chat.create(n,t):void 0,models:r.models?.list?async n=>await r.models.list(n):void 0,readFile:e?async(n,t)=>{let s=await e.stat(n);return t?.etag&&s.etag&&t.etag===s.etag?null:{bytes:new Uint8Array(await(await e.get(n)).arrayBuffer()),etag:s.etag}}:void 0}}function tt(r){if(typeof r.stream=="function")return r;if(typeof r.chat?.stream=="function")return Zs(r);throw new Error("pass a ModelProvider (with stream()) or a RunApps client")}function $o(r){let e=r.baseURL.replace(/\/+$/,""),n=r.fetch??((...o)=>fetch(...o)),t=()=>({"Content-Type":"application/json",...r.apiKey?{Authorization:`Bearer ${r.apiKey}`}:{},...r.headers??{}}),s=async(o,a)=>{let l;try{l=await n(`${e}/chat/completions`,{method:"POST",headers:t(),body:JSON.stringify(o),signal:a})}catch(d){throw a?.aborted?d:new ct(0,`network error: ${d.message}`)}if(!l.ok)throw await Eo(l);return l};return{name:r.name,async*stream(o,a){let l={...o,stream:!0,...r.streamUsage===!1?{}:{stream_options:{include_usage:!0}}},d=await s(l,a?.signal);if(!d.body)throw new ct(0,"the response has no body to stream");for await(let p of Zn(d.body,a?.signal)){if(p==="[DONE]")return;let u;try{u=JSON.parse(p)}catch{continue}if(u.error)throw new ct(500,u.error.message??"stream error",{code:u.error.code});yield u}},async complete(o,a){return await(await s({...o,stream:!1},a?.signal)).json()},models:r.models===void 0?void 0:async()=>{if(Array.isArray(r.models))return r.models;let o=await n(`${e}/models`,{headers:t()});if(!o.ok)throw await Eo(o);return((await o.json()).data??[]).map(({id:l,is_default:d,capability:p,max_input_tokens:u,max_tokens:w,options:x})=>({id:l,is_default:d,capability:p??"text",max_input_tokens:u,max_tokens:w,options:x}))}}}async function Eo(r){let e=`HTTP ${r.status}`,n;try{let s=await r.json();typeof s.error=="string"?e=s.error:s.error?.message?(e=s.error.message,n=s.error.code??s.error.type):s.message&&(e=s.message)}catch{}let t=Number(r.headers.get("Retry-After"));return new ct(r.status,e,{code:n,retryAfter:Number.isFinite(t)&&t>0?t:void 0})}async function*Zn(r,e){let n=r.getReader(),t=new TextDecoder,s="",o=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",o,{once:!0});try{for(;;){let{done:l,value:d}=await n.read();if(l)break;s+=t.decode(d,{stream:!0});let p;for(;(p=s.search(/\r?\n\r?\n/))>=0;){let u=s.slice(0,p);s=s.slice(p).replace(/^\r?\n\r?\n/,"");let w=u.split(/\r?\n/).filter(x=>x.startsWith("data:")).map(x=>x.slice(5).replace(/^ /,"")).join(`
|
|
3
3
|
`);w&&(yield w)}}let a=s.split(/\r?\n/).filter(l=>l.startsWith("data:")).map(l=>l.slice(5).replace(/^ /,"")).join(`
|
|
4
4
|
`);a&&(yield a)}finally{e?.removeEventListener("abort",o),n.releaseLock()}e?.throwIfAborted()}function Ur(r){let e=(r.now??new Date).toISOString().slice(0,10),n=[];n.push(`You are ${r.appName?`the assistant built into ${r.appName}`:"an assistant"}. Today is ${e}.`),r.instructions?.trim()&&n.push(r.instructions.trim()),r.agentsMd?.trim()&&n.push(`Project-specific instructions and guidelines:
|
|
5
5
|
|
|
@@ -31,7 +31,7 @@ There is no runtime for scripts here: a skill's scripts (Python, shell, JavaScri
|
|
|
31
31
|
`+o.join(`
|
|
32
32
|
`)),r.droppedTurns>0&&n.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.`),n.join(`
|
|
33
33
|
|
|
34
|
-
`)}var vl=1600;function Fe(r,e){let n=e?rn(e):0,t=0;for(let s of r){if(n+=16,typeof s.content=="string")n+=rn(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?n+=rn(o.text):t++;if(s.tool_calls)for(let o of s.tool_calls)n+=rn(o.function.name)+rn(o.function.arguments)+24;typeof s.reasoning_content=="string"&&(n+=rn(s.reasoning_content))}return Math.ceil(n/3)+t*vl}function rn(r){let e=0;for(let n=0;n<r.length;n++){let t=r.charCodeAt(n);e+=t<128?1:t<2048?2:t>=55296&&t<=56319?(n++,4):3}return e}function Ir(r,e){let n=Math.max(1,e.keepTurns),t=e.elideAbove??400,s=Xs(r),o=0,a=0,l=()=>Fe(s.flat(),e.system)>e.budget;if(l())for(let d=0;d<s.length-n&&l();d++)s[d]=s[d].map(p=>{if(p.role!=="tool")return p;let u=typeof p.content=="string"?p.content:Lo(p.content);return u.length<=t||u.startsWith("[result elided")?p:(o++,{...p,content:`[result elided to save context: ${u.length} characters; call the tool again if needed]`})});for(;s.length>1&&l();)s.shift(),a++;if(l()&&s.length===1){let d=s[0],p=d.map((b
|
|
34
|
+
`)}var vl=1600;function Fe(r,e){let n=e?rn(e):0,t=0;for(let s of r){if(n+=16,typeof s.content=="string")n+=rn(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?n+=rn(o.text):t++;if(s.tool_calls)for(let o of s.tool_calls)n+=rn(o.function.name)+rn(o.function.arguments)+24;typeof s.reasoning_content=="string"&&(n+=rn(s.reasoning_content))}return Math.ceil(n/3)+t*vl}function rn(r){let e=0;for(let n=0;n<r.length;n++){let t=r.charCodeAt(n);e+=t<128?1:t<2048?2:t>=55296&&t<=56319?(n++,4):3}return e}function Ir(r,e){let n=Math.max(1,e.keepTurns),t=e.elideAbove??400,s=Xs(r),o=0,a=0,l=()=>Fe(s.flat(),e.system)>e.budget;if(l())for(let d=0;d<s.length-n&&l();d++)s[d]=s[d].map(p=>{if(p.role!=="tool")return p;let u=typeof p.content=="string"?p.content:Lo(p.content);return u.length<=t||u.startsWith("[result elided")?p:(o++,{...p,content:`[result elided to save context: ${u.length} characters; call the tool again if needed]`})});for(;s.length>1&&l();)s.shift(),a++;if(l()&&s.length===1){let d=s[0],p=d.map((x,b)=>x.role==="tool"?b:-1).filter(x=>x>=0);for(let x of p.slice(0,Math.max(0,p.length-3))){if(!l())break;let b=d[x],M=typeof b.content=="string"?b.content:Lo(b.content);M.length<=t||M.startsWith("[result elided")||(d[x]={...b,content:`[result elided to save context: ${M.length} characters; call the tool again if needed]`},o++)}let u=d[0]?.role==="user"?1:0,w=x=>{let b=x+1;for(;b<d.length&&d[b].role==="tool";)b++;return b};for(;l()&&!(d.slice(u).filter(b=>b.role==="assistant").length<=1||d[u]?.role!=="assistant");)d.splice(u,w(u)-u),a++}return{messages:s.flat(),droppedTurns:a,elidedResults:o}}function Xs(r){let e=[],n=[];for(let t of r)t.role==="user"&&n.length&&(e.push(n),n=[]),n.push(t);return n.length&&e.push(n),e}function Lo(r){return r?r.map(e=>e.type==="text"?e.text:"").join(""):""}var Po={reserveTokens:16384,keepRecentTokens:2e4},Js=`The conversation history before this point was compacted into the following summary:
|
|
35
35
|
|
|
36
36
|
<summary>
|
|
37
37
|
`,Ys=`
|
|
@@ -105,12 +105,12 @@ 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.`,Ml=2e3;function Ze(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(Js)||!r.content.endsWith(Ys)?null:r.content.slice(Js.length,r.content.length-Ys.length)}function Fr(r){return{role:"user",content:Js+r+Ys}}function Qs(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??Po.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??Po.keepRecentTokens,Math.floor(r*.4))}}function ei(r,e,n){return r>e-n.reserveTokens}function
|
|
108
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,Ml=2e3;function Ze(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(Js)||!r.content.endsWith(Ys)?null:r.content.slice(Js.length,r.content.length-Ys.length)}function Fr(r){return{role:"user",content:Js+r+Ys}}function Qs(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??Po.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??Po.keepRecentTokens,Math.floor(r*.4))}}function ei(r,e,n){return r>e-n.reserveTokens}function Hr(r,e){if(r.length<2)return null;let n=0,t=-1;for(let a=r.length-1;a>=1;a--){n+=Fe([r[a]]);let l=r[a].role;if((l==="user"||l==="assistant")&&(t=a,n>=e))break}if(t<=0)return null;let s,o=[];for(let a of r.slice(0,t)){let l=Ze(a);l!==null&&s===void 0?s=l:o.push(a)}return o.length?{toSummarize:o,previousSummary:s,kept:r.slice(t)}:null}function Xn(r){let e=[];for(let n of r){let t=typeof n.content=="string"?n.content:(n.content??[]).map(s=>s.type==="text"?s.text:`[${s.type}]`).join(`
|
|
109
109
|
`);n.role==="user"?t&&e.push(`[User]: ${t}`):n.role==="assistant"?(t&&e.push(`[Assistant]: ${t}`),n.tool_calls?.length&&e.push(`[Assistant tool calls]: ${n.tool_calls.map(s=>`${s.function.name}(${s.function.arguments})`).join("; ")}`)):n.role==="tool"&&t&&e.push(`[Tool result]: ${Cl(t,Ml)}`)}return e.join(`
|
|
110
110
|
|
|
111
111
|
`)}function Cl(r,e){return r.length<=e?r:`${r.slice(0,e)}
|
|
112
112
|
|
|
113
|
-
[... ${r.length-e} more characters truncated]`}function
|
|
113
|
+
[... ${r.length-e} more characters truncated]`}function jr(r,e){if(r.length<=e)return[r];let n=[],t="";for(let s of r.split(/\n\n(?=\[(?:User|Assistant|Assistant tool calls|Tool result)\]: )/))for(let o=0;o<s.length;o+=e){let a=s.slice(o,o+e);t&&t.length+2+a.length>e&&(n.push(t),t=""),t=t?`${t}
|
|
114
114
|
|
|
115
115
|
${a}`:a}return t&&n.push(t),n}function _o(r,e,n){let t=`<conversation>
|
|
116
116
|
${typeof r=="string"?r:Xn(r)}
|
|
@@ -122,52 +122,52 @@ ${e}
|
|
|
122
122
|
|
|
123
123
|
`),t+=e?Sl:Tl,n?.trim()&&(t+=`
|
|
124
124
|
|
|
125
|
-
The user asked this summary to focus on: ${n.trim()}`),[{role:"system",content:kl},{role:"user",content:t}]}async function Jn(r,e,n={}){let t=n.maxChars??8e5,s="",o="",a=0,l,d,p=new Map;for await(let
|
|
125
|
+
The user asked this summary to focus on: ${n.trim()}`),[{role:"system",content:kl},{role:"user",content:t}]}async function Jn(r,e,n={}){let t=n.maxChars??8e5,s="",o="",a=0,l,d,p=new Map;for await(let b of r(e,{signal:n.signal}))if(n.signal?.throwIfAborted(),b.usage&&(d=b.usage),!!Array.isArray(b.choices))for(let M of b.choices){if((M.index??0)!==0)continue;M.finish_reason&&(l=M.finish_reason);let T=M.delta;if(!T)continue;typeof T.content=="string"&&T.content&&(s+=T.content,a+=T.content.length,n.onText?.(T.content,s));let A=T.reasoning_content??T.reasoning??T.thinking;if(typeof A=="string"&&A&&(o+=A,a+=A.length,n.onReasoning?.(A,o)),T.tool_calls){if(!Array.isArray(T.tool_calls))throw new Error("Malformed streamed tool_calls");for(let P of T.tool_calls){let _=typeof P.index=="number"?P.index:p.size;if(!Number.isInteger(_)||_<0||_>=64)throw new Error("Malformed streamed tool call index");let C=p.get(_);C||(C={index:_,id:"",type:"function",function:{name:"",arguments:""}},p.set(_,C)),P.id&&(C.id=P.id),P.type&&(C.type=P.type),P.function&&(P.function.name&&(C.function.name+=P.function.name),P.function.arguments&&(C.function.arguments+=P.function.arguments,a+=P.function.arguments.length)),n.onToolCall?.({index:_,id:C.id??"",name:C.function.name,arguments:C.function.arguments},P.function?.arguments??"")}}if(a>t)throw new Error("The model's reply exceeded the size limit")}if(n.signal?.throwIfAborted(),!l)throw new Error("The stream ended before the reply was complete");let u=[...p.keys()].sort((b,M)=>b-M);if(u.some((b,M)=>b!==M))throw new Error("Streamed tool calls arrived incomplete");let w=u.map(b=>{let M=p.get(b),{index:T,...A}=M;return A.id||(A.id=`call_${Math.random().toString(36).slice(2,10)}`),A}),x={role:"assistant",content:s.length?s:null};return w.length&&(x.tool_calls=w),{message:x,finishReason:l,usage:d,reasoning:o}}var ti="/prompts";function ni(r){let e=[],n="",t=!1,s=null;for(let o=0;o<r.length;o++){let a=r[o];s?a===s?s=null:n+=a:a==='"'||a==="'"?(s=a,t=!0):/\s/.test(a)?t&&(e.push(n),n="",t=!1):(n+=a,t=!0)}return t&&e.push(n),e}function ri(r,e){let n=e.join(" ");return r.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(t,s,o,a,l,d)=>{if(s){let p=s==="@"||s==="ARGUMENTS"?n:e[parseInt(s,10)-1];return p||o}if(a){let p=parseInt(a,10)-1;return p<0&&(p=0),l?e.slice(p,p+parseInt(l,10)).join(" "):e.slice(p).join(" ")}return d==="ARGUMENTS"||d==="@"?n:e[parseInt(d,10)-1]??""})}async function Nr(r){let e=[];for(let n of await r.list(ti)){if(!n.path.endsWith(".md"))continue;let t=n.path.slice(ti.length+1,-3);if(t.includes("/"))continue;let s;try{s=await r.readText(n.path)}catch{continue}let{fm:o,body:a}=Ro(s),l=o.description||El(a);e.push({name:t,description:l,argumentHint:o["argument-hint"],path:n.path})}return e.sort((n,t)=>n.name.localeCompare(t.name))}async function qr(r,e){let n=/^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(e);if(!n||!r)return e;let t=n[1],s=(n[2]??"").trim();if(t.startsWith("skill:")){let d=t.slice(6),u=(await r.skills()).find(b=>b.name===d);if(!u)return e;let{body:w}=await r.skillBody(d),x=`<skill name="${u.name}" location="${u.path}">
|
|
126
126
|
References are relative to ${u.dir}.
|
|
127
127
|
|
|
128
128
|
${w}
|
|
129
|
-
</skill>`;return s?`${
|
|
129
|
+
</skill>`;return s?`${x}
|
|
130
130
|
|
|
131
|
-
${s}`:
|
|
131
|
+
${s}`:x}let o=`${ti}/${t}.md`,a;try{a=await r.readText(o)}catch{return e}let{body:l}=Ro(a);return ri(l,ni(s))}function Ro(r){let e=r.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
132
132
|
`),n=/^---\n([\s\S]*?)\n---\n?/.exec(e);if(!n)return{fm:{},body:e.trim()};let t={};for(let s of(n[1]??"").split(`
|
|
133
133
|
`)){let o=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(s.trim());o&&(t[o[1]]=o[2].replace(/^["']|["']$/g,""))}return{fm:t,body:e.slice(n[0].length).trim()}}function El(r){let e=r.split(`
|
|
134
|
-
`).find(n=>n.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var Do=/^[A-Za-z0-9_-]{1,64}$/;function
|
|
134
|
+
`).find(n=>n.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var Do=/^[A-Za-z0-9_-]{1,64}$/;function He(r){if(!Do.test(r.name))throw new Error(`tool name "${r.name}" must match ${Do}`);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 si(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parameters}}}function Yn(r,e=32e3){let n,t;r==null?n="OK":typeof r=="string"?n=r.length?r:"OK":Array.isArray(r)&&r.every(zo)?n=r:Al(r)?(n=r.content,t=r.details,typeof n=="string"&&!n.length&&(n="OK")):n=JSON.stringify(r);let s=!1;if(typeof n=="string"){let o=Oo(n,e);s=o.truncated,n=o.text}else n=n.map(o=>{if(o.type!=="text")return o;let a=Oo(o.text,e);return a.truncated&&(s=!0),{type:"text",text:a.text}});return{content:n,text:typeof n=="string"?n:Br(n),details:t,truncated:s}}function zo(r){return!!r&&typeof r=="object"&&typeof r.type=="string"&&["text","image_url","video_url","audio_url"].includes(r.type)}function Al(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r.content,n=Object.keys(r);return(typeof e=="string"||Array.isArray(e)&&e.every(zo))&&n.every(t=>t==="content"||t==="details")}function Oo(r,e){if(r.length<=e)return{text:r,truncated:!1};let n=r.slice(0,Math.max(0,e-120)),t=r.length-n.length;return{text:`${n}
|
|
135
135
|
|
|
136
136
|
[... ${t} more characters not shown. Ask for a narrower range or a smaller result.]`,truncated:!0}}function Br(r){return r?typeof r=="string"?r:r.map(e=>e.type==="text"?e.text:`[${e.type}]`).join(`
|
|
137
|
-
`):""}function Kr(r){if(r.byteLength>52428800)throw new Error("zip larger than 52428800 bytes");let e=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-1;for(let u=r.byteLength-22;u>=Math.max(0,r.byteLength-22-65535);u--)if(e.getUint32(u,!0)===101010256){n=u;break}if(n<0)throw new Error("not a zip file");if(n>=20&&e.getUint32(n-20,!0)===117853008)throw new Error("zip64 archives are not supported");let t=e.getUint16(n+10,!0),s=e.getUint32(n+12,!0),o=e.getUint32(n+16,!0);if(t===65535||s===4294967295||o===4294967295)throw new Error("zip64 archives are not supported");let a=[],l=o,d=new TextDecoder("utf-8"),p=new TextDecoder("latin1");for(let u=0;u<t;u++){if(l+46>r.byteLength||e.getUint32(l,!0)!==33639248)throw new Error("zip central directory is damaged");let w=e.getUint16(l+8,!0),
|
|
138
|
-
`),t=e.replace(/\/[^/]*$/,"")||"/",s=t.split("/").filter(Boolean).pop()??"skill",o=[],a={},l=n,d=/^---\n([\s\S]*?)\n---\n?/.exec(n);d&&(a=ii(d[1]??""),l=n.slice(d[0].length));let p=(a.description??"").trim();if(!p)return null;let u=(a.name??"").trim()||s;(!Io.test(u)||u.length>64)&&(o.push(`skill name "${u}" is not lowercase-hyphenated (\u226464); using the folder name`),u=Io.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let w={name:u,description:p.length>1024?p.slice(0,1024):p,path:e,dir:t};p.length>1024&&o.push(`description of "${u}" cut to 1024 characters`),/^(true|yes)$/i.test(a["disable-model-invocation"]??"")&&(w.disableModelInvocation=!0),a.license&&(w.license=a.license),a.compatibility&&(w.compatibility=a.compatibility),a["allowed-tools"]&&(w.allowedTools=a["allowed-tools"].split(/[\s,]+/).filter(Boolean));let
|
|
139
|
-
`),t=0,s="";for(;t<n.length;){let o=n[t]??"";if(t++,!o.trim()||o.trimStart().startsWith("#"))continue;let a=o.length-o.trimStart().length,l=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(o.trim());if(!l)continue;let d=a>0&&s?`${s}.${l[1]}`:l[1];a===0&&(s="");let p=l[2]??"";if(p===""){let u=n[t]??"";if(u.length-u.trimStart().length>a&&u.trim()){s=l[1];continue}}else if(p===">"||p==="|"||p===">-"||p==="|-"){let u=p.startsWith(">"),w=[];for(;t<n.length;){let
|
|
137
|
+
`):""}function Kr(r){if(r.byteLength>52428800)throw new Error("zip larger than 52428800 bytes");let e=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-1;for(let u=r.byteLength-22;u>=Math.max(0,r.byteLength-22-65535);u--)if(e.getUint32(u,!0)===101010256){n=u;break}if(n<0)throw new Error("not a zip file");if(n>=20&&e.getUint32(n-20,!0)===117853008)throw new Error("zip64 archives are not supported");let t=e.getUint16(n+10,!0),s=e.getUint32(n+12,!0),o=e.getUint32(n+16,!0);if(t===65535||s===4294967295||o===4294967295)throw new Error("zip64 archives are not supported");let a=[],l=o,d=new TextDecoder("utf-8"),p=new TextDecoder("latin1");for(let u=0;u<t;u++){if(l+46>r.byteLength||e.getUint32(l,!0)!==33639248)throw new Error("zip central directory is damaged");let w=e.getUint16(l+8,!0),x=e.getUint16(l+10,!0),b=e.getUint32(l+20,!0),M=e.getUint32(l+24,!0),T=e.getUint16(l+28,!0),A=e.getUint16(l+30,!0),P=e.getUint16(l+32,!0),_=e.getUint32(l+42,!0);if(b===4294967295||M===4294967295||_===4294967295)throw new Error("zip64 archives are not supported");let C=r.subarray(l+46,l+46+T),N=(w&2048?d:p).decode(C).replace(/\\/g,"/");a.push({name:N,size:M,compressedSize:b,method:x,isDir:N.endsWith("/"),offset:_,crc:e.getUint32(l+16,!0)}),l+=46+T+A+P}return a}async function sn(r,e,n){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),s=e.offset;if(s+30>r.byteLength||t.getUint32(s,!0)!==67324752)throw new Error(`zip entry "${e.name}" is damaged`);let o=t.getUint16(s+26,!0),a=t.getUint16(s+28,!0),l=s+30+o+a;if(l+e.compressedSize>r.byteLength)throw new Error(`zip entry "${e.name}" is damaged`);let d=r.subarray(l,l+e.compressedSize);if(e.method===0){if(d.byteLength!==e.size||e.crc!==void 0&&Uo(d)!==e.crc)throw new Error(`zip entry "${e.name}" is damaged`);return d}if(e.method!==8)throw new Error(`zip entry "${e.name}" uses an unsupported compression method (${e.method})`);let p=await(n?n(d):$l(d));if(p.byteLength!==e.size)throw new Error(`zip entry "${e.name}" inflated to the wrong size`);return p}async function $l(r){let e=globalThis.DecompressionStream;if(!e)throw new Error("this runtime has no DecompressionStream; pass an `inflate` function (e.g. zlib.inflateRawSync)");let n=new Blob([r]).stream().pipeThrough(new e("deflate-raw")),t=await new Response(n).arrayBuffer();return new Uint8Array(t)}var Wr=null;function Uo(r){if(!Wr){Wr=new Uint32Array(256);for(let n=0;n<256;n++){let t=n;for(let s=0;s<8;s++)t=t&1?3988292384^t>>>1:t>>>1;Wr[n]=t>>>0}}let e=4294967295;for(let n=0;n<r.length;n++)e=Wr[(e^r[n])&255]^e>>>8;return(e^4294967295)>>>0}async function Ll(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")),n=new Uint8Array(await new Response(e).arrayBuffer());return n.length<r.length?{bytes:n,method:8}:{bytes:r,method:0}}catch{return{bytes:r,method:0}}}function Pl(r){let e=new Date(r),n=Math.max(1980,e.getFullYear())-1980<<9|e.getMonth()+1<<5|e.getDate(),t=e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1;return{date:n,time:t}}async function Vr(r){if(r.length>65534)throw new Error(`too many files for one zip (${r.length}; at most 65534)`);let e=new TextEncoder,n=[],t=[],s=0;for(let u of r){let w=e.encode(u.path.replace(/^\/+/,"")),x=typeof u.data=="string"?e.encode(u.data):u.data,b=Uo(x),{bytes:M,method:T}=await Ll(x),{date:A,time:P}=Pl(u.mtime??Date.now()),_=new DataView(new ArrayBuffer(30));_.setUint32(0,67324752,!0),_.setUint16(4,20,!0),_.setUint16(6,2048,!0),_.setUint16(8,T,!0),_.setUint16(10,P,!0),_.setUint16(12,A,!0),_.setUint32(14,b,!0),_.setUint32(18,M.length,!0),_.setUint32(22,x.length,!0),_.setUint16(26,w.length,!0),_.setUint16(28,0,!0);let C=new DataView(new ArrayBuffer(46));C.setUint32(0,33639248,!0),C.setUint16(4,20,!0),C.setUint16(6,20,!0),C.setUint16(8,2048,!0),C.setUint16(10,T,!0),C.setUint16(12,P,!0),C.setUint16(14,A,!0),C.setUint32(16,b,!0),C.setUint32(20,M.length,!0),C.setUint32(24,x.length,!0),C.setUint16(28,w.length,!0),C.setUint16(30,0,!0),C.setUint16(32,0,!0),C.setUint16(34,0,!0),C.setUint16(36,0,!0),C.setUint32(38,0,!0),C.setUint32(42,s,!0),n.push(new Uint8Array(_.buffer),w,M),t.push(new Uint8Array(C.buffer),w),s+=30+w.length+M.length}let o=t.reduce((u,w)=>u+w.length,0),a=new DataView(new ArrayBuffer(22));a.setUint32(0,101010256,!0),a.setUint16(4,0,!0),a.setUint16(6,0,!0),a.setUint16(8,r.length,!0),a.setUint16(10,r.length,!0),a.setUint32(12,o,!0),a.setUint32(16,s,!0),a.setUint16(20,0,!0);let l=[...n,...t,new Uint8Array(a.buffer)],d=new Uint8Array(l.reduce((u,w)=>u+w.length,0)),p=0;for(let u of l)d.set(u,p),p+=u.length;return d}var Io=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Qn(r,e){let n=r.replace(/^/,"").replace(/\r\n?/g,`
|
|
138
|
+
`),t=e.replace(/\/[^/]*$/,"")||"/",s=t.split("/").filter(Boolean).pop()??"skill",o=[],a={},l=n,d=/^---\n([\s\S]*?)\n---\n?/.exec(n);d&&(a=ii(d[1]??""),l=n.slice(d[0].length));let p=(a.description??"").trim();if(!p)return null;let u=(a.name??"").trim()||s;(!Io.test(u)||u.length>64)&&(o.push(`skill name "${u}" is not lowercase-hyphenated (\u226464); using the folder name`),u=Io.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let w={name:u,description:p.length>1024?p.slice(0,1024):p,path:e,dir:t};p.length>1024&&o.push(`description of "${u}" cut to 1024 characters`),/^(true|yes)$/i.test(a["disable-model-invocation"]??"")&&(w.disableModelInvocation=!0),a.license&&(w.license=a.license),a.compatibility&&(w.compatibility=a.compatibility),a["allowed-tools"]&&(w.allowedTools=a["allowed-tools"].split(/[\s,]+/).filter(Boolean));let x={};for(let[b,M]of Object.entries(a))b.startsWith("metadata.")&&(x[b.slice(9)]=M);return Object.keys(x).length&&(w.metadata=x),{skill:w,body:l.trim(),warnings:o}}function ii(r){let e={},n=r.split(`
|
|
139
|
+
`),t=0,s="";for(;t<n.length;){let o=n[t]??"";if(t++,!o.trim()||o.trimStart().startsWith("#"))continue;let a=o.length-o.trimStart().length,l=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(o.trim());if(!l)continue;let d=a>0&&s?`${s}.${l[1]}`:l[1];a===0&&(s="");let p=l[2]??"";if(p===""){let u=n[t]??"";if(u.length-u.trimStart().length>a&&u.trim()){s=l[1];continue}}else if(p===">"||p==="|"||p===">-"||p==="|-"){let u=p.startsWith(">"),w=[];for(;t<n.length;){let x=n[t]??"";if(x.trim()&&x.length-x.trimStart().length<=a)break;w.push(x.trim()),t++}p=u?w.join(" ").trim():w.join(`
|
|
140
140
|
`).trim()}else p=_l(p);e[d]=p}return e}function _l(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 Rl(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 Fo(r){let e="",n=[],t=[],s=0,o=r.split(`
|
|
141
|
-
`);return o.forEach((a,l)=>{let d=a.trimEnd(),p=0;for(let u of d){let w=Rl(u);for(let
|
|
141
|
+
`);return o.forEach((a,l)=>{let d=a.trimEnd(),p=0;for(let u of d){let w=Rl(u);for(let x=0;x<w.length;x++)n.push(s+p),t.push(s+p+u.length);e+=w,p+=u.length}s+=a.length,l<o.length-1&&(e+=`
|
|
142
142
|
`,n.push(s),t.push(s+1),s+=1)}),{text:e,start:n,end:t}}function oi(r){return Fo(r).text}function Dl(r,e){let n=0,t=0;for(;(t=r.indexOf(e,t))!==-1;)n++,t+=e.length;return n}function Gr(r,e,n){if(!n.length)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");let t=n.length>1,s=e.startsWith("\uFEFF")?"\uFEFF":"",o=/\r\n/.test(e),a=e.slice(s.length).replace(/\r\n/g,`
|
|
143
|
-
`),l=a,d=null,p=!1;for(let
|
|
144
|
-
`))){p=!0;break}if(p){let
|
|
145
|
-
`);if(!
|
|
146
|
-
`),i:M})}),u.sort((
|
|
147
|
-
`):w)}var on=new Map,Ol=64;function zl(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(n=>n==="..")?null:e}function er(r,e){let n=[...r],t=new Map;if(n.includes("SKILL.md"))return t.set(e,""),t;for(let s of n){let o=/^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(s);if(!o)continue;let a=o[1],l=s.slice(0,-8);(!t.has(a)||l.length<t.get(a).length)&&t.set(a,l)}return t}function ai(r){let e=new Map;for(let n of Kr(r)){let t=zl(n.name);t&&e.set(t,n)}return e}function
|
|
143
|
+
`),l=a,d=null,p=!1;for(let b of n)if(b.oldText&&!a.includes(b.oldText.replace(/\r\n/g,`
|
|
144
|
+
`))){p=!0;break}if(p){let b=Fo(a);l=b.text,d=b}let u=[];n.forEach((b,M)=>{let T=b.oldText.replace(/\r\n/g,`
|
|
145
|
+
`);if(!T)throw new Error(t?`edits[${M}].oldText must not be empty in ${r}.`:`oldText must not be empty in ${r}.`);let A=p?oi(T):T,P=Dl(l,A);if(P===0)throw new Error(t?`Could not find edits[${M}] 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(P>1)throw new Error(t?`Found ${P} occurrences of edits[${M}] in ${r}. Each oldText must be unique. Please provide more context to make it unique.`:`Found ${P} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`);let _=l.indexOf(A),C=d?d.start[_]:_,N=d?d.end[_+A.length-1]:_+A.length;u.push({start:C,end:N,newText:b.newText.replace(/\r\n/g,`
|
|
146
|
+
`),i:M})}),u.sort((b,M)=>b.start-M.start);for(let b=1;b<u.length;b++)if(u[b].start<u[b-1].end)throw new Error(`edits[${u[b-1].i}] and edits[${u[b].i}] overlap in ${r}. Merge them into one edit or target disjoint regions.`);let w="",x=0;for(let b of u)w+=a.slice(x,b.start)+b.newText,x=b.end;if(w+=a.slice(x),w===a)throw new Error(t?`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?w.replace(/\n/g,`\r
|
|
147
|
+
`):w)}var on=new Map,Ol=64;function zl(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(n=>n==="..")?null:e}function er(r,e){let n=[...r],t=new Map;if(n.includes("SKILL.md"))return t.set(e,""),t;for(let s of n){let o=/^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(s);if(!o)continue;let a=o[1],l=s.slice(0,-8);(!t.has(a)||l.length<t.get(a).length)&&t.set(a,l)}return t}function ai(r){let e=new Map;for(let n of Kr(r)){let t=zl(n.name);t&&e.set(t,n)}return e}function Ho(r){return on.get(r)}function Zr(r,e,n){let t=on.get(n);if(t&&t.bytes.byteLength===e.byteLength)return t;let s=ai(e),o={entries:s,folders:er(s.keys(),r),bytes:e,cache:new Map};return on.size>=Ol&&on.delete(on.keys().next().value),on.set(n,o),o}var Ul=new TextDecoder("utf-8",{fatal:!0}),Il=r=>{try{return Ul.decode(r)}catch{return null}};function an(r,e,n,t){let s=new Map;for(let a of r.entries.keys())a.startsWith(e)&&s.set("/"+a.slice(e.length),a);let o=a=>{let l=s.get(a);return l?{path:a,size:r.entries.get(l).size,mtime:n}:null};return{async list(a){let l=a==="/"?"/":a.replace(/\/+$/,"")+"/",d=[];for(let p of s.keys())(l==="/"||p.startsWith(l)||p===a)&&d.push(o(p));return d},async stat(a){return o(a)},async read(a){let l=s.get(a);if(!l)throw new Error(`No such file: ${a}`);let d=r.cache.get(l);if(d!==void 0)return d;let p=await sn(r.bytes,r.entries.get(l),t),u=Il(p)??p;return r.cache.set(l,u),u}}}function tr(r,e){return{async list(n){let t=[];for(let s of await r.list(n==="/"?e:e+n)){let o=s.path.startsWith(e+"/")?s.path.slice(e.length):null;o&&t.push({...s,path:o})}return t},async stat(n){let t=r.stat?await r.stat(e+n):null;return t?{...t,path:n}:null},read:n=>r.read(e+n)}}var jo="6.4.299",qt={url:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${jo}/build/pdf.min.mjs`,workerUrl:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${jo}/build/pdf.worker.min.mjs`},ln=null;function No(r){Object.assign(qt,r),ln=null}var Fl=r=>import(r);function Hl(){return ln||(ln=(async()=>{let r=qt.load?await qt.load():await Fl(qt.url),e=r.default?.getDocument?r.default:r;if(!qt.load&&typeof Worker<"u"&&typeof Blob<"u")try{let n=new Blob([`import ${JSON.stringify(qt.workerUrl)};`],{type:"text/javascript"});e.GlobalWorkerOptions.workerPort=new Worker(URL.createObjectURL(n),{type:"module"})}catch{e.GlobalWorkerOptions.workerSrc=qt.workerUrl}return e})(),ln.catch(()=>{ln=null})),ln}function cn(r,e,n){return/\.pdf$/i.test(r)||e==="application/pdf"?!0:n instanceof Uint8Array&&n.length>4&&n[0]===37&&n[1]===80&&n[2]===68&&n[3]===70}async function dn(r,e={}){let t=(await Hl()).getDocument({data:r.slice(),isEvalSupported:!1}),s=await t.promise;try{let o=[],a=Math.min(s.numPages,e.maxPages??500);for(let l=1;l<=a;l++){let d=await s.getPage(l),p=await d.getTextContent();o.push(p.items.map(u=>(u.str??"")+(u.hasEOL?`
|
|
148
148
|
`:"")).join("").replace(/[ \t]+\n/g,`
|
|
149
149
|
`).trim()),d.cleanup?.()}return{pages:o,numPages:s.numPages}}finally{await(t.destroy?t.destroy():s.destroy?.())}}function pn(r,e){let n=`[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(t=>t.trim())?[n,...e.pages.map((t,s)=>`--- page ${s+1} ---
|
|
150
150
|
${t}`)].join(`
|
|
151
151
|
|
|
152
152
|
`):`${n}
|
|
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 di="/.agent/skills";var
|
|
154
|
-
`)}route(e){let n=null;for(let t of this.mounts.keys())(e===t||e.startsWith(t+"/"))&&(!n||t.length>n.length)&&(n=t);return n?{fs:this.mounts.get(n),rel:e.slice(n.length)||"/",prefix:n}:this.root?{fs:this.root,rel:e,prefix:""}:null}inSkills(e){return e===this.skillsDir||e.startsWith(this.skillsDir+"/")}async putFile(e,n,t,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,n,t??dt(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??dt(e,n),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 n=V(e),t=[],s=this.route(n);if(s&&s.prefix){for(let a of await s.fs.list(s.rel))t.push({...a,path:s.prefix+V(a.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}let o=this.root?(await this.root.list(n)).map(a=>({...a,path:V(a.path)})):await sr(this.store,n==="/"?"/":n+"/");for(let a of o)this.route(a.path)?.prefix||t.push(a);for(let[a,l]of this.mounts)if(n==="/"||a.startsWith(n+"/"))for(let d of await l.list("/"))t.push({...d,path:a+V(d.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}async stat(e){await this.ready();let n=V(e),t=this.route(n);if(t){if(t.fs.stat){let o=await t.fs.stat(t.rel);return o?{...o,path:n}:null}let s=(await t.fs.list(t.rel)).find(o=>V(o.path)===V(t.rel));return s?{...s,path:n}:null}return Bo(this.store,n)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let n=V(e),t=this.route(n);if(t)try{let o=await t.fs.read(t.rel);return{data:o,size:Yr(o),contentType:dt(n,o)}}catch(o){throw new Error(await this.missing(n,o))}let s=await this.store.get(n);if(!s)throw new Error(await this.missing(n));return{data:s.data,size:Yr(s.data),contentType:s.contentType}}async isFolder(e){let n=V(e);return n==="/"||this.mounts.has(n)?!0:(await this.list(n)).some(t=>t.path!==n)}async missing(e,n){if(await this.isFolder(e))return`${e} is a folder, not a file; use list_files to see what it holds`;let t=n instanceof Error?n.message:"";return/no such file/i.test(t)||!t?`No such file: ${e}`:`${e}: ${t}`}async readText(e){let{data:n}=await this.read(e);if(typeof n=="string")return n;let t=pt(n);if(t===null)throw new Error(`${V(e)} is a binary file (${n.byteLength} bytes)`);return t}async readAsText(e){let n=V(e),{data:t,size:s,contentType:o}=await this.read(n);if(typeof t=="string")return{text:t,kind:"text"};if(cn(n,o,t)){let l=await this.stat(n),d=`pdftext:${n}`,p=await this.getData(d).catch(()=>{});if(p&&p.size===s&&p.mtime===l?.mtime)return{text:p.text,kind:"pdf"};let u=pn(n,await dn(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:u}).catch(()=>{}),{text:u,kind:"pdf"}}let a=pt(t);return a===null?null:{text:a,kind:"text"}}async write(e,n,t){await this.ready();let s=V(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,n,t),this.emitChange(s,"write");return}await this.putFile(s,n,t,"work")}async edit(e,n){await this.ready();let t=V(e),s=this.route(t);if(s?.fs.edit){await s.fs.edit(s.rel,n),this.emitChange(t,"write");return}if(s&&!s.fs.write)throw new Error(`${s.prefix||"/"} is read-only`);await this.write(t,Gr(t,await this.readText(t),n))}async delete(e){await this.ready();let n=V(e),t=this.route(n);if(t&&t.prefix){if(!t.fs.delete)throw new Error(`${t.prefix} is read-only`);await t.fs.delete(t.rel),this.emitChange(n,"delete");return}if(!await this.stat(n))throw new Error(`No such file: ${n}`);await this.rmFile(n)}mountOf(e){return this.route(V(e))?.prefix||null}isReadOnly(e){let n=this.route(V(e));return n?!n.fs.write:!1}isSkillPath(e){let n=V(e);return this.inSkills(n)||!!this.userSkillsDir&&(n===this.userSkillsDir||n.startsWith(this.userSkillsDir+"/"))}async getData(e){await this.ready();let n=await this.store.getMeta("data:"+e);return n===null?void 0:n}async putData(e,n){await this.ready(),n==null?await this.store.deleteMeta("data:"+e):await this.store.putMeta("data:"+e,n)}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=[],n=new Set;for(let[t,s]of this.skillViews){if(s.lazy){if(n.has(s.lazy.name))continue;n.add(s.lazy.name);let l=`${this.skillsDir}/${t}`;e.push({name:s.lazy.name,description:s.lazy.description,path:`${l}/SKILL.md`,dir:l,builtin:!0,lazy:!0,...s.lazy.disableModelInvocation?{disableModelInvocation:!0}:{}});continue}let o;try{let l=await s.fs.read("/SKILL.md");o=typeof l=="string"?l:pt(l)}catch{continue}if(o===null)continue;let a=Qn(o,`${this.skillsDir}/${t}/SKILL.md`);!a||n.has(a.skill.name)||(n.add(a.skill.name),e.push({...a.skill,...s.builtin?{builtin:!0}:{},...s.from?{from:s.from}:{}}))}return this.skillCache=e.sort((t,s)=>t.name.localeCompare(s.name)),this.skillCache}async installSkill(e,n={}){if(await this.ready(),!this.userSkillsDir)throw new Error("this workspace has no userSkillsDir to install skills into");let t,s;if(typeof e=="string"){let u=await this.fetchSource(e);if(!u)throw new Error("nothing fetched");t=u.bytes,s=n.name??e}else t=e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer()),s=n.name??(e.name||"skill");if(t.byteLength>52428800)throw new Error("skills zip too large");let o=Jr(s),a=ai(t),l=er(a.keys(),o);if(!l.size)throw new Error(`${o}.zip has no SKILL.md (at its root, or one per folder)`);let d=Date.now();if(n.unpack){for(let[u,w]of l){for(let b of await sr(this.lib,`/${u}/`))await this.lib.delete(b.path);for(let[b,x]of a){if(!b.startsWith(w))continue;let M=await sn(t,x,this.inflate),S=pt(M),A=V(`/${u}/${b.slice(w.length)}`);await this.lib.put({path:A,data:S??M,contentType:dt(A,S??M),mtime:d,layer:"work"})}}await this.userSkillsChanged(`/${[...l.keys()][0]}`,"write")}else await this.lib.put({path:`/${o}.zip`,data:t,contentType:"application/zip",mtime:d,layer:"work"}),await this.userSkillsChanged(`/${o}.zip`,"write");let p=new Set([...l.keys()].map(u=>`${this.skillsDir}/${u}`));return(await this.skills()).filter(u=>p.has(u.dir))}async removeSkill(e){let n=(await this.skills()).find(s=>s.name===e);if(!n)return!1;if(n.builtin)throw new Error(`"${e}" comes with the app and cannot be removed`);if(!n.from||!this.userSkillsDir||!n.from.startsWith(this.userSkillsDir+"/"))return!1;let t=n.from.slice(this.userSkillsDir.length);if(/\.zip$/i.test(t))await this.lib.delete(t);else for(let s of await sr(this.lib,t+"/"))await this.lib.delete(s.path);return await this.userSkillsChanged(t,"delete"),!0}async skillBody(e){let n=(await this.skills()).find(s=>s.name===e);if(!n)throw new Error(`No skill named "${e}"`);let t=Qn(await this.readText(n.path),n.path);return{skill:n,body:t?.body??""}}async refreshSkills(){await this.ready();for(let e of this.resolvedSources){if(li(e)){rr.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!Ko(e)&&typeof e.data=="string"?e.data:null;n&&Xr.delete(`${this.dbName}|${this.fetchKey}|${n}`)}this.builtins=await this.loadBuiltins(),await this.rebuildSkills(),this.emitChange(this.skillsDir,"write")}async loadBuiltins(){let e=[],n=[];try{n=typeof this.sources=="function"?[].concat(await this.sources()):this.sources}catch(t){console.warn("[agent] the skills list failed:",t)}this.resolvedSources=n,this.lazySkills=n.filter(li);for(let t of n)if(!li(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!Ko(t)?t:null,o=s?s.data:t,a,l,d=0;if(typeof o=="string"){let u=`${this.dbName}|${this.fetchKey}|${o}`,w=Xr.get(u);w||(w=this.fetchSource(o).then(b=>{if(!b)throw new Error("nothing fetched");return{bytes:b.bytes,at:Date.now()}}),Xr.set(u,w),w.catch(()=>Xr.delete(u))),{bytes:a,at:d}=await w,l=`app:${u}@${d}`}else a=o instanceof Uint8Array?o:new Uint8Array(await o.arrayBuffer()),l=`app:${this.dbName}|obj${ci(o)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let p=Jr(s?.name??(typeof o=="string"?o:o.name||"skills"));e.push({name:p,bytes:a,key:l,at:d})}catch(s){console.warn("[agent] skills source failed:",s)}return e}async rebuildSkills(){let e=new Map;for(let n of this.builtins)try{let t=Zr(n.name,n.bytes,n.key);for(let[s,o]of t.folders)e.has(s)||e.set(s,{fs:an(t,o,n.at,this.inflate),builtin:!0})}catch(t){console.warn(`[agent] skills zip "${n.name}":`,t)}for(let n of this.lazySkills){let t=/^[A-Za-z0-9][\w.-]*$/.test(n.name)?n.name:Jr(n.name);e.has(t)||e.set(t,{fs:this.lazyFS(n,t),builtin:!0,lazy:n})}if(this.root)for(let n of await this.root.list(this.skillsDir).catch(()=>[])){let t=new RegExp("^"+Wl(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(V(n.path));t&&e.set(t[1],{fs:tr(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await sr(this.lib,"/");for(let s of n){let o=/^\/([^/]+)\.zip$/i.exec(s.path);if(o)try{let a=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,l=s.mtime!==void 0?jo(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=Zr(Jr(o[1]),d.data,a)}for(let[d,p]of l.folders)e.set(d,{fs:an(l,p,s.mtime??0,this.inflate),builtin:!1,from:this.userSkillsDir+s.path})}catch(a){console.warn(`[agent] skills zip "${s.path}":`,a)}}let t=this.userFS();for(let s of n){let o=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);o&&e.set(o[1],{fs:tr(t,`/${o[1]}`),builtin:!1,from:`${this.userSkillsDir}/${o[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,n){let t=null,s=async()=>{if(t)return t;let a=rr.get(e);a||(a=(async()=>{let u=await e.load();if(typeof u=="string"){let w=await this.fetchSource(u);if(!w)throw new Error("nothing fetched");return w.bytes}return u instanceof Uint8Array?u:u instanceof ArrayBuffer?new Uint8Array(u):new Uint8Array(await u.arrayBuffer())})(),rr.set(e,a),a.catch(()=>{rr.get(e)===a&&rr.delete(e)}));let l;try{l=await a}catch(u){throw new Error(`the skill "${e.name}" could not be loaded: ${u.message}`)}if(l.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let d=Zr(n,l,`lazy:${ci(e)}:${l.byteLength}`),p=d.folders.get(n)??[...d.folders.values()][0];if(p===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return t=an(d,p,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${n}`,"write"),t},o=a=>a==="/"||a==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async a=>t?t.list(a):o(a),stat:async a=>{if(!t&&a==="/SKILL.md")return{path:a,size:0};let l=await s();return l.stat?l.stat(a):null},read:async a=>(await s()).read(a)}}skillsFS(){let e=n=>{let t=/^\/([^/]+)(\/.*)?$/.exec(n);return t?{name:t[1],rest:t[2]||"/"}:null};return{description:"skills (generated, read-only)",list:async n=>{let t=[],s=e(n);for(let[o,a]of this.skillViews)if(!(s&&s.name!==o))for(let l of await a.fs.list(s?s.rest:"/"))t.push({...l,path:`/${o}${V(l.path)}`});return t},stat:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)return null;let o=s.fs.stat?await s.fs.stat(t.rest):(await s.fs.list(t.rest)).find(a=>V(a.path)===t.rest)??null;return o?{...o,path:n}:null},read:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)throw new Error(`No such file: ${n}`);return s.fs.read(t.rest)}}}userFS(){return{description:"the user's skills, shared by every conversation",list:async e=>sr(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>Bo(this.lib,e),read:async e=>{let n=await this.lib.get(e);if(!n)throw new Error(`No such file: ${e}`);return n.data},write:async(e,n,t)=>{await this.lib.put({path:e,data:n,contentType:t??dt(e,n),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,n){await this.rebuildSkills(),this.openChannel();try{this.channel?.postMessage({userSkills:!0,path:e,kind:n})}catch{}this.emitChange(this.skillsDir,"write")}async migrateSkills(){if(!await this.lib.getMeta("migrated:2")){for(let n of await this.lib.listMeta("zip:"))n.source==="upload"&&!await this.lib.get(`/${n.name}.zip`)&&await this.lib.put({path:`/${n.name}.zip`,data:n.bytes,contentType:"application/zip",mtime:n.at||Date.now(),layer:"work"});for(let n of["zip:","removed:"])for(let t of await this.lib.listMetaKeys(n))await this.lib.deleteMeta(t);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 n=new Set;for(let t of await this.store.listMetaKeys("skills:")){let s=await this.store.getMeta(t);if(!t.startsWith("skills:upload:"))for(let o of s?.files??[])n.add(o);await this.store.deleteMeta(t)}for(let t of e){let s=t.path.slice(this.skillsDir.length);!n.has(t.path)&&this.userSkillsDir&&!await this.lib.get(s)&&await this.lib.put({...t,path:s,layer:"work"}),await this.store.delete(t.path)}}await this.store.putMeta("skills-migrated:2",!0)}async fetchSource(e,n){if(e.startsWith("files:")){if(!this.provider?.readFile)throw new Error("a files: skills source needs a provider that reads files (RunApps)");let a=await this.provider.readFile(e.slice(6),{etag:n?.etag});if(!a)return null;if(a.bytes.byteLength>52428800)throw new Error("skills zip too large");return a}let t={};n?.etag?t["If-None-Match"]=n.etag:n?.lastModified&&(t["If-Modified-Since"]=n.lastModified);let s=await this.fetchFn(e,{headers:t,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 V(r){let e=[];for(let n of String(r??"").replace(/\\/g,"/").split("/"))if(!(!n||n===".")){if(n===".."){e.pop();continue}e.push(n)}return"/"+e.join("/")}function Go(r){return{path:r.path,size:Yr(r.data),contentType:r.contentType,mtime:r.mtime}}function Yr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var Bl=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"]),Wo={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 dt(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return Wo[n]?Wo[n]:typeof e=="string"||Bl.has(n)?"text/plain":"application/octet-stream"}function pt(r){let e=r.subarray(0,8192);for(let n=0;n<e.length;n++)if(e[n]===0)return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return null}}var Ko=r=>typeof Blob<"u"&&r instanceof Blob,Wl=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Jr(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var Kl=4;function Vl(r,e,n){return new Promise((t,s)=>{let o=r.open(e,Kl);o.onupgradeneeded=a=>{let l=o.result,d=o.transaction,p=a.oldVersion,u=()=>l.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(p<3){for(let w of["files","meta","sessions"])l.objectStoreNames.contains(w)&&l.deleteObjectStore(w);l.createObjectStore("files",{keyPath:["space","path"]}),l.createObjectStore("meta",{keyPath:["space","key"]}),u();return}if(p<4){let w=d.objectStore("sessions").getAll();w.onsuccess=()=>{let b=w.result;l.deleteObjectStore("sessions"),u();let x=d.objectStore("sessions");for(let M of b)M.id&&x.put({...M,space:M.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 a=o.result;a.onversionchange=()=>a.close();let l=(p,u,w)=>new Promise((b,x)=>{let M=a.transaction(p,u),S=w(M.objectStore(p)),A;S.onsuccess=()=>{A=S.result,u==="readonly"&&b(A)},S.onerror=()=>x(S.error??new Error("indexedDB request failed")),M.oncomplete=()=>b(A),M.onabort=()=>x(M.error??new Error("indexedDB transaction aborted"))}),d=(p,u)=>IDBKeyRange.bound([p,u],[p,u+"\uFFFF"],!1,!1);t({get:p=>l("files","readonly",u=>u.get([n,p])),put:async p=>{await l("files","readwrite",u=>u.put({...p,space:n}))},delete:async p=>{await l("files","readwrite",u=>u.delete([n,p]))},list:p=>l("files","readonly",u=>u.getAll(d(n,p))),getMeta:async p=>(await l("meta","readonly",u=>u.get([n,p])))?.value,putMeta:async(p,u)=>{await l("meta","readwrite",w=>w.put({space:n,key:p,value:u}))},deleteMeta:async p=>{await l("meta","readwrite",u=>u.delete([n,p]))},listMeta:async p=>(await l("meta","readonly",u=>u.getAll(d(n,p)))).map(u=>u.value),listMetaKeys:async p=>(await l("meta","readonly",u=>u.getAll(d(n,p)))).map(u=>u.key),getSession:(p,u)=>l("sessions","readonly",w=>w.get([p,u])),putSession:async p=>{await l("sessions","readwrite",u=>u.put(p))},deleteSession:async(p,u)=>{await l("sessions","readwrite",w=>w.delete([p,u]))},listSessions:()=>l("sessions","readonly",p=>p.getAll()),clear:async(p=n)=>{await l("files","readwrite",u=>u.delete(d(p,"/"))),await l("meta","readwrite",u=>u.delete(d(p,""))),await l("sessions","readwrite",u=>u.delete(d(p,"")))},close:()=>a.close()})}})}var Vo=new Map;function Gl(r,e){let n=Vo.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},Vo.set(r,n));let t=n,s=()=>{let a=t.files.get(e);return a||(a=new Map,t.files.set(e,a)),a},o=()=>{let a=t.meta.get(e);return a||(a=new Map,t.meta.set(e,a)),a};return{get:async a=>s().get(a),put:async a=>{s().set(a.path,{...a,space:e})},delete:async a=>{s().delete(a)},list:async a=>[...s().values()].filter(l=>a==="/"||l.path.startsWith(a)),getMeta:async a=>o().get(a),putMeta:async(a,l)=>{o().set(a,l)},deleteMeta:async a=>{o().delete(a)},listMeta:async a=>[...o()].filter(([l])=>l.startsWith(a)).map(([,l])=>l),listMetaKeys:async a=>[...o().keys()].filter(l=>l.startsWith(a)),getSession:async(a,l)=>t.sessions.get(`${a}\0${l}`),putSession:async a=>{t.sessions.set(`${a.space??e}\0${a.id}`,a)},deleteSession:async(a,l)=>{t.sessions.delete(`${a}\0${l}`)},listSessions:async()=>[...t.sessions.values()],clear:async(a=e)=>{t.files.delete(a),t.meta.delete(a);for(let[l,d]of t.sessions)d.space===a&&t.sessions.delete(l)},close:()=>{}}}var $t="Untitled";function Bt(r){for(let e of r.messages){if(e.role!=="user"||Ze(e)!==null)continue;let n=e.typed,s=(typeof n=="string"?n: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||Qr(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return $t}function Qr(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Zl(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function Zo(r={},e={}){let n=new Map;for(let[s,o]of Object.entries(r))n.set(V(s),o);let t={files:n,description:e.description,async list(s){let o=V(s);return[...n.entries()].filter(([a])=>o==="/"||a===o||a.startsWith(o+"/")).map(([a,l])=>({path:a,size:Yr(l)}))},async read(s){let o=n.get(V(s));if(o===void 0)throw new Error(`No such file: ${V(s)}`);return o}};return e.readonly||(t.write=async(s,o)=>{n.set(V(s),o)},t.delete=async s=>{if(!n.delete(V(s)))throw new Error(`No such file: ${V(s)}`)}),t}var Xl=4*1024*1024;function Jl(r){let e=typeof r=="string"?r:pt(r),n=2166136261;if(e!==null)for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);else for(let t of r)n^=t,n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Yl(r,e,n){if(n<e)return!1;let t=r.some(([o,a])=>o<=e&&a>=n);r.push([e,n]),r.sort((o,a)=>o[0]-a[0]);let s=[];for(let o of r){let a=s[s.length-1];a&&o[0]<=a[1]+1?a[1]=Math.max(a[1],o[1]):s.push([o[0],o[1]])}return r.splice(0,r.length,...s),!t}var Wt=class extends Error{constructor(n,t,s){super(n);z(this,"path",t);z(this,"coveredTo",s);this.name="PartialReadError"}};function fn(r,e={}){let n=e.enabled!==!1,t=new Map,s=async(o,a)=>{let l=await r.stat(o);if(!l)return null;let d=l.size>Xl?"":Jl(a??(await r.read(o)).data);return`${l.mtime??""}:${l.size}:${d}`};return{enabled:n,async saw(o,a={}){if(!n)return;let l=await s(o,a.text).catch(()=>null);if(!l)return t.delete(o),!0;let d=a.start??1,p=a.end??1/0,u=a.total??1/0,w=t.get(o),b=!!w&&w.version===l,x=b&&d<=w.coveredTo+1?Math.max(w.coveredTo,p):d<=1?p:0,M=b?w.ranges:[],S=Yl(M,d,p)||!b;return t.set(o,{version:l,coveredTo:x,total:u,ranges:M}),S},async wrote(o){if(!n)return;let a=await s(o).catch(()=>null);a?t.set(o,{version:a,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):t.delete(o)},async copied(o,a){if(!n)return;let l=t.get(o),d=l?await s(a).catch(()=>null):null;l&&d?t.set(a,{...l,version:d,ranges:l.ranges.map(([p,u])=>[p,u])}):t.delete(a)},async edited(o){if(!n)return;let a=t.get(o),l=await s(o).catch(()=>null);l&&a?t.set(o,{...a,version:l,total:1/0,ranges:[]}):t.delete(o)},async check(o,a){if(!n)return;let l=await s(o);if(l===null)return;let d=t.get(o);if(!d){if(a==="delete")return;throw new Error(`${o} already exists and you have not read it in this conversation: read it with read_file first, then ${a} it.`)}if(d.version!==l)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 ${a==="delete"?"decide whether to delete it":"make your change on the current content"}.`);if(a==="overwrite"&&d.coveredTo<d.total)throw new Wt(`You have read only lines 1-${d.coveredTo} of ${o}: read the rest (read_file with offset=${d.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,o,d.coveredTo)},async known(o){let a=t.get(o);return!a||await s(o).catch(()=>null)!==a.version?"none":a.coveredTo>=a.total?"all":a.coveredTo>0?"part":"none"},forget(o){t.delete(o)},retain(o){let a=new Set(o);for(let l of[...t.keys()])a.has(l)||t.delete(l)},clear(){t.clear()}}}var es=500,ts=2e3,ns=50*1024,rs=100,Xo=5*1024*1024,Ql={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},ec={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function tc(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function ss(r,e={}){let n=e.guard??fn(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[je({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}){let o=await r.list(s||"/");if(!o.length)return`No files under ${V(s||"/")}.`;let a=o.slice(0,es).map(l=>`${l.path} (${l.size} B)`);return o.length>es&&a.push(`
|
|
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 di="/.agent/skills";var jl="__runapps_agent_ws",pi="/skills",Nl="\0skills",li=r=>typeof r=="object"&&!(r instanceof Uint8Array)&&typeof r.load=="function",rr=new WeakMap,Xr=new Map,qo=new WeakMap,ql=1,ci=r=>{let e=qo.get(r);return e||(e=ql++,qo.set(r,e)),e},sr=async(r,e)=>r.listStats?r.listStats(e):(await r.list(e)).map(Go),Bo=async(r,e)=>{if(r.stat)return r.stat(e);let n=await r.get(e);return n?Go(n):null},un=class r{constructor(e,n={}){z(this,"id");z(this,"dbName");z(this,"skillsDir");z(this,"userSkillsDir");z(this,"root");z(this,"store");z(this,"lib");z(this,"mounts",new Map);z(this,"skillViews",new Map);z(this,"builtins",[]);z(this,"lazySkills",[]);z(this,"resolvedSources",[]);z(this,"changeListeners",new Set);z(this,"channel");z(this,"sources");z(this,"provider");z(this,"inflate");z(this,"fetchFn");z(this,"fetchKey");z(this,"idb");z(this,"storeFactory");z(this,"skillCache",null);z(this,"opened",null);z(this,"sessions",{list:async()=>(await this.ready(),(await this.store.listSessions()).map(e=>({id:e.id??"",title:e.title&&!Qr(e.title)?e.title:Bt(e),model:e.model,messages:e.messages.length,createdAt:e.createdAt??e.savedAt,savedAt:e.savedAt,workspace:e.space})).sort((e,n)=>n.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,n)=>{await this.ready();let t=n??(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(t,e),t===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?tt(e):null,this.id=n.id||"default",this.dbName=`${jl}:${n.project||this.provider?.name||"app"}`,this.sources=typeof n.skills=="function"?n.skills:n.skills?[].concat(n.skills):[],this.skillsDir=V(n.skillsDir||di),this.skillsDir==="/")throw new Error("skillsDir cannot be /");this.userSkillsDir=n.userSkills===!1||n.userSkillsDir===!1?null:V(n.userSkillsDir||pi);let t=(s,o)=>s===o||s.startsWith(o+"/")||o.startsWith(s+"/");if(this.userSkillsDir==="/"||this.userSkillsDir&&t(this.userSkillsDir,this.skillsDir))throw new Error("userSkillsDir must be its own folder, apart from skillsDir");this.root=n.dir??null,this.inflate=n.inflate,this.fetchFn=n.fetch??((...s)=>fetch(...s)),this.fetchKey=n.fetch?`f${ci(n.fetch)}`:"",this.idb=n.indexedDB!==void 0?n.indexedDB:typeof indexedDB<"u"?indexedDB:null,this.storeFactory=n.store??null}static async open(e,n={}){let t=new r(e,n);return await t.ready(),t}ready(){if(!this.opened){let e=(async()=>{let n=t=>this.storeFactory?this.storeFactory.open(this.dbName,t):this.idb?Vl(this.idb,this.dbName,t):Promise.resolve(Gl(this.dbName,t));this.store=await n(this.id),this.lib=await n(Nl),this.openChannel(),await Zl(`${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,n){let t=V(e);if(t==="/")throw new Error("cannot mount at / (open the workspace with `dir` instead)");this.mounts.set(t,n)}unmount(e){this.mounts.delete(V(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=n=>{let t=n.data;if(t?.userSkills){if(this.lib&&this.userSkillsDir&&typeof t.path=="string"&&(t.kind==="write"||t.kind==="delete")){let s=this.userSkillsDir+t.path,o=t.kind;this.rebuildSkills().then(()=>{this.emitChange(s,o,!0),this.emitChange(this.skillsDir,"write",!0)}).catch(()=>{})}return}t&&t.space===this.id&&typeof t.path=="string"&&(t.kind==="write"||t.kind==="delete")&&this.emitChange(t.path,t.kind,!0)},e.unref?.(),this.channel=e}catch{this.channel=null}}}emitChange(e,n,t=!1){if(t&&(e==="/"||this.inSkills(e))&&(this.skillCache=null),!t){this.openChannel();try{this.channel?.postMessage({space:this.id,path:e,kind:n})}catch{}}if(!this.changeListeners.size)return;let s={path:e,kind:n,remote:t};for(let o of this.changeListeners)try{o(s)}catch(a){console.warn("agent: onChange listener failed",a)}}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[n,t]of this.mounts)n!==this.skillsDir&&n!==this.userSkillsDir&&e.push(`${n}/ \u2014 ${t.description||"app files"}${t.write?"":" (read-only)"}.`);return e.join(`
|
|
154
|
+
`)}route(e){let n=null;for(let t of this.mounts.keys())(e===t||e.startsWith(t+"/"))&&(!n||t.length>n.length)&&(n=t);return n?{fs:this.mounts.get(n),rel:e.slice(n.length)||"/",prefix:n}:this.root?{fs:this.root,rel:e,prefix:""}:null}inSkills(e){return e===this.skillsDir||e.startsWith(this.skillsDir+"/")}async putFile(e,n,t,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,n,t??dt(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??dt(e,n),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 n=V(e),t=[],s=this.route(n);if(s&&s.prefix){for(let a of await s.fs.list(s.rel))t.push({...a,path:s.prefix+V(a.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}let o=this.root?(await this.root.list(n)).map(a=>({...a,path:V(a.path)})):await sr(this.store,n==="/"?"/":n+"/");for(let a of o)this.route(a.path)?.prefix||t.push(a);for(let[a,l]of this.mounts)if(n==="/"||a.startsWith(n+"/"))for(let d of await l.list("/"))t.push({...d,path:a+V(d.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}async stat(e){await this.ready();let n=V(e),t=this.route(n);if(t){if(t.fs.stat){let o=await t.fs.stat(t.rel);return o?{...o,path:n}:null}let s=(await t.fs.list(t.rel)).find(o=>V(o.path)===V(t.rel));return s?{...s,path:n}:null}return Bo(this.store,n)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let n=V(e),t=this.route(n);if(t)try{let o=await t.fs.read(t.rel);return{data:o,size:Yr(o),contentType:dt(n,o)}}catch(o){throw new Error(await this.missing(n,o))}let s=await this.store.get(n);if(!s)throw new Error(await this.missing(n));return{data:s.data,size:Yr(s.data),contentType:s.contentType}}async isFolder(e){let n=V(e);return n==="/"||this.mounts.has(n)?!0:(await this.list(n)).some(t=>t.path!==n)}async missing(e,n){if(await this.isFolder(e))return`${e} is a folder, not a file; use list_files to see what it holds`;let t=n instanceof Error?n.message:"";return/no such file/i.test(t)||!t?`No such file: ${e}`:`${e}: ${t}`}async readText(e){let{data:n}=await this.read(e);if(typeof n=="string")return n;let t=pt(n);if(t===null)throw new Error(`${V(e)} is a binary file (${n.byteLength} bytes)`);return t}async readAsText(e){let n=V(e),{data:t,size:s,contentType:o}=await this.read(n);if(typeof t=="string")return{text:t,kind:"text"};if(cn(n,o,t)){let l=await this.stat(n),d=`pdftext:${n}`,p=await this.getData(d).catch(()=>{});if(p&&p.size===s&&p.mtime===l?.mtime)return{text:p.text,kind:"pdf"};let u=pn(n,await dn(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:u}).catch(()=>{}),{text:u,kind:"pdf"}}let a=pt(t);return a===null?null:{text:a,kind:"text"}}async write(e,n,t){await this.ready();let s=V(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,n,t),this.emitChange(s,"write");return}await this.putFile(s,n,t,"work")}async edit(e,n){await this.ready();let t=V(e),s=this.route(t);if(s?.fs.edit){await s.fs.edit(s.rel,n),this.emitChange(t,"write");return}if(s&&!s.fs.write)throw new Error(`${s.prefix||"/"} is read-only`);await this.write(t,Gr(t,await this.readText(t),n))}async delete(e){await this.ready();let n=V(e),t=this.route(n);if(t&&t.prefix){if(!t.fs.delete)throw new Error(`${t.prefix} is read-only`);await t.fs.delete(t.rel),this.emitChange(n,"delete");return}if(!await this.stat(n))throw new Error(`No such file: ${n}`);await this.rmFile(n)}mountOf(e){return this.route(V(e))?.prefix||null}isReadOnly(e){let n=this.route(V(e));return n?!n.fs.write:!1}isSkillPath(e){let n=V(e);return this.inSkills(n)||!!this.userSkillsDir&&(n===this.userSkillsDir||n.startsWith(this.userSkillsDir+"/"))}async getData(e){await this.ready();let n=await this.store.getMeta("data:"+e);return n===null?void 0:n}async putData(e,n){await this.ready(),n==null?await this.store.deleteMeta("data:"+e):await this.store.putMeta("data:"+e,n)}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=[],n=new Set;for(let[t,s]of this.skillViews){if(s.lazy){if(n.has(s.lazy.name))continue;n.add(s.lazy.name);let l=`${this.skillsDir}/${t}`;e.push({name:s.lazy.name,description:s.lazy.description,path:`${l}/SKILL.md`,dir:l,builtin:!0,lazy:!0,...s.lazy.disableModelInvocation?{disableModelInvocation:!0}:{}});continue}let o;try{let l=await s.fs.read("/SKILL.md");o=typeof l=="string"?l:pt(l)}catch{continue}if(o===null)continue;let a=Qn(o,`${this.skillsDir}/${t}/SKILL.md`);!a||n.has(a.skill.name)||(n.add(a.skill.name),e.push({...a.skill,...s.builtin?{builtin:!0}:{},...s.from?{from:s.from}:{}}))}return this.skillCache=e.sort((t,s)=>t.name.localeCompare(s.name)),this.skillCache}async installSkill(e,n={}){if(await this.ready(),!this.userSkillsDir)throw new Error("this workspace has no userSkillsDir to install skills into");let t,s;if(typeof e=="string"){let u=await this.fetchSource(e);if(!u)throw new Error("nothing fetched");t=u.bytes,s=n.name??e}else t=e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer()),s=n.name??(e.name||"skill");if(t.byteLength>52428800)throw new Error("skills zip too large");let o=Jr(s),a=ai(t),l=er(a.keys(),o);if(!l.size)throw new Error(`${o}.zip has no SKILL.md (at its root, or one per folder)`);let d=Date.now();if(n.unpack){for(let[u,w]of l){for(let x of await sr(this.lib,`/${u}/`))await this.lib.delete(x.path);for(let[x,b]of a){if(!x.startsWith(w))continue;let M=await sn(t,b,this.inflate),T=pt(M),A=V(`/${u}/${x.slice(w.length)}`);await this.lib.put({path:A,data:T??M,contentType:dt(A,T??M),mtime:d,layer:"work"})}}await this.userSkillsChanged(`/${[...l.keys()][0]}`,"write")}else await this.lib.put({path:`/${o}.zip`,data:t,contentType:"application/zip",mtime:d,layer:"work"}),await this.userSkillsChanged(`/${o}.zip`,"write");let p=new Set([...l.keys()].map(u=>`${this.skillsDir}/${u}`));return(await this.skills()).filter(u=>p.has(u.dir))}async removeSkill(e){let n=(await this.skills()).find(s=>s.name===e);if(!n)return!1;if(n.builtin)throw new Error(`"${e}" comes with the app and cannot be removed`);if(!n.from||!this.userSkillsDir||!n.from.startsWith(this.userSkillsDir+"/"))return!1;let t=n.from.slice(this.userSkillsDir.length);if(/\.zip$/i.test(t))await this.lib.delete(t);else for(let s of await sr(this.lib,t+"/"))await this.lib.delete(s.path);return await this.userSkillsChanged(t,"delete"),!0}async skillBody(e){let n=(await this.skills()).find(s=>s.name===e);if(!n)throw new Error(`No skill named "${e}"`);let t=Qn(await this.readText(n.path),n.path);return{skill:n,body:t?.body??""}}async refreshSkills(){await this.ready();for(let e of this.resolvedSources){if(li(e)){rr.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!Ko(e)&&typeof e.data=="string"?e.data:null;n&&Xr.delete(`${this.dbName}|${this.fetchKey}|${n}`)}this.builtins=await this.loadBuiltins(),await this.rebuildSkills(),this.emitChange(this.skillsDir,"write")}async loadBuiltins(){let e=[],n=[];try{n=typeof this.sources=="function"?[].concat(await this.sources()):this.sources}catch(t){console.warn("[agent] the skills list failed:",t)}this.resolvedSources=n,this.lazySkills=n.filter(li);for(let t of n)if(!li(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!Ko(t)?t:null,o=s?s.data:t,a,l,d=0;if(typeof o=="string"){let u=`${this.dbName}|${this.fetchKey}|${o}`,w=Xr.get(u);w||(w=this.fetchSource(o).then(x=>{if(!x)throw new Error("nothing fetched");return{bytes:x.bytes,at:Date.now()}}),Xr.set(u,w),w.catch(()=>Xr.delete(u))),{bytes:a,at:d}=await w,l=`app:${u}@${d}`}else a=o instanceof Uint8Array?o:new Uint8Array(await o.arrayBuffer()),l=`app:${this.dbName}|obj${ci(o)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let p=Jr(s?.name??(typeof o=="string"?o:o.name||"skills"));e.push({name:p,bytes:a,key:l,at:d})}catch(s){console.warn("[agent] skills source failed:",s)}return e}async rebuildSkills(){let e=new Map;for(let n of this.builtins)try{let t=Zr(n.name,n.bytes,n.key);for(let[s,o]of t.folders)e.has(s)||e.set(s,{fs:an(t,o,n.at,this.inflate),builtin:!0})}catch(t){console.warn(`[agent] skills zip "${n.name}":`,t)}for(let n of this.lazySkills){let t=/^[A-Za-z0-9][\w.-]*$/.test(n.name)?n.name:Jr(n.name);e.has(t)||e.set(t,{fs:this.lazyFS(n,t),builtin:!0,lazy:n})}if(this.root)for(let n of await this.root.list(this.skillsDir).catch(()=>[])){let t=new RegExp("^"+Wl(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(V(n.path));t&&e.set(t[1],{fs:tr(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await sr(this.lib,"/");for(let s of n){let o=/^\/([^/]+)\.zip$/i.exec(s.path);if(o)try{let a=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,l=s.mtime!==void 0?Ho(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=Zr(Jr(o[1]),d.data,a)}for(let[d,p]of l.folders)e.set(d,{fs:an(l,p,s.mtime??0,this.inflate),builtin:!1,from:this.userSkillsDir+s.path})}catch(a){console.warn(`[agent] skills zip "${s.path}":`,a)}}let t=this.userFS();for(let s of n){let o=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);o&&e.set(o[1],{fs:tr(t,`/${o[1]}`),builtin:!1,from:`${this.userSkillsDir}/${o[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,n){let t=null,s=async()=>{if(t)return t;let a=rr.get(e);a||(a=(async()=>{let u=await e.load();if(typeof u=="string"){let w=await this.fetchSource(u);if(!w)throw new Error("nothing fetched");return w.bytes}return u instanceof Uint8Array?u:u instanceof ArrayBuffer?new Uint8Array(u):new Uint8Array(await u.arrayBuffer())})(),rr.set(e,a),a.catch(()=>{rr.get(e)===a&&rr.delete(e)}));let l;try{l=await a}catch(u){throw new Error(`the skill "${e.name}" could not be loaded: ${u.message}`)}if(l.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let d=Zr(n,l,`lazy:${ci(e)}:${l.byteLength}`),p=d.folders.get(n)??[...d.folders.values()][0];if(p===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return t=an(d,p,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${n}`,"write"),t},o=a=>a==="/"||a==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async a=>t?t.list(a):o(a),stat:async a=>{if(!t&&a==="/SKILL.md")return{path:a,size:0};let l=await s();return l.stat?l.stat(a):null},read:async a=>(await s()).read(a)}}skillsFS(){let e=n=>{let t=/^\/([^/]+)(\/.*)?$/.exec(n);return t?{name:t[1],rest:t[2]||"/"}:null};return{description:"skills (generated, read-only)",list:async n=>{let t=[],s=e(n);for(let[o,a]of this.skillViews)if(!(s&&s.name!==o))for(let l of await a.fs.list(s?s.rest:"/"))t.push({...l,path:`/${o}${V(l.path)}`});return t},stat:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)return null;let o=s.fs.stat?await s.fs.stat(t.rest):(await s.fs.list(t.rest)).find(a=>V(a.path)===t.rest)??null;return o?{...o,path:n}:null},read:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)throw new Error(`No such file: ${n}`);return s.fs.read(t.rest)}}}userFS(){return{description:"the user's skills, shared by every conversation",list:async e=>sr(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>Bo(this.lib,e),read:async e=>{let n=await this.lib.get(e);if(!n)throw new Error(`No such file: ${e}`);return n.data},write:async(e,n,t)=>{await this.lib.put({path:e,data:n,contentType:t??dt(e,n),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,n){await this.rebuildSkills(),this.openChannel();try{this.channel?.postMessage({userSkills:!0,path:e,kind:n})}catch{}this.emitChange(this.skillsDir,"write")}async migrateSkills(){if(!await this.lib.getMeta("migrated:2")){for(let n of await this.lib.listMeta("zip:"))n.source==="upload"&&!await this.lib.get(`/${n.name}.zip`)&&await this.lib.put({path:`/${n.name}.zip`,data:n.bytes,contentType:"application/zip",mtime:n.at||Date.now(),layer:"work"});for(let n of["zip:","removed:"])for(let t of await this.lib.listMetaKeys(n))await this.lib.deleteMeta(t);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 n=new Set;for(let t of await this.store.listMetaKeys("skills:")){let s=await this.store.getMeta(t);if(!t.startsWith("skills:upload:"))for(let o of s?.files??[])n.add(o);await this.store.deleteMeta(t)}for(let t of e){let s=t.path.slice(this.skillsDir.length);!n.has(t.path)&&this.userSkillsDir&&!await this.lib.get(s)&&await this.lib.put({...t,path:s,layer:"work"}),await this.store.delete(t.path)}}await this.store.putMeta("skills-migrated:2",!0)}async fetchSource(e,n){if(e.startsWith("files:")){if(!this.provider?.readFile)throw new Error("a files: skills source needs a provider that reads files (RunApps)");let a=await this.provider.readFile(e.slice(6),{etag:n?.etag});if(!a)return null;if(a.bytes.byteLength>52428800)throw new Error("skills zip too large");return a}let t={};n?.etag?t["If-None-Match"]=n.etag:n?.lastModified&&(t["If-Modified-Since"]=n.lastModified);let s=await this.fetchFn(e,{headers:t,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 V(r){let e=[];for(let n of String(r??"").replace(/\\/g,"/").split("/"))if(!(!n||n===".")){if(n===".."){e.pop();continue}e.push(n)}return"/"+e.join("/")}function Go(r){return{path:r.path,size:Yr(r.data),contentType:r.contentType,mtime:r.mtime}}function Yr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var Bl=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"]),Wo={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 dt(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return Wo[n]?Wo[n]:typeof e=="string"||Bl.has(n)?"text/plain":"application/octet-stream"}function pt(r){let e=r.subarray(0,8192);for(let n=0;n<e.length;n++)if(e[n]===0)return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return null}}var Ko=r=>typeof Blob<"u"&&r instanceof Blob,Wl=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Jr(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var Kl=4;function Vl(r,e,n){return new Promise((t,s)=>{let o=r.open(e,Kl);o.onupgradeneeded=a=>{let l=o.result,d=o.transaction,p=a.oldVersion,u=()=>l.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(p<3){for(let w of["files","meta","sessions"])l.objectStoreNames.contains(w)&&l.deleteObjectStore(w);l.createObjectStore("files",{keyPath:["space","path"]}),l.createObjectStore("meta",{keyPath:["space","key"]}),u();return}if(p<4){let w=d.objectStore("sessions").getAll();w.onsuccess=()=>{let x=w.result;l.deleteObjectStore("sessions"),u();let b=d.objectStore("sessions");for(let M of x)M.id&&b.put({...M,space:M.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 a=o.result;a.onversionchange=()=>a.close();let l=(p,u,w)=>new Promise((x,b)=>{let M=a.transaction(p,u),T=w(M.objectStore(p)),A;T.onsuccess=()=>{A=T.result,u==="readonly"&&x(A)},T.onerror=()=>b(T.error??new Error("indexedDB request failed")),M.oncomplete=()=>x(A),M.onabort=()=>b(M.error??new Error("indexedDB transaction aborted"))}),d=(p,u)=>IDBKeyRange.bound([p,u],[p,u+"\uFFFF"],!1,!1);t({get:p=>l("files","readonly",u=>u.get([n,p])),put:async p=>{await l("files","readwrite",u=>u.put({...p,space:n}))},delete:async p=>{await l("files","readwrite",u=>u.delete([n,p]))},list:p=>l("files","readonly",u=>u.getAll(d(n,p))),getMeta:async p=>(await l("meta","readonly",u=>u.get([n,p])))?.value,putMeta:async(p,u)=>{await l("meta","readwrite",w=>w.put({space:n,key:p,value:u}))},deleteMeta:async p=>{await l("meta","readwrite",u=>u.delete([n,p]))},listMeta:async p=>(await l("meta","readonly",u=>u.getAll(d(n,p)))).map(u=>u.value),listMetaKeys:async p=>(await l("meta","readonly",u=>u.getAll(d(n,p)))).map(u=>u.key),getSession:(p,u)=>l("sessions","readonly",w=>w.get([p,u])),putSession:async p=>{await l("sessions","readwrite",u=>u.put(p))},deleteSession:async(p,u)=>{await l("sessions","readwrite",w=>w.delete([p,u]))},listSessions:()=>l("sessions","readonly",p=>p.getAll()),clear:async(p=n)=>{await l("files","readwrite",u=>u.delete(d(p,"/"))),await l("meta","readwrite",u=>u.delete(d(p,""))),await l("sessions","readwrite",u=>u.delete(d(p,"")))},close:()=>a.close()})}})}var Vo=new Map;function Gl(r,e){let n=Vo.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},Vo.set(r,n));let t=n,s=()=>{let a=t.files.get(e);return a||(a=new Map,t.files.set(e,a)),a},o=()=>{let a=t.meta.get(e);return a||(a=new Map,t.meta.set(e,a)),a};return{get:async a=>s().get(a),put:async a=>{s().set(a.path,{...a,space:e})},delete:async a=>{s().delete(a)},list:async a=>[...s().values()].filter(l=>a==="/"||l.path.startsWith(a)),getMeta:async a=>o().get(a),putMeta:async(a,l)=>{o().set(a,l)},deleteMeta:async a=>{o().delete(a)},listMeta:async a=>[...o()].filter(([l])=>l.startsWith(a)).map(([,l])=>l),listMetaKeys:async a=>[...o().keys()].filter(l=>l.startsWith(a)),getSession:async(a,l)=>t.sessions.get(`${a}\0${l}`),putSession:async a=>{t.sessions.set(`${a.space??e}\0${a.id}`,a)},deleteSession:async(a,l)=>{t.sessions.delete(`${a}\0${l}`)},listSessions:async()=>[...t.sessions.values()],clear:async(a=e)=>{t.files.delete(a),t.meta.delete(a);for(let[l,d]of t.sessions)d.space===a&&t.sessions.delete(l)},close:()=>{}}}var $t="Untitled";function Bt(r){for(let e of r.messages){if(e.role!=="user"||Ze(e)!==null)continue;let n=e.typed,s=(typeof n=="string"?n: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||Qr(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return $t}function Qr(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Zl(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function Zo(r={},e={}){let n=new Map;for(let[s,o]of Object.entries(r))n.set(V(s),o);let t={files:n,description:e.description,async list(s){let o=V(s);return[...n.entries()].filter(([a])=>o==="/"||a===o||a.startsWith(o+"/")).map(([a,l])=>({path:a,size:Yr(l)}))},async read(s){let o=n.get(V(s));if(o===void 0)throw new Error(`No such file: ${V(s)}`);return o}};return e.readonly||(t.write=async(s,o)=>{n.set(V(s),o)},t.delete=async s=>{if(!n.delete(V(s)))throw new Error(`No such file: ${V(s)}`)}),t}var Xl=4*1024*1024;function Jl(r){let e=typeof r=="string"?r:pt(r),n=2166136261;if(e!==null)for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);else for(let t of r)n^=t,n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Yl(r,e,n){if(n<e)return!1;let t=r.some(([o,a])=>o<=e&&a>=n);r.push([e,n]),r.sort((o,a)=>o[0]-a[0]);let s=[];for(let o of r){let a=s[s.length-1];a&&o[0]<=a[1]+1?a[1]=Math.max(a[1],o[1]):s.push([o[0],o[1]])}return r.splice(0,r.length,...s),!t}var Wt=class extends Error{constructor(n,t,s){super(n);z(this,"path",t);z(this,"coveredTo",s);this.name="PartialReadError"}};function fn(r,e={}){let n=e.enabled!==!1,t=new Map,s=async(o,a)=>{let l=await r.stat(o);if(!l)return null;let d=l.size>Xl?"":Jl(a??(await r.read(o)).data);return`${l.mtime??""}:${l.size}:${d}`};return{enabled:n,async saw(o,a={}){if(!n)return;let l=await s(o,a.text).catch(()=>null);if(!l)return t.delete(o),!0;let d=a.start??1,p=a.end??1/0,u=a.total??1/0,w=t.get(o),x=!!w&&w.version===l,b=x&&d<=w.coveredTo+1?Math.max(w.coveredTo,p):d<=1?p:0,M=x?w.ranges:[],T=Yl(M,d,p)||!x;return t.set(o,{version:l,coveredTo:b,total:u,ranges:M}),T},async wrote(o){if(!n)return;let a=await s(o).catch(()=>null);a?t.set(o,{version:a,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):t.delete(o)},async copied(o,a){if(!n)return;let l=t.get(o),d=l?await s(a).catch(()=>null):null;l&&d?t.set(a,{...l,version:d,ranges:l.ranges.map(([p,u])=>[p,u])}):t.delete(a)},async edited(o){if(!n)return;let a=t.get(o),l=await s(o).catch(()=>null);l&&a?t.set(o,{...a,version:l,total:1/0,ranges:[]}):t.delete(o)},async check(o,a){if(!n)return;let l=await s(o);if(l===null)return;let d=t.get(o);if(!d){if(a==="delete")return;throw new Error(`${o} already exists and you have not read it in this conversation: read it with read_file first, then ${a} it.`)}if(d.version!==l)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 ${a==="delete"?"decide whether to delete it":"make your change on the current content"}.`);if(a==="overwrite"&&d.coveredTo<d.total)throw new Wt(`You have read only lines 1-${d.coveredTo} of ${o}: read the rest (read_file with offset=${d.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,o,d.coveredTo)},async known(o){let a=t.get(o);return!a||await s(o).catch(()=>null)!==a.version?"none":a.coveredTo>=a.total?"all":a.coveredTo>0?"part":"none"},forget(o){t.delete(o)},retain(o){let a=new Set(o);for(let l of[...t.keys()])a.has(l)||t.delete(l)},clear(){t.clear()}}}var es=500,ts=2e3,ns=50*1024,rs=100,Xo=5*1024*1024,Ql={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},ec={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function tc(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function ss(r,e={}){let n=e.guard??fn(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[He({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}){let o=await r.list(s||"/");if(!o.length)return`No files under ${V(s||"/")}.`;let a=o.slice(0,es).map(l=>`${l.path} (${l.size} B)`);return o.length>es&&a.push(`
|
|
155
155
|
[${es} entries limit reached (${o.length} in all). List a sub-folder.]`),a.join(`
|
|
156
|
-
`)}}),
|
|
156
|
+
`)}}),He({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:a},l){if(await r.isFolder(s)){let O=await r.list(s);return`${V(s)} is a folder with ${O.length} file${O.length===1?"":"s"}:
|
|
157
157
|
`+O.slice(0,es).map(te=>`${te.path} (${te.size} B)`).join(`
|
|
158
|
-
`)}let d=await r.stat(s),p=d&&Ql[(d.contentType??"").split(";")[0].trim()]?d.contentType.split(";")[0].trim():ec[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(d&&p&&await l.agent?.accepts("image")===!0){if(d.size>Xo)return`${V(s)} is a picture of ${d.size} bytes, more than the ${Xo/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:O}=await r.read(s),te=typeof O=="string"?new TextEncoder().encode(O):O;return await n.saw(V(s)),[{type:"text",text:`${V(s)} (${p}, ${te.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${p};base64,${tc(te)}`}}]}let u;try{u=await r.readAsText(s)}catch(O){if(await r.stat(s)&&/\.pdf$/i.test(s))return`Could not read the PDF ${V(s)}: ${O.message}`;throw O}if(!u){await n.saw(V(s));let O=await r.stat(s),te=p&&await l.agent?.accepts("image")===!1?" The model in use cannot view pictures.":"";return`${V(s)} is a binary file (${O?.contentType??"unknown type"}, ${O?.size??0} bytes).${te}`}let w=u.text,
|
|
159
|
-
`),x
|
|
158
|
+
`)}let d=await r.stat(s),p=d&&Ql[(d.contentType??"").split(";")[0].trim()]?d.contentType.split(";")[0].trim():ec[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(d&&p&&await l.agent?.accepts("image")===!0){if(d.size>Xo)return`${V(s)} is a picture of ${d.size} bytes, more than the ${Xo/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:O}=await r.read(s),te=typeof O=="string"?new TextEncoder().encode(O):O;return await n.saw(V(s)),[{type:"text",text:`${V(s)} (${p}, ${te.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${p};base64,${tc(te)}`}}]}let u;try{u=await r.readAsText(s)}catch(O){if(await r.stat(s)&&/\.pdf$/i.test(s))return`Could not read the PDF ${V(s)}: ${O.message}`;throw O}if(!u){await n.saw(V(s));let O=await r.stat(s),te=p&&await l.agent?.accepts("image")===!1?" The model in use cannot view pictures.":"";return`${V(s)} is a binary file (${O?.contentType??"unknown type"}, ${O?.size??0} bytes).${te}`}let w=u.text,x=w.split(`
|
|
159
|
+
`),b=x.length,M=Math.max(1,o??1);if(M>b)return await n.saw(V(s),{start:b+1,end:b,total:b}),`Offset ${M} is beyond end of file (${b} lines total)`;let T=a!==void 0?Math.min(a,ts):ts,A=[],P=0,_=M-1;for(let O=M-1;O<b&&A.length<T;O++){let te=new TextEncoder().encode(x[O]).byteLength+1;if(P+te>ns&&A.length>0)break;A.push(x[O]),P+=te,_=O+1}let C=await n.saw(V(s),{start:M,end:_,total:b,text:u.kind==="text"?w:void 0});C!==void 0&&l.progress?.(C);let N="";if(_<b){let O=_+1;P>=ns||a===void 0&&A.length>=ts?N=`
|
|
160
160
|
|
|
161
|
-
[Showing lines ${M}-${_} of ${
|
|
161
|
+
[Showing lines ${M}-${_} of ${b}${P>=ns?" (50.0KB limit)":""}. Use offset=${O} to continue.]`:N=`
|
|
162
162
|
|
|
163
|
-
[${
|
|
164
|
-
`)+N}}),
|
|
165
|
-
`).length:0,M=
|
|
166
|
-
`),M=
|
|
163
|
+
[${b-_} more lines in file. Use offset=${O} to continue.]`}return A.join(`
|
|
164
|
+
`)+N}}),He({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."+(t?" 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"},...t?{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:a},l){let d=V(s),p=await r.exists(d),u="";if(p&&a===!0&&t){let w=await n.known(d);if(w!=="all"){let x=await r.readAsText(d).catch(()=>null),b=x?.kind==="text"?x.text.split(`
|
|
165
|
+
`).length:0,M=b?` (${b} line${b===1?"":"s"})`:"";u=w==="part"?` Its previous content${M} was replaced, including the part you had not read.`:` Its previous content${M} was replaced without being read.`}}else if(p)try{await n.check(d,"overwrite")}catch(w){if(!(w instanceof Wt))throw w;let x=await r.readAsText(d).catch(()=>null);if(x?.kind!=="text")throw w;let b=x.text.split(`
|
|
166
|
+
`),M=b.length,T=w.coveredTo+1,A=[],P=0,_=w.coveredTo;for(let O=T-1;O<M&&A.length<ts;O++){let te=new TextEncoder().encode(b[O]).byteLength+1;if(P+te>ns&&A.length>0)break;A.push(b[O]),P+=te,_=O+1}let C=await n.saw(d,{start:T,end:_,total:M,text:x.text});C!==void 0&&l.progress?.(C);let N=_<M?` Lines ${_+1}-${M} are still unread: read them with read_file offset=${_+1} before overwriting.`:"";throw new Error(`${d} was not overwritten: you had read only lines 1-${w.coveredTo} of its ${M}. Here are lines ${T}-${_}, which now count as read.${N} 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
|
${A.join(`
|
|
169
|
-
`)}`)}return await r.write(d,o),await n.wrote(d),`${p?u?"Replaced":"Updated":"Created"} ${d} (${new TextEncoder().encode(o).byteLength} bytes).${u}`}}),
|
|
170
|
-
`);for(let M=0;M<
|
|
169
|
+
`)}`)}return await r.write(d,o),await n.wrote(d),`${p?u?"Replaced":"Updated":"Created"} ${d} (${new TextEncoder().encode(o).byteLength} bytes).${u}`}}),He({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."+(t?" 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=V(s.path),a=Array.isArray(s.edits)?[...s.edits]:[];return s.oldText!==void 0&&a.push({oldText:s.oldText,newText:s.newText??""}),await n.check(o,"edit"),await r.edit(o,a),await n.edited(o),`Successfully replaced ${a.length} block(s) in ${o}.`}}),He({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 ${V(s)}?`,async execute({path:s}){let o=V(s);return await n.check(o,"delete"),await r.delete(o),n.forget(o),`Deleted ${o}.`}}),...["move_file","copy_file"].map(s=>He({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:a}){let l=V(o),d=V(a);if(l===d)throw new Error("The source and the destination are the same path.");if(!await r.exists(l)||await r.isFolder(l))throw new Error(`No such file: ${l}`);if(await r.exists(d))throw new Error(`${d} already exists. Choose another path, or delete it first.`);if(s==="move_file"&&r.isReadOnly(l))throw new Error(`${l} is read-only.`);s==="move_file"&&await n.check(l,"delete");let{data:p,contentType:u}=await r.read(l);return await r.write(d,p,u),await n.copied(l,d),s==="move_file"&&(await r.delete(l),n.forget(l)),`${s==="move_file"?"Moved":"Copied"} ${l} to ${d}.`}})),He({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:a},l){let d;try{d=a?new RegExp(s,"i"):new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i")}catch(w){throw new Error(`Invalid regular expression: ${w.message}`)}let p=[],u=0;for(let w of await r.list(o||"/")){if(l.signal.throwIfAborted(),w.size>2e6)continue;let x;try{x=await r.readText(w.path)}catch{continue}u++;let b=x.split(`
|
|
170
|
+
`);for(let M=0;M<b.length&&p.length<rs;M++)d.test(b[M])&&p.push(`${w.path}:${M+1}: ${b[M].trim().slice(0,200)}`);if(p.length>=rs)break}return p.length?p.join(`
|
|
171
171
|
`)+(p.length>=rs?`
|
|
172
172
|
|
|
173
173
|
[${rs} matches limit reached. Refine the pattern or search a sub-folder.]`:""):`No matches found (${u} text files searched).`}})]}function is(r,e){if(!r)return[];let n=[];return hn(r,e,"",n,0),n}function Jo(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r}function nc(r,e){let n=Jo(e);return r==="number"?n==="number"||n==="integer":r==="integer"?n==="integer":r===n}function hn(r,e,n,t,s){if(s>32)return;let o=n||"arguments";for(let a of["anyOf","oneOf"]){let l=r[a];if(Array.isArray(l)&&l.length){let d=l.filter(p=>{let u=[];return hn(p,e,n,u,s+1),u.length===0}).length;if(d===0){t.push(`${o}: does not match any allowed form`);return}if(a==="oneOf"&&d>1){t.push(`${o}: matches more than one of the allowed forms`);return}}}if(Array.isArray(r.allOf))for(let a of r.allOf)hn(a,e,n,t,s+1);if(r.type!==void 0){let a=Array.isArray(r.type)?r.type:[r.type];if(!a.some(l=>nc(l,e))){t.push(`${o}: expected ${a.join(" or ")}, got ${Jo(e)}`);return}}if(Array.isArray(r.enum)&&!r.enum.some(a=>ui(a,e))){t.push(`${o}: must be one of ${r.enum.map(a=>JSON.stringify(a)).join(", ")}`);return}if("const"in r&&!ui(r.const,e)){t.push(`${o}: must be ${JSON.stringify(r.const)}`);return}if(typeof e=="string"){if(typeof r.minLength=="number"&&e.length<r.minLength&&t.push(`${o}: shorter than ${r.minLength} characters`),typeof r.maxLength=="number"&&e.length>r.maxLength&&t.push(`${o}: longer than ${r.maxLength} characters`),typeof r.pattern=="string")try{new RegExp(r.pattern,"u").test(e)||t.push(`${o}: does not match pattern ${r.pattern}`)}catch{}}else if(typeof e=="number")typeof r.minimum=="number"&&e<r.minimum&&t.push(`${o}: below minimum ${r.minimum}`),typeof r.maximum=="number"&&e>r.maximum&&t.push(`${o}: above maximum ${r.maximum}`),typeof r.exclusiveMinimum=="number"&&e<=r.exclusiveMinimum&&t.push(`${o}: must be greater than ${r.exclusiveMinimum}`),typeof r.exclusiveMaximum=="number"&&e>=r.exclusiveMaximum&&t.push(`${o}: must be less than ${r.exclusiveMaximum}`);else if(Array.isArray(e))typeof r.minItems=="number"&&e.length<r.minItems&&t.push(`${o}: needs at least ${r.minItems} items`),typeof r.maxItems=="number"&&e.length>r.maxItems&&t.push(`${o}: at most ${r.maxItems} items`),r.items&&typeof r.items=="object"&&!Array.isArray(r.items)&&e.forEach((a,l)=>hn(r.items,a,`${n}[${l}]`,t,s+1));else if(e&&typeof e=="object"){let a=e,l=r.properties&&typeof r.properties=="object"?r.properties:{};if(Array.isArray(r.required))for(let d of r.required)(!(d in a)||a[d]===void 0)&&t.push(`${o}: missing required "${d}"`);for(let[d,p]of Object.entries(a)){let u=l[d];if(u)hn(u,p,n?`${n}.${d}`:d,t,s+1);else if(r.additionalProperties===!1){let w=Object.keys(l);t.push(`${o}: unknown field "${d}"${w.length?` (allowed: ${w.join(", ")})`:""}`)}else r.additionalProperties&&typeof r.additionalProperties=="object"&&hn(r.additionalProperties,p,n?`${n}.${d}`:d,t,s+1)}}}function ui(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 n=Object.keys(r),t=Object.keys(e);return n.length!==t.length?!1:n.every(s=>ui(r[s],e[s]))}var Yo=`
|
|
@@ -246,35 +246,35 @@ function onMessage(m) {
|
|
|
246
246
|
}
|
|
247
247
|
}
|
|
248
248
|
if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
|
|
249
|
-
`;async function rc(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let t=URL.createObjectURL(new Blob([Yo],{type:"text/javascript"})),s=new Worker(t);return URL.revokeObjectURL(t),{post:o=>s.postMessage(o),onMessage:o=>{s.onmessage=a=>o(a.data)},terminate:()=>s.terminate()}}let r=new Function("m","return import(m)"),{Worker:e}=await r("node:worker_threads"),n=new e(Yo,{eval:!0});return{post:t=>n.postMessage(t),onMessage:t=>n.on("message",s=>t(s)),terminate:()=>n.terminate()}}async function fi(r,e,n,t={}){let s=Math.min(6e4,Math.max(100,t.timeoutMs??1e4)),o=await rc(),a=Date.now();return new Promise(l=>{let d=!1,p=
|
|
249
|
+
`;async function rc(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let t=URL.createObjectURL(new Blob([Yo],{type:"text/javascript"})),s=new Worker(t);return URL.revokeObjectURL(t),{post:o=>s.postMessage(o),onMessage:o=>{s.onmessage=a=>o(a.data)},terminate:()=>s.terminate()}}let r=new Function("m","return import(m)"),{Worker:e}=await r("node:worker_threads"),n=new e(Yo,{eval:!0});return{post:t=>n.postMessage(t),onMessage:t=>n.on("message",s=>t(s)),terminate:()=>n.terminate()}}async function fi(r,e,n,t={}){let s=Math.min(6e4,Math.max(100,t.timeoutMs??1e4)),o=await rc(),a=Date.now();return new Promise(l=>{let d=!1,p=x=>{d||(d=!0,clearTimeout(u),t.signal?.removeEventListener("abort",w),o.terminate(),l(x))},u=setTimeout(()=>p({ok:!1,logs:"",error:`Timed out after ${s} ms`,durationMs:Date.now()-a}),s),w=()=>p({ok:!1,logs:"",error:"Aborted",durationMs:Date.now()-a});t.signal?.addEventListener("abort",w,{once:!0}),o.onMessage(async x=>{if(x.type==="done")p({ok:!0,result:x.result,logs:x.logs??"",durationMs:x.durationMs??Date.now()-a});else if(x.type==="error")p({ok:!1,error:String(x.error),logs:x.logs??"",durationMs:x.durationMs??Date.now()-a});else if(x.type==="fs"){let b=x.id,M=x.args??[];try{if(!r)throw new Error("no workspace");let T;switch(x.op){case"read":{let A=V(String(M[0])),P=await r.readAsText(A);if(!P)throw new Error(`${A} is a binary file`);await t.guard?.saw(A,{text:P.kind==="text"?P.text:void 0}),T=P.text;break}case"write":{let A=V(String(M[0]));await t.guard?.check(A,"overwrite"),await r.write(A,String(M[1]??"")),await t.guard?.wrote(A),T=!0;break}case"list":T=(await r.list(String(M[0]??"/"))).map(A=>({path:A.path,size:A.size}));break;case"exists":T=await r.exists(String(M[0]));break;case"delete":{let A=V(String(M[0]));if(await t.guard?.check(A,"delete"),t.confirmDelete&&!await t.confirmDelete(A))throw new Error(`the user declined deleting ${A}`);await r.delete(A),t.guard?.forget(A),T=!0;break}default:throw new Error(`unknown fs op ${String(x.op)}`)}o.post({type:"fsResult",id:b,ok:!0,value:T})}catch(T){o.post({type:"fsResult",id:b,ok:!1,error:T.message})}}}),o.post({type:"run",code:e,input:n,network:!!t.network,maxLogChars:t.maxLogChars})})}function os(r,e={}){return He({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 `fs` for the workspace \u2014 `await fs.read(path)` \u2192 text, `await fs.write(path, text)`, `await fs.list(folder)` \u2192 [{path, size}], `await fs.exists(path)`.",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:n,input:t,timeout_ms:s},o){let a=e.confirmDelete??(p=>o.agent?.settings.permissions==="auto"?!0:o.ui.confirm(`Allow run_js to delete ${p}?`,void 0,{danger:!0,signal:o.signal})),l=await fi(r,n,t,{...e,confirmDelete:a,timeoutMs:s??e.timeoutMs,signal:o.signal}),d=[];return l.logs&&d.push(`console:
|
|
250
250
|
${l.logs}`),l.ok?d.push(l.result===void 0?"Returned: undefined":`Returned: ${l.result}`):d.push(`Error: ${l.error}`),d.push(`(${l.durationMs} ms)`),{content:d.join(`
|
|
251
251
|
|
|
252
|
-
`),details:l}}})}function hi(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var sc=["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 Pe(r,e,n){let t=document.createElement(r);return e&&t.setAttribute("style",e),n!==void 0&&(t.textContent=n),t}function gn(r,e,n,t){let s=Pe("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:${n?"#dc2626":"#2563eb"};color:#fff`:"border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit")),s.addEventListener("click",t),s}function gi(r,e,n=null){let t=Pe("dialog",sc),s=n,o=a=>{s=a,t.close()};return r(t,o),e?.aborted?Promise.resolve(n):(document.body.append(t),new Promise(a=>{let l=()=>o(n);e?.addEventListener("abort",l,{once:!0}),t.addEventListener("close",()=>{e?.removeEventListener("abort",l),t.remove(),a(s)},{once:!0}),t.showModal()}))}function as(){return typeof document>"u"||typeof HTMLDialogElement>"u"?mi():{async confirm(r,e,n={}){let t=hi();return await gi((o,a)=>{if(o.append(Pe("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&o.append(Pe("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word",e)),n.body)try{o.append(n.body())}catch(d){console.warn("agent: confirm body failed",d)}let l=Pe("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");l.append(gn(n.cancel??(t?"\u53D6\u6D88":"Cancel"),!1,!1,()=>a(!1)),gn(n.ok??(t?"\u786E\u5B9A":"OK"),!0,!!n.danger,()=>a(!0))),o.append(l),queueMicrotask(()=>l.lastElementChild.focus())},n.signal,!1)===!0},async select(r,e,n={}){let t=hi(),s=await gi((o,a)=>{o.append(Pe("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&o.append(Pe("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=Pe("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),d="ra_sel_"+Math.random().toString(36).slice(2,8),p=[],u=
|
|
252
|
+
`),details:l}}})}function hi(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var sc=["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 Pe(r,e,n){let t=document.createElement(r);return e&&t.setAttribute("style",e),n!==void 0&&(t.textContent=n),t}function gn(r,e,n,t){let s=Pe("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:${n?"#dc2626":"#2563eb"};color:#fff`:"border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit")),s.addEventListener("click",t),s}function gi(r,e,n=null){let t=Pe("dialog",sc),s=n,o=a=>{s=a,t.close()};return r(t,o),e?.aborted?Promise.resolve(n):(document.body.append(t),new Promise(a=>{let l=()=>o(n);e?.addEventListener("abort",l,{once:!0}),t.addEventListener("close",()=>{e?.removeEventListener("abort",l),t.remove(),a(s)},{once:!0}),t.showModal()}))}function as(){return typeof document>"u"||typeof HTMLDialogElement>"u"?mi():{async confirm(r,e,n={}){let t=hi();return await gi((o,a)=>{if(o.append(Pe("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&o.append(Pe("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word",e)),n.body)try{o.append(n.body())}catch(d){console.warn("agent: confirm body failed",d)}let l=Pe("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");l.append(gn(n.cancel??(t?"\u53D6\u6D88":"Cancel"),!1,!1,()=>a(!1)),gn(n.ok??(t?"\u786E\u5B9A":"OK"),!0,!!n.danger,()=>a(!0))),o.append(l),queueMicrotask(()=>l.lastElementChild.focus())},n.signal,!1)===!0},async select(r,e,n={}){let t=hi(),s=await gi((o,a)=>{o.append(Pe("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&o.append(Pe("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=Pe("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),d="ra_sel_"+Math.random().toString(36).slice(2,8),p=[],u=b=>{let M=Pe("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"),T=Pe("input");T.type=n.multi?"checkbox":"radio",T.name=d,T.value=b.value,T.setAttribute("style","margin-top:3px"),p.push(T);let A=Pe("div");A.append(Pe("div","",b.label??b.value)),b.description&&A.append(Pe("div","opacity:.7;font-size:12px",b.description)),M.append(T,A),l.append(M)};e.forEach(u);let w=null;n.allowOther&&(u({value:"__other__",label:t?"\u5176\u4ED6\u2026":"Other\u2026"}),w=Pe("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"),w.placeholder=t?"\u8BF7\u8F93\u5165":"Type your answer",w.addEventListener("focus",()=>{let b=p.find(M=>M.value==="__other__");b&&(b.checked=!0)}),l.append(w)),o.append(l);let x=Pe("div","display:flex;justify-content:flex-end;gap:8px");x.append(gn(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>a(null)),gn(t?"\u786E\u5B9A":"OK",!0,!1,()=>{let b=p.filter(M=>M.checked).map(M=>M.value==="__other__"?w?.value.trim()||"":M.value).filter(Boolean);b.length&&a(b)})),o.append(x),queueMicrotask(()=>p[0]?.focus())},n.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let n=hi(),t=await gi((s,o)=>{s.append(Pe("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(Pe("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let a=Pe(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&&(a.placeholder=e.placeholder),e.initial&&(a.value=e.initial),e.multiline||a.addEventListener("keydown",d=>{let p=d;p.key==="Enter"&&!p.isComposing&&p.keyCode!==229&&o(a.value)}),s.append(a);let l=Pe("div","display:flex;justify-content:flex-end;gap:8px");l.append(gn(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>o(null)),gn(n?"\u786E\u5B9A":"OK",!0,!1,()=>o(a.value))),s.append(l),queueMicrotask(()=>a.focus())},e.signal,null);return typeof t=="string"?t:null},notify(r,e="info"){let n=Pe("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(n),setTimeout(()=>n.remove(),e==="error"?8e3:4e3)}}}function mi(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function ls(){return He({name:"ask_user",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 n=[];for(let s of r){e.signal.throwIfAborted();let o;if(s.options&&s.options.length){let a=await e.ui.select(s.question,s.options.map(l=>({value:l.label,label:l.label,description:l.description})),{multi:!!s.multi,allowOther:s.allow_other!==!1,signal:e.signal});o=a===null?null:s.multi?a:a[0]??null}else o=await e.ui.input(s.question,{multiline:!0,signal:e.signal});if(n.push({question:s.question,answer:o}),o===null)break}return{content:n.some(s=>s.answer===null)||n.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.":n.map(s=>`Q: ${s.question}
|
|
253
253
|
A: ${Array.isArray(s.answer)?s.answer.join(", "):s.answer}`).join(`
|
|
254
254
|
|
|
255
|
-
`),details:{answers:n}}}})}var Qo=100,ic=8192,oc=128e3,ea="/memory/notes.md",ta="/AGENTS.md",ac=6e3,lc=3,cc=3,dc=6;function pc(r,e){let n="ts"in r||"typed"in r||"runUsage"in r,t=e&&r.role==="assistant"&&r.reasoning_content!==void 0;if(!n&&!t)return r;let{ts:s,typed:o,runUsage:a,...l}=r;return t&&delete l.reasoning_content,l}function uc(r){let e=p=>p.role==="tool"&&Array.isArray(p.content)&&p.content.some(u=>u.type!=="text");if(!r.some(e))return r;let n=[],t=-1,s=!1;r.forEach((p,u)=>{if(p.role!=="tool"){t=-1;return}t<0&&(t=u,s=!1),!s&&e(p)&&(n.push(t),s=!0)});let o=n.length>na?n[n.length-na]:0,a=[],l=[],d=()=>{l.length&&a.push({role:"user",content:l}),l=[]};for(let[p,u]of r.entries()){if(u.role!=="tool"&&d(),e(u)){let w=u.content,
|
|
256
|
-
`),M=`${
|
|
257
|
-
`:""}[${M} no longer shown; call the tool again to see the current state]`});continue}a.push({...u,content:`${
|
|
258
|
-
`:""}[${M} follow${b.length===1?"s":""} in the next message]`}),l.push({type:"text",text:`Attachments from tool call ${u.tool_call_id??""}:`.trim()},...b);continue}a.push(u)}return d(),a}var na=2,ra={image:"image_url",video:"video_url",audio:"audio_url"},sa={image:"picture",video:"video",audio:"audio clip"};function fc(r,e,n){let t=Object.keys(ra).filter(o=>e[o]===!1);if(!t.length)return r;let s=o=>t.find(a=>ra[a]===o.type);return r.map(o=>{if(!Array.isArray(o.content)||!o.content.some(l=>s(l)))return o;let a=o.content.map(l=>{let d=s(l);return d?{type:"text",text:`[A ${sa[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${sa[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...o,content:a}})}var yi=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),ir=()=>({runId:"",reason:"aborted",text:"",usage:yi()}),mn="Skipped: the user stopped the run.",ia=()=>new ct(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function cs(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(e.reason??new Error("aborted"))):new Promise((n,t)=>{let s=()=>t(e.reason??new Error("aborted"));e.addEventListener("abort",s,{once:!0}),r.then(o=>{e.removeEventListener("abort",s),n(o)},o=>{e.removeEventListener("abort",s),t(o)})})}var Lt=class{constructor(e,n={}){z(this,"id");z(this,"provider");z(this,"ui");z(this,"workspace");z(this,"tools");z(this,"opts");z(this,"history",[]);z(this,"committed",0);z(this,"droppedTurns",0);z(this,"_usage",yi());z(this,"handlers",new Map);z(this,"anyHandlers",new Set);z(this,"queue",[]);z(this,"current",null);z(this,"chain",Promise.resolve());z(this,"pendingSkills",[]);z(this,"catalogue",null);z(this,"loop",{seen:new Set,idle:0,warned:!1});z(this,"turnNow",0);z(this,"loaded");z(this,"createdAt",Date.now());z(this,"title");z(this,"_ended",null);z(this,"persist");this.provider=tt(e),this.opts=n,this.id=n.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=n.ui??as(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?fn(this.workspace,{enabled:n.readBeforeWrite!==!1}):void 0;if(s){let a=()=>s.retain(this.filesInView());this.on("compaction",a),this.on("rewind",a)}if(this.workspace&&n.fileTools!==!1){let a=Array.isArray(n.fileTools)?new Set(n.fileTools):null;t.push(...ss(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(ls()),n.sandbox!==!1&&t.push(os(this.workspace,{...typeof n.sandbox=="object"?n.sandbox:{},guard:s}));let o=new Set;for(let a of t){if(o.has(a.name))throw new Error(`two tools are named "${a.name}"`);o.add(a.name)}if(this.tools=t,n.serverTools?.length&&(n.tools?.length||this.workspace||n.sandbox!==!1||n.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&&n.persist!==!1,n.restore?(this.applySession(n.restore),this.loaded=Promise.resolve()):this.persist&&n.id?this.loaded=this.workspace.sessions.get(n.id).then(a=>{a&&this.applySession(a)}).catch(a=>{this.persist=!1,console.warn(`agent: could not load session ${n.id}; it will not be saved over`,a)}):this.loaded=Promise.resolve()}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.title=e.title&&!Qr(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,n){if(e==="*")return this.anyHandlers.add(n),()=>{this.anyHandlers.delete(n)};let t=this.handlers.get(e);return t||(t=new Set,this.handlers.set(e,t)),t.add(n),()=>{this.handlers.get(e)?.delete(n)}}emit(e,n){for(let t of this.handlers.get(e)??[])try{t(n)}catch(s){console.error("[agent] listener for",e,"threw:",s)}for(let t of this.anyHandlers)try{t(e,n)}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",n=this.opts.extra?.reasoning_effort;return{model:this.opts.model,maxTurns:this.opts.maxTurns??Qo,maxTokens:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:"auto",permissions:typeof e=="function"?"custom":e,reasoningEffort:typeof n=="string"?n:void 0}}configure(e){if("model"in e&&(this.model=e.model||void 0),"reasoningEffort"in e){let n={...this.opts.extra??{}};e.reasoningEffort?n.reasoning_effort=e.reasoningEffort:delete n.reasoning_effort,this.opts.extra=n}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)}export(){let e=this.history.slice(0,this.committed),n={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.title){let t=Bt(n);t!==$t&&(this.title=t)}return n.title=this.title??$t,n}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.title=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,n={}){let t=this.userMessage(e);return this.current?this.enqueue("followUp",t):this.start(t,n.signal)}steer(e){let n=this.userMessage(e);if(!this.current)return this.start(n);this.queue.push({kind:"steer",message:n}),this.emit("queued",{kind:"steer",message:n})}followUp(e){let n=this.userMessage(e);return this.current?this.enqueue("followUp",n):this.start(n)}get queued(){return this.queue.map(e=>({kind:e.kind,message:e.message}))}dequeue(e){let n=this.queue.find(t=>t.message===e);return n?(this.queue=this.queue.filter(t=>t!==n),n.resolve?.(ir()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(ir())}async abort(){this.clearQueue();let e=this.current;e&&(e.controller.abort(),await e.promise.catch(()=>{}))}enqueue(e,n){return new Promise(t=>{this.queue.push({kind:e,message:n,resolve:t}),this.emit("queued",{kind:e,message:n})})}userMessage(e){let n=typeof e=="string"?[{type:"text",text:e}]:e.slice();return{role:"user",content:n.length===1&&n[0].type==="text"?n[0].text:n,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,n=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(n)||e<0||n>this.history.length||e>=n)throw new Error(`No messages ${e}\u2013${n}`);this.clearQueue(),this.history.splice(e,n-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=yi(),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,n){let t=new AbortController;n&&(n.aborted?t.abort():n.addEventListener("abort",()=>t.abort(),{once:!0}));let s=this.chain.then(()=>this.run(e,t)).finally(()=>{this.current?.controller===t&&(this.current=null),this.drainFollowUps()});return this.current={controller:t,promise:s},this.chain=s.catch(()=>{}),s}drainFollowUps(){let e=this.queue.find(n=>n.kind==="followUp");e&&(this.queue=this.queue.filter(n=>n!==e),this.start(e.message).then(n=>e.resolve?.(n),n=>e.resolve?.({...ir(),reason:"error",error:n instanceof Error?n:new Error(String(n))})))}async run(e,n){await this.loaded;let t=`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,s=n.signal,o="done",a,l="",d=0,p={...this._usage},u=this.history.length;this.applySteering(t);let w=null,b;if(e){try{w=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(_){w=e,b=_ instanceof Error?_:new Error(String(_))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let x=this.opts.maxTurns??Qo,{output:M,input:S}=await this.limits(),A=Qs(S,typeof this.opts.compaction=="object"?this.opts.compaction:{});try{if(b)throw b;for(let _=1;;_++){if(s.aborted){o="aborted";break}if(_>x){o="max_turns";break}this.turnNow=_,this.emit("turn_start",{runId:t,turn:_}),this.applySteering(t);let C=await this.systemPrompt(),N=this.fixedText(C),O=Fe(this.history,N);if(ei(O,S,A)){let fe=this.opts.compaction===!1?!1:await this.compactWith(A,t,s),Se=Fe(this.history,N);if(!fe||ei(Se,S,A)){let _e=this.history.length&&Ze(this.history[0])!==null?[this.history[0]]:[],R=this.history.slice(_e.length),I=Ir(R,{budget:S-A.reserveTokens-Fe(_e),keepTurns:this.opts.keepTurns??4,system:N});(I.droppedTurns||I.elidedResults)&&(this.history=[..._e,...I.messages],this.droppedTurns+=I.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:t,summary:!1,tokensBefore:Se,tokensAfter:Fe(this.history,N),droppedTurns:I.droppedTurns,elidedResults:I.elidedResults}))}}let te=await this.activeTools(),ge={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:C},...this.toWireHistory(await this.mediaSupport())],max_tokens:M};ge.model||delete ge.model,te.length&&(ge.tools=te.map(fe=>si(fe))),this.opts.serverTools?.length&&(ge.server_tools=this.opts.serverTools),this.opts.prompt&&(ge.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(ge.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(ge.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:_,params:ge});let J=Date.now(),ee;try{ee=await this.callModel(ge,t,s)}catch(fe){throw this.emit("response",{runId:t,turn:_,durationMs:Date.now()-J,error:fe instanceof Error?fe.message:String(fe)}),fe}this.emit("response",{runId:t,turn:_,durationMs:Date.now()-J,finishReason:ee.finishReason,usage:ee.usage,message:ee.message}),ee.usage&&this.addUsage(ee.usage);let de={role:"assistant",content:ee.message.content,ts:Date.now()};ee.message.tool_calls?.length&&(de.tool_calls=ee.message.tool_calls),ee.reasoning&&(de.reasoning_content=ee.reasoning),this.history.push(de),typeof de.content=="string"&&de.content&&(l=de.content);let ve=ee.finishReason==="length";this.emit("message_end",{runId:t,message:de,truncated:ve}),this.emit("turn_end",{runId:t,turn:_,usage:ee.usage});let Oe=de.tool_calls??[];if(!Oe.length){if(this.committed=this.history.length,await this.saveSession(),ve&&this.balanceLimited(ee.usage,M)){o="error",a=ia();break}if(!s.aborted&&this.queue.some(fe=>fe.kind==="steer"))continue;break}let pe=await this.runBatch(Oe,t,s,ve);if(this.committed=this.history.length,await this.saveSession(),s.aborted){o="aborted";break}if(!ve&&Br(de.content).trim()&&Oe.every(fe=>this.tools.find(Se=>Se.name===fe.function.name)?.endsRun)){if(this.queue.some(fe=>fe.kind==="steer"))continue;break}if(ve){if(d++,this.balanceLimited(ee.usage,M)){o="error",a=ia();break}if(d>=2){o="error",a=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let we=this.checkLoop(pe);if(we==="stop"){o="error",a=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}we==="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(_){s.aborted?o="aborted":(o="error",a=_ instanceof Error?_:new Error(String(_)))}o==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(u,p),this.committed=this.history.length,this.resetLoop(),this._ended=o==="done"?null:{reason:o,...a?{error:a.message}:{},at:Date.now()},await this.saveSession();let P={runId:t,reason:o,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",P),P}applySteering(e){let n=this.queue.filter(t=>t.kind==="steer").map(t=>t.message);n.length&&(this.queue=this.queue.filter(t=>t.kind!=="steer"),this.history.push(...n),this.loop.idle=0,this.loop.warned=!1,this.emit("steered",{runId:e,messages:n}))}toWireHistory(e={}){let n=-1;for(let t=this.history.length-1;t>=0;t--)if(this.history[t].role==="user"){n=t;break}return fc(uc(this.history.map((t,s)=>pc(t,s<n))),e,this.opts.model)}async mediaSupport(){let[e,n,t]=await Promise.all([this.accepts("image"),this.accepts("video"),this.accepts("audio")]);return{image:e,video:n,audio:t}}async activeTools(){if(!this.tools.some(n=>n.vision))return this.tools;let e=await this.accepts("image");return this.tools.filter(n=>!n.vision||e===!0)}async systemPrompt(){let e=this.workspace,n=async(s,o)=>{if(e)try{let a=await e.readText(s);return a.length>o?a.slice(a.length-o):a}catch{return}},t=await this.activeTools();return Ur({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e?e.describe():void 0,skills:e?await e.skills():[],hasSandbox:t.some(s=>s.name==="run_js"),hasAskUser:t.some(s=>s.name==="ask_user"),canWrite:t.some(s=>s.name==="write_file"||s.name==="edit_file"),agentsMd:this.opts.instructionsFile===!1?void 0:await n(this.opts.instructionsFile??ta,2e4),agentsPath:this.opts.instructionsFile||ta,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??ea,ac),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??ea,droppedTurns:this.droppedTurns})}compact(e){if(this.current)return Promise.reject(new Error("cannot compact while a run is active"));let n=new AbortController,t=this.chain.then(async()=>{await this.loaded;let o=await this.contextTokens(),a=Qs(o,typeof this.opts.compaction=="object"?this.opts.compaction:{}),l=this.history,d=l.length-1;for(;d>0&&!(l[d].role==="user"&&Ze(l[d])===null);)d--;let p=d>0?l.slice(d).reduce((w,b)=>w+Fe([b]),0):Math.floor(Fe(l)/2);a={...a,keepRecentTokens:Math.min(a.keepRecentTokens,p)};let u=await this.compactWith(a,void 0,n.signal,e);return u&&await this.saveSession(),u}),s=t.then(()=>({...ir(),reason:"done"}),()=>ir());return this.current={controller:n,promise:s},this.chain=s,s.finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()}),t}async compactWith(e,n,t,s){let o=jr(this.history,e.keepRecentTokens);if(!o)return!1;s?.trim()&&(o.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=Fe(this.history),l;try{if(typeof this.opts.compaction=="function")l=await this.opts.compaction(o,this);else{let d=await this.limits(),p=Math.min(d.output,Math.max(1024,Math.floor(e.reserveTokens*.8))),u=Math.max(6e3,(d.input-p-1500)*3),w=o.previousSummary;for(let b of Hr(Xn(o.toSummarize),u)){let x={model:this.opts.model??"",messages:_o(b,w,o.focus),max_tokens:p};x.model||delete x.model;let M={runId:n??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...M,params:x}),t.throwIfAborted();let S=Date.now(),A;try{A=this.provider.complete?await this.provider.complete(x,{signal:t}):await Jn((_,C)=>this.provider.stream(_,C),x,{signal:t}).then(_=>({choices:[{message:{..._.message,content:typeof _.message.content=="string"?_.message.content:null},finish_reason:_.finishReason}],usage:_.usage}))}catch(_){throw this.emit("response",{...M,durationMs:Date.now()-S,error:_ instanceof Error?_.message:String(_)}),_}A.usage&&this.addUsage(A.usage);let P=A.choices[0];if(this.emit("response",{...M,durationMs:Date.now()-S,finishReason:P?.finish_reason??void 0,usage:A.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(w=(P.message.content??"").trim(),!w)throw new Error("empty summary")}l=w}}catch(d){if(t.aborted)throw d;return console.warn("[agent] compaction summary failed, falling back to trimming:",d),!1}return this.history=[Fr(l),...o.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:Fe(this.history),droppedTurns:0,elidedResults:0}),!0}async expandSlashes(e){if(!this.workspace)return e;let n=Array.isArray(e.content)?e.content:null,t=n?.[0],s=typeof e.content=="string"?e.content:t?.type==="text"?t.text:"";if(!s.startsWith("/"))return e;let o=await qr(this.workspace,s);if(o===s)return e;let a=n?[{type:"text",text:o},...n.slice(1)]:o;return{...e,content:a,typed:s}}async callModel(e,n,t){let s="",o="",a=!1;for(let l=1;;l++){s="",o="",t.throwIfAborted();try{return await Jn((d,p)=>this.provider.stream(d,p),e,{signal:t,onText:(d,p)=>{a=!0,s=p,this.emit("text_delta",{runId:n,delta:d,text:p})},onReasoning:(d,p)=>{a=!0,o=p,this.emit("reasoning_delta",{runId:n,delta:d,text:p})},onToolCall:(d,p)=>{a=!0,this.emit("tool_call_delta",{runId:n,index:d.index,id:d.id,name:d.name,delta:p,arguments:d.arguments})}})}catch(d){if(t.aborted||l>=lc||!hc(d))throw d;let p=gc(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await mc(p,t)}}}async runBatch(e,n,t,s){let o=l=>this.runTool(l,n,t,s),a=this.opts.parallelTools?await Promise.all(e.map(l=>o(l))):await(async()=>{let l=[],d=!1;for(let p of e){if(d){l.push(this.skipTool(p,n,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}l.push(await o(p)),this.queue.some(u=>u.kind==="steer")&&(d=!0)}return l})();for(let l of a)this.history.push(l.message);return a}skipTool(e,n,t){let s=e.id??"",o=e.function.name;return this.emit("tool_start",{runId:n,id:s,name:o,args:e.function.arguments}),this.emit("tool_end",{runId:n,id:s,name:o,status:"skipped",result:t,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:t},key:"",changed:!1,progress:!0}}async runTool(e,n,t,s){let o=e.id??"",a=e.function.name,l=Date.now(),d,p,u=(S,A,P)=>{let _=Br(A);return this.emit("tool_end",{runId:n,id:o,name:a,status:S,result:_,details:P,durationMs:Date.now()-l,...typeof A=="string"?{}:{content:A}}),{message:{role:"tool",tool_call_id:o,content:A},key:p?.readOnly?`${a}|${S}|${_.slice(0,4e3)}`:`${a}|${e.function.arguments.slice(0,4e3)}|${S}|${_.slice(0,2e3)}`,changed:S==="ok"&&!!p&&!p.readOnly,progress:S==="declined"||S==="skipped"?!0:S==="ok"?d:void 0}};if(t.aborted)return u("skipped",mn);if(s)return this.emit("tool_start",{runId:n,id:o,name:a,args:e.function.arguments}),u("error",`Tool call "${a}" 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 w=await this.activeTools();p=w.find(S=>S.name===a);let b;try{b=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:n,id:o,name:a,args:e.function.arguments}),u("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:n,id:o,name:a,args:b}),!p)return u("error",`Error: there is no tool named "${a}". Available tools: ${w.map(S=>S.name).join(", ")}.`);if(b===null||typeof b!="object"||Array.isArray(b))return u("error","Error: the arguments must be a JSON object.");let x=is(p.parameters,b);if(x.length)return u("error",`Error: invalid arguments for ${a}:
|
|
259
|
-
- ${
|
|
255
|
+
`),details:{answers:n}}}})}var Qo=100,ic=8192,oc=128e3,ea="/memory/notes.md",ta="/AGENTS.md",ac=6e3,lc=3,cc=3,dc=6;function pc(r,e){let n="ts"in r||"typed"in r||"runUsage"in r,t=e&&r.role==="assistant"&&r.reasoning_content!==void 0;if(!n&&!t)return r;let{ts:s,typed:o,runUsage:a,...l}=r;return t&&delete l.reasoning_content,l}function uc(r){let e=p=>p.role==="tool"&&Array.isArray(p.content)&&p.content.some(u=>u.type!=="text");if(!r.some(e))return r;let n=[],t=-1,s=!1;r.forEach((p,u)=>{if(p.role!=="tool"){t=-1;return}t<0&&(t=u,s=!1),!s&&e(p)&&(n.push(t),s=!0)});let o=n.length>na?n[n.length-na]:0,a=[],l=[],d=()=>{l.length&&a.push({role:"user",content:l}),l=[]};for(let[p,u]of r.entries()){if(u.role!=="tool"&&d(),e(u)){let w=u.content,x=w.filter(T=>T.type!=="text"),b=w.filter(T=>T.type==="text").map(T=>T.text).join(`
|
|
256
|
+
`),M=`${x.length} attachment${x.length===1?"":"s"}`;if(p<o){a.push({...u,content:`${b}${b?`
|
|
257
|
+
`:""}[${M} no longer shown; call the tool again to see the current state]`});continue}a.push({...u,content:`${b}${b?`
|
|
258
|
+
`:""}[${M} follow${x.length===1?"s":""} in the next message]`}),l.push({type:"text",text:`Attachments from tool call ${u.tool_call_id??""}:`.trim()},...x);continue}a.push(u)}return d(),a}var na=2,ra={image:"image_url",video:"video_url",audio:"audio_url"},sa={image:"picture",video:"video",audio:"audio clip"};function fc(r,e,n){let t=Object.keys(ra).filter(o=>e[o]===!1);if(!t.length)return r;let s=o=>t.find(a=>ra[a]===o.type);return r.map(o=>{if(!Array.isArray(o.content)||!o.content.some(l=>s(l)))return o;let a=o.content.map(l=>{let d=s(l);return d?{type:"text",text:`[A ${sa[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${sa[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...o,content:a}})}var yi=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),ir=()=>({runId:"",reason:"aborted",text:"",usage:yi()}),mn="Skipped: the user stopped the run.",ia=()=>new ct(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function cs(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(e.reason??new Error("aborted"))):new Promise((n,t)=>{let s=()=>t(e.reason??new Error("aborted"));e.addEventListener("abort",s,{once:!0}),r.then(o=>{e.removeEventListener("abort",s),n(o)},o=>{e.removeEventListener("abort",s),t(o)})})}var Lt=class{constructor(e,n={}){z(this,"id");z(this,"provider");z(this,"ui");z(this,"workspace");z(this,"tools");z(this,"opts");z(this,"history",[]);z(this,"committed",0);z(this,"droppedTurns",0);z(this,"_usage",yi());z(this,"handlers",new Map);z(this,"anyHandlers",new Set);z(this,"queue",[]);z(this,"current",null);z(this,"chain",Promise.resolve());z(this,"pendingSkills",[]);z(this,"catalogue",null);z(this,"loop",{seen:new Set,idle:0,warned:!1});z(this,"turnNow",0);z(this,"loaded");z(this,"createdAt",Date.now());z(this,"title");z(this,"_ended",null);z(this,"persist");this.provider=tt(e),this.opts=n,this.id=n.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=n.ui??as(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?fn(this.workspace,{enabled:n.readBeforeWrite!==!1}):void 0;if(s){let a=()=>s.retain(this.filesInView());this.on("compaction",a),this.on("rewind",a)}if(this.workspace&&n.fileTools!==!1){let a=Array.isArray(n.fileTools)?new Set(n.fileTools):null;t.push(...ss(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(ls()),n.sandbox!==!1&&t.push(os(this.workspace,{...typeof n.sandbox=="object"?n.sandbox:{},guard:s}));let o=new Set;for(let a of t){if(o.has(a.name))throw new Error(`two tools are named "${a.name}"`);o.add(a.name)}if(this.tools=t,n.serverTools?.length&&(n.tools?.length||this.workspace||n.sandbox!==!1||n.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&&n.persist!==!1,n.restore?(this.applySession(n.restore),this.loaded=Promise.resolve()):this.persist&&n.id?this.loaded=this.workspace.sessions.get(n.id).then(a=>{a&&this.applySession(a)}).catch(a=>{this.persist=!1,console.warn(`agent: could not load session ${n.id}; it will not be saved over`,a)}):this.loaded=Promise.resolve()}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.title=e.title&&!Qr(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,n){if(e==="*")return this.anyHandlers.add(n),()=>{this.anyHandlers.delete(n)};let t=this.handlers.get(e);return t||(t=new Set,this.handlers.set(e,t)),t.add(n),()=>{this.handlers.get(e)?.delete(n)}}emit(e,n){for(let t of this.handlers.get(e)??[])try{t(n)}catch(s){console.error("[agent] listener for",e,"threw:",s)}for(let t of this.anyHandlers)try{t(e,n)}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",n=this.opts.extra?.reasoning_effort;return{model:this.opts.model,maxTurns:this.opts.maxTurns??Qo,maxTokens:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:"auto",permissions:typeof e=="function"?"custom":e,reasoningEffort:typeof n=="string"?n:void 0}}configure(e){if("model"in e&&(this.model=e.model||void 0),"reasoningEffort"in e){let n={...this.opts.extra??{}};e.reasoningEffort?n.reasoning_effort=e.reasoningEffort:delete n.reasoning_effort,this.opts.extra=n}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)}export(){let e=this.history.slice(0,this.committed),n={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.title){let t=Bt(n);t!==$t&&(this.title=t)}return n.title=this.title??$t,n}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.title=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,n={}){let t=this.userMessage(e);return this.current?this.enqueue("followUp",t):this.start(t,n.signal)}steer(e){let n=this.userMessage(e);if(!this.current)return this.start(n);this.queue.push({kind:"steer",message:n}),this.emit("queued",{kind:"steer",message:n})}followUp(e){let n=this.userMessage(e);return this.current?this.enqueue("followUp",n):this.start(n)}get queued(){return this.queue.map(e=>({kind:e.kind,message:e.message}))}dequeue(e){let n=this.queue.find(t=>t.message===e);return n?(this.queue=this.queue.filter(t=>t!==n),n.resolve?.(ir()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(ir())}async abort(){this.clearQueue();let e=this.current;e&&(e.controller.abort(),await e.promise.catch(()=>{}))}enqueue(e,n){return new Promise(t=>{this.queue.push({kind:e,message:n,resolve:t}),this.emit("queued",{kind:e,message:n})})}userMessage(e){let n=typeof e=="string"?[{type:"text",text:e}]:e.slice();return{role:"user",content:n.length===1&&n[0].type==="text"?n[0].text:n,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,n=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(n)||e<0||n>this.history.length||e>=n)throw new Error(`No messages ${e}\u2013${n}`);this.clearQueue(),this.history.splice(e,n-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=yi(),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,n){let t=new AbortController;n&&(n.aborted?t.abort():n.addEventListener("abort",()=>t.abort(),{once:!0}));let s=this.chain.then(()=>this.run(e,t)).finally(()=>{this.current?.controller===t&&(this.current=null),this.drainFollowUps()});return this.current={controller:t,promise:s},this.chain=s.catch(()=>{}),s}drainFollowUps(){let e=this.queue.find(n=>n.kind==="followUp");e&&(this.queue=this.queue.filter(n=>n!==e),this.start(e.message).then(n=>e.resolve?.(n),n=>e.resolve?.({...ir(),reason:"error",error:n instanceof Error?n:new Error(String(n))})))}async run(e,n){await this.loaded;let t=`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,s=n.signal,o="done",a,l="",d=0,p={...this._usage},u=this.history.length;this.applySteering(t);let w=null,x;if(e){try{w=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(_){w=e,x=_ instanceof Error?_:new Error(String(_))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let b=this.opts.maxTurns??Qo,{output:M,input:T}=await this.limits(),A=Qs(T,typeof this.opts.compaction=="object"?this.opts.compaction:{});try{if(x)throw x;for(let _=1;;_++){if(s.aborted){o="aborted";break}if(_>b){o="max_turns";break}this.turnNow=_,this.emit("turn_start",{runId:t,turn:_}),this.applySteering(t);let C=await this.systemPrompt(),N=this.fixedText(C),O=Fe(this.history,N);if(ei(O,T,A)){let fe=this.opts.compaction===!1?!1:await this.compactWith(A,t,s),Se=Fe(this.history,N);if(!fe||ei(Se,T,A)){let _e=this.history.length&&Ze(this.history[0])!==null?[this.history[0]]:[],R=this.history.slice(_e.length),I=Ir(R,{budget:T-A.reserveTokens-Fe(_e),keepTurns:this.opts.keepTurns??4,system:N});(I.droppedTurns||I.elidedResults)&&(this.history=[..._e,...I.messages],this.droppedTurns+=I.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:t,summary:!1,tokensBefore:Se,tokensAfter:Fe(this.history,N),droppedTurns:I.droppedTurns,elidedResults:I.elidedResults}))}}let te=await this.activeTools(),ge={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:C},...this.toWireHistory(await this.mediaSupport())],max_tokens:M};ge.model||delete ge.model,te.length&&(ge.tools=te.map(fe=>si(fe))),this.opts.serverTools?.length&&(ge.server_tools=this.opts.serverTools),this.opts.prompt&&(ge.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(ge.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(ge.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:_,params:ge});let J=Date.now(),ee;try{ee=await this.callModel(ge,t,s)}catch(fe){throw this.emit("response",{runId:t,turn:_,durationMs:Date.now()-J,error:fe instanceof Error?fe.message:String(fe)}),fe}this.emit("response",{runId:t,turn:_,durationMs:Date.now()-J,finishReason:ee.finishReason,usage:ee.usage,message:ee.message}),ee.usage&&this.addUsage(ee.usage);let de={role:"assistant",content:ee.message.content,ts:Date.now()};ee.message.tool_calls?.length&&(de.tool_calls=ee.message.tool_calls),ee.reasoning&&(de.reasoning_content=ee.reasoning),this.history.push(de),typeof de.content=="string"&&de.content&&(l=de.content);let ve=ee.finishReason==="length";this.emit("message_end",{runId:t,message:de,truncated:ve}),this.emit("turn_end",{runId:t,turn:_,usage:ee.usage});let Oe=de.tool_calls??[];if(!Oe.length){if(this.committed=this.history.length,await this.saveSession(),ve&&this.balanceLimited(ee.usage,M)){o="error",a=ia();break}if(!s.aborted&&this.queue.some(fe=>fe.kind==="steer"))continue;break}let pe=await this.runBatch(Oe,t,s,ve);if(this.committed=this.history.length,await this.saveSession(),s.aborted){o="aborted";break}if(!ve&&Br(de.content).trim()&&Oe.every(fe=>this.tools.find(Se=>Se.name===fe.function.name)?.endsRun)){if(this.queue.some(fe=>fe.kind==="steer"))continue;break}if(ve){if(d++,this.balanceLimited(ee.usage,M)){o="error",a=ia();break}if(d>=2){o="error",a=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let we=this.checkLoop(pe);if(we==="stop"){o="error",a=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}we==="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(_){s.aborted?o="aborted":(o="error",a=_ instanceof Error?_:new Error(String(_)))}o==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(u,p),this.committed=this.history.length,this.resetLoop(),this._ended=o==="done"?null:{reason:o,...a?{error:a.message}:{},at:Date.now()},await this.saveSession();let P={runId:t,reason:o,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",P),P}applySteering(e){let n=this.queue.filter(t=>t.kind==="steer").map(t=>t.message);n.length&&(this.queue=this.queue.filter(t=>t.kind!=="steer"),this.history.push(...n),this.loop.idle=0,this.loop.warned=!1,this.emit("steered",{runId:e,messages:n}))}toWireHistory(e={}){let n=-1;for(let t=this.history.length-1;t>=0;t--)if(this.history[t].role==="user"){n=t;break}return fc(uc(this.history.map((t,s)=>pc(t,s<n))),e,this.opts.model)}async mediaSupport(){let[e,n,t]=await Promise.all([this.accepts("image"),this.accepts("video"),this.accepts("audio")]);return{image:e,video:n,audio:t}}async activeTools(){if(!this.tools.some(n=>n.vision))return this.tools;let e=await this.accepts("image");return this.tools.filter(n=>!n.vision||e===!0)}async systemPrompt(){let e=this.workspace,n=async(s,o)=>{if(e)try{let a=await e.readText(s);return a.length>o?a.slice(a.length-o):a}catch{return}},t=await this.activeTools();return Ur({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e?e.describe():void 0,skills:e?await e.skills():[],hasSandbox:t.some(s=>s.name==="run_js"),hasAskUser:t.some(s=>s.name==="ask_user"),canWrite:t.some(s=>s.name==="write_file"||s.name==="edit_file"),agentsMd:this.opts.instructionsFile===!1?void 0:await n(this.opts.instructionsFile??ta,2e4),agentsPath:this.opts.instructionsFile||ta,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??ea,ac),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??ea,droppedTurns:this.droppedTurns})}compact(e){if(this.current)return Promise.reject(new Error("cannot compact while a run is active"));let n=new AbortController,t=this.chain.then(async()=>{await this.loaded;let o=await this.contextTokens(),a=Qs(o,typeof this.opts.compaction=="object"?this.opts.compaction:{}),l=this.history,d=l.length-1;for(;d>0&&!(l[d].role==="user"&&Ze(l[d])===null);)d--;let p=d>0?l.slice(d).reduce((w,x)=>w+Fe([x]),0):Math.floor(Fe(l)/2);a={...a,keepRecentTokens:Math.min(a.keepRecentTokens,p)};let u=await this.compactWith(a,void 0,n.signal,e);return u&&await this.saveSession(),u}),s=t.then(()=>({...ir(),reason:"done"}),()=>ir());return this.current={controller:n,promise:s},this.chain=s,s.finally(()=>{this.current?.controller===n&&(this.current=null),this.drainFollowUps()}),t}async compactWith(e,n,t,s){let o=Hr(this.history,e.keepRecentTokens);if(!o)return!1;s?.trim()&&(o.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=Fe(this.history),l;try{if(typeof this.opts.compaction=="function")l=await this.opts.compaction(o,this);else{let d=await this.limits(),p=Math.min(d.output,Math.max(1024,Math.floor(e.reserveTokens*.8))),u=Math.max(6e3,(d.input-p-1500)*3),w=o.previousSummary;for(let x of jr(Xn(o.toSummarize),u)){let b={model:this.opts.model??"",messages:_o(x,w,o.focus),max_tokens:p};b.model||delete b.model;let M={runId:n??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...M,params:b}),t.throwIfAborted();let T=Date.now(),A;try{A=this.provider.complete?await this.provider.complete(b,{signal:t}):await Jn((_,C)=>this.provider.stream(_,C),b,{signal:t}).then(_=>({choices:[{message:{..._.message,content:typeof _.message.content=="string"?_.message.content:null},finish_reason:_.finishReason}],usage:_.usage}))}catch(_){throw this.emit("response",{...M,durationMs:Date.now()-T,error:_ instanceof Error?_.message:String(_)}),_}A.usage&&this.addUsage(A.usage);let P=A.choices[0];if(this.emit("response",{...M,durationMs:Date.now()-T,finishReason:P?.finish_reason??void 0,usage:A.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(w=(P.message.content??"").trim(),!w)throw new Error("empty summary")}l=w}}catch(d){if(t.aborted)throw d;return console.warn("[agent] compaction summary failed, falling back to trimming:",d),!1}return this.history=[Fr(l),...o.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:Fe(this.history),droppedTurns:0,elidedResults:0}),!0}async expandSlashes(e){if(!this.workspace)return e;let n=Array.isArray(e.content)?e.content:null,t=n?.[0],s=typeof e.content=="string"?e.content:t?.type==="text"?t.text:"";if(!s.startsWith("/"))return e;let o=await qr(this.workspace,s);if(o===s)return e;let a=n?[{type:"text",text:o},...n.slice(1)]:o;return{...e,content:a,typed:s}}async callModel(e,n,t){let s="",o="",a=!1;for(let l=1;;l++){s="",o="",t.throwIfAborted();try{return await Jn((d,p)=>this.provider.stream(d,p),e,{signal:t,onText:(d,p)=>{a=!0,s=p,this.emit("text_delta",{runId:n,delta:d,text:p})},onReasoning:(d,p)=>{a=!0,o=p,this.emit("reasoning_delta",{runId:n,delta:d,text:p})},onToolCall:(d,p)=>{a=!0,this.emit("tool_call_delta",{runId:n,index:d.index,id:d.id,name:d.name,delta:p,arguments:d.arguments})}})}catch(d){if(t.aborted||l>=lc||!hc(d))throw d;let p=gc(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await mc(p,t)}}}async runBatch(e,n,t,s){let o=l=>this.runTool(l,n,t,s),a=this.opts.parallelTools?await Promise.all(e.map(l=>o(l))):await(async()=>{let l=[],d=!1;for(let p of e){if(d){l.push(this.skipTool(p,n,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}l.push(await o(p)),this.queue.some(u=>u.kind==="steer")&&(d=!0)}return l})();for(let l of a)this.history.push(l.message);return a}skipTool(e,n,t){let s=e.id??"",o=e.function.name;return this.emit("tool_start",{runId:n,id:s,name:o,args:e.function.arguments}),this.emit("tool_end",{runId:n,id:s,name:o,status:"skipped",result:t,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:t},key:"",changed:!1,progress:!0}}async runTool(e,n,t,s){let o=e.id??"",a=e.function.name,l=Date.now(),d,p,u=(T,A,P)=>{let _=Br(A);return this.emit("tool_end",{runId:n,id:o,name:a,status:T,result:_,details:P,durationMs:Date.now()-l,...typeof A=="string"?{}:{content:A}}),{message:{role:"tool",tool_call_id:o,content:A},key:p?.readOnly?`${a}|${T}|${_.slice(0,4e3)}`:`${a}|${e.function.arguments.slice(0,4e3)}|${T}|${_.slice(0,2e3)}`,changed:T==="ok"&&!!p&&!p.readOnly,progress:T==="declined"||T==="skipped"?!0:T==="ok"?d:void 0}};if(t.aborted)return u("skipped",mn);if(s)return this.emit("tool_start",{runId:n,id:o,name:a,args:e.function.arguments}),u("error",`Tool call "${a}" 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 w=await this.activeTools();p=w.find(T=>T.name===a);let x;try{x=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:n,id:o,name:a,args:e.function.arguments}),u("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:n,id:o,name:a,args:x}),!p)return u("error",`Error: there is no tool named "${a}". Available tools: ${w.map(T=>T.name).join(", ")}.`);if(x===null||typeof x!="object"||Array.isArray(x))return u("error","Error: the arguments must be a JSON object.");let b=is(p.parameters,x);if(b.length)return u("error",`Error: invalid arguments for ${a}:
|
|
259
|
+
- ${b.join(`
|
|
260
260
|
- `)}
|
|
261
|
-
Fix the call and try again.`);if(p.validate){let
|
|
261
|
+
Fix the call and try again.`);if(p.validate){let T;try{T=await cs(Promise.resolve(p.validate(x)),t)}catch(A){T=A instanceof Error?A.message:String(A)}if(t.aborted)return u("skipped",mn);if(T)return u("error",T.startsWith("Error:")?T:`Error: ${T}`)}try{let T=await cs(Promise.resolve(this.opts.onToolCall?.({id:o,name:a,args:x,tool:p})),t);if(T&&T.block)return u("blocked",`${T.reason??"This action was not allowed."} Do not retry it another way; say what you would have done.`);if(!await cs(this.permitted(p,x,t),t))return u("declined","The user declined this action. Do not retry it another way; say what you would have done.")}catch(T){return t.aborted?u("skipped",mn):u("error",`Error: ${T.message}`)}if(t.aborted)return u("skipped",mn);let M=()=>{try{let T=p.whenStopped?.(x);if(T!==void 0){let A=Yn(T,p.maxResultChars);return u("skipped",A.content,A.details)}}catch{}return u("skipped",mn)};try{let T=await cs(Promise.resolve(p.execute(x,{signal:t,ui:this.ui,workspace:this.workspace,agent:this,callId:o,update:P=>this.emit("tool_update",{runId:n,id:o,name:a,content:P}),progress:P=>{d=P}})),t);if(t.aborted)return M();let A=Yn(T,p.maxResultChars);return u("ok",A.content,A.details)}catch(T){if(t.aborted)return M();let A=T instanceof Error?T.message:String(T);return u("error",A.startsWith("Error:")?A:`Error: ${A}`)}}async permitted(e,n,t){let s=this.opts.permissions??"ask";if(typeof s=="function")return s({name:e.name,args:n,tool:e});if(s==="auto")return!0;let o=!1;if(e.confirm?o=await e.confirm(n):e.destructive&&(o=`Allow ${e.name}?`),o===!1)return!0;let{title:a,message:l,always:d,ok:p,body:u}=typeof o=="string"?{title:o,message:void 0,always:void 0,ok:void 0,body:void 0}:o;return this.ui.confirm(a,l,{danger:!!e.destructive,signal:t,always:d,...p?{ok:p}:{},...u?{body:u}:{}})}closeOpenToolCalls(){if(!this.history[this.history.length-1])return;let n=this.history.length-1;for(;n>=0&&this.history[n].role==="tool";)n--;let t=this.history[n];if(!t||t.role!=="assistant"||!t.tool_calls?.length)return;let s=new Set(this.history.slice(n+1).map(o=>o.tool_call_id));for(let o of t.tool_calls)o.id&&!s.has(o.id)&&this.history.push({role:"tool",tool_call_id:o.id,content:mn})}checkLoop(e){let n=this.opts.loopGuard;if(n===!1)return"ok";let t=n?.warn??cc,s=n?.stop??dc,o=this.loop,a=e.map(p=>p.key!==""&&!o.seen.has(p.key)),l=e.some((p,u)=>p.changed&&a[u]);l&&o.seen.clear();for(let p of e)p.key&&o.seen.add(p.key);let d=l||e.some((p,u)=>p.progress??a[u]);return o.seen.size>512&&o.seen.delete(o.seen.values().next().value),d?(o.idle=0,o.warned=!1,"ok"):(o.idle++,o.idle>=s?"stop":o.idle>=t&&!o.warned?(o.warned=!0,"warn"):"ok")}resetLoop(){this.loop={seen:new Set,idle:0,warned:!1}}balanceLimited(e,n){let t=e?.completion_tokens;return typeof t=="number"&&t>0&&t<n*.9}markRunUsage(e,n){let t=this._usage;if(t.calls!==n.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:oa(t.total_cost-n.total_cost),prompt_tokens:t.prompt_tokens-n.prompt_tokens,completion_tokens:t.completion_tokens-n.completion_tokens,calls:t.calls-n.calls};return}}}addUsage(e){this._usage.total_cost=oa(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,n]=await Promise.all([this.contextTokens(),this.systemPrompt().catch(()=>"")]);return{used:Fe(this.history,this.fixedText(n)),window:e}}filesInView(){let e=new Set(this.history.filter(t=>t.role==="tool"&&typeof t.content=="string"&&t.content.startsWith("[result elided")).map(t=>t.tool_call_id)),n=[];for(let t of this.history)for(let s of t.role==="assistant"?t.tool_calls??[]:[]){if(e.has(s.id))continue;let o;try{o=JSON.parse(s.function.arguments)}catch{continue}let a=["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 a=="string"&&n.push(V(a))}return n}fixedText(e){return this.tools.length?`${e}
|
|
262
262
|
${JSON.stringify(this.tools.map(n=>si(n)))}`:e}async limits(){let e=await this.catalogueLimits(),n=typeof(await this.modelInfo())?.max_input_tokens=="number",t=this.opts.maxInputTokens;return{input:typeof t=="number"?n?Math.min(t,e.input):t: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(),n=typeof e?.max_input_tokens=="number"&&e.max_input_tokens>0?e.max_input_tokens:oc,t=typeof e?.max_tokens=="number"&&e.max_tokens>0?e.max_tokens:ic;return{input:n,output:t}}modelInfo(){return this.catalogue||(this.catalogue=(async()=>{try{if(!this.provider.models)return;let e=await this.provider.models(),n=this.opts.model?.toLowerCase();return n?e.find(t=>t.id.toLowerCase()===n):e.find(t=>t.is_default&&(!t.capability||t.capability==="text"||t.capability==="vision"))}catch{queueMicrotask(()=>{this.catalogue=null});return}})()),this.catalogue}async accepts(e){return e==="image"&&typeof this.opts.vision=="boolean"?this.opts.vision:Nt(await this.modelInfo(),e)}async withSkillPrefaces(e){if(!this.pendingSkills.length||!this.workspace)return e;let n=this.pendingSkills.splice(0),t=[];for(let a of n){let{skill:l,body:d}=await this.workspace.skillBody(a);t.push({type:"text",text:`[The user invoked the skill "${l.name}" (${l.path}). Follow these instructions for the request below.]
|
|
263
263
|
|
|
264
|
-
${d}`})}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:[...t,...s],...o!==void 0?{typed:o}:{}}}estimateContext(){return Fe(this.history)}contextWindow(){return this.contextTokens()}};function hc(r){let e=Ao(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 gc(r,e){let n=r&&typeof r=="object"?r.retryAfter:void 0;return typeof n=="number"&&n>0?Math.min(3e4,n*1e3):Math.min(8e3,800*2**(e-1))+Math.random()*300}function mc(r,e){return new Promise((n,t)=>{let s=()=>{clearTimeout(o),t(e.reason??new Error("aborted"))},o=setTimeout(()=>{e.removeEventListener("abort",s),n()},r);e.addEventListener("abort",s,{once:!0})})}function oa(r){return Math.round(r*1e6)/1e6}var aa="2025-06-18",Ce=class extends Error{constructor(n,t,s){super(n);z(this,"status",t);z(this,"code",s);this.name="MCPError"}};async function da(r,e={}){e.signal?.throwIfAborted();let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Ce("An MCP endpoint is an http(s) URL.");let t=e.fetch??globalThis.fetch.bind(globalThis),s=e.timeoutMs??6e4,o,a,l=1,d=!1,p=e.signal,u=J=>({...e.headers??{},...J?{"Content-Type":"application/json",Accept:"application/json, text/event-stream"}:{},...e.token?{Authorization:`Bearer ${e.token}`}:{},...o?{"Mcp-Session-Id":o}:{},...a?{"MCP-Protocol-Version":a}:{}}),w=(J,ee)=>t(n,{method:"POST",headers:u(!0),body:JSON.stringify(J),signal:ee,redirect:"error",credentials:"omit"}),
|
|
265
|
-
`).trim()||`${pe.name} reported an error.`);return B.length===1&&B[0].type==="text"?B[0].text:B}})}),C};try{await te(e.signal)}catch(J){throw await ge(),J}p=void 0;async function ge(){if(!d&&(d=!0,!!o))try{await(await t(n,{method:"DELETE",headers:u(!1),redirect:"error",credentials:"omit",signal:AbortSignal.timeout(5e3)})).body?.cancel()}catch{}}return{get tools(){return C},get serverTools(){return _},server:
|
|
264
|
+
${d}`})}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:[...t,...s],...o!==void 0?{typed:o}:{}}}estimateContext(){return Fe(this.history)}contextWindow(){return this.contextTokens()}};function hc(r){let e=Ao(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 gc(r,e){let n=r&&typeof r=="object"?r.retryAfter:void 0;return typeof n=="number"&&n>0?Math.min(3e4,n*1e3):Math.min(8e3,800*2**(e-1))+Math.random()*300}function mc(r,e){return new Promise((n,t)=>{let s=()=>{clearTimeout(o),t(e.reason??new Error("aborted"))},o=setTimeout(()=>{e.removeEventListener("abort",s),n()},r);e.addEventListener("abort",s,{once:!0})})}function oa(r){return Math.round(r*1e6)/1e6}var aa="2025-06-18",Ce=class extends Error{constructor(n,t,s){super(n);z(this,"status",t);z(this,"code",s);this.name="MCPError"}};async function da(r,e={}){e.signal?.throwIfAborted();let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Ce("An MCP endpoint is an http(s) URL.");let t=e.fetch??globalThis.fetch.bind(globalThis),s=e.timeoutMs??6e4,o,a,l=1,d=!1,p=e.signal,u=J=>({...e.headers??{},...J?{"Content-Type":"application/json",Accept:"application/json, text/event-stream"}:{},...e.token?{Authorization:`Bearer ${e.token}`}:{},...o?{"Mcp-Session-Id":o}:{},...a?{"MCP-Protocol-Version":a}:{}}),w=(J,ee)=>t(n,{method:"POST",headers:u(!0),body:JSON.stringify(J),signal:ee,redirect:"error",credentials:"omit"}),x=J=>{let ee=J.method==="ping"?{jsonrpc:"2.0",id:J.id,result:{}}:{jsonrpc:"2.0",id:J.id,error:{code:-32601,message:`${J.method} is not supported by this client`}};w(ee,AbortSignal.timeout(s)).then(de=>de.body?.cancel()).catch(()=>{})},b=async(J,ee,de,ve,Oe=!1)=>{if(d)throw new Ce("The MCP connection is closed.");let pe=l++,we=AbortSignal.timeout(s),fe=ca([we,...de?[de]:[],...p?[p]:[]]),Se={jsonrpc:"2.0",id:pe,method:J,...ee?{params:ve?{...ee,_meta:{progressToken:pe}}:ee}:{}},_e=()=>{J!=="initialize"&&w({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:pe,reason:"The user stopped it."}},AbortSignal.timeout(5e3)).then(R=>R.body?.cancel()).catch(()=>{})};de?.addEventListener("abort",_e,{once:!0});try{let R;try{R=await w(Se,fe)}catch(K){throw de?.throwIfAborted(),we.aborted?new Ce(`${J} timed out after ${Math.round(s/1e3)} s.`):new Ce(`Could not reach the MCP server (${K.message}). Check the address, its CORS settings and your network.`)}if(R.status===404&&o&&!Oe&&J!=="initialize")return await R.body?.cancel(),o=void 0,await P(de),b(J,ee,de,ve,!0);if(!R.ok)throw await R.body?.cancel(),new Ce(`The MCP server answered ${J} with HTTP ${R.status}${R.status===401||R.status===403?" (check the token)":""}.`,R.status);let I=R.headers.get("mcp-session-id");I&&(o=I);let G=K=>{if(K.id===pe&&(K.result||K.error)){if(K.error)throw new Ce(`${J}: ${K.error.message}`,void 0,K.error.code);return K.result??{}}if(K.method&&K.id!==void 0)x(K);else if(K.method==="notifications/progress"&&K.params?.progressToken===pe&&ve){let ie=K.params;ve(ie.message??(ie.total?`${ie.progress??0} / ${ie.total}`:String(ie.progress??"")))}};if((R.headers.get("content-type")??"").includes("text/event-stream")&&R.body){for await(let K of Zn(R.body,fe)){let ie;try{ie=JSON.parse(K)}catch{continue}for(let j of Array.isArray(ie)?ie:[ie]){let re=G(j);if(re)return R.body.cancel().catch(()=>{}),re}}throw de?.throwIfAborted(),we.aborted?new Ce(`${J} timed out after ${Math.round(s/1e3)} s.`):new Ce(`The MCP server ended the stream without answering ${J}.`)}let H;try{H=await R.json()}catch{throw new Ce(`The MCP server's answer to ${J} is not JSON.`)}for(let K of Array.isArray(H)?H:[H]){let ie=G(K);if(ie)return ie}throw new Ce(`The MCP server did not answer ${J}.`)}finally{de?.removeEventListener("abort",_e)}},M=async J=>{await(await w({jsonrpc:"2.0",method:J},ca([AbortSignal.timeout(s),...p?[p]:[]]))).body?.cancel()},T={name:"mcp"},A,P=async J=>{a=void 0;let ee=await b("initialize",{protocolVersion:aa,capabilities:{},clientInfo:{name:e.clientName??"runapps-agent",version:"1"}},J);a=typeof ee.protocolVersion=="string"?ee.protocolVersion:aa;let de=ee.serverInfo;de?.name&&(T={name:de.name,version:de.version,title:de.title}),typeof ee.instructions=="string"&&(A=ee.instructions),await M("notifications/initialized")};await P(e.signal);let _=[],C=[],N=la(e.prefix??T.name).slice(0,24)||"mcp",O=e.name||T.title||T.name,te=async J=>{let ee=[],de=new Set,ve;do{let pe=await b("tools/list",ve?{cursor:ve}:{},J);if(!Array.isArray(pe.tools))throw new Ce("The MCP server's tool list is malformed.");for(let we of pe.tools){if(!we||typeof we.name!="string"||!we.name)throw new Ce("The MCP server listed a tool without a name.");let fe=we.inputSchema&&typeof we.inputSchema=="object"?we.inputSchema:{type:"object"};ee.push({...we,inputSchema:{type:"object",properties:{},...fe}})}if(ee.length>(e.maxTools??64))throw new Ce(`The MCP server has more than ${e.maxTools??64} tools (maxTools).`);if(ve=typeof pe.nextCursor=="string"&&pe.nextCursor?pe.nextCursor:void 0,ve){if(de.has(ve))throw new Ce("The MCP server's tool list repeats a page.");de.add(ve)}}while(ve);_=ee;let Oe=new Set;return C=ee.map(pe=>{let we=`${N}__${la(pe.name)}`.slice(0,64);for(let R=2;Oe.has(we);R++)we=`${we.slice(0,60)}_${R}`;Oe.add(we);let fe=pe.annotations?.readOnlyHint===!0,Se=e.confirm==="never"?!1:e.confirm==="unless-read-only"?!fe:!0,_e=pe.title??pe.annotations?.title??pe.name;return He({name:we,description:`[${O} \u2014 MCP server] ${_e!==pe.name?`${_e}. `:""}${pe.description??""}`.trim().slice(0,4e3),parameters:pe.inputSchema,readOnly:fe,destructive:pe.annotations?.destructiveHint===!0||!fe&&Se,maxResultChars:e.maxResultChars,confirm:Se?R=>({title:`Run ${O} / ${pe.name}?`,message:JSON.stringify(R,null,2).slice(0,4e3)}):()=>!1,async execute(R,I){let G;try{G=await b("tools/call",{name:pe.name,arguments:R},I.signal,H=>H&&I.update(H))}catch(H){throw I.signal.throwIfAborted(),H instanceof Ce&&H.code!==void 0?H:new Ce(`${H.message} Whether ${pe.name} took effect on the server is unknown; do not repeat it without checking.`)}let B=yc(G,e.images===!0);if(G.isError===!0)throw new Ce(B.map(H=>H.type==="text"?H.text:"").join(`
|
|
265
|
+
`).trim()||`${pe.name} reported an error.`);return B.length===1&&B[0].type==="text"?B[0].text:B}})}),C};try{await te(e.signal)}catch(J){throw await ge(),J}p=void 0;async function ge(){if(!d&&(d=!0,!!o))try{await(await t(n,{method:"DELETE",headers:u(!1),redirect:"error",credentials:"omit",signal:AbortSignal.timeout(5e3)})).body?.cancel()}catch{}}return{get tools(){return C},get serverTools(){return _},server:T,instructions:A,refresh:te,close:ge}}function yc(r,e){let n=Array.isArray(r.content)?r.content:[],t=[];for(let s of n)if(!(!s||typeof s!="object"))if(s.type==="text"&&typeof s.text=="string")t.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?t.push({type:"image_url",image_url:{url:`data:${o};base64,${s.data}`}}):t.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")t.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;t.push({type:"text",text:typeof o.text=="string"?`${o.uri?`${o.uri}:
|
|
266
266
|
`:""}${o.text}`:`[Resource ${o.uri??""} (${o.mimeType??"binary"}); its content is not shown here.]`})}else s.type==="resource_link"&&t.push({type:"text",text:`[Link: ${String(s.name??"")} ${String(s.uri??"")}]`.replace(/\s+\]/,"]")});return!t.length&&r.structuredContent!==void 0&&t.push({type:"text",text:JSON.stringify(r.structuredContent)}),t.length||t.push({type:"text",text:"OK"}),t}function la(r){return r.replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")}function ca(r){let e=AbortSignal.any;if(e)return e(r);let n=new AbortController;for(let t of r){if(t.aborted){n.abort(t.reason);break}t.addEventListener("abort",()=>n.abort(t.reason),{once:!0})}return n.signal}function wc(r,e={}){return new Lt(r,e)}function bc(r,e={}){let n=r?tt(r):null;return un.open(n,{...e,project:e.project??n?.name??void 0})}var xc={"&":"&","<":"<",">":">",'"':""","'":"'"};function xe(r){return r.replace(/[&<>"']/g,e=>xc[e])}function vc(r){let e=r.trim();return/^(https?:\/\/|mailto:)/i.test(e)||/^(\/|\.\/|\.\.\/|#)/.test(e)&&!/^\/\//.test(e)?e:null}var wi=/[\p{L}\p{N}]/u,pa=/`+/y,ua=/\[([^\]]*)\]\(((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?\)/y,fa=/https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))+/y;function bt(r){let e="",n=0,t=r.length,s=new Map,o=-2;for(;n<t;){let a=r[n];if(a==="`"){pa.lastIndex=n;let l=pa.exec(r)[0],d=r.indexOf(l,n+l.length);if(d>0){e+=`<code>${xe(r.slice(n+l.length,d).trim())}</code>`,n=d+l.length;continue}e+=xe(l),n+=l.length;continue}if(a==="["&&(o!==-1&&o<n&&(o=r.indexOf("](",n)),o!==-1)){ua.lastIndex=n;let l=ua.exec(r);if(l){let d=vc(l[2]),p=bt(l[1]);e+=d?`<a href="${xe(d)}" target="_blank" rel="noopener noreferrer">${p}</a>`:p,n+=l[0].length;continue}}if(a==="h"&&r.startsWith("http",n)&&(n===0||!wi.test(r[n-1]))){fa.lastIndex=n;let l=fa.exec(r);if(l){let d=l[0].replace(/[.,;:!?'"]+$/,"");if(d.length>8){e+=`<a href="${xe(d)}" target="_blank" rel="noopener noreferrer">${xe(d)}</a>`,n+=d.length;continue}}}if(a==="*"||a==="_"||a==="~"){let l=r[n+1]===a?a+a:a;if((l.length===2||a!=="~")&&n+l.length<t&&!/\s/.test(r[n+l.length])&&!(a==="_"&&n>0&&wi.test(r[n-1]))&&(s.get(l)??1/0)>n){let p=kc(r,n+l.length,l);if(p>0){let u=bt(r.slice(n+l.length,p));e+=l==="~~"?`<del>${u}</del>`:l.length===2?`<strong>${u}</strong>`:`<em>${u}</em>`,n=p+l.length;continue}s.set(l,Math.min(s.get(l)??1/0,n))}e+=xe(l),n+=l.length;continue}if(a==="\\"&&n+1<t&&/[\\`*_{}\[\]()#+\-.!~|>]/.test(r[n+1])){e+=xe(r[n+1]),n+=2;continue}if(a===`
|
|
267
267
|
`){e+="<br>",n++;continue}e+=xe(a),n++}return e}function kc(r,e,n){let t=e;for(;(t=r.indexOf(n,t))>0;){if(t>e&&r[t-1]!==" "&&r[t-1]!==`
|
|
268
268
|
`&&!(n[0]==="_"&&t+n.length<r.length&&wi.test(r[t+n.length])))return t;t+=n.length}return-1}var Tc=/^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)/;function yn(r){let e=r.replace(/\r\n?/g,`
|
|
269
269
|
`).split(`
|
|
270
270
|
`),n=[],t=0,s=[],o=()=>{s.length&&(n.push(`<p>${bt(s.join(`
|
|
271
|
-
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=Tc.exec(a);if(l&&!(l[2][0]==="`"&&a.slice(l[0].length).includes("`"))){o();let u=l[2],w=l[3]??"",
|
|
271
|
+
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=Tc.exec(a);if(l&&!(l[2][0]==="`"&&a.slice(l[0].length).includes("`"))){o();let u=l[2],w=l[3]??"",x=[];t++;let b=T=>{let A=T.trim();return A.length>=u.length&&A===u[0].repeat(A.length)};for(;t<e.length&&!b(e[t]);)x.push(e[t]),t++;t++;let M=w?` class="language-${xe(w)}"`:"";n.push(`<pre><code${M}>${xe(x.join(`
|
|
272
272
|
`))}
|
|
273
273
|
</code></pre>`);continue}if(!a.trim()){o(),t++;continue}let d=/^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(a);if(d){o(),n.push(`<h${d[1].length}>${bt(d[2])}</h${d[1].length}>`),t++;continue}if(/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(a)){o(),n.push("<hr>"),t++;continue}if(/^\s{0,3}>/.test(a)){o();let u=[];for(;t<e.length&&/^\s{0,3}>/.test(e[t]);)u.push(e[t].replace(/^\s{0,3}>\s?/,"")),t++;n.push(`<blockquote>${yn(u.join(`
|
|
274
|
-
`))}</blockquote>`);continue}if(a.includes("|")&&t+1<e.length&&e[t+1].includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e[t+1])){o();let u=M=>M.trim().replace(/^\|/,"").replace(/(?<!\\)\|$/,"").split(/(?<!\\)\|/).map(
|
|
275
|
-
`)}function Sc(r,e,n){let t=/^(\s*)([-*+]|\d+[.)])\s+/.exec(r[e]),s=/\d/.test(t[2]),o=s?parseInt(t[2],10):1,a=[],l=e;for(;l<r.length;){let u=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(r[l]);if(!u||u[1].length!==n||/\d/.test(u[2])!==s)break;let w=[u[3]];for(l++;l<r.length;){let
|
|
274
|
+
`))}</blockquote>`);continue}if(a.includes("|")&&t+1<e.length&&e[t+1].includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e[t+1])){o();let u=M=>M.trim().replace(/^\|/,"").replace(/(?<!\\)\|$/,"").split(/(?<!\\)\|/).map(T=>T.trim().replace(/\\\|/g,"|")),w=u(e[t+1]).map(M=>M.startsWith(":")&&M.endsWith(":")?"center":M.endsWith(":")?"right":M.startsWith(":")?"left":""),x=(M,T)=>`<tr>${u(M).map((A,P)=>`<${T}${w[P]?` style="text-align:${w[P]}"`:""}>${bt(A)}</${T}>`).join("")}</tr>`,b=`<table><thead>${x(a,"th")}</thead><tbody>`;for(t+=2;t<e.length&&e[t].includes("|")&&e[t].trim();)b+=x(e[t],"td"),t++;n.push(b+"</tbody></table>");continue}let p=/^(\s*)([-*+]|\d+[.)])\s+/.exec(a);if(p){o();let{html:u,next:w}=Sc(e,t,p[1].length);n.push(u),t=w;continue}s.push(a),t++}return o(),n.join(`
|
|
275
|
+
`)}function Sc(r,e,n){let t=/^(\s*)([-*+]|\d+[.)])\s+/.exec(r[e]),s=/\d/.test(t[2]),o=s?parseInt(t[2],10):1,a=[],l=e;for(;l<r.length;){let u=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(r[l]);if(!u||u[1].length!==n||/\d/.test(u[2])!==s)break;let w=[u[3]];for(l++;l<r.length;){let b=r[l];if(!b.trim()){if(l+1<r.length&&/^\s+\S/.test(r[l+1])&&r[l+1].match(/^\s*/)[0].length>n){w.push(""),l++;continue}break}if(b.match(/^\s*/)[0].length>n){w.push(b),l++;continue}break}let x=/^\[([ xX])\]\s+/.exec(w[0]);x&&(w[0]=`<input type="checkbox" disabled${x[1]===" "?"":" checked"}> `+w[0].slice(x[0].length)),a.push(`<li>${Mc(w,n,!!x)}</li>`)}let d=s?"ol":"ul",p=s&&o!==1?` start="${o}"`:"";return{html:`<${d}${p}>${a.join("")}</${d}>`,next:l}}function Mc(r,e,n){let t=r[0],s=r.slice(1).map(d=>d.replace(new RegExp(`^\\s{0,${e+2}}`),"")).join(`
|
|
276
276
|
`).trim(),o=n?t.replace(/^(<input[^>]*> )/,"$1"):"",a=n?o.slice(0,o.indexOf("> ")+2)+bt(o.slice(o.indexOf("> ")+2)):bt(t);if(!s)return a;let l=yn(s);return a+(l.startsWith("<p>")&&!l.includes(`</p>
|
|
277
|
-
`)?`<br>${l.slice(3,-4)}`:l)}var wn=class{constructor(e,n,t={}){z(this,"scroller",e);z(this,"inner",n);z(this,"rows",[]);z(this,"_follow",!0);z(this,"onFollow");z(this,"top");z(this,"win");z(this,"bottom");z(this,"wrappers",new Map);z(this,"ro");z(this,"estimate");z(this,"overscan");z(this,"rowClass");z(this,"followWithin");z(this,"offsets",[]);z(this,"first",0);z(this,"last",-1);z(this,"frame",null);z(this,"disposed",!1);z(this,"expectedTop",-1);z(this,"pinned",null);z(this,"lastTop",0);z(this,"onScroll",()=>{let e=this.scroller,n=e.scrollTop,t=this.expectedTop>=0&&Math.abs(n-this.expectedTop)<=1;this.expectedTop=-1,t||(this.pinned=null,e.scrollHeight-n-e.clientHeight<=this.followWithin?this.follow=!0:n<this.lastTop-.5&&(this.follow=!1)),this.lastTop=n,this.schedule()});z(this,"onWheel",e=>{this.pinned=null,e.deltaY<0&&this.scroller.scrollTop>0&&(this.follow=!1)});z(this,"touchY",0);z(this,"onTouch",e=>{this.touchY=e.touches[0]?.clientY??0;let n=s=>{(s.touches[0]?.clientY??0)>this.touchY+2&&this.scroller.scrollTop>0&&(this.follow=!1)},t=()=>{this.scroller.removeEventListener("touchmove",n),this.scroller.removeEventListener("touchend",t),this.scroller.removeEventListener("touchcancel",t)};this.scroller.addEventListener("touchmove",n,{passive:!0}),this.scroller.addEventListener("touchend",t,{passive:!0}),this.scroller.addEventListener("touchcancel",t,{passive:!0})});this.estimate=t.estimate??96,this.overscan=t.overscan??400,this.rowClass=t.rowClass??"",this.followWithin=t.followWithin??2,this.onFollow=t.onFollow,this.top=document.createElement("div"),this.win=document.createElement("div"),this.bottom=document.createElement("div"),n.append(this.top,this.win,this.bottom),e.style.overflowAnchor="none",e.addEventListener("scroll",this.onScroll,{passive:!0}),e.addEventListener("wheel",this.onWheel,{passive:!0}),e.addEventListener("touchstart",this.onTouch,{passive:!0}),this.ro=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>this.schedule()),this.ro&&this.ro.observe(e)}get follow(){return this._follow}set follow(e){e!==this._follow&&(this._follow=e,this.onFollow?.(e))}setTop(e){let n=this.scroller;Math.abs(n.scrollTop-e)<=.5||(this.expectedTop=e,n.scrollTop=e,this.lastTop=n.scrollTop)}get length(){return this.rows.length}push(e){e.height??(e.height=this.estimate),this.rows.push(e),this.schedule()}remove(e){let n=this.rows.indexOf(e);n<0||(this.rows.splice(n,1),this.detach(e),this.first=0,this.last=-1,this.schedule())}clear(){for(let e of this.rows)this.detach(e);this.rows.length=0,this.offsets=[],this.first=0,this.last=-1,this.follow=!0,this.win.replaceChildren(),this.top.style.height=this.bottom.style.height="0px"}scrollToBottom(){this.pinned=null,this.follow=!0,this.layout()}pin(e,n=800){this.pinned={el:e,offset:e.getBoundingClientRect().top-this.scroller.getBoundingClientRect().top,until:Date.now()+n},this.follow=!1}applyPin(){let e=this.pinned;if(!e)return;if(!e.el.isConnected||Date.now()>e.until){this.pinned=null;return}let n=e.el.getBoundingClientRect().top-this.scroller.getBoundingClientRect().top-e.offset;Math.abs(n)>.5&&this.setTop(this.scroller.scrollTop+n)}schedule(){this.disposed||this.frame!==null||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.layout()}))}dispose(){this.disposed=!0,this.frame!==null&&cancelAnimationFrame(this.frame),this.scroller.removeEventListener("scroll",this.onScroll),this.scroller.removeEventListener("wheel",this.onWheel),this.scroller.removeEventListener("touchstart",this.onTouch),this.ro?.disconnect()}detach(e){let n=this.wrappers.get(e);n&&(this.ro?.unobserve(n),n.remove(),this.wrappers.delete(e))}wrapper(e){let n=this.wrappers.get(e);return n||(n=document.createElement("div"),this.rowClass&&(n.className=this.rowClass),e.el||(e.el=e.render()),n.append(e.el),this.wrappers.set(e,n),this.ro?.observe(n),n)}computeOffsets(){let e=this.rows.length;this.offsets.length=e+1;let n=0;for(let t=0;t<e;t++)this.offsets[t]=n,n+=this.rows[t].height??this.estimate;return this.offsets[e]=n,n}indexAt(e){let n=0,t=this.rows.length-1;for(;n<t;){let s=n+t>>1;this.offsets[s+1]<=e?n=s+1:t=s}return n}layout(){if(!this.disposed)try{this.layoutRows()}finally{this.applyPin()}}layoutRows(){let e=this.scroller,n=this.rows.length;if(!n){this.win.replaceChildren(),this.top.style.height=this.bottom.style.height="0px";return}let t=e.clientHeight||600;for(let s=0;s<4;s++){let o=this.computeOffsets(),a=this.follow?Math.max(0,o-t):e.scrollTop,l=this.indexAt(a),d=this.offsets[l]-a,p=this.indexAt(Math.max(0,a-this.overscan)),u=Math.min(n-1,this.indexAt(Math.min(o-1,a+t+this.overscan)));if(p!==this.first||u!==this.last||this.win.childElementCount!==u-p+1){let b=new Set(this.rows.slice(p,u+1));for(let[M,S]of this.wrappers)b.has(M)||(this.ro?.unobserve(S),S.remove(),this.wrappers.delete(M));let x=[];for(let M=p;M<=u;M++)x.push(this.wrapper(this.rows[M]));this.win.replaceChildren(...x),this.first=p,this.last=u}this.top.style.height=`${this.offsets[p]}px`,this.bottom.style.height=`${o-this.offsets[u+1]}px`;let w=!1;for(let b=p;b<=u;b++){let x=this.rows[b],M=this.wrappers.get(x).offsetHeight;M&&M!==x.height&&(x.height=M,w=!0)}if(w){let b=this.computeOffsets();this.setTop(this.follow?Math.max(0,b-t):Math.max(0,this.offsets[l]-d));continue}this.follow&&Math.abs(e.scrollTop-Math.max(0,o-t))>1&&this.setTop(Math.max(0,o-t));return}}};function h(r,e,n){let t=document.createElement(r);return e&&(t.className=e),n!==void 0&&(t.textContent=n),t}var se=(r,e,n=2)=>`<svg width="${r}" height="${r}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${n}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e}</svg>`,U={tick:(r=14)=>se(r,'<path d="M20 6 9 17l-5-5"/>'),enter:(r=14)=>se(r,'<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),lock:(r=12)=>se(r,'<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),puzzle:(r=14)=>se(r,'<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>'),spark:(r=14)=>se(r,'<path d="M9.9 2.1a1 1 0 0 1 1.9 0l1.3 4.1a4 4 0 0 0 2.6 2.6l4.1 1.3a1 1 0 0 1 0 1.9l-4.1 1.3a4 4 0 0 0-2.6 2.6l-1.3 4.1a1 1 0 0 1-1.9 0l-1.3-4.1a4 4 0 0 0-2.6-2.6L2.1 12a1 1 0 0 1 0-1.9l4.1-1.3a4 4 0 0 0 2.6-2.6z"/><path d="M20 3v4M22 5h-4"/>'),send:(r=16)=>se(r,'<path d="M14.5 9.5 22 2M22 2l-7 20-4-9-9-4z"/>'),hist:(r=14)=>se(r,'<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 3"/>'),eraser:(r=14)=>se(r,'<path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21"/><path d="m5.082 11.09 8.828 8.828"/>'),pointer:(r=14)=>se(r,'<path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/>'),plus:(r=14)=>se(r,'<path d="M12 5v14M5 12h14"/>'),chev:(r=14)=>se(r,'<path d="m9 18 6-6-6-6"/>'),brain:(r=13)=>se(r,'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/><path d="M17.6 6.5a3 3 0 0 0 .4 1M6.4 6.5a3 3 0 0 1-.4 1M12 18v-5"/>'),layers:(r=14)=>se(r,'<path d="m12.8 2.2 8.5 4a1 1 0 0 1 0 1.6l-8.5 4a2 2 0 0 1-1.6 0l-8.5-4a1 1 0 0 1 0-1.6l8.5-4a2 2 0 0 1 1.6 0"/><path d="m2.4 11.9 8.8 4.1a2 2 0 0 0 1.6 0l8.8-4.1"/><path d="m2.4 16.9 8.8 4.1a2 2 0 0 0 1.6 0l8.8-4.1"/>'),check:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>'),xcircle:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6M9 9l6 6"/>'),ban:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/>'),square:(r=12)=>se(r,'<rect x="3" y="3" width="18" height="18" rx="2"/>'),corner:(r=14)=>se(r,'<path d="M20 4v7a4 4 0 0 1-4 4H4"/><path d="m9 10-5 5 5 5"/>'),x:(r=12)=>se(r,'<path d="M18 6 6 18M6 6l12 12"/>'),trash:(r=13)=>se(r,'<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>'),clip:(r=16)=>se(r,'<path d="m21.4 11.1-9.2 9.2a6 6 0 0 1-8.5-8.5l9.2-9.2a4 4 0 0 1 5.7 5.7l-9.2 9.2a2 2 0 0 1-2.8-2.8l8.5-8.5"/>'),file:(r=14)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>'),folder:(r=14)=>se(r,'<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>'),folderOpen:(r=14)=>se(r,'<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>'),upload:(r=14)=>se(r,'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/>'),download:(r=14)=>se(r,'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>'),refresh:(r=13)=>se(r,'<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/>'),save:(r=12)=>se(r,'<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h7"/>'),chevDown:(r=12)=>se(r,'<path d="m6 9 6 6 6-6"/>'),checks:(r=13)=>se(r,'<path d="M18 6 7 17l-5-5"/><path d="m22 10-7.5 7.5L13 16"/>'),undo:(r=13)=>se(r,'<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'),gear:(r=14)=>se(r,'<path d="M12.2 2h-.4a2 2 0 0 0-2 2v.2a2 2 0 0 1-1 1.7l-.4.3a2 2 0 0 1-2 0l-.2-.1a2 2 0 0 0-2.7.7l-.2.4a2 2 0 0 0 .7 2.7l.2.1a2 2 0 0 1 1 1.7v.6a2 2 0 0 1-1 1.8l-.2.1a2 2 0 0 0-.7 2.7l.2.4a2 2 0 0 0 2.7.7l.2-.1a2 2 0 0 1 2 0l.4.2a2 2 0 0 1 1 1.7V20a2 2 0 0 0 2 2h.4a2 2 0 0 0 2-2v-.2a2 2 0 0 1 1-1.7l.4-.2a2 2 0 0 1 2 0l.2.1a2 2 0 0 0 2.7-.7l.2-.4a2 2 0 0 0-.7-2.7l-.2-.1a2 2 0 0 1-1-1.8v-.5a2 2 0 0 1 1-1.7l.2-.1a2 2 0 0 0 .7-2.7l-.2-.4a2 2 0 0 0-2.7-.7l-.2.1a2 2 0 0 1-2 0l-.4-.3a2 2 0 0 1-1-1.7V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>'),wrap:(r=14)=>se(r,'<path d="M3 6h18"/><path d="M3 12h15a3 3 0 1 1 0 6h-4"/><path d="m16 16-2 2 2 2"/><path d="M3 18h7"/>'),eye:(r=14)=>se(r,'<path d="M2.1 12.4a1 1 0 0 1 0-.8 10.5 10.5 0 0 1 19.8 0 1 1 0 0 1 0 .8 10.5 10.5 0 0 1-19.8 0"/><circle cx="12" cy="12" r="3"/>'),pen:(r=14)=>se(r,'<path d="M21.2 6.4a2 2 0 0 0 0-2.8l-.8-.8a2 2 0 0 0-2.8 0L4 16.4V20h3.6z"/><path d="m15 5 4 4"/>'),alert:(r=14)=>se(r,'<path d="m21.7 18-8-14a2 2 0 0 0-3.5 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>'),arrowDown:(r=15)=>se(r,'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),bug:(r=14)=>se(r,'<path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/>'),copy:(r=14)=>se(r,'<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>'),fileText:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8M16 13H8M16 17H8"/>'),filePlus:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M9 15h6M12 18v-6"/>'),filePen:(r=13)=>se(r,'<path d="M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M13.4 20.3a1 1 0 0 0 .5-.3l6.9-6.9a1.4 1.4 0 0 0-2-2l-6.9 6.9a1 1 0 0 0-.3.5l-.4 1.8z"/>'),fileX:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="m14.5 12.5-5 5M9.5 12.5l5 5"/>'),search:(r=13)=>se(r,'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),braces:(r=13)=>se(r,'<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>'),message:(r=13)=>se(r,'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),wrench:(r=13)=>se(r,'<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>')};function ds(r,e){return new Promise(n=>{let t=h("div","ra-modal"),s=h("div","ra-dlg");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",e.title),s.append(h("div","ra-dt",e.title)),e.message&&s.append(h("div","ra-dm",e.message)),e.body&&s.append(...e.body);let o=h("div","ra-btns"),a=u=>{t.remove(),n(u)},l=h("button","ra-btn",e.cancel);l.type="button",l.addEventListener("click",()=>a(!1));let d=h("button","ra-btn "+(e.danger?"red":"solid"),e.ok);d.type="button",d.addEventListener("click",()=>a(!0)),o.append(l,d),s.append(o),t.append(s),t.addEventListener("click",u=>{u.target===t&&a(!1)}),t.addEventListener("keydown",u=>{u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),a(!1)),e.submitOnEnter&&u.key==="Enter"&&!u.isComposing&&u.keyCode!==229&&(u.preventDefault(),a(!0))}),r.append(t);let p=e.focus==="ok"?d:e.focus instanceof HTMLElement?e.focus:l;queueMicrotask(()=>{p.focus(),p instanceof HTMLInputElement&&p.select()})})}function ut(r,e,n,t){return ds(r,{title:e,message:n,...t})}async function ha(r,e,n){let t=h("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await ds(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}function or(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=URL.createObjectURL(t),o=h("a");o.href=s,o.download=r,document.body.append(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function bn(r,e,n){r.innerHTML=yn(e),r.classList.toggle("ra-cursor",n);for(let t of Array.from(r.querySelectorAll("pre"))){let s=t.querySelector("code"),o=s?.className.match(/language-([\w+#-]+)/)?.[1]??"",a=h("div","ra-cb"),l=h("div","ra-cbh");l.append(h("span","",o));let d=h("button","ra-copy");d.type="button",d.innerHTML=U.copy(),d.title=/^zh/i.test(document.documentElement.lang||navigator.language||"")?"\u590D\u5236":"Copy",d.setAttribute("aria-label",d.title),d.addEventListener("click",()=>{navigator.clipboard?.writeText((s?.textContent??"").replace(/\n$/,"")).then(()=>{d.innerHTML=U.check(14),setTimeout(()=>{d.innerHTML=U.copy()},1200)})}),l.append(d),t.replaceWith(a),a.append(l,t)}for(let t of Array.from(r.querySelectorAll("table"))){let s=h("div","ra-tw");t.replaceWith(s),s.append(t)}}function ar(r,e={}){let n=e.options??[],t=e.value??n[0]?.value??"",s=!1,o=h("button","ra-sel");o.type="button",o.setAttribute("aria-haspopup","listbox");let a=h("span","ra-sell"),l=h("span","ra-selc");l.innerHTML=U.chevDown(14),o.append(a,l);let d=null,p=0,u="",w=()=>{let C=n.find(N=>N.value===t);a.textContent=C?.label??e.placeholder??"",a.classList.toggle("ph",!C),o.disabled=s},b=()=>u?n.filter(C=>`${C.label} ${C.note??""}`.toLowerCase().includes(u.toLowerCase())):n,x=(C=!0)=>{d&&(d.remove(),d=null,u="",o.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",M,!0),C&&o.focus())},M=C=>{d&&(!o.isConnected||!d.contains(C.target)&&!o.contains(C.target))&&x(!1)},S=C=>{let N=C!==t;t=C,w(),x(),N&&o.dispatchEvent(new Event("change",{bubbles:!0}))},A=C=>{C.replaceChildren();let N=b();p>=N.length&&(p=Math.max(0,N.length-1)),N.forEach((O,te)=>{let ge=h("div","ra-selo"+(te===p?" act":"")+(O.value===t?" cur":""));ge.setAttribute("role","option"),ge.setAttribute("aria-selected",String(O.value===t));let J=h("span","ra-selt");J.innerHTML=O.value===t?U.tick(13):"",ge.append(J,h("span","ra-selol",O.label)),O.note&&ge.append(h("span","ra-selon",O.note)),ge.addEventListener("pointermove",()=>{p!==te&&(p=te,C.querySelectorAll(".ra-selo").forEach((ee,de)=>ee.classList.toggle("act",de===te)))}),ge.addEventListener("click",()=>S(O.value)),C.append(ge)}),N.length||C.append(h("div","ra-selnone","\u2014")),C.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},P=()=>{if(d||s)return;d=h("div","ra-selp"),d.setAttribute("role","listbox");let C=h("div","ra-sellist"),N=null;n.length>=(e.filterAt??10)&&(N=h("input","ra-self"),N.type="text",N.placeholder=e.filterLabel??"Filter\u2026",N.addEventListener("input",()=>{u=N.value,p=0,A(C)}),N.addEventListener("keydown",_),d.append(N)),d.append(C),p=Math.max(0,n.findIndex(ve=>ve.value===t)),A(C),r.append(d);let O=r.getBoundingClientRect(),te=o.getBoundingClientRect(),ge=O.bottom-te.bottom-8,J=te.top-O.top-8,ee=Math.min(d.scrollHeight,320),de=ge<ee&&J>ge;d.style.left=`${te.left-O.left+r.scrollLeft}px`,d.style.width=`${te.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,de?J:ge))}px`,d.style.top=de?`${te.top-O.top+r.scrollTop-d.offsetHeight-4}px`:`${te.bottom-O.top+r.scrollTop+4}px`,o.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",M,!0),(N??o).focus()},_=C=>{if(!d){(C.key==="ArrowDown"||C.key==="ArrowUp"||C.key==="Enter"||C.key===" ")&&(C.preventDefault(),P());return}let N=b(),O=d.querySelector(".ra-sellist");if(C.key==="ArrowDown")C.preventDefault(),p=Math.min(N.length-1,p+1),A(O);else if(C.key==="ArrowUp")C.preventDefault(),p=Math.max(0,p-1),A(O);else if(C.key==="Enter"){C.preventDefault();let te=N[p];te&&S(te.value)}else C.key==="Escape"?(C.preventDefault(),C.stopPropagation(),x()):C.key==="Tab"&&x(!1)};return o.addEventListener("click",()=>d?x():P()),o.addEventListener("keydown",_),w(),{el:o,get value(){return t},set value(C){t=C,w()},get disabled(){return s},set disabled(C){s=C,C&&x(!1),w()},get options(){return n},setOptions(C){n=C,n.some(N=>N.value===t)||(t=n[0]?.value??""),w()},close(){x(!1)}}}var ga=`
|
|
277
|
+
`)?`<br>${l.slice(3,-4)}`:l)}var wn=class{constructor(e,n,t={}){z(this,"scroller",e);z(this,"inner",n);z(this,"rows",[]);z(this,"_follow",!0);z(this,"onFollow");z(this,"top");z(this,"win");z(this,"bottom");z(this,"wrappers",new Map);z(this,"ro");z(this,"estimate");z(this,"overscan");z(this,"rowClass");z(this,"followWithin");z(this,"offsets",[]);z(this,"first",0);z(this,"last",-1);z(this,"frame",null);z(this,"disposed",!1);z(this,"expectedTop",-1);z(this,"pinned",null);z(this,"lastTop",0);z(this,"onScroll",()=>{let e=this.scroller,n=e.scrollTop,t=this.expectedTop>=0&&Math.abs(n-this.expectedTop)<=1;this.expectedTop=-1,t||(this.pinned=null,e.scrollHeight-n-e.clientHeight<=this.followWithin?this.follow=!0:n<this.lastTop-.5&&(this.follow=!1)),this.lastTop=n,this.schedule()});z(this,"onWheel",e=>{this.pinned=null,e.deltaY<0&&this.scroller.scrollTop>0&&(this.follow=!1)});z(this,"touchY",0);z(this,"onTouch",e=>{this.touchY=e.touches[0]?.clientY??0;let n=s=>{(s.touches[0]?.clientY??0)>this.touchY+2&&this.scroller.scrollTop>0&&(this.follow=!1)},t=()=>{this.scroller.removeEventListener("touchmove",n),this.scroller.removeEventListener("touchend",t),this.scroller.removeEventListener("touchcancel",t)};this.scroller.addEventListener("touchmove",n,{passive:!0}),this.scroller.addEventListener("touchend",t,{passive:!0}),this.scroller.addEventListener("touchcancel",t,{passive:!0})});this.estimate=t.estimate??96,this.overscan=t.overscan??400,this.rowClass=t.rowClass??"",this.followWithin=t.followWithin??2,this.onFollow=t.onFollow,this.top=document.createElement("div"),this.win=document.createElement("div"),this.bottom=document.createElement("div"),n.append(this.top,this.win,this.bottom),e.style.overflowAnchor="none",e.addEventListener("scroll",this.onScroll,{passive:!0}),e.addEventListener("wheel",this.onWheel,{passive:!0}),e.addEventListener("touchstart",this.onTouch,{passive:!0}),this.ro=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>this.schedule()),this.ro&&this.ro.observe(e)}get follow(){return this._follow}set follow(e){e!==this._follow&&(this._follow=e,this.onFollow?.(e))}setTop(e){let n=this.scroller;Math.abs(n.scrollTop-e)<=.5||(this.expectedTop=e,n.scrollTop=e,this.lastTop=n.scrollTop)}get length(){return this.rows.length}push(e){e.height??(e.height=this.estimate),this.rows.push(e),this.schedule()}remove(e){let n=this.rows.indexOf(e);n<0||(this.rows.splice(n,1),this.detach(e),this.first=0,this.last=-1,this.schedule())}clear(){for(let e of this.rows)this.detach(e);this.rows.length=0,this.offsets=[],this.first=0,this.last=-1,this.follow=!0,this.win.replaceChildren(),this.top.style.height=this.bottom.style.height="0px"}scrollToBottom(){this.pinned=null,this.follow=!0,this.layout()}pin(e,n=800){this.pinned={el:e,offset:e.getBoundingClientRect().top-this.scroller.getBoundingClientRect().top,until:Date.now()+n},this.follow=!1}applyPin(){let e=this.pinned;if(!e)return;if(!e.el.isConnected||Date.now()>e.until){this.pinned=null;return}let n=e.el.getBoundingClientRect().top-this.scroller.getBoundingClientRect().top-e.offset;Math.abs(n)>.5&&this.setTop(this.scroller.scrollTop+n)}schedule(){this.disposed||this.frame!==null||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.layout()}))}dispose(){this.disposed=!0,this.frame!==null&&cancelAnimationFrame(this.frame),this.scroller.removeEventListener("scroll",this.onScroll),this.scroller.removeEventListener("wheel",this.onWheel),this.scroller.removeEventListener("touchstart",this.onTouch),this.ro?.disconnect()}detach(e){let n=this.wrappers.get(e);n&&(this.ro?.unobserve(n),n.remove(),this.wrappers.delete(e))}wrapper(e){let n=this.wrappers.get(e);return n||(n=document.createElement("div"),this.rowClass&&(n.className=this.rowClass),e.el||(e.el=e.render()),n.append(e.el),this.wrappers.set(e,n),this.ro?.observe(n),n)}computeOffsets(){let e=this.rows.length;this.offsets.length=e+1;let n=0;for(let t=0;t<e;t++)this.offsets[t]=n,n+=this.rows[t].height??this.estimate;return this.offsets[e]=n,n}indexAt(e){let n=0,t=this.rows.length-1;for(;n<t;){let s=n+t>>1;this.offsets[s+1]<=e?n=s+1:t=s}return n}layout(){if(!this.disposed)try{this.layoutRows()}finally{this.applyPin()}}layoutRows(){let e=this.scroller,n=this.rows.length;if(!n){this.win.replaceChildren(),this.top.style.height=this.bottom.style.height="0px";return}let t=e.clientHeight||600,s=()=>Math.max(0,e.scrollHeight-e.clientHeight);for(let o=0;o<4;o++){let a=this.computeOffsets(),l=this.follow?Math.max(0,a-t):e.scrollTop,d=this.indexAt(l),p=this.offsets[d]-l,u=this.indexAt(Math.max(0,l-this.overscan)),w=Math.min(n-1,this.indexAt(Math.min(a-1,l+t+this.overscan)));if(u!==this.first||w!==this.last||this.win.childElementCount!==w-u+1){let b=new Set(this.rows.slice(u,w+1));for(let[T,A]of this.wrappers)b.has(T)||(this.ro?.unobserve(A),A.remove(),this.wrappers.delete(T));let M=[];for(let T=u;T<=w;T++)M.push(this.wrapper(this.rows[T]));this.win.replaceChildren(...M),this.first=u,this.last=w}this.top.style.height=`${this.offsets[u]}px`,this.bottom.style.height=`${a-this.offsets[w+1]}px`;let x=!1;for(let b=u;b<=w;b++){let M=this.rows[b],T=this.wrappers.get(M).offsetHeight;T&&T!==M.height&&(M.height=T,x=!0)}if(x){this.computeOffsets(),this.setTop(this.follow?s():Math.max(0,this.offsets[d]-p));continue}this.follow&&Math.abs(e.scrollTop-s())>1&&this.setTop(s());return}}};function h(r,e,n){let t=document.createElement(r);return e&&(t.className=e),n!==void 0&&(t.textContent=n),t}var se=(r,e,n=2)=>`<svg width="${r}" height="${r}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${n}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e}</svg>`,U={tick:(r=14)=>se(r,'<path d="M20 6 9 17l-5-5"/>'),enter:(r=14)=>se(r,'<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),lock:(r=12)=>se(r,'<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),puzzle:(r=14)=>se(r,'<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>'),spark:(r=14)=>se(r,'<path d="M9.9 2.1a1 1 0 0 1 1.9 0l1.3 4.1a4 4 0 0 0 2.6 2.6l4.1 1.3a1 1 0 0 1 0 1.9l-4.1 1.3a4 4 0 0 0-2.6 2.6l-1.3 4.1a1 1 0 0 1-1.9 0l-1.3-4.1a4 4 0 0 0-2.6-2.6L2.1 12a1 1 0 0 1 0-1.9l4.1-1.3a4 4 0 0 0 2.6-2.6z"/><path d="M20 3v4M22 5h-4"/>'),send:(r=16)=>se(r,'<path d="M14.5 9.5 22 2M22 2l-7 20-4-9-9-4z"/>'),hist:(r=14)=>se(r,'<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 3"/>'),eraser:(r=14)=>se(r,'<path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21"/><path d="m5.082 11.09 8.828 8.828"/>'),pointer:(r=14)=>se(r,'<path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/>'),plus:(r=14)=>se(r,'<path d="M12 5v14M5 12h14"/>'),chev:(r=14)=>se(r,'<path d="m9 18 6-6-6-6"/>'),brain:(r=13)=>se(r,'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/><path d="M17.6 6.5a3 3 0 0 0 .4 1M6.4 6.5a3 3 0 0 1-.4 1M12 18v-5"/>'),layers:(r=14)=>se(r,'<path d="m12.8 2.2 8.5 4a1 1 0 0 1 0 1.6l-8.5 4a2 2 0 0 1-1.6 0l-8.5-4a1 1 0 0 1 0-1.6l8.5-4a2 2 0 0 1 1.6 0"/><path d="m2.4 11.9 8.8 4.1a2 2 0 0 0 1.6 0l8.8-4.1"/><path d="m2.4 16.9 8.8 4.1a2 2 0 0 0 1.6 0l8.8-4.1"/>'),check:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>'),xcircle:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6M9 9l6 6"/>'),ban:(r=15)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/>'),square:(r=12)=>se(r,'<rect x="3" y="3" width="18" height="18" rx="2"/>'),corner:(r=14)=>se(r,'<path d="M20 4v7a4 4 0 0 1-4 4H4"/><path d="m9 10-5 5 5 5"/>'),x:(r=12)=>se(r,'<path d="M18 6 6 18M6 6l12 12"/>'),trash:(r=13)=>se(r,'<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>'),clip:(r=16)=>se(r,'<path d="m21.4 11.1-9.2 9.2a6 6 0 0 1-8.5-8.5l9.2-9.2a4 4 0 0 1 5.7 5.7l-9.2 9.2a2 2 0 0 1-2.8-2.8l8.5-8.5"/>'),file:(r=14)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>'),folder:(r=14)=>se(r,'<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>'),folderOpen:(r=14)=>se(r,'<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>'),upload:(r=14)=>se(r,'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/>'),download:(r=14)=>se(r,'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>'),refresh:(r=13)=>se(r,'<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/>'),save:(r=12)=>se(r,'<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h7"/>'),chevDown:(r=12)=>se(r,'<path d="m6 9 6 6 6-6"/>'),checks:(r=13)=>se(r,'<path d="M18 6 7 17l-5-5"/><path d="m22 10-7.5 7.5L13 16"/>'),undo:(r=13)=>se(r,'<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'),gear:(r=14)=>se(r,'<path d="M12.2 2h-.4a2 2 0 0 0-2 2v.2a2 2 0 0 1-1 1.7l-.4.3a2 2 0 0 1-2 0l-.2-.1a2 2 0 0 0-2.7.7l-.2.4a2 2 0 0 0 .7 2.7l.2.1a2 2 0 0 1 1 1.7v.6a2 2 0 0 1-1 1.8l-.2.1a2 2 0 0 0-.7 2.7l.2.4a2 2 0 0 0 2.7.7l.2-.1a2 2 0 0 1 2 0l.4.2a2 2 0 0 1 1 1.7V20a2 2 0 0 0 2 2h.4a2 2 0 0 0 2-2v-.2a2 2 0 0 1 1-1.7l.4-.2a2 2 0 0 1 2 0l.2.1a2 2 0 0 0 2.7-.7l.2-.4a2 2 0 0 0-.7-2.7l-.2-.1a2 2 0 0 1-1-1.8v-.5a2 2 0 0 1 1-1.7l.2-.1a2 2 0 0 0 .7-2.7l-.2-.4a2 2 0 0 0-2.7-.7l-.2.1a2 2 0 0 1-2 0l-.4-.3a2 2 0 0 1-1-1.7V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>'),wrap:(r=14)=>se(r,'<path d="M3 6h18"/><path d="M3 12h15a3 3 0 1 1 0 6h-4"/><path d="m16 16-2 2 2 2"/><path d="M3 18h7"/>'),eye:(r=14)=>se(r,'<path d="M2.1 12.4a1 1 0 0 1 0-.8 10.5 10.5 0 0 1 19.8 0 1 1 0 0 1 0 .8 10.5 10.5 0 0 1-19.8 0"/><circle cx="12" cy="12" r="3"/>'),pen:(r=14)=>se(r,'<path d="M21.2 6.4a2 2 0 0 0 0-2.8l-.8-.8a2 2 0 0 0-2.8 0L4 16.4V20h3.6z"/><path d="m15 5 4 4"/>'),alert:(r=14)=>se(r,'<path d="m21.7 18-8-14a2 2 0 0 0-3.5 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>'),arrowDown:(r=15)=>se(r,'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),bug:(r=14)=>se(r,'<path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/>'),copy:(r=14)=>se(r,'<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>'),fileText:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8M16 13H8M16 17H8"/>'),filePlus:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M9 15h6M12 18v-6"/>'),filePen:(r=13)=>se(r,'<path d="M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M13.4 20.3a1 1 0 0 0 .5-.3l6.9-6.9a1.4 1.4 0 0 0-2-2l-6.9 6.9a1 1 0 0 0-.3.5l-.4 1.8z"/>'),fileX:(r=13)=>se(r,'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="m14.5 12.5-5 5M9.5 12.5l5 5"/>'),search:(r=13)=>se(r,'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),braces:(r=13)=>se(r,'<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>'),message:(r=13)=>se(r,'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),wrench:(r=13)=>se(r,'<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>')};function ds(r,e){return new Promise(n=>{let t=h("div","ra-modal"),s=h("div","ra-dlg");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",e.title),s.append(h("div","ra-dt",e.title)),e.message&&s.append(h("div","ra-dm",e.message)),e.body&&s.append(...e.body);let o=h("div","ra-btns"),a=u=>{t.remove(),n(u)},l=h("button","ra-btn",e.cancel);l.type="button",l.addEventListener("click",()=>a(!1));let d=h("button","ra-btn "+(e.danger?"red":"solid"),e.ok);d.type="button",d.addEventListener("click",()=>a(!0)),o.append(l,d),s.append(o),t.append(s),t.addEventListener("click",u=>{u.target===t&&a(!1)}),t.addEventListener("keydown",u=>{u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),a(!1)),e.submitOnEnter&&u.key==="Enter"&&!u.isComposing&&u.keyCode!==229&&(u.preventDefault(),a(!0))}),r.append(t);let p=e.focus==="ok"?d:e.focus instanceof HTMLElement?e.focus:l;queueMicrotask(()=>{p.focus(),p instanceof HTMLInputElement&&p.select()})})}function ut(r,e,n,t){return ds(r,{title:e,message:n,...t})}async function ha(r,e,n){let t=h("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await ds(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}function or(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=URL.createObjectURL(t),o=h("a");o.href=s,o.download=r,document.body.append(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function bn(r,e,n){r.innerHTML=yn(e),r.classList.toggle("ra-cursor",n);for(let t of Array.from(r.querySelectorAll("pre"))){let s=t.querySelector("code"),o=s?.className.match(/language-([\w+#-]+)/)?.[1]??"",a=h("div","ra-cb"),l=h("div","ra-cbh");l.append(h("span","",o));let d=h("button","ra-copy");d.type="button",d.innerHTML=U.copy(),d.title=/^zh/i.test(document.documentElement.lang||navigator.language||"")?"\u590D\u5236":"Copy",d.setAttribute("aria-label",d.title),d.addEventListener("click",()=>{navigator.clipboard?.writeText((s?.textContent??"").replace(/\n$/,"")).then(()=>{d.innerHTML=U.check(14),setTimeout(()=>{d.innerHTML=U.copy()},1200)})}),l.append(d),t.replaceWith(a),a.append(l,t)}for(let t of Array.from(r.querySelectorAll("table"))){let s=h("div","ra-tw");t.replaceWith(s),s.append(t)}}function ar(r,e={}){let n=e.options??[],t=e.value??n[0]?.value??"",s=!1,o=h("button","ra-sel");o.type="button",o.setAttribute("aria-haspopup","listbox");let a=h("span","ra-sell"),l=h("span","ra-selc");l.innerHTML=U.chevDown(14),o.append(a,l);let d=null,p=0,u="",w=()=>{let C=n.find(N=>N.value===t);a.textContent=C?.label??e.placeholder??"",a.classList.toggle("ph",!C),o.disabled=s},x=()=>u?n.filter(C=>`${C.label} ${C.note??""}`.toLowerCase().includes(u.toLowerCase())):n,b=(C=!0)=>{d&&(d.remove(),d=null,u="",o.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",M,!0),C&&o.focus())},M=C=>{d&&(!o.isConnected||!d.contains(C.target)&&!o.contains(C.target))&&b(!1)},T=C=>{let N=C!==t;t=C,w(),b(),N&&o.dispatchEvent(new Event("change",{bubbles:!0}))},A=C=>{C.replaceChildren();let N=x();p>=N.length&&(p=Math.max(0,N.length-1)),N.forEach((O,te)=>{let ge=h("div","ra-selo"+(te===p?" act":"")+(O.value===t?" cur":""));ge.setAttribute("role","option"),ge.setAttribute("aria-selected",String(O.value===t));let J=h("span","ra-selt");J.innerHTML=O.value===t?U.tick(13):"",ge.append(J,h("span","ra-selol",O.label)),O.note&&ge.append(h("span","ra-selon",O.note)),ge.addEventListener("pointermove",()=>{p!==te&&(p=te,C.querySelectorAll(".ra-selo").forEach((ee,de)=>ee.classList.toggle("act",de===te)))}),ge.addEventListener("click",()=>T(O.value)),C.append(ge)}),N.length||C.append(h("div","ra-selnone","\u2014")),C.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},P=()=>{if(d||s)return;d=h("div","ra-selp"),d.setAttribute("role","listbox");let C=h("div","ra-sellist"),N=null;n.length>=(e.filterAt??10)&&(N=h("input","ra-self"),N.type="text",N.placeholder=e.filterLabel??"Filter\u2026",N.addEventListener("input",()=>{u=N.value,p=0,A(C)}),N.addEventListener("keydown",_),d.append(N)),d.append(C),p=Math.max(0,n.findIndex(ve=>ve.value===t)),A(C),r.append(d);let O=r.getBoundingClientRect(),te=o.getBoundingClientRect(),ge=O.bottom-te.bottom-8,J=te.top-O.top-8,ee=Math.min(d.scrollHeight,320),de=ge<ee&&J>ge;d.style.left=`${te.left-O.left+r.scrollLeft}px`,d.style.width=`${te.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,de?J:ge))}px`,d.style.top=de?`${te.top-O.top+r.scrollTop-d.offsetHeight-4}px`:`${te.bottom-O.top+r.scrollTop+4}px`,o.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",M,!0),(N??o).focus()},_=C=>{if(!d){(C.key==="ArrowDown"||C.key==="ArrowUp"||C.key==="Enter"||C.key===" ")&&(C.preventDefault(),P());return}let N=x(),O=d.querySelector(".ra-sellist");if(C.key==="ArrowDown")C.preventDefault(),p=Math.min(N.length-1,p+1),A(O);else if(C.key==="ArrowUp")C.preventDefault(),p=Math.max(0,p-1),A(O);else if(C.key==="Enter"){C.preventDefault();let te=N[p];te&&T(te.value)}else C.key==="Escape"?(C.preventDefault(),C.stopPropagation(),b()):C.key==="Tab"&&b(!1)};return o.addEventListener("click",()=>d?b():P()),o.addEventListener("keydown",_),w(),{el:o,get value(){return t},set value(C){t=C,w()},get disabled(){return s},set disabled(C){s=C,C&&b(!1),w()},get options(){return n},setOptions(C){n=C,n.some(N=>N.value===t)||(t=n[0]?.value??""),w()},close(){b(!1)}}}var ga=`
|
|
278
278
|
:is(.ra-chat,.ra-ui) .ra-sel{display:flex;align-items:center;gap:8px;width:100%;min-width:0;min-height:34px;padding:6px 10px 6px 12px;box-sizing:border-box;font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;text-align:left;cursor:pointer}
|
|
279
279
|
:is(.ra-chat,.ra-ui) .ra-sel:hover:not(:disabled){border-color:color-mix(in srgb,var(--ra-fg) 25%,var(--ra-border))}
|
|
280
280
|
:is(.ra-chat,.ra-ui) .ra-sel:focus-visible,:is(.ra-chat,.ra-ui) .ra-sel[aria-expanded=true]{border-color:var(--ra-accent);outline:0;box-shadow:0 0 0 3px var(--ra-accent-subtle)}
|
|
@@ -294,7 +294,7 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
294
294
|
:is(.ra-chat,.ra-ui) .ra-selo.cur .ra-selol{font-weight:500}
|
|
295
295
|
:is(.ra-chat,.ra-ui) .ra-selo .ra-selon{flex:none;font-size:11.5px;color:var(--ra-fg-muted);font-variant-numeric:tabular-nums}
|
|
296
296
|
:is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
|
|
297
|
-
`;var Cc=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,Kt=r=>r.slice(r.lastIndexOf("/")+1),bi=r=>r.slice(0,r.lastIndexOf("/"))||"/";function Ec(r){let e={name:"",path:"/",folder:!0,children:[]},n=new Map([["/",e]]),t=o=>{let a=n.get(o);if(a)return a;let l=t(bi(o));return a={name:Kt(o),path:o,folder:!0,children:[]},l.children.push(a),n.set(o,a),a};for(let o of r)t(bi(o.path)).children.push({name:Kt(o.path),path:o.path,folder:!1,stat:o,children:[]});let s=o=>{o.children.sort((a,l)=>Number(l.folder)-Number(a.folder)||a.name.localeCompare(l.name)),o.children.forEach(s)};return s(e),e}async function xi(r,e,n){let t=e==="/"?"":e,s=n.lastIndexOf("."),o=s>0?n.slice(0,s):n,a=s>0?n.slice(s):"";for(let l=1;l<1e3;l++){let d=`${t}/${l===1?n:`${o}-${l}${a}`}`;if(!await r.exists(d))return d}return`${t}/${Date.now()}-${n}`}function ma(r){let{t:e,root:n,notify:t,editorHost:s}=r,o=null,a=!1,l=null,d=null,p=null,u=null,w="/",b=new Set(["/.agent"]),x=null,M=0,S=null,A=2*1024*1024,P=null,_=()=>{P||(P=setTimeout(()=>{P=null,$e()},150))},C=new Set,N=!1,O=h("div","ra-fp");O.setAttribute("role","complementary"),O.style.display="none";let te=h("div","ra-fph"),ge=h("span","ra-fpt",e.files),J=(T,q,oe)=>{let Y=h("button","ra-ib");return Y.type="button",Y.innerHTML=T,Y.title=q,Y.setAttribute("aria-label",q),Y.addEventListener("click",oe),Y},ee=h("input");ee.type="file",ee.multiple=!0,ee.style.display="none";let de=J(U.upload(),e.upload,()=>ee.click()),ve=J(U.download(),e.downloadZip,()=>{Xt("/")}),Oe=J(U.filePlus(14),e.newFile,()=>{pr()}),pe=J(U.refresh(),e.refresh,()=>{$e()}),we=J(U.x(14),e.close,()=>{Qe()});te.append(ge,h("span","ra-sp"),ve,de,Oe,pe,we);let fe=h("div","ra-tree"),Se=h("div","ra-ed");Se.style.display="none";let _e=h("div","ra-edh"),R=h("span","ra-edp"),I=h("span","ra-edro");I.innerHTML=U.lock(11)+`<span>${e.readOnly}</span>`,I.style.display="none";let G=h("div","ra-eda"),B=h("button","ra-btn xs solid");B.type="button",B.innerHTML=U.save()+e.save,B.style.display="none",B.addEventListener("click",()=>{An()});let j="__runapps_agent_files:wrap",K=(()=>{try{return localStorage.getItem(j)!=="0"}catch{return!0}})(),ie=!1,H=J(U.wrap(),e.wrap,()=>{K=!K;try{localStorage.setItem(j,K?"1":"0")}catch{}Re()}),re=J(U.eye(),e.preview,()=>{ie=!ie,Vt()}),Ee=h("div","ra-md ra-edmd");Ee.style.display="none",Ee.addEventListener("click",T=>{let q=T.target.closest("a[href]"),oe=q?.getAttribute("href")??"";if(!q||!oe.startsWith("/")||oe.startsWith("//")||!o)return;T.preventDefault();let Y=o;Y.exists(oe).then(ae=>{ae&&Y===o&&He(oe)})});let Re=()=>{ye.classList.toggle("ra-wrap",K),H.classList.toggle("on",K)},xt=T=>!!T&&/\.(md|markdown|mdx)$/i.test(T),Vt=()=>{let T=p!==null;re.style.display=T&&xt(l)?"":"none",(!T||!xt(l))&&(ie=!1),re.innerHTML=ie?U.pen():U.eye(),re.title=ie?e.edit:e.preview,re.setAttribute("aria-label",re.title),re.classList.toggle("on",ie),ie&&bn(Ee,d??ye.value,!1),Ee.style.display=ie?"":"none",ye.style.display=T&&!ie?"":"none"},Gt=J(U.download(),e.download,()=>{l&&Rt(l)}),Mn=J(U.trash(),e.delete,()=>{l&&$n(l)}),_t=J(U.x(14),e.close,()=>{En()});G.append(B,H,re,Gt,Mn,_t),_e.append(R,I,G);let dr=h("div","ra-edb"),ye=h("textarea","ra-edta");ye.spellcheck=!1,ye.setAttribute("aria-label",e.files);let Ae=h("div","ra-edpv");dr.append(ye,Ee,Ae),Re(),Se.append(_e,dr);let nt=h("div","ra-fpdrop",e.upload);O.append(te,fe,ee,nt),s.append(Se);let Ye=T=>{I.style.display=T?"":"none",Mn.style.display=Gt.style.display=T?"none":""},ft=T=>{d=T,B.style.display=T===null?"none":""};ye.addEventListener("input",()=>ft(ye.value===p?null:ye.value)),ye.addEventListener("keydown",T=>{if((T.metaKey||T.ctrlKey)&&T.key==="s"&&(T.preventDefault(),An()),T.key==="Tab"&&!T.shiftKey){T.preventDefault();let q=ye.selectionStart;ye.setRangeText(" ",q,ye.selectionEnd,"end"),ye.dispatchEvent(new Event("input"))}});let Zt=async()=>d===null||ut(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),Xe=(T,q)=>{if(!o)return!1;if(!q)return o.isReadOnly(T);let oe=(S??[]).filter(Y=>Y.path.startsWith(T+"/"));return oe.length>0&&oe.every(Y=>o.isReadOnly(Y.path))},Cn=()=>w!=="/"&&Xe(w,!0)?"/":w,ht=(T,q,oe,Y=!1)=>{for(let ae of T.children){let me=h("div","ra-fr"+(ae.path===l?" ra-cur":""));me.style.paddingLeft=`${q*14+6}px`,me.dataset.path=ae.path;let Ve=ae.folder&&!b.has(ae.path),ws=h("span","ra-frc");ws.innerHTML=ae.folder?Ve?U.chevDown():U.chev(12):"";let ur=h("span","ra-fri");ur.innerHTML=ae.folder?Ve?U.folderOpen():U.folder():U.file();let Dt=h("span","ra-frn",ae.name);if(Dt.title=ae.path,me.append(ws,ur,Dt),C.has(ae.path)){let Le=h("span","ra-dot");Le.title=e.changedByAgent,me.append(Le)}let Pn=Y||Xe(ae.path,ae.folder);if(Pn){if(me.classList.add("ra-ro"),me.title=`${ae.path} \xB7 ${e.readOnly}`,!Y){let Le=h("span","ra-frl");Le.innerHTML=U.lock(),Le.title=e.readOnly,me.append(Le)}}else{let Le=h("span","ra-fra");Le.append(ae.folder?J(U.download(13),e.downloadZip,()=>{Xt(ae.path)}):J(U.download(13),e.download,()=>{Rt(ae.path)})),Le.append(J(U.trash(12),e.delete,()=>{$n(ae.path)})),me.append(Le)}me.addEventListener("click",Le=>{Le.target.closest(".ra-fra")||(ae.folder?(w=ae.path,b.delete(ae.path)||b.add(ae.path),ze()):(w=bi(ae.path),He(ae.path)))}),oe.append(me),ae.folder&&Ve&&ht(ae,q+1,oe,Pn)}},ze=()=>{if(!S)return;let T=document.createDocumentFragment();S.length?ht(Ec(S),0,T):T.append(h("div","ra-fpe",e.noFiles)),fe.replaceChildren(T)},$e=async()=>{if(!o||!a||N)return;let T=++M,q=o;try{let oe=await q.list("/");if(T!==M||q!==o||N)return;S=oe,ze()}catch(oe){if(T!==M||N)return;fe.replaceChildren(h("div","ra-fpe",oe.message))}},Be=T=>{Se.style.display=T?"":"none",n.classList.toggle("ra-editing",T)},He=async T=>{if(o&&!(T!==l&&!await Zt())){l=T,C.delete(T),ft(null),R.textContent=T,u&&(URL.revokeObjectURL(u),u=null),Ae.replaceChildren(),Be(!0);try{let q=await o.read(T);if(l!==T)return;let oe=Cc.test(T)||/^image\//.test(q.contentType??""),Y=null;if(!oe)if(typeof q.data=="string")Y=q.data;else try{Y=new TextDecoder("utf-8",{fatal:!0}).decode(q.data)}catch{Y=null}if(/\.pdf$/i.test(T)||q.contentType==="application/pdf"){p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",u=URL.createObjectURL(new Blob([q.data],{type:"application/pdf"}));let me=h("iframe","ra-edpdf");me.src=u,me.title=Kt(T),H.style.display="none",Ae.replaceChildren(me),Ye(o.isReadOnly(T)),ze();return}H.style.display="",Y!==null&&q.size>A&&(Y=null);let ae=o.isReadOnly(T);if(Ye(ae),Y!==null)p=Y,ye.value=Y,Ae.style.display="none",ye.readOnly=ae,ye.title=ae?e.readOnly:"",Vt();else{if(p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",oe){let me=new Blob([q.data],{type:q.contentType||"image/*"});u=URL.createObjectURL(me);let Ve=h("img");Ve.src=u,Ve.alt=Kt(T),Ae.append(Ve)}else Ae.append(h("div","ra-fpe",q.size>A&&!oe?e.tooBig:e.noPreview));Ae.append(h("div","ra-fpe",`${q.size} B`))}}catch(q){p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",Ae.replaceChildren(h("div","ra-fpe",q.message))}ze()}},En=async()=>l?await Zt()?(l=null,p=null,ft(null),u&&(URL.revokeObjectURL(u),u=null),Be(!1),await $e(),!0):!1:!0,An=async()=>{if(!o||!l||d===null)return;let T=l,q=d,oe=o;try{let Y=await oe.readText(T).catch(()=>null);if(Y!==null&&p!==null&&Y!==p&&!await ut(n,e.conflict,T,{ok:e.save,cancel:e.cancel,danger:!0})||(await oe.write(T,q),l!==T||oe!==o))return;p=q,ft(ye.value===q?null:ye.value),t(`${e.saved}: ${T}`),r.onChange?.()}catch(Y){t(Y.message,"error")}},Rt=async T=>{if(o)try{let q=await o.read(T);or(Kt(T),q.data,q.contentType)}catch(q){t(q.message,"error")}},Xt=async T=>{if(o)try{let q=T==="/"?"/":T+"/",oe=(await o.list(T)).filter(me=>me.path.startsWith(q));if(!oe.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${oe.length}\u2026`);let Y=[];for(let me of oe){let Ve=await o.read(me.path);Y.push({path:me.path.slice(q.length),data:Ve.data,mtime:me.mtime})}let ae=await Vr(Y);or(`${T==="/"?o.id||"directory":Kt(T)}.zip`,ae,"application/zip")}catch(q){t(q.message,"error")}},$n=async T=>{if(!o||!await ut(n,e.delete,e.confirmDeleteFile.replace("{path}",T),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let q=[];try{let oe=await o.isFolder(T)?(await o.list(T)).map(Y=>Y.path).filter(Y=>Y!==T):[T];for(let Y of oe){if(o.isReadOnly(Y)){q.push(Y);continue}try{await o.delete(Y)}catch{q.push(Y)}}}catch(oe){t(oe.message,"error")}l&&(l===T||l.startsWith(T+"/"))&&!await o.exists(l)&&(l=null,p=null,ft(null),Be(!1)),q.length&&t(`${e.readOnly}: ${q.slice(0,3).join(", ")}${q.length>3?` +${q.length-3}`:""}`,"warning"),r.onChange?.(),await $e()},pr=async()=>{if(!o)return;let T=Cn(),q=T==="/"?"/":T+"/",oe=await ha(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${q}untitled.md`});if(!oe)return;let Y="/"+oe.replace(/^\/+/,"");try{await o.exists(Y)||await o.write(Y,""),r.onChange?.(),await $e(),await He(Y),ye.focus()}catch(ae){t(ae.message,"error")}},vt=async T=>{if(!o||!T?.length)return;let q=null;for(let oe of Array.from(T))try{let Y=await xi(o,Cn(),Kt(oe.name.replace(/\\/g,"/"))||"file");await o.write(Y,new Uint8Array(await oe.arrayBuffer()),oe.type||void 0),q=Y}catch(Y){t(Y.message,"error")}r.onChange?.(),await $e(),q&&T.length===1&&await He(q)};ee.addEventListener("change",()=>{let T=Array.from(ee.files??[]);ee.value="",vt(T)});let Ke=0;O.addEventListener("dragenter",T=>{T.dataTransfer?.types.includes("Files")&&(T.preventDefault(),T.stopPropagation(),Ke++,O.dataset.drop="1")}),O.addEventListener("dragover",T=>{O.dataset.drop&&(T.preventDefault(),T.stopPropagation(),T.dataTransfer.dropEffect="copy")}),O.addEventListener("dragleave",T=>{O.dataset.drop&&(T.stopPropagation(),--Ke<=0&&(Ke=0,delete O.dataset.drop))}),O.addEventListener("drop",T=>{O.dataset.drop&&(T.preventDefault(),T.stopPropagation(),Ke=0,delete O.dataset.drop,vt(T.dataTransfer?.files))});let Ln=async T=>{a=!0,O.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await $e(),T&&await He(T)},Qe=async()=>{await En()&&(a=!1,O.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:O,get visible(){return a},open:Ln,close:Qe,toggle:()=>a?Qe():Ln(),setWorkspace(T){if(T!==o){if(o&&l&&d!==null){let[q,oe,Y]=[o,l,d];q.write(oe,Y).then(()=>t(`${e.autoSaved}: ${oe}`),ae=>t(ae.message,"error"))}x?.(),x=null,o=T,T&&(x=T.onChange(q=>{a&&(_(),!(q.path!==l||d!==null)&&(q.kind==="write"?He(q.path):(l=null,p=null,Be(!1))))})),u&&(URL.revokeObjectURL(u),u=null),S=null,l=null,p=null,ft(null),Be(!1),C.clear(),w="/",T?$e():(a=!1,O.style.display="none",n.classList.remove("ra-files-open"))}},refresh:$e,changed(T){C.add(T),ze()},download:Rt,downloadFolder:Xt,dispose(){N=!0,x?.(),P&&clearTimeout(P),u&&URL.revokeObjectURL(u),O.remove(),Se.remove(),n.classList.remove("ra-editing")}}}var vi={spans:400,requests:120,events:600},Ac=new Set(["text_delta","reasoning_delta","tool_update"]);function lr(r){let e=new Date(r);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}function $c(r){try{return JSON.stringify(r,null,2)??"undefined"}catch{return String(r)}}var ps=(r,e)=>{r.length>e&&r.splice(0,r.length-e)};function ya(r){let{t:e,root:n}=r,t=new WeakMap,s=new Map,o=null,a=!1,l="calls",d="",p=null,u=h("div","ra-fp ra-dp");u.setAttribute("role","complementary"),u.style.display="none";let w=h("div","ra-fph"),b=h("div","ra-dtabs"),x=h("button","ra-ib");x.type="button",x.innerHTML=U.x(14),x.title=e.close,x.setAttribute("aria-label",e.close),x.addEventListener("click",()=>_e()),w.append(b,h("span","ra-sp"),x);let M=h("div","ra-dbody");u.append(w,M);let S=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],A=()=>{let R=o?t.get(o):void 0,I={calls:R?.spans.length??0,requests:R?.requests.length??0};b.replaceChildren(...S.map(([G,B])=>{let j=h("button","ra-dtab"+(G===l?" on":""));return j.type="button",j.append(B),I[G]&&j.append(h("span","ra-dcount",String(I[G]))),j.addEventListener("click",()=>{l=G,pe()}),j}))},P=(R,I)=>{let G=h("details","ra-dfold"),B=h("summary"),j=h("span","ra-chev");j.innerHTML=U.chev(12),B.append(j,...R),G.append(B);let K=!1;return G.addEventListener("toggle",()=>{if(G.open&&!K){K=!0;let ie=h("div","ra-dfb");ie.append(...I()),G.append(ie)}}),G},_=(R,I="")=>{let G=h("pre","ra-dpre "+I);return G.textContent=typeof R=="string"?R:$c(R),G},C=R=>h("div","ra-dlabel",R),N=R=>h("span","ra-dmuted",R),O=R=>h("span","ra-dmono",R),te=R=>h("div","ra-fpe",R),ge=R=>{let I=h("span","ra-dst "+(R==="running"?"run":R==="ok"?"ok":"fail"));return R==="running"?I.append(h("span","ra-spin")):I.innerHTML=R==="ok"?U.check(13):U.xcircle(13),I},J=R=>{if(!R.spans.length)return[te(e.dNoCalls)];let I=[];for(let G of[...R.runs].reverse()){let B=R.spans.filter(H=>H.runId===G),j=R.requests.filter(H=>H.runId===G);if(!B.length&&!j.length)continue;let K=h("div","ra-drun");K.append(h("div","ra-drh",`${e.dRun} ${lr(j[0]?.at??B[0]?.startedAt??Date.now())} \xB7 ${G.slice(-4)}`));let ie=[...new Set([...j.map(H=>H.turn),...B.map(H=>H.turn)])].sort((H,re)=>H-re);for(let H of ie){let re=j.find(Re=>Re.turn===H),Ee=h("div","ra-dturn");Ee.append(N(e.dTurn.replace("{n}",String(H)))),re&&Ee.append(O(` \xB7 ${re.params.model||"default"}`),N(re.durationMs!==void 0?` \xB7 ${Math.round(re.durationMs)}ms`:" \xB7 \u2026"),re.error?h("span","ra-dst fail",` ${re.error}`):N(re.finishReason?` \xB7 ${re.finishReason}`:"")),K.append(Ee);for(let Re of B.filter(xt=>xt.turn===H))K.append(P([ge(Re.status),O(Re.name),N(Re.durationMs!==void 0?`${Math.round(Re.durationMs)}ms \xB7 ${lr(Re.startedAt)}`:lr(Re.startedAt))],()=>[h("div","ra-dmuted",Re.id),C(e.args),_(Re.args),...Re.result!==void 0?[C(e.result),_(Re.result)]:[]]))}I.push(K)}return I},ee=R=>R.requests.length?[...R.requests].reverse().map(I=>{let G=I.params,B=I.usage,j=h("span","ra-dbadge "+(I.error?"fail":I.durationMs===void 0?"":"ok"),I.error?"error":I.durationMs===void 0?"\u2026":I.finishReason??"ok");return P([j,O(G.model||"default"),N(`${G.messages?.length??0} msgs \xB7 ${G.tools?.length??0} tools${B?` \xB7 ${B.prompt_tokens??0}\u2192${B.completion_tokens??0} tok`:""}${B?.total_cost?` \xB7 $${B.total_cost.toFixed(4)}`:""}`),N(` ${I.durationMs!==void 0?`${Math.round(I.durationMs)}ms \xB7 `:""}${lr(I.at)}`)],()=>[C(e.dPayload),_(I.params,"tall"),...I.message!==void 0||I.error?[C(e.dResponse),_(I.error??I.message)]:[],...B?[_(B)]:[]])}):[te(e.dNoRequests)],de=R=>{let I=h("div","ra-dbar"),G=h("input","ra-field");G.type="text",G.placeholder=e.dFilter,G.value=d,G.addEventListener("input",()=>{d=G.value,we()});let B=h("button","ra-ib");B.type="button",B.innerHTML=U.trash(13),B.title=e.dClear,B.setAttribute("aria-label",e.dClear),B.addEventListener("click",()=>{R.events.length=0,R.spans.length=0,R.requests.length=0,R.runs.length=0,pe()}),I.append(G,B);let j=R.events.filter(K=>!d||K.name.includes(d)||K.detail.includes(d));return j.length?[I,...[...j].reverse().slice(0,300).map(K=>P([N(lr(K.at)),O(K.name),N(K.detail)],()=>[_(K.data)]))]:[I,te(e.dNoEvents)]},ve=R=>{let I=h("div","ra-dctx"),G=h("div","ra-dkv"),B=(re,Ee)=>{G.append(h("span","ra-dmuted",re),h("span","ra-dmono",Ee))},j=R.usage,K=R.messages;B("session",R.id),B("directory",R.workspace?.id??"\u2014"),B("model",R.settings.model??"(default)"),B("messages",`${K.filter(re=>re.role==="user").length} user \xB7 ${K.filter(re=>re.role==="assistant").length} assistant \xB7 ${K.filter(re=>re.role==="tool").length} tool`),B("usage",`${j.prompt_tokens} in \xB7 ${j.completion_tokens} out \xB7 ${j.calls} calls \xB7 $${j.total_cost.toFixed(4)}`);let ie=h("span","ra-dmono","\u2026");G.append(h("span","ra-dmuted","context"),ie),R.context().then(re=>{ie.textContent=`${re.used} / ${re.window} (${(re.used/re.window*100).toFixed(2)}%)`}).catch(()=>{ie.textContent="\u2014"});let H=_("\u2026","tall");return R.systemPrompt().then(re=>{H.textContent=re}).catch(re=>{H.textContent=String(re)}),I.append(G,C(e.dSystem),H,C(`${e.dMessages} (${K.length})`),_(K,"tall")),[I]},Oe=R=>R.tools.map(I=>P([O(I.name),N(I.destructive?" destructive":"")],()=>[h("div","ra-ddesc",I.description??""),_(I.parameters)]));function pe(){if(p=null,!a)return;if(A(),!o){M.replaceChildren();return}let R=t.get(o),I=M.scrollTop,G=document.activeElement?.classList.contains("ra-field")&&M.contains(document.activeElement),B=l==="calls"?J(R):l==="requests"?ee(R):l==="events"?de(R):l==="context"?ve(o):Oe(o);if(M.replaceChildren(...B),M.scrollTop=I,G){let j=M.querySelector(".ra-field");j?.focus(),j?.setSelectionRange(j.value.length,j.value.length)}}let we=()=>{if(!(!a||p)){if(l==="context"||l==="tools"||M.querySelector("details[open]")){A();return}p=setTimeout(pe,300)}},fe=R=>{if(t.has(R))return;let I={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set(R,I),s.set(R,R.on("*",(G,B)=>{let j=B??{},K=String(j.runId??"");if(G==="run_start"&&(I.runs.push(K),ps(I.runs,60)),G==="turn_start"&&I.turn.set(K,Number(j.turn)||1),G==="request"&&(I.requests.push({runId:K,turn:Number(j.turn),at:Date.now(),params:j.params}),ps(I.requests,vi.requests)),G==="response"){let ie=[...I.requests].reverse().find(H=>H.runId===K&&H.turn===Number(j.turn)&&H.durationMs===void 0);ie&&Object.assign(ie,{durationMs:j.durationMs,finishReason:j.finishReason,usage:j.usage,message:j.message,error:j.error})}if(G==="tool_start"&&(I.spans.push({id:String(j.id),name:String(j.name),args:j.args,status:"running",startedAt:Date.now(),runId:K,turn:I.turn.get(K)??1}),ps(I.spans,vi.spans)),G==="tool_end"){let ie=[...I.spans].reverse().find(H=>H.id===String(j.id));ie&&Object.assign(ie,{status:String(j.status),result:j.result,durationMs:j.durationMs})}if(!Ac.has(G)){let ie=G==="tool_start"||G==="tool_end"?String(j.name??""):G==="run_end"?String(j.reason??""):G==="response"?String(j.error??j.finishReason??""):"";I.events.push({at:Date.now(),name:G,detail:ie,data:G==="request"?{runId:K,turn:j.turn,model:j.params?.model}:B}),ps(I.events,vi.events)}R===o&&we()}))},Se=()=>{a=!0,u.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),pe()};function _e(){a&&(a=!1,u.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:u,get visible(){return a},open:Se,close:_e,toggle:()=>a?_e():Se(),setAgent(R){fe(R),o=R,a&&pe()},forget(R){s.get(R)?.(),s.delete(R),t.delete(R),o===R&&(o=null)},dispose(){for(let R of s.values())R();s.clear(),p&&clearTimeout(p),u.remove()}}}var wa=["bg","panel","subtle","muted","fg","fg-muted","border","accent","accent-fg","accent-subtle","accent-muted","user-bg","link","ok","red","red-subtle","warn-fg","warn-bg","warn-border","shadow","shadow-md"],ba=["font","mono"],Lc='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',Pc='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',us={claude:{light:{bg:"#faf9f5",panel:"#ffffff",subtle:"#f5f4ee",muted:"#f0eee6",fg:"#141413","fg-muted":"#73726c",border:"#e5e3da",accent:"#d97757","accent-fg":"#b85a3a","accent-subtle":"#f7e8e1","accent-muted":"#efcbbd","user-bg":"#f0eee6",link:"#2b6cb0",ok:"#3d8b5a",red:"#b53333","red-subtle":"#f9ebe9","warn-fg":"#a15c07","warn-bg":"#fdf6e7","warn-border":"#f0d9a8",shadow:"0 1px 2px rgba(31,30,29,.06)","shadow-md":"0 6px 20px rgba(31,30,29,.12),0 1px 3px rgba(31,30,29,.08)"},dark:{bg:"#262624",panel:"#30302e",subtle:"#2b2a28",muted:"#343432",fg:"#f5f4ee","fg-muted":"#a3a19a",border:"#3d3d3a",accent:"#d97757","accent-fg":"#e8957a","accent-subtle":"rgba(217,119,87,.14)","accent-muted":"rgba(217,119,87,.32)","user-bg":"#1f1e1d",link:"#7aaeea",ok:"#6bbf86",red:"#e57373","red-subtle":"rgba(229,115,115,.12)","warn-fg":"#f0b45c","warn-bg":"rgba(240,180,92,.08)","warn-border":"rgba(240,180,92,.28)",shadow:"0 1px 2px rgba(0,0,0,.3)","shadow-md":"0 6px 20px rgba(0,0,0,.45),0 1px 3px rgba(0,0,0,.3)"}},violet:{light:{bg:"#ffffff",panel:"#ffffff",subtle:"#fafafa",muted:"#f4f4f5",fg:"#09090b","fg-muted":"#52525b",border:"#e4e4e7",accent:"#9333ea","accent-fg":"#7e22ce","accent-subtle":"#f3e8ff","accent-muted":"#e9d5ff","user-bg":"#f3e8ff",link:"#7e22ce",ok:"#16a34a",red:"#dc2626","red-subtle":"#fef2f2"},dark:{bg:"#09090b",panel:"#09090b",subtle:"#101014",muted:"#18181b",fg:"#fafafa","fg-muted":"#a1a1aa",border:"#27272a",accent:"#9333ea","accent-fg":"#d8b4fe","accent-subtle":"#3b0764","accent-muted":"#581c87","user-bg":"#3b0764",link:"#d8b4fe",ok:"#4ade80",red:"#f87171","red-subtle":"#2a1215"}},slate:{light:{bg:"#ffffff",panel:"#ffffff",subtle:"#f9f9f9",muted:"#f3f3f3",fg:"#0d0d0d","fg-muted":"#5d5d5d",border:"#e5e5e5",accent:"#2563eb","accent-fg":"#1d4ed8","accent-subtle":"#eff4ff","accent-muted":"#c7d7fe","user-bg":"#f3f3f3",link:"#2563eb",ok:"#16a34a",red:"#dc2626","red-subtle":"#fef2f2"},dark:{bg:"#212121",panel:"#2a2a2a",subtle:"#262626",muted:"#303030",fg:"#ececec","fg-muted":"#a0a0a0",border:"#383838",accent:"#3b82f6","accent-fg":"#93b4fd","accent-subtle":"rgba(59,130,246,.15)","accent-muted":"rgba(59,130,246,.35)","user-bg":"#303030",link:"#7cacf8",ok:"#4ade80",red:"#f87171","red-subtle":"rgba(248,113,113,.12)"}},forest:{light:{bg:"#fbfcfa",panel:"#ffffff",subtle:"#f5f7f3",muted:"#eef2eb",fg:"#14201a","fg-muted":"#5f6b63",border:"#e1e7dd",accent:"#2f855a","accent-fg":"#276749","accent-subtle":"#e6f4ec","accent-muted":"#b9e0c9","user-bg":"#eef2eb",link:"#2b6cb0",ok:"#2f855a",red:"#c53030","red-subtle":"#fdecec"},dark:{bg:"#1a201c",panel:"#222a25",subtle:"#1e2520",muted:"#283029",fg:"#eef3ee","fg-muted":"#9aa79e",border:"#334037",accent:"#48bb78","accent-fg":"#7fd3a2","accent-subtle":"rgba(72,187,120,.14)","accent-muted":"rgba(72,187,120,.32)","user-bg":"#141a16",link:"#7aaeea",ok:"#68d391",red:"#fc8181","red-subtle":"rgba(252,129,129,.12)"}}},xn=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function xa(){let r=us.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${Lc};--ra-mono:${Pc};${xn(r.light)}}`,`:where(.ra-chat[data-scheme=dark], .ra-ui[data-scheme=dark]){${xn(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${xn(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(us))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${xn(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${xn(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${xn(t.dark)}}}`));return e.join(`
|
|
297
|
+
`;var Cc=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,Kt=r=>r.slice(r.lastIndexOf("/")+1),bi=r=>r.slice(0,r.lastIndexOf("/"))||"/";function Ec(r){let e={name:"",path:"/",folder:!0,children:[]},n=new Map([["/",e]]),t=o=>{let a=n.get(o);if(a)return a;let l=t(bi(o));return a={name:Kt(o),path:o,folder:!0,children:[]},l.children.push(a),n.set(o,a),a};for(let o of r)t(bi(o.path)).children.push({name:Kt(o.path),path:o.path,folder:!1,stat:o,children:[]});let s=o=>{o.children.sort((a,l)=>Number(l.folder)-Number(a.folder)||a.name.localeCompare(l.name)),o.children.forEach(s)};return s(e),e}async function xi(r,e,n){let t=e==="/"?"":e,s=n.lastIndexOf("."),o=s>0?n.slice(0,s):n,a=s>0?n.slice(s):"";for(let l=1;l<1e3;l++){let d=`${t}/${l===1?n:`${o}-${l}${a}`}`;if(!await r.exists(d))return d}return`${t}/${Date.now()}-${n}`}function ma(r){let{t:e,root:n,notify:t,editorHost:s}=r,o=null,a=!1,l=null,d=null,p=null,u=null,w="/",x=new Set(["/.agent"]),b=null,M=0,T=null,A=2*1024*1024,P=null,_=()=>{P||(P=setTimeout(()=>{P=null,$e()},150))},C=new Set,N=!1,O=h("div","ra-fp");O.setAttribute("role","complementary"),O.style.display="none";let te=h("div","ra-fph"),ge=h("span","ra-fpt",e.files),J=(S,q,oe)=>{let Y=h("button","ra-ib");return Y.type="button",Y.innerHTML=S,Y.title=q,Y.setAttribute("aria-label",q),Y.addEventListener("click",oe),Y},ee=h("input");ee.type="file",ee.multiple=!0,ee.style.display="none";let de=J(U.upload(),e.upload,()=>ee.click()),ve=J(U.download(),e.downloadZip,()=>{Xt("/")}),Oe=J(U.filePlus(14),e.newFile,()=>{pr()}),pe=J(U.refresh(),e.refresh,()=>{$e()}),we=J(U.x(14),e.close,()=>{Qe()});te.append(ge,h("span","ra-sp"),ve,de,Oe,pe,we);let fe=h("div","ra-tree"),Se=h("div","ra-ed");Se.style.display="none";let _e=h("div","ra-edh"),R=h("span","ra-edp"),I=h("span","ra-edro");I.innerHTML=U.lock(11)+`<span>${e.readOnly}</span>`,I.style.display="none";let G=h("div","ra-eda"),B=h("button","ra-btn xs solid");B.type="button",B.innerHTML=U.save()+e.save,B.style.display="none",B.addEventListener("click",()=>{An()});let H="__runapps_agent_files:wrap",K=(()=>{try{return localStorage.getItem(H)!=="0"}catch{return!0}})(),ie=!1,j=J(U.wrap(),e.wrap,()=>{K=!K;try{localStorage.setItem(H,K?"1":"0")}catch{}Re()}),re=J(U.eye(),e.preview,()=>{ie=!ie,Vt()}),Ee=h("div","ra-md ra-edmd");Ee.style.display="none",Ee.addEventListener("click",S=>{let q=S.target.closest("a[href]"),oe=q?.getAttribute("href")??"";if(!q||!oe.startsWith("/")||oe.startsWith("//")||!o)return;S.preventDefault();let Y=o;Y.exists(oe).then(ae=>{ae&&Y===o&&je(oe)})});let Re=()=>{ye.classList.toggle("ra-wrap",K),j.classList.toggle("on",K)},xt=S=>!!S&&/\.(md|markdown|mdx)$/i.test(S),Vt=()=>{let S=p!==null;re.style.display=S&&xt(l)?"":"none",(!S||!xt(l))&&(ie=!1),re.innerHTML=ie?U.pen():U.eye(),re.title=ie?e.edit:e.preview,re.setAttribute("aria-label",re.title),re.classList.toggle("on",ie),ie&&bn(Ee,d??ye.value,!1),Ee.style.display=ie?"":"none",ye.style.display=S&&!ie?"":"none"},Gt=J(U.download(),e.download,()=>{l&&Rt(l)}),Mn=J(U.trash(),e.delete,()=>{l&&$n(l)}),_t=J(U.x(14),e.close,()=>{En()});G.append(B,j,re,Gt,Mn,_t),_e.append(R,I,G);let dr=h("div","ra-edb"),ye=h("textarea","ra-edta");ye.spellcheck=!1,ye.setAttribute("aria-label",e.files);let Ae=h("div","ra-edpv");dr.append(ye,Ee,Ae),Re(),Se.append(_e,dr);let nt=h("div","ra-fpdrop",e.upload);O.append(te,fe,ee,nt),s.append(Se);let Ye=S=>{I.style.display=S?"":"none",Mn.style.display=Gt.style.display=S?"none":""},ft=S=>{d=S,B.style.display=S===null?"none":""};ye.addEventListener("input",()=>ft(ye.value===p?null:ye.value)),ye.addEventListener("keydown",S=>{if((S.metaKey||S.ctrlKey)&&S.key==="s"&&(S.preventDefault(),An()),S.key==="Tab"&&!S.shiftKey){S.preventDefault();let q=ye.selectionStart;ye.setRangeText(" ",q,ye.selectionEnd,"end"),ye.dispatchEvent(new Event("input"))}});let Zt=async()=>d===null||ut(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),Xe=(S,q)=>{if(!o)return!1;if(!q)return o.isReadOnly(S);let oe=(T??[]).filter(Y=>Y.path.startsWith(S+"/"));return oe.length>0&&oe.every(Y=>o.isReadOnly(Y.path))},Cn=()=>w!=="/"&&Xe(w,!0)?"/":w,ht=(S,q,oe,Y=!1)=>{for(let ae of S.children){let me=h("div","ra-fr"+(ae.path===l?" ra-cur":""));me.style.paddingLeft=`${q*14+6}px`,me.dataset.path=ae.path;let Ve=ae.folder&&!x.has(ae.path),ws=h("span","ra-frc");ws.innerHTML=ae.folder?Ve?U.chevDown():U.chev(12):"";let ur=h("span","ra-fri");ur.innerHTML=ae.folder?Ve?U.folderOpen():U.folder():U.file();let Dt=h("span","ra-frn",ae.name);if(Dt.title=ae.path,me.append(ws,ur,Dt),C.has(ae.path)){let Le=h("span","ra-dot");Le.title=e.changedByAgent,me.append(Le)}let Pn=Y||Xe(ae.path,ae.folder);if(Pn){if(me.classList.add("ra-ro"),me.title=`${ae.path} \xB7 ${e.readOnly}`,!Y){let Le=h("span","ra-frl");Le.innerHTML=U.lock(),Le.title=e.readOnly,me.append(Le)}}else{let Le=h("span","ra-fra");Le.append(ae.folder?J(U.download(13),e.downloadZip,()=>{Xt(ae.path)}):J(U.download(13),e.download,()=>{Rt(ae.path)})),Le.append(J(U.trash(12),e.delete,()=>{$n(ae.path)})),me.append(Le)}me.addEventListener("click",Le=>{Le.target.closest(".ra-fra")||(ae.folder?(w=ae.path,x.delete(ae.path)||x.add(ae.path),ze()):(w=bi(ae.path),je(ae.path)))}),oe.append(me),ae.folder&&Ve&&ht(ae,q+1,oe,Pn)}},ze=()=>{if(!T)return;let S=document.createDocumentFragment();T.length?ht(Ec(T),0,S):S.append(h("div","ra-fpe",e.noFiles)),fe.replaceChildren(S)},$e=async()=>{if(!o||!a||N)return;let S=++M,q=o;try{let oe=await q.list("/");if(S!==M||q!==o||N)return;T=oe,ze()}catch(oe){if(S!==M||N)return;fe.replaceChildren(h("div","ra-fpe",oe.message))}},Be=S=>{Se.style.display=S?"":"none",n.classList.toggle("ra-editing",S)},je=async S=>{if(o&&!(S!==l&&!await Zt())){l=S,C.delete(S),ft(null),R.textContent=S,u&&(URL.revokeObjectURL(u),u=null),Ae.replaceChildren(),Be(!0);try{let q=await o.read(S);if(l!==S)return;let oe=Cc.test(S)||/^image\//.test(q.contentType??""),Y=null;if(!oe)if(typeof q.data=="string")Y=q.data;else try{Y=new TextDecoder("utf-8",{fatal:!0}).decode(q.data)}catch{Y=null}if(/\.pdf$/i.test(S)||q.contentType==="application/pdf"){p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",u=URL.createObjectURL(new Blob([q.data],{type:"application/pdf"}));let me=h("iframe","ra-edpdf");me.src=u,me.title=Kt(S),j.style.display="none",Ae.replaceChildren(me),Ye(o.isReadOnly(S)),ze();return}j.style.display="",Y!==null&&q.size>A&&(Y=null);let ae=o.isReadOnly(S);if(Ye(ae),Y!==null)p=Y,ye.value=Y,Ae.style.display="none",ye.readOnly=ae,ye.title=ae?e.readOnly:"",Vt();else{if(p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",oe){let me=new Blob([q.data],{type:q.contentType||"image/*"});u=URL.createObjectURL(me);let Ve=h("img");Ve.src=u,Ve.alt=Kt(S),Ae.append(Ve)}else Ae.append(h("div","ra-fpe",q.size>A&&!oe?e.tooBig:e.noPreview));Ae.append(h("div","ra-fpe",`${q.size} B`))}}catch(q){p=null,ye.style.display="none",Ee.style.display="none",re.style.display="none",Ae.style.display="",Ae.replaceChildren(h("div","ra-fpe",q.message))}ze()}},En=async()=>l?await Zt()?(l=null,p=null,ft(null),u&&(URL.revokeObjectURL(u),u=null),Be(!1),await $e(),!0):!1:!0,An=async()=>{if(!o||!l||d===null)return;let S=l,q=d,oe=o;try{let Y=await oe.readText(S).catch(()=>null);if(Y!==null&&p!==null&&Y!==p&&!await ut(n,e.conflict,S,{ok:e.save,cancel:e.cancel,danger:!0})||(await oe.write(S,q),l!==S||oe!==o))return;p=q,ft(ye.value===q?null:ye.value),t(`${e.saved}: ${S}`),r.onChange?.()}catch(Y){t(Y.message,"error")}},Rt=async S=>{if(o)try{let q=await o.read(S);or(Kt(S),q.data,q.contentType)}catch(q){t(q.message,"error")}},Xt=async S=>{if(o)try{let q=S==="/"?"/":S+"/",oe=(await o.list(S)).filter(me=>me.path.startsWith(q));if(!oe.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${oe.length}\u2026`);let Y=[];for(let me of oe){let Ve=await o.read(me.path);Y.push({path:me.path.slice(q.length),data:Ve.data,mtime:me.mtime})}let ae=await Vr(Y);or(`${S==="/"?o.id||"directory":Kt(S)}.zip`,ae,"application/zip")}catch(q){t(q.message,"error")}},$n=async S=>{if(!o||!await ut(n,e.delete,e.confirmDeleteFile.replace("{path}",S),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let q=[];try{let oe=await o.isFolder(S)?(await o.list(S)).map(Y=>Y.path).filter(Y=>Y!==S):[S];for(let Y of oe){if(o.isReadOnly(Y)){q.push(Y);continue}try{await o.delete(Y)}catch{q.push(Y)}}}catch(oe){t(oe.message,"error")}l&&(l===S||l.startsWith(S+"/"))&&!await o.exists(l)&&(l=null,p=null,ft(null),Be(!1)),q.length&&t(`${e.readOnly}: ${q.slice(0,3).join(", ")}${q.length>3?` +${q.length-3}`:""}`,"warning"),r.onChange?.(),await $e()},pr=async()=>{if(!o)return;let S=Cn(),q=S==="/"?"/":S+"/",oe=await ha(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${q}untitled.md`});if(!oe)return;let Y="/"+oe.replace(/^\/+/,"");try{await o.exists(Y)||await o.write(Y,""),r.onChange?.(),await $e(),await je(Y),ye.focus()}catch(ae){t(ae.message,"error")}},vt=async S=>{if(!o||!S?.length)return;let q=null;for(let oe of Array.from(S))try{let Y=await xi(o,Cn(),Kt(oe.name.replace(/\\/g,"/"))||"file");await o.write(Y,new Uint8Array(await oe.arrayBuffer()),oe.type||void 0),q=Y}catch(Y){t(Y.message,"error")}r.onChange?.(),await $e(),q&&S.length===1&&await je(q)};ee.addEventListener("change",()=>{let S=Array.from(ee.files??[]);ee.value="",vt(S)});let Ke=0;O.addEventListener("dragenter",S=>{S.dataTransfer?.types.includes("Files")&&(S.preventDefault(),S.stopPropagation(),Ke++,O.dataset.drop="1")}),O.addEventListener("dragover",S=>{O.dataset.drop&&(S.preventDefault(),S.stopPropagation(),S.dataTransfer.dropEffect="copy")}),O.addEventListener("dragleave",S=>{O.dataset.drop&&(S.stopPropagation(),--Ke<=0&&(Ke=0,delete O.dataset.drop))}),O.addEventListener("drop",S=>{O.dataset.drop&&(S.preventDefault(),S.stopPropagation(),Ke=0,delete O.dataset.drop,vt(S.dataTransfer?.files))});let Ln=async S=>{a=!0,O.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await $e(),S&&await je(S)},Qe=async()=>{await En()&&(a=!1,O.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:O,get visible(){return a},open:Ln,close:Qe,toggle:()=>a?Qe():Ln(),setWorkspace(S){if(S!==o){if(o&&l&&d!==null){let[q,oe,Y]=[o,l,d];q.write(oe,Y).then(()=>t(`${e.autoSaved}: ${oe}`),ae=>t(ae.message,"error"))}b?.(),b=null,o=S,S&&(b=S.onChange(q=>{a&&(_(),!(q.path!==l||d!==null)&&(q.kind==="write"?je(q.path):(l=null,p=null,Be(!1))))})),u&&(URL.revokeObjectURL(u),u=null),T=null,l=null,p=null,ft(null),Be(!1),C.clear(),w="/",S?$e():(a=!1,O.style.display="none",n.classList.remove("ra-files-open"))}},refresh:$e,changed(S){C.add(S),ze()},download:Rt,downloadFolder:Xt,dispose(){N=!0,b?.(),P&&clearTimeout(P),u&&URL.revokeObjectURL(u),O.remove(),Se.remove(),n.classList.remove("ra-editing")}}}var vi={spans:400,requests:120,events:600},Ac=new Set(["text_delta","reasoning_delta","tool_update"]);function lr(r){let e=new Date(r);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}function $c(r){try{return JSON.stringify(r,null,2)??"undefined"}catch{return String(r)}}var ps=(r,e)=>{r.length>e&&r.splice(0,r.length-e)};function ya(r){let{t:e,root:n}=r,t=new WeakMap,s=new Map,o=null,a=!1,l="calls",d="",p=null,u=h("div","ra-fp ra-dp");u.setAttribute("role","complementary"),u.style.display="none";let w=h("div","ra-fph"),x=h("div","ra-dtabs"),b=h("button","ra-ib");b.type="button",b.innerHTML=U.x(14),b.title=e.close,b.setAttribute("aria-label",e.close),b.addEventListener("click",()=>_e()),w.append(x,h("span","ra-sp"),b);let M=h("div","ra-dbody");u.append(w,M);let T=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],A=()=>{let R=o?t.get(o):void 0,I={calls:R?.spans.length??0,requests:R?.requests.length??0};x.replaceChildren(...T.map(([G,B])=>{let H=h("button","ra-dtab"+(G===l?" on":""));return H.type="button",H.append(B),I[G]&&H.append(h("span","ra-dcount",String(I[G]))),H.addEventListener("click",()=>{l=G,pe()}),H}))},P=(R,I)=>{let G=h("details","ra-dfold"),B=h("summary"),H=h("span","ra-chev");H.innerHTML=U.chev(12),B.append(H,...R),G.append(B);let K=!1;return G.addEventListener("toggle",()=>{if(G.open&&!K){K=!0;let ie=h("div","ra-dfb");ie.append(...I()),G.append(ie)}}),G},_=(R,I="")=>{let G=h("pre","ra-dpre "+I);return G.textContent=typeof R=="string"?R:$c(R),G},C=R=>h("div","ra-dlabel",R),N=R=>h("span","ra-dmuted",R),O=R=>h("span","ra-dmono",R),te=R=>h("div","ra-fpe",R),ge=R=>{let I=h("span","ra-dst "+(R==="running"?"run":R==="ok"?"ok":"fail"));return R==="running"?I.append(h("span","ra-spin")):I.innerHTML=R==="ok"?U.check(13):U.xcircle(13),I},J=R=>{if(!R.spans.length)return[te(e.dNoCalls)];let I=[];for(let G of[...R.runs].reverse()){let B=R.spans.filter(j=>j.runId===G),H=R.requests.filter(j=>j.runId===G);if(!B.length&&!H.length)continue;let K=h("div","ra-drun");K.append(h("div","ra-drh",`${e.dRun} ${lr(H[0]?.at??B[0]?.startedAt??Date.now())} \xB7 ${G.slice(-4)}`));let ie=[...new Set([...H.map(j=>j.turn),...B.map(j=>j.turn)])].sort((j,re)=>j-re);for(let j of ie){let re=H.find(Re=>Re.turn===j),Ee=h("div","ra-dturn");Ee.append(N(e.dTurn.replace("{n}",String(j)))),re&&Ee.append(O(` \xB7 ${re.params.model||"default"}`),N(re.durationMs!==void 0?` \xB7 ${Math.round(re.durationMs)}ms`:" \xB7 \u2026"),re.error?h("span","ra-dst fail",` ${re.error}`):N(re.finishReason?` \xB7 ${re.finishReason}`:"")),K.append(Ee);for(let Re of B.filter(xt=>xt.turn===j))K.append(P([ge(Re.status),O(Re.name),N(Re.durationMs!==void 0?`${Math.round(Re.durationMs)}ms \xB7 ${lr(Re.startedAt)}`:lr(Re.startedAt))],()=>[h("div","ra-dmuted",Re.id),C(e.args),_(Re.args),...Re.result!==void 0?[C(e.result),_(Re.result)]:[]]))}I.push(K)}return I},ee=R=>R.requests.length?[...R.requests].reverse().map(I=>{let G=I.params,B=I.usage,H=h("span","ra-dbadge "+(I.error?"fail":I.durationMs===void 0?"":"ok"),I.error?"error":I.durationMs===void 0?"\u2026":I.finishReason??"ok");return P([H,O(G.model||"default"),N(`${G.messages?.length??0} msgs \xB7 ${G.tools?.length??0} tools${B?` \xB7 ${B.prompt_tokens??0}\u2192${B.completion_tokens??0} tok`:""}${B?.total_cost?` \xB7 $${B.total_cost.toFixed(4)}`:""}`),N(` ${I.durationMs!==void 0?`${Math.round(I.durationMs)}ms \xB7 `:""}${lr(I.at)}`)],()=>[C(e.dPayload),_(I.params,"tall"),...I.message!==void 0||I.error?[C(e.dResponse),_(I.error??I.message)]:[],...B?[_(B)]:[]])}):[te(e.dNoRequests)],de=R=>{let I=h("div","ra-dbar"),G=h("input","ra-field");G.type="text",G.placeholder=e.dFilter,G.value=d,G.addEventListener("input",()=>{d=G.value,we()});let B=h("button","ra-ib");B.type="button",B.innerHTML=U.trash(13),B.title=e.dClear,B.setAttribute("aria-label",e.dClear),B.addEventListener("click",()=>{R.events.length=0,R.spans.length=0,R.requests.length=0,R.runs.length=0,pe()}),I.append(G,B);let H=R.events.filter(K=>!d||K.name.includes(d)||K.detail.includes(d));return H.length?[I,...[...H].reverse().slice(0,300).map(K=>P([N(lr(K.at)),O(K.name),N(K.detail)],()=>[_(K.data)]))]:[I,te(e.dNoEvents)]},ve=R=>{let I=h("div","ra-dctx"),G=h("div","ra-dkv"),B=(re,Ee)=>{G.append(h("span","ra-dmuted",re),h("span","ra-dmono",Ee))},H=R.usage,K=R.messages;B("session",R.id),B("directory",R.workspace?.id??"\u2014"),B("model",R.settings.model??"(default)"),B("messages",`${K.filter(re=>re.role==="user").length} user \xB7 ${K.filter(re=>re.role==="assistant").length} assistant \xB7 ${K.filter(re=>re.role==="tool").length} tool`),B("usage",`${H.prompt_tokens} in \xB7 ${H.completion_tokens} out \xB7 ${H.calls} calls \xB7 $${H.total_cost.toFixed(4)}`);let ie=h("span","ra-dmono","\u2026");G.append(h("span","ra-dmuted","context"),ie),R.context().then(re=>{ie.textContent=`${re.used} / ${re.window} (${(re.used/re.window*100).toFixed(2)}%)`}).catch(()=>{ie.textContent="\u2014"});let j=_("\u2026","tall");return R.systemPrompt().then(re=>{j.textContent=re}).catch(re=>{j.textContent=String(re)}),I.append(G,C(e.dSystem),j,C(`${e.dMessages} (${K.length})`),_(K,"tall")),[I]},Oe=R=>R.tools.map(I=>P([O(I.name),N(I.destructive?" destructive":"")],()=>[h("div","ra-ddesc",I.description??""),_(I.parameters)]));function pe(){if(p=null,!a)return;if(A(),!o){M.replaceChildren();return}let R=t.get(o),I=M.scrollTop,G=document.activeElement?.classList.contains("ra-field")&&M.contains(document.activeElement),B=l==="calls"?J(R):l==="requests"?ee(R):l==="events"?de(R):l==="context"?ve(o):Oe(o);if(M.replaceChildren(...B),M.scrollTop=I,G){let H=M.querySelector(".ra-field");H?.focus(),H?.setSelectionRange(H.value.length,H.value.length)}}let we=()=>{if(!(!a||p)){if(l==="context"||l==="tools"||M.querySelector("details[open]")){A();return}p=setTimeout(pe,300)}},fe=R=>{if(t.has(R))return;let I={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set(R,I),s.set(R,R.on("*",(G,B)=>{let H=B??{},K=String(H.runId??"");if(G==="run_start"&&(I.runs.push(K),ps(I.runs,60)),G==="turn_start"&&I.turn.set(K,Number(H.turn)||1),G==="request"&&(I.requests.push({runId:K,turn:Number(H.turn),at:Date.now(),params:H.params}),ps(I.requests,vi.requests)),G==="response"){let ie=[...I.requests].reverse().find(j=>j.runId===K&&j.turn===Number(H.turn)&&j.durationMs===void 0);ie&&Object.assign(ie,{durationMs:H.durationMs,finishReason:H.finishReason,usage:H.usage,message:H.message,error:H.error})}if(G==="tool_start"&&(I.spans.push({id:String(H.id),name:String(H.name),args:H.args,status:"running",startedAt:Date.now(),runId:K,turn:I.turn.get(K)??1}),ps(I.spans,vi.spans)),G==="tool_end"){let ie=[...I.spans].reverse().find(j=>j.id===String(H.id));ie&&Object.assign(ie,{status:String(H.status),result:H.result,durationMs:H.durationMs})}if(!Ac.has(G)){let ie=G==="tool_start"||G==="tool_end"?String(H.name??""):G==="run_end"?String(H.reason??""):G==="response"?String(H.error??H.finishReason??""):"";I.events.push({at:Date.now(),name:G,detail:ie,data:G==="request"?{runId:K,turn:H.turn,model:H.params?.model}:B}),ps(I.events,vi.events)}R===o&&we()}))},Se=()=>{a=!0,u.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),pe()};function _e(){a&&(a=!1,u.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:u,get visible(){return a},open:Se,close:_e,toggle:()=>a?_e():Se(),setAgent(R){fe(R),o=R,a&&pe()},forget(R){s.get(R)?.(),s.delete(R),t.delete(R),o===R&&(o=null)},dispose(){for(let R of s.values())R();s.clear(),p&&clearTimeout(p),u.remove()}}}var wa=["bg","panel","subtle","muted","fg","fg-muted","border","accent","accent-fg","accent-subtle","accent-muted","user-bg","link","ok","red","red-subtle","warn-fg","warn-bg","warn-border","shadow","shadow-md"],ba=["font","mono"],Lc='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',Pc='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',us={claude:{light:{bg:"#faf9f5",panel:"#ffffff",subtle:"#f5f4ee",muted:"#f0eee6",fg:"#141413","fg-muted":"#73726c",border:"#e5e3da",accent:"#d97757","accent-fg":"#b85a3a","accent-subtle":"#f7e8e1","accent-muted":"#efcbbd","user-bg":"#f0eee6",link:"#2b6cb0",ok:"#3d8b5a",red:"#b53333","red-subtle":"#f9ebe9","warn-fg":"#a15c07","warn-bg":"#fdf6e7","warn-border":"#f0d9a8",shadow:"0 1px 2px rgba(31,30,29,.06)","shadow-md":"0 6px 20px rgba(31,30,29,.12),0 1px 3px rgba(31,30,29,.08)"},dark:{bg:"#262624",panel:"#30302e",subtle:"#2b2a28",muted:"#343432",fg:"#f5f4ee","fg-muted":"#a3a19a",border:"#3d3d3a",accent:"#d97757","accent-fg":"#e8957a","accent-subtle":"rgba(217,119,87,.14)","accent-muted":"rgba(217,119,87,.32)","user-bg":"#1f1e1d",link:"#7aaeea",ok:"#6bbf86",red:"#e57373","red-subtle":"rgba(229,115,115,.12)","warn-fg":"#f0b45c","warn-bg":"rgba(240,180,92,.08)","warn-border":"rgba(240,180,92,.28)",shadow:"0 1px 2px rgba(0,0,0,.3)","shadow-md":"0 6px 20px rgba(0,0,0,.45),0 1px 3px rgba(0,0,0,.3)"}},violet:{light:{bg:"#ffffff",panel:"#ffffff",subtle:"#fafafa",muted:"#f4f4f5",fg:"#09090b","fg-muted":"#52525b",border:"#e4e4e7",accent:"#9333ea","accent-fg":"#7e22ce","accent-subtle":"#f3e8ff","accent-muted":"#e9d5ff","user-bg":"#f3e8ff",link:"#7e22ce",ok:"#16a34a",red:"#dc2626","red-subtle":"#fef2f2"},dark:{bg:"#09090b",panel:"#09090b",subtle:"#101014",muted:"#18181b",fg:"#fafafa","fg-muted":"#a1a1aa",border:"#27272a",accent:"#9333ea","accent-fg":"#d8b4fe","accent-subtle":"#3b0764","accent-muted":"#581c87","user-bg":"#3b0764",link:"#d8b4fe",ok:"#4ade80",red:"#f87171","red-subtle":"#2a1215"}},slate:{light:{bg:"#ffffff",panel:"#ffffff",subtle:"#f9f9f9",muted:"#f3f3f3",fg:"#0d0d0d","fg-muted":"#5d5d5d",border:"#e5e5e5",accent:"#2563eb","accent-fg":"#1d4ed8","accent-subtle":"#eff4ff","accent-muted":"#c7d7fe","user-bg":"#f3f3f3",link:"#2563eb",ok:"#16a34a",red:"#dc2626","red-subtle":"#fef2f2"},dark:{bg:"#212121",panel:"#2a2a2a",subtle:"#262626",muted:"#303030",fg:"#ececec","fg-muted":"#a0a0a0",border:"#383838",accent:"#3b82f6","accent-fg":"#93b4fd","accent-subtle":"rgba(59,130,246,.15)","accent-muted":"rgba(59,130,246,.35)","user-bg":"#303030",link:"#7cacf8",ok:"#4ade80",red:"#f87171","red-subtle":"rgba(248,113,113,.12)"}},forest:{light:{bg:"#fbfcfa",panel:"#ffffff",subtle:"#f5f7f3",muted:"#eef2eb",fg:"#14201a","fg-muted":"#5f6b63",border:"#e1e7dd",accent:"#2f855a","accent-fg":"#276749","accent-subtle":"#e6f4ec","accent-muted":"#b9e0c9","user-bg":"#eef2eb",link:"#2b6cb0",ok:"#2f855a",red:"#c53030","red-subtle":"#fdecec"},dark:{bg:"#1a201c",panel:"#222a25",subtle:"#1e2520",muted:"#283029",fg:"#eef3ee","fg-muted":"#9aa79e",border:"#334037",accent:"#48bb78","accent-fg":"#7fd3a2","accent-subtle":"rgba(72,187,120,.14)","accent-muted":"rgba(72,187,120,.32)","user-bg":"#141a16",link:"#7aaeea",ok:"#68d391",red:"#fc8181","red-subtle":"rgba(252,129,129,.12)"}}},xn=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function xa(){let r=us.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${Lc};--ra-mono:${Pc};${xn(r.light)}}`,`:where(.ra-chat[data-scheme=dark], .ra-ui[data-scheme=dark]){${xn(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${xn(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(us))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${xn(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${xn(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${xn(t.dark)}}}`));return e.join(`
|
|
298
298
|
`)}var va=r=>r.startsWith("--")?r:`--ra-${r}`;var _c={en:{assistant:"Assistant",placeholder:"Ask the agent to do something\u2026 type / for commands",placeholderBusy:"\u21B5 to steer the current task, {mod}\u21B5 to queue for later",send:"Send",stop:"Stop",steer:"Steer",followUp:"Follow-up",steerTip:"Insert into the current task",followUpTip:"Queue after the current task",usageLine:"{cost} \xB7 {tokens} tokens \xB7 {calls} calls",uCost:"Cost",uIn:"Input",uOut:"Output",uCalls:"Calls",uOf:"{used} of {window} tokens",compactNow:"Compact now",emptyResult:"(empty)",queued:"Queued messages",queuedN:"{n} message queued",queuedNs:"{n} messages queued",queueNext:"Next:",sendNow:"Send now (insert into the current task)",editQueued:"Edit",expand:"Show all",collapse:"Collapse",clear:"Clear queue",thinking:"Thinking\u2026",thought:"Thought process",enter:"to send",newline:"new line",hintIdle:"\u21B5 {enter} \xB7 \u21E7\u21B5 {newline}",hintNext:"Tab to use the suggestion \xB7 \u21B5 {enter}",hintBusy:"\u21B5 steer \xB7 {mod}\u21B5 follow-up \xB7 \u21E7\u21B5 {newline}",empty:"Start a conversation",history:"Chats",newChat:"New chat",clearChat:"Clear",confirmClear:"Clear this conversation? Its messages are removed; the files stay.",noSessions:"No other conversations yet",notSaved:"not saved yet",compacted:"Context compacted",trimmed:"Earlier conversation trimmed to fit the context",allow:"Allow",decline:"Decline",cancel:"Cancel",submit:"Submit",ok:"OK",other:"Other\u2026",typeAnswer:"Type your answer",args:"Arguments",result:"Result",error:"Error",declined:"declined",blocked:"blocked",skipped:"skipped",open:"Open in editor",stopped:"Stopped.",maxTurns:"Paused at the turn limit ({n})",retry:"Retry",messages:"messages",skill:"Skill",template:"Template",delete:"Delete",deleteAll:"Delete all",confirmDelete:"Delete this conversation and its files?",confirmDeleteAll:"Delete every conversation, this one included, and their files?",untitled:"New conversation",attach:"Attach files",drop:"Drop files to attach",tooLarge:"is too large (max 20 MB)",remove:"Remove",toolsRunning:"Running",toolsDone:"Ran {n} tool calls",toolsDone1:"Ran 1 tool call",toolsFailed:"{n} failed",actRead:"read {n} file(s)",actList:"listed {n} folder(s)",actSearch:"searched {n} time(s)",actWrite:"wrote {n} file(s)",actEdit:"edited {n} file(s)",actDelete:"deleted {n} file(s)",actRun:"ran {n} snippet(s)",actAsk:"asked you {n} time(s)",actOther:"used {name}",ingRead:"Reading",ingList:"Listing",ingSearch:"Searching",ingWrite:"Writing",ingEdit:"Editing",ingDelete:"Deleting",ingRun:"Running code",ingAsk:"Asking you",ingOther:"Running",current:"Current",jumpEnd:"Jump to the latest",sTabModel:"Model",debug:"Debug",dCalls:"Calls",dRequests:"Requests",dEvents:"Events",dContext:"Context",dTools:"Tools",dClear:"Clear the record",dFilter:"Filter by type",dNoCalls:"No tool calls yet.",dNoRequests:"No model requests yet. Each call to the model is listed here with what was sent and what came back.",dNoEvents:"No events yet.",dSystem:"System prompt",dMessages:"Messages sent to the model",dPayload:"Request",dResponse:"Response",dRun:"Run",dTurn:"Turn {n}",sent:"sent",justNow:"Just now",minutesAgo:"{n} min ago",hoursAgo:"{n} h ago",context:"context",copy:"Copy",copied:"Copied",rewind:"Rewind to here",rewindTitle:"Rewind to this message",regen:"Answer again",regenTitle:"Answer this question again",regenMsg:"This answer and what follows are dropped and the question is sent again.",delTurn:"Delete",delTurnTitle:"Delete this question and its answer?",delTurnMsg:"They are removed from the conversation; files stay as they are.",replyCost:"Cost: {cost}",replyUsage:"{in} in \xB7 {out} out \xB7 {calls} calls",rewindMsg:"The conversation after it is dropped and the message goes back into the composer.",rewindFiles:"Also restore the directory's files to that moment",rewindGone:"This message is no longer in the conversation.",rewindSnapshot:"{n} files ({size}) as they were at {time}",rewindPartial:"Files over 2 MB were not in the snapshot and stay as they are.",rewindGoneFile:"{path} is no longer in the directory.",running:"running",waitingAnswer:"waiting for your answer",finished:"finished",bgLimit:"{n} conversations are already running in the background; stop one before switching away from this one.",settings:"Settings",sVision:"sees pictures",sVisionYes:"sees pictures",sVisionNo:"text only",noVision:"{model} cannot see pictures: they are saved as files, but the model will not see what is in them.",sEffort:"Thinking",sEffortDefault:"Model default",sEffortNone:"this model does not expose a thinking level",sModel:"Model",sDefault:"Platform default",sMaxTurns:"Max turns per run",sMaxTokens:"Max output per reply",sPrice:"Price",sPriceLine:"input {in} \xB7 output {out} per M tokens",sPerCall:"{amount} per call",sAuto:"Model's maximum",sCustomN:"Set a number",filter:"Filter\u2026",sPerms:"Tool permissions",sAsk:"Ask before destructive tools",sAutoPerm:"Allow everything",sCustom:"Decided by the app",apply:"Apply",reset:"Reset to the app's defaults",applied:"Settings applied",continueRun:"Continue",maxTurnsHint:"Raise the limit in Settings, or continue from here.",files:"Files",downloadZip:"Download as zip",zipping:"Zipping",wrap:"Word wrap",preview:"Preview Markdown",edit:"Edit",tooBig:"Too large to edit here; download it.",conflict:"The file changed since you opened it. Overwrite it?",readOnly:"Read-only",autoSaved:"Unsaved edits saved",upload:"Upload",newFile:"New file",refresh:"Refresh",close:"Close",save:"Save",download:"Download",confirmDeleteFile:"Delete {path}?",newFilePath:"Path of the new file",noPreview:"No preview for this file; download it.",changedByAgent:"changed by the agent",noFiles:"The directory is empty.",discard:"Discard unsaved changes?",saved:"Saved",skills:"Skills",uploadZip:"Upload zip",noSkills:"No skills yet. Upload a zip: SKILL.md at its root, or one folder per skill.",useSkill:"Use it: puts /skill:name in the composer",skillFolder:"folder",manualOnly:"manual only",skillsInstalled:"Installed: {names}",skillRemoved:"Removed {name}",notZip:"not a zip file",confirmDeleteZip:"Delete {zip}? All of its skills go: {names}. No conversation will have them any more.",confirmDeleteSkill:"Delete the skill {name} ({path})? No conversation will have it any more.",skillsHint:"Built-in skills come with the app and cannot be removed. Your skills \u2014 zips you upload and skills the agent writes \u2014 are kept in {user} and shared by every conversation. {dir} is generated from both when the agent loads, read-only. Drop a zip here to install it.",skillsHintNoUser:"These skills come with the app. {dir} is generated from them when the agent loads, read-only.",waiting:"Thinking",compactingNow:"Compacting the context",builtinSkill:"built-in",today:"Today",yesterday:"Yesterday",worked:"Worked for {t}",workedNoTime:"Work",sec:"{s}s",minSec:"{m}m {s}s",hourMin:"{h}h {m}m",command:"Command",user:"User",compacting:"Compacting the context\u2026",nothingToCompact:"Nothing to compact yet",busyCmd:"Wait for the current task to finish, or stop it, first",nothingToExport:"Nothing to export yet",nothingToContinue:"Nothing to continue",unknownModel:'No model named "{name}"',modelSet:"Model: {name}",effortSet:"Thinking: {name}",effortLevels:"Thinking levels of {model}: {levels}",unknownEffort:'"{name}" is not a thinking level of {model} ({levels})',debugOff:"Debug mode is off",cmdsTitle:"Commands",cmdsMore:"Templates (/name) and skills (/skill:name) are listed as you type.",autoCompact:"Auto-compaction",autoCompactAt:"when less than {n} tokens are left",directory:"Directory",messagesLabel:"Messages",cmdArgs:{compact:"[focus]",model:"[name]",effort:"[level]"},cmd:{help:"Show these commands",new:"Start a new conversation",resume:"Open a saved conversation",compact:"Summarise older turns now; add what the summary must keep",continue:"Continue the last run",model:"Switch model; no name opens the settings",effort:"Set the thinking level",context:"Context use, model and spending",export:"Download the conversation as Markdown",files:"Open the file manager",settings:"Open the settings",debug:"Show or hide the debug panel"}},zh:{assistant:"\u52A9\u624B",placeholder:"\u8BA9 agent \u505A\u70B9\u4EC0\u4E48\u2026 \u8F93\u5165 / \u67E5\u770B\u547D\u4EE4",placeholderBusy:"\u21B5 \u63D2\u5165\u5F53\u524D\u4EFB\u52A1\uFF0C{mod}\u21B5 \u6392\u961F\u5230\u4E4B\u540E",send:"\u53D1\u9001",stop:"\u505C\u6B62",steer:"\u63D2\u5165",followUp:"\u6392\u961F",steerTip:"\u63D2\u5165\u5230\u5F53\u524D\u4EFB\u52A1\uFF0C\u4E0B\u4E00\u6B65\u5C31\u4F1A\u770B\u5230",followUpTip:"\u6392\u5230\u5F53\u524D\u4EFB\u52A1\u7ED3\u675F\u4E4B\u540E",usageLine:"{cost} \xB7 {tokens} tokens \xB7 {calls} \u6B21\u8C03\u7528",uCost:"\u82B1\u8D39",uIn:"\u8F93\u5165",uOut:"\u8F93\u51FA",uCalls:"\u8C03\u7528",uOf:"{used} / {window} tokens",compactNow:"\u7ACB\u5373\u538B\u7F29",emptyResult:"\uFF08\u7A7A\uFF09",queued:"\u6392\u961F\u4E2D\u7684\u6D88\u606F",queuedN:"{n} \u6761\u6D88\u606F\u6392\u961F\u4E2D",queuedNs:"{n} \u6761\u6D88\u606F\u6392\u961F\u4E2D",queueNext:"\u4E0B\u4E00\u6761\uFF1A",sendNow:"\u7ACB\u5373\u53D1\u9001\uFF08\u63D2\u5165\u5F53\u524D\u4EFB\u52A1\uFF09",editQueued:"\u7F16\u8F91",expand:"\u5C55\u5F00",collapse:"\u6536\u8D77",clear:"\u6E05\u7A7A\u961F\u5217",thinking:"\u601D\u8003\u4E2D\u2026",thought:"\u601D\u8003\u8FC7\u7A0B",enter:"\u53D1\u9001",newline:"\u6362\u884C",hintIdle:"\u21B5 {enter} \xB7 \u21E7\u21B5 {newline}",hintNext:"Tab \u4F7F\u7528\u5EFA\u8BAE \xB7 \u21B5 {enter}",hintBusy:"\u21B5 \u63D2\u5165 \xB7 {mod}\u21B5 \u6392\u961F \xB7 \u21E7\u21B5 {newline}",empty:"\u5F00\u59CB\u5BF9\u8BDD",history:"\u4F1A\u8BDD",newChat:"\u65B0\u5BF9\u8BDD",clearChat:"\u6E05\u9664",confirmClear:"\u6E05\u9664\u8FD9\u6B21\u5BF9\u8BDD\uFF1F\u6D88\u606F\u4F1A\u88AB\u5220\u9664\uFF0C\u6587\u4EF6\u4FDD\u7559\u3002",noSessions:"\u8FD8\u6CA1\u6709\u5176\u5B83\u5BF9\u8BDD",notSaved:"\u5C1A\u672A\u4FDD\u5B58",compacted:"\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29",trimmed:"\u8F83\u65E9\u7684\u5BF9\u8BDD\u5DF2\u88C1\u526A\u4EE5\u9002\u5E94\u4E0A\u4E0B\u6587",allow:"\u5141\u8BB8",decline:"\u62D2\u7EDD",cancel:"\u53D6\u6D88",submit:"\u63D0\u4EA4",ok:"\u786E\u5B9A",other:"\u5176\u4ED6\u2026",typeAnswer:"\u8BF7\u8F93\u5165",args:"\u53C2\u6570",result:"\u7ED3\u679C",error:"\u9519\u8BEF",declined:"\u5DF2\u62D2\u7EDD",blocked:"\u5DF2\u62E6\u622A",skipped:"\u5DF2\u8DF3\u8FC7",open:"\u5728\u7F16\u8F91\u5668\u4E2D\u6253\u5F00",stopped:"\u5DF2\u505C\u6B62\u3002",maxTurns:"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6570 {n}\uFF0C\u6682\u505C",retry:"\u91CD\u8BD5",messages:"\u6761\u6D88\u606F",skill:"Skill",template:"\u6A21\u677F",delete:"\u5220\u9664",deleteAll:"\u5168\u90E8\u5220\u9664",confirmDelete:"\u5220\u9664\u8FD9\u4E2A\u5BF9\u8BDD\u548C\u5B83\u7684\u6587\u4EF6\uFF1F",confirmDeleteAll:"\u5220\u9664\u6240\u6709\u5BF9\u8BDD\uFF08\u5305\u62EC\u5F53\u524D\u8FD9\u4E2A\uFF09\u548C\u5B83\u4EEC\u7684\u6587\u4EF6\uFF1F",untitled:"\u65B0\u5BF9\u8BDD",attach:"\u6DFB\u52A0\u9644\u4EF6",drop:"\u677E\u5F00\u5373\u53EF\u6DFB\u52A0\u9644\u4EF6",tooLarge:"\u592A\u5927\u4E86\uFF08\u6700\u5927 20 MB\uFF09",remove:"\u79FB\u9664",toolsRunning:"\u6B63\u5728\u6267\u884C",toolsDone:"\u6267\u884C\u4E86 {n} \u4E2A\u5DE5\u5177\u8C03\u7528",toolsDone1:"\u6267\u884C\u4E86 1 \u4E2A\u5DE5\u5177\u8C03\u7528",toolsFailed:"{n} \u4E2A\u5931\u8D25",actRead:"\u8BFB\u53D6\u4E86 {n} \u4E2A\u6587\u4EF6",actList:"\u67E5\u770B\u4E86 {n} \u4E2A\u76EE\u5F55",actSearch:"\u641C\u7D22\u4E86 {n} \u6B21",actWrite:"\u5199\u5165\u4E86 {n} \u4E2A\u6587\u4EF6",actEdit:"\u4FEE\u6539\u4E86 {n} \u4E2A\u6587\u4EF6",actDelete:"\u5220\u9664\u4E86 {n} \u4E2A\u6587\u4EF6",actRun:"\u8FD0\u884C\u4E86 {n} \u6BB5\u4EE3\u7801",actAsk:"\u8BE2\u95EE\u4E86\u4F60 {n} \u6B21",actOther:"\u8C03\u7528\u4E86 {name}",ingRead:"\u6B63\u5728\u8BFB\u53D6",ingList:"\u6B63\u5728\u67E5\u770B",ingSearch:"\u6B63\u5728\u641C\u7D22",ingWrite:"\u6B63\u5728\u5199\u5165",ingEdit:"\u6B63\u5728\u4FEE\u6539",ingDelete:"\u6B63\u5728\u5220\u9664",ingRun:"\u6B63\u5728\u8FD0\u884C\u4EE3\u7801",ingAsk:"\u6B63\u5728\u8BE2\u95EE\u4F60",ingOther:"\u6B63\u5728\u6267\u884C",current:"\u5F53\u524D",jumpEnd:"\u56DE\u5230\u6700\u65B0",sTabModel:"\u6A21\u578B",debug:"\u8C03\u8BD5",dCalls:"\u8C03\u7528",dRequests:"\u8BF7\u6C42",dEvents:"\u4E8B\u4EF6",dContext:"\u4E0A\u4E0B\u6587",dTools:"\u5DE5\u5177",dClear:"\u6E05\u7A7A\u8BB0\u5F55",dFilter:"\u6309\u7C7B\u578B\u8FC7\u6EE4",dNoCalls:"\u8FD8\u6CA1\u6709\u5DE5\u5177\u8C03\u7528\u3002",dNoRequests:"\u8FD8\u6CA1\u6709\u6A21\u578B\u8BF7\u6C42\u3002\u6BCF\u6B21\u8C03\u7528\u6A21\u578B\u90FD\u4F1A\u8BB0\u5728\u8FD9\u91CC\uFF0C\u5305\u62EC\u53D1\u4E86\u4EC0\u4E48\u3001\u6536\u5230\u4EC0\u4E48\u3002",dNoEvents:"\u8FD8\u6CA1\u6709\u4E8B\u4EF6\u3002",dSystem:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",dMessages:"\u53D1\u7ED9\u6A21\u578B\u7684\u6D88\u606F",dPayload:"\u8BF7\u6C42\u5185\u5BB9",dResponse:"\u54CD\u5E94",dRun:"\u8FD0\u884C",dTurn:"\u7B2C {n} \u8F6E",sent:"\u5DF2\u53D1\u9001",justNow:"\u521A\u521A",minutesAgo:"{n} \u5206\u949F\u524D",hoursAgo:"{n} \u5C0F\u65F6\u524D",context:"\u4E0A\u4E0B\u6587",copy:"\u590D\u5236",copied:"\u5DF2\u590D\u5236",rewind:"\u56DE\u9000\u5230\u8FD9\u91CC",rewindTitle:"\u56DE\u9000\u5230\u8FD9\u6761\u6D88\u606F",regen:"\u91CD\u65B0\u56DE\u7B54",regenTitle:"\u91CD\u65B0\u56DE\u7B54\u8FD9\u4E2A\u95EE\u9898",regenMsg:"\u8FD9\u4E2A\u56DE\u7B54\u53CA\u4E4B\u540E\u7684\u5BF9\u8BDD\u4F1A\u88AB\u5220\u9664\uFF0C\u95EE\u9898\u91CD\u65B0\u53D1\u9001\u3002",delTurn:"\u5220\u9664",delTurnTitle:"\u5220\u9664\u8FD9\u4E00\u8F6E\u95EE\u7B54\uFF1F",delTurnMsg:"\u8FD9\u6761\u63D0\u95EE\u548C\u5B83\u7684\u56DE\u7B54\u4F1A\u4ECE\u5BF9\u8BDD\u4E2D\u5220\u9664\uFF0C\u6587\u4EF6\u4E0D\u53D7\u5F71\u54CD\u3002",replyCost:"\u8D39\u7528\uFF1A{cost}",replyUsage:"\u8F93\u5165 {in} \xB7 \u8F93\u51FA {out} \xB7 {calls} \u6B21\u8C03\u7528",rewindMsg:"\u5B83\u4E4B\u540E\u7684\u5BF9\u8BDD\u4F1A\u88AB\u5220\u9664\uFF0C\u6D88\u606F\u5185\u5BB9\u653E\u56DE\u8F93\u5165\u6846\u3002",rewindFiles:"\u540C\u65F6\u628A\u76EE\u5F55\u91CC\u7684\u6587\u4EF6\u6062\u590D\u5230\u90A3\u4E00\u523B",rewindGone:"\u8FD9\u6761\u6D88\u606F\u5DF2\u4E0D\u5728\u5BF9\u8BDD\u91CC\uFF08\u53EF\u80FD\u5DF2\u88AB\u538B\u7F29\uFF09\u3002",rewindSnapshot:"{time} \u65F6\u7684 {n} \u4E2A\u6587\u4EF6\uFF08{size}\uFF09",rewindPartial:"\u8D85\u8FC7 2 MB \u7684\u6587\u4EF6\u6CA1\u8FDB\u5FEB\u7167\uFF0C\u4F1A\u4FDD\u6301\u539F\u6837\u3002",rewindGoneFile:"{path} \u5DF2\u4E0D\u5728\u76EE\u5F55\u91CC\u3002",running:"\u8FD0\u884C\u4E2D",waitingAnswer:"\u7B49\u5F85\u4F60\u56DE\u7B54",finished:"\u5DF2\u5B8C\u6210",bgLimit:"\u540E\u53F0\u5DF2\u6709 {n} \u4E2A\u4F1A\u8BDD\u5728\u8FD0\u884C\uFF0C\u5148\u505C\u6389\u4E00\u4E2A\u518D\u5207\u6362\u3002",settings:"\u8BBE\u7F6E",sVision:"\u53EF\u770B\u56FE",sVisionYes:"\u53EF\u770B\u56FE",sVisionNo:"\u4EC5\u6587\u5B57",noVision:"{model} \u4E0D\u80FD\u770B\u56FE\uFF1A\u56FE\u7247\u5DF2\u4FDD\u5B58\u4E3A\u6587\u4EF6\uFF0C\u4F46\u6A21\u578B\u770B\u4E0D\u5230\u56FE\u91CC\u7684\u5185\u5BB9\u3002",sEffort:"\u601D\u8003\u5F3A\u5EA6",sEffortDefault:"\u6A21\u578B\u9ED8\u8BA4",sEffortNone:"\u8FD9\u4E2A\u6A21\u578B\u6CA1\u6709\u601D\u8003\u5F3A\u5EA6\u53EF\u8C03",sModel:"\u6A21\u578B",sDefault:"\u5E73\u53F0\u9ED8\u8BA4",sMaxTurns:"\u6BCF\u6B21\u8FD0\u884C\u6700\u5927\u8F6E\u6570",sMaxTokens:"\u5355\u6B21\u56DE\u590D\u6700\u5927\u8F93\u51FA",sPrice:"\u5355\u4EF7",sPriceLine:"\u6BCF\u767E\u4E07 tokens \u8F93\u5165 {in} \xB7 \u8F93\u51FA {out}",sPerCall:"\u6BCF\u6B21\u8C03\u7528 {amount}",sAuto:"\u6A21\u578B\u4E0A\u9650",sCustomN:"\u81EA\u5B9A\u4E49",filter:"\u641C\u7D22\u2026",sPerms:"\u5DE5\u5177\u6743\u9650",sAsk:"\u7834\u574F\u6027\u64CD\u4F5C\u5148\u8BE2\u95EE",sAutoPerm:"\u5168\u90E8\u81EA\u52A8\u5141\u8BB8",sCustom:"\u7531\u5E94\u7528\u51B3\u5B9A",apply:"\u5E94\u7528",reset:"\u6062\u590D\u5E94\u7528\u9ED8\u8BA4",applied:"\u8BBE\u7F6E\u5DF2\u5E94\u7528",continueRun:"\u7EE7\u7EED",maxTurnsHint:"\u53EF\u5728\u8BBE\u7F6E\u91CC\u8C03\u9AD8\u4E0A\u9650\uFF0C\u6216\u70B9\u7EE7\u7EED\u4ECE\u8FD9\u91CC\u63A5\u7740\u8DD1",files:"\u6587\u4EF6",downloadZip:"\u6253\u5305\u4E0B\u8F7D (zip)",zipping:"\u6B63\u5728\u6253\u5305",wrap:"\u81EA\u52A8\u6362\u884C",preview:"\u9884\u89C8 Markdown",edit:"\u7F16\u8F91",tooBig:"\u6587\u4EF6\u592A\u5927\uFF0C\u65E0\u6CD5\u5728\u8FD9\u91CC\u7F16\u8F91\uFF0C\u53EF\u4EE5\u4E0B\u8F7D\u3002",conflict:"\u6587\u4EF6\u5728\u4F60\u6253\u5F00\u540E\u88AB\u6539\u8FC7\uFF0C\u8981\u8986\u76D6\u5417\uFF1F",readOnly:"\u53EA\u8BFB",autoSaved:"\u672A\u4FDD\u5B58\u7684\u4FEE\u6539\u5DF2\u81EA\u52A8\u4FDD\u5B58",upload:"\u4E0A\u4F20",newFile:"\u65B0\u5EFA\u6587\u4EF6",refresh:"\u5237\u65B0",close:"\u5173\u95ED",save:"\u4FDD\u5B58",download:"\u4E0B\u8F7D",confirmDeleteFile:"\u5220\u9664 {path}\uFF1F",newFilePath:"\u65B0\u6587\u4EF6\u7684\u8DEF\u5F84",noPreview:"\u8FD9\u4E2A\u6587\u4EF6\u65E0\u6CD5\u9884\u89C8\uFF0C\u53EF\u4EE5\u4E0B\u8F7D\u3002",changedByAgent:"agent \u6539\u8FC7",noFiles:"\u76EE\u5F55\u662F\u7A7A\u7684\u3002",discard:"\u653E\u5F03\u672A\u4FDD\u5B58\u7684\u4FEE\u6539\uFF1F",saved:"\u5DF2\u4FDD\u5B58",skills:"\u6280\u80FD",uploadZip:"\u4E0A\u4F20 zip",noSkills:"\u8FD8\u6CA1\u6709\u6280\u80FD\u3002\u4E0A\u4F20\u4E00\u4E2A zip\uFF1A\u6839\u76EE\u5F55\u6709 SKILL.md\uFF0C\u6216\u6BCF\u4E2A\u6280\u80FD\u4E00\u4E2A\u6587\u4EF6\u5939\u3002",useSkill:"\u4F7F\u7528\uFF1A\u5728\u8F93\u5165\u6846\u586B\u5165 /skill:\u540D\u79F0",skillFolder:"\u6587\u4EF6\u5939",manualOnly:"\u4EC5\u624B\u52A8",skillsInstalled:"\u5DF2\u5B89\u88C5\uFF1A{names}",skillRemoved:"\u5DF2\u5220\u9664 {name}",notZip:"\u4E0D\u662F zip \u6587\u4EF6",confirmDeleteZip:"\u5220\u9664 {zip}\uFF1F\u91CC\u9762\u7684\u6280\u80FD\u4F1A\u4E00\u8D77\u5220\u9664\uFF1A{names}\u3002\u6240\u6709\u5BF9\u8BDD\u90FD\u4E0D\u80FD\u518D\u7528\u3002",confirmDeleteSkill:"\u5220\u9664\u6280\u80FD {name}\uFF08{path}\uFF09\uFF1F\u6240\u6709\u5BF9\u8BDD\u90FD\u4E0D\u80FD\u518D\u7528\u3002",skillsHint:"\u5E94\u7528\u81EA\u5E26\u7684\u6280\u80FD\u4E0D\u80FD\u5220\u9664\u3002\u4F60\u4E0A\u4F20\u7684 zip \u548C\u667A\u80FD\u4F53\u5199\u7684\u6280\u80FD\u4FDD\u5B58\u5728 {user}\uFF0C\u6240\u6709\u5BF9\u8BDD\u5171\u7528\u3002{dir} \u662F\u52A0\u8F7D\u65F6\u7531\u8FD9\u4E24\u90E8\u5206\u751F\u6210\u7684\u53EA\u8BFB\u76EE\u5F55\u3002\u628A zip \u62D6\u5230\u8FD9\u91CC\u4E5F\u80FD\u5B89\u88C5\u3002",skillsHintNoUser:"\u8FD9\u4E9B\u6280\u80FD\u662F\u5E94\u7528\u81EA\u5E26\u7684\u3002{dir} \u662F\u52A0\u8F7D\u65F6\u7531\u5B83\u4EEC\u751F\u6210\u7684\u53EA\u8BFB\u76EE\u5F55\u3002",waiting:"\u601D\u8003\u4E2D",compactingNow:"\u6B63\u5728\u538B\u7F29\u4E0A\u4E0B\u6587",builtinSkill:"\u5E94\u7528\u81EA\u5E26",today:"\u4ECA\u5929",yesterday:"\u6628\u5929",worked:"\u5DF2\u5DE5\u4F5C {t}",workedNoTime:"\u5DE5\u4F5C\u8FC7\u7A0B",sec:"{s}\u79D2",minSec:"{m}\u5206{s}\u79D2",hourMin:"{h}\u5C0F\u65F6{m}\u5206",command:"\u547D\u4EE4",user:"\u7528\u6237",compacting:"\u6B63\u5728\u538B\u7F29\u4E0A\u4E0B\u6587\u2026",nothingToCompact:"\u6682\u65F6\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u5185\u5BB9",busyCmd:"\u8BF7\u7B49\u5F53\u524D\u4EFB\u52A1\u7ED3\u675F\uFF08\u6216\u5148\u505C\u6B62\uFF09",nothingToExport:"\u8FD8\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5185\u5BB9",nothingToContinue:"\u6CA1\u6709\u53EF\u7EE7\u7EED\u7684\u5185\u5BB9",unknownModel:"\u6CA1\u6709\u540D\u4E3A\u201C{name}\u201D\u7684\u6A21\u578B",modelSet:"\u6A21\u578B\uFF1A{name}",effortSet:"\u601D\u8003\u5F3A\u5EA6\uFF1A{name}",effortLevels:"{model} \u7684\u601D\u8003\u5F3A\u5EA6\uFF1A{levels}",unknownEffort:"\u201C{name}\u201D\u4E0D\u662F {model} \u7684\u601D\u8003\u5F3A\u5EA6\uFF08{levels}\uFF09",debugOff:"\u8C03\u8BD5\u6A21\u5F0F\u672A\u5F00\u542F",cmdsTitle:"\u547D\u4EE4",cmdsMore:"\u6A21\u677F\uFF08/\u540D\u79F0\uFF09\u548C Skill\uFF08/skill:\u540D\u79F0\uFF09\u5728\u8F93\u5165\u65F6\u5217\u51FA\u3002",autoCompact:"\u81EA\u52A8\u538B\u7F29",autoCompactAt:"\u5269\u4F59\u4E0D\u8DB3 {n} tokens \u65F6",directory:"\u76EE\u5F55",messagesLabel:"\u6D88\u606F",cmdArgs:{compact:"[\u91CD\u70B9]",model:"[\u540D\u79F0]",effort:"[\u6863\u4F4D]"},cmd:{help:"\u663E\u793A\u8FD9\u4E9B\u547D\u4EE4",new:"\u5F00\u59CB\u65B0\u5BF9\u8BDD",resume:"\u6253\u5F00\u4FDD\u5B58\u7684\u5BF9\u8BDD",compact:"\u7ACB\u5373\u538B\u7F29\u8F83\u65E9\u7684\u5BF9\u8BDD\uFF0C\u53EF\u9644\u4E0A\u8981\u4FDD\u7559\u7684\u91CD\u70B9",continue:"\u7EE7\u7EED\u4E0A\u4E00\u6B21\u8FD0\u884C",model:"\u5207\u6362\u6A21\u578B\uFF0C\u4E0D\u5E26\u540D\u79F0\u5219\u6253\u5F00\u8BBE\u7F6E",effort:"\u8BBE\u7F6E\u601D\u8003\u5F3A\u5EA6",context:"\u4E0A\u4E0B\u6587\u5360\u7528\u3001\u6A21\u578B\u548C\u82B1\u8D39",export:"\u628A\u5BF9\u8BDD\u4E0B\u8F7D\u4E3A Markdown",files:"\u6253\u5F00\u6587\u4EF6\u7BA1\u7406",settings:"\u6253\u5F00\u8BBE\u7F6E",debug:"\u663E\u793A\u6216\u9690\u85CF\u8C03\u8BD5\u9762\u677F"}}};function Rc(r){if(r)return r;let e=typeof document<"u"&&document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"";return/^zh/i.test(e)?"zh":"en"}var ka="runapps-agent-chat-style",Dc=xa()+`
|
|
299
299
|
.ra-chat{display:flex;flex-direction:column;height:100%;min-height:0;box-sizing:border-box;background:var(--ra-bg);color:var(--ra-fg);font:14px/1.5 var(--ra-font);position:relative;overflow:hidden;-webkit-font-smoothing:antialiased}
|
|
300
300
|
.ra-chat *,.ra-chat *::before,.ra-chat *::after{box-sizing:border-box}
|
|
@@ -701,32 +701,32 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
701
701
|
.ra-toast.warning{background:#d97706}.ra-toast.error{background:#dc2626}
|
|
702
702
|
`+ga;function Aa(r,e,n={}){$a();let t=()=>Array.from(r.options).map(d=>({value:d.value,label:d.textContent??d.value})),s=ar(e,{options:t(),value:r.value,...n}),o=r.style.display;r.style.display="none",r.after(s.el),s.el.addEventListener("change",()=>{r.value!==s.value&&(r.value=s.value,r.dispatchEvent(new Event("change",{bubbles:!0})))});let a=new MutationObserver(()=>{s.setOptions(t()),s.value=r.value});a.observe(r,{childList:!0,subtree:!0,characterData:!0});let l=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value");return l?.set&&l.get&&Object.defineProperty(r,"value",{configurable:!0,get(){return l.get.call(this)},set(d){l.set.call(this,d),s.value=l.get.call(this)}}),Object.assign(s,{destroy(){s.close(),a.disconnect(),delete r.value,r.style.display=o,s.el.remove()}})}function $a(){if(typeof document>"u"||document.getElementById(ka))return;let r=document.createElement("style");r.id=ka,r.textContent=Dc,document.head.prepend(r)}var Oc={read_file:U.fileText,write_file:U.filePlus,edit_file:U.filePen,delete_file:U.fileX,list_files:U.folderOpen,search_files:U.search,run_js:U.braces,ask_user:U.message};function vn(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
703
703
|
`):""}function ki(r,e){if(!e||typeof e!="object")return typeof e=="string"?e.slice(0,80):"";let n=e,t=typeof n.path=="string"?n.path:void 0;if(r==="search_files")return`${String(n.pattern??"")}${t?` in ${t}`:""}`;if(r==="run_js")return String(n.code??"").split(`
|
|
704
|
-
`).find(o=>o.trim()&&!o.trim().startsWith("//"))?.trim().slice(0,80)??"";if(r==="ask_user"){let o=n.questions;return Array.isArray(o)&&o[0]&&typeof o[0]=="object"?String(o[0].question??""):""}if(t)return t;let s=Object.values(n)[0];return s===void 0?"":(typeof s=="string"?s:JSON.stringify(s)).slice(0,80)}var Ta={read_file:"Read",list_files:"List",search_files:"Search",write_file:"Write",edit_file:"Edit",delete_file:"Delete",run_js:"Run",ask_user:"Ask"},Sa=r=>r&&typeof r=="object"&&typeof r.path=="string"?r.path:void 0;function zc(r){return r.startsWith("Skipped")?"skipped":r.startsWith("The user declined")?"declined":r.includes("Do not retry it another way")?"blocked":/^Error|^Tool call "[^"]*" was not executed/.test(r)?"error":"ok"}function Ti(r,e){let n=La(e);return r===0?`${n}0`:r<.001?`${n}${r.toFixed(5)}`:r<.1?`${n}${r.toFixed(4)}`:`${n}${r.toFixed(3)}`}function La(r){let e=(r||"USD").toUpperCase();return e==="USD"?"$":e==="CNY"||e==="JPY"?"\xA5":e==="EUR"?"\u20AC":e==="GBP"?"\xA3":`${e} `}function cr(r,e){return`${La(e)}${Number(r.toPrecision(4))}`}function Je(r){return r>=1e6?`${(r/1e6).toFixed(r>=1e7?1:2)}M`:r>=1e4?`${(r/1e3).toFixed(1)}k`:String(r)}function kn(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/1024/1024).toFixed(1)} MB`}function Uc(r,e){let n=Math.round((Date.now()-r)/1e3);return n<60?e.justNow:n<3600?e.minutesAgo.replace("{n}",String(Math.floor(n/60))):n<86400?e.hoursAgo.replace("{n}",String(Math.floor(n/3600))):Pa(r)}function Pa(r){let e=new Date(r),n=new Date,t=`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`;if(e.toDateString()===n.toDateString())return t;let s=`${e.getMonth()+1}/${e.getDate()}`;return e.getFullYear()===n.getFullYear()?`${s} ${t}`:`${e.getFullYear()}/${s} ${t}`}var Tn=r=>r?.ts,_a=2*1024*1024,Ic=32*1024*1024,Ra=30,hs=r=>`ckpt:${r}`,gs="ckpt:index";async function Fc(r,e){let n=[],t=[],s=0;for(let a of await r.list("/")){if(r.isSkillPath(a.path)||r.mountOf(a.path))continue;if(a.size>_a||s+a.size>Ic){t.push(a.path);continue}let l=await r.read(a.path);n.push({path:a.path,contentType:l.contentType,data:l.data}),s+=a.size}await r.putData(hs(e),{at:e,files:n,partial:t.length>0,skipped:t});let o=[...(await r.getData(gs)??[]).filter(a=>a!==e),e].sort((a,l)=>a-l);for(let a of o.splice(0,Math.max(0,o.length-Ra)))await r.deleteData(hs(a));await r.putData(gs,o)}async function
|
|
704
|
+
`).find(o=>o.trim()&&!o.trim().startsWith("//"))?.trim().slice(0,80)??"";if(r==="ask_user"){let o=n.questions;return Array.isArray(o)&&o[0]&&typeof o[0]=="object"?String(o[0].question??""):""}if(t)return t;let s=Object.values(n)[0];return s===void 0?"":(typeof s=="string"?s:JSON.stringify(s)).slice(0,80)}var Ta={read_file:"Read",list_files:"List",search_files:"Search",write_file:"Write",edit_file:"Edit",delete_file:"Delete",run_js:"Run",ask_user:"Ask"},Sa=r=>r&&typeof r=="object"&&typeof r.path=="string"?r.path:void 0;function zc(r){return r.startsWith("Skipped")?"skipped":r.startsWith("The user declined")?"declined":r.includes("Do not retry it another way")?"blocked":/^Error|^Tool call "[^"]*" was not executed/.test(r)?"error":"ok"}function Ti(r,e){let n=La(e);return r===0?`${n}0`:r<.001?`${n}${r.toFixed(5)}`:r<.1?`${n}${r.toFixed(4)}`:`${n}${r.toFixed(3)}`}function La(r){let e=(r||"USD").toUpperCase();return e==="USD"?"$":e==="CNY"||e==="JPY"?"\xA5":e==="EUR"?"\u20AC":e==="GBP"?"\xA3":`${e} `}function cr(r,e){return`${La(e)}${Number(r.toPrecision(4))}`}function Je(r){return r>=1e6?`${(r/1e6).toFixed(r>=1e7?1:2)}M`:r>=1e4?`${(r/1e3).toFixed(1)}k`:String(r)}function kn(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/1024/1024).toFixed(1)} MB`}function Uc(r,e){let n=Math.round((Date.now()-r)/1e3);return n<60?e.justNow:n<3600?e.minutesAgo.replace("{n}",String(Math.floor(n/60))):n<86400?e.hoursAgo.replace("{n}",String(Math.floor(n/3600))):Pa(r)}function Pa(r){let e=new Date(r),n=new Date,t=`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`;if(e.toDateString()===n.toDateString())return t;let s=`${e.getMonth()+1}/${e.getDate()}`;return e.getFullYear()===n.getFullYear()?`${s} ${t}`:`${e.getFullYear()}/${s} ${t}`}var Tn=r=>r?.ts,_a=2*1024*1024,Ic=32*1024*1024,Ra=30,hs=r=>`ckpt:${r}`,gs="ckpt:index";async function Fc(r,e){let n=[],t=[],s=0;for(let a of await r.list("/")){if(r.isSkillPath(a.path)||r.mountOf(a.path))continue;if(a.size>_a||s+a.size>Ic){t.push(a.path);continue}let l=await r.read(a.path);n.push({path:a.path,contentType:l.contentType,data:l.data}),s+=a.size}await r.putData(hs(e),{at:e,files:n,partial:t.length>0,skipped:t});let o=[...(await r.getData(gs)??[]).filter(a=>a!==e),e].sort((a,l)=>a-l);for(let a of o.splice(0,Math.max(0,o.length-Ra)))await r.deleteData(hs(a));await r.putData(gs,o)}async function Hc(r,e){let n=await r.getData(gs)??[];for(let t of n.filter(s=>s>e))await r.deleteData(hs(t));await r.putData(gs,n.filter(t=>t<=e))}var ms=r=>`hoststate:${r}`,ys="hoststate:index";async function jc(r,e,n){await r.putData(ms(e),{at:e,value:n});let t=[...(await r.getData(ys)??[]).filter(s=>s!==e),e].sort((s,o)=>s-o);for(let s of t.splice(0,Math.max(0,t.length-Ra)))await r.deleteData(ms(s));await r.putData(ys,t)}async function Nc(r,e){let n=await r.getData(ys)??[];for(let t of n.filter(s=>s>e))await r.deleteData(ms(t));await r.putData(ys,n.filter(t=>t<=e))}async function qc(r,e){let n=new Set([...e.files.map(t=>t.path),...e.skipped??[]]);for(let t of await r.list("/"))r.isSkillPath(t.path)||r.mountOf(t.path)||n.has(t.path)||!e.skipped&&e.partial&&t.size>_a||await r.delete(t.path);for(let t of e.files)await r.write(t.path,t.data,t.contentType)}var Bc=20*1024*1024,Wc=8*1024*1024,Kc=25*1024*1024,Si=64*1024,Vc=/\.(txt|md|markdown|csv|tsv|json|jsonl|ya?ml|toml|xml|html?|css|js|mjs|cjs|ts|tsx|jsx|py|rb|go|rs|java|kt|c|h|cpp|hpp|cs|sh|bash|zsh|sql|ini|cfg|conf|log|env|svg|tex|rst)$/i,Pt="[attachments]",Sn="[context] ";function fs(r){if(Array.isArray(r))return r.filter(s=>s.type==="text").map(s=>s.text);if(typeof r!="string")return[];if(!r.includes(Sn)&&!r.includes(Pt)&&!r.includes("<file name="))return[r];let e=[],n=[],t=!1;for(let s of r.split(`
|
|
705
705
|
`))!t&&(s.startsWith(Sn)||s.startsWith(Pt)||s.startsWith("<file name="))&&n.length&&(e.push(n.join(`
|
|
706
706
|
`)),n=[]),n.push(s),!t&&s.startsWith("<file name=")?t=!s.endsWith("</file>"):t&&s==="</file>"&&(t=!1);return n.length&&e.push(n.join(`
|
|
707
|
-
`)),e}function Ma(r){let e=/^- (.+) \(([^()]*)\)(?: — .*)?$/.exec(r);if(!e)return null;let[n="",t=""]=e[2].split(/,\s*/);return{ref:e[1],type:n,size:t}}var Gc=r=>r?.typed,Zc=r=>`When you create or change a file for the user, name its absolute path in backticks (for example \`/index.html\`); in the chat that path becomes a link that opens the file. Files the user attaches arrive under ${r}.`,Xc=r=>`The user can browse, edit and download every file of the directory from the chat's Files panel. When you create or change a file for the user, name its absolute path in backticks (for example \`${r}/report.csv\`); in the chat that path becomes a link that opens the file, with a download button. Files the user attaches arrive under ${r}.`;function Jc(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Vc.test(r.name))){let t=e.subarray(0,8192);for(let s of t)if(s===0)return null}try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}function Ca(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function Yc(r,e,n,t){let s=new Set,o=(d,p,u)=>new Promise(w=>{if(u?.aborted){w(p);return}let b=h("section","ra-q"),x,M=()=>x.cancel(),S=P=>{u?.removeEventListener("abort",M),s.delete(x),b.remove(),t(),w(P)};x={card:b,cancel:()=>S(p)},u?.addEventListener("abort",M,{once:!0}),b.addEventListener("keydown",P=>{P.key==="Escape"&&!P.isComposing&&(P.preventDefault(),P.stopPropagation(),x.cancel())}),d(b,S),s.add(x),r.append(b),t();let A=b.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>A?.focus())}),a=(d,p,u)=>{d.append(h("div","ra-qt",p)),u&&d.append(h("div","ra-qm",u))},l=(d,p,u)=>{let w=h("button","ra-btn xs "+p,d);return w.type="button",w.addEventListener("click",u),w};return{confirm:(d,p,u={})=>o((w,b)=>{if(a(w,d,p),u.body)try{let S=u.body();S.classList.add("ra-cbody"),w.append(S)}catch(S){console.warn("agent: confirm body failed",S)}let x=h("div","ra-btns");x.append(l(u.cancel??n.decline,"ghost",()=>b(!1)));let M=u.always;M&&x.append(l(M.label,"subtle",()=>{try{M.onChoose()}catch(S){console.warn("agent: always.onChoose failed",S)}b(!0)})),x.append(l(u.ok??n.allow,u.danger?"red":"solid",()=>b(!0))),w.append(x)},!1,u.signal),select:(d,p,u={})=>o((w,b)=>{a(w,d,u.message);let x=h("div","ra-opts");if(!u.multi&&!u.allowOther){for(let C of p){let N=h("button","ra-opt");N.type="button";let O=h("div");O.append(h("span","",C.label??C.value)),C.description&&O.append(h("small","",C.description)),N.append(O),N.addEventListener("click",()=>b([C.value])),x.append(N)}w.append(x,(()=>{let C=h("div","ra-btns");return C.append(l(n.cancel,"ghost",()=>b(null))),C})());return}let M="ra_"+Math.random().toString(36).slice(2,8),S=[],A=C=>{let N=h("label","ra-opt"),O=h("input");O.type=u.multi?"checkbox":"radio",O.name=M,O.value=C.value,S.push(O);let te=h("div");te.append(h("span","",C.label??C.value)),C.description&&te.append(h("small","",C.description)),N.append(O,te),x.append(N)};p.forEach(A);let P=null;u.allowOther&&(A({value:"__other__",label:n.other}),P=h("input","ra-field"),P.type="text",P.placeholder=n.typeAnswer,P.addEventListener("focus",()=>{let C=S.find(N=>N.value==="__other__");C&&(C.checked=!0)}),x.append(P)),w.append(x);let _=h("div","ra-btns");_.append(l(n.cancel,"ghost",()=>b(null)),l(n.ok,"solid",()=>{let C=S.filter(N=>N.checked).map(N=>N.value==="__other__"?P?.value.trim()??"":N.value).filter(Boolean);C.length&&b(C)})),w.append(_)},null,u.signal),input:(d,p={})=>o((u,w)=>{a(u,d,p.message);let b=p.multiline?h("textarea","ra-field"):h("input","ra-field");p.multiline||(b.type="text"),p.placeholder&&(b.placeholder=p.placeholder),p.initial&&(b.value=p.initial),b.addEventListener("keydown",M=>{let S=M;S.key==="Enter"&&!S.isComposing&&(!p.multiline||S.metaKey||S.ctrlKey)&&(S.preventDefault(),w(b.value))}),u.append(b);let x=h("div","ra-btns");x.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(b.value))),u.append(x)},null,p.signal),notify(d,p="info"){let u=h("div","ra-toast "+p,d);e.append(u),setTimeout(()=>u.remove(),p==="error"?8e3:4e3)},cancelAll(d=!1){for(let p of[...s])(d||p.card.isConnected)&&p.cancel()},park(){let d=[];for(let p of s)p.card.isConnected&&(p.card.remove(),d.push(p.card));return t(),d},restore(d){for(let p of d)r.append(p);d.length&&t()}}}var Mi=r=>`__runapps_agent_chat:${r}:last`;function Qc(r){try{return localStorage.getItem(Mi(r))}catch{return null}}function Ea(r,e){try{e?localStorage.setItem(Mi(r),e):localStorage.removeItem(Mi(r))}catch{}}function Da(r,e){if(typeof document>"u")throw new Error("renderChat needs a document");if(!e.agent&&!e.provider&&!e.client)throw new Error("renderChat needs a provider (or a RunApps client, or an agent)");$a();let n=Rc(e.locale),t=_c[n],{client:s,provider:o,agent:a,workspace:l,resume:d,palette:p,vars:u,className:w,debug:b,settings:x,skillsMenu:M,title:S,placeholder:A,emptyState:P,suggestions:_,sessions:C,locale:N,theme:O,showUsage:te,attachments:ge,uploadsDir:J,onOpenFile:ee,onLink:de,onSession:ve,files:Oe,headerActions:pe,headerEnd:we,settingsTabs:fe,composerTop:Se,composerActions:_e,permissionsSetting:R,rewindState:I,nextPrompt:G,...B}=e,j="/"+(J??"/uploads").replace(/^\/+|\/+$/g,""),K=o?tt(o):s?tt(s):a?.provider??null,ie=K?.name??B.appName??"app",H=h("div","ra-chat");w&&H.classList.add(...w.split(/\s+/).filter(Boolean));let re=O??"auto",Ee=p??"claude",Re=u,xt=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,Vt=[],Gt=()=>{let i=re==="auto"?xt?.matches?"dark":"light":re;H.dataset.theme=re,H.dataset.scheme=i,typeof Ee=="string"?H.dataset.palette=Ee:delete H.dataset.palette;for(let g of Vt)H.style.removeProperty(g);Vt=[];let c=g=>{for(let[m,y]of Object.entries(g??{}))if(y!==void 0){let v=va(m);H.style.setProperty(v,y),Vt.push(v)}};typeof Ee!="string"&&c(Ee[i]);let f=Re;f&&("light"in f||"dark"in f)?c(f[i]):c(f)};Gt();let Mn=()=>{re==="auto"&&Gt()};xt?.addEventListener?.("change",Mn);let _t=h("div","ra-head"),dr=h("div","ra-title",S===!1?"":S||B.appName||t.assistant),ye=h("span","ra-badge"),Ae=h("button","ra-btn ghost");Ae.type="button",Ae.innerHTML=U.bug()+`<span>${xe(t.debug)}</span>`;let nt=h("button","ra-btn ghost");nt.type="button",nt.innerHTML=U.folder()+`<span>${xe(t.files)}</span>`;let Ye=h("button","ra-btn ghost");Ye.type="button",Ye.innerHTML=U.puzzle()+`<span>${xe(t.skills)}</span>`;let ft=(i,c)=>{let f=h("b","ra-cnt");return f.style.display="none",i.append(f),g=>{f.textContent=String(g),f.style.display=g?"":"none",i.title=g?`${c} \xB7 ${g}`:c}},Zt=ft(Ye,t.skills),Xe=h("button","ra-btn ghost");Xe.type="button",Xe.innerHTML=U.hist()+`<span>${xe(t.history)}</span>`;let Cn=ft(Xe,t.history),ht=h("button","ra-btn ghost");ht.type="button",ht.innerHTML=U.plus()+`<span>${xe(t.newChat)}</span>`;let ze=h("button","ra-btn ghost");ze.type="button",ze.innerHTML=U.eraser()+`<span>${xe(t.clearChat)}</span>`,ze.style.display="none";let $e=h("button","ra-btn ghost ra-usebtn");$e.type="button",$e.style.display="none";let Be=h("button","ra-btn ghost");Be.type="button",Be.innerHTML=U.gear(),Be.title=t.settings,Be.setAttribute("aria-label",t.settings);for(let[i,c]of[[Ae,t.debug],[nt,t.files],[Ye,t.skills],[Xe,t.history],[ht,t.newChat],[ze,t.clearChat]])i.setAttribute("aria-label",c),i.title||(i.title=c);for(let i of[...pe??[],...we??[],...Se?[Se]:[],...P instanceof HTMLElement?[P]:[]])i.classList.add("ra-host");_t.append(dr,ye,h("span","ra-sp"),$e,Ae,nt,Ye,Xe,ht,ze,...pe??[],Be,...we??[]),S===!1&&(_t.style.display="none");let He=h("div","ra-log"),En=h("div","ra-col");He.append(En);let An=h("div","ra-ask"),Rt=h("div","ra-col");An.append(Rt);let Xt=h("div","ra-status");Xt.style.display="none";let $n=h("div","ra-comp"),pr=h("div","ra-col"),vt=h("div","ra-alert");vt.style.display="none",vt.setAttribute("role","alert");let Ke=h("div","ra-queue");Ke.style.display="none";let Ln=h("div","ra-box"),Qe=h("div","ra-cmds");Qe.style.display="none";let T=h("textarea");T.rows=2,T.setAttribute("aria-label","Message");let q=h("div","ra-files");q.style.display="none";let oe=h("div","ra-bar"),Y=h("div","ra-left"),ae=h("button","ra-attach");ae.type="button",ae.innerHTML=U.clip(),ae.title=t.attach,ae.setAttribute("aria-label",t.attach);let me=h("input");me.type="file",me.multiple=!0,me.style.display="none",ge===!1&&(ae.style.display="none");let Ve=h("span","ra-hint"),ur=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",Dt=i=>i.replace("{mod}",ur).replace("{enter}",t.enter).replace("{newline}",t.newline);Ve.textContent=Dt(t.hintIdle);let Pn=h("div","ra-acts"),Le=h("button","ra-send");Le.type="button",Le.innerHTML=U.corner(18),Le.title=t.send,Le.setAttribute("aria-label",t.send);let Jt=h("button","ra-btn xs subtle");Jt.type="button",Jt.innerHTML=U.corner()+xe(t.steer),Jt.title=t.steerTip;let _n=h("button","ra-btn xs subtle",t.followUp);_n.type="button",_n.title=t.followUpTip;let Ot=h("button","ra-stop");Ot.type="button",Ot.innerHTML='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="2" width="12" height="12" rx="3" fill="currentColor"/></svg>',Ot.title=t.stop,Ot.setAttribute("aria-label",t.stop),Pn.append(Jt,_n,Ot,Le);let Ei=new Map,Ai=(i,c)=>{let f=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${xe(c.label)}</span>`:`<span>${xe(c.label)}</span>`;i.innerHTML=f,i.classList.toggle("icon",!!(c.icon&&c.iconOnly)),i.title=c.title??c.label,i.setAttribute("aria-label",c.label),i.style.display=c.hidden?"none":"",i.disabled=!!c.disabled},Ua=(_e??[]).map(i=>{if(i instanceof HTMLElement)return i.classList.add("ra-host"),i;let c={...i},f=h("button","ra-cbtn");return f.type="button",f.addEventListener("click",()=>c.onClick()),Ai(f,c),c.id&&Ei.set(c.id,{btn:f,a:c}),f});Y.append(ae,...Ua,Ve),oe.append(Y,Pn),Ln.append(Qe,q,T,oe,me);let Ia=h("div","ra-drop",t.drop);pr.append(vt,Ke,...Se?[Se]:[],Ln),$n.append(pr);let $i=h("div","ra-toasts"),Li=h("div","ra-col");Li.append(Xt);let fr=h("div","ra-main"),bs=h("div","ra-chatcol"),Pi=h("div","ra-jumpwrap"),gt=h("button","ra-jump");gt.type="button",gt.innerHTML=U.arrowDown(),gt.title=t.jumpEnd,gt.setAttribute("aria-label",t.jumpEnd),gt.tabIndex=-1,Pi.append(gt),bs.append(He,Pi,An,Li,$n),fr.append(bs),H.append(_t,fr,$i,Ia),r.replaceChildren(H);let F,be=new wn(He,En,{estimate:96,overscan:400,rowClass:"ra-row",onFollow:i=>{let c=!i&&He.scrollHeight-He.clientHeight>40;gt.classList.toggle("show",c),gt.tabIndex=c?0:-1}});gt.addEventListener("click",()=>be.scrollToBottom()),He.addEventListener("click",i=>{let c=i.target.closest("summary");c&&He.contains(c)&&be.pin(c)},!0);let X=null,kt=null,Yt=new Map,xs=new WeakMap,Rn=new Map,hr=[],rt=0,Dn=null,On=[],Te=null,gr=!0,_i=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{H.dataset.short=H.clientHeight&&H.clientHeight<420?"1":""});_i?.observe(H);let Ri=0,Z=Yc(Rt,$i,t,()=>{let i=Rt.childElementCount;H.dataset.asking=i?"1":"",i<Ri?be.scrollToBottom():be.schedule(),Ri=i}),Fa=3,We=new Map,mr=new Map,zn=new Map,zt=new Set,Tt=new Map,vs=(i,c)=>new Promise(f=>{if(F?.id===i){f(!0);return}if(c?.aborted){f(!1);return}zt.add(i);let g=Tt.get(i)??[],m=v=>{c?.removeEventListener("abort",y),f(v)},y=()=>{let v=Tt.get(i);if(v){let k=v.indexOf(m);k>=0&&v.splice(k,1),v.length||(Tt.delete(i),zt.delete(i))}m(!1),Ut()};c?.addEventListener("abort",y,{once:!0}),g.push(m),Tt.set(i,g),Ut()}),ks=(i,c=!0)=>{let f=Tt.get(i);Tt.delete(i),zt.delete(i),f?.forEach(g=>g(c))},ja=i=>({confirm:async(c,f,g)=>await vs(i,g?.signal)?Z.confirm(c,f,g):!1,select:async(c,f,g)=>await vs(i,g?.signal)?Z.select(c,f,g):null,input:async(c,f)=>await vs(i,f?.signal)?Z.input(c,f):null,notify:(c,f)=>Z.notify(c,f)}),Di=i=>!!i.workspace&&typeof l=="function"&&!i.workspace.root,Ts=()=>[...We.values()].filter(i=>i!==F&&(i.busy||i.queued.length>0||zt.has(i.id))),yr=i=>{let c=Bt({v:2,id:i.id,messages:i.messages,usage:i.usage,droppedTurns:0,savedAt:0});return c===$t?t.untitled:c.length>40?c.slice(0,37)+"\u2026":c},Ut=()=>Xe.classList.toggle("ra-bg",Ts().length>0),Qt=null,Ss=()=>{Qt&&clearTimeout(Qt),Qt=setTimeout(async()=>{Qt=null;let i=F?.workspace;if(!i||a){Cn(0);return}try{let f=(await i.sessions.list()).filter(g=>g.id!==F.id).length;F?.workspace===i&&Cn(f?f+1:0)}catch{}},50)},Oi=async(i,c)=>{let f=Tn(c);if(!(!i.workspace||!f)){if(I)try{await Hc(i.workspace,f,await I.take())}catch(g){console.warn("agent: rewindState.take failed",g)}if(Di(i))try{await Fc(i.workspace,f)}catch(g){console.warn("agent: checkpoint failed",g)}}},Ha=i=>{if(mr.has(i.id))return;let c=[];c.push(i.on("run_end",()=>{F!==i&&(Z.notify(`${yr(i)} \xB7 ${t.finished}`),setTimeout(()=>{gr&&(F!==i&&!i.busy&&!i.queued.length&&!zt.has(i.id)&&(We.delete(i.id),wr(i),Dr(i)),Ut())},50))})),c.push(i.on("run_start",f=>{Ut(),f.message&&Oi(i,f.message)})),mr.set(i.id,c),Ut()},wr=i=>{mr.get(i.id)?.forEach(c=>c()),mr.delete(i.id)},Ne=ma({t,root:H,editorHost:bs,notify:(i,c)=>Z.notify(i,c),onChange:()=>{Ct()},onShow:i=>nt.classList.toggle("on",i)});fr.append(Ne.el);let et=ya({t,root:H,onShow:i=>Ae.classList.toggle("on",i)});fr.append(et.el);let It=!!b,br=()=>{if(Ae.style.display=It?"":"none",H.dataset.debug=It?"1":"",It){for(let i of We.values())i!==F&&et.setAgent(i);F&&et.setAgent(F)}else{et.close();for(let i of We.values())et.forget(i)}};br(),nt.addEventListener("click",()=>{et.visible&&(et.close(),br()),Ne.toggle()}),Ae.addEventListener("click",async()=>{Ne.visible&&await Ne.close(),!Ne.visible&&(et.toggle(),br())});let Un=i=>{ee?ee(i):Ne.open(i)},zi=async i=>{let c=F?.workspace;if(c&&!await c.exists(i)){Z.notify(`${t.rewindGoneFile.replace("{path}",i)}`,"warning");return}Un(i)},mt=h("div","ra-empty"),Ms={render:()=>mt},Ui=()=>{if(P!==null){if(mt.replaceChildren(),mt.classList.toggle("start",typeof P=="object"&&!(P instanceof HTMLElement)&&P?.align==="start"),P instanceof HTMLElement)mt.append(P);else if(P&&typeof P=="object"){if(P.icon){let i=h("div","ra-empty-icon");typeof P.icon=="string"?i.innerHTML=P.icon:i.append(P.icon),mt.append(i)}P.title&&mt.append(h("h3","ra-empty-title",P.title)),P.text&&mt.append(h("p","ra-empty-text",P.text))}else mt.append(h("div","",typeof P=="string"?P:t.empty));if(_?.length){let i=h("div","ra-sugs");for(let c of _){let f=typeof c=="string"?c:c.label,g=typeof c=="string"?c:c.prompt,m=h("button","",f);m.type="button",g!==f&&(m.title=g),m.addEventListener("click",()=>{T.value=g,T.focus(),Ge()}),i.append(m)}mt.append(i)}be.rows.includes(Ms)||be.push(Ms)}},Na=()=>be.remove(Ms),St=i=>{Na(),be.push(i)},Ii=(i,c,f)=>{let g=h("span","ra-chip"),m=i.lastIndexOf("."),y=m>0&&i.length-m<=6?i.slice(m):"";if(f){let k=h("img");k.src=f,k.alt="",g.append(k)}else g.append(h("span","ra-ext",(y.slice(1)||"file").slice(0,4)));let v=h("span","ra-cn");return v.title=i,v.append(h("span","st",y?i.slice(0,m):i)),y&&v.append(h("span","ex",y)),g.append(v),c&&g.append(h("small","",c.replace(/\s+(?=[KMG]?B$)/,""))),g},Fi=(i,c,f)=>{let g=h("span","ra-chip ra-ctx"),m=h("span","ra-ctxi");m.innerHTML=f??U.pointer(15);let y=h("span","ra-cn");return y.title=c??i,y.append(h("span","st",i)),g.append(m,y),g},ji=i=>fs(i).flatMap(c=>c.startsWith(Sn)?[{label:c.slice(Sn.length).split(`
|
|
707
|
+
`)),e}function Ma(r){let e=/^- (.+) \(([^()]*)\)(?: — .*)?$/.exec(r);if(!e)return null;let[n="",t=""]=e[2].split(/,\s*/);return{ref:e[1],type:n,size:t}}var Gc=r=>r?.typed,Zc=r=>`When you create or change a file for the user, name its absolute path in backticks (for example \`/index.html\`); in the chat that path becomes a link that opens the file. Files the user attaches arrive under ${r}.`,Xc=r=>`The user can browse, edit and download every file of the directory from the chat's Files panel. When you create or change a file for the user, name its absolute path in backticks (for example \`${r}/report.csv\`); in the chat that path becomes a link that opens the file, with a download button. Files the user attaches arrive under ${r}.`;function Jc(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Vc.test(r.name))){let t=e.subarray(0,8192);for(let s of t)if(s===0)return null}try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}function Ca(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function Yc(r,e,n,t){let s=new Set,o=(d,p,u)=>new Promise(w=>{if(u?.aborted){w(p);return}let x=h("section","ra-q"),b,M=()=>b.cancel(),T=P=>{u?.removeEventListener("abort",M),s.delete(b),x.remove(),t(),w(P)};b={card:x,cancel:()=>T(p)},u?.addEventListener("abort",M,{once:!0}),x.addEventListener("keydown",P=>{P.key==="Escape"&&!P.isComposing&&(P.preventDefault(),P.stopPropagation(),b.cancel())}),d(x,T),s.add(b),r.append(x),t();let A=x.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>A?.focus())}),a=(d,p,u)=>{d.append(h("div","ra-qt",p)),u&&d.append(h("div","ra-qm",u))},l=(d,p,u)=>{let w=h("button","ra-btn xs "+p,d);return w.type="button",w.addEventListener("click",u),w};return{confirm:(d,p,u={})=>o((w,x)=>{if(a(w,d,p),u.body)try{let T=u.body();T.classList.add("ra-cbody"),w.append(T)}catch(T){console.warn("agent: confirm body failed",T)}let b=h("div","ra-btns");b.append(l(u.cancel??n.decline,"ghost",()=>x(!1)));let M=u.always;M&&b.append(l(M.label,"subtle",()=>{try{M.onChoose()}catch(T){console.warn("agent: always.onChoose failed",T)}x(!0)})),b.append(l(u.ok??n.allow,u.danger?"red":"solid",()=>x(!0))),w.append(b)},!1,u.signal),select:(d,p,u={})=>o((w,x)=>{a(w,d,u.message);let b=h("div","ra-opts");if(!u.multi&&!u.allowOther){for(let C of p){let N=h("button","ra-opt");N.type="button";let O=h("div");O.append(h("span","",C.label??C.value)),C.description&&O.append(h("small","",C.description)),N.append(O),N.addEventListener("click",()=>x([C.value])),b.append(N)}w.append(b,(()=>{let C=h("div","ra-btns");return C.append(l(n.cancel,"ghost",()=>x(null))),C})());return}let M="ra_"+Math.random().toString(36).slice(2,8),T=[],A=C=>{let N=h("label","ra-opt"),O=h("input");O.type=u.multi?"checkbox":"radio",O.name=M,O.value=C.value,T.push(O);let te=h("div");te.append(h("span","",C.label??C.value)),C.description&&te.append(h("small","",C.description)),N.append(O,te),b.append(N)};p.forEach(A);let P=null;u.allowOther&&(A({value:"__other__",label:n.other}),P=h("input","ra-field"),P.type="text",P.placeholder=n.typeAnswer,P.addEventListener("focus",()=>{let C=T.find(N=>N.value==="__other__");C&&(C.checked=!0)}),b.append(P)),w.append(b);let _=h("div","ra-btns");_.append(l(n.cancel,"ghost",()=>x(null)),l(n.ok,"solid",()=>{let C=T.filter(N=>N.checked).map(N=>N.value==="__other__"?P?.value.trim()??"":N.value).filter(Boolean);C.length&&x(C)})),w.append(_)},null,u.signal),input:(d,p={})=>o((u,w)=>{a(u,d,p.message);let x=p.multiline?h("textarea","ra-field"):h("input","ra-field");p.multiline||(x.type="text"),p.placeholder&&(x.placeholder=p.placeholder),p.initial&&(x.value=p.initial),x.addEventListener("keydown",M=>{let T=M;T.key==="Enter"&&!T.isComposing&&(!p.multiline||T.metaKey||T.ctrlKey)&&(T.preventDefault(),w(x.value))}),u.append(x);let b=h("div","ra-btns");b.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(x.value))),u.append(b)},null,p.signal),notify(d,p="info"){let u=h("div","ra-toast "+p,d);e.append(u),setTimeout(()=>u.remove(),p==="error"?8e3:4e3)},cancelAll(d=!1){for(let p of[...s])(d||p.card.isConnected)&&p.cancel()},park(){let d=[];for(let p of s)p.card.isConnected&&(p.card.remove(),d.push(p.card));return t(),d},restore(d){for(let p of d)r.append(p);d.length&&t()}}}var Mi=r=>`__runapps_agent_chat:${r}:last`;function Qc(r){try{return localStorage.getItem(Mi(r))}catch{return null}}function Ea(r,e){try{e?localStorage.setItem(Mi(r),e):localStorage.removeItem(Mi(r))}catch{}}function Da(r,e){if(typeof document>"u")throw new Error("renderChat needs a document");if(!e.agent&&!e.provider&&!e.client)throw new Error("renderChat needs a provider (or a RunApps client, or an agent)");$a();let n=Rc(e.locale),t=_c[n],{client:s,provider:o,agent:a,workspace:l,resume:d,palette:p,vars:u,className:w,debug:x,settings:b,skillsMenu:M,title:T,placeholder:A,emptyState:P,suggestions:_,sessions:C,locale:N,theme:O,showUsage:te,attachments:ge,uploadsDir:J,onOpenFile:ee,onLink:de,onSession:ve,files:Oe,headerActions:pe,headerEnd:we,settingsTabs:fe,composerTop:Se,composerActions:_e,permissionsSetting:R,rewindState:I,nextPrompt:G,...B}=e,H="/"+(J??"/uploads").replace(/^\/+|\/+$/g,""),K=o?tt(o):s?tt(s):a?.provider??null,ie=K?.name??B.appName??"app",j=h("div","ra-chat");w&&j.classList.add(...w.split(/\s+/).filter(Boolean));let re=O??"auto",Ee=p??"claude",Re=u,xt=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,Vt=[],Gt=()=>{let i=re==="auto"?xt?.matches?"dark":"light":re;j.dataset.theme=re,j.dataset.scheme=i,typeof Ee=="string"?j.dataset.palette=Ee:delete j.dataset.palette;for(let g of Vt)j.style.removeProperty(g);Vt=[];let c=g=>{for(let[m,y]of Object.entries(g??{}))if(y!==void 0){let v=va(m);j.style.setProperty(v,y),Vt.push(v)}};typeof Ee!="string"&&c(Ee[i]);let f=Re;f&&("light"in f||"dark"in f)?c(f[i]):c(f)};Gt();let Mn=()=>{re==="auto"&&Gt()};xt?.addEventListener?.("change",Mn);let _t=h("div","ra-head"),dr=h("div","ra-title",T===!1?"":T||B.appName||t.assistant),ye=h("span","ra-badge"),Ae=h("button","ra-btn ghost");Ae.type="button",Ae.innerHTML=U.bug()+`<span>${xe(t.debug)}</span>`;let nt=h("button","ra-btn ghost");nt.type="button",nt.innerHTML=U.folder()+`<span>${xe(t.files)}</span>`;let Ye=h("button","ra-btn ghost");Ye.type="button",Ye.innerHTML=U.puzzle()+`<span>${xe(t.skills)}</span>`;let ft=(i,c)=>{let f=h("b","ra-cnt");return f.style.display="none",i.append(f),g=>{f.textContent=String(g),f.style.display=g?"":"none",i.title=g?`${c} \xB7 ${g}`:c}},Zt=ft(Ye,t.skills),Xe=h("button","ra-btn ghost");Xe.type="button",Xe.innerHTML=U.hist()+`<span>${xe(t.history)}</span>`;let Cn=ft(Xe,t.history),ht=h("button","ra-btn ghost");ht.type="button",ht.innerHTML=U.plus()+`<span>${xe(t.newChat)}</span>`;let ze=h("button","ra-btn ghost");ze.type="button",ze.innerHTML=U.eraser()+`<span>${xe(t.clearChat)}</span>`,ze.style.display="none";let $e=h("button","ra-btn ghost ra-usebtn");$e.type="button",$e.style.display="none";let Be=h("button","ra-btn ghost");Be.type="button",Be.innerHTML=U.gear(),Be.title=t.settings,Be.setAttribute("aria-label",t.settings);for(let[i,c]of[[Ae,t.debug],[nt,t.files],[Ye,t.skills],[Xe,t.history],[ht,t.newChat],[ze,t.clearChat]])i.setAttribute("aria-label",c),i.title||(i.title=c);for(let i of[...pe??[],...we??[],...Se?[Se]:[],...P instanceof HTMLElement?[P]:[]])i.classList.add("ra-host");_t.append(dr,ye,h("span","ra-sp"),$e,Ae,nt,Ye,Xe,ht,ze,...pe??[],Be,...we??[]),T===!1&&(_t.style.display="none");let je=h("div","ra-log"),En=h("div","ra-col");je.append(En);let An=h("div","ra-ask"),Rt=h("div","ra-col");An.append(Rt);let Xt=h("div","ra-status");Xt.style.display="none";let $n=h("div","ra-comp"),pr=h("div","ra-col"),vt=h("div","ra-alert");vt.style.display="none",vt.setAttribute("role","alert");let Ke=h("div","ra-queue");Ke.style.display="none";let Ln=h("div","ra-box"),Qe=h("div","ra-cmds");Qe.style.display="none";let S=h("textarea");S.rows=2,S.setAttribute("aria-label","Message");let q=h("div","ra-files");q.style.display="none";let oe=h("div","ra-bar"),Y=h("div","ra-left"),ae=h("button","ra-attach");ae.type="button",ae.innerHTML=U.clip(),ae.title=t.attach,ae.setAttribute("aria-label",t.attach);let me=h("input");me.type="file",me.multiple=!0,me.style.display="none",ge===!1&&(ae.style.display="none");let Ve=h("span","ra-hint"),ur=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",Dt=i=>i.replace("{mod}",ur).replace("{enter}",t.enter).replace("{newline}",t.newline);Ve.textContent=Dt(t.hintIdle);let Pn=h("div","ra-acts"),Le=h("button","ra-send");Le.type="button",Le.innerHTML=U.corner(18),Le.title=t.send,Le.setAttribute("aria-label",t.send);let Jt=h("button","ra-btn xs subtle");Jt.type="button",Jt.innerHTML=U.corner()+xe(t.steer),Jt.title=t.steerTip;let _n=h("button","ra-btn xs subtle",t.followUp);_n.type="button",_n.title=t.followUpTip;let Ot=h("button","ra-stop");Ot.type="button",Ot.innerHTML='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="2" width="12" height="12" rx="3" fill="currentColor"/></svg>',Ot.title=t.stop,Ot.setAttribute("aria-label",t.stop),Pn.append(Jt,_n,Ot,Le);let Ei=new Map,Ai=(i,c)=>{let f=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${xe(c.label)}</span>`:`<span>${xe(c.label)}</span>`;i.innerHTML=f,i.classList.toggle("icon",!!(c.icon&&c.iconOnly)),i.title=c.title??c.label,i.setAttribute("aria-label",c.label),i.style.display=c.hidden?"none":"",i.disabled=!!c.disabled},Ua=(_e??[]).map(i=>{if(i instanceof HTMLElement)return i.classList.add("ra-host"),i;let c={...i},f=h("button","ra-cbtn");return f.type="button",f.addEventListener("click",()=>c.onClick()),Ai(f,c),c.id&&Ei.set(c.id,{btn:f,a:c}),f});Y.append(ae,...Ua,Ve),oe.append(Y,Pn),Ln.append(Qe,q,S,oe,me);let Ia=h("div","ra-drop",t.drop);pr.append(vt,Ke,...Se?[Se]:[],Ln),$n.append(pr);let $i=h("div","ra-toasts"),Li=h("div","ra-col");Li.append(Xt);let fr=h("div","ra-main"),bs=h("div","ra-chatcol"),Pi=h("div","ra-jumpwrap"),gt=h("button","ra-jump");gt.type="button",gt.innerHTML=U.arrowDown(),gt.title=t.jumpEnd,gt.setAttribute("aria-label",t.jumpEnd),gt.tabIndex=-1,Pi.append(gt),bs.append(je,Pi,An,Li,$n),fr.append(bs),j.append(_t,fr,$i,Ia),r.replaceChildren(j);let F,be=new wn(je,En,{estimate:96,overscan:400,rowClass:"ra-row",onFollow:i=>{let c=!i&&je.scrollHeight-je.clientHeight>40;gt.classList.toggle("show",c),gt.tabIndex=c?0:-1}});gt.addEventListener("click",()=>be.scrollToBottom()),je.addEventListener("click",i=>{let c=i.target.closest("summary");c&&je.contains(c)&&be.pin(c)},!0);let X=null,kt=null,Yt=new Map,xs=new WeakMap,Rn=new Map,hr=[],rt=0,Dn=null,On=[],Te=null,gr=!0,_i=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{j.dataset.short=j.clientHeight&&j.clientHeight<420?"1":""});_i?.observe(j);let Ri=0,Z=Yc(Rt,$i,t,()=>{let i=Rt.childElementCount;j.dataset.asking=i?"1":"",i<Ri?be.scrollToBottom():be.schedule(),Ri=i}),Fa=3,We=new Map,mr=new Map,zn=new Map,zt=new Set,Tt=new Map,vs=(i,c)=>new Promise(f=>{if(F?.id===i){f(!0);return}if(c?.aborted){f(!1);return}zt.add(i);let g=Tt.get(i)??[],m=v=>{c?.removeEventListener("abort",y),f(v)},y=()=>{let v=Tt.get(i);if(v){let k=v.indexOf(m);k>=0&&v.splice(k,1),v.length||(Tt.delete(i),zt.delete(i))}m(!1),Ut()};c?.addEventListener("abort",y,{once:!0}),g.push(m),Tt.set(i,g),Ut()}),ks=(i,c=!0)=>{let f=Tt.get(i);Tt.delete(i),zt.delete(i),f?.forEach(g=>g(c))},Ha=i=>({confirm:async(c,f,g)=>await vs(i,g?.signal)?Z.confirm(c,f,g):!1,select:async(c,f,g)=>await vs(i,g?.signal)?Z.select(c,f,g):null,input:async(c,f)=>await vs(i,f?.signal)?Z.input(c,f):null,notify:(c,f)=>Z.notify(c,f)}),Di=i=>!!i.workspace&&typeof l=="function"&&!i.workspace.root,Ts=()=>[...We.values()].filter(i=>i!==F&&(i.busy||i.queued.length>0||zt.has(i.id))),yr=i=>{let c=Bt({v:2,id:i.id,messages:i.messages,usage:i.usage,droppedTurns:0,savedAt:0});return c===$t?t.untitled:c.length>40?c.slice(0,37)+"\u2026":c},Ut=()=>Xe.classList.toggle("ra-bg",Ts().length>0),Qt=null,Ss=()=>{Qt&&clearTimeout(Qt),Qt=setTimeout(async()=>{Qt=null;let i=F?.workspace;if(!i||a){Cn(0);return}try{let f=(await i.sessions.list()).filter(g=>g.id!==F.id).length;F?.workspace===i&&Cn(f?f+1:0)}catch{}},50)},Oi=async(i,c)=>{let f=Tn(c);if(!(!i.workspace||!f)){if(I)try{await jc(i.workspace,f,await I.take())}catch(g){console.warn("agent: rewindState.take failed",g)}if(Di(i))try{await Fc(i.workspace,f)}catch(g){console.warn("agent: checkpoint failed",g)}}},ja=i=>{if(mr.has(i.id))return;let c=[];c.push(i.on("run_end",()=>{F!==i&&(Z.notify(`${yr(i)} \xB7 ${t.finished}`),setTimeout(()=>{gr&&(F!==i&&!i.busy&&!i.queued.length&&!zt.has(i.id)&&(We.delete(i.id),wr(i),Dr(i)),Ut())},50))})),c.push(i.on("run_start",f=>{Ut(),f.message&&Oi(i,f.message)})),mr.set(i.id,c),Ut()},wr=i=>{mr.get(i.id)?.forEach(c=>c()),mr.delete(i.id)},Ne=ma({t,root:j,editorHost:bs,notify:(i,c)=>Z.notify(i,c),onChange:()=>{Ct()},onShow:i=>nt.classList.toggle("on",i)});fr.append(Ne.el);let et=ya({t,root:j,onShow:i=>Ae.classList.toggle("on",i)});fr.append(et.el);let It=!!x,br=()=>{if(Ae.style.display=It?"":"none",j.dataset.debug=It?"1":"",It){for(let i of We.values())i!==F&&et.setAgent(i);F&&et.setAgent(F)}else{et.close();for(let i of We.values())et.forget(i)}};br(),nt.addEventListener("click",()=>{et.visible&&(et.close(),br()),Ne.toggle()}),Ae.addEventListener("click",async()=>{Ne.visible&&await Ne.close(),!Ne.visible&&(et.toggle(),br())});let Un=i=>{ee?ee(i):Ne.open(i)},zi=async i=>{let c=F?.workspace;if(c&&!await c.exists(i)){Z.notify(`${t.rewindGoneFile.replace("{path}",i)}`,"warning");return}Un(i)},mt=h("div","ra-empty"),Ms={render:()=>mt},Ui=()=>{if(P!==null){if(mt.replaceChildren(),mt.classList.toggle("start",typeof P=="object"&&!(P instanceof HTMLElement)&&P?.align==="start"),P instanceof HTMLElement)mt.append(P);else if(P&&typeof P=="object"){if(P.icon){let i=h("div","ra-empty-icon");typeof P.icon=="string"?i.innerHTML=P.icon:i.append(P.icon),mt.append(i)}P.title&&mt.append(h("h3","ra-empty-title",P.title)),P.text&&mt.append(h("p","ra-empty-text",P.text))}else mt.append(h("div","",typeof P=="string"?P:t.empty));if(_?.length){let i=h("div","ra-sugs");for(let c of _){let f=typeof c=="string"?c:c.label,g=typeof c=="string"?c:c.prompt,m=h("button","",f);m.type="button",g!==f&&(m.title=g),m.addEventListener("click",()=>{S.value=g,S.focus(),Ge()}),i.append(m)}mt.append(i)}be.rows.includes(Ms)||be.push(Ms)}},Na=()=>be.remove(Ms),St=i=>{Na(),be.push(i)},Ii=(i,c,f)=>{let g=h("span","ra-chip"),m=i.lastIndexOf("."),y=m>0&&i.length-m<=6?i.slice(m):"";if(f){let k=h("img");k.src=f,k.alt="",g.append(k)}else g.append(h("span","ra-ext",(y.slice(1)||"file").slice(0,4)));let v=h("span","ra-cn");return v.title=i,v.append(h("span","st",y?i.slice(0,m):i)),y&&v.append(h("span","ex",y)),g.append(v),c&&g.append(h("small","",c.replace(/\s+(?=[KMG]?B$)/,""))),g},Fi=(i,c,f)=>{let g=h("span","ra-chip ra-ctx"),m=h("span","ra-ctxi");m.innerHTML=f??U.pointer(15);let y=h("span","ra-cn");return y.title=c??i,y.append(h("span","st",i)),g.append(m,y),g},Hi=i=>fs(i).flatMap(c=>c.startsWith(Sn)?[{label:c.slice(Sn.length).split(`
|
|
708
708
|
`)[0],text:c.includes(`
|
|
709
709
|
`)?c.slice(c.indexOf(`
|
|
710
710
|
`)+1):""}]:[]),qa=(i,c)=>{let f=h("div","ra-user"),g=h("div","ra-bubble"),m=fs(i),y=c.text;g.textContent=y.length>4e3?y.slice(0,4e3)+"\u2026":y;let v=m.find(W=>W.startsWith(Pt));if(v){let W=h("div","ra-files");for(let Q of v.split(`
|
|
711
|
-
`).slice(1)){let ne=Ma(Q);if(!ne)continue;let he=Ii(ne.ref.replace(/^.*\//,""),ne.size,null);if(ne.ref.startsWith("/")){let Ie=ne.ref;he.classList.add("ra-chip-link"),he.title=`${t.open} ${Ie}`,he.setAttribute("role","button"),he.tabIndex=0,he.addEventListener("click",()=>{zi(Ie)}),he.addEventListener("keydown",At=>{At.key==="Enter"&&zi(Ie)})}W.append(he)}W.childElementCount&&g.append(W)}let k=
|
|
712
|
-
`),update:()=>{},render:()=>qa(i,y)};return y},yt=null,xr=(i,c)=>{Vi(Tn(c)??Date.now());let f=Cs(i,c);return St(f),be.scrollToBottom(),f},Ba=async(i,c,f={title:t.rewindTitle,message:t.rewindMsg,ok:t.rewind})=>{let g=h("input");g.type="checkbox",g.checked=!!i;let m=h("input");m.type="checkbox",m.checked=!0;let y=[];if(c&&I){let k=h("label","ra-ck");k.append(m,h("span","",I.label)),y.push(k)}if(i){let k=h("label","ra-ck");k.append(g,h("span","",t.rewindFiles));let L=i.files.reduce((E,$)=>E+(typeof $.data=="string"?new TextEncoder().encode($.data).length:$.data.byteLength),0);y.push(k,h("div","ra-dn",t.rewindSnapshot.replace("{n}",String(i.files.length)).replace("{size}",kn(L)).replace("{time}",Pa(i.at))+(i.partial?` ${t.rewindPartial}`:"")))}return await ds(
|
|
711
|
+
`).slice(1)){let ne=Ma(Q);if(!ne)continue;let he=Ii(ne.ref.replace(/^.*\//,""),ne.size,null);if(ne.ref.startsWith("/")){let Ie=ne.ref;he.classList.add("ra-chip-link"),he.title=`${t.open} ${Ie}`,he.setAttribute("role","button"),he.tabIndex=0,he.addEventListener("click",()=>{zi(Ie)}),he.addEventListener("keydown",At=>{At.key==="Enter"&&zi(Ie)})}W.append(he)}W.childElementCount&&g.append(W)}let k=Hi(i);if(k.length){let W=h("div","ra-files");for(let Q of k)W.append(Fi(Q.label));g.append(W)}for(let W of _s(i)){let Q=h("img");Q.src=W,Q.alt="",g.append(Q)}let L=h("div","ra-uf"),E=h("span","ra-ut"),$=h("button","ra-ib");$.type="button",$.innerHTML=U.copy(13),$.title=t.copy,$.setAttribute("aria-label",t.copy),$.addEventListener("click",()=>{navigator.clipboard?.writeText(c.text).then(()=>Z.notify(t.copied))});let D=h("button","ra-ib");return D.type="button",D.innerHTML=U.undo(),D.title=t.rewind,D.setAttribute("aria-label",t.rewind),D.addEventListener("click",()=>{Wa(c)}),L.append(E,$,D),f.addEventListener("mouseenter",()=>c.update()),c.update=()=>{let W=Tn(c.msg);E.innerHTML=U.checks()+`<span>${xe(W?Uc(W,t):t.sent)}</span>`,D.disabled=!c.msg},c.update(),f.append(g,L),f},Cs=(i,c)=>{let g=fs(i).filter(v=>!v.startsWith(Pt)&&!v.startsWith(Sn)&&!v.startsWith("<file name=")),m=Gc(c),y={msg:c,text:m??g.join(`
|
|
712
|
+
`),update:()=>{},render:()=>qa(i,y)};return y},yt=null,xr=(i,c)=>{Vi(Tn(c)??Date.now());let f=Cs(i,c);return St(f),be.scrollToBottom(),f},Ba=async(i,c,f={title:t.rewindTitle,message:t.rewindMsg,ok:t.rewind})=>{let g=h("input");g.type="checkbox",g.checked=!!i;let m=h("input");m.type="checkbox",m.checked=!0;let y=[];if(c&&I){let k=h("label","ra-ck");k.append(m,h("span","",I.label)),y.push(k)}if(i){let k=h("label","ra-ck");k.append(g,h("span","",t.rewindFiles));let L=i.files.reduce((E,$)=>E+(typeof $.data=="string"?new TextEncoder().encode($.data).length:$.data.byteLength),0);y.push(k,h("div","ra-dn",t.rewindSnapshot.replace("{n}",String(i.files.length)).replace("{size}",kn(L)).replace("{time}",Pa(i.at))+(i.partial?` ${t.rewindPartial}`:"")))}return await ds(j,{title:f.title,message:f.message,body:y,ok:f.ok,cancel:t.cancel,focus:"ok"})?{files:!!i&&g.checked,host:!!c&&m.checked}:null},Wa=i=>i.msg?ji(i.msg,i.text):Promise.resolve(),ji=async(i,c,f=!1)=>{if(!F)return;let g=F,m={msg:i,text:c},y=g.messages.indexOf(m.msg);if(y<0){Z.notify(t.rewindGone,"warning");return}let v=g.workspace,k=Tn(m.msg),L=v&&k&&Di(g)?await v.getData(hs(k)):void 0,E=v&&k&&I?await v.getData(ms(k)):void 0,$=await Ba(L,E,f?{title:t.regenTitle,message:t.regenMsg,ok:t.regen}:void 0);if(!$||F!==g)return;let D=!1;try{if(g.busy&&(Z.cancelAll(),await g.abort()),await g.rewind(y),D=!0,$.files&&v&&L)try{await qc(v,L)}catch(W){Z.notify(W.message,"error")}if($.host&&E&&I)try{await I.restore(E.value)}catch(W){Z.notify(W.message,"error")}v&&k&&(Hc(v,k).catch(()=>{}),Nc(v,k).catch(()=>{}))}catch(W){Z.notify(W.message,"error")}finally{F===g&&(Mr(g.messages),Et(g),Ne.refresh(),Ct())}!D||F!==g||(S.value=m.text,S.focus(),Ge(),await Ka(m.msg),f&&await nn("prompt"))},Ni=i=>i.role==="user"&&!(typeof i.content=="string"&&(Ze(i)!==null||i.content.startsWith("[environment]"))),vr=(i,c)=>{let f=i.messages,g=f.indexOf(c);if(g<0)return null;let m=g;for(;m>=0&&!Ni(f[m]);)m--;let y=g+1;for(;y<f.length&&!Ni(f[y]);)y++;return m<0?null:{start:m,end:y}},qi=i=>{let c=h("div","ra-af"),f=(k,L,E)=>{let $=h("button","ra-ib");return $.type="button",$.innerHTML=k,$.title=L,$.setAttribute("aria-label",L),$.addEventListener("click",E),$},g=f(U.copy(13),t.copy,()=>{let k=F,L=k&&vr(k,i),E=L?k.messages.slice(L.start+1,L.end).filter($=>$.role==="assistant").map($=>vn($.content).trim()).filter(Boolean):[vn(i.content).trim()];navigator.clipboard?.writeText(E.at(-1)??"").then(()=>Z.notify(t.copied))}),m=f(U.refresh(13),t.regen,()=>{let k=F,L=k&&vr(k,i);if(!k||!L){Z.notify(t.rewindGone,"warning");return}let E=k.messages[L.start];ji(E,Cs(E.content,E).text,!0)}),y=f(U.trash(13),t.delTurn,()=>{(async()=>{let k=F;if(!k||!vr(k,i)){Z.notify(t.rewindGone,"warning");return}if(!await ut(j,t.delTurnTitle,t.delTurnMsg,{danger:!0,ok:t.delTurn,cancel:t.cancel}))return;let L=F===k?vr(k,i):null;if(L)try{k.busy&&(Z.cancelAll(),await k.abort()),await k.remove(L.start,L.end)}catch(E){Z.notify(E.message,"error")}})()});c.append(g,m,y);let v=i.runUsage;if(v&&v.calls){let k=$=>{L.textContent=t.replyCost.replace("{cost}",Ti(v.total_cost,$))},L=h("span","ra-cost");k(Rr);let E=F;Rr===void 0&&E&&E.modelInfo().then($=>{$?.price?.currency&&k($.price.currency)}).catch(()=>{}),L.title=t.replyUsage.replace("{in}",Je(v.prompt_tokens)).replace("{out}",Je(v.completion_tokens)).replace("{calls}",String(v.calls)),c.append(L)}return c},Ka=async i=>{if(typeof i.content!="string"&&!Array.isArray(i.content))return;let c=Array.isArray(i.content)?i.content:fs(i.content).map(E=>({type:"text",text:E}));for(let E of Hi(c).reverse())so({label:E.label,text:E.text});let f=c.find(E=>E.type==="text"&&E.text.startsWith(Pt));if(!f)return;let g=F?.workspace,m=new Map;for(let E of c)if(E.type==="text"){let $=/^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec(E.text);$&&m.set($[1],$[2])}let y=c.flatMap(E=>E.type==="image_url"&&E.image_url.url.startsWith("data:")?[E.image_url.url]:[]),v=[],k=[],L=[];for(let E of f.text.split(`
|
|
713
713
|
`).slice(1)){let $=Ma(E);if(!$)continue;let{ref:D,type:W}=$,Q=D.replace(/^.*\//,"");if(D.startsWith("/")&&g)try{let ne=await g.read(D);v.push(new File([ne.data],Q,{type:ne.contentType||W})),k.push(D)}catch{L.push(D)}else if(m.has(Q))v.push(new File([m.get(Q)],Q,{type:W})),k.push(void 0);else if(/^image\//.test(W)&&y.length){let ne=await(await fetch(y.shift())).blob();v.push(new File([ne],Q,{type:W})),k.push(void 0)}else L.push(Q)}v.length&&await Er(v,k),L.length&&Z.notify(t.rewindGoneFile.replace("{path}",L.join(", ")),"warning")},Bi=()=>{let i=h("div","ra-asst"),c=h("div","ra-body");return i.append(c),{render:()=>i,el:i,body:c,text:null,think:null,thinkBody:null,md:"",reasoning:""}},Va=i=>{let c=Math.max(1,Math.round(i/1e3));return c<60?t.sec.replace("{s}",String(c)):c<3600?t.minSec.replace("{m}",String(Math.floor(c/60))).replace("{s}",String(c%60)):t.hourMin.replace("{h}",String(Math.floor(c/3600))).replace("{m}",String(Math.floor(c%3600/60)))},Wi=(i,c)=>{if(i.querySelector(":scope>.ra-work"))return;let f=Array.from(i.children),m=f.at(-1)?.classList.contains("ra-md")?f.slice(0,-1):f;if(!m.length)return;let y=h("details","ra-work"),v=h("summary");v.append(h("span","",c!==void 0&&c>0?t.worked.replace("{t}",Va(c)):t.workedNoTime));let k=h("span","ra-chev");k.innerHTML=U.chev(13),v.append(k),v.addEventListener("click",()=>be.pin(v));let L=h("div","ra-wb");L.append(...m),y.append(v,L),i.prepend(y)},In=0,kr=()=>{if(X){if(As(X),!X.body.childElementCount){be.remove(X),X=null;return}Fn(!0),Wi(X.body,In?Date.now()-In:void 0),X=null,be.schedule()}},Tr=()=>(X||(X=Bi(),St(X)),X),st=(i=t.waiting,c)=>{let f=Tr();f.pending||(f.pending=h("div","ra-pending"),f.pending.append(h("span","",i)));let g=f.pending;g.firstElementChild.textContent=i;let m=g.querySelector(".ra-lpv"),y=c?.text.trim()??"";y?(m||(m=h("div","ra-lpv"),m.append(h("div")),g.append(m)),m.className="ra-lpv"+(c.code?" code":"")+(c.head?" head":""),m.firstElementChild.textContent=c.head?y.slice(0,600):y.slice(-600)):m?.remove(),f.body.lastElementChild!==g&&f.body.append(g),be.schedule()},Ki=i=>{let c=i.lastElementChild;return c?.classList.contains("ra-pending")?c.previousElementSibling:c},Es=(i,c)=>{let f=i.lastElementChild;f?.classList.contains("ra-pending")?i.insertBefore(c,f):i.append(c)},Ga=(i,c)=>{let f=c&&typeof c=="object"?c:{};return i==="run_js"&&typeof f.code=="string"?{text:f.code,code:!0,head:!0}:i==="write_file"&&typeof f.content=="string"?{text:f.content,head:!0}:i==="edit_file"&&Array.isArray(f.edits)?{text:f.edits.map(g=>g&&typeof g=="object"?String(g.newText??""):"").join(`
|
|
714
714
|
\u2026
|
|
715
|
-
`),head:!0}:i==="edit_file"&&typeof f.newText=="string"?{text:f.newText,head:!0}:{text:ki(i,c),head:!0}},As=(i=X)=>{i?.pending&&(i.pending.remove(),i.pending=null)},Za=15*6e4,en=0,Xa=i=>{let c=new Date(i),f=new Date,g=c.toLocaleTimeString(n==="zh"?"zh-CN":void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}),m=k=>new Date(k.getFullYear(),k.getMonth(),k.getDate()).getTime(),y=Math.round((m(f)-m(c))/864e5);return y===0?`${t.today} ${g}`:y===1?`${t.yesterday} ${g}`:`${c.toLocaleDateString(n==="zh"?"zh-CN":void 0,c.getFullYear()===f.getFullYear()?{month:"short",day:"numeric"}:{year:"numeric",month:"short",day:"numeric"})} ${g}`},Vi=i=>{if(i){if(!en||i-en>=Za){let c=h("div","ra-time",Xa(i));St({render:()=>c,el:c})}en=i}},Gi=(i,c)=>{let f=h("details","ra-think"),g=h("summary");g.innerHTML=`<span class="ra-chev">${U.chev(13)}</span>${U.brain()}<span>${xe(c?t.thought:t.thinking)}</span>`;let m=h("div","ra-think-body",i);return f.append(g,m),[f,m]},Zi=i=>{let c=F?.workspace;if(c)for(let f of Array.from(i.querySelectorAll("code"))){if(f.closest("pre")||f.classList.contains("ra-path"))continue;let g=f.textContent?.trim()??"";!/^\/[^\s`'"<>]+$/.test(g)||g.length>200||c.exists(g).then(m=>{m&&!f.classList.contains("ra-path")&&(f.classList.add("ra-path"),f.dataset.path=g,f.title=t.open,f.insertAdjacentHTML("beforeend",U.download(11)))})}},Ja=(i,c)=>{bn(i,c,!1),Zi(i)},Fn=i=>{kt!==null&&(clearTimeout(kt),kt=null),X&&(X.text&&(X.drawn!==X.md||X.drawnFinal!==i)&&(bn(X.text,X.md,!i),X.drawn=X.md,X.drawnFinal=i,i&&Zi(X.text)),X.thinkBody&&(X.thinkBody.textContent=X.reasoning),X.think&&i?(X.think.querySelector("summary span:last-child").textContent=t.thought,X.think.style.display=""):X.pending&&X.reasoning&&!X.text&&st(t.thinking.replace(/…$/,""),{text:X.reasoning}),be.schedule())},Xi=()=>{kt===null&&(kt=window.setTimeout(()=>{kt=null,Fn(!1)},100))},Sr=i=>F?.tools?.find(c=>c.name===i)?.display,$s=i=>{if(i)try{return i()}catch{return}},Ls=(i,c)=>{let f=Sr(i),g=$s(f?.label&&(()=>f.label(c)));return typeof g=="string"&&g.trim()?g:void 0},Ji=(i,c)=>{let f=Sr(i.name);if(!f?.render)return;let g=$s(()=>f.render({args:i.args,...c})),m=i.el.querySelector("summary");if(m.querySelector(".ra-tx")?.remove(),!(g instanceof HTMLElement))return;let y=h("div","ra-tx ra-host");y.addEventListener("click",v=>v.preventDefault()),y.append(g),m.append(y)},Yi=(i,c)=>{let f=h("details","ra-tool");xs.set(f,{name:i,args:c});let g=h("summary"),m=Sr(i),y=Ls(i,c),v=h("span","ra-ticon");v.innerHTML=m?.icon??(Oc[i]??U.wrench)();let k=h("span","ra-tend");k.innerHTML='<span class="ra-spin"></span>',g.innerHTML=`<span class="ra-chev">${U.chev()}</span>`;let L=h("span","ra-tname",y??i);y&&(L.title=i,L.classList.add("own")),g.append(v,L,h("span","ra-tsum",y?"":ki(i,c)),k);let E=h("div","ra-tbody"),$=h("pre","",i==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));E.append(h("div","ra-tlabel",t.args),$);let D=c&&typeof c=="object"&&typeof c.path=="string"?c.path:null;if(D&&i!=="delete_file"&&i!=="list_files"&&i!=="search_files"){let Q=h("div","ra-tacts"),ne=h("button","ra-open",`${t.open} ${D}`);ne.type="button",ne.addEventListener("click",()=>Un(D));let he=h("button","ra-open",t.download);he.type="button",he.addEventListener("click",()=>{Ne.download(D)}),Q.append(ne,he),E.append(Q)}f.append(g,E);let W={el:f,name:i,args:c,end:k,body:E,update:null,result:null};return Ji(W,{status:"running"}),W},Qi=i=>{let c=Ki(i);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let f=h("details","ra-tg"),g=h("summary"),m=h("div","ra-tgb");return f.append(g,m),Es(i,f),m},Ya=i=>{let c=[],f=new Map;for(let g of i){let m=Ls(g.name,g.args);if(m!==void 0){let L=`Own:${m}`;f.has(L)||(c.push(L),f.set(L,0)),f.set(L,f.get(L)+1);continue}let y=Ta[g.name]??"Other",v=y==="Other"?`Other:${g.name}`:y;f.has(v)||(c.push(v),f.set(v,y==="Read"||y==="Write"||y==="Edit"||y==="Delete"?new Set:0));let k=f.get(v);k instanceof Set?k.add(Sa(g.args)??String(k.size)):f.set(v,k+1)}return c.map(g=>{let m=f.get(g),y=String(m instanceof Set?m.size:m);return g.startsWith("Own:")?m===1?g.slice(4):`${g.slice(4)} \xD7${y}`:g.startsWith("Other:")?t.actOther.replace("{name}",g.slice(6)):t[`act${g}`].replace("{n}",y)}).join(n==="zh"?"\uFF0C":", ")},eo=(i,c)=>{let f=Ls(i.name,i.args);if(f!==void 0)return{verb:f,what:""};let g=Ta[i.name]??"Other",m=Sa(i.args),y=t[`ing${g}`];return g==="Other"?{verb:`${y} ${i.name}`,what:c.querySelector(".ra-tsum")?.textContent??""}:g==="Ask"?{verb:y,what:""}:m&&g!=="Search"?{verb:y,what:m.slice(m.lastIndexOf("/")+1)||m,title:m}:{verb:y,what:c.querySelector(".ra-tsum")?.textContent??""}},Ps=i=>{let c=i.closest(".ra-tg");if(!c)return;let f=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),g=f.filter(k=>k.querySelector(".ra-tend .ra-spin")),m=f.filter(k=>k.classList.contains("fail")).length,y=c.querySelector("summary");if(y.replaceChildren(),g.length){let k=g[g.length-1],L=eo(xs.get(k)??{name:k.querySelector(".ra-tname")?.textContent??"",args:void 0},k);y.append(h("span","ra-spin"));let E=h("span","ra-tgt");E.append(`${L.verb} `),L.what&&E.append(h("code","",L.what)),L.title&&(E.title=L.title),y.append(E)}else{let k=f.map($=>xs.get($)).filter($=>!!$),L=k.length?Ya(k):f.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(f.length)),E=h("span","ra-tgt",L);E.title=f.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(f.length)),y.append(E)}m&&y.append(h("span","ra-tgf",t.toolsFailed.replace("{n}",String(m))));let v=h("span","ra-chev");v.innerHTML=U.chev(12),y.append(v)},Qa=(i,c,f,g)=>{let m=Yi(c,f);return Qi(g).append(m.el),Yt.set(i,m),Ps(m.el),be.schedule(),m},_s=i=>Array.isArray(i)?i.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:)/.test(c.image_url.url)?[c.image_url.url]:[]):[],to=(i,c,f,g,m=[],y)=>{let v=c==="ok",k=c==="error"||c==="blocked";i.end.replaceChildren();let L=Sr(i.name),E=$s(L?.outcome&&(()=>L.outcome({args:i.args,status:c,result:f,details:y})));typeof E=="string"&&E?i.end.append(h("span","ra-tout",E)):g!==void 0&&i.end.append(h("span","",`${Math.round(g)}ms`));let $=h("span",v?"ok":k?"fail":"");v?$.innerHTML=U.check():c==="error"?$.innerHTML=U.xcircle():c==="blocked"?($.innerHTML=U.ban(),$.title=t.blocked):$.textContent=t[c]??c,i.end.append($),i.el.classList.toggle("fail",k),Ji(i,{status:c,result:f,details:y}),i.update?.remove(),i.result||(i.result=h("pre",""),i.body.append(h("div","ra-tlabel",c==="error"?t.error:t.result),i.result));let D=m.length?f.replace(/^\[image_url\]$/gm,"").trim():f;if(i.result.textContent=D.length>2e4?D.slice(0,2e4)+"\u2026":D||t.emptyResult,m.length&&!i.body.querySelector(".ra-timgs")){let W=h("div","ra-timgs");for(let Q of m.slice(0,4)){let ne=h("img");ne.src=Q,ne.alt=t.result,ne.addEventListener("load",()=>be.schedule()),W.append(ne)}i.body.append(W)}Ps(i.el),be.schedule()},el=(i,c,f)=>{let g=h("div","ra-card"),m=h("div","ra-ct"+(c?"":" only"));if(m.innerHTML=U.layers()+`<span>${xe(i)}</span>`,g.append(m),c){let y=h("div","ra-md");bn(y,c,!1),g.append(y)}if(f){let y=h("button","ra-btn xs subtle",f.label);y.type="button",y.addEventListener("click",()=>{y.disabled=!0,f.onClick()}),g.append(y)}return g},jn=(i,c,f)=>{St({render:()=>el(i,c,f)}),be.schedule()},tl=(i,c,f)=>{let g={render:()=>{let m=h("div","ra-warn");if(m.setAttribute("role","status"),f&&(m.title=f),m.innerHTML=U.alert(14),m.append(h("span","",i)),c){let y=h("button","ra-btn xs",c.label);y.type="button",y.addEventListener("click",()=>{be.remove(g),c.onClick()}),m.append(y)}return m}};St(g),be.schedule()},Rs=(i,c)=>{let f={render:()=>{let g=h("div","ra-err",i);if(c){let m=h("button","ra-btn xs red-subtle",t.retry);m.type="button",m.addEventListener("click",()=>{be.remove(f),c()}),g.append(m)}return g}};St(f),be.schedule()},Mr=i=>{be.clear(),en=0,Yt.clear(),Rn.clear(),X=null;let c=null,f,g=(m=!1)=>{if(!c)return;let y=c;c=null;let v=!(m&&F?.busy);St({render:()=>{let k=Bi();for(let L of y.items)if(L.kind==="think"){let[E]=Gi(L.text,!0),$=k.body.lastElementChild;$ instanceof HTMLDetailsElement&&$.classList.contains("ra-tg")?$.querySelector(".ra-tgb").append(E):k.body.append(E)}else if(L.kind==="text"){let E=h("div","ra-md");Ja(E,L.text),k.body.append(E)}else{let E=L.call,$=Yi(E.name,E.args);Qi(k.body).append($.el),E.status?to($,E.status,E.result??"",void 0,E.images):(E.id&&Yt.set(E.id,$),Ps($.el))}return v&&Wi(k.body,y.start!==void 0&&y.end!==void 0?y.end-y.start:void 0),v&&y.msg&&k.el.append(qi(y.msg)),k.el}})};for(let m of i)if(m.role==="user"){g();let y=typeof m.content=="string"?Ze(m):null;if(y!==null){jn(t.compacted,y);continue}if(typeof m.content=="string"&&m.content.startsWith("[environment]"))continue;f=Tn(m),Vi(f),St(Cs(m.content,m))}else if(m.role==="assistant"){let y=vn(m.content),v=m.reasoning_content,k=typeof v=="string"?v:"";c||(c={items:[],calls:[],start:f}),c.msg=m,c.end=Tn(m)??c.end,c.end&&(en=c.end),k&&c.items.push({kind:"think",text:k}),y&&c.items.push({kind:"text",text:y});for(let L of m.tool_calls??[]){if(Ds.has(L.function.name))continue;let E=L.function.arguments;try{E=JSON.parse(L.function.arguments)}catch{}let $={id:L.id??"",name:L.function.name,args:E};c.items.push({kind:"call",call:$}),c.calls.push($),$.id&&Rn.set($.id,$)}}else if(m.role==="tool"){let y=vn(m.content),v=c?.calls.find(k=>k.id===(m.tool_call_id??""));v&&(v.result=y,v.status=zc(y),v.images=_s(m.content),Rn.delete(v.id))}g(!0),i.length||Ui(),be.scrollToBottom()},Mt=null,Cr=null,Hn=()=>{Cr=null,Mt!==null&&(Mt=null,Ft(H.dataset.busy==="1"))},nl={name:"suggest_next_prompt",description:`Offer the user their likely next message: it appears greyed in their input box and Tab sends it there. Call it only in the same reply as your final answer, after writing the answer, and only when an obvious next request follows (after writing a strategy: "Backtest it over the last year"). Write it as the user would type it \u2014 in the user's language, one short sentence, a request to you, nothing you already did. When no next step is clear, do not call it.`,parameters:{type:"object",properties:{text:{type:"string",description:"The suggested message, as the user would type it"}},required:["text"],additionalProperties:!1},readOnly:!0,endsRun:!0,display:{hidden:!0},execute:({text:i})=>(Cr=String(i??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},no=[...B.tools??[],...G?[nl]:[]],Ds=new Set(no.filter(i=>i.display?.hidden).map(i=>i.name)),Nn=()=>{let i=H.dataset.busy==="1",c=!!(T.value.trim()||ot.length||at.length);Le.style.display=!i&&c?"":"none",Jt.style.display=_n.style.display=i&&c?"":"none"},Ft=i=>{H.dataset.busy=i?"1":"",T.placeholder=i?Dt(t.placeholderBusy):Mt??A??t.placeholder,Ve.textContent=Dt(i?t.hintBusy:Mt?t.hintNext:t.hintIdle),Nn(),Ot.style.display=i?"":"none",it()},jt=!1,it=()=>{let i=F?.queued??[];if(Ke.style.display=i.length?"":"none",Ke.replaceChildren(),!i.length){jt=!1;return}let c=F,f=E=>vn(E.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),g=(E,$,D)=>{let W=h("button");return W.type="button",W.innerHTML=E,W.title=$,W.setAttribute("aria-label",$),W.addEventListener("click",Q=>{Q.stopPropagation(),D()}),W},m=E=>{let $=h("span","ra-qa");return E.kind!=="steer"&&$.append(g(U.enter(),t.sendNow,()=>{c.dequeue(E.message)&&c.steer(E.message.content),it()})),$.append(g(U.pen(),t.editQueued,()=>{c.dequeue(E.message)&&(T.value=T.value.trim()?`${f(E.message)}
|
|
716
|
-
${
|
|
715
|
+
`),head:!0}:i==="edit_file"&&typeof f.newText=="string"?{text:f.newText,head:!0}:{text:ki(i,c),head:!0}},As=(i=X)=>{i?.pending&&(i.pending.remove(),i.pending=null)},Za=15*6e4,en=0,Xa=i=>{let c=new Date(i),f=new Date,g=c.toLocaleTimeString(n==="zh"?"zh-CN":void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}),m=k=>new Date(k.getFullYear(),k.getMonth(),k.getDate()).getTime(),y=Math.round((m(f)-m(c))/864e5);return y===0?`${t.today} ${g}`:y===1?`${t.yesterday} ${g}`:`${c.toLocaleDateString(n==="zh"?"zh-CN":void 0,c.getFullYear()===f.getFullYear()?{month:"short",day:"numeric"}:{year:"numeric",month:"short",day:"numeric"})} ${g}`},Vi=i=>{if(i){if(!en||i-en>=Za){let c=h("div","ra-time",Xa(i));St({render:()=>c,el:c})}en=i}},Gi=(i,c)=>{let f=h("details","ra-think"),g=h("summary");g.innerHTML=`<span class="ra-chev">${U.chev(13)}</span>${U.brain()}<span>${xe(c?t.thought:t.thinking)}</span>`;let m=h("div","ra-think-body",i);return f.append(g,m),[f,m]},Zi=i=>{let c=F?.workspace;if(c)for(let f of Array.from(i.querySelectorAll("code"))){if(f.closest("pre")||f.classList.contains("ra-path"))continue;let g=f.textContent?.trim()??"";!/^\/[^\s`'"<>]+$/.test(g)||g.length>200||c.exists(g).then(m=>{m&&!f.classList.contains("ra-path")&&(f.classList.add("ra-path"),f.dataset.path=g,f.title=t.open,f.insertAdjacentHTML("beforeend",U.download(11)))})}},Ja=(i,c)=>{bn(i,c,!1),Zi(i)},Fn=i=>{kt!==null&&(clearTimeout(kt),kt=null),X&&(X.text&&(X.drawn!==X.md||X.drawnFinal!==i)&&(bn(X.text,X.md,!i),X.drawn=X.md,X.drawnFinal=i,i&&Zi(X.text)),X.thinkBody&&(X.thinkBody.textContent=X.reasoning),X.think&&i?(X.think.querySelector("summary span:last-child").textContent=t.thought,X.think.style.display=""):X.pending&&X.reasoning&&!X.text&&st(t.thinking.replace(/…$/,""),{text:X.reasoning}),be.schedule())},Xi=()=>{kt===null&&(kt=window.setTimeout(()=>{kt=null,Fn(!1)},100))},Sr=i=>F?.tools?.find(c=>c.name===i)?.display,$s=i=>{if(i)try{return i()}catch{return}},Ls=(i,c)=>{let f=Sr(i),g=$s(f?.label&&(()=>f.label(c)));return typeof g=="string"&&g.trim()?g:void 0},Ji=(i,c)=>{let f=Sr(i.name);if(!f?.render)return;let g=$s(()=>f.render({args:i.args,...c})),m=i.el.querySelector("summary");if(m.querySelector(".ra-tx")?.remove(),!(g instanceof HTMLElement))return;let y=h("div","ra-tx ra-host");y.addEventListener("click",v=>v.preventDefault()),y.append(g),m.append(y)},Yi=(i,c)=>{let f=h("details","ra-tool");xs.set(f,{name:i,args:c});let g=h("summary"),m=Sr(i),y=Ls(i,c),v=h("span","ra-ticon");v.innerHTML=m?.icon??(Oc[i]??U.wrench)();let k=h("span","ra-tend");k.innerHTML='<span class="ra-spin"></span>',g.innerHTML=`<span class="ra-chev">${U.chev()}</span>`;let L=h("span","ra-tname",y??i);y&&(L.title=i,L.classList.add("own")),g.append(v,L,h("span","ra-tsum",y?"":ki(i,c)),k);let E=h("div","ra-tbody"),$=h("pre","",i==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));E.append(h("div","ra-tlabel",t.args),$);let D=c&&typeof c=="object"&&typeof c.path=="string"?c.path:null;if(D&&i!=="delete_file"&&i!=="list_files"&&i!=="search_files"){let Q=h("div","ra-tacts"),ne=h("button","ra-open",`${t.open} ${D}`);ne.type="button",ne.addEventListener("click",()=>Un(D));let he=h("button","ra-open",t.download);he.type="button",he.addEventListener("click",()=>{Ne.download(D)}),Q.append(ne,he),E.append(Q)}f.append(g,E);let W={el:f,name:i,args:c,end:k,body:E,update:null,result:null};return Ji(W,{status:"running"}),W},Qi=i=>{let c=Ki(i);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let f=h("details","ra-tg"),g=h("summary"),m=h("div","ra-tgb");return f.append(g,m),Es(i,f),m},Ya=i=>{let c=[],f=new Map;for(let g of i){let m=Ls(g.name,g.args);if(m!==void 0){let L=`Own:${m}`;f.has(L)||(c.push(L),f.set(L,0)),f.set(L,f.get(L)+1);continue}let y=Ta[g.name]??"Other",v=y==="Other"?`Other:${g.name}`:y;f.has(v)||(c.push(v),f.set(v,y==="Read"||y==="Write"||y==="Edit"||y==="Delete"?new Set:0));let k=f.get(v);k instanceof Set?k.add(Sa(g.args)??String(k.size)):f.set(v,k+1)}return c.map(g=>{let m=f.get(g),y=String(m instanceof Set?m.size:m);return g.startsWith("Own:")?m===1?g.slice(4):`${g.slice(4)} \xD7${y}`:g.startsWith("Other:")?t.actOther.replace("{name}",g.slice(6)):t[`act${g}`].replace("{n}",y)}).join(n==="zh"?"\uFF0C":", ")},eo=(i,c)=>{let f=Ls(i.name,i.args);if(f!==void 0)return{verb:f,what:""};let g=Ta[i.name]??"Other",m=Sa(i.args),y=t[`ing${g}`];return g==="Other"?{verb:`${y} ${i.name}`,what:c.querySelector(".ra-tsum")?.textContent??""}:g==="Ask"?{verb:y,what:""}:m&&g!=="Search"?{verb:y,what:m.slice(m.lastIndexOf("/")+1)||m,title:m}:{verb:y,what:c.querySelector(".ra-tsum")?.textContent??""}},Ps=i=>{let c=i.closest(".ra-tg");if(!c)return;let f=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),g=f.filter(k=>k.querySelector(".ra-tend .ra-spin")),m=f.filter(k=>k.classList.contains("fail")).length,y=c.querySelector("summary");if(y.replaceChildren(),g.length){let k=g[g.length-1],L=eo(xs.get(k)??{name:k.querySelector(".ra-tname")?.textContent??"",args:void 0},k);y.append(h("span","ra-spin"));let E=h("span","ra-tgt");E.append(`${L.verb} `),L.what&&E.append(h("code","",L.what)),L.title&&(E.title=L.title),y.append(E)}else{let k=f.map($=>xs.get($)).filter($=>!!$),L=k.length?Ya(k):f.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(f.length)),E=h("span","ra-tgt",L);E.title=f.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(f.length)),y.append(E)}m&&y.append(h("span","ra-tgf",t.toolsFailed.replace("{n}",String(m))));let v=h("span","ra-chev");v.innerHTML=U.chev(12),y.append(v)},Qa=(i,c,f,g)=>{let m=Yi(c,f);return Qi(g).append(m.el),Yt.set(i,m),Ps(m.el),be.schedule(),m},_s=i=>Array.isArray(i)?i.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:)/.test(c.image_url.url)?[c.image_url.url]:[]):[],to=(i,c,f,g,m=[],y)=>{let v=c==="ok",k=c==="error"||c==="blocked";i.end.replaceChildren();let L=Sr(i.name),E=$s(L?.outcome&&(()=>L.outcome({args:i.args,status:c,result:f,details:y})));typeof E=="string"&&E?i.end.append(h("span","ra-tout",E)):g!==void 0&&i.end.append(h("span","",`${Math.round(g)}ms`));let $=h("span",v?"ok":k?"fail":"");v?$.innerHTML=U.check():c==="error"?$.innerHTML=U.xcircle():c==="blocked"?($.innerHTML=U.ban(),$.title=t.blocked):$.textContent=t[c]??c,i.end.append($),i.el.classList.toggle("fail",k),Ji(i,{status:c,result:f,details:y}),i.update?.remove(),i.result||(i.result=h("pre",""),i.body.append(h("div","ra-tlabel",c==="error"?t.error:t.result),i.result));let D=m.length?f.replace(/^\[image_url\]$/gm,"").trim():f;if(i.result.textContent=D.length>2e4?D.slice(0,2e4)+"\u2026":D||t.emptyResult,m.length&&!i.body.querySelector(".ra-timgs")){let W=h("div","ra-timgs");for(let Q of m.slice(0,4)){let ne=h("img");ne.src=Q,ne.alt=t.result,ne.addEventListener("load",()=>be.schedule()),W.append(ne)}i.body.append(W)}Ps(i.el),be.schedule()},el=(i,c,f)=>{let g=h("div","ra-card"),m=h("div","ra-ct"+(c?"":" only"));if(m.innerHTML=U.layers()+`<span>${xe(i)}</span>`,g.append(m),c){let y=h("div","ra-md");bn(y,c,!1),g.append(y)}if(f){let y=h("button","ra-btn xs subtle",f.label);y.type="button",y.addEventListener("click",()=>{y.disabled=!0,f.onClick()}),g.append(y)}return g},Hn=(i,c,f)=>{St({render:()=>el(i,c,f)}),be.schedule()},tl=(i,c,f)=>{let g={render:()=>{let m=h("div","ra-warn");if(m.setAttribute("role","status"),f&&(m.title=f),m.innerHTML=U.alert(14),m.append(h("span","",i)),c){let y=h("button","ra-btn xs",c.label);y.type="button",y.addEventListener("click",()=>{be.remove(g),c.onClick()}),m.append(y)}return m}};St(g),be.schedule()},Rs=(i,c)=>{let f={render:()=>{let g=h("div","ra-err",i);if(c){let m=h("button","ra-btn xs red-subtle",t.retry);m.type="button",m.addEventListener("click",()=>{be.remove(f),c()}),g.append(m)}return g}};St(f),be.schedule()},Mr=i=>{be.clear(),en=0,Yt.clear(),Rn.clear(),X=null;let c=null,f,g=(m=!1)=>{if(!c)return;let y=c;c=null;let v=!(m&&F?.busy);St({render:()=>{let k=Bi();for(let L of y.items)if(L.kind==="think"){let[E]=Gi(L.text,!0),$=k.body.lastElementChild;$ instanceof HTMLDetailsElement&&$.classList.contains("ra-tg")?$.querySelector(".ra-tgb").append(E):k.body.append(E)}else if(L.kind==="text"){let E=h("div","ra-md");Ja(E,L.text),k.body.append(E)}else{let E=L.call,$=Yi(E.name,E.args);Qi(k.body).append($.el),E.status?to($,E.status,E.result??"",void 0,E.images):(E.id&&Yt.set(E.id,$),Ps($.el))}return v&&Wi(k.body,y.start!==void 0&&y.end!==void 0?y.end-y.start:void 0),v&&y.msg&&k.el.append(qi(y.msg)),k.el}})};for(let m of i)if(m.role==="user"){g();let y=typeof m.content=="string"?Ze(m):null;if(y!==null){Hn(t.compacted,y);continue}if(typeof m.content=="string"&&m.content.startsWith("[environment]"))continue;f=Tn(m),Vi(f),St(Cs(m.content,m))}else if(m.role==="assistant"){let y=vn(m.content),v=m.reasoning_content,k=typeof v=="string"?v:"";c||(c={items:[],calls:[],start:f}),c.msg=m,c.end=Tn(m)??c.end,c.end&&(en=c.end),k&&c.items.push({kind:"think",text:k}),y&&c.items.push({kind:"text",text:y});for(let L of m.tool_calls??[]){if(Ds.has(L.function.name))continue;let E=L.function.arguments;try{E=JSON.parse(L.function.arguments)}catch{}let $={id:L.id??"",name:L.function.name,args:E};c.items.push({kind:"call",call:$}),c.calls.push($),$.id&&Rn.set($.id,$)}}else if(m.role==="tool"){let y=vn(m.content),v=c?.calls.find(k=>k.id===(m.tool_call_id??""));v&&(v.result=y,v.status=zc(y),v.images=_s(m.content),Rn.delete(v.id))}g(!0),i.length||Ui(),be.scrollToBottom()},Mt=null,Cr=null,jn=()=>{Cr=null,Mt!==null&&(Mt=null,Ft(j.dataset.busy==="1"))},nl={name:"suggest_next_prompt",description:`Offer the user their likely next message: it appears greyed in their input box and Tab sends it there. Call it only in the same reply as your final answer, after writing the answer, and only when an obvious next request follows (after writing a strategy: "Backtest it over the last year"). Write it as the user would type it \u2014 in the user's language, one short sentence, a request to you, nothing you already did. When no next step is clear, do not call it.`,parameters:{type:"object",properties:{text:{type:"string",description:"The suggested message, as the user would type it"}},required:["text"],additionalProperties:!1},readOnly:!0,endsRun:!0,display:{hidden:!0},execute:({text:i})=>(Cr=String(i??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},no=[...B.tools??[],...G?[nl]:[]],Ds=new Set(no.filter(i=>i.display?.hidden).map(i=>i.name)),Nn=()=>{let i=j.dataset.busy==="1",c=!!(S.value.trim()||ot.length||at.length);Le.style.display=!i&&c?"":"none",Jt.style.display=_n.style.display=i&&c?"":"none"},Ft=i=>{j.dataset.busy=i?"1":"",S.placeholder=i?Dt(t.placeholderBusy):Mt??A??t.placeholder,Ve.textContent=Dt(i?t.hintBusy:Mt?t.hintNext:t.hintIdle),Nn(),Ot.style.display=i?"":"none",it()},Ht=!1,it=()=>{let i=F?.queued??[];if(Ke.style.display=i.length?"":"none",Ke.replaceChildren(),!i.length){Ht=!1;return}let c=F,f=E=>vn(E.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),g=(E,$,D)=>{let W=h("button");return W.type="button",W.innerHTML=E,W.title=$,W.setAttribute("aria-label",$),W.addEventListener("click",Q=>{Q.stopPropagation(),D()}),W},m=E=>{let $=h("span","ra-qa");return E.kind!=="steer"&&$.append(g(U.enter(),t.sendNow,()=>{c.dequeue(E.message)&&c.steer(E.message.content),it()})),$.append(g(U.pen(),t.editQueued,()=>{c.dequeue(E.message)&&(S.value=S.value.trim()?`${f(E.message)}
|
|
716
|
+
${S.value}`:f(E.message),S.focus(),it())})),$.append(g(U.x(14),t.remove,()=>{c.dequeue(E.message),it()})),$},y=E=>E.kind==="steer"?h("span","ra-qk",t.steer):null;if(Ke.classList.toggle("open",Ht&&i.length>1),i.length===1){let E=i[0],$=h("div","ra-qr"),D=y(E);$.append(h("span","ra-qn",t.queuedN.replace("{n}","1"))),D&&$.append(D),$.append(h("span","ra-qt",f(E.message)),m(E)),Ke.append($);return}let v=h("div","ra-qr ra-qhd"),k=h("span","ra-qt");Ht||(k.append(h("b","",t.queueNext)),k.append(f(i[0].message)));let L=h("span","ra-qtog");if(L.innerHTML=U.chevDown(14),L.title=Ht?t.collapse:t.expand,v.append(h("span","ra-qn",t.queuedNs.replace("{n}",String(i.length))),k,L),v.addEventListener("click",()=>{Ht=!Ht,it()}),Ke.append(v),Ht)for(let E of i){let $=h("div","ra-qr"),D=y(E);D&&$.append(D),$.append(h("span","ra-qt",f(E.message)),m(E)),Ke.append($)}},qn=i=>{vt.style.display=i?"":"none",vt.textContent=i??""},Ct=async()=>{let i=F?.workspace;if(!i){hr=[],Zt(0);return}try{let[c,f]=await Promise.all([i.skills(),Nr(i)]);F?.workspace===i&&Zt(c.length),hr=[...f.map(g=>({name:g.name,description:g.description,kind:t.template})),...c.map(g=>({name:`skill:${g.name}`,description:g.description,kind:t.skill}))]}catch{hr=[],Zt(0)}},Os=!1,ro=()=>{let i=S.value;return Os||!i.startsWith("/")||/\s/.test(i)?[]:[...qs(),...hr].filter(c=>`/${c.name}`.startsWith(i)).slice(0,40)},Ge=()=>{Nn();let i=ro();Qe.style.display=i.length?"":"none",Qe.replaceChildren(),rt>=i.length&&(rt=0),i.forEach((c,f)=>{let g=h("button",f===rt?"ra-cur":"");g.type="button",g.append(h("span","ra-cn",`/${c.name}`)),c.args&&g.append(h("span","ra-ca",c.args)),g.append(h("span","ra-badge",c.kind),h("span","ra-cd",c.description)),g.addEventListener("mousedown",m=>{m.preventDefault(),yo(c),S.focus()}),Qe.append(g),f===rt&&g.scrollIntoView?.({block:"nearest"})})},rl=()=>{Dn===null&&(Dn=requestAnimationFrame(()=>{Dn=null,Ge()}))},ot=[],at=[],tn=()=>{q.style.display=ot.length||at.length?"":"none",Nn()},zs=i=>{let c=at.findIndex(f=>f.id===i);c<0||(at[c].chip.remove(),at.splice(c,1),tn())},so=i=>{let c=i.id??`ctx_${Math.random().toString(36).slice(2,8)}`;zs(c),i={...i,label:i.label.replace(/\s+/g," ").trim()||"context"};let f=Fi(i.label,i.title,i.icon),g=h("button");return g.type="button",g.innerHTML=U.x(),g.title=t.remove,g.setAttribute("aria-label",t.remove),g.addEventListener("click",()=>zs(c)),f.append(g),at.push({id:c,label:i.label,text:i.text,chip:f}),q.prepend(f),tn(),()=>zs(c)},sl=i=>{let c=ot.indexOf(i);c>=0&&ot.splice(c,1),i.preview&&URL.revokeObjectURL(i.preview),i.chip.remove(),tn()},Us=Promise.resolve(),Er=(i,c=[])=>{let f=i?Array.from(i):[],g=Us.then(()=>il(f,c));return Us=g.catch(()=>{}),g},il=async(i,c)=>{if(!(ge===!1||!i?.length)){for(let[f,g]of Array.from(i).entries()){if(g.size>Bc){Z.notify(`${g.name} ${t.tooLarge}`,"warning");continue}let m=new Uint8Array(await g.arrayBuffer()),y=/^image\/(png|jpe?g|gif|webp)$/.test(g.type),v=y?null:Jc(g,m),k=y?URL.createObjectURL(g):null,L=Ii(Ca(g.name),kn(g.size),k),E=h("button");E.type="button",E.innerHTML=U.x(),E.title=t.remove,E.setAttribute("aria-label",t.remove),L.append(E);let $={file:g,name:Ca(g.name),bytes:m,text:v,image:y,preview:k,chip:L,path:c[f]};E.addEventListener("click",()=>sl($)),ot.push($),q.append(L)}tn(),S.focus()}};ae.addEventListener("click",()=>me.click()),me.addEventListener("change",()=>{Er(me.files),me.value=""}),S.addEventListener("paste",i=>{let c=Array.from(i.clipboardData?.files??[]);!c.length||i.clipboardData?.getData("text/plain")||(i.preventDefault(),Er(c))});let Ar=0;j.addEventListener("dragenter",i=>{ge===!1||!i.dataTransfer?.types.includes("Files")||(i.preventDefault(),Ar++,j.dataset.drop="1")}),j.addEventListener("dragover",i=>{j.dataset.drop&&(i.preventDefault(),i.dataTransfer.dropEffect="copy")}),j.addEventListener("dragleave",()=>{j.dataset.drop&&--Ar<=0&&(Ar=0,delete j.dataset.drop)}),j.addEventListener("drop",i=>{j.dataset.drop&&(i.preventDefault(),Ar=0,delete j.dataset.drop,Er(i.dataTransfer?.files))});let ol=async(i,c,f)=>{if(!c.length)return i;let g=B.fileTools===!1?null:f.workspace,m=[],y=[],v=c.some(D=>D.image)&&await f.accepts("image")===!1,k=D=>/^video\//.test(D.file.type)&&D.file.size<=Kc,L=c.some(k)&&await f.accepts("video")!==!1;v&&Z.notify(t.noVision.replace("{model}",f.model||(await f.modelInfo())?.id||t.sDefault),"warning");for(let D of c){let W=D.file.type||(D.text!==null?"text/plain":"application/octet-stream");if(g){let Q=D.path&&await g.exists(D.path)?D.path:await xi(g,H,D.name);Q!==D.path&&await g.write(Q,D.text??D.bytes,W),m.push(`- ${Q} (${W}, ${kn(D.file.size)})`),Ne.refresh()}else if(cn(D.name,D.file.type,D.bytes)){let Q="";try{Q=pn(D.name,await dn(D.bytes))}catch(ne){Q=`Could not read the PDF: ${ne.message}`}Q.length>Si&&(Q=Q.slice(0,Si)+`
|
|
717
717
|
[\u2026 truncated]`),m.push(`- ${D.name} (${W}, ${kn(D.file.size)}) \u2014 its text below`),y.push({type:"text",text:`<file name="${D.name}">
|
|
718
718
|
${Q}
|
|
719
719
|
</file>`})}else D.text!==null&&D.text.length<=Si?(m.push(`- ${D.name} (${W}, ${kn(D.file.size)}) \u2014 contents below`),y.push({type:"text",text:`<file name="${D.name}">
|
|
720
720
|
${D.text}
|
|
721
721
|
</file>`})):m.push(`- ${D.name} (${W}, ${kn(D.file.size)}) \u2014 ${D.image&&!v?"the picture below":k(D)&&L?"the video below":"not readable here"}`);if(k(D)&&L){let Q=await new Promise(ne=>{let he=new FileReader;he.onload=()=>ne(String(he.result)),he.readAsDataURL(D.file)});y.push({type:"video_url",video_url:{url:Q}})}if(D.image&&!v&&D.file.size<=Wc){let Q=await new Promise(ne=>{let he=new FileReader;he.onload=()=>ne(String(he.result)),he.readAsDataURL(D.file)});y.push({type:"image_url",image_url:{url:Q}})}}let E=g?`${Pt} files the user attached, saved in the directory (read them with read_file):`:`${Pt} files the user attached:`,$=[];return i&&$.push({type:"text",text:i}),$.push({type:"text",text:`${E}
|
|
722
722
|
${m.join(`
|
|
723
|
-
`)}`}),$.push(...y),$},Is=!1,nn=async i=>{await Us;let c=
|
|
724
|
-
${L.text}`}))),y=v}}catch(v){T.value=c,ot.unshift(...g);for(let k of g.slice().reverse())q.prepend(k.chip);at.unshift(...m);for(let k of m.slice().reverse())q.prepend(k.chip);tn(),qn(v.message);return}finally{Is=!1}for(let v of g)v.preview&&URL.revokeObjectURL(v.preview);f.busy||(i="prompt");try{if(i==="prompt"){F===f&&!f.busy&&(yt=xr(y)),await f.prompt(y);return}i==="steer"?f.steer(y):f.followUp(y).catch(()=>{}),it()}catch(v){yt=null,qn(v.message)}};T.addEventListener("input",()=>{Os=!1,T.value&&Hn(),Nn(),rl()}),T.addEventListener("keydown",i=>{if(i.isComposing||i.keyCode===229)return;let c=ro();if(c.length){if(i.key==="ArrowDown"){i.preventDefault(),rt=(rt+1)%c.length,Ge();return}if(i.key==="ArrowUp"){i.preventDefault(),rt=(rt-1+c.length)%c.length,Ge();return}if(i.key==="Tab"){i.preventDefault(),T.value=`/${c[rt].name} `,Ge();return}if(i.key==="Enter"&&!i.shiftKey){i.preventDefault(),yo(c[rt]);return}if(i.key==="Escape"){Os=!0,Qe.style.display="none";return}}if(Mt&&!T.value&&i.key==="Tab"&&!i.shiftKey){i.preventDefault(),T.value=Mt,Hn(),Nn();return}if(Mt&&!T.value&&i.key==="Escape"){Hn();return}if(i.key!=="Enter"||i.shiftKey)return;i.preventDefault();let f=i.metaKey||i.ctrlKey||i.altKey;nn(F?.busy?f?"followUp":"steer":"prompt")}),T.addEventListener("blur",()=>{Qe.style.display="none"}),T.addEventListener("focus",()=>Ge()),Le.addEventListener("click",()=>{nn("prompt")}),Jt.addEventListener("click",()=>{nn("steer")}),_n.addEventListener("click",()=>{nn("followUp")}),Ot.addEventListener("click",()=>{Z.cancelAll(),F?.abort()}),He.addEventListener("click",i=>{let c=i.target,f=de?c.closest("a[href]"):null;if(f&&de){let y=!1;try{y=de(f.getAttribute("href")??"",f.textContent??"")===!0}catch(v){console.warn("agent: onLink failed",v)}if(y){i.preventDefault();return}}let g=c.closest(".ra-path");if(g?.dataset.path){i.preventDefault(),Un(g.dataset.path);return}let m=c.closest(".ra-md a[href]");if(m&&F?.workspace){let y=m.getAttribute("href")??"";if(y.startsWith("/")&&!y.startsWith("//")){i.preventDefault(),F.workspace.exists(y).then(k=>{k?Un(y):window.open(m.href,"_blank","noopener")});return}}});let Fs=`__runapps_agent_chat:${ie}:settings`,al=()=>{try{return JSON.parse(localStorage.getItem(Fs)||"{}")}catch{return{}}},io=i=>{try{Object.keys(i).length?localStorage.setItem(Fs,JSON.stringify(i)):localStorage.removeItem(Fs)}catch{}},Ue=a?{}:al(),Bn=null,oo=e.settings??!a,ao=0;oo||(Be.style.display="none");let Ht=null,js=i=>{let c=i?.options?.inputs?.reasoning_effort;if(!c)return null;let f=(c.enum??[]).filter(g=>typeof g=="string");return f.length?{levels:f,def:typeof c.default=="string"?c.default:void 0}:null},lo=(i,c,f)=>{let g=B.extra?.reasoning_effort;i.configure({model:c.model??B.model,maxTurns:c.maxTurns??B.maxTurns??100,maxTokens:c.maxTokens??(typeof B.maxTokens=="number"?B.maxTokens:"auto"),permissions:f??B.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof g=="string"?g:null)}),ye.textContent=i.model??"",ye.style.display=i.model?"":"none"},$r=i=>{Ue=i,io(i);for(let c of We.values())lo(c,i,Bn);Et(F)},Wn=async()=>{if(K?.models)try{Ht??(Ht=(await K.models()).filter(i=>!i.capability||i.capability==="text"||i.capability==="vision"))}catch{}return Ht??[]};Ue.model&&K?.models&&Wn().then(i=>{if(!i.length||!Ue.model||i.some(g=>g.id===Ue.model))return;let{model:c,...f}=Ue;$r(f)});let Lr=i=>typeof i=="number"?i>=1e3?`${Math.round(i/1e3)}k`:String(i):"?",co=i=>{let c=i?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let f=t.sPriceLine.replace("{in}",cr(c.input??0,c.currency)).replace("{out}",cr(c.output??0,c.currency));return c.per_call?`${f} \xB7 ${t.sPerCall.replace("{amount}",cr(c.per_call,c.currency))}`:f},Hs=async()=>{if(Te){Me();return}if(!F)return;let i=F,c=h("div","ra-menu ra-set");Te=c,Pr(c);let f=i.settings,g=(le,ue)=>{let ce=ar(H,{options:le,value:ue,filterLabel:t.filter});return po.push(ce),ce},m=g([{value:"",label:t.sDefault}],""),y=h("div","ra-lim"),v=g([],""),k=h("div","ra-lim"),L=()=>{let le=m.value||Ht?.find(ue=>ue.is_default)?.id;return Ht?.find(ue=>ue.id===le)},E=()=>{let le=L(),ue=Nt(le,"image"),ce=co(le);y.textContent=le?`${t.context} ${Lr(le.max_input_tokens)} \xB7 ${t.sMaxTokens} ${Lr(le.max_tokens)}${ue===void 0?"":` \xB7 ${ue?t.sVisionYes:t.sVisionNo}`}${ce?` \xB7 ${t.sPrice}: ${ce}`:""}`:"";let ke=js(le),De=v.value;v.setOptions([{value:"",label:t.sEffortDefault,note:ke?.def},...(ke?.levels??[]).map(qe=>({value:qe,label:qe}))]),v.disabled=!ke,v.value=ke&&ke.levels.includes(De)?De:"",k.textContent=ke?"":t.sEffortNone,k.style.display=ke?"none":""};m.el.addEventListener("change",E);let $=[];if(K?.models){if(await Wn(),Te!==c)return;let le=Ht?.find(ue=>ue.is_default);$.push({value:"",label:t.sDefault,note:le?.id});for(let ue of Ht??[]){let ce=ue.price,ke=ce&&(ce.input!==void 0||ce.output!==void 0)?` \xB7 ${cr(ce.input??0,ce.currency)} / ${cr(ce.output??0,ce.currency)}`:"";$.push({value:ue.id,label:ue.id,note:`${Nt(ue,"image")?`${t.sVision} \xB7 `:""}${Lr(ue.max_input_tokens)} / ${Lr(ue.max_tokens)}${ke}`})}}else $.push({value:"",label:t.sDefault});f.model&&!$.some(le=>le.value===f.model)&&$.push({value:f.model,label:f.model}),m.setOptions($),m.value=f.model??"",E(),f.reasoningEffort&&v.options.some(le=>le.value===f.reasoningEffort)&&(v.value=f.reasoningEffort);let D=h("input");D.type="number",D.min="1",D.max="1000",D.step="1",D.value=String(f.maxTurns);let W=g([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),Q=h("input");Q.type="number",Q.min="256",Q.step="256",Q.value=String(typeof f.maxTokens=="number"?f.maxTokens:8192),W.value=typeof f.maxTokens=="number"?"n":"auto",Q.style.display=W.value==="n"?"":"none",W.el.addEventListener("change",()=>{Q.style.display=W.value==="n"?"":"none"});let ne=g([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...f.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],f.permissions),he=(le,...ue)=>{let ce=h("div","ra-fld");return ce.append(h("span","",le),...ue),ce},Ie=h("div","ra-row");Ie.append(W.el,Q);let At=h("div","ra-pane");At.append(he(t.sModel,m.el),y,he(t.sEffort,v.el),k,he(t.sMaxTurns,D),he(t.sMaxTokens,Ie)),R!==!1&&At.append(he(t.sPerms,ne.el));let lt=[],Ks=le=>{let ue=h("div","ra-pane");for(let ce of le.fields){if(ce instanceof HTMLElement){ce.classList.add("ra-host"),ue.append(ce);continue}if(ce.type==="toggle"){let ke=h("label","ra-tgl"),De=h("input");De.type="checkbox",De.checked=ce.value();let qe=h("span","",ce.label);ce.hint&&qe.append(h("small","",ce.hint)),ke.append(De,qe),ue.append(ke),lt.push(()=>{De.checked!==ce.value()&&ce.onChange(De.checked)})}else{let ke=g(ce.options,ce.value()),De=he(ce.label,ke.el);ce.hint&&De.append(h("small","",ce.hint)),ue.append(De),lt.push(()=>{ke.value!==ce.value()&&ce.onChange(ke.value)})}}return ue},Or=[At,...(fe??[]).map(Ks)];if(Or.length>1){let le=h("div","ra-tabs");le.setAttribute("role","tablist");let ue=[t.sTabModel,...(fe??[]).map(ke=>ke.label)].map((ke,De)=>{let qe=h("button","ra-tab",ke);return qe.type="button",qe.setAttribute("role","tab"),qe.addEventListener("click",()=>ce(De)),qe}),ce=ke=>{ao=ke,Or.forEach((De,qe)=>{De.hidden=qe!==ke}),ue.forEach((De,qe)=>{De.classList.toggle("on",qe===ke),De.setAttribute("aria-selected",String(qe===ke))})};le.append(...ue),Te.append(le,...Or),ce(Math.min(ao,Or.length-1))}else Te.append(At);let Co=h("div","ra-btns"),Vs=h("button","ra-btn xs ghost",t.reset);Vs.type="button";let Gs=h("button","ra-btn xs solid",t.apply);Gs.type="button",Co.append(Vs,Gs),Te.append(Co),Vs.addEventListener("click",()=>{for(let le of(fe??[]).flatMap(ue=>ue.fields))le instanceof HTMLElement||le.default===void 0||(le.type,le.value()!==le.default&&le.onChange(le.default));Ue={},io({}),Bn=null;for(let le of We.values())lo(le,{},null);Me(),Z.notify(t.applied),Et(F)}),Gs.addEventListener("click",()=>{let le={};m.value&&(le.model=m.value);let ue=parseInt(D.value,10);if(Number.isFinite(ue)&&ue>0&&Math.min(1e3,ue)!==(B.maxTurns??100)&&(le.maxTurns=Math.min(1e3,ue)),W.value==="n"){let ce=parseInt(Q.value,10);Number.isFinite(ce)&&ce>0&&(le.maxTokens=ce)}v.value&&!v.disabled&&(le.reasoningEffort=v.value),(ne.value==="ask"||ne.value==="auto")&&(Bn=ne.value);for(let ce of lt)ce();$r(le),Me(),Z.notify(t.applied)})};Be.addEventListener("click",()=>{Hs()});let po=[],Me=()=>{Te?.remove(),Te=null;for(let i of po.splice(0))i.close()},Pr=i=>{H.append(i),i.style.top=`${_t.offsetTop+_t.offsetHeight+4}px`},uo=async()=>{if(Te){Me();return}if(!F?.workspace)return;let i=F.workspace,c=h("div","ra-menu");Te=c,Pr(c);let f=[];try{f=await i.sessions.list()}catch{}if(Te!==c)return;let g=F,m=f.filter(k=>k.id!==g.id),y=f.find(k=>k.id===g.id),v=k=>{let L=!k||k.id===g.id,E=h("div","ra-mi"+(L?" ra-cur":"")),$=h("button");$.type="button";let D=k?We.get(k.id):void 0,W=k&&D&&D!==g?zt.has(k.id)?` \xB7 ${t.waitingAnswer}`:D.busy||D.queued.length?` \xB7 ${t.running}`:"":"",Q=h("span","ra-mt");if(W&&!zt.has(k.id)&&Q.append(h("span","ra-spin")),Q.append(h("span","ra-mtt",(k?k.title:yr(g))||t.untitled)),L&&(Q.append(h("span","ra-now",t.current)),E.setAttribute("aria-current","true")),$.append(Q,h("small","",k?`${k.messages} ${t.messages} \xB7 ${new Date(k.savedAt).toLocaleString()}${W}`:t.notSaved)),$.addEventListener("click",()=>{Me(),k&&!L&&Mo(k.id).catch(ne=>Z.notify(ne.message,"error"))}),E.append($),k){let ne=h("button","ra-x");ne.type="button",ne.innerHTML=U.trash(),ne.title=t.delete,ne.setAttribute("aria-label",t.delete),ne.addEventListener("click",async he=>{he.stopPropagation(),Me(),await ut(H,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await Ws(k.id,!1,k.workspace).catch(Ie=>Z.notify(Ie.message,"error"))}),E.append(ne)}return E};c.append(v(y??null)),m.length?c.append(h("div","ra-sep")):c.append(h("div","ra-none",t.noSessions));for(let k of m)c.append(v(k));if(m.length){let k=h("div","ra-mf"),L=h("button","ra-btn xs ghost");L.type="button",L.innerHTML=U.trash()+xe(t.deleteAll),L.addEventListener("click",async()=>{if(Me(),!!await ut(H,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let E of f)await Ws(E.id,!0,E.workspace);await Vn()}catch(E){Z.notify(E.message,"error")}}),k.append(L),c.append(k)}};Xe.addEventListener("click",()=>{uo()}),ht.addEventListener("click",()=>{Me(),Vn().catch(i=>Z.notify(i.message,"error"))}),ze.addEventListener("click",async()=>{Me(),await ut(H,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await Bs().catch(i=>Z.notify(i.message,"error"))}),document.addEventListener("click",fo,!0);function fo(i){i.target?.closest?.(".ra-selp")||Te&&!Te.contains(i.target)&&!Xe.contains(i.target)&&!Be.contains(i.target)&&!Ye.contains(i.target)&&!$e.contains(i.target)&&Me()}let wt=h("input");wt.type="file",wt.accept=".zip,application/zip",wt.multiple=!0,wt.style.display="none",H.append(wt);let ho=async i=>{let c=F?.workspace;if(!c||!i?.length)return;let f=[];for(let g of Array.from(i)){if(!/\.zip$/i.test(g.name)&&g.type!=="application/zip"&&g.type!=="application/x-zip-compressed"){Z.notify(`${g.name}: ${t.notZip}`,"warning");continue}try{f.push(...(await c.installSkill(g)).map(m=>m.name))}catch(m){Z.notify(`${g.name}: ${m.message}`,"error")}}f.length&&Z.notify(t.skillsInstalled.replace("{names}",f.join(", "))),await Ct(),Te?.classList.contains("ra-skm")&&(Me(),go())};wt.addEventListener("change",()=>{ho(wt.files),wt.value=""});let go=async()=>{if(Te){let y=Te.classList.contains("ra-skm");if(Me(),y)return}let i=F?.workspace;if(!i)return;let c=h("div","ra-menu ra-skm");Te=c,Pr(c);let f=[];try{f=await i.skills()}catch(y){Z.notify(y.message,"error")}if(Te!==c)return;let g=h("div","ra-skh"),m=h("button","ra-btn xs solid");m.type="button",m.innerHTML=U.upload(13)+`<span>${xe(t.uploadZip)}</span>`,m.addEventListener("click",()=>wt.click()),i.userSkillsDir||(m.style.display="none"),g.append(h("span","",f.length?`${t.skills} \xB7 ${f.length}`:t.skills),m),c.append(g),f.length||c.append(h("div","ra-none",t.noSkills));for(let y of f){let v=h("div","ra-mi"),k=h("button");k.type="button",k.title=t.useSkill;let L=h("span","ra-mt"),E=!!y.from&&/\.zip$/i.test(y.from);L.append(h("span","ra-mtt",y.name),h("span","ra-skb",y.builtin?t.builtinSkill:E?"zip":t.skillFolder)),y.disableModelInvocation&&L.append(h("span","ra-skb",t.manualOnly)),k.append(L,h("small","",y.description)),k.addEventListener("click",()=>{Me(),T.value=`/skill:${y.name} `,T.focus(),Ge()});let $=(ne,he,Ie,At="ra-x ra-ia")=>{let lt=h("button",At);return lt.type="button",lt.innerHTML=ne,lt.title=he,lt.setAttribute("aria-label",he),lt.addEventListener("click",Ks=>{Ks.stopPropagation(),Ie()}),lt},D=$(U.eye(),t.open,()=>{Me(),Un(y.from&&!E?`${y.from}/SKILL.md`:y.path)}),W=$(U.download(),t.download,()=>{E?Ne.download(y.from):Ne.downloadFolder(y.from??y.dir)}),Q=$(U.trash(),t.delete,async()=>{Me();let ne=E?f.filter(Ie=>Ie.from===y.from).map(Ie=>Ie.name):[y.name],he=ne.length>1?t.confirmDeleteZip.replace("{zip}",y.from.replace(/^.*\//,"")).replace("{names}",ne.join("\u3001")):t.confirmDeleteSkill.replace("{name}",y.name).replace("{path}",y.from??"");if(await ut(H,t.delete,he,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await i.removeSkill(y.name),await Ct(),Z.notify(t.skillRemoved.replace("{name}",ne.join(", ")))}catch(Ie){Z.notify(Ie.message,"error")}},"ra-x");(y.builtin||!y.from?.startsWith((i.userSkillsDir??"\0")+"/"))&&(Q.style.display="none"),v.append(k,D,W,Q),c.append(v)}c.append(h("div","ra-skf",(i.userSkillsDir?t.skillsHint.replace("{user}",i.userSkillsDir):t.skillsHintNoUser).replace("{dir}",i.skillsDir))),i.userSkillsDir&&c.addEventListener("dragover",y=>{y.dataTransfer?.types.includes("Files")&&(y.preventDefault(),y.stopPropagation(),c.classList.add("drop"))}),c.addEventListener("dragleave",()=>c.classList.remove("drop")),i.userSkillsDir&&c.addEventListener("drop",y=>{y.preventDefault(),y.stopPropagation(),c.classList.remove("drop"),ho(y.dataTransfer?.files)})};Ye.addEventListener("click",()=>{go()});let mo=i=>Z.notify(i.message,"error"),_r=!1,ll=i=>{let c=[`# ${yr(i)}`,""];for(let f of i.messages){if(f.role==="tool"||f.role==="system")continue;let g=vn(f.content).trim(),m=f.role==="user"&&typeof f.content=="string"?Ze(f):null;if(m!==null){c.push(`> **${t.compacted}**`,">",...m.split(`
|
|
723
|
+
`)}`}),$.push(...y),$},Is=!1,nn=async i=>{await Us;let c=S.value.trim();if(!c&&!ot.length&&!at.length||!F||Is||(jn(),dl(c)))return;_r&&(i="followUp");let f=F,g=ot.splice(0);for(let v of g)v.chip.remove();let m=at.splice(0);for(let v of m)v.chip.remove();tn(),S.value="",Ge(),qn(),Is=!0;let y;try{if(y=await ol(c,g,f),m.length){let v=typeof y=="string"?y?[{type:"text",text:y}]:[]:y,k=v.length&&v[0].type==="text"&&!v[0].text.startsWith(Pt)?1:0;v.splice(k,0,...m.map(L=>({type:"text",text:`${Sn}${L.label}
|
|
724
|
+
${L.text}`}))),y=v}}catch(v){S.value=c,ot.unshift(...g);for(let k of g.slice().reverse())q.prepend(k.chip);at.unshift(...m);for(let k of m.slice().reverse())q.prepend(k.chip);tn(),qn(v.message);return}finally{Is=!1}for(let v of g)v.preview&&URL.revokeObjectURL(v.preview);f.busy||(i="prompt");try{if(i==="prompt"){F===f&&!f.busy&&(yt=xr(y)),await f.prompt(y);return}i==="steer"?f.steer(y):f.followUp(y).catch(()=>{}),it()}catch(v){yt=null,qn(v.message)}};S.addEventListener("input",()=>{Os=!1,S.value&&jn(),Nn(),rl()}),S.addEventListener("keydown",i=>{if(i.isComposing||i.keyCode===229)return;let c=ro();if(c.length){if(i.key==="ArrowDown"){i.preventDefault(),rt=(rt+1)%c.length,Ge();return}if(i.key==="ArrowUp"){i.preventDefault(),rt=(rt-1+c.length)%c.length,Ge();return}if(i.key==="Tab"){i.preventDefault(),S.value=`/${c[rt].name} `,Ge();return}if(i.key==="Enter"&&!i.shiftKey){i.preventDefault(),yo(c[rt]);return}if(i.key==="Escape"){Os=!0,Qe.style.display="none";return}}if(Mt&&!S.value&&i.key==="Tab"&&!i.shiftKey){i.preventDefault(),S.value=Mt,jn(),Nn();return}if(Mt&&!S.value&&i.key==="Escape"){jn();return}if(i.key!=="Enter"||i.shiftKey)return;i.preventDefault();let f=i.metaKey||i.ctrlKey||i.altKey;nn(F?.busy?f?"followUp":"steer":"prompt")}),S.addEventListener("blur",()=>{Qe.style.display="none"}),S.addEventListener("focus",()=>Ge()),Le.addEventListener("click",()=>{nn("prompt")}),Jt.addEventListener("click",()=>{nn("steer")}),_n.addEventListener("click",()=>{nn("followUp")}),Ot.addEventListener("click",()=>{Z.cancelAll(),F?.abort()}),je.addEventListener("click",i=>{let c=i.target,f=de?c.closest("a[href]"):null;if(f&&de){let y=!1;try{y=de(f.getAttribute("href")??"",f.textContent??"")===!0}catch(v){console.warn("agent: onLink failed",v)}if(y){i.preventDefault();return}}let g=c.closest(".ra-path");if(g?.dataset.path){i.preventDefault(),Un(g.dataset.path);return}let m=c.closest(".ra-md a[href]");if(m&&F?.workspace){let y=m.getAttribute("href")??"";if(y.startsWith("/")&&!y.startsWith("//")){i.preventDefault(),F.workspace.exists(y).then(k=>{k?Un(y):window.open(m.href,"_blank","noopener")});return}}});let Fs=`__runapps_agent_chat:${ie}:settings`,al=()=>{try{return JSON.parse(localStorage.getItem(Fs)||"{}")}catch{return{}}},io=i=>{try{Object.keys(i).length?localStorage.setItem(Fs,JSON.stringify(i)):localStorage.removeItem(Fs)}catch{}},Ue=a?{}:al(),Bn=null,oo=e.settings??!a,ao=0;oo||(Be.style.display="none");let jt=null,Hs=i=>{let c=i?.options?.inputs?.reasoning_effort;if(!c)return null;let f=(c.enum??[]).filter(g=>typeof g=="string");return f.length?{levels:f,def:typeof c.default=="string"?c.default:void 0}:null},lo=(i,c,f)=>{let g=B.extra?.reasoning_effort;i.configure({model:c.model??B.model,maxTurns:c.maxTurns??B.maxTurns??100,maxTokens:c.maxTokens??(typeof B.maxTokens=="number"?B.maxTokens:"auto"),permissions:f??B.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof g=="string"?g:null)}),ye.textContent=i.model??"",ye.style.display=i.model?"":"none"},$r=i=>{Ue=i,io(i);for(let c of We.values())lo(c,i,Bn);Et(F)},Wn=async()=>{if(K?.models)try{jt??(jt=(await K.models()).filter(i=>!i.capability||i.capability==="text"||i.capability==="vision"))}catch{}return jt??[]};Ue.model&&K?.models&&Wn().then(i=>{if(!i.length||!Ue.model||i.some(g=>g.id===Ue.model))return;let{model:c,...f}=Ue;$r(f)});let Lr=i=>typeof i=="number"?i>=1e3?`${Math.round(i/1e3)}k`:String(i):"?",co=i=>{let c=i?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let f=t.sPriceLine.replace("{in}",cr(c.input??0,c.currency)).replace("{out}",cr(c.output??0,c.currency));return c.per_call?`${f} \xB7 ${t.sPerCall.replace("{amount}",cr(c.per_call,c.currency))}`:f},js=async()=>{if(Te){Me();return}if(!F)return;let i=F,c=h("div","ra-menu ra-set");Te=c,Pr(c);let f=i.settings,g=(le,ue)=>{let ce=ar(j,{options:le,value:ue,filterLabel:t.filter});return po.push(ce),ce},m=g([{value:"",label:t.sDefault}],""),y=h("div","ra-lim"),v=g([],""),k=h("div","ra-lim"),L=()=>{let le=m.value||jt?.find(ue=>ue.is_default)?.id;return jt?.find(ue=>ue.id===le)},E=()=>{let le=L(),ue=Nt(le,"image"),ce=co(le);y.textContent=le?`${t.context} ${Lr(le.max_input_tokens)} \xB7 ${t.sMaxTokens} ${Lr(le.max_tokens)}${ue===void 0?"":` \xB7 ${ue?t.sVisionYes:t.sVisionNo}`}${ce?` \xB7 ${t.sPrice}: ${ce}`:""}`:"";let ke=Hs(le),De=v.value;v.setOptions([{value:"",label:t.sEffortDefault,note:ke?.def},...(ke?.levels??[]).map(qe=>({value:qe,label:qe}))]),v.disabled=!ke,v.value=ke&&ke.levels.includes(De)?De:"",k.textContent=ke?"":t.sEffortNone,k.style.display=ke?"none":""};m.el.addEventListener("change",E);let $=[];if(K?.models){if(await Wn(),Te!==c)return;let le=jt?.find(ue=>ue.is_default);$.push({value:"",label:t.sDefault,note:le?.id});for(let ue of jt??[]){let ce=ue.price,ke=ce&&(ce.input!==void 0||ce.output!==void 0)?` \xB7 ${cr(ce.input??0,ce.currency)} / ${cr(ce.output??0,ce.currency)}`:"";$.push({value:ue.id,label:ue.id,note:`${Nt(ue,"image")?`${t.sVision} \xB7 `:""}${Lr(ue.max_input_tokens)} / ${Lr(ue.max_tokens)}${ke}`})}}else $.push({value:"",label:t.sDefault});f.model&&!$.some(le=>le.value===f.model)&&$.push({value:f.model,label:f.model}),m.setOptions($),m.value=f.model??"",E(),f.reasoningEffort&&v.options.some(le=>le.value===f.reasoningEffort)&&(v.value=f.reasoningEffort);let D=h("input");D.type="number",D.min="1",D.max="1000",D.step="1",D.value=String(f.maxTurns);let W=g([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),Q=h("input");Q.type="number",Q.min="256",Q.step="256",Q.value=String(typeof f.maxTokens=="number"?f.maxTokens:8192),W.value=typeof f.maxTokens=="number"?"n":"auto",Q.style.display=W.value==="n"?"":"none",W.el.addEventListener("change",()=>{Q.style.display=W.value==="n"?"":"none"});let ne=g([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...f.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],f.permissions),he=(le,...ue)=>{let ce=h("div","ra-fld");return ce.append(h("span","",le),...ue),ce},Ie=h("div","ra-row");Ie.append(W.el,Q);let At=h("div","ra-pane");At.append(he(t.sModel,m.el),y,he(t.sEffort,v.el),k,he(t.sMaxTurns,D),he(t.sMaxTokens,Ie)),R!==!1&&At.append(he(t.sPerms,ne.el));let lt=[],Ks=le=>{let ue=h("div","ra-pane");for(let ce of le.fields){if(ce instanceof HTMLElement){ce.classList.add("ra-host"),ue.append(ce);continue}if(ce.type==="toggle"){let ke=h("label","ra-tgl"),De=h("input");De.type="checkbox",De.checked=ce.value();let qe=h("span","",ce.label);ce.hint&&qe.append(h("small","",ce.hint)),ke.append(De,qe),ue.append(ke),lt.push(()=>{De.checked!==ce.value()&&ce.onChange(De.checked)})}else{let ke=g(ce.options,ce.value()),De=he(ce.label,ke.el);ce.hint&&De.append(h("small","",ce.hint)),ue.append(De),lt.push(()=>{ke.value!==ce.value()&&ce.onChange(ke.value)})}}return ue},Or=[At,...(fe??[]).map(Ks)];if(Or.length>1){let le=h("div","ra-tabs");le.setAttribute("role","tablist");let ue=[t.sTabModel,...(fe??[]).map(ke=>ke.label)].map((ke,De)=>{let qe=h("button","ra-tab",ke);return qe.type="button",qe.setAttribute("role","tab"),qe.addEventListener("click",()=>ce(De)),qe}),ce=ke=>{ao=ke,Or.forEach((De,qe)=>{De.hidden=qe!==ke}),ue.forEach((De,qe)=>{De.classList.toggle("on",qe===ke),De.setAttribute("aria-selected",String(qe===ke))})};le.append(...ue),Te.append(le,...Or),ce(Math.min(ao,Or.length-1))}else Te.append(At);let Co=h("div","ra-btns"),Vs=h("button","ra-btn xs ghost",t.reset);Vs.type="button";let Gs=h("button","ra-btn xs solid",t.apply);Gs.type="button",Co.append(Vs,Gs),Te.append(Co),Vs.addEventListener("click",()=>{for(let le of(fe??[]).flatMap(ue=>ue.fields))le instanceof HTMLElement||le.default===void 0||(le.type,le.value()!==le.default&&le.onChange(le.default));Ue={},io({}),Bn=null;for(let le of We.values())lo(le,{},null);Me(),Z.notify(t.applied),Et(F)}),Gs.addEventListener("click",()=>{let le={};m.value&&(le.model=m.value);let ue=parseInt(D.value,10);if(Number.isFinite(ue)&&ue>0&&Math.min(1e3,ue)!==(B.maxTurns??100)&&(le.maxTurns=Math.min(1e3,ue)),W.value==="n"){let ce=parseInt(Q.value,10);Number.isFinite(ce)&&ce>0&&(le.maxTokens=ce)}v.value&&!v.disabled&&(le.reasoningEffort=v.value),(ne.value==="ask"||ne.value==="auto")&&(Bn=ne.value);for(let ce of lt)ce();$r(le),Me(),Z.notify(t.applied)})};Be.addEventListener("click",()=>{js()});let po=[],Me=()=>{Te?.remove(),Te=null;for(let i of po.splice(0))i.close()},Pr=i=>{j.append(i),i.style.top=`${_t.offsetTop+_t.offsetHeight+4}px`},uo=async()=>{if(Te){Me();return}if(!F?.workspace)return;let i=F.workspace,c=h("div","ra-menu");Te=c,Pr(c);let f=[];try{f=await i.sessions.list()}catch{}if(Te!==c)return;let g=F,m=f.filter(k=>k.id!==g.id),y=f.find(k=>k.id===g.id),v=k=>{let L=!k||k.id===g.id,E=h("div","ra-mi"+(L?" ra-cur":"")),$=h("button");$.type="button";let D=k?We.get(k.id):void 0,W=k&&D&&D!==g?zt.has(k.id)?` \xB7 ${t.waitingAnswer}`:D.busy||D.queued.length?` \xB7 ${t.running}`:"":"",Q=h("span","ra-mt");if(W&&!zt.has(k.id)&&Q.append(h("span","ra-spin")),Q.append(h("span","ra-mtt",(k?k.title:yr(g))||t.untitled)),L&&(Q.append(h("span","ra-now",t.current)),E.setAttribute("aria-current","true")),$.append(Q,h("small","",k?`${k.messages} ${t.messages} \xB7 ${new Date(k.savedAt).toLocaleString()}${W}`:t.notSaved)),$.addEventListener("click",()=>{Me(),k&&!L&&Mo(k.id).catch(ne=>Z.notify(ne.message,"error"))}),E.append($),k){let ne=h("button","ra-x");ne.type="button",ne.innerHTML=U.trash(),ne.title=t.delete,ne.setAttribute("aria-label",t.delete),ne.addEventListener("click",async he=>{he.stopPropagation(),Me(),await ut(j,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await Ws(k.id,!1,k.workspace).catch(Ie=>Z.notify(Ie.message,"error"))}),E.append(ne)}return E};c.append(v(y??null)),m.length?c.append(h("div","ra-sep")):c.append(h("div","ra-none",t.noSessions));for(let k of m)c.append(v(k));if(m.length){let k=h("div","ra-mf"),L=h("button","ra-btn xs ghost");L.type="button",L.innerHTML=U.trash()+xe(t.deleteAll),L.addEventListener("click",async()=>{if(Me(),!!await ut(j,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let E of f)await Ws(E.id,!0,E.workspace);await Vn()}catch(E){Z.notify(E.message,"error")}}),k.append(L),c.append(k)}};Xe.addEventListener("click",()=>{uo()}),ht.addEventListener("click",()=>{Me(),Vn().catch(i=>Z.notify(i.message,"error"))}),ze.addEventListener("click",async()=>{Me(),await ut(j,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await Bs().catch(i=>Z.notify(i.message,"error"))}),document.addEventListener("click",fo,!0);function fo(i){i.target?.closest?.(".ra-selp")||Te&&!Te.contains(i.target)&&!Xe.contains(i.target)&&!Be.contains(i.target)&&!Ye.contains(i.target)&&!$e.contains(i.target)&&Me()}let wt=h("input");wt.type="file",wt.accept=".zip,application/zip",wt.multiple=!0,wt.style.display="none",j.append(wt);let ho=async i=>{let c=F?.workspace;if(!c||!i?.length)return;let f=[];for(let g of Array.from(i)){if(!/\.zip$/i.test(g.name)&&g.type!=="application/zip"&&g.type!=="application/x-zip-compressed"){Z.notify(`${g.name}: ${t.notZip}`,"warning");continue}try{f.push(...(await c.installSkill(g)).map(m=>m.name))}catch(m){Z.notify(`${g.name}: ${m.message}`,"error")}}f.length&&Z.notify(t.skillsInstalled.replace("{names}",f.join(", "))),await Ct(),Te?.classList.contains("ra-skm")&&(Me(),go())};wt.addEventListener("change",()=>{ho(wt.files),wt.value=""});let go=async()=>{if(Te){let y=Te.classList.contains("ra-skm");if(Me(),y)return}let i=F?.workspace;if(!i)return;let c=h("div","ra-menu ra-skm");Te=c,Pr(c);let f=[];try{f=await i.skills()}catch(y){Z.notify(y.message,"error")}if(Te!==c)return;let g=h("div","ra-skh"),m=h("button","ra-btn xs solid");m.type="button",m.innerHTML=U.upload(13)+`<span>${xe(t.uploadZip)}</span>`,m.addEventListener("click",()=>wt.click()),i.userSkillsDir||(m.style.display="none"),g.append(h("span","",f.length?`${t.skills} \xB7 ${f.length}`:t.skills),m),c.append(g),f.length||c.append(h("div","ra-none",t.noSkills));for(let y of f){let v=h("div","ra-mi"),k=h("button");k.type="button",k.title=t.useSkill;let L=h("span","ra-mt"),E=!!y.from&&/\.zip$/i.test(y.from);L.append(h("span","ra-mtt",y.name),h("span","ra-skb",y.builtin?t.builtinSkill:E?"zip":t.skillFolder)),y.disableModelInvocation&&L.append(h("span","ra-skb",t.manualOnly)),k.append(L,h("small","",y.description)),k.addEventListener("click",()=>{Me(),S.value=`/skill:${y.name} `,S.focus(),Ge()});let $=(ne,he,Ie,At="ra-x ra-ia")=>{let lt=h("button",At);return lt.type="button",lt.innerHTML=ne,lt.title=he,lt.setAttribute("aria-label",he),lt.addEventListener("click",Ks=>{Ks.stopPropagation(),Ie()}),lt},D=$(U.eye(),t.open,()=>{Me(),Un(y.from&&!E?`${y.from}/SKILL.md`:y.path)}),W=$(U.download(),t.download,()=>{E?Ne.download(y.from):Ne.downloadFolder(y.from??y.dir)}),Q=$(U.trash(),t.delete,async()=>{Me();let ne=E?f.filter(Ie=>Ie.from===y.from).map(Ie=>Ie.name):[y.name],he=ne.length>1?t.confirmDeleteZip.replace("{zip}",y.from.replace(/^.*\//,"")).replace("{names}",ne.join("\u3001")):t.confirmDeleteSkill.replace("{name}",y.name).replace("{path}",y.from??"");if(await ut(j,t.delete,he,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await i.removeSkill(y.name),await Ct(),Z.notify(t.skillRemoved.replace("{name}",ne.join(", ")))}catch(Ie){Z.notify(Ie.message,"error")}},"ra-x");(y.builtin||!y.from?.startsWith((i.userSkillsDir??"\0")+"/"))&&(Q.style.display="none"),v.append(k,D,W,Q),c.append(v)}c.append(h("div","ra-skf",(i.userSkillsDir?t.skillsHint.replace("{user}",i.userSkillsDir):t.skillsHintNoUser).replace("{dir}",i.skillsDir))),i.userSkillsDir&&c.addEventListener("dragover",y=>{y.dataTransfer?.types.includes("Files")&&(y.preventDefault(),y.stopPropagation(),c.classList.add("drop"))}),c.addEventListener("dragleave",()=>c.classList.remove("drop")),i.userSkillsDir&&c.addEventListener("drop",y=>{y.preventDefault(),y.stopPropagation(),c.classList.remove("drop"),ho(y.dataTransfer?.files)})};Ye.addEventListener("click",()=>{go()});let mo=i=>Z.notify(i.message,"error"),_r=!1,ll=i=>{let c=[`# ${yr(i)}`,""];for(let f of i.messages){if(f.role==="tool"||f.role==="system")continue;let g=vn(f.content).trim(),m=f.role==="user"&&typeof f.content=="string"?Ze(f):null;if(m!==null){c.push(`> **${t.compacted}**`,">",...m.split(`
|
|
725
725
|
`).map(v=>`> ${v}`),"");continue}let y=f.role==="assistant"?(f.tool_calls??[]).filter(v=>!Ds.has(v.function.name)):[];if(!(!g&&!y.length)){c.push(`## ${f.role==="user"?t.user:t.assistant}`,""),g&&c.push(g,"");for(let v of y){let k=v.function.arguments;try{k=JSON.parse(v.function.arguments)}catch{}let L=ki(v.function.name,k);c.push(`- \`${v.function.name}\`${L?` ${L}`:""}`)}y.length&&c.push("")}}return c.join(`
|
|
726
|
-
`)},cl=(i,c)=>{let f=c.toLowerCase(),g=i.find(y=>y.id.toLowerCase()===f);if(g)return g;let m=i.filter(y=>y.id.toLowerCase().includes(f));return m.length===1?m[0]:m.find(y=>y.id.toLowerCase().startsWith(f))},Ns=[{name:"help",run:()=>{let i=qs().map(c=>`- \`/${c.name}${c.args?` ${c.args}`:""}\` \u2014 ${c.description}`);
|
|
727
|
-
`))}},{name:"new",aliases:["clear"],run:()=>(Me(),ze.style.display==="none"?Vn().then(()=>{}):Bs())},{name:"resume",run:()=>uo()},{name:"compact",args:t.cmdArgs.compact,run:async i=>{let c=F;if(c.busy){Z.notify(t.busyCmd,"warning");return}_r=!0;try{await c.compact(i)||Z.notify(t.nothingToCompact)}catch(f){if(!/abort/i.test(f.message??"")&&f.name!=="AbortError")throw f;Z.notify(t.stopped)}finally{_r=!1,F===c&&(kr(),Et(c),setTimeout(()=>{F===c&&!c.busy&&Ft(!1)},0))}}},{name:"continue",run:async()=>{if(F.busy){Z.notify(t.busyCmd,"warning");return}if(!F.messages.length){Z.notify(t.nothingToContinue);return}await F.continue()}},{name:"model",args:t.cmdArgs.model,run:async i=>{if(!i)return
|
|
728
|
-
`))}},{name:"export",run:()=>{if(!F.messages.length){Z.notify(t.nothingToExport);return}let i=yr(F).replace(/[\\/:*?"<>|\s]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"conversation";or(`${i}.md`,ll(F),"text/markdown;charset=utf-8")}},{name:"files",run:()=>Oe===!1?void 0:nt.click()},{name:"settings",run:()=>
|
|
726
|
+
`)},cl=(i,c)=>{let f=c.toLowerCase(),g=i.find(y=>y.id.toLowerCase()===f);if(g)return g;let m=i.filter(y=>y.id.toLowerCase().includes(f));return m.length===1?m[0]:m.find(y=>y.id.toLowerCase().startsWith(f))},Ns=[{name:"help",run:()=>{let i=qs().map(c=>`- \`/${c.name}${c.args?` ${c.args}`:""}\` \u2014 ${c.description}`);Hn(t.cmdsTitle,[...i,"",t.cmdsMore].join(`
|
|
727
|
+
`))}},{name:"new",aliases:["clear"],run:()=>(Me(),ze.style.display==="none"?Vn().then(()=>{}):Bs())},{name:"resume",run:()=>uo()},{name:"compact",args:t.cmdArgs.compact,run:async i=>{let c=F;if(c.busy){Z.notify(t.busyCmd,"warning");return}_r=!0;try{await c.compact(i)||Z.notify(t.nothingToCompact)}catch(f){if(!/abort/i.test(f.message??"")&&f.name!=="AbortError")throw f;Z.notify(t.stopped)}finally{_r=!1,F===c&&(kr(),Et(c),setTimeout(()=>{F===c&&!c.busy&&Ft(!1)},0))}}},{name:"continue",run:async()=>{if(F.busy){Z.notify(t.busyCmd,"warning");return}if(!F.messages.length){Z.notify(t.nothingToContinue);return}await F.continue()}},{name:"model",args:t.cmdArgs.model,run:async i=>{if(!i)return js();let c=cl(await Wn(),i);if(!c){Z.notify(t.unknownModel.replace("{name}",i),"warning");return}let f={...Ue};c.is_default&&!B.model?delete f.model:f.model=c.id;let g=Hs(c);f.reasoningEffort&&!g?.levels.includes(f.reasoningEffort)&&delete f.reasoningEffort,$r(f),Z.notify(t.modelSet.replace("{name}",c.id))}},{name:"effort",args:t.cmdArgs.effort,run:async i=>{let c=await Wn(),f=F.model||c.find(L=>L.is_default)?.id,g=c.find(L=>L.id===f),m=Hs(g),y=g?.id??f??"?";if(!m){Z.notify(`${y}: ${t.sEffortNone}`,"warning");return}let v=m.levels.join(" / ");if(!i){Z.notify(t.effortLevels.replace("{model}",y).replace("{levels}",v));return}let k={...Ue};if(/^(default|auto|默认)$/i.test(i))delete k.reasoningEffort;else if(m.levels.includes(i.toLowerCase()))k.reasoningEffort=i.toLowerCase();else{Z.notify(t.unknownEffort.replace("{name}",i).replace("{model}",y).replace("{levels}",v),"warning");return}$r(k),Z.notify(t.effortSet.replace("{name}",k.reasoningEffort??(m.def?`${t.sEffortDefault} \xB7 ${m.def}`:t.sEffortDefault)))}},{name:"context",run:async()=>{let i=F,[c,f,g]=await Promise.all([i.context(),i.limits(),i.modelInfo()]),m=co(g),y=Math.round(c.used/c.window*100),v=i.usage,k=B.compaction,L=[`- ${t.sModel}: ${i.model||(await Wn()).find(E=>E.is_default)?.id||t.sDefault}`,`- ${t.context}: ${y<1&&c.used?"<1":y}% \xB7 ${Je(c.used)} / ${Je(c.window)} tokens \xB7 ${t.sMaxTokens} ${Je(f.output)}`,m?`- ${t.sPrice}: ${m}`:"",`- ${t.messagesLabel}: ${i.messages.length}`,v.calls?`- ${Dt(t.usageLine.replace("{cost}",Ti(v.total_cost,g?.price?.currency)).replace("{tokens}",Je(v.prompt_tokens+v.completion_tokens)).replace("{calls}",String(v.calls)))}`:"",k===!1?"":`- ${t.autoCompact}: ${t.autoCompactAt.replace("{n}",Je(Math.min(16384,Math.floor(c.window*.2))))}`,i.workspace?`- ${t.directory}: \`${i.workspace.id}\``:""].filter(Boolean);Hn(t.context,L.join(`
|
|
728
|
+
`))}},{name:"export",run:()=>{if(!F.messages.length){Z.notify(t.nothingToExport);return}let i=yr(F).replace(/[\\/:*?"<>|\s]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"conversation";or(`${i}.md`,ll(F),"text/markdown;charset=utf-8")}},{name:"files",run:()=>Oe===!1?void 0:nt.click()},{name:"settings",run:()=>js()},{name:"debug",run:()=>{It?Ae.click():Z.notify(t.debugOff)}}],qs=()=>Ns.filter(i=>(i.name!=="files"||!!F?.workspace&&Oe!==!1)&&(i.name!=="settings"||oo)&&(i.name!=="debug"||It)&&(i.name!=="resume"||!a&&!!F?.workspace&&ze.style.display==="none")).map(i=>({name:i.name,description:i.name==="new"&&ze.style.display!=="none"?t.confirmClear.split(/[??]/)[0]:t.cmd[i.name]??"",kind:t.command,args:i.args,builtin:!0})),dl=i=>{let c=/^\/(\S+)(?:\s+([\s\S]*))?$/.exec(i);if(!c)return!1;let f=c[1].toLowerCase(),g=Ns.find(m=>m.name===f||m.aliases?.includes(f));if(!g||!qs().some(m=>m.name===g.name))return!1;S.value="",Ge();try{Promise.resolve(g.run((c[2]??"").trim())).catch(mo)}catch(m){mo(m)}return!0},yo=i=>{if(i.builtin&&(!i.args||S.value.trim()===`/${i.name}`)){S.value=`/${i.name}`,nn("prompt");return}S.value=`/${i.name} `,Ge()},Rr,Et=i=>{if(!(te===!1||F!==i)){if(!i.messages.length){$e.style.display="none",Te?.classList.contains("ra-use")&&Me();return}Promise.all([i.context(),i.modelInfo()]).then(([c,f])=>{if(F!==i)return;Rr=f?.price?.currency;let g=Math.min(1,c.used/c.window),m=8,y=2*Math.PI*m;$e.innerHTML=`<svg class="ra-ring${g>=.9?" hi":g>=.7?" mid":""}" viewBox="0 0 20 20" aria-hidden="true"><circle class="tr" cx="10" cy="10" r="${m}"/><circle class="pr" cx="10" cy="10" r="${m}" stroke-dasharray="${y.toFixed(2)}" stroke-dashoffset="${(y*(1-Math.max(g,.03))).toFixed(2)}" transform="rotate(-90 10 10)"/></svg>`;let v=`${wo(t.context)} ${bo(c.used,c.window)}`;$e.title=v,$e.setAttribute("aria-label",v),$e.style.display="",Te?.classList.contains("ra-use")&&xo(Te,i,c)})}},wo=i=>i.charAt(0).toUpperCase()+i.slice(1),bo=(i,c)=>{let f=i/c;return i&&f<.01?"<1%":`${Math.round(Math.min(1,f)*100)}%`},xo=(i,c,f)=>{let g=Math.min(1,f.used/f.window),m=c.usage;i.className="ra-menu ra-use"+(g>=.9?" hi":g>=.7?" mid":"");let y=h("div","ra-uh");y.append(h("span","",wo(t.context)),h("b","",bo(f.used,f.window)));let v=h("div","ra-ubar"),k=h("i");k.style.width=`${Math.max(g,f.used?.01:0)*100}%`,v.append(k);let L=h("div","ra-usub");L.append(h("span","",t.uOf.replace("{used}",Je(f.used)).replace("{window}",Je(f.window))),h("span","",c.model||jt?.find(W=>W.is_default)?.id||""));let E=h("div","ra-ugrid");for(let[W,Q]of[[t.uCost,Ti(m.total_cost,Rr)],[t.uIn,Je(m.prompt_tokens)],[t.uOut,Je(m.completion_tokens)],[t.uCalls,String(m.calls)]]){let ne=h("div");ne.append(h("small","",W),h("b","",Q)),E.append(ne)}i.replaceChildren(y,v,L,E),B.compaction!==!1&&i.append(h("div","ra-unote",`${t.autoCompact}: ${t.autoCompactAt.replace("{n}",Je(Math.min(16384,Math.floor(f.window*.2))))}`));let $=h("div","ra-mf"),D=h("button","ra-btn xs ghost");D.type="button",D.textContent=t.compactNow,D.disabled=c.busy||_r,D.addEventListener("click",()=>{Me(),Promise.resolve(Ns.find(W=>W.name==="compact").run("")).catch(W=>Z.notify(W.message,"error"))}),$.append(D),i.append($)},pl=async()=>{if(Te?.classList.contains("ra-use")){Me();return}if(Me(),!F)return;let i=F,c=h("div","ra-menu ra-use");Te=c,Pr(c);let f=await i.context();Te===c&&F===i&&xo(c,i,f)};$e.addEventListener("click",()=>{pl()});let vo=(i,c)=>{if(!c)return;let f=()=>{try{i.continue().catch(g=>Z.notify(g.message,"error"))}catch(g){Z.notify(g.message,"error")}};c.reason==="error"?Rs(c.error??t.error,i.messages.length?f:void 0):c.reason==="max_turns"?tl(t.maxTurns.replace("{n}",String(i.settings.maxTurns)),{label:t.continueRun,onClick:f},t.maxTurnsHint):Hn(t.stopped)},ko=async i=>{for(let m of On)m();if(On=[],i.workspace){let m=i.workspace;On.push(m.onChange(y=>{m.isSkillPath(y.path)&&Ct()}))}F&&F!==i&&zn.set(F.id,Z.park()),F!==i&&jn(),F=i,We.set(i.id,i),wr(i),Z.restore(zn.get(i.id)??[]),zn.delete(i.id),ks(i.id),Ut(),Yt.clear(),X=null,yt=null,ye.textContent=i.model??"",ye.style.display=i.model?"":"none";let c=!a&&(C??!!i.workspace);Xe.style.display=ht.style.display=c&&i.workspace?"":"none",ze.style.display=c&&i.workspace?"none":"",nt.style.display=i.workspace&&Oe!==!1?"":"none",Ye.style.display=i.workspace&&M!==!1?"":"none",Ne.setWorkspace(i.workspace),It&&et.setAgent(i),be.clear(),Ui(),Ft(i.busy),qn(),a||Ea(ie,i.id);let f=(m,y)=>On.push(i.on(m,y));f("run_start",m=>{m.message&&(yt&&!yt.msg?(yt.msg=m.message,yt.update()):xr(m.message.content,m.message),Oi(i,m.message)),yt=null,X=null,In=Date.now(),Ft(!0),st()}),f("turn_start",()=>{Fn(!0),X&&(X.text=null,X.md="",X.drawn=void 0,X.drawnFinal=void 0,X.think=null,X.thinkBody=null,X.reasoning=""),st(),queueMicrotask(it)}),f("steered",m=>{kr(),In=Date.now();for(let y of m.messages)xr(y.content,y);it()}),f("queued",()=>it()),f("rewind",()=>{F===i&&(Mr(i.messages),Et(i))}),f("text_delta",m=>{let y=Tr();As(y),y.text||(y.text=h("div","ra-md"),Es(y.body,y.text)),y.md=m.text,Xi()}),f("reasoning_delta",m=>{let y=Tr();if(!y.pending&&!y.text&&st(),!y.think){[y.think,y.thinkBody]=Gi("",!1),y.think.style.display="none";let v=Ki(y.body);v instanceof HTMLDetailsElement&&v.classList.contains("ra-tg")&&!y.text?v.querySelector(".ra-tgb").append(y.think):y.text?y.body.insertBefore(y.think,y.text):Es(y.body,y.think)}y.reasoning=m.text,Xi()}),f("message_reset",()=>{X&&(X.md="",X.reasoning="",X.text?.remove(),X.text=null,X.think?.remove(),X.think=null,X.thinkBody=null,st())}),f("message_end",()=>{As(),Fn(!0),en=Date.now()}),f("tool_start",m=>{if(Ds.has(m.name))return;Fn(!0);let y=Qa(m.id,m.name,m.args,Tr().body),v=eo({name:m.name,args:m.args},y.el);st(v.title?`${v.verb} ${v.what}`:v.verb,Ga(m.name,m.args))}),f("tool_update",m=>{let y=Yt.get(m.id);y&&(y.update||(y.update=h("div","ra-tupd"),y.el.append(y.update)),y.update.textContent=m.content,X?.pending&&st(X.pending.firstElementChild.textContent??t.waiting,{text:m.content}),be.schedule())}),f("tool_end",m=>{let y=Yt.get(m.id);if(y)to(y,m.status,m.result,m.durationMs,_s(m.content),m.details);else{let k=Rn.get(m.id);k&&(k.status=m.status,k.result=m.result,Rn.delete(m.id))}let v=y?.args&&typeof y.args=="object"?y.args.path:void 0;m.status==="ok"&&typeof v=="string"&&/^(write_file|edit_file|delete_file)$/.test(m.name)&&Ne.changed(v),X?.pending&&!X.body.querySelector(".ra-tend .ra-spin")&&st()});let g=null;f("compaction_start",m=>{m.runId||(Ft(!0),In=Date.now()),st(t.compactingNow)}),f("compaction",m=>{if(m.runId?X?.pending&&st():kr(),!m.summary&&m.runId&&g===m.runId)return;m.summary||(g=m.runId??null);let y=i.messages[0],v=y&&typeof y.content=="string"?Ze(y):null;Hn(m.summary?t.compacted:t.trimmed,m.summary&&v?v:void 0)}),f("run_end",m=>{Mt=m.reason==="done"&&!S.value.trim()?Cr:null,Cr=null;let y=X;kr();let v=[...i.messages].reverse().find(k=>k.role==="assistant");y&&y.body.childElementCount&&v&&!y.el.querySelector(":scope>.ra-af")&&(y.el.append(qi(v)),be.schedule()),Z.cancelAll(),vo(i,m.reason==="done"?null:{reason:m.reason,error:m.error?.message,at:Date.now()}),Ft(!1),Et(i),Ct(),Ne.refresh(),Ss()});try{await i.ready()}catch(m){Rs(m.message)}F!==i||!gr||(ve?.(i),Mr(i.messages),i.busy||vo(i,i.lastEnd),Et(i),Ss(),await Ct())},ul=()=>`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,To=async i=>{let c=i??ul(),f=typeof l=="function"?await l(c):l??null,g=B.instructions,m=Oe===!1?Zc(H):Xc(H),y=f?typeof g=="function"?()=>[g(),m].filter(Boolean).join(`
|
|
729
729
|
|
|
730
730
|
`):[g,m].filter(Boolean).join(`
|
|
731
731
|
|
|
732
|
-
`):g,v={};return Ue.model&&(v.model=Ue.model),Ue.maxTurns&&(v.maxTurns=Ue.maxTurns),Ue.maxTokens&&(v.maxTokens=Ue.maxTokens),Ue.reasoningEffort&&(v.extra={...B.extra??{},reasoning_effort:Ue.reasoningEffort}),Bn&&(v.permissions=Bn),new Lt(K,{...B,...v,tools:no,instructions:y,id:c,workspace:f,ui:B.ui??
|
|
732
|
+
`):g,v={};return Ue.model&&(v.model=Ue.model),Ue.maxTurns&&(v.maxTurns=Ue.maxTurns),Ue.maxTokens&&(v.maxTokens=Ue.maxTokens),Ue.reasoningEffort&&(v.extra={...B.extra??{},reasoning_effort:Ue.reasoningEffort}),Bn&&(v.permissions=Bn),new Lt(K,{...B,...v,tools:no,instructions:y,id:c,workspace:f,ui:B.ui??Ha(c)})},Dr=i=>{et.forget(i),typeof l=="function"&&i.workspace?.close()},Kn=null,So=i=>{if(a)return Promise.reject(new Error("newSession/resume need the chat to own its agent (pass a provider, not an agent)"));if(Kn)return Kn;let c=(async()=>{if(i&&i===F?.id)return F;let f=F;if(f)if(f.busy||f.queued.length>0){if(Ts().length>=Fa)return Z.notify(t.bgLimit.replace("{n}",String(Ts().length)),"warning"),f;ja(f)}else We.delete(f.id),Dr(f);let g=i&&We.get(i)||await To(i);return await ko(g),g})();return Kn=c,c.finally(()=>{Kn===c&&(Kn=null)}).catch(()=>{}),c},Vn=()=>So(),Bs=async()=>{await Gn;let i=F??a;Z.cancelAll(),await i.clear(),(F===i||a===i)&&(Mr(i.messages),Et(i),it(),qn())},Mo=i=>So(i),Ws=async(i,c=!1,f)=>{if(await Gn,a)throw new Error("deleteSession needs the chat to own its agent (pass a provider, not an agent)");let g=F.workspace;if(g){if(i!==F.id){let m=We.get(i);m&&(ks(i,!1),zn.delete(i),await m.abort(),We.delete(i),wr(m),Dr(m),Ut()),await g.sessions.delete(i,f),Ss();return}Z.cancelAll(),await F.abort(),typeof l=="function"?await g.destroy():await g.sessions.delete(i,g.id),Ea(ie,null),c||await Vn()}},fl=B.id??(typeof d=="string"?d:d===!1?void 0:Qc(ie)??void 0),Gn=(a?Promise.resolve(a):To(fl)).then(i=>ko(i));return Gn.catch(i=>{Rs(`${i.message}`),Ft(!1)}),{get agent(){return F??a},get ready(){return Gn},element:j,ui:Z,prompt:async i=>(await Gn,F.busy||(yt=xr(i)),F.prompt(i)),setInput(i){S.value=i,S.focus(),Ge()},insertText(i){let c=document.activeElement===S?S.selectionStart:S.value.length,f=document.activeElement===S?S.selectionEnd:c,g=S.value.slice(0,c),m=S.value.slice(f),y=(g&&!/\s$/.test(g)?" ":"")+i+(m&&/^\S/.test(m)?" ":m?"":" ");S.value=g+y+m,S.focus(),S.setSelectionRange(g.length+y.length,g.length+y.length),Ge()},newSession:Vn,resume:Mo,deleteSession:i=>Ws(i),clear:Bs,addContext:so,setDebug(i){It=i,br()},updateComposerAction(i,c){let f=Ei.get(i);f&&(Object.assign(f.a,c),Ai(f.btn,f.a))},setAppearance(i){i.theme&&(re=i.theme),i.palette&&(Ee=i.palette),i.vars!==void 0&&(Re=i.vars),Gt()},refresh:Ct,unmount(){if(gr){gr=!1,Qt&&clearTimeout(Qt);for(let i of On)i();Z.cancelAll(!0),Me(),document.removeEventListener("click",fo,!0),xt?.removeEventListener?.("change",Mn),kt!==null&&clearTimeout(kt),Dn!==null&&cancelAnimationFrame(Dn),be.dispose(),_i?.disconnect(),Ne.dispose(),et.dispose();for(let i of ot)i.preview&&URL.revokeObjectURL(i.preview);for(let i of[...Tt.keys()])ks(i,!1);if(!a)for(let i of We.values())wr(i),i.abort().finally(()=>Dr(i));We.clear(),zn.clear(),Tt.clear(),ot.length=0,at.length=0,j.remove()}}}}var ed=/^(text\/|application\/(json|xml|yaml|javascript|x-sh))/;function Ci(r){let e=V(r);return e==="/"?[]:e.slice(1).split("/")}function Oa(r){return new Error(`No such file: ${V(r)}`)}function za(r,e={}){let n=async(l,d=!1)=>{let p=r;for(let u of l)p=await p.getDirectoryHandle(u,{create:d});return p},t=async(l,d=!1)=>{let p=Ci(l);if(!p.length)throw new Error(`${V(l)} is a folder, not a file`);return(await n(p.slice(0,-1),d)).getFileHandle(p[p.length-1],{create:d})},s=async(l,d)=>{let p=await d.getFile();return{path:V(l),size:p.size,contentType:p.type||dt(l,new Uint8Array),mtime:p.lastModified}},o=async(l,d,p)=>{for await(let[u,w]of l){let x=`${d}/${u}`;w.kind==="directory"?await o(w,x,p):p.push(await s(x,w))}},a={description:e.description??`the local folder "${r.name}"`,async list(l){let d=[],p=Ci(l),u;try{u=await n(p)}catch{try{let w=await t(l);return[await s(l,w)]}catch{return d}}return await o(u,p.length?"/"+p.join("/"):"",d),d},async stat(l){try{return await s(l,await t(l))}catch{return null}},async read(l){let d;try{d=await t(l)}catch{throw Oa(l)}let p=await d.getFile(),u=new Uint8Array(await p.arrayBuffer()),w=p.type||dt(l,u);if(ed.test(w)){let x=pt(u);if(x!==null)return x}return u}};return e.readonly||(a.write=async(l,d)=>{let u=await(await t(l,!0)).createWritable();try{await u.write(d)}finally{await u.close()}},a.delete=async l=>{let d=Ci(l);if(!d.length)throw new Error("Cannot delete /");let p=await n(d.slice(0,-1));try{await p.removeEntry(d[d.length-1],{recursive:!0})}catch(u){throw u?.name==="NotFoundError"?Oa(l):new Error(`${l}: ${u?.message??String(u)}`)}}),a}return xl(td);})();
|