@runappsai/agent 0.1.15 → 0.2.0
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 +45 -45
- package/dist/agent.d.ts +20 -0
- package/dist/agent.umd.js +117 -110
- package/dist/chat.d.ts +37 -7
- package/dist/chat.js +155 -37
- package/dist/debug-panel.d.ts +1 -1
- package/dist/debug-panel.js +1 -1
- package/dist/dialogs.js +43 -1
- package/dist/index.cjs +41 -1
- package/dist/index.d.ts +2 -2
- package/dist/types.d.ts +36 -2
- package/dist/ui.cjs +166 -34
- package/dist/ui.d.ts +1 -0
- package/dist/vlist.d.ts +6 -0
- package/dist/vlist.js +16 -0
- package/docs/chat-ui.md +49 -0
- package/docs/tools.md +1 -0
- package/package.json +1 -1
package/dist/agent.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/* @runappsai/agent 0.
|
|
2
|
-
"use strict";var RunAppsAgent=(()=>{var
|
|
1
|
+
/* @runappsai/agent 0.2.0 */
|
|
2
|
+
"use strict";var RunAppsAgent=(()=>{var Os=Object.defineProperty;var nd=Object.getOwnPropertyDescriptor;var rd=Object.getOwnPropertyNames;var sd=Object.prototype.hasOwnProperty;var od=(r,e,n)=>e in r?Os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var id=(r,e)=>{for(var n in e)Os(r,n,{get:e[n],enumerable:!0})},ad=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of rd(e))!sd.call(r,s)&&s!==n&&Os(r,s,{get:()=>e[s],enumerable:!(t=nd(e,s))||t.enumerable});return r};var ld=r=>ad(Os({},"__esModule",{value:!0}),r);var N=(r,e,n)=>od(r,typeof e!="symbol"?e+"":e,n);var op={};id(op,{Agent:()=>Xt,CHAT_COLOR_TOKENS:()=>Jl,CHAT_PALETTES:()=>bo,CHAT_SHARED_TOKENS:()=>Yl,ContextOverflowError:()=>Vt,DEFAULT_COMPACTION:()=>En,DEFAULT_SKILLS_DIR:()=>wi,DEFAULT_USER_SKILLS_DIR:()=>bi,MCPError:()=>ze,PartialReadError:()=>$n,ProviderError:()=>st,Scheduler:()=>ur,UNTITLED:()=>Jt,VirtualList:()=>mr,WEB_TOOL_NAMES:()=>Ti,Workspace:()=>ar,applyEdits:()=>Zs,askUserTool:()=>uo,buildSystemPrompt:()=>Fs,buildZip:()=>Vs,changeTask:()=>fr,checkSchedule:()=>pr,collectCompletion:()=>Gr,configurePdf:()=>ul,connectMCP:()=>Il,createAgent:()=>xu,decodeText:()=>$t,defineTool:()=>Ne,describeSchedule:()=>is,directoryFS:()=>mc,domUI:()=>co,enhanceSelect:()=>ac,escapeHTML:()=>Ce,estimateTokens:()=>_e,expandSlash:()=>js,extractPdfText:()=>or,fileGuard:()=>lr,fileTools:()=>ro,fitBudget:()=>Kr,formatLocalTime:()=>ot,formatPdfText:()=>ir,groupTurns:()=>ii,guessType:()=>At,isContextOverflow:()=>Ns,isPdf:()=>sr,listTemplates:()=>Us,listZip:()=>Ks,localSchedules:()=>ho,makeTask:()=>as,memoryFS:()=>wl,memorySchedules:()=>Rl,modelAccepts:()=>Zt,nextRun:()=>Pn,normalizeForFuzzyMatch:()=>hi,normalizePath:()=>Q,normalizeResult:()=>Jr,nullUI:()=>Si,openAIProvider:()=>el,openWorkspace:()=>vu,parseCommandArgs:()=>ui,parseCron:()=>os,parseFrontmatter:()=>fi,parseLocalTime:()=>Ln,parseSkill:()=>Xr,planCut:()=>Is,readZipEntry:()=>er,renderChat:()=>fc,renderInline:()=>zt,renderMarkdown:()=>hr,runInSandbox:()=>ki,runappsProvider:()=>oi,sandboxTool:()=>oo,scheduleTools:()=>mo,selectBox:()=>_n,serializeConversation:()=>Zr,skillFoldersOf:()=>Qr,skillZipFS:()=>nr,splitForSummary:()=>Hs,sseData:()=>Wr,subFS:()=>es,substituteArgs:()=>pi,summaryMessage:()=>Vr,summaryOf:()=>Be,titleOf:()=>An,toProvider:()=>gt,validateSchema:()=>so,webTools:()=>io});function Zt(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 st=class extends Error{constructor(n,t,s={}){super(t);N(this,"status");N(this,"code");N(this,"retryAfter");this.name="ProviderError",this.status=n,this.code=s.code,this.retryAfter=s.retryAfter}get statusCode(){return this.status}},cd={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"},Vt=class extends st{constructor(n,t,s=400){super(s,cd[n.cause],{code:"context_overflow"});N(this,"overflow");N(this,"detail");this.name="ContextOverflowError",this.overflow=n,this.detail=t}},dd=/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 Vt)return!0;let e=zs(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&&dd.test(r.message)}function Qa(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 zs(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 oi(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 gt(r){if(typeof r.stream=="function")return r;if(typeof r.chat?.stream=="function")return oi(r);throw new Error("pass a ModelProvider (with stream()) or a RunApps client")}function el(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 st(0,`network error: ${d.message}`)}if(!l.ok)throw await Xa(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 st(0,"the response has no body to stream");for await(let h of Wr(d.body,a?.signal)){if(h==="[DONE]")return;let f;try{f=JSON.parse(h)}catch{continue}if(f.error)throw new st(500,f.error.message??"stream error",{code:f.error.code});yield f}},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 Xa(i);return((await i.json()).data??[]).map(({id:l,is_default:d,capability:h,max_input_tokens:f,max_tokens:w,options:k})=>({id:l,is_default:d,capability:h??"text",max_input_tokens:f,max_tokens:w,options:k}))}}}async function Xa(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 st(r.status,e,{code:n,retryAfter:Number.isFinite(t)&&t>0?t:void 0})}async function*Wr(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 h;for(;(h=s.search(/\r?\n\r?\n/))>=0;){let f=s.slice(0,h);s=s.slice(h).replace(/^\r?\n\r?\n/,"");let w=f.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 Fs(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 h of[].concat(d))h.trim()&&a.push(`- ${h.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 ud=1600;function _e(r,e){let n=e?Qn(e):0,t=0;for(let s of r){if(n+=16,typeof s.content=="string")n+=Qn(s.content);else if(Array.isArray(s.content))for(let i of s.content)i.type==="text"?n+=Qn(i.text):t++;if(s.tool_calls)for(let i of s.tool_calls)n+=Qn(i.function.name)+Qn(i.function.arguments)+24;typeof s.reasoning_content=="string"&&(n+=Qn(s.reasoning_content))}return Math.ceil(n/3)+t*ud}function Qn(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 Kr(r,e){let n=Math.max(1,e.keepTurns),t=e.elideAbove??400,s=ii(r),i=0,a=0,l=()=>_e(s.flat(),e.system)>e.budget;if(l())for(let d=0;d<s.length-n&&l();d++)s[d]=s[d].map(h=>{if(h.role!=="tool")return h;let f=typeof h.content=="string"?h.content:tl(h.content);return f.length<=t||f.startsWith("[result elided")?h:(i++,{...h,content:`[result elided to save context: ${f.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],h=d.map((k,x)=>k.role==="tool"?x:-1).filter(k=>k>=0);for(let k of h.slice(0,Math.max(0,h.length-(e.keepResults??3)))){if(!l())break;let x=d[k],T=typeof x.content=="string"?x.content:tl(x.content);T.length<=t||T.startsWith("[result elided")||(d[k]={...x,content:`[result elided to save context: ${T.length} characters; call the tool again if needed]`},i++)}let f=d[0]?.role==="user"?1:0,w=k=>{let x=k+1;for(;x<d.length&&d[x].role==="tool";)x++;return x};for(;l()&&!(d.slice(f).filter(x=>x.role==="assistant").length<=1||d[f]?.role!=="assistant");)d.splice(f,w(f)-f),a++}return{messages:s.flat(),droppedTurns:a,elidedResults:i}}function ii(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 tl(r){return r?r.map(e=>e.type==="text"?e.text:"").join(""):""}var En={reserveTokens:16384,keepRecentTokens:2e4},ai=`The conversation history before this point was compacted into the following summary:
|
|
35
35
|
|
|
36
36
|
<summary>
|
|
37
|
-
`,
|
|
38
|
-
</summary>`,
|
|
37
|
+
`,li=`
|
|
38
|
+
</summary>`,pd=`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.`,fd=`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.`,hd=`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.`,md=2e3;function Be(r){return r.role!=="user"||typeof r.content!="string"||!r.content.startsWith(ai)||!r.content.endsWith(li)?null:r.content.slice(ai.length,r.content.length-li.length)}function Vr(r){return{role:"user",content:ai+r+li}}function Gt(r,e={}){return{reserveTokens:Math.min(e.reserveTokens??En.reserveTokens,Math.floor(r*.2)),keepRecentTokens:Math.min(e.keepRecentTokens??En.keepRecentTokens,Math.floor(r*.4))}}function ci(r,e,n){return r>e-n.reserveTokens}function Is(r,e){if(r.length<2)return null;let n=0,t=-1;for(let a=r.length-1;a>=1;a--){n+=_e([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=Be(a);l!==null&&s===void 0?s=l:i.push(a)}return i.length?{toSummarize:i,previousSummary:s,kept:r.slice(t)}:null}function Zr(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]: ${gd(t,md)}`)}return e.join(`
|
|
110
110
|
|
|
111
|
-
`)}function
|
|
111
|
+
`)}function gd(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 Hs(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 nl(r,e,n){let t=`<conversation>
|
|
116
|
+
${typeof r=="string"?r:Zr(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?hd:fd,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:pd},{role:"user",content:t}]}async function Gr(r,e,n={}){let t=n.maxChars??8e5,s="",i="",a=0,l,d,h=new Map;for await(let x of r(e,{signal:n.signal}))if(n.signal?.throwIfAborted(),x.usage&&(d=x.usage),!!Array.isArray(x.choices))for(let T of x.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 D=C.reasoning_content??C.reasoning??C.thinking;if(typeof D=="string"&&D&&(i+=D,a+=D.length,n.onReasoning?.(D,i)),C.tool_calls){if(!Array.isArray(C.tool_calls))throw new Error("Malformed streamed tool_calls");for(let O of C.tool_calls){let M=typeof O.index=="number"?O.index:h.size;if(!Number.isInteger(M)||M<0||M>=64)throw new Error("Malformed streamed tool call index");let S=h.get(M);S||(S={index:M,id:"",type:"function",function:{name:"",arguments:""}},h.set(M,S)),O.id&&(S.id=O.id),O.type&&(S.type=O.type),O.function&&(O.function.name&&(S.function.name+=O.function.name),O.function.arguments&&(S.function.arguments+=O.function.arguments,a+=O.function.arguments.length)),n.onToolCall?.({index:M,id:S.id??"",name:S.function.name,arguments:S.function.arguments},O.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 f=[...h.keys()].sort((x,T)=>x-T);if(f.some((x,T)=>x!==T))throw new Error("Streamed tool calls arrived incomplete");let w=f.map(x=>{let T=h.get(x),{index:C,...D}=T;return D.id||(D.id=`call_${Math.random().toString(36).slice(2,10)}`),D}),k={role:"assistant",content:s.length?s:null};return w.length&&(k.tool_calls=w),{message:k,finishReason:l,usage:d,reasoning:i}}var di="/prompts";function ui(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 pi(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 h=s==="@"||s==="ARGUMENTS"?n:e[parseInt(s,10)-1];return h||i}if(a){let h=parseInt(a,10)-1;return h<0&&(h=0),l?e.slice(h,h+parseInt(l,10)).join(" "):e.slice(h).join(" ")}return d==="ARGUMENTS"||d==="@"?n:e[parseInt(d,10)-1]??""})}async function Us(r){let e=[];for(let n of await r.list(di)){if(!n.path.endsWith(".md"))continue;let t=n.path.slice(di.length+1,-3);if(t.includes("/"))continue;let s;try{s=await r.readText(n.path)}catch{continue}let{fm:i,body:a}=rl(s),l=i.description||yd(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 js(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),f=(await r.skills()).find(x=>x.name===d);if(!f)return e;let{body:w}=await r.skillBody(d),k=`<skill name="${f.name}" location="${f.path}">
|
|
126
|
+
References are relative to ${f.dir}.
|
|
127
127
|
|
|
128
128
|
${w}
|
|
129
129
|
</skill>`;return s?`${k}
|
|
130
130
|
|
|
131
|
-
${s}`:k}let i=`${
|
|
131
|
+
${s}`:k}let i=`${di}/${t}.md`,a;try{a=await r.readText(i)}catch{return e}let{body:l}=rl(a);return pi(l,ui(s))}function rl(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(!C)throw new Error(t?`edits[${T}].oldText must not be empty in ${r}.`:`oldText must not be empty in ${r}.`);let
|
|
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 yd(r){let e=r.split(`
|
|
134
|
+
`).find(n=>n.trim())??"";return e.length>60?e.slice(0,60)+"...":e}var sl=/^[A-Za-z0-9_-]{1,64}$/;function Ne(r){if(!sl.test(r.name))throw new Error(`tool name "${r.name}" must match ${sl}`);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 Bs(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parameters}}}function Jr(r,e=32e3){let n,t;r==null?n="OK":typeof r=="string"?n=r.length?r:"OK":Array.isArray(r)&&r.every(ol)?n=r:wd(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=qs(n,e);s=i.truncated,n=i.text}else n=n.map(i=>{if(i.type!=="text")return i;let a=qs(i.text,e);return a.truncated&&(s=!0),{type:"text",text:a.text}});return{content:n,text:typeof n=="string"?n:Yr(n),details:t,truncated:s}}function ol(r){return!!r&&typeof r=="object"&&typeof r.type=="string"&&["text","image_url","video_url","audio_url"].includes(r.type)}function wd(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(ol))&&n.every(t=>t==="content"||t==="details")}function qs(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 Yr(r){return r?typeof r=="string"?r:r.map(e=>e.type==="text"?e.text:`[${e.type}]`).join(`
|
|
137
|
+
`):""}function Ks(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 f=r.byteLength-22;f>=Math.max(0,r.byteLength-22-65535);f--)if(e.getUint32(f,!0)===101010256){n=f;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"),h=new TextDecoder("latin1");for(let f=0;f<t;f++){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),x=e.getUint32(l+20,!0),T=e.getUint32(l+24,!0),C=e.getUint16(l+28,!0),D=e.getUint16(l+30,!0),O=e.getUint16(l+32,!0),M=e.getUint32(l+42,!0);if(x===4294967295||T===4294967295||M===4294967295)throw new Error("zip64 archives are not supported");let S=r.subarray(l+46,l+46+C),q=(w&2048?d:h).decode(S).replace(/\\/g,"/");a.push({name:q,size:T,compressedSize:x,method:k,isDir:q.endsWith("/"),offset:M,crc:e.getUint32(l+16,!0)}),l+=46+C+D+O}return a}async function er(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&&il(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 h=await(n?n(d):bd(d));if(h.byteLength!==e.size)throw new Error(`zip entry "${e.name}" inflated to the wrong size`);return h}async function bd(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 Ws=null;function il(r){if(!Ws){Ws=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;Ws[n]=t>>>0}}let e=4294967295;for(let n=0;n<r.length;n++)e=Ws[(e^r[n])&255]^e>>>8;return(e^4294967295)>>>0}async function xd(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 vd(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 Vs(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 f of r){let w=e.encode(f.path.replace(/^\/+/,"")),k=typeof f.data=="string"?e.encode(f.data):f.data,x=il(k),{bytes:T,method:C}=await xd(k),{date:D,time:O}=vd(f.mtime??Date.now()),M=new DataView(new ArrayBuffer(30));M.setUint32(0,67324752,!0),M.setUint16(4,20,!0),M.setUint16(6,2048,!0),M.setUint16(8,C,!0),M.setUint16(10,O,!0),M.setUint16(12,D,!0),M.setUint32(14,x,!0),M.setUint32(18,T.length,!0),M.setUint32(22,k.length,!0),M.setUint16(26,w.length,!0),M.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,O,!0),S.setUint16(14,D,!0),S.setUint32(16,x,!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(M.buffer),w,T),t.push(new Uint8Array(S.buffer),w),s+=30+w.length+T.length}let i=t.reduce((f,w)=>f+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((f,w)=>f+w.length,0)),h=0;for(let f of l)d.set(f,h),h+=f.length;return d}var al=/^[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=fi(d[1]??""),l=n.slice(d[0].length));let h=(a.description??"").trim();if(!h)return null;let f=(a.name??"").trim()||s;(!al.test(f)||f.length>64)&&(i.push(`skill name "${f}" is not lowercase-hyphenated (\u226464); using the folder name`),f=al.test(s)?s:s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill");let w={name:f,description:h.length>1024?h.slice(0,1024):h,path:e,dir:t};h.length>1024&&i.push(`description of "${f}" 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[x,T]of Object.entries(a))x.startsWith("metadata.")&&(k[x.slice(9)]=T);return Object.keys(k).length&&(w.metadata=k),{skill:w,body:l.trim(),warnings:i}}function fi(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 h=l[2]??"";if(h===""){let f=n[t]??"";if(f.length-f.trimStart().length>a&&f.trim()){s=l[1];continue}}else if(h===">"||h==="|"||h===">-"||h==="|-"){let f=h.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++}h=f?w.join(" ").trim():w.join(`
|
|
140
|
+
`).trim()}else h=kd(h);e[d]=h}return e}function kd(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 Td(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 ll(r){let e="",n=[],t=[],s=0,i=r.split(`
|
|
141
|
+
`);return i.forEach((a,l)=>{let d=a.trimEnd(),h=0;for(let f of d){let w=Td(f);for(let k=0;k<w.length;k++)n.push(s+h),t.push(s+h+f.length);e+=w,h+=f.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 hi(r){return ll(r).text}function Sd(r,e){let n=0,t=0;for(;(t=r.indexOf(e,t))!==-1;)n++,t+=e.length;return n}function Zs(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,h=!1;for(let x of n)if(x.oldText&&!a.includes(x.oldText.replace(/\r\n/g,`
|
|
144
|
+
`))){h=!0;break}if(h){let x=ll(a);l=x.text,d=x}let f=[];n.forEach((x,T)=>{let C=x.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 D=h?hi(C):C,O=Sd(l,D);if(O===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(O>1)throw new Error(t?`Found ${O} occurrences of edits[${T}] in ${r}. Each oldText must be unique. Please provide more context to make it unique.`:`Found ${O} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`);let M=l.indexOf(D),S=d?d.start[M]:M,q=d?d.end[M+D.length-1]:M+D.length;f.push({start:S,end:q,newText:x.newText.replace(/\r\n/g,`
|
|
146
|
+
`),i:T})}),f.sort((x,T)=>x.start-T.start);for(let x=1;x<f.length;x++)if(f[x].start<f[x-1].end)throw new Error(`edits[${f[x-1].i}] and edits[${f[x].i}] overlap in ${r}. Merge them into one edit or target disjoint regions.`);let w="",k=0;for(let x of f)w+=a.slice(k,x.start)+x.newText,k=x.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 tr=new Map,Cd=64;function Ed(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 Qr(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 mi(r){let e=new Map;for(let n of Ks(r)){let t=Ed(n.name);t&&e.set(t,n)}return e}function cl(r){return tr.get(r)}function Gs(r,e,n){let t=tr.get(n);if(t&&t.bytes.byteLength===e.byteLength)return t;let s=mi(e),i={entries:s,folders:Qr(s.keys(),r),bytes:e,cache:new Map};return tr.size>=Cd&&tr.delete(tr.keys().next().value),tr.set(n,i),i}var Md=new TextDecoder("utf-8",{fatal:!0}),Ad=r=>{try{return Md.decode(r)}catch{return null}};function nr(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 h of s.keys())(l==="/"||h.startsWith(l)||h===a)&&d.push(i(h));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 h=await er(r.bytes,r.entries.get(l),t),f=Ad(h)??h;return r.cache.set(l,f),f}}}function es(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 dl="6.4.299",Mn={url:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${dl}/build/pdf.min.mjs`,workerUrl:`https://cdn.jsdelivr.net/npm/pdfjs-dist@${dl}/build/pdf.worker.min.mjs`},rr=null;function ul(r){Object.assign(Mn,r),rr=null}var $d=r=>import(r);function Ld(){return rr||(rr=(async()=>{let r=Mn.load?await Mn.load():await $d(Mn.url),e=r.default?.getDocument?r.default:r;if(!Mn.load&&typeof Worker<"u"&&typeof Blob<"u")try{let n=new Blob([`import ${JSON.stringify(Mn.workerUrl)};`],{type:"text/javascript"});e.GlobalWorkerOptions.workerPort=new Worker(URL.createObjectURL(n),{type:"module"})}catch{e.GlobalWorkerOptions.workerSrc=Mn.workerUrl}return e})(),rr.catch(()=>{rr=null})),rr}function sr(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 or(r,e={}){let t=(await Ld()).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),h=await d.getTextContent();i.push(h.items.map(f=>(f.str??"")+(f.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 ir(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??Lt(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??Lt(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=ee(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+ee(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:ee(a.path)})):await Qr(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+ee(d.path)});return t.sort((a,l)=>a.path.localeCompare(l.path))}async stat(e){await this.ready();let n=ee(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=>ee(i.path)===ee(t.rel));return s?{...s,path:n}:null}return il(this.store,n)}async exists(e){return await this.stat(e)!==null}async read(e){await this.ready();let n=ee(e),t=this.route(n);if(t)try{let i=await t.fs.read(t.rel);return{data:i,size:Vs(i),contentType:Lt(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:Vs(s.data),contentType:s.contentType}}async isFolder(e){let n=ee(e);return n==="/"||this.mounts.has(n)?!0:(await this.list(n)).some(t=>t.path!==n)}async missing(e,n){if(await this.isFolder(e))return`${e} is a folder, not a file; use list_files to see what it holds`;let t=n instanceof Error?n.message:"";return/no such file/i.test(t)||!t?`No such file: ${e}`:`${e}: ${t}`}async readText(e){let{data:n}=await this.read(e);if(typeof n=="string")return n;let t=Pt(n);if(t===null)throw new Error(`${ee(e)} is a binary file (${n.byteLength} bytes)`);return t}async readAsText(e){let n=ee(e),{data:t,size:s,contentType:i}=await this.read(n);if(typeof t=="string")return{text:t,kind:"text"};if(Qn(n,i,t)){let l=await this.stat(n),d=`pdftext:${n}`,f=await this.getData(d).catch(()=>{});if(f&&f.size===s&&f.mtime===l?.mtime)return{text:f.text,kind:"pdf"};let h=tr(n,await er(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:h}).catch(()=>{}),{text:h,kind:"pdf"}}let a=Pt(t);return a===null?null:{text:a,kind:"text"}}async write(e,n,t){await this.ready();let s=ee(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=ee(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,qs(t,await this.readText(t),n))}async delete(e){await this.ready();let n=ee(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(ee(e))?.prefix||null}isReadOnly(e){let n=this.route(ee(e));return n?!n.fs.write:!1}isSkillPath(e){let n=ee(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:Pt(l)}catch{continue}if(i===null)continue;let a=Zr(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=Ks(s),a=ci(t),l=Gr(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 Qr(this.lib,`/${h}/`))await this.lib.delete(k.path);for(let[k,v]of a){if(!k.startsWith(w))continue;let T=await Gn(t,v,this.inflate),C=Pt(T),O=ee(`/${h}/${k.slice(w.length)}`);await this.lib.put({path:O,data:C??T,contentType:Lt(O,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 f=new Set([...l.keys()].map(h=>`${this.skillsDir}/${h}`));return(await this.skills()).filter(h=>f.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 Qr(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=Zr(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(di(e)){Xr.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!ll(e)&&typeof e.data=="string"?e.data:null;n&&Ws.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(di);for(let t of n)if(!di(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!ll(t)?t:null,i=s?s.data:t,a,l,d=0;if(typeof i=="string"){let h=`${this.dbName}|${this.fetchKey}|${i}`,w=Ws.get(h);w||(w=this.fetchSource(i).then(k=>{if(!k)throw new Error("nothing fetched");return{bytes:k.bytes,at:Date.now()}}),Ws.set(h,w),w.catch(()=>Ws.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${ui(i)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let f=Ks(s?.name??(typeof i=="string"?i:i.name||"skills"));e.push({name:f,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=Bs(n.name,n.bytes,n.key);for(let[s,i]of t.folders)e.has(s)||e.set(s,{fs:Yn(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:Ks(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("^"+Md(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(ee(n.path));t&&e.set(t[1],{fs:Jr(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await Qr(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?nl(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=Bs(Ks(i[1]),d.data,a)}for(let[d,f]of l.folders)e.set(d,{fs:Yn(l,f,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:Jr(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=Xr.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())})(),Xr.set(e,a),a.catch(()=>{Xr.get(e)===a&&Xr.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=Bs(n,l,`lazy:${ui(e)}:${l.byteLength}`),f=d.folders.get(n)??[...d.folders.values()][0];if(f===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return t=Yn(d,f,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}${ee(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=>ee(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=>Qr(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>il(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??Lt(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 ee(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 dl(r){return{path:r.path,size:Vs(r.data),contentType:r.contentType,mtime:r.mtime}}function Vs(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var Ed=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"]),al={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 Lt(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return al[n]?al[n]:typeof e=="string"||Ed.has(n)?"text/plain":"application/octet-stream"}function Pt(r){let e=r.subarray(0,8192);for(let n=0;n<e.length;n++)if(e[n]===0)return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return null}}var ll=r=>typeof Blob<"u"&&r instanceof Blob,Md=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Ks(r){return(r.split(/[?#]/)[0].split("/").pop()||"skill").replace(/\.zip$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"skill"}var Ad=4;function $d(r,e,n){return new Promise((t,s)=>{let i=r.open(e,Ad);i.onupgradeneeded=a=>{let l=i.result,d=i.transaction,f=a.oldVersion,h=()=>l.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(f<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(f<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=(f,h,w)=>new Promise((k,v)=>{let T=a.transaction(f,h),C=w(T.objectStore(f)),O;C.onsuccess=()=>{O=C.result,h==="readonly"&&k(O)},C.onerror=()=>v(C.error??new Error("indexedDB request failed")),T.oncomplete=()=>k(O),T.onabort=()=>v(T.error??new Error("indexedDB transaction aborted"))}),d=(f,h)=>IDBKeyRange.bound([f,h],[f,h+"\uFFFF"],!1,!1);t({get:f=>l("files","readonly",h=>h.get([n,f])),put:async f=>{await l("files","readwrite",h=>h.put({...f,space:n}))},delete:async f=>{await l("files","readwrite",h=>h.delete([n,f]))},list:f=>l("files","readonly",h=>h.getAll(d(n,f))),getMeta:async f=>(await l("meta","readonly",h=>h.get([n,f])))?.value,putMeta:async(f,h)=>{await l("meta","readwrite",w=>w.put({space:n,key:f,value:h}))},deleteMeta:async f=>{await l("meta","readwrite",h=>h.delete([n,f]))},listMeta:async f=>(await l("meta","readonly",h=>h.getAll(d(n,f)))).map(h=>h.value),listMetaKeys:async f=>(await l("meta","readonly",h=>h.getAll(d(n,f)))).map(h=>h.key),getSession:(f,h)=>l("sessions","readonly",w=>w.get([f,h])),putSession:async f=>{await l("sessions","readwrite",h=>h.put(f))},deleteSession:async(f,h)=>{await l("sessions","readwrite",w=>w.delete([f,h]))},listSessions:()=>l("sessions","readonly",f=>f.getAll()),clear:async(f=n)=>{await l("files","readwrite",h=>h.delete(d(f,"/"))),await l("meta","readwrite",h=>h.delete(d(f,""))),await l("sessions","readwrite",h=>h.delete(d(f,"")))},close:()=>a.close()})}})}var cl=new Map;function Ld(r,e){let n=cl.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},cl.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 Qt="Untitled";function kn(r){for(let e of r.messages){if(e.role!=="user"||Be(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||Zs(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return Qt}function Zs(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Pd(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function ul(r={},e={}){let n=new Map;for(let[s,i]of Object.entries(r))n.set(ee(s),i);let t={files:n,description:e.description,async list(s){let i=ee(s);return[...n.entries()].filter(([a])=>i==="/"||a===i||a.startsWith(i+"/")).map(([a,l])=>({path:a,size:Vs(l)}))},async read(s){let i=n.get(ee(s));if(i===void 0)throw new Error(`No such file: ${ee(s)}`);return i}};return e.readonly||(t.write=async(s,i)=>{n.set(ee(s),i)},t.delete=async s=>{if(!n.delete(ee(s)))throw new Error(`No such file: ${ee(s)}`)}),t}var _d=4*1024*1024;function Rd(r){let e=typeof r=="string"?r:Pt(r),n=2166136261;if(e!==null)for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);else for(let t of r)n^=t,n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Dd(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 Tn=class extends Error{constructor(n,t,s){super(n);D(this,"path",t);D(this,"coveredTo",s);this.name="PartialReadError"}};function rr(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>_d?"":Rd(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,f=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,f):d<=1?f:0,T=k?w.ranges:[],C=Dd(T,d,f)||!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(([f,h])=>[f,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 Tn(`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 hi=500,Gs=2e3,Js=50*1024,Ys=100,pl=5*1024*1024,Od={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},Nd={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function zd(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Xs(r,e={}){let n=e.guard??rr(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[Ne({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 ${ee(s||"/")}.`;let l=i?.parentId?1/0:hi,d=a.slice(0,l).map(f=>`${f.path} (${f.size} B)`);return a.length>l&&d.push(`
|
|
155
|
-
[${
|
|
156
|
-
`)}}),Ne({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
|
|
157
|
-
`+
|
|
158
|
-
`)}let d=await r.stat(s),
|
|
159
|
-
`),
|
|
160
|
-
|
|
161
|
-
[Showing lines ${T}-${S} of ${
|
|
162
|
-
|
|
163
|
-
[${
|
|
164
|
-
`)+
|
|
165
|
-
`).length:0,T=
|
|
166
|
-
`),T=
|
|
167
|
-
|
|
168
|
-
${
|
|
169
|
-
`)}`)}return await r.write(d,i),await n.wrote(d),`${f?
|
|
170
|
-
`);for(let T=0;T<
|
|
171
|
-
`)+(
|
|
172
|
-
|
|
173
|
-
[${
|
|
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 wi="/.agent/skills";var Pd="__runapps_agent_ws",bi="/skills",_d="\0skills",gi=r=>typeof r=="object"&&!(r instanceof Uint8Array)&&typeof r.load=="function",ns=new WeakMap,Js=new Map,pl=new WeakMap,Rd=1,yi=r=>{let e=pl.get(r);return e||(e=Rd++,pl.set(r,e)),e},rs=async(r,e)=>r.listStats?r.listStats(e):(await r.list(e)).map(yl),fl=async(r,e)=>{if(r.stat)return r.stat(e);let n=await r.get(e);return n?yl(n):null},ar=class r{constructor(e,n={}){N(this,"id");N(this,"dbName");N(this,"skillsDir");N(this,"userSkillsDir");N(this,"root");N(this,"store");N(this,"lib");N(this,"mounts",new Map);N(this,"skillViews",new Map);N(this,"builtins",[]);N(this,"lazySkills",[]);N(this,"resolvedSources",[]);N(this,"changeListeners",new Set);N(this,"channel");N(this,"sources");N(this,"provider");N(this,"inflate");N(this,"fetchFn");N(this,"fetchKey");N(this,"idb");N(this,"storeFactory");N(this,"skillCache",null);N(this,"opened",null);N(this,"sessions",{list:async()=>(await this.ready(),(await this.store.listSessions()).map(e=>({id:e.id??"",title:e.title&&!Qs(e.title)?e.title:An(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?gt(e):null,this.id=n.id||"default",this.dbName=`${Pd}:${n.project||this.provider?.name||"app"}`,this.sources=typeof n.skills=="function"?n.skills:n.skills?[].concat(n.skills):[],this.skillsDir=Q(n.skillsDir||wi),this.skillsDir==="/")throw new Error("skillsDir cannot be /");this.userSkillsDir=n.userSkills===!1||n.userSkillsDir===!1?null:Q(n.userSkillsDir||bi);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${yi(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?zd(this.idb,this.dbName,t):Promise.resolve(Fd(this.dbName,t));this.store=await n(this.id),this.lib=await n(_d),this.openChannel(),await Id(`${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??At(e,n)),this.emitChange(e,"write");return}await this.store.put({path:e,data:n,contentType:t??At(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 rs(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 fl(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:Xs(i),contentType:At(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:Xs(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=$t(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(sr(n,i,t)){let l=await this.stat(n),d=`pdftext:${n}`,h=await this.getData(d).catch(()=>{});if(h&&h.size===s&&h.mtime===l?.mtime)return{text:h.text,kind:"pdf"};let f=ir(n,await or(t));return await this.putData(d,{size:s,mtime:l?.mtime,text:f}).catch(()=>{}),{text:f,kind:"pdf"}}let a=$t(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,Zs(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:$t(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 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=Ys(s),a=mi(t),l=Qr(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 rs(this.lib,`/${f}/`))await this.lib.delete(k.path);for(let[k,x]of a){if(!k.startsWith(w))continue;let T=await er(t,x,this.inflate),C=$t(T),D=Q(`/${f}/${k.slice(w.length)}`);await this.lib.put({path:D,data:C??T,contentType:At(D,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 h=new Set([...l.keys()].map(f=>`${this.skillsDir}/${f}`));return(await this.skills()).filter(f=>h.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 rs(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(gi(e)){ns.delete(e);continue}let n=typeof e=="string"?e:!(e instanceof Uint8Array)&&!ml(e)&&typeof e.data=="string"?e.data:null;n&&Js.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(gi);for(let t of n)if(!gi(t))try{let s=typeof t=="object"&&!(t instanceof Uint8Array)&&!ml(t)?t:null,i=s?s.data:t,a,l,d=0;if(typeof i=="string"){let f=`${this.dbName}|${this.fetchKey}|${i}`,w=Js.get(f);w||(w=this.fetchSource(i).then(k=>{if(!k)throw new Error("nothing fetched");return{bytes:k.bytes,at:Date.now()}}),Js.set(f,w),w.catch(()=>Js.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${yi(i)}`;if(a.byteLength>52428800)throw new Error("skills zip too large");let h=Ys(s?.name??(typeof i=="string"?i:i.name||"skills"));e.push({name:h,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=Gs(n.name,n.bytes,n.key);for(let[s,i]of t.folders)e.has(s)||e.set(s,{fs:nr(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("^"+Od(this.skillsDir)+"/([^/]+)/SKILL\\.md$").exec(Q(n.path));t&&e.set(t[1],{fs:es(this.root,`${this.skillsDir}/${t[1]}`),builtin:!1,from:`${this.skillsDir}/${t[1]}`})}if(this.userSkillsDir){let n=await rs(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?cl(a):void 0;if(!l){let d=await this.lib.get(s.path);if(!d||!(d.data instanceof Uint8Array))continue;l=Gs(Ys(i[1]),d.data,a)}for(let[d,h]of l.folders)e.set(d,{fs:nr(l,h,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:es(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=ns.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())})(),ns.set(e,a),a.catch(()=>{ns.get(e)===a&&ns.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=Gs(n,l,`lazy:${yi(e)}:${l.byteLength}`),h=d.folders.get(n)??[...d.folders.values()][0];if(h===void 0)throw new Error(`the skill "${e.name}": its zip has no SKILL.md`);return t=nr(d,h,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=>rs(this.lib,e==="/"?"/":e.replace(/\/+$/,"")+"/"),stat:async e=>fl(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??At(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 yl(r){return{path:r.path,size:Xs(r.data),contentType:r.contentType,mtime:r.mtime}}function Xs(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}var Dd=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"]),hl={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 At(r,e){let n=r.split(".").pop()?.toLowerCase()??"";return hl[n]?hl[n]:typeof e=="string"||Dd.has(n)?"text/plain":"application/octet-stream"}function $t(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 ml=r=>typeof Blob<"u"&&r instanceof Blob,Od=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 Nd=4;function zd(r,e,n){return new Promise((t,s)=>{let i=r.open(e,Nd);i.onupgradeneeded=a=>{let l=i.result,d=i.transaction,h=a.oldVersion,f=()=>l.createObjectStore("sessions",{keyPath:["space","id"]}).createIndex("space","space");if(h<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(h<4){let w=d.objectStore("sessions").getAll();w.onsuccess=()=>{let k=w.result;l.deleteObjectStore("sessions"),f();let x=d.objectStore("sessions");for(let T of k)T.id&&x.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=(h,f,w)=>new Promise((k,x)=>{let T=a.transaction(h,f),C=w(T.objectStore(h)),D;C.onsuccess=()=>{D=C.result,f==="readonly"&&k(D)},C.onerror=()=>x(C.error??new Error("indexedDB request failed")),T.oncomplete=()=>k(D),T.onabort=()=>x(T.error??new Error("indexedDB transaction aborted"))}),d=(h,f)=>IDBKeyRange.bound([h,f],[h,f+"\uFFFF"],!1,!1);t({get:h=>l("files","readonly",f=>f.get([n,h])),put:async h=>{await l("files","readwrite",f=>f.put({...h,space:n}))},delete:async h=>{await l("files","readwrite",f=>f.delete([n,h]))},list:h=>l("files","readonly",f=>f.getAll(d(n,h))),getMeta:async h=>(await l("meta","readonly",f=>f.get([n,h])))?.value,putMeta:async(h,f)=>{await l("meta","readwrite",w=>w.put({space:n,key:h,value:f}))},deleteMeta:async h=>{await l("meta","readwrite",f=>f.delete([n,h]))},listMeta:async h=>(await l("meta","readonly",f=>f.getAll(d(n,h)))).map(f=>f.value),listMetaKeys:async h=>(await l("meta","readonly",f=>f.getAll(d(n,h)))).map(f=>f.key),getSession:(h,f)=>l("sessions","readonly",w=>w.get([h,f])),putSession:async h=>{await l("sessions","readwrite",f=>f.put(h))},deleteSession:async(h,f)=>{await l("sessions","readwrite",w=>w.delete([h,f]))},listSessions:()=>l("sessions","readonly",h=>h.getAll()),clear:async(h=n)=>{await l("files","readwrite",f=>f.delete(d(h,"/"))),await l("meta","readwrite",f=>f.delete(d(h,""))),await l("sessions","readwrite",f=>f.delete(d(h,"")))},close:()=>a.close()})}})}var gl=new Map;function Fd(r,e){let n=gl.get(r);n||(n={files:new Map,meta:new Map,sessions:new Map},gl.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 Jt="Untitled";function An(r){for(let e of r.messages){if(e.role!=="user"||Be(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||Qs(s)))return s.length>80?s.slice(0,77)+"\u2026":s}return Jt}function Qs(r){return/^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(r)}function Id(r,e){let n=typeof navigator<"u"?navigator.locks:void 0;return n&&typeof n.request=="function"?n.request(r,e):e()}function wl(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:Xs(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 Hd=4*1024*1024;function Ud(r){let e=typeof r=="string"?r:$t(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 jd(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 $n=class extends Error{constructor(n,t,s){super(n);N(this,"path",t);N(this,"coveredTo",s);this.name="PartialReadError"}};function lr(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>Hd?"":Ud(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,h=a.end??1/0,f=a.total??1/0,w=t.get(i),k=!!w&&w.version===l,x=k&&d<=w.coveredTo+1?Math.max(w.coveredTo,h):d<=1?h:0,T=k?w.ranges:[],C=jd(T,d,h)||!k;return t.set(i,{version:l,coveredTo:x,total:f,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(([h,f])=>[h,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 $n(`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 xi=500,eo=2e3,to=50*1024,no=100,bl=5*1024*1024,qd={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},Bd={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function Wd(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function ro(r,e={}){let n=e.guard??lr(r,{enabled:e.readBeforeWrite!==!1}),t=n.enabled;return[Ne({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:xi,d=a.slice(0,l).map(h=>`${h.path} (${h.size} B)`);return a.length>l&&d.push(`
|
|
155
|
+
[${xi} entries limit reached (${a.length} in all). List a sub-folder.]`),d.join(`
|
|
156
|
+
`)}}),Ne({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,xi).map(ie=>`${ie.path} (${ie.size} B)`).join(`
|
|
158
|
+
`)}let d=await r.stat(s),h=d&&qd[(d.contentType??"").split(";")[0].trim()]?d.contentType.split(";")[0].trim():Bd[/\.([a-z0-9]+)$/i.exec(s)?.[1]?.toLowerCase()??""];if(d&&h&&await l.agent?.accepts("image")===!0){if(d.size>bl)return`${Q(s)} is a picture of ${d.size} bytes, more than the ${bl/1024/1024} MB that can be shown; describe what you need from it to the user instead.`;let{data:V}=await r.read(s),ie=typeof V=="string"?new TextEncoder().encode(V):V;return await n.saw(Q(s)),[{type:"text",text:`${Q(s)} (${h}, ${ie.byteLength} bytes):`},{type:"image_url",image_url:{url:`data:${h};base64,${Wd(ie)}`}}]}let f;try{f=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(!f){await n.saw(Q(s));let V=await r.stat(s),ie=h&&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).${ie}`}let w=f.text,k=w.split(`
|
|
159
|
+
`),x=k.length,T=Math.max(1,i??1);if(T>x)return await n.saw(Q(s),{start:x+1,end:x,total:x}),`Offset ${T} is beyond end of file (${x} lines total)`;let C=!!l?.parentId,D=C?a??1/0:a!==void 0?Math.min(a,eo):eo,O=[],M=0,S=T-1;for(let V=T-1;V<x&&O.length<D;V++){let ie=new TextEncoder().encode(k[V]).byteLength+1;if(!C&&M+ie>to&&O.length>0)break;O.push(k[V]),M+=ie,S=V+1}let q=await n.saw(Q(s),{start:T,end:S,total:x,text:f.kind==="text"?w:void 0});q!==void 0&&l.progress?.(q);let R="";if(S<x){let V=S+1;M>=to||a===void 0&&O.length>=eo?R=`
|
|
160
|
+
|
|
161
|
+
[Showing lines ${T}-${S} of ${x}${M>=to?" (50.0KB limit)":""}. Use offset=${V} to continue.]`:R=`
|
|
162
|
+
|
|
163
|
+
[${x-S} more lines in file. Use offset=${V} to continue.]`}return O.join(`
|
|
164
|
+
`)+R}}),Ne({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),h=await r.exists(d),f="";if(h&&a===!0&&t){let w=await n.known(d);if(w!=="all"){let k=await r.readAsText(d).catch(()=>null),x=k?.kind==="text"?k.text.split(`
|
|
165
|
+
`).length:0,T=x?` (${x} line${x===1?"":"s"})`:"";f=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(h)try{await n.check(d,"overwrite")}catch(w){if(!(w instanceof $n))throw w;let k=await r.readAsText(d).catch(()=>null);if(k?.kind!=="text")throw w;let x=k.text.split(`
|
|
166
|
+
`),T=x.length,C=w.coveredTo+1,D=[],O=0,M=w.coveredTo;for(let R=C-1;R<T&&D.length<eo;R++){let V=new TextEncoder().encode(x[R]).byteLength+1;if(O+V>to&&D.length>0)break;D.push(x[R]),O+=V,M=R+1}let S=await n.saw(d,{start:C,end:M,total:T,text:k.text});S!==void 0&&l.progress?.(S);let q=M<T?` Lines ${M+1}-${T} are still unread: read them with read_file offset=${M+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}-${M}, which now count as read.${q} Make sure your new content keeps what it should, then call write_file again, or change the file with edit_file.
|
|
167
|
+
|
|
168
|
+
${D.join(`
|
|
169
|
+
`)}`)}return await r.write(d,i),await n.wrote(d),`${h?f?"Replaced":"Updated":"Created"} ${d} (${new TextEncoder().encode(i).byteLength} bytes).${f}`}}),Ne({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}.`}}),Ne({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=>Ne({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:h,contentType:f}=await r.read(l);return await r.write(d,h,f),await n.copied(l,d),s==="move_file"&&(await r.delete(l),n.forget(l)),`${s==="move_file"?"Moved":"Copied"} ${l} to ${d}.`}})),Ne({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 h=[],f=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}f++;let x=k.split(`
|
|
170
|
+
`);for(let T=0;T<x.length&&h.length<no;T++)d.test(x[T])&&h.push(`${w.path}:${T+1}: ${x[T].trim().slice(0,200)}`);if(h.length>=no)break}return h.length?h.join(`
|
|
171
|
+
`)+(h.length>=no?`
|
|
172
|
+
|
|
173
|
+
[${no} matches limit reached. Refine the pattern or search a sub-folder.]`:""):`No matches found (${f} text files searched).`}})]}function so(r,e){if(!r)return[];let n=[];return cr(r,e,"",n,0),n}function xl(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r}function Kd(r,e){let n=xl(e);return r==="number"?n==="number"||n==="integer":r==="integer"?n==="integer":r===n}function cr(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(h=>{let f=[];return cr(h,e,n,f,s+1),f.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)cr(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=>Kd(l,e))){t.push(`${i}: expected ${a.join(" or ")}, got ${xl(e)}`);return}}if(Array.isArray(r.enum)&&!r.enum.some(a=>vi(a,e))){t.push(`${i}: must be one of ${r.enum.map(a=>JSON.stringify(a)).join(", ")}`);return}if("const"in r&&!vi(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)=>cr(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,h]of Object.entries(a)){let f=l[d];if(f)cr(f,h,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"&&cr(r.additionalProperties,h,n?`${n}.${d}`:d,t,s+1)}}}function vi(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=>vi(r[s],e[s]))}var vl=`
|
|
174
174
|
"use strict";
|
|
175
175
|
var isNode = typeof self === "undefined";
|
|
176
176
|
var port, send;
|
|
@@ -254,38 +254,38 @@ 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 Vd(){if(typeof Worker=="function"&&typeof Blob=="function"&&typeof URL?.createObjectURL=="function"){let t=URL.createObjectURL(new Blob([vl],{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(vl,{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 ki(r,e,n={}){let t=Math.min(6e4,Math.max(100,n.timeoutMs??1e4)),s=await Vd(),i=Date.now(),a=n.bridge;return new Promise(l=>{let d=!1,h=new AbortController,f=R=>{d||(d=!0,clearTimeout(T),n.signal?.removeEventListener("abort",O),s.terminate(),h.abort(),l(R))},w=t,k=0,x=0,T,C=()=>{k=Date.now(),T=setTimeout(()=>f({ok:!1,logs:"",error:`Timed out after ${t} ms`,durationMs:Date.now()-i}),Math.max(0,w))},D=async R=>{x++===0&&(clearTimeout(T),w-=Date.now()-k);try{return await R()}finally{--x===0&&!d&&C()}};C();let O=()=>f({ok:!1,logs:"",error:"Aborted",durationMs:Date.now()-i});if(n.signal?.addEventListener("abort",O,{once:!0}),n.signal?.aborted)return O();s.onFail(R=>f({ok:!1,logs:"",error:R,durationMs:Date.now()-i}));let M=0,S=Promise.resolve(),q=(R,V)=>{if(!a?.names.includes(R))throw new Error(`there is no tool named "${R}"`);let ie=a.max??50;if(++M>ie)throw new Error(`this run has used its ${ie} tool calls; return what you have and continue in another run_js`);let I=S.then(()=>{if(d)throw new Error("the code has finished");return a.call(R,V,h.signal)});return S=I.catch(()=>{}),I};s.onMessage(async R=>{R.type==="done"?f({ok:!0,result:R.result,logs:R.logs??"",durationMs:R.durationMs??Date.now()-i}):R.type==="error"?f({ok:!1,error:String(R.error),logs:R.logs??"",durationMs:R.durationMs??Date.now()-i}):R.type==="tool"&&D(async()=>{try{s.post({type:"toolResult",id:R.id,ok:!0,value:await q(String(R.name),R.args)})}catch(V){s.post({type:"toolResult",id:R.id,ok:!1,error:V.message})}})}),s.post({type:"run",code:r,input:e,network:!!n.network,maxLogChars:n.maxLogChars,tools:a?.names})})}function oo(r={}){let e=r.maxCodeChars??2e4;return Ne({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(h=>h.name!=="run_js"&&!h.endsRun&&!h.vision&&!h.display?.hidden&&h.callableFromCode!==!1).map(h=>h.name),max:r.maxToolCalls,call:async(h,f,w)=>{let k=await i.callTool(h,f,{signal:w});if(k.status!=="ok")throw new Error(k.text.replace(/^Error:\s*/,""));return k.text}},l=await ki(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 yi=["web_search","web_fetch"],ml=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>`,Hd=ml('<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"/>'),Ud=ml('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),jd=["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 qd(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 to(r,e={}){let n=await r.list(e.signal?{signal:e.signal}:void 0),t=[];for(let s of yi){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:jd}:{},display:{icon:a?Ud:Hd,outcome:({details:l})=>{if(a){let f=l?.results?.length;return typeof f=="number"?String(f):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(qd(l.url));let f=await r.call(s,l,{signal:d.signal}),h=f.usage?.total_cost;return typeof h=="number"&&h>0&&e.onCost?.(h),{content:f.content,details:f.data}}})}return t}function wi(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var Bd=["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 Ie(r,e,n){let t=document.createElement(r);return e&&t.setAttribute("style",e),n!==void 0&&(t.textContent=n),t}function or(r,e,n,t){let s=Ie("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 bi(r,e,n=null){let t=Ie("dialog",Bd),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 no(){return typeof document>"u"||typeof HTMLDialogElement>"u"?xi():{async confirm(r,e,n={}){let t=wi();return await bi((i,a)=>{if(i.append(Ie("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&i.append(Ie("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=Ie("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");l.append(or(n.cancel??(t?"\u53D6\u6D88":"Cancel"),!1,!1,()=>a(!1)),or(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=wi(),s=await bi((i,a)=>{i.append(Ie("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&i.append(Ie("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=Ie("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),d="ra_sel_"+Math.random().toString(36).slice(2,8),f=[],h=v=>{let T=Ie("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=Ie("input");C.type=n.multi?"checkbox":"radio",C.name=d,C.value=v.value,C.setAttribute("style","margin-top:3px"),f.push(C);let O=Ie("div");O.append(Ie("div","",v.label??v.value)),v.description&&O.append(Ie("div","opacity:.7;font-size:12px",v.description)),T.append(C,O),l.append(T)};e.forEach(h);let w=null;n.allowOther&&(h({value:"__other__",label:t?"\u5176\u4ED6\u2026":"Other\u2026"}),w=Ie("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=f.find(T=>T.value==="__other__");v&&(v.checked=!0)}),l.append(w)),i.append(l);let k=Ie("div","display:flex;justify-content:flex-end;gap:8px");k.append(or(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>a(null)),or(t?"\u786E\u5B9A":"OK",!0,!1,()=>{let v=f.filter(T=>T.checked).map(T=>T.value==="__other__"?w?.value.trim()||"":T.value).filter(Boolean);v.length&&a(v)})),i.append(k),queueMicrotask(()=>f[0]?.focus())},n.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let n=wi(),t=await bi((s,i)=>{s.append(Ie("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(Ie("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let a=Ie(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 f=d;f.key==="Enter"&&!f.isComposing&&f.keyCode!==229&&i(a.value)}),s.append(a);let l=Ie("div","display:flex;justify-content:flex-end;gap:8px");l.append(or(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),or(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=Ie("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 xi(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function ro(){return Ne({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}
|
|
260
|
+
`),details:l}}})}var Ti=["web_search","web_fetch"],kl=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>`,Zd=kl('<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"/>'),Gd=kl('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),Jd=["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 Yd(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 io(r,e={}){let n=await r.list(e.signal?{signal:e.signal}:void 0),t=[];for(let s of Ti){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:Jd}:{},display:{icon:a?Gd:Zd,outcome:({details:l})=>{if(a){let h=l?.results?.length;return typeof h=="number"?String(h):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(Yd(l.url));let h=await r.call(s,l,{signal:d.signal}),f=h.usage?.total_cost;return typeof f=="number"&&f>0&&e.onCost?.(f),{content:h.content,details:h.data}}})}return t}function ao(){return typeof document>"u"?!1:/^zh/i.test(document.documentElement.lang||(typeof navigator<"u"?navigator.language:"")||"")}var Xd=["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 Le(r,e,n){let t=document.createElement(r);return e&&t.setAttribute("style",e),n!==void 0&&(t.textContent=n),t}function Yt(r,e,n,t){let s=Le("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 lo(r,e,n=null){let t=Le("dialog",Xd),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 co(){return typeof document>"u"||typeof HTMLDialogElement>"u"?Si():{async confirm(r,e,n={}){let t=ao();return await lo((i,a)=>{if(i.append(Le("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e&&i.append(Le("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=Le("div","display:flex;justify-content:flex-end;gap:8px;margin-top:10px");l.append(Yt(n.cancel??(t?"\u53D6\u6D88":"Cancel"),!1,!1,()=>a(!1)),Yt(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=ao(),s=await lo((i,a)=>{i.append(Le("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&i.append(Le("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=Le("div","display:flex;flex-direction:column;gap:6px;margin:8px 0 12px"),d="ra_sel_"+Math.random().toString(36).slice(2,8),h=[],f=x=>{let T=Le("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=Le("input");C.type=n.multi?"checkbox":"radio",C.name=d,C.value=x.value,C.setAttribute("style","margin-top:3px"),h.push(C);let D=Le("div");D.append(Le("div","",x.label??x.value)),x.description&&D.append(Le("div","opacity:.7;font-size:12px",x.description)),T.append(C,D),l.append(T)};e.forEach(f);let w=null;n.allowOther&&(f({value:"__other__",label:t?"\u5176\u4ED6\u2026":"Other\u2026"}),w=Le("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 x=h.find(T=>T.value==="__other__");x&&(x.checked=!0)}),l.append(w)),i.append(l);let k=Le("div","display:flex;justify-content:flex-end;gap:8px");k.append(Yt(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>a(null)),Yt(t?"\u786E\u5B9A":"OK",!0,!1,()=>{let x=h.filter(D=>D.checked).map(D=>D.value==="__other__"?w?.value.trim()||"":D.value).filter(Boolean),T=n.multi?n.min??1:1,C=n.multi?n.max:void 0;x.length<T||C!==void 0&&x.length>C||a(x)})),i.append(k),queueMicrotask(()=>h[0]?.focus())},n.signal,null);return Array.isArray(s)?s:null},async input(r,e={}){let n=ao(),t=await lo((s,i)=>{s.append(Le("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),e.message&&s.append(Le("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",e.message));let a=Le(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 h=d;h.key==="Enter"&&!h.isComposing&&h.keyCode!==229&&i(a.value)}),s.append(a);let l=Le("div","display:flex;justify-content:flex-end;gap:8px");l.append(Yt(n?"\u53D6\u6D88":"Cancel",!1,!1,()=>i(null)),Yt(n?"\u786E\u5B9A":"OK",!0,!1,()=>i(a.value))),s.append(l),queueMicrotask(()=>a.focus())},e.signal,null);return typeof t=="string"?t:null},async form(r,e,n={}){let t=ao(),s=await lo((i,a)=>{i.append(Le("div","font-weight:600;font-size:15px;margin-bottom:6px",r)),n.message&&i.append(Le("div","white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px",n.message));let l=e.map(f=>{let w=Le("label","display:block;font-size:13px;margin:8px 0");w.append(Le("div","opacity:.8;margin-bottom:4px",(f.label??f.name)+(f.required?" *":"")));let k=Le("input","font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box");return k.type=f.type==="number"?"number":"text",f.type==="number"&&(k.step="any"),f.placeholder&&(k.placeholder=f.placeholder),f.initial!==void 0&&(k.value=String(f.initial)),w.append(k),i.append(w),{f,input:k}}),d=()=>{let f={};for(let{f:w,input:k}of l){let x=k.value.trim();if(!x&&w.required||x&&w.type==="number"&&!Number.isFinite(Number(x))){k.focus();return}x&&(f[w.name]=w.type==="number"?Number(x):x)}a(f)},h=Le("div","display:flex;justify-content:flex-end;gap:8px;margin-top:12px");h.append(Yt(t?"\u53D6\u6D88":"Cancel",!1,!1,()=>a(null)),Yt(n.ok??(t?"\u786E\u5B9A":"OK"),!0,!1,d)),i.append(h),queueMicrotask(()=>l[0]?.input.focus())},n.signal,null);return s&&typeof s=="object"&&!Array.isArray(s)?s:null},notify(r,e="info"){let n=Le("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 Si(){return{confirm:async()=>!1,select:async()=>null,input:async()=>null,notify:(r,e="info")=>{(e==="error"?console.error:console.log)(`[agent] ${r}`)}}}function uo(){return Ne({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 ${h.tool_call_id??""}:`.trim()},...k);continue}a.push(h)}return d(),a}var xl=2,vl={image:"image_url",video:"video_url",audio:"audio_url"},kl={image:"picture",video:"video",audio:"audio clip"};function eu(r,e,n){let t=Object.keys(vl).filter(i=>e[i]===!1);if(!t.length)return r;let s=i=>t.find(a=>vl[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 ${kl[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${kl[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...i,content:a}})}var ki=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),es=()=>({runId:"",reason:"aborted",text:"",usage:ki()}),ir="Skipped: the user stopped the run.",tu=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),Tl=()=>new lt(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function so(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 en=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",ki());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,"fixedTitle");D(this,"_ended",null);D(this,"persist");this.provider=yt(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??no(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?rr(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(...Xs(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(ro()),n.sandbox!==!1&&t.push(eo(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()}get title(){return this.fixedTitle}setTitle(e){this.fixedTitle=e.trim()||void 0}applySession(e){if(e.v!==1&&e.v!==2)throw new Error("unknown session format");this.history=e.messages.slice(),this.committed=this.history.length,this.droppedTurns=e.droppedTurns??0,this._usage={...e.usage},this.createdAt=e.createdAt??e.savedAt??Date.now(),this._ended=e.ended??null,this.fixedTitle=e.title&&!Zs(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??gl,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,...Xt(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.fixedTitle){let t=kn(n);t!==Qt&&(this.fixedTitle=t)}return n.title=this.fixedTitle??Qt,n}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.fixedTitle=void 0,this._ended=null,this.committed=0,this.droppedTurns=0,this.resetLoop()}useSkill(e){if(!this.workspace)throw new Error("useSkill needs a workspace");this.pendingSkills.push(e)}prompt(e,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?.(es()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(es())}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=ki(),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?.({...es(),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,f={...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(_){w=e,k=_ instanceof Error?_:new Error(String(_))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let v=this.opts.maxTurns??gl,{output:T,input:C}=await this.limits(),O=C,I=Xt(O,this.compactThresholds),$=0;try{if(k)throw k;for(let _=1;;_++){if(s.aborted){i="aborted";break}if(_>v){i="max_turns";break}this.turnNow=_,this.emit("turn_start",{runId:t,turn:_}),this.applySteering(t);let W=await this.systemPrompt(),ae=this.fixedText(W),Z=Le(this.history,ae);if(ri(Z,O,I)){let L=this.compactSummaries?await this.compactWith(I,t,s):!1,U=Le(this.history,ae);if(!L||ri(U,O,I)){let B=this.history.length&&Be(this.history[0])!==null?[this.history[0]]:[],G=this.history.slice(B.length),j=jr(G,{budget:O-I.reserveTokens-Le(B),keepTurns:this.opts.keepTurns??4,system:ae});(j.droppedTurns||j.elidedResults)&&(this.history=[...B,...j.messages],this.droppedTurns+=j.droppedTurns,this.committed=Math.min(this.committed,this.history.length),this.emit("compaction",{runId:t,summary:!1,tokensBefore:U,tokensAfter:Le(this.history,ae),droppedTurns:j.droppedTurns,elidedResults:j.elidedResults}))}}let ge=await this.activeTools(),we={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:W},...this.toWireHistory(await this.mediaSupport())],max_tokens:T};we.model||delete we.model,ge.length&&(we.tools=ge.map(L=>Fs(L))),this.opts.serverTools?.length&&(we.server_tools=this.opts.serverTools),this.opts.prompt&&(we.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(we.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(we.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:_,params:we});let $e=Date.now(),Ce;try{if(Le(this.history,ae)>O*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new lt(413,"the request is far larger than the model's context");Ce=await this.callModel(we,t,s)}catch(L){if(this.emit("response",{runId:t,turn:_,durationMs:Date.now()-$e,error:L instanceof Error?L.message:String(L)}),s.aborted||!Ps(L))throw L;let U=Ka(L);U!==void 0&&U<O&&(O=U,I=Xt(O,this.compactThresholds));let B=!1;for(;!B&&$<2;)B=await this.squeeze(O,$++,I,ae,t,s);if(B){_--;continue}throw new Jt({cause:this.overflowCause(O,ae),used:Le(this.history,ae),window:O},L instanceof Error?L.message:String(L),_s(L)??400)}this.emit("response",{runId:t,turn:_,durationMs:Date.now()-$e,finishReason:Ce.finishReason,usage:Ce.usage,message:Ce.message}),Ce.usage&&this.addUsage(Ce.usage);let ce={role:"assistant",content:Ce.message.content,ts:Date.now()};Ce.message.tool_calls?.length&&(ce.tool_calls=Ce.message.tool_calls),Ce.reasoning&&(ce.reasoning_content=Ce.reasoning),this.history.push(ce),typeof ce.content=="string"&&ce.content&&(l=ce.content);let be=Ce.finishReason==="length";this.emit("message_end",{runId:t,message:ce,truncated:be}),this.emit("turn_end",{runId:t,turn:_,usage:Ce.usage});let De=ce.tool_calls??[];if(!De.length){if(this.committed=this.history.length,await this.saveSession(),be&&this.balanceLimited(Ce.usage,T)){i="error",a=Tl();break}if(!s.aborted&&this.queue.some(L=>L.kind==="steer"))continue;break}let Ue=await this.runBatch(De,t,s,be);if(this.committed=this.history.length,await this.saveSession(),s.aborted){i="aborted";break}if(!be&&Vr(ce.content).trim()&&De.every(L=>this.tools.find(U=>U.name===L.function.name)?.endsRun)){if(this.queue.some(L=>L.kind==="steer"))continue;break}if(be){if(d++,this.balanceLimited(Ce.usage,T)){i="error",a=Tl();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 Fe=this.checkLoop(Ue);if(Fe==="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}Fe==="warn"&&this.history.push({role:"user",content:"[environment] The last rounds of tool calls brought nothing new: the same results, the same errors, or parts of files you had already read. Do not repeat them. Use what you have already read (it is above), read only what is still missing, take a different approach, or explain the blocker and finish."})}}catch(_){s.aborted?i="aborted":(i="error",a=_ instanceof Error?_:new Error(String(_)))}i==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(h,f),this.committed=this.history.length,this.resetLoop();let S=a instanceof Jt?{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 H={runId:t,reason:i,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",H),H}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 eu(Qd(this.history.map((t,s)=>Xd(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=to(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 Rs({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e&&t.some(s=>tu.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??wl,2e4),agentsPath:this.opts.instructionsFile||wl,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??yl,Zd),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??yl,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async n=>{let t=await this.contextTokens(),s=this.squeezed(Xt(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]?Be(t[0]):null,i=s===null?t:t.slice(1);if(!i.length)return s;let a=await this.contextTokens(),l=Xt(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=[qr(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(()=>({...es(),reason:"done"}),()=>es());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"&&Be(n[t])===null);)t--;let s=t>0?n.slice(t).reduce((i,a)=>i+Le([a]),0):Math.floor(Le(n)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,n,t,s,i,a){let l=Le(this.history,s);n===0&&this.compactSummaries&&await this.compactWith(this.squeezed(t),i,a);let d=this.history.length&&Be(this.history[0])!==null?[this.history[0]]:[],f=this.history.slice(d.length),h=Math.floor(e*(n===0?.7:.4))-Le(d),w=jr(f,{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:Le(this.history,s),droppedTurns:w.droppedTurns,elidedResults:w.elidedResults})),Le(this.history,s)<l}overflowCause(e,n){let t=this.tools.length?Le([],JSON.stringify(this.tools.map(d=>Fs(d)))):0,s=[...this.history].reverse().find(d=>d.role==="user"&&Be(d)===null),i=s?Le([s]):0,a=Le(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 f of Os(Br(e.toSummarize),l)){let h={model:this.opts.model??"",messages:Ga(f,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 Wr((C,O)=>this.provider.stream(C,O),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=Ds(this.history,e.keepRecentTokens);if(!i)return!1;s?.trim()&&(i.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=Le(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=[qr(l),...i.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:Le(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 zs(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 Wr((d,f)=>this.provider.stream(d,f),e,{signal:t,onText:(d,f)=>{a=!0,s=f,this.emit("text_delta",{runId:n,delta:d,text:f})},onReasoning:(d,f)=>{a=!0,i=f,this.emit("reasoning_delta",{runId:n,delta:d,text:f})},onToolCall:(d,f)=>{a=!0,this.emit("tool_call_delta",{runId:n,index:d.index,id:d.id,name:d.name,delta:f,arguments:d.arguments})}})}catch(d){if(t.aborted||l>=Gd||!nu(d))throw d;let f=ru(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await su(f,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 f of e){if(d){l.push(this.skipTool(f,n,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}l.push(await i(f)),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,f=Date.now(),h,w,k=($,S,H)=>{let _=Vr(S);return this.emit("tool_end",{runId:n,id:a,name:d,status:$,result:i?Is(_,32e3).text:_,details:H,durationMs:Date.now()-f,...l,...typeof S=="string"?{}:{content:S}}),{status:$,details:H,message:{role:"tool",tool_call_id:a,content:S},key:w?.readOnly?`${d}|${$}|${_.slice(0,4e3)}`:`${d}|${e.function.arguments.slice(0,4e3)}|${$}|${_.slice(0,2e3)}`,changed:$==="ok"&&!!w&&!w.readOnly,progress:$==="declined"||$==="skipped"?!0:$==="ok"?h:void 0}};if(t.aborted)return k("skipped",ir);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($=>$.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($=>$.name).join(", ")}.`);if(T===null||typeof T!="object"||Array.isArray(T))return k("error","Error: the arguments must be a JSON object.");let C=Qs(w.parameters,T);if(C.length)return k("error",`Error: invalid arguments for ${d}:
|
|
263
|
+
`),details:{answers:n}}}})}var Tl=100,eu=8192,tu=128e3,Sl="/memory/notes.md",Cl="/AGENTS.md",nu=6e3,ru=3,El=2e6,su=3,ou=6;function iu(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 au(r){let e=h=>h.role==="tool"&&Array.isArray(h.content)&&h.content.some(f=>f.type!=="text");if(!r.some(e))return r;let n=[],t=-1,s=!1;r.forEach((h,f)=>{if(h.role!=="tool"){t=-1;return}t<0&&(t=f,s=!1),!s&&e(h)&&(n.push(t),s=!0)});let i=n.length>Ml?n[n.length-Ml]:0,a=[],l=[],d=()=>{l.length&&a.push({role:"user",content:l}),l=[]};for(let[h,f]of r.entries()){if(f.role!=="tool"&&d(),e(f)){let w=f.content,k=w.filter(C=>C.type!=="text"),x=w.filter(C=>C.type==="text").map(C=>C.text).join(`
|
|
264
|
+
`),T=`${k.length} attachment${k.length===1?"":"s"}`;if(h<i){a.push({...f,content:`${x}${x?`
|
|
265
|
+
`:""}[${T} no longer shown; call the tool again to see the current state]`});continue}a.push({...f,content:`${x}${x?`
|
|
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 Ml=2,Al={image:"image_url",video:"video_url",audio:"audio_url"},$l={image:"picture",video:"video",audio:"audio clip"};function lu(r,e,n){let t=Object.keys(Al).filter(i=>e[i]===!1);if(!t.length)return r;let s=i=>t.find(a=>Al[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 ${$l[d]} was attached here; the model in use${n?` (${n})`:""} does not take ${$l[d]}s, so it is not shown. Say so if it matters.]`}:l});return{...i,content:a}})}var Ei=()=>({total_cost:0,prompt_tokens:0,completion_tokens:0,calls:0}),ss=()=>({runId:"",reason:"aborted",text:"",usage:Ei()}),dr="Skipped: the user stopped the run.",cu=new Set(["read_file","list_files","search_files","write_file","edit_file","move_file","copy_file","delete_file"]),Ll=()=>new st(402,"The reply was cut short because the balance could not cover a full answer; top up to continue",{code:"insufficient_balance"});function po(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 Xt=class{constructor(e,n={}){N(this,"id");N(this,"provider");N(this,"ui");N(this,"workspace");N(this,"tools");N(this,"opts");N(this,"web");N(this,"compactSummaries");N(this,"compactThresholds");N(this,"webCache",null);N(this,"history",[]);N(this,"committed",0);N(this,"droppedTurns",0);N(this,"_usage",Ei());N(this,"handlers",new Map);N(this,"anyHandlers",new Set);N(this,"queue",[]);N(this,"current",null);N(this,"chain",Promise.resolve());N(this,"pendingSkills",[]);N(this,"catalogue",null);N(this,"loop",{seen:new Set,idle:0,warned:!1});N(this,"turnNow",0);N(this,"loaded");N(this,"createdAt",Date.now());N(this,"fixedTitle");N(this,"_ended",null);N(this,"persist");this.provider=gt(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??co(),this.workspace=n.workspace??null;let t=[...n.tools??[]],s=this.workspace?lr(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(...ro(this.workspace,{guard:s}).filter(l=>!a||a.has(l.name)))}n.askUser!==!1&&t.push(uo()),n.sandbox!==!1&&t.push(oo(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()}get title(){return this.fixedTitle}setTitle(e){this.fixedTitle=e.trim()||void 0}applySession(e){if(e.v!==1&&e.v!==2)throw new Error("unknown session format");this.history=e.messages.slice(),this.committed=this.history.length,this.droppedTurns=e.droppedTurns??0,this._usage={...e.usage},this.createdAt=e.createdAt??e.savedAt??Date.now(),this._ended=e.ended??null,this.fixedTitle=e.title&&!Qs(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??Tl,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,...Gt(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.fixedTitle){let t=An(n);t!==Jt&&(this.fixedTitle=t)}return n.title=this.fixedTitle??Jt,n}reset(){if(this.current)throw new Error("cannot reset while a run is active; abort() first");this.history=[],this.fixedTitle=void 0,this._ended=null,this.committed=0,this.droppedTurns=0,this.resetLoop()}useSkill(e){if(!this.workspace)throw new Error("useSkill needs a workspace");this.pendingSkills.push(e)}prompt(e,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?.(ss()),!0):!1}clearQueue(){let e=this.queue;this.queue=[];for(let n of e)n.resolve?.(ss())}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=Ei(),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?.({...ss(),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,h={...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(R){w=e,k=R instanceof Error?R:new Error(String(R))}this.history.push(w)}this._ended=null,this.emit("run_start",{runId:t,message:w});let x=this.opts.maxTurns??Tl,{output:T,input:C}=await this.limits(),D=C,O=Gt(D,this.compactThresholds),M=0;try{if(k)throw k;for(let R=1;;R++){if(s.aborted){i="aborted";break}if(R>x){i="max_turns";break}this.turnNow=R,this.emit("turn_start",{runId:t,turn:R}),this.applySteering(t);let V=await this.systemPrompt(),ie=this.fixedText(V),I=_e(this.history,ie);if(ci(I,D,O)){let P=this.compactSummaries?await this.compactWith(O,t,s):!1,U=_e(this.history,ie);if(!P||ci(U,D,O)){let W=this.history.length&&Be(this.history[0])!==null?[this.history[0]]:[],J=this.history.slice(W.length),j=Kr(J,{budget:D-O.reserveTokens-_e(W),keepTurns:this.opts.keepTurns??4,system:ie});(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:U,tokensAfter:_e(this.history,ie),droppedTurns:j.droppedTurns,elidedResults:j.elidedResults}))}}let ae=await this.activeTools(),le={...this.opts.extra??{},model:this.opts.model??"",messages:[{role:"system",content:V},...this.toWireHistory(await this.mediaSupport())],max_tokens:T};le.model||delete le.model,ae.length&&(le.tools=ae.map(P=>Bs(P))),this.opts.serverTools?.length&&(le.server_tools=this.opts.serverTools),this.opts.prompt&&(le.prompt=this.opts.prompt),this.opts.temperature!==void 0&&(le.temperature=this.opts.temperature),this.opts.top_p!==void 0&&(le.top_p=this.opts.top_p),this.emit("request",{runId:t,turn:R,params:le});let Ee=Date.now(),Me;try{if(_e(this.history,ie)>D*2&&(typeof this.opts.maxInputTokens=="number"||typeof(await this.modelInfo())?.max_input_tokens=="number"))throw new st(413,"the request is far larger than the model's context");Me=await this.callModel(le,t,s)}catch(P){if(this.emit("response",{runId:t,turn:R,durationMs:Date.now()-Ee,error:P instanceof Error?P.message:String(P)}),s.aborted||!Ns(P))throw P;let U=Qa(P);U!==void 0&&U<D&&(D=U,O=Gt(D,this.compactThresholds));let W=!1;for(;!W&&M<2;)W=await this.squeeze(D,M++,O,ie,t,s);if(W){R--;continue}throw new Vt({cause:this.overflowCause(D,ie),used:_e(this.history,ie),window:D},P instanceof Error?P.message:String(P),zs(P)??400)}this.emit("response",{runId:t,turn:R,durationMs:Date.now()-Ee,finishReason:Me.finishReason,usage:Me.usage,message:Me.message}),Me.usage&&this.addUsage(Me.usage);let ue={role:"assistant",content:Me.message.content,ts:Date.now()};Me.message.tool_calls?.length&&(ue.tool_calls=Me.message.tool_calls),Me.reasoning&&(ue.reasoning_content=Me.reasoning),this.history.push(ue),typeof ue.content=="string"&&ue.content&&(l=ue.content);let be=Me.finishReason==="length";this.emit("message_end",{runId:t,message:ue,truncated:be}),this.emit("turn_end",{runId:t,turn:R,usage:Me.usage});let De=ue.tool_calls??[];if(!De.length){if(this.committed=this.history.length,await this.saveSession(),be&&this.balanceLimited(Me.usage,T)){i="error",a=Ll();break}if(!s.aborted&&this.queue.some(P=>P.kind==="steer"))continue;break}let He=await this.runBatch(De,t,s,be);if(this.committed=this.history.length,await this.saveSession(),s.aborted){i="aborted";break}if(!be&&Yr(ue.content).trim()&&De.every(P=>this.tools.find(U=>U.name===P.function.name)?.endsRun)){if(this.queue.some(P=>P.kind==="steer"))continue;break}if(be){if(d++,this.balanceLimited(Me.usage,T)){i="error",a=Ll();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 Fe=this.checkLoop(He);if(Fe==="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}Fe==="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(R){s.aborted?i="aborted":(i="error",a=R instanceof Error?R:new Error(String(R)))}i==="aborted"&&this.closeOpenToolCalls(),this.markRunUsage(f,h),this.committed=this.history.length,this.resetLoop();let S=a instanceof Vt?{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 q={runId:t,reason:i,text:l,usage:this.usage,...a?{error:a}:{}};return this.emit("run_end",q),q}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 lu(au(this.history.map((t,s)=>iu(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=io(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 Fs({appName:this.opts.appName,instructions:typeof this.opts.instructions=="function"?this.opts.instructions():this.opts.instructions,tools:t,workspaceDescription:e&&t.some(s=>cu.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??Cl,2e4),agentsPath:this.opts.instructionsFile||Cl,memory:this.opts.memoryFile===!1?void 0:await n(this.opts.memoryFile??Sl,nu),memoryPath:this.opts.memoryFile===!1?void 0:this.opts.memoryFile??Sl,droppedTurns:this.droppedTurns})}compact(e){return this.exclusive("compact",async n=>{let t=await this.contextTokens(),s=this.squeezed(Gt(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]?Be(t[0]):null,i=s===null?t:t.slice(1);if(!i.length)return s;let a=await this.contextTokens(),l=Gt(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=[Vr(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(()=>({...ss(),reason:"done"}),()=>ss());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"&&Be(n[t])===null);)t--;let s=t>0?n.slice(t).reduce((i,a)=>i+_e([a]),0):Math.floor(_e(n)/2);return{...e,keepRecentTokens:Math.min(e.keepRecentTokens,s)}}async squeeze(e,n,t,s,i,a){let l=_e(this.history,s);n===0&&this.compactSummaries&&await this.compactWith(this.squeezed(t),i,a);let d=this.history.length&&Be(this.history[0])!==null?[this.history[0]]:[],h=this.history.slice(d.length),f=Math.floor(e*(n===0?.7:.4))-_e(d),w=Kr(h,{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:_e(this.history,s),droppedTurns:w.droppedTurns,elidedResults:w.elidedResults})),_e(this.history,s)<l}overflowCause(e,n){let t=this.tools.length?_e([],JSON.stringify(this.tools.map(d=>Bs(d)))):0,s=[...this.history].reverse().find(d=>d.role==="user"&&Be(d)===null),i=s?_e([s]):0,a=_e(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 h of Hs(Zr(e.toSummarize),l)){let f={model:this.opts.model??"",messages:nl(h,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(),x;try{x=this.provider.complete?await this.provider.complete(f,{signal:s}):await Gr((C,D)=>this.provider.stream(C,D),f,{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}x.usage&&this.addUsage(x.usage);let T=x.choices[0];if(this.emit("response",{...w,durationMs:Date.now()-k,finishReason:T?.finish_reason??void 0,usage:x.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=Is(this.history,e.keepRecentTokens);if(!i)return!1;s?.trim()&&(i.focus=s.trim()),this.emit("compaction_start",{runId:n});let a=_e(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=[Vr(l),...i.kept],this.committed=this.history.length,this.emit("compaction",{runId:n,summary:!0,tokensBefore:a,tokensAfter:_e(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 js(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 Gr((d,h)=>this.provider.stream(d,h),e,{signal:t,onText:(d,h)=>{a=!0,s=h,this.emit("text_delta",{runId:n,delta:d,text:h})},onReasoning:(d,h)=>{a=!0,i=h,this.emit("reasoning_delta",{runId:n,delta:d,text:h})},onToolCall:(d,h)=>{a=!0,this.emit("tool_call_delta",{runId:n,index:d.index,id:d.id,name:d.name,delta:h,arguments:d.arguments})}})}catch(d){if(t.aborted||l>=ru||!du(d))throw d;let h=uu(d,l);a&&this.emit("message_reset",{runId:n,reason:d.message}),a=!1,await pu(h,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 h of e){if(d){l.push(this.skipTool(h,n,"Skipped: the user sent a new instruction; the following tool calls were not run."));continue}l.push(await i(h)),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,h=Date.now(),f,w,k=(M,S,q)=>{let R=Yr(S);return this.emit("tool_end",{runId:n,id:a,name:d,status:M,result:i?qs(R,32e3).text:R,details:q,durationMs:Date.now()-h,...l,...typeof S=="string"?{}:{content:S}}),{status:M,details:q,message:{role:"tool",tool_call_id:a,content:S},key:w?.readOnly?`${d}|${M}|${R.slice(0,4e3)}`:`${d}|${e.function.arguments.slice(0,4e3)}|${M}|${R.slice(0,2e3)}`,changed:M==="ok"&&!!w&&!w.readOnly,progress:M==="declined"||M==="skipped"?!0:M==="ok"?f:void 0}};if(t.aborted)return k("skipped",dr);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 x=await this.activeTools();w=x.find(M=>M.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: ${x.map(M=>M.name).join(", ")}.`);if(T===null||typeof T!="object"||Array.isArray(T))return k("error","Error: the arguments must be a JSON object.");let C=so(w.parameters,T);if(C.length)return k("error",`Error: invalid arguments for ${d}:
|
|
267
267
|
- ${C.join(`
|
|
268
268
|
- `)}
|
|
269
|
-
Fix the call and try again.`);if(w.validate){let
|
|
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
|
-
${a.length?JSON.stringify(a.map(l=>
|
|
274
|
-
Added: ${JSON.stringify(
|
|
275
|
-
Updated: ${JSON.stringify(
|
|
276
|
-
`).trim()||`${
|
|
277
|
-
`:""}${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
|
|
278
|
-
`){e+="<br>",n++;continue}e+=
|
|
279
|
-
`&&!(n[0]==="_"&&t+n.length<r.length&&
|
|
269
|
+
Fix the call and try again.`);if(w.validate){let M;try{M=await po(Promise.resolve(w.validate(T)),t)}catch(S){M=S instanceof Error?S.message:String(S)}if(t.aborted)return k("skipped",dr);if(M)return k("error",M.startsWith("Error:")?M:`Error: ${M}`)}try{let M=await po(Promise.resolve(this.opts.onToolCall?.({id:a,name:d,args:T,tool:w})),t);if(M&&M.block)return k("blocked",`${M.reason??"This action was not allowed."} Do not retry it another way; say what you would have done.`);if(!await po(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(M){return t.aborted?k("skipped",dr):k("error",`Error: ${M.message}`)}if(t.aborted)return k("skipped",dr);let D=()=>{try{let M=w.whenStopped?.(T);if(M!==void 0){let S=Jr(M,i?El:w.maxResultChars);return k("skipped",S.content,S.details)}}catch{}return k("skipped",dr)},O=0;try{let M=await po(Promise.resolve(w.execute(T,{signal:t,ui:this.ui,workspace:this.workspace,agent:this,callId:a,parentId:i,update:q=>this.emit("tool_update",{runId:n,id:a,name:d,content:q,...l}),progress:q=>{f=q},callTool:async(q,R,V)=>{let ie=await this.runTool({id:`${a}.${++O}`,type:"function",function:{name:q,arguments:JSON.stringify(R??{})}},n,V?.signal??t,!1,a);return{status:ie.status,text:Yr(ie.message.content),details:ie.details}}})),t);if(t.aborted)return D();let S=Jr(M,i?El:w.maxResultChars);return k("ok",S.content,S.details)}catch(M){if(t.aborted)return D();let S=M instanceof Error?M.message:String(M);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:h,body:f}=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,permission:!0,...h?{ok:h}:{},...f?{body:f}:{}})}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:dr})}checkLoop(e){let n=this.opts.loopGuard;if(n===!1)return"ok";let t=n?.warn??su,s=n?.stop??ou,i=this.loop,a=e.map(h=>h.key!==""&&!i.seen.has(h.key)),l=e.some((h,f)=>h.changed&&a[f]);l&&i.seen.clear();for(let h of e)h.key&&i.seen.add(h.key);let d=l||e.some((h,f)=>h.progress??a[f]);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:Ci(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=Ci(this._usage.total_cost+e)}addUsage(e){this._usage.total_cost=Ci(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:_e(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=>Bs(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:tu,t=typeof e?.max_tokens=="number"&&e.max_tokens>0?e.max_tokens:eu;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:Zt(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 _e(this.history)}contextWindow(){return this.contextTokens()}};function du(r){let e=zs(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 uu(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 pu(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 Ci(r){return Math.round(r*1e6)/1e6}function ho(r){let e=()=>{try{let s=JSON.parse(localStorage.getItem(r)||"[]");return Array.isArray(s)?s:[]}catch{return[]}},n=s=>{try{s.length?localStorage.setItem(r,JSON.stringify(s)):localStorage.removeItem(r)}catch{}},t=s=>fu(`${r}:write`,async()=>{n(s(e()))});return{list:async()=>e(),get:async s=>e().find(i=>i.id===s),put:s=>t(i=>{let a=i.findIndex(l=>l.id===s.id);return a>=0?i[a]=s:i.push(s),i}),delete:s=>t(i=>i.filter(a=>a.id!==s)),subscribe(s){if(typeof window>"u")return()=>{};let i=a=>{a.key===r&&s()};return window.addEventListener("storage",i),()=>window.removeEventListener("storage",i)}}}function Rl(r=[]){let e=new Map(r.map(n=>[n.id,structuredClone(n)]));return{list:async()=>[...e.values()].map(n=>structuredClone(n)),get:async n=>{let t=e.get(n);return t&&structuredClone(t)},put:async n=>{e.set(n.id,structuredClone(n))},delete:async n=>{e.delete(n)}}}var Dl=()=>typeof navigator<"u"?navigator.locks:void 0;function fu(r,e){let n=Dl();return n?n.request(r,{},e):e()}async function hu(r,e){let n=Dl();if(!n)return await e(),!0;let t=!1;return await n.request(r,{ifAvailable:!0},async s=>{s&&(t=!0,await e())}),t}var Ol=/^([01]?\d|2[0-3]):([0-5]\d)$/;function Ln(r){let e=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(r.trim());return e?new Date(+e[1],+e[2]-1,+e[3],+e[4],+e[5],+(e[6]??0)).getTime():/[zZ]|[+-]\d{2}:?\d{2}$/.test(r)?Date.parse(r):NaN}function ot(r){let e=new Date(r),n=t=>String(t).padStart(2,"0");return`${e.getFullYear()}-${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}var mu={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6,jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function os(r){let e=r.trim().split(/\s+/);if(e.length!==5)throw new Error(`cron needs five fields (minute hour day month weekday), got "${r}"`);let n=(t,s,i,a)=>{let l=new Set;for(let d of t.toLowerCase().split(",")){let[h,f]=d.split("/"),w=f===void 0?1:Number(f);if(!Number.isInteger(w)||w<1)throw new Error(`cron ${a}: bad step in "${d}"`);let k=C=>{let D=mu[C]??Number(C);if(!Number.isInteger(D))throw new Error(`cron ${a}: "${C}" is not a number`);return D},x,T;if(h==="*")x=s,T=i;else if(h.includes("-")){let[C,D]=h.split("-");x=k(C),T=k(D)}else x=k(h),T=f===void 0?x:i;if(a==="weekday"&&(x===7&&(x=0),T===7&&x!==0&&(T=6,l.add(0))),x<s||T>i||x>T)throw new Error(`cron ${a}: "${d}" is outside ${s}-${i}`);for(let C=x;C<=T;C+=w)l.add(C)}return l};return{min:n(e[0],0,59,"minute"),hour:n(e[1],0,23,"hour"),dom:n(e[2],1,31,"day"),mon:n(e[3],1,12,"month"),dow:n(e[4],0,7,"weekday"),domAny:e[2]==="*",dowAny:e[4]==="*"}}function fo(r,e){let n=new Date(e);n.setSeconds(0,0),n.setMinutes(n.getMinutes()+1);let t=[...r.hour].sort((i,a)=>i-a),s=[...r.min].sort((i,a)=>i-a);for(let i=0;i<366*5;i++){let a=new Date(n.getFullYear(),n.getMonth(),n.getDate()+i);if(!r.mon.has(a.getMonth()+1))continue;let l=r.dom.has(a.getDate()),d=r.dow.has(a.getDay());if(r.domAny&&r.dowAny||(r.domAny?d:r.dowAny?l:l||d))for(let h of t)for(let f of s){let w=new Date(a.getFullYear(),a.getMonth(),a.getDate(),h,f).getTime();if(w>=n.getTime())return w}}return null}function pr(r,e=1){switch(r?.type){case"once":return Number.isFinite(Ln(r.at))?void 0:`"at" must be a local time like 2026-11-28 09:00, got "${r.at}"`;case"every":return Number.isFinite(r.minutes)&&r.minutes>=e?void 0:`"minutes" must be at least ${e}`;case"daily":return Ol.test(r.time??"")?r.days&&(!r.days.length||r.days.some(n=>!Number.isInteger(n)||n<0||n>6))?'"days" must be weekday numbers 0 (Sunday) to 6':void 0:`"time" must be HH:mm, got "${r.time}"`;case"cron":{try{let n=os(r.cron);if(fo(n,Date.now())===null)return"this cron never runs"}catch(n){return n.message}if(e>1){let n=os(r.cron),t=fo(n,Date.now()),s=fo(n,t);if(s!==null&&s-t<e*6e4)return`runs more often than every ${e} minutes`}return}default:return'"type" must be once, every, daily or cron'}}function Pn(r,e,n=e){switch(r.type){case"once":{let t=Ln(r.at);return Number.isFinite(t)&&t>e?t:null}case"every":{let t=r.minutes*6e4,s=n+t;return s<=e&&(s=e+t),s}case"daily":{let t=Ol.exec(r.time);if(!t)return null;let s=new Date(e);for(let i=0;i<8;i++){let a=new Date(s.getFullYear(),s.getMonth(),s.getDate()+i,+t[1],+t[2]);if(a.getTime()>e&&(!r.days?.length||r.days.includes(a.getDay())))return a.getTime()}return null}case"cron":try{return fo(os(r.cron),e)}catch{return null}}}var gu=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yu=["\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"];function is(r,e="en"){let n=e==="zh";switch(r.type){case"once":{let t=Ln(r.at);return(n?"\u4E00\u6B21 \xB7 ":"Once \xB7 ")+(Number.isFinite(t)?ot(t):r.at)}case"every":{let t=r.minutes,s=t%1440===0?n?`${t/1440} \u5929`:`${t/1440} d`:t%60===0?n?`${t/60} \u5C0F\u65F6`:`${t/60} h`:n?`${t} \u5206\u949F`:`${t} min`;return n?`\u6BCF ${s}`:`Every ${s}`}case"daily":{let t=[...new Set(r.days??[])].sort((s,i)=>s-i);return!t.length||t.length===7?(n?"\u6BCF\u5929 ":"Daily ")+r.time:t.join()==="1,2,3,4,5"?(n?"\u5DE5\u4F5C\u65E5 ":"Weekdays ")+r.time:t.join()==="0,6"?(n?"\u5468\u672B ":"Weekends ")+r.time:(n?"\u6BCF\u5468"+t.map(s=>yu[s]).join("\u3001")+" ":t.map(s=>gu[s]).join(", ")+" ")+r.time}case"cron":return`cron ${r.cron}`}}var wu=()=>`t_${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`;function as(r,e={},n=Date.now()){let t=r.name?.trim(),s=r.prompt?.trim();if(!t)throw new Error("a task needs a name");if(!s)throw new Error("a task needs a prompt");let i=pr(r.schedule,e.minMinutes??5);if(i)throw new Error(i);let a=r.enabled??!0,l=a?Pn(r.schedule,n):null;if(a&&l===null)throw new Error("that time has already passed");return{id:wu(),name:t,prompt:s,schedule:r.schedule,enabled:a,next:l,by:r.by,created:n,updated:n,runs:0}}function fr(r,e,n={},t=Date.now()){let s={...r,updated:t};if(e.name!==void 0){if(!e.name.trim())throw new Error("a task needs a name");s.name=e.name.trim()}if(e.prompt!==void 0){if(!e.prompt.trim())throw new Error("a task needs a prompt");s.prompt=e.prompt.trim()}if(e.schedule){let i=pr(e.schedule,n.minMinutes??5);if(i)throw new Error(i);s.schedule=e.schedule}if(e.enabled!==void 0&&(s.enabled=e.enabled),(e.schedule||e.enabled!==void 0)&&(s.next=s.enabled?Pn(s.schedule,t):null,s.enabled&&s.next===null))throw new Error("that time has already passed");return s}var Pl={type:"object",description:`When it runs, in the user's local time. type "once": at ("YYYY-MM-DD HH:mm") or in_minutes (from now). type "every": minutes. type "daily": time ("HH:mm") and optional days (0 = Sunday \u2026 6 = Saturday; [1,2,3,4,5] for weekdays). type "cron": cron (five fields, local time).`,properties:{type:{type:"string",enum:["once","every","daily","cron"]},at:{type:"string"},in_minutes:{type:"number"},minutes:{type:"number"},time:{type:"string"},days:{type:"array",items:{type:"integer",minimum:0,maximum:6}},cron:{type:"string"}},required:["type"],additionalProperties:!1};function _l(r,e){switch(r.type){case"once":return{type:"once",at:r.at??(r.in_minutes!==void 0?ot(e+Math.max(1,Math.round(r.in_minutes))*6e4):"")};case"every":return{type:"every",minutes:Math.round(r.minutes??0)};case"daily":return{type:"daily",time:r.time??"",...r.days?.length?{days:r.days}:{}};case"cron":return{type:"cron",cron:r.cron??""}}}function Mi(r,e=Date.now()){return{id:r.id,name:r.name,prompt:r.prompt,schedule:is(r.schedule),enabled:r.enabled,next:r.next?ot(r.next):null,runs:r.runs,...r.last?{last_run:`${ot(r.last.at)} ${r.last.status}${r.last.note?": "+r.last.note:""}`}:{},...r.next&&r.next<e?{overdue:!0}:{}}}function mo(r,e={}){let n=e.now??Date.now,t=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"local"}})(),s=()=>{try{e.onChange?.()}catch{}},i=()=>`Now: ${ot(n())} (${t}).`;return[Ne({name:"schedule_list",description:"Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",readOnly:!0,display:{label:()=>"Scheduled tasks"},execute:async()=>{let a=await r.list();return`${i()}
|
|
273
|
+
${a.length?JSON.stringify(a.map(l=>Mi(l,n())),null,1):"No scheduled tasks."}`}}),Ne({name:"schedule_add",description:`Adds a scheduled task: at the set times the agent is given \`prompt\` in a conversation of the task's own and works on it unattended (the user may not be watching; questions wait for them). Runs only while the app is open in a browser; a run missed while it was closed happens once when it is next opened. Repeats at most every ${e.minMinutes??5} minutes. Write the prompt so it stands alone: the run does not see this conversation.`,parameters:{type:"object",properties:{name:{type:"string",description:'Short name the user sees, e.g. "Morning news digest".'},prompt:{type:"string",description:"The instruction for each run, complete on its own."},schedule:Pl,enabled:{type:"boolean",description:"Default true."}},required:["name","prompt","schedule"],additionalProperties:!1},display:{label:a=>`Schedule \u201C${a.name??""}\u201D`},execute:async a=>{let l=await r.list();if(l.length>=(e.maxTasks??20))throw new Error(`there are already ${l.length} tasks, the most allowed; remove one first`);let d=as({name:a.name,prompt:a.prompt,schedule:_l(a.schedule,n()),enabled:a.enabled,by:"agent"},e,n());return await r.put(d),s(),`${i()}
|
|
274
|
+
Added: ${JSON.stringify(Mi(d,n()))}`}}),Ne({name:"schedule_update",description:"Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",parameters:{type:"object",properties:{id:{type:"string"},name:{type:"string"},prompt:{type:"string"},schedule:Pl,enabled:{type:"boolean"}},required:["id"],additionalProperties:!1},display:{label:a=>`Update scheduled task ${a.id??""}`},execute:async a=>{let l=await r.get(a.id);if(!l)throw new Error(`no task with id ${a.id}; schedule_list shows them`);let d=fr(l,{name:a.name,prompt:a.prompt,schedule:a.schedule?_l(a.schedule,n()):void 0,enabled:a.enabled},e,n());return await r.put(d),s(),`${i()}
|
|
275
|
+
Updated: ${JSON.stringify(Mi(d,n()))}`}}),Ne({name:"schedule_remove",description:"Removes a scheduled task (by id). Its conversation stays.",parameters:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},display:{label:a=>`Remove scheduled task ${a.id??""}`},execute:async a=>{let l=await r.get(a.id);if(!l)throw new Error(`no task with id ${a.id}`);return await r.delete(a.id),s(),`Removed \u201C${l.name}\u201D.`}})]}var ur=class{constructor(e){N(this,"opts",e);N(this,"timer",null);N(this,"busy",!1);N(this,"unsub",null);N(this,"running",new Set);N(this,"poke",()=>{this.tick()})}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.opts.interval??2e4),this.unsub=this.opts.store.subscribe?.(()=>this.opts.onChange?.())??null,typeof window<"u"&&window.addEventListener("focus",this.poke),this.tick())}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.unsub?.(),this.unsub=null,typeof window<"u"&&window.removeEventListener("focus",this.poke)}async tick(){if(this.busy||!this.opts.idle())return;let e=(this.opts.now??Date.now)(),n=(await this.opts.store.list()).filter(t=>t.enabled&&t.next!==null&&t.next<=e).sort((t,s)=>t.next-s.next);for(let t of n)if(this.busy||!this.opts.idle()||await this.fire(t.id,!1))return}runNow(e){return this.fire(e,!0)}async fire(e,n){if(this.busy)return!1;this.busy=!0;let t=!1;try{return await hu(`${this.opts.lockPrefix}:task:${e}`,async()=>{let s=this.opts.store,i=this.opts.now??Date.now,a=await s.get(e),l=i();if(!a||!n&&(!a.enabled||a.next===null||a.next>l))return;let d=a.enabled?Pn(a.schedule,l,l):a.next;await s.put({...a,next:a.schedule.type==="once"&&!n?null:d,...a.schedule.type==="once"&&!n?{enabled:!1}:{}}),t=!0,this.running.add(e),this.opts.onChange?.();let h;try{h=await this.opts.run(a)}catch(w){h={status:"error",note:w.message}}this.running.delete(e);let f=await s.get(e);f&&await s.put({...f,runs:f.runs+1,last:{at:l,...h}}),this.opts.onChange?.()}),t}finally{this.busy=!1}}};var Nl="2025-06-18",ze=class extends Error{constructor(n,t,s){super(n);N(this,"status",t);N(this,"code",s);this.name="MCPError"}};async function Il(r,e={}){e.signal?.throwIfAborted();let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new ze("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,h=e.signal,f=I=>({...e.headers??{},...I?{"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=(I,ae)=>t(n,{method:"POST",headers:f(!0),body:JSON.stringify(I),signal:ae,redirect:"error",credentials:"omit"}),k=I=>{let ae=I.method==="ping"?{jsonrpc:"2.0",id:I.id,result:{}}:{jsonrpc:"2.0",id:I.id,error:{code:-32601,message:`${I.method} is not supported by this client`}};w(ae,AbortSignal.timeout(s)).then(le=>le.body?.cancel()).catch(()=>{})},x=async(I,ae,le,Ee,Me=!1)=>{if(d)throw new ze("The MCP connection is closed.");let ue=l++,be=AbortSignal.timeout(s),De=Fl([be,...le?[le]:[],...h?[h]:[]]),He={jsonrpc:"2.0",id:ue,method:I,...ae?{params:Ee?{...ae,_meta:{progressToken:ue}}:ae}:{}},Fe=()=>{I!=="initialize"&&w({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:ue,reason:"The user stopped it."}},AbortSignal.timeout(5e3)).then(P=>P.body?.cancel()).catch(()=>{})};le?.addEventListener("abort",Fe,{once:!0});try{let P;try{P=await w(He,De)}catch(ee){throw le?.throwIfAborted(),be.aborted?new ze(`${I} timed out after ${Math.round(s/1e3)} s.`):new ze(`Could not reach the MCP server (${ee.message}). Check the address, its CORS settings and your network.`)}if(P.status===404&&i&&!Me&&I!=="initialize")return await P.body?.cancel(),i=void 0,await O(le),x(I,ae,le,Ee,!0);if(!P.ok)throw await P.body?.cancel(),new ze(`The MCP server answered ${I} with HTTP ${P.status}${P.status===401||P.status===403?" (check the token)":""}.`,P.status);let U=P.headers.get("mcp-session-id");U&&(i=U);let W=ee=>{if(ee.id===ue&&(ee.result||ee.error)){if(ee.error)throw new ze(`${I}: ${ee.error.message}`,void 0,ee.error.code);return ee.result??{}}if(ee.method&&ee.id!==void 0)k(ee);else if(ee.method==="notifications/progress"&&ee.params?.progressToken===ue&&Ee){let fe=ee.params;Ee(fe.message??(fe.total?`${fe.progress??0} / ${fe.total}`:String(fe.progress??"")))}};if((P.headers.get("content-type")??"").includes("text/event-stream")&&P.body){for await(let ee of Wr(P.body,De)){let fe;try{fe=JSON.parse(ee)}catch{continue}for(let ve of Array.isArray(fe)?fe:[fe]){let pe=W(ve);if(pe)return P.body.cancel().catch(()=>{}),pe}}throw le?.throwIfAborted(),be.aborted?new ze(`${I} timed out after ${Math.round(s/1e3)} s.`):new ze(`The MCP server ended the stream without answering ${I}.`)}let j;try{j=await P.json()}catch{throw new ze(`The MCP server's answer to ${I} is not JSON.`)}for(let ee of Array.isArray(j)?j:[j]){let fe=W(ee);if(fe)return fe}throw new ze(`The MCP server did not answer ${I}.`)}finally{le?.removeEventListener("abort",Fe)}},T=async I=>{await(await w({jsonrpc:"2.0",method:I},Fl([AbortSignal.timeout(s),...h?[h]:[]]))).body?.cancel()},C={name:"mcp"},D,O=async I=>{a=void 0;let ae=await x("initialize",{protocolVersion:Nl,capabilities:{},clientInfo:{name:e.clientName??"runapps-agent",version:"1"}},I);a=typeof ae.protocolVersion=="string"?ae.protocolVersion:Nl;let le=ae.serverInfo;le?.name&&(C={name:le.name,version:le.version,title:le.title}),typeof ae.instructions=="string"&&(D=ae.instructions),await T("notifications/initialized")};await O(e.signal);let M=[],S=[],q=zl(e.prefix??C.name).slice(0,24)||"mcp",R=e.name||C.title||C.name,V=async I=>{let ae=[],le=new Set,Ee;do{let ue=await x("tools/list",Ee?{cursor:Ee}:{},I);if(!Array.isArray(ue.tools))throw new ze("The MCP server's tool list is malformed.");for(let be of ue.tools){if(!be||typeof be.name!="string"||!be.name)throw new ze("The MCP server listed a tool without a name.");let De=be.inputSchema&&typeof be.inputSchema=="object"?be.inputSchema:{type:"object"};ae.push({...be,inputSchema:{type:"object",properties:{},...De}})}if(ae.length>(e.maxTools??64))throw new ze(`The MCP server has more than ${e.maxTools??64} tools (maxTools).`);if(Ee=typeof ue.nextCursor=="string"&&ue.nextCursor?ue.nextCursor:void 0,Ee){if(le.has(Ee))throw new ze("The MCP server's tool list repeats a page.");le.add(Ee)}}while(Ee);M=ae;let Me=new Set;return S=ae.map(ue=>{let be=`${q}__${zl(ue.name)}`.slice(0,64);for(let P=2;Me.has(be);P++)be=`${be.slice(0,60)}_${P}`;Me.add(be);let De=ue.annotations?.readOnlyHint===!0,He=e.confirm==="never"?!1:e.confirm==="unless-read-only"?!De:!0,Fe=ue.title??ue.annotations?.title??ue.name;return Ne({name:be,description:`[${R} \u2014 MCP server] ${Fe!==ue.name?`${Fe}. `:""}${ue.description??""}`.trim().slice(0,4e3),parameters:ue.inputSchema,readOnly:De,destructive:ue.annotations?.destructiveHint===!0||!De&&He,maxResultChars:e.maxResultChars,confirm:He?P=>({title:`Run ${R} / ${ue.name}?`,message:JSON.stringify(P,null,2).slice(0,4e3)}):()=>!1,async execute(P,U){let W;try{W=await x("tools/call",{name:ue.name,arguments:P},U.signal,j=>j&&U.update(j))}catch(j){throw U.signal.throwIfAborted(),j instanceof ze&&j.code!==void 0?j:new ze(`${j.message} Whether ${ue.name} took effect on the server is unknown; do not repeat it without checking.`)}let J=bu(W,e.images===!0);if(W.isError===!0)throw new ze(J.map(j=>j.type==="text"?j.text:"").join(`
|
|
276
|
+
`).trim()||`${ue.name} reported an error.`);return J.length===1&&J[0].type==="text"?J[0].text:J}})}),S};try{await V(e.signal)}catch(I){throw await ie(),I}h=void 0;async function ie(){if(!d&&(d=!0,!!i))try{await(await t(n,{method:"DELETE",headers:f(!1),redirect:"error",credentials:"omit",signal:AbortSignal.timeout(5e3)})).body?.cancel()}catch{}}return{get tools(){return S},get serverTools(){return M},server:C,instructions:D,refresh:V,close:ie}}function bu(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}:
|
|
277
|
+
`:""}${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 zl(r){return r.replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")}function Fl(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 xu(r,e={}){return new Xt(r,e)}function vu(r,e={}){let n=r?gt(r):null;return ar.open(n,{...e,project:e.project??n?.name??void 0})}var ku={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ce(r){return r.replace(/[&<>"']/g,e=>ku[e])}function Tu(r){let e=r.trim();return/^(https?:\/\/|mailto:)/i.test(e)||/^(\/|\.\/|\.\.\/|#)/.test(e)&&!/^\/\//.test(e)?e:null}var Ai=/[\p{L}\p{N}]/u,Hl=/`+/y,Ul=/\[([^\]]*)\]\(((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?\)/y,jl=/https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))+/y;function zt(r){let e="",n=0,t=r.length,s=new Map,i=-2;for(;n<t;){let a=r[n];if(a==="`"){Hl.lastIndex=n;let l=Hl.exec(r)[0],d=r.indexOf(l,n+l.length);if(d>0){e+=`<code>${Ce(r.slice(n+l.length,d).trim())}</code>`,n=d+l.length;continue}e+=Ce(l),n+=l.length;continue}if(a==="["&&(i!==-1&&i<n&&(i=r.indexOf("](",n)),i!==-1)){Ul.lastIndex=n;let l=Ul.exec(r);if(l){let d=Tu(l[2]),h=zt(l[1]);e+=d?`<a href="${Ce(d)}" target="_blank" rel="noopener noreferrer">${h}</a>`:h,n+=l[0].length;continue}}if(a==="h"&&r.startsWith("http",n)&&(n===0||!Ai.test(r[n-1]))){jl.lastIndex=n;let l=jl.exec(r);if(l){let d=l[0].replace(/[.,;:!?'"]+$/,"");if(d.length>8){e+=`<a href="${Ce(d)}" target="_blank" rel="noopener noreferrer">${Ce(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&&Ai.test(r[n-1]))&&(s.get(l)??1/0)>n){let h=Su(r,n+l.length,l);if(h>0){let f=zt(r.slice(n+l.length,h));e+=l==="~~"?`<del>${f}</del>`:l.length===2?`<strong>${f}</strong>`:`<em>${f}</em>`,n=h+l.length;continue}s.set(l,Math.min(s.get(l)??1/0,n))}e+=Ce(l),n+=l.length;continue}if(a==="\\"&&n+1<t&&/[\\`*_{}\[\]()#+\-.!~|>]/.test(r[n+1])){e+=Ce(r[n+1]),n+=2;continue}if(a===`
|
|
278
|
+
`){e+="<br>",n++;continue}e+=Ce(a),n++}return e}function Su(r,e,n){let t=e;for(;(t=r.indexOf(n,t))>0;){if(t>e&&r[t-1]!==" "&&r[t-1]!==`
|
|
279
|
+
`&&!(n[0]==="_"&&t+n.length<r.length&&Ai.test(r[t+n.length])))return t;t+=n.length}return-1}var Cu=/^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)/;function hr(r){let e=r.replace(/\r\n?/g,`
|
|
280
280
|
`).split(`
|
|
281
|
-
`),n=[],t=0,s=[],i=()=>{s.length&&(n.push(`<p>${
|
|
282
|
-
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=
|
|
281
|
+
`),n=[],t=0,s=[],i=()=>{s.length&&(n.push(`<p>${zt(s.join(`
|
|
282
|
+
`))}</p>`),s.length=0)};for(;t<e.length;){let a=e[t],l=Cu.exec(a);if(l&&!(l[2][0]==="`"&&a.slice(l[0].length).includes("`"))){i();let f=l[2],w=l[3]??"",k=[];t++;let x=C=>{let D=C.trim();return D.length>=f.length&&D===f[0].repeat(D.length)};for(;t<e.length&&!x(e[t]);)k.push(e[t]),t++;t++;let T=w?` class="language-${Ce(w)}"`:"";n.push(`<pre><code${T}>${Ce(k.join(`
|
|
283
283
|
`))}
|
|
284
|
-
</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}>${
|
|
285
|
-
`))}</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
|
|
286
|
-
`)}function
|
|
287
|
-
`).trim(),i=n?t.replace(/^(<input[^>]*> )/,"$1"):"",a=n?i.slice(0,i.indexOf("> ")+2)+
|
|
288
|
-
`)?`<br>${l.slice(3,-4)}`:l)}var ur=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),f=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(([O])=>!v.has(O)),C=null;for(let O=h;O<=w;O++){let I=this.wrapper(this.rows[O]);I.parentNode!==this.win&&this.win.insertBefore(I,C?C.nextSibling:this.win.firstChild),C=I}for(let[O,I]of T)this.ro?.unobserve(I),I.remove(),this.wrappers.delete(O);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]-f));continue}this.follow&&Math.abs(e.scrollTop-s())>1&&this.setTop(s());return}}};function u(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>`,N={clock:(r=14)=>se(r,'<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/>'),play:(r=13)=>se(r,'<polygon points="6 3 20 12 6 21 6 3"/>'),pause:(r=13)=>se(r,'<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>'),pencil:(r=13)=>se(r,'<path d="M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5z"/>'),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 co(r,e){return new Promise(n=>{let t=u("div","ra-modal"),s=u("div","ra-dlg");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",e.title),s.append(u("div","ra-dt",e.title)),e.message&&s.append(u("div","ra-dm",e.message)),e.body&&s.append(...e.body);let i=u("div","ra-btns"),a=h=>{t.remove(),n(h)},l=u("button","ra-btn",e.cancel);l.type="button",l.addEventListener("click",()=>a(!1));let d=u("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 f=e.focus==="ok"?d:e.focus instanceof HTMLElement?e.focus:l;queueMicrotask(()=>{f.focus(),f instanceof HTMLInputElement&&f.select()})})}function wt(r,e,n,t){return co(r,{title:e,message:n,...t})}async function zl(r,e,n){let t=u("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await co(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}var lo;function Il(r){lo=r}function Fl(){if(lo===!1)return;if(lo)return lo;let r=globalThis.puter?.ui;return typeof r?.openFiles=="function"&&typeof r?.saveFile=="function"?r:void 0}function ss(r,e){let n=Fl();if(!n){r.click();return}n.openFiles({accept:r.accept||void 0,multiple:r.multiple}).then(t=>{t?.length&&e(t)},()=>r.click())}function os(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=Fl();if(s){s.saveFile(t,r).catch(()=>Nl(t,r));return}Nl(t,r)}function Nl(r,e){let n=URL.createObjectURL(r),t=u("a");t.href=n,t.download=e,document.body.append(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4)}function pr(r,e,n){r.innerHTML=dr(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=u("div","ra-cb"),l=u("div","ra-cbh");l.append(u("span","",i));let d=u("button","ra-copy");d.type="button",d.innerHTML=N.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=N.check(14),setTimeout(()=>{d.innerHTML=N.copy()},1200)})}),l.append(d),t.replaceWith(a),a.append(l,t)}for(let t of Array.from(r.querySelectorAll("table"))){let s=u("div","ra-tw");t.replaceWith(s),s.append(t)}}function En(r,e={}){let n=e.options??[],t=e.value??n[0]?.value??"",s=!1,i=u("button","ra-sel");i.type="button",i.setAttribute("aria-haspopup","listbox");let a=u("span","ra-sell"),l=u("span","ra-selc");l.innerHTML=N.chevDown(14),i.append(a,l);let d=null,f=0,h="",w=()=>{let S=n.find(H=>H.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 H=S!==t;t=S,w(),v(),H&&i.dispatchEvent(new Event("change",{bubbles:!0}))},O=S=>{S.replaceChildren();let H=k();f>=H.length&&(f=Math.max(0,H.length-1)),H.forEach((_,W)=>{let ae=u("div","ra-selo"+(W===f?" act":"")+(_.value===t?" cur":""));ae.setAttribute("role","option"),ae.setAttribute("aria-selected",String(_.value===t));let Z=u("span","ra-selt");Z.innerHTML=_.value===t?N.tick(13):"",ae.append(Z,u("span","ra-selol",_.label)),_.note&&ae.append(u("span","ra-selon",_.note)),ae.addEventListener("pointermove",()=>{f!==W&&(f=W,S.querySelectorAll(".ra-selo").forEach((ge,we)=>ge.classList.toggle("act",we===W)))}),ae.addEventListener("click",()=>C(_.value)),S.append(ae)}),H.length||S.append(u("div","ra-selnone","\u2014")),S.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},I=()=>{if(d||s)return;d=u("div","ra-selp"),d.setAttribute("role","listbox");let S=u("div","ra-sellist"),H=null;n.length>=(e.filterAt??10)&&(H=u("input","ra-self"),H.type="text",H.placeholder=e.filterLabel??"Filter\u2026",H.addEventListener("input",()=>{h=H.value,f=0,O(S)}),H.addEventListener("keydown",$),d.append(H)),d.append(S),f=Math.max(0,n.findIndex($e=>$e.value===t)),O(S),r.append(d);let _=r.getBoundingClientRect(),W=i.getBoundingClientRect(),ae=_.bottom-W.bottom-8,Z=W.top-_.top-8,ge=Math.min(d.scrollHeight,320),we=ae<ge&&Z>ae;d.style.left=`${W.left-_.left+r.scrollLeft}px`,d.style.width=`${W.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,we?Z:ae))}px`,d.style.top=we?`${W.top-_.top+r.scrollTop-d.offsetHeight-4}px`:`${W.bottom-_.top+r.scrollTop+4}px`,i.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",T,!0),(H??i).focus()},$=S=>{if(!d){(S.key==="ArrowDown"||S.key==="ArrowUp"||S.key==="Enter"||S.key===" ")&&(S.preventDefault(),I());return}let H=k(),_=d.querySelector(".ra-sellist");if(S.key==="ArrowDown")S.preventDefault(),f=Math.min(H.length-1,f+1),O(_);else if(S.key==="ArrowUp")S.preventDefault(),f=Math.max(0,f-1),O(_);else if(S.key==="Enter"){S.preventDefault();let W=H[f];W&&C(W.value)}else S.key==="Escape"?(S.preventDefault(),S.stopPropagation(),v()):S.key==="Tab"&&v(!1)};return i.addEventListener("click",()=>d?v():I()),i.addEventListener("keydown",$),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(H=>H.value===t)||(t=n[0]?.value??""),w()},close(){v(!1)}}}var Hl=`
|
|
284
|
+
</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}>${zt(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 f=[];for(;t<e.length&&/^\s{0,3}>/.test(e[t]);)f.push(e[t].replace(/^\s{0,3}>\s?/,"")),t++;n.push(`<blockquote>${hr(f.join(`
|
|
285
|
+
`))}</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 f=T=>T.trim().replace(/^\|/,"").replace(/(?<!\\)\|$/,"").split(/(?<!\\)\|/).map(C=>C.trim().replace(/\\\|/g,"|")),w=f(e[t+1]).map(T=>T.startsWith(":")&&T.endsWith(":")?"center":T.endsWith(":")?"right":T.startsWith(":")?"left":""),k=(T,C)=>`<tr>${f(T).map((D,O)=>`<${C}${w[O]?` style="text-align:${w[O]}"`:""}>${zt(D)}</${C}>`).join("")}</tr>`,x=`<table><thead>${k(a,"th")}</thead><tbody>`;for(t+=2;t<e.length&&e[t].includes("|")&&e[t].trim();)x+=k(e[t],"td"),t++;n.push(x+"</tbody></table>");continue}let h=/^(\s*)([-*+]|\d+[.)])\s+/.exec(a);if(h){i();let{html:f,next:w}=Eu(e,t,h[1].length);n.push(f),t=w;continue}s.push(a),t++}return i(),n.join(`
|
|
286
|
+
`)}function Eu(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 f=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(r[l]);if(!f||f[1].length!==n||/\d/.test(f[2])!==s)break;let w=[f[3]];for(l++;l<r.length;){let x=r[l];if(!x.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(x.match(/^\s*/)[0].length>n){w.push(x),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>${Mu(w,n,!!k)}</li>`)}let d=s?"ol":"ul",h=s&&i!==1?` start="${i}"`:"";return{html:`<${d}${h}>${a.join("")}</${d}>`,next:l}}function Mu(r,e,n){let t=r[0],s=r.slice(1).map(d=>d.replace(new RegExp(`^\\s{0,${e+2}}`),"")).join(`
|
|
287
|
+
`).trim(),i=n?t.replace(/^(<input[^>]*> )/,"$1"):"",a=n?i.slice(0,i.indexOf("> ")+2)+zt(i.slice(i.indexOf("> ")+2)):zt(t);if(!s)return a;let l=hr(s);return a+(l.startsWith("<p>")&&!l.includes(`</p>
|
|
288
|
+
`)?`<br>${l.slice(3,-4)}`:l)}var mr=class{constructor(e,n,t={}){N(this,"scroller",e);N(this,"inner",n);N(this,"rows",[]);N(this,"_follow",!0);N(this,"onFollow");N(this,"top");N(this,"win");N(this,"bottom");N(this,"wrappers",new Map);N(this,"ro");N(this,"estimate");N(this,"overscan");N(this,"rowClass");N(this,"followWithin");N(this,"offsets",[]);N(this,"first",0);N(this,"last",-1);N(this,"frame",null);N(this,"disposed",!1);N(this,"expectedTop",-1);N(this,"pinned",null);N(this,"lastTop",0);N(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()});N(this,"onWheel",e=>{this.pinned=null,e.deltaY<0&&this.scroller.scrollTop>0&&(this.follow=!1)});N(this,"touchY",0);N(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"}scrollToIndex(e){if(this.disposed||e<0||e>=this.rows.length)return;this.pinned=null,this.follow=!1;let n=this.computeOffsets();this.bottom.style.height=`${n}px`,this.setTop(this.offsets[e]),this.layout()}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),h=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 x=new Set(this.rows.slice(f,w+1)),T=[...this.wrappers].filter(([D])=>!x.has(D)),C=null;for(let D=f;D<=w;D++){let O=this.wrapper(this.rows[D]);O.parentNode!==this.win&&this.win.insertBefore(O,C?C.nextSibling:this.win.firstChild),C=O}for(let[D,O]of T)this.ro?.unobserve(O),O.remove(),this.wrappers.delete(D);this.first=f,this.last=w}let k=!1;for(let x=f;x<=w;x++){let T=this.rows[x],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]-h));continue}this.follow&&Math.abs(e.scrollTop-s())>1&&this.setTop(s());return}}};function u(r,e,n){let t=document.createElement(r);return e&&(t.className=e),n!==void 0&&(t.textContent=n),t}var oe=(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>`,z={clock:(r=14)=>oe(r,'<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/>'),play:(r=13)=>oe(r,'<polygon points="6 3 20 12 6 21 6 3"/>'),pause:(r=13)=>oe(r,'<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>'),pencil:(r=13)=>oe(r,'<path d="M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5z"/>'),tick:(r=14)=>oe(r,'<path d="M20 6 9 17l-5-5"/>'),enter:(r=14)=>oe(r,'<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),lock:(r=12)=>oe(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)=>oe(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)=>oe(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)=>oe(r,'<path d="M14.5 9.5 22 2M22 2l-7 20-4-9-9-4z"/>'),hist:(r=14)=>oe(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)=>oe(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)=>oe(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)=>oe(r,'<path d="M12 5v14M5 12h14"/>'),chev:(r=14)=>oe(r,'<path d="m9 18 6-6-6-6"/>'),brain:(r=13)=>oe(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)=>oe(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)=>oe(r,'<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>'),xcircle:(r=15)=>oe(r,'<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6M9 9l6 6"/>'),ban:(r=15)=>oe(r,'<circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/>'),square:(r=12)=>oe(r,'<rect x="3" y="3" width="18" height="18" rx="2"/>'),corner:(r=14)=>oe(r,'<path d="M20 4v7a4 4 0 0 1-4 4H4"/><path d="m9 10-5 5 5 5"/>'),x:(r=12)=>oe(r,'<path d="M18 6 6 18M6 6l12 12"/>'),trash:(r=13)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(r,'<path d="m6 9 6 6 6-6"/>'),checks:(r=13)=>oe(r,'<path d="M18 6 7 17l-5-5"/><path d="m22 10-7.5 7.5L13 16"/>'),undo:(r=13)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(r,'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),bug:(r=14)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(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)=>oe(r,'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),braces:(r=13)=>oe(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)=>oe(r,'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),wrench:(r=13)=>oe(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 yo(r,e){return new Promise(n=>{let t=u("div","ra-modal"),s=u("div","ra-dlg");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",e.title),s.append(u("div","ra-dt",e.title)),e.message&&s.append(u("div","ra-dm",e.message)),e.body&&s.append(...e.body);let i=u("div","ra-btns"),a=f=>{t.remove(),n(f)},l=u("button","ra-btn",e.cancel);l.type="button",l.addEventListener("click",()=>a(!1));let d=u("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 h=e.focus==="ok"?d:e.focus instanceof HTMLElement?e.focus:l;queueMicrotask(()=>{h.focus(),h instanceof HTMLInputElement&&h.select()})})}function yt(r,e,n,t){return yo(r,{title:e,message:n,...t})}async function Bl(r,e,n){let t=u("input","ra-field");return t.type="text",t.value=n.initial??"",n.placeholder&&(t.placeholder=n.placeholder),await yo(r,{title:e,body:[t],ok:n.ok,cancel:n.cancel,focus:t,submitOnEnter:!0})&&t.value.trim()||null}var go;function Wl(r){go=r}function Kl(){if(go===!1)return;if(go)return go;let r=globalThis.puter?.ui;return typeof r?.openFiles=="function"&&typeof r?.saveFile=="function"?r:void 0}function ls(r,e){let n=Kl();if(!n){r.click();return}n.openFiles({accept:r.accept||void 0,multiple:r.multiple}).then(t=>{t?.length&&e(t)},()=>r.click())}function cs(r,e,n){let t=new Blob([e],{type:n||"application/octet-stream"}),s=Kl();if(s){s.saveFile(t,r).catch(()=>ql(t,r));return}ql(t,r)}function ql(r,e){let n=URL.createObjectURL(r),t=u("a");t.href=n,t.download=e,document.body.append(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4)}function gr(r,e,n){r.innerHTML=hr(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=u("div","ra-cb"),l=u("div","ra-cbh");l.append(u("span","",i));let d=u("button","ra-copy");d.type="button",d.innerHTML=z.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=z.check(14),setTimeout(()=>{d.innerHTML=z.copy()},1200)})}),l.append(d),t.replaceWith(a),a.append(l,t)}for(let t of Array.from(r.querySelectorAll("table"))){let s=u("div","ra-tw");t.replaceWith(s),s.append(t)}}function _n(r,e={}){let n=e.options??[],t=e.value??n[0]?.value??"",s=!1,i=u("button","ra-sel");i.type="button",i.setAttribute("aria-haspopup","listbox");let a=u("span","ra-sell"),l=u("span","ra-selc");l.innerHTML=z.chevDown(14),i.append(a,l);let d=null,h=0,f="",w=()=>{let S=n.find(q=>q.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,x=(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))&&x(!1)},C=S=>{let q=S!==t;t=S,w(),x(),q&&i.dispatchEvent(new Event("change",{bubbles:!0}))},D=S=>{S.replaceChildren();let q=k();h>=q.length&&(h=Math.max(0,q.length-1)),q.forEach((R,V)=>{let ie=u("div","ra-selo"+(V===h?" act":"")+(R.value===t?" cur":""));ie.setAttribute("role","option"),ie.setAttribute("aria-selected",String(R.value===t));let I=u("span","ra-selt");I.innerHTML=R.value===t?z.tick(13):"",ie.append(I,u("span","ra-selol",R.label)),R.note&&ie.append(u("span","ra-selon",R.note)),ie.addEventListener("pointermove",()=>{h!==V&&(h=V,S.querySelectorAll(".ra-selo").forEach((ae,le)=>ae.classList.toggle("act",le===V)))}),ie.addEventListener("click",()=>C(R.value)),S.append(ie)}),q.length||S.append(u("div","ra-selnone","\u2014")),S.querySelector(".act")?.scrollIntoView?.({block:"nearest"})},O=()=>{if(d||s)return;d=u("div","ra-selp"),d.setAttribute("role","listbox");let S=u("div","ra-sellist"),q=null;n.length>=(e.filterAt??10)&&(q=u("input","ra-self"),q.type="text",q.placeholder=e.filterLabel??"Filter\u2026",q.addEventListener("input",()=>{f=q.value,h=0,D(S)}),q.addEventListener("keydown",M),d.append(q)),d.append(S),h=Math.max(0,n.findIndex(Ee=>Ee.value===t)),D(S),r.append(d);let R=r.getBoundingClientRect(),V=i.getBoundingClientRect(),ie=R.bottom-V.bottom-8,I=V.top-R.top-8,ae=Math.min(d.scrollHeight,320),le=ie<ae&&I>ie;d.style.left=`${V.left-R.left+r.scrollLeft}px`,d.style.width=`${V.width}px`,d.style.maxHeight=`${Math.max(120,Math.min(320,le?I:ie))}px`,d.style.top=le?`${V.top-R.top+r.scrollTop-d.offsetHeight-4}px`:`${V.bottom-R.top+r.scrollTop+4}px`,i.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",T,!0),(q??i).focus()},M=S=>{if(!d){(S.key==="ArrowDown"||S.key==="ArrowUp"||S.key==="Enter"||S.key===" ")&&(S.preventDefault(),O());return}let q=k(),R=d.querySelector(".ra-sellist");if(S.key==="ArrowDown")S.preventDefault(),h=Math.min(q.length-1,h+1),D(R);else if(S.key==="ArrowUp")S.preventDefault(),h=Math.max(0,h-1),D(R);else if(S.key==="Enter"){S.preventDefault();let V=q[h];V&&C(V.value)}else S.key==="Escape"?(S.preventDefault(),S.stopPropagation(),x()):S.key==="Tab"&&x(!1)};return i.addEventListener("click",()=>d?x():O()),i.addEventListener("keydown",M),w(),{el:i,get value(){return t},set value(S){t=S,w()},get disabled(){return s},set disabled(S){s=S,S&&x(!1),w()},get options(){return n},setOptions(S){n=S,n.some(q=>q.value===t)||(t=n[0]?.value??""),w()},close(){x(!1)}}}var Vl=`
|
|
289
289
|
: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}
|
|
290
290
|
:is(.ra-chat,.ra-ui) .ra-sel:hover:not(:disabled){border-color:color-mix(in srgb,var(--ra-fg) 25%,var(--ra-border))}
|
|
291
291
|
: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)}
|
|
@@ -305,10 +305,10 @@ Updated: ${JSON.stringify(Ti(d,n()))}`}}),Ne({name:"schedule_remove",description
|
|
|
305
305
|
:is(.ra-chat,.ra-ui) .ra-selo.cur .ra-selol{font-weight:500}
|
|
306
306
|
: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}
|
|
307
307
|
:is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
|
|
308
|
-
`;var xu=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,Mn=r=>r.slice(r.lastIndexOf("/")+1),Ci=r=>r.slice(0,r.lastIndexOf("/"))||"/";function vu(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(Ci(i));return a={name:Mn(i),path:i,folder:!0,children:[]},l.children.push(a),n.set(i,a),a};for(let i of r)t(Ci(i.path)).children.push({name:Mn(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 Ei(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 Ul(r){let{t:e,root:n,notify:t,editorHost:s}=r,i=null,a=!1,l=null,d=null,f=null,h=null,w="/",k=new Set(["/.agent"]),v=null,T=0,C=null,O=2*1024*1024,I=null,$=()=>{I||(I=setTimeout(()=>{I=null,je()},150))},S=new Set,H=!1,_=u("div","ra-fp");_.setAttribute("role","complementary"),_.style.display="none";let W=u("div","ra-fph"),ae=u("span","ra-fpt",e.files),Z=(P,K,de)=>{let ne=u("button","ra-ib");return ne.type="button",ne.innerHTML=P,ne.title=K,ne.setAttribute("aria-label",K),ne.addEventListener("click",de),ne},ge=u("input");ge.type="file",ge.multiple=!0,ge.style.display="none";let we=Z(N.upload(),e.upload,()=>ss(ge,P=>{ot(P)})),$e=Z(N.download(),e.downloadZip,()=>{et("/")}),Ce=Z(N.filePlus(14),e.newFile,()=>{st()}),ce=Z(N.refresh(),e.refresh,()=>{je()}),be=Z(N.x(14),e.close,()=>{_n()});W.append(ae,u("span","ra-sp"),$e,we,Ce,ce,be);let De=u("div","ra-tree"),Ue=u("div","ra-ed");Ue.style.display="none";let Fe=u("div","ra-edh"),L=u("span","ra-edp"),U=u("span","ra-edro");U.innerHTML=N.lock(11)+`<span>${e.readOnly}</span>`,U.style.display="none";let B=u("div","ra-eda"),G=u("button","ra-btn xs solid");G.type="button",G.innerHTML=N.save()+e.save,G.style.display="none",G.addEventListener("click",()=>{Rt()});let j="__runapps_agent_files:wrap",te=(()=>{try{return localStorage.getItem(j)!=="0"}catch{return!0}})(),ue=!1,J=Z(N.wrap(),e.wrap,()=>{te=!te;try{localStorage.setItem(j,te?"1":"0")}catch{}Pe()}),le=Z(N.eye(),e.preview,()=>{ue=!ue,Ut()}),Re=u("div","ra-md ra-edmd");Re.style.display="none",Re.addEventListener("click",P=>{let K=P.target.closest("a[href]"),de=K?.getAttribute("href")??"";if(!K||!de.startsWith("/")||de.startsWith("//")||!i)return;P.preventDefault();let ne=i;ne.exists(de).then(he=>{he&&ne===i&&We(de)})});let Pe=()=>{Ee.classList.toggle("ra-wrap",te),J.classList.toggle("on",te)},oe=P=>!!P&&/\.(md|markdown|mdx)$/i.test(P),Ut=()=>{let P=f!==null;le.style.display=P&&oe(l)?"":"none",(!P||!oe(l))&&(ue=!1),le.innerHTML=ue?N.pen():N.eye(),le.title=ue?e.edit:e.preview,le.setAttribute("aria-label",le.title),le.classList.toggle("on",ue),ue&&pr(Re,d??Ee.value,!1),Re.style.display=ue?"":"none",Ee.style.display=P&&!ue?"":"none"},jt=Z(N.download(),e.download,()=>{l&&ft(l)}),yr=Z(N.trash(),e.delete,()=>{l&&Pn(l)}),wr=Z(N.x(14),e.close,()=>{br()});B.append(G,J,le,jt,yr,wr),Fe.append(L,U,B);let $n=u("div","ra-edb"),Ee=u("textarea","ra-edta");Ee.spellcheck=!1,Ee.setAttribute("aria-label",e.files);let Xe=u("div","ra-edpv");$n.append(Ee,Re,Xe),Pe(),Ue.append(Fe,$n);let nn=u("div","ra-fpdrop",e.upload);_.append(W,De,ge,nn),s.append(Ue);let ls=P=>{U.style.display=P?"":"none",yr.style.display=jt.style.display=P?"none":""},rt=P=>{d=P,G.style.display=P===null?"none":""};Ee.addEventListener("input",()=>rt(Ee.value===f?null:Ee.value)),Ee.addEventListener("keydown",P=>{if((P.metaKey||P.ctrlKey)&&P.key==="s"&&(P.preventDefault(),Rt()),P.key==="Tab"&&!P.shiftKey){P.preventDefault();let K=Ee.selectionStart;Ee.setRangeText(" ",K,Ee.selectionEnd,"end"),Ee.dispatchEvent(new Event("input"))}});let dt=async()=>d===null||wt(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),ut=(P,K)=>{if(!i)return!1;if(!K)return i.isReadOnly(P);let de=(C??[]).filter(ne=>ne.path.startsWith(P+"/"));return de.length>0&&de.every(ne=>i.isReadOnly(ne.path))},pt=()=>w!=="/"&&ut(w,!0)?"/":w,Ln=(P,K,de,ne=!1)=>{for(let he of P.children){let ve=u("div","ra-fr"+(he.path===l?" ra-cur":""));ve.style.paddingLeft=`${K*14+6}px`,ve.dataset.path=he.path;let it=he.folder&&!k.has(he.path),bt=u("span","ra-frc");bt.innerHTML=he.folder?it?N.chevDown():N.chev(12):"";let Y=u("span","ra-fri");Y.innerHTML=he.folder?it?N.folderOpen():N.folder():N.file();let xt=u("span","ra-frn",he.name);if(xt.title=he.path,ve.append(bt,Y,xt),S.has(he.path)){let Ve=u("span","ra-dot");Ve.title=e.changedByAgent,ve.append(Ve)}let vr=ne||ut(he.path,he.folder);if(vr){if(ve.classList.add("ra-ro"),ve.title=`${he.path} \xB7 ${e.readOnly}`,!ne){let Ve=u("span","ra-frl");Ve.innerHTML=N.lock(),Ve.title=e.readOnly,ve.append(Ve)}}else{let Ve=u("span","ra-fra");Ve.append(he.folder?Z(N.download(13),e.downloadZip,()=>{et(he.path)}):Z(N.download(13),e.download,()=>{ft(he.path)})),Ve.append(Z(N.trash(12),e.delete,()=>{Pn(he.path)})),ve.append(Ve)}ve.addEventListener("click",Ve=>{Ve.target.closest(".ra-fra")||(he.folder?(w=he.path,k.delete(he.path)||k.add(he.path),_t()):(w=Ci(he.path),We(he.path)))}),de.append(ve),he.folder&&it&&Ln(he,K+1,de,vr)}},_t=()=>{if(!C)return;let P=document.createDocumentFragment();C.length?Ln(vu(C),0,P):P.append(u("div","ra-fpe",e.noFiles)),De.replaceChildren(P)},je=async()=>{if(!i||!a||H)return;let P=++T,K=i;try{let de=await K.list("/");if(P!==T||K!==i||H)return;C=de,_t()}catch(de){if(P!==T||H)return;De.replaceChildren(u("div","ra-fpe",de.message))}},rn=P=>{Ue.style.display=P?"":"none",n.classList.toggle("ra-editing",P)},We=async P=>{if(i&&!(P!==l&&!await dt())){l=P,S.delete(P),rt(null),L.textContent=P,h&&(URL.revokeObjectURL(h),h=null),Xe.replaceChildren(),rn(!0);try{let K=await i.read(P);if(l!==P)return;let de=xu.test(P)||/^image\//.test(K.contentType??""),ne=null;if(!de)if(typeof K.data=="string")ne=K.data;else try{ne=new TextDecoder("utf-8",{fatal:!0}).decode(K.data)}catch{ne=null}if(/\.pdf$/i.test(P)||K.contentType==="application/pdf"){f=null,Ee.style.display="none",Re.style.display="none",le.style.display="none",Xe.style.display="",h=URL.createObjectURL(new Blob([K.data],{type:"application/pdf"}));let ve=u("iframe","ra-edpdf");ve.src=h,ve.title=Mn(P),J.style.display="none",Xe.replaceChildren(ve),ls(i.isReadOnly(P)),_t();return}J.style.display="",ne!==null&&K.size>O&&(ne=null);let he=i.isReadOnly(P);if(ls(he),ne!==null)f=ne,Ee.value=ne,Xe.style.display="none",Ee.readOnly=he,Ee.title=he?e.readOnly:"",Ut();else{if(f=null,Ee.style.display="none",Re.style.display="none",le.style.display="none",Xe.style.display="",de){let ve=new Blob([K.data],{type:K.contentType||"image/*"});h=URL.createObjectURL(ve);let it=u("img");it.src=h,it.alt=Mn(P),Xe.append(it)}else Xe.append(u("div","ra-fpe",K.size>O&&!de?e.tooBig:e.noPreview));Xe.append(u("div","ra-fpe",`${K.size} B`))}}catch(K){f=null,Ee.style.display="none",Re.style.display="none",le.style.display="none",Xe.style.display="",Xe.replaceChildren(u("div","ra-fpe",K.message))}_t()}},br=async()=>l?await dt()?(l=null,f=null,rt(null),h&&(URL.revokeObjectURL(h),h=null),rn(!1),await je(),!0):!1:!0,Rt=async()=>{if(!i||!l||d===null)return;let P=l,K=d,de=i;try{let ne=await de.readText(P).catch(()=>null);if(ne!==null&&f!==null&&ne!==f&&!await wt(n,e.conflict,P,{ok:e.save,cancel:e.cancel,danger:!0})||(await de.write(P,K),l!==P||de!==i))return;f=K,rt(Ee.value===K?null:Ee.value),t(`${e.saved}: ${P}`),r.onChange?.()}catch(ne){t(ne.message,"error")}},ft=async P=>{if(i)try{let K=await i.read(P);os(Mn(P),K.data,K.contentType)}catch(K){t(K.message,"error")}},et=async P=>{if(i)try{let K=P==="/"?"/":P+"/",de=(await i.list(P)).filter(ve=>ve.path.startsWith(K));if(!de.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${de.length}\u2026`);let ne=[];for(let ve of de){let it=await i.read(ve.path);ne.push({path:ve.path.slice(K.length),data:it.data,mtime:ve.mtime})}let he=await js(ne);os(`${P==="/"?i.id||"directory":Mn(P)}.zip`,he,"application/zip")}catch(K){t(K.message,"error")}},Pn=async P=>{if(!i||!await wt(n,e.delete,e.confirmDeleteFile.replace("{path}",P),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let K=[];try{let de=await i.isFolder(P)?(await i.list(P)).map(ne=>ne.path).filter(ne=>ne!==P):[P];for(let ne of de){if(i.isReadOnly(ne)){K.push(ne);continue}try{await i.delete(ne)}catch{K.push(ne)}}}catch(de){t(de.message,"error")}l&&(l===P||l.startsWith(P+"/"))&&!await i.exists(l)&&(l=null,f=null,rt(null),rn(!1)),K.length&&t(`${e.readOnly}: ${K.slice(0,3).join(", ")}${K.length>3?` +${K.length-3}`:""}`,"warning"),r.onChange?.(),await je()},st=async()=>{if(!i)return;let P=pt(),K=P==="/"?"/":P+"/",de=await zl(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${K}untitled.md`});if(!de)return;let ne="/"+de.replace(/^\/+/,"");try{await i.exists(ne)||await i.write(ne,""),r.onChange?.(),await je(),await We(ne),Ee.focus()}catch(he){t(he.message,"error")}},ot=async P=>{if(!i||!P?.length)return;let K=null;for(let de of Array.from(P))try{let ne=await Ei(i,pt(),Mn(de.name.replace(/\\/g,"/"))||"file");await i.write(ne,new Uint8Array(await de.arrayBuffer()),de.type||void 0),K=ne}catch(ne){t(ne.message,"error")}r.onChange?.(),await je(),K&&P.length===1&&await We(K)};ge.addEventListener("change",()=>{let P=Array.from(ge.files??[]);ge.value="",ot(P)});let tt=0;_.addEventListener("dragenter",P=>{P.dataTransfer?.types.includes("Files")&&(P.preventDefault(),P.stopPropagation(),tt++,_.dataset.drop="1")}),_.addEventListener("dragover",P=>{_.dataset.drop&&(P.preventDefault(),P.stopPropagation(),P.dataTransfer.dropEffect="copy")}),_.addEventListener("dragleave",P=>{_.dataset.drop&&(P.stopPropagation(),--tt<=0&&(tt=0,delete _.dataset.drop))}),_.addEventListener("drop",P=>{_.dataset.drop&&(P.preventDefault(),P.stopPropagation(),tt=0,delete _.dataset.drop,ot(P.dataTransfer?.files))});let xr=async P=>{a=!0,_.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await je(),P&&await We(P)},_n=async()=>{await br()&&(a=!1,_.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:_,get visible(){return a},open:xr,close:_n,toggle:()=>a?_n():xr(),setWorkspace(P){if(P!==i){if(i&&l&&d!==null){let[K,de,ne]=[i,l,d];K.write(de,ne).then(()=>t(`${e.autoSaved}: ${de}`),he=>t(he.message,"error"))}v?.(),v=null,i=P,P&&(v=P.onChange(K=>{a&&($(),!(K.path!==l||d!==null)&&(K.kind==="write"?We(K.path):(l=null,f=null,rn(!1))))})),h&&(URL.revokeObjectURL(h),h=null),C=null,l=null,f=null,rt(null),rn(!1),S.clear(),w="/",P?je():(a=!1,_.style.display="none",n.classList.remove("ra-files-open"))}},refresh:je,changed(P){S.add(P),_t()},download:ft,downloadFolder:et,dispose(){H=!0,v?.(),I&&clearTimeout(I),h&&URL.revokeObjectURL(h),_.remove(),Ue.remove(),n.classList.remove("ra-editing")}}}var Mi={spans:400,requests:120,events:600},ku=new Set(["text_delta","reasoning_delta","tool_update"]);function is(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 Tu(r){try{return JSON.stringify(r,null,2)??"undefined"}catch{return String(r)}}var uo=(r,e)=>{r.length>e&&r.splice(0,r.length-e)};function jl(r){let{t:e,root:n}=r,t=new WeakMap,s=new Map,i=null,a=!1,l="calls",d="",f=null,h=u("div","ra-fp ra-dp");h.setAttribute("role","complementary"),h.style.display="none";let w=u("div","ra-fph"),k=u("div","ra-dtabs"),v=u("button","ra-ib");v.type="button",v.innerHTML=N.x(14),v.title=e.close,v.setAttribute("aria-label",e.close),v.addEventListener("click",()=>Fe()),w.append(k,u("span","ra-sp"),v);let T=u("div","ra-dbody");h.append(w,T);let C=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],O=()=>{let L=i?t.get(i):void 0,U={calls:L?.spans.length??0,requests:L?.requests.length??0};k.replaceChildren(...C.map(([B,G])=>{let j=u("button","ra-dtab"+(B===l?" on":""));return j.type="button",j.append(G),U[B]&&j.append(u("span","ra-dcount",String(U[B]))),j.addEventListener("click",()=>{l=B,ce()}),j}))},I=(L,U)=>{let B=u("details","ra-dfold"),G=u("summary"),j=u("span","ra-chev");j.innerHTML=N.chev(12),G.append(j,...L),B.append(G);let te=!1;return B.addEventListener("toggle",()=>{if(B.open&&!te){te=!0;let ue=u("div","ra-dfb");ue.append(...U()),B.append(ue)}}),B},$=(L,U="")=>{let B=u("pre","ra-dpre "+U);return B.textContent=typeof L=="string"?L:Tu(L),B},S=L=>u("div","ra-dlabel",L),H=L=>u("span","ra-dmuted",L),_=L=>u("span","ra-dmono",L),W=L=>u("div","ra-fpe",L),ae=L=>{let U=u("span","ra-dst "+(L==="running"?"run":L==="ok"?"ok":"fail"));return L==="running"?U.append(u("span","ra-spin")):U.innerHTML=L==="ok"?N.check(13):N.xcircle(13),U},Z=L=>{if(!L.spans.length)return[W(e.dNoCalls)];let U=[];for(let B of[...L.runs].reverse()){let G=L.spans.filter(J=>J.runId===B),j=L.requests.filter(J=>J.runId===B);if(!G.length&&!j.length)continue;let te=u("div","ra-drun");te.append(u("div","ra-drh",`${e.dRun} ${is(j[0]?.at??G[0]?.startedAt??Date.now())} \xB7 ${B.slice(-4)}`));let ue=[...new Set([...j.map(J=>J.turn),...G.map(J=>J.turn)])].sort((J,le)=>J-le);for(let J of ue){let le=j.find(Pe=>Pe.turn===J),Re=u("div","ra-dturn");Re.append(H(e.dTurn.replace("{n}",String(J)))),le&&Re.append(_(` \xB7 ${le.params.model||"default"}`),H(le.durationMs!==void 0?` \xB7 ${Math.round(le.durationMs)}ms`:" \xB7 \u2026"),le.error?u("span","ra-dst fail",` ${le.error}`):H(le.finishReason?` \xB7 ${le.finishReason}`:"")),te.append(Re);for(let Pe of G.filter(oe=>oe.turn===J))te.append(I([ae(Pe.status),_(Pe.name),H(Pe.durationMs!==void 0?`${Math.round(Pe.durationMs)}ms \xB7 ${is(Pe.startedAt)}`:is(Pe.startedAt))],()=>[u("div","ra-dmuted",Pe.id),S(e.args),$(Pe.args),...Pe.result!==void 0?[S(e.result),$(Pe.result)]:[]]))}U.push(te)}return U},ge=L=>L.requests.length?[...L.requests].reverse().map(U=>{let B=U.params,G=U.usage,j=u("span","ra-dbadge "+(U.error?"fail":U.durationMs===void 0?"":"ok"),U.error?"error":U.durationMs===void 0?"\u2026":U.finishReason??"ok");return I([j,_(B.model||"default"),H(`${B.messages?.length??0} msgs \xB7 ${B.tools?.length??0} tools${G?` \xB7 ${G.prompt_tokens??0}\u2192${G.completion_tokens??0} tok`:""}${G?.total_cost?` \xB7 $${G.total_cost.toFixed(4)}`:""}`),H(` ${U.durationMs!==void 0?`${Math.round(U.durationMs)}ms \xB7 `:""}${is(U.at)}`)],()=>[S(e.dPayload),$(U.params,"tall"),...U.message!==void 0||U.error?[S(e.dResponse),$(U.error??U.message)]:[],...G?[$(G)]:[]])}):[W(e.dNoRequests)],we=L=>{let U=u("div","ra-dbar"),B=u("input","ra-field");B.type="text",B.placeholder=e.dFilter,B.value=d,B.addEventListener("input",()=>{d=B.value,be()});let G=u("button","ra-ib");G.type="button",G.innerHTML=N.trash(13),G.title=e.dClear,G.setAttribute("aria-label",e.dClear),G.addEventListener("click",()=>{L.events.length=0,L.spans.length=0,L.requests.length=0,L.runs.length=0,ce()}),U.append(B,G);let j=L.events.filter(te=>!d||te.name.includes(d)||te.detail.includes(d));return j.length?[U,...[...j].reverse().slice(0,300).map(te=>I([H(is(te.at)),_(te.name),H(te.detail)],()=>[$(te.data)]))]:[U,W(e.dNoEvents)]},$e=L=>{let U=u("div","ra-dctx"),B=u("div","ra-dkv"),G=(le,Re)=>{B.append(u("span","ra-dmuted",le),u("span","ra-dmono",Re))},j=L.usage,te=L.messages;G("session",L.id),G("directory",L.workspace?.id??"\u2014"),G("model",L.settings.model??"(default)"),G("messages",`${te.filter(le=>le.role==="user").length} user \xB7 ${te.filter(le=>le.role==="assistant").length} assistant \xB7 ${te.filter(le=>le.role==="tool").length} tool`),G("usage",`${j.prompt_tokens} in \xB7 ${j.completion_tokens} out \xB7 ${j.calls} calls \xB7 $${j.total_cost.toFixed(4)}`);let ue=u("span","ra-dmono","\u2026");B.append(u("span","ra-dmuted","context"),ue),L.context().then(le=>{ue.textContent=`${le.used} / ${le.window} (${(le.used/le.window*100).toFixed(2)}%)`}).catch(()=>{ue.textContent="\u2014"});let J=$("\u2026","tall");return L.systemPrompt().then(le=>{J.textContent=le}).catch(le=>{J.textContent=String(le)}),U.append(B,S(e.dSystem),J,S(`${e.dMessages} (${te.length})`),$(te,"tall")),[U]},Ce=L=>L.tools.map(U=>I([_(U.name),H(U.destructive?" destructive":"")],()=>[u("div","ra-ddesc",U.description??""),$(U.parameters)]));function ce(){if(f=null,!a)return;if(O(),!i){T.replaceChildren();return}let L=t.get(i),U=T.scrollTop,B=document.activeElement?.classList.contains("ra-field")&&T.contains(document.activeElement),G=l==="calls"?Z(L):l==="requests"?ge(L):l==="events"?we(L):l==="context"?$e(i):Ce(i);if(T.replaceChildren(...G),T.scrollTop=U,B){let j=T.querySelector(".ra-field");j?.focus(),j?.setSelectionRange(j.value.length,j.value.length)}}let be=()=>{if(!(!a||f)){if(l==="context"||l==="tools"||T.querySelector("details[open]")){O();return}f=setTimeout(ce,300)}},De=L=>{if(t.has(L))return;let U={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set(L,U),s.set(L,L.on("*",(B,G)=>{let j=G??{},te=String(j.runId??"");if(B==="run_start"&&(U.runs.push(te),uo(U.runs,60)),B==="turn_start"&&U.turn.set(te,Number(j.turn)||1),B==="request"&&(U.requests.push({runId:te,turn:Number(j.turn),at:Date.now(),params:j.params}),uo(U.requests,Mi.requests)),B==="response"){let ue=[...U.requests].reverse().find(J=>J.runId===te&&J.turn===Number(j.turn)&&J.durationMs===void 0);ue&&Object.assign(ue,{durationMs:j.durationMs,finishReason:j.finishReason,usage:j.usage,message:j.message,error:j.error})}if(B==="tool_start"&&(U.spans.push({id:String(j.id),name:String(j.name),args:j.args,status:"running",startedAt:Date.now(),runId:te,turn:U.turn.get(te)??1}),uo(U.spans,Mi.spans)),B==="tool_end"){let ue=[...U.spans].reverse().find(J=>J.id===String(j.id));ue&&Object.assign(ue,{status:String(j.status),result:j.result,durationMs:j.durationMs})}if(!ku.has(B)){let ue=B==="tool_start"||B==="tool_end"?String(j.name??""):B==="run_end"?String(j.reason??""):B==="response"?String(j.error??j.finishReason??""):"";U.events.push({at:Date.now(),name:B,detail:ue,data:B==="request"?{runId:te,turn:j.turn,model:j.params?.model}:G}),uo(U.events,Mi.events)}L===i&&be()}))},Ue=()=>{a=!0,h.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),ce()};function Fe(){a&&(a=!1,h.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:h,get visible(){return a},open:Ue,close:Fe,toggle:()=>a?Fe():Ue(),setAgent(L){De(L),i=L,a&&ce()},forget(L){s.get(L)?.(),s.delete(L),t.delete(L),i===L&&(i=null)},dispose(){for(let L of s.values())L();s.clear(),f&&clearTimeout(f),h.remove()}}}var ql=["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"],Bl=["font","mono"],Su='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',Cu='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',po={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)"}}},fr=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function Wl(){let r=po.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${Su};--ra-mono:${Cu};${fr(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]){${fr(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${fr(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(po))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${fr(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${fr(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${fr(t.dark)}}}`));return e.join(`
|
|
309
|
-
`)}var
|
|
310
|
-
(Running unattended: the user may not be watching.)`,schedStarted:'Scheduled task "{name}" started',schedFailed:'Scheduled task "{name}" failed: {error}',schedNamePh:"e.g. Morning news digest",schedPromptPh:"What the AI should do each time. Write it to stand alone: the run does not see this conversation.",schedDayNames:"Sun,Mon,Tue,Wed,Thu,Fri,Sat",tSchedList:"Scheduled tasks",tSchedAdd:'Schedule "{name}"',tSchedUpdate:"Change scheduled task",tSchedRemove:"Remove scheduled task",permAutoNote:"Auto-run is on: the AI will no longer ask before deleting, overwriting or publishing. Turn it off in Settings \u2192 Tool permissions.",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",permAlways:"\u4EE5\u540E\u90FD\u5141\u8BB8\uFF08\u672C\u5E94\u7528\uFF09",sched:"\u5B9A\u65F6\u4EFB\u52A1",schedNew:"\u65B0\u5EFA",schedNone:"\u8FD8\u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\u53EF\u4EE5\u76F4\u63A5\u8BA9 AI \u5B89\u6392\uFF08\u6BD4\u5982\u300C\u6BCF\u4E2A\u5DE5\u4F5C\u65E5\u65E9\u4E0A 9 \u70B9\u6574\u7406\u65B0\u95FB\u300D\uFF09\uFF0C\u6216\u70B9\u65B0\u5EFA\u3002",schedHint:"\u5B9A\u65F6\u4EFB\u52A1\u53EA\u5728\u672C\u5E94\u7528\u9875\u9762\u6253\u5F00\u65F6\u8FD0\u884C\uFF0C\u5E76\u7B49\u5BF9\u8BDD\u7A7A\u95F2\u65F6\u624D\u5F00\u59CB\uFF1B\u9875\u9762\u5173\u95ED\u671F\u95F4\u9519\u8FC7\u7684\uFF0C\u4E0B\u6B21\u6253\u5F00\u65F6\u8865\u8DD1\u4E00\u6B21\u3002",schedName:"\u540D\u79F0",schedPrompt:"\u8981\u505A\u4EC0\u4E48",schedWhen:"\u65F6\u95F4",schedOnce:"\u4E00\u6B21",schedEvery:"\u6BCF\u9694",schedDaily:"\u6BCF\u5929 / \u6BCF\u5468",schedCron:"Cron",schedMin:"\u5206\u949F",schedHour:"\u5C0F\u65F6",schedDay:"\u5929",schedCronHint:"\u5206 \u65F6 \u65E5 \u6708 \u5468\uFF0C\u5982 0 9 * * 1-5",schedNext:"\u4E0B\u6B21 {time}",schedNoNext:"\u4E0D\u4F1A\u518D\u8FD0\u884C",schedPaused:"\u5DF2\u6682\u505C",schedRunning:"\u8FD0\u884C\u4E2D",schedLast:"\u4E0A\u6B21 {time} \xB7 {status}",schedOk:"\u5B8C\u6210",schedErr:"\u5931\u8D25",schedStopped:"\u5DF2\u505C\u6B62",schedRunNow:"\u7ACB\u5373\u8FD0\u884C",schedPause:"\u6682\u505C",schedResume:"\u6062\u590D",schedEdit:"\u7F16\u8F91",schedOpen:"\u6253\u5F00\u5B83\u7684\u5BF9\u8BDD",schedDel:"\u5220\u9664\u4EFB\u52A1",schedDelMsg:"\u5220\u9664\u300C{name}\u300D\uFF1F\u5B83\u7684\u5BF9\u8BDD\u4F1A\u4FDD\u7559\u3002",schedSave:"\u4FDD\u5B58",schedBusy:"\u53E6\u4E00\u4E2A\u5B9A\u65F6\u4EFB\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u7ED3\u675F\u540E\u518D\u8BD5\u3002",schedByAI:"AI \u521B\u5EFA",schedRunHead:`\u23F0 \u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D \xB7 {time}
|
|
311
|
-
\uFF08\u65E0\u4EBA\u503C\u5B88\u8FD0\u884C\uFF1A\u7528\u6237\u53EF\u80FD\u4E0D\u5728\u65C1\u8FB9\u3002\uFF09`,schedStarted:"\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5F00\u59CB\u8FD0\u884C",schedFailed:"\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5931\u8D25\uFF1A{error}",schedNamePh:"\u5982\uFF1A\u65E9\u95F4\u65B0\u95FB\u6458\u8981",schedPromptPh:"\u6BCF\u6B21\u8FD0\u884C\u65F6 AI \u8981\u505A\u7684\u4E8B\u3002\u5199\u5B8C\u6574\uFF1A\u8FD0\u884C\u65F6\u770B\u4E0D\u5230\u8FD9\u6BB5\u5BF9\u8BDD\u3002",schedDayNames:"\u65E5,\u4E00,\u4E8C,\u4E09,\u56DB,\u4E94,\u516D",tSchedList:"\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1",tSchedAdd:"\u5B89\u6392\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D",tSchedUpdate:"\u4FEE\u6539\u5B9A\u65F6\u4EFB\u52A1",tSchedRemove:"\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1",permAutoNote:"\u5DF2\u5F00\u542F\u81EA\u52A8\u6267\u884C\uFF1A\u5220\u9664\u3001\u8986\u76D6\u3001\u53D1\u5E03\u7B49\u64CD\u4F5C\u4E5F\u4E0D\u518D\u8BE2\u95EE\u3002\u53EF\u5728\u8BBE\u7F6E \u2192 \u5DE5\u5177\u6743\u9650\u91CC\u5173\u95ED\u3002",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 Mu(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 Vl="runapps-agent-chat-style",Au=Wl()+`
|
|
308
|
+
`;var Au=/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,Rn=r=>r.slice(r.lastIndexOf("/")+1),$i=r=>r.slice(0,r.lastIndexOf("/"))||"/";function $u(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($i(i));return a={name:Rn(i),path:i,folder:!0,children:[]},l.children.push(a),n.set(i,a),a};for(let i of r)t($i(i.path)).children.push({name:Rn(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 Li(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 Zl(r){let{t:e,root:n,notify:t,editorHost:s}=r,i=null,a=!1,l=null,d=null,h=null,f=null,w="/",k=new Set(["/.agent"]),x=null,T=0,C=null,D=2*1024*1024,O=null,M=()=>{O||(O=setTimeout(()=>{O=null,tt()},150))},S=new Set,q=!1,R=u("div","ra-fp");R.setAttribute("role","complementary"),R.style.display="none";let V=u("div","ra-fph"),ie=u("span","ra-fpt",e.files),I=(L,K,se)=>{let Z=u("button","ra-ib");return Z.type="button",Z.innerHTML=L,Z.title=K,Z.setAttribute("aria-label",K),Z.addEventListener("click",se),Z},ae=u("input");ae.type="file",ae.multiple=!0,ae.style.display="none";let le=I(z.upload(),e.upload,()=>ls(ae,L=>{Qe(L)})),Ee=I(z.download(),e.downloadZip,()=>{sn("/")}),Me=I(z.filePlus(14),e.newFile,()=>{Co()}),ue=I(z.refresh(),e.refresh,()=>{tt()}),be=I(z.x(14),e.close,()=>{ut()});V.append(ie,u("span","ra-sp"),Ee,le,Me,ue,be);let De=u("div","ra-tree"),He=u("div","ra-ed");He.style.display="none";let Fe=u("div","ra-edh"),P=u("span","ra-edp"),U=u("span","ra-edro");U.innerHTML=z.lock(11)+`<span>${e.readOnly}</span>`,U.style.display="none";let W=u("div","ra-eda"),J=u("button","ra-btn xs solid");J.type="button",J.innerHTML=z.save()+e.save,J.style.display="none",J.addEventListener("click",()=>{ct()});let j="__runapps_agent_files:wrap",ee=(()=>{try{return localStorage.getItem(j)!=="0"}catch{return!0}})(),fe=!1,ve=I(z.wrap(),e.wrap,()=>{ee=!ee;try{localStorage.setItem(j,ee?"1":"0")}catch{}Ue()}),pe=I(z.eye(),e.preview,()=>{fe=!fe,vr()}),We=u("div","ra-md ra-edmd");We.style.display="none",We.addEventListener("click",L=>{let K=L.target.closest("a[href]"),se=K?.getAttribute("href")??"";if(!K||!se.startsWith("/")||se.startsWith("//")||!i)return;L.preventDefault();let Z=i;Z.exists(se).then(de=>{de&&Z===i&&Ve(se)})});let Ue=()=>{ke.classList.toggle("ra-wrap",ee),ve.classList.toggle("on",ee)},en=L=>!!L&&/\.(md|markdown|mdx)$/i.test(L),vr=()=>{let L=h!==null;pe.style.display=L&&en(l)?"":"none",(!L||!en(l))&&(fe=!1),pe.innerHTML=fe?z.pen():z.eye(),pe.title=fe?e.edit:e.preview,pe.setAttribute("aria-label",pe.title),pe.classList.toggle("on",fe),fe&&gr(We,d??ke.value,!1),We.style.display=fe?"":"none",ke.style.display=L&&!fe?"":"none"},Te=I(z.download(),e.download,()=>{l&&rn(l)}),tn=I(z.trash(),e.delete,()=>{l&&dt(l)}),On=I(z.x(14),e.close,()=>{lt()});W.append(J,ve,pe,Te,tn,On),Fe.append(P,U,W);let wt=u("div","ra-edb"),ke=u("textarea","ra-edta");ke.spellcheck=!1,ke.setAttribute("aria-label",e.files);let ne=u("div","ra-edpv");wt.append(ke,We,ne),Ue(),He.append(Fe,wt);let nn=u("div","ra-fpdrop",e.upload);R.append(V,De,ae,nn),s.append(He);let Ft=L=>{U.style.display=L?"":"none",tn.style.display=Te.style.display=L?"none":""},Lt=L=>{d=L,J.style.display=L===null?"none":""};ke.addEventListener("input",()=>Lt(ke.value===h?null:ke.value)),ke.addEventListener("keydown",L=>{if((L.metaKey||L.ctrlKey)&&L.key==="s"&&(L.preventDefault(),ct()),L.key==="Tab"&&!L.shiftKey){L.preventDefault();let K=ke.selectionStart;ke.setRangeText(" ",K,ke.selectionEnd,"end"),ke.dispatchEvent(new Event("input"))}});let Nn=async()=>d===null||yt(n,e.discard,"",{ok:e.ok,cancel:e.cancel,danger:!0}),zn=(L,K)=>{if(!i)return!1;if(!K)return i.isReadOnly(L);let se=(C??[]).filter(Z=>Z.path.startsWith(L+"/"));return se.length>0&&se.every(Z=>i.isReadOnly(Z.path))},Fn=()=>w!=="/"&&zn(w,!0)?"/":w,kr=(L,K,se,Z=!1)=>{for(let de of L.children){let Pe=u("div","ra-fr"+(de.path===l?" ra-cur":""));Pe.style.paddingLeft=`${K*14+6}px`,Pe.dataset.path=de.path;let nt=de.folder&&!k.has(de.path),In=u("span","ra-frc");In.innerHTML=de.folder?nt?z.chevDown():z.chev(12):"";let Tr=u("span","ra-fri");Tr.innerHTML=de.folder?nt?z.folderOpen():z.folder():z.file();let Sr=u("span","ra-frn",de.name);if(Sr.title=de.path,Pe.append(In,Tr,Sr),S.has(de.path)){let je=u("span","ra-dot");je.title=e.changedByAgent,Pe.append(je)}let Cr=Z||zn(de.path,de.folder);if(Cr){if(Pe.classList.add("ra-ro"),Pe.title=`${de.path} \xB7 ${e.readOnly}`,!Z){let je=u("span","ra-frl");je.innerHTML=z.lock(),je.title=e.readOnly,Pe.append(je)}}else{let je=u("span","ra-fra");je.append(de.folder?I(z.download(13),e.downloadZip,()=>{sn(de.path)}):I(z.download(13),e.download,()=>{rn(de.path)})),je.append(I(z.trash(12),e.delete,()=>{dt(de.path)})),Pe.append(je)}Pe.addEventListener("click",je=>{je.target.closest(".ra-fra")||(de.folder?(w=de.path,k.delete(de.path)||k.add(de.path),it()):(w=$i(de.path),Ve(de.path)))}),se.append(Pe),de.folder&&nt&&kr(de,K+1,se,Cr)}},it=()=>{if(!C)return;let L=document.createDocumentFragment();C.length?kr($u(C),0,L):L.append(u("div","ra-fpe",e.noFiles)),De.replaceChildren(L)},tt=async()=>{if(!i||!a||q)return;let L=++T,K=i;try{let se=await K.list("/");if(L!==T||K!==i||q)return;C=se,it()}catch(se){if(L!==T||q)return;De.replaceChildren(u("div","ra-fpe",se.message))}},at=L=>{He.style.display=L?"":"none",n.classList.toggle("ra-editing",L)},Ve=async L=>{if(i&&!(L!==l&&!await Nn())){l=L,S.delete(L),Lt(null),P.textContent=L,f&&(URL.revokeObjectURL(f),f=null),ne.replaceChildren(),at(!0);try{let K=await i.read(L);if(l!==L)return;let se=Au.test(L)||/^image\//.test(K.contentType??""),Z=null;if(!se)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"){h=null,ke.style.display="none",We.style.display="none",pe.style.display="none",ne.style.display="",f=URL.createObjectURL(new Blob([K.data],{type:"application/pdf"}));let Pe=u("iframe","ra-edpdf");Pe.src=f,Pe.title=Rn(L),ve.style.display="none",ne.replaceChildren(Pe),Ft(i.isReadOnly(L)),it();return}ve.style.display="",Z!==null&&K.size>D&&(Z=null);let de=i.isReadOnly(L);if(Ft(de),Z!==null)h=Z,ke.value=Z,ne.style.display="none",ke.readOnly=de,ke.title=de?e.readOnly:"",vr();else{if(h=null,ke.style.display="none",We.style.display="none",pe.style.display="none",ne.style.display="",se){let Pe=new Blob([K.data],{type:K.contentType||"image/*"});f=URL.createObjectURL(Pe);let nt=u("img");nt.src=f,nt.alt=Rn(L),ne.append(nt)}else ne.append(u("div","ra-fpe",K.size>D&&!se?e.tooBig:e.noPreview));ne.append(u("div","ra-fpe",`${K.size} B`))}}catch(K){h=null,ke.style.display="none",We.style.display="none",pe.style.display="none",ne.style.display="",ne.replaceChildren(u("div","ra-fpe",K.message))}it()}},lt=async()=>l?await Nn()?(l=null,h=null,Lt(null),f&&(URL.revokeObjectURL(f),f=null),at(!1),await tt(),!0):!1:!0,ct=async()=>{if(!i||!l||d===null)return;let L=l,K=d,se=i;try{let Z=await se.readText(L).catch(()=>null);if(Z!==null&&h!==null&&Z!==h&&!await yt(n,e.conflict,L,{ok:e.save,cancel:e.cancel,danger:!0})||(await se.write(L,K),l!==L||se!==i))return;h=K,Lt(ke.value===K?null:ke.value),t(`${e.saved}: ${L}`),r.onChange?.()}catch(Z){t(Z.message,"error")}},rn=async L=>{if(i)try{let K=await i.read(L);cs(Rn(L),K.data,K.contentType)}catch(K){t(K.message,"error")}},sn=async L=>{if(i)try{let K=L==="/"?"/":L+"/",se=(await i.list(L)).filter(Pe=>Pe.path.startsWith(K));if(!se.length){t(e.noFiles,"warning");return}t(`${e.zipping} ${se.length}\u2026`);let Z=[];for(let Pe of se){let nt=await i.read(Pe.path);Z.push({path:Pe.path.slice(K.length),data:nt.data,mtime:Pe.mtime})}let de=await Vs(Z);cs(`${L==="/"?i.id||"directory":Rn(L)}.zip`,de,"application/zip")}catch(K){t(K.message,"error")}},dt=async L=>{if(!i||!await yt(n,e.delete,e.confirmDeleteFile.replace("{path}",L),{ok:e.delete,cancel:e.cancel,danger:!0}))return;let K=[];try{let se=await i.isFolder(L)?(await i.list(L)).map(Z=>Z.path).filter(Z=>Z!==L):[L];for(let Z of se){if(i.isReadOnly(Z)){K.push(Z);continue}try{await i.delete(Z)}catch{K.push(Z)}}}catch(se){t(se.message,"error")}l&&(l===L||l.startsWith(L+"/"))&&!await i.exists(l)&&(l=null,h=null,Lt(null),at(!1)),K.length&&t(`${e.readOnly}: ${K.slice(0,3).join(", ")}${K.length>3?` +${K.length-3}`:""}`,"warning"),r.onChange?.(),await tt()},Co=async()=>{if(!i)return;let L=Fn(),K=L==="/"?"/":L+"/",se=await Bl(n,e.newFilePath,{ok:e.ok,cancel:e.cancel,initial:`${K}untitled.md`});if(!se)return;let Z="/"+se.replace(/^\/+/,"");try{await i.exists(Z)||await i.write(Z,""),r.onChange?.(),await tt(),await Ve(Z),ke.focus()}catch(de){t(de.message,"error")}},Qe=async L=>{if(!i||!L?.length)return;let K=null;for(let se of Array.from(L))try{let Z=await Li(i,Fn(),Rn(se.name.replace(/\\/g,"/"))||"file");await i.write(Z,new Uint8Array(await se.arrayBuffer()),se.type||void 0),K=Z}catch(Z){t(Z.message,"error")}r.onChange?.(),await tt(),K&&L.length===1&&await Ve(K)};ae.addEventListener("change",()=>{let L=Array.from(ae.files??[]);ae.value="",Qe(L)});let on=0;R.addEventListener("dragenter",L=>{L.dataTransfer?.types.includes("Files")&&(L.preventDefault(),L.stopPropagation(),on++,R.dataset.drop="1")}),R.addEventListener("dragover",L=>{R.dataset.drop&&(L.preventDefault(),L.stopPropagation(),L.dataTransfer.dropEffect="copy")}),R.addEventListener("dragleave",L=>{R.dataset.drop&&(L.stopPropagation(),--on<=0&&(on=0,delete R.dataset.drop))}),R.addEventListener("drop",L=>{R.dataset.drop&&(L.preventDefault(),L.stopPropagation(),on=0,delete R.dataset.drop,Qe(L.dataTransfer?.files))});let Pt=async L=>{a=!0,R.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),await tt(),L&&await Ve(L)},ut=async()=>{await lt()&&(a=!1,R.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))};return{el:R,get visible(){return a},open:Pt,close:ut,toggle:()=>a?ut():Pt(),setWorkspace(L){if(L!==i){if(i&&l&&d!==null){let[K,se,Z]=[i,l,d];K.write(se,Z).then(()=>t(`${e.autoSaved}: ${se}`),de=>t(de.message,"error"))}x?.(),x=null,i=L,L&&(x=L.onChange(K=>{a&&(M(),!(K.path!==l||d!==null)&&(K.kind==="write"?Ve(K.path):(l=null,h=null,at(!1))))})),f&&(URL.revokeObjectURL(f),f=null),C=null,l=null,h=null,Lt(null),at(!1),S.clear(),w="/",L?tt():(a=!1,R.style.display="none",n.classList.remove("ra-files-open"))}},refresh:tt,changed(L){S.add(L),it()},download:rn,downloadFolder:sn,dispose(){q=!0,x?.(),O&&clearTimeout(O),f&&URL.revokeObjectURL(f),R.remove(),He.remove(),n.classList.remove("ra-editing")}}}var Pi={spans:400,requests:120,events:600},Lu=new Set(["text_delta","reasoning_delta","tool_update"]);function ds(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 Pu(r){try{return JSON.stringify(r,null,2)??"undefined"}catch{return String(r)}}var wo=(r,e)=>{r.length>e&&r.splice(0,r.length-e)};function Gl(r){let{t:e,root:n}=r,t=new WeakMap,s=new Map,i=null,a=!1,l="calls",d="",h=null,f=u("div","ra-fp ra-dp");f.setAttribute("role","complementary"),f.style.display="none";let w=u("div","ra-fph"),k=u("div","ra-dtabs"),x=u("button","ra-ib");x.type="button",x.innerHTML=z.x(14),x.title=e.close,x.setAttribute("aria-label",e.close),x.addEventListener("click",()=>Fe()),w.append(k,u("span","ra-sp"),x);let T=u("div","ra-dbody");f.append(w,T);let C=[["calls",e.dCalls],["requests",e.dRequests],["events",e.dEvents],["context",e.dContext],["tools",e.dTools]],D=()=>{let P=i?t.get(i):void 0,U={calls:P?.spans.length??0,requests:P?.requests.length??0};k.replaceChildren(...C.map(([W,J])=>{let j=u("button","ra-dtab"+(W===l?" on":""));return j.type="button",j.append(J),U[W]&&j.append(u("span","ra-dcount",String(U[W]))),j.addEventListener("click",()=>{l=W,ue()}),j}))},O=(P,U)=>{let W=u("details","ra-dfold"),J=u("summary"),j=u("span","ra-chev");j.innerHTML=z.chev(12),J.append(j,...P),W.append(J);let ee=!1;return W.addEventListener("toggle",()=>{if(W.open&&!ee){ee=!0;let fe=u("div","ra-dfb");fe.append(...U()),W.append(fe)}}),W},M=(P,U="")=>{let W=u("pre","ra-dpre "+U);return W.textContent=typeof P=="string"?P:Pu(P),W},S=P=>u("div","ra-dlabel",P),q=P=>u("span","ra-dmuted",P),R=P=>u("span","ra-dmono",P),V=P=>u("div","ra-fpe",P),ie=P=>{let U=u("span","ra-dst "+(P==="running"?"run":P==="ok"?"ok":"fail"));return P==="running"?U.append(u("span","ra-spin")):U.innerHTML=P==="ok"?z.check(13):z.xcircle(13),U},I=P=>{if(!P.spans.length)return[V(e.dNoCalls)];let U=[];for(let W of[...P.runs].reverse()){let J=P.spans.filter(ve=>ve.runId===W),j=P.requests.filter(ve=>ve.runId===W);if(!J.length&&!j.length)continue;let ee=u("div","ra-drun");ee.append(u("div","ra-drh",`${e.dRun} ${ds(j[0]?.at??J[0]?.startedAt??Date.now())} \xB7 ${W.slice(-4)}`));let fe=[...new Set([...j.map(ve=>ve.turn),...J.map(ve=>ve.turn)])].sort((ve,pe)=>ve-pe);for(let ve of fe){let pe=j.find(Ue=>Ue.turn===ve),We=u("div","ra-dturn");We.append(q(e.dTurn.replace("{n}",String(ve)))),pe&&We.append(R(` \xB7 ${pe.params.model||"default"}`),q(pe.durationMs!==void 0?` \xB7 ${Math.round(pe.durationMs)}ms`:" \xB7 \u2026"),pe.error?u("span","ra-dst fail",` ${pe.error}`):q(pe.finishReason?` \xB7 ${pe.finishReason}`:"")),ee.append(We);for(let Ue of J.filter(en=>en.turn===ve))ee.append(O([ie(Ue.status),R(Ue.name),q(Ue.durationMs!==void 0?`${Math.round(Ue.durationMs)}ms \xB7 ${ds(Ue.startedAt)}`:ds(Ue.startedAt))],()=>[u("div","ra-dmuted",Ue.id),S(e.args),M(Ue.args),...Ue.result!==void 0?[S(e.result),M(Ue.result)]:[]]))}U.push(ee)}return U},ae=P=>P.requests.length?[...P.requests].reverse().map(U=>{let W=U.params,J=U.usage,j=u("span","ra-dbadge "+(U.error?"fail":U.durationMs===void 0?"":"ok"),U.error?"error":U.durationMs===void 0?"\u2026":U.finishReason??"ok");return O([j,R(W.model||"default"),q(`${W.messages?.length??0} msgs \xB7 ${W.tools?.length??0} tools${J?` \xB7 ${J.prompt_tokens??0}\u2192${J.completion_tokens??0} tok`:""}${J?.total_cost?` \xB7 $${J.total_cost.toFixed(4)}`:""}`),q(` ${U.durationMs!==void 0?`${Math.round(U.durationMs)}ms \xB7 `:""}${ds(U.at)}`)],()=>[S(e.dPayload),M(U.params,"tall"),...U.message!==void 0||U.error?[S(e.dResponse),M(U.error??U.message)]:[],...J?[M(J)]:[]])}):[V(e.dNoRequests)],le=P=>{let U=u("div","ra-dbar"),W=u("input","ra-field");W.type="text",W.placeholder=e.dFilter,W.value=d,W.addEventListener("input",()=>{d=W.value,be()});let J=u("button","ra-ib");J.type="button",J.innerHTML=z.trash(13),J.title=e.dClear,J.setAttribute("aria-label",e.dClear),J.addEventListener("click",()=>{P.events.length=0,P.spans.length=0,P.requests.length=0,P.runs.length=0,ue()}),U.append(W,J);let j=P.events.filter(ee=>!d||ee.name.includes(d)||ee.detail.includes(d));return j.length?[U,...[...j].reverse().slice(0,300).map(ee=>O([q(ds(ee.at)),R(ee.name),q(ee.detail)],()=>[M(ee.data)]))]:[U,V(e.dNoEvents)]},Ee=P=>{let U=u("div","ra-dctx"),W=u("div","ra-dkv"),J=(pe,We)=>{W.append(u("span","ra-dmuted",pe),u("span","ra-dmono",We))},j=P.usage,ee=P.messages;J("session",P.id),J("directory",P.workspace?.id??"\u2014"),J("model",P.settings.model??"(default)"),J("messages",`${ee.filter(pe=>pe.role==="user").length} user \xB7 ${ee.filter(pe=>pe.role==="assistant").length} assistant \xB7 ${ee.filter(pe=>pe.role==="tool").length} tool`),J("usage",`${j.prompt_tokens} in \xB7 ${j.completion_tokens} out \xB7 ${j.calls} calls \xB7 $${j.total_cost.toFixed(4)}`);let fe=u("span","ra-dmono","\u2026");W.append(u("span","ra-dmuted","context"),fe),P.context().then(pe=>{fe.textContent=`${pe.used} / ${pe.window} (${(pe.used/pe.window*100).toFixed(2)}%)`}).catch(()=>{fe.textContent="\u2014"});let ve=M("\u2026","tall");return(P.systemPrompt?.()??Promise.resolve("(this agent does not expose its system prompt)")).then(pe=>{ve.textContent=pe}).catch(pe=>{ve.textContent=String(pe)}),U.append(W,S(e.dSystem),ve,S(`${e.dMessages} (${ee.length})`),M(ee,"tall")),[U]},Me=P=>P.tools.map(U=>O([R(U.name),q(U.destructive?" destructive":"")],()=>[u("div","ra-ddesc",U.description??""),M(U.parameters)]));function ue(){if(h=null,!a)return;if(D(),!i){T.replaceChildren();return}let P=t.get(i),U=T.scrollTop,W=document.activeElement?.classList.contains("ra-field")&&T.contains(document.activeElement),J=l==="calls"?I(P):l==="requests"?ae(P):l==="events"?le(P):l==="context"?Ee(i):Me(i);if(T.replaceChildren(...J),T.scrollTop=U,W){let j=T.querySelector(".ra-field");j?.focus(),j?.setSelectionRange(j.value.length,j.value.length)}}let be=()=>{if(!(!a||h)){if(l==="context"||l==="tools"||T.querySelector("details[open]")){D();return}h=setTimeout(ue,300)}},De=P=>{if(t.has(P))return;let U={spans:[],requests:[],events:[],turn:new Map,runs:[]};t.set(P,U),s.set(P,P.on("*",(W,J)=>{let j=J??{},ee=String(j.runId??"");if(W==="run_start"&&(U.runs.push(ee),wo(U.runs,60)),W==="turn_start"&&U.turn.set(ee,Number(j.turn)||1),W==="request"&&(U.requests.push({runId:ee,turn:Number(j.turn),at:Date.now(),params:j.params}),wo(U.requests,Pi.requests)),W==="response"){let fe=[...U.requests].reverse().find(ve=>ve.runId===ee&&ve.turn===Number(j.turn)&&ve.durationMs===void 0);fe&&Object.assign(fe,{durationMs:j.durationMs,finishReason:j.finishReason,usage:j.usage,message:j.message,error:j.error})}if(W==="tool_start"&&(U.spans.push({id:String(j.id),name:String(j.name),args:j.args,status:"running",startedAt:Date.now(),runId:ee,turn:U.turn.get(ee)??1}),wo(U.spans,Pi.spans)),W==="tool_end"){let fe=[...U.spans].reverse().find(ve=>ve.id===String(j.id));fe&&Object.assign(fe,{status:String(j.status),result:j.result,durationMs:j.durationMs})}if(!Lu.has(W)){let fe=W==="tool_start"||W==="tool_end"?String(j.name??""):W==="run_end"?String(j.reason??""):W==="response"?String(j.error??j.finishReason??""):"";U.events.push({at:Date.now(),name:W,detail:fe,data:W==="request"?{runId:ee,turn:j.turn,model:j.params?.model}:J}),wo(U.events,Pi.events)}P===i&&be()}))},He=()=>{a=!0,f.style.display="",n.classList.add("ra-files-open"),r.onShow?.(!0),ue()};function Fe(){a&&(a=!1,f.style.display="none",n.classList.remove("ra-files-open"),r.onShow?.(!1))}return{el:f,get visible(){return a},open:He,close:Fe,toggle:()=>a?Fe():He(),setAgent(P){De(P),i=P,a&&ue()},forget(P){s.get(P)?.(),s.delete(P),t.delete(P),i===P&&(i=null)},dispose(){for(let P of s.values())P();s.clear(),h&&clearTimeout(h),f.remove()}}}var Jl=["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"],Yl=["font","mono"],_u='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue","PingFang SC","Noto Sans SC",Arial,sans-serif',Ru='ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace',bo={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)"}}},yr=r=>Object.entries(r).map(([e,n])=>`--ra-${e}:${n}`).join(";");function Xl(){let r=bo.claude,e=[`:where(.ra-chat, .ra-ui){--ra-font:${_u};--ra-mono:${Ru};${yr(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]){${yr(r.dark)};color-scheme:dark}`,`@media (prefers-color-scheme: dark){:where(.ra-ui:not([data-scheme=light])){${yr(r.dark)};color-scheme:dark}}`];for(let[n,t]of Object.entries(bo))n!=="claude"&&(e.push(`:where(.ra-chat[data-palette=${n}], .ra-ui[data-palette=${n}]){${yr(t.light)}}`),e.push(`:where(.ra-chat[data-palette=${n}][data-scheme=dark], .ra-ui[data-palette=${n}][data-scheme=dark]){${yr(t.dark)}}`),e.push(`@media (prefers-color-scheme: dark){:where(.ra-ui[data-palette=${n}]:not([data-scheme=light])){${yr(t.dark)}}}`));return e.join(`
|
|
309
|
+
`)}var Ql=r=>r.startsWith("--")?r:`--ra-${r}`;var Du={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",permAlways:"Always allow (this app)",sched:"Scheduled",schedNew:"New task",schedNone:'No scheduled tasks yet. Ask the AI ("every weekday at 9, summarise the news") or add one.',schedHint:"Tasks run only while this app is open, and wait until the chat is idle. A run missed while it was closed happens once when you next open it.",schedName:"Name",schedPrompt:"What to do",schedWhen:"When",schedOnce:"Once",schedEvery:"Every",schedDaily:"Daily / weekly",schedCron:"Cron",schedMin:"minutes",schedHour:"hours",schedDay:"days",schedCronHint:"minute hour day month weekday, e.g. 0 9 * * 1-5",schedNext:"Next {time}",schedNoNext:"Will not run again",schedPaused:"Paused",schedRunning:"Running",schedLast:"Last {time} \xB7 {status}",schedOk:"done",schedErr:"failed",schedStopped:"stopped",schedRunNow:"Run now",schedPause:"Pause",schedResume:"Resume",schedEdit:"Edit",schedOpen:"Open its conversation",schedDel:"Delete task",schedDelMsg:'Delete "{name}"? Its conversation stays.',schedSave:"Save",schedBusy:"Another scheduled task is running; try again when it ends.",schedByAI:"by AI",schedRunHead:`\u23F0 Scheduled task "{name}" \xB7 {time}
|
|
310
|
+
(Running unattended: the user may not be watching.)`,schedStarted:'Scheduled task "{name}" started',schedFailed:'Scheduled task "{name}" failed: {error}',schedNamePh:"e.g. Morning news digest",schedPromptPh:"What the AI should do each time. Write it to stand alone: the run does not see this conversation.",schedDayNames:"Sun,Mon,Tue,Wed,Thu,Fri,Sat",tSchedList:"Scheduled tasks",tSchedAdd:'Schedule "{name}"',tSchedUpdate:"Change scheduled task",tSchedRemove:"Remove scheduled task",permAutoNote:"Auto-run is on: the AI will no longer ask before deleting, overwriting or publishing. Turn it off in Settings \u2192 Tool permissions.",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",older:"Load earlier messages",olderBusy:"Wait for the reply to finish, then load earlier messages.",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",autoCompactFull:"when the context is full",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",permAlways:"\u4EE5\u540E\u90FD\u5141\u8BB8\uFF08\u672C\u5E94\u7528\uFF09",sched:"\u5B9A\u65F6\u4EFB\u52A1",schedNew:"\u65B0\u5EFA",schedNone:"\u8FD8\u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\u53EF\u4EE5\u76F4\u63A5\u8BA9 AI \u5B89\u6392\uFF08\u6BD4\u5982\u300C\u6BCF\u4E2A\u5DE5\u4F5C\u65E5\u65E9\u4E0A 9 \u70B9\u6574\u7406\u65B0\u95FB\u300D\uFF09\uFF0C\u6216\u70B9\u65B0\u5EFA\u3002",schedHint:"\u5B9A\u65F6\u4EFB\u52A1\u53EA\u5728\u672C\u5E94\u7528\u9875\u9762\u6253\u5F00\u65F6\u8FD0\u884C\uFF0C\u5E76\u7B49\u5BF9\u8BDD\u7A7A\u95F2\u65F6\u624D\u5F00\u59CB\uFF1B\u9875\u9762\u5173\u95ED\u671F\u95F4\u9519\u8FC7\u7684\uFF0C\u4E0B\u6B21\u6253\u5F00\u65F6\u8865\u8DD1\u4E00\u6B21\u3002",schedName:"\u540D\u79F0",schedPrompt:"\u8981\u505A\u4EC0\u4E48",schedWhen:"\u65F6\u95F4",schedOnce:"\u4E00\u6B21",schedEvery:"\u6BCF\u9694",schedDaily:"\u6BCF\u5929 / \u6BCF\u5468",schedCron:"Cron",schedMin:"\u5206\u949F",schedHour:"\u5C0F\u65F6",schedDay:"\u5929",schedCronHint:"\u5206 \u65F6 \u65E5 \u6708 \u5468\uFF0C\u5982 0 9 * * 1-5",schedNext:"\u4E0B\u6B21 {time}",schedNoNext:"\u4E0D\u4F1A\u518D\u8FD0\u884C",schedPaused:"\u5DF2\u6682\u505C",schedRunning:"\u8FD0\u884C\u4E2D",schedLast:"\u4E0A\u6B21 {time} \xB7 {status}",schedOk:"\u5B8C\u6210",schedErr:"\u5931\u8D25",schedStopped:"\u5DF2\u505C\u6B62",schedRunNow:"\u7ACB\u5373\u8FD0\u884C",schedPause:"\u6682\u505C",schedResume:"\u6062\u590D",schedEdit:"\u7F16\u8F91",schedOpen:"\u6253\u5F00\u5B83\u7684\u5BF9\u8BDD",schedDel:"\u5220\u9664\u4EFB\u52A1",schedDelMsg:"\u5220\u9664\u300C{name}\u300D\uFF1F\u5B83\u7684\u5BF9\u8BDD\u4F1A\u4FDD\u7559\u3002",schedSave:"\u4FDD\u5B58",schedBusy:"\u53E6\u4E00\u4E2A\u5B9A\u65F6\u4EFB\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u7ED3\u675F\u540E\u518D\u8BD5\u3002",schedByAI:"AI \u521B\u5EFA",schedRunHead:`\u23F0 \u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D \xB7 {time}
|
|
311
|
+
\uFF08\u65E0\u4EBA\u503C\u5B88\u8FD0\u884C\uFF1A\u7528\u6237\u53EF\u80FD\u4E0D\u5728\u65C1\u8FB9\u3002\uFF09`,schedStarted:"\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5F00\u59CB\u8FD0\u884C",schedFailed:"\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5931\u8D25\uFF1A{error}",schedNamePh:"\u5982\uFF1A\u65E9\u95F4\u65B0\u95FB\u6458\u8981",schedPromptPh:"\u6BCF\u6B21\u8FD0\u884C\u65F6 AI \u8981\u505A\u7684\u4E8B\u3002\u5199\u5B8C\u6574\uFF1A\u8FD0\u884C\u65F6\u770B\u4E0D\u5230\u8FD9\u6BB5\u5BF9\u8BDD\u3002",schedDayNames:"\u65E5,\u4E00,\u4E8C,\u4E09,\u56DB,\u4E94,\u516D",tSchedList:"\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1",tSchedAdd:"\u5B89\u6392\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D",tSchedUpdate:"\u4FEE\u6539\u5B9A\u65F6\u4EFB\u52A1",tSchedRemove:"\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1",permAutoNote:"\u5DF2\u5F00\u542F\u81EA\u52A8\u6267\u884C\uFF1A\u5220\u9664\u3001\u8986\u76D6\u3001\u53D1\u5E03\u7B49\u64CD\u4F5C\u4E5F\u4E0D\u518D\u8BE2\u95EE\u3002\u53EF\u5728\u8BBE\u7F6E \u2192 \u5DE5\u5177\u6743\u9650\u91CC\u5173\u95ED\u3002",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",older:"\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F",olderBusy:"\u7B49\u8FD9\u6B21\u56DE\u590D\u7ED3\u675F\u540E\u518D\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F\u3002",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",autoCompactFull:"\u4E0A\u4E0B\u6587\u7528\u6EE1\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 Ou(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 ec="runapps-agent-chat-style",Nu=Xl()+`
|
|
312
312
|
.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}
|
|
313
313
|
.ra-chat *,.ra-chat *::before,.ra-chat *::after{box-sizing:border-box}
|
|
314
314
|
/* 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. */
|
|
@@ -534,6 +534,8 @@ Updated: ${JSON.stringify(Ti(d,n()))}`}}),Ne({name:"schedule_remove",description
|
|
|
534
534
|
@keyframes ra-shimmer{from{background-position:100% 0}to{background-position:0 0}}
|
|
535
535
|
@media (prefers-reduced-motion:reduce){.ra-pending>span{animation:none;color:var(--ra-fg-muted);background:none}}
|
|
536
536
|
.ra-time{text-align:center;font-size:12px;color:var(--ra-fg-muted);padding:14px 0 2px}
|
|
537
|
+
.ra-olderrow{display:flex;justify-content:center;padding:6px 0 2px}
|
|
538
|
+
.ra-chat .ra-older{font-size:12px;color:var(--ra-fg-muted)}
|
|
537
539
|
.ra-work{border-bottom:1px solid var(--ra-border);padding-bottom:6px;margin-bottom:4px}
|
|
538
540
|
.ra-work>summary{display:inline-flex;align-items:center;gap:4px;font-size:13px;color:var(--ra-fg-muted);cursor:pointer;list-style:none;user-select:none;padding:2px 0}
|
|
539
541
|
.ra-work>summary::-webkit-details-marker{display:none}
|
|
@@ -586,6 +588,8 @@ Updated: ${JSON.stringify(Ti(d,n()))}`}}),Ne({name:"schedule_remove",description
|
|
|
586
588
|
.ra-tool>summary .ra-chev{color:var(--ra-fg-muted);transition:transform .15s}
|
|
587
589
|
.ra-tool[open]>summary .ra-chev{transform:rotate(90deg)}
|
|
588
590
|
.ra-tool .ra-ticon{width:20px;height:20px;border-radius:4px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg);display:inline-flex;align-items:center;justify-content:center}
|
|
591
|
+
.ra-tool .ra-ticon[data-tone="warning"]{background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
|
|
592
|
+
.ra-tool .ra-ticon[data-tone="danger"]{background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
589
593
|
.ra-tool.fail .ra-ticon{background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
590
594
|
.ra-tool .ra-tname{font-weight:600;white-space:nowrap}
|
|
591
595
|
.ra-tool .ra-tname.own{font-weight:500;min-width:0;overflow:hidden;text-overflow:ellipsis}
|
|
@@ -637,6 +641,9 @@ Updated: ${JSON.stringify(Ti(d,n()))}`}}),Ne({name:"schedule_remove",description
|
|
|
637
641
|
.ra-q .ra-opt small{display:block;color:var(--ra-fg-muted);font-size:12px}
|
|
638
642
|
.ra-q .ra-field{border:1px solid var(--ra-border);border-radius:6px;padding:6px 10px;background:var(--ra-bg);width:100%;font-size:14px}
|
|
639
643
|
.ra-q .ra-field:focus{border-color:var(--ra-accent)}
|
|
644
|
+
.ra-q .ra-field.bad{border-color:var(--ra-red)}
|
|
645
|
+
.ra-q .ra-form{display:flex;flex-direction:column;gap:8px;margin:2px 0 4px}
|
|
646
|
+
.ra-q .ra-ff{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ra-fg-muted)}
|
|
640
647
|
.ra-q textarea.ra-field{min-height:96px;max-height:200px;resize:vertical}
|
|
641
648
|
.ra-btns{display:flex;justify-content:flex-end;gap:8px}
|
|
642
649
|
.ra-cbody{margin:2px 0 10px;max-height:min(60vh,560px);overflow:auto;min-width:0}
|
|
@@ -745,37 +752,37 @@ Updated: ${JSON.stringify(Ti(d,n()))}`}}),Ne({name:"schedule_remove",description
|
|
|
745
752
|
.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)}
|
|
746
753
|
.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}
|
|
747
754
|
.ra-toast.warning{background:#d97706}.ra-toast.error{background:#dc2626}
|
|
748
|
-
`+
|
|
749
|
-
`):""}function
|
|
750
|
-
`).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
|
|
751
|
-
`))!t&&(s.startsWith(
|
|
755
|
+
`+Vl;function ac(r,e,n={}){lc();let t=()=>Array.from(r.options).map(d=>({value:d.value,label:d.textContent??d.value})),s=_n(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 lc(){if(typeof document>"u"||document.getElementById(ec))return;let r=document.createElement("style");r.id=ec,r.textContent=Nu,document.head.prepend(r)}var zu={read_file:z.fileText,write_file:z.filePlus,edit_file:z.filePen,delete_file:z.fileX,list_files:z.folderOpen,search_files:z.search,run_js:z.braces,ask_user:z.message,web_search:z.search,web_fetch:z.globe};function Dn(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
756
|
+
`):""}function _i(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(`
|
|
757
|
+
`).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 tc={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"},nc=r=>r&&typeof r=="object"&&typeof r.path=="string"?r.path:void 0;function Fu(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 Ri(r,e){let n=cc(e);return r===0?`${n}0`:r<.001?`${n}${r.toFixed(5)}`:r<.1?`${n}${r.toFixed(4)}`:`${n}${r.toFixed(3)}`}function cc(r){let e=(r||"USD").toUpperCase();return e==="USD"?"$":e==="CNY"||e==="JPY"?"\xA5":e==="EUR"?"\u20AC":e==="GBP"?"\xA3":`${e} `}function us(r,e){return`${cc(e)}${Number(r.toPrecision(4))}`}function Ye(r){return r>=1e6?`${(r/1e6).toFixed(r>=1e7?1:2)}M`:r>=1e4?`${(r/1e3).toFixed(1)}k`:String(r)}function wr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/1024/1024).toFixed(1)} MB`}function Iu(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))):dc(r)}function dc(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 br=r=>r?.ts,uc=2*1024*1024,Hu=32*1024*1024,pc=30,vo=r=>`ckpt:${r}`,ko="ckpt:index";async function Uu(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>uc||s+a.size>Hu){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(vo(e),{at:e,files:n,partial:t.length>0,skipped:t});let i=[...(await r.getData(ko)??[]).filter(a=>a!==e),e].sort((a,l)=>a-l);for(let a of i.splice(0,Math.max(0,i.length-pc)))await r.deleteData(vo(a));await r.putData(ko,i)}async function ju(r,e){let n=await r.getData(ko)??[];for(let t of n.filter(s=>s>e))await r.deleteData(vo(t));await r.putData(ko,n.filter(t=>t<=e))}var To=r=>`hoststate:${r}`,So="hoststate:index";async function qu(r,e,n){await r.putData(To(e),{at:e,value:n});let t=[...(await r.getData(So)??[]).filter(s=>s!==e),e].sort((s,i)=>s-i);for(let s of t.splice(0,Math.max(0,t.length-pc)))await r.deleteData(To(s));await r.putData(So,t)}async function Bu(r,e){let n=await r.getData(So)??[];for(let t of n.filter(s=>s>e))await r.deleteData(To(t));await r.putData(So,n.filter(t=>t<=e))}async function Wu(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>uc||await r.delete(t.path);for(let t of e.files)await r.write(t.path,t.data,t.contentType)}var Ku=20*1024*1024,Vu=8*1024*1024,Zu=25*1024*1024,Di=64*1024,Gu=/\.(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,Qt="[attachments]",xr="[context] ";function xo(r){if(Array.isArray(r))return r.filter(s=>s.type==="text").map(s=>s.text);if(typeof r!="string")return[];if(!r.includes(xr)&&!r.includes(Qt)&&!r.includes("<file name="))return[r];let e=[],n=[],t=!1;for(let s of r.split(`
|
|
758
|
+
`))!t&&(s.startsWith(xr)||s.startsWith(Qt)||s.startsWith("<file name="))&&n.length&&(e.push(n.join(`
|
|
752
759
|
`)),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(`
|
|
753
|
-
`)),e}function Jl(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 ju=r=>r?.typed,qu=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}.`,Bu=r=>`Files the user attaches arrive under ${r}.`,Wu=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 Ku(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Uu.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 Yl(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function Vu(r,e,n,t){let s=new Set,i=(d,f,h)=>new Promise(w=>{if(h?.aborted){w(f);return}let k=u("section","ra-q"),v,T=()=>v.cancel(),C=I=>{h?.removeEventListener("abort",T),s.delete(v),k.remove(),t(),w(I)};v={card:k,cancel:()=>C(f)},h?.addEventListener("abort",T,{once:!0}),k.addEventListener("keydown",I=>{I.key==="Escape"&&!I.isComposing&&(I.preventDefault(),I.stopPropagation(),v.cancel())}),d(k,C),s.add(v),r.append(k),t();let O=k.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>O?.focus())}),a=(d,f,h)=>{d.append(u("div","ra-qt",f)),h&&d.append(u("div","ra-qm",h))},l=(d,f,h)=>{let w=u("button","ra-btn xs "+f,d);return w.type="button",w.addEventListener("click",h),w};return{confirm:(d,f,h={})=>i((w,k)=>{if(a(w,d,f),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=u("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,f,h={})=>i((w,k)=>{a(w,d,h.message);let v=u("div","ra-opts");if(!h.multi&&!h.allowOther){for(let S of f){let H=u("button","ra-opt");H.type="button";let _=u("div");_.append(u("span","",S.label??S.value)),S.description&&_.append(u("small","",S.description)),H.append(_),H.addEventListener("click",()=>k([S.value])),v.append(H)}w.append(v,(()=>{let S=u("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=[],O=S=>{let H=u("label","ra-opt"),_=u("input");_.type=h.multi?"checkbox":"radio",_.name=T,_.value=S.value,C.push(_);let W=u("div");W.append(u("span","",S.label??S.value)),S.description&&W.append(u("small","",S.description)),H.append(_,W),v.append(H)};f.forEach(O);let I=null;h.allowOther&&(O({value:"__other__",label:n.other}),I=u("input","ra-field"),I.type="text",I.placeholder=n.typeAnswer,I.addEventListener("focus",()=>{let S=C.find(H=>H.value==="__other__");S&&(S.checked=!0)}),v.append(I)),w.append(v);let $=u("div","ra-btns");$.append(l(n.cancel,"ghost",()=>k(null)),l(n.ok,"solid",()=>{let S=C.filter(H=>H.checked).map(H=>H.value==="__other__"?I?.value.trim()??"":H.value).filter(Boolean);S.length&&k(S)})),w.append($)},null,h.signal),input:(d,f={})=>i((h,w)=>{a(h,d,f.message);let k=f.multiline?u("textarea","ra-field"):u("input","ra-field");f.multiline||(k.type="text"),f.placeholder&&(k.placeholder=f.placeholder),f.initial&&(k.value=f.initial),k.addEventListener("keydown",T=>{let C=T;C.key==="Enter"&&!C.isComposing&&(!f.multiline||C.metaKey||C.ctrlKey)&&(C.preventDefault(),w(k.value))}),h.append(k);let v=u("div","ra-btns");v.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(k.value))),h.append(v)},null,f.signal),notify(d,f="info"){let h=u("div","ra-toast "+f,d);e.append(h),setTimeout(()=>h.remove(),f==="error"?8e3:4e3)},cancelAll(d=!1){for(let f of[...s])(d||f.card.isConnected)&&f.cancel()},park(){let d=[];for(let f of s)f.card.isConnected&&(f.card.remove(),d.push(f.card));return t(),d},restore(d){for(let f of d)r.append(f);d.length&&t()}}}var Zu=new Set(["read_file","write_file","edit_file"]),Xl=async(r,e)=>{try{return await r.exists(e)&&!await r.isFolder(e)}catch{return!1}},Pi=r=>`__runapps_agent_chat:${r}:last`;function Gu(r){try{return localStorage.getItem(Pi(r))}catch{return null}}function Ql(r,e){try{e?localStorage.setItem(Pi(r),e):localStorage.removeItem(Pi(r))}catch{}}function ic(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)");tc();let n=Mu(e.locale),t=Eu[n],{toolSettings:s,client:i,provider:a,agent:l,workspace:d,resume:f,palette:h,vars:w,className:k,debug:v,settings:T,skillsMenu:C,title:O,placeholder:I,emptyState:$,suggestions:S,sessions:H,locale:_,theme:W,showUsage:ae,attachments:Z,fileDialog:ge,uploadsDir:we,onOpenFile:$e,onLink:Ce,onSession:ce,files:be,headerActions:De,headerEnd:Ue,settingsTabs:Fe,composerTop:L,composerActions:U,permissionsSetting:B,rewindState:G,nextPrompt:j,webSearch:te,schedule:ue,...J}=e,le="/"+(we??"/uploads").replace(/^\/+|\/+$/g,"");Il(ge);let Re=a?yt(a):i?yt(i):l?.provider??null,Pe=Re?.name??J.appName??"app",oe=u("div","ra-chat");k&&oe.classList.add(...k.split(/\s+/).filter(Boolean));let Ut=W??"auto",jt=h??"claude",yr=w,wr=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,$n=[],Ee=()=>{let o=Ut==="auto"?wr?.matches?"dark":"light":Ut;oe.dataset.theme=Ut,oe.dataset.scheme=o,typeof jt=="string"?oe.dataset.palette=jt:delete oe.dataset.palette;for(let m of $n)oe.style.removeProperty(m);$n=[];let c=m=>{for(let[y,g]of Object.entries(m??{}))if(g!==void 0){let b=Kl(y);oe.style.setProperty(b,g),$n.push(b)}};typeof jt!="string"&&c(jt[o]);let p=yr;p&&("light"in p||"dark"in p)?c(p[o]):c(p)};Ee();let Xe=()=>{Ut==="auto"&&Ee()};wr?.addEventListener?.("change",Xe);let nn=u("div","ra-head"),ls=u("div","ra-title",O===!1?"":O||J.appName||t.assistant),rt=u("span","ra-badge"),dt=u("button","ra-btn ghost");dt.type="button",dt.innerHTML=N.bug()+`<span>${Se(t.debug)}</span>`;let ut=u("button","ra-btn ghost");ut.type="button",ut.innerHTML=N.folder()+`<span>${Se(t.files)}</span>`;let pt=u("button","ra-btn ghost");pt.type="button",pt.innerHTML=N.puzzle()+`<span>${Se(t.skills)}</span>`;let Ln=(o,c)=>{let p=u("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}},_t=Ln(pt,t.skills),je=u("button","ra-btn ghost");je.type="button",je.innerHTML=N.clock()+`<span>${Se(t.sched)}</span>`;let rn=Ln(je,t.sched),We=u("button","ra-btn ghost");We.type="button",We.innerHTML=N.hist()+`<span>${Se(t.history)}</span>`;let br=Ln(We,t.history),Rt=u("button","ra-btn ghost");Rt.type="button",Rt.innerHTML=N.plus()+`<span>${Se(t.newChat)}</span>`;let ft=u("button","ra-btn ghost");ft.type="button",ft.innerHTML=N.eraser()+`<span>${Se(t.clearChat)}</span>`,ft.style.display="none";let et=!1,Pn=()=>{ft.style.display=et&&z?.messages.length?"":"none"},st=u("button","ra-btn ghost ra-usebtn");st.type="button",st.style.display="none";let ot=u("button","ra-btn ghost");ot.type="button",ot.innerHTML=N.gear(),ot.title=t.settings,ot.setAttribute("aria-label",t.settings);for(let[o,c]of[[dt,t.debug],[ut,t.files],[pt,t.skills],[je,t.sched],[We,t.history],[Rt,t.newChat],[ft,t.clearChat]])o.setAttribute("aria-label",c),o.title||(o.title=c);for(let o of[...De??[],...Ue??[],...L?[L]:[],...$ instanceof HTMLElement?[$]:[]])o.classList.add("ra-host");nn.append(ls,rt,u("span","ra-sp"),st,dt,ut,pt,je,We,Rt,ft,...De??[],ot,...Ue??[]),O===!1&&(nn.style.display="none");let tt=u("div","ra-log"),xr=u("div","ra-col");tt.append(xr);let _n=u("div","ra-ask"),P=u("div","ra-col");_n.append(P);let K=u("div","ra-status");K.style.display="none";let de=u("div","ra-comp"),ne=u("div","ra-col"),he=u("div","ra-alert");he.style.display="none",he.setAttribute("role","alert");let ve=u("div","ra-queue");ve.style.display="none";let it=u("div","ra-box"),bt=u("div","ra-cmds");bt.style.display="none";let Y=u("textarea");Y.rows=2,Y.setAttribute("aria-label","Message");let xt=u("div","ra-files");xt.style.display="none";let vr=u("div","ra-bar"),Ve=u("div","ra-left"),sn=u("button","ra-attach");sn.type="button",sn.innerHTML=N.clip(),sn.title=t.attach,sn.setAttribute("aria-label",t.attach);let qt=u("input");qt.type="file",qt.multiple=!0,qt.style.display="none",Z===!1&&(sn.style.display="none");let wo=u("span","ra-hint"),cc=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",cs=o=>o.replace("{mod}",cc).replace("{enter}",t.enter).replace("{newline}",t.newline);wo.textContent=cs(t.hintIdle);let Ri=u("div","ra-acts"),on=u("button","ra-send");on.type="button",on.innerHTML=N.corner(18),on.title=t.send,on.setAttribute("aria-label",t.send);let Rn=u("button","ra-btn xs subtle");Rn.type="button",Rn.innerHTML=N.corner()+Se(t.steer),Rn.title=t.steerTip;let kr=u("button","ra-btn xs subtle",t.followUp);kr.type="button",kr.title=t.followUpTip;let an=u("button","ra-stop");an.type="button",an.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>',an.title=t.stop,an.setAttribute("aria-label",t.stop),Ri.append(Rn,kr,an,on);let Di=new Map,Oi=(o,c)=>{let p=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${Se(c.label)}</span>`:`<span>${Se(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},dc=(U??[]).map(o=>{if(o instanceof HTMLElement)return o.classList.add("ra-host"),o;let c={...o},p=u("button","ra-cbtn");return p.type="button",p.addEventListener("click",()=>c.onClick()),Oi(p,c),c.id&&Di.set(c.id,{btn:p,a:c}),p}),Ni=`__runapps_agent_chat:${Pe}:web`,zi=!!Re?.platformTools&&(te??typeof J.webTools!="function"),Dt=(()=>{try{let o=localStorage.getItem(Ni);if(o!==null)return o==="1"}catch{}return J.webTools===!0})(),vt=u("button","ra-cbtn ra-web");vt.type="button";let Ii=()=>{let o=Dt?t.webOn:t.webOff;vt.innerHTML=N.globe(15)+(Dt?`<span>${Se(t.web)}</span>`:""),vt.classList.toggle("on",Dt),vt.classList.toggle("icon",!Dt),vt.setAttribute("aria-pressed",String(Dt)),vt.setAttribute("aria-label",o),vt.title=`${o}
|
|
754
|
-
${t.webHint}`};
|
|
760
|
+
`)),e}function rc(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 Ju=r=>r?.typed,Yu=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}.`,Xu=r=>`Files the user attaches arrive under ${r}.`,Qu=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 ep(r,e){if(!(/^text\//.test(r.type)||/json|xml|javascript|yaml|csv|svg/.test(r.type)||Gu.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 sc(r){let e=r.replace(/^.*[\\/]/,"").replace(/[\u0000-\u001f]/g,"").trim()||"file";return e.length>120?e.slice(-120):e}function tp(r,e,n,t){let s=new Set,i=(d,h,f)=>new Promise(w=>{if(f?.aborted){w(h);return}let k=u("section","ra-q"),x,T=()=>x.cancel(),C=O=>{f?.removeEventListener("abort",T),s.delete(x),k.remove(),t(),w(O)};x={card:k,cancel:()=>C(h)},f?.addEventListener("abort",T,{once:!0}),k.addEventListener("keydown",O=>{O.key==="Escape"&&!O.isComposing&&(O.preventDefault(),O.stopPropagation(),x.cancel())}),d(k,C),s.add(x),r.append(k),t();let D=k.querySelector("input,textarea,button.solid,button");queueMicrotask(()=>D?.focus())}),a=(d,h,f)=>{d.append(u("div","ra-qt",h)),f&&d.append(u("div","ra-qm",f))},l=(d,h,f)=>{let w=u("button","ra-btn xs "+h,d);return w.type="button",w.addEventListener("click",f),w};return{confirm:(d,h,f={})=>i((w,k)=>{if(a(w,d,h),f.body)try{let C=f.body();C.classList.add("ra-cbody"),w.append(C)}catch(C){console.warn("agent: confirm body failed",C)}let x=u("div","ra-btns");x.append(l(f.cancel??n.decline,"ghost",()=>k(!1)));let T=f.always;T&&x.append(l(T.label,"subtle",()=>{try{T.onChoose()}catch(C){console.warn("agent: always.onChoose failed",C)}k(!0)})),x.append(l(f.ok??n.allow,f.danger?"red":"solid",()=>k(!0))),w.append(x)},!1,f.signal),select:(d,h,f={})=>i((w,k)=>{a(w,d,f.message);let x=u("div","ra-opts");if(!f.multi&&!f.allowOther){for(let I of h){let ae=u("button","ra-opt");ae.type="button";let le=u("div");le.append(u("span","",I.label??I.value)),I.description&&le.append(u("small","",I.description)),ae.append(le),ae.addEventListener("click",()=>k([I.value])),x.append(ae)}w.append(x,(()=>{let I=u("div","ra-btns");return I.append(l(n.cancel,"ghost",()=>k(null))),I})());return}let T="ra_"+Math.random().toString(36).slice(2,8),C=[],D=I=>{let ae=u("label","ra-opt"),le=u("input");le.type=f.multi?"checkbox":"radio",le.name=T,le.value=I.value,C.push(le);let Ee=u("div");Ee.append(u("span","",I.label??I.value)),I.description&&Ee.append(u("small","",I.description)),ae.append(le,Ee),x.append(ae)};h.forEach(D);let O=null;f.allowOther&&(D({value:"__other__",label:n.other}),O=u("input","ra-field"),O.type="text",O.placeholder=n.typeAnswer,O.addEventListener("focus",()=>{let I=C.find(ae=>ae.value==="__other__");I&&(I.checked=!0)}),x.append(O)),w.append(x);let M=u("div","ra-btns"),S=()=>C.filter(I=>I.checked).map(I=>I.value==="__other__"?O?.value.trim()??"":I.value).filter(Boolean),q=f.multi?f.min??1:1,R=f.multi?f.max:void 0,V=I=>I>=q&&(R===void 0||I<=R),ie=l(n.ok,"solid",()=>{let I=S();V(I.length)&&k(I)});if(f.multi&&(f.min!==void 0||f.max!==void 0)){let I=()=>{ie.disabled=!V(S().length)};x.addEventListener("change",I),x.addEventListener("input",I),I()}M.append(l(n.cancel,"ghost",()=>k(null)),ie),w.append(M)},null,f.signal),form:(d,h,f={})=>i((w,k)=>{a(w,d,f.message);let x=u("div","ra-form"),T=h.map(O=>{let M=u("label","ra-ff");M.append(u("span","",(O.label??O.name)+(O.required?" *":"")));let S=u("input","ra-field");return S.type=O.type==="number"?"number":"text",S.name=O.name,O.type==="number"&&(S.step="any"),O.placeholder&&(S.placeholder=O.placeholder),O.initial!==void 0&&(S.value=String(O.initial)),M.append(S),x.append(M),{f:O,input:S}}),C=()=>{let O={};for(let{f:M,input:S}of T){let q=S.value.trim(),R=!q&&M.required||!!q&&M.type==="number"&&!Number.isFinite(Number(q));if(S.classList.toggle("bad",R),R){S.focus();return}q&&(O[M.name]=M.type==="number"?Number(q):q)}k(O)};x.addEventListener("keydown",O=>{let M=O;M.key==="Enter"&&!M.isComposing&&(M.preventDefault(),C())}),w.append(x);let D=u("div","ra-btns");D.append(l(n.cancel,"ghost",()=>k(null)),l(f.ok??n.submit,"solid",C)),w.append(D)},null,f.signal),input:(d,h={})=>i((f,w)=>{a(f,d,h.message);let k=h.multiline?u("textarea","ra-field"):u("input","ra-field");h.multiline||(k.type="text"),h.placeholder&&(k.placeholder=h.placeholder),h.initial&&(k.value=h.initial),k.addEventListener("keydown",T=>{let C=T;C.key==="Enter"&&!C.isComposing&&(!h.multiline||C.metaKey||C.ctrlKey)&&(C.preventDefault(),w(k.value))}),f.append(k);let x=u("div","ra-btns");x.append(l(n.cancel,"ghost",()=>w(null)),l(n.submit,"solid",()=>w(k.value))),f.append(x)},null,h.signal),notify(d,h="info"){let f=u("div","ra-toast "+h,d);e.append(f),setTimeout(()=>f.remove(),h==="error"?8e3:4e3)},cancelAll(d=!1){for(let h of[...s])(d||h.card.isConnected)&&h.cancel()},park(){let d=[];for(let h of s)h.card.isConnected&&(h.card.remove(),d.push(h.card));return t(),d},restore(d){for(let h of d)r.append(h);d.length&&t()}}}var np=new Set(["read_file","write_file","edit_file"]),oc=async(r,e)=>{try{return await r.exists(e)&&!await r.isFolder(e)}catch{return!1}},Oi=r=>`__runapps_agent_chat:${r}:last`;function rp(r){try{return localStorage.getItem(Oi(r))}catch{return null}}function ic(r,e){try{e?localStorage.setItem(Oi(r),e):localStorage.removeItem(Oi(r))}catch{}}function fc(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)");lc();let n=Ou(e.locale),t=Du[n],{toolSettings:s,client:i,provider:a,agent:l,workspace:d,resume:h,palette:f,vars:w,className:k,debug:x,settings:T,skillsMenu:C,title:D,placeholder:O,emptyState:M,suggestions:S,sessions:q,locale:R,theme:V,showUsage:ie,attachments:I,fileDialog:ae,uploadsDir:le,onOpenFile:Ee,onLink:Me,onSession:ue,files:be,headerActions:De,headerEnd:He,settingsTabs:Fe,composerTop:P,composerActions:U,permissionsSetting:W,rewindState:J,nextPrompt:j,webSearch:ee,schedule:fe,queue:ve,replyActions:pe,clearButton:We,commands:Ue,uploadImage:en,headerStart:vr,...Te}=e,tn=ve!==!1,On="/"+(le??"/uploads").replace(/^\/+|\/+$/g,"");Wl(ae);let wt=a?gt(a):i?gt(i):l?.provider??null,ke=wt?.name??Te.appName??"app",ne=u("div","ra-chat");k&&ne.classList.add(...k.split(/\s+/).filter(Boolean));let nn=V??"auto",Ft=f??"claude",Lt=w,Nn=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,zn=[],Fn=()=>{let o=nn==="auto"?Nn?.matches?"dark":"light":nn;ne.dataset.theme=nn,ne.dataset.scheme=o,typeof Ft=="string"?ne.dataset.palette=Ft:delete ne.dataset.palette;for(let g of zn)ne.style.removeProperty(g);zn=[];let c=g=>{for(let[y,m]of Object.entries(g??{}))if(m!==void 0){let b=Ql(y);ne.style.setProperty(b,m),zn.push(b)}};typeof Ft!="string"&&c(Ft[o]);let p=Lt;p&&("light"in p||"dark"in p)?c(p[o]):c(p)};Fn();let kr=()=>{nn==="auto"&&Fn()};Nn?.addEventListener?.("change",kr);let it=u("div","ra-head"),tt=u("div","ra-title",D===!1?"":D||Te.appName||t.assistant),at=u("span","ra-badge"),Ve=u("button","ra-btn ghost");Ve.type="button",Ve.innerHTML=z.bug()+`<span>${Ce(t.debug)}</span>`;let lt=u("button","ra-btn ghost");lt.type="button",lt.innerHTML=z.folder()+`<span>${Ce(t.files)}</span>`;let ct=u("button","ra-btn ghost");ct.type="button",ct.innerHTML=z.puzzle()+`<span>${Ce(t.skills)}</span>`;let rn=(o,c)=>{let p=u("b","ra-cnt");return p.style.display="none",o.append(p),g=>{p.textContent=String(g),p.style.display=g?"":"none",o.title=g?`${c} \xB7 ${g}`:c}},sn=rn(ct,t.skills),dt=u("button","ra-btn ghost");dt.type="button",dt.innerHTML=z.clock()+`<span>${Ce(t.sched)}</span>`;let Co=rn(dt,t.sched),Qe=u("button","ra-btn ghost");Qe.type="button",Qe.innerHTML=z.hist()+`<span>${Ce(t.history)}</span>`;let on=rn(Qe,t.history),Pt=u("button","ra-btn ghost");Pt.type="button",Pt.innerHTML=z.plus()+`<span>${Ce(t.newChat)}</span>`;let ut=u("button","ra-btn ghost");ut.type="button",ut.innerHTML=z.eraser()+`<span>${Ce(t.clearChat)}</span>`,ut.style.display="none";let L=!1,K=()=>{ut.style.display=We!==!1&&L&&F?.messages.length?"":"none"},se=u("button","ra-btn ghost ra-usebtn");se.type="button",se.style.display="none";let Z=u("button","ra-btn ghost");Z.type="button",Z.innerHTML=z.gear(),Z.title=t.settings,Z.setAttribute("aria-label",t.settings);for(let[o,c]of[[Ve,t.debug],[lt,t.files],[ct,t.skills],[dt,t.sched],[Qe,t.history],[Pt,t.newChat],[ut,t.clearChat]])o.setAttribute("aria-label",c),o.title||(o.title=c);for(let o of[...vr??[],...De??[],...He??[],...P?[P]:[],...M instanceof HTMLElement?[M]:[]])o.classList.add("ra-host");it.append(...vr??[],tt,at,u("span","ra-sp"),se,Ve,lt,ct,dt,Qe,Pt,ut,...De??[],Z,...He??[]),D===!1&&(it.style.display="none");let de=u("div","ra-log"),Pe=u("div","ra-col");de.append(Pe);let nt=u("div","ra-ask"),In=u("div","ra-col");nt.append(In);let Tr=u("div","ra-status");Tr.style.display="none";let Sr=u("div","ra-comp"),Cr=u("div","ra-col"),je=u("div","ra-alert");je.style.display="none",je.setAttribute("role","alert");let It=u("div","ra-queue");It.style.display="none";let zi=u("div","ra-box"),an=u("div","ra-cmds");an.style.display="none";let re=u("textarea");re.rows=2,re.setAttribute("aria-label","Message");let ln=u("div","ra-files");ln.style.display="none";let Fi=u("div","ra-bar"),Ii=u("div","ra-left"),cn=u("button","ra-attach");cn.type="button",cn.innerHTML=z.clip(),cn.title=t.attach,cn.setAttribute("aria-label",t.attach);let Ht=u("input");Ht.type="file",Ht.multiple=!0,Ht.style.display="none",I===!1&&(cn.style.display="none");let Eo=u("span","ra-hint"),gc=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform??""} ${navigator.platform??""}`)?"\u2318":"Ctrl+",ps=o=>o.replace("{mod}",gc).replace("{enter}",t.enter).replace("{newline}",t.newline);Eo.textContent=ps(t.hintIdle);let Hi=u("div","ra-acts"),dn=u("button","ra-send");dn.type="button",dn.innerHTML=z.corner(18),dn.title=t.send,dn.setAttribute("aria-label",t.send);let Hn=u("button","ra-btn xs subtle");Hn.type="button",Hn.innerHTML=z.corner()+Ce(t.steer),Hn.title=t.steerTip;let Er=u("button","ra-btn xs subtle",t.followUp);Er.type="button",Er.title=t.followUpTip;let un=u("button","ra-stop");un.type="button",un.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>',un.title=t.stop,un.setAttribute("aria-label",t.stop),Hi.append(Hn,Er,un,dn);let Ui=new Map,ji=(o,c)=>{let p=c.icon&&c.iconOnly?c.icon:c.icon?c.icon+`<span>${Ce(c.label)}</span>`:`<span>${Ce(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},yc=(U??[]).map(o=>{if(o instanceof HTMLElement)return o.classList.add("ra-host"),o;let c={...o},p=u("button","ra-cbtn");return p.type="button",p.addEventListener("click",()=>c.onClick()),ji(p,c),c.id&&Ui.set(c.id,{btn:p,a:c}),p}),qi=`__runapps_agent_chat:${ke}:web`,Bi=!!wt?.platformTools&&(ee??typeof Te.webTools!="function"),_t=(()=>{try{let o=localStorage.getItem(qi);if(o!==null)return o==="1"}catch{}return Te.webTools===!0})(),bt=u("button","ra-cbtn ra-web");bt.type="button";let Wi=()=>{let o=_t?t.webOn:t.webOff;bt.innerHTML=z.globe(15)+(_t?`<span>${Ce(t.web)}</span>`:""),bt.classList.toggle("on",_t),bt.classList.toggle("icon",!_t),bt.setAttribute("aria-pressed",String(_t)),bt.setAttribute("aria-label",o),bt.title=`${o}
|
|
761
|
+
${t.webHint}`};Wi(),Bi||(bt.style.display="none");let Ki=o=>{Bi&&o.configure({webTools:_t})};bt.addEventListener("click",()=>{_t=!_t;try{localStorage.setItem(qi,_t?"1":"0")}catch{}Wi();for(let o of Ie.values())Ki(o)});let Mo=`__runapps_agent_chat:${ke}:perm`,Ao=!l&&typeof Te.permissions!="function"&&W!==!1,Mr=(()=>{if(!Ao)return null;try{let o=localStorage.getItem(Mo);if(o==="ask"||o==="auto")return o}catch{}return null})(),$o=()=>(Mr??Te.permissions??"ask")==="auto",Lo=(o,c=!1)=>{let p=$o();if(Mr=o,Ao)try{o?localStorage.setItem(Mo,o):localStorage.removeItem(Mo)}catch{}for(let g of Ie.values())g.configure({permissions:o??Te.permissions??"ask"});!c&&!p&&$o()&&B.notify(t.permAutoNote)};Ii.append(cn,bt,...yc,Eo),Fi.append(Ii,Hi),zi.append(an,ln,re,Fi,Ht);let wc=u("div","ra-drop",t.drop);Cr.append(je,It,...P?[P]:[],zi),Sr.append(Cr);let Vi=u("div","ra-toasts"),Zi=u("div","ra-col");Zi.append(Tr);let fs=u("div","ra-main"),Po=u("div","ra-chatcol"),Gi=u("div","ra-jumpwrap"),Rt=u("button","ra-jump");Rt.type="button",Rt.innerHTML=z.arrowDown(),Rt.title=t.jumpEnd,Rt.setAttribute("aria-label",t.jumpEnd),Rt.tabIndex=-1,Gi.append(Rt),Po.append(de,Gi,nt,Zi,Sr),fs.append(Po),ne.append(it,fs,Vi,wc),r.replaceChildren(ne);let F,we=new mr(de,Pe,{estimate:96,overscan:400,rowClass:"ra-row",onFollow:o=>{let c=!o&&de.scrollHeight-de.clientHeight>40;Rt.classList.toggle("show",c),Rt.tabIndex=c?0:-1}});Rt.addEventListener("click",()=>we.scrollToBottom()),de.addEventListener("click",o=>{let c=o.target.closest("summary");c&&de.contains(c)&&we.pin(c)},!0);let Y=null,Ut=null,pn=new Map,_o=new WeakMap,Ar=new Map,hs=[],xt=0,$r=null,Lr=[],Ji=[],Se=null,Un=!0,Yi=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{ne.dataset.short=ne.clientHeight&&ne.clientHeight<420?"1":""});Yi?.observe(ne);let Ro=0,B=tp(In,Vi,t,()=>{let o=In.childElementCount;ne.dataset.asking=o?"1":"",o<Ro?we.scrollToBottom():we.schedule(),Ro=o}),bc=3,Ie=new Map,ms=new Map,Pr=new Map,jt=new Set,qt=new Map,Do=(o,c)=>new Promise(p=>{if(F?.id===o){p(!0);return}if(c?.aborted){p(!1);return}jt.add(o);let g=qt.get(o)??[],y=b=>{c?.removeEventListener("abort",m),p(b)},m=()=>{let b=qt.get(o);if(b){let v=b.indexOf(y);v>=0&&b.splice(v,1),b.length||(qt.delete(o),jt.delete(o))}y(!1),fn()};c?.addEventListener("abort",m,{once:!0}),g.push(y),qt.set(o,g),fn()}),Oo=(o,c=!0)=>{let p=qt.get(o);qt.delete(o),jt.delete(o),p?.forEach(g=>g(c))},xc=o=>({confirm:async(c,p,g)=>await Do(o,g?.signal)?B.confirm(c,p,g?.permission&&Ao&&!g.always?{...g,always:{label:t.permAlways,onChoose:()=>Lo("auto")}}:g):!1,select:async(c,p,g)=>await Do(o,g?.signal)?B.select(c,p,g):null,input:async(c,p)=>await Do(o,p?.signal)?B.input(c,p):null,notify:(c,p)=>B.notify(c,p)}),Xi=o=>!!o.workspace&&typeof d=="function"&&!o.workspace.root,No=()=>[...Ie.values()].filter(o=>o!==F&&(o.busy||(o.queued?.length??0)>0||jt.has(o.id))),gs=o=>{let c=o.title??An({v:2,id:o.id,messages:o.messages,usage:o.usage,droppedTurns:0,savedAt:0});return c===Jt?t.untitled:c.length>40?c.slice(0,37)+"\u2026":c},fn=()=>Qe.classList.toggle("ra-bg",No().length>0),jn=null,ys=()=>{jn&&clearTimeout(jn),jn=setTimeout(async()=>{jn=null;let o=F?.workspace;if(!o||l){on(0);return}try{let p=(await o.sessions.list()).filter(g=>g.id!==F.id).length;F?.workspace===o&&on(p?p+1:0)}catch{}},50)},Qi=async(o,c)=>{let p=br(c);if(!(!o.workspace||!p)){if(J)try{await qu(o.workspace,p,await J.take())}catch(g){console.warn("agent: rewindState.take failed",g)}if(Xi(o))try{await Uu(o.workspace,p)}catch(g){console.warn("agent: checkpoint failed",g)}}},ea=o=>{if(ms.has(o.id))return;let c=[];c.push(o.on("run_end",()=>{F!==o&&(B.notify(`${gs(o)} \xB7 ${t.finished}`),setTimeout(()=>{Un&&(F!==o&&!o.busy&&!o.queued?.length&&!jt.has(o.id)&&(Ie.delete(o.id),ws(o),Rs(o)),fn())},50))})),c.push(o.on("run_start",p=>{fn(),p.message&&Qi(o,p.message)})),ms.set(o.id,c),fn()},ws=o=>{ms.get(o.id)?.forEach(c=>c()),ms.delete(o.id)},Ze=Zl({t,root:ne,editorHost:Po,notify:(o,c)=>B.notify(o,c),onChange:()=>{Wt()},onShow:o=>lt.classList.toggle("on",o)});fs.append(Ze.el);let pt=Gl({t,root:ne,onShow:o=>Ve.classList.toggle("on",o)});fs.append(pt.el);let hn=!!x,bs=()=>{if(Ve.style.display=hn?"":"none",ne.dataset.debug=hn?"1":"",hn){for(let o of Ie.values())o!==F&&pt.setAgent(o);F&&pt.setAgent(F)}else{pt.close();for(let o of Ie.values())pt.forget(o)}};bs(),lt.addEventListener("click",()=>{pt.visible&&(pt.close(),bs()),Ze.toggle()}),Ve.addEventListener("click",async()=>{Ze.visible&&await Ze.close(),!Ze.visible&&(pt.toggle(),bs())});let _r=o=>{Ee?Ee(o):Ze.open(o)},ta=async o=>{let c=F?.workspace;if(c&&!await c.exists(o)){B.notify(`${t.rewindGoneFile.replace("{path}",o)}`,"warning");return}_r(o)},Dt=u("div","ra-empty"),zo={render:()=>Dt},na=()=>{if(M!==null){if(Dt.replaceChildren(),Dt.classList.toggle("start",typeof M=="object"&&!(M instanceof HTMLElement)&&M?.align==="start"),M instanceof HTMLElement)Dt.append(M);else if(M&&typeof M=="object"){if(M.icon){let o=u("div","ra-empty-icon");typeof M.icon=="string"?o.innerHTML=M.icon:o.append(M.icon),Dt.append(o)}M.title&&Dt.append(u("h3","ra-empty-title",M.title)),M.text&&Dt.append(u("p","ra-empty-text",M.text))}else Dt.append(u("div","",typeof M=="string"?M:t.empty));if(S?.length){let o=u("div","ra-sugs");for(let c of S){let p=typeof c=="string"?c:c.label,g=typeof c=="string"?c:c.prompt,y=u("button","",p);y.type="button",g!==p&&(y.title=g),y.addEventListener("click",()=>{re.value=g,re.focus(),et()}),o.append(y)}Dt.append(o)}we.rows.includes(zo)||we.push(zo)}},vc=()=>we.remove(zo),vt=o=>{vc(),we.push(o)},ra=(o,c,p)=>{let g=u("span","ra-chip"),y=o.lastIndexOf("."),m=y>0&&o.length-y<=6?o.slice(y):"";if(p){let v=u("img");v.src=p,v.alt="",g.append(v)}else g.append(u("span","ra-ext",(m.slice(1)||"file").slice(0,4)));let b=u("span","ra-cn");return b.title=o,b.append(u("span","st",m?o.slice(0,y):o)),m&&b.append(u("span","ex",m)),g.append(b),c&&g.append(u("small","",c.replace(/\s+(?=[KMG]?B$)/,""))),g},sa=(o,c,p)=>{let g=u("span","ra-chip ra-ctx"),y=u("span","ra-ctxi");y.innerHTML=p??z.pointer(15);let m=u("span","ra-cn");return m.title=c??o,m.append(u("span","st",o)),g.append(y,m),g},oa=o=>xo(o).flatMap(c=>c.startsWith(xr)?[{label:c.slice(xr.length).split(`
|
|
755
762
|
`)[0],text:c.includes(`
|
|
756
763
|
`)?c.slice(c.indexOf(`
|
|
757
|
-
`)+1):""}]:[]),
|
|
758
|
-
`).slice(1)){let
|
|
759
|
-
`),update:()=>{},render:()=>
|
|
760
|
-
`).slice(1)){let A=
|
|
764
|
+
`)+1):""}]:[]),kc=(o,c)=>{let p=u("div","ra-user"),g=u("div","ra-bubble"),y=xo(o),m=c.text;g.textContent=m.length>4e3?m.slice(0,4e3)+"\u2026":m;let b=y.find(H=>H.startsWith(Qt));if(b){let H=u("div","ra-files");for(let G of b.split(`
|
|
765
|
+
`).slice(1)){let te=rc(G);if(!te)continue;let he=ra(te.ref.replace(/^.*\//,""),te.size,null);if(te.ref.startsWith("/")){let ge=te.ref;he.classList.add("ra-chip-link"),he.title=`${t.open} ${ge}`,he.setAttribute("role","button"),he.tabIndex=0,he.addEventListener("click",()=>{ta(ge)}),he.addEventListener("keydown",Xe=>{Xe.key==="Enter"&&ta(ge)})}H.append(he)}H.childElementCount&&g.append(H)}let v=oa(o);if(v.length){let H=u("div","ra-files");for(let G of v)H.append(sa(G.label));g.append(H)}for(let H of Ts(o)){let G=u("img");G.src=H,G.alt="",g.append(G)}let E=u("div","ra-uf"),$=u("span","ra-ut"),A=u("button","ra-ib");A.type="button",A.innerHTML=z.copy(13),A.title=t.copy,A.setAttribute("aria-label",t.copy),A.addEventListener("click",()=>{navigator.clipboard?.writeText(c.text).then(()=>B.notify(t.copied))});let _=u("button","ra-ib");return _.type="button",_.innerHTML=z.undo(),_.title=t.rewind,_.setAttribute("aria-label",t.rewind),_.addEventListener("click",()=>{Sc(c)}),E.append($,A,...pe?.rewind===!1?[]:[_]),p.addEventListener("mouseenter",()=>c.update()),c.update=()=>{let H=br(c.msg);$.innerHTML=z.checks()+`<span>${Ce(H?Iu(H,t):t.sent)}</span>`,_.disabled=!c.msg},c.update(),p.append(g,E),p},Fo=(o,c)=>{let g=xo(o).filter(b=>!b.startsWith(Qt)&&!b.startsWith(xr)&&!b.startsWith("<file name=")),y=Ju(c),m={msg:c,text:y??g.join(`
|
|
766
|
+
`),update:()=>{},render:()=>kc(o,m)};return m},kt=null,Rr=(o,c)=>{fa(br(c)??Date.now());let p=Fo(o,c);return vt(p),we.scrollToBottom(),p},Tc=async(o,c,p={title:t.rewindTitle,message:t.rewindMsg,ok:t.rewind})=>{let g=u("input");g.type="checkbox",g.checked=!!o;let y=u("input");y.type="checkbox",y.checked=!0;let m=[];if(c&&J){let v=u("label","ra-ck");v.append(y,u("span","",J.label)),m.push(v)}if(o){let v=u("label","ra-ck");v.append(g,u("span","",t.rewindFiles));let E=o.files.reduce(($,A)=>$+(typeof A.data=="string"?new TextEncoder().encode(A.data).length:A.data.byteLength),0);m.push(v,u("div","ra-dn",t.rewindSnapshot.replace("{n}",String(o.files.length)).replace("{size}",wr(E)).replace("{time}",dc(o.at))+(o.partial?` ${t.rewindPartial}`:"")))}return await yo(ne,{title:p.title,message:p.message,body:m,ok:p.ok,cancel:t.cancel,focus:"ok"})?{files:!!o&&g.checked,host:!!c&&y.checked}:null},Sc=o=>o.msg?ia(o.msg,o.text):Promise.resolve(),ia=async(o,c,p=!1)=>{if(!F)return;let g=F,y={msg:o,text:c},m=g.messages.indexOf(y.msg);if(m<0){B.notify(t.rewindGone,"warning");return}let b=g.workspace,v=br(y.msg),E=b&&v&&Xi(g)?await b.getData(vo(v)):void 0,$=b&&v&&J?await b.getData(To(v)):void 0,A=await Tc(E,$,p?{title:t.regenTitle,message:t.regenMsg,ok:t.regen}:void 0);if(!A||F!==g)return;let _=!1;try{if(g.busy&&(B.cancelAll(),await g.abort()),await g.rewind(m),_=!0,A.files&&b&&E)try{await Wu(b,E)}catch(H){B.notify(H.message,"error")}if(A.host&&$&&J)try{await J.restore($.value)}catch(H){B.notify(H.message,"error")}b&&v&&(ju(b,v).catch(()=>{}),Bu(b,v).catch(()=>{}))}catch(H){B.notify(H.message,"error")}finally{F===g&&(mn(g.messages),ft(g),Ze.refresh(),Wt())}!_||F!==g||(re.value=y.text,re.focus(),et(),await ca(y.msg),p&&await Kn("prompt"))},aa=o=>o.role==="user"&&!(typeof o.content=="string"&&(Be(o)!==null||o.content.startsWith("[environment]"))),xs=(o,c)=>{let p=o.messages,g=p.indexOf(c);if(g<0)return null;let y=g;for(;y>=0&&!aa(p[y]);)y--;let m=g+1;for(;m<p.length&&!aa(p[m]);)m++;return y<0?null:{start:y,end:m}},la=o=>{let c=u("div","ra-af"),p=(v,E,$)=>{let A=u("button","ra-ib");return A.type="button",A.innerHTML=v,A.title=E,A.setAttribute("aria-label",E),A.addEventListener("click",$),A},g=p(z.copy(13),t.copy,()=>{let v=F,E=v&&xs(v,o),$=E?v.messages.slice(E.start+1,E.end).filter(A=>A.role==="assistant").map(A=>Dn(A.content).trim()).filter(Boolean):[Dn(o.content).trim()];navigator.clipboard?.writeText($.at(-1)??"").then(()=>B.notify(t.copied))}),y=p(z.refresh(13),t.regen,()=>{let v=F,E=v&&xs(v,o);if(!v||!E){B.notify(t.rewindGone,"warning");return}let $=v.messages[E.start];ia($,Fo($.content,$).text,!0)}),m=p(z.trash(13),t.delTurn,()=>{(async()=>{let v=F;if(!v||!xs(v,o)){B.notify(t.rewindGone,"warning");return}if(!await yt(ne,t.delTurnTitle,t.delTurnMsg,{danger:!0,ok:t.delTurn,cancel:t.cancel}))return;let E=F===v?xs(v,o):null;if(E)try{v.busy&&(B.cancelAll(),await v.abort()),await v.remove?.(E.start,E.end)}catch($){B.notify($.message,"error")}})()});c.append(g,...pe?.retry===!1?[]:[y],...pe?.delete===!1?[]:[m]);let b=o.runUsage;if(b&&b.calls){let v=A=>{E.textContent=t.replyCost.replace("{cost}",Ri(b.total_cost,A))},E=u("span","ra-cost");v(_s);let $=F;_s===void 0&&$&&$.modelInfo().then(A=>{A?.price?.currency&&v(A.price.currency)}).catch(()=>{}),E.title=t.replyUsage.replace("{in}",Ye(b.prompt_tokens)).replace("{out}",Ye(b.completion_tokens)).replace("{calls}",String(b.calls)),c.append(E)}return c},ca=async o=>{if(typeof o.content!="string"&&!Array.isArray(o.content))return;let c=Array.isArray(o.content)?o.content:xo(o.content).map($=>({type:"text",text:$}));for(let $ of oa(c).reverse())Ca({label:$.label,text:$.text});let p=c.find($=>$.type==="text"&&$.text.startsWith(Qt));if(!p)return;let g=F?.workspace,y=new Map;for(let $ of c)if($.type==="text"){let A=/^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec($.text);A&&y.set(A[1],A[2])}let m=Ts(c),b=[],v=[],E=[];for(let $ of p.text.split(`
|
|
767
|
+
`).slice(1)){let A=rc($);if(!A)continue;let{ref:_,type:H}=A,G=_.replace(/^.*\//,"");if(_.startsWith("/")&&g)try{let te=await g.read(_);b.push(new File([te.data],G,{type:te.contentType||H})),v.push(_)}catch{E.push(_)}else if(y.has(G))b.push(new File([y.get(G)],G,{type:H})),v.push(void 0);else if(/^image\//.test(H)&&m.length){let te=await(await fetch(m.shift())).blob();b.push(new File([te],G,{type:H})),v.push(void 0)}else E.push(G)}b.length&&await Ur(b,v),E.length&&B.notify(t.rewindGoneFile.replace("{path}",E.join(", ")),"warning")},da=()=>{let o=u("div","ra-asst"),c=u("div","ra-body");return o.append(c),{render:()=>o,el:o,body:c,text:null,think:null,thinkBody:null,md:"",reasoning:""}},Cc=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)))},ua=(o,c)=>{if(o.querySelector(":scope>.ra-work"))return;let p=Array.from(o.children),y=p.at(-1)?.classList.contains("ra-md")?p.slice(0,-1):p;if(!y.length)return;let m=u("details","ra-work"),b=u("summary");b.append(u("span","",c!==void 0&&c>0?t.worked.replace("{t}",Cc(c)):t.workedNoTime));let v=u("span","ra-chev");v.innerHTML=z.chev(13),b.append(v),b.addEventListener("click",()=>we.pin(b));let E=u("div","ra-wb");E.append(...y),m.append(b,E),o.prepend(m)},Dr=0,Or=()=>{if(Y){if(Ho(Y),!Y.body.childElementCount){we.remove(Y),Y=null;return}Nr(!0),ua(Y.body,Dr?Date.now()-Dr:void 0),Y=null,we.schedule()}},vs=()=>(Y||(Y=da(),vt(Y)),Y),Tt=(o=t.waiting,c)=>{let p=vs();p.pending||(p.pending=u("div","ra-pending"),p.pending.append(u("span","",o)));let g=p.pending;g.firstElementChild.textContent=o;let y=g.querySelector(".ra-lpv"),m=c?.text.trim()??"";m?(y||(y=u("div","ra-lpv"),y.append(u("div")),g.append(y)),y.className="ra-lpv"+(c.code?" code":"")+(c.head?" head":""),y.firstElementChild.textContent=c.head?m.slice(0,600):m.slice(-600)):y?.remove(),p.body.lastElementChild!==g&&p.body.append(g),we.schedule()},pa=o=>{let c=o.lastElementChild;return c?.classList.contains("ra-pending")?c.previousElementSibling:c},Io=(o,c)=>{let p=o.lastElementChild;p?.classList.contains("ra-pending")?o.insertBefore(c,p):o.append(c)},Ec=(o,c)=>{let p=c&&typeof c=="object"?c:{};return o==="run_js"&&typeof p.code=="string"?{text:p.code,code:!0,head:!0}:o==="write_file"&&typeof p.content=="string"?{text:p.content,head:!0}:o==="edit_file"&&Array.isArray(p.edits)?{text:p.edits.map(g=>g&&typeof g=="object"?String(g.newText??""):"").join(`
|
|
761
768
|
\u2026
|
|
762
|
-
`),head:!0}:o==="edit_file"&&typeof p.newText=="string"?{text:p.newText,head:!0}:{text:Ai(o,c),head:!0}},_o=(o=X)=>{o?.pending&&(o.pending.remove(),o.pending=null)},xc=15*6e4,Nn=0,vc=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}),y=x=>new Date(x.getFullYear(),x.getMonth(),x.getDate()).getTime(),g=Math.round((y(p)-y(c))/864e5);return g===0?`${t.today} ${m}`:g===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}`},ia=o=>{if(o){if(!Nn||o-Nn>=xc){let c=u("div","ra-time",vc(o));zt({render:()=>c,el:c})}Nn=o}},aa=(o,c)=>{let p=u("details","ra-think"),m=u("summary");m.innerHTML=`<span class="ra-chev">${N.chev(13)}</span>${N.brain()}<span>${Se(c?t.thought:t.thinking)}</span>`;let y=u("div","ra-think-body",o);return p.append(m,y),[p,y]},la=o=>{let c=z?.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||Xl(c,m).then(y=>{y&&!p.classList.contains("ra-path")&&(p.classList.add("ra-path"),p.dataset.path=m,p.title=t.open,p.insertAdjacentHTML("beforeend",N.file(11)))})}},kc=(o,c)=>{pr(o,c,!1),la(o)},_r=o=>{Bt!==null&&(clearTimeout(Bt),Bt=null),X&&(X.text&&(X.drawn!==X.md||X.drawnFinal!==o)&&(pr(X.text,X.md,!o),X.drawn=X.md,X.drawnFinal=o,o&&la(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&&St(t.thinking.replace(/…$/,""),{text:X.reasoning}),ke.schedule())},ca=()=>{Bt===null&&(Bt=window.setTimeout(()=>{Bt=null,_r(!1)},100))},Rr=o=>z?.tools?.find(c=>c.name===o)?.display,bs=o=>{if(o)try{return o()}catch{return}},Ro=(o,c)=>{let p=Rr(o),m=bs(p?.label&&(()=>p.label(c)));return typeof m=="string"&&m.trim()?m:void 0},da=(o,c)=>{let p=Rr(o.name);if(!p?.render)return;let m=bs(()=>p.render({args:o.args,...c})),y=o.el.querySelector("summary");if(y.querySelector(".ra-tx")?.remove(),!(m instanceof HTMLElement))return;let g=u("div","ra-tx ra-host");g.addEventListener("click",b=>b.preventDefault()),g.append(m),y.append(g)},ua=(o,c)=>{let p=u("details","ra-tool");So.set(p,{name:o,args:c});let m=u("summary"),y=Rr(o),g=Ro(o,c),b=u("span","ra-ticon");b.innerHTML=y?.icon??($u[o]??N.wrench)();let x=u("span","ra-tend");x.innerHTML='<span class="ra-spin"></span>',m.innerHTML=`<span class="ra-chev">${N.chev()}</span>`;let M=g??(o==="run_js"?t.runCode:void 0),E=u("span","ra-tname",M??o);M&&(E.title=o,E.classList.add("own")),m.append(b,E,u("span","ra-tsum",g?"":Ai(o,c)),x);let A=u("div","ra-tbody"),R=u("pre","",o==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));A.append(u("div","ra-tlabel",t.args),R),p.append(m,A);let F={el:p,name:o,args:c,end:x,body:A,update:null,result:null};return da(F,{status:"running"}),F},pa=o=>{let c=oa(o);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let p=u("details","ra-tg"),m=u("summary"),y=u("div","ra-tgb");return p.append(m,y),Po(o,p),y},Tc=o=>{let c=[],p=new Map;for(let m of o){let y=Ro(m.name,m.args);if(y!==void 0){let M=`Own:${y}`;p.has(M)||(c.push(M),p.set(M,0)),p.set(M,p.get(M)+1);continue}let g=Zl[m.name]??"Other",b=g==="Other"?`Other:${m.name}`:g;p.has(b)||(c.push(b),p.set(b,g==="Read"||g==="Write"||g==="Edit"||g==="Delete"?new Set:0));let x=p.get(b);x instanceof Set?x.add(Gl(m.args)??String(x.size)):p.set(b,x+1)}return c.map(m=>{let y=p.get(m),g=String(y instanceof Set?y.size:y);return m.startsWith("Own:")?y===1?m.slice(4):`${m.slice(4)} \xD7${g}`:m.startsWith("Other:")?t.actOther.replace("{name}",m.slice(6)):t[`act${m}`].replace("{n}",g)}).join(n==="zh"?"\uFF0C":", ")},fa=(o,c)=>{let p=Ro(o.name,o.args);if(p!==void 0)return{verb:p,what:""};let m=Zl[o.name]??"Other",y=Gl(o.args),g=t[`ing${m}`];return m==="Other"?{verb:`${g} ${o.name}`,what:c.querySelector(".ra-tsum")?.textContent??""}:m==="Ask"?{verb:g,what:""}:y&&m!=="Search"?{verb:g,what:y.slice(y.lastIndexOf("/")+1)||y,title:y}:{verb:g,what:c.querySelector(".ra-tsum")?.textContent??""}},Do=o=>{let c=o.closest(".ra-tg");if(!c)return;let p=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),m=p.filter(x=>x.querySelector(".ra-tend .ra-spin")),y=p.filter(x=>x.classList.contains("fail")).length,g=c.querySelector("summary");if(g.replaceChildren(),m.length){let x=m[m.length-1],M=fa(So.get(x)??{name:x.querySelector(".ra-tname")?.textContent??"",args:void 0},x);g.append(u("span","ra-spin"));let E=u("span","ra-tgt");E.append(`${M.verb} `),M.what&&E.append(u("code","",M.what)),M.title&&(E.title=M.title),g.append(E)}else{let x=p.map(A=>So.get(A)).filter(A=>!!A),M=x.length?Tc(x):p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),E=u("span","ra-tgt",M);E.title=p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),g.append(E)}y&&g.append(u("span","ra-tgf",t.toolsFailed.replace("{n}",String(y))));let b=u("span","ra-chev");b.innerHTML=N.chev(12),g.append(b)},Sc=(o,c,p,m,y)=>{let g=ua(c,p);return y?(y.nested||(y.nested=u("div","ra-tnest"),y.body.append(y.nested)),y.nested.append(g.el)):pa(m).append(g.el),ln.set(o,g),Do(g.el),ke.schedule(),g},Oo=o=>Array.isArray(o)?o.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:)/.test(c.image_url.url)?[c.image_url.url]:[]):[],ha=async o=>{let c=z?.workspace,p=Rr(o.name),m=o.args,y=p?.file?bs(()=>p.file(o.args)):Zu.has(o.name)&&m&&typeof m=="object"&&typeof m.path=="string"?m.path:null;if(!c||!y||!await Xl(c,y))return;let g=u("div","ra-tacts"),b=u("button","ra-open",`${t.open} ${y}`);if(b.type="button",b.addEventListener("click",()=>Ar(y)),g.append(b),!$e){let x=u("button","ra-open",t.download);x.type="button",x.addEventListener("click",()=>{Ze.download(y)}),g.append(x)}o.body.querySelector(":scope>pre")?.after(g),ke.schedule()},ma=(o,c,p,m,y=[],g)=>{let b=c==="ok",x=c==="error"||c==="blocked";o.end.replaceChildren();let M=Rr(o.name),E=bs(M?.outcome&&(()=>M.outcome({args:o.args,status:c,result:p,details:g})));typeof E=="string"&&E?o.end.append(u("span","ra-tout",E)):m!==void 0&&o.end.append(u("span","",`${Math.round(m)}ms`));let A=u("span",b?"ok":x?"fail":"");b?A.innerHTML=N.check():c==="error"?A.innerHTML=N.xcircle():c==="blocked"?(A.innerHTML=N.ban(),A.title=t.blocked):A.textContent=t[c]??c,o.end.append(A),o.el.classList.toggle("fail",x),da(o,{status:c,result:p,details:g}),o.update?.remove(),b&&(o.el.open?ha(o):o.el.addEventListener("toggle",()=>{ha(o)},{once:!0})),o.result||(o.result=u("pre",""),o.body.append(u("div","ra-tlabel",c==="error"?t.error:t.result),o.result));let R=y.length?p.replace(/^\[image_url\]$/gm,"").trim():p;if(o.result.textContent=R.length>2e4?R.slice(0,2e4)+"\u2026":R||t.emptyResult,y.length&&!o.body.querySelector(".ra-timgs")){let F=u("div","ra-timgs");for(let V of y.slice(0,4)){let re=u("img");re.src=V,re.alt=t.result,re.addEventListener("load",()=>ke.schedule()),F.append(re)}o.body.append(F)}Do(o.el),ke.schedule()},Cc=(o,c,p)=>{let m=u("div","ra-card"),y=u("div","ra-ct"+(c?"":" only"));if(y.innerHTML=N.layers()+`<span>${Se(o)}</span>`,m.append(y),c){let g=u("div","ra-md");pr(g,c,!1),m.append(g)}if(p){let g=u("button","ra-btn xs subtle",p.label);g.type="button",g.addEventListener("click",()=>{g.disabled=!0,p.onClick()}),m.append(g)}return m},Dr=(o,c,p)=>{zt({render:()=>Cc(o,c,p)}),ke.schedule()},Ec=(o,c,p)=>{let m={render:()=>{let y=u("div","ra-warn");if(y.setAttribute("role","status"),p&&(y.title=p),y.innerHTML=N.alert(14),y.append(u("span","",o)),c){let g=u("button","ra-btn xs",c.label);g.type="button",g.addEventListener("click",()=>{ke.remove(m),c.onClick()}),y.append(g)}return y}};zt(m),ke.schedule()},xs=(o,c)=>{let p={render:()=>{let m=u("div","ra-err",o);if(c){let y=u("button","ra-btn xs red-subtle",t.retry);y.type="button",y.addEventListener("click",()=>{ke.remove(p),c()}),m.append(y)}return m}};zt(p),ke.schedule()},zn=o=>{ke.clear(),Nn=0,ln.clear(),Sr.clear(),X=null;let c=null,p,m=(y=!1)=>{if(!c)return;let g=c;c=null;let b=!(y&&z?.busy);zt({render:()=>{let x=ra();for(let M of g.items)if(M.kind==="think"){let[E]=aa(M.text,!0),A=x.body.lastElementChild;A instanceof HTMLDetailsElement&&A.classList.contains("ra-tg")?A.querySelector(".ra-tgb").append(E):x.body.append(E)}else if(M.kind==="text"){let E=u("div","ra-md");kc(E,M.text),x.body.append(E)}else{let E=M.call,A=ua(E.name,E.args);pa(x.body).append(A.el),E.status?ma(A,E.status,E.result??"",void 0,E.images):(E.id&&ln.set(E.id,A),Do(A.el))}return b&&sa(x.body,g.start!==void 0&&g.end!==void 0?g.end-g.start:void 0),b&&g.msg&&x.el.append(ta(g.msg)),x.el}})};for(let y of o)if(y.role==="user"){m();let g=typeof y.content=="string"?Be(y):null;if(g!==null){Dr(t.compacted,g);continue}if(typeof y.content=="string"&&y.content.startsWith("[environment]"))continue;p=mr(y),ia(p),zt(Lo(y.content,y))}else if(y.role==="assistant"){let g=An(y.content),b=y.reasoning_content,x=typeof b=="string"?b:"";c||(c={items:[],calls:[],start:p}),c.msg=y,c.end=mr(y)??c.end,c.end&&(Nn=c.end),x&&c.items.push({kind:"think",text:x}),g&&c.items.push({kind:"text",text:g});for(let M of y.tool_calls??[]){if(No.has(M.function.name))continue;let E=M.function.arguments;try{E=JSON.parse(M.function.arguments)}catch{}let A={id:M.id??"",name:M.function.name,args:E};c.items.push({kind:"call",call:A}),c.calls.push(A),A.id&&Sr.set(A.id,A)}}else if(y.role==="tool"){let g=An(y.content),b=c?.calls.find(x=>x.id===(y.tool_call_id??""));b&&(b.result=g,b.status=Lu(g),b.images=Oo(y.content),Sr.delete(b.id))}m(!0),o.length||Gi(),Pn(),ke.scrollToBottom()},Vt=null,vs=null,Or=()=>{vs=null,Vt!==null&&(Vt=null,It(oe.dataset.busy==="1"))},Mc={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})=>(vs=String(o??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},In=ue?ue===!0?{}:ue:null,qe=In?In.store??io(`__runapps_agent_chat:${Pe}:schedules`):null,Ac={schedule_list:()=>t.tSchedList,schedule_add:o=>t.tSchedAdd.replace("{name}",o.name??""),schedule_update:()=>t.tSchedUpdate,schedule_remove:()=>t.tSchedRemove},$c=qe&&In.tools!==!1?ao(qe,{...In,onChange:()=>gn()}).map(o=>({...o,display:{...o.display,icon:N.clock(),label:Ac[o.name]}})):[],ga=[...J.tools??[],...j?[Mc]:[],...$c],No=new Set(ga.filter(o=>o.display?.hidden).map(o=>o.name)),un=()=>{let o=oe.dataset.busy==="1",c=!!(Y.value.trim()||Et.length||Mt.length);on.style.display=!o&&c?"":"none",Rn.style.display=kr.style.display=o&&c?"":"none"},It=o=>{oe.dataset.busy=o?"1":"",Y.placeholder=o?cs(t.placeholderBusy):Vt??I??t.placeholder,wo.textContent=cs(o?t.hintBusy:Vt?t.hintNext:t.hintIdle),un(),an.style.display=o?"":"none",Ct()},pn=!1,Ct=()=>{let o=z?.queued??[];if(ve.style.display=o.length?"":"none",ve.replaceChildren(),!o.length){pn=!1;return}let c=z,p=E=>An(E.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),m=(E,A,R)=>{let F=u("button");return F.type="button",F.innerHTML=E,F.title=A,F.setAttribute("aria-label",A),F.addEventListener("click",V=>{V.stopPropagation(),R()}),F},y=E=>{let A=u("span","ra-qa");return E.kind!=="steer"&&A.append(m(N.enter(),t.sendNow,()=>{c.dequeue(E.message)&&c.steer(E.message.content),Ct()})),A.append(m(N.pen(),t.editQueued,()=>{c.dequeue(E.message)&&(Y.value=Y.value.trim()?`${p(E.message)}
|
|
763
|
-
${
|
|
764
|
-
[\u2026 truncated]`),y.push(`- ${
|
|
765
|
-
${
|
|
766
|
-
</file>`})}else
|
|
767
|
-
${
|
|
768
|
-
</file>`})):y.push(`- ${
|
|
769
|
+
`),head:!0}:o==="edit_file"&&typeof p.newText=="string"?{text:p.newText,head:!0}:{text:_i(o,c),head:!0}},Ho=(o=Y)=>{o?.pending&&(o.pending.remove(),o.pending=null)},Mc=15*6e4,qn=0,Ac=o=>{let c=new Date(o),p=new Date,g=c.toLocaleTimeString(n==="zh"?"zh-CN":void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}),y=v=>new Date(v.getFullYear(),v.getMonth(),v.getDate()).getTime(),m=Math.round((y(p)-y(c))/864e5);return m===0?`${t.today} ${g}`:m===1?`${t.yesterday} ${g}`:`${c.toLocaleDateString(n==="zh"?"zh-CN":void 0,c.getFullYear()===p.getFullYear()?{month:"short",day:"numeric"}:{year:"numeric",month:"short",day:"numeric"})} ${g}`},fa=o=>{if(o){if(!qn||o-qn>=Mc){let c=u("div","ra-time",Ac(o));vt({render:()=>c,el:c})}qn=o}},ha=(o,c)=>{let p=u("details","ra-think"),g=u("summary");g.innerHTML=`<span class="ra-chev">${z.chev(13)}</span>${z.brain()}<span>${Ce(c?t.thought:t.thinking)}</span>`;let y=u("div","ra-think-body",o);return p.append(g,y),[p,y]},ma=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 g=p.textContent?.trim()??"";!/^\/[^\s`'"<>]+$/.test(g)||g.length>200||oc(c,g).then(y=>{y&&!p.classList.contains("ra-path")&&(p.classList.add("ra-path"),p.dataset.path=g,p.title=t.open,p.insertAdjacentHTML("beforeend",z.file(11)))})}},$c=(o,c)=>{gr(o,c,!1),ma(o)},Nr=o=>{Ut!==null&&(clearTimeout(Ut),Ut=null),Y&&(Y.text&&(Y.drawn!==Y.md||Y.drawnFinal!==o)&&(gr(Y.text,Y.md,!o),Y.drawn=Y.md,Y.drawnFinal=o,o&&ma(Y.text)),Y.thinkBody&&(Y.thinkBody.textContent=Y.reasoning),Y.think&&o?(Y.think.querySelector("summary span:last-child").textContent=t.thought,Y.think.style.display=""):Y.pending&&Y.reasoning&&!Y.text&&Tt(t.thinking.replace(/…$/,""),{text:Y.reasoning}),we.schedule())},ga=()=>{Ut===null&&(Ut=window.setTimeout(()=>{Ut=null,Nr(!1)},100))},zr=o=>F?.tools?.find(c=>c.name===o)?.display,ks=o=>{if(o)try{return o()}catch{return}},Uo=(o,c)=>{let p=zr(o),g=ks(p?.label&&(()=>p.label(c)));return typeof g=="string"&&g.trim()?g:void 0},ya=(o,c)=>{let p=zr(o.name);if(!p?.render)return;let g=ks(()=>p.render({args:o.args,...c})),y=o.el.querySelector("summary");if(y.querySelector(".ra-tx")?.remove(),!(g instanceof HTMLElement))return;let m=u("div","ra-tx ra-host");m.addEventListener("click",b=>b.preventDefault()),m.append(g),y.append(m)},wa=(o,c)=>{let p=u("details","ra-tool");_o.set(p,{name:o,args:c});let g=u("summary"),y=zr(o),m=Uo(o,c),b=u("span","ra-ticon");b.innerHTML=y?.icon??(zu[o]??z.wrench)(),y?.tone&&(b.dataset.tone=y.tone);let v=u("span","ra-tend");v.innerHTML='<span class="ra-spin"></span>',g.innerHTML=`<span class="ra-chev">${z.chev()}</span>`;let E=m??(o==="run_js"?t.runCode:void 0),$=u("span","ra-tname",E??o);E&&($.title=o,$.classList.add("own")),g.append(b,$,u("span","ra-tsum",m?"":_i(o,c)),v);let A=u("div","ra-tbody"),_=u("pre","",o==="run_js"&&c&&typeof c=="object"&&typeof c.code=="string"?c.code:typeof c=="string"?c:JSON.stringify(c,null,2));A.append(u("div","ra-tlabel",t.args),_),p.append(g,A);let H={el:p,name:o,args:c,end:v,body:A,update:null,result:null};return ya(H,{status:"running"}),H},ba=o=>{let c=pa(o);if(c instanceof HTMLDetailsElement&&c.classList.contains("ra-tg"))return c.querySelector(".ra-tgb");let p=u("details","ra-tg"),g=u("summary"),y=u("div","ra-tgb");return p.append(g,y),Io(o,p),y},Lc=o=>{let c=[],p=new Map;for(let g of o){let y=Uo(g.name,g.args);if(y!==void 0){let E=`Own:${y}`;p.has(E)||(c.push(E),p.set(E,0)),p.set(E,p.get(E)+1);continue}let m=tc[g.name]??"Other",b=m==="Other"?`Other:${g.name}`:m;p.has(b)||(c.push(b),p.set(b,m==="Read"||m==="Write"||m==="Edit"||m==="Delete"?new Set:0));let v=p.get(b);v instanceof Set?v.add(nc(g.args)??String(v.size)):p.set(b,v+1)}return c.map(g=>{let y=p.get(g),m=String(y instanceof Set?y.size:y);return g.startsWith("Own:")?y===1?g.slice(4):`${g.slice(4)} \xD7${m}`:g.startsWith("Other:")?t.actOther.replace("{name}",g.slice(6)):t[`act${g}`].replace("{n}",m)}).join(n==="zh"?"\uFF0C":", ")},xa=(o,c)=>{let p=Uo(o.name,o.args);if(p!==void 0)return{verb:p,what:""};let g=tc[o.name]??"Other",y=nc(o.args),m=t[`ing${g}`];return g==="Other"?{verb:`${m} ${o.name}`,what:c.querySelector(".ra-tsum")?.textContent??""}:g==="Ask"?{verb:m,what:""}:y&&g!=="Search"?{verb:m,what:y.slice(y.lastIndexOf("/")+1)||y,title:y}:{verb:m,what:c.querySelector(".ra-tsum")?.textContent??""}},jo=o=>{let c=o.closest(".ra-tg");if(!c)return;let p=Array.from(c.querySelectorAll(".ra-tgb > .ra-tool")),g=p.filter(v=>v.querySelector(".ra-tend .ra-spin")),y=p.filter(v=>v.classList.contains("fail")).length,m=c.querySelector("summary");if(m.replaceChildren(),g.length){let v=g[g.length-1],E=xa(_o.get(v)??{name:v.querySelector(".ra-tname")?.textContent??"",args:void 0},v);m.append(u("span","ra-spin"));let $=u("span","ra-tgt");$.append(`${E.verb} `),E.what&&$.append(u("code","",E.what)),E.title&&($.title=E.title),m.append($)}else{let v=p.map(A=>_o.get(A)).filter(A=>!!A),E=v.length?Lc(v):p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),$=u("span","ra-tgt",E);$.title=p.length===1?t.toolsDone1:t.toolsDone.replace("{n}",String(p.length)),m.append($)}y&&m.append(u("span","ra-tgf",t.toolsFailed.replace("{n}",String(y))));let b=u("span","ra-chev");b.innerHTML=z.chev(12),m.append(b)},Pc=(o,c,p,g,y)=>{let m=wa(c,p);return y?(y.nested||(y.nested=u("div","ra-tnest"),y.body.append(y.nested)),y.nested.append(m.el)):ba(g).append(m.el),pn.set(o,m),jo(m.el),we.schedule(),m},Ts=o=>Array.isArray(o)?o.flatMap(c=>c.type==="image_url"&&/^(data:image\/|https?:|\/(?!\/))/.test(c.image_url.url)?[c.image_url.url]:[]):[],va=async o=>{let c=F?.workspace,p=zr(o.name),g=o.args,y=p?.file?ks(()=>p.file(o.args)):np.has(o.name)&&g&&typeof g=="object"&&typeof g.path=="string"?g.path:null;if(!c||!y||!await oc(c,y))return;let m=u("div","ra-tacts"),b=u("button","ra-open",`${t.open} ${y}`);if(b.type="button",b.addEventListener("click",()=>_r(y)),m.append(b),!Ee){let v=u("button","ra-open",t.download);v.type="button",v.addEventListener("click",()=>{Ze.download(y)}),m.append(v)}o.body.querySelector(":scope>pre")?.after(m),we.schedule()},ka=(o,c,p,g,y=[],m)=>{let b=c==="ok",v=c==="error"||c==="blocked";o.end.replaceChildren();let E=zr(o.name),$=ks(E?.outcome&&(()=>E.outcome({args:o.args,status:c,result:p,details:m})));typeof $=="string"&&$?o.end.append(u("span","ra-tout",$)):g!==void 0&&o.end.append(u("span","",`${Math.round(g)}ms`));let A=u("span",b?"ok":v?"fail":"");b?A.innerHTML=z.check():c==="error"?A.innerHTML=z.xcircle():c==="blocked"?(A.innerHTML=z.ban(),A.title=t.blocked):A.textContent=t[c]??c,o.end.append(A),o.el.classList.toggle("fail",v),ya(o,{status:c,result:p,details:m}),o.update?.remove(),b&&(o.el.open?va(o):o.el.addEventListener("toggle",()=>{va(o)},{once:!0})),o.result||(o.result=u("pre",""),o.body.append(u("div","ra-tlabel",c==="error"?t.error:t.result),o.result));let _=y.length?p.replace(/^\[image_url\]$/gm,"").trim():p;if(o.result.textContent=_.length>2e4?_.slice(0,2e4)+"\u2026":_||t.emptyResult,y.length&&!o.body.querySelector(".ra-timgs")){let H=u("div","ra-timgs");for(let G of y.slice(0,4)){let te=u("img");te.src=G,te.alt=t.result,te.addEventListener("load",()=>we.schedule()),H.append(te)}o.body.append(H)}jo(o.el),we.schedule()},_c=(o,c,p)=>{let g=u("div","ra-card"),y=u("div","ra-ct"+(c?"":" only"));if(y.innerHTML=z.layers()+`<span>${Ce(o)}</span>`,g.append(y),c){let m=u("div","ra-md");gr(m,c,!1),g.append(m)}if(p){let m=u("button","ra-btn xs subtle",p.label);m.type="button",m.addEventListener("click",()=>{m.disabled=!0,p.onClick()}),g.append(m)}return g},Fr=(o,c,p)=>{vt({render:()=>_c(o,c,p)}),we.schedule()},Rc=(o,c,p)=>{let g={render:()=>{let y=u("div","ra-warn");if(y.setAttribute("role","status"),p&&(y.title=p),y.innerHTML=z.alert(14),y.append(u("span","",o)),c){let m=u("button","ra-btn xs",c.label);m.type="button",m.addEventListener("click",()=>{we.remove(g),c.onClick()}),y.append(m)}return y}};vt(g),we.schedule()},Ss=(o,c)=>{let p={render:()=>{let g=u("div","ra-err",o);if(c){let y=u("button","ra-btn xs red-subtle",t.retry);y.type="button",y.addEventListener("click",()=>{we.remove(p),c()}),g.append(y)}return g}};vt(p),we.schedule()},mn=o=>{we.clear(),qn=0,pn.clear(),Ar.clear(),Y=null;let c=null,p,g=F;if(g?.hasOlder&&g.loadOlder){let m=u("button","ra-btn ghost ra-older");m.type="button",m.textContent=t.older,m.addEventListener("click",()=>{if(g.busy){B.notify(t.olderBusy,"warning");return}m.disabled=!0,g.loadOlder().catch(v=>{m.disabled=!1,B.notify(v.message,"error")})});let b=u("div","ra-olderrow");b.append(m),vt({render:()=>b,el:b})}let y=(m=!1)=>{if(!c)return;let b=c;c=null;let v=!(m&&F?.busy);vt({render:()=>{let E=da();for(let $ of b.items)if($.kind==="think"){let[A]=ha($.text,!0),_=E.body.lastElementChild;_ instanceof HTMLDetailsElement&&_.classList.contains("ra-tg")?_.querySelector(".ra-tgb").append(A):E.body.append(A)}else if($.kind==="text"){let A=u("div","ra-md");$c(A,$.text),E.body.append(A)}else{let A=$.call,_=wa(A.name,A.args);ba(E.body).append(_.el),A.status?ka(_,A.status,A.result??"",void 0,A.images):(A.id&&pn.set(A.id,_),jo(_.el))}return v&&ua(E.body,b.start!==void 0&&b.end!==void 0?b.end-b.start:void 0),v&&b.msg&&E.el.append(la(b.msg)),E.el}})};for(let m of o)if(m.role==="user"){y();let b=typeof m.content=="string"?Be(m):null;if(b!==null){Fr(t.compacted,b);continue}if(typeof m.content=="string"&&m.content.startsWith("[environment]"))continue;p=br(m),fa(p),vt(Fo(m.content,m))}else if(m.role==="assistant"){let b=Dn(m.content),v=m.reasoning_content,E=typeof v=="string"?v:"";c||(c={items:[],calls:[],start:p}),c.msg=m,c.end=br(m)??c.end,c.end&&(qn=c.end),E&&c.items.push({kind:"think",text:E}),b&&c.items.push({kind:"text",text:b});for(let $ of m.tool_calls??[]){if(Es.has($.function.name))continue;let A=$.function.arguments;try{A=JSON.parse($.function.arguments)}catch{}let _={id:$.id??"",name:$.function.name,args:A};c.items.push({kind:"call",call:_}),c.calls.push(_),_.id&&Ar.set(_.id,_)}}else if(m.role==="tool"){let b=Dn(m.content),v=c?.calls.find(E=>E.id===(m.tool_call_id??""));v&&(v.result=b,v.status=Fu(b),v.images=Ts(m.content),Ar.delete(v.id))}y(!0),o.length||na(),K(),we.scrollToBottom()},Bt=null,Cs=null,Ir=()=>{Cs=null,Bt!==null&&(Bt=null,Ot(ne.dataset.busy==="1"))},Dc={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})=>(Cs=String(o??"").replace(/\s+/g," ").trim().slice(0,200)||null,"Shown to the user.")},Bn=fe?fe===!0?{}:fe:null,qe=Bn?Bn.store??ho(`__runapps_agent_chat:${ke}:schedules`):null,Oc={schedule_list:()=>t.tSchedList,schedule_add:o=>t.tSchedAdd.replace("{name}",o.name??""),schedule_update:()=>t.tSchedUpdate,schedule_remove:()=>t.tSchedRemove},Nc=qe&&Bn.tools!==!1?mo(qe,{...Bn,onChange:()=>vn()}).map(o=>({...o,display:{...o.display,icon:z.clock(),label:Oc[o.name]}})):[],Ta=[...Te.tools??[],...j?[Dc]:[],...Nc],Es=new Set(Ta.filter(o=>o.display?.hidden).map(o=>o.name)),zc=o=>{for(let c of o.tools??[])c.display?.hidden&&Es.add(c.name)},gn=()=>{let o=ne.dataset.busy==="1",c=!!(re.value.trim()||Ct.length||Et.length);dn.style.display=!o&&c?"":"none",Hn.style.display=Er.style.display=tn&&o&&c?"":"none"},Ot=o=>{ne.dataset.busy=o?"1":"",re.placeholder=o&&tn?ps(t.placeholderBusy):Bt??O??t.placeholder,Eo.textContent=ps(o&&tn?t.hintBusy:Bt?t.hintNext:t.hintIdle),gn(),un.style.display=o?"":"none",St()},yn=!1,St=()=>{let o=F?.queued??[];if(It.style.display=o.length?"":"none",It.replaceChildren(),!o.length){yn=!1;return}let c=F,p=$=>Dn($.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,"").replace(/\s+/g," ").trim(),g=($,A,_)=>{let H=u("button");return H.type="button",H.innerHTML=$,H.title=A,H.setAttribute("aria-label",A),H.addEventListener("click",G=>{G.stopPropagation(),_()}),H},y=$=>{let A=u("span","ra-qa");return $.kind!=="steer"&&A.append(g(z.enter(),t.sendNow,()=>{c.dequeue?.($.message)&&c.steer?.($.message.content),St()})),A.append(g(z.pen(),t.editQueued,()=>{c.dequeue?.($.message)&&(re.value=re.value.trim()?`${p($.message)}
|
|
770
|
+
${re.value}`:p($.message),re.focus(),St())})),A.append(g(z.x(14),t.remove,()=>{c.dequeue?.($.message),St()})),A},m=$=>$.kind==="steer"?u("span","ra-qk",t.steer):null;if(It.classList.toggle("open",yn&&o.length>1),o.length===1){let $=o[0],A=u("div","ra-qr"),_=m($);A.append(u("span","ra-qn",t.queuedN.replace("{n}","1"))),_&&A.append(_),A.append(u("span","ra-qt",p($.message)),y($)),It.append(A);return}let b=u("div","ra-qr ra-qhd"),v=u("span","ra-qt");yn||(v.append(u("b","",t.queueNext)),v.append(p(o[0].message)));let E=u("span","ra-qtog");if(E.innerHTML=z.chevDown(14),E.title=yn?t.collapse:t.expand,b.append(u("span","ra-qn",t.queuedNs.replace("{n}",String(o.length))),v,E),b.addEventListener("click",()=>{yn=!yn,St()}),It.append(b),yn)for(let $ of o){let A=u("div","ra-qr"),_=m($);_&&A.append(_),A.append(u("span","ra-qt",p($.message)),y($)),It.append(A)}},Hr=o=>{je.style.display=o?"":"none",je.textContent=o??""},Wt=async()=>{let o=F?.workspace;if(!o){hs=[],sn(0);return}try{let[c,p]=await Promise.all([o.skills(),Us(o)]);F?.workspace===o&&sn(c.length),hs=[...p.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{hs=[],sn(0)}},qo=!1,Sa=()=>{let o=re.value;return qo||!o.startsWith("/")||/\s/.test(o)?[]:[...Qo(),...hs].filter(c=>`/${c.name}`.startsWith(o)).slice(0,40)},et=()=>{gn();let o=Sa();an.style.display=o.length?"":"none",an.replaceChildren(),xt>=o.length&&(xt=0),o.forEach((c,p)=>{let g=u("button",p===xt?"ra-cur":"");g.type="button",g.append(u("span","ra-cn",`/${c.name}`)),c.args&&g.append(u("span","ra-ca",c.args)),g.append(u("span","ra-badge",c.kind),u("span","ra-cd",c.description)),g.addEventListener("mousedown",y=>{y.preventDefault(),ja(c),re.focus()}),an.append(g),p===xt&&g.scrollIntoView?.({block:"nearest"})})},Fc=()=>{$r===null&&($r=requestAnimationFrame(()=>{$r=null,et()}))},Ct=[],Et=[],Wn=()=>{ln.style.display=Ct.length||Et.length?"":"none",gn()},Bo=o=>{let c=Et.findIndex(p=>p.id===o);c<0||(Et[c].chip.remove(),Et.splice(c,1),Wn())},Ca=o=>{let c=o.id??`ctx_${Math.random().toString(36).slice(2,8)}`;Bo(c),o={...o,label:o.label.replace(/\s+/g," ").trim()||"context"};let p=sa(o.label,o.title,o.icon),g=u("button");return g.type="button",g.innerHTML=z.x(),g.title=t.remove,g.setAttribute("aria-label",t.remove),g.addEventListener("click",()=>Bo(c)),p.append(g),Et.push({id:c,label:o.label,text:o.text,chip:p}),ln.prepend(p),Wn(),()=>Bo(c)},Ic=o=>{let c=Ct.indexOf(o);c>=0&&Ct.splice(c,1),o.preview&&URL.revokeObjectURL(o.preview),o.chip.remove(),Wn()},Wo=Promise.resolve(),Ur=(o,c=[])=>{let p=o?Array.from(o):[],g=Wo.then(()=>Hc(p,c));return Wo=g.catch(()=>{}),g},Hc=async(o,c)=>{if(!(I===!1||!o?.length)){for(let[p,g]of Array.from(o).entries()){if(g.size>Ku){B.notify(`${g.name} ${t.tooLarge}`,"warning");continue}let y=new Uint8Array(await g.arrayBuffer()),m=/^image\/(png|jpe?g|gif|webp)$/.test(g.type),b=m?null:ep(g,y),v=m?URL.createObjectURL(g):null,E=ra(sc(g.name),wr(g.size),v),$=u("button");$.type="button",$.innerHTML=z.x(),$.title=t.remove,$.setAttribute("aria-label",t.remove),E.append($);let A={file:g,name:sc(g.name),bytes:y,text:b,image:m,preview:v,chip:E,path:c[p]};$.addEventListener("click",()=>Ic(A)),Ct.push(A),ln.append(E)}Wn(),re.focus()}};cn.addEventListener("click",()=>ls(Ht,o=>{Ur(o)})),Ht.addEventListener("change",()=>{Ur(Ht.files),Ht.value=""}),re.addEventListener("paste",o=>{let c=Array.from(o.clipboardData?.files??[]);!c.length||o.clipboardData?.getData("text/plain")||(o.preventDefault(),Ur(c))});let Ms=0;ne.addEventListener("dragenter",o=>{I===!1||!o.dataTransfer?.types.includes("Files")||(o.preventDefault(),Ms++,ne.dataset.drop="1")}),ne.addEventListener("dragover",o=>{ne.dataset.drop&&(o.preventDefault(),o.dataTransfer.dropEffect="copy")}),ne.addEventListener("dragleave",()=>{ne.dataset.drop&&--Ms<=0&&(Ms=0,delete ne.dataset.drop)}),ne.addEventListener("drop",o=>{ne.dataset.drop&&(o.preventDefault(),Ms=0,delete ne.dataset.drop,Ur(o.dataTransfer?.files))});let Uc=async(o,c,p)=>{if(!c.length)return o;let g=Te.fileTools===!1?null:p.workspace,y=[],m=[],b=c.some(_=>_.image)&&await p.accepts("image")===!1,v=_=>/^video\//.test(_.file.type)&&_.file.size<=Zu,E=c.some(v)&&await p.accepts("video")!==!1;b&&B.notify(t.noVision.replace("{model}",p.model||(await p.modelInfo())?.id||t.sDefault),"warning");for(let _ of c){let H=_.file.type||(_.text!==null?"text/plain":"application/octet-stream");if(g){let G=_.path&&await g.exists(_.path)?_.path:await Li(g,On,_.name);G!==_.path&&await g.write(G,_.text??_.bytes,H),y.push(`- ${G} (${H}, ${wr(_.file.size)})`),Ze.refresh()}else if(sr(_.name,_.file.type,_.bytes)){let G="";try{G=ir(_.name,await or(_.bytes))}catch(te){G=`Could not read the PDF: ${te.message}`}G.length>Di&&(G=G.slice(0,Di)+`
|
|
771
|
+
[\u2026 truncated]`),y.push(`- ${_.name} (${H}, ${wr(_.file.size)}) \u2014 its text below`),m.push({type:"text",text:`<file name="${_.name}">
|
|
772
|
+
${G}
|
|
773
|
+
</file>`})}else _.text!==null&&_.text.length<=Di?(y.push(`- ${_.name} (${H}, ${wr(_.file.size)}) \u2014 contents below`),m.push({type:"text",text:`<file name="${_.name}">
|
|
774
|
+
${_.text}
|
|
775
|
+
</file>`})):y.push(`- ${_.name} (${H}, ${wr(_.file.size)}) \u2014 ${_.image&&!b?"the picture below":v(_)&&E?"the video below":"not readable here"}`);if(v(_)&&E){let G=await new Promise(te=>{let he=new FileReader;he.onload=()=>te(String(he.result)),he.readAsDataURL(_.file)});m.push({type:"video_url",video_url:{url:G}})}if(_.image&&!b&&_.file.size<=Vu){if(en){try{m.push({type:"image_url",image_url:{url:await en(_.file)}})}catch(te){B.notify(`${_.name}: ${te?.message||String(te)}`,"error")}continue}let G=await new Promise(te=>{let he=new FileReader;he.onload=()=>te(String(he.result)),he.readAsDataURL(_.file)});m.push({type:"image_url",image_url:{url:G}})}}let $=g?`${Qt} files the user attached, saved in the directory (read them with read_file):`:`${Qt} files the user attached:`,A=[];return o&&A.push({type:"text",text:o}),A.push({type:"text",text:`${$}
|
|
769
776
|
${y.join(`
|
|
770
|
-
`)}`}),A.push(...
|
|
771
|
-
${M.text}`}))),g=b}}catch(b){Y.value=c,Et.unshift(...m);for(let x of m.slice().reverse())xt.prepend(x.chip);Mt.unshift(...y);for(let x of y.slice().reverse())xt.prepend(x.chip);Fn(),Nr(b.message);return}finally{Ho=!1}for(let b of m)b.preview&&URL.revokeObjectURL(b.preview);p.busy||(o="prompt");try{if(o==="prompt"){z===p&&!p.busy&&(Tt=$r(g)),await p.prompt(g);return}o==="steer"?p.steer(g):p.followUp(g).catch(()=>{}),Ct()}catch(b){Tt=null,Nr(b.message)}};Y.addEventListener("input",()=>{zo=!1,Y.value&&Or(),un(),Lc()}),Y.addEventListener("keydown",o=>{if(o.isComposing||o.keyCode===229)return;let c=ya();if(c.length){if(o.key==="ArrowDown"){o.preventDefault(),kt=(kt+1)%c.length,nt();return}if(o.key==="ArrowUp"){o.preventDefault(),kt=(kt-1+c.length)%c.length,nt();return}if(o.key==="Tab"){o.preventDefault(),Y.value=`/${c[kt].name} `,nt();return}if(o.key==="Enter"&&!o.shiftKey){o.preventDefault(),Oa(c[kt]);return}if(o.key==="Escape"){zo=!0,bt.style.display="none";return}}if(Vt&&!Y.value&&o.key==="Tab"&&!o.shiftKey){o.preventDefault(),Y.value=Vt,Or(),un();return}if(Vt&&!Y.value&&o.key==="Escape"){Or();return}if(o.key!=="Enter"||o.shiftKey)return;o.preventDefault();let p=o.metaKey||o.ctrlKey||o.altKey;Hn(z?.busy?p?"followUp":"steer":"prompt")}),Y.addEventListener("blur",()=>{bt.style.display="none"}),Y.addEventListener("focus",()=>nt()),on.addEventListener("click",()=>{Hn("prompt")}),Rn.addEventListener("click",()=>{Hn("steer")}),kr.addEventListener("click",()=>{Hn("followUp")}),an.addEventListener("click",()=>{q.cancelAll(),z?.abort()}),tt.addEventListener("click",o=>{let c=o.target,p=Ce?c.closest("a[href]"):null;if(p&&Ce){let g=!1;try{g=Ce(p.getAttribute("href")??"",p.textContent??"")===!0}catch(b){console.warn("agent: onLink failed",b)}if(g){o.preventDefault();return}}let m=c.closest(".ra-path");if(m?.dataset.path){o.preventDefault(),Ar(m.dataset.path);return}let y=c.closest(".ra-md a[href]");if(y&&z?.workspace){let g=y.getAttribute("href")??"";if(g.startsWith("/")&&!g.startsWith("//")){o.preventDefault(),z.workspace.exists(g).then(x=>{x?Ar(g):window.open(y.href,"_blank","noopener")});return}}});let Gt={summarize:J.compaction!==!1,...typeof J.compaction=="object"?J.compaction:{}},Uo=`__runapps_agent_chat:${Pe}:settings`,Dc=()=>{try{return JSON.parse(localStorage.getItem(Uo)||"{}")}catch{return{}}},ba=o=>{try{Object.keys(o).length?localStorage.setItem(Uo,JSON.stringify(o)):localStorage.removeItem(Uo)}catch{}},Ke=l?{}:Dc(),xa=e.settings??!l,va=0;xa||(ot.style.display="none");let fn=null,jo=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},ka=(o,c,p)=>{let m=J.extra?.reasoning_effort;o.configure({model:c.model??J.model,maxTurns:c.maxTurns??J.maxTurns??100,maxTokens:c.maxTokens??(typeof J.maxTokens=="number"?J.maxTokens:"auto"),permissions:p??J.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof m=="string"?m:null),compaction:{summarize:c.summarize??Gt.summarize,reserveTokens:c.reserveTokens??Gt.reserveTokens,keepRecentTokens:c.keepRecentTokens??Gt.keepRecentTokens}}),rt.textContent=o.model??"",rt.style.display=o.model?"":"none"},Ts=o=>{Ke=o,ba(o);for(let c of He.values())ka(c,o,Tr);At(z)},Un=async()=>{if(Re?.models)try{fn??(fn=(await Re.models()).filter(o=>!o.capability||o.capability==="text"||o.capability==="vision"))}catch{}return fn??[]};Ke.model&&Re?.models&&Un().then(o=>{if(!o.length||!Ke.model||o.some(m=>m.id===Ke.model))return;let{model:c,...p}=Ke;Ts(p)});let Ss=o=>typeof o=="number"?o>=1e3?`${Math.round(o/1e3)}k`:String(o):"?",Ta=o=>{let c=o?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let p=t.sPriceLine.replace("{in}",as(c.input??0,c.currency)).replace("{out}",as(c.output??0,c.currency));return c.per_call?`${p} \xB7 ${t.sPerCall.replace("{amount}",as(c.per_call,c.currency))}`:p},qo=async()=>{if(Te){_e();return}if(!z)return;let o=z,c=u("div","ra-menu ra-set");Te=c,Ir(c);let p=o.settings,m=(Q,fe)=>{let ie=En(oe,{options:Q,value:fe,filterLabel:t.filter});return hn.push(ie),ie},y=m([{value:"",label:t.sDefault}],""),g=u("div","ra-lim"),b=m([],""),x=u("div","ra-lim"),M=()=>{let Q=y.value||fn?.find(fe=>fe.is_default)?.id;return fn?.find(fe=>fe.id===Q)},E=()=>{let Q=M(),fe=Yt(Q,"image"),ie=Ta(Q);g.textContent=Q?`${t.context} ${Ss(Q.max_input_tokens)} \xB7 ${t.sMaxTokens} ${Ss(Q.max_tokens)}${fe===void 0?"":` \xB7 ${fe?t.sVisionYes:t.sVisionNo}`}${ie?` \xB7 ${t.sPrice}: ${ie}`:""}`:"";let ye=jo(Q),Me=b.value;b.setOptions([{value:"",label:t.sEffortDefault,note:ye?.def},...(ye?.levels??[]).map(Ae=>({value:Ae,label:Ae}))]),b.disabled=!ye,b.value=ye&&ye.levels.includes(Me)?Me:"",x.textContent=ye?"":t.sEffortNone,x.style.display=ye?"none":""};y.el.addEventListener("change",E);let A=[];if(Re?.models){if(await Un(),Te!==c)return;let Q=fn?.find(fe=>fe.is_default);A.push({value:"",label:t.sDefault,note:Q?.id});for(let fe of fn??[]){let ie=fe.price,ye=ie&&(ie.input!==void 0||ie.output!==void 0)?` \xB7 ${as(ie.input??0,ie.currency)} / ${as(ie.output??0,ie.currency)}`:"";A.push({value:fe.id,label:fe.id,note:`${Yt(fe,"image")?`${t.sVision} \xB7 `:""}${Ss(fe.max_input_tokens)} / ${Ss(fe.max_tokens)}${ye}`})}}else A.push({value:"",label:t.sDefault});p.model&&!A.some(Q=>Q.value===p.model)&&A.push({value:p.model,label:p.model}),y.setOptions(A),y.value=p.model??"",E(),p.reasoningEffort&&b.options.some(Q=>Q.value===p.reasoningEffort)&&(b.value=p.reasoningEffort);let R=u("input");R.type="number",R.min="1",R.max="1000",R.step="1",R.value=String(p.maxTurns);let F=m([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),V=u("input");V.type="number",V.min="256",V.step="256",V.value=String(typeof p.maxTokens=="number"?p.maxTokens:8192),F.value=typeof p.maxTokens=="number"?"n":"auto",V.style.display=F.value==="n"?"":"none",F.el.addEventListener("change",()=>{V.style.display=F.value==="n"?"":"none"});let re=m([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...p.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],p.permissions),pe=(Q,...fe)=>{let ie=u("div","ra-fld");return ie.append(u("span","",Q),...fe),ie},me=u("div","ra-row");me.append(F.el,V);let Qe=u("div","ra-pane");Qe.append(pe(t.sModel,y.el),g,pe(t.sEffort,b.el),x,pe(t.sMaxTurns,R),pe(t.sMaxTokens,me)),B!==!1&&Qe.append(pe(t.sPerms,re.el));let Ge=p.compaction,Je=m([{value:"summary",label:t.sCompactSummary},{value:"trim",label:t.sCompactTrim}],Ge.summarize===!1?"trim":"summary"),at=(Q,fe)=>{let ie=m([{value:"auto",label:t.sDefaultN.replace("{n}",Ye(fe))},{value:"n",label:t.sCustomN}],Q!==void 0&&Q!==fe?"n":"auto"),ye=u("input");ye.type="number",ye.min="1024",ye.step="1024",ye.value=String(Q??fe);let Me=u("div","ra-row");Me.append(ie.el,ye);let Ae=()=>{ye.style.display=ie.value==="n"?"":"none"};return ie.el.addEventListener("change",Ae),Ae(),{row:Me,read:()=>{if(ie.value!=="n")return;let Xo=parseInt(ye.value,10);return Number.isFinite(Xo)&&Xo>=1024?Xo:void 0},mode:ie,input:ye}},$t=at(Ge.reserveTokens,Gt.reserveTokens??xn.reserveTokens),mt=at(Ge.keepRecentTokens,Gt.keepRecentTokens??xn.keepRecentTokens),Fr=pe(t.sKeepRecent,mt.row),wn=u("div","ra-lim"),Kn=()=>{let Q=Je.value==="summary";Fr.style.display=Q?"":"none";let fe=M(),ie=J.maxInputTokens,ye=typeof fe?.max_input_tokens=="number"&&fe.max_input_tokens>0?fe.max_input_tokens:128e3,Me=typeof ie=="number"?Math.min(ie,ye):ye,Ae=Xt(Me,{reserveTokens:$t.read()??Gt.reserveTokens,keepRecentTokens:mt.read()??Gt.keepRecentTokens}),Ba=fe?.id??(y.value||t.sDefault);wn.textContent=(Q?t.sCompactNote.replace("{keep}",Ye(Ae.keepRecentTokens)):t.sCompactNoteTrim).replace("{model}",Ba).replace("{at}",Ye(Ae.reserveTokens)).replace("{window}",Ye(Me))};for(let Q of[Je.el,y.el,$t.mode.el,mt.mode.el])Q.addEventListener("change",Kn);for(let Q of[$t.input,mt.input])Q.addEventListener("input",Kn);Kn();let Hr=u("div","ra-pane");Hr.append(pe(t.sCompact,Je.el),pe(t.sCompactAt,$t.row),Fr,wn);let bn=[],Vn=Q=>{let fe=u("div","ra-pane");for(let ie of Q.fields){if(ie instanceof HTMLElement){ie.classList.add("ra-host"),fe.append(ie);continue}if(ie.type==="toggle"){let ye=u("label","ra-tgl"),Me=u("input");Me.type="checkbox",Me.checked=ie.value();let Ae=u("span","",ie.label);ie.hint&&Ae.append(u("small","",ie.hint)),ye.append(Me,Ae),fe.append(ye),bn.push(()=>{Me.checked!==ie.value()&&ie.onChange(Me.checked)})}else{let ye=m(ie.options,ie.value()),Me=pe(ie.label,ye.el);ie.hint&&Me.append(u("small","",ie.hint)),fe.append(Me),bn.push(()=>{ye.value!==ie.value()&&ie.onChange(ye.value)})}}return fe},xe=[Qe,Hr,...(Fe??[]).map(Vn)];if(xe.length>1){let Q=u("div","ra-tabs");Q.setAttribute("role","tablist");let fe=[t.sTabModel,t.sTabContext,...(Fe??[]).map(ye=>ye.label)].map((ye,Me)=>{let Ae=u("button","ra-tab",ye);return Ae.type="button",Ae.setAttribute("role","tab"),Ae.addEventListener("click",()=>ie(Me)),Ae}),ie=ye=>{va=ye,xe.forEach((Me,Ae)=>{Me.hidden=Ae!==ye}),fe.forEach((Me,Ae)=>{Me.classList.toggle("on",Ae===ye),Me.setAttribute("aria-selected",String(Ae===ye))})};Q.append(...fe),Te.append(Q,...xe),ie(Math.min(va,xe.length-1))}else Te.append(Qe);let Oe=u("div","ra-btns"),gt=u("button","ra-btn xs ghost",t.reset);gt.type="button";let Yo=u("button","ra-btn xs solid",t.apply);Yo.type="button",Oe.append(gt,Yo),Te.append(Oe),gt.addEventListener("click",()=>{for(let Q of(Fe??[]).flatMap(fe=>fe.fields))Q instanceof HTMLElement||Q.default===void 0||(Q.type,Q.value()!==Q.default&&Q.onChange(Q.default));Ke={},ba({}),ko(null,!0);for(let Q of He.values())ka(Q,{},null);_e(),q.notify(t.applied),At(z)}),Yo.addEventListener("click",()=>{let Q={};y.value&&(Q.model=y.value);let fe=parseInt(R.value,10);if(Number.isFinite(fe)&&fe>0&&Math.min(1e3,fe)!==(J.maxTurns??100)&&(Q.maxTurns=Math.min(1e3,fe)),F.value==="n"){let Ae=parseInt(V.value,10);Number.isFinite(Ae)&&Ae>0&&(Q.maxTokens=Ae)}b.value&&!b.disabled&&(Q.reasoningEffort=b.value),(re.value==="ask"||re.value==="auto")&&re.value!==(vo()?"auto":"ask")&&ko(re.value);let ie=Je.value==="summary";ie!==Gt.summarize&&(Q.summarize=ie);let ye=$t.read();ye!==void 0&&(Q.reserveTokens=ye);let Me=mt.read();Me!==void 0&&(Q.keepRecentTokens=Me);for(let Ae of bn)Ae();Ts(Q),_e(),q.notify(t.applied)})};ot.addEventListener("click",()=>{qo()});let hn=[],_e=()=>{Te?.remove(),Te=null;for(let o of hn.splice(0))o.close()},Ir=o=>{oe.append(o),o.style.top=`${nn.offsetTop+nn.offsetHeight+4}px`},Sa=async()=>{if(Te){_e();return}if(!z?.workspace)return;let o=z.workspace,c=u("div","ra-menu");Te=c,Ir(c);let p=[];try{p=await o.sessions.list()}catch{}if(Te!==c)return;let m=z,y=p.filter(x=>x.id!==m.id),g=p.find(x=>x.id===m.id),b=x=>{let M=!x||x.id===m.id,E=u("div","ra-mi"+(M?" ra-cur":"")),A=u("button");A.type="button";let R=x?He.get(x.id):void 0,F=x&&R&&R!==m?Wt.has(x.id)?` \xB7 ${t.waitingAnswer}`:R.busy||R.queued.length?` \xB7 ${t.running}`:"":"",V=u("span","ra-mt");if(F&&!Wt.has(x.id)&&V.append(u("span","ra-spin")),V.append(u("span","ra-mtt",(x?x.title:fs(m))||t.untitled)),M&&(V.append(u("span","ra-now",t.current)),E.setAttribute("aria-current","true")),A.append(V,u("small","",x?`${x.messages} ${t.messages} \xB7 ${new Date(x.savedAt).toLocaleString()}${F}`:t.notSaved)),A.addEventListener("click",()=>{_e(),x&&!M&&Go(x.id).catch(re=>q.notify(re.message,"error"))}),E.append(A),x){let re=u("button","ra-x");re.type="button",re.innerHTML=N.trash(),re.title=t.delete,re.setAttribute("aria-label",t.delete),re.addEventListener("click",async pe=>{pe.stopPropagation(),_e(),await wt(oe,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await Jo(x.id,!1,x.workspace).catch(me=>q.notify(me.message,"error"))}),E.append(re)}return E};c.append(b(g??null)),y.length?c.append(u("div","ra-sep")):c.append(u("div","ra-none",t.noSessions));for(let x of y)c.append(b(x));if(y.length){let x=u("div","ra-mf"),M=u("button","ra-btn xs ghost");M.type="button",M.innerHTML=N.trash()+Se(t.deleteAll),M.addEventListener("click",async()=>{if(_e(),!!await wt(oe,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let E of p)await Jo(E.id,!0,E.workspace);await Wn()}catch(E){q.notify(E.message,"error")}}),x.append(M),c.append(x)}};We.addEventListener("click",()=>{Sa()}),Rt.addEventListener("click",()=>{_e(),Wn().catch(o=>q.notify(o.message,"error"))}),ft.addEventListener("click",async()=>{_e(),await wt(oe,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await $s().catch(o=>q.notify(o.message,"error"))}),document.addEventListener("click",Ca,!0);function Ca(o){o.target?.closest?.(".ra-selp")||Te&&!Te.contains(o.target)&&!We.contains(o.target)&&!ot.contains(o.target)&&!pt.contains(o.target)&&!je.contains(o.target)&&!st.contains(o.target)&&_e()}let Ft=u("input");Ft.type="file",Ft.accept=".zip,application/zip",Ft.multiple=!0,Ft.style.display="none",oe.append(Ft);let Bo=async o=>{let c=z?.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"){q.notify(`${m.name}: ${t.notZip}`,"warning");continue}try{p.push(...(await c.installSkill(m)).map(y=>y.name))}catch(y){q.notify(`${m.name}: ${y.message}`,"error")}}p.length&&q.notify(t.skillsInstalled.replace("{names}",p.join(", "))),await Zt(),Te?.classList.contains("ra-skm")&&(_e(),Ea())};Ft.addEventListener("change",()=>{Bo(Ft.files),Ft.value=""});let Ea=async()=>{if(Te){let g=Te.classList.contains("ra-skm");if(_e(),g)return}let o=z?.workspace;if(!o)return;let c=u("div","ra-menu ra-skm");Te=c,Ir(c);let p=[];try{p=await o.skills()}catch(g){q.notify(g.message,"error")}if(Te!==c)return;let m=u("div","ra-skh"),y=u("button","ra-btn xs solid");y.type="button",y.innerHTML=N.upload(13)+`<span>${Se(t.uploadZip)}</span>`,y.addEventListener("click",()=>ss(Ft,g=>{Bo(g)})),o.userSkillsDir||(y.style.display="none"),m.append(u("span","",p.length?`${t.skills} \xB7 ${p.length}`:t.skills),y),c.append(m),p.length||c.append(u("div","ra-none",t.noSkills));for(let g of p){let b=u("div","ra-mi"),x=u("button");x.type="button",x.title=t.useSkill;let M=u("span","ra-mt"),E=!!g.from&&/\.zip$/i.test(g.from);M.append(u("span","ra-mtt",g.name),u("span","ra-skb",g.builtin?t.builtinSkill:E?"zip":t.skillFolder)),g.disableModelInvocation&&M.append(u("span","ra-skb",t.manualOnly)),x.append(M,u("small","",g.description)),x.addEventListener("click",()=>{_e(),Y.value=`/skill:${g.name} `,Y.focus(),nt()});let A=(re,pe,me,Qe="ra-x ra-ia")=>{let Ge=u("button",Qe);return Ge.type="button",Ge.innerHTML=re,Ge.title=pe,Ge.setAttribute("aria-label",pe),Ge.addEventListener("click",Je=>{Je.stopPropagation(),me()}),Ge},R=A(N.eye(),t.open,()=>{_e(),Ar(g.from&&!E?`${g.from}/SKILL.md`:g.path)}),F=A(N.download(),t.download,()=>{E?Ze.download(g.from):Ze.downloadFolder(g.from??g.dir)}),V=A(N.trash(),t.delete,async()=>{_e();let re=E?p.filter(me=>me.from===g.from).map(me=>me.name):[g.name],pe=re.length>1?t.confirmDeleteZip.replace("{zip}",g.from.replace(/^.*\//,"")).replace("{names}",re.join("\u3001")):t.confirmDeleteSkill.replace("{name}",g.name).replace("{path}",g.from??"");if(await wt(oe,t.delete,pe,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await o.removeSkill(g.name),await Zt(),q.notify(t.skillRemoved.replace("{name}",re.join(", ")))}catch(me){q.notify(me.message,"error")}},"ra-x");(g.builtin||!g.from?.startsWith((o.userSkillsDir??"\0")+"/"))&&(V.style.display="none"),b.append(x,R,F,V),c.append(b)}c.append(u("div","ra-skf",(o.userSkillsDir?t.skillsHint.replace("{user}",o.userSkillsDir):t.skillsHintNoUser).replace("{dir}",o.skillsDir))),o.userSkillsDir&&c.addEventListener("dragover",g=>{g.dataTransfer?.types.includes("Files")&&(g.preventDefault(),g.stopPropagation(),c.classList.add("drop"))}),c.addEventListener("dragleave",()=>c.classList.remove("drop")),o.userSkillsDir&&c.addEventListener("drop",g=>{g.preventDefault(),g.stopPropagation(),c.classList.remove("drop"),Bo(g.dataTransfer?.files)})};pt.addEventListener("click",()=>{Ea()}),qe||(je.style.display="none");let jn={minMinutes:In?.minMinutes,maxTasks:In?.maxTasks},Oc=t.schedDayNames.split(","),Nc=/[\u4e00-\u9fff]/.test(t.sched),Ma=o=>{let c=ct(o);return c.slice(0,4)===String(new Date().getFullYear())?c.slice(5):c},zc=async o=>{await yn;let c=`${t.schedRunHead.replace("{name}",o.name).replace("{time}",ct(Date.now()))}
|
|
777
|
+
`)}`}),A.push(...m),A},Ko=!1,Kn=async o=>{await Wo;let c=re.value.trim();if(!c&&!Ct.length&&!Et.length||!F||Ko||(Ir(),Xc(c))||!tn&&(F.busy||kn))return;kn&&(o="followUp");let p=F,g=Ct.splice(0);for(let b of g)b.chip.remove();let y=Et.splice(0);for(let b of y)b.chip.remove();Wn(),re.value="",et(),Hr(),Ko=!0;let m;try{if(m=await Uc(c,g,p),y.length){let b=typeof m=="string"?m?[{type:"text",text:m}]:[]:m,v=b.length&&b[0].type==="text"&&!b[0].text.startsWith(Qt)?1:0;b.splice(v,0,...y.map(E=>({type:"text",text:`${xr}${E.label}
|
|
778
|
+
${E.text}`}))),m=b}}catch(b){re.value=c,Ct.unshift(...g);for(let v of g.slice().reverse())ln.prepend(v.chip);Et.unshift(...y);for(let v of y.slice().reverse())ln.prepend(v.chip);Wn(),Hr(b.message);return}finally{Ko=!1}for(let b of g)b.preview&&URL.revokeObjectURL(b.preview);p.busy||(o="prompt");try{if(o==="prompt"){F===p&&!p.busy&&(kt=Rr(m)),await p.prompt(m);return}o==="steer"?p.steer?.(m):p.followUp?.(m).catch(()=>{}),St()}catch(b){kt=null,Hr(b.message)}};re.addEventListener("input",()=>{qo=!1,re.value&&Ir(),gn(),Fc()}),re.addEventListener("keydown",o=>{if(o.isComposing||o.keyCode===229)return;let c=Sa();if(c.length){if(o.key==="ArrowDown"){o.preventDefault(),xt=(xt+1)%c.length,et();return}if(o.key==="ArrowUp"){o.preventDefault(),xt=(xt-1+c.length)%c.length,et();return}if(o.key==="Tab"){o.preventDefault(),re.value=`/${c[xt].name} `,et();return}if(o.key==="Enter"&&!o.shiftKey){o.preventDefault(),ja(c[xt]);return}if(o.key==="Escape"){qo=!0,an.style.display="none";return}}if(Bt&&!re.value&&o.key==="Tab"&&!o.shiftKey){o.preventDefault(),re.value=Bt,Ir(),gn();return}if(Bt&&!re.value&&o.key==="Escape"){Ir();return}if(o.key!=="Enter"||o.shiftKey)return;o.preventDefault();let p=o.metaKey||o.ctrlKey||o.altKey;Kn(F?.busy?p?"followUp":"steer":"prompt")}),re.addEventListener("blur",()=>{an.style.display="none"}),re.addEventListener("focus",()=>et()),dn.addEventListener("click",()=>{Kn("prompt")}),Hn.addEventListener("click",()=>{Kn("steer")}),Er.addEventListener("click",()=>{Kn("followUp")}),un.addEventListener("click",()=>{B.cancelAll(),F?.abort()}),de.addEventListener("click",o=>{let c=o.target,p=Me?c.closest("a[href]"):null;if(p&&Me){let m=!1;try{m=Me(p.getAttribute("href")??"",p.textContent??"")===!0}catch(b){console.warn("agent: onLink failed",b)}if(m){o.preventDefault();return}}let g=c.closest(".ra-path");if(g?.dataset.path){o.preventDefault(),_r(g.dataset.path);return}let y=c.closest(".ra-md a[href]");if(y&&F?.workspace){let m=y.getAttribute("href")??"";if(m.startsWith("/")&&!m.startsWith("//")){o.preventDefault(),F.workspace.exists(m).then(v=>{v?_r(m):window.open(y.href,"_blank","noopener")});return}}});let Kt={summarize:Te.compaction!==!1,...typeof Te.compaction=="object"?Te.compaction:{}},Vo=`__runapps_agent_chat:${ke}:settings`,jc=()=>{try{return JSON.parse(localStorage.getItem(Vo)||"{}")}catch{return{}}},Ea=o=>{try{Object.keys(o).length?localStorage.setItem(Vo,JSON.stringify(o)):localStorage.removeItem(Vo)}catch{}},Ke=l?{}:jc(),Ma=e.settings??!l,Aa=0;Ma||(Z.style.display="none");let wn=null,Zo=o=>{let c=o?.options?.inputs?.reasoning_effort;if(!c)return null;let p=(c.enum??[]).filter(g=>typeof g=="string");return p.length?{levels:p,def:typeof c.default=="string"?c.default:void 0}:null},$a=(o,c,p)=>{let g=Te.extra?.reasoning_effort;o.configure({model:c.model??Te.model,maxTurns:c.maxTurns??Te.maxTurns??100,maxTokens:c.maxTokens??(typeof Te.maxTokens=="number"?Te.maxTokens:"auto"),permissions:p??Te.permissions??"ask",reasoningEffort:c.reasoningEffort??(typeof g=="string"?g:null),compaction:{summarize:c.summarize??Kt.summarize,reserveTokens:c.reserveTokens??Kt.reserveTokens,keepRecentTokens:c.keepRecentTokens??Kt.keepRecentTokens}}),at.textContent=o.model??"",at.style.display=o.model?"":"none"},As=o=>{Ke=o,Ea(o);for(let c of Ie.values())$a(c,o,Mr);ft(F)},Vn=async()=>{if(wt?.models)try{wn??(wn=(await wt.models()).filter(o=>!o.capability||o.capability==="text"||o.capability==="vision"))}catch{}return wn??[]};Ke.model&&wt?.models&&Vn().then(o=>{if(!o.length||!Ke.model||o.some(g=>g.id===Ke.model))return;let{model:c,...p}=Ke;As(p)});let $s=o=>typeof o=="number"?o>=1e3?`${Math.round(o/1e3)}k`:String(o):"?",La=o=>{let c=o?.price;if(!c||c.input===void 0&&c.output===void 0)return"";let p=t.sPriceLine.replace("{in}",us(c.input??0,c.currency)).replace("{out}",us(c.output??0,c.currency));return c.per_call?`${p} \xB7 ${t.sPerCall.replace("{amount}",us(c.per_call,c.currency))}`:p},Go=async()=>{if(Se){Re();return}if(!F)return;let o=F,c=u("div","ra-menu ra-set");Se=c,jr(c);let p=o.settings,g=(X,me)=>{let ce=_n(ne,{options:X,value:me,filterLabel:t.filter});return bn.push(ce),ce},y=g([{value:"",label:t.sDefault}],""),m=u("div","ra-lim"),b=g([],""),v=u("div","ra-lim"),E=()=>{let X=y.value||wn?.find(me=>me.is_default)?.id;return wn?.find(me=>me.id===X)},$=()=>{let X=E(),me=Zt(X,"image"),ce=La(X);m.textContent=X?`${t.context} ${$s(X.max_input_tokens)} \xB7 ${t.sMaxTokens} ${$s(X.max_tokens)}${me===void 0?"":` \xB7 ${me?t.sVisionYes:t.sVisionNo}`}${ce?` \xB7 ${t.sPrice}: ${ce}`:""}`:"";let ye=Zo(X),Ae=b.value;b.setOptions([{value:"",label:t.sEffortDefault,note:ye?.def},...(ye?.levels??[]).map($e=>({value:$e,label:$e}))]),b.disabled=!ye,b.value=ye&&ye.levels.includes(Ae)?Ae:"",v.textContent=ye?"":t.sEffortNone,v.style.display=ye?"none":""};y.el.addEventListener("change",$);let A=[];if(wt?.models){if(await Vn(),Se!==c)return;let X=wn?.find(me=>me.is_default);A.push({value:"",label:t.sDefault,note:X?.id});for(let me of wn??[]){let ce=me.price,ye=ce&&(ce.input!==void 0||ce.output!==void 0)?` \xB7 ${us(ce.input??0,ce.currency)} / ${us(ce.output??0,ce.currency)}`:"";A.push({value:me.id,label:me.id,note:`${Zt(me,"image")?`${t.sVision} \xB7 `:""}${$s(me.max_input_tokens)} / ${$s(me.max_tokens)}${ye}`})}}else A.push({value:"",label:t.sDefault});p.model&&!A.some(X=>X.value===p.model)&&A.push({value:p.model,label:p.model}),y.setOptions(A),y.value=p.model??"",$(),p.reasoningEffort&&b.options.some(X=>X.value===p.reasoningEffort)&&(b.value=p.reasoningEffort);let _=u("input");_.type="number",_.min="1",_.max="1000",_.step="1",_.value=String(p.maxTurns);let H=g([{value:"auto",label:t.sAuto},{value:"n",label:t.sCustomN}],"auto"),G=u("input");G.type="number",G.min="256",G.step="256",G.value=String(typeof p.maxTokens=="number"?p.maxTokens:8192),H.value=typeof p.maxTokens=="number"?"n":"auto",G.style.display=H.value==="n"?"":"none",H.el.addEventListener("change",()=>{G.style.display=H.value==="n"?"":"none"});let te=g([{value:"ask",label:t.sAsk},{value:"auto",label:t.sAutoPerm},...p.permissions==="custom"?[{value:"custom",label:t.sCustom}]:[]],p.permissions),he=(X,...me)=>{let ce=u("div","ra-fld");return ce.append(u("span","",X),...me),ce},ge=u("div","ra-row");ge.append(H.el,G);let Xe=u("div","ra-pane");Xe.append(he(t.sModel,y.el),m,he(t.sEffort,b.el),v,he(t.sMaxTurns,_),he(t.sMaxTokens,ge)),W!==!1&&Xe.append(he(t.sPerms,te.el));let Ge=p.compaction,Je=g([{value:"summary",label:t.sCompactSummary},{value:"trim",label:t.sCompactTrim}],Ge.summarize===!1?"trim":"summary"),rt=(X,me)=>{let ce=g([{value:"auto",label:t.sDefaultN.replace("{n}",Ye(me))},{value:"n",label:t.sCustomN}],X!==void 0&&X!==me?"n":"auto"),ye=u("input");ye.type="number",ye.min="1024",ye.step="1024",ye.value=String(X??me);let Ae=u("div","ra-row");Ae.append(ce.el,ye);let $e=()=>{ye.style.display=ce.value==="n"?"":"none"};return ce.el.addEventListener("change",$e),$e(),{row:Ae,read:()=>{if(ce.value!=="n")return;let si=parseInt(ye.value,10);return Number.isFinite(si)&&si>=1024?si:void 0},mode:ce,input:ye}},Mt=rt(Ge.reserveTokens,Kt.reserveTokens??En.reserveTokens),ht=rt(Ge.keepRecentTokens,Kt.keepRecentTokens??En.keepRecentTokens),qr=he(t.sKeepRecent,ht.row),Sn=u("div","ra-lim"),Yn=()=>{let X=Je.value==="summary";qr.style.display=X?"":"none";let me=E(),ce=Te.maxInputTokens,ye=typeof me?.max_input_tokens=="number"&&me.max_input_tokens>0?me.max_input_tokens:128e3,Ae=typeof ce=="number"?Math.min(ce,ye):ye,$e=Gt(Ae,{reserveTokens:Mt.read()??Kt.reserveTokens,keepRecentTokens:ht.read()??Kt.keepRecentTokens}),Ya=me?.id??(y.value||t.sDefault);Sn.textContent=(X?t.sCompactNote.replace("{keep}",Ye($e.keepRecentTokens)):t.sCompactNoteTrim).replace("{model}",Ya).replace("{at}",Ye($e.reserveTokens)).replace("{window}",Ye(Ae))};for(let X of[Je.el,y.el,Mt.mode.el,ht.mode.el])X.addEventListener("change",Yn);for(let X of[Mt.input,ht.input])X.addEventListener("input",Yn);Yn();let Br=u("div","ra-pane");Br.append(he(t.sCompact,Je.el),he(t.sCompactAt,Mt.row),qr,Sn);let Cn=[],Xn=X=>{let me=u("div","ra-pane");for(let ce of X.fields){if(ce instanceof HTMLElement){ce.classList.add("ra-host"),me.append(ce);continue}if(ce.type==="toggle"){let ye=u("label","ra-tgl"),Ae=u("input");Ae.type="checkbox",Ae.checked=ce.value();let $e=u("span","",ce.label);ce.hint&&$e.append(u("small","",ce.hint)),ye.append(Ae,$e),me.append(ye),Cn.push(()=>{Ae.checked!==ce.value()&&ce.onChange(Ae.checked)})}else{let ye=g(ce.options,ce.value()),Ae=he(ce.label,ye.el);ce.hint&&Ae.append(u("small","",ce.hint)),me.append(Ae),Cn.push(()=>{ye.value!==ce.value()&&ce.onChange(ye.value)})}}return me},xe=[Xe,Br,...(Fe??[]).map(Xn)];if(xe.length>1){let X=u("div","ra-tabs");X.setAttribute("role","tablist");let me=[t.sTabModel,t.sTabContext,...(Fe??[]).map(ye=>ye.label)].map((ye,Ae)=>{let $e=u("button","ra-tab",ye);return $e.type="button",$e.setAttribute("role","tab"),$e.addEventListener("click",()=>ce(Ae)),$e}),ce=ye=>{Aa=ye,xe.forEach((Ae,$e)=>{Ae.hidden=$e!==ye}),me.forEach((Ae,$e)=>{Ae.classList.toggle("on",$e===ye),Ae.setAttribute("aria-selected",String($e===ye))})};X.append(...me),Se.append(X,...xe),ce(Math.min(Aa,xe.length-1))}else Se.append(Xe);let Oe=u("div","ra-btns"),mt=u("button","ra-btn xs ghost",t.reset);mt.type="button";let ri=u("button","ra-btn xs solid",t.apply);ri.type="button",Oe.append(mt,ri),Se.append(Oe),mt.addEventListener("click",()=>{for(let X of(Fe??[]).flatMap(me=>me.fields))X instanceof HTMLElement||X.default===void 0||(X.type,X.value()!==X.default&&X.onChange(X.default));Ke={},Ea({}),Lo(null,!0);for(let X of Ie.values())$a(X,{},null);Re(),B.notify(t.applied),ft(F)}),ri.addEventListener("click",()=>{let X={};y.value&&(X.model=y.value);let me=parseInt(_.value,10);if(Number.isFinite(me)&&me>0&&Math.min(1e3,me)!==(Te.maxTurns??100)&&(X.maxTurns=Math.min(1e3,me)),H.value==="n"){let $e=parseInt(G.value,10);Number.isFinite($e)&&$e>0&&(X.maxTokens=$e)}b.value&&!b.disabled&&(X.reasoningEffort=b.value),(te.value==="ask"||te.value==="auto")&&te.value!==($o()?"auto":"ask")&&Lo(te.value);let ce=Je.value==="summary";ce!==Kt.summarize&&(X.summarize=ce);let ye=Mt.read();ye!==void 0&&(X.reserveTokens=ye);let Ae=ht.read();Ae!==void 0&&(X.keepRecentTokens=Ae);for(let $e of Cn)$e();As(X),Re(),B.notify(t.applied)})};Z.addEventListener("click",()=>{Go()});let bn=[],Re=()=>{Se?.remove(),Se=null;for(let o of bn.splice(0))o.close()},jr=o=>{ne.append(o),o.style.top=`${it.offsetTop+it.offsetHeight+4}px`},Pa=async()=>{if(Se){Re();return}if(!F?.workspace)return;let o=F.workspace,c=u("div","ra-menu");Se=c,jr(c);let p=[];try{p=await o.sessions.list()}catch{}if(Se!==c)return;let g=F,y=p.filter(v=>v.id!==g.id),m=p.find(v=>v.id===g.id),b=v=>{let E=!v||v.id===g.id,$=u("div","ra-mi"+(E?" ra-cur":"")),A=u("button");A.type="button";let _=v?Ie.get(v.id):void 0,H=v&&_&&_!==g?jt.has(v.id)?` \xB7 ${t.waitingAnswer}`:_.busy||_.queued?.length?` \xB7 ${t.running}`:"":"",G=u("span","ra-mt");if(H&&!jt.has(v.id)&&G.append(u("span","ra-spin")),G.append(u("span","ra-mtt",(v?v.title:gs(g))||t.untitled)),E&&(G.append(u("span","ra-now",t.current)),$.setAttribute("aria-current","true")),A.append(G,u("small","",v?`${v.messages} ${t.messages} \xB7 ${new Date(v.savedAt).toLocaleString()}${H}`:t.notSaved)),A.addEventListener("click",()=>{Re(),v&&!E&&ti(v.id).catch(te=>B.notify(te.message,"error"))}),$.append(A),v){let te=u("button","ra-x");te.type="button",te.innerHTML=z.trash(),te.title=t.delete,te.setAttribute("aria-label",t.delete),te.addEventListener("click",async he=>{he.stopPropagation(),Re(),await yt(ne,t.delete,t.confirmDelete,{danger:!0,ok:t.delete,cancel:t.cancel})&&await ni(v.id,!1,v.workspace).catch(ge=>B.notify(ge.message,"error"))}),$.append(te)}return $};c.append(b(m??null)),y.length?c.append(u("div","ra-sep")):c.append(u("div","ra-none",t.noSessions));for(let v of y)c.append(b(v));if(y.length){let v=u("div","ra-mf"),E=u("button","ra-btn xs ghost");E.type="button",E.innerHTML=z.trash()+Ce(t.deleteAll),E.addEventListener("click",async()=>{if(Re(),!!await yt(ne,t.deleteAll,t.confirmDeleteAll,{danger:!0,ok:t.deleteAll,cancel:t.cancel}))try{for(let $ of p)await ni($.id,!0,$.workspace);await Jn()}catch($){B.notify($.message,"error")}}),v.append(E),c.append(v)}};Qe.addEventListener("click",()=>{Pa()}),Pt.addEventListener("click",()=>{Re(),Jn().catch(o=>B.notify(o.message,"error"))}),ut.addEventListener("click",async()=>{Re(),await yt(ne,t.clearChat,t.confirmClear,{danger:!0,ok:t.clearChat,cancel:t.cancel})&&await Ds().catch(o=>B.notify(o.message,"error"))}),document.addEventListener("click",_a,!0);function _a(o){o.target?.closest?.(".ra-selp")||Se&&!Se.contains(o.target)&&!Qe.contains(o.target)&&!Z.contains(o.target)&&!ct.contains(o.target)&&!dt.contains(o.target)&&!se.contains(o.target)&&Re()}let Nt=u("input");Nt.type="file",Nt.accept=".zip,application/zip",Nt.multiple=!0,Nt.style.display="none",ne.append(Nt);let Jo=async o=>{let c=F?.workspace;if(!c||!o?.length)return;let p=[];for(let g of Array.from(o)){if(!/\.zip$/i.test(g.name)&&g.type!=="application/zip"&&g.type!=="application/x-zip-compressed"){B.notify(`${g.name}: ${t.notZip}`,"warning");continue}try{p.push(...(await c.installSkill(g)).map(y=>y.name))}catch(y){B.notify(`${g.name}: ${y.message}`,"error")}}p.length&&B.notify(t.skillsInstalled.replace("{names}",p.join(", "))),await Wt(),Se?.classList.contains("ra-skm")&&(Re(),Ra())};Nt.addEventListener("change",()=>{Jo(Nt.files),Nt.value=""});let Ra=async()=>{if(Se){let m=Se.classList.contains("ra-skm");if(Re(),m)return}let o=F?.workspace;if(!o)return;let c=u("div","ra-menu ra-skm");Se=c,jr(c);let p=[];try{p=await o.skills()}catch(m){B.notify(m.message,"error")}if(Se!==c)return;let g=u("div","ra-skh"),y=u("button","ra-btn xs solid");y.type="button",y.innerHTML=z.upload(13)+`<span>${Ce(t.uploadZip)}</span>`,y.addEventListener("click",()=>ls(Nt,m=>{Jo(m)})),o.userSkillsDir||(y.style.display="none"),g.append(u("span","",p.length?`${t.skills} \xB7 ${p.length}`:t.skills),y),c.append(g),p.length||c.append(u("div","ra-none",t.noSkills));for(let m of p){let b=u("div","ra-mi"),v=u("button");v.type="button",v.title=t.useSkill;let E=u("span","ra-mt"),$=!!m.from&&/\.zip$/i.test(m.from);E.append(u("span","ra-mtt",m.name),u("span","ra-skb",m.builtin?t.builtinSkill:$?"zip":t.skillFolder)),m.disableModelInvocation&&E.append(u("span","ra-skb",t.manualOnly)),v.append(E,u("small","",m.description)),v.addEventListener("click",()=>{Re(),re.value=`/skill:${m.name} `,re.focus(),et()});let A=(te,he,ge,Xe="ra-x ra-ia")=>{let Ge=u("button",Xe);return Ge.type="button",Ge.innerHTML=te,Ge.title=he,Ge.setAttribute("aria-label",he),Ge.addEventListener("click",Je=>{Je.stopPropagation(),ge()}),Ge},_=A(z.eye(),t.open,()=>{Re(),_r(m.from&&!$?`${m.from}/SKILL.md`:m.path)}),H=A(z.download(),t.download,()=>{$?Ze.download(m.from):Ze.downloadFolder(m.from??m.dir)}),G=A(z.trash(),t.delete,async()=>{Re();let te=$?p.filter(ge=>ge.from===m.from).map(ge=>ge.name):[m.name],he=te.length>1?t.confirmDeleteZip.replace("{zip}",m.from.replace(/^.*\//,"")).replace("{names}",te.join("\u3001")):t.confirmDeleteSkill.replace("{name}",m.name).replace("{path}",m.from??"");if(await yt(ne,t.delete,he,{danger:!0,ok:t.delete,cancel:t.cancel}))try{await o.removeSkill(m.name),await Wt(),B.notify(t.skillRemoved.replace("{name}",te.join(", ")))}catch(ge){B.notify(ge.message,"error")}},"ra-x");(m.builtin||!m.from?.startsWith((o.userSkillsDir??"\0")+"/"))&&(G.style.display="none"),b.append(v,_,H,G),c.append(b)}c.append(u("div","ra-skf",(o.userSkillsDir?t.skillsHint.replace("{user}",o.userSkillsDir):t.skillsHintNoUser).replace("{dir}",o.skillsDir))),o.userSkillsDir&&c.addEventListener("dragover",m=>{m.dataTransfer?.types.includes("Files")&&(m.preventDefault(),m.stopPropagation(),c.classList.add("drop"))}),c.addEventListener("dragleave",()=>c.classList.remove("drop")),o.userSkillsDir&&c.addEventListener("drop",m=>{m.preventDefault(),m.stopPropagation(),c.classList.remove("drop"),Jo(m.dataTransfer?.files)})};ct.addEventListener("click",()=>{Ra()}),qe||(dt.style.display="none");let Zn={minMinutes:Bn?.minMinutes,maxTasks:Bn?.maxTasks},qc=t.schedDayNames.split(","),Bc=/[\u4e00-\u9fff]/.test(t.sched),Da=o=>{let c=ot(o);return c.slice(0,4)===String(new Date().getFullYear())?c.slice(5):c},Wc=async o=>{await Tn;let c=`${t.schedRunHead.replace("{name}",o.name).replace("{time}",ot(Date.now()))}
|
|
772
779
|
|
|
773
|
-
${o.prompt}`,p;if(l||
|
|
774
|
-
`).map(b=>`> ${b}`),"");continue}let
|
|
775
|
-
`)},
|
|
776
|
-
`))}},{name:"new",aliases:["clear"],run:()=>(
|
|
777
|
-
`))}},{name:"export",run:()=>{if(!
|
|
780
|
+
${o.prompt}`,p;if(l||L)p=F??l;else{let y=o.session??`sched_${o.id}`;if(!o.session){let m=await qe.get(o.id);m&&await qe.put({...m,session:y})}p=F?.id===y?F:Ie.get(y)??await ei(y),p!==F&&(await p.ready(),Ie.set(y,p),ea(p))}!l&&!L&&p.setTitle?.(`\u23F0 ${o.name}`),B.notify(t.schedStarted.replace("{name}",o.name));let g=p===F?await Ja(c):await p.prompt(c);return ys(),(g.reason==="error"||g.reason==="max_turns")&&B.notify(t.schedFailed.replace("{name}",o.name).replace("{error}",g.error?.message??g.reason),"warning"),{status:g.reason==="done"?"ok":g.reason==="aborted"?"stopped":"error",...g.error?{note:g.error.message}:g.reason==="max_turns"?{note:"turn limit"}:{},...g.usage?.total_cost?{cost:g.usage.total_cost}:{}}},Oa=()=>Un&&!Gn&&!!F&&Ro===0&&jt.size===0&&![...Ie.values()].some(o=>o.busy||(o.queued?.length??0)>0)&&!(document.activeElement===re&&re.value.trim()),xn=qe?new ur({store:qe,run:Wc,idle:Oa,lockPrefix:`__runapps_agent_chat:${ke}:schedules`,onChange:()=>vn()}):null;if(xn){let o=()=>setTimeout(()=>{xn.tick()},1500),c=!1,p=setInterval(()=>{let g=!Oa();c&&!g&&o(),c=g},3e3);Ji.push(()=>{clearInterval(p),xn.stop()})}let Yo="list",vn=()=>{qe&&qe.list().then(o=>{Co(o.filter(c=>c.enabled).length),Se?.classList.contains("ra-schm")&&Yo==="list"&&Ls(Se)}).catch(()=>{})},Kc=()=>{if(Se){let c=Se.classList.contains("ra-schm");if(Re(),c)return}if(!qe)return;let o=u("div","ra-menu ra-skm ra-schm");Se=o,jr(o),Ls(o)},Ls=async o=>{Yo="list";let c=[];try{c=await qe.list()}catch(m){B.notify(m.message,"error")}if(Se!==o)return;c.sort((m,b)=>m.enabled===b.enabled?(m.next??1/0)-(b.next??1/0):m.enabled?-1:1),o.replaceChildren();let p=u("div","ra-skh"),g=u("button","ra-btn xs solid");g.type="button",g.innerHTML=z.plus(13)+`<span>${Ce(t.schedNew)}</span>`,g.addEventListener("click",()=>Na(o,null)),p.append(u("span","",c.length?`${t.sched} \xB7 ${c.length}`:t.sched),g),o.append(p),c.length||o.append(u("div","ra-none",t.schedNone));let y={ok:t.schedOk,error:t.schedErr,stopped:t.schedStopped};for(let m of c){let b=u("div","ra-mi"+(m.enabled?"":" ra-off")),v=u("button");v.type="button",v.title=t.schedEdit;let E=u("span","ra-mt"),$=xn?.running.has(m.id);$&&E.append(u("span","ra-spin")),E.append(u("span","ra-mtt",m.name)),$?E.append(u("span","ra-skb on",t.schedRunning)):m.enabled||E.append(u("span","ra-skb",t.schedPaused)),m.by==="agent"&&E.append(u("span","ra-skb",t.schedByAI));let A=`${is(m.schedule,Bc?"zh":"en")} \xB7 ${m.enabled&&m.next?t.schedNext.replace("{time}",Da(m.next)):m.enabled?t.schedNoNext:t.schedPaused}`;v.append(E,u("small","",A)),m.last&&v.append(u("small",m.last.status==="ok"?"":"ra-bad",t.schedLast.replace("{time}",Da(m.last.at)).replace("{status}",y[m.last.status]+(m.last.note?` (${m.last.note})`:"")))),v.addEventListener("click",()=>Na(o,m));let _=(ge,Xe,Ge,Je="ra-x ra-ia")=>{let rt=u("button",Je);return rt.type="button",rt.innerHTML=ge,rt.title=Xe,rt.setAttribute("aria-label",Xe),rt.addEventListener("click",Mt=>{Mt.stopPropagation(),Ge()}),rt},H=_(z.play(),t.schedRunNow,()=>{xn.runNow(m.id).then(ge=>{ge||B.notify(t.schedBusy,"warning")}),setTimeout(vn,100)}),G=_(m.enabled?z.pause():z.clock(13),m.enabled?t.schedPause:t.schedResume,async()=>{try{let ge=await qe.get(m.id);ge&&await qe.put(fr(ge,{enabled:!ge.enabled},Zn))}catch(ge){B.notify(ge.message,"error")}vn()}),te=_(z.message(),t.schedOpen,()=>{Re(),m.session&&ti(m.session).catch(ge=>B.notify(ge.message,"error"))});(!m.session||l||L)&&(te.style.display="none");let he=_(z.trash(),t.schedDel,async()=>{if(Re(),!!await yt(ne,t.schedDel,t.schedDelMsg.replace("{name}",m.name),{danger:!0,ok:t.delete,cancel:t.cancel})){try{await qe.delete(m.id)}catch(ge){B.notify(ge.message,"error")}vn()}},"ra-x");b.append(v,H,G,te,he),o.append(b)}o.append(u("div","ra-skf",t.schedHint))},Na=(o,c)=>{Yo="form";for(let xe of bn.splice(0))xe.close();o.replaceChildren();let p=u("div","ra-schf"),g=(xe,...Oe)=>{let mt=u("div","ra-fld");return mt.append(u("span","",xe),...Oe),mt},y=u("input");y.type="text",y.placeholder=t.schedNamePh,y.value=c?.name??"";let m=u("textarea");m.placeholder=t.schedPromptPh,m.value=c?.prompt??"";let b=c?.schedule??{type:"daily",time:"09:00"},v=_n(ne,{options:[{value:"once",label:t.schedOnce},{value:"every",label:t.schedEvery},{value:"daily",label:t.schedDaily},{value:"cron",label:t.schedCron}],value:b.type});bn.push(v);let E=u("input");E.type="datetime-local";let $=b.type==="once"?Ln(b.at):Date.now()+36e5;E.value=ot(Number.isFinite($)?$:Date.now()+36e5).replace(" ","T");let A=u("input");A.type="number",A.min="1",A.step="1";let _=b.type==="every"?b.minutes:60,H=_%1440===0?"1440":_%60===0?"60":"1";A.value=String(_/Number(H));let G=_n(ne,{options:[{value:"1",label:t.schedMin},{value:"60",label:t.schedHour},{value:"1440",label:t.schedDay}],value:H});bn.push(G);let te=u("div","ra-row");te.append(A,G.el);let he=u("input");he.type="time",he.value=b.type==="daily"?b.time:"09:00";let ge=new Set(b.type==="daily"&&b.days?.length?b.days:[0,1,2,3,4,5,6]),Xe=u("div","ra-days");for(let xe of[1,2,3,4,5,6,0]){let Oe=u("button",ge.has(xe)?"on":"",qc[xe]);Oe.type="button",Oe.addEventListener("click",()=>{ge.has(xe)?ge.size>1&&ge.delete(xe):ge.add(xe),Oe.classList.toggle("on",ge.has(xe)),Sn()}),Xe.append(Oe)}let Ge=u("div","ra-row ra-col2");Ge.append(he,Xe);let Je=u("input");Je.type="text",Je.placeholder="0 9 * * 1-5",Je.value=b.type==="cron"?b.cron:"";let rt=u("div","ra-fld");rt.append(Je,u("span","ra-note",t.schedCronHint));let Mt=u("div","ra-fld"),ht=u("div","ra-note"),qr=()=>{switch(v.value){case"once":return{type:"once",at:E.value.replace("T"," ")};case"every":return{type:"every",minutes:Math.round(Number(A.value)*Number(G.value))};case"cron":return{type:"cron",cron:Je.value.trim()};default:return{type:"daily",time:he.value,...ge.size<7?{days:[...ge].sort((xe,Oe)=>xe-Oe)}:{}}}},Sn=()=>{let xe=qr(),Oe=pr(xe,Zn.minMinutes??5),mt=Oe?null:Pn(xe,Date.now());ht.textContent=Oe??(mt?t.schedNext.replace("{time}",ot(mt)):t.schedNoNext),ht.classList.toggle("err",!!Oe||!mt),Xn.disabled=!!Oe||!mt||!y.value.trim()||!m.value.trim()},Yn=()=>{let xe=v.value;Mt.replaceChildren(v.el,...xe==="once"?[E]:xe==="every"?[te]:xe==="cron"?[rt]:[Ge]),Sn()};v.el.addEventListener("change",Yn),G.el.addEventListener("change",Sn);for(let xe of[y,m,E,A,he,Je])xe.addEventListener("input",Sn);let Br=u("div","ra-btns"),Cn=u("button","ra-btn xs ghost",t.cancel);Cn.type="button";let Xn=u("button","ra-btn xs solid",t.schedSave);Xn.type="button",Cn.addEventListener("click",()=>{for(let xe of bn.splice(0))xe.close();Ls(o)}),Xn.addEventListener("click",async()=>{try{let xe={name:y.value,prompt:m.value,schedule:qr()};if(c){let Oe=await qe.get(c.id);if(!Oe)throw new Error("gone");await qe.put(fr(Oe,{...xe,enabled:!0},Zn))}else{if((await qe.list()).length>=(Zn.maxTasks??20))throw new Error(`${Zn.maxTasks??20} tasks at most`);await qe.put(as({...xe,by:"user"},Zn))}for(let Oe of bn.splice(0))Oe.close();await Ls(o),vn()}catch(xe){ht.textContent=xe.message,ht.classList.add("err")}}),Br.append(Cn,Xn),p.append(u("div","ra-schh",c?t.schedEdit:t.schedNew),g(t.schedName,y),g(t.schedPrompt,m),g(t.schedWhen,Mt),ht,Br),o.append(p),Yn(),queueMicrotask(()=>(c?m:y).focus())};dt.addEventListener("click",()=>Kc()),vn();let za=o=>B.notify(o.message,"error"),kn=!1,Vc=o=>{let c=[`# ${gs(o)}`,""];for(let p of o.messages){if(p.role==="tool"||p.role==="system")continue;let g=Dn(p.content).trim(),y=p.role==="user"&&typeof p.content=="string"?Be(p):null;if(y!==null){c.push(`> **${t.compacted}**`,">",...y.split(`
|
|
781
|
+
`).map(b=>`> ${b}`),"");continue}let m=p.role==="assistant"?(p.tool_calls??[]).filter(b=>!Es.has(b.function.name)):[];if(!(!g&&!m.length)){c.push(`## ${p.role==="user"?t.user:t.assistant}`,""),g&&c.push(g,"");for(let b of m){let v=b.function.arguments;try{v=JSON.parse(b.function.arguments)}catch{}let E=_i(b.function.name,v);c.push(`- \`${b.function.name}\`${E?` ${E}`:""}`)}m.length&&c.push("")}}return c.join(`
|
|
782
|
+
`)},Fa=o=>{let c={...Ke};o.is_default&&!Te.model?delete c.model:c.model=o.id;let p=Zo(o);c.reasoningEffort&&!p?.levels.includes(c.reasoningEffort)&&delete c.reasoningEffort,As(c)},Ia=async o=>{let c=F;if(c.busy)return B.notify(t.busyCmd,"warning"),!1;kn=!0;try{let p=await c.compact(o);return p||B.notify(t.nothingToCompact),p}catch(p){if(!/abort/i.test(p.message??"")&&p.name!=="AbortError")throw p;return B.notify(t.stopped),!1}finally{kn=!1,F===c&&(Or(),ft(c),setTimeout(()=>{F===c&&!c.busy&&Ot(!1)},0))}},Ps=o=>{let c=o.messages,p=c.length-1;for(;p>=0&&!(c[p].role==="user"&&Be(c[p])===null);)p--;let g=c[p];if(!g)return null;let y=g.typed??Dn(g.content).replace(/\s*\[attachments\][\s\S]*$/,"").replace(/(^|\n)\[context\] [\s\S]*$/,""),m=Array.isArray(g.content)?g.content.length>1:/(^|\n)\[attachments\]/.test(String(g.content??""));return{index:p,msg:g,text:y.trim(),files:m}},Zc=async(o,c,p)=>{let g=o.model||(await o.modelInfo())?.id,y=Ps(o)?.msg.content,m=Array.isArray(y)&&y.some(v=>v.type==="image_url"),b=(await Vn()).filter(v=>v.id!==g&&(v.max_input_tokens??0)>p&&(!m||Zt(v,"image")!==!1)).sort((v,E)=>v.max_input_tokens-E.max_input_tokens);return b.find(v=>v.max_input_tokens>=c*1.2)??b[b.length-1]},Ha=async o=>{let c=Ps(o);return c?(await o.rewind(c.index),F===o&&(mn(o.messages),ft(o)),c):null},Ua=async(o,c)=>{F===o&&!o.busy&&(kt=Rr(c)),await o.prompt(c)},Gc=async o=>{let c=Ps(o);kn=!0;let p=null;try{p=await o.summarize?.(c?.msg)??null}finally{kn=!1,Or()}await new Promise(y=>setTimeout(y,0)),await(L?Ds():Jn().then(()=>{}));let g=F;p?(await g.seed?.(p),mn(g.messages),ft(g)):o.messages.length>1&&B.notify(t.ovNoSummary,"warning"),Ot(!1),c&&(c.files?(await ca(c.msg),re.value=c.text,gn(),re.focus()):c.text&&await Ua(g,c.text))},Jc=async(o,c)=>{let p=async()=>{await new Promise(H=>setTimeout(H,0)),await o.continue()},g=o.messages.slice(0,Ps(o)?.index??0),y=g.some(H=>Be(H)===null),m=[],b={label:t.ovEdit,run:async()=>{let H=await Ha(o);H&&(re.value=H.text,gn(),re.focus())}},v={label:t.ovCompact,run:async()=>{await Ia(),await p()}},E={label:t.ovNew,run:()=>Gc(o)};c.cause==="attachments"?m.push({label:t.ovDropFiles,run:async()=>{let H=await Ha(o);H&&(H.text?await Ua(o,H.text):(B.notify(t.ovNoText,"warning"),re.focus()))}}):c.cause==="message"?m.push(b):c.cause==="tools"?s&&m.push({label:t.ovToolSettings,run:async()=>s()}):c.cause==="history"?(y&&m.push(v),m.push(E)):(y&&m.push(v),g.length&&m.push(E),m.push(b));let $=await Zc(o,c.used,c.window).catch(()=>{});if($&&m.push({label:t.ovUseModel.replace("{name}",$.id),run:async()=>{Fa($),await p()}}),F!==o)return;let A={attachments:t.ovAttachments,message:t.ovMessage,tools:t.ovTools,history:t.ovHistory,model:t.ovModel}[c.cause],_={render:()=>{let H=u("div","ra-err ra-over",A);H.setAttribute("role","alert");let G=u("div","ra-acts");for(let te of m){let he=u("button","ra-btn xs",te.label);he.type="button",he.addEventListener("click",()=>{if(o.busy){B.notify(t.busyCmd,"warning");return}we.remove(_),te.run().catch(ge=>{Ss(ge.message),Ot(!1)})}),G.append(he)}return m.length&&H.append(G),H}};vt(_),we.schedule()},Yc=(o,c)=>{let p=c.toLowerCase(),g=o.find(m=>m.id.toLowerCase()===p);if(g)return g;let y=o.filter(m=>m.id.toLowerCase().includes(p));return y.length===1?y[0]:y.find(m=>m.id.toLowerCase().startsWith(p))},Xo=[{name:"help",run:()=>{let o=Qo().map(c=>`- \`/${c.name}${c.args?` ${c.args}`:""}\` \u2014 ${c.description}`);Fr(t.cmdsTitle,[...o,"",t.cmdsMore].join(`
|
|
783
|
+
`))}},{name:"new",aliases:["clear"],run:()=>(Re(),L?Ds():Jn().then(()=>{}))},{name:"resume",run:()=>Pa()},{name:"compact",args:t.cmdArgs.compact,run:async o=>{await Ia(o)}},{name:"continue",run:async()=>{if(F.busy){B.notify(t.busyCmd,"warning");return}if(!F.messages.length){B.notify(t.nothingToContinue);return}await F.continue()}},{name:"model",args:t.cmdArgs.model,run:async o=>{if(!o)return Go();let c=Yc(await Vn(),o);if(!c){B.notify(t.unknownModel.replace("{name}",o),"warning");return}Fa(c),B.notify(t.modelSet.replace("{name}",c.id))}},{name:"effort",args:t.cmdArgs.effort,run:async o=>{let c=await Vn(),p=F.model||c.find(E=>E.is_default)?.id,g=c.find(E=>E.id===p),y=Zo(g),m=g?.id??p??"?";if(!y){B.notify(`${m}: ${t.sEffortNone}`,"warning");return}let b=y.levels.join(" / ");if(!o){B.notify(t.effortLevels.replace("{model}",m).replace("{levels}",b));return}let v={...Ke};if(/^(default|auto|默认)$/i.test(o))delete v.reasoningEffort;else if(y.levels.includes(o.toLowerCase()))v.reasoningEffort=o.toLowerCase();else{B.notify(t.unknownEffort.replace("{name}",o).replace("{model}",m).replace("{levels}",b),"warning");return}As(v),B.notify(t.effortSet.replace("{name}",v.reasoningEffort??(y.def?`${t.sEffortDefault} \xB7 ${y.def}`:t.sEffortDefault)))}},{name:"context",run:async()=>{let o=F,[c,p,g]=await Promise.all([o.context(),o.limits(),o.modelInfo()]),y=La(g),m=Math.round(c.used/c.window*100),b=o.usage,v=[`- ${t.sModel}: ${o.model||(await Vn()).find(E=>E.is_default)?.id||t.sDefault}`,`- ${t.context}: ${m<1&&c.used?"<1":m}% \xB7 ${Ye(c.used)} / ${Ye(c.window)} tokens \xB7 ${t.sMaxTokens} ${Ye(p.output)}`,y?`- ${t.sPrice}: ${y}`:"",`- ${t.messagesLabel}: ${o.messages.length}`,b.calls?`- ${ps(t.usageLine.replace("{cost}",Ri(b.total_cost,g?.price?.currency)).replace("{tokens}",Ye(b.prompt_tokens+b.completion_tokens)).replace("{calls}",String(b.calls)))}`:"",`- ${Ba(o,c.window)}`,o.workspace?`- ${t.directory}: \`${o.workspace.id}\``:""].filter(Boolean);Fr(t.context,v.join(`
|
|
784
|
+
`))}},{name:"export",run:()=>{if(!F.messages.length){B.notify(t.nothingToExport);return}let o=gs(F).replace(/[\\/:*?"<>|\s]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"conversation";cs(`${o}.md`,Vc(F),"text/markdown;charset=utf-8")}},{name:"files",run:()=>be===!1?void 0:lt.click()},{name:"settings",run:()=>Go()},{name:"debug",run:()=>{hn?Ve.click():B.notify(t.debugOff)}}],Qo=()=>Xo.filter(o=>(!Ue||Ue.includes(o.name))&&(o.name!=="files"||!!F?.workspace&&be!==!1)&&(o.name!=="settings"||Ma)&&(o.name!=="debug"||hn)&&(o.name!=="resume"||!l&&!!F?.workspace&&!L)).map(o=>({name:o.name,description:o.name==="new"&&L?t.confirmClear.split(/[??]/)[0]:t.cmd[o.name]??"",kind:t.command,args:o.args,builtin:!0})),Xc=o=>{let c=/^\/(\S+)(?:\s+([\s\S]*))?$/.exec(o);if(!c)return!1;let p=c[1].toLowerCase(),g=Xo.find(y=>y.name===p||y.aliases?.includes(p));if(!g||!Qo().some(y=>y.name===g.name))return!1;re.value="",et();try{Promise.resolve(g.run((c[2]??"").trim())).catch(za)}catch(y){za(y)}return!0},ja=o=>{if(o.builtin&&(!o.args||re.value.trim()===`/${o.name}`)){re.value=`/${o.name}`,Kn("prompt");return}re.value=`/${o.name} `,et()},_s,ft=o=>{if(!(ie===!1||F!==o)){if(!o.messages.length){se.style.display="none",Se?.classList.contains("ra-use")&&Re();return}Promise.all([o.context(),o.modelInfo()]).then(([c,p])=>{if(F!==o)return;_s=p?.price?.currency;let g=Math.min(1,c.used/c.window),y=8,m=2*Math.PI*y;se.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="${y}"/><circle class="pr" cx="10" cy="10" r="${y}" stroke-dasharray="${m.toFixed(2)}" stroke-dashoffset="${(m*(1-Math.max(g,.03))).toFixed(2)}" transform="rotate(-90 10 10)"/></svg>`;let b=`${qa(t.context)} ${Wa(c.used,c.window)}`;se.title=b,se.setAttribute("aria-label",b),se.style.display="",Se?.classList.contains("ra-use")&&Ka(Se,o,c)})}},qa=o=>o.charAt(0).toUpperCase()+o.slice(1),Ba=(o,c)=>{let p=o.compactionFor(c);return`${p.summarize?t.autoCompact:t.autoTrim}: ${p.reserveTokens>0?t.autoCompactAt.replace("{n}",Ye(p.reserveTokens)):t.autoCompactFull}`},Wa=(o,c)=>{let p=o/c;return o&&p<.01?"<1%":`${Math.round(Math.min(1,p)*100)}%`},Ka=(o,c,p)=>{let g=Math.min(1,p.used/p.window),y=c.usage;o.className="ra-menu ra-use"+(g>=.9?" hi":g>=.7?" mid":"");let m=u("div","ra-uh");m.append(u("span","",qa(t.context)),u("b","",Wa(p.used,p.window)));let b=u("div","ra-ubar"),v=u("i");v.style.width=`${Math.max(g,p.used?.01:0)*100}%`,b.append(v);let E=u("div","ra-usub");E.append(u("span","",t.uOf.replace("{used}",Ye(p.used)).replace("{window}",Ye(p.window))),u("span","",c.model||wn?.find(H=>H.is_default)?.id||""));let $=u("div","ra-ugrid");for(let[H,G]of[[t.uCost,Ri(y.total_cost,_s)],[t.uIn,Ye(y.prompt_tokens)],[t.uOut,Ye(y.completion_tokens)],[t.uCalls,String(y.calls)]]){let te=u("div");te.append(u("small","",H),u("b","",G)),$.append(te)}o.replaceChildren(m,b,E,$),o.append(u("div","ra-unote",Ba(c,p.window)));let A=u("div","ra-mf"),_=u("button","ra-btn xs ghost");_.type="button",_.textContent=t.compactNow,_.disabled=c.busy||kn,_.addEventListener("click",()=>{Re(),Promise.resolve(Xo.find(H=>H.name==="compact").run("")).catch(H=>B.notify(H.message,"error"))}),A.append(_),o.append(A)},Qc=async()=>{if(Se?.classList.contains("ra-use")){Re();return}if(Re(),!F)return;let o=F,c=u("div","ra-menu ra-use");Se=c,jr(c);let p=await o.context();Se===c&&F===o&&Ka(c,o,p)};se.addEventListener("click",()=>{Qc()});let Va=(o,c)=>{if(!c)return;let p=()=>{try{o.continue().catch(g=>B.notify(g.message,"error"))}catch(g){B.notify(g.message,"error")}};c.overflow?Jc(o,c.overflow):c.reason==="error"?Ss(c.error??t.error,o.messages.length?p:void 0):c.reason==="max_turns"?Rc(t.maxTurns.replace("{n}",String(o.settings.maxTurns)),{label:t.continueRun,onClick:p},t.maxTurnsHint):Fr(t.stopped)},Za=async o=>{for(let y of Lr)y();if(Lr=[],zc(o),o.workspace){let y=o.workspace;Lr.push(y.onChange(m=>{y.isSkillPath(m.path)&&Wt()}))}F&&F!==o&&Pr.set(F.id,B.park()),F!==o&&Ir(),F=o,Ie.set(o.id,o),Ki(o),ws(o),B.restore(Pr.get(o.id)??[]),Pr.delete(o.id),Oo(o.id),fn(),pn.clear(),Y=null,kt=null,at.textContent=o.model??"",at.style.display=o.model?"":"none";let c=!l&&(q??!!o.workspace);Qe.style.display=Pt.style.display=c&&o.workspace?"":"none",L=!(c&&o.workspace),K(),lt.style.display=o.workspace&&be!==!1?"":"none",ct.style.display=o.workspace&&C!==!1?"":"none",Ze.setWorkspace(o.workspace),hn&&pt.setAgent(o),we.clear(),na(),Ot(o.busy),Hr(),l||ic(ke,o.id);let p=(y,m)=>Lr.push(o.on(y,m));p("run_start",y=>{K(),y.message&&(kt&&!kt.msg?(kt.msg=y.message,kt.update()):Rr(y.message.content,y.message),Qi(o,y.message)),kt=null,Y=null,Dr=Date.now(),Ot(!0),Tt()}),p("turn_start",()=>{Nr(!0),Y&&(Y.text=null,Y.md="",Y.drawn=void 0,Y.drawnFinal=void 0,Y.think=null,Y.thinkBody=null,Y.reasoning=""),Tt(),queueMicrotask(St)}),p("steered",y=>{Or(),Dr=Date.now();for(let m of y.messages)Rr(m.content,m);St()}),p("queued",()=>St()),p("rewind",()=>{F===o&&(mn(o.messages),ft(o))}),p("history",y=>{if(F!==o)return;let m=we.length,b=m>0&&we.rows[0]?.el?.classList.contains("ra-olderrow")===!0,v=we.follow,E=de.scrollTop;mn(o.messages),y.reason==="older"?we.scrollToIndex(Math.max(0,we.length-(m-(b?1:0)))):y.reason==="newer"&&!v&&(we.follow=!1,de.scrollTop=E,we.layout()),ft(o)}),p("text_delta",y=>{let m=vs();Ho(m),m.text||(m.text=u("div","ra-md"),Io(m.body,m.text)),m.md=y.text,ga()}),p("reasoning_delta",y=>{let m=vs();if(!m.pending&&!m.text&&Tt(),!m.think){[m.think,m.thinkBody]=ha("",!1),m.think.style.display="none";let b=pa(m.body);b instanceof HTMLDetailsElement&&b.classList.contains("ra-tg")&&!m.text?b.querySelector(".ra-tgb").append(m.think):m.text?m.body.insertBefore(m.think,m.text):Io(m.body,m.think)}m.reasoning=y.text,ga()}),p("message_reset",()=>{Y&&(Y.md="",Y.reasoning="",Y.text?.remove(),Y.text=null,Y.think?.remove(),Y.think=null,Y.thinkBody=null,Tt())}),p("message_end",()=>{Ho(),Nr(!0),qn=Date.now()}),p("tool_start",y=>{if(Es.has(y.name))return;Nr(!0);let m=Pc(y.id,y.name,y.args,vs().body,y.parentId?pn.get(y.parentId):void 0),b=xa({name:y.name,args:y.args},m.el);Tt(b.title?`${b.verb} ${b.what}`:b.verb,Ec(y.name,y.args))}),p("tool_update",y=>{let m=pn.get(y.id);m&&(m.update||(m.update=u("div","ra-tupd"),m.el.append(m.update)),m.update.textContent=y.content,Y?.pending&&Tt(Y.pending.firstElementChild.textContent??t.waiting,{text:y.content}),we.schedule())}),p("tool_end",y=>{let m=pn.get(y.id);if(m)ka(m,y.status,y.result,y.durationMs,Ts(y.content),y.details);else{let v=Ar.get(y.id);v&&(v.status=y.status,v.result=y.result,Ar.delete(y.id))}let b=m?.args&&typeof m.args=="object"?m.args.path:void 0;y.status==="ok"&&typeof b=="string"&&/^(write_file|edit_file|delete_file)$/.test(y.name)&&Ze.changed(b),Y?.pending&&!Y.body.querySelector(".ra-tend .ra-spin")&&Tt()});let g=null;p("compaction_start",y=>{y.runId||(Ot(!0),Dr=Date.now()),Tt(t.compactingNow)}),p("compaction",y=>{if(y.runId?Y?.pending&&Tt():Or(),!y.summary&&y.runId&&g===y.runId)return;y.summary||(g=y.runId??null);let m=o.messages[0],b=y.summaryText??(m&&typeof m.content=="string"?Be(m):null);Fr(y.summary?t.compacted:t.trimmed,y.summary&&b?b:void 0)}),p("run_end",y=>{Bt=y.reason==="done"&&!re.value.trim()?Cs:null,Cs=null;let m=Y;Or();let b=[...o.messages].reverse().find(v=>v.role==="assistant");m&&m.body.childElementCount&&b&&!m.el.querySelector(":scope>.ra-af")&&(m.el.append(la(b)),we.schedule()),B.cancelAll(),Va(o,y.reason==="done"?null:o.lastEnd??{reason:y.reason,error:y.error?.message,at:Date.now()}),Ot(!1),ft(o),Wt(),Ze.refresh(),ys()});try{await o.ready()}catch(y){Ss(y.message)}F!==o||!Un||(ue?.(o),mn(o.messages),o.busy||Va(o,o.lastEnd),ft(o),ys(),await Wt())},ed=()=>`agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ei=async o=>{let c=o??ed(),p=typeof d=="function"?await d(c):d??null,g=Te.instructions,y=Te.fileTools,m=y===void 0||y===!0||Array.isArray(y)&&(y.includes("write_file")||y.includes("edit_file")),b=y===!1?"":m?be===!1?Yu(On):Qu(On):Xu(On),v=!p||!b?g:typeof g=="function"?()=>[g(),b].filter(Boolean).join(`
|
|
778
785
|
|
|
779
|
-
`):[
|
|
786
|
+
`):[g,b].filter(Boolean).join(`
|
|
780
787
|
|
|
781
|
-
`),
|
|
788
|
+
`),E={};return Ke.model&&(E.model=Ke.model),Ke.maxTurns&&(E.maxTurns=Ke.maxTurns),Ke.maxTokens&&(E.maxTokens=Ke.maxTokens),Ke.reasoningEffort&&(E.extra={...Te.extra??{},reasoning_effort:Ke.reasoningEffort}),Mr&&(E.permissions=Mr),new Xt(wt,{...Te,...E,tools:Ta,instructions:v,id:c,workspace:p,ui:Te.ui??xc(c)})},Rs=o=>{pt.forget(o),typeof d=="function"&&o.workspace?.close()},Gn=null,Ga=o=>{if(l)return Promise.reject(new Error("newSession/resume need the chat to own its agent (pass a provider, not an agent)"));if(Gn)return Gn;let c=(async()=>{if(o&&o===F?.id)return F;let p=F;if(p)if(p.busy||(p.queued?.length??0)>0){if(No().length>=bc)return B.notify(t.bgLimit.replace("{n}",String(No().length)),"warning"),p;ea(p)}else Ie.delete(p.id),Rs(p);let g=o&&Ie.get(o)||await ei(o);return await Za(g),g})();return Gn=c,c.finally(()=>{Gn===c&&(Gn=null)}).catch(()=>{}),c},Jn=()=>Ga(),Ds=async()=>{await Tn;let o=F??l;B.cancelAll(),await o.clear?.(),(F===o||l===o)&&(mn(o.messages),ft(o),St(),Hr())},ti=o=>Ga(o),ni=async(o,c=!1,p)=>{if(await Tn,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 y=Ie.get(o);y&&(Oo(o,!1),Pr.delete(o),await y.abort(),Ie.delete(o),ws(y),Rs(y),fn()),await g.sessions.delete(o,p),ys();return}B.cancelAll(),await F.abort(),typeof d=="function"?await g.destroy():await g.sessions.delete(o,g.id),ic(ke,null),c||await Jn()}},td=Te.id??(typeof h=="string"?h:h===!1?void 0:rp(ke)??void 0),Tn=(l?Promise.resolve(l):ei(td)).then(o=>Za(o));xn&&Tn.then(()=>{Un&&xn.start()}).catch(()=>{}),Tn.catch(o=>{Ss(`${o.message}`),Ot(!1)});let Ja=async o=>(await Tn,F.busy||(kt=Rr(o)),F.prompt(o));return{get agent(){return F??l},get ready(){return Tn},element:ne,ui:B,prompt:Ja,setInput(o){re.value=o,re.focus(),et()},insertText(o){let c=document.activeElement===re?re.selectionStart:re.value.length,p=document.activeElement===re?re.selectionEnd:c,g=re.value.slice(0,c),y=re.value.slice(p),m=(g&&!/\s$/.test(g)?" ":"")+o+(y&&/^\S/.test(y)?" ":y?"":" ");re.value=g+m+y,re.focus(),re.setSelectionRange(g.length+m.length,g.length+m.length),et()},newSession:Jn,resume:ti,deleteSession:o=>ni(o),clear:Ds,addContext:Ca,setDebug(o){hn=o,bs()},setTitle(o){tt.textContent=o},updateComposerAction(o,c){let p=Ui.get(o);p&&(Object.assign(p.a,c),ji(p.btn,p.a))},setAppearance(o){o.theme&&(nn=o.theme),o.palette&&(Ft=o.palette),o.vars!==void 0&&(Lt=o.vars),Fn()},refresh:Wt,unmount(){if(Un){Un=!1,jn&&clearTimeout(jn);for(let o of Lr)o();for(let o of Ji.splice(0))try{o()}catch{}B.cancelAll(!0),Re(),document.removeEventListener("click",_a,!0),Nn?.removeEventListener?.("change",kr),Ut!==null&&clearTimeout(Ut),$r!==null&&cancelAnimationFrame($r),we.dispose(),Yi?.disconnect(),Ze.dispose(),pt.dispose();for(let o of Ct)o.preview&&URL.revokeObjectURL(o.preview);for(let o of[...qt.keys()])Oo(o,!1);if(!l)for(let o of Ie.values())ws(o),o.abort().finally(()=>Rs(o));Ie.clear(),Pr.clear(),qt.clear(),Ct.length=0,Et.length=0,ne.remove()}}}}var sp=/^(text\/|application\/(json|xml|yaml|javascript|x-sh))/;function Ni(r){let e=Q(r);return e==="/"?[]:e.slice(1).split("/")}function hc(r){return new Error(`No such file: ${Q(r)}`)}function mc(r,e={}){let n=async(l,d=!1)=>{let h=r;for(let f of l)h=await h.getDirectoryHandle(f,{create:d});return h},t=async(l,d=!1)=>{let h=Ni(l);if(!h.length)throw new Error(`${Q(l)} is a folder, not a file`);return(await n(h.slice(0,-1),d)).getFileHandle(h[h.length-1],{create:d})},s=async(l,d)=>{let h=await d.getFile();return{path:Q(l),size:h.size,contentType:h.type||At(l,new Uint8Array),mtime:h.lastModified}},i=async(l,d,h)=>{for await(let[f,w]of l){let k=`${d}/${f}`;w.kind==="directory"?await i(w,k,h):h.push(await s(k,w))}},a={description:e.description??`the local folder "${r.name}"`,async list(l){let d=[],h=Ni(l),f;try{f=await n(h)}catch{try{let w=await t(l);return[await s(l,w)]}catch{return d}}return await i(f,h.length?"/"+h.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 hc(l)}let h=await d.getFile(),f=new Uint8Array(await h.arrayBuffer()),w=h.type||At(l,f);if(sp.test(w)){let k=$t(f);if(k!==null)return k}return f}};return e.readonly||(a.write=async(l,d)=>{let f=await(await t(l,!0)).createWritable();try{await f.write(d)}finally{await f.close()}},a.delete=async l=>{let d=Ni(l);if(!d.length)throw new Error("Cannot delete /");let h=await n(d.slice(0,-1));try{await h.removeEntry(d[d.length-1],{recursive:!0})}catch(f){throw f?.name==="NotFoundError"?hc(l):new Error(`${l}: ${f?.message??String(f)}`)}}),a}return ld(op);})();
|