@runappsai/agent 0.1.9 → 0.1.11
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 +34 -34
- package/dist/agent.d.ts +16 -0
- package/dist/agent.js +37 -7
- package/dist/agent.umd.js +112 -104
- package/dist/chat-theme.js +3 -0
- package/dist/chat.js +77 -13
- package/dist/compaction.d.ts +10 -0
- package/dist/index.cjs +33 -7
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/ui.cjs +103 -10
- package/docs/agent.md +3 -1
- package/docs/chat-ui.md +3 -3
- package/docs/reference.md +2 -1
- package/package.json +1 -1
package/dist/agent.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/* @runappsai/agent 0.1.
|
|
2
|
-
"use strict";var RunAppsAgent=(()=>{var
|
|
1
|
+
/* @runappsai/agent 0.1.11 */
|
|
2
|
+
"use strict";var RunAppsAgent=(()=>{var ts=Object.defineProperty;var ec=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var nc=Object.prototype.hasOwnProperty;var rc=(r,e,n)=>e in r?ts(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var sc=(r,e)=>{for(var n in e)ts(r,n,{get:e[n],enumerable:!0})},oc=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tc(e))!nc.call(r,s)&&s!==n&&ts(r,s,{get:()=>e[s],enumerable:!(t=ec(e,s))||t.enumerable});return r};var ic=r=>oc(ts({},"__esModule",{value:!0}),r);var D=(r,e,n)=>rc(r,typeof e!="symbol"?e+"":e,n);var Xd={};sc(Xd,{Agent:()=>Ut,CHAT_COLOR_TOKENS:()=>Qa,CHAT_PALETTES:()=>_s,CHAT_SHARED_TOKENS:()=>el,ContextOverflowError:()=>Ot,DEFAULT_COMPACTION:()=>Xt,DEFAULT_SKILLS_DIR:()=>Eo,DEFAULT_USER_SKILLS_DIR:()=>Ao,MCPError:()=>Pe,PartialReadError:()=>en,ProviderError:()=>et,UNTITLED:()=>It,VirtualList:()=>Dn,WEB_TOOL_NAMES:()=>_o,Workspace:()=>$n,applyEdits:()=>hs,askUserTool:()=>As,buildSystemPrompt:()=>ss,buildZip:()=>fs,collectCompletion:()=>yr,configurePdf:()=>ka,connectMCP:()=>Wa,createAgent:()=>pd,decodeText:()=>wt,defineTool:()=>Fe,directoryFS:()=>wl,domUI:()=>Es,enhanceSelect:()=>dl,escapeHTML:()=>ve,estimateTokens:()=>Me,expandSlash:()=>ls,extractPdfText:()=>En,fileGuard:()=>Ln,fileTools:()=>Ts,fitBudget:()=>hr,formatPdfText:()=>An,groupTurns:()=>mo,guessType:()=>yt,isContextOverflow:()=>ns,isPdf:()=>Mn,listTemplates:()=>as,listZip:()=>ps,memoryFS:()=>$a,modelAccepts:()=>Dt,normalizeForFuzzyMatch:()=>To,normalizePath:()=>Q,normalizeResult:()=>wr,nullUI:()=>Do,openAIProvider:()=>ua,openWorkspace:()=>fd,parseCommandArgs:()=>xo,parseFrontmatter:()=>ko,parseSkill:()=>xr,planCut:()=>os,readZipEntry:()=>kn,renderChat:()=>gl,renderInline:()=>Mt,renderMarkdown:()=>On,runInSandbox:()=>Po,runappsProvider:()=>ho,sandboxTool:()=>Cs,selectBox:()=>Ar,serializeConversation:()=>gr,skillFoldersOf:()=>vr,skillZipFS:()=>Sn,splitForSummary:()=>is,sseData:()=>fr,subFS:()=>kr,substituteArgs:()=>vo,summaryMessage:()=>mr,summaryOf:()=>ze,titleOf:()=>Qt,toProvider:()=>ot,validateSchema:()=>Ss,webTools:()=>Ms});function Dt(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 et=class extends Error{constructor(n,t,s={}){super(t);D(this,"status");D(this,"code");D(this,"retryAfter");this.name="ProviderError",this.status=n,this.code=s.code,this.retryAfter=s.retryAfter}get statusCode(){return this.status}},ac={attachments:"The attachments on this message are too large for the model's context",message:"This message is too long for the model's context",tools:"The connected tools take up too much of the model's context",history:"This conversation is too long for the model's context",model:"This request does not fit the model's context"},Ot=class extends et{constructor(n,t,s=400){super(s,ac[n.cause],{code:"context_overflow"});D(this,"overflow");D(this,"detail");this.name="ContextOverflowError",this.overflow=n,this.detail=t}},lc=/context[_ ]length|context[_ ]window|maximum context|(?:prompt|input|request|message)s? (?:is |are )?too (?:long|large)|too many (?:input |prompt )?tokens|prompt tokens too many|exceed\w* .{0,30}(?:context|token limit|input token)|input token count|max_input_tokens|range of input length|payload too large|entity too large/i;function ns(r){if(r instanceof Ot)return!0;let e=rs(r);if(e===401||e===402||e===403||e===404||e===429)return!1;if(e===413)return!0;let n=r?.code;return n==="context_length_exceeded"||n==="context_overflow"?!0:r instanceof Error&&lc.test(r.message)}function da(r){let e=r instanceof Error?r.message:"",t=/its ([\d,]+) max_input_tokens|maximum context length is ([\d,]+)|> ?([\d,]+) maximum|context (?:window|length) of ([\d,]+)|token limit\D{0,5}([\d,]+)|\[1, ?([\d,]+)\]/i.exec(e)?.slice(1).find(Boolean),s=t?Number(t.replace(/,/g,"")):NaN;return s>=1e3?s:void 0}function rs(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 ho(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,platformTools:r.tools,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 ot(r){if(typeof r.stream=="function")return r;if(typeof r.chat?.stream=="function")return ho(r);throw new Error("pass a ModelProvider (with stream()) or a RunApps client")}function ua(r){let e=r.baseURL.replace(/\/+$/,""),n=r.fetch??((...i)=>fetch(...i)),t=()=>({"Content-Type":"application/json",...r.apiKey?{Authorization:`Bearer ${r.apiKey}`}:{},...r.headers??{}}),s=async(i,a)=>{let l;try{l=await n(`${e}/chat/completions`,{method:"POST",headers:t(),body:JSON.stringify(i),signal:a})}catch(d){throw a?.aborted?d:new et(0,`network error: ${d.message}`)}if(!l.ok)throw await ca(l);return l};return{name:r.name,async*stream(i,a){let l={...i,stream:!0,...r.streamUsage===!1?{}:{stream_options:{include_usage:!0}}},d=await s(l,a?.signal);if(!d.body)throw new et(0,"the response has no body to stream");for await(let p of fr(d.body,a?.signal)){if(p==="[DONE]")return;let h;try{h=JSON.parse(p)}catch{continue}if(h.error)throw new et(500,h.error.message??"stream error",{code:h.error.code});yield h}},async complete(i,a){return await(await s({...i,stream:!1},a?.signal)).json()},models:r.models===void 0?void 0:async()=>{if(Array.isArray(r.models))return r.models;let i=await n(`${e}/models`,{headers:t()});if(!i.ok)throw await ca(i);return((await i.json()).data??[]).map(({id:l,is_default:d,capability:p,max_input_tokens:h,max_tokens:w,options:k})=>({id:l,is_default:d,capability:p??"text",max_input_tokens:h,max_tokens:w,options:k}))}}}async function ca(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 et(r.status,e,{code:n,retryAfter:Number.isFinite(t)&&t>0?t:void 0})}async function*fr(r,e){let n=r.getReader(),t=new TextDecoder,s="",i=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",i,{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 h=s.slice(0,p);s=s.slice(p).replace(/^\r?\n\r?\n/,"");let w=h.split(/\r?\n/).filter(k=>k.startsWith("data:")).map(k=>k.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
|
-
`);a&&(yield a)}finally{e?.removeEventListener("abort",i),n.releaseLock()}e?.throwIfAborted()}function
|
|
4
|
+
`);a&&(yield a)}finally{e?.removeEventListener("abort",i),n.releaseLock()}e?.throwIfAborted()}function ss(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
|
|
|
6
6
|
<project_instructions path="${r.agentsPath??"/AGENTS.md"}">
|
|
7
7
|
${r.agentsMd.trim()}
|
|
@@ -27,17 +27,17 @@ There is no runtime for scripts here: a skill's scripts (Python, shell, JavaScri
|
|
|
27
27
|
<location>${l(d.path)}</location>
|
|
28
28
|
</skill>`).join(`
|
|
29
29
|
`)+`
|
|
30
|
-
</available_skills>`)}let a=[];for(let l of r.tools){let d=l.guidelines;if(d)for(let
|
|
30
|
+
</available_skills>`)}let a=[];for(let l of r.tools){let d=l.guidelines;if(d)for(let p of[].concat(d))p.trim()&&a.push(`- ${p.trim()}`)}return a.length&&n.push(`# Tool notes
|
|
31
31
|
`+a.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
|
|
34
|
+
`)}var cc=1600;function Me(r,e){let n=e?vn(e):0,t=0;for(let s of r){if(n+=16,typeof s.content=="string")n+=vn(s.content);else if(Array.isArray(s.content))for(let i of s.content)i.type==="text"?n+=vn(i.text):t++;if(s.tool_calls)for(let i of s.tool_calls)n+=vn(i.function.name)+vn(i.function.arguments)+24;typeof s.reasoning_content=="string"&&(n+=vn(s.reasoning_content))}return Math.ceil(n/3)+t*cc}function vn(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 hr(r,e){let n=Math.max(1,e.keepTurns),t=e.elideAbove??400,s=mo(r),i=0,a=0,l=()=>Me(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 h=typeof p.content=="string"?p.content:pa(p.content);return h.length<=t||h.startsWith("[result elided")?p:(i++,{...p,content:`[result elided to save context: ${h.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((k,v)=>k.role==="tool"?v:-1).filter(k=>k>=0);for(let k of p.slice(0,Math.max(0,p.length-(e.keepResults??3)))){if(!l())break;let v=d[k],T=typeof v.content=="string"?v.content:pa(v.content);T.length<=t||T.startsWith("[result elided")||(d[k]={...v,content:`[result elided to save context: ${T.length} characters; call the tool again if needed]`},i++)}let h=d[0]?.role==="user"?1:0,w=k=>{let v=k+1;for(;v<d.length&&d[v].role==="tool";)v++;return v};for(;l()&&!(d.slice(h).filter(v=>v.role==="assistant").length<=1||d[h]?.role!=="assistant");)d.splice(h,w(h)-h),a++}return{messages:s.flat(),droppedTurns:a,elidedResults:i}}function mo(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 pa(r){return r?r.map(e=>e.type==="text"?e.text:"").join(""):""}var Xt={reserveTokens:16384,keepRecentTokens:2e4},go=`The conversation history before this point was compacted into the following summary:
|
|
35
35
|
|
|
36
36
|
<summary>
|
|
37
|
-
`,
|
|
38
|
-
</summary>`,
|
|
37
|
+
`,yo=`
|
|
38
|
+
</summary>`,dc=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
|
|
39
39
|
|
|
40
|
-
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,
|
|
40
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,uc=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
41
41
|
|
|
42
42
|
Use this EXACT format:
|
|
43
43
|
|
|
@@ -68,7 +68,7 @@ Use this EXACT format:
|
|
|
68
68
|
- [Any data, examples, or references needed to continue]
|
|
69
69
|
- [Or "(none)" if not applicable]
|
|
70
70
|
|
|
71
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`,
|
|
71
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,pc=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
72
72
|
|
|
73
73
|
Update the existing structured summary with new information. RULES:
|
|
74
74
|
- PRESERVE all existing information from the previous summary
|
|
@@ -105,72 +105,72 @@ 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.`,
|
|
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]: ${
|
|
108
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,fc=2e3;function ze(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(go)||!r.content.endsWith(yo)?null:r.content.slice(go.length,r.content.length-yo.length)}function mr(r){return{role:"user",content:go+r+yo}}function zt(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??Xt.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??Xt.keepRecentTokens,Math.floor(r*.4))}}function wo(r,e,n){return r>e-n.reserveTokens}function os(r,e){if(r.length<2)return null;let n=0,t=-1;for(let a=r.length-1;a>=1;a--){n+=Me([r[a]]);let l=r[a].role;if((l==="user"||l==="assistant")&&(t=a,n>=e))break}if(t<=0)return null;let s,i=[];for(let a of r.slice(0,t)){let l=ze(a);l!==null&&s===void 0?s=l:i.push(a)}return i.length?{toSummarize:i,previousSummary:s,kept:r.slice(t)}:null}function gr(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
|
+
`);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]: ${hc(t,fc)}`)}return e.join(`
|
|
110
110
|
|
|
111
|
-
`)}function
|
|
111
|
+
`)}function hc(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 is(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 i=0;i<s.length;i+=e){let a=s.slice(i,i+e);t&&t.length+2+a.length>e&&(n.push(t),t=""),t=t?`${t}
|
|
114
114
|
|
|
115
|
-
${a}`:a}return t&&n.push(t),n}function
|
|
116
|
-
${typeof r=="string"?r:
|
|
115
|
+
${a}`:a}return t&&n.push(t),n}function fa(r,e,n){let t=`<conversation>
|
|
116
|
+
${typeof r=="string"?r:gr(r)}
|
|
117
117
|
</conversation>
|
|
118
118
|
|
|
119
119
|
`;return e&&(t+=`<previous-summary>
|
|
120
120
|
${e}
|
|
121
121
|
</previous-summary>
|
|
122
122
|
|
|
123
|
-
`),t+=e?
|
|
123
|
+
`),t+=e?pc:uc,n?.trim()&&(t+=`
|
|
124
124
|
|
|
125
|
-
The user asked this summary to focus on: ${n.trim()}`),[{role:"system",content:
|
|
126
|
-
References are relative to ${
|
|
125
|
+
The user asked this summary to focus on: ${n.trim()}`),[{role:"system",content:dc},{role:"user",content:t}]}async function yr(r,e,n={}){let t=n.maxChars??8e5,s="",i="",a=0,l,d,p=new Map;for await(let v of r(e,{signal:n.signal}))if(n.signal?.throwIfAborted(),v.usage&&(d=v.usage),!!Array.isArray(v.choices))for(let T of v.choices){if((T.index??0)!==0)continue;T.finish_reason&&(l=T.finish_reason);let C=T.delta;if(!C)continue;typeof C.content=="string"&&C.content&&(s+=C.content,a+=C.content.length,n.onText?.(C.content,s));let R=C.reasoning_content??C.reasoning??C.thinking;if(typeof R=="string"&&R&&(i+=R,a+=R.length,n.onReasoning?.(R,i)),C.tool_calls){if(!Array.isArray(C.tool_calls))throw new Error("Malformed streamed tool_calls");for(let U of C.tool_calls){let E=typeof U.index=="number"?U.index:p.size;if(!Number.isInteger(E)||E<0||E>=64)throw new Error("Malformed streamed tool call index");let S=p.get(E);S||(S={index:E,id:"",type:"function",function:{name:"",arguments:""}},p.set(E,S)),U.id&&(S.id=U.id),U.type&&(S.type=U.type),U.function&&(U.function.name&&(S.function.name+=U.function.name),U.function.arguments&&(S.function.arguments+=U.function.arguments,a+=U.function.arguments.length)),n.onToolCall?.({index:E,id:S.id??"",name:S.function.name,arguments:S.function.arguments},U.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 h=[...p.keys()].sort((v,T)=>v-T);if(h.some((v,T)=>v!==T))throw new Error("Streamed tool calls arrived incomplete");let w=h.map(v=>{let T=p.get(v),{index:C,...R}=T;return R.id||(R.id=`call_${Math.random().toString(36).slice(2,10)}`),R}),k={role:"assistant",content:s.length?s:null};return w.length&&(k.tool_calls=w),{message:k,finishReason:l,usage:d,reasoning:i}}var bo="/prompts";function xo(r){let e=[],n="",t=!1,s=null;for(let i=0;i<r.length;i++){let a=r[i];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 vo(r,e){let n=e.join(" ");return r.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(t,s,i,a,l,d)=>{if(s){let p=s==="@"||s==="ARGUMENTS"?n:e[parseInt(s,10)-1];return p||i}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 as(r){let e=[];for(let n of await r.list(bo)){if(!n.path.endsWith(".md"))continue;let t=n.path.slice(bo.length+1,-3);if(t.includes("/"))continue;let s;try{s=await r.readText(n.path)}catch{continue}let{fm:i,body:a}=ha(s),l=i.description||mc(a);e.push({name:t,description:l,argumentHint:i["argument-hint"],path:n.path})}return e.sort((n,t)=>n.name.localeCompare(t.name))}async function ls(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),h=(await r.skills()).find(v=>v.name===d);if(!h)return e;let{body:w}=await r.skillBody(d),k=`<skill name="${h.name}" location="${h.path}">
|
|
126
|
+
References are relative to ${h.dir}.
|
|
127
127
|
|
|
128
128
|
${w}
|
|
129
129
|
</skill>`;return s?`${k}
|
|
130
130
|
|
|
131
|
-
${s}`:k}let i=`${
|
|
131
|
+
${s}`:k}let i=`${bo}/${t}.md`,a;try{a=await r.readText(i)}catch{return e}let{body:l}=ha(a);return vo(l,xo(s))}function ha(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
|
-
`)){let i=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(s.trim());i&&(t[i[1]]=i[2].replace(/^["']|["']$/g,""))}return{fm:t,body:e.slice(n[0].length).trim()}}function
|
|
134
|
-
`).find(n=>n.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var
|
|
135
|
-
|
|
136
|
-
[... ${t} more characters not shown. Ask for a narrower range or a smaller result.]`,truncated:!0}}function
|
|
137
|
-
`):""}function
|
|
138
|
-
`),t=e.replace(/\/[^/]*$/,"")||"/",s=t.split("/").filter(Boolean).pop()??"skill",i=[],a={},l=n,d=/^---\n([\s\S]*?)\n---\n?/.exec(n);d&&(a=
|
|
139
|
-
`),t=0,s="";for(;t<n.length;){let i=n[t]??"";if(t++,!i.trim()||i.trimStart().startsWith("#"))continue;let a=i.length-i.trimStart().length,l=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(i.trim());if(!l)continue;let d=a>0&&s?`${s}.${l[1]}`:l[1];a===0&&(s="");let
|
|
140
|
-
`).trim()}else
|
|
141
|
-
`);return i.forEach((a,l)=>{let d=a.trimEnd(),
|
|
142
|
-
`,n.push(s),t.push(s+1),s+=1)}),{text:e,start:n,end:t}}function
|
|
143
|
-
`),l=a,d=null,
|
|
144
|
-
`))){
|
|
145
|
-
`);if(!
|
|
146
|
-
`),i:T})}),
|
|
147
|
-
`):w)}var
|
|
133
|
+
`)){let i=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(s.trim());i&&(t[i[1]]=i[2].replace(/^["']|["']$/g,""))}return{fm:t,body:e.slice(n[0].length).trim()}}function mc(r){let e=r.split(`
|
|
134
|
+
`).find(n=>n.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var ma=/^[A-Za-z0-9_-]{1,64}$/;function Fe(r){if(!ma.test(r.name))throw new Error(`tool name "${r.name}" must match ${ma}`);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 ds(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parameters}}}function wr(r,e=32e3){let n,t;r==null?n="OK":typeof r=="string"?n=r.length?r:"OK":Array.isArray(r)&&r.every(ga)?n=r:gc(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 i=cs(n,e);s=i.truncated,n=i.text}else n=n.map(i=>{if(i.type!=="text")return i;let a=cs(i.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 ga(r){return!!r&&typeof r=="object"&&typeof r.type=="string"&&["text","image_url","video_url","audio_url"].includes(r.type)}function gc(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(ga))&&n.every(t=>t==="content"||t==="details")}function cs(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
|
+
|
|
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 ps(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 h=r.byteLength-22;h>=Math.max(0,r.byteLength-22-65535);h--)if(e.getUint32(h,!0)===101010256){n=h;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),i=e.getUint32(n+16,!0);if(t===65535||s===4294967295||i===4294967295)throw new Error("zip64 archives are not supported");let a=[],l=i,d=new TextDecoder("utf-8"),p=new TextDecoder("latin1");for(let h=0;h<t;h++){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),k=e.getUint16(l+10,!0),v=e.getUint32(l+20,!0),T=e.getUint32(l+24,!0),C=e.getUint16(l+28,!0),R=e.getUint16(l+30,!0),U=e.getUint16(l+32,!0),E=e.getUint32(l+42,!0);if(v===4294967295||T===4294967295||E===4294967295)throw new Error("zip64 archives are not supported");let S=r.subarray(l+46,l+46+C),N=(w&2048?d:p).decode(S).replace(/\\/g,"/");a.push({name:N,size:T,compressedSize:v,method:k,isDir:N.endsWith("/"),offset:E,crc:e.getUint32(l+16,!0)}),l+=46+C+R+U}return a}async function kn(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 i=t.getUint16(s+26,!0),a=t.getUint16(s+28,!0),l=s+30+i+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&&ya(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):yc(d));if(p.byteLength!==e.size)throw new Error(`zip entry "${e.name}" inflated to the wrong size`);return p}async function yc(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 us=null;function ya(r){if(!us){us=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;us[n]=t>>>0}}let e=4294967295;for(let n=0;n<r.length;n++)e=us[(e^r[n])&255]^e>>>8;return(e^4294967295)>>>0}async function wc(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 bc(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 fs(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 h of r){let w=e.encode(h.path.replace(/^\/+/,"")),k=typeof h.data=="string"?e.encode(h.data):h.data,v=ya(k),{bytes:T,method:C}=await wc(k),{date:R,time:U}=bc(h.mtime??Date.now()),E=new DataView(new ArrayBuffer(30));E.setUint32(0,67324752,!0),E.setUint16(4,20,!0),E.setUint16(6,2048,!0),E.setUint16(8,C,!0),E.setUint16(10,U,!0),E.setUint16(12,R,!0),E.setUint32(14,v,!0),E.setUint32(18,T.length,!0),E.setUint32(22,k.length,!0),E.setUint16(26,w.length,!0),E.setUint16(28,0,!0);let S=new DataView(new ArrayBuffer(46));S.setUint32(0,33639248,!0),S.setUint16(4,20,!0),S.setUint16(6,20,!0),S.setUint16(8,2048,!0),S.setUint16(10,C,!0),S.setUint16(12,U,!0),S.setUint16(14,R,!0),S.setUint32(16,v,!0),S.setUint32(20,T.length,!0),S.setUint32(24,k.length,!0),S.setUint16(28,w.length,!0),S.setUint16(30,0,!0),S.setUint16(32,0,!0),S.setUint16(34,0,!0),S.setUint16(36,0,!0),S.setUint32(38,0,!0),S.setUint32(42,s,!0),n.push(new Uint8Array(E.buffer),w,T),t.push(new Uint8Array(S.buffer),w),s+=30+w.length+T.length}let i=t.reduce((h,w)=>h+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,i,!0),a.setUint32(16,s,!0),a.setUint16(20,0,!0);let l=[...n,...t,new Uint8Array(a.buffer)],d=new Uint8Array(l.reduce((h,w)=>h+w.length,0)),p=0;for(let h of l)d.set(h,p),p+=h.length;return d}var wa=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xr(r,e){let n=r.replace(/^/,"").replace(/\r\n?/g,`
|
|
138
|
+
`),t=e.replace(/\/[^/]*$/,"")||"/",s=t.split("/").filter(Boolean).pop()??"skill",i=[],a={},l=n,d=/^---\n([\s\S]*?)\n---\n?/.exec(n);d&&(a=ko(d[1]??""),l=n.slice(d[0].length));let p=(a.description??"").trim();if(!p)return null;let h=(a.name??"").trim()||s;(!wa.test(h)||h.length>64)&&(i.push(`skill name "${h}" is not lowercase-hyphenated (\u226464); using the folder name`),h=wa.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let w={name:h,description:p.length>1024?p.slice(0,1024):p,path:e,dir:t};p.length>1024&&i.push(`description of "${h}" 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 k={};for(let[v,T]of Object.entries(a))v.startsWith("metadata.")&&(k[v.slice(9)]=T);return Object.keys(k).length&&(w.metadata=k),{skill:w,body:l.trim(),warnings:i}}function ko(r){let e={},n=r.split(`
|
|
139
|
+
`),t=0,s="";for(;t<n.length;){let i=n[t]??"";if(t++,!i.trim()||i.trimStart().startsWith("#"))continue;let a=i.length-i.trimStart().length,l=/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(i.trim());if(!l)continue;let d=a>0&&s?`${s}.${l[1]}`:l[1];a===0&&(s="");let p=l[2]??"";if(p===""){let h=n[t]??"";if(h.length-h.trimStart().length>a&&h.trim()){s=l[1];continue}}else if(p===">"||p==="|"||p===">-"||p==="|-"){let h=p.startsWith(">"),w=[];for(;t<n.length;){let k=n[t]??"";if(k.trim()&&k.length-k.trimStart().length<=a)break;w.push(k.trim()),t++}p=h?w.join(" ").trim():w.join(`
|
|
140
|
+
`).trim()}else p=xc(p);e[d]=p}return e}function xc(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 vc(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 ba(r){let e="",n=[],t=[],s=0,i=r.split(`
|
|
141
|
+
`);return i.forEach((a,l)=>{let d=a.trimEnd(),p=0;for(let h of d){let w=vc(h);for(let k=0;k<w.length;k++)n.push(s+p),t.push(s+p+h.length);e+=w,p+=h.length}s+=a.length,l<i.length-1&&(e+=`
|
|
142
|
+
`,n.push(s),t.push(s+1),s+=1)}),{text:e,start:n,end:t}}function To(r){return ba(r).text}function kc(r,e){let n=0,t=0;for(;(t=r.indexOf(e,t))!==-1;)n++,t+=e.length;return n}function hs(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":"",i=/\r\n/.test(e),a=e.slice(s.length).replace(/\r\n/g,`
|
|
143
|
+
`),l=a,d=null,p=!1;for(let v of n)if(v.oldText&&!a.includes(v.oldText.replace(/\r\n/g,`
|
|
144
|
+
`))){p=!0;break}if(p){let v=ba(a);l=v.text,d=v}let h=[];n.forEach((v,T)=>{let C=v.oldText.replace(/\r\n/g,`
|
|
145
|
+
`);if(!C)throw new Error(t?`edits[${T}].oldText must not be empty in ${r}.`:`oldText must not be empty in ${r}.`);let R=p?To(C):C,U=kc(l,R);if(U===0)throw new Error(t?`Could not find edits[${T}] 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(U>1)throw new Error(t?`Found ${U} occurrences of edits[${T}] in ${r}. Each oldText must be unique. Please provide more context to make it unique.`:`Found ${U} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`);let E=l.indexOf(R),S=d?d.start[E]:E,N=d?d.end[E+R.length-1]:E+R.length;h.push({start:S,end:N,newText:v.newText.replace(/\r\n/g,`
|
|
146
|
+
`),i:T})}),h.sort((v,T)=>v.start-T.start);for(let v=1;v<h.length;v++)if(h[v].start<h[v-1].end)throw new Error(`edits[${h[v-1].i}] and edits[${h[v].i}] overlap in ${r}. Merge them into one edit or target disjoint regions.`);let w="",k=0;for(let v of h)w+=a.slice(k,v.start)+v.newText,k=v.end;if(w+=a.slice(k),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+(i?w.replace(/\n/g,`\r
|
|
147
|
+
`):w)}var Tn=new Map,Tc=64;function Sc(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 vr(r,e){let n=[...r],t=new Map;if(n.includes("SKILL.md"))return t.set(e,""),t;for(let s of n){let i=/^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(s);if(!i)continue;let a=i[1],l=s.slice(0,-8);(!t.has(a)||l.length<t.get(a).length)&&t.set(a,l)}return t}function So(r){let e=new Map;for(let n of ps(r)){let t=Sc(n.name);t&&e.set(t,n)}return e}function xa(r){return Tn.get(r)}function ms(r,e,n){let t=Tn.get(n);if(t&&t.bytes.byteLength===e.byteLength)return t;let s=So(e),i={entries:s,folders:vr(s.keys(),r),bytes:e,cache:new Map};return Tn.size>=Tc&&Tn.delete(Tn.keys().next().value),Tn.set(n,i),i}var Cc=new TextDecoder("utf-8",{fatal:!0}),Mc=r=>{try{return Cc.decode(r)}catch{return null}};function Sn(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 i=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(i(p));return d},async stat(a){return i(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 kn(r.bytes,r.entries.get(l),t),h=Mc(p)??p;return r.cache.set(l,h),h}}}function kr(r,e){return{async list(n){let t=[];for(let s of await r.list(n==="/"?e:e+n)){let i=s.path.startsWith(e+"/")?s.path.slice(e.length):null;i&&t.push({...s,path:i})}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 va="6.4.299",Yt={url:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${va}/build/pdf.min.mjs`,workerUrl:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${va}/build/pdf.worker.min.mjs`},Cn=null;function ka(r){Object.assign(Yt,r),Cn=null}var Ec=r=>import(r);function Ac(){return Cn||(Cn=(async()=>{let r=Yt.load?await Yt.load():await Ec(Yt.url),e=r.default?.getDocument?r.default:r;if(!Yt.load&&typeof Worker<"u"&&typeof Blob<"u")try{let n=new Blob([`import ${JSON.stringify(Yt.workerUrl)};`],{type:"text/javascript"});e.GlobalWorkerOptions.workerPort=new Worker(URL.createObjectURL(n),{type:"module"})}catch{e.GlobalWorkerOptions.workerSrc=Yt.workerUrl}return e})(),Cn.catch(()=>{Cn=null})),Cn}function Mn(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 En(r,e={}){let t=(await Ac()).getDocument({data:r.slice(),isEvalSupported:!1}),s=await t.promise;try{let i=[],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();i.push(p.items.map(h=>(h.str??"")+(h.hasEOL?`
|
|
148
148
|
`:"")).join("").replace(/[ \t]+\n/g,`
|
|
149
|
-
`).trim()),d.cleanup?.()}return{pages:i,numPages:s.numPages}}finally{await(t.destroy?t.destroy():s.destroy?.())}}function
|
|
149
|
+
`).trim()),d.cleanup?.()}return{pages:i,numPages:s.numPages}}finally{await(t.destroy?t.destroy():s.destroy?.())}}function An(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
|
|
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,i){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??yt(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??yt(e,n),mtime:Date.now(),layer:s,source:i}),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=Y(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+Y(a.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}let i=this.root?(await this.root.list(n)).map(a=>({...a,path:Y(a.path)})):await xr(this.store,n==="/"?"/":n+"/");for(let a of i)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+Y(d.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}async stat(e){await this.ready();let n=Y(e),t=this.route(n);if(t){if(t.fs.stat){let i=await t.fs.stat(t.rel);return i?{...i,path:n}:null}let s=(await t.fs.list(t.rel)).find(i=>Y(i.path)===Y(t.rel));return s?{...s,path:n}:null}return pa(this.store,n)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let n=Y(e),t=this.route(n);if(t)try{let i=await t.fs.read(t.rel);return{data:i,size:fs(i),contentType:yt(n,i)}}catch(i){throw new Error(await this.missing(n,i))}let s=await this.store.get(n);if(!s)throw new Error(await this.missing(n));return{data:s.data,size:fs(s.data),contentType:s.contentType}}async isFolder(e){let n=Y(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=wt(n);if(t===null)throw new Error(`${Y(e)} is a binary file (${n.byteLength} bytes)`);return t}async readAsText(e){let n=Y(e),{data:t,size:s,contentType:i}=await this.read(n);if(typeof t=="string")return{text:t,kind:"text"};if(kn(n,i,t)){let l=await this.stat(n),d=`pdftext:${n}`,u=await this.getData(d).catch(()=>{});if(u&&u.size===s&&u.mtime===l?.mtime)return{text:u.text,kind:"pdf"};let f=Sn(n,await Tn(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:f}).catch(()=>{}),{text:f,kind:"pdf"}}let a=wt(t);return a===null?null:{text:a,kind:"text"}}async write(e,n,t){await this.ready();let s=Y(e);if(s==="/")throw new Error("Cannot write to /");let i=this.route(s);if(i&&i.prefix){if(!i.fs.write)throw new Error(`${i.prefix} is read-only`);await i.fs.write(i.rel,n,t),this.emitChange(s,"write");return}await this.putFile(s,n,t,"work")}async edit(e,n){await this.ready();let t=Y(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,cs(t,await this.readText(t),n))}async delete(e){await this.ready();let n=Y(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(Y(e))?.prefix||null}isReadOnly(e){let n=this.route(Y(e));return n?!n.fs.write:!1}isSkillPath(e){let n=Y(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 i;try{let l=await s.fs.read("/SKILL.md");i=typeof l=="string"?l:wt(l)}catch{continue}if(i===null)continue;let a=gr(i,`${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 f=await this.fetchSource(e);if(!f)throw new Error("nothing fetched");t=f.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 i=ps(s),a=yo(t),l=mr(a.keys(),i);if(!l.size)throw new Error(`${i}.zip has no SKILL.md (at its root, or one per folder)`);let d=Date.now();if(n.unpack){for(let[f,w]of l){for(let k of await xr(this.lib,`/${f}/`))await this.lib.delete(k.path);for(let[k,v]of a){if(!k.startsWith(w))continue;let T=await wn(t,v,this.inflate),M=wt(T),R=Y(`/${f}/${k.slice(w.length)}`);await this.lib.put({path:R,data:M??T,contentType:yt(R,M??T),mtime:d,layer:"work"})}}await this.userSkillsChanged(`/${[...l.keys()][0]}`,"write")}else await this.lib.put({path:`/${i}.zip`,data:t,contentType:"application/zip",mtime:d,layer:"work"}),await this.userSkillsChanged(`/${i}.zip`,"write");let u=new Set([...l.keys()].map(f=>`${this.skillsDir}/${f}`));return(await this.skills()).filter(f=>u.has(f.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 xr(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=gr(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(wo(e)){br.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!ha(e)&&typeof e.data=="string"?e.data:null;n&&us.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(wo);for(let t of n)if(!wo(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!ha(t)?t:null,i=s?s.data:t,a,l,d=0;if(typeof i=="string"){let f=`${this.dbName}|${this.fetchKey}|${i}`,w=us.get(f);w||(w=this.fetchSource(i).then(k=>{if(!k)throw new Error("nothing fetched");return{bytes:k.bytes,at:Date.now()}}),us.set(f,w),w.catch(()=>us.delete(f))),{bytes:a,at:d}=await w,l=`app:${f}@${d}`}else a=i instanceof Uint8Array?i:new Uint8Array(await i.arrayBuffer()),l=`app:${this.dbName}|obj${bo(i)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let u=ps(s?.name??(typeof i=="string"?i:i.name||"skills"));e.push({name:u,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=ds(n.name,n.bytes,n.key);for(let[s,i]of t.folders)e.has(s)||e.set(s,{fs:xn(t,i,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:ps(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("^"+xc(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(Y(n.path));t&&e.set(t[1],{fs:yr(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await xr(this.lib,"/");for(let s of n){let i=/^\/([^/]+)\.zip$/i.exec(s.path);if(i)try{let a=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,l=s.mtime!==void 0?la(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=ds(ps(i[1]),d.data,a)}for(let[d,u]of l.folders)e.set(d,{fs:xn(l,u,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 i=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);i&&e.set(i[1],{fs:yr(t,`/${i[1]}`),builtin:!1,from:`${this.userSkillsDir}/${i[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,n){let t=null,s=async()=>{if(t)return t;let a=br.get(e);a||(a=(async()=>{let f=await e.load();if(typeof f=="string"){let w=await this.fetchSource(f);if(!w)throw new Error("nothing fetched");return w.bytes}return f instanceof Uint8Array?f:f instanceof ArrayBuffer?new Uint8Array(f):new Uint8Array(await f.arrayBuffer())})(),br.set(e,a),a.catch(()=>{br.get(e)===a&&br.delete(e)}));let l;try{l=await a}catch(f){throw new Error(`the skill "${e.name}" could not be loaded: ${f.message}`)}if(l.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let d=ds(n,l,`lazy:${bo(e)}:${l.byteLength}`),u=d.folders.get(n)??[...d.folders.values()][0];if(u===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return t=xn(d,u,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${n}`,"write"),t},i=a=>a==="/"||a==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async a=>t?t.list(a):i(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[i,a]of this.skillViews)if(!(s&&s.name!==i))for(let l of await a.fs.list(s?s.rest:"/"))t.push({...l,path:`/${i}${Y(l.path)}`});return t},stat:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)return null;let i=s.fs.stat?await s.fs.stat(t.rest):(await s.fs.list(t.rest)).find(a=>Y(a.path)===t.rest)??null;return i?{...i,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=>xr(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>pa(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??yt(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 i of s?.files??[])n.add(i);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 i=await s.arrayBuffer();if(i.byteLength>52428800)throw new Error("skills zip too large");return{bytes:new Uint8Array(i),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 Y(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 ma(r){return{path:r.path,size:fs(r.data),contentType:r.contentType,mtime:r.mtime}}function fs(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var bc=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"]),fa={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 yt(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return fa[n]?fa[n]:typeof e=="string"||bc.has(n)?"text/plain":"application/octet-stream"}function wt(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 ha=r=>typeof Blob<"u"&&r instanceof Blob,xc=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function ps(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var vc=4;function kc(r,e,n){return new Promise((t,s)=>{let i=r.open(e,vc);i.onupgradeneeded=a=>{let l=i.result,d=i.transaction,u=a.oldVersion,f=()=>l.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(u<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"]}),f();return}if(u<4){let w=d.objectStore("sessions").getAll();w.onsuccess=()=>{let k=w.result;l.deleteObjectStore("sessions"),f();let v=d.objectStore("sessions");for(let T of k)T.id&&v.put({...T,space:T.space??"default"})}}},i.onerror=()=>s(i.error??new Error("indexedDB open failed")),i.onblocked=()=>console.warn(`agent: ${e} is waiting for another tab to release the database`),i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>a.close();let l=(u,f,w)=>new Promise((k,v)=>{let T=a.transaction(u,f),M=w(T.objectStore(u)),R;M.onsuccess=()=>{R=M.result,f==="readonly"&&k(R)},M.onerror=()=>v(M.error??new Error("indexedDB request failed")),T.oncomplete=()=>k(R),T.onabort=()=>v(T.error??new Error("indexedDB transaction aborted"))}),d=(u,f)=>IDBKeyRange.bound([u,f],[u,f+"\uFFFF"],!1,!1);t({get:u=>l("files","readonly",f=>f.get([n,u])),put:async u=>{await l("files","readwrite",f=>f.put({...u,space:n}))},delete:async u=>{await l("files","readwrite",f=>f.delete([n,u]))},list:u=>l("files","readonly",f=>f.getAll(d(n,u))),getMeta:async u=>(await l("meta","readonly",f=>f.get([n,u])))?.value,putMeta:async(u,f)=>{await l("meta","readwrite",w=>w.put({space:n,key:u,value:f}))},deleteMeta:async u=>{await l("meta","readwrite",f=>f.delete([n,u]))},listMeta:async u=>(await l("meta","readonly",f=>f.getAll(d(n,u)))).map(f=>f.value),listMetaKeys:async u=>(await l("meta","readonly",f=>f.getAll(d(n,u)))).map(f=>f.key),getSession:(u,f)=>l("sessions","readonly",w=>w.get([u,f])),putSession:async u=>{await l("sessions","readwrite",f=>f.put(u))},deleteSession:async(u,f)=>{await l("sessions","readwrite",w=>w.delete([u,f]))},listSessions:()=>l("sessions","readonly",u=>u.getAll()),clear:async(u=n)=>{await l("files","readwrite",f=>f.delete(d(u,"/"))),await l("meta","readwrite",f=>f.delete(d(u,""))),await l("sessions","readwrite",f=>f.delete(d(u,"")))},close:()=>a.close()})}})}var ga=new Map;function Tc(r,e){let n=ga.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},ga.set(r,n));let t=n,s=()=>{let a=t.files.get(e);return a||(a=new Map,t.files.set(e,a)),a},i=()=>{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=>i().get(a),putMeta:async(a,l)=>{i().set(a,l)},deleteMeta:async a=>{i().delete(a)},listMeta:async a=>[...i()].filter(([l])=>l.startsWith(a)).map(([,l])=>l),listMetaKeys:async a=>[...i().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 Dt="Untitled";function Jt(r){for(let e of r.messages){if(e.role!=="user"||De(e)!==null)continue;let n=e.typed,s=(typeof n=="string"?n:typeof e.content=="string"?e.content:(e.content??[]).find(i=>i.type==="text")?.text??"").replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim();if(!(!s||hs(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return Dt}function hs(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Sc(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function ya(r={},e={}){let n=new Map;for(let[s,i]of Object.entries(r))n.set(Y(s),i);let t={files:n,description:e.description,async list(s){let i=Y(s);return[...n.entries()].filter(([a])=>i==="/"||a===i||a.startsWith(i+"/")).map(([a,l])=>({path:a,size:fs(l)}))},async read(s){let i=n.get(Y(s));if(i===void 0)throw new Error(`No such file: ${Y(s)}`);return i}};return e.readonly||(t.write=async(s,i)=>{n.set(Y(s),i)},t.delete=async s=>{if(!n.delete(Y(s)))throw new Error(`No such file: ${Y(s)}`)}),t}var Cc=4*1024*1024;function Mc(r){let e=typeof r=="string"?r:wt(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 Ec(r,e,n){if(n<e)return!1;let t=r.some(([i,a])=>i<=e&&a>=n);r.push([e,n]),r.sort((i,a)=>i[0]-a[0]);let s=[];for(let i of r){let a=s[s.length-1];a&&i[0]<=a[1]+1?a[1]=Math.max(a[1],i[1]):s.push([i[0],i[1]])}return r.splice(0,r.length,...s),!t}var Xt=class extends Error{constructor(n,t,s){super(n);D(this,"path",t);D(this,"coveredTo",s);this.name="PartialReadError"}};function Mn(r,e={}){let n=e.enabled!==!1,t=new Map,s=async(i,a)=>{let l=await r.stat(i);if(!l)return null;let d=l.size>Cc?"":Mc(a??(await r.read(i)).data);return`${l.mtime??""}:${l.size}:${d}`};return{enabled:n,async saw(i,a={}){if(!n)return;let l=await s(i,a.text).catch(()=>null);if(!l)return t.delete(i),!0;let d=a.start??1,u=a.end??1/0,f=a.total??1/0,w=t.get(i),k=!!w&&w.version===l,v=k&&d<=w.coveredTo+1?Math.max(w.coveredTo,u):d<=1?u:0,T=k?w.ranges:[],M=Ec(T,d,u)||!k;return t.set(i,{version:l,coveredTo:v,total:f,ranges:T}),M},async wrote(i){if(!n)return;let a=await s(i).catch(()=>null);a?t.set(i,{version:a,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):t.delete(i)},async copied(i,a){if(!n)return;let l=t.get(i),d=l?await s(a).catch(()=>null):null;l&&d?t.set(a,{...l,version:d,ranges:l.ranges.map(([u,f])=>[u,f])}):t.delete(a)},async edited(i){if(!n)return;let a=t.get(i),l=await s(i).catch(()=>null);l&&a?t.set(i,{...a,version:l,total:1/0,ranges:[]}):t.delete(i)},async check(i,a){if(!n)return;let l=await s(i);if(l===null)return;let d=t.get(i);if(!d){if(a==="delete")return;throw new Error(`${i} 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(`${i} 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 Xt(`You have read only lines 1-${d.coveredTo} of ${i}: read the rest (read_file with offset=${d.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,i,d.coveredTo)},async known(i){let a=t.get(i);return!a||await s(i).catch(()=>null)!==a.version?"none":a.coveredTo>=a.total?"all":a.coveredTo>0?"part":"none"},forget(i){t.delete(i)},retain(i){let a=new Set(i);for(let l of[...t.keys()])a.has(l)||t.delete(l)},clear(){t.clear()}}}var ko=500,gs=2e3,ms=50*1024,ys=100,wa=5*1024*1024,Ac={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},$c={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function Lc(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function ws(r,e={}){let n=e.guard??Mn(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[Ue({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},i){let a=await r.list(s||"/");if(!a.length)return`No files under ${Y(s||"/")}.`;let l=i?.parentId?1/0:ko,d=a.slice(0,l).map(u=>`${u.path} (${u.size} B)`);return a.length>l&&d.push(`
|
|
155
|
-
[${
|
|
156
|
-
`)}}),
|
|
157
|
-
`+V.slice(0
|
|
158
|
-
`)}let d=await r.stat(s),
|
|
159
|
-
`),v=k.length,T=Math.max(1,i??1);if(T>v)return await n.saw(
|
|
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 Eo="/.agent/skills";var $c="__runapps_agent_ws",Ao="/skills",Lc="\0skills",Co=r=>typeof r=="object"&&!(r instanceof Uint8Array)&&typeof r.load=="function",Sr=new WeakMap,gs=new Map,Ta=new WeakMap,Pc=1,Mo=r=>{let e=Ta.get(r);return e||(e=Pc++,Ta.set(r,e)),e},Cr=async(r,e)=>r.listStats?r.listStats(e):(await r.list(e)).map(Aa),Sa=async(r,e)=>{if(r.stat)return r.stat(e);let n=await r.get(e);return n?Aa(n):null},$n=class r{constructor(e,n={}){D(this,"id");D(this,"dbName");D(this,"skillsDir");D(this,"userSkillsDir");D(this,"root");D(this,"store");D(this,"lib");D(this,"mounts",new Map);D(this,"skillViews",new Map);D(this,"builtins",[]);D(this,"lazySkills",[]);D(this,"resolvedSources",[]);D(this,"changeListeners",new Set);D(this,"channel");D(this,"sources");D(this,"provider");D(this,"inflate");D(this,"fetchFn");D(this,"fetchKey");D(this,"idb");D(this,"storeFactory");D(this,"skillCache",null);D(this,"opened",null);D(this,"sessions",{list:async()=>(await this.ready(),(await this.store.listSessions()).map(e=>({id:e.id??"",title:e.title&&!bs(e.title)?e.title:Qt(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?ot(e):null,this.id=n.id||"default",this.dbName=`${$c}:${n.project||this.provider?.name||"app"}`,this.sources=typeof n.skills=="function"?n.skills:n.skills?[].concat(n.skills):[],this.skillsDir=Q(n.skillsDir||Eo),this.skillsDir==="/")throw new Error("skillsDir cannot be /");this.userSkillsDir=n.userSkills===!1||n.userSkillsDir===!1?null:Q(n.userSkillsDir||Ao);let t=(s,i)=>s===i||s.startsWith(i+"/")||i.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${Mo(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?Dc(this.idb,this.dbName,t):Promise.resolve(zc(this.dbName,t));this.store=await n(this.id),this.lib=await n(Lc),this.openChannel(),await Ic(`${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=Q(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(Q(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,i=t.kind;this.rebuildSkills().then(()=>{this.emitChange(s,i,!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 i of this.changeListeners)try{i(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,i){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??yt(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??yt(e,n),mtime:Date.now(),layer:s,source:i}),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=Q(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+Q(a.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}let i=this.root?(await this.root.list(n)).map(a=>({...a,path:Q(a.path)})):await Cr(this.store,n==="/"?"/":n+"/");for(let a of i)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+Q(d.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}async stat(e){await this.ready();let n=Q(e),t=this.route(n);if(t){if(t.fs.stat){let i=await t.fs.stat(t.rel);return i?{...i,path:n}:null}let s=(await t.fs.list(t.rel)).find(i=>Q(i.path)===Q(t.rel));return s?{...s,path:n}:null}return Sa(this.store,n)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let n=Q(e),t=this.route(n);if(t)try{let i=await t.fs.read(t.rel);return{data:i,size:ws(i),contentType:yt(n,i)}}catch(i){throw new Error(await this.missing(n,i))}let s=await this.store.get(n);if(!s)throw new Error(await this.missing(n));return{data:s.data,size:ws(s.data),contentType:s.contentType}}async isFolder(e){let n=Q(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=wt(n);if(t===null)throw new Error(`${Q(e)} is a binary file (${n.byteLength} bytes)`);return t}async readAsText(e){let n=Q(e),{data:t,size:s,contentType:i}=await this.read(n);if(typeof t=="string")return{text:t,kind:"text"};if(Mn(n,i,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 h=An(n,await En(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:h}).catch(()=>{}),{text:h,kind:"pdf"}}let a=wt(t);return a===null?null:{text:a,kind:"text"}}async write(e,n,t){await this.ready();let s=Q(e);if(s==="/")throw new Error("Cannot write to /");let i=this.route(s);if(i&&i.prefix){if(!i.fs.write)throw new Error(`${i.prefix} is read-only`);await i.fs.write(i.rel,n,t),this.emitChange(s,"write");return}await this.putFile(s,n,t,"work")}async edit(e,n){await this.ready();let t=Q(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,hs(t,await this.readText(t),n))}async delete(e){await this.ready();let n=Q(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(Q(e))?.prefix||null}isReadOnly(e){let n=this.route(Q(e));return n?!n.fs.write:!1}isSkillPath(e){let n=Q(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 i;try{let l=await s.fs.read("/SKILL.md");i=typeof l=="string"?l:wt(l)}catch{continue}if(i===null)continue;let a=xr(i,`${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 h=await this.fetchSource(e);if(!h)throw new Error("nothing fetched");t=h.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 i=ys(s),a=So(t),l=vr(a.keys(),i);if(!l.size)throw new Error(`${i}.zip has no SKILL.md (at its root, or one per folder)`);let d=Date.now();if(n.unpack){for(let[h,w]of l){for(let k of await Cr(this.lib,`/${h}/`))await this.lib.delete(k.path);for(let[k,v]of a){if(!k.startsWith(w))continue;let T=await kn(t,v,this.inflate),C=wt(T),R=Q(`/${h}/${k.slice(w.length)}`);await this.lib.put({path:R,data:C??T,contentType:yt(R,C??T),mtime:d,layer:"work"})}}await this.userSkillsChanged(`/${[...l.keys()][0]}`,"write")}else await this.lib.put({path:`/${i}.zip`,data:t,contentType:"application/zip",mtime:d,layer:"work"}),await this.userSkillsChanged(`/${i}.zip`,"write");let p=new Set([...l.keys()].map(h=>`${this.skillsDir}/${h}`));return(await this.skills()).filter(h=>p.has(h.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 Cr(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=xr(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(Co(e)){Sr.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!Ma(e)&&typeof e.data=="string"?e.data:null;n&&gs.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(Co);for(let t of n)if(!Co(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!Ma(t)?t:null,i=s?s.data:t,a,l,d=0;if(typeof i=="string"){let h=`${this.dbName}|${this.fetchKey}|${i}`,w=gs.get(h);w||(w=this.fetchSource(i).then(k=>{if(!k)throw new Error("nothing fetched");return{bytes:k.bytes,at:Date.now()}}),gs.set(h,w),w.catch(()=>gs.delete(h))),{bytes:a,at:d}=await w,l=`app:${h}@${d}`}else a=i instanceof Uint8Array?i:new Uint8Array(await i.arrayBuffer()),l=`app:${this.dbName}|obj${Mo(i)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let p=ys(s?.name??(typeof i=="string"?i:i.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=ms(n.name,n.bytes,n.key);for(let[s,i]of t.folders)e.has(s)||e.set(s,{fs:Sn(t,i,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:ys(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("^"+Rc(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(Q(n.path));t&&e.set(t[1],{fs:kr(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await Cr(this.lib,"/");for(let s of n){let i=/^\/([^/]+)\.zip$/i.exec(s.path);if(i)try{let a=`user:${this.dbName}|${s.path}@${s.mtime}:${s.size}`,l=s.mtime!==void 0?xa(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=ms(ys(i[1]),d.data,a)}for(let[d,p]of l.folders)e.set(d,{fs:Sn(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 i=/^\/([^/]+)\/SKILL\.md$/.exec(s.path);i&&e.set(i[1],{fs:kr(t,`/${i[1]}`),builtin:!1,from:`${this.userSkillsDir}/${i[1]}`})}}this.skillViews=e,this.skillCache=null}lazyFS(e,n){let t=null,s=async()=>{if(t)return t;let a=Sr.get(e);a||(a=(async()=>{let h=await e.load();if(typeof h=="string"){let w=await this.fetchSource(h);if(!w)throw new Error("nothing fetched");return w.bytes}return h instanceof Uint8Array?h:h instanceof ArrayBuffer?new Uint8Array(h):new Uint8Array(await h.arrayBuffer())})(),Sr.set(e,a),a.catch(()=>{Sr.get(e)===a&&Sr.delete(e)}));let l;try{l=await a}catch(h){throw new Error(`the skill "${e.name}" could not be loaded: ${h.message}`)}if(l.byteLength>52428800)throw new Error(`the skill "${e.name}": zip too large`);let d=ms(n,l,`lazy:${Mo(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=Sn(d,p,Date.now(),this.inflate),this.emitChange(`${this.skillsDir}/${n}`,"write"),t},i=a=>a==="/"||a==="/SKILL.md"?[{path:"/SKILL.md",size:0}]:[];return{list:async a=>t?t.list(a):i(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[i,a]of this.skillViews)if(!(s&&s.name!==i))for(let l of await a.fs.list(s?s.rest:"/"))t.push({...l,path:`/${i}${Q(l.path)}`});return t},stat:async n=>{let t=e(n),s=t&&this.skillViews.get(t.name);if(!s||!t)return null;let i=s.fs.stat?await s.fs.stat(t.rest):(await s.fs.list(t.rest)).find(a=>Q(a.path)===t.rest)??null;return i?{...i,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=>Cr(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>Sa(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??yt(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 i of s?.files??[])n.add(i);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 i=await s.arrayBuffer();if(i.byteLength>52428800)throw new Error("skills zip too large");return{bytes:new Uint8Array(i),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 Q(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 Aa(r){return{path:r.path,size:ws(r.data),contentType:r.contentType,mtime:r.mtime}}function ws(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var _c=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"]),Ca={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 yt(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return Ca[n]?Ca[n]:typeof e=="string"||_c.has(n)?"text/plain":"application/octet-stream"}function wt(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 Ma=r=>typeof Blob<"u"&&r instanceof Blob,Rc=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function ys(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var Oc=4;function Dc(r,e,n){return new Promise((t,s)=>{let i=r.open(e,Oc);i.onupgradeneeded=a=>{let l=i.result,d=i.transaction,p=a.oldVersion,h=()=>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"]}),h();return}if(p<4){let w=d.objectStore("sessions").getAll();w.onsuccess=()=>{let k=w.result;l.deleteObjectStore("sessions"),h();let v=d.objectStore("sessions");for(let T of k)T.id&&v.put({...T,space:T.space??"default"})}}},i.onerror=()=>s(i.error??new Error("indexedDB open failed")),i.onblocked=()=>console.warn(`agent: ${e} is waiting for another tab to release the database`),i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>a.close();let l=(p,h,w)=>new Promise((k,v)=>{let T=a.transaction(p,h),C=w(T.objectStore(p)),R;C.onsuccess=()=>{R=C.result,h==="readonly"&&k(R)},C.onerror=()=>v(C.error??new Error("indexedDB request failed")),T.oncomplete=()=>k(R),T.onabort=()=>v(T.error??new Error("indexedDB transaction aborted"))}),d=(p,h)=>IDBKeyRange.bound([p,h],[p,h+"\uFFFF"],!1,!1);t({get:p=>l("files","readonly",h=>h.get([n,p])),put:async p=>{await l("files","readwrite",h=>h.put({...p,space:n}))},delete:async p=>{await l("files","readwrite",h=>h.delete([n,p]))},list:p=>l("files","readonly",h=>h.getAll(d(n,p))),getMeta:async p=>(await l("meta","readonly",h=>h.get([n,p])))?.value,putMeta:async(p,h)=>{await l("meta","readwrite",w=>w.put({space:n,key:p,value:h}))},deleteMeta:async p=>{await l("meta","readwrite",h=>h.delete([n,p]))},listMeta:async p=>(await l("meta","readonly",h=>h.getAll(d(n,p)))).map(h=>h.value),listMetaKeys:async p=>(await l("meta","readonly",h=>h.getAll(d(n,p)))).map(h=>h.key),getSession:(p,h)=>l("sessions","readonly",w=>w.get([p,h])),putSession:async p=>{await l("sessions","readwrite",h=>h.put(p))},deleteSession:async(p,h)=>{await l("sessions","readwrite",w=>w.delete([p,h]))},listSessions:()=>l("sessions","readonly",p=>p.getAll()),clear:async(p=n)=>{await l("files","readwrite",h=>h.delete(d(p,"/"))),await l("meta","readwrite",h=>h.delete(d(p,""))),await l("sessions","readwrite",h=>h.delete(d(p,"")))},close:()=>a.close()})}})}var Ea=new Map;function zc(r,e){let n=Ea.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},Ea.set(r,n));let t=n,s=()=>{let a=t.files.get(e);return a||(a=new Map,t.files.set(e,a)),a},i=()=>{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=>i().get(a),putMeta:async(a,l)=>{i().set(a,l)},deleteMeta:async a=>{i().delete(a)},listMeta:async a=>[...i()].filter(([l])=>l.startsWith(a)).map(([,l])=>l),listMetaKeys:async a=>[...i().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 It="Untitled";function Qt(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(i=>i.type==="text")?.text??"").replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim();if(!(!s||bs(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return It}function bs(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Ic(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function $a(r={},e={}){let n=new Map;for(let[s,i]of Object.entries(r))n.set(Q(s),i);let t={files:n,description:e.description,async list(s){let i=Q(s);return[...n.entries()].filter(([a])=>i==="/"||a===i||a.startsWith(i+"/")).map(([a,l])=>({path:a,size:ws(l)}))},async read(s){let i=n.get(Q(s));if(i===void 0)throw new Error(`No such file: ${Q(s)}`);return i}};return e.readonly||(t.write=async(s,i)=>{n.set(Q(s),i)},t.delete=async s=>{if(!n.delete(Q(s)))throw new Error(`No such file: ${Q(s)}`)}),t}var Uc=4*1024*1024;function Fc(r){let e=typeof r=="string"?r:wt(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 Nc(r,e,n){if(n<e)return!1;let t=r.some(([i,a])=>i<=e&&a>=n);r.push([e,n]),r.sort((i,a)=>i[0]-a[0]);let s=[];for(let i of r){let a=s[s.length-1];a&&i[0]<=a[1]+1?a[1]=Math.max(a[1],i[1]):s.push([i[0],i[1]])}return r.splice(0,r.length,...s),!t}var en=class extends Error{constructor(n,t,s){super(n);D(this,"path",t);D(this,"coveredTo",s);this.name="PartialReadError"}};function Ln(r,e={}){let n=e.enabled!==!1,t=new Map,s=async(i,a)=>{let l=await r.stat(i);if(!l)return null;let d=l.size>Uc?"":Fc(a??(await r.read(i)).data);return`${l.mtime??""}:${l.size}:${d}`};return{enabled:n,async saw(i,a={}){if(!n)return;let l=await s(i,a.text).catch(()=>null);if(!l)return t.delete(i),!0;let d=a.start??1,p=a.end??1/0,h=a.total??1/0,w=t.get(i),k=!!w&&w.version===l,v=k&&d<=w.coveredTo+1?Math.max(w.coveredTo,p):d<=1?p:0,T=k?w.ranges:[],C=Nc(T,d,p)||!k;return t.set(i,{version:l,coveredTo:v,total:h,ranges:T}),C},async wrote(i){if(!n)return;let a=await s(i).catch(()=>null);a?t.set(i,{version:a,coveredTo:1/0,total:1/0,ranges:[[1,1/0]]}):t.delete(i)},async copied(i,a){if(!n)return;let l=t.get(i),d=l?await s(a).catch(()=>null):null;l&&d?t.set(a,{...l,version:d,ranges:l.ranges.map(([p,h])=>[p,h])}):t.delete(a)},async edited(i){if(!n)return;let a=t.get(i),l=await s(i).catch(()=>null);l&&a?t.set(i,{...a,version:l,total:1/0,ranges:[]}):t.delete(i)},async check(i,a){if(!n)return;let l=await s(i);if(l===null)return;let d=t.get(i);if(!d){if(a==="delete")return;throw new Error(`${i} 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(`${i} 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 en(`You have read only lines 1-${d.coveredTo} of ${i}: read the rest (read_file with offset=${d.coveredTo+1}) before overwriting it, or change it with edit_file instead.`,i,d.coveredTo)},async known(i){let a=t.get(i);return!a||await s(i).catch(()=>null)!==a.version?"none":a.coveredTo>=a.total?"all":a.coveredTo>0?"part":"none"},forget(i){t.delete(i)},retain(i){let a=new Set(i);for(let l of[...t.keys()])a.has(l)||t.delete(l)},clear(){t.clear()}}}var $o=500,xs=2e3,vs=50*1024,ks=100,La=5*1024*1024,Hc={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},jc={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function qc(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Ts(r,e={}){let n=e.guard??Ln(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[Fe({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},i){let a=await r.list(s||"/");if(!a.length)return`No files under ${Q(s||"/")}.`;let l=i?.parentId?1/0:$o,d=a.slice(0,l).map(p=>`${p.path} (${p.size} B)`);return a.length>l&&d.push(`
|
|
155
|
+
[${$o} entries limit reached (${a.length} in all). List a sub-folder.]`),d.join(`
|
|
156
|
+
`)}}),Fe({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:i,limit:a},l){if(await r.isFolder(s)){let V=await r.list(s);return`${Q(s)} is a folder with ${V.length} file${V.length===1?"":"s"}:
|
|
157
|
+
`+V.slice(0,$o).map(se=>`${se.path} (${se.size} B)`).join(`
|
|
158
|
+
`)}let d=await r.stat(s),p=d&&Hc[(d.contentType??"").split(";")[0].trim()]?d.contentType.split(";")[0].trim():jc[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(d&&p&&await l.agent?.accepts("image")===!0){if(d.size>La)return`${Q(s)} is a picture of ${d.size} bytes, more than the ${La/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:V}=await r.read(s),se=typeof V=="string"?new TextEncoder().encode(V):V;return await n.saw(Q(s)),[{type:"text",text:`${Q(s)} (${p}, ${se.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${p};base64,${qc(se)}`}}]}let h;try{h=await r.readAsText(s)}catch(V){if(await r.stat(s)&&/\.pdf$/i.test(s))return`Could not read the PDF ${Q(s)}: ${V.message}`;throw V}if(!h){await n.saw(Q(s));let V=await r.stat(s),se=p&&await l.agent?.accepts("image")===!1?" The model in use cannot view pictures.":"";return`${Q(s)} is a binary file (${V?.contentType??"unknown type"}, ${V?.size??0} bytes).${se}`}let w=h.text,k=w.split(`
|
|
159
|
+
`),v=k.length,T=Math.max(1,i??1);if(T>v)return await n.saw(Q(s),{start:v+1,end:v,total:v}),`Offset ${T} is beyond end of file (${v} lines total)`;let C=!!l?.parentId,R=C?a??1/0:a!==void 0?Math.min(a,xs):xs,U=[],E=0,S=T-1;for(let V=T-1;V<v&&U.length<R;V++){let se=new TextEncoder().encode(k[V]).byteLength+1;if(!C&&E+se>vs&&U.length>0)break;U.push(k[V]),E+=se,S=V+1}let N=await n.saw(Q(s),{start:T,end:S,total:v,text:h.kind==="text"?w:void 0});N!==void 0&&l.progress?.(N);let P="";if(S<v){let V=S+1;E>=vs||a===void 0&&U.length>=xs?P=`
|
|
160
160
|
|
|
161
|
-
[Showing lines ${T}-${S} of ${v}${E>=
|
|
161
|
+
[Showing lines ${T}-${S} of ${v}${E>=vs?" (50.0KB limit)":""}. Use offset=${V} to continue.]`:P=`
|
|
162
162
|
|
|
163
163
|
[${v-S} more lines in file. Use offset=${V} to continue.]`}return U.join(`
|
|
164
|
-
`)+P}}),
|
|
165
|
-
`).length:0,T=v?` (${v} line${v===1?"":"s"})`:"";
|
|
166
|
-
`),T=v.length,
|
|
164
|
+
`)+P}}),Fe({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:i,replace:a},l){let d=Q(s),p=await r.exists(d),h="";if(p&&a===!0&&t){let w=await n.known(d);if(w!=="all"){let k=await r.readAsText(d).catch(()=>null),v=k?.kind==="text"?k.text.split(`
|
|
165
|
+
`).length:0,T=v?` (${v} line${v===1?"":"s"})`:"";h=w==="part"?` Its previous content${T} was replaced, including the part you had not read.`:` Its previous content${T} was replaced without being read.`}}else if(p)try{await n.check(d,"overwrite")}catch(w){if(!(w instanceof en))throw w;let k=await r.readAsText(d).catch(()=>null);if(k?.kind!=="text")throw w;let v=k.text.split(`
|
|
166
|
+
`),T=v.length,C=w.coveredTo+1,R=[],U=0,E=w.coveredTo;for(let P=C-1;P<T&&R.length<xs;P++){let V=new TextEncoder().encode(v[P]).byteLength+1;if(U+V>vs&&R.length>0)break;R.push(v[P]),U+=V,E=P+1}let S=await n.saw(d,{start:C,end:E,total:T,text:k.text});S!==void 0&&l.progress?.(S);let N=E<T?` Lines ${E+1}-${T} are still unread: read them with read_file offset=${E+1} before overwriting.`:"";throw new Error(`${d} was not overwritten: you had read only lines 1-${w.coveredTo} of its ${T}. Here are lines ${C}-${E}, 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
|
${R.join(`
|
|
169
|
-
`)}`)}return await r.write(d,i),await n.wrote(d),`${
|
|
170
|
-
`);for(let T=0;T<v.length&&
|
|
171
|
-
`)+(
|
|
169
|
+
`)}`)}return await r.write(d,i),await n.wrote(d),`${p?h?"Replaced":"Updated":"Created"} ${d} (${new TextEncoder().encode(i).byteLength} bytes).${h}`}}),Fe({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 i=Q(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(i,"edit"),await r.edit(i,a),await n.edited(i),`Successfully replaced ${a.length} block(s) in ${i}.`}}),Fe({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 ${Q(s)}?`,async execute({path:s}){let i=Q(s);return await n.check(i,"delete"),await r.delete(i),n.forget(i),`Deleted ${i}.`}}),...["move_file","copy_file"].map(s=>Fe({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:i,to:a}){let l=Q(i),d=Q(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:h}=await r.read(l);return await r.write(d,p,h),await n.copied(l,d),s==="move_file"&&(await r.delete(l),n.forget(l)),`${s==="move_file"?"Moved":"Copied"} ${l} to ${d}.`}})),Fe({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:i,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=[],h=0;for(let w of await r.list(i||"/")){if(l.signal.throwIfAborted(),w.size>2e6)continue;let k;try{k=await r.readText(w.path)}catch{continue}h++;let v=k.split(`
|
|
170
|
+
`);for(let T=0;T<v.length&&p.length<ks;T++)d.test(v[T])&&p.push(`${w.path}:${T+1}: ${v[T].trim().slice(0,200)}`);if(p.length>=ks)break}return p.length?p.join(`
|
|
171
|
+
`)+(p.length>=ks?`
|
|
172
172
|
|
|
173
|
-
[${
|
|
173
|
+
[${ks} matches limit reached. Refine the pattern or search a sub-folder.]`:""):`No matches found (${h} text files searched).`}})]}function Ss(r,e){if(!r)return[];let n=[];return Pn(r,e,"",n,0),n}function Pa(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r}function Bc(r,e){let n=Pa(e);return r==="number"?n==="number"||n==="integer":r==="integer"?n==="integer":r===n}function Pn(r,e,n,t,s){if(s>32)return;let i=n||"arguments";for(let a of["anyOf","oneOf"]){let l=r[a];if(Array.isArray(l)&&l.length){let d=l.filter(p=>{let h=[];return Pn(p,e,n,h,s+1),h.length===0}).length;if(d===0){t.push(`${i}: does not match any allowed form`);return}if(a==="oneOf"&&d>1){t.push(`${i}: matches more than one of the allowed forms`);return}}}if(Array.isArray(r.allOf))for(let a of r.allOf)Pn(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=>Bc(l,e))){t.push(`${i}: expected ${a.join(" or ")}, got ${Pa(e)}`);return}}if(Array.isArray(r.enum)&&!r.enum.some(a=>Lo(a,e))){t.push(`${i}: must be one of ${r.enum.map(a=>JSON.stringify(a)).join(", ")}`);return}if("const"in r&&!Lo(r.const,e)){t.push(`${i}: must be ${JSON.stringify(r.const)}`);return}if(typeof e=="string"){if(typeof r.minLength=="number"&&e.length<r.minLength&&t.push(`${i}: shorter than ${r.minLength} characters`),typeof r.maxLength=="number"&&e.length>r.maxLength&&t.push(`${i}: longer than ${r.maxLength} characters`),typeof r.pattern=="string")try{new RegExp(r.pattern,"u").test(e)||t.push(`${i}: does not match pattern ${r.pattern}`)}catch{}}else if(typeof e=="number")typeof r.minimum=="number"&&e<r.minimum&&t.push(`${i}: below minimum ${r.minimum}`),typeof r.maximum=="number"&&e>r.maximum&&t.push(`${i}: above maximum ${r.maximum}`),typeof r.exclusiveMinimum=="number"&&e<=r.exclusiveMinimum&&t.push(`${i}: must be greater than ${r.exclusiveMinimum}`),typeof r.exclusiveMaximum=="number"&&e>=r.exclusiveMaximum&&t.push(`${i}: must be less than ${r.exclusiveMaximum}`);else if(Array.isArray(e))typeof r.minItems=="number"&&e.length<r.minItems&&t.push(`${i}: needs at least ${r.minItems} items`),typeof r.maxItems=="number"&&e.length>r.maxItems&&t.push(`${i}: at most ${r.maxItems} items`),r.items&&typeof r.items=="object"&&!Array.isArray(r.items)&&e.forEach((a,l)=>Pn(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(`${i}: missing required "${d}"`);for(let[d,p]of Object.entries(a)){let h=l[d];if(h)Pn(h,p,n?`${n}.${d}`:d,t,s+1);else if(r.additionalProperties===!1){let w=Object.keys(l);t.push(`${i}: unknown field "${d}"${w.length?` (allowed: ${w.join(", ")})`:""}`)}else r.additionalProperties&&typeof r.additionalProperties=="object"&&Pn(r.additionalProperties,p,n?`${n}.${d}`:d,t,s+1)}}}function Lo(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=>Lo(r[s],e[s]))}var _a=`
|
|
174
174
|
"use strict";
|
|
175
175
|
var isNode = typeof self === "undefined";
|
|
176
176
|
var port, send;
|
|
@@ -254,35 +254,35 @@ function onMessage(m) {
|
|
|
254
254
|
}
|
|
255
255
|
}
|
|
256
256
|
if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
|
|
257
|
-
`;async function
|
|
257
|
+
`;async function Wc(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let t=URL.createObjectURL(new Blob([_a],{type:"text/javascript"})),s=new Worker(t);return URL.revokeObjectURL(t),{post:i=>s.postMessage(i),onMessage:i=>{s.onmessage=a=>i(a.data)},onFail:i=>{s.onerror=a=>{a.preventDefault(),i(a.message||"The sandbox worker could not run; the page's Content-Security-Policy may block it.")}},terminate:()=>s.terminate()}}let r=new Function("m","return import(m)"),{Worker:e}=await r("node:worker_threads"),n=new e(_a,{eval:!0});return{post:t=>n.postMessage(t),onMessage:t=>n.on("message",s=>t(s)),onFail:t=>{n.on("error",s=>t(s instanceof Error?s.message:String(s))),n.on("exit",()=>t("The sandbox worker exited before the code finished."))},terminate:()=>n.terminate()}}async function Po(r,e,n={}){let t=Math.min(6e4,Math.max(100,n.timeoutMs??1e4)),s=await Wc(),i=Date.now(),a=n.bridge;return new Promise(l=>{let d=!1,p=new AbortController,h=P=>{d||(d=!0,clearTimeout(T),n.signal?.removeEventListener("abort",U),s.terminate(),p.abort(),l(P))},w=t,k=0,v=0,T,C=()=>{k=Date.now(),T=setTimeout(()=>h({ok:!1,logs:"",error:`Timed out after ${t} ms`,durationMs:Date.now()-i}),Math.max(0,w))},R=async P=>{v++===0&&(clearTimeout(T),w-=Date.now()-k);try{return await P()}finally{--v===0&&!d&&C()}};C();let U=()=>h({ok:!1,logs:"",error:"Aborted",durationMs:Date.now()-i});if(n.signal?.addEventListener("abort",U,{once:!0}),n.signal?.aborted)return U();s.onFail(P=>h({ok:!1,logs:"",error:P,durationMs:Date.now()-i}));let E=0,S=Promise.resolve(),N=(P,V)=>{if(!a?.names.includes(P))throw new Error(`there is no tool named "${P}"`);let se=a.max??50;if(++E>se)throw new Error(`this run has used its ${se} tool calls; return what you have and continue in another run_js`);let J=S.then(()=>{if(d)throw new Error("the code has finished");return a.call(P,V,p.signal)});return S=J.catch(()=>{}),J};s.onMessage(async P=>{P.type==="done"?h({ok:!0,result:P.result,logs:P.logs??"",durationMs:P.durationMs??Date.now()-i}):P.type==="error"?h({ok:!1,error:String(P.error),logs:P.logs??"",durationMs:P.durationMs??Date.now()-i}):P.type==="tool"&&R(async()=>{try{s.post({type:"toolResult",id:P.id,ok:!0,value:await N(String(P.name),P.args)})}catch(V){s.post({type:"toolResult",id:P.id,ok:!1,error:V.message})}})}),s.post({type:"run",code:r,input:e,network:!!n.network,maxLogChars:n.maxLogChars,tools:a?.names})})}function Cs(r={}){let e=r.maxCodeChars??2e4;return Fe({name:"run_js",description:`Run JavaScript in a sandbox (no DOM, no network) and get back what it returns plus its console output. Use it for arithmetic, dates, parsing, data transformation and to run a skill's scripts instead of working them out by hand. The code is the body of an async function: use \`return\` for the result (JSON), \`console.log\` for notes. Available: \`input\` (the input argument), and \`tools\` \u2014 \`await tools.<name>(args)\` calls any of your other tools with the same arguments and rules, one at a time, and resolves with its full text result (it throws when the call fails or the user declines; do not work around a decline). A tool that cannot be called from code says so when called. Up to ${r.maxToolCalls??50} calls per run and ${e} characters of code; time spent waiting for a tool does not count against the time limit.`,guidelines:"A large result you only need to compute over (logs, orders, a long list): fetch it inside run_js with `tools` and return the numbers, so the data never passes through this conversation. Parse a tool's text there rather than assuming a shape: try one call and look at it first.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript, the body of an async function"},input:{description:"Any JSON value made available as `input`"},timeout_ms:{type:"integer",minimum:100,maximum:6e4}},required:["code"],additionalProperties:!1},maxResultChars:24e3,async execute({code:n,input:t,timeout_ms:s},i){if(n.length>e)throw new Error(`the code is ${n.length} characters; the limit is ${e}. Do less in one run.`);let a={names:i.agent.tools.filter(p=>p.name!=="run_js"&&!p.endsRun&&!p.vision&&!p.display?.hidden&&p.callableFromCode!==!1).map(p=>p.name),max:r.maxToolCalls,call:async(p,h,w)=>{let k=await i.callTool(p,h,{signal:w});if(k.status!=="ok")throw new Error(k.text.replace(/^Error:\s*/,""));return k.text}},l=await Po(n,t,{...r,timeoutMs:s??r.timeoutMs,signal:i.signal,bridge:a}),d=[];return l.logs&&d.push(`console:
|
|
258
258
|
${l.logs}`),l.ok?d.push(l.result===void 0?"Returned: undefined":`Returned: ${l.result}`):d.push(/^\w*Error\b/.test(l.error??"")?String(l.error):`Error: ${l.error}`),d.push(`(${l.durationMs} ms)`),{content:d.join(`
|
|
259
259
|
|
|
260
|
-
`),details:l}}})}var
|
|
260
|
+
`),details:l}}})}var _o=["web_search","web_fetch"],Ra=r=>`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${r}</svg>`,Kc=Ra('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),Vc=Ra('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),Gc=["web_search finds pages and web_fetch reads one: use them for facts you can't know or that change (news, prices, releases, people, places, a work's details, a reference the user names), not for what the conversation or your own knowledge already answers.","Read the most relevant results with web_fetch before relying on them; a snippet is not the page. Say where an answer came from, with the link.","Each call costs the user a little: search with a precise query, and stop when you have enough."];function Zc(r){if(typeof r!="string")return"";try{let e=new URL(r.includes("://")?r:`https://${r}`),n=e.pathname==="/"?"":e.pathname;return e.host+(n.length>32?n.slice(0,31)+"\u2026":n)}catch{return r.slice(0,48)}}async function Ms(r,e={}){let n=await r.list(e.signal?{signal:e.signal}:void 0),t=[];for(let s of _o){let i=n.find(l=>l.name===s);if(!i)continue;let a=s==="web_search";t.push({name:s,description:i.description,parameters:i.parameters??{type:"object",properties:{}},readOnly:!0,maxResultChars:a?16e3:42e3,...a?{guidelines:Gc}:{},display:{icon:a?Vc:Kc,outcome:({details:l})=>{if(a){let p=l?.results?.length;return typeof p=="number"?String(p):void 0}let d=l?.title;return d?d.slice(0,40):void 0}},async execute(l,d){!a&&typeof l.url=="string"&&d.update(Zc(l.url));let p=await r.call(s,l,{signal:d.signal}),h=p.usage?.total_cost;return typeof h=="number"&&h>0&&e.onCost?.(h),{content:p.content,details:p.data}}})}return t}function Ro(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var Jc=["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 Re(r,e,n){let t=document.createElement(r);return e&&t.setAttribute("style",e),n!==void 0&&(t.textContent=n),t}function _n(r,e,n,t){let s=Re("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 Oo(r,e,n=null){let t=Re("dialog",Jc),s=n,i=a=>{s=a,t.close()};return r(t,i),e?.aborted?Promise.resolve(n):(document.body.append(t),new Promise(a=>{let l=()=>i(n);e?.addEventListener("abort",l,{once:!0}),t.addEventListener("close",()=>{e?.removeEventListener("abort",l),t.remove(),a(s)},{once:!0}),t.showModal()}))}function Es(){return typeof document>"u"||typeof HTMLDialogElement>"u"?Do():{async confirm(r,e,n={}){let t=Ro();return await Oo((i,a)=>{if(i.append(Re("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&i.append(Re("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word",e)),n.body)try{i.append(n.body())}catch(d){console.warn("agent: confirm body failed",d)}let l=Re("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");l.append(_n(n.cancel??(t?"\u53D6\u6D88":"Cancel"),!1,!1,()=>a(!1)),_n(n.ok??(t?"\u786E\u5B9A":"OK"),!0,!!n.danger,()=>a(!0))),i.append(l),queueMicrotask(()=>l.lastElementChild.focus())},n.signal,!1)===!0},async select(r,e,n={}){let t=Ro(),s=await Oo((i,a)=>{i.append(Re("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&i.append(Re("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=Re("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),d="ra_sel_"+Math.random().toString(36).slice(2,8),p=[],h=v=>{let T=Re("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"),C=Re("input");C.type=n.multi?"checkbox":"radio",C.name=d,C.value=v.value,C.setAttribute("style","margin-top:3px"),p.push(C);let R=Re("div");R.append(Re("div","",v.label??v.value)),v.description&&R.append(Re("div","opacity:.7;font-size:12px",v.description)),T.append(C,R),l.append(T)};e.forEach(h);let w=null;n.allowOther&&(h({value:"__other__",label:t?"\u5176\u4ED6\u2026":"Other\u2026"}),w=Re("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 v=p.find(T=>T.value==="__other__");v&&(v.checked=!0)}),l.append(w)),i.append(l);let k=Re("div","display:flex;justify-content:flex-end;gap:8px");k.append(_n(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>a(null)),_n(t?"\u786E\u5B9A":"OK",!0,!1,()=>{let v=p.filter(T=>T.checked).map(T=>T.value==="__other__"?w?.value.trim()||"":T.value).filter(Boolean);v.length&&a(v)})),i.append(k),queueMicrotask(()=>p[0]?.focus())},n.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let n=Ro(),t=await Oo((s,i)=>{s.append(Re("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(Re("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let a=Re(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&&i(a.value)}),s.append(a);let l=Re("div","display:flex;justify-content:flex-end;gap:8px");l.append(_n(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),_n(n?"\u786E\u5B9A":"OK",!0,!1,()=>i(a.value))),s.append(l),queueMicrotask(()=>a.focus())},e.signal,null);return typeof t=="string"?t:null},notify(r,e="info"){let n=Re("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 Do(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function As(){return Fe({name:"ask_user",callableFromCode:!1,description:"Ask the user one to three questions when the request is genuinely ambiguous and the answer changes what you would do. Give 2\u20135 short options when there are natural choices (allow_other adds a free-text choice); leave options out for a free-text answer. Do not ask what you can reasonably decide yourself.",parameters:{type:"object",properties:{questions:{type:"array",minItems:1,maxItems:3,items:{type:"object",properties:{question:{type:"string",minLength:1},options:{type:"array",minItems:2,maxItems:5,items:{type:"object",properties:{label:{type:"string",minLength:1},description:{type:"string"}},required:["label"],additionalProperties:!1}},allow_other:{type:"boolean"},multi:{type:"boolean"}},required:["question"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},async execute({questions:r},e){let n=[];for(let s of r){e.signal.throwIfAborted();let i;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});i=a===null?null:s.multi?a:a[0]??null}else i=await e.ui.input(s.question,{multiline:!0,signal:e.signal});if(n.push({question:s.question,answer:i}),i===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}
|
|
261
261
|
A: ${Array.isArray(s.answer)?s.answer.join(", "):s.answer}`).join(`
|
|
262
262
|
|
|
263
|
-
`),details:{answers:n}}}})}var
|
|
264
|
-
`),T=`${k.length} attachment${k.length===1?"":"s"}`;if(
|
|
265
|
-
`:""}[${T} no longer shown; call the tool again to see the current state]`});continue}a.push({...
|
|
266
|
-
`:""}[${T} follow${k.length===1?"s":""} in the next message]`}),l.push({type:"text",text:`Attachments from tool call ${f.tool_call_id??""}:`.trim()},...k);continue}a.push(f)}return d(),a}var Ma=2,Ea={image:"image_url",video:"video_url",audio:"audio_url"},Aa={image:"picture",video:"video",audio:"audio clip"};function Vc(r,e,n){let t=Object.keys(Ea).filter(i=>e[i]===!1);if(!t.length)return r;let s=i=>t.find(a=>Ea[a]===i.type);return r.map(i=>{if(!Array.isArray(i.content)||!i.content.some(l=>s(l)))return i;let a=i.content.map(l=>{let d=s(l);return d?{type:"text",text:`[A ${Aa[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${Aa[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...i,content:a}})}var Lo=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),vr=()=>({runId:"",reason:"aborted",text:"",usage:Lo()}),$n="Skipped: the user stopped the run.",Gc=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),$a=()=>new Qe(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function Ss(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(i=>{e.removeEventListener("abort",s),n(i)},i=>{e.removeEventListener("abort",s),t(i)})})}var zt=class{constructor(e,n={}){D(this,"id");D(this,"provider");D(this,"ui");D(this,"workspace");D(this,"tools");D(this,"opts");D(this,"web");D(this,"webCache",null);D(this,"history",[]);D(this,"committed",0);D(this,"droppedTurns",0);D(this,"_usage",Lo());D(this,"handlers",new Map);D(this,"anyHandlers",new Set);D(this,"queue",[]);D(this,"current",null);D(this,"chain",Promise.resolve());D(this,"pendingSkills",[]);D(this,"catalogue",null);D(this,"loop",{seen:new Set,idle:0,warned:!1});D(this,"turnNow",0);D(this,"loaded");D(this,"createdAt",Date.now());D(this,"title");D(this,"_ended",null);D(this,"persist");this.provider=ot(e),this.opts=n,this.id=n.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=n.ui??ks(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?Mn(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(...ws(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(Ts()),n.sandbox!==!1&&t.push(xs(typeof n.sandbox=="object"?n.sandbox:{}));let i=new Set;for(let a of t){if(i.has(a.name))throw new Error(`two tools are named "${a.name}"`);i.add(a.name)}if(this.tools=t,this.web=n.webTools??!1,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&&!hs(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??ka,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),typeof e.webTools=="boolean"&&(this.web=e.webTools),"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=Jt(n);t!==Dt&&(this.title=t)}return n.title=this.title??Dt,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?.(vr()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(vr())}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=Lo(),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?.({...vr(),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,i="done",a,l="",d=0,u={...this._usage},f=this.history.length;this.applySteering(t);let w=null,k;if(e){try{w=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(P){w=e,k=P instanceof Error?P:new Error(String(P))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let v=this.opts.maxTurns??ka,{output:T,input:M}=await this.limits(),R=M,U=dr(R,typeof this.opts.compaction=="object"?this.opts.compaction:{}),E=0;try{if(k)throw k;for(let P=1;;P++){if(s.aborted){i="aborted";break}if(P>v){i="max_turns";break}this.turnNow=P,this.emit("turn_start",{runId:t,turn:P}),this.applySteering(t);let V=await this.systemPrompt(),ne=this.fixedText(V),J=Se(this.history,ne);if(uo(J,R,U)){let $=this.opts.compaction===!1?!1:await this.compactWith(U,t,s),H=Se(this.history,ne);if(!$||uo(H,R,U)){let W=this.history.length&&De(this.history[0])!==null?[this.history[0]]:[],te=this.history.slice(W.length),N=lr(te,{budget:R-U.reserveTokens-Se(W),keepTurns:this.opts.keepTurns??4,system:ne});(N.droppedTurns||N.elidedResults)&&(this.history=[...W,...N.messages],this.droppedTurns+=N.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:t,summary:!1,tokensBefore:H,tokensAfter:Se(this.history,ne),droppedTurns:N.droppedTurns,elidedResults:N.elidedResults}))}}let pe=await this.activeTools(),ue={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:V},...this.toWireHistory(await this.mediaSupport())],max_tokens:T};ue.model||delete ue.model,pe.length&&(ue.tools=pe.map($=>os($))),this.opts.serverTools?.length&&(ue.server_tools=this.opts.serverTools),this.opts.prompt&&(ue.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(ue.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(ue.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:P,params:ue});let ke=Date.now(),ve;try{if(Se(this.history,ne)>R*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new Qe(413,"the request is far larger than the model's context");ve=await this.callModel(ue,t,s)}catch($){if(this.emit("response",{runId:t,turn:P,durationMs:Date.now()-ke,error:$ instanceof Error?$.message:String($)}),s.aborted||!Xr($))throw $;let H=Xi($);H!==void 0&&H<R&&(R=H,U=dr(R,typeof this.opts.compaction=="object"?this.opts.compaction:{}));let W=!1;for(;!W&&E<2;)W=await this.squeeze(R,E++,U,ne,t,s);if(W){P--;continue}throw new Rt({cause:this.overflowCause(R,ne),used:Se(this.history,ne),window:R},$ instanceof Error?$.message:String($),Yr($)??400)}this.emit("response",{runId:t,turn:P,durationMs:Date.now()-ke,finishReason:ve.finishReason,usage:ve.usage,message:ve.message}),ve.usage&&this.addUsage(ve.usage);let re={role:"assistant",content:ve.message.content,ts:Date.now()};ve.message.tool_calls?.length&&(re.tool_calls=ve.message.tool_calls),ve.reasoning&&(re.reasoning_content=ve.reasoning),this.history.push(re),typeof re.content=="string"&&re.content&&(l=re.content);let me=ve.finishReason==="length";this.emit("message_end",{runId:t,message:re,truncated:me}),this.emit("turn_end",{runId:t,turn:P,usage:ve.usage});let Me=re.tool_calls??[];if(!Me.length){if(this.committed=this.history.length,await this.saveSession(),me&&this.balanceLimited(ve.usage,T)){i="error",a=$a();break}if(!s.aborted&&this.queue.some($=>$.kind==="steer"))continue;break}let _e=await this.runBatch(Me,t,s,me);if(this.committed=this.history.length,await this.saveSession(),s.aborted){i="aborted";break}if(!me&&hr(re.content).trim()&&Me.every($=>this.tools.find(H=>H.name===$.function.name)?.endsRun)){if(this.queue.some($=>$.kind==="steer"))continue;break}if(me){if(d++,this.balanceLimited(ve.usage,T)){i="error",a=$a();break}if(d>=2){i="error",a=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let Le=this.checkLoop(_e);if(Le==="stop"){i="error",a=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}Le==="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(P){s.aborted?i="aborted":(i="error",a=P instanceof Error?P:new Error(String(P)))}i==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(f,u),this.committed=this.history.length,this.resetLoop();let S=a instanceof Rt?{code:a.code,overflow:a.overflow}:{};this._ended=i==="done"?null:{reason:i,...a?{error:a.message}:{},...S,at:Date.now()},await this.saveSession();let j={runId:t,reason:i,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",j),j}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 Vc(Kc(this.history.map((t,s)=>Wc(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}}get webTools(){return this.webToolsAvailable&&(typeof this.web=="function"?!!this.web():this.web)}get webToolsAvailable(){return!!this.provider.platformTools}async activeTools(){let e=this.tools;if(e.some(n=>n.vision)){let n=await this.accepts("image");e=e.filter(t=>!t.vision||n===!0)}if(this.webTools){let n=await this.loadWeb(),t=new Set(e.map(i=>i.name)),s=n.filter(i=>!t.has(i.name));s.length&&(e=[...e,...s])}return e}loadWeb(){let e=this.provider.platformTools;return e?(this.webCache??(this.webCache=vs(e,{onCost:n=>this.addToolCost(n)}).catch(n=>(this.webCache=null,console.warn("[agent] could not load the web tools:",n),[]))),this.webCache):Promise.resolve([])}async systemPrompt(){let e=this.workspace,n=async(s,i)=>{if(e)try{let a=await e.readText(s);return a.length>i?a.slice(a.length-i):a}catch{return}},t=await this.activeTools();return Qr({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e&&t.some(s=>Gc.has(s.name))?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??Sa,2e4),agentsPath:this.opts.instructionsFile||Sa,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??Ta,Hc),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??Ta,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async n=>{let t=await this.contextTokens(),s=this.squeezed(dr(t,typeof this.opts.compaction=="object"?this.opts.compaction:{})),i=await this.compactWith(s,void 0,n,e);return i&&await this.saveSession(),i})}summarize(e){return this.exclusive("summarize",async n=>{let t=this.history.filter(d=>d!==e),s=t[0]?De(t[0]):null,i=s===null?t:t.slice(1);if(!i.length)return s;let a=await this.contextTokens(),l=dr(a,typeof this.opts.compaction=="object"?this.opts.compaction:{});this.emit("compaction_start",{});try{return await this.writeSummary({toSummarize:i,previousSummary:s??void 0,kept:[]},l,void 0,n)}catch(d){if(n.aborted)throw d;return console.warn("[agent] summary failed:",d),null}})}async seed(e){if(await this.loaded,this.current)throw new Error("cannot seed while a run is active");if(this.history.length)throw new Error("seed needs an empty conversation");this.history=[cr(e)],this.committed=1,this._ended=null,await this.saveSession()}exclusive(e,n){if(this.current)return Promise.reject(new Error(`cannot ${e} while a run is active`));let t=new AbortController,s=this.chain.then(async()=>(await this.loaded,n(t.signal))),i=s.then(()=>({...vr(),reason:"done"}),()=>vr());return this.current={controller:t,promise:i},this.chain=i,i.finally(()=>{this.current?.controller===t&&(this.current=null),this.drainFollowUps()}),s}squeezed(e){let n=this.history,t=n.length-1;for(;t>0&&!(n[t].role==="user"&&De(n[t])===null);)t--;let s=t>0?n.slice(t).reduce((i,a)=>i+Se([a]),0):Math.floor(Se(n)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,n,t,s,i,a){let l=Se(this.history,s);n===0&&this.opts.compaction!==!1&&await this.compactWith(this.squeezed(t),i,a);let d=this.history.length&&De(this.history[0])!==null?[this.history[0]]:[],u=this.history.slice(d.length),f=Math.floor(e*(n===0?.7:.4))-Se(d),w=lr(u,{budget:f,keepTurns:1,system:s,keepResults:n===0?3:0});return(w.droppedTurns||w.elidedResults)&&(this.history=[...d,...w.messages],this.droppedTurns+=w.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:i,summary:!1,tokensBefore:l,tokensAfter:Se(this.history,s),droppedTurns:w.droppedTurns,elidedResults:w.elidedResults})),Se(this.history,s)<l}overflowCause(e,n){let t=this.tools.length?Se([],JSON.stringify(this.tools.map(d=>os(d)))):0,s=[...this.history].reverse().find(d=>d.role==="user"&&De(d)===null),i=s?Se([s]):0,a=Se(this.history)-i,l=Math.max(t,i,a);return l*2<e?"model":l===i?(Array.isArray(s.content)?s.content.length>1:/(^|\n)\[attachments\]/.test(String(s.content??"")))?"attachments":"message":l===t?"tools":"history"}async writeSummary(e,n,t,s){if(typeof this.opts.compaction=="function")return this.opts.compaction(e,this);let i=await this.limits(),a=Math.min(i.output,Math.max(1024,Math.floor(n.reserveTokens*.8))),l=Math.max(6e3,(i.input-a-1500)*3),d=e.previousSummary;for(let u of ts(ur(e.toSummarize),l)){let f={model:this.opts.model??"",messages:ta(u,d,e.focus),max_tokens:a};f.model||delete f.model;let w={runId:t??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...w,params:f}),s.throwIfAborted();let k=Date.now(),v;try{v=this.provider.complete?await this.provider.complete(f,{signal:s}):await pr((M,R)=>this.provider.stream(M,R),f,{signal:s}).then(M=>({choices:[{message:{...M.message,content:typeof M.message.content=="string"?M.message.content:null},finish_reason:M.finishReason}],usage:M.usage}))}catch(M){throw this.emit("response",{...w,durationMs:Date.now()-k,error:M instanceof Error?M.message:String(M)}),M}v.usage&&this.addUsage(v.usage);let T=v.choices[0];if(this.emit("response",{...w,durationMs:Date.now()-k,finishReason:T?.finish_reason??void 0,usage:v.usage??void 0,message:T?.message}),!T||T.finish_reason==="length")throw new Error("the summary is incomplete");if(T.message.tool_calls?.length)throw new Error("the summariser attempted to call a tool");if(d=(T.message.content??"").trim(),!d)throw new Error("empty summary")}return d}async compactWith(e,n,t,s){let i=es(this.history,e.keepRecentTokens);if(!i)return!1;s?.trim()&&(i.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=Se(this.history),l;try{l=await this.writeSummary(i,e,n,t)}catch(d){if(t.aborted)throw d;return console.warn("[agent] compaction summary failed, falling back to trimming:",d),!1}return this.history=[cr(l),...i.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:Se(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 i=await rs(this.workspace,s);if(i===s)return e;let a=n?[{type:"text",text:i},...n.slice(1)]:i;return{...e,content:a,typed:s}}async callModel(e,n,t){let s="",i="",a=!1;for(let l=1;;l++){s="",i="",t.throwIfAborted();try{return await pr((d,u)=>this.provider.stream(d,u),e,{signal:t,onText:(d,u)=>{a=!0,s=u,this.emit("text_delta",{runId:n,delta:d,text:u})},onReasoning:(d,u)=>{a=!0,i=u,this.emit("reasoning_delta",{runId:n,delta:d,text:u})},onToolCall:(d,u)=>{a=!0,this.emit("tool_call_delta",{runId:n,index:d.index,id:d.id,name:d.name,delta:u,arguments:d.arguments})}})}catch(d){if(t.aborted||l>=Nc||!Zc(d))throw d;let u=Jc(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await Xc(u,t)}}}async runBatch(e,n,t,s){let i=l=>this.runTool(l,n,t,s),a=this.opts.parallelTools?await Promise.all(e.map(l=>i(l))):await(async()=>{let l=[],d=!1;for(let u of e){if(d){l.push(this.skipTool(u,n,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}l.push(await i(u)),this.queue.some(f=>f.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??"",i=e.function.name;return this.emit("tool_start",{runId:n,id:s,name:i,args:e.function.arguments}),this.emit("tool_end",{runId:n,id:s,name:i,status:"skipped",result:t,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:t},key:"",changed:!1,progress:!0,status:"skipped"}}async runTool(e,n,t,s,i){let a=e.id??"",l=i?{parentId:i}:{},d=e.function.name,u=Date.now(),f,w,k=(E,S,j)=>{let P=hr(S);return this.emit("tool_end",{runId:n,id:a,name:d,status:E,result:i?ss(P,32e3).text:P,details:j,durationMs:Date.now()-u,...l,...typeof S=="string"?{}:{content:S}}),{status:E,details:j,message:{role:"tool",tool_call_id:a,content:S},key:w?.readOnly?`${d}|${E}|${P.slice(0,4e3)}`:`${d}|${e.function.arguments.slice(0,4e3)}|${E}|${P.slice(0,2e3)}`,changed:E==="ok"&&!!w&&!w.readOnly,progress:E==="declined"||E==="skipped"?!0:E==="ok"?f:void 0}};if(t.aborted)return k("skipped",$n);if(s)return this.emit("tool_start",{runId:n,id:a,name:d,args:e.function.arguments,...l}),k("error",`Tool call "${d}" 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 v=await this.activeTools();w=v.find(E=>E.name===d);let T;try{T=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:n,id:a,name:d,args:e.function.arguments,...l}),k("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:n,id:a,name:d,args:T,...l}),!w)return k("error",`Error: there is no tool named "${d}". Available tools: ${v.map(E=>E.name).join(", ")}.`);if(T===null||typeof T!="object"||Array.isArray(T))return k("error","Error: the arguments must be a JSON object.");let M=bs(w.parameters,T);if(M.length)return k("error",`Error: invalid arguments for ${d}:
|
|
267
|
-
- ${
|
|
263
|
+
`),details:{answers:n}}}})}var Oa=100,Yc=8192,Qc=128e3,Da="/memory/notes.md",za="/AGENTS.md",ed=6e3,td=3,Ia=2e6,nd=3,rd=6;function sd(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:i,runUsage:a,...l}=r;return t&&delete l.reasoning_content,l}function od(r){let e=p=>p.role==="tool"&&Array.isArray(p.content)&&p.content.some(h=>h.type!=="text");if(!r.some(e))return r;let n=[],t=-1,s=!1;r.forEach((p,h)=>{if(p.role!=="tool"){t=-1;return}t<0&&(t=h,s=!1),!s&&e(p)&&(n.push(t),s=!0)});let i=n.length>Ua?n[n.length-Ua]:0,a=[],l=[],d=()=>{l.length&&a.push({role:"user",content:l}),l=[]};for(let[p,h]of r.entries()){if(h.role!=="tool"&&d(),e(h)){let w=h.content,k=w.filter(C=>C.type!=="text"),v=w.filter(C=>C.type==="text").map(C=>C.text).join(`
|
|
264
|
+
`),T=`${k.length} attachment${k.length===1?"":"s"}`;if(p<i){a.push({...h,content:`${v}${v?`
|
|
265
|
+
`:""}[${T} no longer shown; call the tool again to see the current state]`});continue}a.push({...h,content:`${v}${v?`
|
|
266
|
+
`:""}[${T} follow${k.length===1?"s":""} in the next message]`}),l.push({type:"text",text:`Attachments from tool call ${h.tool_call_id??""}:`.trim()},...k);continue}a.push(h)}return d(),a}var Ua=2,Fa={image:"image_url",video:"video_url",audio:"audio_url"},Na={image:"picture",video:"video",audio:"audio clip"};function id(r,e,n){let t=Object.keys(Fa).filter(i=>e[i]===!1);if(!t.length)return r;let s=i=>t.find(a=>Fa[a]===i.type);return r.map(i=>{if(!Array.isArray(i.content)||!i.content.some(l=>s(l)))return i;let a=i.content.map(l=>{let d=s(l);return d?{type:"text",text:`[A ${Na[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${Na[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...i,content:a}})}var Io=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),Mr=()=>({runId:"",reason:"aborted",text:"",usage:Io()}),Rn="Skipped: the user stopped the run.",ad=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),Ha=()=>new et(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function $s(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(i=>{e.removeEventListener("abort",s),n(i)},i=>{e.removeEventListener("abort",s),t(i)})})}var Ut=class{constructor(e,n={}){D(this,"id");D(this,"provider");D(this,"ui");D(this,"workspace");D(this,"tools");D(this,"opts");D(this,"web");D(this,"compactSummaries");D(this,"compactThresholds");D(this,"webCache",null);D(this,"history",[]);D(this,"committed",0);D(this,"droppedTurns",0);D(this,"_usage",Io());D(this,"handlers",new Map);D(this,"anyHandlers",new Set);D(this,"queue",[]);D(this,"current",null);D(this,"chain",Promise.resolve());D(this,"pendingSkills",[]);D(this,"catalogue",null);D(this,"loop",{seen:new Set,idle:0,warned:!1});D(this,"turnNow",0);D(this,"loaded");D(this,"createdAt",Date.now());D(this,"title");D(this,"_ended",null);D(this,"persist");this.provider=ot(e),this.opts=n,this.compactSummaries=n.compaction!==!1,this.compactThresholds=typeof n.compaction=="object"?{...n.compaction}:{},this.id=n.id||`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,this.ui=n.ui??Es(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?Ln(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(...Ts(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(As()),n.sandbox!==!1&&t.push(Cs(typeof n.sandbox=="object"?n.sandbox:{}));let i=new Set;for(let a of t){if(i.has(a.name))throw new Error(`two tools are named "${a.name}"`);i.add(a.name)}if(this.tools=t,this.web=n.webTools??!1,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&&!bs(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??Oa,maxTokens:typeof this.opts.maxTokens=="number"?this.opts.maxTokens:"auto",permissions:typeof e=="function"?"custom":e,reasoningEffort:typeof n=="string"?n:void 0,compaction:{summarize:this.compactSummaries,...this.compactThresholds}}}configure(e){if(e.compaction){let n=e.compaction;typeof n.summarize=="boolean"&&(this.compactSummaries=n.summarize);for(let t of["reserveTokens","keepRecentTokens"]){if(!(t in n))continue;let s=n[t];typeof s=="number"&&Number.isFinite(s)&&s>0?this.compactThresholds[t]=Math.floor(s):delete this.compactThresholds[t]}}if("model"in e&&(this.model=e.model||void 0),typeof e.webTools=="boolean"&&(this.web=e.webTools),"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)}compactionFor(e){return{summarize:this.compactSummaries,...zt(e,this.compactThresholds)}}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=Qt(n);t!==It&&(this.title=t)}return n.title=this.title??It,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?.(Mr()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(Mr())}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=Io(),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?.({...Mr(),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,i="done",a,l="",d=0,p={...this._usage},h=this.history.length;this.applySteering(t);let w=null,k;if(e){try{w=await this.withSkillPrefaces(await this.expandSlashes(e))}catch(P){w=e,k=P instanceof Error?P:new Error(String(P))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let v=this.opts.maxTurns??Oa,{output:T,input:C}=await this.limits(),R=C,U=zt(R,this.compactThresholds),E=0;try{if(k)throw k;for(let P=1;;P++){if(s.aborted){i="aborted";break}if(P>v){i="max_turns";break}this.turnNow=P,this.emit("turn_start",{runId:t,turn:P}),this.applySteering(t);let V=await this.systemPrompt(),se=this.fixedText(V),J=Me(this.history,se);if(wo(J,R,U)){let $=this.compactSummaries?await this.compactWith(U,t,s):!1,H=Me(this.history,se);if(!$||wo(H,R,U)){let W=this.history.length&&ze(this.history[0])!==null?[this.history[0]]:[],ne=this.history.slice(W.length),j=hr(ne,{budget:R-U.reserveTokens-Me(W),keepTurns:this.opts.keepTurns??4,system:se});(j.droppedTurns||j.elidedResults)&&(this.history=[...W,...j.messages],this.droppedTurns+=j.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:t,summary:!1,tokensBefore:H,tokensAfter:Me(this.history,se),droppedTurns:j.droppedTurns,elidedResults:j.elidedResults}))}}let fe=await this.activeTools(),pe={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:V},...this.toWireHistory(await this.mediaSupport())],max_tokens:T};pe.model||delete pe.model,fe.length&&(pe.tools=fe.map($=>ds($))),this.opts.serverTools?.length&&(pe.server_tools=this.opts.serverTools),this.opts.prompt&&(pe.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(pe.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(pe.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:P,params:pe});let Ce=Date.now(),Se;try{if(Me(this.history,se)>R*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new et(413,"the request is far larger than the model's context");Se=await this.callModel(pe,t,s)}catch($){if(this.emit("response",{runId:t,turn:P,durationMs:Date.now()-Ce,error:$ instanceof Error?$.message:String($)}),s.aborted||!ns($))throw $;let H=da($);H!==void 0&&H<R&&(R=H,U=zt(R,this.compactThresholds));let W=!1;for(;!W&&E<2;)W=await this.squeeze(R,E++,U,se,t,s);if(W){P--;continue}throw new Ot({cause:this.overflowCause(R,se),used:Me(this.history,se),window:R},$ instanceof Error?$.message:String($),rs($)??400)}this.emit("response",{runId:t,turn:P,durationMs:Date.now()-Ce,finishReason:Se.finishReason,usage:Se.usage,message:Se.message}),Se.usage&&this.addUsage(Se.usage);let oe={role:"assistant",content:Se.message.content,ts:Date.now()};Se.message.tool_calls?.length&&(oe.tool_calls=Se.message.tool_calls),Se.reasoning&&(oe.reasoning_content=Se.reasoning),this.history.push(oe),typeof oe.content=="string"&&oe.content&&(l=oe.content);let ye=Se.finishReason==="length";this.emit("message_end",{runId:t,message:oe,truncated:ye}),this.emit("turn_end",{runId:t,turn:P,usage:Se.usage});let Ae=oe.tool_calls??[];if(!Ae.length){if(this.committed=this.history.length,await this.saveSession(),ye&&this.balanceLimited(Se.usage,T)){i="error",a=Ha();break}if(!s.aborted&&this.queue.some($=>$.kind==="steer"))continue;break}let Oe=await this.runBatch(Ae,t,s,ye);if(this.committed=this.history.length,await this.saveSession(),s.aborted){i="aborted";break}if(!ye&&br(oe.content).trim()&&Ae.every($=>this.tools.find(H=>H.name===$.function.name)?.endsRun)){if(this.queue.some($=>$.kind==="steer"))continue;break}if(ye){if(d++,this.balanceLimited(Se.usage,T)){i="error",a=Ha();break}if(d>=2){i="error",a=new Error("the model's tool calls were cut off by the output limit twice in a row");break}}let _e=this.checkLoop(Oe);if(_e==="stop"){i="error",a=new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");break}_e==="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(P){s.aborted?i="aborted":(i="error",a=P instanceof Error?P:new Error(String(P)))}i==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(h,p),this.committed=this.history.length,this.resetLoop();let S=a instanceof Ot?{code:a.code,overflow:a.overflow}:{};this._ended=i==="done"?null:{reason:i,...a?{error:a.message}:{},...S,at:Date.now()},await this.saveSession();let N={runId:t,reason:i,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",N),N}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 id(od(this.history.map((t,s)=>sd(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}}get webTools(){return this.webToolsAvailable&&(typeof this.web=="function"?!!this.web():this.web)}get webToolsAvailable(){return!!this.provider.platformTools}async activeTools(){let e=this.tools;if(e.some(n=>n.vision)){let n=await this.accepts("image");e=e.filter(t=>!t.vision||n===!0)}if(this.webTools){let n=await this.loadWeb(),t=new Set(e.map(i=>i.name)),s=n.filter(i=>!t.has(i.name));s.length&&(e=[...e,...s])}return e}loadWeb(){let e=this.provider.platformTools;return e?(this.webCache??(this.webCache=Ms(e,{onCost:n=>this.addToolCost(n)}).catch(n=>(this.webCache=null,console.warn("[agent] could not load the web tools:",n),[]))),this.webCache):Promise.resolve([])}async systemPrompt(){let e=this.workspace,n=async(s,i)=>{if(e)try{let a=await e.readText(s);return a.length>i?a.slice(a.length-i):a}catch{return}},t=await this.activeTools();return ss({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e&&t.some(s=>ad.has(s.name))?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??za,2e4),agentsPath:this.opts.instructionsFile||za,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??Da,ed),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??Da,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async n=>{let t=await this.contextTokens(),s=this.squeezed(zt(t,this.compactThresholds)),i=await this.compactWith(s,void 0,n,e);return i&&await this.saveSession(),i})}summarize(e){return this.exclusive("summarize",async n=>{let t=this.history.filter(d=>d!==e),s=t[0]?ze(t[0]):null,i=s===null?t:t.slice(1);if(!i.length)return s;let a=await this.contextTokens(),l=zt(a,this.compactThresholds);this.emit("compaction_start",{});try{return await this.writeSummary({toSummarize:i,previousSummary:s??void 0,kept:[]},l,void 0,n)}catch(d){if(n.aborted)throw d;return console.warn("[agent] summary failed:",d),null}})}async seed(e){if(await this.loaded,this.current)throw new Error("cannot seed while a run is active");if(this.history.length)throw new Error("seed needs an empty conversation");this.history=[mr(e)],this.committed=1,this._ended=null,await this.saveSession()}exclusive(e,n){if(this.current)return Promise.reject(new Error(`cannot ${e} while a run is active`));let t=new AbortController,s=this.chain.then(async()=>(await this.loaded,n(t.signal))),i=s.then(()=>({...Mr(),reason:"done"}),()=>Mr());return this.current={controller:t,promise:i},this.chain=i,i.finally(()=>{this.current?.controller===t&&(this.current=null),this.drainFollowUps()}),s}squeezed(e){let n=this.history,t=n.length-1;for(;t>0&&!(n[t].role==="user"&&ze(n[t])===null);)t--;let s=t>0?n.slice(t).reduce((i,a)=>i+Me([a]),0):Math.floor(Me(n)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,n,t,s,i,a){let l=Me(this.history,s);n===0&&this.compactSummaries&&await this.compactWith(this.squeezed(t),i,a);let d=this.history.length&&ze(this.history[0])!==null?[this.history[0]]:[],p=this.history.slice(d.length),h=Math.floor(e*(n===0?.7:.4))-Me(d),w=hr(p,{budget:h,keepTurns:1,system:s,keepResults:n===0?3:0});return(w.droppedTurns||w.elidedResults)&&(this.history=[...d,...w.messages],this.droppedTurns+=w.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:i,summary:!1,tokensBefore:l,tokensAfter:Me(this.history,s),droppedTurns:w.droppedTurns,elidedResults:w.elidedResults})),Me(this.history,s)<l}overflowCause(e,n){let t=this.tools.length?Me([],JSON.stringify(this.tools.map(d=>ds(d)))):0,s=[...this.history].reverse().find(d=>d.role==="user"&&ze(d)===null),i=s?Me([s]):0,a=Me(this.history)-i,l=Math.max(t,i,a);return l*2<e?"model":l===i?(Array.isArray(s.content)?s.content.length>1:/(^|\n)\[attachments\]/.test(String(s.content??"")))?"attachments":"message":l===t?"tools":"history"}async writeSummary(e,n,t,s){if(typeof this.opts.compaction=="function")return this.opts.compaction(e,this);let i=await this.limits(),a=Math.min(i.output,Math.max(1024,Math.floor(n.reserveTokens*.8))),l=Math.max(6e3,(i.input-a-1500)*3),d=e.previousSummary;for(let p of is(gr(e.toSummarize),l)){let h={model:this.opts.model??"",messages:fa(p,d,e.focus),max_tokens:a};h.model||delete h.model;let w={runId:t??"",turn:this.turnNow,purpose:"compaction"};this.emit("request",{...w,params:h}),s.throwIfAborted();let k=Date.now(),v;try{v=this.provider.complete?await this.provider.complete(h,{signal:s}):await yr((C,R)=>this.provider.stream(C,R),h,{signal:s}).then(C=>({choices:[{message:{...C.message,content:typeof C.message.content=="string"?C.message.content:null},finish_reason:C.finishReason}],usage:C.usage}))}catch(C){throw this.emit("response",{...w,durationMs:Date.now()-k,error:C instanceof Error?C.message:String(C)}),C}v.usage&&this.addUsage(v.usage);let T=v.choices[0];if(this.emit("response",{...w,durationMs:Date.now()-k,finishReason:T?.finish_reason??void 0,usage:v.usage??void 0,message:T?.message}),!T||T.finish_reason==="length")throw new Error("the summary is incomplete");if(T.message.tool_calls?.length)throw new Error("the summariser attempted to call a tool");if(d=(T.message.content??"").trim(),!d)throw new Error("empty summary")}return d}async compactWith(e,n,t,s){let i=os(this.history,e.keepRecentTokens);if(!i)return!1;s?.trim()&&(i.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=Me(this.history),l;try{l=await this.writeSummary(i,e,n,t)}catch(d){if(t.aborted)throw d;return console.warn("[agent] compaction summary failed, falling back to trimming:",d),!1}return this.history=[mr(l),...i.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:Me(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 i=await ls(this.workspace,s);if(i===s)return e;let a=n?[{type:"text",text:i},...n.slice(1)]:i;return{...e,content:a,typed:s}}async callModel(e,n,t){let s="",i="",a=!1;for(let l=1;;l++){s="",i="",t.throwIfAborted();try{return await yr((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,i=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>=td||!ld(d))throw d;let p=cd(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await dd(p,t)}}}async runBatch(e,n,t,s){let i=l=>this.runTool(l,n,t,s),a=this.opts.parallelTools?await Promise.all(e.map(l=>i(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 i(p)),this.queue.some(h=>h.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??"",i=e.function.name;return this.emit("tool_start",{runId:n,id:s,name:i,args:e.function.arguments}),this.emit("tool_end",{runId:n,id:s,name:i,status:"skipped",result:t,durationMs:0}),{message:{role:"tool",tool_call_id:s,content:t},key:"",changed:!1,progress:!0,status:"skipped"}}async runTool(e,n,t,s,i){let a=e.id??"",l=i?{parentId:i}:{},d=e.function.name,p=Date.now(),h,w,k=(E,S,N)=>{let P=br(S);return this.emit("tool_end",{runId:n,id:a,name:d,status:E,result:i?cs(P,32e3).text:P,details:N,durationMs:Date.now()-p,...l,...typeof S=="string"?{}:{content:S}}),{status:E,details:N,message:{role:"tool",tool_call_id:a,content:S},key:w?.readOnly?`${d}|${E}|${P.slice(0,4e3)}`:`${d}|${e.function.arguments.slice(0,4e3)}|${E}|${P.slice(0,2e3)}`,changed:E==="ok"&&!!w&&!w.readOnly,progress:E==="declined"||E==="skipped"?!0:E==="ok"?h:void 0}};if(t.aborted)return k("skipped",Rn);if(s)return this.emit("tool_start",{runId:n,id:a,name:d,args:e.function.arguments,...l}),k("error",`Tool call "${d}" 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 v=await this.activeTools();w=v.find(E=>E.name===d);let T;try{T=e.function.arguments.trim()?JSON.parse(e.function.arguments):{}}catch{return this.emit("tool_start",{runId:n,id:a,name:d,args:e.function.arguments,...l}),k("error","Error: the arguments are not valid JSON.")}if(this.emit("tool_start",{runId:n,id:a,name:d,args:T,...l}),!w)return k("error",`Error: there is no tool named "${d}". Available tools: ${v.map(E=>E.name).join(", ")}.`);if(T===null||typeof T!="object"||Array.isArray(T))return k("error","Error: the arguments must be a JSON object.");let C=Ss(w.parameters,T);if(C.length)return k("error",`Error: invalid arguments for ${d}:
|
|
267
|
+
- ${C.join(`
|
|
268
268
|
- `)}
|
|
269
|
-
Fix the call and try again.`);if(w.validate){let E;try{E=await
|
|
270
|
-
${JSON.stringify(this.tools.map(n=>
|
|
271
|
-
|
|
272
|
-
${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content??[],i=e.typed??(typeof e.content=="string"?e.content:void 0);return{...e,role:"user",content:[...t,...s],...i!==void 0?{typed:i}:{}}}estimateContext(){return
|
|
273
|
-
`).trim()||`${
|
|
274
|
-
`:""}${i.text}`:`[Resource ${i.uri??""} (${i.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
|
|
275
|
-
`){e+="<br>",n++;continue}e+=
|
|
276
|
-
`&&!(n[0]==="_"&&t+n.length<r.length&&
|
|
269
|
+
Fix the call and try again.`);if(w.validate){let E;try{E=await $s(Promise.resolve(w.validate(T)),t)}catch(S){E=S instanceof Error?S.message:String(S)}if(t.aborted)return k("skipped",Rn);if(E)return k("error",E.startsWith("Error:")?E:`Error: ${E}`)}try{let E=await $s(Promise.resolve(this.opts.onToolCall?.({id:a,name:d,args:T,tool:w})),t);if(E&&E.block)return k("blocked",`${E.reason??"This action was not allowed."} Do not retry it another way; say what you would have done.`);if(!await $s(this.permitted(w,T,t),t))return k("declined","The user declined this action. Do not retry it another way; say what you would have done.")}catch(E){return t.aborted?k("skipped",Rn):k("error",`Error: ${E.message}`)}if(t.aborted)return k("skipped",Rn);let R=()=>{try{let E=w.whenStopped?.(T);if(E!==void 0){let S=wr(E,i?Ia:w.maxResultChars);return k("skipped",S.content,S.details)}}catch{}return k("skipped",Rn)},U=0;try{let E=await $s(Promise.resolve(w.execute(T,{signal:t,ui:this.ui,workspace:this.workspace,agent:this,callId:a,parentId:i,update:N=>this.emit("tool_update",{runId:n,id:a,name:d,content:N,...l}),progress:N=>{h=N},callTool:async(N,P,V)=>{let se=await this.runTool({id:`${a}.${++U}`,type:"function",function:{name:N,arguments:JSON.stringify(P??{})}},n,V?.signal??t,!1,a);return{status:se.status,text:br(se.message.content),details:se.details}}})),t);if(t.aborted)return R();let S=wr(E,i?Ia:w.maxResultChars);return k("ok",S.content,S.details)}catch(E){if(t.aborted)return R();let S=E instanceof Error?E.message:String(E);return k("error",S.startsWith("Error:")?S:`Error: ${S}`)}}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 i=!1;if(e.confirm?i=await e.confirm(n):e.destructive&&(i=`Allow ${e.name}?`),i===!1)return!0;let{title:a,message:l,always:d,ok:p,body:h}=typeof i=="string"?{title:i,message:void 0,always:void 0,ok:void 0,body:void 0}:i;return this.ui.confirm(a,l,{danger:!!e.destructive,signal:t,always:d,...p?{ok:p}:{},...h?{body:h}:{}})}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(i=>i.tool_call_id));for(let i of t.tool_calls)i.id&&!s.has(i.id)&&this.history.push({role:"tool",tool_call_id:i.id,content:Rn})}checkLoop(e){let n=this.opts.loopGuard;if(n===!1)return"ok";let t=n?.warn??nd,s=n?.stop??rd,i=this.loop,a=e.map(p=>p.key!==""&&!i.seen.has(p.key)),l=e.some((p,h)=>p.changed&&a[h]);l&&i.seen.clear();for(let p of e)p.key&&i.seen.add(p.key);let d=l||e.some((p,h)=>p.progress??a[h]);return i.seen.size>512&&i.seen.delete(i.seen.values().next().value),d?(i.idle=0,i.warned=!1,"ok"):(i.idle++,i.idle>=s?"stop":i.idle>=t&&!i.warned?(i.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 i=this.history[s];if(i.role==="assistant"){i.runUsage={total_cost:zo(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}}}addToolCost(e){this._usage.total_cost=zo(this._usage.total_cost+e)}addUsage(e){this._usage.total_cost=zo(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:Me(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 i;try{i=JSON.parse(s.function.arguments)}catch{continue}let a=["read_file","write_file","edit_file"].includes(s.function.name)?i.path:["move_file","copy_file"].includes(s.function.name)?i.to:void 0;typeof a=="string"&&n.push(Q(a))}return n}fixedText(e){return this.tools.length?`${e}
|
|
270
|
+
${JSON.stringify(this.tools.map(n=>ds(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:Qc,t=typeof e?.max_tokens=="number"&&e.max_tokens>0?e.max_tokens:Yc;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:Dt(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.]
|
|
271
|
+
|
|
272
|
+
${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content??[],i=e.typed??(typeof e.content=="string"?e.content:void 0);return{...e,role:"user",content:[...t,...s],...i!==void 0?{typed:i}:{}}}estimateContext(){return Me(this.history)}contextWindow(){return this.contextTokens()}};function ld(r){let e=rs(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 cd(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 dd(r,e){return new Promise((n,t)=>{let s=()=>{clearTimeout(i),t(e.reason??new Error("aborted"))},i=setTimeout(()=>{e.removeEventListener("abort",s),n()},r);e.addEventListener("abort",s,{once:!0})})}function zo(r){return Math.round(r*1e6)/1e6}var ja="2025-06-18",Pe=class extends Error{constructor(n,t,s){super(n);D(this,"status",t);D(this,"code",s);this.name="MCPError"}};async function Wa(r,e={}){e.signal?.throwIfAborted();let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Pe("An MCP endpoint is an http(s) URL.");let t=e.fetch??globalThis.fetch.bind(globalThis),s=e.timeoutMs??6e4,i,a,l=1,d=!1,p=e.signal,h=J=>({...e.headers??{},...J?{"Content-Type":"application/json",Accept:"application/json, text/event-stream"}:{},...e.token?{Authorization:`Bearer ${e.token}`}:{},...i?{"Mcp-Session-Id":i}:{},...a?{"MCP-Protocol-Version":a}:{}}),w=(J,fe)=>t(n,{method:"POST",headers:h(!0),body:JSON.stringify(J),signal:fe,redirect:"error",credentials:"omit"}),k=J=>{let fe=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(fe,AbortSignal.timeout(s)).then(pe=>pe.body?.cancel()).catch(()=>{})},v=async(J,fe,pe,Ce,Se=!1)=>{if(d)throw new Pe("The MCP connection is closed.");let oe=l++,ye=AbortSignal.timeout(s),Ae=Ba([ye,...pe?[pe]:[],...p?[p]:[]]),Oe={jsonrpc:"2.0",id:oe,method:J,...fe?{params:Ce?{...fe,_meta:{progressToken:oe}}:fe}:{}},_e=()=>{J!=="initialize"&&w({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:oe,reason:"The user stopped it."}},AbortSignal.timeout(5e3)).then($=>$.body?.cancel()).catch(()=>{})};pe?.addEventListener("abort",_e,{once:!0});try{let $;try{$=await w(Oe,Ae)}catch(q){throw pe?.throwIfAborted(),ye.aborted?new Pe(`${J} timed out after ${Math.round(s/1e3)} s.`):new Pe(`Could not reach the MCP server (${q.message}). Check the address, its CORS settings and your network.`)}if($.status===404&&i&&!Se&&J!=="initialize")return await $.body?.cancel(),i=void 0,await U(pe),v(J,fe,pe,Ce,!0);if(!$.ok)throw await $.body?.cancel(),new Pe(`The MCP server answered ${J} with HTTP ${$.status}${$.status===401||$.status===403?" (check the token)":""}.`,$.status);let H=$.headers.get("mcp-session-id");H&&(i=H);let W=q=>{if(q.id===oe&&(q.result||q.error)){if(q.error)throw new Pe(`${J}: ${q.error.message}`,void 0,q.error.code);return q.result??{}}if(q.method&&q.id!==void 0)k(q);else if(q.method==="notifications/progress"&&q.params?.progressToken===oe&&Ce){let ce=q.params;Ce(ce.message??(ce.total?`${ce.progress??0} / ${ce.total}`:String(ce.progress??"")))}};if(($.headers.get("content-type")??"").includes("text/event-stream")&&$.body){for await(let q of fr($.body,Ae)){let ce;try{ce=JSON.parse(q)}catch{continue}for(let me of Array.isArray(ce)?ce:[ce]){let ae=W(me);if(ae)return $.body.cancel().catch(()=>{}),ae}}throw pe?.throwIfAborted(),ye.aborted?new Pe(`${J} timed out after ${Math.round(s/1e3)} s.`):new Pe(`The MCP server ended the stream without answering ${J}.`)}let j;try{j=await $.json()}catch{throw new Pe(`The MCP server's answer to ${J} is not JSON.`)}for(let q of Array.isArray(j)?j:[j]){let ce=W(q);if(ce)return ce}throw new Pe(`The MCP server did not answer ${J}.`)}finally{pe?.removeEventListener("abort",_e)}},T=async J=>{await(await w({jsonrpc:"2.0",method:J},Ba([AbortSignal.timeout(s),...p?[p]:[]]))).body?.cancel()},C={name:"mcp"},R,U=async J=>{a=void 0;let fe=await v("initialize",{protocolVersion:ja,capabilities:{},clientInfo:{name:e.clientName??"runapps-agent",version:"1"}},J);a=typeof fe.protocolVersion=="string"?fe.protocolVersion:ja;let pe=fe.serverInfo;pe?.name&&(C={name:pe.name,version:pe.version,title:pe.title}),typeof fe.instructions=="string"&&(R=fe.instructions),await T("notifications/initialized")};await U(e.signal);let E=[],S=[],N=qa(e.prefix??C.name).slice(0,24)||"mcp",P=e.name||C.title||C.name,V=async J=>{let fe=[],pe=new Set,Ce;do{let oe=await v("tools/list",Ce?{cursor:Ce}:{},J);if(!Array.isArray(oe.tools))throw new Pe("The MCP server's tool list is malformed.");for(let ye of oe.tools){if(!ye||typeof ye.name!="string"||!ye.name)throw new Pe("The MCP server listed a tool without a name.");let Ae=ye.inputSchema&&typeof ye.inputSchema=="object"?ye.inputSchema:{type:"object"};fe.push({...ye,inputSchema:{type:"object",properties:{},...Ae}})}if(fe.length>(e.maxTools??64))throw new Pe(`The MCP server has more than ${e.maxTools??64} tools (maxTools).`);if(Ce=typeof oe.nextCursor=="string"&&oe.nextCursor?oe.nextCursor:void 0,Ce){if(pe.has(Ce))throw new Pe("The MCP server's tool list repeats a page.");pe.add(Ce)}}while(Ce);E=fe;let Se=new Set;return S=fe.map(oe=>{let ye=`${N}__${qa(oe.name)}`.slice(0,64);for(let $=2;Se.has(ye);$++)ye=`${ye.slice(0,60)}_${$}`;Se.add(ye);let Ae=oe.annotations?.readOnlyHint===!0,Oe=e.confirm==="never"?!1:e.confirm==="unless-read-only"?!Ae:!0,_e=oe.title??oe.annotations?.title??oe.name;return Fe({name:ye,description:`[${P} \u2014 MCP server] ${_e!==oe.name?`${_e}. `:""}${oe.description??""}`.trim().slice(0,4e3),parameters:oe.inputSchema,readOnly:Ae,destructive:oe.annotations?.destructiveHint===!0||!Ae&&Oe,maxResultChars:e.maxResultChars,confirm:Oe?$=>({title:`Run ${P} / ${oe.name}?`,message:JSON.stringify($,null,2).slice(0,4e3)}):()=>!1,async execute($,H){let W;try{W=await v("tools/call",{name:oe.name,arguments:$},H.signal,j=>j&&H.update(j))}catch(j){throw H.signal.throwIfAborted(),j instanceof Pe&&j.code!==void 0?j:new Pe(`${j.message} Whether ${oe.name} took effect on the server is unknown; do not repeat it without checking.`)}let ne=ud(W,e.images===!0);if(W.isError===!0)throw new Pe(ne.map(j=>j.type==="text"?j.text:"").join(`
|
|
273
|
+
`).trim()||`${oe.name} reported an error.`);return ne.length===1&&ne[0].type==="text"?ne[0].text:ne}})}),S};try{await V(e.signal)}catch(J){throw await se(),J}p=void 0;async function se(){if(!d&&(d=!0,!!i))try{await(await t(n,{method:"DELETE",headers:h(!1),redirect:"error",credentials:"omit",signal:AbortSignal.timeout(5e3)})).body?.cancel()}catch{}}return{get tools(){return S},get serverTools(){return E},server:C,instructions:R,refresh:V,close:se}}function ud(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 i=typeof s.mimeType=="string"?s.mimeType:"image/png";e?t.push({type:"image_url",image_url:{url:`data:${i};base64,${s.data}`}}):t.push({type:"text",text:`[A picture (${i}, ${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 i=s.resource;t.push({type:"text",text:typeof i.text=="string"?`${i.uri?`${i.uri}:
|
|
274
|
+
`:""}${i.text}`:`[Resource ${i.uri??""} (${i.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 qa(r){return r.replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")}function Ba(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 pd(r,e={}){return new Ut(r,e)}function fd(r,e={}){let n=r?ot(r):null;return $n.open(n,{...e,project:e.project??n?.name??void 0})}var hd={"&":"&","<":"<",">":">",'"':""","'":"'"};function ve(r){return r.replace(/[&<>"']/g,e=>hd[e])}function md(r){let e=r.trim();return/^(https?:\/\/|mailto:)/i.test(e)||/^(\/|\.\/|\.\.\/|#)/.test(e)&&!/^\/\//.test(e)?e:null}var Uo=/[\p{L}\p{N}]/u,Ka=/`+/y,Va=/\[([^\]]*)\]\(((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?\)/y,Ga=/https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))+/y;function Mt(r){let e="",n=0,t=r.length,s=new Map,i=-2;for(;n<t;){let a=r[n];if(a==="`"){Ka.lastIndex=n;let l=Ka.exec(r)[0],d=r.indexOf(l,n+l.length);if(d>0){e+=`<code>${ve(r.slice(n+l.length,d).trim())}</code>`,n=d+l.length;continue}e+=ve(l),n+=l.length;continue}if(a==="["&&(i!==-1&&i<n&&(i=r.indexOf("](",n)),i!==-1)){Va.lastIndex=n;let l=Va.exec(r);if(l){let d=md(l[2]),p=Mt(l[1]);e+=d?`<a href="${ve(d)}" target="_blank" rel="noopener noreferrer">${p}</a>`:p,n+=l[0].length;continue}}if(a==="h"&&r.startsWith("http",n)&&(n===0||!Uo.test(r[n-1]))){Ga.lastIndex=n;let l=Ga.exec(r);if(l){let d=l[0].replace(/[.,;:!?'"]+$/,"");if(d.length>8){e+=`<a href="${ve(d)}" target="_blank" rel="noopener noreferrer">${ve(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&&Uo.test(r[n-1]))&&(s.get(l)??1/0)>n){let p=gd(r,n+l.length,l);if(p>0){let h=Mt(r.slice(n+l.length,p));e+=l==="~~"?`<del>${h}</del>`:l.length===2?`<strong>${h}</strong>`:`<em>${h}</em>`,n=p+l.length;continue}s.set(l,Math.min(s.get(l)??1/0,n))}e+=ve(l),n+=l.length;continue}if(a==="\\"&&n+1<t&&/[\\`*_{}\[\]()#+\-.!~|>]/.test(r[n+1])){e+=ve(r[n+1]),n+=2;continue}if(a===`
|
|
275
|
+
`){e+="<br>",n++;continue}e+=ve(a),n++}return e}function gd(r,e,n){let t=e;for(;(t=r.indexOf(n,t))>0;){if(t>e&&r[t-1]!==" "&&r[t-1]!==`
|
|
276
|
+
`&&!(n[0]==="_"&&t+n.length<r.length&&Uo.test(r[t+n.length])))return t;t+=n.length}return-1}var yd=/^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)/;function On(r){let e=r.replace(/\r\n?/g,`
|
|
277
277
|
`).split(`
|
|
278
278
|
`),n=[],t=0,s=[],i=()=>{s.length&&(n.push(`<p>${Mt(s.join(`
|
|
279
|
-
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=
|
|
279
|
+
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=yd.exec(a);if(l&&!(l[2][0]==="`"&&a.slice(l[0].length).includes("`"))){i();let h=l[2],w=l[3]??"",k=[];t++;let v=C=>{let R=C.trim();return R.length>=h.length&&R===h[0].repeat(R.length)};for(;t<e.length&&!v(e[t]);)k.push(e[t]),t++;t++;let T=w?` class="language-${ve(w)}"`:"";n.push(`<pre><code${T}>${ve(k.join(`
|
|
280
280
|
`))}
|
|
281
|
-
</code></pre>`);continue}if(!a.trim()){i(),t++;continue}let d=/^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(a);if(d){i(),n.push(`<h${d[1].length}>${Mt(d[2])}</h${d[1].length}>`),t++;continue}if(/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(a)){i(),n.push("<hr>"),t++;continue}if(/^\s{0,3}>/.test(a)){i();let
|
|
282
|
-
`))}</blockquote>`);continue}if(a.includes("|")&&t+1<e.length&&e[t+1].includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e[t+1])){i();let
|
|
283
|
-
`)}function
|
|
284
|
-
`).trim(),i=n?t.replace(/^(<input[^>]*> )/,"$1"):"",a=n?i.slice(0,i.indexOf("> ")+2)+Mt(i.slice(i.indexOf("> ")+2)):Mt(t);if(!s)return a;let l=
|
|
285
|
-
`)?`<br>${l.slice(3,-4)}`:l)}var Pn=class{constructor(e,n,t={}){D(this,"scroller",e);D(this,"inner",n);D(this,"rows",[]);D(this,"_follow",!0);D(this,"onFollow");D(this,"top");D(this,"win");D(this,"bottom");D(this,"wrappers",new Map);D(this,"ro");D(this,"estimate");D(this,"overscan");D(this,"rowClass");D(this,"followWithin");D(this,"offsets",[]);D(this,"first",0);D(this,"last",-1);D(this,"frame",null);D(this,"disposed",!1);D(this,"expectedTop",-1);D(this,"pinned",null);D(this,"lastTop",0);D(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()});D(this,"onWheel",e=>{this.pinned=null,e.deltaY<0&&this.scroller.scrollTop>0&&(this.follow=!1)});D(this,"touchY",0);D(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 i=0;i<4;i++){let a=this.computeOffsets(),l=this.follow?Math.max(0,a-t):e.scrollTop,d=this.indexAt(l),u=this.offsets[d]-l,f=this.indexAt(Math.max(0,l-this.overscan)),w=Math.min(n-1,this.indexAt(Math.min(a-1,l+t+this.overscan)));if(this.top.style.height=`${this.offsets[f]}px`,this.bottom.style.height=`${a-this.offsets[w+1]}px`,f!==this.first||w!==this.last||this.win.childElementCount!==w-f+1){let v=new Set(this.rows.slice(f,w+1)),T=[...this.wrappers].filter(([R])=>!v.has(R)),M=null;for(let R=f;R<=w;R++){let U=this.wrapper(this.rows[R]);U.parentNode!==this.win&&this.win.insertBefore(U,M?M.nextSibling:this.win.firstChild),M=U}for(let[R,U]of T)this.ro?.unobserve(U),U.remove(),this.wrappers.delete(R);this.first=f,this.last=w}let k=!1;for(let v=f;v<=w;v++){let T=this.rows[v],M=this.wrappers.get(T).offsetHeight;M&&M!==T.height&&(T.height=M,k=!0)}if(k){this.computeOffsets(),this.setTop(this.follow?s():Math.max(0,this.offsets[d]-u));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>`,I={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"/>'),globe:(r=14)=>se(r,'<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),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 Cs(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 i=h("div","ra-btns"),a=f=>{t.remove(),n(f)},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)),i.append(l,d),s.append(i),t.append(s),t.addEventListener("click",f=>{f.target===t&&a(!1)}),t.addEventListener("keydown",f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),a(!1)),e.submitOnEnter&&f.key==="Enter"&&!f.isComposing&&f.keyCode!==229&&(f.preventDefault(),a(!0))}),r.append(t);let u=e.focus==="ok"?d:e.focus instanceof HTMLElement?e.focus:l;queueMicrotask(()=>{u.focus(),u instanceof HTMLInputElement&&u.select()})})}function bt(r,e,n,t){return Cs(r,{title:e,message:n,...t})}async function Ia(r,e,n){let t=h("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await Cs(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}function kr(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=URL.createObjectURL(t),i=h("a");i.href=s,i.download=r,document.body.append(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function _n(r,e,n){r.innerHTML=Ln(e),r.classList.toggle("ra-cursor",n);for(let t of Array.from(r.querySelectorAll("pre"))){let s=t.querySelector("code"),i=s?.className.match(/language-([\w+#-]+)/)?.[1]??"",a=h("div","ra-cb"),l=h("div","ra-cbh");l.append(h("span","",i));let d=h("button","ra-copy");d.type="button",d.innerHTML=I.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=I.check(14),setTimeout(()=>{d.innerHTML=I.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 Tr(r,e={}){let n=e.options??[],t=e.value??n[0]?.value??"",s=!1,i=h("button","ra-sel");i.type="button",i.setAttribute("aria-haspopup","listbox");let a=h("span","ra-sell"),l=h("span","ra-selc");l.innerHTML=I.chevDown(14),i.append(a,l);let d=null,u=0,f="",w=()=>{let S=n.find(j=>j.value===t);a.textContent=S?.label??e.placeholder??"",a.classList.toggle("ph",!S),i.disabled=s},k=()=>f?n.filter(S=>`${S.label} ${S.note??""}`.toLowerCase().includes(f.toLowerCase())):n,v=(S=!0)=>{d&&(d.remove(),d=null,f="",i.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",T,!0),S&&i.focus())},T=S=>{d&&(!i.isConnected||!d.contains(S.target)&&!i.contains(S.target))&&v(!1)},M=S=>{let j=S!==t;t=S,w(),v(),j&&i.dispatchEvent(new Event("change",{bubbles:!0}))},R=S=>{S.replaceChildren();let j=k();u>=j.length&&(u=Math.max(0,j.length-1)),j.forEach((P,V)=>{let ne=h("div","ra-selo"+(V===u?" act":"")+(P.value===t?" cur":""));ne.setAttribute("role","option"),ne.setAttribute("aria-selected",String(P.value===t));let J=h("span","ra-selt");J.innerHTML=P.value===t?I.tick(13):"",ne.append(J,h("span","ra-selol",P.label)),P.note&&ne.append(h("span","ra-selon",P.note)),ne.addEventListener("pointermove",()=>{u!==V&&(u=V,S.querySelectorAll(".ra-selo").forEach((pe,ue)=>pe.classList.toggle("act",ue===V)))}),ne.addEventListener("click",()=>M(P.value)),S.append(ne)}),j.length||S.append(h("div","ra-selnone","\u2014")),S.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},U=()=>{if(d||s)return;d=h("div","ra-selp"),d.setAttribute("role","listbox");let S=h("div","ra-sellist"),j=null;n.length>=(e.filterAt??10)&&(j=h("input","ra-self"),j.type="text",j.placeholder=e.filterLabel??"Filter\u2026",j.addEventListener("input",()=>{f=j.value,u=0,R(S)}),j.addEventListener("keydown",E),d.append(j)),d.append(S),u=Math.max(0,n.findIndex(ke=>ke.value===t)),R(S),r.append(d);let P=r.getBoundingClientRect(),V=i.getBoundingClientRect(),ne=P.bottom-V.bottom-8,J=V.top-P.top-8,pe=Math.min(d.scrollHeight,320),ue=ne<pe&&J>ne;d.style.left=`${V.left-P.left+r.scrollLeft}px`,d.style.width=`${V.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,ue?J:ne))}px`,d.style.top=ue?`${V.top-P.top+r.scrollTop-d.offsetHeight-4}px`:`${V.bottom-P.top+r.scrollTop+4}px`,i.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",T,!0),(j??i).focus()},E=S=>{if(!d){(S.key==="ArrowDown"||S.key==="ArrowUp"||S.key==="Enter"||S.key===" ")&&(S.preventDefault(),U());return}let j=k(),P=d.querySelector(".ra-sellist");if(S.key==="ArrowDown")S.preventDefault(),u=Math.min(j.length-1,u+1),R(P);else if(S.key==="ArrowUp")S.preventDefault(),u=Math.max(0,u-1),R(P);else if(S.key==="Enter"){S.preventDefault();let V=j[u];V&&M(V.value)}else S.key==="Escape"?(S.preventDefault(),S.stopPropagation(),v()):S.key==="Tab"&&v(!1)};return i.addEventListener("click",()=>d?v():U()),i.addEventListener("keydown",E),w(),{el:i,get value(){return t},set value(S){t=S,w()},get disabled(){return s},set disabled(S){s=S,S&&v(!1),w()},get options(){return n},setOptions(S){n=S,n.some(j=>j.value===t)||(t=n[0]?.value??""),w()},close(){v(!1)}}}var Ua=`
|
|
281
|
+
</code></pre>`);continue}if(!a.trim()){i(),t++;continue}let d=/^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(a);if(d){i(),n.push(`<h${d[1].length}>${Mt(d[2])}</h${d[1].length}>`),t++;continue}if(/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(a)){i(),n.push("<hr>"),t++;continue}if(/^\s{0,3}>/.test(a)){i();let h=[];for(;t<e.length&&/^\s{0,3}>/.test(e[t]);)h.push(e[t].replace(/^\s{0,3}>\s?/,"")),t++;n.push(`<blockquote>${On(h.join(`
|
|
282
|
+
`))}</blockquote>`);continue}if(a.includes("|")&&t+1<e.length&&e[t+1].includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e[t+1])){i();let h=T=>T.trim().replace(/^\|/,"").replace(/(?<!\\)\|$/,"").split(/(?<!\\)\|/).map(C=>C.trim().replace(/\\\|/g,"|")),w=h(e[t+1]).map(T=>T.startsWith(":")&&T.endsWith(":")?"center":T.endsWith(":")?"right":T.startsWith(":")?"left":""),k=(T,C)=>`<tr>${h(T).map((R,U)=>`<${C}${w[U]?` style="text-align:${w[U]}"`:""}>${Mt(R)}</${C}>`).join("")}</tr>`,v=`<table><thead>${k(a,"th")}</thead><tbody>`;for(t+=2;t<e.length&&e[t].includes("|")&&e[t].trim();)v+=k(e[t],"td"),t++;n.push(v+"</tbody></table>");continue}let p=/^(\s*)([-*+]|\d+[.)])\s+/.exec(a);if(p){i();let{html:h,next:w}=wd(e,t,p[1].length);n.push(h),t=w;continue}s.push(a),t++}return i(),n.join(`
|
|
283
|
+
`)}function wd(r,e,n){let t=/^(\s*)([-*+]|\d+[.)])\s+/.exec(r[e]),s=/\d/.test(t[2]),i=s?parseInt(t[2],10):1,a=[],l=e;for(;l<r.length;){let h=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(r[l]);if(!h||h[1].length!==n||/\d/.test(h[2])!==s)break;let w=[h[3]];for(l++;l<r.length;){let v=r[l];if(!v.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(v.match(/^\s*/)[0].length>n){w.push(v),l++;continue}break}let k=/^\[([ xX])\]\s+/.exec(w[0]);k&&(w[0]=`<input type="checkbox" disabled${k[1]===" "?"":" checked"}> `+w[0].slice(k[0].length)),a.push(`<li>${bd(w,n,!!k)}</li>`)}let d=s?"ol":"ul",p=s&&i!==1?` start="${i}"`:"";return{html:`<${d}${p}>${a.join("")}</${d}>`,next:l}}function bd(r,e,n){let t=r[0],s=r.slice(1).map(d=>d.replace(new RegExp(`^\\s{0,${e+2}}`),"")).join(`
|
|
284
|
+
`).trim(),i=n?t.replace(/^(<input[^>]*> )/,"$1"):"",a=n?i.slice(0,i.indexOf("> ")+2)+Mt(i.slice(i.indexOf("> ")+2)):Mt(t);if(!s)return a;let l=On(s);return a+(l.startsWith("<p>")&&!l.includes(`</p>
|
|
285
|
+
`)?`<br>${l.slice(3,-4)}`:l)}var Dn=class{constructor(e,n,t={}){D(this,"scroller",e);D(this,"inner",n);D(this,"rows",[]);D(this,"_follow",!0);D(this,"onFollow");D(this,"top");D(this,"win");D(this,"bottom");D(this,"wrappers",new Map);D(this,"ro");D(this,"estimate");D(this,"overscan");D(this,"rowClass");D(this,"followWithin");D(this,"offsets",[]);D(this,"first",0);D(this,"last",-1);D(this,"frame",null);D(this,"disposed",!1);D(this,"expectedTop",-1);D(this,"pinned",null);D(this,"lastTop",0);D(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()});D(this,"onWheel",e=>{this.pinned=null,e.deltaY<0&&this.scroller.scrollTop>0&&(this.follow=!1)});D(this,"touchY",0);D(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 i=0;i<4;i++){let a=this.computeOffsets(),l=this.follow?Math.max(0,a-t):e.scrollTop,d=this.indexAt(l),p=this.offsets[d]-l,h=this.indexAt(Math.max(0,l-this.overscan)),w=Math.min(n-1,this.indexAt(Math.min(a-1,l+t+this.overscan)));if(this.top.style.height=`${this.offsets[h]}px`,this.bottom.style.height=`${a-this.offsets[w+1]}px`,h!==this.first||w!==this.last||this.win.childElementCount!==w-h+1){let v=new Set(this.rows.slice(h,w+1)),T=[...this.wrappers].filter(([R])=>!v.has(R)),C=null;for(let R=h;R<=w;R++){let U=this.wrapper(this.rows[R]);U.parentNode!==this.win&&this.win.insertBefore(U,C?C.nextSibling:this.win.firstChild),C=U}for(let[R,U]of T)this.ro?.unobserve(U),U.remove(),this.wrappers.delete(R);this.first=h,this.last=w}let k=!1;for(let v=h;v<=w;v++){let T=this.rows[v],C=this.wrappers.get(T).offsetHeight;C&&C!==T.height&&(T.height=C,k=!0)}if(k){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 f(r,e,n){let t=document.createElement(r);return e&&(t.className=e),n!==void 0&&(t.textContent=n),t}var ie=(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>`,I={tick:(r=14)=>ie(r,'<path d="M20 6 9 17l-5-5"/>'),enter:(r=14)=>ie(r,'<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),lock:(r=12)=>ie(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)=>ie(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)=>ie(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)=>ie(r,'<path d="M14.5 9.5 22 2M22 2l-7 20-4-9-9-4z"/>'),hist:(r=14)=>ie(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)=>ie(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)=>ie(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)=>ie(r,'<path d="M12 5v14M5 12h14"/>'),chev:(r=14)=>ie(r,'<path d="m9 18 6-6-6-6"/>'),brain:(r=13)=>ie(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)=>ie(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)=>ie(r,'<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>'),xcircle:(r=15)=>ie(r,'<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6M9 9l6 6"/>'),ban:(r=15)=>ie(r,'<circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/>'),square:(r=12)=>ie(r,'<rect x="3" y="3" width="18" height="18" rx="2"/>'),corner:(r=14)=>ie(r,'<path d="M20 4v7a4 4 0 0 1-4 4H4"/><path d="m9 10-5 5 5 5"/>'),x:(r=12)=>ie(r,'<path d="M18 6 6 18M6 6l12 12"/>'),trash:(r=13)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(r,'<path d="m6 9 6 6 6-6"/>'),checks:(r=13)=>ie(r,'<path d="M18 6 7 17l-5-5"/><path d="m22 10-7.5 7.5L13 16"/>'),undo:(r=13)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(r,'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),bug:(r=14)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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)=>ie(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"/>'),globe:(r=14)=>ie(r,'<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),search:(r=13)=>ie(r,'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),braces:(r=13)=>ie(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)=>ie(r,'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),wrench:(r=13)=>ie(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 Ls(r,e){return new Promise(n=>{let t=f("div","ra-modal"),s=f("div","ra-dlg");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",e.title),s.append(f("div","ra-dt",e.title)),e.message&&s.append(f("div","ra-dm",e.message)),e.body&&s.append(...e.body);let i=f("div","ra-btns"),a=h=>{t.remove(),n(h)},l=f("button","ra-btn",e.cancel);l.type="button",l.addEventListener("click",()=>a(!1));let d=f("button","ra-btn "+(e.danger?"red":"solid"),e.ok);d.type="button",d.addEventListener("click",()=>a(!0)),i.append(l,d),s.append(i),t.append(s),t.addEventListener("click",h=>{h.target===t&&a(!1)}),t.addEventListener("keydown",h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),a(!1)),e.submitOnEnter&&h.key==="Enter"&&!h.isComposing&&h.keyCode!==229&&(h.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 bt(r,e,n,t){return Ls(r,{title:e,message:n,...t})}async function Za(r,e,n){let t=f("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await Ls(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}function Er(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=URL.createObjectURL(t),i=f("a");i.href=s,i.download=r,document.body.append(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function zn(r,e,n){r.innerHTML=On(e),r.classList.toggle("ra-cursor",n);for(let t of Array.from(r.querySelectorAll("pre"))){let s=t.querySelector("code"),i=s?.className.match(/language-([\w+#-]+)/)?.[1]??"",a=f("div","ra-cb"),l=f("div","ra-cbh");l.append(f("span","",i));let d=f("button","ra-copy");d.type="button",d.innerHTML=I.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=I.check(14),setTimeout(()=>{d.innerHTML=I.copy()},1200)})}),l.append(d),t.replaceWith(a),a.append(l,t)}for(let t of Array.from(r.querySelectorAll("table"))){let s=f("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,i=f("button","ra-sel");i.type="button",i.setAttribute("aria-haspopup","listbox");let a=f("span","ra-sell"),l=f("span","ra-selc");l.innerHTML=I.chevDown(14),i.append(a,l);let d=null,p=0,h="",w=()=>{let S=n.find(N=>N.value===t);a.textContent=S?.label??e.placeholder??"",a.classList.toggle("ph",!S),i.disabled=s},k=()=>h?n.filter(S=>`${S.label} ${S.note??""}`.toLowerCase().includes(h.toLowerCase())):n,v=(S=!0)=>{d&&(d.remove(),d=null,h="",i.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",T,!0),S&&i.focus())},T=S=>{d&&(!i.isConnected||!d.contains(S.target)&&!i.contains(S.target))&&v(!1)},C=S=>{let N=S!==t;t=S,w(),v(),N&&i.dispatchEvent(new Event("change",{bubbles:!0}))},R=S=>{S.replaceChildren();let N=k();p>=N.length&&(p=Math.max(0,N.length-1)),N.forEach((P,V)=>{let se=f("div","ra-selo"+(V===p?" act":"")+(P.value===t?" cur":""));se.setAttribute("role","option"),se.setAttribute("aria-selected",String(P.value===t));let J=f("span","ra-selt");J.innerHTML=P.value===t?I.tick(13):"",se.append(J,f("span","ra-selol",P.label)),P.note&&se.append(f("span","ra-selon",P.note)),se.addEventListener("pointermove",()=>{p!==V&&(p=V,S.querySelectorAll(".ra-selo").forEach((fe,pe)=>fe.classList.toggle("act",pe===V)))}),se.addEventListener("click",()=>C(P.value)),S.append(se)}),N.length||S.append(f("div","ra-selnone","\u2014")),S.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},U=()=>{if(d||s)return;d=f("div","ra-selp"),d.setAttribute("role","listbox");let S=f("div","ra-sellist"),N=null;n.length>=(e.filterAt??10)&&(N=f("input","ra-self"),N.type="text",N.placeholder=e.filterLabel??"Filter\u2026",N.addEventListener("input",()=>{h=N.value,p=0,R(S)}),N.addEventListener("keydown",E),d.append(N)),d.append(S),p=Math.max(0,n.findIndex(Ce=>Ce.value===t)),R(S),r.append(d);let P=r.getBoundingClientRect(),V=i.getBoundingClientRect(),se=P.bottom-V.bottom-8,J=V.top-P.top-8,fe=Math.min(d.scrollHeight,320),pe=se<fe&&J>se;d.style.left=`${V.left-P.left+r.scrollLeft}px`,d.style.width=`${V.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,pe?J:se))}px`,d.style.top=pe?`${V.top-P.top+r.scrollTop-d.offsetHeight-4}px`:`${V.bottom-P.top+r.scrollTop+4}px`,i.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",T,!0),(N??i).focus()},E=S=>{if(!d){(S.key==="ArrowDown"||S.key==="ArrowUp"||S.key==="Enter"||S.key===" ")&&(S.preventDefault(),U());return}let N=k(),P=d.querySelector(".ra-sellist");if(S.key==="ArrowDown")S.preventDefault(),p=Math.min(N.length-1,p+1),R(P);else if(S.key==="ArrowUp")S.preventDefault(),p=Math.max(0,p-1),R(P);else if(S.key==="Enter"){S.preventDefault();let V=N[p];V&&C(V.value)}else S.key==="Escape"?(S.preventDefault(),S.stopPropagation(),v()):S.key==="Tab"&&v(!1)};return i.addEventListener("click",()=>d?v():U()),i.addEventListener("keydown",E),w(),{el:i,get value(){return t},set value(S){t=S,w()},get disabled(){return s},set disabled(S){s=S,S&&v(!1),w()},get options(){return n},setOptions(S){n=S,n.some(N=>N.value===t)||(t=n[0]?.value??""),w()},close(){v(!1)}}}var Ja=`
|
|
286
286
|
: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}
|
|
287
287
|
:is(.ra-chat,.ra-ui) .ra-sel:hover:not(:disabled){border-color:color-mix(in srgb,var(--ra-fg) 25%,var(--ra-border))}
|
|
288
288
|
: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)}
|
|
@@ -302,8 +302,8 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
302
302
|
:is(.ra-chat,.ra-ui) .ra-selo.cur .ra-selol{font-weight:500}
|
|
303
303
|
: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}
|
|
304
304
|
:is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
|
|
305
|
-
`;var ad=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,Yt=r=>r.slice(r.lastIndexOf("/")+1),_o=r=>r.slice(0,r.lastIndexOf("/"))||"/";function ld(r){let e={name:"",path:"/",folder:!0,children:[]},n=new Map([["/",e]]),t=i=>{let a=n.get(i);if(a)return a;let l=t(_o(i));return a={name:Yt(i),path:i,folder:!0,children:[]},l.children.push(a),n.set(i,a),a};for(let i of r)t(_o(i.path)).children.push({name:Yt(i.path),path:i.path,folder:!1,stat:i,children:[]});let s=i=>{i.children.sort((a,l)=>Number(l.folder)-Number(a.folder)||a.name.localeCompare(l.name)),i.children.forEach(s)};return s(e),e}async function Ro(r,e,n){let t=e==="/"?"":e,s=n.lastIndexOf("."),i=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:`${i}-${l}${a}`}`;if(!await r.exists(d))return d}return`${t}/${Date.now()}-${n}`}function Fa(r){let{t:e,root:n,notify:t,editorHost:s}=r,i=null,a=!1,l=null,d=null,u=null,f=null,w="/",k=new Set(["/.agent"]),v=null,T=0,M=null,R=2*1024*1024,U=null,E=()=>{U||(U=setTimeout(()=>{U=null,ze()},150))},S=new Set,j=!1,P=h("div","ra-fp");P.setAttribute("role","complementary"),P.style.display="none";let V=h("div","ra-fph"),ne=h("span","ra-fpt",e.files),J=(L,K,le)=>{let Z=h("button","ra-ib");return Z.type="button",Z.innerHTML=L,Z.title=K,Z.setAttribute("aria-label",K),Z.addEventListener("click",le),Z},pe=h("input");pe.type="file",pe.multiple=!0,pe.style.display="none";let ue=J(I.upload(),e.upload,()=>pe.click()),ke=J(I.download(),e.downloadZip,()=>{Xe("/")}),ve=J(I.filePlus(14),e.newFile,()=>{Mr()}),re=J(I.refresh(),e.refresh,()=>{ze()}),me=J(I.x(14),e.close,()=>{on()});V.append(ne,h("span","ra-sp"),ke,ue,ve,re,me);let Me=h("div","ra-tree"),_e=h("div","ra-ed");_e.style.display="none";let Le=h("div","ra-edh"),$=h("span","ra-edp"),H=h("span","ra-edro");H.innerHTML=I.lock(11)+`<span>${e.readOnly}</span>`,H.style.display="none";let W=h("div","ra-eda"),te=h("button","ra-btn xs solid");te.type="button",te.innerHTML=I.save()+e.save,te.style.display="none",te.addEventListener("click",()=>{Ke()});let N="__runapps_agent_files:wrap",q=(()=>{try{return localStorage.getItem(N)!=="0"}catch{return!0}})(),ae=!1,fe=J(I.wrap(),e.wrap,()=>{q=!q;try{localStorage.setItem(N,q?"1":"0")}catch{}Ee()}),oe=J(I.eye(),e.preview,()=>{ae=!ae,In()}),Q=h("div","ra-md ra-edmd");Q.style.display="none",Q.addEventListener("click",L=>{let K=L.target.closest("a[href]"),le=K?.getAttribute("href")??"";if(!K||!le.startsWith("/")||le.startsWith("//")||!i)return;L.preventDefault();let Z=i;Z.exists(le).then(z=>{z&&Z===i&&We(le)})});let Ee=()=>{be.classList.toggle("ra-wrap",q),fe.classList.toggle("on",q)},it=L=>!!L&&/\.(md|markdown|mdx)$/i.test(L),In=()=>{let L=u!==null;oe.style.display=L&&it(l)?"":"none",(!L||!it(l))&&(ae=!1),oe.innerHTML=ae?I.pen():I.eye(),oe.title=ae?e.edit:e.preview,oe.setAttribute("aria-label",oe.title),oe.classList.toggle("on",ae),ae&&_n(Q,d??be.value,!1),Q.style.display=ae?"":"none",be.style.display=L&&!ae?"":"none"},en=J(I.download(),e.download,()=>{l&&Je(l)}),tn=J(I.trash(),e.delete,()=>{l&&Hn(l)}),Un=J(I.x(14),e.close,()=>{rn()});W.append(te,fe,oe,en,tn,Un),Le.append($,H,W);let Fn=h("div","ra-edb"),be=h("textarea","ra-edta");be.spellcheck=!1,be.setAttribute("aria-label",e.files);let qe=h("div","ra-edpv");Fn.append(be,Q,qe),Ee(),_e.append(Le,Fn);let Ut=h("div","ra-fpdrop",e.upload);P.append(V,Me,pe,Ut),s.append(_e);let tt=L=>{H.style.display=L?"":"none",tn.style.display=en.style.display=L?"none":""},Fe=L=>{d=L,te.style.display=L===null?"none":""};be.addEventListener("input",()=>Fe(be.value===u?null:be.value)),be.addEventListener("keydown",L=>{if((L.metaKey||L.ctrlKey)&&L.key==="s"&&(L.preventDefault(),Ke()),L.key==="Tab"&&!L.shiftKey){L.preventDefault();let K=be.selectionStart;be.setRangeText(" ",K,be.selectionEnd,"end"),be.dispatchEvent(new Event("input"))}});let nt=async()=>d===null||bt(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),jn=(L,K)=>{if(!i)return!1;if(!K)return i.isReadOnly(L);let le=(M??[]).filter(Z=>Z.path.startsWith(L+"/"));return le.length>0&&le.every(Z=>i.isReadOnly(Z.path))},nn=()=>w!=="/"&&jn(w,!0)?"/":w,Ze=(L,K,le,Z=!1)=>{for(let z of L.children){let we=h("div","ra-fr"+(z.path===l?" ra-cur":""));we.style.paddingLeft=`${K*14+6}px`,we.dataset.path=z.path;let Ye=z.folder&&!k.has(z.path),qn=h("span","ra-frc");qn.innerHTML=z.folder?Ye?I.chevDown():I.chev(12):"";let at=h("span","ra-fri");at.innerHTML=z.folder?Ye?I.folderOpen():I.folder():I.file();let rt=h("span","ra-frn",z.name);if(rt.title=z.path,we.append(qn,at,rt),S.has(z.path)){let Ve=h("span","ra-dot");Ve.title=e.changedByAgent,we.append(Ve)}let an=Z||jn(z.path,z.folder);if(an){if(we.classList.add("ra-ro"),we.title=`${z.path} \xB7 ${e.readOnly}`,!Z){let Ve=h("span","ra-frl");Ve.innerHTML=I.lock(),Ve.title=e.readOnly,we.append(Ve)}}else{let Ve=h("span","ra-fra");Ve.append(z.folder?J(I.download(13),e.downloadZip,()=>{Xe(z.path)}):J(I.download(13),e.download,()=>{Je(z.path)})),Ve.append(J(I.trash(12),e.delete,()=>{Hn(z.path)})),we.append(Ve)}we.addEventListener("click",Ve=>{Ve.target.closest(".ra-fra")||(z.folder?(w=z.path,k.delete(z.path)||k.add(z.path),Et()):(w=_o(z.path),We(z.path)))}),le.append(we),z.folder&&Ye&&Ze(z,K+1,le,an)}},Et=()=>{if(!M)return;let L=document.createDocumentFragment();M.length?Ze(ld(M),0,L):L.append(h("div","ra-fpe",e.noFiles)),Me.replaceChildren(L)},ze=async()=>{if(!i||!a||j)return;let L=++T,K=i;try{let le=await K.list("/");if(L!==T||K!==i||j)return;M=le,Et()}catch(le){if(L!==T||j)return;Me.replaceChildren(h("div","ra-fpe",le.message))}},Be=L=>{_e.style.display=L?"":"none",n.classList.toggle("ra-editing",L)},We=async L=>{if(i&&!(L!==l&&!await nt())){l=L,S.delete(L),Fe(null),$.textContent=L,f&&(URL.revokeObjectURL(f),f=null),qe.replaceChildren(),Be(!0);try{let K=await i.read(L);if(l!==L)return;let le=ad.test(L)||/^image\//.test(K.contentType??""),Z=null;if(!le)if(typeof K.data=="string")Z=K.data;else try{Z=new TextDecoder("utf-8",{fatal:!0}).decode(K.data)}catch{Z=null}if(/\.pdf$/i.test(L)||K.contentType==="application/pdf"){u=null,be.style.display="none",Q.style.display="none",oe.style.display="none",qe.style.display="",f=URL.createObjectURL(new Blob([K.data],{type:"application/pdf"}));let we=h("iframe","ra-edpdf");we.src=f,we.title=Yt(L),fe.style.display="none",qe.replaceChildren(we),tt(i.isReadOnly(L)),Et();return}fe.style.display="",Z!==null&&K.size>R&&(Z=null);let z=i.isReadOnly(L);if(tt(z),Z!==null)u=Z,be.value=Z,qe.style.display="none",be.readOnly=z,be.title=z?e.readOnly:"",In();else{if(u=null,be.style.display="none",Q.style.display="none",oe.style.display="none",qe.style.display="",le){let we=new Blob([K.data],{type:K.contentType||"image/*"});f=URL.createObjectURL(we);let Ye=h("img");Ye.src=f,Ye.alt=Yt(L),qe.append(Ye)}else qe.append(h("div","ra-fpe",K.size>R&&!le?e.tooBig:e.noPreview));qe.append(h("div","ra-fpe",`${K.size} B`))}}catch(K){u=null,be.style.display="none",Q.style.display="none",oe.style.display="none",qe.style.display="",qe.replaceChildren(h("div","ra-fpe",K.message))}Et()}},rn=async()=>l?await nt()?(l=null,u=null,Fe(null),f&&(URL.revokeObjectURL(f),f=null),Be(!1),await ze(),!0):!1:!0,Ke=async()=>{if(!i||!l||d===null)return;let L=l,K=d,le=i;try{let Z=await le.readText(L).catch(()=>null);if(Z!==null&&u!==null&&Z!==u&&!await bt(n,e.conflict,L,{ok:e.save,cancel:e.cancel,danger:!0})||(await le.write(L,K),l!==L||le!==i))return;u=K,Fe(be.value===K?null:be.value),t(`${e.saved}: ${L}`),r.onChange?.()}catch(Z){t(Z.message,"error")}},Je=async L=>{if(i)try{let K=await i.read(L);kr(Yt(L),K.data,K.contentType)}catch(K){t(K.message,"error")}},Xe=async L=>{if(i)try{let K=L==="/"?"/":L+"/",le=(await i.list(L)).filter(we=>we.path.startsWith(K));if(!le.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${le.length}\u2026`);let Z=[];for(let we of le){let Ye=await i.read(we.path);Z.push({path:we.path.slice(K.length),data:Ye.data,mtime:we.mtime})}let z=await ls(Z);kr(`${L==="/"?i.id||"directory":Yt(L)}.zip`,z,"application/zip")}catch(K){t(K.message,"error")}},Hn=async L=>{if(!i||!await bt(n,e.delete,e.confirmDeleteFile.replace("{path}",L),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let K=[];try{let le=await i.isFolder(L)?(await i.list(L)).map(Z=>Z.path).filter(Z=>Z!==L):[L];for(let Z of le){if(i.isReadOnly(Z)){K.push(Z);continue}try{await i.delete(Z)}catch{K.push(Z)}}}catch(le){t(le.message,"error")}l&&(l===L||l.startsWith(L+"/"))&&!await i.exists(l)&&(l=null,u=null,Fe(null),Be(!1)),K.length&&t(`${e.readOnly}: ${K.slice(0,3).join(", ")}${K.length>3?` +${K.length-3}`:""}`,"warning"),r.onChange?.(),await ze()},Mr=async()=>{if(!i)return;let L=nn(),K=L==="/"?"/":L+"/",le=await Ia(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${K}untitled.md`});if(!le)return;let Z="/"+le.replace(/^\/+/,"");try{await i.exists(Z)||await i.write(Z,""),r.onChange?.(),await ze(),await We(Z),be.focus()}catch(z){t(z.message,"error")}},sn=async L=>{if(!i||!L?.length)return;let K=null;for(let le of Array.from(L))try{let Z=await Ro(i,nn(),Yt(le.name.replace(/\\/g,"/"))||"file");await i.write(Z,new Uint8Array(await le.arrayBuffer()),le.type||void 0),K=Z}catch(Z){t(Z.message,"error")}r.onChange?.(),await ze(),K&&L.length===1&&await We(K)};pe.addEventListener("change",()=>{let L=Array.from(pe.files??[]);pe.value="",sn(L)});let Ft=0;P.addEventListener("dragenter",L=>{L.dataTransfer?.types.includes("Files")&&(L.preventDefault(),L.stopPropagation(),Ft++,P.dataset.drop="1")}),P.addEventListener("dragover",L=>{P.dataset.drop&&(L.preventDefault(),L.stopPropagation(),L.dataTransfer.dropEffect="copy")}),P.addEventListener("dragleave",L=>{P.dataset.drop&&(L.stopPropagation(),--Ft<=0&&(Ft=0,delete P.dataset.drop))}),P.addEventListener("drop",L=>{P.dataset.drop&&(L.preventDefault(),L.stopPropagation(),Ft=0,delete P.dataset.drop,sn(L.dataTransfer?.files))});let Nn=async L=>{a=!0,P.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await ze(),L&&await We(L)},on=async()=>{await rn()&&(a=!1,P.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:P,get visible(){return a},open:Nn,close:on,toggle:()=>a?on():Nn(),setWorkspace(L){if(L!==i){if(i&&l&&d!==null){let[K,le,Z]=[i,l,d];K.write(le,Z).then(()=>t(`${e.autoSaved}: ${le}`),z=>t(z.message,"error"))}v?.(),v=null,i=L,L&&(v=L.onChange(K=>{a&&(E(),!(K.path!==l||d!==null)&&(K.kind==="write"?We(K.path):(l=null,u=null,Be(!1))))})),f&&(URL.revokeObjectURL(f),f=null),M=null,l=null,u=null,Fe(null),Be(!1),S.clear(),w="/",L?ze():(a=!1,P.style.display="none",n.classList.remove("ra-files-open"))}},refresh:ze,changed(L){S.add(L),Et()},download:Je,downloadFolder:Xe,dispose(){j=!0,v?.(),U&&clearTimeout(U),f&&URL.revokeObjectURL(f),P.remove(),_e.remove(),n.classList.remove("ra-editing")}}}var Oo={spans:400,requests:120,events:600},cd=new Set(["text_delta","reasoning_delta","tool_update"]);function Sr(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 dd(r){try{return JSON.stringify(r,null,2)??"undefined"}catch{return String(r)}}var Ms=(r,e)=>{r.length>e&&r.splice(0,r.length-e)};function ja(r){let{t:e,root:n}=r,t=new WeakMap,s=new Map,i=null,a=!1,l="calls",d="",u=null,f=h("div","ra-fp ra-dp");f.setAttribute("role","complementary"),f.style.display="none";let w=h("div","ra-fph"),k=h("div","ra-dtabs"),v=h("button","ra-ib");v.type="button",v.innerHTML=I.x(14),v.title=e.close,v.setAttribute("aria-label",e.close),v.addEventListener("click",()=>Le()),w.append(k,h("span","ra-sp"),v);let T=h("div","ra-dbody");f.append(w,T);let M=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],R=()=>{let $=i?t.get(i):void 0,H={calls:$?.spans.length??0,requests:$?.requests.length??0};k.replaceChildren(...M.map(([W,te])=>{let N=h("button","ra-dtab"+(W===l?" on":""));return N.type="button",N.append(te),H[W]&&N.append(h("span","ra-dcount",String(H[W]))),N.addEventListener("click",()=>{l=W,re()}),N}))},U=($,H)=>{let W=h("details","ra-dfold"),te=h("summary"),N=h("span","ra-chev");N.innerHTML=I.chev(12),te.append(N,...$),W.append(te);let q=!1;return W.addEventListener("toggle",()=>{if(W.open&&!q){q=!0;let ae=h("div","ra-dfb");ae.append(...H()),W.append(ae)}}),W},E=($,H="")=>{let W=h("pre","ra-dpre "+H);return W.textContent=typeof $=="string"?$:dd($),W},S=$=>h("div","ra-dlabel",$),j=$=>h("span","ra-dmuted",$),P=$=>h("span","ra-dmono",$),V=$=>h("div","ra-fpe",$),ne=$=>{let H=h("span","ra-dst "+($==="running"?"run":$==="ok"?"ok":"fail"));return $==="running"?H.append(h("span","ra-spin")):H.innerHTML=$==="ok"?I.check(13):I.xcircle(13),H},J=$=>{if(!$.spans.length)return[V(e.dNoCalls)];let H=[];for(let W of[...$.runs].reverse()){let te=$.spans.filter(fe=>fe.runId===W),N=$.requests.filter(fe=>fe.runId===W);if(!te.length&&!N.length)continue;let q=h("div","ra-drun");q.append(h("div","ra-drh",`${e.dRun} ${Sr(N[0]?.at??te[0]?.startedAt??Date.now())} \xB7 ${W.slice(-4)}`));let ae=[...new Set([...N.map(fe=>fe.turn),...te.map(fe=>fe.turn)])].sort((fe,oe)=>fe-oe);for(let fe of ae){let oe=N.find(Ee=>Ee.turn===fe),Q=h("div","ra-dturn");Q.append(j(e.dTurn.replace("{n}",String(fe)))),oe&&Q.append(P(` \xB7 ${oe.params.model||"default"}`),j(oe.durationMs!==void 0?` \xB7 ${Math.round(oe.durationMs)}ms`:" \xB7 \u2026"),oe.error?h("span","ra-dst fail",` ${oe.error}`):j(oe.finishReason?` \xB7 ${oe.finishReason}`:"")),q.append(Q);for(let Ee of te.filter(it=>it.turn===fe))q.append(U([ne(Ee.status),P(Ee.name),j(Ee.durationMs!==void 0?`${Math.round(Ee.durationMs)}ms \xB7 ${Sr(Ee.startedAt)}`:Sr(Ee.startedAt))],()=>[h("div","ra-dmuted",Ee.id),S(e.args),E(Ee.args),...Ee.result!==void 0?[S(e.result),E(Ee.result)]:[]]))}H.push(q)}return H},pe=$=>$.requests.length?[...$.requests].reverse().map(H=>{let W=H.params,te=H.usage,N=h("span","ra-dbadge "+(H.error?"fail":H.durationMs===void 0?"":"ok"),H.error?"error":H.durationMs===void 0?"\u2026":H.finishReason??"ok");return U([N,P(W.model||"default"),j(`${W.messages?.length??0} msgs \xB7 ${W.tools?.length??0} tools${te?` \xB7 ${te.prompt_tokens??0}\u2192${te.completion_tokens??0} tok`:""}${te?.total_cost?` \xB7 $${te.total_cost.toFixed(4)}`:""}`),j(` ${H.durationMs!==void 0?`${Math.round(H.durationMs)}ms \xB7 `:""}${Sr(H.at)}`)],()=>[S(e.dPayload),E(H.params,"tall"),...H.message!==void 0||H.error?[S(e.dResponse),E(H.error??H.message)]:[],...te?[E(te)]:[]])}):[V(e.dNoRequests)],ue=$=>{let H=h("div","ra-dbar"),W=h("input","ra-field");W.type="text",W.placeholder=e.dFilter,W.value=d,W.addEventListener("input",()=>{d=W.value,me()});let te=h("button","ra-ib");te.type="button",te.innerHTML=I.trash(13),te.title=e.dClear,te.setAttribute("aria-label",e.dClear),te.addEventListener("click",()=>{$.events.length=0,$.spans.length=0,$.requests.length=0,$.runs.length=0,re()}),H.append(W,te);let N=$.events.filter(q=>!d||q.name.includes(d)||q.detail.includes(d));return N.length?[H,...[...N].reverse().slice(0,300).map(q=>U([j(Sr(q.at)),P(q.name),j(q.detail)],()=>[E(q.data)]))]:[H,V(e.dNoEvents)]},ke=$=>{let H=h("div","ra-dctx"),W=h("div","ra-dkv"),te=(oe,Q)=>{W.append(h("span","ra-dmuted",oe),h("span","ra-dmono",Q))},N=$.usage,q=$.messages;te("session",$.id),te("directory",$.workspace?.id??"\u2014"),te("model",$.settings.model??"(default)"),te("messages",`${q.filter(oe=>oe.role==="user").length} user \xB7 ${q.filter(oe=>oe.role==="assistant").length} assistant \xB7 ${q.filter(oe=>oe.role==="tool").length} tool`),te("usage",`${N.prompt_tokens} in \xB7 ${N.completion_tokens} out \xB7 ${N.calls} calls \xB7 $${N.total_cost.toFixed(4)}`);let ae=h("span","ra-dmono","\u2026");W.append(h("span","ra-dmuted","context"),ae),$.context().then(oe=>{ae.textContent=`${oe.used} / ${oe.window} (${(oe.used/oe.window*100).toFixed(2)}%)`}).catch(()=>{ae.textContent="\u2014"});let fe=E("\u2026","tall");return $.systemPrompt().then(oe=>{fe.textContent=oe}).catch(oe=>{fe.textContent=String(oe)}),H.append(W,S(e.dSystem),fe,S(`${e.dMessages} (${q.length})`),E(q,"tall")),[H]},ve=$=>$.tools.map(H=>U([P(H.name),j(H.destructive?" destructive":"")],()=>[h("div","ra-ddesc",H.description??""),E(H.parameters)]));function re(){if(u=null,!a)return;if(R(),!i){T.replaceChildren();return}let $=t.get(i),H=T.scrollTop,W=document.activeElement?.classList.contains("ra-field")&&T.contains(document.activeElement),te=l==="calls"?J($):l==="requests"?pe($):l==="events"?ue($):l==="context"?ke(i):ve(i);if(T.replaceChildren(...te),T.scrollTop=H,W){let N=T.querySelector(".ra-field");N?.focus(),N?.setSelectionRange(N.value.length,N.value.length)}}let me=()=>{if(!(!a||u)){if(l==="context"||l==="tools"||T.querySelector("details[open]")){R();return}u=setTimeout(re,300)}},Me=$=>{if(t.has($))return;let H={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set($,H),s.set($,$.on("*",(W,te)=>{let N=te??{},q=String(N.runId??"");if(W==="run_start"&&(H.runs.push(q),Ms(H.runs,60)),W==="turn_start"&&H.turn.set(q,Number(N.turn)||1),W==="request"&&(H.requests.push({runId:q,turn:Number(N.turn),at:Date.now(),params:N.params}),Ms(H.requests,Oo.requests)),W==="response"){let ae=[...H.requests].reverse().find(fe=>fe.runId===q&&fe.turn===Number(N.turn)&&fe.durationMs===void 0);ae&&Object.assign(ae,{durationMs:N.durationMs,finishReason:N.finishReason,usage:N.usage,message:N.message,error:N.error})}if(W==="tool_start"&&(H.spans.push({id:String(N.id),name:String(N.name),args:N.args,status:"running",startedAt:Date.now(),runId:q,turn:H.turn.get(q)??1}),Ms(H.spans,Oo.spans)),W==="tool_end"){let ae=[...H.spans].reverse().find(fe=>fe.id===String(N.id));ae&&Object.assign(ae,{status:String(N.status),result:N.result,durationMs:N.durationMs})}if(!cd.has(W)){let ae=W==="tool_start"||W==="tool_end"?String(N.name??""):W==="run_end"?String(N.reason??""):W==="response"?String(N.error??N.finishReason??""):"";H.events.push({at:Date.now(),name:W,detail:ae,data:W==="request"?{runId:q,turn:N.turn,model:N.params?.model}:te}),Ms(H.events,Oo.events)}$===i&&me()}))},_e=()=>{a=!0,f.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),re()};function Le(){a&&(a=!1,f.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:f,get visible(){return a},open:_e,close:Le,toggle:()=>a?Le():_e(),setAgent($){Me($),i=$,a&&re()},forget($){s.get($)?.(),s.delete($),t.delete($),i===$&&(i=null)},dispose(){for(let $ of s.values())$();s.clear(),u&&clearTimeout(u),f.remove()}}}var Ha=["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"],Na=["font","mono"],ud='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',pd='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',Es={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)"}}},Rn=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function qa(){let r=Es.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${ud};--ra-mono:${pd};${Rn(r.light)}}`,`:where(.ra-chat[data-scheme=dark], .ra-ui[data-scheme=dark]){${Rn(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${Rn(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(Es))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${Rn(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${Rn(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${Rn(t.dark)}}}`));return e.join(`
|
|
306
|
-
`)}var Ba=r=>r.startsWith("--")?r:`--ra-${r}`;var fd={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",ovAttachments:"The attachments on this message are too large for the model.",ovMessage:"This message is too long for the model.",ovHistory:"This conversation has grown too long for the model.",ovTools:"The connected tools take up too much of the model's context.",ovModel:"This request does not fit the current model.",ovDropFiles:"Resend without attachments",ovEdit:"Edit the message",ovCompact:"Compact and continue",ovNew:"Continue in a new chat",ovToolSettings:"Tool settings",ovUseModel:"Retry with {name}",ovNoText:"The message had only attachments: type what you want to ask.",ovNoSummary:"Could not summarise the conversation; the new chat starts without it.",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}",actWeb:"searched the web {n} time(s)",actBrowse:"read {n} web page(s)",ingWeb:"Searching the web",ingBrowse:"Reading",web:"Web",webOn:"Web search: on",webOff:"Web search: off",webHint:"When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",runCode:"Run code",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",ovAttachments:"\u8FD9\u6761\u6D88\u606F\u7684\u9644\u4EF6\u592A\u5927\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",ovMessage:"\u8FD9\u6761\u6D88\u606F\u592A\u957F\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",ovHistory:"\u8FD9\u6BB5\u5BF9\u8BDD\u592A\u957F\uFF0C\u6A21\u578B\u653E\u4E0D\u4E0B\u4E86\u3002",ovTools:"\u5DF2\u8FDE\u63A5\u7684\u5DE5\u5177\u592A\u591A\uFF0C\u5360\u6EE1\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u3002",ovModel:"\u5F53\u524D\u6A21\u578B\u653E\u4E0D\u4E0B\u8FD9\u6B21\u8BF7\u6C42\u3002",ovDropFiles:"\u53BB\u6389\u9644\u4EF6\u540E\u91CD\u53D1",ovEdit:"\u4FEE\u6539\u8FD9\u6761\u6D88\u606F",ovCompact:"\u538B\u7F29\u540E\u7EE7\u7EED",ovNew:"\u5F00\u65B0\u5BF9\u8BDD\u7EE7\u7EED",ovToolSettings:"\u6253\u5F00\u5DE5\u5177\u8BBE\u7F6E",ovUseModel:"\u6362\u7528 {name} \u91CD\u8BD5",ovNoText:"\u8FD9\u6761\u6D88\u606F\u53EA\u6709\u9644\u4EF6\uFF0C\u8BF7\u8F93\u5165\u60F3\u95EE\u7684\u5185\u5BB9\u3002",ovNoSummary:"\u8FD9\u6BB5\u5BF9\u8BDD\u6CA1\u80FD\u751F\u6210\u6458\u8981\uFF0C\u65B0\u5BF9\u8BDD\u4E0D\u4F1A\u5E26\u4E0A\u4E4B\u524D\u7684\u5185\u5BB9\u3002",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}",actWeb:"\u8054\u7F51\u641C\u7D22\u4E86 {n} \u6B21",actBrowse:"\u9605\u8BFB\u4E86 {n} \u4E2A\u7F51\u9875",ingWeb:"\u6B63\u5728\u8054\u7F51\u641C\u7D22",ingBrowse:"\u6B63\u5728\u9605\u8BFB",web:"\u8054\u7F51",webOn:"\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5F00\u542F",webOff:"\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5173\u95ED",webHint:"\u5F00\u542F\u540E AI \u53EF\u4EE5\u641C\u7D22\u548C\u9605\u8BFB\u7F51\u9875\uFF0C\u67E5\u8D44\u6599\u548C\u6700\u65B0\u4FE1\u606F\uFF1B\u6BCF\u6B21\u641C\u7D22\u3001\u6BCF\u8BFB\u4E00\u4E2A\u7F51\u9875\u6309\u6B21\u8BA1\u8D39",runCode:"\u8FD0\u884C\u4EE3\u7801",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 hd(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 Wa="runapps-agent-chat-style",gd=qa()+`
|
|
305
|
+
`;var xd=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,tn=r=>r.slice(r.lastIndexOf("/")+1),Fo=r=>r.slice(0,r.lastIndexOf("/"))||"/";function vd(r){let e={name:"",path:"/",folder:!0,children:[]},n=new Map([["/",e]]),t=i=>{let a=n.get(i);if(a)return a;let l=t(Fo(i));return a={name:tn(i),path:i,folder:!0,children:[]},l.children.push(a),n.set(i,a),a};for(let i of r)t(Fo(i.path)).children.push({name:tn(i.path),path:i.path,folder:!1,stat:i,children:[]});let s=i=>{i.children.sort((a,l)=>Number(l.folder)-Number(a.folder)||a.name.localeCompare(l.name)),i.children.forEach(s)};return s(e),e}async function No(r,e,n){let t=e==="/"?"":e,s=n.lastIndexOf("."),i=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:`${i}-${l}${a}`}`;if(!await r.exists(d))return d}return`${t}/${Date.now()}-${n}`}function Xa(r){let{t:e,root:n,notify:t,editorHost:s}=r,i=null,a=!1,l=null,d=null,p=null,h=null,w="/",k=new Set(["/.agent"]),v=null,T=0,C=null,R=2*1024*1024,U=null,E=()=>{U||(U=setTimeout(()=>{U=null,Ie()},150))},S=new Set,N=!1,P=f("div","ra-fp");P.setAttribute("role","complementary"),P.style.display="none";let V=f("div","ra-fph"),se=f("span","ra-fpt",e.files),J=(L,K,de)=>{let Z=f("button","ra-ib");return Z.type="button",Z.innerHTML=L,Z.title=K,Z.setAttribute("aria-label",K),Z.addEventListener("click",de),Z},fe=f("input");fe.type="file",fe.multiple=!0,fe.style.display="none";let pe=J(I.upload(),e.upload,()=>fe.click()),Ce=J(I.download(),e.downloadZip,()=>{Ye("/")}),Se=J(I.filePlus(14),e.newFile,()=>{Pr()}),oe=J(I.refresh(),e.refresh,()=>{Ie()}),ye=J(I.x(14),e.close,()=>{cn()});V.append(se,f("span","ra-sp"),Ce,pe,Se,oe,ye);let Ae=f("div","ra-tree"),Oe=f("div","ra-ed");Oe.style.display="none";let _e=f("div","ra-edh"),$=f("span","ra-edp"),H=f("span","ra-edro");H.innerHTML=I.lock(11)+`<span>${e.readOnly}</span>`,H.style.display="none";let W=f("div","ra-eda"),ne=f("button","ra-btn xs solid");ne.type="button",ne.innerHTML=I.save()+e.save,ne.style.display="none",ne.addEventListener("click",()=>{Ve()});let j="__runapps_agent_files:wrap",q=(()=>{try{return localStorage.getItem(j)!=="0"}catch{return!0}})(),ce=!1,me=J(I.wrap(),e.wrap,()=>{q=!q;try{localStorage.setItem(j,q?"1":"0")}catch{}$e()}),ae=J(I.eye(),e.preview,()=>{ce=!ce,Hn()}),ee=f("div","ra-md ra-edmd");ee.style.display="none",ee.addEventListener("click",L=>{let K=L.target.closest("a[href]"),de=K?.getAttribute("href")??"";if(!K||!de.startsWith("/")||de.startsWith("//")||!i)return;L.preventDefault();let Z=i;Z.exists(de).then(z=>{z&&Z===i&&Ke(de)})});let $e=()=>{xe.classList.toggle("ra-wrap",q),me.classList.toggle("on",q)},it=L=>!!L&&/\.(md|markdown|mdx)$/i.test(L),Hn=()=>{let L=p!==null;ae.style.display=L&&it(l)?"":"none",(!L||!it(l))&&(ce=!1),ae.innerHTML=ce?I.pen():I.eye(),ae.title=ce?e.edit:e.preview,ae.setAttribute("aria-label",ae.title),ae.classList.toggle("on",ce),ce&&zn(ee,d??xe.value,!1),ee.style.display=ce?"":"none",xe.style.display=L&&!ce?"":"none"},rn=J(I.download(),e.download,()=>{l&&Xe(l)}),sn=J(I.trash(),e.delete,()=>{l&&Wn(l)}),jn=J(I.x(14),e.close,()=>{an()});W.append(ne,me,ae,rn,sn,jn),_e.append($,H,W);let qn=f("div","ra-edb"),xe=f("textarea","ra-edta");xe.spellcheck=!1,xe.setAttribute("aria-label",e.files);let Be=f("div","ra-edpv");qn.append(xe,ee,Be),$e(),Oe.append(_e,qn);let Nt=f("div","ra-fpdrop",e.upload);P.append(V,Ae,fe,Nt),s.append(Oe);let tt=L=>{H.style.display=L?"":"none",sn.style.display=rn.style.display=L?"none":""},Ne=L=>{d=L,ne.style.display=L===null?"none":""};xe.addEventListener("input",()=>Ne(xe.value===p?null:xe.value)),xe.addEventListener("keydown",L=>{if((L.metaKey||L.ctrlKey)&&L.key==="s"&&(L.preventDefault(),Ve()),L.key==="Tab"&&!L.shiftKey){L.preventDefault();let K=xe.selectionStart;xe.setRangeText(" ",K,xe.selectionEnd,"end"),xe.dispatchEvent(new Event("input"))}});let nt=async()=>d===null||bt(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),Bn=(L,K)=>{if(!i)return!1;if(!K)return i.isReadOnly(L);let de=(C??[]).filter(Z=>Z.path.startsWith(L+"/"));return de.length>0&&de.every(Z=>i.isReadOnly(Z.path))},on=()=>w!=="/"&&Bn(w,!0)?"/":w,Je=(L,K,de,Z=!1)=>{for(let z of L.children){let be=f("div","ra-fr"+(z.path===l?" ra-cur":""));be.style.paddingLeft=`${K*14+6}px`,be.dataset.path=z.path;let Qe=z.folder&&!k.has(z.path),Vn=f("span","ra-frc");Vn.innerHTML=z.folder?Qe?I.chevDown():I.chev(12):"";let at=f("span","ra-fri");at.innerHTML=z.folder?Qe?I.folderOpen():I.folder():I.file();let rt=f("span","ra-frn",z.name);if(rt.title=z.path,be.append(Vn,at,rt),S.has(z.path)){let Ge=f("span","ra-dot");Ge.title=e.changedByAgent,be.append(Ge)}let dn=Z||Bn(z.path,z.folder);if(dn){if(be.classList.add("ra-ro"),be.title=`${z.path} \xB7 ${e.readOnly}`,!Z){let Ge=f("span","ra-frl");Ge.innerHTML=I.lock(),Ge.title=e.readOnly,be.append(Ge)}}else{let Ge=f("span","ra-fra");Ge.append(z.folder?J(I.download(13),e.downloadZip,()=>{Ye(z.path)}):J(I.download(13),e.download,()=>{Xe(z.path)})),Ge.append(J(I.trash(12),e.delete,()=>{Wn(z.path)})),be.append(Ge)}be.addEventListener("click",Ge=>{Ge.target.closest(".ra-fra")||(z.folder?(w=z.path,k.delete(z.path)||k.add(z.path),Et()):(w=Fo(z.path),Ke(z.path)))}),de.append(be),z.folder&&Qe&&Je(z,K+1,de,dn)}},Et=()=>{if(!C)return;let L=document.createDocumentFragment();C.length?Je(vd(C),0,L):L.append(f("div","ra-fpe",e.noFiles)),Ae.replaceChildren(L)},Ie=async()=>{if(!i||!a||N)return;let L=++T,K=i;try{let de=await K.list("/");if(L!==T||K!==i||N)return;C=de,Et()}catch(de){if(L!==T||N)return;Ae.replaceChildren(f("div","ra-fpe",de.message))}},We=L=>{Oe.style.display=L?"":"none",n.classList.toggle("ra-editing",L)},Ke=async L=>{if(i&&!(L!==l&&!await nt())){l=L,S.delete(L),Ne(null),$.textContent=L,h&&(URL.revokeObjectURL(h),h=null),Be.replaceChildren(),We(!0);try{let K=await i.read(L);if(l!==L)return;let de=xd.test(L)||/^image\//.test(K.contentType??""),Z=null;if(!de)if(typeof K.data=="string")Z=K.data;else try{Z=new TextDecoder("utf-8",{fatal:!0}).decode(K.data)}catch{Z=null}if(/\.pdf$/i.test(L)||K.contentType==="application/pdf"){p=null,xe.style.display="none",ee.style.display="none",ae.style.display="none",Be.style.display="",h=URL.createObjectURL(new Blob([K.data],{type:"application/pdf"}));let be=f("iframe","ra-edpdf");be.src=h,be.title=tn(L),me.style.display="none",Be.replaceChildren(be),tt(i.isReadOnly(L)),Et();return}me.style.display="",Z!==null&&K.size>R&&(Z=null);let z=i.isReadOnly(L);if(tt(z),Z!==null)p=Z,xe.value=Z,Be.style.display="none",xe.readOnly=z,xe.title=z?e.readOnly:"",Hn();else{if(p=null,xe.style.display="none",ee.style.display="none",ae.style.display="none",Be.style.display="",de){let be=new Blob([K.data],{type:K.contentType||"image/*"});h=URL.createObjectURL(be);let Qe=f("img");Qe.src=h,Qe.alt=tn(L),Be.append(Qe)}else Be.append(f("div","ra-fpe",K.size>R&&!de?e.tooBig:e.noPreview));Be.append(f("div","ra-fpe",`${K.size} B`))}}catch(K){p=null,xe.style.display="none",ee.style.display="none",ae.style.display="none",Be.style.display="",Be.replaceChildren(f("div","ra-fpe",K.message))}Et()}},an=async()=>l?await nt()?(l=null,p=null,Ne(null),h&&(URL.revokeObjectURL(h),h=null),We(!1),await Ie(),!0):!1:!0,Ve=async()=>{if(!i||!l||d===null)return;let L=l,K=d,de=i;try{let Z=await de.readText(L).catch(()=>null);if(Z!==null&&p!==null&&Z!==p&&!await bt(n,e.conflict,L,{ok:e.save,cancel:e.cancel,danger:!0})||(await de.write(L,K),l!==L||de!==i))return;p=K,Ne(xe.value===K?null:xe.value),t(`${e.saved}: ${L}`),r.onChange?.()}catch(Z){t(Z.message,"error")}},Xe=async L=>{if(i)try{let K=await i.read(L);Er(tn(L),K.data,K.contentType)}catch(K){t(K.message,"error")}},Ye=async L=>{if(i)try{let K=L==="/"?"/":L+"/",de=(await i.list(L)).filter(be=>be.path.startsWith(K));if(!de.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${de.length}\u2026`);let Z=[];for(let be of de){let Qe=await i.read(be.path);Z.push({path:be.path.slice(K.length),data:Qe.data,mtime:be.mtime})}let z=await fs(Z);Er(`${L==="/"?i.id||"directory":tn(L)}.zip`,z,"application/zip")}catch(K){t(K.message,"error")}},Wn=async L=>{if(!i||!await bt(n,e.delete,e.confirmDeleteFile.replace("{path}",L),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let K=[];try{let de=await i.isFolder(L)?(await i.list(L)).map(Z=>Z.path).filter(Z=>Z!==L):[L];for(let Z of de){if(i.isReadOnly(Z)){K.push(Z);continue}try{await i.delete(Z)}catch{K.push(Z)}}}catch(de){t(de.message,"error")}l&&(l===L||l.startsWith(L+"/"))&&!await i.exists(l)&&(l=null,p=null,Ne(null),We(!1)),K.length&&t(`${e.readOnly}: ${K.slice(0,3).join(", ")}${K.length>3?` +${K.length-3}`:""}`,"warning"),r.onChange?.(),await Ie()},Pr=async()=>{if(!i)return;let L=on(),K=L==="/"?"/":L+"/",de=await Za(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${K}untitled.md`});if(!de)return;let Z="/"+de.replace(/^\/+/,"");try{await i.exists(Z)||await i.write(Z,""),r.onChange?.(),await Ie(),await Ke(Z),xe.focus()}catch(z){t(z.message,"error")}},ln=async L=>{if(!i||!L?.length)return;let K=null;for(let de of Array.from(L))try{let Z=await No(i,on(),tn(de.name.replace(/\\/g,"/"))||"file");await i.write(Z,new Uint8Array(await de.arrayBuffer()),de.type||void 0),K=Z}catch(Z){t(Z.message,"error")}r.onChange?.(),await Ie(),K&&L.length===1&&await Ke(K)};fe.addEventListener("change",()=>{let L=Array.from(fe.files??[]);fe.value="",ln(L)});let Ht=0;P.addEventListener("dragenter",L=>{L.dataTransfer?.types.includes("Files")&&(L.preventDefault(),L.stopPropagation(),Ht++,P.dataset.drop="1")}),P.addEventListener("dragover",L=>{P.dataset.drop&&(L.preventDefault(),L.stopPropagation(),L.dataTransfer.dropEffect="copy")}),P.addEventListener("dragleave",L=>{P.dataset.drop&&(L.stopPropagation(),--Ht<=0&&(Ht=0,delete P.dataset.drop))}),P.addEventListener("drop",L=>{P.dataset.drop&&(L.preventDefault(),L.stopPropagation(),Ht=0,delete P.dataset.drop,ln(L.dataTransfer?.files))});let Kn=async L=>{a=!0,P.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await Ie(),L&&await Ke(L)},cn=async()=>{await an()&&(a=!1,P.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:P,get visible(){return a},open:Kn,close:cn,toggle:()=>a?cn():Kn(),setWorkspace(L){if(L!==i){if(i&&l&&d!==null){let[K,de,Z]=[i,l,d];K.write(de,Z).then(()=>t(`${e.autoSaved}: ${de}`),z=>t(z.message,"error"))}v?.(),v=null,i=L,L&&(v=L.onChange(K=>{a&&(E(),!(K.path!==l||d!==null)&&(K.kind==="write"?Ke(K.path):(l=null,p=null,We(!1))))})),h&&(URL.revokeObjectURL(h),h=null),C=null,l=null,p=null,Ne(null),We(!1),S.clear(),w="/",L?Ie():(a=!1,P.style.display="none",n.classList.remove("ra-files-open"))}},refresh:Ie,changed(L){S.add(L),Et()},download:Xe,downloadFolder:Ye,dispose(){N=!0,v?.(),U&&clearTimeout(U),h&&URL.revokeObjectURL(h),P.remove(),Oe.remove(),n.classList.remove("ra-editing")}}}var Ho={spans:400,requests:120,events:600},kd=new Set(["text_delta","reasoning_delta","tool_update"]);function $r(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 Td(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,i=null,a=!1,l="calls",d="",p=null,h=f("div","ra-fp ra-dp");h.setAttribute("role","complementary"),h.style.display="none";let w=f("div","ra-fph"),k=f("div","ra-dtabs"),v=f("button","ra-ib");v.type="button",v.innerHTML=I.x(14),v.title=e.close,v.setAttribute("aria-label",e.close),v.addEventListener("click",()=>_e()),w.append(k,f("span","ra-sp"),v);let T=f("div","ra-dbody");h.append(w,T);let C=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],R=()=>{let $=i?t.get(i):void 0,H={calls:$?.spans.length??0,requests:$?.requests.length??0};k.replaceChildren(...C.map(([W,ne])=>{let j=f("button","ra-dtab"+(W===l?" on":""));return j.type="button",j.append(ne),H[W]&&j.append(f("span","ra-dcount",String(H[W]))),j.addEventListener("click",()=>{l=W,oe()}),j}))},U=($,H)=>{let W=f("details","ra-dfold"),ne=f("summary"),j=f("span","ra-chev");j.innerHTML=I.chev(12),ne.append(j,...$),W.append(ne);let q=!1;return W.addEventListener("toggle",()=>{if(W.open&&!q){q=!0;let ce=f("div","ra-dfb");ce.append(...H()),W.append(ce)}}),W},E=($,H="")=>{let W=f("pre","ra-dpre "+H);return W.textContent=typeof $=="string"?$:Td($),W},S=$=>f("div","ra-dlabel",$),N=$=>f("span","ra-dmuted",$),P=$=>f("span","ra-dmono",$),V=$=>f("div","ra-fpe",$),se=$=>{let H=f("span","ra-dst "+($==="running"?"run":$==="ok"?"ok":"fail"));return $==="running"?H.append(f("span","ra-spin")):H.innerHTML=$==="ok"?I.check(13):I.xcircle(13),H},J=$=>{if(!$.spans.length)return[V(e.dNoCalls)];let H=[];for(let W of[...$.runs].reverse()){let ne=$.spans.filter(me=>me.runId===W),j=$.requests.filter(me=>me.runId===W);if(!ne.length&&!j.length)continue;let q=f("div","ra-drun");q.append(f("div","ra-drh",`${e.dRun} ${$r(j[0]?.at??ne[0]?.startedAt??Date.now())} \xB7 ${W.slice(-4)}`));let ce=[...new Set([...j.map(me=>me.turn),...ne.map(me=>me.turn)])].sort((me,ae)=>me-ae);for(let me of ce){let ae=j.find($e=>$e.turn===me),ee=f("div","ra-dturn");ee.append(N(e.dTurn.replace("{n}",String(me)))),ae&&ee.append(P(` \xB7 ${ae.params.model||"default"}`),N(ae.durationMs!==void 0?` \xB7 ${Math.round(ae.durationMs)}ms`:" \xB7 \u2026"),ae.error?f("span","ra-dst fail",` ${ae.error}`):N(ae.finishReason?` \xB7 ${ae.finishReason}`:"")),q.append(ee);for(let $e of ne.filter(it=>it.turn===me))q.append(U([se($e.status),P($e.name),N($e.durationMs!==void 0?`${Math.round($e.durationMs)}ms \xB7 ${$r($e.startedAt)}`:$r($e.startedAt))],()=>[f("div","ra-dmuted",$e.id),S(e.args),E($e.args),...$e.result!==void 0?[S(e.result),E($e.result)]:[]]))}H.push(q)}return H},fe=$=>$.requests.length?[...$.requests].reverse().map(H=>{let W=H.params,ne=H.usage,j=f("span","ra-dbadge "+(H.error?"fail":H.durationMs===void 0?"":"ok"),H.error?"error":H.durationMs===void 0?"\u2026":H.finishReason??"ok");return U([j,P(W.model||"default"),N(`${W.messages?.length??0} msgs \xB7 ${W.tools?.length??0} tools${ne?` \xB7 ${ne.prompt_tokens??0}\u2192${ne.completion_tokens??0} tok`:""}${ne?.total_cost?` \xB7 $${ne.total_cost.toFixed(4)}`:""}`),N(` ${H.durationMs!==void 0?`${Math.round(H.durationMs)}ms \xB7 `:""}${$r(H.at)}`)],()=>[S(e.dPayload),E(H.params,"tall"),...H.message!==void 0||H.error?[S(e.dResponse),E(H.error??H.message)]:[],...ne?[E(ne)]:[]])}):[V(e.dNoRequests)],pe=$=>{let H=f("div","ra-dbar"),W=f("input","ra-field");W.type="text",W.placeholder=e.dFilter,W.value=d,W.addEventListener("input",()=>{d=W.value,ye()});let ne=f("button","ra-ib");ne.type="button",ne.innerHTML=I.trash(13),ne.title=e.dClear,ne.setAttribute("aria-label",e.dClear),ne.addEventListener("click",()=>{$.events.length=0,$.spans.length=0,$.requests.length=0,$.runs.length=0,oe()}),H.append(W,ne);let j=$.events.filter(q=>!d||q.name.includes(d)||q.detail.includes(d));return j.length?[H,...[...j].reverse().slice(0,300).map(q=>U([N($r(q.at)),P(q.name),N(q.detail)],()=>[E(q.data)]))]:[H,V(e.dNoEvents)]},Ce=$=>{let H=f("div","ra-dctx"),W=f("div","ra-dkv"),ne=(ae,ee)=>{W.append(f("span","ra-dmuted",ae),f("span","ra-dmono",ee))},j=$.usage,q=$.messages;ne("session",$.id),ne("directory",$.workspace?.id??"\u2014"),ne("model",$.settings.model??"(default)"),ne("messages",`${q.filter(ae=>ae.role==="user").length} user \xB7 ${q.filter(ae=>ae.role==="assistant").length} assistant \xB7 ${q.filter(ae=>ae.role==="tool").length} tool`),ne("usage",`${j.prompt_tokens} in \xB7 ${j.completion_tokens} out \xB7 ${j.calls} calls \xB7 $${j.total_cost.toFixed(4)}`);let ce=f("span","ra-dmono","\u2026");W.append(f("span","ra-dmuted","context"),ce),$.context().then(ae=>{ce.textContent=`${ae.used} / ${ae.window} (${(ae.used/ae.window*100).toFixed(2)}%)`}).catch(()=>{ce.textContent="\u2014"});let me=E("\u2026","tall");return $.systemPrompt().then(ae=>{me.textContent=ae}).catch(ae=>{me.textContent=String(ae)}),H.append(W,S(e.dSystem),me,S(`${e.dMessages} (${q.length})`),E(q,"tall")),[H]},Se=$=>$.tools.map(H=>U([P(H.name),N(H.destructive?" destructive":"")],()=>[f("div","ra-ddesc",H.description??""),E(H.parameters)]));function oe(){if(p=null,!a)return;if(R(),!i){T.replaceChildren();return}let $=t.get(i),H=T.scrollTop,W=document.activeElement?.classList.contains("ra-field")&&T.contains(document.activeElement),ne=l==="calls"?J($):l==="requests"?fe($):l==="events"?pe($):l==="context"?Ce(i):Se(i);if(T.replaceChildren(...ne),T.scrollTop=H,W){let j=T.querySelector(".ra-field");j?.focus(),j?.setSelectionRange(j.value.length,j.value.length)}}let ye=()=>{if(!(!a||p)){if(l==="context"||l==="tools"||T.querySelector("details[open]")){R();return}p=setTimeout(oe,300)}},Ae=$=>{if(t.has($))return;let H={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set($,H),s.set($,$.on("*",(W,ne)=>{let j=ne??{},q=String(j.runId??"");if(W==="run_start"&&(H.runs.push(q),Ps(H.runs,60)),W==="turn_start"&&H.turn.set(q,Number(j.turn)||1),W==="request"&&(H.requests.push({runId:q,turn:Number(j.turn),at:Date.now(),params:j.params}),Ps(H.requests,Ho.requests)),W==="response"){let ce=[...H.requests].reverse().find(me=>me.runId===q&&me.turn===Number(j.turn)&&me.durationMs===void 0);ce&&Object.assign(ce,{durationMs:j.durationMs,finishReason:j.finishReason,usage:j.usage,message:j.message,error:j.error})}if(W==="tool_start"&&(H.spans.push({id:String(j.id),name:String(j.name),args:j.args,status:"running",startedAt:Date.now(),runId:q,turn:H.turn.get(q)??1}),Ps(H.spans,Ho.spans)),W==="tool_end"){let ce=[...H.spans].reverse().find(me=>me.id===String(j.id));ce&&Object.assign(ce,{status:String(j.status),result:j.result,durationMs:j.durationMs})}if(!kd.has(W)){let ce=W==="tool_start"||W==="tool_end"?String(j.name??""):W==="run_end"?String(j.reason??""):W==="response"?String(j.error??j.finishReason??""):"";H.events.push({at:Date.now(),name:W,detail:ce,data:W==="request"?{runId:q,turn:j.turn,model:j.params?.model}:ne}),Ps(H.events,Ho.events)}$===i&&ye()}))},Oe=()=>{a=!0,h.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),oe()};function _e(){a&&(a=!1,h.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:h,get visible(){return a},open:Oe,close:_e,toggle:()=>a?_e():Oe(),setAgent($){Ae($),i=$,a&&oe()},forget($){s.get($)?.(),s.delete($),t.delete($),i===$&&(i=null)},dispose(){for(let $ of s.values())$();s.clear(),p&&clearTimeout(p),h.remove()}}}var Qa=["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"],el=["font","mono"],Sd='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',Cd='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',_s={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)"}}},In=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function tl(){let r=_s.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${Sd};--ra-mono:${Cd};${In(r.light)}}`,":where(.ra-chat[data-scheme=light], .ra-ui[data-scheme=light]){color-scheme:light}",`:where(.ra-chat[data-scheme=dark], .ra-ui[data-scheme=dark]){${In(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${In(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(_s))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${In(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${In(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${In(t.dark)}}}`));return e.join(`
|
|
306
|
+
`)}var nl=r=>r.startsWith("--")?r:`--ra-${r}`;var Md={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",ovAttachments:"The attachments on this message are too large for the model.",ovMessage:"This message is too long for the model.",ovHistory:"This conversation has grown too long for the model.",ovTools:"The connected tools take up too much of the model's context.",ovModel:"This request does not fit the current model.",ovDropFiles:"Resend without attachments",ovEdit:"Edit the message",ovCompact:"Compact and continue",ovNew:"Continue in a new chat",ovToolSettings:"Tool settings",ovUseModel:"Retry with {name}",ovNoText:"The message had only attachments: type what you want to ask.",ovNoSummary:"Could not summarise the conversation; the new chat starts without it.",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}",actWeb:"searched the web {n} time(s)",actBrowse:"read {n} web page(s)",ingWeb:"Searching the web",ingBrowse:"Reading",web:"Web",webOn:"Web search: on",webOff:"Web search: off",webHint:"When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",runCode:"Run code",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",sTabContext:"Context",sCompact:"When the context is nearly full",sCompactSummary:"Summarise older turns (one extra model call)",sCompactTrim:"Only trim: drop old tool results, then the oldest turns",sCompactAt:"Start when fewer tokens than this are left",sKeepRecent:"Keep this many of the newest tokens word for word",sDefaultN:"Default ({n})",sCompactNote:"{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)",sCompactNoteTrim:"{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)",autoTrim:"Auto-trim",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",ovAttachments:"\u8FD9\u6761\u6D88\u606F\u7684\u9644\u4EF6\u592A\u5927\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",ovMessage:"\u8FD9\u6761\u6D88\u606F\u592A\u957F\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",ovHistory:"\u8FD9\u6BB5\u5BF9\u8BDD\u592A\u957F\uFF0C\u6A21\u578B\u653E\u4E0D\u4E0B\u4E86\u3002",ovTools:"\u5DF2\u8FDE\u63A5\u7684\u5DE5\u5177\u592A\u591A\uFF0C\u5360\u6EE1\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u3002",ovModel:"\u5F53\u524D\u6A21\u578B\u653E\u4E0D\u4E0B\u8FD9\u6B21\u8BF7\u6C42\u3002",ovDropFiles:"\u53BB\u6389\u9644\u4EF6\u540E\u91CD\u53D1",ovEdit:"\u4FEE\u6539\u8FD9\u6761\u6D88\u606F",ovCompact:"\u538B\u7F29\u540E\u7EE7\u7EED",ovNew:"\u5F00\u65B0\u5BF9\u8BDD\u7EE7\u7EED",ovToolSettings:"\u6253\u5F00\u5DE5\u5177\u8BBE\u7F6E",ovUseModel:"\u6362\u7528 {name} \u91CD\u8BD5",ovNoText:"\u8FD9\u6761\u6D88\u606F\u53EA\u6709\u9644\u4EF6\uFF0C\u8BF7\u8F93\u5165\u60F3\u95EE\u7684\u5185\u5BB9\u3002",ovNoSummary:"\u8FD9\u6BB5\u5BF9\u8BDD\u6CA1\u80FD\u751F\u6210\u6458\u8981\uFF0C\u65B0\u5BF9\u8BDD\u4E0D\u4F1A\u5E26\u4E0A\u4E4B\u524D\u7684\u5185\u5BB9\u3002",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}",actWeb:"\u8054\u7F51\u641C\u7D22\u4E86 {n} \u6B21",actBrowse:"\u9605\u8BFB\u4E86 {n} \u4E2A\u7F51\u9875",ingWeb:"\u6B63\u5728\u8054\u7F51\u641C\u7D22",ingBrowse:"\u6B63\u5728\u9605\u8BFB",web:"\u8054\u7F51",webOn:"\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5F00\u542F",webOff:"\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5173\u95ED",webHint:"\u5F00\u542F\u540E AI \u53EF\u4EE5\u641C\u7D22\u548C\u9605\u8BFB\u7F51\u9875\uFF0C\u67E5\u8D44\u6599\u548C\u6700\u65B0\u4FE1\u606F\uFF1B\u6BCF\u6B21\u641C\u7D22\u3001\u6BCF\u8BFB\u4E00\u4E2A\u7F51\u9875\u6309\u6B21\u8BA1\u8D39",runCode:"\u8FD0\u884C\u4EE3\u7801",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",sTabContext:"\u4E0A\u4E0B\u6587",sCompact:"\u4E0A\u4E0B\u6587\u5FEB\u6EE1\u65F6",sCompactSummary:"\u628A\u8F83\u65E9\u7684\u5BF9\u8BDD\u5199\u6210\u6458\u8981\uFF08\u591A\u4E00\u6B21\u6A21\u578B\u8C03\u7528\uFF09",sCompactTrim:"\u53EA\u88C1\u526A\uFF1A\u5148\u5220\u65E7\u7684\u5DE5\u5177\u7ED3\u679C\uFF0C\u518D\u5220\u6700\u65E9\u7684\u5BF9\u8BDD",sCompactAt:"\u5269\u4F59\u5C11\u4E8E\u591A\u5C11 tokens \u65F6\u5F00\u59CB",sKeepRecent:"\u539F\u6837\u4FDD\u7559\u6700\u8FD1\u591A\u5C11 tokens",sDefaultN:"\u9ED8\u8BA4\uFF08{n}\uFF09",sCompactNote:"{model}\uFF1A\u5269\u4F59 {at} tokens \u65F6\u5F00\u59CB\uFF0C\u539F\u6837\u4FDD\u7559\u7EA6 {keep} tokens\uFF08\u6700\u591A\u4E3A\u4E0A\u4E0B\u6587 {window} \u7684 20% / 40%\uFF09",sCompactNoteTrim:"{model}\uFF1A\u5269\u4F59\u5C11\u4E8E {at} tokens \u65F6\u88C1\u526A\uFF08\u6700\u591A\u4E3A\u4E0A\u4E0B\u6587 {window} \u7684 20%\uFF09",autoTrim:"\u81EA\u52A8\u88C1\u526A",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 Ed(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 rl="runapps-agent-chat-style",Ad=tl()+`
|
|
307
307
|
.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}
|
|
308
308
|
.ra-chat *,.ra-chat *::before,.ra-chat *::after{box-sizing:border-box}
|
|
309
309
|
/* The chat's own controls start bare; what the host puts in (.ra-host: header actions, the empty state, composerTop, a tool's own content) keeps the host's styles. */
|
|
@@ -362,7 +362,7 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
362
362
|
.ra-set .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
|
|
363
363
|
.ra-set input[type=number]{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 12px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
|
|
364
364
|
.ra-set input:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
|
|
365
|
-
.ra-set .ra-row{display:flex;gap:8px;align-items:center}
|
|
365
|
+
.ra-set .ra-row{display:flex;gap:8px;align-items:center;padding:0}
|
|
366
366
|
.ra-set .ra-row>*{flex:1;min-width:0}
|
|
367
367
|
.ra-set .ra-lim{font-size:11px;color:var(--ra-fg-muted);margin-top:-4px}
|
|
368
368
|
.ra-set .ra-btns{justify-content:space-between}
|
|
@@ -373,7 +373,7 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
373
373
|
.ra-set .ra-tab:hover{color:var(--ra-fg)}
|
|
374
374
|
.ra-set .ra-tab.on{color:var(--ra-fg);border-bottom-color:var(--ra-accent);font-weight:500}
|
|
375
375
|
.ra-set .ra-tgl{display:flex;gap:8px;align-items:flex-start;font-size:13px;color:var(--ra-fg);cursor:pointer}
|
|
376
|
-
.ra-set .ra-tgl input{margin:3px 0 0
|
|
376
|
+
.ra-set .ra-tgl input{margin:3px 0 0}
|
|
377
377
|
.ra-set .ra-tgl small,.ra-set .ra-fld small{display:block;font-size:11.5px;color:var(--ra-fg-muted);margin-top:1px}
|
|
378
378
|
.ra-card .ra-btn{margin-top:8px}
|
|
379
379
|
.ra-menu .ra-mi .ra-spin{margin-right:6px}
|
|
@@ -497,7 +497,7 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
497
497
|
.ra-uf .ra-ut::after{content:"\xB7";margin-left:4px}
|
|
498
498
|
.ra-uf .ra-ib{width:22px;height:22px}
|
|
499
499
|
.ra-modal label.ra-ck{display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer}
|
|
500
|
-
.ra-modal label.ra-ck input{
|
|
500
|
+
.ra-modal label.ra-ck input{margin:0}
|
|
501
501
|
.ra-modal .ra-dn{font-size:12px;color:var(--ra-fg-muted);margin:-4px 0 0 24px}
|
|
502
502
|
.ra-asst{min-width:0}
|
|
503
503
|
.ra-body{min-width:0;display:flex;flex-direction:column;gap:8px}
|
|
@@ -596,7 +596,15 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
596
596
|
.ra-q .ra-opts{display:flex;flex-direction:column;gap:4px}
|
|
597
597
|
.ra-q .ra-opt{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--ra-border);border-radius:6px;padding:6px 12px;text-align:left;width:100%;background:var(--ra-bg);font-size:14px;min-height:32px}
|
|
598
598
|
.ra-q .ra-opt:hover{background:var(--ra-muted)}
|
|
599
|
-
.ra-q .ra-opt input[type=radio],.ra-q .ra-opt input[type=checkbox]{
|
|
599
|
+
.ra-q .ra-opt input[type=radio],.ra-q .ra-opt input[type=checkbox]{margin:4px 0 0}
|
|
600
|
+
/* Checkboxes and radios are drawn here, in the palette's colours, not by the browser: a native one takes its look from the page's color-scheme and the system's accent, which need not be the chat's (a dark system under a light host drew unchecked boxes as dark squares). */
|
|
601
|
+
.ra-chat input:is([type=radio],[type=checkbox]):not(.ra-x){appearance:none;-webkit-appearance:none;box-sizing:border-box;width:15px;height:15px;min-width:15px;padding:0;flex:none;display:inline-grid;place-content:center;vertical-align:-2px;background:var(--ra-bg);border:1px solid color-mix(in srgb,var(--ra-fg-muted) 55%,transparent);border-radius:4px;cursor:pointer;transition:background-color .12s,border-color .12s}
|
|
602
|
+
.ra-chat input[type=radio]:not(.ra-x){border-radius:50%}
|
|
603
|
+
.ra-chat input:is([type=radio],[type=checkbox]):not(.ra-x):hover{border-color:var(--ra-accent)}
|
|
604
|
+
.ra-chat input:is([type=radio],[type=checkbox]):not(.ra-x):checked{background:var(--ra-accent);border-color:var(--ra-accent)}
|
|
605
|
+
.ra-chat input[type=checkbox]:not(.ra-x):checked::before{content:"";width:9px;height:9px;background:#fff;clip-path:polygon(13% 50%,2% 62%,38% 96%,98% 24%,86% 13%,37% 70%)}
|
|
606
|
+
.ra-chat input[type=radio]:not(.ra-x):checked::before{content:"";width:6px;height:6px;border-radius:50%;background:#fff}
|
|
607
|
+
.ra-chat input:is([type=radio],[type=checkbox]):not(.ra-x):disabled{opacity:.5;cursor:default}
|
|
600
608
|
/* A host's form styles (antd's .ant-form input[type=radio]:focus) put a square focus shadow on our radios and checkboxes: none here (more specific than theirs on purpose). Keyboard focus shows on the option's row for a radio, as a ring for a checkbox. */
|
|
601
609
|
.ra-chat input:is([type=radio],[type=checkbox]):focus:not(.ra-x){box-shadow:none;outline:0}
|
|
602
610
|
.ra-chat input[type=checkbox]:focus-visible:not(.ra-x){outline:2px solid var(--ra-accent);outline-offset:1px}
|
|
@@ -713,35 +721,35 @@ ${d}`})}let s=typeof e.content=="string"?[{type:"text",text:e.content}]:e.conten
|
|
|
713
721
|
.ra-toasts{position:absolute;top:10px;left:50%;transform:translateX(-50%);z-index:7;display:flex;flex-direction:column;gap:6px;pointer-events:none;max-width:calc(100% - 32px)}
|
|
714
722
|
.ra-toast{background:#18181b;color:#fff;font-size:13px;padding:8px 14px;border-radius:8px;box-shadow:var(--ra-shadow-md);white-space:pre-wrap;word-break:break-word}
|
|
715
723
|
.ra-toast.warning{background:#d97706}.ra-toast.error{background:#dc2626}
|
|
716
|
-
`+
|
|
717
|
-
`):""}function
|
|
718
|
-
`).find(i=>i.trim()&&!i.trim().startsWith("//"))?.trim().slice(0,80)??"";if(r==="ask_user"){let i=n.questions;return Array.isArray(i)&&i[0]&&typeof i[0]=="object"?String(i[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
|
|
719
|
-
`))!t&&(s.startsWith(
|
|
724
|
+
`+Ja;function dl(r,e,n={}){ul();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}),i=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=i,s.el.remove()}})}function ul(){if(typeof document>"u"||document.getElementById(rl))return;let r=document.createElement("style");r.id=rl,r.textContent=Ad,document.head.prepend(r)}var $d={read_file:I.fileText,write_file:I.filePlus,edit_file:I.filePen,delete_file:I.fileX,list_files:I.folderOpen,search_files:I.search,run_js:I.braces,ask_user:I.message,web_search:I.search,web_fetch:I.globe};function nn(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
725
|
+
`):""}function jo(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(`
|
|
726
|
+
`).find(i=>i.trim()&&!i.trim().startsWith("//"))?.trim().slice(0,80)??"";if(r==="ask_user"){let i=n.questions;return Array.isArray(i)&&i[0]&&typeof i[0]=="object"?String(i[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 sl={read_file:"Read",list_files:"List",search_files:"Search",write_file:"Write",edit_file:"Edit",delete_file:"Delete",run_js:"Run",ask_user:"Ask",web_search:"Web",web_fetch:"Browse"},ol=r=>r&&typeof r=="object"&&typeof r.path=="string"?r.path:void 0;function Ld(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 qo(r,e){let n=pl(e);return r===0?`${n}0`:r<.001?`${n}${r.toFixed(5)}`:r<.1?`${n}${r.toFixed(4)}`:`${n}${r.toFixed(3)}`}function pl(r){let e=(r||"USD").toUpperCase();return e==="USD"?"$":e==="CNY"||e==="JPY"?"\xA5":e==="EUR"?"\u20AC":e==="GBP"?"\xA3":`${e} `}function Lr(r,e){return`${pl(e)}${Number(r.toPrecision(4))}`}function qe(r){return r>=1e6?`${(r/1e6).toFixed(r>=1e7?1:2)}M`:r>=1e4?`${(r/1e3).toFixed(1)}k`:String(r)}function Un(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/1024/1024).toFixed(1)} MB`}function Pd(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))):fl(r)}function fl(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 Fn=r=>r?.ts,hl=2*1024*1024,_d=32*1024*1024,ml=30,Os=r=>`ckpt:${r}`,Ds="ckpt:index";async function Rd(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>hl||s+a.size>_d){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(Os(e),{at:e,files:n,partial:t.length>0,skipped:t});let i=[...(await r.getData(Ds)??[]).filter(a=>a!==e),e].sort((a,l)=>a-l);for(let a of i.splice(0,Math.max(0,i.length-ml)))await r.deleteData(Os(a));await r.putData(Ds,i)}async function Od(r,e){let n=await r.getData(Ds)??[];for(let t of n.filter(s=>s>e))await r.deleteData(Os(t));await r.putData(Ds,n.filter(t=>t<=e))}var zs=r=>`hoststate:${r}`,Is="hoststate:index";async function Dd(r,e,n){await r.putData(zs(e),{at:e,value:n});let t=[...(await r.getData(Is)??[]).filter(s=>s!==e),e].sort((s,i)=>s-i);for(let s of t.splice(0,Math.max(0,t.length-ml)))await r.deleteData(zs(s));await r.putData(Is,t)}async function zd(r,e){let n=await r.getData(Is)??[];for(let t of n.filter(s=>s>e))await r.deleteData(zs(t));await r.putData(Is,n.filter(t=>t<=e))}async function Id(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>hl||await r.delete(t.path);for(let t of e.files)await r.write(t.path,t.data,t.contentType)}var Ud=20*1024*1024,Fd=8*1024*1024,Nd=25*1024*1024,Bo=64*1024,Hd=/\.(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,Ft="[attachments]",Nn="[context] ";function Rs(r){if(Array.isArray(r))return r.filter(s=>s.type==="text").map(s=>s.text);if(typeof r!="string")return[];if(!r.includes(Nn)&&!r.includes(Ft)&&!r.includes("<file name="))return[r];let e=[],n=[],t=!1;for(let s of r.split(`
|
|
727
|
+
`))!t&&(s.startsWith(Nn)||s.startsWith(Ft)||s.startsWith("<file name="))&&n.length&&(e.push(n.join(`
|
|
720
728
|
`)),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(`
|
|
721
|
-
`)),e}function Ga(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 $d=r=>r?.typed,Ld=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}.`,Pd=r=>`Files the user attaches arrive under ${r}.`,_d=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 Rd(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Ad.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 Za(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function Od(r,e,n,t){let s=new Set,i=(d,u,f)=>new Promise(w=>{if(f?.aborted){w(u);return}let k=h("section","ra-q"),v,T=()=>v.cancel(),M=U=>{f?.removeEventListener("abort",T),s.delete(v),k.remove(),t(),w(U)};v={card:k,cancel:()=>M(u)},f?.addEventListener("abort",T,{once:!0}),k.addEventListener("keydown",U=>{U.key==="Escape"&&!U.isComposing&&(U.preventDefault(),U.stopPropagation(),v.cancel())}),d(k,M),s.add(v),r.append(k),t();let R=k.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>R?.focus())}),a=(d,u,f)=>{d.append(h("div","ra-qt",u)),f&&d.append(h("div","ra-qm",f))},l=(d,u,f)=>{let w=h("button","ra-btn xs "+u,d);return w.type="button",w.addEventListener("click",f),w};return{confirm:(d,u,f={})=>i((w,k)=>{if(a(w,d,u),f.body)try{let M=f.body();M.classList.add("ra-cbody"),w.append(M)}catch(M){console.warn("agent: confirm body failed",M)}let v=h("div","ra-btns");v.append(l(f.cancel??n.decline,"ghost",()=>k(!1)));let T=f.always;T&&v.append(l(T.label,"subtle",()=>{try{T.onChoose()}catch(M){console.warn("agent: always.onChoose failed",M)}k(!0)})),v.append(l(f.ok??n.allow,f.danger?"red":"solid",()=>k(!0))),w.append(v)},!1,f.signal),select:(d,u,f={})=>i((w,k)=>{a(w,d,f.message);let v=h("div","ra-opts");if(!f.multi&&!f.allowOther){for(let S of u){let j=h("button","ra-opt");j.type="button";let P=h("div");P.append(h("span","",S.label??S.value)),S.description&&P.append(h("small","",S.description)),j.append(P),j.addEventListener("click",()=>k([S.value])),v.append(j)}w.append(v,(()=>{let S=h("div","ra-btns");return S.append(l(n.cancel,"ghost",()=>k(null))),S})());return}let T="ra_"+Math.random().toString(36).slice(2,8),M=[],R=S=>{let j=h("label","ra-opt"),P=h("input");P.type=f.multi?"checkbox":"radio",P.name=T,P.value=S.value,M.push(P);let V=h("div");V.append(h("span","",S.label??S.value)),S.description&&V.append(h("small","",S.description)),j.append(P,V),v.append(j)};u.forEach(R);let U=null;f.allowOther&&(R({value:"__other__",label:n.other}),U=h("input","ra-field"),U.type="text",U.placeholder=n.typeAnswer,U.addEventListener("focus",()=>{let S=M.find(j=>j.value==="__other__");S&&(S.checked=!0)}),v.append(U)),w.append(v);let E=h("div","ra-btns");E.append(l(n.cancel,"ghost",()=>k(null)),l(n.ok,"solid",()=>{let S=M.filter(j=>j.checked).map(j=>j.value==="__other__"?U?.value.trim()??"":j.value).filter(Boolean);S.length&&k(S)})),w.append(E)},null,f.signal),input:(d,u={})=>i((f,w)=>{a(f,d,u.message);let k=u.multiline?h("textarea","ra-field"):h("input","ra-field");u.multiline||(k.type="text"),u.placeholder&&(k.placeholder=u.placeholder),u.initial&&(k.value=u.initial),k.addEventListener("keydown",T=>{let M=T;M.key==="Enter"&&!M.isComposing&&(!u.multiline||M.metaKey||M.ctrlKey)&&(M.preventDefault(),w(k.value))}),f.append(k);let v=h("div","ra-btns");v.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(k.value))),f.append(v)},null,u.signal),notify(d,u="info"){let f=h("div","ra-toast "+u,d);e.append(f),setTimeout(()=>f.remove(),u==="error"?8e3:4e3)},cancelAll(d=!1){for(let u of[...s])(d||u.card.isConnected)&&u.cancel()},park(){let d=[];for(let u of s)u.card.isConnected&&(u.card.remove(),d.push(u.card));return t(),d},restore(d){for(let u of d)r.append(u);d.length&&t()}}}var Dd=new Set(["read_file","write_file","edit_file"]),Ja=async(r,e)=>{try{return await r.exists(e)&&!await r.isFolder(e)}catch{return!1}},Uo=r=>`__runapps_agent_chat:${r}:last`;function zd(r){try{return localStorage.getItem(Uo(r))}catch{return null}}function Xa(r,e){try{e?localStorage.setItem(Uo(r),e):localStorage.removeItem(Uo(r))}catch{}}function sl(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)");Qa();let n=hd(e.locale),t=fd[n],{toolSettings:s,client:i,provider:a,agent:l,workspace:d,resume:u,palette:f,vars:w,className:k,debug:v,settings:T,skillsMenu:M,title:R,placeholder:U,emptyState:E,suggestions:S,sessions:j,locale:P,theme:V,showUsage:ne,attachments:J,uploadsDir:pe,onOpenFile:ue,onLink:ke,onSession:ve,files:re,headerActions:me,headerEnd:Me,settingsTabs:_e,composerTop:Le,composerActions:$,permissionsSetting:H,rewindState:W,nextPrompt:te,webSearch:N,...q}=e,ae="/"+(pe??"/uploads").replace(/^\/+|\/+$/g,""),fe=a?ot(a):i?ot(i):l?.provider??null,oe=fe?.name??q.appName??"app",Q=h("div","ra-chat");k&&Q.classList.add(...k.split(/\s+/).filter(Boolean));let Ee=V??"auto",it=f??"claude",In=w,en=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,tn=[],Un=()=>{let o=Ee==="auto"?en?.matches?"dark":"light":Ee;Q.dataset.theme=Ee,Q.dataset.scheme=o,typeof it=="string"?Q.dataset.palette=it:delete Q.dataset.palette;for(let m of tn)Q.style.removeProperty(m);tn=[];let c=m=>{for(let[g,y]of Object.entries(m??{}))if(y!==void 0){let x=Ba(g);Q.style.setProperty(x,y),tn.push(x)}};typeof it!="string"&&c(it[o]);let p=In;p&&("light"in p||"dark"in p)?c(p[o]):c(p)};Un();let Fn=()=>{Ee==="auto"&&Un()};en?.addEventListener?.("change",Fn);let be=h("div","ra-head"),qe=h("div","ra-title",R===!1?"":R||q.appName||t.assistant),Ut=h("span","ra-badge"),tt=h("button","ra-btn ghost");tt.type="button",tt.innerHTML=I.bug()+`<span>${xe(t.debug)}</span>`;let Fe=h("button","ra-btn ghost");Fe.type="button",Fe.innerHTML=I.folder()+`<span>${xe(t.files)}</span>`;let nt=h("button","ra-btn ghost");nt.type="button",nt.innerHTML=I.puzzle()+`<span>${xe(t.skills)}</span>`;let jn=(o,c)=>{let p=h("b","ra-cnt");return p.style.display="none",o.append(p),m=>{p.textContent=String(m),p.style.display=m?"":"none",o.title=m?`${c} \xB7 ${m}`:c}},nn=jn(nt,t.skills),Ze=h("button","ra-btn ghost");Ze.type="button",Ze.innerHTML=I.hist()+`<span>${xe(t.history)}</span>`;let Et=jn(Ze,t.history),ze=h("button","ra-btn ghost");ze.type="button",ze.innerHTML=I.plus()+`<span>${xe(t.newChat)}</span>`;let Be=h("button","ra-btn ghost");Be.type="button",Be.innerHTML=I.eraser()+`<span>${xe(t.clearChat)}</span>`,Be.style.display="none";let We=!1,rn=()=>{Be.style.display=We&&F?.messages.length?"":"none"},Ke=h("button","ra-btn ghost ra-usebtn");Ke.type="button",Ke.style.display="none";let Je=h("button","ra-btn ghost");Je.type="button",Je.innerHTML=I.gear(),Je.title=t.settings,Je.setAttribute("aria-label",t.settings);for(let[o,c]of[[tt,t.debug],[Fe,t.files],[nt,t.skills],[Ze,t.history],[ze,t.newChat],[Be,t.clearChat]])o.setAttribute("aria-label",c),o.title||(o.title=c);for(let o of[...me??[],...Me??[],...Le?[Le]:[],...E instanceof HTMLElement?[E]:[]])o.classList.add("ra-host");be.append(qe,Ut,h("span","ra-sp"),Ke,tt,Fe,nt,Ze,ze,Be,...me??[],Je,...Me??[]),R===!1&&(be.style.display="none");let Xe=h("div","ra-log"),Hn=h("div","ra-col");Xe.append(Hn);let Mr=h("div","ra-ask"),sn=h("div","ra-col");Mr.append(sn);let Ft=h("div","ra-status");Ft.style.display="none";let Nn=h("div","ra-comp"),on=h("div","ra-col"),L=h("div","ra-alert");L.style.display="none",L.setAttribute("role","alert");let K=h("div","ra-queue");K.style.display="none";let le=h("div","ra-box"),Z=h("div","ra-cmds");Z.style.display="none";let z=h("textarea");z.rows=2,z.setAttribute("aria-label","Message");let we=h("div","ra-files");we.style.display="none";let Ye=h("div","ra-bar"),qn=h("div","ra-left"),at=h("button","ra-attach");at.type="button",at.innerHTML=I.clip(),at.title=t.attach,at.setAttribute("aria-label",t.attach);let rt=h("input");rt.type="file",rt.multiple=!0,rt.style.display="none",J===!1&&(at.style.display="none");let an=h("span","ra-hint"),al=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",Er=o=>o.replace("{mod}",al).replace("{enter}",t.enter).replace("{newline}",t.newline);an.textContent=Er(t.hintIdle);let jo=h("div","ra-acts"),jt=h("button","ra-send");jt.type="button",jt.innerHTML=I.corner(18),jt.title=t.send,jt.setAttribute("aria-label",t.send);let ln=h("button","ra-btn xs subtle");ln.type="button",ln.innerHTML=I.corner()+xe(t.steer),ln.title=t.steerTip;let Bn=h("button","ra-btn xs subtle",t.followUp);Bn.type="button",Bn.title=t.followUpTip;let Ht=h("button","ra-stop");Ht.type="button",Ht.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>',Ht.title=t.stop,Ht.setAttribute("aria-label",t.stop),jo.append(ln,Bn,Ht,jt);let Ho=new Map,No=(o,c)=>{let p=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${xe(c.label)}</span>`:`<span>${xe(c.label)}</span>`;o.innerHTML=p,o.classList.toggle("icon",!!(c.icon&&c.iconOnly)),o.title=c.title??c.label,o.setAttribute("aria-label",c.label),o.style.display=c.hidden?"none":"",o.disabled=!!c.disabled},ll=($??[]).map(o=>{if(o instanceof HTMLElement)return o.classList.add("ra-host"),o;let c={...o},p=h("button","ra-cbtn");return p.type="button",p.addEventListener("click",()=>c.onClick()),No(p,c),c.id&&Ho.set(c.id,{btn:p,a:c}),p}),qo=`__runapps_agent_chat:${oe}:web`,Bo=!!fe?.platformTools&&(N??typeof q.webTools!="function"),xt=(()=>{try{let o=localStorage.getItem(qo);if(o!==null)return o==="1"}catch{}return q.webTools===!0})(),lt=h("button","ra-cbtn ra-web");lt.type="button";let Wo=()=>{let o=xt?t.webOn:t.webOff;lt.innerHTML=I.globe(15)+(xt?`<span>${xe(t.web)}</span>`:""),lt.classList.toggle("on",xt),lt.classList.toggle("icon",!xt),lt.setAttribute("aria-pressed",String(xt)),lt.setAttribute("aria-label",o),lt.title=`${o}
|
|
722
|
-
${t.webHint}`};
|
|
729
|
+
`)),e}function il(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 jd=r=>r?.typed,qd=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}.`,Bd=r=>`Files the user attaches arrive under ${r}.`,Wd=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 Kd(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Hd.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 al(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function Vd(r,e,n,t){let s=new Set,i=(d,p,h)=>new Promise(w=>{if(h?.aborted){w(p);return}let k=f("section","ra-q"),v,T=()=>v.cancel(),C=U=>{h?.removeEventListener("abort",T),s.delete(v),k.remove(),t(),w(U)};v={card:k,cancel:()=>C(p)},h?.addEventListener("abort",T,{once:!0}),k.addEventListener("keydown",U=>{U.key==="Escape"&&!U.isComposing&&(U.preventDefault(),U.stopPropagation(),v.cancel())}),d(k,C),s.add(v),r.append(k),t();let R=k.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>R?.focus())}),a=(d,p,h)=>{d.append(f("div","ra-qt",p)),h&&d.append(f("div","ra-qm",h))},l=(d,p,h)=>{let w=f("button","ra-btn xs "+p,d);return w.type="button",w.addEventListener("click",h),w};return{confirm:(d,p,h={})=>i((w,k)=>{if(a(w,d,p),h.body)try{let C=h.body();C.classList.add("ra-cbody"),w.append(C)}catch(C){console.warn("agent: confirm body failed",C)}let v=f("div","ra-btns");v.append(l(h.cancel??n.decline,"ghost",()=>k(!1)));let T=h.always;T&&v.append(l(T.label,"subtle",()=>{try{T.onChoose()}catch(C){console.warn("agent: always.onChoose failed",C)}k(!0)})),v.append(l(h.ok??n.allow,h.danger?"red":"solid",()=>k(!0))),w.append(v)},!1,h.signal),select:(d,p,h={})=>i((w,k)=>{a(w,d,h.message);let v=f("div","ra-opts");if(!h.multi&&!h.allowOther){for(let S of p){let N=f("button","ra-opt");N.type="button";let P=f("div");P.append(f("span","",S.label??S.value)),S.description&&P.append(f("small","",S.description)),N.append(P),N.addEventListener("click",()=>k([S.value])),v.append(N)}w.append(v,(()=>{let S=f("div","ra-btns");return S.append(l(n.cancel,"ghost",()=>k(null))),S})());return}let T="ra_"+Math.random().toString(36).slice(2,8),C=[],R=S=>{let N=f("label","ra-opt"),P=f("input");P.type=h.multi?"checkbox":"radio",P.name=T,P.value=S.value,C.push(P);let V=f("div");V.append(f("span","",S.label??S.value)),S.description&&V.append(f("small","",S.description)),N.append(P,V),v.append(N)};p.forEach(R);let U=null;h.allowOther&&(R({value:"__other__",label:n.other}),U=f("input","ra-field"),U.type="text",U.placeholder=n.typeAnswer,U.addEventListener("focus",()=>{let S=C.find(N=>N.value==="__other__");S&&(S.checked=!0)}),v.append(U)),w.append(v);let E=f("div","ra-btns");E.append(l(n.cancel,"ghost",()=>k(null)),l(n.ok,"solid",()=>{let S=C.filter(N=>N.checked).map(N=>N.value==="__other__"?U?.value.trim()??"":N.value).filter(Boolean);S.length&&k(S)})),w.append(E)},null,h.signal),input:(d,p={})=>i((h,w)=>{a(h,d,p.message);let k=p.multiline?f("textarea","ra-field"):f("input","ra-field");p.multiline||(k.type="text"),p.placeholder&&(k.placeholder=p.placeholder),p.initial&&(k.value=p.initial),k.addEventListener("keydown",T=>{let C=T;C.key==="Enter"&&!C.isComposing&&(!p.multiline||C.metaKey||C.ctrlKey)&&(C.preventDefault(),w(k.value))}),h.append(k);let v=f("div","ra-btns");v.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(k.value))),h.append(v)},null,p.signal),notify(d,p="info"){let h=f("div","ra-toast "+p,d);e.append(h),setTimeout(()=>h.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 Gd=new Set(["read_file","write_file","edit_file"]),ll=async(r,e)=>{try{return await r.exists(e)&&!await r.isFolder(e)}catch{return!1}},Wo=r=>`__runapps_agent_chat:${r}:last`;function Zd(r){try{return localStorage.getItem(Wo(r))}catch{return null}}function cl(r,e){try{e?localStorage.setItem(Wo(r),e):localStorage.removeItem(Wo(r))}catch{}}function gl(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)");ul();let n=Ed(e.locale),t=Md[n],{toolSettings:s,client:i,provider:a,agent:l,workspace:d,resume:p,palette:h,vars:w,className:k,debug:v,settings:T,skillsMenu:C,title:R,placeholder:U,emptyState:E,suggestions:S,sessions:N,locale:P,theme:V,showUsage:se,attachments:J,uploadsDir:fe,onOpenFile:pe,onLink:Ce,onSession:Se,files:oe,headerActions:ye,headerEnd:Ae,settingsTabs:Oe,composerTop:_e,composerActions:$,permissionsSetting:H,rewindState:W,nextPrompt:ne,webSearch:j,...q}=e,ce="/"+(fe??"/uploads").replace(/^\/+|\/+$/g,""),me=a?ot(a):i?ot(i):l?.provider??null,ae=me?.name??q.appName??"app",ee=f("div","ra-chat");k&&ee.classList.add(...k.split(/\s+/).filter(Boolean));let $e=V??"auto",it=h??"claude",Hn=w,rn=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,sn=[],jn=()=>{let o=$e==="auto"?rn?.matches?"dark":"light":$e;ee.dataset.theme=$e,ee.dataset.scheme=o,typeof it=="string"?ee.dataset.palette=it:delete ee.dataset.palette;for(let g of sn)ee.style.removeProperty(g);sn=[];let c=g=>{for(let[m,y]of Object.entries(g??{}))if(y!==void 0){let x=nl(m);ee.style.setProperty(x,y),sn.push(x)}};typeof it!="string"&&c(it[o]);let u=Hn;u&&("light"in u||"dark"in u)?c(u[o]):c(u)};jn();let qn=()=>{$e==="auto"&&jn()};rn?.addEventListener?.("change",qn);let xe=f("div","ra-head"),Be=f("div","ra-title",R===!1?"":R||q.appName||t.assistant),Nt=f("span","ra-badge"),tt=f("button","ra-btn ghost");tt.type="button",tt.innerHTML=I.bug()+`<span>${ve(t.debug)}</span>`;let Ne=f("button","ra-btn ghost");Ne.type="button",Ne.innerHTML=I.folder()+`<span>${ve(t.files)}</span>`;let nt=f("button","ra-btn ghost");nt.type="button",nt.innerHTML=I.puzzle()+`<span>${ve(t.skills)}</span>`;let Bn=(o,c)=>{let u=f("b","ra-cnt");return u.style.display="none",o.append(u),g=>{u.textContent=String(g),u.style.display=g?"":"none",o.title=g?`${c} \xB7 ${g}`:c}},on=Bn(nt,t.skills),Je=f("button","ra-btn ghost");Je.type="button",Je.innerHTML=I.hist()+`<span>${ve(t.history)}</span>`;let Et=Bn(Je,t.history),Ie=f("button","ra-btn ghost");Ie.type="button",Ie.innerHTML=I.plus()+`<span>${ve(t.newChat)}</span>`;let We=f("button","ra-btn ghost");We.type="button",We.innerHTML=I.eraser()+`<span>${ve(t.clearChat)}</span>`,We.style.display="none";let Ke=!1,an=()=>{We.style.display=Ke&&F?.messages.length?"":"none"},Ve=f("button","ra-btn ghost ra-usebtn");Ve.type="button",Ve.style.display="none";let Xe=f("button","ra-btn ghost");Xe.type="button",Xe.innerHTML=I.gear(),Xe.title=t.settings,Xe.setAttribute("aria-label",t.settings);for(let[o,c]of[[tt,t.debug],[Ne,t.files],[nt,t.skills],[Je,t.history],[Ie,t.newChat],[We,t.clearChat]])o.setAttribute("aria-label",c),o.title||(o.title=c);for(let o of[...ye??[],...Ae??[],..._e?[_e]:[],...E instanceof HTMLElement?[E]:[]])o.classList.add("ra-host");xe.append(Be,Nt,f("span","ra-sp"),Ve,tt,Ne,nt,Je,Ie,We,...ye??[],Xe,...Ae??[]),R===!1&&(xe.style.display="none");let Ye=f("div","ra-log"),Wn=f("div","ra-col");Ye.append(Wn);let Pr=f("div","ra-ask"),ln=f("div","ra-col");Pr.append(ln);let Ht=f("div","ra-status");Ht.style.display="none";let Kn=f("div","ra-comp"),cn=f("div","ra-col"),L=f("div","ra-alert");L.style.display="none",L.setAttribute("role","alert");let K=f("div","ra-queue");K.style.display="none";let de=f("div","ra-box"),Z=f("div","ra-cmds");Z.style.display="none";let z=f("textarea");z.rows=2,z.setAttribute("aria-label","Message");let be=f("div","ra-files");be.style.display="none";let Qe=f("div","ra-bar"),Vn=f("div","ra-left"),at=f("button","ra-attach");at.type="button",at.innerHTML=I.clip(),at.title=t.attach,at.setAttribute("aria-label",t.attach);let rt=f("input");rt.type="file",rt.multiple=!0,rt.style.display="none",J===!1&&(at.style.display="none");let dn=f("span","ra-hint"),bl=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",_r=o=>o.replace("{mod}",bl).replace("{enter}",t.enter).replace("{newline}",t.newline);dn.textContent=_r(t.hintIdle);let Vo=f("div","ra-acts"),jt=f("button","ra-send");jt.type="button",jt.innerHTML=I.corner(18),jt.title=t.send,jt.setAttribute("aria-label",t.send);let un=f("button","ra-btn xs subtle");un.type="button",un.innerHTML=I.corner()+ve(t.steer),un.title=t.steerTip;let Gn=f("button","ra-btn xs subtle",t.followUp);Gn.type="button",Gn.title=t.followUpTip;let qt=f("button","ra-stop");qt.type="button",qt.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>',qt.title=t.stop,qt.setAttribute("aria-label",t.stop),Vo.append(un,Gn,qt,jt);let Go=new Map,Zo=(o,c)=>{let u=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${ve(c.label)}</span>`:`<span>${ve(c.label)}</span>`;o.innerHTML=u,o.classList.toggle("icon",!!(c.icon&&c.iconOnly)),o.title=c.title??c.label,o.setAttribute("aria-label",c.label),o.style.display=c.hidden?"none":"",o.disabled=!!c.disabled},xl=($??[]).map(o=>{if(o instanceof HTMLElement)return o.classList.add("ra-host"),o;let c={...o},u=f("button","ra-cbtn");return u.type="button",u.addEventListener("click",()=>c.onClick()),Zo(u,c),c.id&&Go.set(c.id,{btn:u,a:c}),u}),Jo=`__runapps_agent_chat:${ae}:web`,Xo=!!me?.platformTools&&(j??typeof q.webTools!="function"),xt=(()=>{try{let o=localStorage.getItem(Jo);if(o!==null)return o==="1"}catch{}return q.webTools===!0})(),lt=f("button","ra-cbtn ra-web");lt.type="button";let Yo=()=>{let o=xt?t.webOn:t.webOff;lt.innerHTML=I.globe(15)+(xt?`<span>${ve(t.web)}</span>`:""),lt.classList.toggle("on",xt),lt.classList.toggle("icon",!xt),lt.setAttribute("aria-pressed",String(xt)),lt.setAttribute("aria-label",o),lt.title=`${o}
|
|
730
|
+
${t.webHint}`};Yo(),Xo||(lt.style.display="none");let Qo=o=>{Xo&&o.configure({webTools:xt})};lt.addEventListener("click",()=>{xt=!xt;try{localStorage.setItem(Jo,xt?"1":"0")}catch{}Yo();for(let o of He.values())Qo(o)}),Vn.append(at,lt,...xl,dn),Qe.append(Vn,Vo),de.append(Z,be,z,Qe,rt);let vl=f("div","ra-drop",t.drop);cn.append(L,K,..._e?[_e]:[],de),Kn.append(cn);let ei=f("div","ra-toasts"),ti=f("div","ra-col");ti.append(Ht);let Rr=f("div","ra-main"),Us=f("div","ra-chatcol"),ni=f("div","ra-jumpwrap"),vt=f("button","ra-jump");vt.type="button",vt.innerHTML=I.arrowDown(),vt.title=t.jumpEnd,vt.setAttribute("aria-label",t.jumpEnd),vt.tabIndex=-1,ni.append(vt),Us.append(Ye,ni,Pr,ti,Kn),Rr.append(Us),ee.append(xe,Rr,ei,vl),r.replaceChildren(ee);let F,we=new Dn(Ye,Wn,{estimate:96,overscan:400,rowClass:"ra-row",onFollow:o=>{let c=!o&&Ye.scrollHeight-Ye.clientHeight>40;vt.classList.toggle("show",c),vt.tabIndex=c?0:-1}});vt.addEventListener("click",()=>we.scrollToBottom()),Ye.addEventListener("click",o=>{let c=o.target.closest("summary");c&&Ye.contains(c)&&we.pin(c)},!0);let X=null,At=null,Bt=new Map,Fs=new WeakMap,Zn=new Map,Or=[],ct=0,Jn=null,Xn=[],Ee=null,Dr=!0,ri=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{ee.dataset.short=ee.clientHeight&&ee.clientHeight<420?"1":""});ri?.observe(ee);let si=0,G=Vd(ln,ei,t,()=>{let o=ln.childElementCount;ee.dataset.asking=o?"1":"",o<si?we.scrollToBottom():we.schedule(),si=o}),kl=3,He=new Map,zr=new Map,Yn=new Map,Wt=new Set,$t=new Map,Ns=(o,c)=>new Promise(u=>{if(F?.id===o){u(!0);return}if(c?.aborted){u(!1);return}Wt.add(o);let g=$t.get(o)??[],m=x=>{c?.removeEventListener("abort",y),u(x)},y=()=>{let x=$t.get(o);if(x){let b=x.indexOf(m);b>=0&&x.splice(b,1),x.length||($t.delete(o),Wt.delete(o))}m(!1),Kt()};c?.addEventListener("abort",y,{once:!0}),g.push(m),$t.set(o,g),Kt()}),Hs=(o,c=!0)=>{let u=$t.get(o);$t.delete(o),Wt.delete(o),u?.forEach(g=>g(c))},Tl=o=>({confirm:async(c,u,g)=>await Ns(o,g?.signal)?G.confirm(c,u,g):!1,select:async(c,u,g)=>await Ns(o,g?.signal)?G.select(c,u,g):null,input:async(c,u)=>await Ns(o,u?.signal)?G.input(c,u):null,notify:(c,u)=>G.notify(c,u)}),oi=o=>!!o.workspace&&typeof d=="function"&&!o.workspace.root,js=()=>[...He.values()].filter(o=>o!==F&&(o.busy||o.queued.length>0||Wt.has(o.id))),Ir=o=>{let c=Qt({v:2,id:o.id,messages:o.messages,usage:o.usage,droppedTurns:0,savedAt:0});return c===It?t.untitled:c.length>40?c.slice(0,37)+"\u2026":c},Kt=()=>Je.classList.toggle("ra-bg",js().length>0),pn=null,qs=()=>{pn&&clearTimeout(pn),pn=setTimeout(async()=>{pn=null;let o=F?.workspace;if(!o||l){Et(0);return}try{let u=(await o.sessions.list()).filter(g=>g.id!==F.id).length;F?.workspace===o&&Et(u?u+1:0)}catch{}},50)},ii=async(o,c)=>{let u=Fn(c);if(!(!o.workspace||!u)){if(W)try{await Dd(o.workspace,u,await W.take())}catch(g){console.warn("agent: rewindState.take failed",g)}if(oi(o))try{await Rd(o.workspace,u)}catch(g){console.warn("agent: checkpoint failed",g)}}},Sl=o=>{if(zr.has(o.id))return;let c=[];c.push(o.on("run_end",()=>{F!==o&&(G.notify(`${Ir(o)} \xB7 ${t.finished}`),setTimeout(()=>{Dr&&(F!==o&&!o.busy&&!o.queued.length&&!Wt.has(o.id)&&(He.delete(o.id),Ur(o),Yr(o)),Kt())},50))})),c.push(o.on("run_start",u=>{Kt(),u.message&&ii(o,u.message)})),zr.set(o.id,c),Kt()},Ur=o=>{zr.get(o.id)?.forEach(c=>c()),zr.delete(o.id)},je=Xa({t,root:ee,editorHost:Us,notify:(o,c)=>G.notify(o,c),onChange:()=>{Pt()},onShow:o=>Ne.classList.toggle("on",o)});Rr.append(je.el);let st=Ya({t,root:ee,onShow:o=>tt.classList.toggle("on",o)});Rr.append(st.el);let Vt=!!v,Fr=()=>{if(tt.style.display=Vt?"":"none",ee.dataset.debug=Vt?"1":"",Vt){for(let o of He.values())o!==F&&st.setAgent(o);F&&st.setAgent(F)}else{st.close();for(let o of He.values())st.forget(o)}};Fr(),Ne.addEventListener("click",()=>{st.visible&&(st.close(),Fr()),je.toggle()}),tt.addEventListener("click",async()=>{je.visible&&await je.close(),!je.visible&&(st.toggle(),Fr())});let Qn=o=>{pe?pe(o):je.open(o)},ai=async o=>{let c=F?.workspace;if(c&&!await c.exists(o)){G.notify(`${t.rewindGoneFile.replace("{path}",o)}`,"warning");return}Qn(o)},kt=f("div","ra-empty"),Bs={render:()=>kt},li=()=>{if(E!==null){if(kt.replaceChildren(),kt.classList.toggle("start",typeof E=="object"&&!(E instanceof HTMLElement)&&E?.align==="start"),E instanceof HTMLElement)kt.append(E);else if(E&&typeof E=="object"){if(E.icon){let o=f("div","ra-empty-icon");typeof E.icon=="string"?o.innerHTML=E.icon:o.append(E.icon),kt.append(o)}E.title&&kt.append(f("h3","ra-empty-title",E.title)),E.text&&kt.append(f("p","ra-empty-text",E.text))}else kt.append(f("div","",typeof E=="string"?E:t.empty));if(S?.length){let o=f("div","ra-sugs");for(let c of S){let u=typeof c=="string"?c:c.label,g=typeof c=="string"?c:c.prompt,m=f("button","",u);m.type="button",g!==u&&(m.title=g),m.addEventListener("click",()=>{z.value=g,z.focus(),Ze()}),o.append(m)}kt.append(o)}we.rows.includes(Bs)||we.push(Bs)}},Cl=()=>we.remove(Bs),Tt=o=>{Cl(),we.push(o)},ci=(o,c,u)=>{let g=f("span","ra-chip"),m=o.lastIndexOf("."),y=m>0&&o.length-m<=6?o.slice(m):"";if(u){let b=f("img");b.src=u,b.alt="",g.append(b)}else g.append(f("span","ra-ext",(y.slice(1)||"file").slice(0,4)));let x=f("span","ra-cn");return x.title=o,x.append(f("span","st",y?o.slice(0,m):o)),y&&x.append(f("span","ex",y)),g.append(x),c&&g.append(f("small","",c.replace(/\s+(?=[KMG]?B$)/,""))),g},di=(o,c,u)=>{let g=f("span","ra-chip ra-ctx"),m=f("span","ra-ctxi");m.innerHTML=u??I.pointer(15);let y=f("span","ra-cn");return y.title=c??o,y.append(f("span","st",o)),g.append(m,y),g},ui=o=>Rs(o).flatMap(c=>c.startsWith(Nn)?[{label:c.slice(Nn.length).split(`
|
|
723
731
|
`)[0],text:c.includes(`
|
|
724
732
|
`)?c.slice(c.indexOf(`
|
|
725
|
-
`)+1):""}]:[]),
|
|
726
|
-
`).slice(1)){let
|
|
727
|
-
`),update:()=>{},render:()=>
|
|
728
|
-
`).slice(1)){let _=
|
|
733
|
+
`)+1):""}]:[]),Ml=(o,c)=>{let u=f("div","ra-user"),g=f("div","ra-bubble"),m=Rs(o),y=c.text;g.textContent=y.length>4e3?y.slice(0,4e3)+"\u2026":y;let x=m.find(B=>B.startsWith(Ft));if(x){let B=f("div","ra-files");for(let te of x.split(`
|
|
734
|
+
`).slice(1)){let le=il(te);if(!le)continue;let ge=ci(le.ref.replace(/^.*\//,""),le.size,null);if(le.ref.startsWith("/")){let De=le.ref;ge.classList.add("ra-chip-link"),ge.title=`${t.open} ${De}`,ge.setAttribute("role","button"),ge.tabIndex=0,ge.addEventListener("click",()=>{ai(De)}),ge.addEventListener("keydown",Rt=>{Rt.key==="Enter"&&ai(De)})}B.append(ge)}B.childElementCount&&g.append(B)}let b=ui(o);if(b.length){let B=f("div","ra-files");for(let te of b)B.append(di(te.label));g.append(B)}for(let B of Js(o)){let te=f("img");te.src=B,te.alt="",g.append(te)}let A=f("div","ra-uf"),M=f("span","ra-ut"),_=f("button","ra-ib");_.type="button",_.innerHTML=I.copy(13),_.title=t.copy,_.setAttribute("aria-label",t.copy),_.addEventListener("click",()=>{navigator.clipboard?.writeText(c.text).then(()=>G.notify(t.copied))});let O=f("button","ra-ib");return O.type="button",O.innerHTML=I.undo(),O.title=t.rewind,O.setAttribute("aria-label",t.rewind),O.addEventListener("click",()=>{Al(c)}),A.append(M,_,O),u.addEventListener("mouseenter",()=>c.update()),c.update=()=>{let B=Fn(c.msg);M.innerHTML=I.checks()+`<span>${ve(B?Pd(B,t):t.sent)}</span>`,O.disabled=!c.msg},c.update(),u.append(g,A),u},Ws=(o,c)=>{let g=Rs(o).filter(x=>!x.startsWith(Ft)&&!x.startsWith(Nn)&&!x.startsWith("<file name=")),m=jd(c),y={msg:c,text:m??g.join(`
|
|
735
|
+
`),update:()=>{},render:()=>Ml(o,y)};return y},dt=null,er=(o,c)=>{bi(Fn(c)??Date.now());let u=Ws(o,c);return Tt(u),we.scrollToBottom(),u},El=async(o,c,u={title:t.rewindTitle,message:t.rewindMsg,ok:t.rewind})=>{let g=f("input");g.type="checkbox",g.checked=!!o;let m=f("input");m.type="checkbox",m.checked=!0;let y=[];if(c&&W){let b=f("label","ra-ck");b.append(m,f("span","",W.label)),y.push(b)}if(o){let b=f("label","ra-ck");b.append(g,f("span","",t.rewindFiles));let A=o.files.reduce((M,_)=>M+(typeof _.data=="string"?new TextEncoder().encode(_.data).length:_.data.byteLength),0);y.push(b,f("div","ra-dn",t.rewindSnapshot.replace("{n}",String(o.files.length)).replace("{size}",Un(A)).replace("{time}",fl(o.at))+(o.partial?` ${t.rewindPartial}`:"")))}return await Ls(ee,{title:u.title,message:u.message,body:y,ok:u.ok,cancel:t.cancel,focus:"ok"})?{files:!!o&&g.checked,host:!!c&&m.checked}:null},Al=o=>o.msg?pi(o.msg,o.text):Promise.resolve(),pi=async(o,c,u=!1)=>{if(!F)return;let g=F,m={msg:o,text:c},y=g.messages.indexOf(m.msg);if(y<0){G.notify(t.rewindGone,"warning");return}let x=g.workspace,b=Fn(m.msg),A=x&&b&&oi(g)?await x.getData(Os(b)):void 0,M=x&&b&&W?await x.getData(zs(b)):void 0,_=await El(A,M,u?{title:t.regenTitle,message:t.regenMsg,ok:t.regen}:void 0);if(!_||F!==g)return;let O=!1;try{if(g.busy&&(G.cancelAll(),await g.abort()),await g.rewind(y),O=!0,_.files&&x&&A)try{await Id(x,A)}catch(B){G.notify(B.message,"error")}if(_.host&&M&&W)try{await W.restore(M.value)}catch(B){G.notify(B.message,"error")}x&&b&&(Od(x,b).catch(()=>{}),zd(x,b).catch(()=>{}))}catch(B){G.notify(B.message,"error")}finally{F===g&&(hn(g.messages),mt(g),je.refresh(),Pt())}!O||F!==g||(z.value=m.text,z.focus(),Ze(),await mi(m.msg),u&&await gn("prompt"))},fi=o=>o.role==="user"&&!(typeof o.content=="string"&&(ze(o)!==null||o.content.startsWith("[environment]"))),Nr=(o,c)=>{let u=o.messages,g=u.indexOf(c);if(g<0)return null;let m=g;for(;m>=0&&!fi(u[m]);)m--;let y=g+1;for(;y<u.length&&!fi(u[y]);)y++;return m<0?null:{start:m,end:y}},hi=o=>{let c=f("div","ra-af"),u=(b,A,M)=>{let _=f("button","ra-ib");return _.type="button",_.innerHTML=b,_.title=A,_.setAttribute("aria-label",A),_.addEventListener("click",M),_},g=u(I.copy(13),t.copy,()=>{let b=F,A=b&&Nr(b,o),M=A?b.messages.slice(A.start+1,A.end).filter(_=>_.role==="assistant").map(_=>nn(_.content).trim()).filter(Boolean):[nn(o.content).trim()];navigator.clipboard?.writeText(M.at(-1)??"").then(()=>G.notify(t.copied))}),m=u(I.refresh(13),t.regen,()=>{let b=F,A=b&&Nr(b,o);if(!b||!A){G.notify(t.rewindGone,"warning");return}let M=b.messages[A.start];pi(M,Ws(M.content,M).text,!0)}),y=u(I.trash(13),t.delTurn,()=>{(async()=>{let b=F;if(!b||!Nr(b,o)){G.notify(t.rewindGone,"warning");return}if(!await bt(ee,t.delTurnTitle,t.delTurnMsg,{danger:!0,ok:t.delTurn,cancel:t.cancel}))return;let A=F===b?Nr(b,o):null;if(A)try{b.busy&&(G.cancelAll(),await b.abort()),await b.remove(A.start,A.end)}catch(M){G.notify(M.message,"error")}})()});c.append(g,m,y);let x=o.runUsage;if(x&&x.calls){let b=_=>{A.textContent=t.replyCost.replace("{cost}",qo(x.total_cost,_))},A=f("span","ra-cost");b(Xr);let M=F;Xr===void 0&&M&&M.modelInfo().then(_=>{_?.price?.currency&&b(_.price.currency)}).catch(()=>{}),A.title=t.replyUsage.replace("{in}",qe(x.prompt_tokens)).replace("{out}",qe(x.completion_tokens)).replace("{calls}",String(x.calls)),c.append(A)}return c},mi=async o=>{if(typeof o.content!="string"&&!Array.isArray(o.content))return;let c=Array.isArray(o.content)?o.content:Rs(o.content).map(M=>({type:"text",text:M}));for(let M of ui(c).reverse())Pi({label:M.label,text:M.text});let u=c.find(M=>M.type==="text"&&M.text.startsWith(Ft));if(!u)return;let g=F?.workspace,m=new Map;for(let M of c)if(M.type==="text"){let _=/^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec(M.text);_&&m.set(_[1],_[2])}let y=c.flatMap(M=>M.type==="image_url"&&M.image_url.url.startsWith("data:")?[M.image_url.url]:[]),x=[],b=[],A=[];for(let M of u.text.split(`
|
|
736
|
+
`).slice(1)){let _=il(M);if(!_)continue;let{ref:O,type:B}=_,te=O.replace(/^.*\//,"");if(O.startsWith("/")&&g)try{let le=await g.read(O);x.push(new File([le.data],te,{type:le.contentType||B})),b.push(O)}catch{A.push(O)}else if(m.has(te))x.push(new File([m.get(te)],te,{type:B})),b.push(void 0);else if(/^image\//.test(B)&&y.length){let le=await(await fetch(y.shift())).blob();x.push(new File([le],te,{type:B})),b.push(void 0)}else A.push(te)}x.length&&await Wr(x,b),A.length&&G.notify(t.rewindGoneFile.replace("{path}",A.join(", ")),"warning")},gi=()=>{let o=f("div","ra-asst"),c=f("div","ra-body");return o.append(c),{render:()=>o,el:o,body:c,text:null,think:null,thinkBody:null,md:"",reasoning:""}},$l=o=>{let c=Math.max(1,Math.round(o/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)))},yi=(o,c)=>{if(o.querySelector(":scope>.ra-work"))return;let u=Array.from(o.children),m=u.at(-1)?.classList.contains("ra-md")?u.slice(0,-1):u;if(!m.length)return;let y=f("details","ra-work"),x=f("summary");x.append(f("span","",c!==void 0&&c>0?t.worked.replace("{t}",$l(c)):t.workedNoTime));let b=f("span","ra-chev");b.innerHTML=I.chev(13),x.append(b),x.addEventListener("click",()=>we.pin(x));let A=f("div","ra-wb");A.append(...m),y.append(x,A),o.prepend(y)},tr=0,nr=()=>{if(X){if(Vs(X),!X.body.childElementCount){we.remove(X),X=null;return}rr(!0),yi(X.body,tr?Date.now()-tr:void 0),X=null,we.schedule()}},Hr=()=>(X||(X=gi(),Tt(X)),X),ut=(o=t.waiting,c)=>{let u=Hr();u.pending||(u.pending=f("div","ra-pending"),u.pending.append(f("span","",o)));let g=u.pending;g.firstElementChild.textContent=o;let m=g.querySelector(".ra-lpv"),y=c?.text.trim()??"";y?(m||(m=f("div","ra-lpv"),m.append(f("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(),u.body.lastElementChild!==g&&u.body.append(g),we.schedule()},wi=o=>{let c=o.lastElementChild;return c?.classList.contains("ra-pending")?c.previousElementSibling:c},Ks=(o,c)=>{let u=o.lastElementChild;u?.classList.contains("ra-pending")?o.insertBefore(c,u):o.append(c)},Ll=(o,c)=>{let u=c&&typeof c=="object"?c:{};return o==="run_js"&&typeof u.code=="string"?{text:u.code,code:!0,head:!0}:o==="write_file"&&typeof u.content=="string"?{text:u.content,head:!0}:o==="edit_file"&&Array.isArray(u.edits)?{text:u.edits.map(g=>g&&typeof g=="object"?String(g.newText??""):"").join(`
|
|
729
737
|
\u2026
|
|
730
|
-
`),head:!0}:o==="edit_file"&&typeof p.newText=="string"?{text:p.newText,head:!0}:{text:Do(o,c),head:!0}},Ns=(o=X)=>{o?.pending&&(o.pending.remove(),o.pending=null)},bl=15*6e4,dn=0,xl=o=>{let c=new Date(o),p=new Date,m=c.toLocaleTimeString(n==="zh"?"zh-CN":void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}),g=b=>new Date(b.getFullYear(),b.getMonth(),b.getDate()).getTime(),y=Math.round((g(p)-g(c))/864e5);return y===0?`${t.today} ${m}`:y===1?`${t.yesterday} ${m}`:`${c.toLocaleDateString(n==="zh"?"zh-CN":void 0,c.getFullYear()===p.getFullYear()?{month:"short",day:"numeric"}:{year:"numeric",month:"short",day:"numeric"})} ${m}`},pi=o=>{if(o){if(!dn||o-dn>=bl){let c=h("div","ra-time",xl(o));Tt({render:()=>c,el:c})}dn=o}},fi=(o,c)=>{let p=h("details","ra-think"),m=h("summary");m.innerHTML=`<span class="ra-chev">${I.chev(13)}</span>${I.brain()}<span>${xe(c?t.thought:t.thinking)}</span>`;let g=h("div","ra-think-body",o);return p.append(m,g),[p,g]},hi=o=>{let c=F?.workspace;if(c)for(let p of Array.from(o.querySelectorAll("code"))){if(p.closest("pre")||p.classList.contains("ra-path"))continue;let m=p.textContent?.trim()??"";!/^\/[^\s`'"<>]+$/.test(m)||m.length>200||Ja(c,m).then(g=>{g&&!p.classList.contains("ra-path")&&(p.classList.add("ra-path"),p.dataset.path=m,p.title=t.open,p.insertAdjacentHTML("beforeend",I.file(11)))})}},vl=(o,c)=>{_n(o,c,!1),hi(o)},Qn=o=>{At!==null&&(clearTimeout(At),At=null),X&&(X.text&&(X.drawn!==X.md||X.drawnFinal!==o)&&(_n(X.text,X.md,!o),X.drawn=X.md,X.drawnFinal=o,o&&hi(X.text)),X.thinkBody&&(X.thinkBody.textContent=X.reasoning),X.think&&o?(X.think.querySelector("summary span:last-child").textContent=t.thought,X.think.style.display=""):X.pending&&X.reasoning&&!X.text&&ut(t.thinking.replace(/…$/,""),{text:X.reasoning}),ye.schedule())},gi=()=>{At===null&&(At=window.setTimeout(()=>{At=null,Qn(!1)},100))},er=o=>F?.tools?.find(c=>c.name===o)?.display,Ir=o=>{if(o)try{return o()}catch{return}},qs=(o,c)=>{let p=er(o),m=Ir(p?.label&&(()=>p.label(c)));return typeof m=="string"&&m.trim()?m:void 0},mi=(o,c)=>{let p=er(o.name);if(!p?.render)return;let m=Ir(()=>p.render({args:o.args,...c})),g=o.el.querySelector("summary");if(g.querySelector(".ra-tx")?.remove(),!(m instanceof HTMLElement))return;let y=h("div","ra-tx ra-host");y.addEventListener("click",x=>x.preventDefault()),y.append(m),g.append(y)},yi=(o,c)=>{let p=h("details","ra-tool");Os.set(p,{name:o,args:c});let m=h("summary"),g=er(o),y=qs(o,c),x=h("span","ra-ticon");x.innerHTML=g?.icon??(md[o]??I.wrench)();let b=h("span","ra-tend");b.innerHTML='<span class="ra-spin"></span>',m.innerHTML=`<span class="ra-chev">${I.chev()}</span>`;let A=y??(o==="run_js"?t.runCode:void 0),C=h("span","ra-tname",A??o);A&&(C.title=o,C.classList.add("own")),m.append(x,C,h("span","ra-tsum",y?"":Do(o,c)),b);let _=h("div","ra-tbody"),O=h("pre","",o==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));_.append(h("div","ra-tlabel",t.args),O),p.append(m,_);let B={el:p,name:o,args:c,end:b,body:_,update:null,result:null};return mi(B,{status:"running"}),B},wi=o=>{let c=ui(o);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let p=h("details","ra-tg"),m=h("summary"),g=h("div","ra-tgb");return p.append(m,g),Hs(o,p),g},kl=o=>{let c=[],p=new Map;for(let m of o){let g=qs(m.name,m.args);if(g!==void 0){let A=`Own:${g}`;p.has(A)||(c.push(A),p.set(A,0)),p.set(A,p.get(A)+1);continue}let y=Ka[m.name]??"Other",x=y==="Other"?`Other:${m.name}`:y;p.has(x)||(c.push(x),p.set(x,y==="Read"||y==="Write"||y==="Edit"||y==="Delete"?new Set:0));let b=p.get(x);b instanceof Set?b.add(Va(m.args)??String(b.size)):p.set(x,b+1)}return c.map(m=>{let g=p.get(m),y=String(g instanceof Set?g.size:g);return m.startsWith("Own:")?g===1?m.slice(4):`${m.slice(4)} \xD7${y}`:m.startsWith("Other:")?t.actOther.replace("{name}",m.slice(6)):t[`act${m}`].replace("{n}",y)}).join(n==="zh"?"\uFF0C":", ")},bi=(o,c)=>{let p=qs(o.name,o.args);if(p!==void 0)return{verb:p,what:""};let m=Ka[o.name]??"Other",g=Va(o.args),y=t[`ing${m}`];return m==="Other"?{verb:`${y} ${o.name}`,what:c.querySelector(".ra-tsum")?.textContent??""}:m==="Ask"?{verb:y,what:""}:g&&m!=="Search"?{verb:y,what:g.slice(g.lastIndexOf("/")+1)||g,title:g}:{verb:y,what:c.querySelector(".ra-tsum")?.textContent??""}},Bs=o=>{let c=o.closest(".ra-tg");if(!c)return;let p=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),m=p.filter(b=>b.querySelector(".ra-tend .ra-spin")),g=p.filter(b=>b.classList.contains("fail")).length,y=c.querySelector("summary");if(y.replaceChildren(),m.length){let b=m[m.length-1],A=bi(Os.get(b)??{name:b.querySelector(".ra-tname")?.textContent??"",args:void 0},b);y.append(h("span","ra-spin"));let C=h("span","ra-tgt");C.append(`${A.verb} `),A.what&&C.append(h("code","",A.what)),A.title&&(C.title=A.title),y.append(C)}else{let b=p.map(_=>Os.get(_)).filter(_=>!!_),A=b.length?kl(b):p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),C=h("span","ra-tgt",A);C.title=p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),y.append(C)}g&&y.append(h("span","ra-tgf",t.toolsFailed.replace("{n}",String(g))));let x=h("span","ra-chev");x.innerHTML=I.chev(12),y.append(x)},Tl=(o,c,p,m,g)=>{let y=yi(c,p);return g?(g.nested||(g.nested=h("div","ra-tnest"),g.body.append(g.nested)),g.nested.append(y.el)):wi(m).append(y.el),Nt.set(o,y),Bs(y.el),ye.schedule(),y},Ws=o=>Array.isArray(o)?o.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:)/.test(c.image_url.url)?[c.image_url.url]:[]):[],xi=async o=>{let c=F?.workspace,p=er(o.name),m=o.args,g=p?.file?Ir(()=>p.file(o.args)):Dd.has(o.name)&&m&&typeof m=="object"&&typeof m.path=="string"?m.path:null;if(!c||!g||!await Ja(c,g))return;let y=h("div","ra-tacts"),x=h("button","ra-open",`${t.open} ${g}`);if(x.type="button",x.addEventListener("click",()=>Zn(g)),y.append(x),!ue){let b=h("button","ra-open",t.download);b.type="button",b.addEventListener("click",()=>{He.download(g)}),y.append(b)}o.body.querySelector(":scope>pre")?.after(y),ye.schedule()},vi=(o,c,p,m,g=[],y)=>{let x=c==="ok",b=c==="error"||c==="blocked";o.end.replaceChildren();let A=er(o.name),C=Ir(A?.outcome&&(()=>A.outcome({args:o.args,status:c,result:p,details:y})));typeof C=="string"&&C?o.end.append(h("span","ra-tout",C)):m!==void 0&&o.end.append(h("span","",`${Math.round(m)}ms`));let _=h("span",x?"ok":b?"fail":"");x?_.innerHTML=I.check():c==="error"?_.innerHTML=I.xcircle():c==="blocked"?(_.innerHTML=I.ban(),_.title=t.blocked):_.textContent=t[c]??c,o.end.append(_),o.el.classList.toggle("fail",b),mi(o,{status:c,result:p,details:y}),o.update?.remove(),x&&(o.el.open?xi(o):o.el.addEventListener("toggle",()=>{xi(o)},{once:!0})),o.result||(o.result=h("pre",""),o.body.append(h("div","ra-tlabel",c==="error"?t.error:t.result),o.result));let O=g.length?p.replace(/^\[image_url\]$/gm,"").trim():p;if(o.result.textContent=O.length>2e4?O.slice(0,2e4)+"\u2026":O||t.emptyResult,g.length&&!o.body.querySelector(".ra-timgs")){let B=h("div","ra-timgs");for(let ee of g.slice(0,4)){let ie=h("img");ie.src=ee,ie.alt=t.result,ie.addEventListener("load",()=>ye.schedule()),B.append(ie)}o.body.append(B)}Bs(o.el),ye.schedule()},Sl=(o,c,p)=>{let m=h("div","ra-card"),g=h("div","ra-ct"+(c?"":" only"));if(g.innerHTML=I.layers()+`<span>${xe(o)}</span>`,m.append(g),c){let y=h("div","ra-md");_n(y,c,!1),m.append(y)}if(p){let y=h("button","ra-btn xs subtle",p.label);y.type="button",y.addEventListener("click",()=>{y.disabled=!0,p.onClick()}),m.append(y)}return m},tr=(o,c,p)=>{Tt({render:()=>Sl(o,c,p)}),ye.schedule()},Cl=(o,c,p)=>{let m={render:()=>{let g=h("div","ra-warn");if(g.setAttribute("role","status"),p&&(g.title=p),g.innerHTML=I.alert(14),g.append(h("span","",o)),c){let y=h("button","ra-btn xs",c.label);y.type="button",y.addEventListener("click",()=>{ye.remove(m),c.onClick()}),g.append(y)}return g}};Tt(m),ye.schedule()},Ur=(o,c)=>{let p={render:()=>{let m=h("div","ra-err",o);if(c){let g=h("button","ra-btn xs red-subtle",t.retry);g.type="button",g.addEventListener("click",()=>{ye.remove(p),c()}),m.append(g)}return m}};Tt(p),ye.schedule()},un=o=>{ye.clear(),dn=0,Nt.clear(),Wn.clear(),X=null;let c=null,p,m=(g=!1)=>{if(!c)return;let y=c;c=null;let x=!(g&&F?.busy);Tt({render:()=>{let b=ci();for(let A of y.items)if(A.kind==="think"){let[C]=fi(A.text,!0),_=b.body.lastElementChild;_ instanceof HTMLDetailsElement&&_.classList.contains("ra-tg")?_.querySelector(".ra-tgb").append(C):b.body.append(C)}else if(A.kind==="text"){let C=h("div","ra-md");vl(C,A.text),b.body.append(C)}else{let C=A.call,_=yi(C.name,C.args);wi(b.body).append(_.el),C.status?vi(_,C.status,C.result??"",void 0,C.images):(C.id&&Nt.set(C.id,_),Bs(_.el))}return x&&di(b.body,y.start!==void 0&&y.end!==void 0?y.end-y.start:void 0),x&&y.msg&&b.el.append(ai(y.msg)),b.el}})};for(let g of o)if(g.role==="user"){m();let y=typeof g.content=="string"?De(g):null;if(y!==null){tr(t.compacted,y);continue}if(typeof g.content=="string"&&g.content.startsWith("[environment]"))continue;p=Dn(g),pi(p),Tt(js(g.content,g))}else if(g.role==="assistant"){let y=Qt(g.content),x=g.reasoning_content,b=typeof x=="string"?x:"";c||(c={items:[],calls:[],start:p}),c.msg=g,c.end=Dn(g)??c.end,c.end&&(dn=c.end),b&&c.items.push({kind:"think",text:b}),y&&c.items.push({kind:"text",text:y});for(let A of g.tool_calls??[]){if(Ks.has(A.function.name))continue;let C=A.function.arguments;try{C=JSON.parse(A.function.arguments)}catch{}let _={id:A.id??"",name:A.function.name,args:C};c.items.push({kind:"call",call:_}),c.calls.push(_),_.id&&Wn.set(_.id,_)}}else if(g.role==="tool"){let y=Qt(g.content),x=c?.calls.find(b=>b.id===(g.tool_call_id??""));x&&(x.result=y,x.status=yd(y),x.images=Ws(g.content),Wn.delete(x.id))}m(!0),o.length||ti(),rn(),ye.scrollToBottom()},Lt=null,Fr=null,nr=()=>{Fr=null,Lt!==null&&(Lt=null,St(Q.dataset.busy==="1"))},Ml={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:o})=>(Fr=String(o??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},ki=[...q.tools??[],...te?[Ml]:[]],Ks=new Set(ki.filter(o=>o.display?.hidden).map(o=>o.name)),Kt=()=>{let o=Q.dataset.busy==="1",c=!!(z.value.trim()||ft.length||ht.length);jt.style.display=!o&&c?"":"none",ln.style.display=Bn.style.display=o&&c?"":"none"},St=o=>{Q.dataset.busy=o?"1":"",z.placeholder=o?Er(t.placeholderBusy):Lt??U??t.placeholder,an.textContent=Er(o?t.hintBusy:Lt?t.hintNext:t.hintIdle),Kt(),Ht.style.display=o?"":"none",pt()},Vt=!1,pt=()=>{let o=F?.queued??[];if(K.style.display=o.length?"":"none",K.replaceChildren(),!o.length){Vt=!1;return}let c=F,p=C=>Qt(C.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),m=(C,_,O)=>{let B=h("button");return B.type="button",B.innerHTML=C,B.title=_,B.setAttribute("aria-label",_),B.addEventListener("click",ee=>{ee.stopPropagation(),O()}),B},g=C=>{let _=h("span","ra-qa");return C.kind!=="steer"&&_.append(m(I.enter(),t.sendNow,()=>{c.dequeue(C.message)&&c.steer(C.message.content),pt()})),_.append(m(I.pen(),t.editQueued,()=>{c.dequeue(C.message)&&(z.value=z.value.trim()?`${p(C.message)}
|
|
731
|
-
${z.value}`:
|
|
732
|
-
[\u2026 truncated]`),
|
|
733
|
-
${
|
|
734
|
-
</file>`})}else O.text!==null&&O.text.length<=
|
|
738
|
+
`),head:!0}:o==="edit_file"&&typeof u.newText=="string"?{text:u.newText,head:!0}:{text:jo(o,c),head:!0}},Vs=(o=X)=>{o?.pending&&(o.pending.remove(),o.pending=null)},Pl=15*6e4,fn=0,_l=o=>{let c=new Date(o),u=new Date,g=c.toLocaleTimeString(n==="zh"?"zh-CN":void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}),m=b=>new Date(b.getFullYear(),b.getMonth(),b.getDate()).getTime(),y=Math.round((m(u)-m(c))/864e5);return y===0?`${t.today} ${g}`:y===1?`${t.yesterday} ${g}`:`${c.toLocaleDateString(n==="zh"?"zh-CN":void 0,c.getFullYear()===u.getFullYear()?{month:"short",day:"numeric"}:{year:"numeric",month:"short",day:"numeric"})} ${g}`},bi=o=>{if(o){if(!fn||o-fn>=Pl){let c=f("div","ra-time",_l(o));Tt({render:()=>c,el:c})}fn=o}},xi=(o,c)=>{let u=f("details","ra-think"),g=f("summary");g.innerHTML=`<span class="ra-chev">${I.chev(13)}</span>${I.brain()}<span>${ve(c?t.thought:t.thinking)}</span>`;let m=f("div","ra-think-body",o);return u.append(g,m),[u,m]},vi=o=>{let c=F?.workspace;if(c)for(let u of Array.from(o.querySelectorAll("code"))){if(u.closest("pre")||u.classList.contains("ra-path"))continue;let g=u.textContent?.trim()??"";!/^\/[^\s`'"<>]+$/.test(g)||g.length>200||ll(c,g).then(m=>{m&&!u.classList.contains("ra-path")&&(u.classList.add("ra-path"),u.dataset.path=g,u.title=t.open,u.insertAdjacentHTML("beforeend",I.file(11)))})}},Rl=(o,c)=>{zn(o,c,!1),vi(o)},rr=o=>{At!==null&&(clearTimeout(At),At=null),X&&(X.text&&(X.drawn!==X.md||X.drawnFinal!==o)&&(zn(X.text,X.md,!o),X.drawn=X.md,X.drawnFinal=o,o&&vi(X.text)),X.thinkBody&&(X.thinkBody.textContent=X.reasoning),X.think&&o?(X.think.querySelector("summary span:last-child").textContent=t.thought,X.think.style.display=""):X.pending&&X.reasoning&&!X.text&&ut(t.thinking.replace(/…$/,""),{text:X.reasoning}),we.schedule())},ki=()=>{At===null&&(At=window.setTimeout(()=>{At=null,rr(!1)},100))},sr=o=>F?.tools?.find(c=>c.name===o)?.display,jr=o=>{if(o)try{return o()}catch{return}},Gs=(o,c)=>{let u=sr(o),g=jr(u?.label&&(()=>u.label(c)));return typeof g=="string"&&g.trim()?g:void 0},Ti=(o,c)=>{let u=sr(o.name);if(!u?.render)return;let g=jr(()=>u.render({args:o.args,...c})),m=o.el.querySelector("summary");if(m.querySelector(".ra-tx")?.remove(),!(g instanceof HTMLElement))return;let y=f("div","ra-tx ra-host");y.addEventListener("click",x=>x.preventDefault()),y.append(g),m.append(y)},Si=(o,c)=>{let u=f("details","ra-tool");Fs.set(u,{name:o,args:c});let g=f("summary"),m=sr(o),y=Gs(o,c),x=f("span","ra-ticon");x.innerHTML=m?.icon??($d[o]??I.wrench)();let b=f("span","ra-tend");b.innerHTML='<span class="ra-spin"></span>',g.innerHTML=`<span class="ra-chev">${I.chev()}</span>`;let A=y??(o==="run_js"?t.runCode:void 0),M=f("span","ra-tname",A??o);A&&(M.title=o,M.classList.add("own")),g.append(x,M,f("span","ra-tsum",y?"":jo(o,c)),b);let _=f("div","ra-tbody"),O=f("pre","",o==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));_.append(f("div","ra-tlabel",t.args),O),u.append(g,_);let B={el:u,name:o,args:c,end:b,body:_,update:null,result:null};return Ti(B,{status:"running"}),B},Ci=o=>{let c=wi(o);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let u=f("details","ra-tg"),g=f("summary"),m=f("div","ra-tgb");return u.append(g,m),Ks(o,u),m},Ol=o=>{let c=[],u=new Map;for(let g of o){let m=Gs(g.name,g.args);if(m!==void 0){let A=`Own:${m}`;u.has(A)||(c.push(A),u.set(A,0)),u.set(A,u.get(A)+1);continue}let y=sl[g.name]??"Other",x=y==="Other"?`Other:${g.name}`:y;u.has(x)||(c.push(x),u.set(x,y==="Read"||y==="Write"||y==="Edit"||y==="Delete"?new Set:0));let b=u.get(x);b instanceof Set?b.add(ol(g.args)??String(b.size)):u.set(x,b+1)}return c.map(g=>{let m=u.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":", ")},Mi=(o,c)=>{let u=Gs(o.name,o.args);if(u!==void 0)return{verb:u,what:""};let g=sl[o.name]??"Other",m=ol(o.args),y=t[`ing${g}`];return g==="Other"?{verb:`${y} ${o.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??""}},Zs=o=>{let c=o.closest(".ra-tg");if(!c)return;let u=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),g=u.filter(b=>b.querySelector(".ra-tend .ra-spin")),m=u.filter(b=>b.classList.contains("fail")).length,y=c.querySelector("summary");if(y.replaceChildren(),g.length){let b=g[g.length-1],A=Mi(Fs.get(b)??{name:b.querySelector(".ra-tname")?.textContent??"",args:void 0},b);y.append(f("span","ra-spin"));let M=f("span","ra-tgt");M.append(`${A.verb} `),A.what&&M.append(f("code","",A.what)),A.title&&(M.title=A.title),y.append(M)}else{let b=u.map(_=>Fs.get(_)).filter(_=>!!_),A=b.length?Ol(b):u.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(u.length)),M=f("span","ra-tgt",A);M.title=u.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(u.length)),y.append(M)}m&&y.append(f("span","ra-tgf",t.toolsFailed.replace("{n}",String(m))));let x=f("span","ra-chev");x.innerHTML=I.chev(12),y.append(x)},Dl=(o,c,u,g,m)=>{let y=Si(c,u);return m?(m.nested||(m.nested=f("div","ra-tnest"),m.body.append(m.nested)),m.nested.append(y.el)):Ci(g).append(y.el),Bt.set(o,y),Zs(y.el),we.schedule(),y},Js=o=>Array.isArray(o)?o.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:)/.test(c.image_url.url)?[c.image_url.url]:[]):[],Ei=async o=>{let c=F?.workspace,u=sr(o.name),g=o.args,m=u?.file?jr(()=>u.file(o.args)):Gd.has(o.name)&&g&&typeof g=="object"&&typeof g.path=="string"?g.path:null;if(!c||!m||!await ll(c,m))return;let y=f("div","ra-tacts"),x=f("button","ra-open",`${t.open} ${m}`);if(x.type="button",x.addEventListener("click",()=>Qn(m)),y.append(x),!pe){let b=f("button","ra-open",t.download);b.type="button",b.addEventListener("click",()=>{je.download(m)}),y.append(b)}o.body.querySelector(":scope>pre")?.after(y),we.schedule()},Ai=(o,c,u,g,m=[],y)=>{let x=c==="ok",b=c==="error"||c==="blocked";o.end.replaceChildren();let A=sr(o.name),M=jr(A?.outcome&&(()=>A.outcome({args:o.args,status:c,result:u,details:y})));typeof M=="string"&&M?o.end.append(f("span","ra-tout",M)):g!==void 0&&o.end.append(f("span","",`${Math.round(g)}ms`));let _=f("span",x?"ok":b?"fail":"");x?_.innerHTML=I.check():c==="error"?_.innerHTML=I.xcircle():c==="blocked"?(_.innerHTML=I.ban(),_.title=t.blocked):_.textContent=t[c]??c,o.end.append(_),o.el.classList.toggle("fail",b),Ti(o,{status:c,result:u,details:y}),o.update?.remove(),x&&(o.el.open?Ei(o):o.el.addEventListener("toggle",()=>{Ei(o)},{once:!0})),o.result||(o.result=f("pre",""),o.body.append(f("div","ra-tlabel",c==="error"?t.error:t.result),o.result));let O=m.length?u.replace(/^\[image_url\]$/gm,"").trim():u;if(o.result.textContent=O.length>2e4?O.slice(0,2e4)+"\u2026":O||t.emptyResult,m.length&&!o.body.querySelector(".ra-timgs")){let B=f("div","ra-timgs");for(let te of m.slice(0,4)){let le=f("img");le.src=te,le.alt=t.result,le.addEventListener("load",()=>we.schedule()),B.append(le)}o.body.append(B)}Zs(o.el),we.schedule()},zl=(o,c,u)=>{let g=f("div","ra-card"),m=f("div","ra-ct"+(c?"":" only"));if(m.innerHTML=I.layers()+`<span>${ve(o)}</span>`,g.append(m),c){let y=f("div","ra-md");zn(y,c,!1),g.append(y)}if(u){let y=f("button","ra-btn xs subtle",u.label);y.type="button",y.addEventListener("click",()=>{y.disabled=!0,u.onClick()}),g.append(y)}return g},or=(o,c,u)=>{Tt({render:()=>zl(o,c,u)}),we.schedule()},Il=(o,c,u)=>{let g={render:()=>{let m=f("div","ra-warn");if(m.setAttribute("role","status"),u&&(m.title=u),m.innerHTML=I.alert(14),m.append(f("span","",o)),c){let y=f("button","ra-btn xs",c.label);y.type="button",y.addEventListener("click",()=>{we.remove(g),c.onClick()}),m.append(y)}return m}};Tt(g),we.schedule()},qr=(o,c)=>{let u={render:()=>{let g=f("div","ra-err",o);if(c){let m=f("button","ra-btn xs red-subtle",t.retry);m.type="button",m.addEventListener("click",()=>{we.remove(u),c()}),g.append(m)}return g}};Tt(u),we.schedule()},hn=o=>{we.clear(),fn=0,Bt.clear(),Zn.clear(),X=null;let c=null,u,g=(m=!1)=>{if(!c)return;let y=c;c=null;let x=!(m&&F?.busy);Tt({render:()=>{let b=gi();for(let A of y.items)if(A.kind==="think"){let[M]=xi(A.text,!0),_=b.body.lastElementChild;_ instanceof HTMLDetailsElement&&_.classList.contains("ra-tg")?_.querySelector(".ra-tgb").append(M):b.body.append(M)}else if(A.kind==="text"){let M=f("div","ra-md");Rl(M,A.text),b.body.append(M)}else{let M=A.call,_=Si(M.name,M.args);Ci(b.body).append(_.el),M.status?Ai(_,M.status,M.result??"",void 0,M.images):(M.id&&Bt.set(M.id,_),Zs(_.el))}return x&&yi(b.body,y.start!==void 0&&y.end!==void 0?y.end-y.start:void 0),x&&y.msg&&b.el.append(hi(y.msg)),b.el}})};for(let m of o)if(m.role==="user"){g();let y=typeof m.content=="string"?ze(m):null;if(y!==null){or(t.compacted,y);continue}if(typeof m.content=="string"&&m.content.startsWith("[environment]"))continue;u=Fn(m),bi(u),Tt(Ws(m.content,m))}else if(m.role==="assistant"){let y=nn(m.content),x=m.reasoning_content,b=typeof x=="string"?x:"";c||(c={items:[],calls:[],start:u}),c.msg=m,c.end=Fn(m)??c.end,c.end&&(fn=c.end),b&&c.items.push({kind:"think",text:b}),y&&c.items.push({kind:"text",text:y});for(let A of m.tool_calls??[]){if(Xs.has(A.function.name))continue;let M=A.function.arguments;try{M=JSON.parse(A.function.arguments)}catch{}let _={id:A.id??"",name:A.function.name,args:M};c.items.push({kind:"call",call:_}),c.calls.push(_),_.id&&Zn.set(_.id,_)}}else if(m.role==="tool"){let y=nn(m.content),x=c?.calls.find(b=>b.id===(m.tool_call_id??""));x&&(x.result=y,x.status=Ld(y),x.images=Js(m.content),Zn.delete(x.id))}g(!0),o.length||li(),an(),we.scrollToBottom()},Lt=null,Br=null,ir=()=>{Br=null,Lt!==null&&(Lt=null,St(ee.dataset.busy==="1"))},Ul={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:o})=>(Br=String(o??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},$i=[...q.tools??[],...ne?[Ul]:[]],Xs=new Set($i.filter(o=>o.display?.hidden).map(o=>o.name)),Gt=()=>{let o=ee.dataset.busy==="1",c=!!(z.value.trim()||ft.length||ht.length);jt.style.display=!o&&c?"":"none",un.style.display=Gn.style.display=o&&c?"":"none"},St=o=>{ee.dataset.busy=o?"1":"",z.placeholder=o?_r(t.placeholderBusy):Lt??U??t.placeholder,dn.textContent=_r(o?t.hintBusy:Lt?t.hintNext:t.hintIdle),Gt(),qt.style.display=o?"":"none",pt()},Zt=!1,pt=()=>{let o=F?.queued??[];if(K.style.display=o.length?"":"none",K.replaceChildren(),!o.length){Zt=!1;return}let c=F,u=M=>nn(M.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),g=(M,_,O)=>{let B=f("button");return B.type="button",B.innerHTML=M,B.title=_,B.setAttribute("aria-label",_),B.addEventListener("click",te=>{te.stopPropagation(),O()}),B},m=M=>{let _=f("span","ra-qa");return M.kind!=="steer"&&_.append(g(I.enter(),t.sendNow,()=>{c.dequeue(M.message)&&c.steer(M.message.content),pt()})),_.append(g(I.pen(),t.editQueued,()=>{c.dequeue(M.message)&&(z.value=z.value.trim()?`${u(M.message)}
|
|
739
|
+
${z.value}`:u(M.message),z.focus(),pt())})),_.append(g(I.x(14),t.remove,()=>{c.dequeue(M.message),pt()})),_},y=M=>M.kind==="steer"?f("span","ra-qk",t.steer):null;if(K.classList.toggle("open",Zt&&o.length>1),o.length===1){let M=o[0],_=f("div","ra-qr"),O=y(M);_.append(f("span","ra-qn",t.queuedN.replace("{n}","1"))),O&&_.append(O),_.append(f("span","ra-qt",u(M.message)),m(M)),K.append(_);return}let x=f("div","ra-qr ra-qhd"),b=f("span","ra-qt");Zt||(b.append(f("b","",t.queueNext)),b.append(u(o[0].message)));let A=f("span","ra-qtog");if(A.innerHTML=I.chevDown(14),A.title=Zt?t.collapse:t.expand,x.append(f("span","ra-qn",t.queuedNs.replace("{n}",String(o.length))),b,A),x.addEventListener("click",()=>{Zt=!Zt,pt()}),K.append(x),Zt)for(let M of o){let _=f("div","ra-qr"),O=y(M);O&&_.append(O),_.append(f("span","ra-qt",u(M.message)),m(M)),K.append(_)}},ar=o=>{L.style.display=o?"":"none",L.textContent=o??""},Pt=async()=>{let o=F?.workspace;if(!o){Or=[],on(0);return}try{let[c,u]=await Promise.all([o.skills(),as(o)]);F?.workspace===o&&on(c.length),Or=[...u.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{Or=[],on(0)}},Ys=!1,Li=()=>{let o=z.value;return Ys||!o.startsWith("/")||/\s/.test(o)?[]:[...io(),...Or].filter(c=>`/${c.name}`.startsWith(o)).slice(0,40)},Ze=()=>{Gt();let o=Li();Z.style.display=o.length?"":"none",Z.replaceChildren(),ct>=o.length&&(ct=0),o.forEach((c,u)=>{let g=f("button",u===ct?"ra-cur":"");g.type="button",g.append(f("span","ra-cn",`/${c.name}`)),c.args&&g.append(f("span","ra-ca",c.args)),g.append(f("span","ra-badge",c.kind),f("span","ra-cd",c.description)),g.addEventListener("mousedown",m=>{m.preventDefault(),Vi(c),z.focus()}),Z.append(g),u===ct&&g.scrollIntoView?.({block:"nearest"})})},Fl=()=>{Jn===null&&(Jn=requestAnimationFrame(()=>{Jn=null,Ze()}))},ft=[],ht=[],mn=()=>{be.style.display=ft.length||ht.length?"":"none",Gt()},Qs=o=>{let c=ht.findIndex(u=>u.id===o);c<0||(ht[c].chip.remove(),ht.splice(c,1),mn())},Pi=o=>{let c=o.id??`ctx_${Math.random().toString(36).slice(2,8)}`;Qs(c),o={...o,label:o.label.replace(/\s+/g," ").trim()||"context"};let u=di(o.label,o.title,o.icon),g=f("button");return g.type="button",g.innerHTML=I.x(),g.title=t.remove,g.setAttribute("aria-label",t.remove),g.addEventListener("click",()=>Qs(c)),u.append(g),ht.push({id:c,label:o.label,text:o.text,chip:u}),be.prepend(u),mn(),()=>Qs(c)},Nl=o=>{let c=ft.indexOf(o);c>=0&&ft.splice(c,1),o.preview&&URL.revokeObjectURL(o.preview),o.chip.remove(),mn()},eo=Promise.resolve(),Wr=(o,c=[])=>{let u=o?Array.from(o):[],g=eo.then(()=>Hl(u,c));return eo=g.catch(()=>{}),g},Hl=async(o,c)=>{if(!(J===!1||!o?.length)){for(let[u,g]of Array.from(o).entries()){if(g.size>Ud){G.notify(`${g.name} ${t.tooLarge}`,"warning");continue}let m=new Uint8Array(await g.arrayBuffer()),y=/^image\/(png|jpe?g|gif|webp)$/.test(g.type),x=y?null:Kd(g,m),b=y?URL.createObjectURL(g):null,A=ci(al(g.name),Un(g.size),b),M=f("button");M.type="button",M.innerHTML=I.x(),M.title=t.remove,M.setAttribute("aria-label",t.remove),A.append(M);let _={file:g,name:al(g.name),bytes:m,text:x,image:y,preview:b,chip:A,path:c[u]};M.addEventListener("click",()=>Nl(_)),ft.push(_),be.append(A)}mn(),z.focus()}};at.addEventListener("click",()=>rt.click()),rt.addEventListener("change",()=>{Wr(rt.files),rt.value=""}),z.addEventListener("paste",o=>{let c=Array.from(o.clipboardData?.files??[]);!c.length||o.clipboardData?.getData("text/plain")||(o.preventDefault(),Wr(c))});let Kr=0;ee.addEventListener("dragenter",o=>{J===!1||!o.dataTransfer?.types.includes("Files")||(o.preventDefault(),Kr++,ee.dataset.drop="1")}),ee.addEventListener("dragover",o=>{ee.dataset.drop&&(o.preventDefault(),o.dataTransfer.dropEffect="copy")}),ee.addEventListener("dragleave",()=>{ee.dataset.drop&&--Kr<=0&&(Kr=0,delete ee.dataset.drop)}),ee.addEventListener("drop",o=>{ee.dataset.drop&&(o.preventDefault(),Kr=0,delete ee.dataset.drop,Wr(o.dataTransfer?.files))});let jl=async(o,c,u)=>{if(!c.length)return o;let g=q.fileTools===!1?null:u.workspace,m=[],y=[],x=c.some(O=>O.image)&&await u.accepts("image")===!1,b=O=>/^video\//.test(O.file.type)&&O.file.size<=Nd,A=c.some(b)&&await u.accepts("video")!==!1;x&&G.notify(t.noVision.replace("{model}",u.model||(await u.modelInfo())?.id||t.sDefault),"warning");for(let O of c){let B=O.file.type||(O.text!==null?"text/plain":"application/octet-stream");if(g){let te=O.path&&await g.exists(O.path)?O.path:await No(g,ce,O.name);te!==O.path&&await g.write(te,O.text??O.bytes,B),m.push(`- ${te} (${B}, ${Un(O.file.size)})`),je.refresh()}else if(Mn(O.name,O.file.type,O.bytes)){let te="";try{te=An(O.name,await En(O.bytes))}catch(le){te=`Could not read the PDF: ${le.message}`}te.length>Bo&&(te=te.slice(0,Bo)+`
|
|
740
|
+
[\u2026 truncated]`),m.push(`- ${O.name} (${B}, ${Un(O.file.size)}) \u2014 its text below`),y.push({type:"text",text:`<file name="${O.name}">
|
|
741
|
+
${te}
|
|
742
|
+
</file>`})}else O.text!==null&&O.text.length<=Bo?(m.push(`- ${O.name} (${B}, ${Un(O.file.size)}) \u2014 contents below`),y.push({type:"text",text:`<file name="${O.name}">
|
|
735
743
|
${O.text}
|
|
736
|
-
</file>`})):
|
|
737
|
-
${
|
|
738
|
-
`)}`}),_.push(...y),_},
|
|
739
|
-
${A.text}`}))),y=x}}catch(x){z.value=c,ft.unshift(...m);for(let b of m.slice().reverse())we.prepend(b.chip);ht.unshift(...g);for(let b of g.slice().reverse())we.prepend(b.chip);pn(),rr(x.message);return}finally{Js=!1}for(let x of m)x.preview&&URL.revokeObjectURL(x.preview);p.busy||(o="prompt");try{if(o==="prompt"){F===p&&!p.busy&&(dt=Jn(y)),await p.prompt(y);return}o==="steer"?p.steer(y):p.followUp(y).catch(()=>{}),pt()}catch(x){dt=null,rr(x.message)}};z.addEventListener("input",()=>{Vs=!1,z.value&&nr(),Kt(),El()}),z.addEventListener("keydown",o=>{if(o.isComposing||o.keyCode===229)return;let c=Ti();if(c.length){if(o.key==="ArrowDown"){o.preventDefault(),ct=(ct+1)%c.length,Ge();return}if(o.key==="ArrowUp"){o.preventDefault(),ct=(ct-1+c.length)%c.length,Ge();return}if(o.key==="Tab"){o.preventDefault(),z.value=`/${c[ct].name} `,Ge();return}if(o.key==="Enter"&&!o.shiftKey){o.preventDefault(),ji(c[ct]);return}if(o.key==="Escape"){Vs=!0,Z.style.display="none";return}}if(Lt&&!z.value&&o.key==="Tab"&&!o.shiftKey){o.preventDefault(),z.value=Lt,nr(),Kt();return}if(Lt&&!z.value&&o.key==="Escape"){nr();return}if(o.key!=="Enter"||o.shiftKey)return;o.preventDefault();let p=o.metaKey||o.ctrlKey||o.altKey;fn(F?.busy?p?"followUp":"steer":"prompt")}),z.addEventListener("blur",()=>{Z.style.display="none"}),z.addEventListener("focus",()=>Ge()),jt.addEventListener("click",()=>{fn("prompt")}),ln.addEventListener("click",()=>{fn("steer")}),Bn.addEventListener("click",()=>{fn("followUp")}),Ht.addEventListener("click",()=>{G.cancelAll(),F?.abort()}),Xe.addEventListener("click",o=>{let c=o.target,p=ke?c.closest("a[href]"):null;if(p&&ke){let y=!1;try{y=ke(p.getAttribute("href")??"",p.textContent??"")===!0}catch(x){console.warn("agent: onLink failed",x)}if(y){o.preventDefault();return}}let m=c.closest(".ra-path");if(m?.dataset.path){o.preventDefault(),Zn(m.dataset.path);return}let g=c.closest(".ra-md a[href]");if(g&&F?.workspace){let y=g.getAttribute("href")??"";if(y.startsWith("/")&&!y.startsWith("//")){o.preventDefault(),F.workspace.exists(y).then(b=>{b?Zn(y):window.open(g.href,"_blank","noopener")});return}}});let Xs=`__runapps_agent_chat:${oe}:settings`,Pl=()=>{try{return JSON.parse(localStorage.getItem(Xs)||"{}")}catch{return{}}},Ci=o=>{try{Object.keys(o).length?localStorage.setItem(Xs,JSON.stringify(o)):localStorage.removeItem(Xs)}catch{}},Ie=l?{}:Pl(),sr=null,Mi=e.settings??!l,Ei=0;Mi||(Je.style.display="none");let Gt=null,Ys=o=>{let c=o?.options?.inputs?.reasoning_effort;if(!c)return null;let p=(c.enum??[]).filter(m=>typeof m=="string");return p.length?{levels:p,def:typeof c.default=="string"?c.default:void 0}:null},Ai=(o,c,p)=>{let m=q.extra?.reasoning_effort;o.configure({model:c.model??q.model,maxTurns:c.maxTurns??q.maxTurns??100,maxTokens:c.maxTokens??(typeof q.maxTokens=="number"?q.maxTokens:"auto"),permissions:p??q.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof m=="string"?m:null)}),Ut.textContent=o.model??"",Ut.style.display=o.model?"":"none"},Nr=o=>{Ie=o,Ci(o);for(let c of je.values())Ai(c,o,sr);gt(F)},hn=async()=>{if(fe?.models)try{Gt??(Gt=(await fe.models()).filter(o=>!o.capability||o.capability==="text"||o.capability==="vision"))}catch{}return Gt??[]};Ie.model&&fe?.models&&hn().then(o=>{if(!o.length||!Ie.model||o.some(m=>m.id===Ie.model))return;let{model:c,...p}=Ie;Nr(p)});let qr=o=>typeof o=="number"?o>=1e3?`${Math.round(o/1e3)}k`:String(o):"?",$i=o=>{let c=o?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let p=t.sPriceLine.replace("{in}",Cr(c.input??0,c.currency)).replace("{out}",Cr(c.output??0,c.currency));return c.per_call?`${p} \xB7 ${t.sPerCall.replace("{amount}",Cr(c.per_call,c.currency))}`:p},Qs=async()=>{if(Ce){Ae();return}if(!F)return;let o=F,c=h("div","ra-menu ra-set");Ce=c,Br(c);let p=o.settings,m=(ce,he)=>{let de=Tr(Q,{options:ce,value:he,filterLabel:t.filter});return Li.push(de),de},g=m([{value:"",label:t.sDefault}],""),y=h("div","ra-lim"),x=m([],""),b=h("div","ra-lim"),A=()=>{let ce=g.value||Gt?.find(he=>he.is_default)?.id;return Gt?.find(he=>he.id===ce)},C=()=>{let ce=A(),he=Ot(ce,"image"),de=$i(ce);y.textContent=ce?`${t.context} ${qr(ce.max_input_tokens)} \xB7 ${t.sMaxTokens} ${qr(ce.max_tokens)}${he===void 0?"":` \xB7 ${he?t.sVisionYes:t.sVisionNo}`}${de?` \xB7 ${t.sPrice}: ${de}`:""}`:"";let Te=Ys(ce),Oe=x.value;x.setOptions([{value:"",label:t.sEffortDefault,note:Te?.def},...(Te?.levels??[]).map(Ne=>({value:Ne,label:Ne}))]),x.disabled=!Te,x.value=Te&&Te.levels.includes(Oe)?Oe:"",b.textContent=Te?"":t.sEffortNone,b.style.display=Te?"none":""};g.el.addEventListener("change",C);let _=[];if(fe?.models){if(await hn(),Ce!==c)return;let ce=Gt?.find(he=>he.is_default);_.push({value:"",label:t.sDefault,note:ce?.id});for(let he of Gt??[]){let de=he.price,Te=de&&(de.input!==void 0||de.output!==void 0)?` \xB7 ${Cr(de.input??0,de.currency)} / ${Cr(de.output??0,de.currency)}`:"";_.push({value:he.id,label:he.id,note:`${Ot(he,"image")?`${t.sVision} \xB7 `:""}${qr(he.max_input_tokens)} / ${qr(he.max_tokens)}${Te}`})}}else _.push({value:"",label:t.sDefault});p.model&&!_.some(ce=>ce.value===p.model)&&_.push({value:p.model,label:p.model}),g.setOptions(_),g.value=p.model??"",C(),p.reasoningEffort&&x.options.some(ce=>ce.value===p.reasoningEffort)&&(x.value=p.reasoningEffort);let O=h("input");O.type="number",O.min="1",O.max="1000",O.step="1",O.value=String(p.maxTurns);let B=m([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),ee=h("input");ee.type="number",ee.min="256",ee.step="256",ee.value=String(typeof p.maxTokens=="number"?p.maxTokens:8192),B.value=typeof p.maxTokens=="number"?"n":"auto",ee.style.display=B.value==="n"?"":"none",B.el.addEventListener("change",()=>{ee.style.display=B.value==="n"?"":"none"});let ie=m([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...p.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],p.permissions),ge=(ce,...he)=>{let de=h("div","ra-fld");return de.append(h("span","",ce),...he),de},Re=h("div","ra-row");Re.append(B.el,ee);let _t=h("div","ra-pane");_t.append(ge(t.sModel,g.el),y,ge(t.sEffort,x.el),b,ge(t.sMaxTurns,O),ge(t.sMaxTokens,Re)),H!==!1&&_t.append(ge(t.sPerms,ie.el));let mt=[],ro=ce=>{let he=h("div","ra-pane");for(let de of ce.fields){if(de instanceof HTMLElement){de.classList.add("ra-host"),he.append(de);continue}if(de.type==="toggle"){let Te=h("label","ra-tgl"),Oe=h("input");Oe.type="checkbox",Oe.checked=de.value();let Ne=h("span","",de.label);de.hint&&Ne.append(h("small","",de.hint)),Te.append(Oe,Ne),he.append(Te),mt.push(()=>{Oe.checked!==de.value()&&de.onChange(Oe.checked)})}else{let Te=m(de.options,de.value()),Oe=ge(de.label,Te.el);de.hint&&Oe.append(h("small","",de.hint)),he.append(Oe),mt.push(()=>{Te.value!==de.value()&&de.onChange(Te.value)})}}return he},Zr=[_t,...(_e??[]).map(ro)];if(Zr.length>1){let ce=h("div","ra-tabs");ce.setAttribute("role","tablist");let he=[t.sTabModel,...(_e??[]).map(Te=>Te.label)].map((Te,Oe)=>{let Ne=h("button","ra-tab",Te);return Ne.type="button",Ne.setAttribute("role","tab"),Ne.addEventListener("click",()=>de(Oe)),Ne}),de=Te=>{Ei=Te,Zr.forEach((Oe,Ne)=>{Oe.hidden=Ne!==Te}),he.forEach((Oe,Ne)=>{Oe.classList.toggle("on",Ne===Te),Oe.setAttribute("aria-selected",String(Ne===Te))})};ce.append(...he),Ce.append(ce,...Zr),de(Math.min(Ei,Zr.length-1))}else Ce.append(_t);let Zi=h("div","ra-btns"),so=h("button","ra-btn xs ghost",t.reset);so.type="button";let oo=h("button","ra-btn xs solid",t.apply);oo.type="button",Zi.append(so,oo),Ce.append(Zi),so.addEventListener("click",()=>{for(let ce of(_e??[]).flatMap(he=>he.fields))ce instanceof HTMLElement||ce.default===void 0||(ce.type,ce.value()!==ce.default&&ce.onChange(ce.default));Ie={},Ci({}),sr=null;for(let ce of je.values())Ai(ce,{},null);Ae(),G.notify(t.applied),gt(F)}),oo.addEventListener("click",()=>{let ce={};g.value&&(ce.model=g.value);let he=parseInt(O.value,10);if(Number.isFinite(he)&&he>0&&Math.min(1e3,he)!==(q.maxTurns??100)&&(ce.maxTurns=Math.min(1e3,he)),B.value==="n"){let de=parseInt(ee.value,10);Number.isFinite(de)&&de>0&&(ce.maxTokens=de)}x.value&&!x.disabled&&(ce.reasoningEffort=x.value),(ie.value==="ask"||ie.value==="auto")&&(sr=ie.value);for(let de of mt)de();Nr(ce),Ae(),G.notify(t.applied)})};Je.addEventListener("click",()=>{Qs()});let Li=[],Ae=()=>{Ce?.remove(),Ce=null;for(let o of Li.splice(0))o.close()},Br=o=>{Q.append(o),o.style.top=`${be.offsetTop+be.offsetHeight+4}px`},Pi=async()=>{if(Ce){Ae();return}if(!F?.workspace)return;let o=F.workspace,c=h("div","ra-menu");Ce=c,Br(c);let p=[];try{p=await o.sessions.list()}catch{}if(Ce!==c)return;let m=F,g=p.filter(b=>b.id!==m.id),y=p.find(b=>b.id===m.id),x=b=>{let A=!b||b.id===m.id,C=h("div","ra-mi"+(A?" ra-cur":"")),_=h("button");_.type="button";let O=b?je.get(b.id):void 0,B=b&&O&&O!==m?qt.has(b.id)?` \xB7 ${t.waitingAnswer}`:O.busy||O.queued.length?` \xB7 ${t.running}`:"":"",ee=h("span","ra-mt");if(B&&!qt.has(b.id)&&ee.append(h("span","ra-spin")),ee.append(h("span","ra-mtt",(b?b.title:_r(m))||t.untitled)),A&&(ee.append(h("span","ra-now",t.current)),C.setAttribute("aria-current","true")),_.append(ee,h("small","",b?`${b.messages} ${t.messages} \xB7 ${new Date(b.savedAt).toLocaleString()}${B}`:t.notSaved)),_.addEventListener("click",()=>{Ae(),b&&!A&&Gi(b.id).catch(ie=>G.notify(ie.message,"error"))}),C.append(_),b){let ie=h("button","ra-x");ie.type="button",ie.innerHTML=I.trash(),ie.title=t.delete,ie.setAttribute("aria-label",t.delete),ie.addEventListener("click",async ge=>{ge.stopPropagation(),Ae(),await bt(Q,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await no(b.id,!1,b.workspace).catch(Re=>G.notify(Re.message,"error"))}),C.append(ie)}return C};c.append(x(y??null)),g.length?c.append(h("div","ra-sep")):c.append(h("div","ra-none",t.noSessions));for(let b of g)c.append(x(b));if(g.length){let b=h("div","ra-mf"),A=h("button","ra-btn xs ghost");A.type="button",A.innerHTML=I.trash()+xe(t.deleteAll),A.addEventListener("click",async()=>{if(Ae(),!!await bt(Q,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let C of p)await no(C.id,!0,C.workspace);await mn()}catch(C){G.notify(C.message,"error")}}),b.append(A),c.append(b)}};Ze.addEventListener("click",()=>{Pi()}),ze.addEventListener("click",()=>{Ae(),mn().catch(o=>G.notify(o.message,"error"))}),Be.addEventListener("click",async()=>{Ae(),await bt(Q,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await Gr().catch(o=>G.notify(o.message,"error"))}),document.addEventListener("click",_i,!0);function _i(o){o.target?.closest?.(".ra-selp")||Ce&&!Ce.contains(o.target)&&!Ze.contains(o.target)&&!Je.contains(o.target)&&!nt.contains(o.target)&&!Ke.contains(o.target)&&Ae()}let Ct=h("input");Ct.type="file",Ct.accept=".zip,application/zip",Ct.multiple=!0,Ct.style.display="none",Q.append(Ct);let Ri=async o=>{let c=F?.workspace;if(!c||!o?.length)return;let p=[];for(let m of Array.from(o)){if(!/\.zip$/i.test(m.name)&&m.type!=="application/zip"&&m.type!=="application/x-zip-compressed"){G.notify(`${m.name}: ${t.notZip}`,"warning");continue}try{p.push(...(await c.installSkill(m)).map(g=>g.name))}catch(g){G.notify(`${m.name}: ${g.message}`,"error")}}p.length&&G.notify(t.skillsInstalled.replace("{names}",p.join(", "))),await Pt(),Ce?.classList.contains("ra-skm")&&(Ae(),Oi())};Ct.addEventListener("change",()=>{Ri(Ct.files),Ct.value=""});let Oi=async()=>{if(Ce){let y=Ce.classList.contains("ra-skm");if(Ae(),y)return}let o=F?.workspace;if(!o)return;let c=h("div","ra-menu ra-skm");Ce=c,Br(c);let p=[];try{p=await o.skills()}catch(y){G.notify(y.message,"error")}if(Ce!==c)return;let m=h("div","ra-skh"),g=h("button","ra-btn xs solid");g.type="button",g.innerHTML=I.upload(13)+`<span>${xe(t.uploadZip)}</span>`,g.addEventListener("click",()=>Ct.click()),o.userSkillsDir||(g.style.display="none"),m.append(h("span","",p.length?`${t.skills} \xB7 ${p.length}`:t.skills),g),c.append(m),p.length||c.append(h("div","ra-none",t.noSkills));for(let y of p){let x=h("div","ra-mi"),b=h("button");b.type="button",b.title=t.useSkill;let A=h("span","ra-mt"),C=!!y.from&&/\.zip$/i.test(y.from);A.append(h("span","ra-mtt",y.name),h("span","ra-skb",y.builtin?t.builtinSkill:C?"zip":t.skillFolder)),y.disableModelInvocation&&A.append(h("span","ra-skb",t.manualOnly)),b.append(A,h("small","",y.description)),b.addEventListener("click",()=>{Ae(),z.value=`/skill:${y.name} `,z.focus(),Ge()});let _=(ie,ge,Re,_t="ra-x ra-ia")=>{let mt=h("button",_t);return mt.type="button",mt.innerHTML=ie,mt.title=ge,mt.setAttribute("aria-label",ge),mt.addEventListener("click",ro=>{ro.stopPropagation(),Re()}),mt},O=_(I.eye(),t.open,()=>{Ae(),Zn(y.from&&!C?`${y.from}/SKILL.md`:y.path)}),B=_(I.download(),t.download,()=>{C?He.download(y.from):He.downloadFolder(y.from??y.dir)}),ee=_(I.trash(),t.delete,async()=>{Ae();let ie=C?p.filter(Re=>Re.from===y.from).map(Re=>Re.name):[y.name],ge=ie.length>1?t.confirmDeleteZip.replace("{zip}",y.from.replace(/^.*\//,"")).replace("{names}",ie.join("\u3001")):t.confirmDeleteSkill.replace("{name}",y.name).replace("{path}",y.from??"");if(await bt(Q,t.delete,ge,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await o.removeSkill(y.name),await Pt(),G.notify(t.skillRemoved.replace("{name}",ie.join(", ")))}catch(Re){G.notify(Re.message,"error")}},"ra-x");(y.builtin||!y.from?.startsWith((o.userSkillsDir??"\0")+"/"))&&(ee.style.display="none"),x.append(b,O,B,ee),c.append(x)}c.append(h("div","ra-skf",(o.userSkillsDir?t.skillsHint.replace("{user}",o.userSkillsDir):t.skillsHintNoUser).replace("{dir}",o.skillsDir))),o.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")),o.userSkillsDir&&c.addEventListener("drop",y=>{y.preventDefault(),y.stopPropagation(),c.classList.remove("drop"),Ri(y.dataTransfer?.files)})};nt.addEventListener("click",()=>{Oi()});let Di=o=>G.notify(o.message,"error"),gn=!1,_l=o=>{let c=[`# ${_r(o)}`,""];for(let p of o.messages){if(p.role==="tool"||p.role==="system")continue;let m=Qt(p.content).trim(),g=p.role==="user"&&typeof p.content=="string"?De(p):null;if(g!==null){c.push(`> **${t.compacted}**`,">",...g.split(`
|
|
740
|
-
`).map(x=>`> ${x}`),"");continue}let y=
|
|
741
|
-
`)},
|
|
742
|
-
`))}},{name:"new",aliases:["clear"],run:()=>(
|
|
743
|
-
`))}},{name:"export",run:()=>{if(!F.messages.length){G.notify(t.nothingToExport);return}let o=
|
|
744
|
-
|
|
745
|
-
`):[
|
|
746
|
-
|
|
747
|
-
`),A={};return
|
|
744
|
+
</file>`})):m.push(`- ${O.name} (${B}, ${Un(O.file.size)}) \u2014 ${O.image&&!x?"the picture below":b(O)&&A?"the video below":"not readable here"}`);if(b(O)&&A){let te=await new Promise(le=>{let ge=new FileReader;ge.onload=()=>le(String(ge.result)),ge.readAsDataURL(O.file)});y.push({type:"video_url",video_url:{url:te}})}if(O.image&&!x&&O.file.size<=Fd){let te=await new Promise(le=>{let ge=new FileReader;ge.onload=()=>le(String(ge.result)),ge.readAsDataURL(O.file)});y.push({type:"image_url",image_url:{url:te}})}}let M=g?`${Ft} files the user attached, saved in the directory (read them with read_file):`:`${Ft} files the user attached:`,_=[];return o&&_.push({type:"text",text:o}),_.push({type:"text",text:`${M}
|
|
745
|
+
${m.join(`
|
|
746
|
+
`)}`}),_.push(...y),_},to=!1,gn=async o=>{await eo;let c=z.value.trim();if(!c&&!ft.length&&!ht.length||!F||to||(ir(),Zl(c)))return;wn&&(o="followUp");let u=F,g=ft.splice(0);for(let x of g)x.chip.remove();let m=ht.splice(0);for(let x of m)x.chip.remove();mn(),z.value="",Ze(),ar(),to=!0;let y;try{if(y=await jl(c,g,u),m.length){let x=typeof y=="string"?y?[{type:"text",text:y}]:[]:y,b=x.length&&x[0].type==="text"&&!x[0].text.startsWith(Ft)?1:0;x.splice(b,0,...m.map(A=>({type:"text",text:`${Nn}${A.label}
|
|
747
|
+
${A.text}`}))),y=x}}catch(x){z.value=c,ft.unshift(...g);for(let b of g.slice().reverse())be.prepend(b.chip);ht.unshift(...m);for(let b of m.slice().reverse())be.prepend(b.chip);mn(),ar(x.message);return}finally{to=!1}for(let x of g)x.preview&&URL.revokeObjectURL(x.preview);u.busy||(o="prompt");try{if(o==="prompt"){F===u&&!u.busy&&(dt=er(y)),await u.prompt(y);return}o==="steer"?u.steer(y):u.followUp(y).catch(()=>{}),pt()}catch(x){dt=null,ar(x.message)}};z.addEventListener("input",()=>{Ys=!1,z.value&&ir(),Gt(),Fl()}),z.addEventListener("keydown",o=>{if(o.isComposing||o.keyCode===229)return;let c=Li();if(c.length){if(o.key==="ArrowDown"){o.preventDefault(),ct=(ct+1)%c.length,Ze();return}if(o.key==="ArrowUp"){o.preventDefault(),ct=(ct-1+c.length)%c.length,Ze();return}if(o.key==="Tab"){o.preventDefault(),z.value=`/${c[ct].name} `,Ze();return}if(o.key==="Enter"&&!o.shiftKey){o.preventDefault(),Vi(c[ct]);return}if(o.key==="Escape"){Ys=!0,Z.style.display="none";return}}if(Lt&&!z.value&&o.key==="Tab"&&!o.shiftKey){o.preventDefault(),z.value=Lt,ir(),Gt();return}if(Lt&&!z.value&&o.key==="Escape"){ir();return}if(o.key!=="Enter"||o.shiftKey)return;o.preventDefault();let u=o.metaKey||o.ctrlKey||o.altKey;gn(F?.busy?u?"followUp":"steer":"prompt")}),z.addEventListener("blur",()=>{Z.style.display="none"}),z.addEventListener("focus",()=>Ze()),jt.addEventListener("click",()=>{gn("prompt")}),un.addEventListener("click",()=>{gn("steer")}),Gn.addEventListener("click",()=>{gn("followUp")}),qt.addEventListener("click",()=>{G.cancelAll(),F?.abort()}),Ye.addEventListener("click",o=>{let c=o.target,u=Ce?c.closest("a[href]"):null;if(u&&Ce){let y=!1;try{y=Ce(u.getAttribute("href")??"",u.textContent??"")===!0}catch(x){console.warn("agent: onLink failed",x)}if(y){o.preventDefault();return}}let g=c.closest(".ra-path");if(g?.dataset.path){o.preventDefault(),Qn(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("//")){o.preventDefault(),F.workspace.exists(y).then(b=>{b?Qn(y):window.open(m.href,"_blank","noopener")});return}}});let _t={summarize:q.compaction!==!1,...typeof q.compaction=="object"?q.compaction:{}},no=`__runapps_agent_chat:${ae}:settings`,ql=()=>{try{return JSON.parse(localStorage.getItem(no)||"{}")}catch{return{}}},_i=o=>{try{Object.keys(o).length?localStorage.setItem(no,JSON.stringify(o)):localStorage.removeItem(no)}catch{}},Ue=l?{}:ql(),lr=null,Ri=e.settings??!l,Oi=0;Ri||(Xe.style.display="none");let Jt=null,ro=o=>{let c=o?.options?.inputs?.reasoning_effort;if(!c)return null;let u=(c.enum??[]).filter(g=>typeof g=="string");return u.length?{levels:u,def:typeof c.default=="string"?c.default:void 0}:null},Di=(o,c,u)=>{let g=q.extra?.reasoning_effort;o.configure({model:c.model??q.model,maxTurns:c.maxTurns??q.maxTurns??100,maxTokens:c.maxTokens??(typeof q.maxTokens=="number"?q.maxTokens:"auto"),permissions:u??q.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof g=="string"?g:null),compaction:{summarize:c.summarize??_t.summarize,reserveTokens:c.reserveTokens??_t.reserveTokens,keepRecentTokens:c.keepRecentTokens??_t.keepRecentTokens}}),Nt.textContent=o.model??"",Nt.style.display=o.model?"":"none"},Vr=o=>{Ue=o,_i(o);for(let c of He.values())Di(c,o,lr);mt(F)},yn=async()=>{if(me?.models)try{Jt??(Jt=(await me.models()).filter(o=>!o.capability||o.capability==="text"||o.capability==="vision"))}catch{}return Jt??[]};Ue.model&&me?.models&&yn().then(o=>{if(!o.length||!Ue.model||o.some(g=>g.id===Ue.model))return;let{model:c,...u}=Ue;Vr(u)});let Gr=o=>typeof o=="number"?o>=1e3?`${Math.round(o/1e3)}k`:String(o):"?",zi=o=>{let c=o?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let u=t.sPriceLine.replace("{in}",Lr(c.input??0,c.currency)).replace("{out}",Lr(c.output??0,c.currency));return c.per_call?`${u} \xB7 ${t.sPerCall.replace("{amount}",Lr(c.per_call,c.currency))}`:u},so=async()=>{if(Ee){Le();return}if(!F)return;let o=F,c=f("div","ra-menu ra-set");Ee=c,Zr(c);let u=o.settings,g=(Y,ue)=>{let re=Ar(ee,{options:Y,value:ue,filterLabel:t.filter});return Ii.push(re),re},m=g([{value:"",label:t.sDefault}],""),y=f("div","ra-lim"),x=g([],""),b=f("div","ra-lim"),A=()=>{let Y=m.value||Jt?.find(ue=>ue.is_default)?.id;return Jt?.find(ue=>ue.id===Y)},M=()=>{let Y=A(),ue=Dt(Y,"image"),re=zi(Y);y.textContent=Y?`${t.context} ${Gr(Y.max_input_tokens)} \xB7 ${t.sMaxTokens} ${Gr(Y.max_tokens)}${ue===void 0?"":` \xB7 ${ue?t.sVisionYes:t.sVisionNo}`}${re?` \xB7 ${t.sPrice}: ${re}`:""}`:"";let he=ro(Y),ke=x.value;x.setOptions([{value:"",label:t.sEffortDefault,note:he?.def},...(he?.levels??[]).map(Te=>({value:Te,label:Te}))]),x.disabled=!he,x.value=he&&he.levels.includes(ke)?ke:"",b.textContent=he?"":t.sEffortNone,b.style.display=he?"none":""};m.el.addEventListener("change",M);let _=[];if(me?.models){if(await yn(),Ee!==c)return;let Y=Jt?.find(ue=>ue.is_default);_.push({value:"",label:t.sDefault,note:Y?.id});for(let ue of Jt??[]){let re=ue.price,he=re&&(re.input!==void 0||re.output!==void 0)?` \xB7 ${Lr(re.input??0,re.currency)} / ${Lr(re.output??0,re.currency)}`:"";_.push({value:ue.id,label:ue.id,note:`${Dt(ue,"image")?`${t.sVision} \xB7 `:""}${Gr(ue.max_input_tokens)} / ${Gr(ue.max_tokens)}${he}`})}}else _.push({value:"",label:t.sDefault});u.model&&!_.some(Y=>Y.value===u.model)&&_.push({value:u.model,label:u.model}),m.setOptions(_),m.value=u.model??"",M(),u.reasoningEffort&&x.options.some(Y=>Y.value===u.reasoningEffort)&&(x.value=u.reasoningEffort);let O=f("input");O.type="number",O.min="1",O.max="1000",O.step="1",O.value=String(u.maxTurns);let B=g([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),te=f("input");te.type="number",te.min="256",te.step="256",te.value=String(typeof u.maxTokens=="number"?u.maxTokens:8192),B.value=typeof u.maxTokens=="number"?"n":"auto",te.style.display=B.value==="n"?"":"none",B.el.addEventListener("change",()=>{te.style.display=B.value==="n"?"":"none"});let le=g([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...u.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],u.permissions),ge=(Y,...ue)=>{let re=f("div","ra-fld");return re.append(f("span","",Y),...ue),re},De=f("div","ra-row");De.append(B.el,te);let Rt=f("div","ra-pane");Rt.append(ge(t.sModel,m.el),y,ge(t.sEffort,x.el),b,ge(t.sMaxTurns,O),ge(t.sMaxTokens,De)),H!==!1&&Rt.append(ge(t.sPerms,le.el));let gt=u.compaction,xn=g([{value:"summary",label:t.sCompactSummary},{value:"trim",label:t.sCompactTrim}],gt.summarize===!1?"trim":"summary"),ra=(Y,ue)=>{let re=g([{value:"auto",label:t.sDefaultN.replace("{n}",qe(ue))},{value:"n",label:t.sCustomN}],Y!==void 0&&Y!==ue?"n":"auto"),he=f("input");he.type="number",he.min="1024",he.step="1024",he.value=String(Y??ue);let ke=f("div","ra-row");ke.append(re.el,he);let Te=()=>{he.style.display=re.value==="n"?"":"none"};return re.el.addEventListener("change",Te),Te(),{row:ke,read:()=>{if(re.value!=="n")return;let fo=parseInt(he.value,10);return Number.isFinite(fo)&&fo>=1024?fo:void 0},mode:re,input:he}},ur=ra(gt.reserveTokens,_t.reserveTokens??Xt.reserveTokens),pr=ra(gt.keepRecentTokens,_t.keepRecentTokens??Xt.keepRecentTokens),sa=ge(t.sKeepRecent,pr.row),oa=f("div","ra-lim"),lo=()=>{let Y=xn.value==="summary";sa.style.display=Y?"":"none";let ue=A(),re=q.maxInputTokens,he=typeof ue?.max_input_tokens=="number"&&ue.max_input_tokens>0?ue.max_input_tokens:128e3,ke=typeof re=="number"?Math.min(re,he):he,Te=zt(ke,{reserveTokens:ur.read()??_t.reserveTokens,keepRecentTokens:pr.read()??_t.keepRecentTokens}),la=ue?.id??(m.value||t.sDefault);oa.textContent=(Y?t.sCompactNote.replace("{keep}",qe(Te.keepRecentTokens)):t.sCompactNoteTrim).replace("{model}",la).replace("{at}",qe(Te.reserveTokens)).replace("{window}",qe(ke))};for(let Y of[xn.el,m.el,ur.mode.el,pr.mode.el])Y.addEventListener("change",lo);for(let Y of[ur.input,pr.input])Y.addEventListener("input",lo);lo();let ia=f("div","ra-pane");ia.append(ge(t.sCompact,xn.el),ge(t.sCompactAt,ur.row),sa,oa);let co=[],Ql=Y=>{let ue=f("div","ra-pane");for(let re of Y.fields){if(re instanceof HTMLElement){re.classList.add("ra-host"),ue.append(re);continue}if(re.type==="toggle"){let he=f("label","ra-tgl"),ke=f("input");ke.type="checkbox",ke.checked=re.value();let Te=f("span","",re.label);re.hint&&Te.append(f("small","",re.hint)),he.append(ke,Te),ue.append(he),co.push(()=>{ke.checked!==re.value()&&re.onChange(ke.checked)})}else{let he=g(re.options,re.value()),ke=ge(re.label,he.el);re.hint&&ke.append(f("small","",re.hint)),ue.append(ke),co.push(()=>{he.value!==re.value()&&re.onChange(he.value)})}}return ue},es=[Rt,ia,...(Oe??[]).map(Ql)];if(es.length>1){let Y=f("div","ra-tabs");Y.setAttribute("role","tablist");let ue=[t.sTabModel,t.sTabContext,...(Oe??[]).map(he=>he.label)].map((he,ke)=>{let Te=f("button","ra-tab",he);return Te.type="button",Te.setAttribute("role","tab"),Te.addEventListener("click",()=>re(ke)),Te}),re=he=>{Oi=he,es.forEach((ke,Te)=>{ke.hidden=Te!==he}),ue.forEach((ke,Te)=>{ke.classList.toggle("on",Te===he),ke.setAttribute("aria-selected",String(Te===he))})};Y.append(...ue),Ee.append(Y,...es),re(Math.min(Oi,es.length-1))}else Ee.append(Rt);let aa=f("div","ra-btns"),uo=f("button","ra-btn xs ghost",t.reset);uo.type="button";let po=f("button","ra-btn xs solid",t.apply);po.type="button",aa.append(uo,po),Ee.append(aa),uo.addEventListener("click",()=>{for(let Y of(Oe??[]).flatMap(ue=>ue.fields))Y instanceof HTMLElement||Y.default===void 0||(Y.type,Y.value()!==Y.default&&Y.onChange(Y.default));Ue={},_i({}),lr=null;for(let Y of He.values())Di(Y,{},null);Le(),G.notify(t.applied),mt(F)}),po.addEventListener("click",()=>{let Y={};m.value&&(Y.model=m.value);let ue=parseInt(O.value,10);if(Number.isFinite(ue)&&ue>0&&Math.min(1e3,ue)!==(q.maxTurns??100)&&(Y.maxTurns=Math.min(1e3,ue)),B.value==="n"){let Te=parseInt(te.value,10);Number.isFinite(Te)&&Te>0&&(Y.maxTokens=Te)}x.value&&!x.disabled&&(Y.reasoningEffort=x.value),(le.value==="ask"||le.value==="auto")&&(lr=le.value);let re=xn.value==="summary";re!==_t.summarize&&(Y.summarize=re);let he=ur.read();he!==void 0&&(Y.reserveTokens=he);let ke=pr.read();ke!==void 0&&(Y.keepRecentTokens=ke);for(let Te of co)Te();Vr(Y),Le(),G.notify(t.applied)})};Xe.addEventListener("click",()=>{so()});let Ii=[],Le=()=>{Ee?.remove(),Ee=null;for(let o of Ii.splice(0))o.close()},Zr=o=>{ee.append(o),o.style.top=`${xe.offsetTop+xe.offsetHeight+4}px`},Ui=async()=>{if(Ee){Le();return}if(!F?.workspace)return;let o=F.workspace,c=f("div","ra-menu");Ee=c,Zr(c);let u=[];try{u=await o.sessions.list()}catch{}if(Ee!==c)return;let g=F,m=u.filter(b=>b.id!==g.id),y=u.find(b=>b.id===g.id),x=b=>{let A=!b||b.id===g.id,M=f("div","ra-mi"+(A?" ra-cur":"")),_=f("button");_.type="button";let O=b?He.get(b.id):void 0,B=b&&O&&O!==g?Wt.has(b.id)?` \xB7 ${t.waitingAnswer}`:O.busy||O.queued.length?` \xB7 ${t.running}`:"":"",te=f("span","ra-mt");if(B&&!Wt.has(b.id)&&te.append(f("span","ra-spin")),te.append(f("span","ra-mtt",(b?b.title:Ir(g))||t.untitled)),A&&(te.append(f("span","ra-now",t.current)),M.setAttribute("aria-current","true")),_.append(te,f("small","",b?`${b.messages} ${t.messages} \xB7 ${new Date(b.savedAt).toLocaleString()}${B}`:t.notSaved)),_.addEventListener("click",()=>{Le(),b&&!A&&na(b.id).catch(le=>G.notify(le.message,"error"))}),M.append(_),b){let le=f("button","ra-x");le.type="button",le.innerHTML=I.trash(),le.title=t.delete,le.setAttribute("aria-label",t.delete),le.addEventListener("click",async ge=>{ge.stopPropagation(),Le(),await bt(ee,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await ao(b.id,!1,b.workspace).catch(De=>G.notify(De.message,"error"))}),M.append(le)}return M};c.append(x(y??null)),m.length?c.append(f("div","ra-sep")):c.append(f("div","ra-none",t.noSessions));for(let b of m)c.append(x(b));if(m.length){let b=f("div","ra-mf"),A=f("button","ra-btn xs ghost");A.type="button",A.innerHTML=I.trash()+ve(t.deleteAll),A.addEventListener("click",async()=>{if(Le(),!!await bt(ee,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let M of u)await ao(M.id,!0,M.workspace);await bn()}catch(M){G.notify(M.message,"error")}}),b.append(A),c.append(b)}};Je.addEventListener("click",()=>{Ui()}),Ie.addEventListener("click",()=>{Le(),bn().catch(o=>G.notify(o.message,"error"))}),We.addEventListener("click",async()=>{Le(),await bt(ee,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await Qr().catch(o=>G.notify(o.message,"error"))}),document.addEventListener("click",Fi,!0);function Fi(o){o.target?.closest?.(".ra-selp")||Ee&&!Ee.contains(o.target)&&!Je.contains(o.target)&&!Xe.contains(o.target)&&!nt.contains(o.target)&&!Ve.contains(o.target)&&Le()}let Ct=f("input");Ct.type="file",Ct.accept=".zip,application/zip",Ct.multiple=!0,Ct.style.display="none",ee.append(Ct);let Ni=async o=>{let c=F?.workspace;if(!c||!o?.length)return;let u=[];for(let g of Array.from(o)){if(!/\.zip$/i.test(g.name)&&g.type!=="application/zip"&&g.type!=="application/x-zip-compressed"){G.notify(`${g.name}: ${t.notZip}`,"warning");continue}try{u.push(...(await c.installSkill(g)).map(m=>m.name))}catch(m){G.notify(`${g.name}: ${m.message}`,"error")}}u.length&&G.notify(t.skillsInstalled.replace("{names}",u.join(", "))),await Pt(),Ee?.classList.contains("ra-skm")&&(Le(),Hi())};Ct.addEventListener("change",()=>{Ni(Ct.files),Ct.value=""});let Hi=async()=>{if(Ee){let y=Ee.classList.contains("ra-skm");if(Le(),y)return}let o=F?.workspace;if(!o)return;let c=f("div","ra-menu ra-skm");Ee=c,Zr(c);let u=[];try{u=await o.skills()}catch(y){G.notify(y.message,"error")}if(Ee!==c)return;let g=f("div","ra-skh"),m=f("button","ra-btn xs solid");m.type="button",m.innerHTML=I.upload(13)+`<span>${ve(t.uploadZip)}</span>`,m.addEventListener("click",()=>Ct.click()),o.userSkillsDir||(m.style.display="none"),g.append(f("span","",u.length?`${t.skills} \xB7 ${u.length}`:t.skills),m),c.append(g),u.length||c.append(f("div","ra-none",t.noSkills));for(let y of u){let x=f("div","ra-mi"),b=f("button");b.type="button",b.title=t.useSkill;let A=f("span","ra-mt"),M=!!y.from&&/\.zip$/i.test(y.from);A.append(f("span","ra-mtt",y.name),f("span","ra-skb",y.builtin?t.builtinSkill:M?"zip":t.skillFolder)),y.disableModelInvocation&&A.append(f("span","ra-skb",t.manualOnly)),b.append(A,f("small","",y.description)),b.addEventListener("click",()=>{Le(),z.value=`/skill:${y.name} `,z.focus(),Ze()});let _=(le,ge,De,Rt="ra-x ra-ia")=>{let gt=f("button",Rt);return gt.type="button",gt.innerHTML=le,gt.title=ge,gt.setAttribute("aria-label",ge),gt.addEventListener("click",xn=>{xn.stopPropagation(),De()}),gt},O=_(I.eye(),t.open,()=>{Le(),Qn(y.from&&!M?`${y.from}/SKILL.md`:y.path)}),B=_(I.download(),t.download,()=>{M?je.download(y.from):je.downloadFolder(y.from??y.dir)}),te=_(I.trash(),t.delete,async()=>{Le();let le=M?u.filter(De=>De.from===y.from).map(De=>De.name):[y.name],ge=le.length>1?t.confirmDeleteZip.replace("{zip}",y.from.replace(/^.*\//,"")).replace("{names}",le.join("\u3001")):t.confirmDeleteSkill.replace("{name}",y.name).replace("{path}",y.from??"");if(await bt(ee,t.delete,ge,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await o.removeSkill(y.name),await Pt(),G.notify(t.skillRemoved.replace("{name}",le.join(", ")))}catch(De){G.notify(De.message,"error")}},"ra-x");(y.builtin||!y.from?.startsWith((o.userSkillsDir??"\0")+"/"))&&(te.style.display="none"),x.append(b,O,B,te),c.append(x)}c.append(f("div","ra-skf",(o.userSkillsDir?t.skillsHint.replace("{user}",o.userSkillsDir):t.skillsHintNoUser).replace("{dir}",o.skillsDir))),o.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")),o.userSkillsDir&&c.addEventListener("drop",y=>{y.preventDefault(),y.stopPropagation(),c.classList.remove("drop"),Ni(y.dataTransfer?.files)})};nt.addEventListener("click",()=>{Hi()});let ji=o=>G.notify(o.message,"error"),wn=!1,Bl=o=>{let c=[`# ${Ir(o)}`,""];for(let u of o.messages){if(u.role==="tool"||u.role==="system")continue;let g=nn(u.content).trim(),m=u.role==="user"&&typeof u.content=="string"?ze(u):null;if(m!==null){c.push(`> **${t.compacted}**`,">",...m.split(`
|
|
748
|
+
`).map(x=>`> ${x}`),"");continue}let y=u.role==="assistant"?(u.tool_calls??[]).filter(x=>!Xs.has(x.function.name)):[];if(!(!g&&!y.length)){c.push(`## ${u.role==="user"?t.user:t.assistant}`,""),g&&c.push(g,"");for(let x of y){let b=x.function.arguments;try{b=JSON.parse(x.function.arguments)}catch{}let A=jo(x.function.name,b);c.push(`- \`${x.function.name}\`${A?` ${A}`:""}`)}y.length&&c.push("")}}return c.join(`
|
|
749
|
+
`)},qi=o=>{let c={...Ue};o.is_default&&!q.model?delete c.model:c.model=o.id;let u=ro(o);c.reasoningEffort&&!u?.levels.includes(c.reasoningEffort)&&delete c.reasoningEffort,Vr(c)},Bi=async o=>{let c=F;if(c.busy)return G.notify(t.busyCmd,"warning"),!1;wn=!0;try{let u=await c.compact(o);return u||G.notify(t.nothingToCompact),u}catch(u){if(!/abort/i.test(u.message??"")&&u.name!=="AbortError")throw u;return G.notify(t.stopped),!1}finally{wn=!1,F===c&&(nr(),mt(c),setTimeout(()=>{F===c&&!c.busy&&St(!1)},0))}},Jr=o=>{let c=o.messages,u=c.length-1;for(;u>=0&&!(c[u].role==="user"&&ze(c[u])===null);)u--;let g=c[u];if(!g)return null;let m=g.typed??nn(g.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,""),y=Array.isArray(g.content)?g.content.length>1:/(^|\n)\[attachments\]/.test(String(g.content??""));return{index:u,msg:g,text:m.trim(),files:y}},Wl=async(o,c,u)=>{let g=o.model||(await o.modelInfo())?.id,m=Jr(o)?.msg.content,y=Array.isArray(m)&&m.some(b=>b.type==="image_url"),x=(await yn()).filter(b=>b.id!==g&&(b.max_input_tokens??0)>u&&(!y||Dt(b,"image")!==!1)).sort((b,A)=>b.max_input_tokens-A.max_input_tokens);return x.find(b=>b.max_input_tokens>=c*1.2)??x[x.length-1]},Wi=async o=>{let c=Jr(o);return c?(await o.rewind(c.index),F===o&&(hn(o.messages),mt(o)),c):null},Ki=async(o,c)=>{F===o&&!o.busy&&(dt=er(c)),await o.prompt(c)},Kl=async o=>{let c=Jr(o);wn=!0;let u=null;try{u=await o.summarize(c?.msg)}finally{wn=!1,nr()}await new Promise(m=>setTimeout(m,0)),await(Ke?Qr():bn().then(()=>{}));let g=F;u?(await g.seed(u),hn(g.messages),mt(g)):o.messages.length>1&&G.notify(t.ovNoSummary,"warning"),St(!1),c&&(c.files?(await mi(c.msg),z.value=c.text,Gt(),z.focus()):c.text&&await Ki(g,c.text))},Vl=async(o,c)=>{let u=async()=>{await new Promise(B=>setTimeout(B,0)),await o.continue()},g=o.messages.slice(0,Jr(o)?.index??0),m=g.some(B=>ze(B)===null),y=[],x={label:t.ovEdit,run:async()=>{let B=await Wi(o);B&&(z.value=B.text,Gt(),z.focus())}},b={label:t.ovCompact,run:async()=>{await Bi(),await u()}},A={label:t.ovNew,run:()=>Kl(o)};c.cause==="attachments"?y.push({label:t.ovDropFiles,run:async()=>{let B=await Wi(o);B&&(B.text?await Ki(o,B.text):(G.notify(t.ovNoText,"warning"),z.focus()))}}):c.cause==="message"?y.push(x):c.cause==="tools"?s&&y.push({label:t.ovToolSettings,run:async()=>s()}):c.cause==="history"?(m&&y.push(b),y.push(A)):(m&&y.push(b),g.length&&y.push(A),y.push(x));let M=await Wl(o,c.used,c.window).catch(()=>{});if(M&&y.push({label:t.ovUseModel.replace("{name}",M.id),run:async()=>{qi(M),await u()}}),F!==o)return;let _={attachments:t.ovAttachments,message:t.ovMessage,tools:t.ovTools,history:t.ovHistory,model:t.ovModel}[c.cause],O={render:()=>{let B=f("div","ra-err ra-over",_);B.setAttribute("role","alert");let te=f("div","ra-acts");for(let le of y){let ge=f("button","ra-btn xs",le.label);ge.type="button",ge.addEventListener("click",()=>{if(o.busy){G.notify(t.busyCmd,"warning");return}we.remove(O),le.run().catch(De=>{qr(De.message),St(!1)})}),te.append(ge)}return y.length&&B.append(te),B}};Tt(O),we.schedule()},Gl=(o,c)=>{let u=c.toLowerCase(),g=o.find(y=>y.id.toLowerCase()===u);if(g)return g;let m=o.filter(y=>y.id.toLowerCase().includes(u));return m.length===1?m[0]:m.find(y=>y.id.toLowerCase().startsWith(u))},oo=[{name:"help",run:()=>{let o=io().map(c=>`- \`/${c.name}${c.args?` ${c.args}`:""}\` \u2014 ${c.description}`);or(t.cmdsTitle,[...o,"",t.cmdsMore].join(`
|
|
750
|
+
`))}},{name:"new",aliases:["clear"],run:()=>(Le(),Ke?Qr():bn().then(()=>{}))},{name:"resume",run:()=>Ui()},{name:"compact",args:t.cmdArgs.compact,run:async o=>{await Bi(o)}},{name:"continue",run:async()=>{if(F.busy){G.notify(t.busyCmd,"warning");return}if(!F.messages.length){G.notify(t.nothingToContinue);return}await F.continue()}},{name:"model",args:t.cmdArgs.model,run:async o=>{if(!o)return so();let c=Gl(await yn(),o);if(!c){G.notify(t.unknownModel.replace("{name}",o),"warning");return}qi(c),G.notify(t.modelSet.replace("{name}",c.id))}},{name:"effort",args:t.cmdArgs.effort,run:async o=>{let c=await yn(),u=F.model||c.find(A=>A.is_default)?.id,g=c.find(A=>A.id===u),m=ro(g),y=g?.id??u??"?";if(!m){G.notify(`${y}: ${t.sEffortNone}`,"warning");return}let x=m.levels.join(" / ");if(!o){G.notify(t.effortLevels.replace("{model}",y).replace("{levels}",x));return}let b={...Ue};if(/^(default|auto|默认)$/i.test(o))delete b.reasoningEffort;else if(m.levels.includes(o.toLowerCase()))b.reasoningEffort=o.toLowerCase();else{G.notify(t.unknownEffort.replace("{name}",o).replace("{model}",y).replace("{levels}",x),"warning");return}Vr(b),G.notify(t.effortSet.replace("{name}",b.reasoningEffort??(m.def?`${t.sEffortDefault} \xB7 ${m.def}`:t.sEffortDefault)))}},{name:"context",run:async()=>{let o=F,[c,u,g]=await Promise.all([o.context(),o.limits(),o.modelInfo()]),m=zi(g),y=Math.round(c.used/c.window*100),x=o.usage,b=[`- ${t.sModel}: ${o.model||(await yn()).find(A=>A.is_default)?.id||t.sDefault}`,`- ${t.context}: ${y<1&&c.used?"<1":y}% \xB7 ${qe(c.used)} / ${qe(c.window)} tokens \xB7 ${t.sMaxTokens} ${qe(u.output)}`,m?`- ${t.sPrice}: ${m}`:"",`- ${t.messagesLabel}: ${o.messages.length}`,x.calls?`- ${_r(t.usageLine.replace("{cost}",qo(x.total_cost,g?.price?.currency)).replace("{tokens}",qe(x.prompt_tokens+x.completion_tokens)).replace("{calls}",String(x.calls)))}`:"",`- ${Zi(o,c.window)}`,o.workspace?`- ${t.directory}: \`${o.workspace.id}\``:""].filter(Boolean);or(t.context,b.join(`
|
|
751
|
+
`))}},{name:"export",run:()=>{if(!F.messages.length){G.notify(t.nothingToExport);return}let o=Ir(F).replace(/[\\/:*?"<>|\s]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"conversation";Er(`${o}.md`,Bl(F),"text/markdown;charset=utf-8")}},{name:"files",run:()=>oe===!1?void 0:Ne.click()},{name:"settings",run:()=>so()},{name:"debug",run:()=>{Vt?tt.click():G.notify(t.debugOff)}}],io=()=>oo.filter(o=>(o.name!=="files"||!!F?.workspace&&oe!==!1)&&(o.name!=="settings"||Ri)&&(o.name!=="debug"||Vt)&&(o.name!=="resume"||!l&&!!F?.workspace&&!Ke)).map(o=>({name:o.name,description:o.name==="new"&&Ke?t.confirmClear.split(/[??]/)[0]:t.cmd[o.name]??"",kind:t.command,args:o.args,builtin:!0})),Zl=o=>{let c=/^\/(\S+)(?:\s+([\s\S]*))?$/.exec(o);if(!c)return!1;let u=c[1].toLowerCase(),g=oo.find(m=>m.name===u||m.aliases?.includes(u));if(!g||!io().some(m=>m.name===g.name))return!1;z.value="",Ze();try{Promise.resolve(g.run((c[2]??"").trim())).catch(ji)}catch(m){ji(m)}return!0},Vi=o=>{if(o.builtin&&(!o.args||z.value.trim()===`/${o.name}`)){z.value=`/${o.name}`,gn("prompt");return}z.value=`/${o.name} `,Ze()},Xr,mt=o=>{if(!(se===!1||F!==o)){if(!o.messages.length){Ve.style.display="none",Ee?.classList.contains("ra-use")&&Le();return}Promise.all([o.context(),o.modelInfo()]).then(([c,u])=>{if(F!==o)return;Xr=u?.price?.currency;let g=Math.min(1,c.used/c.window),m=8,y=2*Math.PI*m;Ve.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 x=`${Gi(t.context)} ${Ji(c.used,c.window)}`;Ve.title=x,Ve.setAttribute("aria-label",x),Ve.style.display="",Ee?.classList.contains("ra-use")&&Xi(Ee,o,c)})}},Gi=o=>o.charAt(0).toUpperCase()+o.slice(1),Zi=(o,c)=>{let u=o.compactionFor(c);return`${u.summarize?t.autoCompact:t.autoTrim}: ${t.autoCompactAt.replace("{n}",qe(u.reserveTokens))}`},Ji=(o,c)=>{let u=o/c;return o&&u<.01?"<1%":`${Math.round(Math.min(1,u)*100)}%`},Xi=(o,c,u)=>{let g=Math.min(1,u.used/u.window),m=c.usage;o.className="ra-menu ra-use"+(g>=.9?" hi":g>=.7?" mid":"");let y=f("div","ra-uh");y.append(f("span","",Gi(t.context)),f("b","",Ji(u.used,u.window)));let x=f("div","ra-ubar"),b=f("i");b.style.width=`${Math.max(g,u.used?.01:0)*100}%`,x.append(b);let A=f("div","ra-usub");A.append(f("span","",t.uOf.replace("{used}",qe(u.used)).replace("{window}",qe(u.window))),f("span","",c.model||Jt?.find(B=>B.is_default)?.id||""));let M=f("div","ra-ugrid");for(let[B,te]of[[t.uCost,qo(m.total_cost,Xr)],[t.uIn,qe(m.prompt_tokens)],[t.uOut,qe(m.completion_tokens)],[t.uCalls,String(m.calls)]]){let le=f("div");le.append(f("small","",B),f("b","",te)),M.append(le)}o.replaceChildren(y,x,A,M),o.append(f("div","ra-unote",Zi(c,u.window)));let _=f("div","ra-mf"),O=f("button","ra-btn xs ghost");O.type="button",O.textContent=t.compactNow,O.disabled=c.busy||wn,O.addEventListener("click",()=>{Le(),Promise.resolve(oo.find(B=>B.name==="compact").run("")).catch(B=>G.notify(B.message,"error"))}),_.append(O),o.append(_)},Jl=async()=>{if(Ee?.classList.contains("ra-use")){Le();return}if(Le(),!F)return;let o=F,c=f("div","ra-menu ra-use");Ee=c,Zr(c);let u=await o.context();Ee===c&&F===o&&Xi(c,o,u)};Ve.addEventListener("click",()=>{Jl()});let Yi=(o,c)=>{if(!c)return;let u=()=>{try{o.continue().catch(g=>G.notify(g.message,"error"))}catch(g){G.notify(g.message,"error")}};c.overflow?Vl(o,c.overflow):c.reason==="error"?qr(c.error??t.error,o.messages.length?u:void 0):c.reason==="max_turns"?Il(t.maxTurns.replace("{n}",String(o.settings.maxTurns)),{label:t.continueRun,onClick:u},t.maxTurnsHint):or(t.stopped)},Qi=async o=>{for(let m of Xn)m();if(Xn=[],o.workspace){let m=o.workspace;Xn.push(m.onChange(y=>{m.isSkillPath(y.path)&&Pt()}))}F&&F!==o&&Yn.set(F.id,G.park()),F!==o&&ir(),F=o,He.set(o.id,o),Qo(o),Ur(o),G.restore(Yn.get(o.id)??[]),Yn.delete(o.id),Hs(o.id),Kt(),Bt.clear(),X=null,dt=null,Nt.textContent=o.model??"",Nt.style.display=o.model?"":"none";let c=!l&&(N??!!o.workspace);Je.style.display=Ie.style.display=c&&o.workspace?"":"none",Ke=!(c&&o.workspace),an(),Ne.style.display=o.workspace&&oe!==!1?"":"none",nt.style.display=o.workspace&&C!==!1?"":"none",je.setWorkspace(o.workspace),Vt&&st.setAgent(o),we.clear(),li(),St(o.busy),ar(),l||cl(ae,o.id);let u=(m,y)=>Xn.push(o.on(m,y));u("run_start",m=>{an(),m.message&&(dt&&!dt.msg?(dt.msg=m.message,dt.update()):er(m.message.content,m.message),ii(o,m.message)),dt=null,X=null,tr=Date.now(),St(!0),ut()}),u("turn_start",()=>{rr(!0),X&&(X.text=null,X.md="",X.drawn=void 0,X.drawnFinal=void 0,X.think=null,X.thinkBody=null,X.reasoning=""),ut(),queueMicrotask(pt)}),u("steered",m=>{nr(),tr=Date.now();for(let y of m.messages)er(y.content,y);pt()}),u("queued",()=>pt()),u("rewind",()=>{F===o&&(hn(o.messages),mt(o))}),u("text_delta",m=>{let y=Hr();Vs(y),y.text||(y.text=f("div","ra-md"),Ks(y.body,y.text)),y.md=m.text,ki()}),u("reasoning_delta",m=>{let y=Hr();if(!y.pending&&!y.text&&ut(),!y.think){[y.think,y.thinkBody]=xi("",!1),y.think.style.display="none";let x=wi(y.body);x instanceof HTMLDetailsElement&&x.classList.contains("ra-tg")&&!y.text?x.querySelector(".ra-tgb").append(y.think):y.text?y.body.insertBefore(y.think,y.text):Ks(y.body,y.think)}y.reasoning=m.text,ki()}),u("message_reset",()=>{X&&(X.md="",X.reasoning="",X.text?.remove(),X.text=null,X.think?.remove(),X.think=null,X.thinkBody=null,ut())}),u("message_end",()=>{Vs(),rr(!0),fn=Date.now()}),u("tool_start",m=>{if(Xs.has(m.name))return;rr(!0);let y=Dl(m.id,m.name,m.args,Hr().body,m.parentId?Bt.get(m.parentId):void 0),x=Mi({name:m.name,args:m.args},y.el);ut(x.title?`${x.verb} ${x.what}`:x.verb,Ll(m.name,m.args))}),u("tool_update",m=>{let y=Bt.get(m.id);y&&(y.update||(y.update=f("div","ra-tupd"),y.el.append(y.update)),y.update.textContent=m.content,X?.pending&&ut(X.pending.firstElementChild.textContent??t.waiting,{text:m.content}),we.schedule())}),u("tool_end",m=>{let y=Bt.get(m.id);if(y)Ai(y,m.status,m.result,m.durationMs,Js(m.content),m.details);else{let b=Zn.get(m.id);b&&(b.status=m.status,b.result=m.result,Zn.delete(m.id))}let x=y?.args&&typeof y.args=="object"?y.args.path:void 0;m.status==="ok"&&typeof x=="string"&&/^(write_file|edit_file|delete_file)$/.test(m.name)&&je.changed(x),X?.pending&&!X.body.querySelector(".ra-tend .ra-spin")&&ut()});let g=null;u("compaction_start",m=>{m.runId||(St(!0),tr=Date.now()),ut(t.compactingNow)}),u("compaction",m=>{if(m.runId?X?.pending&&ut():nr(),!m.summary&&m.runId&&g===m.runId)return;m.summary||(g=m.runId??null);let y=o.messages[0],x=y&&typeof y.content=="string"?ze(y):null;or(m.summary?t.compacted:t.trimmed,m.summary&&x?x:void 0)}),u("run_end",m=>{Lt=m.reason==="done"&&!z.value.trim()?Br:null,Br=null;let y=X;nr();let x=[...o.messages].reverse().find(b=>b.role==="assistant");y&&y.body.childElementCount&&x&&!y.el.querySelector(":scope>.ra-af")&&(y.el.append(hi(x)),we.schedule()),G.cancelAll(),Yi(o,m.reason==="done"?null:o.lastEnd??{reason:m.reason,error:m.error?.message,at:Date.now()}),St(!1),mt(o),Pt(),je.refresh(),qs()});try{await o.ready()}catch(m){qr(m.message)}F!==o||!Dr||(Se?.(o),hn(o.messages),o.busy||Yi(o,o.lastEnd),mt(o),qs(),await Pt())},Xl=()=>`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ea=async o=>{let c=o??Xl(),u=typeof d=="function"?await d(c):d??null,g=q.instructions,m=q.fileTools,y=m===void 0||m===!0||Array.isArray(m)&&(m.includes("write_file")||m.includes("edit_file")),x=m===!1?"":y?oe===!1?qd(ce):Wd(ce):Bd(ce),b=!u||!x?g:typeof g=="function"?()=>[g(),x].filter(Boolean).join(`
|
|
752
|
+
|
|
753
|
+
`):[g,x].filter(Boolean).join(`
|
|
754
|
+
|
|
755
|
+
`),A={};return Ue.model&&(A.model=Ue.model),Ue.maxTurns&&(A.maxTurns=Ue.maxTurns),Ue.maxTokens&&(A.maxTokens=Ue.maxTokens),Ue.reasoningEffort&&(A.extra={...q.extra??{},reasoning_effort:Ue.reasoningEffort}),lr&&(A.permissions=lr),new Ut(me,{...q,...A,tools:$i,instructions:b,id:c,workspace:u,ui:q.ui??Tl(c)})},Yr=o=>{st.forget(o),typeof d=="function"&&o.workspace?.close()},cr=null,ta=o=>{if(l)return Promise.reject(new Error("newSession/resume need the chat to own its agent (pass a provider, not an agent)"));if(cr)return cr;let c=(async()=>{if(o&&o===F?.id)return F;let u=F;if(u)if(u.busy||u.queued.length>0){if(js().length>=kl)return G.notify(t.bgLimit.replace("{n}",String(js().length)),"warning"),u;Sl(u)}else He.delete(u.id),Yr(u);let g=o&&He.get(o)||await ea(o);return await Qi(g),g})();return cr=c,c.finally(()=>{cr===c&&(cr=null)}).catch(()=>{}),c},bn=()=>ta(),Qr=async()=>{await dr;let o=F??l;G.cancelAll(),await o.clear(),(F===o||l===o)&&(hn(o.messages),mt(o),pt(),ar())},na=o=>ta(o),ao=async(o,c=!1,u)=>{if(await dr,l)throw new Error("deleteSession needs the chat to own its agent (pass a provider, not an agent)");let g=F.workspace;if(g){if(o!==F.id){let m=He.get(o);m&&(Hs(o,!1),Yn.delete(o),await m.abort(),He.delete(o),Ur(m),Yr(m),Kt()),await g.sessions.delete(o,u),qs();return}G.cancelAll(),await F.abort(),typeof d=="function"?await g.destroy():await g.sessions.delete(o,g.id),cl(ae,null),c||await bn()}},Yl=q.id??(typeof p=="string"?p:p===!1?void 0:Zd(ae)??void 0),dr=(l?Promise.resolve(l):ea(Yl)).then(o=>Qi(o));return dr.catch(o=>{qr(`${o.message}`),St(!1)}),{get agent(){return F??l},get ready(){return dr},element:ee,ui:G,prompt:async o=>(await dr,F.busy||(dt=er(o)),F.prompt(o)),setInput(o){z.value=o,z.focus(),Ze()},insertText(o){let c=document.activeElement===z?z.selectionStart:z.value.length,u=document.activeElement===z?z.selectionEnd:c,g=z.value.slice(0,c),m=z.value.slice(u),y=(g&&!/\s$/.test(g)?" ":"")+o+(m&&/^\S/.test(m)?" ":m?"":" ");z.value=g+y+m,z.focus(),z.setSelectionRange(g.length+y.length,g.length+y.length),Ze()},newSession:bn,resume:na,deleteSession:o=>ao(o),clear:Qr,addContext:Pi,setDebug(o){Vt=o,Fr()},updateComposerAction(o,c){let u=Go.get(o);u&&(Object.assign(u.a,c),Zo(u.btn,u.a))},setAppearance(o){o.theme&&($e=o.theme),o.palette&&(it=o.palette),o.vars!==void 0&&(Hn=o.vars),jn()},refresh:Pt,unmount(){if(Dr){Dr=!1,pn&&clearTimeout(pn);for(let o of Xn)o();G.cancelAll(!0),Le(),document.removeEventListener("click",Fi,!0),rn?.removeEventListener?.("change",qn),At!==null&&clearTimeout(At),Jn!==null&&cancelAnimationFrame(Jn),we.dispose(),ri?.disconnect(),je.dispose(),st.dispose();for(let o of ft)o.preview&&URL.revokeObjectURL(o.preview);for(let o of[...$t.keys()])Hs(o,!1);if(!l)for(let o of He.values())Ur(o),o.abort().finally(()=>Yr(o));He.clear(),Yn.clear(),$t.clear(),ft.length=0,ht.length=0,ee.remove()}}}}var Jd=/^(text\/|application\/(json|xml|yaml|javascript|x-sh))/;function Ko(r){let e=Q(r);return e==="/"?[]:e.slice(1).split("/")}function yl(r){return new Error(`No such file: ${Q(r)}`)}function wl(r,e={}){let n=async(l,d=!1)=>{let p=r;for(let h of l)p=await p.getDirectoryHandle(h,{create:d});return p},t=async(l,d=!1)=>{let p=Ko(l);if(!p.length)throw new Error(`${Q(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:Q(l),size:p.size,contentType:p.type||yt(l,new Uint8Array),mtime:p.lastModified}},i=async(l,d,p)=>{for await(let[h,w]of l){let k=`${d}/${h}`;w.kind==="directory"?await i(w,k,p):p.push(await s(k,w))}},a={description:e.description??`the local folder "${r.name}"`,async list(l){let d=[],p=Ko(l),h;try{h=await n(p)}catch{try{let w=await t(l);return[await s(l,w)]}catch{return d}}return await i(h,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 yl(l)}let p=await d.getFile(),h=new Uint8Array(await p.arrayBuffer()),w=p.type||yt(l,h);if(Jd.test(w)){let k=wt(h);if(k!==null)return k}return h}};return e.readonly||(a.write=async(l,d)=>{let h=await(await t(l,!0)).createWritable();try{await h.write(d)}finally{await h.close()}},a.delete=async l=>{let d=Ko(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(h){throw h?.name==="NotFoundError"?yl(l):new Error(`${l}: ${h?.message??String(h)}`)}}),a}return ic(Xd);})();
|