@easbot/agent 0.2.41 → 0.2.42
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/assets/txt/tool/agent-client.txt +6 -10
- package/dist/chunks/acp-AJ7O6XNE.mjs +22 -0
- package/dist/chunks/adapter-loader-VUS3UYMT.mjs +1 -0
- package/dist/chunks/{agent-CYRU65IN.mjs → agent-SKRC54QG.mjs} +1 -1
- package/dist/chunks/{agent-JHX64CI6.mjs → agent-VUPXBEWR.mjs} +1 -1
- package/dist/chunks/agent-service-registry-DPO5SSXA.mjs +1 -0
- package/dist/chunks/app-EPNEAPMS.mjs +58 -0
- package/dist/chunks/{auth-SUHJJM24.mjs → auth-34JK273T.mjs} +1 -1
- package/dist/chunks/bootstrap-3KXRWM6D.mjs +1 -0
- package/dist/chunks/build-program-2AR3LYQJ.mjs +11 -0
- package/dist/chunks/bus-QOWILU5Z.mjs +1 -0
- package/dist/chunks/chunk-2YNYVTYT.mjs +2 -0
- package/dist/chunks/{chunk-D4GDS5UI.mjs → chunk-3472MC45.mjs} +1 -1
- package/dist/chunks/{chunk-X7KLQIAQ.mjs → chunk-4OHDEBAX.mjs} +1 -1
- package/dist/chunks/chunk-BDS2JWYG.mjs +2 -0
- package/dist/chunks/{chunk-KTMZPMCI.mjs → chunk-EB3OP6TL.mjs} +1 -1
- package/dist/chunks/chunk-IJVW4VME.mjs +1 -0
- package/dist/chunks/{chunk-75IQNF4I.mjs → chunk-J6VEDKPT.mjs} +1 -1
- package/dist/chunks/{chunk-IEQ4VD66.mjs → chunk-JTVO3U27.mjs} +1 -1
- package/dist/chunks/chunk-LGMGGNPW.mjs +1 -0
- package/dist/chunks/{chunk-TYD2M4SP.mjs → chunk-MYI75W3D.mjs} +1 -1
- package/dist/chunks/{chunk-R4BPTF6V.mjs → chunk-PEMUENKB.mjs} +1 -1
- package/dist/chunks/{chunk-UBCLKZWP.mjs → chunk-WGJIT5HU.mjs} +1 -1
- package/dist/chunks/chunk-XMIQEMED.mjs +1051 -0
- package/dist/chunks/{command-CPT2YSIR.mjs → command-CJGBEATT.mjs} +1 -1
- package/dist/chunks/compaction-R4RTVEDY.mjs +1 -0
- package/dist/chunks/config-YSZNIWZT.mjs +1 -0
- package/dist/chunks/debug-GZCL57Q7.mjs +3 -0
- package/dist/chunks/event-2JDHF3UV.mjs +1 -0
- package/dist/chunks/file-G4WHJKUX.mjs +1 -0
- package/dist/chunks/gateway-D6XCB2OA.mjs +16 -0
- package/dist/chunks/gateway-loader-OH3VCEUD.mjs +1 -0
- package/dist/chunks/{generate-4UO6UCUB.mjs → generate-NYQCTBY7.mjs} +1 -1
- package/dist/chunks/{github-XIWTIRCK.mjs → github-IGWZXZRB.mjs} +2 -2
- package/dist/chunks/global-5WFCDQ45.mjs +1 -0
- package/dist/chunks/{import-K45ZW3NR.mjs → import-TYN474UK.mjs} +1 -1
- package/dist/chunks/installation-6S6OCY6F.mjs +1 -0
- package/dist/chunks/instance-YVRWMB6M.mjs +1 -0
- package/dist/chunks/loader-VV3FV5NS.mjs +1 -0
- package/dist/chunks/loader-XGUYA6ZM.mjs +1 -0
- package/dist/chunks/lsp-J7UR4JNX.mjs +1 -0
- package/dist/chunks/{mcp-JBHKJN6X.mjs → mcp-FYDYPGLE.mjs} +1 -1
- package/dist/chunks/mcp-GEZSPY2W.mjs +1 -0
- package/dist/chunks/models-JNSS4QSZ.mjs +1 -0
- package/dist/chunks/{pr-MCLQ6KQO.mjs → pr-DQZIG2CT.mjs} +1 -1
- package/dist/chunks/preferences-QCM3RIAL.mjs +1 -0
- package/dist/chunks/project-53ZMRKRI.mjs +1 -0
- package/dist/chunks/prompt-XYHKPB7Q.mjs +1 -0
- package/dist/chunks/provider-2RFHZVX4.mjs +1 -0
- package/dist/chunks/registry-GGSZXBFC.mjs +1 -0
- package/dist/chunks/revert-7RBPZDWL.mjs +1 -0
- package/dist/chunks/ripgrep-U54LYBZO.mjs +1 -0
- package/dist/chunks/{run-EGRUZXP2.mjs → run-EQ5GHPKF.mjs} +1 -1
- package/dist/chunks/scheduler-3AYHIZGY.mjs +1 -0
- package/dist/chunks/server-ITUF2HX7.mjs +1 -0
- package/dist/chunks/session-5OU5P7UF.mjs +1 -0
- package/dist/chunks/{session-VCIKEQYZ.mjs → session-R2LCLNAY.mjs} +1 -1
- package/dist/chunks/session-XA4RMN7D.mjs +1 -0
- package/dist/chunks/share-45SYUA47.mjs +1 -0
- package/dist/chunks/snapshot-YC3DAH7Q.mjs +1 -0
- package/dist/chunks/{stats-RPGHGZUR.mjs → stats-TREO4CFV.mjs} +1 -1
- package/dist/chunks/storage-6F64537E.mjs +1 -0
- package/dist/chunks/{tui-ZMS6CJQ7.mjs → tui-FVQHBIJ7.mjs} +1 -1
- package/dist/chunks/types-OIHWEQYC.mjs +1 -0
- package/dist/chunks/{update-KDCCJIPI.mjs → update-V3GTL4TX.mjs} +1 -1
- package/dist/cli.mjs +5 -5
- package/package.json +15 -14
- package/dist/chunks/acp-D5UOHKRU.mjs +0 -22
- package/dist/chunks/adapter-loader-SHO4LOSU.mjs +0 -1
- package/dist/chunks/app-S6QDTGNJ.mjs +0 -1
- package/dist/chunks/bootstrap-FHSG4M5N.mjs +0 -1
- package/dist/chunks/build-program-YDOM5ROT.mjs +0 -11
- package/dist/chunks/bus-7GPWVWOA.mjs +0 -1
- package/dist/chunks/chunk-CCRIJZBK.mjs +0 -1
- package/dist/chunks/chunk-EM2QJ5NQ.mjs +0 -59
- package/dist/chunks/chunk-FWVB6X4X.mjs +0 -1050
- package/dist/chunks/chunk-GRDTQW6K.mjs +0 -2
- package/dist/chunks/chunk-SB4J2R54.mjs +0 -2
- package/dist/chunks/chunk-ZBRXNYEM.mjs +0 -1
- package/dist/chunks/compaction-JR5FOLBX.mjs +0 -1
- package/dist/chunks/config-O5EE574O.mjs +0 -1
- package/dist/chunks/debug-BWJVMW7Q.mjs +0 -3
- package/dist/chunks/event-NO7SFKKX.mjs +0 -1
- package/dist/chunks/file-Q52INNX3.mjs +0 -1
- package/dist/chunks/gateway-XSXBPTB7.mjs +0 -16
- package/dist/chunks/gateway-loader-6P6BTWQP.mjs +0 -1
- package/dist/chunks/global-XQYOBWZR.mjs +0 -1
- package/dist/chunks/installation-55Z2PXMV.mjs +0 -1
- package/dist/chunks/instance-S5GBRS3K.mjs +0 -1
- package/dist/chunks/loader-JAKTXQ6M.mjs +0 -1
- package/dist/chunks/loader-S2BSLSAZ.mjs +0 -1
- package/dist/chunks/lsp-4VYPJGAN.mjs +0 -1
- package/dist/chunks/mcp-ZGGTG6YT.mjs +0 -1
- package/dist/chunks/models-TI5SNTLO.mjs +0 -1
- package/dist/chunks/preferences-LWCCEUB3.mjs +0 -1
- package/dist/chunks/project-OEBG6JHE.mjs +0 -1
- package/dist/chunks/prompt-JSZCNKQD.mjs +0 -1
- package/dist/chunks/provider-TU4AF2GP.mjs +0 -1
- package/dist/chunks/registry-NITFPORZ.mjs +0 -1
- package/dist/chunks/revert-PDDRJVNK.mjs +0 -1
- package/dist/chunks/ripgrep-7VVA7THG.mjs +0 -1
- package/dist/chunks/scheduler-VUQ33E5B.mjs +0 -1
- package/dist/chunks/server-3RDX4X3L.mjs +0 -1
- package/dist/chunks/session-GQAYKB6Q.mjs +0 -1
- package/dist/chunks/session-TXC5Z4O2.mjs +0 -1
- package/dist/chunks/share-RUV4SIRB.mjs +0 -1
- package/dist/chunks/snapshot-PXRGQ6JR.mjs +0 -1
- package/dist/chunks/storage-3T5H5KBY.mjs +0 -1
- package/dist/chunks/tui-5BQORL3N.mjs +0 -1
- package/dist/chunks/types-RWQQETDC.mjs +0 -1
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
import {b as b$4,a as a$b}from'./chunk-WGJIT5HU.mjs';import {b as b$2,a as a$a,c as c$2}from'./chunk-IJVW4VME.mjs';import {a as a$8}from'./chunk-3472MC45.mjs';import {a as a$4,b,c as c$1}from'./chunk-LGMGGNPW.mjs';import {f,e as e$1,c as c$3}from'./chunk-J6VEDKPT.mjs';import {a as a$9}from'./chunk-AAJAKVQY.mjs';import {e,h,g,i,f as f$1,o,m,r,q,l,n,p}from'./chunk-2RSIOAZV.mjs';import {i as i$1}from'./chunk-UNBJ6Y7L.mjs';import {a as a$3}from'./chunk-4OHDEBAX.mjs';import {a as a$2,b as b$3}from'./chunk-EB3OP6TL.mjs';import {a as a$5}from'./chunk-CJTCCLW4.mjs';import {a as a$6}from'./chunk-2YNYVTYT.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-BDS2JWYG.mjs';import {b as b$1,a as a$7,c,d}from'./chunk-X6ISXWBN.mjs';import N,{z}from'zod';import {PKG,Filesystem,Archive,$,NamedError,lazy,fn as fn$1,Identifier,Wildcard,whichSync,Shell,loadTextFile,lazyAsync,abortAfterAny,Fetch,iife,formatLocalISOCompact,defer,parseModelId,git,AsyncQueue,Slug,Context,PackageRegistry,proxied,withTimeout,Ignore,Token,createPkgShell,SessionTitle,Glob,retry,TruncateContent,work,shell,loadTextFileAsync}from'@easbot/utils';import*as Tt from'fs/promises';import Tt__default,{realpath,mkdir,access,readFile,writeFile,unlink,readdir,copyFile,stat,rm as rm$1}from'fs/promises';import*as Se from'path';import Se__default,{join,sep}from'path';import {Decimal}from'decimal.js';import {convertToModelMessages,APICallError,LoadAPIKeyError,tool,jsonSchema,streamText,wrapLanguageModel,asSchema,streamObject,generateObject,NoSuchModelError,dynamicTool}from'ai';import ec from'os';import {mergeDeep,mapValues,pipe,splitWhen,values,sortBy,unique,filter,map,fromEntries,clone,pickBy,omit}from'remeda';import gl,{createReadStream,existsSync,constants,readFileSync}from'fs';import {parse as parse$1,printParseErrorCode,modify,applyEdits}from'jsonc-parser';import {pathToFileURL,fileURLToPath}from'url';import {EventEmitter}from'events';import {createMessageConnection,StreamMessageReader,StreamMessageWriter}from'vscode-jsonrpc/node.js';import {createServer,STATUS_CODES}from'http';import {glob}from'glob';import {initLog as initLog$2,createNoteKnowledge}from'@easbot/note';import gy from'fuzzysort';import {createEasbotClient}from'@easbot/sdk';import {resolver,describeRoute,validator,openAPIRouteHandler,generateSpecs}from'hono-openapi';import {Hono}from'hono';import {cors}from'hono/cors';import {stream,streamSSE}from'hono/streaming';import {proxy}from'hono/proxy';import {basicAuth}from'hono/basic-auth';import {compress}from'hono/compress';import {createTwoFilesPatch,diffLines,structuredPatch,formatPatch}from'diff';import {Status,MCPClient,initLog as initLog$3}from'@easbot/mcp';import {connect}from'net';import Sx from'open';import {HookEvent}from'@easbot/plugin';export{HookEvent as Ia}from'@easbot/plugin';import {LRUCache}from'lru-cache';import {createInterface}from'readline';import {ulid}from'ulid';import {ndJsonStream,ClientSideConnection}from'@agentclientprotocol/sdk';import {spawn}from'child_process';import {initLog,createMemorySystem}from'@easbot/memory';import {initLog as initLog$1,createCodebase}from'@easbot/codebase';import'@easbot/types';import rS from'bash-parser';import {createRequire}from'module';import QS from'turndown';import {parse}from'node-html-parser';import*as pC from'node-pty';import {createHash}from'crypto';import Vk from'zod/v4';import {zodToJsonSchema}from'zod-to-json-schema';import {HTTPException}from'hono/http-exception';import IE from'bonjour-service';import {serve}from'@hono/node-server';var bo;(re=>{let e=a.create({service:"lsp.server"}),t=process.platform==="win32"?"cmd":void 0;function n(Q,H=[],F){let te=H.length>0?`${Q} ${H.join(" ")}`:Q,V=process.platform==="win32"?{...F,windowsHide:true}:F;return Shell.spawn(t,te,V)}function o(Q,H){let F=process.platform==="win32"?{...H,windowsHide:true}:H;return Shell.spawn(t,Q.join(" "),F)}function s(Q,H=[],F){return PKG.spawn([Q,...H],F)}async function r(Q,H){let F=process.platform==="win32"?{...H,windowsHide:true}:H;return Shell.run(t,Q,F)}let i=async Q=>Tt__default.stat(Q).then(()=>true).catch(()=>false),c=(Q,H)=>async F=>{if(H){let J=Filesystem.up({targets:H,start:Se__default.dirname(F),stop:R.directory}),oe=await J.next();if(await J.return(void 0),oe.value)return}let te=Filesystem.up({targets:Q,start:Se__default.dirname(F),stop:R.directory}),V=await te.next();return await te.return(void 0),V.value?Se__default.dirname(V.value):R.directory};re.ServerInitTimeout={bash:3e4,json:3e4,yaml:3e4,dockerfile:3e4,terraform:6e4,lua:6e4,zls:6e4,nixd:6e4,deno:6e4,biome:6e4,oxlint:6e4,gopls:9e4,eslint:9e4,ruby_lsp:9e4,pyright:9e4,ty:9e4,elixir_ls:9e4,prisma:9e4,dart:9e4,ocaml_lsp:9e4,svelte:9e4,astro:9e4,gleam:9e4,tinymist:9e4,clojure_lsp:9e4,intelephense:9e4,typescript:18e4,vue:18e4,rust:18e4,clangd:18e4,csharp:18e4,fsharp:18e4,sourcekit_lsp:18e4,kotlin_ls:18e4,texlab:18e4,jdtls:3e5,haskell_language_server:3e5};function d(Q){if(Q in re.ServerInitTimeout)return re.ServerInitTimeout[Q];let H=Q.replace(/\s+/g,"_");if(H in re.ServerInitTimeout)return re.ServerInitTimeout[H];let F=Q.split(/\s+/).pop();return F&&F in re.ServerInitTimeout?re.ServerInitTimeout[F]:a$2.EASBOT_LSP_INIT_TIMEOUT}re.getServerInitTimeout=d,re.Deno={id:"deno",initTimeout:re.ServerInitTimeout.deno,root:async Q=>{let H=Filesystem.up({targets:["deno.json","deno.jsonc"],start:Se__default.dirname(Q),stop:R.directory}),F=await H.next();if(await H.return(void 0),!!F.value)return Se__default.dirname(F.value)},extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(Q){let H=await PKG.which("deno");if(!H){e.info("deno not found, please install deno first");return}return {process:n(H,["lsp"],{cwd:Q,stderr:"ignore"})}}};let f=[{name:"@vtsls/language-server",command:"vtsls",description:"Standalone version of VSCode TypeScript extension, full features, better performance"},{name:"typescript-language-server",command:"typescript-language-server",description:"Traditional implementation based on tsserver"}];re.Typescript={id:"typescript",root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],initTimeout:re.ServerInitTimeout.typescript,async spawn(Q){e.info("typescript server spawn",{PATH:process.env.PATH});let H=null,F;for(let J of f){if(e.info(`trying to find ${J.name}...`),H=await PKG.which(J.command),H){e.info(`${J.name} found`,{binary:H}),F=J;break}let oe=await PKG.resolve(J.name,R.directory).catch(()=>{});if(oe){H=oe,e.info(`${J.name} resolved`,{binary:H}),F=J;break}}if(!H||!F){let J=f.map(oe=>`npm install -g ${oe.name}`).join(" \u6216 ");e.error(`typescript LSP server not found, please install: ${J}`);return}e.info(`typescript server starting with ${F.name}`,{binary:H});let te=F.command==="vtsls"?["--stdio"]:["--stdio"];return {process:n(H,te,{cwd:Q,env:{...process.env},stderr:"ignore"})}}},re.Vue={id:"vue",initTimeout:re.ServerInitTimeout.vue,extensions:[".vue"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let H=await PKG.which("vue-language-server"),F=[];if(!H){let J=Se__default.join(a$1.Path.bin,"node_modules","@vue","language-server","bin","vue-language-server.js");if(!await PKG.file(J).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let de=await PKG.which();if(!de)return;await n(de,["install","@vue/language-server"],{cwd:a$1.Path.bin,env:{...process.env},stdout:"pipe",stderr:"pipe"}).exited;}let oe=await PKG.which();if(!oe)return;H=oe,F.push("run",J);}if(!H)return;let te=await PKG.which();return te?{process:n(te,F,{cwd:Q}),initialization:{}}:void 0}},re.ESLint={id:"eslint",initTimeout:re.ServerInitTimeout.eslint,root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn(Q){if(!await PKG.resolve("eslint",R.directory).catch(()=>{}))return;e.info("spawning eslint server");let F=Se__default.join(a$1.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await PKG.file(F).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading and building VS Code ESLint server");let J=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!J.ok)return;let oe=Se__default.join(a$1.Path.bin,"vscode-eslint.zip");if(await PKG.write(oe,J),!await Archive.extractZip(oe,a$1.Path.bin).then(()=>true).catch(Ie=>(e.error("Failed to extract vscode-eslint archive",{error:Ie}),false)))return;await Tt__default.rm(oe,{force:true});let me=Se__default.join(a$1.Path.bin,"vscode-eslint-main"),ce=Se__default.join(a$1.Path.bin,"vscode-eslint");await Tt__default.stat(ce).catch(()=>{})&&(e.info("removing old eslint installation",{path:ce}),await Tt__default.rm(ce,{force:true,recursive:true})),await Tt__default.rename(me,ce);let je=process.platform==="win32"?"npm.cmd":"npm";await $`${je} install`.cwd(ce).quiet(),await $`${je} run compile`.cwd(ce).quiet(),e.info("installed VS Code ESLint server",{serverPath:F});}let te=await PKG.which();return te?{process:n(te,[F,"--stdio"],{cwd:Q,env:{...process.env},stderr:"ignore"})}:void 0}},re.Oxlint={id:"oxlint",initTimeout:re.ServerInitTimeout.oxlint,root:c([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn(Q){let H=process.platform==="win32"?".cmd":"",F=Se__default.join("node_modules",".bin","oxc_language_server"+H),te=Se__default.join("node_modules",".bin","oxlint"+H),V=async de=>{let me=Se__default.join(Q,de);if(await PKG.file(me).exists())return me;let ce=Filesystem.up({targets:[de],start:Q,stop:R.worktree}),ye=await ce.next();if(await ce.return(void 0),ye.value)return ye.value},J=await V(te);if(!J){let de=await PKG.which("oxlint");de&&(J=de);}if(J){let de=n(J,["--help"],{stdout:"pipe"});if(await de.exited,(await PKG.nodeReadableStreamToText(de.stdout)).includes("--lsp"))return {process:n(J,["--lsp"],{cwd:Q,stderr:"ignore"})}}let oe=await V(F);if(!oe){let de=await PKG.which("oxc_language_server");de&&(oe=de);}if(oe)return {process:n(oe,[],{cwd:Q,stderr:"ignore"})};e.info("oxlint not found, please install oxlint");}},re.Biome={id:"biome",initTimeout:re.ServerInitTimeout.biome,root:c(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn(Q){let H=process.platform==="win32",F=Se__default.join(Q,"node_modules",".bin",H?"biome.cmd":"biome");if(await PKG.file(F).exists())return {process:n(F,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})};let te=await PKG.which("biome");if(te)return {process:n(te,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})};if(H){let de=await PKG.which("biome.cmd");if(de)return {process:n(de,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})}}let V=Se__default.join(a$1.Path.bin,"node_modules","@biomejs","biome","bin","biome");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD){e.info("Biome LSP download disabled by flag");return}e.info("Installing @biomejs/biome...");let de=await PKG.which();if(!de){e.warn("Package manager not found");return}try{await n(de,["install","@biomejs/biome"],{cwd:a$1.Path.bin,env:process.env,stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited,e.info("Biome installed successfully");}catch(me){e.error("Failed to install biome",{error:me});return}}let J=await PKG.which();return J?{process:n(J,["run",V,"lsp-proxy","--stdio"],{cwd:Q,env:process.env,timeout:false,stderr:"ignore"})}:void 0}},re.Gopls={id:"gopls",initTimeout:re.ServerInitTimeout.gopls,root:async Q=>{let H=await c(["go.work"])(Q);return H||c(["go.mod","go.sum"])(Q)},extensions:[".go"],async spawn(Q){let H=await PKG.which("gopls",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("go")||a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing gopls");let te=await r("go install golang.org/x/tools/gopls@latest",{env:{...process.env,GOBIN:a$1.Path.bin}});if(te.code!==0){e.error("Failed to install gopls",{stderr:te.stderr});return}H=Se__default.join(a$1.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),e.info("installed gopls",{bin:H});}if(H)return {process:n(H)}}},re.Rubocop={id:"ruby-lsp",initTimeout:re.ServerInitTimeout.ruby_lsp,root:c(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(Q){let H=await PKG.which("rubocop",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){let F=await PKG.which("ruby"),te=await PKG.which("gem");if(!F||!te){e.info("Ruby not found, please install Ruby first");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing rubocop");let V=await r(`gem install rubocop --bindir "${a$1.Path.bin}"`);if(V.code!==0){e.error("Failed to install rubocop",{stderr:V.stderr});return}H=Se__default.join(a$1.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),e.info("installed rubocop",{bin:H});}if(H)return {process:n(H,["--lsp"],{cwd:Q,stderr:"ignore"})}}},re.Ty={id:"ty",initTimeout:re.ServerInitTimeout.ty,extensions:[".py",".pyi"],root:c(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(Q){if(!a$2.EASBOT_LSP_TY)return;let H=await PKG.which("ty"),F={},te=[process.env.VIRTUAL_ENV,Se__default.join(Q,".venv"),Se__default.join(Q,"venv")].filter(J=>J!==void 0);for(let J of te){let de=process.platform==="win32"?Se__default.join(J,"Scripts","python.exe"):Se__default.join(J,"bin","python");if(await PKG.file(de).exists()){F.pythonPath=de;break}}if(!H)for(let J of te){let de=process.platform==="win32"?Se__default.join(J,"Scripts","ty.exe"):Se__default.join(J,"bin","ty");if(await PKG.file(de).exists()){H=de;break}}if(!H){e.error("ty not found, please install ty first");return}return {process:n(H,["server"],{cwd:Q,stderr:"ignore"}),initialization:F}}},re.Pyright={id:"pyright",initTimeout:re.ServerInitTimeout.pyright,extensions:[".py",".pyi"],root:c(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(Q){let H=await PKG.which("pyright-langserver"),F=[];if(!H){let oe=Se__default.join(a$1.Path.bin,"node_modules","pyright","dist","pyright-langserver.js");if(!await PKG.file(oe).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let me=await PKG.which();if(!me)return;await r(`${me} install pyright`,{cwd:a$1.Path.bin,env:{...process.env}});}let de=await PKG.which();if(!de)return;H=de,F.push("run",oe);}F.push("--stdio");let te={},V=[process.env.VIRTUAL_ENV,Se__default.join(Q,".venv"),Se__default.join(Q,"venv")].filter(oe=>oe!==void 0);for(let oe of V){let me=process.platform==="win32"?Se__default.join(oe,"Scripts","python.exe"):Se__default.join(oe,"bin","python");if(await PKG.file(me).exists()){te.pythonPath=me;break}}return H?{process:n(H,F,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:te}:void 0}},re.ElixirLS={id:"elixir-ls",initTimeout:re.ServerInitTimeout.elixir_ls,extensions:[".ex",".exs"],root:c(["mix.exs","mix.lock"]),async spawn(Q){let H=await PKG.which("elixir-ls");if(!H){let F=Se__default.join(a$1.Path.bin,"elixir-ls");if(H=Se__default.join(a$1.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await PKG.file(H).exists()){if(!await PKG.which("elixir")){e.error("elixir is required to run elixir-ls");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading elixir-ls from GitHub releases");let V=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!V.ok)return;let J=Se__default.join(a$1.Path.bin,"elixir-ls.zip");if(await PKG.write(J,V),!await Archive.extractZip(J,a$1.Path.bin).then(()=>true).catch(de=>(e.error("Failed to extract elixir-ls archive",{error:de}),false)))return;await Tt__default.rm(J,{force:true,recursive:true}),await $`mix deps.get && mix compile && mix elixir_ls.release2 -o release`.quiet().cwd(Se__default.join(a$1.Path.bin,"elixir-ls-master")).env({MIX_ENV:"prod",...process.env}),e.info("installed elixir-ls",{path:F});}}if(H)return {process:n(H)}}},re.Zls={id:"zls",initTimeout:re.ServerInitTimeout.zls,extensions:[".zig",".zon"],root:c(["build.zig"]),async spawn(Q){let H=await PKG.which("zls",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("zig")){e.error("Zig is required to use zls. Please install Zig first.");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading zls from GitHub releases");let te=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!te.ok){e.error("Failed to fetch zls release info");return}let V=await te.json(),J=process.platform,oe=process.arch,de="",me=oe;oe==="arm64"?me="aarch64":oe==="x64"?me="x86_64":oe==="ia32"&&(me="x86");let ce=J;J==="darwin"?ce="macos":J==="win32"&&(ce="windows");let ye=J==="win32"?"zip":"tar.xz";if(de=`zls-${me}-${ce}.${ye}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(de)){e.error(`Platform ${J} and architecture ${oe} is not supported by zls`);return}let Ie=V.assets.find(Ae=>Ae.name===de);if(!Ie){e.error(`Could not find asset ${de} in latest zls release`);return}let Ce=Ie.browser_download_url,ie=await fetch(Ce);if(!ie.ok){e.error("Failed to download zls");return}let $e=Se__default.join(a$1.Path.bin,de);if(await PKG.write($e,ie),ye==="zip"){if(!await Archive.extractZip($e,a$1.Path.bin).then(()=>true).catch(pt=>(e.error("Failed to extract zls archive",{error:pt}),false)))return}else await $`tar -xf ${$e}`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm($e,{force:true}),H=Se__default.join(a$1.Path.bin,"zls"+(J==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract zls binary");return}J!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed zls",{bin:H});}return {process:n(H,[],{cwd:Q,stderr:"ignore"})}}},re.CSharp={id:"csharp",initTimeout:re.ServerInitTimeout.csharp,root:c([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn(Q){let H=await PKG.which("csharp-ls",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("dotnet")){e.error(".NET SDK is required to install csharp-ls");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing csharp-ls via dotnet tool");let te=await r(`dotnet tool install csharp-ls --tool-path "${a$1.Path.bin}"`);if(te.code!==0){e.error("Failed to install csharp-ls",{stderr:te.stderr});return}H=Se__default.join(a$1.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),e.info("installed csharp-ls",{bin:H});}return {process:n(H,[],{cwd:Q,stderr:"ignore"})}}},re.FSharp={id:"fsharp",initTimeout:re.ServerInitTimeout.fsharp,root:c([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(Q){let H=await PKG.which("fsautocomplete",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("dotnet")){e.error(".NET SDK is required to install fsautocomplete");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing fsautocomplete via dotnet tool");let te=await r(`dotnet tool install fsautocomplete --tool-path "${a$1.Path.bin}"`);if(te.code!==0){e.error("Failed to install fsautocomplete",{stderr:te.stderr});return}H=Se__default.join(a$1.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),e.info("installed fsautocomplete",{bin:H});}if(H)return {process:n(H,[],{cwd:Q,stderr:"ignore"})}}},re.SourceKit={id:"sourcekit-lsp",initTimeout:re.ServerInitTimeout.sourcekit_lsp,extensions:[".swift",".objc","objcpp"],root:c(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(Q){let H=await PKG.which("sourcekit-lsp");if(H)return {process:n(H,[],{cwd:Q,stderr:"ignore"})};if(!await PKG.which("xcrun"))return;let te=await $`xcrun --find sourcekit-lsp`.quiet().nothrow();if(te.exitCode!==0)return;let V=await te.text();if(V)return {process:n(V.trim(),[],{cwd:Q,stderr:"ignore"})}}},re.RustAnalyzer={id:"rust",initTimeout:re.ServerInitTimeout.rust,root:async Q=>{let H=await c(["Cargo.toml","Cargo.lock"])(Q);if(H===void 0)return;let F=H;for(;F!==Se__default.dirname(F);){let te=Se__default.join(F,"Cargo.toml");try{if((await PKG.file(te).text()).includes("[workspace]"))return F}catch{}let V=Se__default.dirname(F);if(V===F||(F=V,!F.startsWith(R.worktree)))break}return H},extensions:[".rs"],async spawn(Q){let H=await PKG.which("rust-analyzer");if(!H){e.info("rust-analyzer not found in path, please install it");return}return {process:s(H,[],{cwd:Q,stderr:"ignore"})}}},re.Clangd={id:"clangd",initTimeout:re.ServerInitTimeout.clangd,root:c(["compile_commands.json","compile_flags.txt",".clangd","CMakeLists.txt","Makefile"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(Q){let H=["--background-index","--clang-tidy"],F=await PKG.which("clangd");if(F)return {process:s(F,H,{cwd:Q,stderr:"ignore"})};let te=process.platform==="win32"?".exe":"",V=Se__default.join(a$1.Path.bin,"clangd"+te);if(await PKG.file(V).exists())return {process:s(V,H,{cwd:Q,stderr:"ignore"})};let J=await Tt__default.readdir(a$1.Path.bin,{withFileTypes:true}).catch(()=>[]);for(let Ht of J){if(!Ht.isDirectory()||!Ht.name.startsWith("clangd_"))continue;let Zs=Se__default.join(a$1.Path.bin,Ht.name,"bin","clangd"+te);if(await PKG.file(Zs).exists())return {process:s(Zs,H,{cwd:Q,stderr:"ignore"})}}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading clangd from GitHub releases");let oe=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!oe.ok){e.error("Failed to fetch clangd release info");return}let de=await oe.json(),me=de.tag_name;if(!me){e.error("clangd release did not include a tag name");return}let ce=process.platform,je={darwin:"mac",linux:"linux",win32:"windows"}[ce];if(!je){e.error(`Platform ${ce} is not supported by clangd auto-download`);return}let Ie=de.assets??[],Ce=Ht=>!Ht.name||!Ht.browser_download_url||!Ht.name.includes(je)?false:Ht.name.includes(me),ie=Ie.find(Ht=>Ce(Ht)&&Ht.name?.endsWith(".zip"))??Ie.find(Ht=>Ce(Ht)&&Ht.name?.endsWith(".tar.xz"))??Ie.find(Ht=>Ce(Ht));if(!ie?.name||!ie.browser_download_url){e.error("clangd could not match release asset",{tag:me,platform:ce});return}let $e=ie.name,Ae=await fetch(ie.browser_download_url);if(!Ae.ok){e.error("Failed to download clangd");return}let pt=Se__default.join(a$1.Path.bin,$e),Ct=await Ae.arrayBuffer();if(Ct.byteLength===0){e.error("Failed to write clangd archive");return}await PKG.write(pt,Buffer.from(Ct));let cn=$e.endsWith(".zip"),ri=$e.endsWith(".tar.xz");if(!cn&&!ri){e.error("clangd encountered unsupported asset",{asset:$e});return}if(cn&&!await Archive.extractZip(pt,a$1.Path.bin).then(()=>true).catch(Zs=>(e.error("Failed to extract clangd archive",{error:Zs}),false)))return;ri&&await $`tar -xf ${pt}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(pt,{force:true});let hs=Se__default.join(a$1.Path.bin,"clangd_"+me,"bin","clangd"+te);if(!await PKG.file(hs).exists()){e.error("Failed to extract clangd binary");return}return ce!=="win32"&&await $`chmod +x ${hs}`.quiet().nothrow(),await Tt__default.unlink(Se__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),await Tt__default.symlink(hs,Se__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),e.info("installed clangd",{bin:hs}),{process:n(hs,H,{cwd:Q,stderr:"ignore"})}}},re.Svelte={id:"svelte",initTimeout:re.ServerInitTimeout.svelte,extensions:[".svelte"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let H=await PKG.which("svelteserver"),F=[];if(!H){let V=Se__default.join(a$1.Path.bin,"node_modules","svelte-language-server","bin","server.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let oe=await PKG.which();if(!oe)return;await r(`${oe} install svelte-language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let J=await PKG.which();if(!J)return;H=J,F.push("run",V);}return H?(F.push("--stdio"),{process:n(H,F,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:{}}):void 0}},re.Astro={id:"astro",initTimeout:re.ServerInitTimeout.astro,extensions:[".astro"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let H=await PKG.resolve("typescript/lib/tsserver.js",R.directory).catch(()=>{});if(!H){e.info("typescript not found, required for Astro language server");return}let F=Se__default.dirname(H),te=await PKG.which("astro-ls"),V=[];if(!te){let oe=Se__default.join(a$1.Path.bin,"node_modules","@astrojs","language-server","bin","nodeServer.js");if(!await PKG.file(oe).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let me=await PKG.which();if(!me)return;await r(`${me} install @astrojs/language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let de=await PKG.which();if(!de)return;te=de,V.push("run",oe);}return te?(V.push("--stdio"),{process:n(te,V,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:{typescript:{tsdk:F}}}):void 0}},re.JDTLS={id:"jdtls",initTimeout:re.ServerInitTimeout.jdtls,root:c(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"]),extensions:[".java"],async spawn(Q){let H=await PKG.which("java");if(!H){e.error("Java 21 or newer is required to run the JDTLS. Please install it first.");return}let F=await $`java -version`.quiet().nothrow(),te=(()=>{let Ce=/"(\d+)\.\d+\.\d+"/.exec(F.stderr?.toString()??"");return Ce?.[1]?parseInt(Ce[1],10):void 0})();if(te==null||te<21){e.error("JDTLS requires at least Java 21.");return}let V=Se__default.join(a$1.Path.bin,"jdtls"),J=Se__default.join(V,"plugins");if(!await i(J)){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading JDTLS LSP server."),await Tt__default.mkdir(V,{recursive:true});let Ce="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",ie="release.tar.gz";e.info("Downloading JDTLS archive",{url:Ce,dest:V});let $e=await $`curl -L -o ${ie} '${Ce}'`.cwd(V).quiet().nothrow();if($e.exitCode!==0){e.error("Failed to download JDTLS",{exitCode:$e.exitCode,stderr:$e.stderr.toString()});return}e.info("Extracting JDTLS archive");let Ae=await $`tar -xzf ${ie}`.cwd(V).quiet().nothrow();if(Ae.exitCode!==0){e.error("Failed to extract JDTLS",{exitCode:Ae.exitCode,stderr:Ae.stderr.toString()});return}await Tt__default.rm(Se__default.join(V,ie),{force:true}),e.info("JDTLS download and extraction completed");}let me=(await $`ls org.eclipse.equinox.launcher_*.jar`.cwd(J).quiet().nothrow()).stdout?.toString().trim();if(!me){e.error(`Failed to find JDTLS launcher jar in ${J}.`);return}let ce=Se__default.join(J,me);if(!await i(ce)){e.error(`Failed to locate the JDTLS launcher module in the installed directory: ${V}.`);return}let ye=Se__default.join(V,(()=>{switch(process.platform){case "darwin":return "config_mac";case "linux":return "config_linux";case "win32":return "config_win";default:return "config_linux"}})()),je=await Tt__default.mkdtemp(Se__default.join(ec.tmpdir(),"easbot-jdtls-data"));return {process:o([H,"-jar",ce,"-configuration",ye,"-data",je,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens=java.base/java.util=ALL-UNNAMED","--add-opens=java.base/java.lang=ALL-UNNAMED"],{cwd:Q})}}},re.KotlinLS={id:"kotlin-ls",initTimeout:re.ServerInitTimeout.kotlin_ls,extensions:[".kt",".kts"],root:async Q=>{let H=await c(["settings.gradle.kts","settings.gradle"])(Q);if(H)return H;let F=await c(["gradlew","gradlew.bat"])(Q);if(F)return F;let te=await c(["build.gradle.kts","build.gradle"])(Q);return te||c(["pom.xml"])(Q)},async spawn(Q){let H=Se__default.join(a$1.Path.bin,"kotlin-ls"),F=process.platform==="win32"?Se__default.join(H,"kotlin-lsp.cmd"):Se__default.join(H,"kotlin-lsp.sh");if(!await PKG.file(F).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading Kotlin Language Server from GitHub.");let V=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!V.ok){e.error("Failed to fetch kotlin-lsp release info");return}let oe=(await V.json()).name?.replace(/^v/,"");if(!oe){e.error("Could not determine Kotlin LSP version from release");return}let de=process.platform,me=process.arch,ce=me;me==="arm64"?ce="aarch64":me==="x64"&&(ce="x64");let ye=de;de==="darwin"?ye="mac":de==="linux"?ye="linux":de==="win32"&&(ye="win");let je=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],Ie=`${ye}-${ce}`;if(!je.includes(Ie)){e.error(`Platform ${de}/${me} is not supported by Kotlin LSP`);return}let Ce=`kotlin-lsp-${oe}-${ye}-${ce}.zip`,ie=`https://download-cdn.jetbrains.com/kotlin-lsp/${oe}/${Ce}`;await Tt__default.mkdir(H,{recursive:true});let $e=Se__default.join(H,"kotlin-ls.zip");if(await $`curl -L -o '${$e}' '${ie}'`.quiet().nothrow(),!await Archive.extractZip($e,H).then(()=>true).catch(pt=>(e.error("Failed to extract Kotlin LS archive",{error:pt}),false)))return;await Tt__default.rm($e,{force:true}),process.platform!=="win32"&&await $`chmod +x ${F}`.quiet().nothrow(),e.info("Installed Kotlin Language Server",{path:F});}if(!await PKG.file(F).exists()){e.error(`Failed to locate the Kotlin LS launcher script in the installed directory: ${H}.`);return}return {process:n(F,["--stdio"],{cwd:Q,stderr:"ignore"})}}},re.YamlLS={id:"yaml-ls",initTimeout:re.ServerInitTimeout.yaml,extensions:[".yaml",".yml"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let H=await PKG.which("yaml-language-server"),F=[];if(!H){let V=Se__default.join(a$1.Path.bin,"node_modules","yaml-language-server","out","server","src","server.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let de=await PKG.which();if(!de)return;await r(`${de} install yaml-language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let oe=await PKG.which();if(!oe)return;H=oe,F.push("run",V);}return H?(F.push("--stdio"),{process:n(H,F,{cwd:Q,env:{...process.env},stderr:"ignore"})}):void 0}},re.LuaLS={id:"lua-ls",initTimeout:re.ServerInitTimeout.lua,root:c([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(Q){let H=await PKG.which("lua-language-server",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading lua-language-server from GitHub releases");let F=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!F.ok){e.error("Failed to fetch lua-language-server release info");return}let te=await F.json(),V=process.platform,J=process.arch,oe="",de=J;J==="arm64"?de="arm64":J==="x64"?de="x64":J==="ia32"&&(de="ia32");let me=V;V==="darwin"?me="darwin":V==="linux"?me="linux":V==="win32"&&(me="win32");let ce=V==="win32"?"zip":"tar.gz";oe=`lua-language-server-${te.tag_name}-${me}-${de}.${ce}`;let ye=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],je=`${me}-${de}.${ce}`;if(!ye.includes(je)){e.error(`Platform ${V} and architecture ${J} is not supported by lua-language-server`);return}let Ie=te.assets.find(Ct=>Ct.name===oe);if(!Ie){e.error(`Could not find asset ${oe} in latest lua-language-server release`);return}let Ce=Ie.browser_download_url,ie=await fetch(Ce);if(!ie.ok){e.error("Failed to download lua-language-server");return}let $e=Se__default.join(a$1.Path.bin,oe);await PKG.write($e,ie);let Ae=Se__default.join(a$1.Path.bin,`lua-language-server-${de}-${me}`);if(await Tt__default.stat(Ae).catch(()=>{})&&await Tt__default.rm(Ae,{force:true,recursive:true}),await Tt__default.mkdir(Ae,{recursive:true}),ce==="zip"){if(!await Archive.extractZip($e,Ae).then(()=>true).catch(cn=>(e.error("Failed to extract lua-language-server archive",{error:cn}),false)))return}else if(!await $`tar -xzf ${$e} -C ${Ae}`.quiet().then(()=>true).catch(cn=>(e.error("Failed to extract lua-language-server archive",{error:cn}),false)))return;if(await Tt__default.rm($e,{force:true}),H=Se__default.join(Ae,"bin","lua-language-server"+(V==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract lua-language-server binary");return}if(V!=="win32"&&!await $`chmod +x ${H}`.quiet().catch(cn=>{e.error("Failed to set executable permission for lua-language-server binary",{error:cn});}))return;e.info("installed lua-language-server",{bin:H});}return {process:n(H,[],{cwd:Q,stderr:"ignore"})}}},re.PHPIntelephense={id:"php intelephense",initTimeout:re.ServerInitTimeout.intelephense,extensions:[".php"],root:c(["composer.json","composer.lock",".php-version"]),async spawn(Q){let H=await PKG.which("intelephense"),F=[];if(!H){let V=Se__default.join(a$1.Path.bin,"node_modules","intelephense","lib","intelephense.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let oe=await PKG.which();if(!oe)return;await r(`${oe} install intelephense`,{cwd:a$1.Path.bin,env:{...process.env}});}let J=await PKG.which();if(!J)return;H=J,F.push("run",V);}return H?(F.push("--stdio"),{process:n(H,F,{cwd:Q,env:{...process.env}}),initialization:{telemetry:{enabled:false}}}):void 0}},re.Prisma={id:"prisma",initTimeout:re.ServerInitTimeout.prisma,extensions:[".prisma"],root:c(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(Q){let H=await PKG.which("prisma");if(!H){e.info("prisma not found, please install prisma");return}return {process:n(H,["language-server"],{cwd:Q,stderr:"ignore"})}}},re.Dart={id:"dart",initTimeout:re.ServerInitTimeout.dart,extensions:[".dart"],root:c(["pubspec.yaml","analysis_options.yaml"]),async spawn(Q){let H=await PKG.which("dart");if(!H){e.info("dart not found, please install dart first");return}return {process:s(H,["language-server","--lsp"],{cwd:Q,stderr:"ignore"})}}},re.Ocaml={id:"ocaml-lsp",initTimeout:re.ServerInitTimeout.ocaml_lsp,extensions:[".ml",".mli"],root:c(["dune-project","dune-workspace",".merlin","opam"]),async spawn(Q){let H=await PKG.which("ocamllsp");if(!H){e.info("ocamllsp not found, please install ocaml-lsp-server");return}return {process:s(H,[],{cwd:Q,stderr:"ignore"})}}},re.BashLS={id:"bash",initTimeout:re.ServerInitTimeout.bash,extensions:[".sh",".bash",".zsh",".ksh"],root:async()=>R.directory,async spawn(Q){let H=await PKG.which("bash-language-server"),F=[];if(!H){let V=Se__default.join(a$1.Path.bin,"node_modules","bash-language-server","out","cli.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let oe=await PKG.which();if(!oe)return;await r(`${oe} install bash-language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let J=await PKG.which();if(!J)return;H=J,F.push("run",V);}return H?(F.push("start"),{process:n(H,F,{cwd:Q,env:{...process.env}})}):void 0}},re.TerraformLS={id:"terraform",initTimeout:re.ServerInitTimeout.terraform,extensions:[".tf",".tfvars"],root:c([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(Q){let H=await PKG.which("terraform-ls",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading terraform-ls from GitHub releases");let F=await fetch("https://api.github.com/repos/hashicorp/terraform-ls/releases/latest");if(!F.ok){e.error("Failed to fetch terraform-ls release info");return}let te=await F.json(),V=te.tag_name?.replace("v","");if(!V){e.error("terraform-ls release did not include a version tag");return}let J=process.platform,de=process.arch==="arm64"?"arm64":"amd64",ce=`terraform-ls_${V}_${J==="win32"?"windows":J}_${de}.zip`,je=(te.assets??[]).find($e=>$e.name===ce);if(!je?.browser_download_url){e.error(`Could not find asset ${ce} in terraform-ls release`);return}let Ie=await fetch(je.browser_download_url);if(!Ie.ok){e.error("Failed to download terraform-ls");return}let Ce=Se__default.join(a$1.Path.bin,ce);if(await PKG.write(Ce,Ie),!await Archive.extractZip(Ce,a$1.Path.bin).then(()=>true).catch($e=>(e.error("Failed to extract terraform-ls archive",{error:$e}),false)))return;if(await Tt__default.rm(Ce,{force:true}),H=Se__default.join(a$1.Path.bin,"terraform-ls"+(J==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract terraform-ls binary");return}J!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed terraform-ls",{bin:H});}return {process:s(H,["serve"],{cwd:Q,stderr:"ignore"}),initialization:{experimentalFeatures:{prefillRequiredFields:true,validateOnSave:true}}}}},re.TexLab={id:"texlab",initTimeout:re.ServerInitTimeout.texlab,extensions:[".tex",".bib"],root:c([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(Q){let H=await PKG.which("texlab",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading texlab from GitHub releases");let F=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!F.ok){e.error("Failed to fetch texlab release info");return}let te=await F.json();if(!te.tag_name?.replace("v","")){e.error("texlab release did not include a version tag");return}let J=process.platform,de=process.arch==="arm64"?"aarch64":"x86_64",me=J==="darwin"?"macos":J==="win32"?"windows":"linux",ce=J==="win32"?"zip":"tar.gz",ye=`texlab-${de}-${me}.${ce}`,Ie=(te.assets??[]).find($e=>$e.name===ye);if(!Ie?.browser_download_url){e.error(`Could not find asset ${ye} in texlab release`);return}let Ce=await fetch(Ie.browser_download_url);if(!Ce.ok){e.error("Failed to download texlab");return}let ie=Se__default.join(a$1.Path.bin,ye);if(await PKG.write(ie,Ce),ce==="zip"&&!await Archive.extractZip(ie,a$1.Path.bin).then(()=>true).catch(Ae=>(e.error("Failed to extract texlab archive",{error:Ae}),false)))return;if(ce==="tar.gz"&&await $`tar -xzf ${ie}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(ie,{force:true}),H=Se__default.join(a$1.Path.bin,"texlab"+(J==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract texlab binary");return}J!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed texlab",{bin:H});}return {process:s(H,[],{cwd:Q,stderr:"ignore"})}}},re.DockerfileLS={id:"dockerfile",initTimeout:re.ServerInitTimeout.dockerfile,extensions:[".dockerfile","Dockerfile"],root:async()=>R.directory,async spawn(Q){let H=await PKG.which("docker-langserver"),F=[];if(!H){let V=Se__default.join(a$1.Path.bin,"node_modules","dockerfile-language-server-nodejs","lib","server.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let oe=await PKG.which();if(!oe)return;await r(`${oe} install dockerfile-language-server-nodejs`,{cwd:a$1.Path.bin,env:{...process.env}});}let J=await PKG.which();if(!J)return;H=J,F.push("run",V);}return H?(F.push("--stdio"),{process:n(H,F,{cwd:Q,env:{...process.env}})}):void 0}},re.Gleam={id:"gleam",initTimeout:re.ServerInitTimeout.gleam,extensions:[".gleam"],root:c(["gleam.toml"]),async spawn(Q){let H=await PKG.which("gleam");if(!H){e.info("gleam not found, please install gleam first");return}return {process:s(H,["lsp"],{cwd:Q,stderr:"ignore"})}}},re.Clojure={id:"clojure-lsp",initTimeout:re.ServerInitTimeout.clojure_lsp,extensions:[".clj",".cljs",".cljc",".edn"],root:c(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(Q){let H=await PKG.which("clojure-lsp");if(!H&&process.platform==="win32"&&(H=await PKG.which("clojure-lsp.exe")),!H){e.info("clojure-lsp not found, please install clojure-lsp first");return}return {process:s(H,["listen"],{cwd:Q,stderr:"ignore"})}}},re.Nixd={id:"nixd",initTimeout:re.ServerInitTimeout.nixd,extensions:[".nix"],root:async Q=>{let H=await c(["flake.nix"])(Q);return H&&H!==R.directory?H:R.worktree&&R.worktree!==R.directory?R.worktree:R.directory},async spawn(Q){let H=await PKG.which("nixd");if(!H){e.info("nixd not found, please install nixd first");return}return {process:s(H,[],{cwd:Q,env:{...process.env},stderr:"ignore"})}}},re.Tinymist={id:"tinymist",initTimeout:re.ServerInitTimeout.tinymist,extensions:[".typ",".typc"],root:c(["typst.toml"]),async spawn(Q){let H=await PKG.which("tinymist",{PATH:process.env.PATH+Se__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading tinymist from GitHub releases");let F=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!F.ok){e.error("Failed to fetch tinymist release info");return}let te=await F.json(),V=process.platform,oe=process.arch==="arm64"?"aarch64":"x86_64",de,me;V==="darwin"?(de="apple-darwin",me="tar.gz"):V==="win32"?(de="pc-windows-msvc",me="zip"):(de="unknown-linux-gnu",me="tar.gz");let ce=`tinymist-${oe}-${de}.${me}`,je=(te.assets??[]).find(ie=>ie.name===ce);if(!je?.browser_download_url){e.error(`Could not find asset ${ce} in tinymist release`);return}let Ie=await fetch(je.browser_download_url);if(!Ie.ok){e.error("Failed to download tinymist");return}let Ce=Se__default.join(a$1.Path.bin,ce);if(await PKG.write(Ce,Ie),me==="zip"){if(!await Archive.extractZip(Ce,a$1.Path.bin).then(()=>true).catch($e=>(e.error("Failed to extract tinymist archive",{error:$e}),false)))return}else await $`tar -xzf ${Ce} --strip-components=1`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm(Ce,{force:true}),H=Se__default.join(a$1.Path.bin,"tinymist"+(V==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract tinymist binary");return}V!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed tinymist",{bin:H});}return {process:s(H,[],{cwd:Q,stderr:"ignore"})}}},re.HLS={id:"haskell-language-server",initTimeout:re.ServerInitTimeout.haskell_language_server,extensions:[".hs",".lhs"],root:c(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(Q){let H=await PKG.which("haskell-language-server-wrapper");if(!H){e.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return {process:s(H,["--lsp"],{cwd:Q,stderr:"ignore"})}}};})(bo||(bo={}));var Ap=(o=>(o.STDIO="stdio",o.HTTP="http",o.WS="websocket",o))(Ap||{});function Dy(e){return e==="local"?"stdio":e}var Ep=z.object({command:z.string(),args:z.array(z.string())}),Rp=z.object({baseUrl:z.string().url(),timeout:z.number().positive().default(3e4)}).strict(),_p=z.object({url:z.string().url(),timeout:z.number().positive().default(3e4),batchSize:z.number().positive().default(10),batchInterval:z.number().positive().default(50),heartbeatInterval:z.number().positive().default(3e4)}),$y=z.object({stdio:Ep.optional(),http:Rp.optional(),ws:_p.optional()});function Fy(e){if(!e||e.trim()==="")return false;let t=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/;return !(e.startsWith("-")||e.endsWith("-")||!t.test(e))}var Ny=z.object({id:z.string().min(1),options:z.record(z.string(),z.unknown()).optional()}),Uy=z.object({agent:z.string().optional(),model:Ny.optional()}),Mp=z.object({directory:z.string().default(process.cwd()),enabled:z.boolean().default(true),channel:z.preprocess(Dy,z.enum(["stdio","http","websocket"])).default("websocket"),port:z.number().int().min(1).max(65535).default(3e3),hostname:z.string().min(1).default("localhost"),timeout:z.number().positive().default(3e4),name:z.string().optional(),agentId:z.string().optional(),stdio:Ep.optional(),http:Rp.optional(),ws:_p.optional(),agent:Uy.optional()}).refine(e=>!!Fy(e.hostname),{message:"Invalid hostname format",path:["hostname"]}).transform(e=>{let n={stdio:"stdio",http:"http",websocket:"websocket"}[e.channel]??"websocket";return {...e,channel:n}}),zy=z.object({id:z.string().min(1),type:z.enum(["easbot","custom"]),name:z.string().optional(),agentId:z.string().optional(),channel:z.enum(["stdio","http","websocket"]).optional(),connection:$y,autoConnect:z.boolean().default(false),priority:z.number().int().nonnegative().default(0)}).transform(e=>{let t=e.channel;t||(e.connection.ws?t="websocket":e.connection.http?t="http":e.connection.stdio?t="stdio":t="websocket");let o={stdio:"stdio",http:"http",websocket:"websocket"}[t]??"websocket";return {...e,channel:o}}),Op=z.object({clients:z.array(zy).min(1),defaultClientId:z.string().optional()});z.object({server:Mp});z.object({clients:Op});var Dd=z.object({server:Mp,clients:Op.optional()}),jp={enabled:true,directory:process.cwd(),channel:"websocket",port:3e3,hostname:"localhost",timeout:3e4};var $d=N.object({model:N.string().optional().describe("Embedding model, defaults to config embedding model"),batchSize:N.number().int().positive().optional().describe("Batch size for embedding operations"),dimensions:N.number().int().positive().optional().describe("Embedding dimensions (optional, auto-detect)")}).optional(),Fd=N.object({maxResults:N.number().int().positive().optional().describe("Max search results"),minScore:N.number().min(0).max(1).optional().describe("Min score threshold (default: 0.3)"),hybrid:N.object({enabled:N.boolean().optional().describe("Enable hybrid search"),vectorWeight:N.number().min(0).max(1).optional().describe("Vector search weight (default: 0.7)"),textWeight:N.number().min(0).max(1).optional().describe("FTS text search weight (default: 0.3)")}).optional().describe("Hybrid search configuration")}).optional().describe("Search configuration"),Lp=N.object({ignorePatterns:N.array(N.string()).optional().describe("File patterns to ignore"),batchSize:N.number().int().positive().optional().describe("Batch size for indexing"),incremental:N.boolean().optional().describe("Enable incremental indexing")}).optional(),Dp=N.object({onBoot:N.boolean().optional().describe("Sync on boot"),onSearch:N.boolean().optional().describe("Sync on search"),onSessionStart:N.boolean().optional().describe("Sync on session start"),intervalMs:N.number().int().positive().optional().describe("Sync interval in milliseconds")}).optional().describe("Sync configuration"),Nd=N.object({dictPath:N.array(N.string()).optional().describe("Custom dictionary paths")}).optional().describe("Tokenizer configuration"),qy=N.object({model:N.string().optional().describe("Rerank model, defaults to config rerank_model"),topK:N.number().int().positive().optional().describe("Number of candidates for reranking")}).optional().describe("Rerank configuration"),$p=N.object({model:N.string().optional().describe("Graph LLM model, defaults to config graph_model"),entityExtractionPrompt:N.string().optional().describe("Entity extraction prompt template"),relationExtractionPrompt:N.string().optional().describe("Relation extraction prompt template")}).optional().describe("Graph LLM configuration for entity and relation extraction"),Pa=N.object({enabled:N.boolean().optional().describe("Enable codebase knowledge base"),database:N.string().optional().describe("Codebase database path"),embedding:$d,search:Fd,indexer:Lp,tokenizer:Nd,sync:Dp,parser:N.object({languages:N.array(N.string()).optional().describe("Supported languages"),lazyLoad:N.boolean().optional().describe("Lazy load parsers")}).optional().describe("Code parser configuration")}).optional().describe("Codebase knowledge base configuration"),Ta=N.object({enabled:N.boolean().optional().describe("Enable memory knowledge base"),workspaceDir:N.string().optional().describe("Memory workspace directory (contains MEMORY.md, active/, archive/)"),sessionsDir:N.string().optional().describe("Sessions directory for extracting historical long-term memory"),database:N.string().optional().describe("Memory database path"),embedding:$d,graph:$p,search:Fd,tokenizer:Nd,archiveDays:N.number().int().positive().optional().describe("Days before archiving memories (default: 30)"),shortTermMaxRounds:N.number().int().positive().optional().describe("Max rounds for short-term memory (default: 20)")}).optional().describe("Memory knowledge base configuration"),Aa=N.object({enabled:N.boolean().optional().describe("Enable note knowledge base"),database:N.string().optional().describe("Note database path"),search:Fd,indexer:Lp,tokenizer:Nd,sync:Dp,embedding:$d,graph:$p,rerank:qy,extraPaths:N.array(N.string()).optional().describe("Extra search paths (extended directories)"),sources:N.array(N.enum(["docs"])).optional().describe("Source types"),chunkSize:N.number().int().positive().optional().describe("Chunk size"),chunkOverlap:N.number().int().min(0).optional().describe("Chunk overlap size")}).optional().describe("Note knowledge base configuration"),kn=a.create({service:"knowledge-loader"});async function nr(){try{let t=(await he.get())?.note;if(!t){kn.debug("No note config found in Config.Info");return}let n=Aa.safeParse(t);if(n.success)return kn.debug("Note config loaded"),n.data;kn.warn("Invalid note config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load note config",{error:e});return}}async function or(){try{let t=(await he.get())?.codebase;if(!t){kn.debug("No codebase config found in Config.Info");return}let n=Pa.safeParse(t);if(n.success)return kn.debug("Codebase config loaded"),n.data;kn.warn("Invalid codebase config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load codebase config",{error:e});return}}async function sr(){try{let e=await he.get();kn.debug("loadMemory() configState.memory",{memoryConfig:e?.memory});let t=e?.memory;if(!t){kn.debug("No memory config found in Config.Info");return}let n=Ta.safeParse(t);if(n.success)return kn.debug("Memory config loaded",{data:n.data}),n.data;kn.warn("Invalid memory config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load memory config",{error:e});return}}async function Ud(){let e={},[t,n,o]=await Promise.all([nr(),or(),sr()]);return t&&(e.note=t),n&&(e.codebase=n),o&&(e.memory=o),kn.debug("Knowledge configs loaded",{types:Object.keys(e),count:Object.keys(e).length}),e}var Fp="easbot-oauth-dummy-key",Qe;(d=>{d.Oauth=N.object({type:N.literal("oauth"),refresh:N.string(),access:N.string(),expires:N.number(),accountId:N.string().optional(),enterpriseUrl:N.string().optional()}).meta({ref:"OAuth"}),d.Api=N.object({type:N.literal("api"),key:N.string()}).meta({ref:"ApiAuth"}),d.WellKnown=N.object({type:N.literal("wellknown"),key:N.string(),token:N.string()}).meta({ref:"WellKnownAuth"}),d.Info=N.discriminatedUnion("type",[d.Oauth,d.Api,d.WellKnown]).meta({ref:"Auth"});let s=Se__default.join(a$1.Path.data,"auth.json");async function r(m){return (await i())[m]}d.get=r;async function i(){let f=await PKG.file(s).json().catch(()=>({}));return Object.entries(f).reduce((a,[p,u])=>{let h=d.Info.safeParse(u);return h.success&&(a[p]=h.data),a},{})}d.all=i;async function c(m,f){let a=await i();await PKG.write(s,JSON.stringify({...a,[m]:f},null,2));}d.set=c;async function l(m){let f=await i();delete f[m],await PKG.write(s,JSON.stringify(f,null,2));}d.remove=l;})(Qe||(Qe={}));function no(e,t){let n=mergeDeep(e,t);return e.plugin&&t.plugin&&(n.plugin=Array.from(new Set([...e.plugin,...t.plugin]))),e.instructions&&t.instructions&&(n.instructions=Array.from(new Set([...e.instructions,...t.instructions]))),n}var qd=a.create({service:"config"});async function Zy(e){try{return await Tt__default.access(e,constants.W_OK),!0}catch{return false}}async function ii(e){if(!await Zy(e))return qd.debug("config dir is not writable, skipping dependency install",{dir:e}),false;let n=Se__default.join(e,"node_modules");if(!existsSync(n))return true;let o=Se__default.join(e,"package.json"),s=PKG.file(o);if(!await s.exists())return true;let l=((await s.json().catch(()=>null))?.dependencies??{})["@easbot/plugin"];if(!l)return true;let d=b$3.isLocal()?"latest":b$3.getVersion();return d==="latest"?await PackageRegistry.isOutdated("@easbot/plugin",l,e)?(qd.info("Cached version is outdated, proceeding with install",{pkg:"@easbot/plugin",cachedVersion:l}),true):false:l!==d}async function ai(e){let t=Se__default.join(e,"package.json"),n=b$3.isLocal()?"*":b$3.getVersion(),o=await PKG.file(t).json().catch(()=>({}));o.dependencies={...o.dependencies,"@easbot/plugin":n},await PKG.write(t,JSON.stringify(o,null,2)),await new Promise(d=>setTimeout(d,3e3));let s=Se__default.join(e,".gitignore");await PKG.file(s).exists()||await PKG.write(s,["node_modules","package.json","package-lock.json","pnpm-lock.yaml","bun.lock",".gitignore"].join(`
|
|
2
|
+
`));let i=await PKG.packageManager();if(!i){qd.debug("No package manager found, skipping install");return}let c=proxied()?" --no-cache":"",l=process.platform==="win32"?"cmd":void 0;await Shell.run(l,`${i.name} install${c}`,{cwd:e}).catch(()=>{});}var Bd=a.create({service:"config"}),Eo=NamedError.create("ConfigJsonError",N.object({path:N.string(),message:N.string().optional()})),oo=NamedError.create("ConfigInvalidError",N.object({path:N.string(),issues:N.custom().optional(),message:N.string().optional()}));async function so(e){Bd.info("loading",{path:e});let t=await PKG.file(e).text().catch(n=>{if(n.code!=="ENOENT")throw new Eo({path:e},{cause:n})});return t?ir(t,e):{}}async function ir(e,t){let n=e;e=e.replace(/\{env:([^}]+)\}/g,(c,l)=>process.env[l]||"");let o=e.match(/\{file:[^}]+\}/g);if(o){let c=Se__default.dirname(t),l=e.split(`
|
|
3
|
+
`);for(let d of o){let m=l.findIndex(h=>h.includes(d)),f=l[m];if(m!==-1&&f?.trim().startsWith("//"))continue;let a=d.replace(/^\{file:/,"").replace(/\}$/,"");a.startsWith("~/")&&(a=Se__default.join(ec.homedir(),a.slice(2)));let p=Se__default.isAbsolute(a)?a:Se__default.resolve(c,a),u=(await PKG.file(p).text().catch(h=>{let g=`bad file reference: "${d}"`;throw h.code==="ENOENT"?new oo({path:t,message:g+` ${p} does not exist`},{cause:h}):new oo({path:t,message:g},{cause:h})})).trim();e=e.replace(d,()=>JSON.stringify(u).slice(1,-1));}}let s=[],r=parse$1(e,s,{allowTrailingComma:true});if(s.length>0){let c=e.split(`
|
|
4
|
+
`),l=s.map(d=>{let m=e.substring(0,d.offset).split(`
|
|
5
|
+
`),f=m.length,a=m[m.length-1]?.length??1,p=c[f-1],u=`${printParseErrorCode(d.error)} at line ${f}, column ${a}`;return p?`${u}
|
|
6
|
+
Line ${f}: ${p}
|
|
7
|
+
${"".padStart(a+9)}^`:u}).join(`
|
|
8
|
+
`);throw new Eo({path:t,message:`
|
|
9
|
+
--- JSONC Input ---
|
|
10
|
+
${e}
|
|
11
|
+
--- Errors ---
|
|
12
|
+
${l}
|
|
13
|
+
--- End ---`})}let i=cr.safeParse(r);if(i.success){if(!i.data.$schema){i.data.$schema="https://easbot.cn/config.json";let l=n.replace(/^\s*\{/,`{
|
|
14
|
+
"$schema": "https://easbot.cn/config.json",`);await PKG.write(t,l).catch(()=>{});}let c=i.data;if(c.plugin)for(let l=0;l<c.plugin.length;l++){let d=c.plugin[l];if(d)try{c.plugin[l]=import.meta.resolve(d,t);}catch{}}return c}throw Bd.error("Configuration validation failed",{path:t,issues:i.error.issues}),new oo({path:t,issues:i.error.issues})}function ar(e,t){let n=[],o=parse$1(e,n,{allowTrailingComma:true});if(n.length>0){let r=e.split(`
|
|
15
|
+
`),i=n.map(c=>{let l=e.substring(0,c.offset).split(`
|
|
16
|
+
`),d=l.length,m=l[l.length-1]?.length??1,f=r[d-1],a=`${printParseErrorCode(c.error)} at line ${d}, column ${m}`;return f?`${a}
|
|
17
|
+
Line ${d}: ${f}
|
|
18
|
+
${"".padStart(m+9)}^`:a}).join(`
|
|
19
|
+
`);throw new Eo({path:t,message:`
|
|
20
|
+
--- JSONC Input ---
|
|
21
|
+
${e}
|
|
22
|
+
--- Errors ---
|
|
23
|
+
${i}
|
|
24
|
+
--- End ---`})}let s=cr.safeParse(o);if(s.success)return s.data;throw Bd.error("Configuration validation failed",{path:t,issues:s.error.issues}),new oo({path:t,issues:s.error.issues})}var rb=a.create({service:"config"});function ib(e,t){for(let n of t){let o=e.indexOf(n);if(o!==-1)return e.slice(o+n.length)}}function ab(e){let t=Se__default.extname(e);return t.length>0?e.slice(0,-t.length):e}var cb=new PKG.Glob("{agent,agents}/**/*.md");async function ci(e){let{Agent:t}=await import('./types-OIHWEQYC.mjs'),n={};for await(let o of cb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(o).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse agent ${o}`,{Session:a}=await import('./session-5OU5P7UF.mjs');await pe.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),rb.error("failed to load agent",{agent:o,err:m});});if(!s)continue;let i=ib(o,["/.easbot/agent/","/.easbot/agents/","/agent/","/agents/"])??Se__default.basename(o),l={name:ab(i),...s.data,prompt:s.content.trim()},d=t.safeParse(l);if(d.success){n[l.name]=d.data;continue}throw new oo({path:o,issues:d.error.issues},{cause:d.error})}return n}var pb=a.create({service:"config"});function mb(e,t){for(let n of t){let o=e.indexOf(n);if(o!==-1)return e.slice(o+n.length)}}function fb(e){let t=Se__default.extname(e);return t.length>0?e.slice(0,-t.length):e}var gb=new PKG.Glob("{command,commands}/**/*.md");async function di(e){let{Command:t}=await import('./types-OIHWEQYC.mjs'),n={};for await(let o of gb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(o).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse command ${o}`,{Session:a}=await import('./session-5OU5P7UF.mjs');await pe.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),pb.error("failed to load command",{command:o,err:m});});if(!s)continue;let i=mb(o,["/.easbot/command/","/.easbot/commands/","/command/","/commands/"])??Se__default.basename(o),l={name:fb(i),...s.data,template:s.content.trim()},d=t.safeParse(l);if(d.success){n[l.name]=d.data;continue}throw new oo({path:o,issues:d.error.issues},{cause:d.error})}return n}var xb=new PKG.Glob("{plugin,plugins}/*.{ts,js}");async function li(e){let t=[];for await(let n of xb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e}))t.push(pathToFileURL(n).href);return t}function _a(e){if(e.startsWith("file://"))return Se__default.parse(new URL(e).pathname).name;let t=e.lastIndexOf("@");return t>0?e.substring(0,t):e}function ui(e){let t=new Set,n=[];for(let o of e.toReversed()){let s=_a(o);t.has(s)||(t.add(s),n.push(o));}return n.toReversed()}var dr=a.create({service:"config"}),Bp=process.env.EASBOT_TEST_MANAGED_CONFIG_DIR||Ab();function Ab(){switch(process.platform){case "darwin":return "/Library/Application Support/easbot";case "win32":return Se__default.join(process.env.ProgramData||"C:\\ProgramData","easbot");default:return "/etc/easbot"}}var Wd;function Eb(){return Wd||(Wd=R.state(async()=>{let e=await Qe.all(),t={};for(let[s,r]of Object.entries(e))if(r.type==="wellknown"){process.env[r.key]=r.token,dr.debug("fetching remote config",{url:`${s}/.well-known/easbot`});let i=await Fetch.get(`${s}/.well-known/easbot`);if(!i.ok)throw new Error(`failed to fetch remote config from ${s}: ${i.status}`);let l=i.data.config??{};l.$schema||(l.$schema="https://easbot.cn/config.json"),t=no(t,await ir(JSON.stringify(l),`${s}/.well-known/easbot`)),dr.debug("loaded remote config from well-known",{url:s});}if(t=no(t,await fi()),!a$2.EASBOT_DISABLE_PROJECT_CONFIG)for(let s of ["easbot.json"]){let r=await Filesystem.findUp(s,R.directory,R.worktree);for(let i of r.toReversed())t=no(t,await so(i));}a$2.EASBOT_CONFIG&&(t=no(t,await so(a$2.EASBOT_CONFIG)),dr.debug("loaded custom config",{path:a$2.EASBOT_CONFIG})),t.agent=t.agent||{},t.plugin=t.plugin||[];let n=[a$1.Path.config,...a$2.EASBOT_DISABLE_PROJECT_CONFIG?[]:await Array.fromAsync(Filesystem.up({targets:[".easbot"],start:R.directory,stop:R.worktree})),...await Array.fromAsync(Filesystem.up({targets:[".easbot"],start:a$1.Path.home,stop:a$1.Path.home}))];a$2.EASBOT_CONFIG_DIR&&(n.push(a$2.EASBOT_CONFIG_DIR),dr.debug("loading config from EASBOT_CONFIG_DIR",{path:a$2.EASBOT_CONFIG_DIR}));let o=[];for(let s of unique(n)){if(s.endsWith(".easbot")||s===a$2.EASBOT_CONFIG_DIR)for(let r of ["easbot.json"])dr.debug(`loading config from ${Se__default.join(s,r)}`),t=no(t,await so(Se__default.join(s,r))),t.agent??(t.agent={}),t.plugin??(t.plugin=[]);o.push(iife(async()=>{await ii(s)&&await ai(s);})),t.command=mergeDeep(t.command??{},await di(s)),t.agent=mergeDeep(t.agent,await ci(s)),t.plugin.push(...await li(s));}if(a$2.EASBOT_CONFIG_CONTENT&&(t=no(t,JSON.parse(a$2.EASBOT_CONFIG_CONTENT)),dr.debug("loaded custom config from EASBOT_CONFIG_CONTENT")),existsSync(Bp))for(let s of ["easbot.json"])t=no(t,await so(Se__default.join(Bp,s)));if(a$2.EASBOT_PERMISSION&&(t.permission=mergeDeep(t.permission??{},JSON.parse(a$2.EASBOT_PERMISSION))),t.tools){await import('./types-OIHWEQYC.mjs');let r={};for(let[i,c]of Object.entries(t.tools)){let l=c?"allow":"deny";if(i==="write"||i==="edit"||i==="patch"||i==="multiedit"){r.edit=l;continue}r[i]=l;}t.permission=mergeDeep(r,t.permission??{});}if(t.username||(t.username=ec.userInfo().username),t.autoshare===true&&!t.share&&(t.share="auto"),!t.keybinds){let{Info:s}=await import('./types-OIHWEQYC.mjs');t.keybinds=s.shape.keybinds.parse({});}return a$2.EASBOT_DISABLE_AUTOCOMPACT&&(t.compaction={...t.compaction,auto:false}),a$2.EASBOT_DISABLE_PRUNE&&(t.compaction={...t.compaction,prune:{enabled:false}}),t.plugin=ui(t.plugin??[]),{config:t,directories:n,deps:o}})),Wd}function lr(){return Eb()()}async function Vd(){let e=await lr().then(t=>t.deps);await Promise.all(e);}async function Ro(){return lr().then(e=>e.config)}async function Kd(){return lr().then(e=>e.directories)}var fi=lazy(async()=>{let e={},{pipe:t}=await import('remeda');return e=t({},mergeDeep(await so(Se__default.join(a$1.Path.config,"easbot.json")))),e});async function Jd(){return fi()}var _b=N.object({enabled:N.boolean().optional(),timeThresholdMs:N.number().int().nonnegative().optional(),keepRecentTools:N.number().int().positive().optional(),tokenThreshold:N.number().int().nonnegative().optional(),protectedTools:N.array(N.string()).optional()}),Mb=N.object({enabled:N.boolean().optional(),ttlMs:N.number().int().positive().optional(),maxSizeBytes:N.number().int().positive().optional(),maxEntries:N.number().int().positive().optional(),persist:N.boolean().optional()}),Yd=N.object({auto:N.boolean().optional(),prune:_b.optional(),reserved:N.number().int().min(0).optional(),backup:Mb.optional()}),Wp=a.create({service:"compaction-loader"}),Vp={enabled:true,timeThresholdMs:3e5,keepRecentTools:3,tokenThreshold:5e3,protectedTools:["skill"]},Kp={enabled:true,ttlMs:3e5,maxSizeBytes:25*1024*1024,maxEntries:100,persist:false},Jp={auto:true};async function gi(){try{let t=(await Ro())?.compaction??{},n={prune:mergeDeep(Vp,t.prune??{}),backup:mergeDeep(Kp,t.backup??{}),auto:t.auto??Jp.auto,reserved:t.reserved};return Wp.debug("compaction config loaded",{auto:n.auto,pruneEnabled:n?.prune?.enabled,backupEnabled:n?.backup?.enabled}),n}catch(e){return Wp.warn("failed to load compaction config, using defaults",{error:String(e)}),{prune:Vp,backup:Kp,auto:Jp.auto}}}async function Xd(){return gi()}async function Ob(){return (await Xd()).auto!==false}async function jb(){return (await Xd())?.prune?.enabled!==false}async function Lb(){return (await Xd())?.backup?.enabled!==false}var Fb=N.enum(e),Nb=N.enum(h),Ub=N.enum(["read","write"]),zb=N.object({name:N.string(),description:N.string().optional(),type:N.enum(["system","extension"]).default("extension"),scope:Nb.default("all"),priority:N.number().int().default(1e3),owner:N.array(N.string()).optional(),share:N.array(N.string()).optional(),permission:Ub.default("read"),dynamic:N.boolean().optional()}),qb=N.record(N.string(),N.array(N.string())),Hb=N.object({maxEntries:N.number().int().positive().optional(),maxBytes:N.number().int().positive().optional(),timestampCheck:N.boolean().optional()}),Bb=N.object({charsPerToken:N.number().positive().optional()}),Qd=N.object({mode:Fb.optional(),fileCache:Hb.optional(),tokenEstimation:Bb.optional(),maxTokens:N.number().int().nonnegative().optional(),searchMaxResults:N.number().int().positive().optional(),files:N.record(N.string(),zb).optional(),contextFiles:qb.optional()}),Yp=a.create({service:"context-loader"}),Gb={maxEntries:100,maxBytes:25*1024*1024,timestampCheck:true},Wb={charsPerToken:4},Xp={mode:"general",maxTokens:2e3,searchMaxResults:3};function Vb(){return Gb}function Kb(){return Wb}async function hi(){try{let t=(await Ro()).context??{},n=mergeDeep(Xp,t);return Yp.debug("loaded context config",{context:n}),n}catch(e){return Yp.warn("failed to load context config from config, using defaults",{error:String(e)}),Xp}}var Qp=a.create({service:"subagent-loader"}),Ma=N.enum(["ephemeral","persistent"]).meta({ref:"SubAgentRunMode"}),Zd=N.enum(["stdio","http","websocket","cli"]).meta({ref:"SubAgentTransportType"}),el=N.object({modelId:N.string().describe("Model ID"),providerId:N.string().describe("Provider ID")}).strict().meta({ref:"SubAgentModel"}),tl=N.object({name:N.string().describe("Unique name for this agent"),role:N.string().describe("Agent role type (e.g., researcher, planner, coder, executor)"),transport:Zd.describe("Transport type for communication"),runMode:Ma.describe("Run mode: ephemeral or persistent"),uri:N.string().optional().describe("Connection URI for HTTP/WebSocket transport"),command:N.string().optional().describe("Command to execute for StdIO/CLI transport"),args:N.string().array().optional().describe("Command line arguments"),env:N.record(N.string(),N.string()).optional().describe("Environment variables to pass to subprocess"),timeout:N.number().int().positive().optional().describe("Timeout in milliseconds"),maxConcurrent:N.number().int().positive().optional().describe("Maximum concurrent instances"),cwd:N.string().optional().describe("Working directory for subprocess"),mcpServers:N.string().array().optional().describe("MCP server list to pass to subprocess"),agentConfig:N.object({model:el.optional().describe("Model configuration"),system:N.string().optional().describe("System prompt"),tools:N.record(N.string(),N.boolean()).optional().describe("Tools to enable")}).strict().optional().describe("Agent-specific configuration")}).strict().meta({ref:"SubAgentConfig"}),Oa=N.object({enabled:N.boolean().optional().default(true).describe("Enable SubAgent system"),defaultRunMode:Ma.optional().default("ephemeral").describe("Default run mode"),timeout:N.number().int().positive().optional().default(12e4).describe("Global timeout in milliseconds"),maxConcurrent:N.number().int().positive().optional().default(5).describe("Maximum concurrent agents"),idleTimeout:N.number().int().positive().optional().default(1800*1e3).describe("Idle timeout in milliseconds"),idleCheckInterval:N.number().int().positive().optional().default(300*1e3).describe("Idle cleanup check interval in milliseconds"),agents:N.array(tl).optional().default([]).describe("List of SubAgent configurations")}).strict().meta({ref:"SubAgentConfigSchema"}),Zp={enabled:true,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,idleTimeout:300*1e3,idleCheckInterval:300*1e3,agents:[{name:"gateway",role:"gateway",transport:"stdio",runMode:"persistent",command:"easbot",args:["acp","--channel","stdio"],timeout:1800*1e3,env:{EASBOT_RUN_MODE:"persistent"}},{name:"task_general",role:"executor",transport:"stdio",runMode:"ephemeral",command:"easbot",args:["acp","--channel","stdio"],timeout:300*1e3,env:{EASBOT_RUN_MODE:"ephemeral"}}]};async function ur(){try{let t=(await Ro())?.subagent??{},{agents:n,...o}=Zp;t.agents=n.concat(t?.agents??[]);let s=mergeDeep(o,t);return Qp.debug("subagent config loaded",{enabled:s.enabled,agentCount:s.agents.length}),s}catch(e){return Qp.warn("failed to load subagent config, using defaults",{error:String(e)}),Zp}}async function Xb(){return ur()}var ws=N.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"}),ja=N.object({type:N.literal("local").describe("Type of MCP server connection"),command:N.string().describe("Command to run the MCP server"),args:N.string().array().optional().describe("Arguments to pass to the command"),env:N.record(N.string(),N.string()).optional().describe("Environment variables to set when running the MCP server"),enabled:N.boolean().optional().describe("Enable or disable the MCP server on startup"),timeout:N.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:N.string().optional().describe("Description of the MCP server"),scope:N.enum(h).optional().default(g.All).describe("Context mode scope for the MCP server: all/general/coder. Defaults to all.")}).strict().meta({ref:"McpLocalConfig"}),La=N.object({clientId:N.string().optional().describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),clientSecret:N.string().optional().describe("OAuth client secret (if required by the authorization server)"),scope:N.string().optional().describe("OAuth scopes to request during authorization")}).strict().meta({ref:"McpOAuthConfig"}),Da=N.object({type:N.literal("remote").describe("Type of MCP server connection"),url:N.string().describe("URL of the remote MCP server"),enabled:N.boolean().optional().describe("Enable or disable the MCP server on startup"),headers:N.record(N.string(),N.string()).optional().describe("Headers to send with the request"),oauth:N.union([La,N.literal(false)]).optional().describe("OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."),timeout:N.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:N.string().optional().describe("Description of the MCP server"),scope:N.enum([g.All,g.General,g.Coder]).optional().default(g.All).describe("Context mode scope for the MCP server: all/general/coder. Defaults to all.")}).strict().meta({ref:"McpRemoteConfig"}),$a=N.discriminatedUnion("type",[ja,Da]),Kn=N.enum(["ask","allow","deny"]).meta({ref:"PermissionActionConfig"}),Fa=N.record(N.string(),Kn).meta({ref:"PermissionObjectConfig"}),ht=N.union([Kn,Fa]).meta({ref:"PermissionRuleConfig"}),Zb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?{__originalKeys:Object.keys(e),...e}:e,ew=e=>{if(typeof e=="string")return {"*":e};let t=e,{__originalKeys:n,...o}=t;if(!n)return o;let s={};for(let r of n)r in o&&(s[r]=o[r]);return s},yi=N.preprocess(Zb,N.object({__originalKeys:N.string().array().optional(),read:ht.optional(),edit:ht.optional(),glob:ht.optional(),grep:ht.optional(),list:ht.optional(),bash:ht.optional(),task:ht.optional(),external_directory:ht.optional(),todo:Kn.optional(),question:Kn.optional(),webfetch:Kn.optional(),websearch:Kn.optional(),codesearch:Kn.optional(),lsp:ht.optional(),doom_loop:Kn.optional(),skill:ht.optional(),pty_session:ht.optional(),pty_manage:ht.optional(),write:ht.optional(),multiedit:ht.optional(),note:ht.optional(),memory:ht.optional(),codebase:ht.optional(),agent_client:ht.optional(),gateway:ht.optional(),apply_patch:ht.optional(),batch:ht.optional(),plan:ht.optional()}).catchall(ht).or(Kn)).transform(ew).meta({ref:"PermissionConfig"}),Na=N.object({template:N.string(),description:N.string().optional(),agent:N.string().optional(),model:ws.optional(),subtask:N.boolean().optional(),scope:N.enum(h).optional().describe("Context mode scope")}),Ua=N.object({paths:N.array(N.string()).optional().describe("Additional paths to skill folders"),urls:N.array(N.string()).optional().describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)")}),ro=N.object({model:ws.optional(),variant:N.string().optional().describe("Default model variant for this agent (applies only when using the agent's configured model)."),temperature:N.number().optional(),top_p:N.number().optional(),prompt:N.string().optional(),tools:N.record(N.string(),N.boolean()).optional().describe("@deprecated Use 'permission' field instead"),disable:N.boolean().optional(),description:N.string().optional().describe("Description of when to use the agent"),mode:N.enum(["subagent","primary","all"]).optional(),hidden:N.boolean().optional().describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),options:N.record(N.string(),N.any()).optional(),color:N.union([N.string().regex(/^#[0-9a-fA-F]{6}$/,"Invalid hex color format"),N.enum(["primary","secondary","accent","success","warning","error","info"])]).optional().describe("Hex color code (e.g., #FF5733) or theme color (e.g., primary)"),steps:N.number().int().positive().optional().describe("Maximum number of agentic iterations before forcing text-only response"),maxSteps:N.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),permission:yi.optional()}).catchall(N.any()).transform((e,t)=>{let n=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools"]),o={...e.options};for(let[i,c]of Object.entries(e))n.has(i)||(o[i]=c);let s={};for(let[i,c]of Object.entries(e.tools??{})){let l=c?"allow":"deny";i==="write"||i==="edit"||i==="patch"||i==="multiedit"?s.edit=l:s[i]=l;}Object.assign(s,e.permission);let r=e.steps??e.maxSteps;return {...e,options:o,permission:s,steps:r}}).meta({ref:"AgentConfig"}),za=N.object({leader:N.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),app_exit:N.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),editor_open:N.string().optional().default("<leader>e").describe("Open external editor"),theme_list:N.string().optional().default("<leader>t").describe("List available themes"),sidebar_toggle:N.string().optional().default("<leader>b").describe("Toggle sidebar"),scrollbar_toggle:N.string().optional().default("none").describe("Toggle session scrollbar"),username_toggle:N.string().optional().default("none").describe("Toggle username visibility"),status_view:N.string().optional().default("<leader>s").describe("View status"),session_export:N.string().optional().default("<leader>x").describe("Export session to editor"),session_new:N.string().optional().default("<leader>n").describe("Create a new session"),session_list:N.string().optional().default("<leader>l").describe("List all sessions"),session_timeline:N.string().optional().default("<leader>g").describe("Show session timeline"),session_fork:N.string().optional().default("none").describe("Fork session from message"),session_rename:N.string().optional().default("ctrl+r").describe("Rename session"),session_delete:N.string().optional().default("ctrl+d").describe("Delete session"),stash_delete:N.string().optional().default("ctrl+d").describe("Delete stash entry"),model_provider_list:N.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),model_favorite_toggle:N.string().optional().default("ctrl+f").describe("Toggle model favorite status"),session_share:N.string().optional().default("none").describe("Share current session"),session_unshare:N.string().optional().default("none").describe("Unshare current session"),session_interrupt:N.string().optional().default("escape").describe("Interrupt current session"),session_compact:N.string().optional().default("<leader>c").describe("Compact the session"),messages_page_up:N.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),messages_page_down:N.string().optional().default("pagedown,ctrl+alt+f").describe("Scroll messages down by one page"),messages_line_up:N.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),messages_line_down:N.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),messages_half_page_up:N.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),messages_half_page_down:N.string().optional().default("ctrl+alt+d").describe("Scroll messages down by half page"),messages_first:N.string().optional().default("ctrl+g,home").describe("Navigate to first message"),messages_last:N.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),messages_next:N.string().optional().default("none").describe("Navigate to next message"),messages_previous:N.string().optional().default("none").describe("Navigate to previous message"),messages_last_user:N.string().optional().default("none").describe("Navigate to last user message"),messages_copy:N.string().optional().default("<leader>y").describe("Copy message"),messages_undo:N.string().optional().default("<leader>u").describe("Undo message"),messages_redo:N.string().optional().default("<leader>r").describe("Redo message"),messages_toggle_conceal:N.string().optional().default("<leader>h").describe("Toggle code block concealment in messages"),tool_details:N.string().optional().default("none").describe("Toggle tool details visibility"),model_list:N.string().optional().default("<leader>m").describe("List available models"),model_cycle_recent:N.string().optional().default("f2").describe("Next recently used model"),model_cycle_recent_reverse:N.string().optional().default("shift+f2").describe("Previous recently used model"),model_cycle_favorite:N.string().optional().default("none").describe("Next favorite model"),model_cycle_favorite_reverse:N.string().optional().default("none").describe("Previous favorite model"),command_list:N.string().optional().default("ctrl+p").describe("List available commands"),agent_list:N.string().optional().default("<leader>a").describe("List agents"),agent_cycle:N.string().optional().default("tab").describe("Next agent"),agent_cycle_reverse:N.string().optional().default("shift+tab").describe("Previous agent"),variant_cycle:N.string().optional().default("ctrl+t").describe("Cycle model variants"),input_clear:N.string().optional().default("ctrl+c").describe("Clear input field"),input_paste:N.string().optional().default("ctrl+v").describe("Paste from clipboard"),input_submit:N.string().optional().default("return").describe("Submit input"),input_newline:N.string().optional().default("shift+return,ctrl+return,alt+return,ctrl+j").describe("Insert newline in input"),input_move_left:N.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),input_move_right:N.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),input_move_up:N.string().optional().default("up").describe("Move cursor up in input"),input_move_down:N.string().optional().default("down").describe("Move cursor down in input"),input_select_left:N.string().optional().default("shift+left").describe("Select left in input"),input_select_right:N.string().optional().default("shift+right").describe("Select right in input"),input_select_up:N.string().optional().default("shift+up").describe("Select up in input"),input_select_down:N.string().optional().default("shift+down").describe("Select down in input"),input_line_home:N.string().optional().default("ctrl+a").describe("Move to start of line in input"),input_line_end:N.string().optional().default("ctrl+e").describe("Move to end of line in input"),input_select_line_home:N.string().optional().default("ctrl+shift+a").describe("Select to start of line in input"),input_select_line_end:N.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),input_visual_line_home:N.string().optional().default("alt+a").describe("Move to start of visual line in input"),input_visual_line_end:N.string().optional().default("alt+e").describe("Move to end of visual line in input"),input_select_visual_line_home:N.string().optional().default("alt+shift+a").describe("Select to start of visual line in input"),input_select_visual_line_end:N.string().optional().default("alt+shift+e").describe("Select to end of visual line in input"),input_buffer_home:N.string().optional().default("home").describe("Move to start of buffer in input"),input_buffer_end:N.string().optional().default("end").describe("Move to end of buffer in input"),input_select_buffer_home:N.string().optional().default("shift+home").describe("Select to start of buffer in input"),input_select_buffer_end:N.string().optional().default("shift+end").describe("Select to end of buffer in input"),input_delete_line:N.string().optional().default("ctrl+shift+d").describe("Delete line in input"),input_delete_to_line_end:N.string().optional().default("ctrl+k").describe("Delete to end of line in input"),input_delete_to_line_start:N.string().optional().default("ctrl+u").describe("Delete to start of line in input"),input_backspace:N.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),input_delete:N.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),input_undo:N.string().optional().default("ctrl+-,super+z").describe("Undo in input"),input_redo:N.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),input_word_forward:N.string().optional().default("alt+f,alt+right,ctrl+right").describe("Move word forward in input"),input_word_backward:N.string().optional().default("alt+b,alt+left,ctrl+left").describe("Move word backward in input"),input_select_word_forward:N.string().optional().default("alt+shift+f,alt+shift+right").describe("Select word forward in input"),input_select_word_backward:N.string().optional().default("alt+shift+b,alt+shift+left").describe("Select word backward in input"),input_delete_word_forward:N.string().optional().default("alt+d,alt+delete,ctrl+delete").describe("Delete word forward in input"),input_delete_word_backward:N.string().optional().default("ctrl+w,ctrl+backspace,alt+backspace").describe("Delete word backward in input"),history_previous:N.string().optional().default("up").describe("Previous history item"),history_next:N.string().optional().default("down").describe("Next history item"),session_child_cycle:N.string().optional().default("<leader>right").describe("Next child session"),session_child_cycle_reverse:N.string().optional().default("<leader>left").describe("Previous child session"),session_parent:N.string().optional().default("<leader>up").describe("Go to parent session"),terminal_suspend:N.string().optional().default("ctrl+z").describe("Suspend terminal"),terminal_title_toggle:N.string().optional().default("none").describe("Toggle terminal title"),tips_toggle:N.string().optional().default("<leader>h").describe("Toggle tips on home screen"),display_thinking:N.string().optional().default("none").describe("Toggle thinking blocks visibility")}).strict().meta({ref:"KeybindsConfig"}),qa=N.object({scroll_speed:N.number().min(.001).optional().describe("TUI scroll speed"),scroll_acceleration:N.object({enabled:N.boolean().describe("Enable scroll acceleration")}).optional().describe("Scroll acceleration settings"),diff_style:N.enum(["auto","stacked"]).optional().describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column")}),Ha=N.object({port:N.number().int().positive().optional().describe("Port to listen on"),hostname:N.string().optional().describe("Hostname to listen on"),mdns:N.boolean().optional().describe("Enable mDNS service discovery"),mdnsDomain:N.string().optional().describe("Custom domain name for mDNS service (default: easbot.local)"),cors:N.array(N.string()).optional().describe("Additional domains to allow for CORS")}).strict().meta({ref:"ServerConfig"}),Ba=N.enum(["auto","stretch"]).meta({ref:"LayoutConfig"}),Ga=a$3.Provider.partial().extend({whitelist:N.array(N.string()).optional(),blacklist:N.array(N.string()).optional(),models:N.record(N.string(),a$3.Model.partial().extend({variants:N.record(N.string(),N.object({disabled:N.boolean().optional().describe("Disable this variant for the model")}).catchall(N.any())).optional().describe("Variant-specific configuration")})).optional(),options:N.object({apiKey:N.string().optional(),baseURL:N.string().optional(),enterpriseUrl:N.string().optional().describe("GitHub Enterprise URL for copilot authentication"),setCacheKey:N.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),timeout:N.union([N.number().int().positive().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."),N.literal(false).describe("Disable timeout for this provider entirely.")]).optional().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.")}).catchall(N.any()).optional()}).strict().meta({ref:"ProviderConfig"}),cr=N.object({$schema:N.string().optional().describe("JSON schema reference for configuration validation"),theme:N.string().optional().describe("Theme name to use for the interface"),keybinds:za.optional().describe("Custom keybind configurations"),logLevel:a.Level.optional().describe("Log level"),tui:qa.optional().describe("TUI specific settings"),server:Ha.optional().describe("Server configuration for easbot serve and web commands"),command:N.record(N.string(),Na).optional().describe("Command configuration, see https://easbot.cn/docs/commands"),skills:Ua.optional().describe("Additional skill folder paths"),watcher:N.object({ignore:N.array(N.string()).optional()}).optional(),plugin:N.string().array().optional(),snapshot:N.boolean().optional(),share:N.enum(["manual","auto","disabled"]).optional().describe("Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing"),autoshare:N.boolean().optional().describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),autoupdate:N.union([N.boolean(),N.literal("notify")]).optional().describe("Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications"),disabled_providers:N.array(N.string()).optional().describe("Disable providers that are loaded automatically"),enabled_providers:N.array(N.string()).optional().describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),model:ws.describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),small_model:ws.describe("Small model to use for tasks like title generation in the format of provider/model").optional(),default_agent:N.string().optional().describe("Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid."),username:N.string().optional().describe("Custom username to display in conversations instead of system username"),agent:N.object({plan:ro.optional(),build:ro.optional(),general:ro.optional(),explore:ro.optional(),title:ro.optional(),summary:ro.optional(),compaction:ro.optional()}).catchall(ro).optional().describe("Agent configuration, see https://easbot.cn/docs/agents"),provider:N.record(N.string(),Ga).optional().describe("Custom provider configurations and model overrides"),mcp:N.record(N.string(),N.union([$a,N.object({enabled:N.boolean()}).strict()])).optional().describe("MCP (Model Context Protocol) server configurations"),acp:Dd.optional(),gateway:a$4.optional().describe("Gateway configuration for multi-channel communication"),subagent:Oa.optional().describe("SubAgent system configuration"),formatter:N.union([N.literal(false),N.record(N.string(),N.object({disabled:N.boolean().optional(),command:N.array(N.string()).optional(),environment:N.record(N.string(),N.string()).optional(),extensions:N.array(N.string()).optional()}))]).optional(),lsp:N.union([N.literal(false),N.record(N.string(),N.union([N.object({disabled:N.literal(true)}),N.object({command:N.array(N.string()),extensions:N.array(N.string()).optional(),disabled:N.boolean().optional(),env:N.record(N.string(),N.string()).optional(),initialization:N.record(N.string(),N.any()).optional()})]))]).optional().refine(e=>{if(!e||typeof e=="boolean")return true;let t=new Set(Object.values(bo).filter(n=>"id"in n&&"extensions"in n&&"spawn"in n).map(n=>n.id));return Object.entries(e).every(([n,o])=>o.disabled||t.has(n)?true:!!o.extensions)},{error:"For custom LSP servers, 'extensions' array is required."}),instructions:N.array(N.string()).optional().describe("Additional instruction files or patterns to include"),layout:Ba.optional().describe("@deprecated Always uses stretch layout."),permission:yi.optional(),tools:N.record(N.string(),N.boolean()).optional(),enterprise:N.object({url:N.string().optional().describe("Enterprise URL")}).optional(),compaction:Yd.optional(),context:Qd.optional(),embedding_model:N.string().optional().describe("Embedding model, defaults to easbot-local/bge-base-zh-v1.5"),graph_model:N.string().optional().describe("Graph model for entity and relation extraction, defaults to easbot-local/qwen2.5-7b-instruct"),rerank_model:N.string().optional().describe("Rerank model for search result reranking, defaults to easbot-local/qwen2.5-7b-instruct"),codebase:Pa.optional(),memory:Ta.optional(),note:Aa.optional(),local:N.string().optional(),timezone:N.string().optional(),experimental:N.object({disable_paste_summary:N.boolean().optional(),batch_tool:N.boolean().optional().describe("Enable the batch tool"),openTelemetry:N.boolean().optional().describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),primary_tools:N.array(N.string()).optional().describe("Tools that should only be available to primary agents."),continue_loop_on_deny:N.boolean().optional().describe("Continue the agent loop when a tool call is denied"),mcp_timeout:N.number().int().positive().optional().describe("Timeout in milliseconds for model context protocol (MCP) requests")}).optional()}).strict().meta({ref:"Config"});var ft=new EventEmitter;function iw(){let e=["easbot.json"].map(t=>Se__default.join(a$1.Path.config,t));for(let t of e)if(existsSync(t))return t;return e[0]}function aw(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function nm(e,t,n=[]){if(!aw(t)){let o=modify(e,n,t,{formattingOptions:{insertSpaces:true,tabSize:2}});return applyEdits(e,o)}return Object.entries(t).reduce((o,[s,r])=>r===void 0?o:nm(o,r,[...n,s]),e)}async function nl(e){let t=Se__default.join(R.directory,"config.json"),n=await so(t);await PKG.write(t,JSON.stringify(mergeDeep(n,e),null,2)),await R.dispose();}async function ol(e){let{global:t}=await import('./loader-XGUYA6ZM.mjs'),n=iw();if(!n)throw new Eo({path:"global",message:"Could not determine global config file path"});let o=await PKG.file(n).text().catch(r=>{if(r.code==="ENOENT")return "{}";throw new Eo({path:n},{cause:r})}),s=await(async()=>{if(!n.endsWith(".jsonc")){let c=ar(o,n),l=mergeDeep(c,e);return await PKG.write(n,JSON.stringify(l,null,2)),l}let r=nm(o,e),i=ar(r,n);return await PKG.write(n,r),i})();return t.reset(),R.disposeAll().catch(()=>{}).finally(()=>{ft.emit("event",{directory:"global",payload:{type:a$a.Disposed.type,properties:{}}});}),s}var pr=a.create({service:"adapter-loader"});async function bi(){try{let t=(await he.get())?.acp;if(!t){pr.debug("No ACP config found in Config.Info");return}let o={server:om(t.server),clients:t.clients};return pr.info("ACP config loaded",{config:o}),o}catch(e){pr.error("Failed to load ACP config",{error:e});return}}async function Va(){let e=await bi();return e?.server?e.server:om(jp)}async function dw(){return (await bi())?.clients}function om(e){let t={...e};if(process.env.ACP_CHANNEL){let n=process.env.ACP_CHANNEL.toLowerCase();["stdio","http","websocket"].includes(n)?t.channel=n:pr.warn("Invalid ACP_CHANNEL environment variable",{value:process.env.ACP_CHANNEL});}if(process.env.ACP_PORT){let n=parseInt(process.env.ACP_PORT,10);!Number.isNaN(n)&&n>0&&n<=65535?t.port=n:pr.warn("Invalid ACP_PORT environment variable",{value:process.env.ACP_PORT});}if(process.env.ACP_HOSTNAME&&(t.hostname=process.env.ACP_HOSTNAME),process.env.ACP_TIMEOUT){let n=parseInt(process.env.ACP_TIMEOUT,10);!Number.isNaN(n)&&n>0?t.timeout=n:pr.warn("Invalid ACP_TIMEOUT environment variable",{value:process.env.ACP_TIMEOUT});}return process.env.ACP_ENABLED&&(t.enabled=process.env.ACP_ENABLED.toLowerCase()==="true"),process.env.ACP_AGENT_ID&&(t.agentId=process.env.ACP_AGENT_ID),t}async function sl(){return (await Va()).agent}async function lw(){return (await sl())?.model}async function uw(){return (await sl())?.agent}var fw=NamedError.create("ConfigDirectoryTypoError",N.object({path:N.string(),dir:N.string(),suggestion:N.string()})),gw=fw,he;(F=>(F.ModelId=ws,F.McpLocal=ja,F.McpOAuth=La,F.McpRemote=Da,F.Mcp=$a,F.PermissionAction=Kn,F.PermissionObject=Fa,F.PermissionRule=ht,F.Permission=yi,F.Command=Na,F.Skills=Ua,F.Agent=ro,F.Keybinds=za,F.TUI=qa,F.Server=Ha,F.Layout=Ba,F.Provider=Ga,F.Info=cr,F.mergeConfigConcatArrays=no,F.needsInstall=ii,F.installDependencies=ai,F.loadFile=so,F.load=ir,F.parseConfig=ar,F.JsonError=Eo,F.InvalidError=oo,F.loadAgent=ci,F.loadCommand=di,F.loadPlugin=li,F.getPluginName=_a,F.deduplicatePlugins=ui,F.loadNote=nr,F.loadCodebase=or,F.loadMemory=sr,F.loadKnowledge=Ud,F.update=nl,F.updateGlobal=ol,F.state=lr,F.waitForDependencies=Vd,F.get=Ro,F.directories=Kd,F.global=fi,F.getGlobal=Jd,F.loadACPConfig=bi,F.getACPServerConfig=Va,F.loadCompaction=gi,F.loadContextConfig=hi,F.loadGatewayConfig=b,F.loadSubAgentConfig=ur,F.ConfigDirectoryTypoError=gw))(he||(he={}));var sm={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};var Iw=150;a$2.EASBOT_LSP_INIT_TIMEOUT;var rm=a$2.EASBOT_LSP_DIAGNOSTICS_TIMEOUT,vw=1,Sw=2,Cw=2,Ja;(u=>{let e=a.create({service:"lsp.client"}),t=new Map;function n(h){return t.get(h)}u.getActiveClient=n;function o(h){return t.has(h)}u.hasActiveClient=o;function s(h){t.delete(h);}u.removeActiveClient=s,u.InitializeError=NamedError.create("LSPInitializeError",N.object({serverId:N.string()})),u.Event={Diagnostics:a$5.define("lsp.client.diagnostics",N.object({serverId:N.string(),path:N.string()}))};function c(h){if(!h)return;let g=h.textDocumentSync;return typeof g=="number"?g:g?.change}async function l(h,g){let I=h.server.capabilities;if(!I)return;let T=pathToFileURL(h.root+"/").href,y=3e4,x=async()=>{if(I.workspace?.symbolProvider===void 0)try{await withTimeout(g.sendRequest("workspace/symbol",{query:""}),y),I.workspace=I.workspace||{},I.workspace.symbolProvider=!0,e.debug("probed workspaceSymbol capability",{serverId:h.serverId});}catch(k){let v=k instanceof Error?k.message:String(k);(v.includes("methodNotFound")||v.includes("not found")||v.includes("undefined method"))&&(I.workspace=I.workspace||{},I.workspace.symbolProvider=false,e.debug("probed workspaceSymbol capability: not supported",{serverId:h.serverId}));}},b=async()=>{if(I.implementationProvider===void 0)try{await withTimeout(g.sendRequest("textDocument/implementation",{textDocument:{uri:T},position:{line:0,character:0}}),y),I.implementationProvider=!0,e.debug("probed implementation capability",{serverId:h.serverId});}catch(k){let v=k instanceof Error?k.message:String(k);(v.includes("methodNotFound")||v.includes("not found")||v.includes("undefined method"))&&(I.implementationProvider=false,e.debug("probed implementation capability: not supported",{serverId:h.serverId}));}},w=async()=>{if(I.callHierarchyProvider===void 0)try{await withTimeout(g.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:T},position:{line:0,character:0}}),y),I.callHierarchyProvider=!0,e.debug("probed callHierarchy capability",{serverId:h.serverId});}catch(k){let v=k instanceof Error?k.message:String(k);(v.includes("methodNotFound")||v.includes("not found")||v.includes("undefined method"))&&(I.callHierarchyProvider=false,e.debug("probed callHierarchy capability: not supported",{serverId:h.serverId}));}};setTimeout(()=>{x().catch(()=>{}),b().catch(()=>{}),w().catch(()=>{});},100);}function d(h){let g=h.split(/\r\n|\r|\n/);return {line:g.length-1,character:g.at(-1)?.length??0}}function m(h){let g=new Set;return h.filter(I=>{let T=JSON.stringify({code:I.code,severity:I.severity,message:I.message,source:I.source,range:I.range});return g.has(T)?false:(g.add(T),true)})}function f(h,g){return g?g.split(".").reduce((T,y)=>{if(!(!T||typeof T!="object"||!(y in T)))return T[y]},h)??null:h??null}function a$1(h){return h==="typescript"}async function p(h){let g=e.clone().tag("serverId",h.serverId);g.info("starting client");let I=`${h.serverId}:${h.root}`;if(t.has(I)){let D=t.get(I);if(D.createdAt>Date.now()-5e3)return g.warn("duplicate LSP client detected, reusing existing client",{clientKey:I}),D;g.info("removing stale LSP client",{clientKey:I});try{await D.shutdown();}catch{}t.delete(I);}let T=h.initTimeout??bo.getServerInitTimeout(h.serverId),y=createMessageConnection(new StreamMessageReader(h.server.process.stdout),new StreamMessageWriter(h.server.process.stdin));h.server.process.stderr?.on("data",D=>{let K=D.toString().trim();K&&g.debug("server stderr",{text:K.slice(0,1e3)});});let x=new Map,b=new Map,w=new Map,k=D=>m([...x.get(D)??[],...b.get(D)??[]]),v=(D,K)=>{x.set(D,K),pe.publish(u.Event.Diagnostics,{path:D,serverId:h.serverId});};y.onNotification("textDocument/publishDiagnostics",D=>{let K=Filesystem.normalize(fileURLToPath(D.uri));if(K){if(g.info("textDocument/publishDiagnostics",{path:K,count:D.diagnostics.length,version:D.version}),w.set(K,{at:Date.now(),version:typeof D.version=="number"?D.version:void 0}),a$1(h.serverId)&&!x.has(K)){x.set(K,D.diagnostics);return}v(K,D.diagnostics);}}),y.onRequest("window/workDoneProgress/create",D=>(g.info("window/workDoneProgress/create",D),null)),y.onRequest("workspace/configuration",async D=>(D.items??[]).map(X=>f(h.server.initialization,X.section))),y.onRequest("client/registerCapability",async()=>{}),y.onRequest("client/unregisterCapability",async()=>{}),y.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:pathToFileURL(h.root).href}]),y.onRequest("workspace/diagnostic/refresh",async()=>null),y.listen(),g.info("sending initialize",{timeout:T});let C=await withTimeout(y.sendRequest("initialize",{rootUri:pathToFileURL(h.root).href,processId:h.server.process.pid,workspaceFolders:[{name:"workspace",uri:pathToFileURL(h.root).href}],initializationOptions:{...h.server.initialization},capabilities:{window:{workDoneProgress:true},workspace:{configuration:true,didChangeWatchedFiles:{dynamicRegistration:true},diagnostics:{refreshSupport:false}},textDocument:{synchronization:{didOpen:true,didChange:true},publishDiagnostics:{versionSupport:false}}}}),T).catch(D=>{throw g.error("initialize error",{error:D,timeout:T}),new u.InitializeError({serverId:h.serverId},{cause:D})}),E=c(C.capabilities);h.server.capabilities=C.capabilities,l(h,y).catch(()=>{}),await y.sendNotification("initialized",{}),h.server.initialization&&await y.sendNotification("workspace/didChangeConfiguration",{settings:h.server.initialization});let O={},U={root:h.root,get serverId(){return h.serverId},get connection(){return y},get capabilities(){return h.server.capabilities},notify:{async open(D){D.path=Se__default.isAbsolute(D.path)?D.path:Se__default.resolve(R.directory,D.path);let K=await Filesystem.readText(D.path),X=Se__default.extname(D.path),$=sm[X]??"plaintext",M=O[D.path];if(M!==void 0){g.info("workspace/didChangeWatchedFiles",D),await y.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL(D.path).href,type:Sw}]});let A=M.version+1;return O[D.path]={version:A,text:K},g.info("textDocument/didChange",{path:D.path,version:A}),await y.sendNotification("textDocument/didChange",{textDocument:{uri:pathToFileURL(D.path).href,version:A},contentChanges:E===Cw?[{range:{start:{line:0,character:0},end:d(M.text)},text:K}]:[{text:K}]}),A}return g.info("workspace/didChangeWatchedFiles",D),await y.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL(D.path).href,type:vw}]}),g.info("textDocument/didOpen",D),x.delete(D.path),b.delete(D.path),await y.sendNotification("textDocument/didOpen",{textDocument:{uri:pathToFileURL(D.path).href,languageId:$,version:0,text:K}}),O[D.path]={version:0,text:K},0}},get diagnostics(){let D=new Map;for(let K of new Set([...x.keys(),...b.keys()]))D.set(K,k(K));return D},async waitForDiagnostics(D){let K=Filesystem.normalize(Se__default.isAbsolute(D.path)?D.path:Se__default.resolve(R.directory,D.path));g.info("waiting for diagnostics",{path:K,timeout:rm});let X,$;return await withTimeout(new Promise(M=>{X=pe.subscribe(u.Event.Diagnostics,A=>{A.properties.path===K&&A.properties.serverId===U.serverId&&($&&clearTimeout($),$=setTimeout(()=>{g.info("got diagnostics",{path:K}),X?.(),M();},Iw));});}),rm).catch(()=>{}).finally(()=>{$&&clearTimeout($),X?.();})},async shutdown(){g.info("shutting down"),y.end(),y.dispose(),h.server.process.kill(),t.delete(I),g.info("shutdown");},clientKey:I,createdAt:Date.now()};return t.set(I,U),g.info("initialized"),U}u.create=p;})(Ja||(Ja={}));var im=3,Tw=1e3,We;(L=>{let e=a.create({service:"lsp"});L.Event={Updated:a$5.define("lsp.updated",N.object({}))},L.Range=N.object({start:N.object({line:N.number(),character:N.number()}),end:N.object({line:N.number(),character:N.number()})}).meta({ref:"Range"}),L.LspSymbol=N.object({name:N.string(),kind:N.number(),location:N.object({uri:N.string(),range:L.Range})}).meta({ref:"LspSymbol"}),L.DocumentSymbol=N.object({name:N.string(),detail:N.string().optional(),kind:N.number(),range:L.Range,selectionRange:L.Range}).meta({ref:"DocumentSymbol"});let r=S=>{a$2.EASBOT_LSP_TY?S.pyright&&(e.info("LSP server pyright is disabled because EASBOT_LSP_TY is enabled"),delete S.pyright):S.ty&&delete S.ty;},i;async function c(){let S=[],P={},_=await he.get();if(_.lsp===false)return e.info("all LSPs are disabled"),{servers:P,clients:S,broken:new Set,spawning:new Map};for(let j of Object.values(bo))"id"in j&&"extensions"in j&&"spawn"in j&&(P[j.id]=j);r(P);for(let[j,B]of Object.entries(_.lsp??{})){let Z=P[j];if(B.disabled){e.info(`LSP server ${j} is disabled`),delete P[j];continue}P[j]={...Z,id:j,root:Z?.root??(async()=>R.directory),extensions:B.extensions??Z?.extensions??[],initTimeout:Z?.initTimeout??bo.getServerInitTimeout(j),spawn:async ee=>({process:PKG.spawn([B.command[0],...B.command.slice(1)],{cwd:ee,env:{...process.env,...B.env}}),initialization:B.initialization})};}return e.info("enabled LSP servers",{serverIds:Object.values(P).map(j=>j.id).join(", ")}),{servers:P,clients:S,broken:new Set,spawning:new Map}}async function l(S){await Promise.all(S.clients.map(P=>P.shutdown()));}function d(){return i||(i=R.state(c,l)),i}function m(){return d()()}async function f(){return m()}L.init=f;async function a$1(S){if(!a$2.EASBOT_LSP_TOOL||!S)return false;let{Session:P}=await import('./session-XA4RMN7D.mjs'),_=await P.getContextMode(S);return !(_&&_!=="coder")}L.isAvailable=a$1,L.Status=N.object({id:N.string(),name:N.string(),root:N.string(),status:N.union([N.literal("connected"),N.literal("error")])}).meta({ref:"LSPStatus"});async function u(){return m().then(S=>{let P=[];for(let _ of S.clients)P.push({id:_.serverId,name:S.servers[_.serverId]?.id??"unknown",root:Se__default.posix.relative(R.directory,_.root),status:"connected"});return P})}L.status=u;async function h(S,P){try{let _=await g(P);if(_.length===0)return !1;let j=_[0]?.capabilities;if(!j)return !1;switch(S){case "workspaceSymbol":return !!j.workspace?.symbolProvider;case "callHierarchy":return !!j.callHierarchyProvider;case "implementation":return !!j.implementationProvider;default:return !1}}catch{return false}}L.hasCapability=h;async function g(S){let P=await m(),_=Se__default.parse(S).ext||S,j=[],B=new Map;async function Z(ee,se,le){let ae;try{ae=await ee.spawn(se);}catch(Q){P.broken.add(le),e.error(`Failed to spawn LSP server ${ee.id}`,{error:Q,root:se});return}if(!ae){P.broken.add(le),e.warn(`LSP server ${ee.id} spawn returned undefined`,{root:se});return}ae.initTimeout=ee.initTimeout??bo.getServerInitTimeout(ee.id),e.debug("spawned lsp server",{serverId:ee.id,initTimeout:ae.initTimeout,root:se}),ae.process.exited.catch(Q=>{let H=Q instanceof Error?Q.message:String(Q),F=Q instanceof Error?Q.stack:void 0;e.error("LSP process exited with error",{serverId:ee.id,root:se,error:H,stack:F});let te=P.clients.findIndex(J=>J.root===se&&J.serverId===ee.id);te!==-1&&(P.clients.splice(te,1),e.info("removed disconnected LSP client",{serverId:ee.id,root:se}));let V=B.get(le)??0;V<im?(B.set(le,V+1),e.info(`LSP server ${ee.id} will restart (attempt ${V+1}/${im})`,{serverId:ee.id,root:se}),setTimeout(async()=>{if(!P.broken.has(le)){let J=await Z(ee,se,le);J&&(j.push(J),await pe.publish(L.Event.Updated,{}));}},Tw)):(e.error(`LSP server ${ee.id} exceeded max restart attempts, marking as broken`,{serverId:ee.id,root:se}),P.broken.add(le),B.delete(le));});let we;try{we=await Ja.create({serverId:ee.id,server:ae,root:se,initTimeout:ee.initTimeout});}catch(Q){P.broken.add(le),e.error(`Failed to initialize LSP client ${ee.id}`,{error:Q,root:se}),ae.process.kill();return}let re=P.clients.find(Q=>Q.root===se&&Q.serverId===ee.id);return re?(ae.process.kill(),re):(B.delete(le),P.clients.push(we),we)}for(let ee of Object.values(P.servers)){if(ee.extensions.length>0&&!ee.extensions.includes(_))continue;let se=await ee.root(S);if(!se||P.broken.has(se+ee.id))continue;let le=P.clients.find(Q=>Q.root===se&&Q.serverId===ee.id);if(le){j.push(le);continue}let ae=P.spawning.get(se+ee.id);if(ae){let Q=await ae;if(!Q)continue;j.push(Q);continue}let we=Z(ee,se,se+ee.id);P.spawning.set(se+ee.id,we),await we.finally(()=>{P.spawning.get(se+ee.id)===we&&P.spawning.delete(se+ee.id);});let re=await we;re&&(j.push(re),await pe.publish(L.Event.Updated,{}));}return j}L.getClients=g;async function I(S){let P=await m(),_=Se__default.parse(S).ext||S;for(let j of Object.values(P.servers)){if(j.extensions.length>0&&!j.extensions.includes(_))continue;let B=await j.root(S);if(B&&!P.broken.has(B+j.id))return true}return false}L.hasClients=I;async function T(S,P){e.debug("touching file",{file:S});let _=await g(S);await Promise.all(_.map(async j=>{let B=P?j.waitForDiagnostics({path:S}):Promise.resolve();return await j.notify.open({path:S}),B})).catch(j=>{e.error("failed to touch file",{err:j,file:S});});}L.touchFile=T;async function y(){let S={};for(let P of await $(async _=>_.diagnostics))for(let[_,j]of P.entries()){let B=S[_]||[];B.push(...j),S[_]=B;}return S}L.diagnostics=y;async function x(S){let P=await g(S),_=Filesystem.normalize(S),j=[];for(let B of P){let Z=B.diagnostics.get(_);Z&&j.push(...Z);}return j}L.getFileDiagnostics=x;async function b(S){return M(S.file,P=>P.connection.sendRequest("textDocument/hover",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>null))}L.hover=b;let w;(ie=>(ie[ie.File=1]="File",ie[ie.Module=2]="Module",ie[ie.Namespace=3]="Namespace",ie[ie.Package=4]="Package",ie[ie.Class=5]="Class",ie[ie.Method=6]="Method",ie[ie.Property=7]="Property",ie[ie.Field=8]="Field",ie[ie.Constructor=9]="Constructor",ie[ie.Enum=10]="Enum",ie[ie.Interface=11]="Interface",ie[ie.Function=12]="Function",ie[ie.Variable=13]="Variable",ie[ie.Constant=14]="Constant",ie[ie.String=15]="String",ie[ie.Number=16]="Number",ie[ie.Boolean=17]="Boolean",ie[ie.Array=18]="Array",ie[ie.Object=19]="Object",ie[ie.Key=20]="Key",ie[ie.Null=21]="Null",ie[ie.EnumMember=22]="EnumMember",ie[ie.Struct=23]="Struct",ie[ie.Event=24]="Event",ie[ie.Operator=25]="Operator",ie[ie.TypeParameter=26]="TypeParameter"))(w||(w={}));let k=[5,12,6,11,13,14,23,10];async function v(S,P){let _=P??await R.directory+"/package.json",j=await g(_);if(j.length===0)throw new Error("No LSP client available");let B=j[0]?.capabilities;if(B&&!B.workspace?.symbolProvider)throw new Error("LSP server does not support workspaceSymbol");return M(_,Z=>Z.connection.sendRequest("workspace/symbol",{query:S}).then(ee=>!ee||!Array.isArray(ee)?[]:ee.filter(se=>k.includes(se.kind))).then(ee=>ee.slice(0,10)).catch(()=>[])).then(Z=>Z.flat())}L.workspaceSymbol=v;async function C(S){let P=pathToFileURL(S.file).href;return M(S.file,_=>_.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:P}}).catch(()=>[])).then(_=>_.flat()).then(_=>_.filter(Boolean))}L.documentSymbol=C;async function E(S){return M(S.file,P=>P.connection.sendRequest("textDocument/definition",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>null)).then(P=>P.flat().filter(Boolean))}L.definition=E;async function O(S){return M(S.file,P=>P.connection.sendRequest("textDocument/references",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character},context:{includeDeclaration:true}}).catch(()=>[])).then(P=>P.flat().filter(Boolean))}L.references=O;async function U(S){let P=await g(S.file);if(P.length>0){let _=P[0]?.capabilities;if(_&&!_.implementationProvider)throw new Error("LSP server does not support implementation")}return M(S.file,_=>_.connection.sendRequest("textDocument/implementation",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>null)).then(_=>_.flat().filter(Boolean))}L.implementation=U;async function D(S){let P=await g(S.file);if(P.length>0){let _=P[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(S.file,_=>_.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>[])).then(_=>_.flat().filter(Boolean))}L.prepareCallHierarchy=D;async function K(S){let P=await g(S.file);if(P.length>0){let _=P[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(S.file,async _=>{try{let j=await _.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>[]);return j?.length===0?[]:await _.connection.sendRequest("callHierarchy/incomingCalls",{item:j[0]}).catch(()=>[])}catch{return []}}).then(_=>_.flat().filter(Boolean))}L.incomingCalls=K;async function X(S){let P=await g(S.file);if(P.length>0){let _=P[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(S.file,async _=>{try{let j=await _.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(S.file).href},position:{line:S.line,character:S.character}}).catch(()=>[]);return j?.length===0?[]:await _.connection.sendRequest("callHierarchy/outgoingCalls",{item:j[0]}).catch(()=>[])}catch{return []}}).then(_=>_.flat().filter(Boolean))}L.outgoingCalls=X;async function $(S){let P=await m().then(j=>j.clients);return (await Promise.allSettled(P.map(j=>S(j)))).filter(j=>j.status==="fulfilled").map(j=>j.value)}async function M(S,P){try{let _=await g(S);await Promise.all(_.map(B=>B.notify.open({path:S})));let j=_.map(B=>P(B));return await Promise.all(j)}catch(_){return e.error("LSP run failed",{file:S,error:_}),[]}}(P=>{function S(_){let B={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[_.severity||1],Z=_.range.start.line+1,ee=_.range.start.character+1;return `${B} [${Z}:${ee}] ${_.message}`}P.pretty=S;})(L.Diagnostic||(L.Diagnostic={}));})(We||(We={}));var yt;(p=>{let e=a.create({service:"snapshot"}),t="7.days";async function n(){try{let{Scheduler:u}=await import('./scheduler-3AYHIZGY.mjs');await u.createCommand({id:"cmd_snapshot-cleanup",name:"snapshot-cleanup",cron:"0 * * * *",command:"cleanup",arguments:"snapshot",recurring:!0,durable:!0});}catch(u){e.error("Failed to register cleanup task",{error:u});}}p.init=n;async function o(){if(R.project.vcs!=="git"||(await he.get()).snapshot===false)return;let h=a$2();if(!await Tt__default.stat(h).then(()=>true).catch(()=>false))return;let I=await $`git --git-dir ${h} --work-tree ${R.worktree} gc --prune=${t}`.quiet().cwd(R.directory).nothrow();if(I.exitCode!==0){e.warn("cleanup failed",{exitCode:I.exitCode,stderr:I.stderr.toString(),stdout:I.stdout.toString()});return}e.info("cleanup",{prune:t});}p.cleanup=o;async function s(){if(R.project.vcs!=="git"||(await he.get()).snapshot===false)return;let h=a$2();await Tt__default.mkdir(h,{recursive:true})&&(await $`git init`.env({...process.env,GIT_DIR:h,GIT_WORK_TREE:R.worktree}).quiet().nothrow(),await $`git --git-dir ${h} config core.autocrlf false`.quiet().nothrow(),e.info("initialized")),await $`git --git-dir ${h} --work-tree ${R.worktree} add .`.quiet().cwd(R.directory).nothrow();let g=await $`git --git-dir ${h} --work-tree ${R.worktree} write-tree`.quiet().cwd(R.directory).nothrow().text();return e.info("tracking",{hash:g,cwd:R.directory,git:h}),g.trim()}p.track=s,p.Patch=N.object({hash:N.string(),files:N.string().array()});async function i(u){let h=a$2();await $`git --git-dir ${h} --work-tree ${R.worktree} add .`.quiet().cwd(R.directory).nothrow();let g=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${h} --work-tree ${R.worktree} diff --no-ext-diff --name-only ${u} -- .`.quiet().cwd(R.directory).nothrow();if(g.exitCode!==0)return e.warn("failed to get diff",{hash:u,exitCode:g.exitCode}),{hash:u,files:[]};let I=g.text();return {hash:u,files:I.trim().split(`
|
|
25
|
+
`).map(T=>T.trim()).filter(Boolean).map(T=>Se__default.join(R.worktree,T))}}p.patch=i;async function c(u){e.info("restore",{commit:u});let h=a$2(),g=await $`git --git-dir ${h} --work-tree ${R.worktree} read-tree ${u} && git --git-dir ${h} --work-tree ${R.worktree} checkout-index -a -f`.quiet().cwd(R.worktree).nothrow();g.exitCode!==0&&e.error("failed to restore snapshot",{snapshot:u,exitCode:g.exitCode,stderr:g.stderr.toString(),stdout:g.stdout.toString()});}p.restore=c;async function l(u){let h=new Set,g=a$2();for(let I of u)for(let T of I.files){if(h.has(T))continue;if(e.info("reverting",{file:T,hash:I.hash}),(await $`git --git-dir ${g} --work-tree ${R.worktree} checkout ${I.hash} -- ${T}`.quiet().cwd(R.worktree).nothrow()).exitCode!==0){let x=Se__default.posix.relative(R.worktree,T),b=await $`git --git-dir ${g} --work-tree ${R.worktree} ls-tree ${I.hash} -- ${x}`.quiet().cwd(R.worktree).nothrow();b.exitCode===0&&b.text().trim()?e.info("file existed in snapshot but checkout failed, keeping",{file:T}):(e.info("file did not exist in snapshot, deleting",{file:T}),await Tt__default.unlink(T).catch(()=>{}));}h.add(T);}}p.revert=l;async function d(u){let h=a$2();await $`git --git-dir ${h} --work-tree ${R.worktree} add .`.quiet().cwd(R.directory).nothrow();let g=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${h} --work-tree ${R.worktree} diff --no-ext-diff ${u} -- .`.quiet().cwd(R.worktree).nothrow();return g.exitCode!==0?(e.warn("failed to get diff",{hash:u,exitCode:g.exitCode,stderr:g.stderr.toString(),stdout:g.stdout.toString()}),""):g.text().trim()}p.diff=d,p.FileDiff=N.object({file:N.string(),before:N.string(),after:N.string(),additions:N.number(),deletions:N.number(),status:N.enum(["added","deleted","modified"]).optional()}).meta({ref:"FileDiff"});async function f(u,h){let g=a$2(),I=[],T=new Map,y=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${g} --work-tree ${R.worktree} diff --no-ext-diff --name-status --no-renames ${u} ${h} -- .`.quiet().cwd(R.directory).nothrow().text();for(let b of y.trim().split(`
|
|
26
|
+
`)){if(!b)continue;let[w,k]=b.split(" ");if(!w||!k)continue;let v=w.startsWith("A")?"added":w.startsWith("D")?"deleted":"modified";T.set(k,v);}let x=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${g} --work-tree ${R.worktree} diff --no-ext-diff --no-renames --numstat ${u} ${h} -- .`.quiet().cwd(R.directory).nothrow().lines();for(let b of x){if(!b)continue;let w=b.split(" ");if(w.length<3)continue;let[k,v,C]=w;if(!k||!v||!C)continue;let E=k==="-"&&v==="-",O=E?"":await $`git -c core.autocrlf=false --git-dir ${g} --work-tree ${R.worktree} show ${u}:${C}`.quiet().nothrow().text(),U=E?"":await $`git -c core.autocrlf=false --git-dir ${g} --work-tree ${R.worktree} show ${h}:${C}`.quiet().nothrow().text(),D=E?0:parseInt(k,10),K=E?0:parseInt(v,10);I.push({file:C,before:O,after:U,additions:Number.isFinite(D)?D:0,deletions:Number.isFinite(K)?K:0,status:T.get(C)??"modified"});}return I}p.diffFull=f;function a$2(){let u=R.project;return Se__default.join(a$1.Path.data,"snapshot",u.id)}})(yt||(yt={}));var vi;(l=>{let e=[/prompt is too long/i,/input is too long for requested model/i,/exceeds the context window/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/context[_ ]length[_ ]exceeded/i,/request entity too large/i,/context length is only \d+ tokens/i,/input length.*exceeds.*context length/i,/prompt too long; exceeded (?:max )?context length/i,/too large for model with \d+ maximum context length/i,/model_context_window_exceeded/i];function t(d){let m=d.statusCode;return m&&m===404||d.isRetryable}function n(d){return e.some(m=>m.test(d))?true:/^4(00|13)\s*(status code)?\s*\(no body\)/i.test(d)}function o(d,m){return d.includes("github-copilot")&&m.statusCode===403?"Please reauthenticate with the copilot provider to ensure your credentials work properly with EasBot.":m.message}function s(d,m){return iife(()=>{let f=m.message;if(f===""){if(m.responseBody)return m.responseBody;if(m.statusCode){let p=STATUS_CODES[m.statusCode];if(p)return p}return "Unknown error"}let a=o(d,m);if(a!==f)return a;if(!m.responseBody||m.statusCode&&f!==STATUS_CODES[m.statusCode])return f;try{let p=JSON.parse(m.responseBody),u=p.message||p.error||p.error?.message;if(u&&typeof u=="string")return `${f}: ${u}`}catch{}return `${f}: ${m.responseBody}`}).trim()}function r(d){if(typeof d=="string")try{let m=JSON.parse(d);return m&&typeof m=="object"?m:void 0}catch{return}if(typeof d=="object"&&d!==null)return d}function i(d){let m=r(d),f=typeof m?.message=="string"?r(m.message)??m:m;if(!f)return;let a=JSON.stringify(f);if(f.type==="error")switch(f?.error?.code){case "context_length_exceeded":return {type:"context_overflow",message:"Input exceeds context window of this model",responseBody:a};case "insufficient_quota":return {type:"api_error",message:"Quota exceeded. Check your plan and billing details.",isRetryable:false,responseBody:a};case "usage_not_included":return {type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:false,responseBody:a};case "invalid_prompt":return {type:"api_error",message:typeof f?.error?.message=="string"?f?.error?.message:"Invalid prompt.",isRetryable:false,responseBody:a};case "server_error":return {type:"api_error",message:typeof f?.error?.message=="string"?f?.error?.message:"Server error.",isRetryable:true,responseBody:a}}}l.parseStreamError=i;function c(d){let m=s(d.providerId,d.error),f=r(d.error.responseBody);if(n(m)||d.error.statusCode===413||f?.error?.code==="context_length_exceeded")return {type:"context_overflow",message:m,responseBody:d.error.responseBody};let a=d.error.url?{url:d.error.url}:void 0;return {type:"api_error",message:m,statusCode:d.error.statusCode,isRetryable:d.providerId.startsWith("openai")?t(d.error):d.error.isRetryable,responseHeaders:d.error.responseHeaders,responseBody:d.error.responseBody,metadata:a}}l.parseAPICallError=c;})(vi||(vi={}));var ve;(F=>{function e(te){return te.startsWith("image/")||te==="application/pdf"}F.isMedia=e,F.OutputLengthError=NamedError.create("MessageOutputLengthError",N.object({})),F.AbortedError=NamedError.create("MessageAbortedError",N.object({message:N.string()})),F.StructuredOutputError=NamedError.create("StructuredOutputError",N.object({message:N.string(),retries:N.number()})),F.AuthError=NamedError.create("ProviderAuthError",N.object({providerId:N.string(),message:N.string()})),F.APIError=NamedError.create("APIError",N.object({message:N.string(),statusCode:N.number().optional(),isRetryable:N.boolean(),responseHeaders:N.record(N.string(),N.string()).optional(),responseBody:N.string().optional(),metadata:N.record(N.string(),N.string()).optional()})),F.ContextOverflowError=NamedError.create("ContextOverflowError",N.object({message:N.string(),responseBody:N.string().optional()})),F.OutputFormatText=N.object({type:N.literal("text")}).meta({ref:"OutputFormatText"}),F.OutputFormatJsonSchema=N.object({type:N.literal("json_schema"),schema:N.record(N.string(),N.any()).meta({ref:"JSONSchema"}),retryCount:N.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),F.Format=N.discriminatedUnion("type",[F.OutputFormatText,F.OutputFormatJsonSchema]).meta({ref:"OutputFormat"});let m=N.object({id:N.string(),sessionId:N.string(),messageId:N.string()});F.SnapshotPart=m.extend({type:N.literal("snapshot"),snapshot:N.string()}).meta({ref:"SnapshotPart"}),F.PatchPart=m.extend({type:N.literal("patch"),hash:N.string(),files:N.string().array()}).meta({ref:"PatchPart"}),F.TextPart=m.extend({type:N.literal("text"),text:N.string(),synthetic:N.boolean().optional(),ignored:N.boolean().optional(),time:N.object({start:N.number(),end:N.number().optional()}).optional(),metadata:N.record(N.string(),N.any()).optional()}).meta({ref:"TextPart"}),F.ReasoningPart=m.extend({type:N.literal("reasoning"),text:N.string(),metadata:N.record(N.string(),N.any()).optional(),time:N.object({start:N.number(),end:N.number().optional()})}).meta({ref:"ReasoningPart"});let h=N.object({text:N.object({value:N.string(),start:N.number().int(),end:N.number().int()}).meta({ref:"FilePartSourceText"})});F.FileSource=h.extend({type:N.literal("file"),path:N.string()}).meta({ref:"FileSource"}),F.SymbolSource=h.extend({type:N.literal("symbol"),path:N.string(),range:We.Range,name:N.string(),kind:N.number().int()}).meta({ref:"SymbolSource"}),F.ResourceSource=h.extend({type:N.literal("resource"),clientName:N.string(),uri:N.string()}).meta({ref:"ResourceSource"}),F.FilePartSource=N.discriminatedUnion("type",[F.FileSource,F.SymbolSource,F.ResourceSource]).meta({ref:"FilePartSource"}),F.FilePart=m.extend({type:N.literal("file"),mime:N.string(),filename:N.string().optional(),url:N.string(),source:F.FilePartSource.optional()}).meta({ref:"FilePart"}),F.AgentPart=m.extend({type:N.literal("agent"),name:N.string(),source:N.object({value:N.string(),start:N.number().int(),end:N.number().int()}).optional()}).meta({ref:"AgentPart"}),F.CompactionPart=m.extend({type:N.literal("compaction"),auto:N.boolean(),overflow:N.boolean().optional()}).meta({ref:"CompactionPart"}),F.MemoryPart=m.extend({type:N.literal("memory"),status:N.enum(["pending","processing","completed","failed","skipped"]),time:N.object({start:N.number(),end:N.number().optional()}),result:N.string().optional(),error:N.string().optional(),reason:N.string().optional()}).meta({ref:"MemoryPart"}),F.SubtaskPart=m.extend({type:N.literal("subtask"),taskId:N.string().describe("Task unique identifier"),prompt:N.string(),description:N.string(),agent:N.string(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),command:N.string().optional()}).meta({ref:"SubtaskPart"}),F.SubtaskResultPart=m.extend({type:N.literal("subtask-result"),taskId:N.string().describe("Task unique identifier"),source:N.enum(["tool","scheduler","cli","api","agent-client"]).describe("Task source"),agent:N.string().describe("Agent name"),status:N.enum(["pending","running","completed","error"]).describe("Task status"),result:N.string().optional().describe("Task result content"),error:N.string().optional().describe("Error message if failed"),duration:N.number().optional().describe("Duration in milliseconds"),time:N.object({start:N.number().describe("Start timestamp"),end:N.number().optional().describe("End timestamp")}).optional().describe("Task time"),rounds:N.object({current:N.number(),max:N.number()}).optional().describe("Interaction rounds"),thinking:N.string().optional().describe("Thinking content"),tools:N.array(N.object({name:N.string(),status:N.string(),input:N.record(N.string(),N.unknown()).optional(),output:N.string().optional()})).optional().describe("Tool calls during task"),attachments:N.array(N.lazy(()=>F.FilePart)).optional().describe("Result attachments"),metadata:N.record(N.string(),N.unknown()).optional().describe("Source-specific metadata")}).meta({ref:"SubtaskResultPart"});function E(te){let V=[];if(V.push("=== SubAgent Result ==="),V.push(`Task ID: ${te.taskId}`),V.push(`Source: ${te.source}`),V.push(`Agent: ${te.agent}`),V.push(`Status: ${te.status}`),te.duration&&V.push(`Duration: ${te.duration}ms`),te.rounds&&V.push(`Rounds: ${te.rounds.current}/${te.rounds.max}`),te.time&&(V.push(`Start(Local): ${formatLocalISOCompact(new Date(te.time.start))}`),te.time.end&&V.push(`End(Local): ${formatLocalISOCompact(new Date(te.time.end))}`)),te.metadata&&Object.keys(te.metadata).length>0){V.push("");for(let[J,oe]of Object.entries(te.metadata))V.push(`${J}: ${oe}`);}if(te.thinking&&V.push("","<think>",te.thinking,"</think>"),(te?.tools?.length??0)>0){V.push("","<tool_calls>");for(let J of te?.tools??[])V.push(`- ${J.name}: ${String(J.input)}`);V.push("</tool_calls>");}return V.push(""),te.status==="error"?V.push("Error:",te.error??"Unknown error"):V.push("Result:",te.result??""),V.push("=================="),V.join(`
|
|
27
|
+
`)}F.formatSubtaskResultPart=E,F.RetryPart=m.extend({type:N.literal("retry"),attempt:N.number(),error:F.APIError.Schema,time:N.object({created:N.number()})}).meta({ref:"RetryPart"}),F.StepStartPart=m.extend({type:N.literal("step-start"),snapshot:N.string().optional()}).meta({ref:"StepStartPart"}),F.StepFinishPart=m.extend({type:N.literal("step-finish"),reason:N.string(),snapshot:N.string().optional(),cost:N.number(),tokens:N.object({total:N.number().optional(),input:N.number(),output:N.number(),reasoning:N.number(),cache:N.object({read:N.number(),write:N.number()})})}).meta({ref:"StepFinishPart"}),F.ToolStatePending=N.object({status:N.literal("pending"),input:N.record(N.string(),N.any()),raw:N.string()}).meta({ref:"ToolStatePending"}),F.ToolStateRunning=N.object({status:N.literal("running"),input:N.record(N.string(),N.any()),title:N.string().optional(),metadata:N.record(N.string(),N.any()).optional(),time:N.object({start:N.number()})}).meta({ref:"ToolStateRunning"}),F.ToolStateCompleted=N.object({status:N.literal("completed"),input:N.record(N.string(),N.any()),output:N.string(),title:N.string(),metadata:N.record(N.string(),N.any()),time:N.object({start:N.number(),end:N.number(),compacted:N.number().optional()}),attachments:F.FilePart.array().optional()}).meta({ref:"ToolStateCompleted"}),F.ToolStateError=N.object({status:N.literal("error"),input:N.record(N.string(),N.any()),error:N.string(),metadata:N.record(N.string(),N.any()).optional(),time:N.object({start:N.number(),end:N.number()})}).meta({ref:"ToolStateError"}),F.ToolState=N.discriminatedUnion("status",[F.ToolStatePending,F.ToolStateRunning,F.ToolStateCompleted,F.ToolStateError]).meta({ref:"ToolState"}),F.ToolPart=m.extend({type:N.literal("tool"),callId:N.string(),tool:N.string(),state:F.ToolState,metadata:N.record(N.string(),N.any()).optional()}).meta({ref:"ToolPart"});let S=N.object({id:N.string(),sessionId:N.string()});F.User=S.extend({role:N.literal("user"),time:N.object({created:N.number()}),format:F.Format.optional(),summary:N.object({title:N.string().optional(),body:N.string().optional(),diffs:yt.FileDiff.array()}).optional(),agent:N.string(),model:N.object({providerId:N.string(),modelId:N.string()}),system:N.string().optional(),tools:N.record(N.string(),N.boolean()).optional(),variant:N.string().optional()}).meta({ref:"UserMessage"}),F.Part=N.discriminatedUnion("type",[F.TextPart,F.SubtaskPart,F.ReasoningPart,F.FilePart,F.ToolPart,F.StepStartPart,F.StepFinishPart,F.SnapshotPart,F.PatchPart,F.AgentPart,F.SubtaskResultPart,F.RetryPart,F.CompactionPart,F.MemoryPart]).meta({ref:"Part"}),F.Assistant=S.extend({role:N.literal("assistant"),time:N.object({created:N.number(),completed:N.number().optional()}),error:N.discriminatedUnion("name",[F.AuthError.Schema,NamedError.Unknown.Schema,F.OutputLengthError.Schema,F.AbortedError.Schema,F.StructuredOutputError.Schema,F.ContextOverflowError.Schema,F.APIError.Schema]).optional(),parentId:N.string(),modelId:N.string(),providerId:N.string(),mode:N.string(),agent:N.string(),path:N.object({cwd:N.string(),root:N.string()}),summary:N.boolean().optional(),cost:N.number(),tokens:N.object({total:N.number().optional(),input:N.number(),output:N.number(),reasoning:N.number(),cache:N.object({read:N.number(),write:N.number()})}),structured:N.any().optional(),variant:N.string().optional(),finish:N.string().optional()}).meta({ref:"AssistantMessage"}),F.Info=N.discriminatedUnion("role",[F.User,F.Assistant]).meta({ref:"Message"}),F.Event={Updated:a$5.define("message.updated",N.object({info:F.Info})),Removed:a$5.define("message.removed",N.object({sessionId:N.string(),messageId:N.string()})),PartUpdated:a$5.define("message.part.updated",N.object({part:F.Part,delta:N.string().optional(),time:N.number()})),PartRemoved:a$5.define("message.part.removed",N.object({sessionId:N.string(),messageId:N.string(),partId:N.string()}))},F.WithParts=N.object({info:F.Info,parts:N.array(F.Part)});async function se(te,V,J){let oe=new Set,de=(()=>{if(V.api.npm==="@ai-sdk/anthropic"||V.api.npm==="@ai-sdk/openai"||V.api.npm==="@ai-sdk/amazon-bedrock"||V.api.npm==="@ai-sdk/google-vertex/anthropic")return true;if(V.api.npm==="@ai-sdk/google"){let Ie=V.api.id.toLowerCase();return Ie.includes("gemini-3")&&!Ie.includes("gemini-2")}return false})(),me=Ie=>{if(typeof Ie=="string")return {type:"text",value:Ie};if(typeof Ie=="object"){let Ce=Ie,ie=(Ce.attachments??[]).filter(Ae=>Ae.url.startsWith("data:")&&Ae.url.includes(","));return {type:"content",value:[{type:"text",text:Ce.text??Ce.output??"[Tool result content missing]"},...ie.map(Ae=>({type:"media",mediaType:Ae.mime,data:iife(()=>{let pt=Ae.url.indexOf(",");return pt===-1?Ae.url:Ae.url.slice(pt+1)})}))]}}return {type:"json",value:Ie}},ce=[];for(let Ie of te)if(Ie.parts.length!==0){if(Ie.info.role==="user"){let Ce={id:Ie.info.id,role:"user",parts:[]};ce.push(Ce);for(let ie of Ie.parts)ie.type==="text"&&!ie.ignored&&Ce.parts.push({type:"text",text:ie.text}),ie.type==="file"&&ie.mime!=="text/plain"&&ie.mime!=="application/x-directory"&&(J?.stripMedia&&e(ie.mime)?Ce.parts.push({type:"text",text:`[Attached ${ie.mime}: ${ie.filename??"file"}]`}):Ce.parts.push({type:"file",url:ie.url,mediaType:ie.mime,filename:ie.filename})),ie.type==="compaction"&&Ce.parts.push({type:"text",text:"What did we do so far?"}),ie.type==="subtask"&&Ce.parts.push({type:"text",text:"The following tool was executed by user"}),ie.type==="subtask-result"&&Ce.parts.push({type:"text",text:F.formatSubtaskResultPart(ie)});}if(Ie.info.role==="assistant"){let Ce=`${V.providerId}/${V.id}`!=`${Ie.info.providerId}/${Ie.info.modelId}`,ie=[];if(Ie.info.error&&!(F.AbortedError.isInstance(Ie.info.error)&&Ie.parts.some(Ae=>Ae.type!=="step-start"&&Ae.type!=="reasoning")))continue;let $e={id:Ie.info.id,role:"assistant",parts:[]};for(let Ae of Ie.parts){if(Ae.type==="text"&&$e.parts.push({type:"text",text:Ae.text,...Ce?{}:{providerMetadata:Ae.metadata}}),Ae.type==="step-start"&&$e.parts.push({type:"step-start"}),Ae.type==="tool"){if(oe.add(Ae.tool),Ae.state.status==="completed"){let pt=Ae.state.time.compacted?"[Old tool result content cleared]":Ae.state.output??"[Tool result content missing]",Ct=Ae.state.time.compacted||J?.stripMedia?[]:Ae.state.attachments??[],cn=Ia=>Ia.mime.startsWith("image/")||Ia.mime==="application/pdf",ri=Ct.filter(cn),hs=Ct.filter(Ia=>!cn(Ia));!de&&ri.length>0&&ie.push(...ri);let Ht=de?Ct:hs,Zs=Ht.length>0?{text:pt,attachments:Ht}:pt;$e.parts.push({type:"tool-"+Ae.tool,state:"output-available",toolCallId:Ae.callId,input:Ae.state.input,output:Zs,...Ce?{}:{callProviderMetadata:Ae.metadata}});}Ae.state.status==="error"&&$e.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:Ae.state.error,...Ce?{}:{callProviderMetadata:Ae.metadata}}),(Ae.state.status==="pending"||Ae.state.status==="running")&&$e.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:"[Tool execution was interrupted]",...Ce?{}:{callProviderMetadata:Ae.metadata}});}Ae.type==="reasoning"&&$e.parts.push({type:"reasoning",text:Ae.text,...Ce?{}:{providerMetadata:Ae.metadata}});}$e.parts.length>0&&(ce.push($e),ie.length>0&&ce.push({id:Identifier.ascending("message"),role:"user",parts:[{type:"text",text:"Attached image(s) from tool result:"},...ie.map(Ae=>({type:"file",url:Ae.url,mediaType:Ae.mime,providerMetadata:void 0}))]}));}}let ye=Object.fromEntries(Array.from(oe).map(Ie=>[Ie,{toModelOutput:me}])),je=ce.filter(Ie=>Ie.parts.some(Ce=>Ce.type!=="step-start"));return await convertToModelMessages(je,{tools:ye})}F.toModelMessages=se,F.stream=fn$1(Identifier.schema("session"),async function*(te){let V=await Array.fromAsync(await a$6.list(["message",te]));for(let J=V.length-1;J>=0;J--){let oe=V[J]?.[2];oe&&(yield await(0, F.get)({sessionId:te,messageId:oe}));}}),F.parts=fn$1(Identifier.schema("message"),async te=>{let V=[];for(let J of await a$6.list(["part",te])){let oe=await a$6.read(J);V.push(oe);}return V.sort((J,oe)=>J.id>oe.id?1:-1),V}),F.get=fn$1(N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message")}),async te=>({info:await a$6.read(["message",te.sessionId,te.messageId]),parts:await(0, F.parts)(te.messageId)}));async function re(te){let V=[],J=new Set;for await(let oe of te){if(V.push(oe),oe.info.role==="user"&&J.has(oe.info.id)&&oe.parts.some(de=>de.type==="compaction"))break;oe.info.role==="assistant"&&oe.info.summary&&oe.info.finish&&J.add(oe.info.parentId);}return V.reverse(),V}F.filterCompacted=re;async function Q(te,V){let J=await re((0, F.stream)(te)),oe=J;V?.maxMessages&&V.maxMessages>0&&(oe=J.slice(-V.maxMessages));let de,me,ce,ye,je;for(let Ie=oe.length-1;Ie>=0;Ie--){let Ce=oe[Ie];if(Ce&&(!de&&Ce.info.role==="user"&&(de=Ce.info,me=Ce),!ce&&Ce.info.role==="assistant"&&(ce=Ce.info),!ye&&Ce.info.role==="assistant"&&Ce.info.finish&&(ye=Ce),V?.filterByText!==false&&!je&&Ce.info.role==="assistant"&&Ce.parts.some(ie=>ie.type==="text")&&(je=Ce),de&&je&&ye))break}return {lastUser:de,lastUserMessage:me,lastAssistant:ce,lastFinished:ye,lastAssistantWithText:je}}F.getLastMessages=Q;function H(te,V){switch(true){case(te instanceof DOMException&&te.name==="AbortError"):return new F.AbortedError({message:te.message},{cause:te}).toObject();case F.OutputLengthError.isInstance(te):return te;case LoadAPIKeyError.isInstance(te):{let J=te;return new F.AuthError({providerId:V.providerId,message:J.message},{cause:J}).toObject()}case te?.code==="ECONNRESET":{let J=te;return new F.APIError({message:"Connection reset by server",isRetryable:true,metadata:{code:J.code??"",syscall:J.syscall??"",message:J.message??""}},{cause:J}).toObject()}case(te instanceof Error&&te.code==="ZlibError"):{let J=te;return V.aborted?new F.AbortedError({message:J.message},{cause:J}).toObject():new F.APIError({message:"Response decompression failed",isRetryable:true,metadata:{code:J.code,message:J.message}},{cause:J}).toObject()}case APICallError.isInstance(te):{let J=vi.parseAPICallError({providerId:V.providerId,error:te});return J.type==="context_overflow"?new F.ContextOverflowError({message:J.message,responseBody:J.responseBody},{cause:te}).toObject():new F.APIError({message:J.message,statusCode:J.statusCode,isRetryable:J.isRetryable,responseHeaders:J.responseHeaders,responseBody:J.responseBody,metadata:J.metadata},{cause:te}).toObject()}default:{let J=te;try{let oe=vi.parseStreamError(J);if(oe)return oe.type==="context_overflow"?new F.ContextOverflowError({message:oe.message,responseBody:oe.responseBody},{cause:J}).toObject():new F.APIError({message:oe.message,isRetryable:oe.isRetryable,responseBody:oe.responseBody},{cause:J}).toObject()}catch{}return new NamedError.Unknown({message:String(J)},{cause:J}).toObject()}}}F.fromError=H;})(ve||(ve={}));var dm=a.create({service:"context-workspace"}),ul=".easbot",jw="protocol.json",lm=1;function Lw(e){return Se__default.join(e,jw)}async function pl(e){try{let t=await Tt__default.readFile(e,"utf-8"),n=JSON.parse(t);return {version:lm,bootstrapSeededAt:n.bootstrapSeededAt,setupCompletedAt:n.setupCompletedAt,metadata:n.metadata}}catch{return {version:lm}}}async function Ci(e){return e?Se__default.join(e,ul):Se__default.join(R.directory,ul)}async function Ya(e){let t=e?await Ci(e):await Ci(),n=Lw(t);dm.debug("isSetupCompleted checking",{workspace:e,easbotDir:t,statePath:n});let o=await pl(n),s=typeof o.setupCompletedAt=="string"&&o.setupCompletedAt.trim().length>0;return dm.debug("isSetupCompleted result",{statePath:n,setupCompletedAt:o.setupCompletedAt,completed:s}),s}var Xa;(s=>{let e=a.create({service:"skill-discovery"});function t(){return Se__default.join(a$1.Path.cache,"skills")}s.dir=t;async function n(r,i){try{return await access(i),!0}catch{}try{let c=await Fetch.get(r);return c.ok?(await writeFile(i,String(c.data)),!0):(e.error("failed to download",{url:r,status:c.status}),!1)}catch(c){return e.error("failed to download",{url:r,err:c}),false}}async function o(r){let i=[],c=r.endsWith("/")?r:`${r}/`,l=new URL("index.json",c).href,d=t(),m=c.slice(0,-1);e.info("fetching index",{url:l});try{let f=await Fetch.get(l);if(!f.ok)return e.error("failed to fetch index",{url:l,status:f.status}),i;let a=f.data;if(!a?.skills||!Array.isArray(a.skills))return e.warn("invalid index format",{url:l}),i;let p=a.skills.filter(u=>!u?.name||!Array.isArray(u.files)?(e.warn("invalid skill entry",{url:l,skill:u}),!1):!0);await Promise.all(p.map(async u=>{let h=Se__default.join(d,u.name);await Promise.all(u.files.map(async I=>{let T=new URL(I,`${m}/${u.name}/`).href,y=Se__default.join(h,I);await mkdir(Se__default.dirname(y),{recursive:!0}),await n(T,y);}));let g=Se__default.join(h,"SKILL.md");try{await access(g),i.push(h);}catch{}}));}catch(f){e.error("failed to fetch index",{url:l,err:f});}return i}s.pull=o;})(Xa||(Xa={}));var Me;(k=>{let e=a.create({service:"permission"});function t(v){return v.startsWith("~/")?ec.homedir()+v.slice(1):v==="~"?ec.homedir():v.startsWith("$HOME/")?ec.homedir()+v.slice(5):v.startsWith("$HOME")?ec.homedir()+v.slice(5):v}k.Action=N.enum(["allow","deny","ask"]).meta({ref:"PermissionAction"}),k.Rule=N.object({permission:N.string(),pattern:N.string(),action:k.Action}).meta({ref:"PermissionRule"}),k.Ruleset=k.Rule.array().meta({ref:"PermissionRuleset"});function r(v){let C=[];for(let[E,O]of Object.entries(v)){if(typeof O=="string"){C.push({permission:E,action:O,pattern:"*"});continue}C.push(...Object.entries(O).map(([U,D])=>({permission:E,pattern:t(U),action:D})));}return C}k.fromConfig=r;function i(...v){return v.flat()}k.merge=i,k.Request=N.object({id:Identifier.schema("permission"),sessionId:Identifier.schema("session"),permission:N.string(),patterns:N.string().array(),metadata:N.record(N.string(),N.any()),always:N.string().array(),tool:N.object({messageId:N.string(),callId:N.string()}).optional()}).meta({ref:"PermissionRequest"}),k.Reply=N.enum(["once","always","reject"]),k.Approval=N.object({providerId:N.string(),patterns:N.string().array()}),k.Event={Asked:a$5.define("permission.asked",k.Request),Replied:a$5.define("permission.replied",N.object({sessionId:N.string(),requestId:N.string(),reply:k.Reply}))};let f;function a$1(){return f||(f=R.state(async()=>{let v=R.project.id,C=await a$6.read(["permission",v]).catch(()=>[]);return {pending:{},approved:C}})),f}function p(){return a$1()()}k.ask=fn$1(k.Request.partial({id:true}).extend({ruleset:k.Ruleset}),async v=>{let C=await p(),{ruleset:E,...O}=v;for(let U of O.patterns??[]){let D=g(O.permission,U,E,C.approved);if(e.debug("evaluated",{permission:O.permission,pattern:U,action:D}),D.action==="deny")throw new b(E.filter(K=>Wildcard.match(O.permission,K.permission)));if(D.action==="ask"){let K=v.id??Identifier.ascending("permission");return new Promise((X,$)=>{let M={id:K,...O};C.pending[K]={info:M,resolve:X,reject:$},pe.publish(k.Event.Asked,M);})}}}),k.reply=fn$1(N.object({requestId:Identifier.schema("permission"),reply:k.Reply,message:N.string().optional()}),async v=>{let C=await p(),E=C.pending[v.requestId];if(E){if(delete C.pending[v.requestId],await pe.publish(k.Event.Replied,{sessionId:E.info.sessionId,requestId:E.info.id,reply:v.reply}),v.reply==="reject"){E.reject(v.message?new x(v.message):new y);let O=E.info.sessionId;for(let[U,D]of Object.entries(C.pending))D.info.sessionId===O&&(delete C.pending[U],await pe.publish(k.Event.Replied,{sessionId:D.info.sessionId,requestId:D.info.id,reply:"reject"}),D.reject(new y));return}if(v.reply==="once"){E.resolve();return}if(v.reply==="always"){for(let U of E.info.always)C.approved.push({permission:E.info.permission,pattern:U,action:"allow"});E.resolve();let O=E.info.sessionId;for(let[U,D]of Object.entries(C.pending))D.info.sessionId!==O||!D.info.patterns.every(X=>g(D.info.permission,X,C.approved).action==="allow")||(delete C.pending[U],await pe.publish(k.Event.Replied,{sessionId:D.info.sessionId,requestId:D.info.id,reply:"always"}),D.resolve());return}}});function g(v,C,...E){let O=i(...E);return e.debug("evaluate",{permission:v,pattern:C,ruleset:O}),O.findLast(D=>Wildcard.match(v,D.permission)&&Wildcard.match(C,D.pattern))??{action:"ask",permission:v,pattern:"*"}}k.evaluate=g;let I=["edit","write","patch","multiedit"];function T(v,C){let E=new Set;for(let O of v){let U=I.includes(O)?"edit":O,D=C.findLast(K=>Wildcard.match(U,K.permission));D&&D.pattern==="*"&&D.action==="deny"&&E.add(O);}return E}k.disabled=T;class y extends Error{constructor(){super("The user rejected permission to use this specific tool call.");}}k.RejectedError=y;class x extends Error{constructor(C){super(`The user rejected permission to use this specific tool call with the following feedback: ${C}`);}}k.CorrectedError=x;class b extends Error{constructor(E){super(`The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules ${JSON.stringify(E)}`);b$1(this,"ruleset",E);}}k.DeniedError=b;async function w(){return p().then(v=>Object.values(v.pending).map(C=>C.info))}k.list=w;})(Me||(Me={}));var Vt;(g=>{let e=a.create({service:"skill"});g.Info=N.object({name:N.string(),description:N.string(),location:N.string(),content:N.string(),scope:N.enum(h).optional().describe("Context mode scope")}),g.InvalidError=NamedError.create("SkillInvalidError",N.object({path:N.string(),message:N.string().optional(),issues:N.custom().optional()})),g.NameMismatchError=NamedError.create("SkillNameMismatchError",N.object({message:N.string(),path:N.string(),expected:N.string(),actual:N.string()}));let s=[".agents"],r="skills/**/SKILL.md",i$1="skills/**/SKILL.md",c="**/SKILL.md",l;function d(){return l||(l=R.state(async()=>{let I={},T=new Set,y=async w=>{let k=await a$9.parse(w).catch(C=>{let E=a$9.FrontmatterError.isInstance(C)?C.data.message:`Failed to parse skill ${w}`;pe.publish(Y.Event.Error,{error:new NamedError.Unknown({message:E}).toObject()}),e.error("failed to load skill",{skill:w,err:C});});if(!k)return;let v=g.Info.pick({name:true,description:true}).safeParse(k.data);v.success&&(I[v.data.name]&&e.warn("duplicate skill name",{name:v.data.name,existing:I[v.data.name]?.location,duplicate:w}),T.add(Se__default.dirname(w)),I[v.data.name]={name:v.data.name,description:v.data.description,location:w,content:k.content,scope:k.data.scope});},x=async(w,k)=>glob(r,{cwd:w,absolute:true,nodir:true,follow:true,dot:true}).then(v=>Promise.all(v.map(y))).catch(v=>{e.error(`failed to scan ${k} skills`,{dir:w,error:v});});if(!a$2.EASBOT_DISABLE_EXTERNAL_SKILLS){for(let w of s){let k=Se__default.join(a$1.Path.home,w);await Filesystem.isDir(k)&&await x(k,"global");}for await(let w of Filesystem.up({targets:s,start:R.directory,stop:R.worktree}))await x(w,"project");}for(let w of await he.directories()){let k=await glob(i$1,{cwd:w,absolute:true,nodir:true,follow:true});for(let v of k)await y(v);}let b=await he.get();for(let w of b.skills?.paths??[]){let k=w.startsWith("~/")?Se__default.join(ec.homedir(),w.slice(2)):w,v=Se__default.isAbsolute(k)?k:Se__default.join(R.directory,k);if(!await Filesystem.isDir(v)){e.warn("skill path not found",{path:v});continue}let C=await glob(c,{cwd:v,absolute:true,nodir:true,follow:true});for(let E of C)await y(E);}for(let w of b.skills?.urls??[]){let k=await Xa.pull(w);for(let v of k){T.add(v);let C=await glob(c,{cwd:v,absolute:true,nodir:true,follow:true});for(let E of C)await y(E);}}return {skills:I,dirs:Array.from(T)}})),l}function m(){return d()()}g.state=m;async function f(I){return m().then(T=>T.skills[I])}g.get=f;async function a$3(){return m().then(I=>Object.values(I.skills))}g.all=a$3;async function p(){return m().then(I=>I.dirs)}g.dirs=p;async function u(I,T=i){let y=await m();return Object.values(y.skills).toSorted((b,w)=>b.name.localeCompare(w.name)).filter(b=>{if(I&&Me.evaluate("skill",b.name,I.permission).action==="deny")return false;if(T){let w=b.scope??i;if(w!=="all"&&w!==T)return false}return true})}g.available=u;function h$1(I,T){if(I.length===0)return "No skills are currently available.";let y=I.toSorted((x,b)=>x.name.localeCompare(b.name));return T.verbose?["<available_skills>",...y.flatMap(x=>[" <skill>",` <name>${x.name}</name>`,` <description>${x.description}</description>`,` <location>${pathToFileURL(x.location).href}</location>`," </skill>"]),"</available_skills>"].join(`
|
|
28
|
+
`):["## Available Skills","Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.","",...y.map(x=>[`- **${x.name}**: ${x.description}`,` - Location: ${pathToFileURL(x.location).href}`].join(`
|
|
29
|
+
`))].join(`
|
|
30
|
+
`)}g.format=h$1;})(Vt||(Vt={}));var bt;(b=>{let e=a.create({service:"file"});b.Info=N.object({path:N.string(),added:N.number().int(),removed:N.number().int(),status:N.enum(["added","deleted","modified"])}).meta({ref:"File"}),b.Node=N.object({name:N.string(),path:N.string(),absolute:N.string(),type:N.enum(["file","directory"]),ignored:N.boolean()}).meta({ref:"FileNode"}),b.Content=N.object({type:N.enum(["text","binary"]),content:N.string(),diff:N.string().optional(),patch:N.object({oldFileName:N.string(),newFileName:N.string(),oldHeader:N.string().optional(),newHeader:N.string().optional(),hunks:N.array(N.object({oldStart:N.number(),oldLines:N.number(),newStart:N.number(),newLines:N.number(),lines:N.array(N.string())})),index:N.string().optional()}).optional(),encoding:N.literal("base64").optional(),mimeType:N.string().optional()}).meta({ref:"FileContent"});let s=new Set(["exe","dll","pdb","bin","so","dylib","o","a","lib","wav","mp3","ogg","oga","ogv","ogx","flac","aac","wma","m4a","weba","mp4","avi","mov","wmv","flv","webm","mkv","zip","tar","gz","gzip","bz","bz2","bzip","bzip2","7z","rar","xz","lz","z","pdf","doc","docx","ppt","pptx","xls","xlsx","dmg","iso","img","vmdk","ttf","otf","woff","woff2","eot","sqlite","db","mdb","apk","ipa","aab","xapk","app","pkg","deb","rpm","snap","flatpak","appimage","msi","msp","jar","war","ear","class","kotlin_module","dex","vdex","odex","oat","art","wasm","wat","bc","ll","s","ko","sys","drv","efi","rom","com","bat","cmd","ps1","sh","bash","zsh","fish"]),r=new Set(["png","jpg","jpeg","gif","bmp","webp","ico","tif","tiff","svg","svgz","avif","apng","jxl","heic","heif","raw","cr2","nef","arw","dng","orf","raf","pef","x3f"]);function i(w){let k=Filesystem.extname(w).toLowerCase().slice(1);return r.has(k)}function c$1(w){let k=Filesystem.extname(w).toLowerCase().slice(1);return {png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",svgz:"image/svg+xml",avif:"image/avif",apng:"image/apng",jxl:"image/jxl",heic:"image/heic",heif:"image/heif"}[k]||"image/"+k}function l(w){let k=Filesystem.extname(w).toLowerCase().slice(1);return s.has(k)}function d$1(w){return w.startsWith("image/")}async function m(w){let k=w.type?.toLowerCase();if(e.info("shouldEncode",{type:k}),!k||k.startsWith("text/")||k.includes("charset="))return false;let C=k.split("/",2)[0];return !!["image","audio","video","font","model","multipart"].includes(C)}b.Event={Edited:a$5.define("file.edited",N.object({file:N.string()}))};async function a$2(){let w={files:[],dirs:[]},k=false,v=R.directory===a$1.Path.home&&R.project.id==="global",C=async E=>{if(R.directory===Se__default.parse(R.directory).root)return;if(k=true,v){let U=new Set,D=new Set;process.platform==="darwin"&&D.add("Library"),process.platform==="win32"&&D.add("AppData");let K=new Set(["node_modules","dist","build","target","vendor"]),X=A=>A.startsWith(".")||D.has(A),$=A=>A.startsWith(".")||K.has(A),M=await gl.promises.readdir(R.directory,{withFileTypes:true}).catch(()=>[]);for(let A of M){if(!A.isDirectory()||X(A.name))continue;U.add(A.name+"/");let L=Filesystem.join(R.directory,A.name),S=await gl.promises.readdir(L,{withFileTypes:true}).catch(()=>[]);for(let P of S)P.isDirectory()&&($(P.name)||U.add(A.name+"/"+P.name+"/"));}E.dirs=Array.from(U).toSorted(),w=E,k=false;return}let O=new Set;for await(let U of a$8.files({cwd:R.directory})){E.files.push(U);let D=U;for(;;){let K=Se__default.posix.dirname(D);if(K==="."||K===D)break;D=K,!O.has(K)&&(O.add(K),E.dirs.push(K+"/"));}}w=E,k=false;};return await C(w),{async files(){return k||await C({files:[],dirs:[]}),w}}}let p;function u(){return p||(p=R.state(a$2)),p}function h(){return u()()}function g(){h();}b.init=g;async function I(){if(R.project.vcs!=="git")return [];let k=await $`git -c core.quotepath=false diff --numstat HEAD`.cwd(R.directory).quiet().nothrow().text(),v=[];if(k.trim()){let O=k.trim().split(`
|
|
31
|
+
`);for(let U of O){let D=U.split(" "),K=D[2];K&&v.push({path:K,added:D[0]==="-"?0:parseInt(D[0]||"0",10),removed:D[1]==="-"?0:parseInt(D[1]||"0",10),status:"modified"});}}let C=await $`git -c core.quotepath=false ls-files --others --exclude-standard`.cwd(R.directory).quiet().nothrow().text();if(C.trim()){let O=C.trim().split(`
|
|
32
|
+
`);for(let U of O)try{let K=(await PKG.file(Filesystem.join(R.directory,U)).text()).split(`
|
|
33
|
+
`).length;v.push({path:U,added:K,removed:0,status:"added"});}catch{}}let E=await $`git -c core.quotepath=false diff --name-only --diff-filter=D HEAD`.cwd(R.directory).quiet().nothrow().text();if(E.trim()){let O=E.trim().split(`
|
|
34
|
+
`);for(let U of O)v.push({path:U,added:0,removed:0,status:"deleted"});}return v.map(O=>({...O,path:Se__default.posix.relative(R.directory,O.path)}))}b.status=I;async function T(w){var K=[];try{let k=c(K,e.time("read",{file:w}));let v=R.project;let C=Filesystem.join(R.directory,w);if(!R.containsPath(C))throw new Error("Access denied: path escapes project directory");if(i(w)){let A=PKG.file(C);if(await A.exists()){let L=await A.arrayBuffer().catch(()=>new ArrayBuffer(0)),S=Buffer.from(L).toString("base64"),P=c$1(w);return {type:"text",content:S,mimeType:P,encoding:"base64"}}return {type:"text",content:""}}if(l(w))return {type:"binary",content:""};let E=PKG.file(C);if(!await E.exists())return {type:"text",content:""};let O=await m(E);let U=E.type||"application/octet-stream";if(O&&!d$1(U))return {type:"binary",content:"",mimeType:U};if(O){let A=await E.bytes().catch(()=>new Uint8Array(0));return {type:"text",content:Buffer.from(A).toString("base64"),mimeType:U,encoding:"base64"}}let D=await E.text().catch(()=>"").then(A=>A.trim());if(v.vcs==="git"){let A=await $`git diff ${w}`.cwd(R.directory).quiet().nothrow().text();if(A.trim()||(A=await $`git diff --staged ${w}`.cwd(R.directory).quiet().nothrow().text()),A.trim()){let L=await $`git show HEAD:${w}`.cwd(R.directory).quiet().nothrow().text(),S=structuredPatch(w,w,L,D,"old","new",{context:1/0,ignoreWhitespace:!0}),P=formatPatch(S);return {type:"text",content:D,patch:{oldFileName:S.oldFileName??w,newFileName:S.newFileName??w,oldHeader:S.oldHeader,newHeader:S.newHeader,hunks:S.hunks,index:S.index},diff:P}}}return {type:"text",content:D}}catch(X){var $$1=X,M=true;}finally{d(K,$$1,M);}}b.read=T;async function y(w){let k=[".git",".DS_Store"],v=R.project,C=U=>false;if(v.vcs==="git"){let U=Ignore.create(),D=PKG.file(Filesystem.join(R.worktree,".gitignore"));await D.exists()&&U.add((await D.text()).split(`
|
|
35
|
+
`));let K=PKG.file(Filesystem.join(R.worktree,".ignore"));await K.exists()&&U.add((await K.text()).split(`
|
|
36
|
+
`)),C=U.createFilter();}let E=w?Filesystem.join(R.directory,w):R.directory;if(!R.containsPath(E))throw new Error("Access denied: path escapes project directory");let O=[];for(let U of await gl.promises.readdir(E,{withFileTypes:true}).catch(()=>[])){if(k.includes(U.name))continue;let D=Filesystem.join(E,U.name),K=Se__default.posix.relative(R.directory,D),X=U.isDirectory()?"directory":"file";O.push({name:U.name,path:K,absolute:D,type:X,ignored:C(X==="directory"?K+"/":K)});}return O.sort((U,D)=>U.type!==D.type?U.type==="directory"?-1:1:U.name.localeCompare(D.name))}b.list=y;async function x(w){let k=w.query.trim(),v=w.limit??100,C=w.type??(w.dirs===false?"file":"all");e.info("search",{query:k,kind:C});let E=await(await h()).files(),O=A=>A.replaceAll("\\","/").replace(/\/+$/,"").split("/").some(S=>S.startsWith(".")&&S.length>1),U=k.startsWith(".")||k.includes("/."),D=A=>{if(U)return A;let L=[],S=[];for(let P of A){let _=O(P);_&&S.push(P),_||L.push(P);}return [...L,...S]};if(!k)return C==="file"?E.files.slice(0,v):D(E.dirs.toSorted()).slice(0,v);let K=C==="file"?E.files:C==="directory"?E.dirs:[...E.files,...E.dirs],X=C==="directory"&&!U?v*20:v,$=gy.go(k,K,{limit:X}).map(A=>A.target),M=C==="directory"?D($).slice(0,v):$;return e.info("search",{query:k,kind:C,results:M.length}),M}b.search=x;})(bt||(bt={}));var yl={};a$7(yl,{biome:()=>Vw,clang:()=>Jw,dart:()=>nx,gleam:()=>ix,gofmt:()=>Hw,htmlbeautifier:()=>tx,ktlint:()=>Yw,latexindent:()=>rx,mix:()=>Bw,nixfmt:()=>cx,ocamlformat:()=>ox,ormolu:()=>ux,oxfmt:()=>Ww,pint:()=>lx,prettier:()=>Gw,rlang:()=>Xw,rubocop:()=>Zw,ruff:()=>hm,rustfmt:()=>dx,shfmt:()=>ax,standardrb:()=>ex,terraform:()=>sx,uvformat:()=>Qw,zig:()=>Kw});var Hw={name:"gofmt",command:["gofmt","-w","$FILE"],extensions:[".go"],async enabled(){return await PKG.which("gofmt")!==null}},Bw={name:"mix",command:["mix","format","$FILE"],extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){return await PKG.which("mix")!==null}},Gw={name:"prettier",command:[whichSync(),"x","prettier","--write","$FILE"],environment:{},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(){let e=await Filesystem.findUp("package.json",R.directory,R.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.dependencies?.prettier||n.devDependencies?.prettier)return true}return false}},Ww={name:"oxfmt",command:[whichSync(),"x","oxfmt","$FILE"],environment:{},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],async enabled(){if(!a$2.EASBOT_OXFMT)return false;let e=await Filesystem.findUp("package.json",R.directory,R.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.dependencies?.oxfmt||n.devDependencies?.oxfmt)return true}return false}},Vw={name:"biome",command:[whichSync(),"x","@biomejs/biome","check","--write","$FILE"],environment:{},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(){let e=["biome.json","biome.jsonc"];for(let t of e)if((await Filesystem.findUp(t,R.directory,R.worktree)).length>0)return true;return false}},Kw={name:"zig",command:["zig","fmt","$FILE"],extensions:[".zig",".zon"],async enabled(){return await PKG.which("zig")!==null}},Jw={name:"clang-format",command:["clang-format","-i","$FILE"],extensions:[".c",".cc",".cpp",".cxx",".c++",".h",".hh",".hpp",".hxx",".h++",".ino",".C",".H"],async enabled(){return (await Filesystem.findUp(".clang-format",R.directory,R.worktree)).length>0}},Yw={name:"ktlint",command:["ktlint","-F","$FILE"],extensions:[".kt",".kts"],async enabled(){return await PKG.which("ktlint")!==null}},hm={name:"ruff",command:["ruff","format","$FILE"],extensions:[".py",".pyi"],async enabled(){if(!await PKG.which("ruff"))return false;let e=["pyproject.toml","ruff.toml",".ruff.toml"];for(let n of e){let o=await Filesystem.findUp(n,R.directory,R.worktree);if(o.length>0)if(n==="pyproject.toml"){if((await PKG.file(o[0]).text()).includes("[tool.ruff]"))return true}else return true}let t=["requirements.txt","pyproject.toml","Pipfile"];for(let n of t){let o=await Filesystem.findUp(n,R.directory,R.worktree);if(o.length>0&&(await PKG.file(o[0]).text()).includes("ruff"))return true}return false}},Xw={name:"air",command:["air","format","$FILE"],extensions:[".R"],async enabled(){if(await PKG.which("air")==null)return false;try{let t=process.platform==="win32"?"cmd":void 0,n=Shell.spawn(t,"air --help",{stdout:"pipe",stderr:"pipe"});await n.exited;let s=(await PKG.nodeReadableStreamToText(n.stdout)).split(`
|
|
37
|
+
`)[0];if(!s)return !1;let r=s.includes("R language"),i=s.includes("formatter");return r&&i}catch{return false}}},Qw={name:"uv",command:["uv","format","--","$FILE"],extensions:[".py",".pyi"],async enabled(){if(await hm.enabled())return false;if(await PKG.which("uv")!==null){let e=process.platform==="win32"?"cmd":void 0;return await Shell.spawn(e,"uv format --help",{stderr:"pipe",stdout:"pipe"}).exited===0}return false}},Zw={name:"rubocop",command:["rubocop","--autocorrect","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("rubocop")!==null}},ex={name:"standardrb",command:["standardrb","--fix","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("standardrb")!==null}},tx={name:"htmlbeautifier",command:["htmlbeautifier","$FILE"],extensions:[".erb",".html.erb"],async enabled(){return await PKG.which("htmlbeautifier")!==null}},nx={name:"dart",command:["dart","format","$FILE"],extensions:[".dart"],async enabled(){return await PKG.which("dart")!==null}},ox={name:"ocamlformat",command:["ocamlformat","-i","$FILE"],extensions:[".ml",".mli"],async enabled(){return await PKG.which("ocamlformat")?(await Filesystem.findUp(".ocamlformat",R.directory,R.worktree)).length>0:false}},sx={name:"terraform",command:["terraform","fmt","$FILE"],extensions:[".tf",".tfvars"],async enabled(){return await PKG.which("terraform")!==null}},rx={name:"latexindent",command:["latexindent","-w","-s","$FILE"],extensions:[".tex"],async enabled(){return await PKG.which("latexindent")!==null}},ix={name:"gleam",command:["gleam","format","$FILE"],extensions:[".gleam"],async enabled(){return await PKG.which("gleam")!==null}},ax={name:"shfmt",command:["shfmt","-w","$FILE"],extensions:[".sh",".bash"],async enabled(){return await PKG.which("shfmt")!==null}},cx={name:"nixfmt",command:["nixfmt","$FILE"],extensions:[".nix"],async enabled(){return await PKG.which("nixfmt")!==null}},dx={name:"rustfmt",command:["rustfmt","$FILE"],extensions:[".rs"],async enabled(){return await PKG.which("rustfmt")!==null}},lx={name:"pint",command:["./vendor/bin/pint","$FILE"],extensions:[".php"],async enabled(){let e=await Filesystem.findUp("composer.json",R.directory,R.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.require?.["laravel/pint"]||n["require-dev"]?.["laravel/pint"])return true}return false}},ux={name:"ormolu",command:["ormolu","-i","$FILE"],extensions:[".hs"],async enabled(){return await PKG.which("ormolu")!==null}};var xs;(m=>{let e=a.create({service:"format"});m.Status=N.object({name:N.string(),extensions:N.string().array(),enabled:N.boolean()}).meta({ref:"FormatterStatus"});async function n(){let f={},a=await he.get(),p={};if(a.formatter===false)return e.info("all formatters are disabled"),{enabled:f,formatters:p};for(let u of Object.values(yl))p[u.name]=u;for(let[u,h]of Object.entries(a.formatter??{})){if(h.disabled){delete p[u];continue}let g=mergeDeep(p[u]??{},{name:u,enabled:async()=>true,command:[],extensions:[],...h});g.command.length!==0&&(p[u]=g);}return {enabled:f,formatters:p}}let o;function s(){return o||(o=R.state(n)),o}async function r(){return s()()}async function i(f){let a=await r(),p=a.enabled[f.name];return p===void 0&&(p=await f.enabled(),a.enabled[f.name]=p),p}async function c(f){let a=await r().then(u=>u.formatters),p=[];for(let u of Object.values(a))e.debug("checking",{name:u.name,ext:f}),u.extensions.includes(f)&&await i(u)&&(e.debug("enabled",{name:u.name,ext:f}),p.push(u));return p}async function l(){let f=await r(),a=[];for(let p of Object.values(f.formatters)){let u=await i(p);a.push({name:p.name,extensions:p.extensions,enabled:u});}return a}m.status=l;function d(){e.debug("init"),pe.subscribe(bt.Event.Edited,async f=>{let a=f.properties.file;e.debug("formatting",{file:a});let p=Se__default.extname(a);for(let u of await c(p)){e.debug("running",{command:u.command});try{let h=u.command.map(I=>I.replace("$FILE",a)),g=await PKG.run(h,{cwd:R.directory,env:{...process.env,...u.environment},stdout:"ignore",stderr:"pipe"});g.code!==0&&e.error("format failed",{command:h,exitCode:g.code,stderr:g.stderr});}catch(h){e.error("failed to format file",{error:h,command:u.command,...u.environment,file:a});}}});}m.init=d;})(xs||(xs={}));var Tn;(I=>{I.Tokens=N.object({accessToken:N.string(),refreshToken:N.string().optional(),expiresAt:N.number().optional(),scope:N.string().optional()}),I.ClientInfo=N.object({clientId:N.string(),clientSecret:N.string().optional(),clientIdIssuedAt:N.number().optional(),clientSecretExpiresAt:N.number().optional()}),I.Entry=N.object({tokens:I.Tokens.optional(),clientInfo:I.ClientInfo.optional(),codeVerifier:N.string().optional(),oauthState:N.string().optional(),serverUrl:N.string().optional()});let o=Se__default.join(a$1.Path.data,"mcp-auth.json");async function s(T){return (await i())[T]}I.get=s;async function r(T,y){let x=await s(T);if(x&&x.serverUrl&&x.serverUrl===y)return x}I.getForUrl=r;async function i(){return PKG.file(o).json().catch(()=>({}))}I.all=i;async function c(T,y,x){PKG.file(o);let w=await i();x&&(y.serverUrl=x),await PKG.write(o,JSON.stringify({...w,[T]:y},null,2));}I.set=c;async function l(T){PKG.file(o);let x=await i();delete x[T],await PKG.write(o,JSON.stringify(x,null,2));}I.remove=l;async function d(T,y,x){let b=await s(T)??{};b.tokens=y,await c(T,b,x);}I.updateTokens=d;async function m(T,y,x){let b=await s(T)??{};b.clientInfo=y,await c(T,b,x);}I.updateClientInfo=m;async function f(T,y){let x=await s(T)??{};x.codeVerifier=y,await c(T,x);}I.updateCodeVerifier=f;async function a(T){let y=await s(T);y&&(delete y.codeVerifier,await c(T,y));}I.clearCodeVerifier=a;async function p(T,y){let x=await s(T)??{};x.oauthState=y,await c(T,x);}I.updateOAuthState=p;async function u(T){return (await s(T))?.oauthState}I.getOAuthState=u;async function h(T){let y=await s(T);y&&(delete y.oauthState,await c(T,y));}I.clearOAuthState=h;async function g(T){let y=await s(T);return y?.tokens?y.tokens.expiresAt?y.tokens.expiresAt<Date.now()/1e3:false:null}I.isTokenExpired=g;})(Tn||(Tn={}));a.create({service:"mcp.oauth"});var fr=19876,ym="/mcp/oauth/callback";var gr=a.create({service:"mcp.oauth-callback"}),bx=`<!DOCTYPE html>
|
|
38
|
+
<html>
|
|
39
|
+
<head>
|
|
40
|
+
<title>EasBot - Authorization Successful</title>
|
|
41
|
+
<style>
|
|
42
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
43
|
+
.container { text-align: center; padding: 2rem; }
|
|
44
|
+
h1 { color: #4ade80; margin-bottom: 1rem; }
|
|
45
|
+
p { color: #aaa; }
|
|
46
|
+
</style>
|
|
47
|
+
</head>
|
|
48
|
+
<body>
|
|
49
|
+
<div class="container">
|
|
50
|
+
<h1>Authorization Successful</h1>
|
|
51
|
+
<p>You can close this window and return to EasBot.</p>
|
|
52
|
+
</div>
|
|
53
|
+
<script>setTimeout(() => window.close(), 2000);</script>
|
|
54
|
+
</body>
|
|
55
|
+
</html>`,sc=e=>`<!DOCTYPE html>
|
|
56
|
+
<html>
|
|
57
|
+
<head>
|
|
58
|
+
<title>EasBot - Authorization Failed</title>
|
|
59
|
+
<style>
|
|
60
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
61
|
+
.container { text-align: center; padding: 2rem; }
|
|
62
|
+
h1 { color: #f87171; margin-bottom: 1rem; }
|
|
63
|
+
p { color: #aaa; }
|
|
64
|
+
.error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
|
|
65
|
+
</style>
|
|
66
|
+
</head>
|
|
67
|
+
<body>
|
|
68
|
+
<div class="container">
|
|
69
|
+
<h1>Authorization Failed</h1>
|
|
70
|
+
<p>An error occurred during authorization.</p>
|
|
71
|
+
<div class="error">${e}</div>
|
|
72
|
+
</div>
|
|
73
|
+
</body>
|
|
74
|
+
</html>`,hr;(d=>{let e,t=new Map,n=300*1e3;async function o(){if(e)return;if(await i()){gr.info("oauth callback server already running on another instance",{port:fr});return}e=createServer((f,a)=>{let p=new URL(f.url||"",`http://localhost:${fr}`);if(p.pathname!==ym){a.writeHead(404,{"Content-Type":"text/plain"}),a.end("Not found");return}let u=p.searchParams.get("code"),h=p.searchParams.get("state"),g=p.searchParams.get("error"),I=p.searchParams.get("error_description");if(gr.info("received oauth callback",{hasCode:!!u,state:h,error:g}),!h){let y="Missing required state parameter - potential CSRF attack";gr.error("oauth callback missing state parameter",{url:p.toString()}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(sc(y));return}if(g){let y=I||g;if(t.has(h)){let x=t.get(h);clearTimeout(x.timeout),t.delete(h),x.reject(new Error(y));}a.writeHead(200,{"Content-Type":"text/html"}),a.end(sc(y));return}if(!u){a.writeHead(400,{"Content-Type":"text/html"}),a.end(sc("No authorization code provided"));return}if(!t.has(h)){let y="Invalid or expired state parameter - potential CSRF attack";gr.error("oauth callback with invalid state",{state:h,pendingStates:Array.from(t.keys())}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(sc(y));return}let T=t.get(h);clearTimeout(T.timeout),t.delete(h),T.resolve(u),a.writeHead(200,{"Content-Type":"text/html"}),a.end(bx);}).listen(fr),gr.info("oauth callback server started",{port:fr});}d.ensureRunning=o;function s(m){return new Promise((f,a)=>{let p=setTimeout(()=>{t.has(m)&&(t.delete(m),a(new Error("OAuth callback timeout - authorization took too long")));},n);t.set(m,{resolve:f,reject:a,timeout:p});})}d.waitForCallback=s;function r(m){let f=t.get(m);f&&(clearTimeout(f.timeout),t.delete(m),f.reject(new Error("Authorization cancelled")));}d.cancelPending=r;async function i(){return new Promise(m=>{let f=connect({host:"127.0.0.1",port:fr});f.on("connect",()=>{f.end(),m(true);}),f.on("error",()=>{m(false);});})}d.isPortInUse=i;async function c(){e&&(e.close(),e=void 0,gr.info("oauth callback server stopped"));for(let[,m]of t)clearTimeout(m.timeout),m.reject(new Error("OAuth callback server stopped"));t.clear();}d.stop=c;function l(){return e!==void 0}d.isRunning=l;})(hr||(hr={}));var ze;(L=>{let e=a.create({service:"mcp"}),t=3e4;L.ToolsChanged=a$5.define("mcp.tools.changed",N.object({server:N.string()})),L.BrowserOpenFailed=a$5.define("mcp.browser.open.failed",N.object({mcpName:N.string(),url:N.string()})),L.Failed=NamedError.create("MCPFailed",N.object({name:N.string()}));function r(S){return typeof S=="object"&&S!==null&&"type"in S}async function i(){let P=(await he.get()).mcp??{},_={},j={};return await Promise.all(Object.entries(P).map(async([B,Z])=>{if(!r(Z)){e.error("Ignoring MCP config entry without type",{key:B});return}if(Z.enabled===false)return;let ee=await p(B,Z).catch(()=>{});ee&&(_[B]=ee),j[B]={name:B,config:Z,scope:Z.scope};})),{clients:_,configInfo:j}}let c;function l(){return c||(c=R.state(i,async S=>{await initLog$3({logDir:a$1.Path.log,logFile:"mcp.log",level:a.getLevel(),print:false}),await Promise.all(Object.values(S.clients).map(P=>P.disconnect().catch(_=>{e.error("Failed to close MCP client",{error:_});}))),O.clear();})),c}async function d(){return l()()}function m(S){return S?S.status:{status:"disconnected"}}async function f(S,P){let _=await P.listPrompts().catch(B=>(e.error("failed to get prompts",{clientName:S,error:B.message}),[])),j={};for(let B of _){let Z=S.replace(/[^a-zA-Z0-9_-]/g,"_"),ee=B.name.replace(/[^a-zA-Z0-9_-]/g,"_"),se=Z+":"+ee;j[se]={...B,client:S};}return j}async function a$2(S,P){let _=await P.listResources().catch(B=>(e.error("failed to get resources",{clientName:S,error:B.message}),[])),j={};for(let B of _){let Z=S.replace(/[^a-zA-Z0-9_-]/g,"_"),ee=B.name.replace(/[^a-zA-Z0-9_-]/g,"_"),se=Z+":"+ee;j[se]={...B,client:S};}return j}async function p(S,P){if(P.enabled===false){e.info("mcp server disabled",{key:S});return}e.info("found",{key:S,type:P.type});let _=new MCPClient;if(P.type==="remote"){let B=P.oauth===false,Z=typeof P.oauth=="object"?P.oauth:void 0,ee={type:"remote",url:P.url,headers:P.headers,oauth:B?false:Z,timeout:P.timeout},se=P.timeout??t;try{await bl(_.connect(S,ee),se),_.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:S}),await pe.publish(L.ToolsChanged,{server:S});}),e.info("connected",{key:S});}catch(le){_.isAuthRequired()?(O.set(S,_),pe.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${S}" requires authentication. Run: easbot mcp auth ${S}`,variant:"warning",duration:8e3}).catch(ae=>e.debug("failed to show toast",{error:ae}))):_.isClientRegistrationRequired()?pe.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${S}" requires a pre-registered client ID. Add clientId to your config.`,variant:"warning",duration:8e3}).catch(ae=>e.debug("failed to show toast",{error:ae})):e.error("remote mcp connection failed",{key:S,error:le instanceof Error?le.message:String(le)});}}if(P.type==="local"){if(!P.command){e.error("MCP command is empty",{key:S});return}let B={type:"local",command:[P.command,...P.args??[]],cwd:R.directory,environment:P.env,timeout:P.timeout},Z=P.timeout??t;try{await bl(_.connect(S,B),Z),_.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:S}),await pe.publish(L.ToolsChanged,{server:S});}),e.info("local mcp connected",{key:S});}catch(ee){e.error("local mcp startup failed",{key:S,command:P.command,args:P.args,cwd:R.directory,error:ee instanceof Error?ee.message:String(ee)});}}if(_.status.status!=="connected")return _;let j=await bl(Promise.resolve(_.listTools()).then(B=>({tools:Object.values(B).map(Z=>Z)})),P.timeout??t).catch(B=>{e.error("failed to get tools from client",{key:S,error:B});});if(!j){await _.disconnect().catch(B=>{e.error("Failed to close MCP client",{error:B});});return}return e.info("create() successfully created client",{key:S,toolCount:j.tools.length}),_}async function u(S,P){let _=await d(),j=await p(S,P);if(!j)return {status:await h()};let B=_.clients[S];return B&&await B.disconnect().catch(Z=>{e.error("Failed to close existing MCP client",{name:S,error:Z});}),_.clients[S]=j,{status:await h()}}L.add=u;async function h(){let S=await d(),_=(await he.get()).mcp??{},j={};for(let[B,Z]of Object.entries(_)){if(!r(Z))continue;let ee=S.clients[B];Z.enabled===false?j[B]={status:"disabled"}:j[B]=m(ee);}return j}L.status=h;async function g(){return d().then(S=>S.clients)}L.clients=g;async function I(){return d().then(S=>S.configInfo)}L.configInfo=I;async function T(S){return (await I())[S]}L.getConfig=T;async function y(S){let j=((await he.get()).mcp??{})[S];if(!j){e.error("MCP config not found",{name:S});return}if(!r(j)){e.error("Ignoring MCP connect request for config without type",{name:S});return}let B=await p(S,j),Z=await d();if(B){let ee=Z.clients[S];ee&&await ee.disconnect().catch(se=>{e.error("Failed to close existing MCP client",{name:S,error:se});}),Z.clients[S]=B;}}L.connect=y;async function x(S){let P=await d(),_=P.clients[S];_&&(await _.disconnect().catch(j=>{e.error("Failed to close MCP client",{name:S,error:j});}),delete P.clients[S]);}L.disconnect=x;async function b(){let S={},P=await he.get(),_=await g(),j=P.experimental?.mcp_timeout;for(let[B,Z]of Object.entries(_)){if(Z.status.status!=="connected")continue;let ee=await Z.listTools().catch(se=>(e.error("failed to get tools",{clientName:B,error:se.message}),{}));for(let[se,le]of Object.entries(ee)){let ae=le,we=B.replace(/[^a-zA-Z0-9_-]/g,"_"),re=se.replace(/[^a-zA-Z0-9_-]/g,"_"),Q=we+"_"+re;S[Q]=await w(ae,Z,j);}}return S}L.tools=b;async function w(S,P,_){let j=S.inputSchema,B={...j,type:"object",properties:j.properties??{},additionalProperties:false};return dynamicTool({description:S.description??"",inputSchema:jsonSchema(B),execute:async Z=>{let ee=await P.callTool(S.name,Z||{},_);return {content:ee.content.map(se=>se.type==="text"?{type:"text",text:se.text??""}:se.type==="image"?{type:"image",data:se.data??"",mimeType:se.mimeType}:se.type==="resource"&&se.resource?{type:"resource",resource:se.resource}:{type:"text",text:String(se)}),metadata:ee.metadata}}})}async function k(){let S=await g(),P=await I(),_=[];for(let[j,B]of Object.entries(S)){if(B.status.status!=="connected")continue;let Z=await f(j,B),se=P[j]?.scope??"all";for(let[le,ae]of Object.entries(Z))_.push([le,{...ae,scope:se}]);}return Object.fromEntries(_)}L.prompts=k;async function v(){let S=await g();return Object.fromEntries((await Promise.all(Object.entries(S).map(async([_,j])=>j.status.status!=="connected"?[]:Object.entries(await a$2(_,j))))).flat())}L.resources=v;async function C(S,P,_){let B=(await g())[S];if(!B){e.warn("client not found for prompt",{clientName:S});return}return B.getPrompt(P,_).catch(Z=>{e.error("failed to get prompt from MCP server",{clientName:S,promptName:P,error:Z.message});})}L.getPrompt=C;async function E(S,P){let j=(await g())[S];if(!j){e.warn("client not found for resource",{clientName:S});return}return j.readResource(P).catch(B=>{e.error("failed to read resource from MCP server",{clientName:S,resourceUri:P,error:B.message});})}L.readResource=E;let O=new Map;async function U(S){let _=(await he.get()).mcp?.[S];if(!_)throw new Error(`MCP server not found: ${S}`);if(!r(_))throw new Error(`MCP server ${S} is disabled or missing configuration`);if(_.type!=="remote")throw new Error(`MCP server ${S} is not a remote server`);if(_.oauth===false)throw new Error(`MCP server ${S} has OAuth explicitly disabled`);await hr.ensureRunning();let j=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(ee=>ee.toString(16).padStart(2,"0")).join("");await Tn.updateOAuthState(S,j);let B=typeof _.oauth=="object"?_.oauth:void 0,Z=new MCPClient;try{return await Z.connect(S,{type:"remote",url:_.url,headers:_.headers,oauth:B,timeout:_.timeout}),{authorizationUrl:""}}catch(ee){if(Z.isAuthRequired())return O.set(S,Z),{authorizationUrl:Z.getAuthorizationUrl()};throw ee}}L.startAuth=U;async function D(S){let{authorizationUrl:P}=await U(S);if(!P){let se=(await d()).clients[S];return m(se)}let _=await Tn.getOAuthState(S);if(!_)throw new Error("OAuth state not found");e.info("opening browser for oauth",{mcpName:S,url:P,state:_});let j=hr.waitForCallback(_);try{let ee=await Sx(P);await new Promise((se,le)=>{let ae=setTimeout(()=>se(),500);ee.on("error",we=>{clearTimeout(ae),le(we);}),ee.on("exit",we=>{we!==null&&we!==0&&(clearTimeout(ae),le(new Error(`Browser open failed with exit code ${we}`)));});});}catch(ee){e.warn("failed to open browser, user must open URL manually",{mcpName:S,error:ee}),await pe.publish(L.BrowserOpenFailed,{mcpName:S,url:P});}let B=await j;if(await Tn.getOAuthState(S)!==_)throw await Tn.clearOAuthState(S),new Error("OAuth state mismatch");return await Tn.clearOAuthState(S),K(S,B)}L.authenticate=D;async function K(S,P){let _=O.get(S);if(!_)throw new Error(`No pending OAuth flow for MCP server: ${S}`);try{await _.finishAuth(P),await Tn.clearCodeVerifier(S);let B=(await he.get()).mcp?.[S];if(!B||!r(B))throw new Error(`MCP server not found: ${S}`);O.delete(S),await u(S,B);let Z=await d();return m(Z.clients[S])}catch(j){return e.error("failed to finish oauth",{mcpName:S,error:j}),{status:"failed",error:j instanceof Error?j.message:String(j)}}}L.finishAuth=K;async function X(S){await Tn.remove(S),hr.cancelPending(S),O.delete(S),await Tn.clearOAuthState(S),e.info("removed oauth credentials",{mcpName:S});}L.removeAuth=X;async function $(S){let _=(await he.get()).mcp?.[S];return !_||!r(_)?false:_.type==="remote"&&_.oauth!==false}L.supportsOAuth=$;async function M(S){return !!(await Tn.get(S))?.tokens}L.hasStoredTokens=M;async function A(S){return await M(S)?await Tn.isTokenExpired(S)?"expired":"authenticated":"not_authenticated"}L.getAuthStatus=A;})(ze||(ze={}));function bl(e,t){return new Promise((n,o)=>{let s=setTimeout(()=>o(new Error(`Operation timed out after ${t}ms`)),t);e.then(r=>{clearTimeout(s),n(r);}).catch(r=>{clearTimeout(s),o(r);});})}var ds={};a$7(ds,{create:()=>zP,createAgent:()=>ch,getAgent:()=>nd,getDefaultAgent:()=>NP,list:()=>UP,listAgents:()=>ah});var Ve;(f=>{let e=a.create({service:"tool-truncation"});f.MAX_LINES=500,f.MAX_BYTES=50*1024,f.DIR=Filesystem.join(a$1.Path.data,"tool-output"),f.GLOB=Filesystem.join(f.DIR,"*");let r=10080*60*1e3;async function i(){try{let{Scheduler:a}=await import('./scheduler-3AYHIZGY.mjs');await a.createCommand({id:"cmd_tool-truncation-cleanup",name:"truncation-cleanup",cron:"0 * * * *",command:"cleanup",arguments:"truncation",recurring:!0,durable:!0});}catch(a){e.error("Failed to register cleanup task",{error:a});}}f.init=i;async function c(){let a=Identifier.timestamp(Identifier.create("tool",false,Date.now()-r)),u=(await Tt__default.readdir(f.DIR).catch(()=>[])).filter(h=>h.startsWith("tool_"));for(let h of u)Identifier.timestamp(h)>=a||await Tt__default.unlink(Filesystem.join(f.DIR,h)).catch(()=>{});}f.cleanup=c;function l(a){return a?.permission?Me.evaluate("task","*",a.permission).action!=="deny":false}async function d(a,p={},u){let h=p.maxLines??f.MAX_LINES,g=p.maxBytes??f.MAX_BYTES,I=p.direction??"head",T=a.split(`
|
|
75
|
+
`),y=Buffer.byteLength(a,"utf-8");if(T.length<=h&&y<=g)return {content:a,truncated:false};let x=[],b=0,w=0;if(I==="head")for(b=0;b<T.length&&b<h;b++){let $=T[b];if(!$)continue;let M=Buffer.byteLength($,"utf-8")+(b>0?1:0);if(w+M>g){break}x.push($),w+=M;}else for(b=T.length-1;b>=0&&x.length<h;b--){let $=T[b];if(!$)continue;let M=Buffer.byteLength($,"utf-8")+(x.length>0?1:0);if(w+M>g){break}x.unshift($),w+=M;}let v=T.length-x.length,C=y-w,E=x.join(`
|
|
76
|
+
`),O=Identifier.ascending("tool"),U=Filesystem.join(f.DIR,O);await Tt__default.mkdir(f.DIR,{recursive:true}).catch(()=>{}),await Tt__default.writeFile(U,a,"utf-8");let D=l(u)?`The tool call succeeded but the output was truncated. Full output saved to: ${U}
|
|
77
|
+
Use the Task tool to have explore agent process this file with Grep and Read (with offset/limit). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${U}
|
|
78
|
+
Use Grep to search the full content or Read with offset/limit to view specific sections.`,K=`${v}/${T.length} lines (${C}/${y} bytes) truncated`;return {content:I==="head"?`${E}
|
|
79
|
+
|
|
80
|
+
...${K}...
|
|
81
|
+
|
|
82
|
+
${D}`:`...${K}...
|
|
83
|
+
|
|
84
|
+
${D}
|
|
85
|
+
|
|
86
|
+
${E}`,truncated:true,outputPath:U}}f.output=d;function m(a,p){if(!a.truncated)return "";let{outputPath:u}=a;return l(p)?`The tool call succeeded but the output was truncated. Full output saved to: ${u}
|
|
87
|
+
Use the Task tool to have explore agent process this file (with Grep and Read tools). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${u}
|
|
88
|
+
Use Grep to search the full content, or use Read tool with offset/limit parameters to view specific sections.`}f.formatHint=m;})(Ve||(Ve={}));a.create({service:"provider-transform"});function kx(e){if(e.startsWith("image/"))return "image";if(e.startsWith("audio/"))return "audio";if(e.startsWith("video/"))return "video";if(e==="application/pdf")return "pdf"}var wt;(T=>{T.OUTPUT_TOKEN_MAX=a$2.EASBOT_OUTPUT_TOKEN_MAX||32e3;function t(y){switch(y){case "@ai-sdk/github-copilot":return "copilot";case "@ai-sdk/openai":case "@ai-sdk/azure":return "openai";case "@ai-sdk/amazon-bedrock":return "bedrock";case "@ai-sdk/anthropic":case "@ai-sdk/google-vertex/anthropic":return "anthropic";case "@ai-sdk/google-vertex":case "@ai-sdk/google":return "google";case "@ai-sdk/gateway":return "gateway";case "@openrouter/ai-sdk-provider":return "openrouter";case "@easbot/ollama-sdk":return "ollama";case "@easbot/local-model-sdk":return "easbot-local"}}function n(y,x,b){if(x.api.npm==="@ai-sdk/anthropic"&&(y=y.map(w=>{if(typeof w.content=="string")return w.content===""?void 0:w;if(!Array.isArray(w.content))return w;let k=w.content.filter(v=>v.type==="text"||v.type==="reasoning"?v.text!=="":true);if(k.length!==0)return {...w,content:k}}).filter(w=>w!==void 0&&w.content!=="")),x.api.id.includes("claude"))return y.map(w=>((w.role==="assistant"||w.role==="tool")&&Array.isArray(w.content)&&(w.content=w.content.map(k=>(k.type==="tool-call"||k.type==="tool-result")&&"toolCallId"in k?{...k,toolCallId:k.toolCallId.replace(/[^a-zA-Z0-9_-]/g,"_")}:k)),w));if(x.providerId==="mistral"||x.api.id.toLowerCase().includes("mistral")||x.api.id.toLocaleLowerCase().includes("devstral")){let w=[];for(let k=0;k<y.length;k++){let v=y[k];if(!v)continue;let C=y[k+1];(v.role==="assistant"||v.role==="tool")&&Array.isArray(v.content)&&(v.content=v.content.map(E=>{if((E.type==="tool-call"||E.type==="tool-result")&&"toolCallId"in E){let O=E.toolCallId.replace(/[^a-zA-Z0-9]/g,"").substring(0,9).padEnd(9,"0");return {...E,toolCallId:O}}return E})),w.push(v),v.role==="tool"&&C?.role==="user"&&w.push({role:"assistant",content:[{type:"text",text:"Done."}]});}return w}if(typeof x.capabilities.interleaved=="object"&&x.capabilities.interleaved.field){let w=x.capabilities.interleaved.field;return y.map(k=>{if(k.role==="assistant"&&Array.isArray(k.content)){let C=k.content.filter(O=>O.type==="reasoning").map(O=>O.text).join(""),E=k.content.filter(O=>O.type!=="reasoning");return C?{...k,content:E,providerOptions:{...k.providerOptions,openaiCompatible:{...k.providerOptions?.openaiCompatible,[w]:C}}}:{...k,content:E}}return k})}return y}function o(y,x){let b=y.filter(v=>v.role==="system").slice(0,2),w=y.filter(v=>v.role!=="system").slice(-2),k={anthropic:{cacheControl:{type:"ephemeral"}},openrouter:{cacheControl:{type:"ephemeral"}},bedrock:{cachePoint:{type:"default"}},openaiCompatible:{cache_control:{type:"ephemeral"}},copilot:{copilot_cache_control:{type:"ephemeral"}}};for(let v of unique([...b,...w])){if(!(x==="anthropic"||x.includes("bedrock"))&&Array.isArray(v.content)&&v.content.length>0){let O=v.content[v.content.length-1];if(O&&typeof O=="object"){O.providerOptions=mergeDeep(O.providerOptions??{},k);continue}}v.providerOptions=mergeDeep(v.providerOptions??{},k);}return y}function s(y,x){return y.map(b=>{if(b.role!=="user"||!Array.isArray(b.content))return b;let w=b.content.map(k=>{if(k.type!=="file"&&k.type!=="image")return k;if(k.type==="image"){let U=k.image.toString();if(U.startsWith("data:")){let D=U.match(/^data:([^;]+);base64,(.*)$/);if(D&&(!D[2]||D[2].length===0))return {type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let v=k.type==="image"?k.image?.toString()?.split(";")?.[0]?.replace("data:",""):k.mediaType,C=k.type==="file"?k.filename:void 0,E=kx(v??"");return !E||x.capabilities.input[E]?k:{type:"text",text:`ERROR: Cannot read ${C?`"${C}"`:E} (this model does not support ${E} input). Inform the user.`}});return {...b,content:w}})}function r(y,x,b){y=s(y,x),y=n(y,x),(x.providerId==="anthropic"||x.api.id.includes("anthropic")||x.api.id.includes("claude")||x.id.includes("anthropic")||x.id.includes("claude")||x.api.npm==="@ai-sdk/anthropic")&&(y=o(y,x.providerId));let w=t(x.api.npm);if(w&&w!==x.providerId&&x.api.npm!=="@ai-sdk/azure"){let k=v=>{if(!v||!(x.providerId in v))return v;let C={...v};return C[w]=C[x.providerId],delete C[x.providerId],C};y=y.map(v=>Array.isArray(v.content)?{...v,providerOptions:k(v.providerOptions),content:v.content.map(C=>({...C,providerOptions:k(C.providerOptions)}))}:{...v,providerOptions:k(v.providerOptions)});}return y}T.message=r;function i(y){let x=y.id.toLowerCase();if(x.includes("qwen"))return .55;if(!x.includes("claude")){if(x.includes("gemini")||x.includes("glm-4.6")||x.includes("glm-4.7")||x.includes("minimax-m2"))return 1;if(x.includes("kimi-k2"))return x.includes("thinking")||x.includes("k2.")||x.includes("k2p")?1:.6}}T.temperature=i;function c(y){let x=y.id.toLowerCase();if(x.includes("qwen"))return 1;if(x.includes("minimax-m2")||x.includes("kimi-k2.5")||x.includes("kimi-k2p5")||x.includes("gemini"))return .95}T.topP=c;function l(y){let x=y.id.toLowerCase();if(x.includes("minimax-m2"))return x.includes("m2.1")?40:20;if(x.includes("gemini"))return 64}T.topK=l;let d=["low","medium","high"],m=["none","minimal",...d,"xhigh"];function f(y){if(!y.capabilities.reasoning)return {};let x=y.id.toLowerCase();if(x.includes("deepseek")||x.includes("minimax")||x.includes("glm")||x.includes("mistral")||x.includes("kimi")||x.includes("k2p5"))return {};if(x.includes("grok")&&x.includes("grok-3-mini"))return y.api.npm==="@openrouter/ai-sdk-provider"?{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}}:{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}};if(x.includes("grok"))return {};switch(y.api.npm){case "@openrouter/ai-sdk-provider":return !y.id.includes("gpt")&&!y.id.includes("gemini-3")?{}:Object.fromEntries(m.map(b=>[b,{reasoning:{effort:b}}]));case "@ai-sdk/gateway":return Object.fromEntries(m.map(b=>[b,{reasoningEffort:b}]));case "@ai-sdk/github-copilot":{if(y.id.includes("gemini"))return {};if(y.id.includes("claude"))return {thinking:{thinking_budget:4e3}};let b=iife(()=>x.includes("5.1-codex-max")||x.includes("5.2")||x.includes("5.3")?[...d,"xhigh"]:d);return Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/cerebras":case "@ai-sdk/togetherai":case "@ai-sdk/xai":case "@ai-sdk/deepinfra":case "@ai-sdk/openai-compatible":return Object.fromEntries(d.map(b=>[b,{reasoningEffort:b}]));case "@ai-sdk/azure":{if(x==="o1-mini")return {};let b=["low","medium","high"];return (x.includes("gpt-5-")||x==="gpt-5")&&b.unshift("minimal"),Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/openai":{if(x==="gpt-5-pro")return {};let b=iife(()=>{if(x.includes("codex"))return x.includes("5.2")||x.includes("5.3")?[...d,"xhigh"]:d;let w=[...d];return (x.includes("gpt-5-")||x==="gpt-5")&&w.unshift("minimal"),y.release_date>="2025-11-13"&&w.unshift("none"),y.release_date>="2025-12-04"&&w.push("xhigh"),w});return Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/anthropic":case "@ai-sdk/google-vertex/anthropic":return {high:{thinking:{type:"enabled",budgetTokens:Math.min(16e3,Math.floor(y.limit.output/2-1))}},max:{thinking:{type:"enabled",budgetTokens:Math.min(31999,y.limit.output-1)}}};case "@ai-sdk/amazon-bedrock":return y.api.id.includes("anthropic")?{high:{reasoningConfig:{type:"enabled",budgetTokens:16e3}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(b=>[b,{reasoningConfig:{type:"enabled",maxReasoningEffort:b}}]));case "@ai-sdk/google-vertex":case "@ai-sdk/google":return x.includes("2.5")?{high:{thinkingConfig:{includeThoughts:true,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:true,thinkingBudget:24576}}}:Object.fromEntries(["low","high"].map(b=>[b,{includeThoughts:true,thinkingLevel:b}]));case "@ai-sdk/mistral":return {};case "@ai-sdk/cohere":return {};case "@ai-sdk/groq":{let b=["none",...d];return Object.fromEntries(b.map(w=>[w,{includeThoughts:true,thinkingLevel:w}]))}case "@ai-sdk/perplexity":return {};case "@mymediset/sap-ai-provider":case "@jerome-benoit/sap-ai-provider-v2":return y.api.id.includes("anthropic")?{high:{thinking:{type:"enabled",budgetTokens:16e3}},max:{thinking:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(b=>[b,{reasoningEffort:b}]))}return {}}T.variants=f;function a(y){let x={};(y.model.providerId==="openai"||y.model.api.npm==="@ai-sdk/openai"||y.model.api.npm==="@ai-sdk/github-copilot")&&(x.store=false),y.model.api.npm==="@openrouter/ai-sdk-provider"&&(x.usage={include:true},y.model.api.id.includes("gemini-3")&&(x.reasoning={effort:"high"})),(y.model.providerId==="baseten"||y.model.providerId==="easbot"&&["kimi-k2-thinking","glm-4.6"].includes(y.model.api.id))&&(x.chat_template_args={enable_thinking:true}),["zai","zhipuai"].includes(y.model.providerId)&&y.model.api.npm==="@ai-sdk/openai-compatible"&&(x.thinking={type:"enabled",clear_thinking:false}),(y.model.providerId==="openai"||y.providerOptions?.setCacheKey)&&(x.promptCacheKey=y.sessionId),(y.model.api.npm==="@ai-sdk/google"||y.model.api.npm==="@ai-sdk/google-vertex")&&(x.thinkingConfig={includeThoughts:true},y.model.api.id.includes("gemini-3")&&(x.thinkingConfig.thinkingLevel="high"));let b=y.model.api.id.toLowerCase();return (y.model.api.npm==="@ai-sdk/anthropic"||y.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(b.includes("k2p5")||b.includes("kimi-k2.5")||b.includes("kimi-k2p5"))&&(x.thinking={type:"enabled",budgetTokens:Math.min(16e3,Math.floor(y.model.limit.output/2-1))}),y.model.providerId==="alibaba-cn"&&y.model.capabilities.reasoning&&y.model.api.npm==="@ai-sdk/openai-compatible"&&!b.includes("kimi-k2-thinking")&&(x.enable_thinking=true),y.model.api.id.includes("gpt-5")&&!y.model.api.id.includes("gpt-5-chat")&&(y.model.api.id.includes("gpt-5-pro")||(x.reasoningEffort="medium",x.reasoningSummary="auto"),y.model.api.id.includes("gpt-5.")&&!y.model.api.id.includes("codex")&&!y.model.api.id.includes("-chat")&&y.model.providerId!=="azure"&&(x.textVerbosity="low"),y.model.providerId.startsWith("easbot")&&(x.promptCacheKey=y.sessionId,x.include=["reasoning.encrypted_content"],x.reasoningSummary="auto")),y.model.providerId==="venice"&&(x.promptCacheKey=y.sessionId),x}T.options=a;function p(y){return y.providerId==="openai"||y.api.npm==="@ai-sdk/openai"||y.api.npm==="@ai-sdk/github-copilot"?y.api.id.includes("gpt-5")?y.api.id.includes("5.")?{store:false,reasoningEffort:"low"}:{store:false,reasoningEffort:"minimal"}:{store:false}:y.providerId==="google"?y.api.id.includes("gemini-3")?{thinkingConfig:{thinkingLevel:"minimal"}}:{thinkingConfig:{thinkingBudget:0}}:y.providerId==="openrouter"?y.api.id.includes("google")?{reasoning:{enabled:false}}:{reasoningEffort:"minimal"}:{}}T.smallOptions=p;let u={amazon:"bedrock"};function h(y,x){if(y.api.npm==="@ai-sdk/gateway"){let w=y.api.id.indexOf("/"),k=w>0?y.api.id.slice(0,w):void 0,v=k?u[k]??k:void 0,C=x.gateway,E=Object.fromEntries(Object.entries(x).filter(([D])=>D!=="gateway")),O=Object.keys(E).length>0,U={};return C!==void 0&&(U.gateway=C),O&&(v?U[v]=E:C&&typeof C=="object"&&!Array.isArray(C)?U.gateway={...C,...E}:U.gateway=E),U}return {[t(y.api.npm)??y.providerId]:x}}T.providerOptions=h;function g(y){return Math.min(y.limit.output,T.OUTPUT_TOKEN_MAX)||T.OUTPUT_TOKEN_MAX}T.maxOutputTokens=g;function I(y,x){if(y.providerId==="google"||y.api.id.includes("gemini")){let b=w=>{if(w===null||typeof w!="object")return w;if(Array.isArray(w))return w.map(b);let k={};for(let[v,C]of Object.entries(w))v==="enum"&&Array.isArray(C)?(k[v]=C.map(E=>String(E)),(k.type==="integer"||k.type==="number")&&(k.type="string")):typeof C=="object"&&C!==null?k[v]=b(C):k[v]=C;return k.type==="object"&&k.properties&&Array.isArray(k.required)&&(k.required=k.required.filter(v=>v in k.properties)),k.type==="array"&&(k.items==null&&(k.items={}),typeof k.items=="object"&&!Array.isArray(k.items)&&!k.items.type&&(k.items.type="string")),k.type&&k.type!=="object"&&(delete k.properties,delete k.required),k};x=b(x);}return x}T.schema=I;})(wt||(wt={}));function Kt(e,t){let n=typeof e=="string"?e:"anonymous",o=typeof e=="string"?t:e,{init:s}=o,r=s instanceof Function?s:()=>s;return {name:n,init:r}}var Jo;(s=>{let e=a.create({service:"llm"});s.OUTPUT_TOKEN_MAX=wt.OUTPUT_TOKEN_MAX;async function n(r){let i=e.clone().tag("providerId",r.model.providerId).tag("modelId",r.model.id).tag("sessionId",r.sessionId).tag("small",(r.small??false).toString()).tag("agent",r.agent.name).tag("mode",r.agent.mode);i.info("stream",{modelId:r.model.id,providerId:r.model.providerId});let[c,l,d,m]=await Promise.all([xe.getLanguage(r.model),he.get(),xe.getProvider(r.model.providerId),Qe.get(r.model.providerId)]),f=d?.id==="openai"&&m?.type==="oauth",a=[r.system.filter(E=>E).join(`
|
|
89
|
+
`)],p=a[0];if(a.length>2&&a[0]===p){let E=a.slice(1);a.length=0,a.push(p,E.join(`
|
|
90
|
+
`));}let u=!r.small&&r.model.variants&&r.user.variant?r.model.variants[r.user.variant]:{},h=r.small?wt.smallOptions(r.model):wt.options({model:r.model,sessionId:r.sessionId,providerOptions:d?.options??{}}),g=pipe(h,mergeDeep(r.model.options??{}),mergeDeep(r.agent.options??{}),mergeDeep(u??{}));f&&(g.instructions=a.join(`
|
|
91
|
+
`));let I=await Le.triggerEvent(HookEvent.LlmParams,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user}),T=Object.assign({temperature:r.model.capabilities.temperature?r.agent.temperature??wt.temperature(r.model):void 0,topP:r.agent.topP??wt.topP(r.model),topK:wt.topK(r.model),options:g},I.output??{}),x=(await Le.triggerEvent(HookEvent.LlmHeaders,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user})).output?.headers??{},b=f||d?.id?.includes("github-copilot")?void 0:wt.maxOutputTokens(r.model),w=r.tools;(d?.options?.litellmProxy===true||r.model.providerId.toLowerCase().includes("litellm")||r.model.api.id.toLowerCase().includes("litellm")||r.model.providerId.includes("github-copilot"))&&Object.keys(w).length===0&&o(r.messages)&&(w._noop=tool({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:jsonSchema({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:async()=>({output:"",title:"",metadata:{}})}));let v=[...a.map(E=>({role:"system",content:E??""}))],C=streamText({onError(E){i.error("stream error",{error:E});},async experimental_repairToolCall(E){let O=E.toolCall.toolName.toLowerCase();return O!==E.toolCall.toolName&&w[O]?{...E.toolCall,toolName:O}:{...E.toolCall,input:JSON.stringify({tool:E.toolCall.toolName,error:E.error.message}),toolName:"invalid"}},temperature:T.temperature,topP:T.topP,topK:T.topK,providerOptions:wt.providerOptions(r.model,T.options??{}),activeTools:Object.keys(w).filter(E=>E!=="invalid"),tools:w,maxOutputTokens:b,abortSignal:r.abort,headers:{...r.model.providerId.startsWith("easbot")?{"x-easbot-project":R.project.id,"x-easbot-session":r.sessionId,"x-easbot-request":r.user.id,"x-easbot-client":a$2.EASBOT_CLIENT}:r.model.providerId!=="anthropic"?{"User-Agent":`easbot/${b$3.getVersion()}`}:void 0,...r.model.headers,...x},maxRetries:r.retries??0,system:v,messages:r.messages,model:wrapLanguageModel({model:c,middleware:[{specificationVersion:"v3",async transformParams(E){if(E.type==="stream"){let O=E.params.prompt;O&&Array.isArray(O)&&(E.params.prompt=wt.message(O,r.model,g));}return E.params}}]}),experimental_telemetry:{isEnabled:l.experimental?.openTelemetry,metadata:{userId:l.username??"unknown",sessionId:r.sessionId}}});return i.debug("streamText returned",{hasFullStream:!!C.fullStream,fullStreamType:typeof C.fullStream,resultKeys:Object.keys(C),baseStreamType:typeof C.baseStream,hasBaseStream:!!C.baseStream,textStreamType:typeof C.textStream,hasTextStream:!!C.textStream}),C}s.stream=n;function o(r){for(let i of r)if(Array.isArray(i.content)){for(let c of i.content)if(c.type==="tool-call"||c.type==="tool-result")return true}return false}s.hasToolCalls=o;})(Jo||(Jo={}));var Yo;(c=>{let e=a.create({service:"session.summary"});function t(l){if(!l.startsWith('"')||!l.endsWith('"'))return l;let d=l.slice(1,-1),m=[];for(let f=0;f<d.length;f++){let a=d[f];if(a!=="\\"){m.push(a.charCodeAt(0));continue}let p=d[f+1];if(!p){m.push(92);continue}if(p>="0"&&p<="7"){let g=d.slice(f+1,f+4).match(/^[0-7]{1,3}/);if(!g){m.push(p.charCodeAt(0)),f++;continue}m.push(parseInt(g[0],8)),f+=g[0].length;continue}let u=p==="n"?`
|
|
92
|
+
`:p==="r"?"\r":p==="t"?" ":p==="b"?"\b":p==="f"?"\f":p==="v"?"\v":p==="\\"||p==='"'?p:void 0;m.push((u??p).charCodeAt(0)),f++;}return Buffer.from(m).toString()}c.summarize=fn$1(N.object({sessionId:N.string(),messageId:N.string()}),async l=>{let d=await Y.messages({sessionId:l.sessionId});await Promise.all([o({sessionId:l.sessionId,messages:d}),s({messageId:l.messageId,messages:d})]);});async function o(l){let d=await i({messages:l.messages});await Y.update(l.sessionId,m=>{m.summary={additions:d.reduce((f,a)=>f+a.additions,0),deletions:d.reduce((f,a)=>f+a.deletions,0),files:d.length};}),await a$6.write(["session_diff",l.sessionId],d),await pe.publish(Y.Event.Diff,{sessionId:l.sessionId,diff:d});}async function s(l){let d=l.messages.filter(u=>u.info.id===l.messageId||u.info.role==="assistant"&&u.info.parentId===l.messageId),m=d.find(u=>u.info.id===l.messageId),f=m.info,a=await i({messages:d});f.summary={...f.summary,diffs:a},await Y.updateMessage(f);let p=m.parts.find(u=>u.type==="text"&&!u.synthetic);if(p&&!f.summary?.title){let u=await Ue.get("title");if(!u)return;let h=await Jo.stream({agent:u,user:f,tools:{},model:u.model?await xe.getModel(u.model.providerId,u.model.modelId):await xe.getSmallModel(f.model.providerId)??await xe.getModel(f.model.providerId,f.model.modelId),small:true,messages:[{role:"user",content:`
|
|
93
|
+
The following is the text to summarize:
|
|
94
|
+
<text>
|
|
95
|
+
${p?.text??""}
|
|
96
|
+
</text>
|
|
97
|
+
`}],abort:new AbortController().signal,sessionId:f.sessionId,system:[u.prompt??""],retries:3});e.debug("stream object received",{hasFullStream:!!h.fullStream,hasText:!!h.text,streamKeys:Object.keys(h)});let g=await h.text;e.debug("title",{title:g}),f.summary.title=g,await Y.updateMessage(f);}}c.diff=fn$1(N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message").optional()}),async l=>{let d=await a$6.read(["session_diff",l.sessionId]).catch(()=>[]),m=d.map(a=>{let p=t(a.file);return p===a.file?a:{...a,file:p}});return m.some((a,p)=>a.file!==d[p]?.file)&&a$6.write(["session_diff",l.sessionId],m).catch(()=>{}),m});async function i(l){let d,m;for(let f of l.messages){if(!d){for(let a of f.parts)if(a.type==="step-start"&&a.snapshot){d=a.snapshot;break}}for(let a of f.parts)a.type==="step-finish"&&a.snapshot&&(m=a.snapshot);}return d&&m?yt.diffFull(d,m):[]}c.computeDiff=i;})(Yo||(Yo={}));var io;(r=>{let e=a.create({service:"session.revert"});r.RevertInput=N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part").optional()});async function n(i){Je.assertNotBusy(i.sessionId);let c=await Y.messages({sessionId:i.sessionId}),l,d=await Y.get(i.sessionId),m,f=[];for(let a of c){a.info.role==="user"&&(l=a.info);let p=[];for(let u of a.parts){if(m){u.type==="patch"&&f.push(u);continue}if(!m){if(a.info.id===i.messageId&&!i.partId||u.id===i.partId){let h=p.some(g=>["text","tool"].includes(g.type))?i.partId:void 0;m={messageId:!h&&l?l.id:a.info.id,partId:h};}p.push(u);}}}if(m){let a=await Y.get(i.sessionId);m.snapshot=a.revert?.snapshot??await yt.track(),await yt.revert(f),m.snapshot&&(m.diff=await yt.diff(m.snapshot));let p=c.filter(h=>h.info.id>=m.messageId),u=await Yo.computeDiff({messages:p});return await a$6.write(["session_diff",i.sessionId],u),await pe.publish(Y.Event.Diff,{sessionId:i.sessionId,diff:u}),Y.update(i.sessionId,h=>{h.revert=m,h.summary={additions:u.reduce((g,I)=>g+I.additions,0),deletions:u.reduce((g,I)=>g+I.deletions,0),files:u.length};})}return d}r.revert=n;async function o(i){e.debug("unreverting",i),Je.assertNotBusy(i.sessionId);let c=await Y.get(i.sessionId);return c.revert?(c.revert.snapshot&&await yt.restore(c.revert.snapshot),await Y.update(i.sessionId,d=>{d.revert=void 0;})):c}r.unrevert=o;async function s(i){if(!i.revert)return;let c=i.id,l=await Y.messages({sessionId:c}),d=i.revert.messageId,[m,f]=splitWhen(l,p=>p.info.id===d);l=m;for(let p of f)await a$6.remove(["message",c,p.info.id]),await pe.publish(ve.Event.Removed,{sessionId:c,messageId:p.info.id});let a=m.at(-1);if(i.revert.partId&&a){let p=i.revert.partId,[u,h]=splitWhen(a.parts,g=>g.id===p);a.parts=u;for(let g of h)await a$6.remove(["part",a.info.id,g.id]),await pe.publish(ve.Event.PartRemoved,{sessionId:c,messageId:a.info.id,partId:g.id});}await Y.update(c,p=>{p.revert=void 0;});}r.cleanup=s;})(io||(io={}));async function Xo(e){for await(let t of ve.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return xe.defaultModel()}async function Cm(e){for await(let t of ve.stream(e))if(t.info.role==="user")return t.info}var yr;(c=>{c.RETRY_INITIAL_DELAY=2e3,c.RETRY_BACKOFF_FACTOR=2,c.RETRY_MAX_DELAY_NO_HEADERS=3e4,c.RETRY_MAX_DELAY=2147483647;async function s(l,d){return new Promise((m,f)=>{let a=()=>{clearTimeout(p),f(new DOMException("Aborted","AbortError"));},p=setTimeout(()=>{d.removeEventListener("abort",a),m();},Math.min(l,2147483647));d.addEventListener("abort",a,{once:true});})}c.sleep=s;function r(l,d){if(d){let m=d.data.responseHeaders;if(m){let f=m["retry-after-ms"];if(f){let p=Number.parseFloat(f);if(!Number.isNaN(p))return p}let a=m["retry-after"];if(a){let p=Number.parseFloat(a);if(!Number.isNaN(p))return Math.ceil(p*1e3);let u=Date.parse(a)-Date.now();if(!Number.isNaN(u)&&u>0)return Math.ceil(u)}return 2e3*2**(l-1)}}return Math.min(2e3*2**(l-1),3e4)}c.delay=r;function i(l){if(ve.ContextOverflowError.isInstance(l))return;let d=l;if(ve.APIError.isInstance(d)){let p=d;return p.data.isRetryable?p.data.responseBody?.includes("FreeUsageLimitError")?"Free usage exceeded, add credits https://easbot.cn/zen":p.data.message.includes("Overloaded")?"Provider is overloaded":p.data.message:void 0}let f=d?.data,a=iife(()=>{try{return typeof f?.message=="string"?JSON.parse(f.message):f?JSON.parse(String(f.message)):void 0}catch{return}});try{if(!a||typeof a!="object")return;let p=typeof a.code=="string"?a.code:"";return a.type==="error"&&a.error?.type==="too_many_requests"?"Too Many Requests":p.includes("exhausted")||p.includes("unavailable")?"Provider is overloaded":a.type==="error"&&a.error?.code?.includes("rate_limit")?"Rate Limited":JSON.stringify(a)}catch{return}}c.retryable=i;})(yr||(yr={}));var Mt;(l=>{l.Info=N.union([N.object({type:N.literal("idle")}),N.object({type:N.literal("retry"),attempt:N.number(),message:N.string(),next:N.number()}),N.object({type:N.literal("busy")})]).meta({ref:"SessionStatus"}),l.Event={Status:a$5.define("session.status",N.object({sessionId:N.string(),status:l.Info}))};let n;function o(){return n||(n=R.state(async()=>({}))),n}function s(){return o()()}async function r(d){return (await s())[d]??{type:"idle"}}l.get=r;async function i(){return s()}l.list=i;async function c(d,m){if(await pe.publish(l.Event.Status,{sessionId:d,status:m}),m.type==="idle"){let a=await s();delete a[d];return}let f=await s();f[d]=m;}l.set=c;})(Mt||(Mt={}));var Ot;(h=>{let e=a.create({service:"question"});h.Option=N.object({label:N.string().describe("Display text (1-5 words, concise)"),description:N.string().describe("Explanation of choice")}).meta({ref:"QuestionOption"}),h.Info=N.object({question:N.string().describe("Complete question"),header:N.string().describe("Very short label (max 30 chars)"),options:N.array(h.Option).describe("Available choices"),multiple:N.boolean().optional().describe("Allow selecting multiple choices"),custom:N.boolean().optional().describe("Allow typing a custom answer (default: true)")}).meta({ref:"QuestionInfo"}),h.Request=N.object({id:Identifier.schema("question"),sessionId:Identifier.schema("session"),questions:N.array(h.Info).describe("Questions to ask"),tool:N.object({messageId:N.string(),callId:N.string()}).optional()}).meta({ref:"QuestionRequest"}),h.Answer=N.array(N.string()).meta({ref:"QuestionAnswer"}),h.Reply=N.object({answers:N.array(h.Answer).describe("User answers in order of questions (each answer is an array of selected labels)")}),h.Event={Asked:a$5.define("question.asked",h.Request),Replied:a$5.define("question.replied",N.object({sessionId:N.string(),requestId:N.string(),answers:N.array(h.Answer)})),Rejected:a$5.define("question.rejected",N.object({sessionId:N.string(),requestId:N.string()}))};let c;function l(){return c||(c=R.state(async()=>({pending:{}}))),c}function d(){return l()()}async function m(g){let I=await d(),T=Identifier.ascending("question");return e.debug("asking",{id:T,questions:g.questions.length}),new Promise((y,x)=>{let b={id:T,sessionId:g.sessionId,questions:g.questions,tool:g.tool};I.pending[T]={info:b,resolve:y,reject:x},pe.publish(h.Event.Asked,b);})}h.ask=m;async function f(g){let I=await d(),T=I.pending[g.requestId];if(!T){e.warn("reply for unknown request",{requestId:g.requestId});return}delete I.pending[g.requestId],e.info("replied",{requestId:g.requestId,answers:g.answers}),await pe.publish(h.Event.Replied,{sessionId:T.info.sessionId,requestId:T.info.id,answers:g.answers}),T.resolve(g.answers);}h.reply=f;async function a$1(g){let I=await d(),T=I.pending[g];if(!T){e.warn("reject for unknown request",{requestId:g});return}delete I.pending[g],e.debug("rejected",{requestId:g}),await pe.publish(h.Event.Rejected,{sessionId:T.info.sessionId,requestId:T.info.id}),T.reject(new p);}h.reject=a$1;class p extends Error{constructor(){super("The user dismissed this question");}}h.RejectedError=p;async function u(){return d().then(g=>Object.values(g.pending).map(I=>I.info))}h.list=u;})(Ot||(Ot={}));var wr;(o=>{let t=a.create({service:"session.processor"});function n(s){let r={},i=false,c=0,l=false;s.mode??"general";return {get message(){return s.assistantMessage},partFromToolCall(f){return r[f]},async process(f){l=false;let a=(await he.get()).experimental?.continue_loop_on_deny!==true;for(;;){try{let u,h={},g=await Jo.stream(f);for await(let I of g.fullStream){switch(s.abort.throwIfAborted(),I.type){case "start":await Mt.set(s.sessionId,{type:"busy"});break;case "reasoning-start":if(I.id in h)continue;h[I.id]={id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"reasoning",text:"",time:{start:Date.now()},metadata:I.providerMetadata},await Y.updatePart(h[I.id]);break;case "reasoning-delta":if(I.id in h){let T=h[I.id];if(!T){t.warn("reasoning-delta: part not found in map",{id:I.id});break}let y=I.delta||I.text||"";T.text+=y,I.providerMetadata&&(T.metadata=I.providerMetadata),T.text&&await Y.updatePart({part:T,delta:y});}break;case "reasoning-end":if(I.id in h){let T=h[I.id];if(!T){t.warn("reasoning-end: part not found in map",{id:I.id});break}T.text=T.text.trimEnd(),T.time={...T.time,end:Date.now()},I.providerMetadata&&(T.metadata=I.providerMetadata),await Y.updatePart(T),delete h[I.id];}break;case "tool-input-start":{let T=await Y.updatePart({id:r[I.id]?.id??Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"tool",tool:I.toolName,callId:I.id,state:{status:"pending",input:{},raw:""}});r[I.id]=T;break}case "tool-input-delta":break;case "tool-input-end":break;case "tool-call":{let T=r[I.toolCallId];if(T){let y=await Y.updatePart({...T,tool:I.toolName,state:{status:"running",input:I.input,time:{start:Date.now()}},metadata:I.providerMetadata});r[I.toolCallId]=y;let b=(await ve.parts(s.assistantMessage.id)).slice(-3);if(b.length===3&&b.every(w=>w.type==="tool"&&w.tool===I.toolName&&w.state.status!=="pending"&&JSON.stringify(w.state.input)===JSON.stringify(I.input))){let w=await Ue.get(s.assistantMessage.agent);if(!w)break;await Me.ask({permission:"doom_loop",patterns:[I.toolName],sessionId:s.assistantMessage.sessionId,metadata:{tool:I.toolName,input:I.input},always:[I.toolName],ruleset:w.permission});}}break}case "tool-result":{let T=r[I.toolCallId];if(T&&T.state.status==="running"){let y;I.output.attachments&&I.output.attachments.length>0&&(y=I.output.attachments.map(x=>({...x,id:x.id??Identifier.ascending("part"),sessionId:x.sessionId??T.sessionId,messageId:x.messageId??T.messageId}))),await Y.updatePart({...T,state:{status:"completed",input:I.input??T.state.input,output:I.output.output,metadata:I.output.metadata,title:I.output.title,time:{start:T.state.time.start,end:Date.now()},attachments:y}}),delete r[I.toolCallId];}break}case "tool-error":{let T=r[I.toolCallId];T&&T.state.status==="running"&&(await Y.updatePart({...T,state:{status:"error",input:I.input??T.state.input,error:I.error instanceof Error?I.error.message:String(I.error),time:{start:T.state.time.start,end:Date.now()}}}),(I.error instanceof Me.RejectedError||I.error instanceof Ot.RejectedError)&&(i=a),delete r[I.toolCallId]);break}case "error":throw I.error;case "start-step":await Le.triggerEvent(HookEvent.StepStart,{sessionId:s.sessionId,userMessageId:s.assistantMessage.parentId,messageId:s.assistantMessage.id,model:s.model},{sessionId:s.sessionId,model:s.model?.id}),await Y.updatePart({id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.sessionId,type:"step-start"});break;case "finish-step":{let T=Y.getUsage({model:s.model,usage:I.usage,metadata:I.providerMetadata});s.assistantMessage.finish=I.finishReason,s.assistantMessage.cost+=T.cost,s.assistantMessage.tokens=T.tokens,await Y.updatePart({id:Identifier.ascending("part"),reason:I.finishReason,messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"step-finish",tokens:T.tokens,cost:T.cost}),await Y.updateMessage(s.assistantMessage),await Le.triggerEvent(HookEvent.StepFinish,{sessionId:s.sessionId,userMessageId:s.assistantMessage.parentId,messageId:s.assistantMessage.id,model:s.model,finishReason:I.finishReason},{sessionId:s.sessionId,model:s.model?.id}),!s.assistantMessage.summary&&await on.isOverflow({tokens:T.tokens,model:s.model})&&(l=!0);break}case "text-start":u={id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"text",text:"",time:{start:Date.now()},metadata:I.providerMetadata},await Y.updatePart(u);break;case "text-delta":if(u){let T=I.delta||I.text||"";u.text+=T,I.providerMetadata&&(u.metadata=I.providerMetadata),u.text&&await Y.updatePart({part:u,delta:T});}else t.warn("text-delta: no currentText available");break;case "text-end":u?.time?(u.text=u.text.trimEnd(),await Le.triggerEvent(HookEvent.TextComplete,{sessionId:s.sessionId,messageId:s.assistantMessage.id,partId:u.id},{sessionId:s.sessionId}),u.time={start:u.time.start??Date.now(),end:Date.now()},I.providerMetadata&&(u.metadata=I.providerMetadata),await Y.updatePart(u)):t.warn("text-end: no currentText available or time not set"),u=void 0;break;case "finish":break;default:t.debug("unhandled",{...I});continue}if(l)break}}catch(u){let h=u?.message??String(u);t.error("process",{error:h});let g=ve.fromError(u,{providerId:s.model.providerId,aborted:s.abort.aborted});if(ve.ContextOverflowError.isInstance(g))l=true,pe.publish(Y.Event.Error,{sessionId:s.sessionId,error:g});else {let I=yr.retryable(g);if(I!==void 0){c++;let T=yr.delay(c,ve.APIError.isInstance(g)?g:void 0);await Mt.set(s.sessionId,{type:"retry",attempt:c,message:I,next:Date.now()+T}),await yr.sleep(T,s.abort).catch(()=>{});continue}s.assistantMessage.error=g,await pe.publish(Y.Event.Error,{sessionId:s.assistantMessage.sessionId,error:s.assistantMessage.error}),await Mt.set(s.sessionId,{type:"idle"});}}let p=await ve.parts(s.assistantMessage.id);for(let u of p)u.type==="tool"&&u.state.status!=="completed"&&u.state.status!=="error"&&await Y.updatePart({...u,state:{...u.state,status:"error",error:"Tool execution aborted",time:{start:Date.now(),end:Date.now()}}});return s.assistantMessage.time.completed=Date.now(),await Y.updateMessage(s.assistantMessage),l?"compact":i||s.assistantMessage.error?"stop":"continue"}}}}o.create=n;})(wr||(wr={}));var km=`Provide a detailed summary of the conversation above that will help continue the work.
|
|
98
|
+
|
|
99
|
+
Focus on information that would be helpful for continuing the conversation, including what was accomplished, what is being worked on, and what comes next.`;function Ox(e){return `<compaction_summary>
|
|
100
|
+
${e}
|
|
101
|
+
</compaction_summary>`}function Pm(e,t){let n=[Ox(e)];return n.push("Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."),t?.customInstructions&&n.push(t.customInstructions),n.join(`
|
|
102
|
+
|
|
103
|
+
`)}var ao=a.create({service:"compaction.cache"}),Em=100,Rm=25*1024*1024,_m=300*1e3,Tm="cache.json",Fx={maxEntries:Em,maxSizeBytes:Rm,ttlMs:_m,persist:false};function Cl(e){return join(a$1.Path.cache,"compaction",e)}var dc=class{constructor(t){b$1(this,"cache");b$1(this,"config");b$1(this,"hits",0);b$1(this,"misses",0);this.config={maxEntries:t?.maxEntries??Em,maxSizeBytes:t?.maxSizeBytes??Rm,ttlMs:t?.ttlMs??_m,persist:t?.persist??false,sessionId:t?.sessionId},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:n=>{let o=n.value,s=typeof o=="string"?o:o==null?"":typeof o=="object"?JSON.stringify(o):String(o);return Math.max(1,Buffer.byteLength(s,"utf8"))},ttl:this.config.ttlMs,updateAgeOnGet:true,updateAgeOnHas:true}),ao.debug("compaction cache initialized",{maxEntries:this.config.maxEntries,maxSizeBytes:this.config.maxSizeBytes,ttlMs:this.config.ttlMs});}get(t){let n=this.cache.get(t);if(n!==void 0)return this.hits++,n.value;this.misses++;}set(t,n){let o={value:n,timestamp:Date.now()};return this.cache.set(t,o),this}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear(),this.hits=0,this.misses=0,ao.debug("cache cleared");}getStats(){let t=this.hits+this.misses;return {size:this.cache.size,calculatedSize:this.cache.calculatedSize??0,maxEntries:this.config.maxEntries,maxSizeBytes:this.config.maxSizeBytes,hits:this.hits,misses:this.misses,hitRate:t>0?this.hits/t:0}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}async persistToFile(){if(!this.config.persist||!this.config.sessionId){ao.debug("persist skipped: persistence disabled or no sessionId");return}let t=Cl(this.config.sessionId),n=join(t,Tm),o={entries:this.entries(),stats:this.getStats(),timestamp:Date.now()};try{await mkdir(t,{recursive:!0}),await writeFile(n,JSON.stringify(o),"utf-8"),ao.debug("cache persisted",{path:n,entries:o.entries.length});}catch(s){throw ao.error("cache persist failed",{error:String(s)}),s}}async restoreFromFile(){if(!this.config.persist||!this.config.sessionId){ao.debug("restore skipped: persistence disabled or no sessionId");return}let t=Cl(this.config.sessionId),n=join(t,Tm);try{let o=await readFile(n,"utf-8"),s=JSON.parse(o);if(s.entries&&Array.isArray(s.entries))for(let[r,i]of s.entries)Date.now()-i.timestamp<this.config.ttlMs&&this.cache.set(r,i);ao.debug("cache restored",{path:n,entries:this.cache.size});}catch(o){ao.warn("cache restore failed, starting fresh",{error:String(o)});}}dump(){return {entries:this.entries(),stats:this.getStats()}}load(t){for(let[n,o]of t.entries)Date.now()-o.timestamp<this.config.ttlMs&&this.cache.set(n,o);ao.debug("cache loaded",{entries:this.cache.size});}};function Nx(e){return new dc(e)}async function Ux(e){let t=Cl(e);try{await rm$1(t,{recursive:!0,force:!0}),ao.info("session cache cleared",{sessionId:e,path:t});}catch(n){ao.warn("failed to clear session cache",{sessionId:e,error:String(n)});}}function zx(){pe.subscribe(Y.Event.Deleted,async e=>{await Ux(e.properties.info.id);});}var kl=class{constructor(t){b$1(this,"cache");b$1(this,"config");let n={ttlMs:3e5,maxSizeBytes:26214400,maxEntries:100,persist:false};this.config={...n,...t},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:o=>Buffer.byteLength(o.originalOutput,"utf8")+Buffer.byteLength(JSON.stringify(o.metadata),"utf8"),ttl:this.config.ttlMs,updateAgeOnGet:true});}getKey(t,n){return `${t}:${n}`}async backup(t){let n=this.getKey(t.sessionId,t.partId);this.cache.set(n,t);}get(t,n){let o=this.getKey(t,n);return this.cache.get(o)}has(t,n){let o=this.getKey(t,n);return this.cache.has(o)}delete(t,n){let o=this.getKey(t,n);return this.cache.delete(o)}clearSession(t){let n=`${t}:`;for(let o of this.cache.keys())o.startsWith(n)&&this.cache.delete(o);}clear(){this.cache.clear();}size(){return this.cache.size}getStats(){return {size:this.cache.size,calculatedSize:this.cache.calculatedSize??0}}},vl;function Qo(){return vl||(vl=new kl),vl}var Ei={async backup(e){await Qo().backup(e);},get(e,t){return Qo().get(e,t)},has(e,t){return Qo().has(e,t)},delete(e,t){return Qo().delete(e,t)},clearSession(e){Qo().clearSession(e);},clear(){Qo().clear();},size(){return Qo().size()},getStats(){return Qo().getStats()}};var Et=a.create({service:"compaction"}),on;(M=>{M.COMPACTION_BUFFER=2e4,M.AUTOCOMPACT_BUFFER_TOKENS=13e3,M.WARNING_THRESHOLD_BUFFER_TOKENS=2e4,M.MANUAL_COMPACT_BUFFER_TOKENS=3e3,M.PRUNE_MINIMUM=2e4,M.PRUNE_PROTECT=4e4,M.MAX_COMPACTION_FAILURES=3,M.PRUNE_PROTECTED_TOOLS=["skill"],M.BLOCKING_LIMIT_THRESHOLD=1e3,M.COMPACTION_WINDOW_MS=6e4,M.COMPACTION_WINDOW_THRESHOLD=3;let f;function a(){return f||(f=R.state(async()=>({config:await gi(),consecutiveFailures:new Map,compactionAttempts:new Map,initialized:true}))),f}async function p(){return a()()}async function u(){return (await p()).config}M.getConfig=u;async function h(A){let L=await p(),S=Date.now(),P=L.compactionAttempts.get(A);if(P){let _=S-P.firstAttemptTime;if(_<6e4){if(P.count>=3)return Et.warn("compaction skipped: time window circuit breaker open",{sessionId:A,attempts:P.count,elapsed:_,windowMs:6e4,threshold:3}),await pe.publish(M.Event.CircuitBreakerOpened,{sessionId:A,consecutiveFailures:P.count,maxFailures:3}),true;P.count++;}else P.count=1,P.firstAttemptTime=S;}else L.compactionAttempts.set(A,{count:1,firstAttemptTime:S});return false}async function g(A){(await p()).compactionAttempts.delete(A);}M.resetTimeWindowAttempts=g;async function I(A){return (await p()).consecutiveFailures.get(A)??0}async function T(A){let L=await p(),P=(L.consecutiveFailures.get(A)??0)+1;return L.consecutiveFailures.set(A,P),P}async function y(A){(await p()).consecutiveFailures.set(A,0);}M.resetSessionFailures=y;function x(A){if(a$2.EASBOT_AUTO_COMPACT_WINDOW)return a$2.EASBOT_AUTO_COMPACT_WINDOW;let L=wt.maxOutputTokens(A),S=Math.min(L,2e4),P=A.limit.context??0,j=(P>0?P:xe.DEFAULT_CONTEXT_LIMIT)-S;return Math.max(j,5e4)}M.getEffectiveContextWindowSize=x;function b(A,L){let S=x(L),P=Math.max(0,(S-A)/S*100),_=S-2e4,j=S-13e3;a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE&&(j=S*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100));let B=S-1e3;return a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE&&(B=a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE),{percentLeft:P,isAboveWarningThreshold:A>=_,isAboveAutoCompactThreshold:A>=j,isAtBlockingLimit:A>=B}}M.calculateTokenUsageState=b;async function w(A){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return false;let L=await u();if(L.auto===false)return false;let S=A.model.limit.context??0,P=S>0?S:xe.DEFAULT_CONTEXT_LIMIT;if(P===0)return false;let _=wt.maxOutputTokens(A.model),j=L.reserved??Math.min(2e4,_),B=A.model.limit.input?A.model.limit.input-j:P-j,Z=Math.max(B,5e4);if(a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE)return A.tokens?Token.total(A.tokens)>=Z*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100):false;if(A.tokens)return Token.total(A.tokens)>=Z;if(!A.sessionId)return false;let ee=await Y.messages({sessionId:A.sessionId});for(let se=ee.length-1;se>=0;se--){let le=ee[se];if(le&&le.info.role==="assistant"&&!le.info.summary)return Token.total(le.info.tokens)>=B}return false}M.isOverflow=w;async function k(A){let L=await u(),S=L.prune;if(S?.enabled===false)return Et.debug("prune skipped: config.compaction.prune.enabled is false"),{prunedCount:0,prunedTokens:0,success:true};let P=S?.timeThresholdMs??3e5,_=S?.keepRecentTools??3,j=S?.tokenThreshold??5e3,B=S?.protectedTools??M.PRUNE_PROTECTED_TOOLS,Z=L?.backup?.enabled!==false,ee=await Y.messages({sessionId:A.sessionId}),se=Date.now(),le=0,ae=0,we=0,re=[],Q=[],H=0;e:for(let te=ee.length-1;te>=0;te--){let V=ee[te];if(V&&(V.info.role==="user"&&H++,!(H<2))){if(V.info.role==="assistant"&&V.info.summary)break;for(let J=V.parts.length-1;J>=0;J--){let oe=V.parts[J];if(oe&&oe.type==="tool"&&oe.state.status==="completed"){if(B.includes(oe.tool))continue;if(oe.state.time.compacted)break e;let me=se-(oe.state.time.end??0)>P;if(Q.length<_){Q.push(oe.id);continue}if(!me)continue;let ce=Token.estimate(oe.state.output??"");le+=ce,le>4e4&&(ae+=ce,re.push(oe));}}}}Et.debug("pruning analysis",{prunedTokens:ae,toPruneCount:re.length});let F=ae>j;if(F&&re.length>0){let te=A.reason??"prune";for(let V of re)V.type==="tool"&&V.state.status==="completed"&&(Z&&V.state.output&&(await Ei.backup({sessionId:A.sessionId,messageId:V.messageId,partId:V.id,tool:V.tool,originalOutput:V.state.output,metadata:{input:V.state.input??{},title:V.state.title,attachments:V.state.attachments},compactedAt:se,reason:te}),we++),V.state.time.compacted=se,await Y.updatePart(V));Et.debug("pruning completed",{count:re.length,tokens:ae,backups:we});}else Et.debug("pruning skipped: insufficient benefit",{prunedTokens:ae,minimum:j});return {prunedCount:re.length,prunedTokens:ae,success:F,backups:we}}M.prune=k;async function v(A){let L=await Y.messages({sessionId:A.sessionId}),S=0,P=0;for(let _ of L)if(!(A.messageId&&_.info.id!==A.messageId))for(let j of _.parts){if(A.partId&&j.id!==A.partId||j.type!=="tool"||j.state.status!=="completed"||!j.state.time.compacted)continue;let B=Ei.get(A.sessionId,j.id);if(!B){Et.warn("restore skipped: no backup found",{partId:j.id});continue}j.state.output=B.originalOutput,j.state.time.compacted=void 0,await Y.updatePart(j),S++,P+=Token.estimate(B.originalOutput),Et.debug("restore completed",{partId:j.id,tokens:Token.estimate(B.originalOutput)});}return Et.debug("restore completed",{restoredCount:S,restoredTokens:P}),{restoredCount:S,restoredTokens:P,success:true}}M.restore=v;function C(){return Ei}M.getBackupCache=C;function E(A){Ei.clearSession(A);}M.clearBackups=E;async function O(A){let L=await I(A.sessionId);if(L>=3)return Et.warn("compaction skipped: circuit breaker open (failures)",{sessionId:A.sessionId,consecutiveFailures:L,maxFailures:3}),await pe.publish(M.Event.CircuitBreakerOpened,{sessionId:A.sessionId,consecutiveFailures:L,maxFailures:3}),await Je.cancel(A.sessionId),"stop";if(await h(A.sessionId))return await Je.cancel(A.sessionId),"stop";let S=A.messages.findLast(le=>le.info.id===A.parentId).info,P=await Ue.get("compaction");if(!P)return Et.error("compaction agent not found"),"stop";let _=P.model?await xe.getModel(P.model.providerId,P.model.modelId):await xe.getModel(S.model.providerId,S.model.modelId),j=await Y.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:A.parentId,sessionId:A.sessionId,mode:"compaction",agent:"compaction",variant:S.variant,summary:true,path:{cwd:R.directory,root:R.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelId:_.id,providerId:_.providerId,time:{created:Date.now()}}),B=wr.create({assistantMessage:j,sessionId:A.sessionId,model:_,abort:A.abort}),Z=[],ee;try{let le=await Le.triggerEvent(HookEvent.SessionCompacting,{sessionId:A.sessionId,auto:A.auto});if(le.success&&le.output){let ae=le.output;ae.context&&Z.push(...ae.context),ae.prompt&&(ee=ae.prompt);}}catch(le){Et.warn("session.compacting hook error, using default",{error:String(le)});}let se=ee??[km,...Z].join(`
|
|
104
|
+
|
|
105
|
+
`);try{if(await B.process({user:S,agent:P,abort:A.abort,sessionId:A.sessionId,tools:{},system:P.prompt?[P.prompt]:[],messages:[...await ve.toModelMessages(A.messages.filter(ae=>!ae.parts.some(we=>we.type==="compaction")),_),{role:"user",content:[{type:"text",text:se}]}],model:_})==="continue"&&A.auto){let we=(await ve.parts(j.id)).find(H=>H.type==="text")?.text??"",re=Pm(we,{continuePrompt:!0}),Q=await Y.updateMessage({id:Identifier.ascending("message"),role:"user",sessionId:A.sessionId,time:{created:Date.now()},agent:S.agent,model:S.model});await Y.updatePart({id:Identifier.ascending("part"),messageId:Q.id,sessionId:A.sessionId,type:"text",synthetic:!0,text:re,time:{start:Date.now(),end:Date.now()}});}return B.message.error?(Et.error("compaction failed: processor error",{error:B.message.error}),await T(A.sessionId),"stop"):(await pe.publish(M.Event.Compacted,{sessionId:A.sessionId}),Et.debug("compaction completed successfully",{sessionId:A.sessionId}),await y(A.sessionId),"continue")}catch(le){let ae=await T(A.sessionId);throw Et.error("compaction failed",{sessionId:A.sessionId,error:String(le),consecutiveFailures:ae,maxFailures:3}),le}}M.compactConversation=O;async function U(A){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return Et.debug("auto compact skipped: disabled by flag"),"not_needed";if((await u()).auto===false)return Et.debug("auto compact skipped: config.compaction.auto is false"),"not_needed";if(!await w({sessionId:A.sessionId,model:A.model,tokens:A.tokens}))return Et.debug("no overflow detected, skipping auto compact"),"not_needed";Et.debug("auto compact triggered",{sessionId:A.sessionId});let P=await ve.filterCompacted(ve.stream(A.sessionId));if(P.length===0)return Et.debug("auto compact skipped: no uncompacted messages",{sessionId:A.sessionId}),"not_needed";let _=P.findLast(ee=>ee?.info.role==="user"&&!ee.parts.some(se=>se.type==="compaction"));if(!_)return Et.error("no user message found for compaction"),"not_needed";let j=new AbortController,B=A.sessionId?Object.assign(j.signal,{sessionId:A.sessionId}):j.signal,Z=await O({sessionId:A.sessionId,parentId:_.info.id,messages:P,abort:B,auto:true});return await M.prune({sessionId:A.sessionId}),Z==="continue"?(Et.debug("auto compact succeeded",{sessionId:A.sessionId}),"compacted"):"not_needed"}M.autoCompactIfNeeded=U;async function D(A){await y(A),Et.debug("circuit breaker reset",{sessionId:A});}M.resetCircuitBreaker=D;async function K(A){return I(A)}M.getConsecutiveFailures=K,M.Event={Compacted:a$5.define("session.compacted",N.object({sessionId:N.string()})),CircuitBreakerOpened:a$5.define("session.compaction.circuit_breaker_opened",N.object({sessionId:N.string(),consecutiveFailures:N.number(),maxFailures:N.number()}))},M.create=fn$1(N.object({sessionId:Identifier.schema("session"),agent:N.string().optional(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),auto:N.boolean()}),async A=>{let{sessionId:L,model:S,agent:P="compaction",auto:_=false}=A,j;S?.providerId&&S.modelId?j={providerId:S.providerId,modelId:S.modelId}:j=(await Ue.get(P))?.model??await Xo(L);let B=await Y.updateMessage({id:Identifier.ascending("message"),role:"user",model:j,sessionId:L,agent:P,time:{created:Date.now()}});await Y.updatePart({id:Identifier.ascending("part"),messageId:B.id,sessionId:B.sessionId,type:"compaction",auto:_}),Et.debug("compaction task created",{sessionId:L,auto:_});});})(on||(on={}));var Gx=a.create({service:"instruction"}),Mm=["AGENTS.md"];function Wx(){let e=[];return a$2.EASBOT_CONFIG_DIR&&e.push(Se__default.join(a$2.EASBOT_CONFIG_DIR,"AGENTS.md")),e.push(Se__default.join(a$1.Path.config,"AGENTS.md")),e}async function Vx(e){return a$2.EASBOT_DISABLE_PROJECT_CONFIG?a$2.EASBOT_CONFIG_DIR?Filesystem.globUp(e,a$2.EASBOT_CONFIG_DIR,a$2.EASBOT_CONFIG_DIR).catch(()=>[]):(Gx.warn(`Skipping relative instruction "${e}" - no EASBOT_CONFIG_DIR set while project config is disabled`),[]):Filesystem.globUp(e,R.directory,R.worktree).catch(()=>[])}var vs;(f=>{let e;function t(){return e||(e=R.state(async()=>({claims:new Map}))),e}function n(){return t()()}async function o(a,p){let h=(await n()).claims.get(a);return h?h.has(p):false}async function s(a,p){let u=await n(),h=u.claims.get(a);h||(h=new Set,u.claims.set(a,h)),h.add(p);}async function r(a){(await n()).claims.delete(a);}f.clear=r;async function i(){let a=await he.get(),p=new Set;if(!a$2.EASBOT_DISABLE_PROJECT_CONFIG)for(let u of Mm){let h=await Filesystem.findUp(u,R.directory,R.worktree);if(h.length>0){h.forEach(g=>{p.add(Se__default.resolve(g));});break}}for(let u of Wx())try{await Tt__default.access(u),p.add(Se__default.resolve(u));break}catch{}if(a.instructions)for(let u of a.instructions){if(u.startsWith("https://")||u.startsWith("http://"))continue;u.startsWith("~/")&&(u=Se__default.join(ec.homedir(),u.slice(2))),(Se__default.isAbsolute(u)?await glob(Se__default.basename(u),{cwd:Se__default.dirname(u),absolute:true,nodir:true,follow:false,dot:false}):await Vx(u)).forEach(g=>{p.add(Se__default.resolve(g));});}return p}f.systemPaths=i;async function c(){let a=await he.get(),p=await i(),u=Array.from(p).map(async I=>{let T=await Tt__default.readFile(I,"utf-8").catch(()=>"");return {path:I,content:T}}),h=[];if(a.instructions)for(let I of a.instructions)(I.startsWith("https://")||I.startsWith("http://"))&&h.push(I);let g=h.map(I=>fetch(I,{signal:AbortSignal.timeout(5e3)}).then(T=>T.ok?T.text():"").catch(()=>"").then(T=>T?"Instructions from: "+I+`
|
|
106
|
+
`+T:""));return Promise.all([...u,...g]).then(I=>I.filter(Boolean))}f.system=c;function l(a){let p=new Set;for(let u of a)for(let h of u.parts)if(h.type==="tool"&&h.tool==="read"&&h.state.status==="completed"){if(h.state.time.compacted)continue;let g=h.state.metadata?.loaded;if(!g||!Array.isArray(g))continue;for(let I of g)typeof I=="string"&&p.add(I);}return p}f.loaded=l;async function d(a){for(let p of Mm){let u=Se__default.resolve(Se__default.join(a,p));try{return await Tt__default.access(u),u}catch{}}}f.find=d;async function m(a,p,u){let h=await i(),g=l(a),I=[],T=Se__default.resolve(p),y=Se__default.dirname(T),x=Se__default.resolve(R.directory);for(;y.startsWith(x)&&y!==x;){let b=await d(y);if(b&&b!==T&&!h.has(b)&&!g.has(b)&&!o(u,b)){await s(u,b);let w=await Tt__default.readFile(b,"utf-8").catch(()=>{});w&&I.push({filepath:b,content:"Instructions from: "+b+`
|
|
107
|
+
`+w});}y=Se__default.dirname(y);}return I}f.resolve=m;})(vs||(vs={}));var De;(t=>{function e(n,o){return {id:n,isEnabled:typeof o=="function"?void 0:o.isEnabled,scope:typeof o=="function"?void 0:o.scope,init:async s=>{let r=typeof o=="function"?await o(s):o,i=r.execute;return r.execute=async(c,l)=>{try{r.parameters.parse(c);}catch(f){throw f instanceof N.ZodError&&r.formatValidationError?new Error(r.formatValidationError(f),{cause:f}):new Error(`The ${n} tool was called with invalid arguments: ${f instanceof Error?f.message:String(f)}.
|
|
108
|
+
Please rewrite the input so it satisfies the expected schema.`,{cause:f})}let d=await i(c,l);if(d.metadata?.truncated===true)return d;let m=await Ve.output(d.output,{},s?.agent);return {...d,output:m.content,metadata:{...d.metadata||{},truncated:m.truncated,...m.truncated&&{outputPath:m.outputPath}}}},{description:r.description,parameters:r.parameters,execute:r.execute,formatValidationError:r.formatValidationError}}}}t.define=e;})(De||(De={}));var An;(l=>{let e=a.create({service:"file.time"}),t;function n(){return t||(t=R.state(()=>({read:{},locks:new Map}))),t}function o(){return n()()}l.state=o;function s(d,m){e.debug("read",{sessionId:d,file:m});let{read:f}=o();f[d]=f[d]||{},f[d][m]=new Date;}l.read=s;function r(d,m){return o().read[d]?.[m]}l.get=r;async function i(d,m){let f=o(),a=f.locks.get(d)??Promise.resolve(),p=()=>{},u=new Promise(g=>{p=g;}),h=a.then(()=>u);f.locks.set(d,h),await a;try{return await m()}finally{p(),f.locks.get(d)===h&&f.locks.delete(d);}}l.withLock=i;async function c(d,m){if(a$2.EASBOT_DISABLE_FILETIME_CHECK===true)return;let f=r(d,m);if(!f)throw new Error(`You must read file ${m} before overwriting it. Use the Read tool first`);let a=await PKG.file(m).stat();if(a.mtime.getTime()>f.getTime())throw new Error(`File ${m} has been modified since it was last read.
|
|
109
|
+
Last modification: ${a.mtime.toISOString()}
|
|
110
|
+
Last read: ${f.toISOString()}
|
|
111
|
+
|
|
112
|
+
Please read the file again before modifying it.`)}l.assert=c;})(An||(An={}));async function Jt(e,t,n){if(!t||n?.bypass)return;let o=Filesystem.normalize(Se__default.isAbsolute(t)?t:Se__default.resolve(R.directory,t)),s=await Yx(o),r=s??o;if(R.containsPath(r))return;let c=(n?.kind??"file")==="directory"?o:Se__default.posix.dirname(o),l=Se__default.posix.join(c,"*");await e.ask({permission:"external_directory",patterns:[l],always:[l],metadata:{filepath:o,realPath:s??void 0,parentDir:c,tool:n?.tool??"read"}});}async function Yx(e){try{let t=await Tt.realpath(e);return Filesystem.normalize(t)}catch{return}}var eI=loadTextFile("./read.txt",import.meta.url),tI=eI(),Lm=2e3,Tl=2e3,nI=`... (line truncated to ${Tl} chars)`,Dm=50*1024,oI=`${Dm/1024} KB`,mc=De.define("read",{description:tI,parameters:N.object({filePath:N.string().describe("The absolute path to the file or directory to read"),offset:N.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),limit:N.coerce.number().describe("The maximum number of lines to read (defaults to 2000)").optional()}),async execute(e,t){if(e.offset!==void 0&&e.offset<1)throw new Error("offset must be greater than or equal to 1");let n=Filesystem.normalize(Se.isAbsolute(e.filePath)?e.filePath:Se.resolve(R.directory,e.filePath)),o=Se.posix.relative(R.worktree,n),s=Filesystem.stat(n);if(await Jt(t,n,{bypass:!!t.extra?.bypassCwdCheck,kind:s?.isDirectory()?"directory":"file",tool:"read"}),await t.ask({permission:"read",patterns:[Se.posix.relative(R.worktree,n)],always:["*"],metadata:{}}),!s){let O=Filesystem.dirname(n),U=Filesystem.basename(n),D=await Tt.readdir(O).then(K=>K.filter(X=>X.toLowerCase().includes(U.toLowerCase())||U.toLowerCase().includes(X.toLowerCase())).map(X=>Filesystem.join(O,X)).slice(0,3)).catch(()=>[]);throw D.length>0?new Error(`File not found: ${n}
|
|
113
|
+
|
|
114
|
+
Did you mean one of these?
|
|
115
|
+
${D.join(`
|
|
116
|
+
`)}`):new Error(`File not found: ${n}`)}if(s.isDirectory()){let O=await Tt.readdir(n,{withFileTypes:true}),U=await Promise.all(O.map(async L=>L.isDirectory()||L.isSymbolicLink()&&(await Tt.stat(Filesystem.join(n,L.name)).catch(()=>{}))?.isDirectory()?L.name+"/":L.name));U.sort((L,S)=>L.localeCompare(S));let D=e.limit??Lm,K=e.offset??1,X=K-1,$=U.slice(X,X+D),M=X+$.length<U.length,A=[`<path>${n}</path>`,"<type>directory</type>","<entries>",$.join(`
|
|
117
|
+
`),M?`
|
|
118
|
+
(Showing ${$.length} of ${U.length} entries. Use 'offset' parameter to read beyond entry ${K+$.length})`:`
|
|
119
|
+
(${U.length} entries)`,"</entries>"].join(`
|
|
120
|
+
`);return {title:o,output:A,metadata:{preview:$.slice(0,20).join(`
|
|
121
|
+
`),truncated:M,loaded:[]}}}let r=await vs.resolve(t.messages,n,t.messageId),i=Filesystem.mimeType(n),c=i?.startsWith("image/")&&i!=="image/svg+xml"&&i!=="image/vnd.fastbidsheet";if(c||i==="application/pdf"){let O=`${c?"Image":"PDF"} read successfully`;return {title:o,output:O,metadata:{preview:O,truncated:false,loaded:r.map(U=>U.filepath)},attachments:[{type:"file",mime:i??"application/octet-stream",url:`data:${i??"application/octet-stream"};base64,${Buffer.from(await Filesystem.readBytes(n)).toString("base64")}`}]}}if(await sI(n,Number(s.size)))throw new Error(`Cannot read binary file: ${n}`);let m=createReadStream(n,{encoding:"utf8"}),f=createInterface({input:m,crlfDelay:1/0}),a=e.limit??Lm,p=e.offset??1,u=p-1,h=[],g=0,I=0,T=false,y=false;try{for await(let O of f){if(I+=1,I<=u)continue;if(h.length>=a){y=!0;continue}let U=O.length>Tl?O.substring(0,Tl)+nI:O,D=Buffer.byteLength(U,"utf-8")+(h.length>0?1:0);if(g+D>Dm){T=!0,y=!0;break}h.push(U),g+=D;}}finally{f.close(),m.destroy();}if(I<p&&!(I===0&&p===1))throw new Error(`Offset ${p} is out of range for this file (${I} lines)`);let x=h.map((O,U)=>`${U+p}: ${O}`),b=h.slice(0,20).join(`
|
|
122
|
+
`),w=[`<path>${n}</path>`,"<type>file</type>","<content>"].join(`
|
|
123
|
+
`);w+=x.join(`
|
|
124
|
+
`);let k=I,v=p+h.length-1,C=v+1,E=y||T;return T?w+=`
|
|
125
|
+
|
|
126
|
+
(Output capped at ${oI}. Showing lines ${p}-${v}. Use offset=${C} to continue.)`:y?w+=`
|
|
127
|
+
|
|
128
|
+
(Showing lines ${p}-${v} of ${k}. Use offset=${C} to continue.)`:w+=`
|
|
129
|
+
|
|
130
|
+
(End of file - total ${k} lines)`,w+=`
|
|
131
|
+
</content>`,await We.isAvailable(t.sessionId)&&await We.touchFile(n,false),An.read(t.sessionId,n),r.length>0&&(w+=`
|
|
132
|
+
|
|
133
|
+
<system-reminder>
|
|
134
|
+
${r.map(O=>O.content).join(`
|
|
135
|
+
|
|
136
|
+
`)}
|
|
137
|
+
</system-reminder>`),{title:o,output:w,metadata:{filepath:n,preview:b,truncated:E,loaded:r.map(O=>O.filepath)}}}});async function sI(e,t){switch(Filesystem.extname(e).toLowerCase()){case ".zip":case ".tar":case ".gz":case ".exe":case ".dll":case ".so":case ".class":case ".jar":case ".war":case ".7z":case ".doc":case ".docx":case ".xls":case ".xlsx":case ".ppt":case ".pptx":case ".odt":case ".ods":case ".odp":case ".bin":case ".dat":case ".obj":case ".o":case ".a":case ".lib":case ".wasm":case ".pyc":case ".pyo":return true;}if(t===0)return false;let o=await Tt.open(e,"r");try{let s=Math.min(4096,t),r=Buffer.alloc(s),i=await o.read(r,0,s,0);if(i.bytesRead===0)return !1;let c=0;for(let l=0;l<i.bytesRead;l++){let d=r[l];if(d!==void 0){if(d===0)return !0;(d<9||d>13&&d<32)&&c++;}}return c/i.bytesRead>.3}finally{await o.close();}}var iI=loadTextFile("./ls.txt",import.meta.url),aI=iI(),cI=["node_modules/","__pycache__/",".git/","dist/","build/","target/","vendor/","bin/","obj/",".idea/",".vscode/",".zig-cache/","zig-out/",".coverage/","coverage/","tmp/","temp/",".cache/","logs/",".venv/","venv/","env/"],dI=100,fc=De.define("list",{description:aI,parameters:N.object({path:N.string().default(".").optional().describe("The directory to list (default: current directory"),ignore:N.array(N.string()).default([]).optional().describe("List of glob patterns to ignore"),limit:N.number().default(100).optional().describe("Maximum number of entries to return (default: 100")}),execute:async(e,t)=>{let n=Filesystem.normalize(Se.isAbsolute(e.path||".")?e.path||".":Se.resolve(R.directory,e.path||"."));await Jt(t,n,{kind:"directory",tool:"list"}),await t.ask({permission:"list",patterns:[Se.posix.relative(R.worktree,n)],always:["*"],metadata:{path:n}});let o=e.limit??dI,s="/",r=cI.map(a=>`!${a}*`).concat(e.ignore?.map(a=>`!${a}`)||[]),i=[],c=false;for await(let a of a$8.files({cwd:n,glob:r,signal:t.abort})){if(i.length>=o){c=true;break}i.push(Filesystem.toUnixPath(a));}let l=new Set,d=new Map;for(let a of i){let p=Se.posix.dirname(a),u=p==="."?[]:p.split(s);for(let h=0;h<=u.length;h++){let g=h===0?".":u.slice(0,h).join(s);l.add(g);}d.has(p)||d.set(p,[]),d.get(p).push(Se.posix.basename(a));}let m=(a,p)=>{let u=" ".repeat(p),h="";p>0&&(h+=`${u}${Se.posix.basename(a)}/
|
|
138
|
+
`);let g=" ".repeat(p+1),I=Array.from(l).filter(y=>Se.posix.dirname(y)===a&&y!==a).sort();for(let y of I)h+=m(y,p+1);let T=d.get(a)||[];for(let y of T.sort())h+=`${g}${y}
|
|
139
|
+
`;return h},f=`${n}/
|
|
140
|
+
`+m(".",0);return c&&(f+=`
|
|
141
|
+
[${o} entries limit reached, Use limit=${o*2} for more]`),{title:Se.posix.relative(R.worktree,n),metadata:{path:n,count:i.length,truncated:c},output:f}}});function Al(e){return e.startsWith("ws://")||e.startsWith("wss://")?e:e.startsWith("https://")?e.replace("https://","wss://"):e.startsWith("http://")?e.replace("http://","ws://"):`ws://${e}`}function El(e){let t=e;t.startsWith("wss://")?t=t.replace("wss://","https://"):t.startsWith("ws://")?t=t.replace("ws://","http://"):!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`http://${t}`);try{let n=new URL(t);return `${n.protocol}//${n.host}`}catch{let n=t.match(/^(https?:\/\/[^/]+)/);return n?n[1]:t}}var He=a.create({service:"acp-client-connection"}),_l=class{constructor(t){b$1(this,"ws",null);b$1(this,"config");b$1(this,"_state","disconnected");b$1(this,"pendingRequests",new Map);b$1(this,"requestId",1);b$1(this,"subscriptions",new Map);b$1(this,"reconnectAttempts",0);b$1(this,"abortController",null);let n=t.url;n.startsWith("acp-ws://")&&(n=n.replace("acp-ws://","ws://")),n.includes("/acp")||(n=n.replace(/\/$/,"")+"/acp"),this.config={...t,url:n};}get state(){return this._state}async connect(){this._state!=="connected"&&(this._state="connecting",He.debug("WebSocketConnection: connecting",{url:this.config.url}),await retry(async()=>new Promise((t,n)=>{try{this.abortController=new AbortController,this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{He.debug("WebSocketConnection: connected"),this._state="connected",this.reconnectAttempts=0,t();},this.ws.onmessage=async o=>{let s;if(typeof o.data=="string")s=o.data;else if(o.data instanceof Blob){let r=await o.data.arrayBuffer();s=new TextDecoder("utf-8").decode(r);}else o.data instanceof ArrayBuffer?s=new TextDecoder("utf-8").decode(o.data):s=String(o.data);this.handleMessage(s);},this.ws.onerror=o=>{He.error("WebSocketConnection: error",{error:String(o)}),this._state==="connecting"&&n(new Error("WebSocket connection error"));},this.ws.onclose=()=>{He.debug("WebSocketConnection: closed"),this._state="disconnected";for(let[,o]of this.pendingRequests)o.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.handleReconnect();};}catch(o){this._state="disconnected",n(o);}}),{attempts:3}));}async disconnect(){He.debug("WebSocketConnection: disconnecting"),this.abortController&&(this.abortController.abort(),this.abortController=null),this.ws&&(this.ws.close(),this.ws=null),this._state="disconnected";for(let[t,n]of this.pendingRequests)n.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.subscriptions.clear();}async send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");let o=this.requestId++,s={jsonrpc:"2.0",id:o,method:t,params:n};return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),i(new Error(`Request timeout: ${t}`));},this.config.timeout??3e5);this.pendingRequests.set(o,{resolve:l=>{clearTimeout(c),l.error?i(new Error(l.error.message)):r(l.result);},reject:i}),this.ws.send(JSON.stringify(s)),He.debug("WebSocketConnection: sent request",{method:t,id:o});})}subscribe(t,n){return He.debug("WebSocketConnection: subscribe called",{sessionId:t}),this.subscriptions.has(t)?He.debug("WebSocketConnection: already subscribed",{sessionId:t,callbackCount:this.subscriptions.get(t)?.size}):(this.subscriptions.set(t,new Set),He.debug("WebSocketConnection: subscribing to session",{sessionId:t}),this.send("session.subscribe",{sessionId:t}).catch(o=>{He.error("WebSocketConnection: subscribe failed",{sessionId:t,error:String(o)});})),this.subscriptions.get(t).add(n),He.debug("WebSocketConnection: callback added",{sessionId:t,callbackCount:this.subscriptions.get(t)?.size}),()=>{He.debug("WebSocketConnection: unsubscribe called",{sessionId:t});let o=this.subscriptions.get(t);o&&(o.delete(n),He.debug("WebSocketConnection: callback removed",{sessionId:t,remainingCallbacks:o.size}),o.size===0&&(this.subscriptions.delete(t),this.send("session.unsubscribe",{sessionId:t}).catch(s=>{He.error("WebSocketConnection: unsubscribe failed",{sessionId:t,error:String(s)});})));}}isConnected(){return this._state==="connected"}handleMessage(t){He.debug("WebSocketConnection: received message",{data:t.slice(0,200)});try{let n=JSON.parse(t);if(He.debug("WebSocketConnection: parsed message",{method:n.method,id:n.id,hasParams:!!n.params}),n.id!==void 0&&n.id!==null){He.debug("WebSocketConnection: handling response",{id:n.id});let o=this.pendingRequests.get(n.id);if(o){this.pendingRequests.delete(n.id),o.resolve(n);return}He.debug("WebSocketConnection: no handler for response",{id:n.id});return}if(n.jsonrpc==="2.0"&&n.method&&!n.id){He.debug("WebSocketConnection: notification",{method:n.method});let o=n.params||{},s=o.sessionId;if(He.debug("WebSocketConnection: sessionId from notification",{sessionId:s}),s){let r=this.subscriptions.get(s);if(He.debug("WebSocketConnection: callbacks for notification",{sessionId:s,callbackCount:r?.size??0}),r&&r.size>0){let i={type:n.method,properties:o};for(let c of r)try{c(i);}catch(l){He.error("WebSocketConnection: notification callback error",{method:n.method,error:String(l)});}}else He.debug("WebSocketConnection: no callbacks for notification",{method:n.method,sessionId:s});}else He.debug("WebSocketConnection: no sessionId in notification",{method:n.method});}}catch(n){He.warn("WebSocketConnection: failed to parse message",{error:String(n)});}}handleReconnect(){if(!this.config.reconnect?.enabled)return;if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){He.warn("WebSocketConnection: max reconnect attempts reached");return}this.reconnectAttempts++;let t=this.config.reconnect.delayMs*this.reconnectAttempts;He.debug("WebSocketConnection: attempting reconnect",{attempt:this.reconnectAttempts,delay:t}),this._state="reconnecting",setTimeout(async()=>{try{await this.connect();for(let n of this.subscriptions.keys())await this.send("session.subscribe",{sessionId:n});}catch(n){He.error("WebSocketConnection: reconnect failed",{error:String(n)});}},t);}},Ml=class{constructor(t){b$1(this,"config");b$1(this,"_state","disconnected");b$1(this,"connectionId",null);b$1(this,"abortController",null);b$1(this,"sseAbortFn",null);b$1(this,"reader",null);b$1(this,"subscriptions",new Map);b$1(this,"pendingRequests",new Map);b$1(this,"requestId",1);let n=t.url.replace(/\/$/,"");n.includes("/acp")||(n+="/acp"),this.config={...t,url:n};}get state(){return this._state}async connect(){this._state!=="connected"&&(this._state="connected");}async disconnect(){if(this.sseAbortFn&&(this.sseAbortFn(),this.sseAbortFn=null),this.connectionId)try{let t={};this.config.token&&(t.Authorization=`Bearer ${this.config.token}`),t["Acp-Connection-Id"]=this.connectionId,await Fetch.request(this.config.url,{method:"DELETE",headers:t});}catch{}if(this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader){try{await this.reader.cancel();}catch{}this.reader=null;}this._state="disconnected",this.connectionId=null,this.subscriptions.clear();}async send(t,n){let o=this.config.url,s="POST",r=["initialize","session.new","session.load","session.fork","session.resume","session.prompt","session.cancel","session.setMode","session.setConfigOption","session.setModel","session.close","authenticate"],i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);let c;n&&typeof n=="object"&&"sessionId"in n&&(c=n.sessionId,this.connectionId&&(i["Acp-Connection-Id"]=this.connectionId,i["Acp-Session-Id"]=c));let l={jsonrpc:"2.0",id:String(this.requestId++),method:t,params:n};r.includes(t)&&(s="POST");let d=await Fetch.request(o,{method:s,headers:i,body:JSON.stringify(l),timeout:this.config.timeout??300*1e3});if(!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);let m=d.headers.get("Acp-Connection-Id");return m&&t==="initialize"&&!this.connectionId&&(this.connectionId=m,He.debug("HTTPConnection: got connectionId",{connectionId:m})),d.data.result??d.data}subscribe(t,n){return this.subscriptions.has(t)||(this.subscriptions.set(t,new Set),this.startSSE(t).catch(o=>{He.error("HTTPConnection: startSSE failed",{sessionId:t,error:String(o)});})),this.subscriptions.get(t).add(n),()=>{let o=this.subscriptions.get(t);o&&(o.delete(n),o.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}async startSSE(t){let n=this.config.url,o={};this.config.token&&(o.Authorization=`Bearer ${this.config.token}`),this.connectionId&&(o["Acp-Connection-Id"]=this.connectionId,o["Acp-Session-Id"]=t),this.abortController=new AbortController,this.sseAbortFn=Fetch.sse(n,{onMessage:s=>{try{let r=JSON.parse(s);if(r.jsonrpc==="2.0"&&r.method&&!r.id){let i={type:r.method,properties:{...r.params,sessionId:r.params?.sessionId||t}},c=this.subscriptions.get(t);if(c)for(let l of c)try{l(i);}catch(d){He.error("HTTPConnection: callback error",{sessionId:t,error:String(d)});}}}catch{}},onError:s=>{He.error("HTTPConnection: SSE connection failed",{sessionId:t,error:s.message});},onComplete:()=>{He.debug("HTTPConnection: SSE stream completed",{sessionId:t});}},{headers:o});}},Ol=class{constructor(t){b$1(this,"config");b$1(this,"_state","disconnected");b$1(this,"process",null);b$1(this,"connection",null);b$1(this,"subscriptions",new Map);b$1(this,"questionCallbacks",[]);b$1(this,"connectionReadyPromise",null);this.config=t;}get state(){return this._state}async connect(){if(this._state!=="connected"){this._state="connecting",He.debug("STDIOConnection: connecting",{command:this.config.command});try{let t=process.platform==="win32"?"cmd":void 0;if(this.process=Shell.spawn(t,this.config.command,{stdout:"pipe",stderr:"pipe",stdin:"pipe",env:this.config.env,cwd:this.config.cwd||process.cwd(),timeout:this.config.timeout??1800*1e3}),!this.process.stdout||!this.process.stdin)throw new Error("Failed to create stdio pipes");let n=this.process.stdin,o=this.process.stdout,s=new WritableStream({write:d=>new Promise((m,f)=>{n.write(d,a=>{a?f(a):m();});})}),r=new ReadableStream({start(d){let m="";o.on("data",f=>{m+=f.toString();let a=m.split(`
|
|
142
|
+
`);m=a.pop()??"";for(let p of a)p.trim()?.startsWith("{")&&d.enqueue(new TextEncoder().encode(p+`
|
|
143
|
+
`));}),o.on("end",()=>{m.trim()&&m.startsWith("{")&&d.enqueue(new TextEncoder().encode(m+`
|
|
144
|
+
`)),d.close();}),o.on("error",f=>d.error(f));}}),i=ndJsonStream(s,r),c=this,l={async sessionUpdate(d){let m=d.sessionId,f=c.subscriptions.get(m),a=Array.from(c.subscriptions.keys());if(He.debug("STDIOConnection: sessionUpdate",{sessionId:m,updateType:d.update?.sessionUpdate,messageId:d.update?.messageId,subscribedCount:c.subscriptions.size,subscribedSessionIds:a,hasCallbacks:f&&f.size>0}),f&&f.size>0){let p={type:d.update.sessionUpdate,properties:{sessionId:m,...d.update}};for(let u of f)try{u(p);}catch(h){He.error("STDIOConnection: sessionUpdate callback error",{sessionId:m,error:String(h)});}}else He.debug("STDIOConnection: sessionUpdate skipped - session not subscribed",{sessionId:m,updateType:d.update?.sessionUpdate,messageId:d.update?.messageId});},async requestPermission(d){return He.debug("STDIOConnection: requestPermission",{toolCall:d.toolCall}),{outcome:{outcome:"selected",optionId:"allow"}}},async extNotification(d,m){He.debug("STDIOConnection: extNotification",{method:d,params:m});},async extMethod(d,m){return He.debug("STDIOConnection: extMethod",{method:d,params:m}),{}},async requestQuestion(d){if(He.debug("STDIOConnection: requestQuestion",{requestId:d.requestId,questionCount:d.questions.length}),c.questionCallbacks.length>0){let m=c.questionCallbacks[c.questionCallbacks.length-1];return m(d)}return {outcome:"cancelled",answers:[]}}};this.connection=new ClientSideConnection(d=>l,i),this.process.exited.then(d=>{He.debug("STDIOConnection: subprocess exited",{code:d}),this._state="disconnected",this.connection=null;}).catch(d=>{He.debug("STDIOConnection: subprocess exited with error",{error:String(d)}),this._state="disconnected",this.connection=null;}),this.connectionReadyPromise?await Promise.race([this.connectionReadyPromise,new Promise(d=>setTimeout(d,2e3))]):await new Promise(d=>setTimeout(d,500)),this._state="connected",He.debug("STDIOConnection: connected");}catch(t){throw He.error("STDIOConnection: failed to connect",{error:String(t)}),this._state="disconnected",t}}}async disconnect(){He.debug("STDIOConnection: disconnecting"),this.process&&(this.process.kill(),this.process=null),this.connection=null,this._state="disconnected",this.subscriptions.clear();}async send(t,n){if(!this.connection)throw new Error("Not connected");if(this._state!=="connected")throw new Error(`Cannot send ${t}: connection state is ${this._state}`);He.debug("STDIOConnection: send",{method:t,state:this._state});try{switch(t){case "initialize":return this.connection.initialize(n);case "session.new":return this.connection.newSession(n);case "session.load":return this.connection.loadSession(n);case "session.list":return this.connection.listSessions(n);case "session.fork":return this.connection.unstable_forkSession(n);case "session.resume":return this.connection.resumeSession(n);case "session.close":return this.connection.closeSession(n);case "session.prompt":return this.connection.prompt(n);case "session.cancel":return this.connection.cancel(n);case "session.setMode":return this.connection.setSessionMode(n);case "session.setConfigOption":return this.connection.setSessionConfigOption(n);case "authenticate":return this.connection.authenticate(n);default:throw new Error(`Unsupported method: ${t}`)}}catch(o){throw o instanceof Error&&o.message.includes("stream")&&(He.error("STDIOConnection: stream error, marking as disconnected",{error:o.message,method:t}),this._state="disconnected",this.connection=null),o}}subscribe(t,n){return this.subscriptions.has(t)||this.subscriptions.set(t,new Set),this.subscriptions.get(t).add(n),()=>{let o=this.subscriptions.get(t);o&&(o.delete(n),o.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}};function jl(e){switch(e.type){case "websocket":return new _l({url:e.url,token:e.token,reconnect:e.reconnect,timeout:e.timeout});case "http":return new Ml({url:e.url,token:e.token,timeout:e.timeout});case "stdio":return new Ol({command:e.url,env:e.token?{EASBOT_TOKEN:e.token}:void 0,cwd:e.cwd,timeout:e.timeout});default:throw new Error(`Unsupported connection type: ${e.type}`)}}var En={includeThinking:false,includeToolDetails:false,includeToolOutput:false};var Oe=a.create({service:"acp-client"}),fI=300*1e3,Mo=class{constructor(t){b$1(this,"config");b$1(this,"connection");b$1(this,"initialized",false);b$1(this,"disconnected",false);b$1(this,"toolCallbacks",new Set);b$1(this,"questionCallbacks",new Set);b$1(this,"permissionCallbacks",new Set);b$1(this,"usageCallbacks",new Set);b$1(this,"commandsCallbacks",new Set);b$1(this,"configCallbacks",new Set);b$1(this,"modeCallbacks",new Set);b$1(this,"sessionStatusCallbacks",new Set);b$1(this,"notificationCallbacks",new Map);b$1(this,"messageCollectors",new Map);b$1(this,"questionHandlers",[]);b$1(this,"messageCallbacks",new Set);b$1(this,"collectorCleanupTimers",new Map);this.config=t,this.connection=jl(t),Oe.debug("ACPClient created",{type:t.type,url:t.url});}async initialize(t={protocolVersion:1}){if(this.initialized)return Oe.debug("ACPClient: already initialized"),{protocolVersion:t.protocolVersion,agentInfo:{name:"acp-client",version:"1.0.0"}};Oe.debug("ACPClient: initializing connection");try{await this.connection.connect();let n=await this.connection.send("initialize",t);return this.initialized=!0,Oe.debug("ACPClient: initialization complete"),n}catch(n){throw Oe.error("ACPClient: initialization failed",{error:n instanceof Error?n.message:String(n)}),n}}async authenticate(t){this.ensureInitialized(),Oe.debug("ACPClient: authenticate");try{return await this.connection.send("authenticate",t)}catch(n){throw Oe.error("ACPClient: authentication failed",{error:n instanceof Error?n.message:String(n)}),n}}async disconnect(){this.disconnected||(Oe.debug("ACPClient: disconnecting"),this.disconnected=true,await this.connection.disconnect(),Oe.debug("ACPClient: disconnected"));}async newSession(t){this.ensureInitialized(),Oe.debug("ACPClient: newSession",{cwd:t.cwd});let n=await this.connection.send("session.new",t);return Oe.debug("ACPClient: newSession complete",{sessionId:n.sessionId}),n}async loadSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: loadSession",{sessionId:t.sessionId}),this.connection.send("session.load",t)}async listSessions(t){return this.ensureInitialized(),Oe.debug("ACPClient: listSessions",{cwd:t.cwd}),this.connection.send("session.list",t)}async unstable_forkSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: forkSession",{sessionId:t.sessionId}),this.connection.send("session.fork",t)}async resumeSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: resumeSession",{sessionId:t.sessionId}),this.connection.send("session.resume",t)}async closeSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: closeSession",{sessionId:t.sessionId}),this.connection.send("session.close",t)}async prompt(t){this.ensureInitialized();let n=t.sessionId;Oe.debug("ACPClient: prompt",{sessionId:n,promptLength:t.prompt.length});let o=await this.connection.send("session.prompt",t);return Oe.debug("ACPClient: prompt complete",{sessionId:n,stopReason:o.stopReason}),o}async cancel(t){this.ensureInitialized(),Oe.debug("ACPClient: cancel",{sessionId:t.sessionId}),await this.connection.send("session.cancel",t),Oe.debug("ACPClient: cancel complete",{sessionId:t.sessionId});}async setSessionMode(t){return this.ensureInitialized(),Oe.debug("ACPClient: setSessionMode",{sessionId:t.sessionId,modeId:t.modeId}),this.connection.send("session.setMode",t)}async setSessionConfigOption(t){return this.ensureInitialized(),Oe.debug("ACPClient: setSessionConfigOption",{sessionId:t.sessionId,configId:t.configId}),this.connection.send("session.setConfigOption",t)}subscribeSessionEvents(t,n,o=En){return n.onMessage&&this.messageCallbacks.add(n.onMessage),this.connection.subscribe(t,s=>{let r=s.properties.messageId;if(s.type==="agent_thought_chunk"&&o.includeThinking&&r){let d=s.properties;if(d.content?.type==="text"&&d.content.text){let m=this.messageCollectors.get(r);m||(m={sessionId:t,text:"",thinkings:[],tools:[],hasText:false,hasUsage:false,filterConfig:o,createdAt:Date.now()},this.messageCollectors.set(r,m)),m.thinkings.push(d.content.text);}}if(s.type==="agent_message_chunk")if(Oe.debug("agent_message_chunk: received",{eventMessageId:r}),r){let d=s.properties;if(d.content?.type==="text"&&d.content.text){let m=this.messageCollectors.get(r);m||(m={sessionId:t,text:"",thinkings:[],tools:[],hasText:false,hasUsage:false,filterConfig:o,createdAt:Date.now()},this.messageCollectors.set(r,m),Oe.debug("agent_message_chunk: created new collector",{eventMessageId:r,collectorCount:this.messageCollectors.size})),m.text+=d.content.text,m.hasText=true,Oe.debug("agent_message_chunk: hasText=true",{eventMessageId:r,hasUsage:m.hasUsage}),m.hasUsage&&(Oe.debug("agent_message_chunk: triggering send",{eventMessageId:r}),this.checkAndSendMessage(r,m.tokens));}else Oe.debug("agent_message_chunk: skipped - no text content",{contentType:d.content?.type});}else Oe.debug("agent_message_chunk: skipped - no messageId");let i=d=>["agent_message_chunk","agent_message","tool_call_update","message_text","message_end","thinking_chunk","usage_update","available_commands_update","config_option_update","current_mode_update","error"].includes(d),c=s.type,l=s.properties?.sessionUpdate||c;if(!i(l))Oe.debug("subscribeSessionEvents: non-standard event type, dispatching as notification",{actualEventType:l,rawEventType:c,properties:s.properties}),this.dispatchNotification(l,s.properties);else {let d={...s,type:l};this.dispatchEvent(d);}n.onSessionUpdate&&n.onSessionUpdate(s);})}dispatchNotification(t,n){let o=this.notificationCallbacks.get(t);if(o&&o.size>0){Oe.debug("ACPClient: dispatching notification",{method:t,callbackCount:o.size});for(let s of o)try{s(n);}catch(r){Oe.error("ACPClient: notification callback error",{method:t,error:String(r)});}}if(t==="session.status"){let s=n.status?.type??"idle";for(let r of this.sessionStatusCallbacks)try{r(s);}catch(i){Oe.error("ACPClient: sessionStatus callback error",{error:String(i)});}}}checkAndSendMessage(t,n){let o=this.messageCollectors.get(t);if(!o){Oe.debug("checkAndSendMessage: collector not found",{messageId:t});return}if(!o.hasText||!o.hasUsage){Oe.debug("checkAndSendMessage: conditions not met",{messageId:t,hasText:o.hasText,hasUsage:o.hasUsage});return}Oe.debug("checkAndSendMessage: sending message",{messageId:t,callbackCount:this.messageCallbacks.size}),this.messageCallbacks.size===0&&Oe.warn("checkAndSendMessage: no message callbacks registered",{messageId:t});try{let r={role:"assistant",text:o.text||void 0,thinking:o.filterConfig.includeThinking&&o.thinkings.join("")||void 0,tools:o.filterConfig.includeToolDetails&&(o.tools?.length??0)>0?o.tools:void 0,metadata:{sessionId:o.sessionId,messageId:t,timestamp:Date.now(),tokens:n?{input:n.input,output:n.output,total:n.input+n.output+(n.reasoning??0)}:void 0}};for(let i of this.messageCallbacks)i(r);}catch(r){Oe.error("ACPClient: checkAndSendMessage error",{error:r instanceof Error?r.message:String(r)});}this.messageCollectors.delete(t);let s=this.collectorCleanupTimers.get(t);s&&(clearTimeout(s),this.collectorCleanupTimers.delete(t)),Oe.debug("checkAndSendMessage: message sent and collector cleaned",{messageId:t});}dispatchEvent(t){let{type:n,properties:o}=t;switch(n){case "tool_call_update":{let s=o.status==="running"?"in_progress":o.status??"pending",r={callId:o.toolCallId??"",tool:o.title??"",status:s,kind:o.kind,title:o.title,input:o.rawInput,output:o.rawOutput?.output,error:o.rawOutput?.error,content:o.content,locations:[]},c=o._meta?.messageId;if(c){let l=this.messageCollectors.get(c);l?.filterConfig.includeToolDetails&&(s==="completed"||s==="error")&&(l.tools||(l.tools=[]),l.tools.push({name:r.tool,status:s==="completed"?"completed":"error",output:l.filterConfig.includeToolOutput?r.output:void 0,error:r.error}));}for(let l of this.toolCallbacks)try{l(r);}catch(d){Oe.error("ACPClient: tool callback error",{error:d instanceof Error?d.message:String(d)});}break}case "error":{o.error&&Oe.error("ACPClient: received error event",{name:o.error.name,data:o.error.data});break}case "usage_update":{let s=o,r=s._meta?.messageId;if(r){let i=this.messageCollectors.get(r);i||(i={sessionId:o.sessionId??"",text:"",thinkings:[],tools:[],hasText:false,hasUsage:true,tokens:void 0,filterConfig:s._meta?.filterConfig??En,createdAt:Date.now()},this.messageCollectors.set(r,i),Oe.debug("usage_update: created new collector",{messageId:r,collectorCount:this.messageCollectors.size})),i.hasUsage=true,i.tokens={input:0,output:0,reasoning:0,...o.tokens},Oe.debug("usage_update: hasUsage=true",{messageId:r,hasText:i.hasText}),i.hasText?(Oe.debug("usage_update: triggering send",{messageId:r}),this.checkAndSendMessage(r,i.tokens)):this.scheduleCollectorCleanup(r);}for(let i of this.usageCallbacks)try{i({used:o.used??0,size:o.size??0});}catch(c){Oe.error("ACPClient: usage callback error",{error:c instanceof Error?c.message:String(c)});}break}case "available_commands_update":{for(let s of this.commandsCallbacks)try{s(o.availableCommands??[]);}catch(r){Oe.error("ACPClient: commands callback error",{error:r instanceof Error?r.message:String(r)});}break}case "config_option_update":{for(let s of this.configCallbacks)try{s(o.configOptions??[]);}catch(r){Oe.error("ACPClient: config callback error",{error:r instanceof Error?r.message:String(r)});}break}case "current_mode_update":{for(let s of this.modeCallbacks)try{s(o.currentModeId??"");}catch(r){Oe.error("ACPClient: mode callback error",{error:r instanceof Error?r.message:String(r)});}break}}}onToolCall(t){return this.toolCallbacks.add(t),Oe.debug("ACPClient: tool callback registered",{callbackCount:this.toolCallbacks.size}),()=>{this.toolCallbacks.delete(t),Oe.debug("ACPClient: tool callback unregistered",{callbackCount:this.toolCallbacks.size});}}onQuestion(t){return this.questionCallbacks.add(t),Oe.debug("ACPClient: question callback registered",{callbackCount:this.questionCallbacks.size}),()=>{this.questionCallbacks.delete(t),Oe.debug("ACPClient: question callback unregistered",{callbackCount:this.questionCallbacks.size});}}onPermission(t){return this.permissionCallbacks.add(t),Oe.debug("ACPClient: permission callback registered",{callbackCount:this.permissionCallbacks.size}),()=>{this.permissionCallbacks.delete(t),Oe.debug("ACPClient: permission callback unregistered",{callbackCount:this.permissionCallbacks.size});}}onUsage(t){return this.usageCallbacks.add(t),()=>{this.usageCallbacks.delete(t);}}onCommands(t){return this.commandsCallbacks.add(t),()=>{this.commandsCallbacks.delete(t);}}onConfig(t){return this.configCallbacks.add(t),()=>{this.configCallbacks.delete(t);}}onMode(t){return this.modeCallbacks.add(t),()=>{this.modeCallbacks.delete(t);}}onSessionStatus(t){return this.sessionStatusCallbacks.add(t),()=>{this.sessionStatusCallbacks.delete(t);}}onNotification(t,n){return this.notificationCallbacks.has(t)||this.notificationCallbacks.set(t,new Set),this.notificationCallbacks.get(t).add(n),Oe.debug("ACPClient: notification callback registered",{method:t,callbackCount:this.notificationCallbacks.get(t)?.size}),()=>{let o=this.notificationCallbacks.get(t);o&&(o.delete(n),o.size===0&&this.notificationCallbacks.delete(t)),Oe.debug("ACPClient: notification callback unregistered",{method:t});}}registerQuestionHandler(t){return this.questionHandlers.push(t),Oe.debug("ACPClient: question handler registered",{handlerCount:this.questionHandlers.length}),()=>{let n=this.questionHandlers.indexOf(t);n>-1&&this.questionHandlers.splice(n,1),Oe.debug("ACPClient: question handler unregistered",{handlerCount:this.questionHandlers.length});}}async answerQuestion(t){this.ensureInitialized(),Oe.debug("ACPClient: answerQuestion",{sessionId:t.sessionId,requestId:t.requestId,answerCount:t.answers.length});let n=t.answers.map(o=>`[QUESTION_ANSWER:${t.requestId}] answer: "${o.join(", ")}"`).join(`
|
|
145
|
+
`);await this.connection.send("session.prompt",{sessionId:t.sessionId,prompt:[{type:"text",text:n}]}),Oe.debug("ACPClient: answerQuestion sent",{sessionId:t.sessionId,requestId:t.requestId});}ensureInitialized(){if(!this.initialized)throw new Error("ACPClient not initialized. Call initialize() first.");if(this.disconnected)throw new Error("ACPClient disconnected")}scheduleCollectorCleanup(t){if(this.collectorCleanupTimers.has(t))return;let n=setTimeout(()=>{this.collectorCleanupTimers.delete(t);let o=this.messageCollectors.get(t);o&&(!o.hasText||!o.hasUsage)&&(Oe.debug("scheduleCollectorCleanup: cleaning orphaned collector",{messageId:t,hasText:o.hasText,hasUsage:o.hasUsage}),this.messageCollectors.delete(t));},fI);this.collectorCleanupTimers.set(t,n);}};var gI=a.create({service:"websocket-subscriber"});function Ll(e){return new gc(e)}var gc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"websocket",url:""},gI.info("WebSocketSubscriber created",{config:this._config});}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url||await this.getConfigWebSocketUrl();if(!s)throw new Error("No WebSocket URL provided and no config URL found");this._client||(this._client=new Mo({...o,type:"websocket",url:s}),await this._client.initialize());}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}async getConfigWebSocketUrl(){let t=process.env.EASBOT_WS_URL;return t||""}};var hI=a.create({service:"http-subscriber"});function $l(e){return new Dl(e)}var Dl=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"http",url:""},hI.info("HTTPSubscriber created",{config:this._config});}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url;this._client||(this._client=new Mo({...o,type:"http",url:s}),await this._client.initialize());}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};a.create({service:"stdio-subscriber"});function Fl(e){return new hc(e)}var hc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"stdio",url:""};}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url;if(this._client)return;let r;s.startsWith("stdio://")?r=`${new URL(s).hostname||"easbot"} acp --channel stdio --log-level ${a.getLevel()}`:s.startsWith("easbot")?r=`${s} --log-level ${a.getLevel()}`:r=`node dist/cli.mjs acp --channel stdio --log-level ${a.getLevel()}`,this._client=new Mo({...o,type:"stdio",url:r}),await this._client.initialize();}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};var vr=class{constructor(t){b$1(this,"log",a.create({service:"gateway:client"}));b$1(this,"config");b$1(this,"ws",null);b$1(this,"state","disconnected");b$1(this,"lastNotifiedState","disconnected");b$1(this,"subscriptions",new Map);b$1(this,"messageCallbacks",new Set);b$1(this,"agentListCallbacks",new Set);b$1(this,"stateCallbacks",new Set);b$1(this,"cachedAgentList",[]);b$1(this,"localAgentList",[]);b$1(this,"heartbeatTimer",null);b$1(this,"heartbeatTimeoutTimer",null);b$1(this,"lastPongReceived",0);b$1(this,"agentListRequestId",null);b$1(this,"agentListRequestResolve",null);b$1(this,"isClosing",false);b$1(this,"connectReject",null);b$1(this,"connectPendingResolve");b$1(this,"connectPendingReject",new Set);this.config={url:t.url,type:t.type,id:t.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,heartbeat:{enabled:t.heartbeat?.enabled??true,interval:t.heartbeat?.interval??6e4}},this.log=a.create({service:`gateway:client:${this.config.id}`}),this.connect().catch(()=>{}).finally(()=>{if(this.config.heartbeat.enabled)try{this.startHeartbeat();}catch(n){this.log.error("[gateway:client] failed to start heartbeat:",{error:String(n)});}});}async connect(){if(this.state!=="connected")return this.state==="connecting"?new Promise((t,n)=>{let o=setTimeout(()=>{this.connectPendingReject?.delete(n),n(new Error("Connection timeout while waiting"));},3e4);this.connectPendingReject?.add(n);this.connectPendingResolve;this.connectPendingResolve=()=>{clearTimeout(o),this.connectPendingReject?.delete(n),t(void 0);};}):(this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),this.isClosing=false,new Promise((t,n)=>{this.connectReject=n;let o=setTimeout(()=>{this.state==="connecting"&&(this.log.warn("connection timeout, closing socket"),this.state="disconnected",this.connectReject=null,this.ws&&(this.ws.close(4001,"Connection timeout"),this.ws=null),n(new Error("Connection timeout")));},3e4);try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{clearTimeout(o),this.state="connected",this.connectReject=null,this.lastPongReceived=Date.now(),this.notifyStateChange(),this.connectPendingResolve?.(),this.connectPendingResolve=void 0,this.resubscribeAll(),t();},this.ws.onmessage=s=>{this.handleMessage(s.data);},this.ws.onclose=s=>{clearTimeout(o),this.handleClose(s.code,s.reason);},this.ws.onerror=s=>{clearTimeout(o);};}catch(s){clearTimeout(o),this.state="disconnected",this.connectReject=null,this.notifyStateChange(),n(s);}}))}async disconnect(){this.state!=="disconnected"&&(this.isClosing=true,this.stopHeartbeat(),this.cachedAgentList=[],this.localAgentList=[],this.agentListRequestId=null,this.agentListRequestResolve&&(this.agentListRequestResolve([]),this.agentListRequestResolve=null),this.subscriptions.clear(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"),this.notifyStateChange());}async subscribe(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.subscriptions.has(t)||(this.subscriptions.set(t,{sessionId:t}),this.sendData({type:"subscribe",sessionId:t,clientId:this.config.id}));}async unsubscribe(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:t,clientId:this.config.id}),this.subscriptions.delete(t);}async send(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:t});}onMessage(t){this.messageCallbacks.add(t);}offMessage(t){this.messageCallbacks.delete(t);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(t){this.localAgentList=t,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((t,n)=>{let o=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=o,this.agentListRequestResolve=t,this.sendData({type:"agent_list_request",requestId:o}),setTimeout(()=>{this.agentListRequestId===o&&(this.agentListRequestId=null,this.agentListRequestResolve=null,n(new Error("Agent list request timeout")));},1e4);})}async registerAgent(t){if(this.state!=="connected")throw new Error("Not connected to gateway");if(!t.agentId||!t.name||!t.address)throw new Error("Agent ID, name and address are required");this.sendData({type:"agent_register",payload:{agentId:t.agentId,name:t.name,address:t.address,capabilities:t.capabilities,metadata:t.metadata}});}async deregisterAgent(t){if(this.state!=="connected")throw new Error("Not connected to gateway");if(!t)throw new Error("Agent ID is required");this.sendData({type:"agent_deregister",payload:{agentId:t}}),this.log.debug("Agent deregistration sent",{agentId:t});}async subscribeAgentList(t){if(this.state!=="connected"){this.log.debug("Cannot subscribe to agent list: not connected to gateway",{state:this.state});return}this.sendData({type:"agent_subscribe",subscribe:t,clientId:this.config.id}),this.log.debug("Agent list subscription changed",{subscribe:t,clientId:this.config.id});}async agentHeartbeat(t,n){if(this.state!=="connected"){this.log.debug("Cannot send agent heartbeat: not connected to gateway",{state:this.state});return}this.sendData({type:"agent_register",payload:{agentId:t,...n??{}}}),this.log.debug("Agent heartbeat sent",{agentId:t});}getConnectableAgents(t={}){let{localAgents:n,preferLocal:o=true,filterOffline:s=true}=t,r=n||this.localAgentList,i=this.cachedAgentList,c=this.mergeAgentLists(r,i,o);return s?c.filter(l=>l.status!=="offline"):c}onAgentListChange(t){this.agentListCallbacks.add(t);}offAgentListChange(t){this.agentListCallbacks.delete(t);}mergeAgentLists(t,n,o){let s=new Map,r=o?n:t,i=o?t:n;for(let c of r)s.set(c.id,c);for(let c of i)s.set(c.id,c);return Array.from(s.values())}updateMergedAgentList(){let t=this.getConnectableAgents({filterOffline:false});for(let n of this.agentListCallbacks)try{n(t);}catch(o){this.log.error("agent list callback error",{error:String(o)});}}handleAgentListResponse(t,n){n&&this.agentListRequestId===n&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(t),this.agentListRequestResolve=null),this.cachedAgentList=t,this.updateMergedAgentList(),this.log.debug("received agent list",{count:t.length});}sendData(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(t));}handleMessage(t){try{let n=JSON.parse(t);switch(n.type){case "message":if(this.log.debug("message received",{type:n.type,sessionId:n.sessionId,payloadId:n.payload?.id,payloadType:n.payload?.type}),n.payload&&typeof n.payload=="object"){let o={...n.payload,sessionId:n.sessionId};this.handleGatewayMessage(o);}else this.log.warn("received message with invalid or missing payload");break;case "subscribed":this.subscriptions.set(n.sessionId,n.subscription);break;case "unsubscribed":this.subscriptions.delete(n.sessionId);break;case "pong":this.lastPongReceived=Date.now(),this.log.debug("pong received");break;case "agent_list_response":this.handleAgentListResponse(n.agents||[],n.requestId);break;case "agent_update":this.handleAgentUpdate(n.agent,n.action);break;default:this.log.debug("unknown message type",{type:n.type});}}catch(n){this.log.error("failed to parse message",{error:String(n)});}}handleAgentUpdate(t,n){switch(n){case "add":case "update":{let o=this.cachedAgentList.findIndex(s=>s.id===t.id);o>=0?this.cachedAgentList[o]=t:this.cachedAgentList.push(t);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(o=>o.id!==t.id);break}this.updateMergedAgentList();}handleGatewayMessage(t){for(let n of this.messageCallbacks)try{n(t);}catch(o){this.log.error("message callback error",{error:String(o)});}}handleClose(t,n){if(this.log.debug("connection closed",{code:t,reason:n,isClosing:this.isClosing}),this.isClosing){this.log.debug("intentional close, skipping reconnect"),this.isClosing=false;return}this.connectReject&&(this.connectReject(new Error(`Connection failed: ${n||t}`)),this.connectReject=null);for(let o of this.connectPendingReject)o(new Error(`Connection failed: ${n||t}`));this.connectPendingReject.clear(),this.connectPendingResolve=void 0,this.state="disconnected",this.ws=null,this.notifyStateChange();}startHeartbeat(){this.lastPongReceived=Date.now(),this.log.info("heartbeat started",{interval:this.config.heartbeat.interval}),this.heartbeatTimer=setInterval(()=>{this.state==="disconnected"?(this.log.debug("heartbeat: disconnected, attempting to connect with backoff"),retry(()=>this.connectWithBackoff(),{attempts:3,delay:1e3,factor:2,maxDelay:4e3,retryIf:()=>false}).catch(()=>{this.log.debug("heartbeat: all retry attempts failed, waiting for next cycle");})):this.state==="connected"&&(this.sendData({type:"ping"}),this.log.debug("ping sent"));},this.config.heartbeat.interval);let t=this.config.heartbeat.interval*5;this.log.debug("heartbeat check started",{interval:this.config.heartbeat.interval,timeout:t}),this.heartbeatTimeoutTimer=setInterval(()=>{if(this.state==="connected"){let n=Date.now()-this.lastPongReceived;n>t&&(this.log.warn("heartbeat timeout",{elapsed:n,timeout:t}),this.ws&&this.ws.close(4e3,"Heartbeat timeout"));}},this.config.heartbeat.interval);}async connectWithBackoff(){this.state==="connected"||this.state==="connecting"||await this.connect();}notifyStateChange(){if(this.state===this.lastNotifiedState){this.log.debug("state unchanged, skipping notification",{state:this.state});return}let t=this.lastNotifiedState;this.lastNotifiedState=this.state,this.log.debug("state changed",{previousState:t,currentState:this.state});for(let n of this.stateCallbacks)try{n(this.state);}catch(o){this.log.error("state callback error",{error:String(o)});}}onStateChange(t){this.stateCallbacks.add(t);}offStateChange(t){this.stateCallbacks.delete(t);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeoutTimer&&(clearInterval(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null);}async resubscribeAll(){for(let t of this.subscriptions.keys())try{await this.subscribe(t);}catch(n){this.log.error("failed to resubscribe",{sessionId:t,error:String(n)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(t,n={}){let o=`${this.getHttpUrl()}${t}`,s=n.method||"GET",{signal:r,...i}=n,c=await Fetch.request(o,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!c.ok){let l=c.data,d=typeof l=="object"?JSON.stringify(l):String(l||"Unknown error");throw new Error(`HTTP ${c.status}: ${d}`)}return c.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(t,n={}){let o=new URLSearchParams({platform:t,limit:String(n.limit??100),offset:String(n.offset??0)});return this.httpRequest(`/contacts?${o}`)}async getContact(t){return this.httpRequest(`/contacts/${encodeURIComponent(t)}`)}async getSession(t){return this.httpRequest(`/sessions/${encodeURIComponent(t)}`)}async createSession(t){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(t??{})})}async getOrCreateSession(t){if(t.sessionId)try{return await this.getSession(t.sessionId),{sessionId:t.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:t.sessionId});}if(t.platform||t.channel||t.userId){let o=t.chatId??t.userId;try{let i=await this.listSessions({platform:t.platform,channelId:t.channel,userId:t.userId,chatId:o});if(i.sessions.length>0){let c=i.sessions[0];if(c)return this.log.debug("found existing session",{sessionId:c.id,channel:t.channel,userId:t.userId,chatId:o}),{sessionId:c.id,created:!1}}}catch(i){this.log.warn("failed to search sessions",{error:String(i)});}let s={channel:{platform:t.platform,channelId:t.channel,userId:t.userId,chatId:o}},r=await this.createSession(s);return this.log.debug("session created",{sessionId:r.id,params:s}),{sessionId:r.id,created:true}}let n=await this.createSession({channel:{platform:"api",channelId:"default"}});return this.log.debug("session created (default)",{sessionId:n.id}),{sessionId:n.id,created:true}}async listSessions(t={}){let n=new URLSearchParams;return n.set("limit",String(t.limit??100)),n.set("offset",String(t.offset??0)),t.platform&&n.set("platform",t.platform),t.channelId&&n.set("channelId",t.channelId),t.userId&&n.set("userId",t.userId),t.chatId&&n.set("chatId",t.chatId),this.httpRequest(`/sessions?${n}`)}async sendMessage(t,n){return this.httpRequest(`/session/${encodeURIComponent(t)}/prompt`,{method:"POST",body:JSON.stringify(n)})}};var Zo;(I=>{let e=a.create({service:"agent-services"});function t(T){switch(T){case "healthy":return "online";case "unhealthy":return "offline";case "offline":return "offline";default:return "unknown"}}class n{constructor(y){b$1(this,"storagePath");b$1(this,"gatewayUrl");b$1(this,"services",new Map);b$1(this,"gatewayClient",null);b$1(this,"gatewayCallbacks",{onAgentListChange:y=>{this.updateFromGateway(y);},onStateChange:y=>{y==="connected"&&this.gatewayClient?.subscribeAgentList(true).catch(()=>{});}});this.storagePath=Se__default.join(a$1.Path.data,"state","agent-services.json"),this.gatewayUrl=y,e.debug("AgentServiceRegistry created",{storagePath:this.storagePath,gatewayUrl:this.gatewayUrl});}async load(y="",x=false){if(await Promise.all([this.loadFromLocalConfig(),this.loadFromClientsConfig()]),x)for(let b of this.services.keys())b.startsWith("gateway:")&&this.services.delete(b);this.gatewayUrl&&await this.loadFromGateway(y),e.debug("Agent services loaded",{count:this.services.size});}async loadFromClientsConfig(){try{let{getACPClientsConfig:y}=await import('./adapter-loader-VUS3UYMT.mjs'),x=await y();if(!x?.clients||x.clients.length===0)return;for(let b of x.clients){let w=this.extractBaseUrl(b);if(!w)continue;let k=`clients:${b.id}`;if(this.services.has(k))continue;let v=b.agentId??b.id;this.services.set(k,{id:k,name:b.name??b.id,baseUrl:w,agentId:v,capabilities:b.channel?[b.channel]:[],status:"unknown",metadata:{type:b.type,channel:b.channel,autoConnect:b.autoConnect,priority:b.priority},updatedAt:Date.now()});}e.debug("Loaded services from clients config",{count:x.clients.length});}catch(y){e.warn("Failed to load clients config",{error:String(y)});}}extractBaseUrl(y){if(y.connection?.http?.baseUrl)return y.connection.http.baseUrl;if(y.connection?.ws?.url)return y.connection.ws.url;if(y.connection?.stdio)return "stdio://local"}async loadFromLocalConfig(){try{if(!await Tt__default.access(this.storagePath).then(()=>!0).catch(()=>!1))return;let x=await Tt__default.readFile(this.storagePath,"utf-8"),b=JSON.parse(x);if(b.services)for(let w of b.services)this.services.set(w.id,{...w,updatedAt:w.updatedAt??Date.now()});e.debug("Loaded services from local config",{count:b.services?.length??0});}catch(y){e.warn("Failed to load local config",{error:String(y)});}}async loadFromGateway(y=""){if(!this.gatewayUrl)return;let x=`${y}_agent_services`;this.gatewayClient=new vr({url:this.gatewayUrl,type:"subagent",id:x,heartbeat:{enabled:true,interval:6e4}}),this.gatewayClient.onAgentListChange(this.gatewayCallbacks.onAgentListChange),this.gatewayClient.onStateChange(this.gatewayCallbacks.onStateChange),e.debug("Gateway client initialized, will subscribe on connect");}updateFromGateway(y){for(let x of y){let b=`gateway:${x.id}`;this.services.set(b,{id:b,name:x.name,baseUrl:x.address,agentId:x.id,capabilities:x.capabilities??[],status:t(x.status),metadata:{sourceGatewayId:x.sourceGatewayId,...x.metadata},updatedAt:x.updatedAt});}e.debug("Gateway agent list updated",{count:y.length});}listServices(y){let x=Array.from(this.services.values());return y?.status&&(x=x.filter(b=>b.status===y.status)),y?.capability&&(x=x.filter(b=>b.capabilities.includes(y.capability))),x}getService(y){return this.services.get(y)}getServiceByUrl(y){for(let x of this.services.values())if(x.baseUrl===y)return x}async registerService(y){let x={...y,updatedAt:Date.now()};this.services.set(y.id,x),await this.save();}async unregisterService(y){this.services.delete(y)&&await this.save();}async updateServiceStatus(y,x){let b=this.services.get(y);b&&(b.status=x,b.updatedAt=Date.now(),await this.save());}async save(){let y={version:1,services:Array.from(this.services.values())};try{await Tt__default.mkdir(Se__default.dirname(this.storagePath),{recursive:!0}),await Tt__default.writeFile(this.storagePath,JSON.stringify(y,null,2),"utf-8"),e.debug("Services saved",{count:this.services.size});}catch(x){e.error("Failed to save services",{error:String(x)}),await this.saveBackup(y);}}async saveBackup(y){try{let x=this.storagePath+".backup";await Tt__default.writeFile(x,JSON.stringify(y,null,2),"utf-8"),e.debug("Services backup saved",{backupPath:x});}catch(x){e.error("Failed to save services backup",{error:String(x)});}}async disconnect(){this.gatewayClient&&(this.gatewayClient.offAgentListChange(this.gatewayCallbacks.onAgentListChange),this.gatewayClient.offStateChange(this.gatewayCallbacks.onStateChange),await this.gatewayClient.subscribeAgentList(false),await this.gatewayClient.disconnect(),this.gatewayClient=null);}}let o=new Map,s="";function r(T){let y=o.get(T);return y||(y=R.state(async()=>{let x;try{let{getGatewayClientUrl:w}=await import('./gateway-loader-OH3VCEUD.mjs');x=await w();}catch(w){e.warn("Failed to get Gateway URL",{error:String(w)});}let b=new n(x);return await b.load(T),e.info("AgentServices initialized",{prefix:T,gatewayUrl:x,servicesCount:b.listServices().length}),{registry:b,gatewayUrl:x,initialized:true}},async x=>{x?.registry&&await x.registry.disconnect();}),o.set(T,y)),y}function i(){return r(s)()}async function c(){return (await i()).registry}I.get=c;async function l(T){return (await c()).listServices(T)}I.listServices=l;async function d(T){return (await c()).getService(T)}I.getService=d;async function m(T){return (await c()).getServiceByUrl(T)}I.getServiceByUrl=m;async function f(T){await(await c()).registerService(T);}I.registerService=f;async function a$2(T){await(await c()).unregisterService(T);}I.unregisterService=a$2;async function p(T,y){await(await c()).updateServiceStatus(T,y);}I.updateServiceStatus=p;async function u(){return (await i()).initialized}I.isInitialized=u;async function h(T){s=T,await r(T)(),e.debug("AgentServices init",{prefix:T});}I.init=h;async function g(){await(await c()).load(s,true);}I.refresh=g;})(Zo||(Zo={}));function wI(e,t){switch(t){case "websocket":return Al(e);case "http":return El(e);case "stdio":return e;default:throw new Error(`Unsupported channel type: ${t}`)}}function xI(e){let t=e.type;switch(t){case "websocket":return Ll(e);case "http":return $l(e);case "stdio":return Fl(e);default:throw new Error(`Unsupported channel type: ${t}`)}}var Xn;(l=>{async function e(d){let{config:m,sessionId:f}=d,a=m.type,p=m.url,u=m.cwd??process.cwd(),h=xI(m);await h.connect(p);let g=f;if(g?(await h.client.listSessions({cwd:u})).sessions?.find(y=>y.sessionId===g)?await h.client.resumeSession({sessionId:g,cwd:u}):g=(await h.client.newSession({cwd:u,mcpServers:[]})).sessionId:g=(await h.client.newSession({cwd:u,mcpServers:[]})).sessionId,!g)throw new Error("Failed to create remote session");return {baseUrl:p,sessionId:g,channel:a,subscriber:h}}l.connect=e;async function t(d,m,f){await d.client.prompt({sessionId:m,prompt:f});}l.send=t;async function n(d,m){await d.client.cancel({sessionId:m});}l.interrupt=n;async function o(d){let m=await d.client.initialize({protocolVersion:1});return {protocolVersion:m.protocolVersion,agentCapabilities:{modes:[],models:[],...m.agentInfo},authMethods:[]}}l.capabilities=o;async function s(d,m){let a=(await d.client.listSessions({cwd:process.cwd()})).sessions?.find(p=>p.sessionId===m);return a?{status:"active",sessionId:a.sessionId,cwd:a.cwd,title:a.title,exists:true}:{status:"not_found",sessionId:m,exists:false}}l.status=s;async function r(d,m){await d.client.cancel({sessionId:m});}l.releaseSubscription=r;async function i(d){return {sessions:(await d.client.listSessions({cwd:process.cwd()})).sessions??[]}}l.subscriptions=i;function c(d,m){return wI(d,m)}l.getConnectionUrl=c;})(Xn||(Xn={}));function Nm(e,t){let n=btoa(String.fromCharCode(...e));return `data:${t??"application/octet-stream"};base64,${n}`}function Um(e,t){let n=[];if(t&&n.push(`<system-reminder>
|
|
146
|
+
${t}
|
|
147
|
+
</system-reminder>`),e)for(let o of e)switch(o.type){case "text":o.text&&n.push(`<text>
|
|
148
|
+
${o.text}
|
|
149
|
+
</text>`);break;case "image":{let s="";typeof o.image=="string"?s=o.image:o.image instanceof URL?s=o.image.toString():o.image instanceof Uint8Array&&(s=Nm(o.image,o.mime)),n.push(`<image mime="${o.mime??"image/png"}">
|
|
150
|
+
${s}
|
|
151
|
+
</image>`);break}case "file":{let s="";typeof o.data=="string"?s=o.data:o.data instanceof URL?s=o.data.toString():o.data instanceof Uint8Array&&(s=Nm(o.data,o.mime)),n.push(`<file mime="${o.mime??"application/octet-stream"}">
|
|
152
|
+
${s}
|
|
153
|
+
</file>`);break}case "command":n.push(o.arguments?`/${o.command} ${o.arguments}`:`/${o.command}`);break}return n.join(`
|
|
154
|
+
`)}var un=a.create({service:"subagent.acp"}),yc=class{constructor(t){b$1(this,"subscriber",null);b$1(this,"config");b$1(this,"sessionId",null);b$1(this,"_isRunning",false);b$1(this,"unsubscribeFn",null);this.config=t;}async start(){if(this.subscriber&&this._isRunning){un.debug("ACPAgentHandler.start: already connected, reusing",{name:this.config.name});return}let t=this.config.transport==="websocket"?"websocket":this.config.transport==="http"?"http":"stdio",n=this.config.uri??this.buildUrl(this.config);un.debug("ACPAgentHandler.start",{type:t,url:n,cwd:this.config.cwd??R.directory??process.cwd(),name:this.config.name});try{let o=await Xn.connect({config:{type:t,url:n,cwd:this.config.cwd??R.directory??process.cwd(),timeout:this.config.timeout,env:this.config.env}});this.subscriber=o.subscriber,this.sessionId=o.sessionId,this._isRunning=!0,un.info("ACPAgentHandler started",{name:this.config.name,type:t,url:n});}catch(o){throw un.error("ACPAgentHandler.start failed",{name:this.config.name,error:String(o)}),o}}async stop(){if(un.debug("ACPAgentHandler.stop",{sessionId:this.sessionId,name:this.config?.name}),this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),this.subscriber&&this.sessionId)try{await Xn.releaseSubscription(this.subscriber,this.sessionId);}catch(t){un.warn("Error releasing subscription",{error:String(t)});}this.subscriber=null,this.sessionId=null,this._isRunning=false;}async execute(t){if(!this.subscriber||!this._isRunning)throw new Error("ACP agent not running");un.debug("ACPAgentHandler.execute",{title:t.title,agent:t.agent,partsCount:t.parts?.length??1});let n=this.config?.timeout??300*1e3;this.config?.cwd??process.cwd();let s=this.subscriber.client,r=await new Promise((i,c)=>{let l="",d,m,f=0,a=false,p=setTimeout(()=>{a||(a=true,un.debug("ACPAgentHandler.execute timeout",{timeout:n,messageCount:f}),i({title:t.title,output:l,metadata:{sessionId:this.sessionId??void 0,agent:t.agent,messageId:d,tokens:m}}));},n);(async()=>{try{let u=this.sessionId;if(!u)throw new Error("No session available. Call start() first.");un.debug("ACPAgentHandler: using existing session",{sessionId:u}),this.unsubscribeFn=s.subscribeSessionEvents(u,{onMessage:g=>{f++,un.debug("ACPAgentHandler: message received",{messageCount:f,hasText:!!g.text,textLength:g.text?.length??0}),g.text&&(l=g.text),d=g.metadata.messageId,m=g.metadata.tokens,a||(a=!0,clearTimeout(p),i({title:t.title,output:l,metadata:{sessionId:u,agent:t.agent,messageId:d,tokens:m}}));},onError:g=>{if(g.message?.includes("NotFoundError")){un.debug("ACPAgentHandler: ignored NotFoundError",{sessionId:u});return}un.error("ACPAgentHandler: subscription error",{error:g.message});}},{includeThinking:!1,includeToolDetails:!1,includeToolOutput:!1});let h=Um(t.parts,t.system);await s.prompt({sessionId:u,prompt:[{type:"text",text:h}]}),un.debug("ACPAgentHandler.execute prompt sent",{title:t.title,sessionId:u});}catch(u){a||(a=true,clearTimeout(p),c(u));}})();});return un.debug("ACPAgentHandler.execute completed",{title:t.title,textLength:r.output.length}),this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),r}async interrupt(){this.subscriber?.client&&this.sessionId&&(un.debug("ACPAgentHandler.interrupt",{sessionId:this.sessionId}),await Xn.interrupt(this.subscriber,this.sessionId));}isRunning(){return this._isRunning}async checkHealth(){if(!this._isRunning||!this.subscriber)return false;try{if(this.sessionId){let n=(await this.subscriber.client.listSessions({cwd:this.config?.cwd??process.cwd()}))?.sessions;return !n||!Array.isArray(n)?!1:n.some(o=>o.sessionId===this.sessionId)}return !0}catch(t){return un.debug("ACPAgentHandler.checkHealth failed",{error:String(t)}),false}}buildUrl(t){if(t.uri)return t.uri;let n=t.command??"easbot",o=t.args??["acp","--channel","stdio"];return `${n} ${o.join(" ")}`}};var tt;(c=>{let e;function t(){return e||(e=R.state(async()=>({...process.env}))),e}function n(){return t()()}async function o(l){return (await n())[l]}c.get=o;async function s(){return await n()}c.all=s;async function r(l,d){let m=await n();m[l]=d;}c.set=r;async function i(l){let d=await n();delete d[l];}c.remove=i;})(tt||(tt={}));var bc=a.create({service:"subagent.cli"}),wc=class{constructor(t){b$1(this,"process",null);b$1(this,"config");b$1(this,"_isRunning",false);b$1(this,"abortController",null);this.config=t;}async start(){this._isRunning=true,bc.debug("CLIAgentHandler.start",{command:this.config.command});}async stop(){this.abortController&&this.abortController.abort(),this._isRunning=false;}async execute(t){if(!this.config.command)throw new Error("CLI command not configured");bc.debug("CLIAgentHandler.execute",{title:t.title,command:this.config.command});let n=this.buildArgs(t),o=this.config.command,s=this.config.cwd,i={...await tt.all(),...this.config.env},c=this.config.timeout??3e5,l={...process.env,...i};this.abortController=new AbortController;let d=process.platform==="win32"?"cmd":void 0;this.process=Shell.spawn(d,`${o} ${n.join(" ")}`,{cwd:s,env:l,stdout:"pipe",stderr:"pipe",stdin:"null",timeout:c,signal:this.abortController.signal});let m="",f="";this.process.stdout?.on("data",a=>{m+=a.toString("utf-8");}),this.process.stderr?.on("data",a=>{f+=a.toString("utf-8");});try{let a=await this.process.exited;if(a===0)return {title:t.title,output:m.trim(),metadata:{command:o,args:n,exitCode:a}};throw bc.error("CLI exited with error",{code:a,stderr:f}),new Error(`CLI exited with code ${a}: ${f}`)}catch(a){let p=a;throw bc.error("CLI process error",{error:p.message}),a}finally{this.process=null,this._isRunning=false;}}async interrupt(){this.abortController&&this.abortController.abort();}isRunning(){return this._isRunning}async checkHealth(){return this._isRunning?this.process!==null||this._isRunning:false}buildArgs(t){let n=[...this.config?.args??[]],o=t.parts?.filter(s=>s.type==="text").map(s=>s.type==="text"&&"text"in s?s.text:"").filter(Boolean).join(`
|
|
155
|
+
`)||t.title;return n.push("--prompt",o),n}};var xn=a.create({service:"subagent.registry"}),xc=class{constructor(t){b$1(this,"instances",new Map);b$1(this,"handlers",new Map);b$1(this,"config");b$1(this,"agentCounts",new Map);b$1(this,"idleCleanupTimer",null);this.config=t,this.startIdleCleanup();}startIdleCleanup(){if(this.idleCleanupTimer)return;let t=this.config.idleCheckInterval??300*1e3,n=this.config.idleTimeout??1800*1e3;this.idleCleanupTimer=setInterval(()=>{this.cleanupIdleInstances(n);},t),xn.debug("Idle cleanup timer started",{interval:t,timeout:n});}stopIdleCleanup(){this.idleCleanupTimer&&(clearInterval(this.idleCleanupTimer),this.idleCleanupTimer=null,xn.debug("Idle cleanup timer stopped"));}async cleanupIdleInstances(t){let n=Date.now(),o=[];for(let[s,r]of this.instances){if(r.config.runMode!=="persistent"||r.status!=="idle"&&r.status!=="error")continue;n-r.lastActiveAt>t&&o.push(s);}if(o.length>0){xn.debug("Cleaning up idle instances",{count:o.length,maxIdleTime:t});for(let s of o)try{await this.terminate(s);}catch(r){xn.warn("Failed to cleanup idle instance",{id:s,error:String(r)});}}}async checkInstanceHealth(t){let n=this.handlers.get(t.id);if(!n)return false;try{return "checkHealth"in n&&typeof n.checkHealth=="function"?await n.checkHealth():n.isRunning()}catch{return false}}async spawn(t){let n=Identifier.ascending("subagent"),o={id:n,config:t,status:"starting",createdAt:Date.now(),lastActiveAt:Date.now()},s=this.createHandler(t);this.handlers.set(n,s),this.instances.set(n,o);try{return await s.start(t),o.status="idle",this.agentCounts.set(t.name,(this.agentCounts.get(t.name)??0)+1),xn.debug("Agent spawned",{id:n,name:t.name,status:o.status}),o}catch(r){throw o.status="error",o.error=String(r),this.handlers.delete(n),this.instances.delete(n),xn.error("Failed to spawn agent, cleaned up",{id:n,name:t.name,error:String(r)}),r}}createHandler(t){switch(t.transport){case "stdio":case "http":case "websocket":return new yc(t);case "cli":return new wc(t);default:throw new Error(`Unknown transport type: ${t.transport}`)}}async acquire(t){let n=await this.findIdleInstance(t.name);if(!n){let s=this.agentCounts.get(t.name)??0,r=t.maxConcurrent??this.config.maxConcurrent;s<r?n=await this.spawn(t):(xn.debug("Max concurrent reached, waiting for idle instance",{name:t.name,currentCount:s,maxConcurrent:r}),n=await this.waitForIdleInstance(t.name));}n.status="running",n.lastActiveAt=Date.now();let o=this.handlers.get(n.id);if(!o)throw new Error(`Handler not found for instance: ${n.id}`);return {instance:n,execute:async s=>{n.status="busy";try{let r=await o.execute(s);return n.status="idle",n.lastActiveAt=Date.now(),r}catch(r){throw n.status="error",r}},interrupt:()=>o.interrupt()}}async release(t,n){n==="ephemeral"?await this.terminate(t.id):(t.status="idle",xn.debug("Agent released to pool",{id:t.id,name:t.config.name}));}async terminate(t){let n=this.handlers.get(t),o=this.instances.get(t);if(this.handlers.delete(t),n)try{await n.stop();}catch(s){xn.warn("Error stopping agent",{id:t,error:String(s)});}if(o){let s=this.agentCounts.get(o.config.name)??0;s>0&&this.agentCounts.set(o.config.name,s-1),o.status="stopped",this.instances.delete(t);}xn.debug("Agent terminated",{id:t});}async interrupt(t){let n=this.handlers.get(t);if(n)try{await n.interrupt(),xn.debug("Agent interrupted",{id:t});}catch(o){xn.warn("Error interrupting agent",{id:t,error:String(o)});}}async shutdownAll(){this.stopIdleCleanup();let t=Array.from(this.instances.keys());await Promise.all(t.map(n=>this.terminate(n))),xn.debug("All agents shut down",{count:t.length});}list(){return Array.from(this.instances.values())}get(t){return this.instances.get(t)}async findIdleInstance(t){let n=[];for(let[o,s]of this.instances){if(s.config.name!==t||s.status!=="idle")continue;if(!await this.checkInstanceHealth(s)){xn.warn("Found unhealthy idle instance, marking for cleanup",{id:o,name:t,lastActiveAt:s.lastActiveAt}),n.push(o);continue}return s}for(let o of n)try{await this.terminate(o);}catch(s){xn.warn("Failed to terminate unhealthy instance",{id:o,error:String(s)});}}async waitForIdleInstance(t,n=6e4){let o=Date.now();for(;Date.now()-o<n;){let s=await this.findIdleInstance(t);if(s)return s;await new Promise(r=>setTimeout(r,1e3));}throw new Error(`Timeout waiting for idle ${t} agent`)}};var en=a.create({service:"subagent"});function Nl(e,t){return t?{...e,...t}:e}var ks;(T=>{let e,t;function n(){return e||(e=R.state(async()=>{try{let y=await o();if(!y.enabled)return en.debug("SubAgent system disabled"),{registry:null,config:y,initialized:!0};let x=new xc(y),b=y.agents.filter(w=>w.runMode==="persistent");for(let w of b)try{await x.spawn(w),en.debug("Persistent agent spawned",{name:w.name});}catch(k){en.error("Failed to spawn persistent agent",{name:w.name,error:String(k)});}return en.info("SubAgent system initialized",{totalAgents:y.agents.length,persistentAgents:b.length}),{registry:x,config:y,initialized:!0}}catch(y){return t=y instanceof Error?y:new Error(String(y)),en.error("SubAgent system initialization failed, continuing without SubAgent",{error:t.message}),{registry:null,config:{enabled:false,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,agents:[],idleTimeout:1800*1e3,idleCheckInterval:300*1e3},initialized:false,initError:t}}},async y=>{y?.registry&&await y.registry.shutdownAll();})),e}async function o(){let y=await ur();if(!y.enabled)return {enabled:false,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,idleTimeout:1800*1e3,idleCheckInterval:300*1e3,agents:[]};let b=y.defaultRunMode==="persistent"?"persistent":"ephemeral",w=y.timeout,k=y.maxConcurrent,v=y.idleTimeout??1800*1e3,C=y.idleCheckInterval??300*1e3,E=y.agents.map(O=>({...O,transport:O.transport,runMode:O.runMode}));return {enabled:true,defaultRunMode:b,timeout:w,maxConcurrent:k,idleTimeout:v,idleCheckInterval:C,agents:E}}function s(){return n()()}T.state=s;async function r(){return (await s()).config?.enabled??false}T.isEnabled=r;async function i(){return (await s()).initialized}T.isInitialized=i;function c(){return t}T.getInitError=c;async function l(y){let x=await s();if(!x.config?.enabled)throw new Error("SubAgent system is disabled");let b=x.config.agents.find(v=>v.name===y.agent);if(!b)throw new Error(`Unknown agent: ${y.agent}`);let w=Nl(b,y.config);if(en.debug("SubAgent.run started",{title:y.title,agent:y.agent,runMode:w.runMode,transport:w.transport}),!x.registry)throw new Error("SubAgent registry not initialized");let k=await x.registry.acquire(w);try{return await k.execute(y)}catch(v){if(en.error("SubAgent.run failed",{title:y.title,agent:y.agent,runMode:w.runMode,error:String(v)}),w.runMode==="persistent"){en.warn("Persistent agent failed, terminating instance",{id:k.instance.id,name:y.agent});try{await x.registry.terminate(k.instance.id);}catch(C){en.warn("Failed to terminate persistent agent",{id:k.instance.id,error:String(C)});}}throw v}finally{if(w.runMode==="ephemeral")try{await x.registry.release(k.instance,"ephemeral");}catch(v){en.warn("Failed to release ephemeral agent",{id:k.instance.id,error:String(v)});}}}T.run=l;async function d(y,x){let b=await s();if(!b.config?.enabled)throw new Error("SubAgent system is disabled");let w=b.config.agents.find(E=>E.name===y.agent);if(!w)throw new Error(`Unknown agent: ${y.agent}`);let k=Nl(w,y.config);if(en.debug("SubAgent.runAsync started",{title:y.title,agent:y.agent,runMode:k.runMode,transport:k.transport}),!b.registry)throw new Error("SubAgent registry not initialized");let v=b.registry,C=await v.acquire(k);return (async()=>{try{let E=await C.execute(y);try{await x(E);}finally{await v.release(C.instance,k.runMode);}}catch(E){en.error("SubAgent.runAsync failed",{title:y.title,agent:y.agent,error:String(E)});try{await x({title:y.title,output:`Error: ${E}`,metadata:{error:String(E)}});}finally{await v.release(C.instance,k.runMode);}}})(),C.instance.id}T.runAsync=d;function m(y){return (async()=>{let x=await s();if(!x.config?.enabled)throw new Error("SubAgent system is disabled");let b=x.config.agents.find(C=>C.name===y.agent);if(!b)throw new Error(`Unknown agent: ${y.agent}`);let w=Nl(b,y.config);if(en.debug("SubAgent.runPromise started",{title:y.title,agent:y.agent,runMode:w.runMode,transport:w.transport}),!x.registry)throw new Error("SubAgent registry not initialized");let k=x.registry,v=await k.acquire(w);try{return {...await v.execute(y),instanceId:v.instance.id}}catch(C){throw en.error("SubAgent.runPromise failed",{title:y.title,agent:y.agent,error:String(C)}),C}finally{await k.release(v.instance,w.runMode);}})()}T.runPromise=m;async function f(){return (await s()).registry?.list()??[]}T.list=f;async function a(y){return (await s()).registry?.get(y)}T.get=a;async function p(y){let x=await s();x.registry&&await x.registry.terminate(y);}T.close=p;async function u(){let y=await s();y.registry&&await y.registry.shutdownAll();}T.closeAll=u;async function h(y){let x=await s();x.registry&&x.registry.get(y)&&await x.registry.interrupt(y);}T.interrupt=h;async function g(y){let x=await s();if(x.config){if(x.config.agents.find(w=>w.name===y.name)){en.warn("Agent already registered",{name:y.name});return}if(x.config.agents.push(y),y.runMode==="persistent"&&x.registry)try{await x.registry.spawn(y);}catch(w){en.error("Failed to spawn persistent agent after register",{name:y.name,error:String(w)});}en.info("Agent registered",{name:y.name});}}T.register=g;async function I(y){let x=await s();if(x.config){let b=x.config.agents.findIndex(w=>w.name===y);b!==-1&&(x.config.agents.splice(b,1),en.info("Agent unregistered",{name:y}));}}T.unregister=I;})(ks||(ks={}));var Ul=class extends Error{constructor(n,o){super(`Too many concurrent tasks: ${n} running, limit is ${o}`);b$1(this,"running");b$1(this,"limit");this.name="TaskConcurrencyError",this.running=n,this.limit=o;}},jt;(x=>{let e=a.create({service:"task"});x.MAX_CONCURRENT_TASKS=5;async function n(b){let w=await o(b);if(w>=x.MAX_CONCURRENT_TASKS)throw new Ul(w,x.MAX_CONCURRENT_TASKS)}async function o(b){return (await g(b)).filter(k=>k.status==="running").length}x.getRunningCount=o;let s;async function r(){return Filesystem.normalize(Se__default.join(a$1.Path.data,"task"))}async function i(b){let w=await r();return Filesystem.normalize(Se__default.join(w,`${b}.json`))}async function c(b){let w=await i(b);try{let k=await Filesystem.readText(w);return k?JSON.parse(k):[]}catch{return []}}async function l(b,w){let k=await i(b);try{await Filesystem.write(k,JSON.stringify(w,null,2)),e.debug("Session tasks saved",{sessionId:b,count:w.length});}catch(v){e.error("Failed to save session tasks",{sessionId:b,error:String(v)});}}async function d(){let b=await r(),w=new Map;try{let k=await readdir(b);for(let v of k){if(!v.endsWith(".json"))continue;let C=v.replace(".json",""),E=await c(C);for(let O of E)w.set(O.taskId,O);}}catch(k){e.debug("Task directory not found or empty",{error:String(k)});}return w}function m(){return s||(s=R.state(async()=>{let b=await d();return e.debug("Task state initialized",{taskCount:b.size}),{tasks:b,initialized:true}},async()=>{})),s}function f(){return m()()}x.state=f;async function a$2(b){return (await f()).tasks.get(b)}x.get=a$2;async function p(b){await n(b.sessionId);let w=await f(),k=Date.now(),v={taskId:b.taskId,sessionId:b.sessionId,description:b.description,prompt:b.prompt,agentType:b.agentType,source:b.source||"tool",status:"pending",createdAt:k,updatedAt:k,metadata:b.metadata};w.tasks.set(b.taskId,v);let C=await c(b.sessionId);return C.push(v),await l(b.sessionId,C),e.debug("Task created",{taskId:b.taskId,sessionId:b.sessionId}),v}x.create=p;async function u(b,w){let k=await f(),v=k.tasks.get(b);if(!v){e.warn("Task not found for update",{taskId:b});return}w.status!==void 0&&(v.status=w.status),w.result!==void 0&&(v.result=w.result),w.error!==void 0&&(v.error=w.error),w.duration!==void 0&&(v.duration=w.duration),w.metadata!==void 0&&(v.metadata={...v.metadata,...w.metadata}),v.updatedAt=Date.now(),k.tasks.set(b,v);let C=await c(v.sessionId),E=C.findIndex(O=>O.taskId===b);E>=0?C[E]=v:C.push(v),await l(v.sessionId,C),e.debug("Task updated",{taskId:b,status:v.status});}x.update=u;async function h(b){let w=await f(),k=w.tasks.get(b);if(!k){e.warn("Task not found for remove",{taskId:b});return}let v=k.sessionId;w.tasks.delete(b);let E=(await c(v)).filter(O=>O.taskId!==b);await l(v,E),e.debug("Task removed",{taskId:b,sessionId:v});}x.remove=h;async function g(b){return c(b)}x.list=g;async function I(b){return (await g(b)).filter(k=>k.status==="running"||k.status==="pending")}x.active=I;async function T(b){let w=await g(b);return {total:w.length,pending:w.filter(k=>k.status==="pending").length,running:w.filter(k=>k.status==="running").length,completed:w.filter(k=>k.status==="completed").length,error:w.filter(k=>k.status==="error").length}}x.stats=T;async function y(b=10080*60*1e3){let w=await f(),k=Date.now(),v=0;for(let[C,E]of w.tasks)(E.status==="completed"||E.status==="error")&&k-E.updatedAt>b&&(w.tasks.delete(C),v++);if(v>0){let C=new Map;for(let E of w.tasks.values()){let O=C.get(E.sessionId)||[];O.push(E),C.set(E.sessionId,O);}for(let[E,O]of C)await l(E,O);e.debug("Cleaned up old tasks",{count:v});}return v}x.cleanup=y;})(jt||(jt={}));a.create({service:"tool.task"});var PI=loadTextFile("./task.txt",import.meta.url),TI=PI(),Mi={create:N.object({operation:N.literal("create").describe("Create a new async subtask"),description:N.string().describe("Task description, brief summary of task goal"),prompt:N.string().describe("Task prompt, detailed description of work to execute"),subagent_type:N.string().describe("Agent type, specifies the Agent role for executing the task")}),query:N.object({operation:N.literal("query").describe("Query task status or list"),taskId:N.string().optional().describe("Task ID, omit to list all tasks")}),continue:N.object({operation:N.literal("continue").describe("Continue executing a task"),taskId:N.string().describe("Task ID, the task to continue executing")}),delete:N.object({operation:N.literal("delete").describe("Delete task record"),taskId:N.string().describe("Task ID, the task to delete")}),agents:N.object({operation:N.literal("agents").describe("Get list of available Agent types")})},AI=N.discriminatedUnion("operation",[Mi.create,Mi.query,Mi.continue,Mi.delete,Mi.agents]),Oi=De.define("task",{description:TI,parameters:AI,formatValidationError(e){return `Task tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(e.operation==="create")return EI(e,t);if(e.operation==="query")return RI(e,t);if(e.operation==="continue")return _I(e,t);if(e.operation==="delete")return MI(e);if(e.operation==="agents")return jI();throw new Error(`Unknown operation: ${e.operation}`)}});async function EI(e,t){if(!t.messageId)throw new Error("messageId is required");if((await ve.get({sessionId:t.sessionId,messageId:t.messageId}))?.info.role!=="assistant")throw new Error("Not an assistant message");let o=await jt.getRunningCount(t.sessionId);if(o>=jt.MAX_CONCURRENT_TASKS)throw new Error(`Too many concurrent tasks: ${o} running, max is ${jt.MAX_CONCURRENT_TASKS}`);t.extra?.bypassAgentCheck||await t.ask({permission:"task",patterns:[e.subagent_type],always:["*"],metadata:{description:e.description,subagent_type:e.subagent_type}});let s=Identifier.ascending("task"),r=Date.now();await Le.triggerEvent(HookEvent.TaskStart,{taskId:s,sessionId:t.sessionId,source:"tool",agentType:e.subagent_type,description:e.description,prompt:e.prompt}),t.metadata({title:e.description,metadata:{taskId:s}});let i=[{type:"text",text:e.prompt}],c=await Ue.get(e.subagent_type);return ks.runAsync({source:t.sessionId,title:e.description,agent:"task_general",system:c?.prompt??"",parts:i,config:{runMode:"ephemeral",transport:"stdio"}},async l=>{let d=Date.now()-r;await Le.triggerEvent(HookEvent.TaskComplete,{taskId:s,sessionId:t.sessionId,source:"tool",result:l.output,duration:d,agentType:e.subagent_type,metadata:{...l.metadata,tool:"task",title:e.description}});}),await Le.triggerEvent(HookEvent.TaskRunning,{taskId:s,sessionId:t.sessionId,source:"tool"}),{output:`taskId: ${s}
|
|
156
|
+
|
|
157
|
+
Task started, results will be injected when complete`,title:e.description,metadata:{operation:"create",taskId:s}}}async function RI(e,t){if(e.taskId){let s=await jt.get(e.taskId);if(!s)return {output:`<task>
|
|
158
|
+
Task not found: ${e.taskId}
|
|
159
|
+
</task>`,title:"Task Query",metadata:{operation:"query",found:false,taskId:e.taskId}};let r=[`<task taskId="${s.taskId}" status="${s.status}">`];return s.description&&r.push(` description: ${s.description}`),s.agentType&&r.push(` agent: ${s.agentType}`),s.result&&r.push(` result: ${s.result}`),s.error&&r.push(` error: ${s.error}`),s.duration&&r.push(` duration: ${s.duration}ms`),r.push(` created: ${new Date(s.createdAt).toISOString()}`),r.push(` updated: ${new Date(s.updatedAt).toISOString()}`),r.push("</task>"),{output:r.join(`
|
|
160
|
+
`),title:`Task: ${s.description}`,metadata:{operation:"query",found:true,taskId:e.taskId,status:s.status}}}let n=await jt.list(t.sessionId);if(n.length===0)return {output:`<tasks>
|
|
161
|
+
No tasks found
|
|
162
|
+
</tasks>`,title:"Task Query",metadata:{operation:"query",total:0}};let o=[`<tasks total="${n.length}">`];for(let s of n)o.push(`[task_id="${s.taskId}"]`),o.push(` status: ${s.status}`),s.description&&o.push(` description: ${s.description}`),s.agentType&&o.push(` agent: ${s.agentType}`),o.push("");return o.push("</tasks>"),{output:o.join(`
|
|
163
|
+
`),title:`Tasks: ${n.length}`,metadata:{operation:"query",total:n.length}}}async function _I(e,t){let n=await jt.get(e.taskId);if(!n)return {output:`<task>
|
|
164
|
+
Task not found: ${e.taskId}
|
|
165
|
+
</task>`,title:"Task Continue",metadata:{operation:"continue",found:false,taskId:e.taskId}};if(n.status==="completed"||n.status==="running")return {output:`<task>
|
|
166
|
+
Task ${e.taskId} is already ${n.status}. Cannot restart.
|
|
167
|
+
</task>`,title:"Task Continue",metadata:{operation:"continue",taskId:e.taskId,status:n.status}};await jt.update(e.taskId,{status:"running"});let o=Date.now();t.metadata({title:n.description,metadata:{taskId:e.taskId}});let s=[{type:"text",text:n.prompt}],r=await Ue.get(n.agentType);return ks.runAsync({source:t.sessionId,title:n.description,agent:"task_general",system:r?.prompt??"",parts:s,config:{runMode:"ephemeral",transport:"stdio"}},async i=>{let c=Date.now()-o;await jt.update(e.taskId,{status:"completed",result:i.output,duration:c}),await Le.triggerEvent(HookEvent.TaskComplete,{taskId:e.taskId,sessionId:t.sessionId,source:"tool",result:i.output,duration:c,agentType:n.agentType});}),{output:`taskId: ${e.taskId}
|
|
168
|
+
|
|
169
|
+
Task continued, results will be injected when complete`,title:n.description,metadata:{operation:"continue",taskId:e.taskId}}}async function MI(e,t){return await jt.get(e.taskId)?(await jt.remove(e.taskId),{output:`<task>
|
|
170
|
+
Task ${e.taskId} deleted successfully.
|
|
171
|
+
</task>`,title:"Task Delete",metadata:{operation:"delete",found:true,taskId:e.taskId}}):{output:`<task>
|
|
172
|
+
Task not found: ${e.taskId}
|
|
173
|
+
</task>`,title:"Task Delete",metadata:{operation:"delete",found:false,taskId:e.taskId}}}async function OI(){return (await Ue.list()).filter(t=>t.hidden!==true).map(t=>({name:t.name,description:t.description}))}async function jI(){let e=await OI(),t=[`<agents total="${e.length}">`];for(let n of e)t.push(`- ${n.name}: ${n.description??"No description"}`);return t.push("</agents>"),{output:t.join(`
|
|
174
|
+
`),title:`Agents: ${e.length}`,metadata:{operation:"agents",total:e.length}}}var DI=loadTextFile("./init.txt",import.meta.url),zl=f("init",{description:"create/update AGENTS.md",source:"command",commandType:"prompt",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=DI(),o=e$1(n,e);return {title:"Initialize",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var FI=loadTextFile("./review.txt",import.meta.url),ql=f("review",{description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=FI(),o=e$1(n,e);return {title:"Code Review",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var UI=loadTextFile("./vuln.txt",import.meta.url),Hl=f("vuln",{description:"analyze code for security vulnerabilities",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=UI(),o=e$1(n,e);return {title:"Security Vulnerability Analysis",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var qI=loadTextFile("./arch.txt",import.meta.url),Bl=f("arch",{description:"review code architecture and design patterns",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=qI(),o=e$1(n,e);return {title:"Architecture Review",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var HI="Never use question tool (question)",Gl=f("btw",{description:"ask a side question without interrupting current task",source:"command",commandType:"local",agent:"btw",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{Provider:n}=await import('./provider-2RFHZVX4.mjs'),o;t.model?o=n.parseModel(t.model):o=await Xo(t.sessionId);let s=typeof e=="string"?e:JSON.stringify(e),r=await Sr.run({source:t.sessionId,title:"BTW Response",agent:t.agent,model:{providerId:o.providerId,modelId:o.modelId},parts:[{type:"text",text:s}],system:HI,syncMessages:false});return {title:r.title,metadata:{userMessage:r.metadata.userMessage,assistantMessage:r.metadata.assistantMessage,sessionId:t.sessionId},output:r.output,success:true}},init:async()=>({})});function GI(e){return typeof e=="string"?e:JSON.stringify(e)}var Wl=f("shell",{description:"execute shell command locally",source:"command",commandType:"local",subtask:false,hidden:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=GI(e).trim();if(!n)return {title:"Shell Command",metadata:{sessionId:t.sessionId},output:"No command provided",success:true};try{let o=await Shell.run(void 0,n,{cwd:R.directory});if(o.code!==0){let r=o.stderr||o.stdout||`Exit code: ${o.code}`;throw new Error(`Command failed (${o.code}): ${r}`)}let s=o.stdout||o.stderr;return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:n},output:s||"(empty output)",success:!0}}catch(o){return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:n,error:o instanceof Error?o.message:String(o)},output:`Error: ${o instanceof Error?o.message:String(o)}`,success:false}}},init:async()=>({})});var ji=a.create({service:"scheduler.task-store"}),VI="scheduler",KI="tasks.json",Hm=1,Be;(k=>{let e={heartbeats:[],scheduled:[],commands:[],version:Hm},t=false;function n(){return Se__default.join(a$1.Path.data,VI)}function o(){let v=n();return Se__default.join(v,KI)}async function s(){let v=n();await Filesystem.exists(v)||await mkdir(v,{recursive:true});}async function r(){let v=o();if(!await Filesystem.exists(v)){ji.debug("Task store file not found, using empty store");return}try{let C=await Filesystem.readText(v),E=JSON.parse(C);e.heartbeats=Array.isArray(E.heartbeats)?E.heartbeats:[],e.scheduled=Array.isArray(E.scheduled)?E.scheduled:[],e.commands=Array.isArray(E.commands)?E.commands:[],e.version=typeof E.version=="number"?E.version:Hm,ji.info("Task store loaded",{heartbeats:e.heartbeats.length,scheduled:e.scheduled.length,commands:e.commands.length});}catch(C){ji.error("Failed to load task store",{error:C});}}async function i(){if(!t)return;await s();let v=o();try{let C=JSON.stringify(e,null,2);await Filesystem.write(v,C),t=!1,ji.debug("Task store saved");}catch(C){throw ji.error("Failed to save task store",{error:C}),C}}async function c(){await r();}k.init=c;async function l(){return [...e.heartbeats]}k.getHeartbeats=l;async function d(){return [...e.scheduled]}k.getScheduled=d;async function m(v){return e.heartbeats.find(C=>C.id===v)}k.getHeartbeat=m;async function f(v){return e.scheduled.find(C=>C.id===v)}k.getScheduledTask=f;async function a(v){let C=e.heartbeats.findIndex(E=>E.id===v.id);C>=0?e.heartbeats[C]=v:e.heartbeats.push(v),t=true,await i();}k.saveHeartbeat=a;async function p(v){let C=e.scheduled.findIndex(E=>E.id===v.id);C>=0?e.scheduled[C]=v:e.scheduled.push(v),t=true,await i();}k.saveScheduled=p;async function u(v){e.heartbeats=e.heartbeats.filter(C=>C.id!==v),t=true,await i();}k.deleteHeartbeat=u;async function h(v){e.scheduled=e.scheduled.filter(C=>C.id!==v),t=true,await i();}k.deleteScheduled=h;async function g(v,C){let E=e.heartbeats.findIndex(D=>D.id===v);if(E<0)throw new Error(`Heartbeat task not found: ${v}`);let O=e.heartbeats[E],U={id:v,name:C.name??O.name,cron:C.cron??O.cron,type:"heartbeat",enabled:C.enabled??O.enabled,parts:C.parts??O.parts,config:C.config??O.config,recurring:true,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:C.lastFiredAt??O.lastFiredAt,nextFireAt:C.nextFireAt??O.nextFireAt};e.heartbeats[E]=U,t=true,await i();}k.updateHeartbeat=g;async function I(v,C){let E=e.scheduled.findIndex(D=>D.id===v);if(E<0)throw new Error(`Scheduled task not found: ${v}`);let O=e.scheduled[E],U={id:v,name:C.name??O.name,cron:C.cron??O.cron,type:"scheduled",enabled:C.enabled??O.enabled,parts:C.parts??O.parts,agentType:C.agentType??O.agentType,transport:C.transport??O.transport,agentConfig:C.agentConfig??O.agentConfig,recurring:C.recurring??O.recurring,durable:C.durable??O.durable,permanent:C.permanent??O.permanent,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:C.lastFiredAt??O.lastFiredAt,nextFireAt:C.nextFireAt??O.nextFireAt};e.scheduled[E]=U,t=true,await i();}k.updateScheduled=I;async function T(){return [...e.commands]}k.getCommands=T;async function y(v){return e.commands.find(C=>C.id===v)}k.getCommand=y;async function x(v){let C=e.commands.findIndex(E=>E.id===v.id);C>=0?e.commands[C]=v:e.commands.push(v),t=true,await i();}k.saveCommand=x;async function b(v){e.commands=e.commands.filter(C=>C.id!==v),t=true,await i();}k.deleteCommand=b;async function w(v,C){let E=e.commands.findIndex(D=>D.id===v);if(E<0)throw new Error(`Command task not found: ${v}`);let O=e.commands[E],U={id:v,name:C.name??O.name,cron:C.cron??O.cron,type:"command",enabled:C.enabled??O.enabled,config:C.config??O.config,recurring:C.recurring??O.recurring,durable:C.durable??O.durable,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:C.lastFiredAt??O.lastFiredAt,nextFireAt:C.nextFireAt??O.nextFireAt};e.commands[E]=U,t=true,await i();}k.updateCommand=w;})(Be||(Be={}));var Vl;(h=>{async function e(){return Be.getHeartbeats()}h.getHeartbeats=e;async function t(){return Be.getScheduled()}h.getScheduled=t;async function n(g){return Be.getHeartbeat(g)}h.getHeartbeat=n;async function o(g){return Be.getScheduledTask(g)}h.getScheduledTask=o;async function s(g){return Be.saveHeartbeat(g)}h.saveHeartbeat=s;async function r(g){return Be.saveScheduled(g)}h.saveScheduled=r;async function i(g){return Be.deleteHeartbeat(g)}h.deleteHeartbeat=i;async function c(g){return Be.deleteScheduled(g)}h.deleteScheduled=c;async function l(g,I){return Be.updateHeartbeat(g,I)}h.updateHeartbeat=l;async function d(g,I){return Be.updateScheduled(g,I)}h.updateScheduled=d;async function m(){return Be.getCommands()}h.getCommands=m;async function f(g){return Be.getCommand(g)}h.getCommand=f;async function a(g){return Be.saveCommand(g)}h.saveCommand=a;async function p(g){return Be.deleteCommand(g)}h.deleteCommand=p;async function u(g,I){return Be.updateCommand(g,I)}h.updateCommand=u;})(Vl||(Vl={}));function Li(e,t,n){if(e==="*"){let r=[];for(let i=t;i<=n;i++)r.push(i);return r}let o=new Set,s=e.split(",");for(let r of s)if(r.includes("/")){let[i,c]=r.split("/"),l=Bm(i??"*",t,n),d=parseInt(c??"1",10);for(let m=0;m<l.length;m+=d)m<l.length&&o.add(l[m]);}else if(r.includes("-")){let i=Bm(r,t,n);for(let c of i)o.add(c);}else {let i=parseInt(r,10);!Number.isNaN(i)&&i>=t&&i<=n&&o.add(i);}return Array.from(o).sort((r,i)=>r-i)}function Bm(e,t,n){if(e==="*"){let l=[];for(let d=t;d<=n;d++)l.push(d);return l}let[o,s]=e.split("-"),r=o?parseInt(o,10):t,i=s?parseInt(s,10):n,c=[];for(let l=r;l<=i;l++)l>=t&&l<=n&&c.push(l);return c}function Cr(e){if(!e||typeof e!="string")return null;let n=e.trim().split(/\s+/);if(n.length!==5)return null;try{let[o,s,r,i,c]=n;return {minutes:Li(o??"*",0,59),hours:Li(s??"*",0,23),days:Li(r??"*",1,31),months:Li(i??"*",1,12),weekdays:Li(c??"*",0,6)}}catch{return null}}function es(e){return Cr(e)!==null}function Cc(e,t=new Date){let n=new Date(t);n.setSeconds(0,0);for(let o=0;o<366*24*60;o++){n.setMinutes(n.getMinutes()+1);let s=n.getMinutes(),r=n.getHours(),i=n.getDate(),c=n.getMonth()+1,l=n.getDay();if(e.minutes.includes(s)&&e.hours.includes(r)&&e.days.includes(i)&&e.months.includes(c)&&e.weekdays.includes(l))return new Date(n)}return new Date(n.getTime()+1440*60*1e3*366)}function JI(e){let t=(n,o,s)=>{if(n.length===s-o+1)return "*";if(n.length===1)return n[0].toString();let r=[...n],i=[],c=r[0],l=r[0];for(let d=1;d<r.length;d++)r[d]!==l+1&&(i.push(c===l?`${c}`:`${c}-${l}`),c=r[d]),l=r[d];return i.push(c===l?`${c}`:`${c}-${l}`),i.join(",")};return [t(e.minutes,0,59),t(e.hours,0,23),t(e.days,1,31),t(e.months,1,12),t(e.weekdays,0,6)].join(" ")}function YI(e){if(!Cr(e))return null;let n=e.trim().split(/\s+/);return n.length!==5?null:{minute:n[0]??"",hour:n[1]??"",day:n[2]??"",month:n[3]??"",weekday:n[4]??""}}function Gm(e){let t=YI(e);if(!t)return "Invalid cron expression";let n=[];if(t.minute==="*")n.push("every minute");else if(t.minute.startsWith("*/")){let o=t.minute.slice(2);n.push(`every ${o} minutes`);}else n.push(`at minute ${t.minute}`);if(t.hour!=="*")if(t.hour.startsWith("*/")){let o=t.hour.slice(2);n.push(`every ${o} hours`);}else n.push(`at hour ${t.hour}`);if(t.day!=="*"&&n.push(`on day ${t.day}`),t.month!=="*"){let o=["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=parseInt(t.month,10);!Number.isNaN(s)&&s>=1&&s<=12&&n.push(`in ${o[s]}`);}if(t.weekday!=="*"){let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=parseInt(t.weekday,10);!Number.isNaN(s)&&s>=0&&s<=6&&n.push(`on ${o[s]}`);}return n.join(" ")}var ZI=loadTextFile("./heartbeat.txt",import.meta.url),ev=loadTextFile("./scheduled.txt",import.meta.url),Qm=ZI(),Zm=ev(),Jm=a.create({service:"scheduler.history"}),tv=/\{\{([A-Z_]+)\}/g,Jl;(s=>{function e(r,i){return r.replace(tv,(c,l)=>t(l,i)??c)}s.render=e;function t(r,i){switch(r){case "TASK_ID":return i.taskId;case "TASK_NAME":return i.taskName;case "TASK_TYPE":return i.taskType;case "SESSION":return i.session;case "AGENT":return i.agent;case "MODEL":return i.model;case "TIME":return new Date().toISOString();case "TIME_LOCAL":return new Date().toLocaleString();case "TIMESTAMP":return String(Date.now());default:return}}s.resolveVariable=t;function n(r){let i={taskId:r.id,taskName:r.name,taskType:"heartbeat",session:r.session,agent:r.agent,model:r.model,timestamp:Date.now()};return s.render(Qm,i)}s.buildHeartbeatPrompt=n;function o(r,i){let c={taskId:r.id,taskName:r.name,taskType:"scheduled",agent:r.agentType,model:r.model,timestamp:Date.now()};return `${s.render(Zm,c)}
|
|
175
|
+
|
|
176
|
+
## User Request
|
|
177
|
+
|
|
178
|
+
${i}`}s.buildScheduledPrompt=o;})(Jl||(Jl={}));var nv="scheduler/history",Ym=100;function Tc(){return Se__default.join(a$1.Path.data,nv)}function Kl(e){let t=Tc(),n=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Se__default.join(t,`${n}.json`)}async function kr(e){try{return await access(e),!0}catch{return false}}async function ov(){let e=Tc();await kr(e)||await mkdir(e,{recursive:true});}var Ac;(i=>{async function e(c){await ov();let l=Kl(c.taskId),d=[];if(await kr(l))try{let f=await readFile(l,"utf-8");d=JSON.parse(f);}catch{d=[];}d.unshift(c),d.length>Ym&&(d=d.slice(0,Ym)),await writeFile(l,JSON.stringify(d,null,2)),Jm.debug("Task history record added",{taskId:c.taskId,success:c.success});}i.add=e;async function t(c,l){let d=Kl(c);if(!await kr(d))return [];try{let f=await readFile(d,"utf-8"),a=JSON.parse(f);return l?a.slice(0,l):a}catch{return []}}i.get=t;async function n(c){let l=Kl(c);await kr(l)&&await unlink(l);}i.clear=n;async function o(c){let l=Tc(),d=0,m=c?Date.now()-c:Date.now()-720*60*60*1e3;if(!await kr(l))return 0;let a=await readdir(l);for(let p of a){if(!p.endsWith(".json"))continue;let u=Se__default.join(l,p);try{let h=await readFile(u,"utf-8"),g=JSON.parse(h),I=g.filter(T=>T.endTime>m);I.length!==g.length&&(I.length===0?await unlink(u):await writeFile(u,JSON.stringify(I,null,2)),d+=g.length-I.length);}catch{}}return Jm.info("Task history pruned",{prunedCount:d}),d}i.prune=o;async function s(){let c=Tc(),l=0,d=0;if(!await kr(c))return {totalTasks:0,totalRecords:0,successRate:0};let f=await readdir(c);for(let a of f){if(!a.endsWith(".json"))continue;let p=Se__default.join(c,a);try{let u=await readFile(p,"utf-8"),h=JSON.parse(u);l+=h.length,d+=h.filter(g=>g.success).length;}catch{}}return {totalTasks:f.filter(a=>a.endsWith(".json")).length,totalRecords:l,successRate:l>0?d/l:0}}i.getStats=s;async function r(c){return (await t(c,1))[0]}i.getLastResult=r;})(Ac||(Ac={}));function sv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return `hist_${e}_${t}`}async function ts(e,t,n,o){let s={id:sv(),taskId:e,taskType:t,startTime:n,endTime:Date.now(),success:o.success,output:o.output,error:o.error};await Ac.add(s);}var at=a.create({service:"scheduler"});function Oo(e,t){let n=Cr(e);return n?Cc(n,new Date(t??Date.now())).getTime():0}var pn;(X=>{let e;function t(){return e||(e=R.state(async()=>(await Be.init(),{status:"stopped",timers:new Map,listeners:new Map,initialized:true}),async M=>{if(M){for(let A of M.timers.values())clearTimeout(A);M.timers.clear(),M.listeners.clear();}})),e}function n(){return t()()}X.state=n;async function o(){return (await n()).status}X.getStatus=o;async function s(){return (await n()).initialized}X.isInitialized=s;async function r(){let $=await n();if($.status==="running"){at.warn("Scheduler already running");return}at.info("Starting scheduler"),$.status="running";let M=await Be.getHeartbeats();for(let S of M)S.enabled&&C($,S);let A=await Be.getScheduled();for(let S of A)S.enabled&&E($,S);let L=await Be.getCommands();for(let S of L)S.enabled&&D($,S);at.info("Scheduler started",{heartbeats:M.length,scheduled:A.length,commands:L.length});}X.start=r;async function i(){let $=await n();if($.status==="running"){at.info("Stopping scheduler");for(let M of $.timers.values())clearTimeout(M);$.timers.clear(),$.status="stopped",at.info("Scheduler stopped");}}X.stop=i;function c($,M){return n().then(A=>{A.listeners.has($)||A.listeners.set($,new Set),A.listeners.get($).add(M);}),()=>{n().then(A=>{A.listeners.get($)?.delete(M);});}}X.onTaskComplete=c;async function l($){if(!es($.cron))throw new Error(`Invalid cron expression: ${$.cron}`);let A={id:$.id??Identifier.ascending("heartbeat"),name:$.name,cron:$.cron,type:"heartbeat",enabled:true,parts:$.parts,config:{session:$.session,mode:$.mode??"session",agentId:$.agentId,transport:$.transport,agentConfig:$.agentConfig},recurring:true,createdAt:Date.now(),updatedAt:Date.now(),nextFireAt:Oo($.cron,Date.now())};await Be.saveHeartbeat(A);let L=await n();return L.status==="running"&&A.enabled&&C(L,A),at.info("Heartbeat task created",{id:A.id,name:A.name}),A}X.createHeartbeat=l;async function d($){if(!es($.cron))throw new Error(`Invalid cron expression: ${$.cron}`);let M=$.id??Identifier.ascending("task"),A=Date.now(),L={id:M,name:$.name,cron:$.cron,type:"scheduled",enabled:true,parts:$.parts,agentType:$.agentType??"default",transport:$.transport??"stdio",agentConfig:$.agentConfig,recurring:$.recurring??true,durable:$.durable??true,createdAt:A,updatedAt:A,nextFireAt:Oo($.cron,A)};await Be.saveScheduled(L);let S=await n();return S.status==="running"&&L.enabled&&E(S,L),at.info("Scheduled task created",{id:L.id,name:L.name}),L}X.createScheduled=d;async function m($){if(!es($.cron))throw new Error(`Invalid cron expression: ${$.cron}`);let M=$.id??Identifier.ascending("command"),A=Date.now(),L={id:M,name:$.name,cron:$.cron,type:"command",enabled:true,config:{command:$.command,arguments:$.arguments,session:$.session,durable:$.durable},recurring:$.recurring??true,durable:$.durable??true,createdAt:A,updatedAt:A,nextFireAt:Oo($.cron,A)};await Be.saveCommand(L);let S=await n();return S.status==="running"&&L.enabled&&D(S,L),at.debug("Command task created",{id:L.id,name:L.name,command:L.config.command}),L}X.createCommand=m;async function f(){return Be.getHeartbeats()}X.listHeartbeats=f;async function a(){return Be.getScheduled()}X.listScheduled=a;async function p(){return Be.getCommands()}X.listCommands=p;async function u($){return Be.getHeartbeat($)}X.getHeartbeat=u;async function h($){return Be.getScheduledTask($)}X.getScheduled=h;async function g($){let M=await n();v(M,$),await Be.deleteHeartbeat($),at.info("Heartbeat task deleted",{id:$});}X.deleteHeartbeat=g;async function I($){let M=await n();v(M,$),await Be.deleteScheduled($),at.info("Scheduled task deleted",{id:$});}X.deleteScheduled=I;async function T($){let M=await Be.getHeartbeat($);if(!M)throw new Error(`Heartbeat task not found: ${$}`);await Be.updateHeartbeat($,{enabled:true});let A=await n();C(A,{...M,enabled:true}),at.debug("Heartbeat task enabled",{id:$});}X.enableHeartbeat=T;async function y($){let M=await n();v(M,$),await Be.updateHeartbeat($,{enabled:false}),at.info("Heartbeat task disabled",{id:$});}X.disableHeartbeat=y;async function x($){let M=await Be.getScheduledTask($);if(!M)throw new Error(`Scheduled task not found: ${$}`);await Be.updateScheduled($,{enabled:true});let A=await n();E(A,{...M,enabled:true}),at.info("Scheduled task enabled",{id:$});}X.enableScheduled=x;async function b($){let M=await n();v(M,$),await Be.updateScheduled($,{enabled:false}),at.info("Scheduled task disabled",{id:$});}X.disableScheduled=b;async function w($){let M=await Be.getHeartbeat($);if(!M)throw new Error(`Heartbeat task not found: ${$}`);return O(M)}X.triggerHeartbeat=w;async function k($){let M=await Be.getScheduledTask($);if(!M)throw new Error(`Scheduled task not found: ${$}`);return U(M)}X.triggerScheduled=k;function v($,M){let A=$.timers.get(M);A&&(clearTimeout(A),$.timers.delete(M));}function C($,M){v($,M.id);let A=(M.nextFireAt??Oo(M.cron))-Date.now(),L=Math.max(0,A);at.info("Scheduling heartbeat",{id:M.id,nextFireAt:M.nextFireAt,delay:L});let S=setTimeout(async()=>{try{let P=await O(M),_=$.listeners.get(M.id);if(_)for(let j of _)try{j(P);}catch(B){at.error("Task listener error",{taskId:M.id,error:B});}if(M.enabled&&M.recurring){let j=Oo(M.cron);await Be.updateHeartbeat(M.id,{lastFiredAt:Date.now(),nextFireAt:j});let B=await Be.getHeartbeat(M.id);B&&C($,{...B,nextFireAt:j});}}catch(P){at.error("Heartbeat execution failed",{id:M.id,error:P});}},L);S.unref(),$.timers.set(M.id,S);}function E($,M){v($,M.id);let A=(M.nextFireAt??Oo(M.cron))-Date.now(),L=Math.max(0,A);at.info("Scheduling task",{id:M.id,nextFireAt:M.nextFireAt,delay:L});let S=setTimeout(async()=>{try{let P=await U(M),_=$.listeners.get(M.id);if(_)for(let j of _)try{j(P);}catch(B){at.error("Task listener error",{taskId:M.id,error:B});}if(M.enabled&&(M.recurring??!0)){let j=Oo(M.cron);await Be.updateScheduled(M.id,{lastFiredAt:Date.now(),nextFireAt:j});let B=await Be.getScheduledTask(M.id);B&&E($,{...B,nextFireAt:j});}}catch(P){at.error("Scheduled task execution failed",{id:M.id,error:P});}},L);S.unref(),$.timers.set(M.id,S);}async function O($){let M=Date.now(),A={type:"heartbeat",parts:$.parts,system:$.config.agentConfig?.system,config:{session:$.config.session,mode:$.config.mode,agent:$.config.agentId,model:$.config.agentConfig?.model,tools:$.config.agentConfig?.tools}},L={sessionId:$.config.session,agent:$.config.agentId,model:$.config.agentConfig?.model},S={taskId:$.id,taskName:$.name,sessionId:$.config.session,mode:$.config.mode,definition:A,context:L};try{at.debug("Executing heartbeat",{id:$.id,mode:$.config.mode});let j=(await Le.triggerEvent(HookEvent.HeartbeatTrigger,S,L)).output?.execution;if(!j)throw new Error(`No heartbeat hook handled event: ${HookEvent.HeartbeatTrigger}`);return await ts($.id,"heartbeat",M,j),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:$.id,taskName:$.name,success:j.success,output:j.output,error:j.error,duration:Date.now()-M},L),{taskId:$.id,success:j.success,output:j.output,error:j.error,executedAt:M,duration:Date.now()-M}}catch(P){at.error("Heartbeat execution error",{id:$.id,error:P});let _={success:false,error:P instanceof Error?P.message:String(P)};return await ts($.id,"heartbeat",M,_),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:$.id,taskName:$.name,success:false,error:P instanceof Error?P.message:String(P),duration:Date.now()-M},L),{taskId:$.id,success:false,error:P instanceof Error?P.message:String(P),executedAt:M,duration:Date.now()-M}}}async function U($){let M=Date.now(),A={type:"scheduler",parts:$.parts,system:$.agentConfig?.system,config:{agentType:$.agentType,transport:$.transport,model:$.agentConfig?.model,tools:$.agentConfig?.tools}},L={agent:$.agentType,model:$.agentConfig?.model},S={taskId:$.id,taskName:$.name,agentType:$.agentType,transport:$.transport,definition:A,context:L};try{at.debug("Executing scheduled task",{id:$.id,agentType:$.agentType});let j=(await Le.triggerEvent(HookEvent.ScheduledTaskTrigger,S,L)).output?.execution;if(!j)throw new Error(`No scheduler hook handled event: ${HookEvent.ScheduledTaskTrigger}`);return await ts($.id,"scheduled",M,j),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:$.id,taskName:$.name,success:j.success,output:j.output,error:j.error,duration:Date.now()-M},L),{taskId:$.id,success:j.success,output:j.output,error:j.error,executedAt:M,duration:Date.now()-M}}catch(P){at.error("Scheduled task execution error",{id:$.id,error:P});let _={success:false,error:P instanceof Error?P.message:String(P)};return await ts($.id,"scheduled",M,_),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:$.id,taskName:$.name,success:false,error:P instanceof Error?P.message:String(P),duration:Date.now()-M},L),{taskId:$.id,success:false,error:P instanceof Error?P.message:String(P),executedAt:M,duration:Date.now()-M}}}function D($,M){v($,M.id);let A=(M.nextFireAt??Oo(M.cron))-Date.now(),L=Math.max(0,A);at.debug("Scheduling command task",{id:M.id,nextFireAt:M.nextFireAt,delay:L});let S=setTimeout(async()=>{try{let P=await K(M),_=$.listeners.get(M.id);if(_)for(let j of _)try{j(P);}catch(B){at.error("Task listener error",{taskId:M.id,error:B});}if(M.enabled&&(M.recurring??!0)){let j=Oo(M.cron);await Be.updateCommand(M.id,{lastFiredAt:Date.now(),nextFireAt:j});let B=await Be.getCommand(M.id);B&&D($,{...B,nextFireAt:j});}}catch(P){at.error("Command task execution failed",{id:M.id,error:P});}},L);S.unref(),$.timers.set(M.id,S);}async function K($){let M=Date.now();at.debug("Executing command task",{id:$.id,command:$.config.command});try{let A=await Je.command({sessionId:$.config.session??"scheduler",command:$.config.command,arguments:$.config.arguments??""}),L={success:!A.error,output:A.output,error:A.error};return await ts($.id,"command",M,L),{taskId:$.id,success:L.success,output:L.output,error:L.error,executedAt:M,duration:Date.now()-M}}catch(A){at.error("Command task execution error",{id:$.id,error:A});let L={success:false,error:A instanceof Error?A.message:String(A)};return await ts($.id,"command",M,L),{taskId:$.id,success:false,error:A instanceof Error?A.message:String(A),executedAt:M,duration:Date.now()-M}}}})(pn||(pn={}));function rv(e){let t={};if(typeof e=="string"){let n=e.trim().split(/\s+/);n.length>0&&(t.subcommand=n[0],t.name=n[1]);for(let o=2;o<n.length;o++){let s=n[o];s==="--cron"&&o+1<n.length?t.cron=n[++o]:s==="--type"&&o+1<n.length?t.type=n[++o]:s==="--session"&&o+1<n.length?t.session=n[++o]:s==="--mode"&&o+1<n.length?t.mode=n[++o]:s==="--prompt"&&o+1<n.length?t.prompt=n[++o]:s==="--agent-type"&&o+1<n.length?t.agentType=n[++o]:s==="--transport"&&o+1<n.length?t.transport=n[++o]:s==="--recurring"?t.recurring=true:s==="--durable"&&(t.durable=true);}}return t}function ef(e,t){let n=["Tasks:"];if(e.length>0){n.push(`
|
|
179
|
+
Heartbeats:`),n.push("ID | Name | Cron | Session | Mode | Enabled"),n.push("------------------|---------------|---------------|---------|---------|--------");for(let o of e)n.push(`${o.id.padEnd(17)}| ${o.name.padEnd(12)}| ${o.cron.padEnd(12)}| ${o.config.session.padEnd(7)}| ${o.config.mode.padEnd(7)}| ${o.enabled}`);}else n.push(`
|
|
180
|
+
Heartbeats: (none)`);if(t.length>0){n.push(`
|
|
181
|
+
Scheduled:`),n.push("ID | Name | Cron | Agent Type | Recurring | Durable"),n.push("------------------|---------------|---------------|------------|-----------|--------");for(let o of t)n.push(`${o.id.padEnd(17)}| ${o.name.padEnd(12)}| ${o.cron.padEnd(12)}| ${(o.agentType||"default").padEnd(11)}| ${(o.recurring?"yes":"no").padEnd(7)}| ${o.durable?"yes":"no"}`);}else n.push(`
|
|
182
|
+
Scheduled: (none)`);return n.join(`
|
|
183
|
+
`)}var Xl=f("loop",{description:"Create and manage scheduled tasks and heartbeats",source:"command",commandType:"local",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=rv(e);if(!n.subcommand)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:Pr(),success:true,parts:[{type:"text",text:Pr()}]};switch(n.subcommand){case "create":return iv(n,t);case "list":return av(t);case "delete":return cv(n,t);case "enable":return dv(n,t);case "disable":return lv(n,t);case "trigger":return uv(n,t);case "help":return {title:"Loop Command Help",metadata:{sessionId:t.sessionId},output:Pr(),success:true,parts:[{type:"text",text:Pr()}]};default:return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Unknown subcommand: ${n.subcommand}
|
|
184
|
+
|
|
185
|
+
${Pr()}`,success:true,parts:[{type:"text",text:Pr()}]}}},init:async()=>({})});async function iv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task name is required
|
|
186
|
+
|
|
187
|
+
Usage: /loop create <name> --cron <expression> [options]`,success:false,parts:[{type:"text",text:"Error: Task name is required"}]};if(!e.cron)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Cron expression is required
|
|
188
|
+
|
|
189
|
+
Usage: /loop create <name> --cron <expression> [options]`,success:false,parts:[{type:"text",text:"Error: Cron expression is required"}]};if(!es(e.cron))return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Invalid cron expression: ${e.cron}`,success:false,parts:[{type:"text",text:`Error: Invalid cron expression: ${e.cron}`}]};if((e.type??"heartbeat")==="heartbeat"){if(!e.session)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Session is required for heartbeat tasks
|
|
190
|
+
|
|
191
|
+
Usage: /loop create <name> --cron <expression> --session <session-name> --type heartbeat`,success:false,parts:[{type:"text",text:"Error: Session is required for heartbeat tasks"}]};try{let o=await pn.createHeartbeat({name:e.name,cron:e.cron,session:e.session,mode:e.mode,agentId:e.agentType,transport:e.transport,parts:[{type:"text",text:e.prompt??`Heartbeat: ${e.name}`}]});return {title:"Heartbeat Created",metadata:{sessionId:t.sessionId},output:`Heartbeat task created successfully!
|
|
192
|
+
|
|
193
|
+
ID: ${o.id}
|
|
194
|
+
Name: ${o.name}
|
|
195
|
+
Cron: ${o.cron}
|
|
196
|
+
Session: ${o.config.session}
|
|
197
|
+
Mode: ${o.config.mode}
|
|
198
|
+
Next Fire: ${new Date(o.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Heartbeat task created: ${o.id}`}]}}catch(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating heartbeat: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}if(!e.prompt)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Prompt is required for scheduled tasks
|
|
199
|
+
|
|
200
|
+
Usage: /loop create <name> --cron <expression> --prompt <text> --type scheduled`,success:false,parts:[{type:"text",text:"Error: Prompt is required for scheduled tasks"}]};try{let o=await pn.createScheduled({name:e.name,cron:e.cron,parts:[{type:"text",text:e.prompt}],agentType:e.agentType??"default",transport:e.transport??"stdio",recurring:e.recurring??!0,durable:e.durable??!0});return {title:"Scheduled Task Created",metadata:{sessionId:t.sessionId},output:`Scheduled task created successfully!
|
|
201
|
+
|
|
202
|
+
ID: ${o.id}
|
|
203
|
+
Name: ${o.name}
|
|
204
|
+
Cron: ${o.cron}
|
|
205
|
+
Agent Type: ${o.agentType}
|
|
206
|
+
Recurring: ${o.recurring}
|
|
207
|
+
Next Fire: ${new Date(o.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Scheduled task created: ${o.id}`}]}}catch(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating scheduled task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}async function av(e){try{let t=await pn.listHeartbeats(),n=await pn.listScheduled();return {title:"Task List",metadata:{sessionId:e.sessionId},output:ef(t,n),success:!0,parts:[{type:"text",text:ef(t,n)}]}}catch(t){return {title:"Loop Command",metadata:{sessionId:e.sessionId},output:`Error listing tasks: ${t instanceof Error?t.message:String(t)}`,success:false,parts:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}]}}}async function cv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
|
|
208
|
+
|
|
209
|
+
Usage: /loop delete <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await pn.deleteHeartbeat(e.name).catch(()=>pn.deleteScheduled(e.name)),{title:"Task Deleted",metadata:{sessionId:t.sessionId},output:`Task deleted: ${e.name}`,success:!0,parts:[{type:"text",text:`Task deleted: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error deleting task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function dv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
|
|
210
|
+
|
|
211
|
+
Usage: /loop enable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await pn.enableHeartbeat(e.name).catch(()=>pn.enableScheduled(e.name)),{title:"Task Enabled",metadata:{sessionId:t.sessionId},output:`Task enabled: ${e.name}`,success:!0,parts:[{type:"text",text:`Task enabled: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error enabling task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function lv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
|
|
212
|
+
|
|
213
|
+
Usage: /loop disable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await pn.disableHeartbeat(e.name).catch(()=>pn.disableScheduled(e.name)),{title:"Task Disabled",metadata:{sessionId:t.sessionId},output:`Task disabled: ${e.name}`,success:!0,parts:[{type:"text",text:`Task disabled: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error disabling task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function uv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
|
|
214
|
+
|
|
215
|
+
Usage: /loop trigger <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{let n=await pn.triggerHeartbeat(e.name).catch(()=>pn.triggerScheduled(e.name));return {title:"Task Triggered",metadata:{sessionId:t.sessionId},output:n.success?`Task triggered successfully!
|
|
216
|
+
|
|
217
|
+
Output: ${n.output||"(no output)"}`:`Task failed: ${n.error}`,success:n.success,parts:[{type:"text",text:n.success?`Task executed: ${n.output||"(no output)"}`:`Task failed: ${n.error}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error triggering task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}function Pr(){return `Loop Command - Create and manage scheduled tasks and heartbeats
|
|
218
|
+
|
|
219
|
+
Usage:
|
|
220
|
+
/loop <subcommand> [options]
|
|
221
|
+
|
|
222
|
+
Subcommands:
|
|
223
|
+
create <name> --cron <expression> [options]
|
|
224
|
+
Create a scheduled task or heartbeat
|
|
225
|
+
|
|
226
|
+
list
|
|
227
|
+
List all tasks
|
|
228
|
+
|
|
229
|
+
delete <id>
|
|
230
|
+
Delete a task
|
|
231
|
+
|
|
232
|
+
enable <id>
|
|
233
|
+
Enable a task
|
|
234
|
+
|
|
235
|
+
disable <id>
|
|
236
|
+
Disable a task
|
|
237
|
+
|
|
238
|
+
trigger <id>
|
|
239
|
+
Manually trigger a task
|
|
240
|
+
|
|
241
|
+
help
|
|
242
|
+
Show this help message
|
|
243
|
+
|
|
244
|
+
Options:
|
|
245
|
+
--cron <expr> Cron expression (required)
|
|
246
|
+
--type <type> Task type: heartbeat (default) | scheduled
|
|
247
|
+
--session <name> Session name (heartbeat required)
|
|
248
|
+
--mode <mode> Mode: session (default) | fork
|
|
249
|
+
--prompt <text> Prompt (scheduled required)
|
|
250
|
+
--agent-type <type> Agent type (default: default)
|
|
251
|
+
--transport <type> Transport: stdio (default) | http | websocket | cli
|
|
252
|
+
--recurring Recurring execution
|
|
253
|
+
--durable Persistent storage
|
|
254
|
+
|
|
255
|
+
Cron Expression Format:
|
|
256
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0-59)
|
|
257
|
+
\u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0-23)
|
|
258
|
+
\u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day (1-31)
|
|
259
|
+
\u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 month (1-12)
|
|
260
|
+
\u2502 \u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 weekday (0-6, 0=Sun)
|
|
261
|
+
\u2502 \u2502 \u2502 \u2502 \u2502
|
|
262
|
+
* * * * *
|
|
263
|
+
|
|
264
|
+
Examples:
|
|
265
|
+
/loop create main-heartbeat --cron "*/5 * * * *" --session main --type heartbeat
|
|
266
|
+
/loop create hourly-sync --cron "0 * * * *" --prompt "Sync data" --type scheduled
|
|
267
|
+
/loop list
|
|
268
|
+
/loop delete hb_xxx
|
|
269
|
+
/loop enable st_xxx
|
|
270
|
+
/loop trigger hb_xxx
|
|
271
|
+
`}var Ql=f("cleanup",{description:"Internal cleanup command for truncating old files",source:"command",commandType:"local",subtask:false,hidden:true,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=[],o=[];if(typeof e=="string"&&e.includes("truncation"))try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(r){o.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("snapshot"))try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(r){o.push(`Snapshot cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("all")){try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(r){o.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(r){o.push(`Snapshot cleanup failed: ${r instanceof Error?r.message:String(r)}`);}}if(typeof e=="object"&&e!==null){let r=e;if(r.type==="truncation"||r.target==="truncation")try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(i){o.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(r.type==="snapshot"||r.target==="snapshot")try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(i){o.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(!r.type&&!r.target){try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(i){o.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(i){o.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}}}let s=[...n,...o].join(`
|
|
272
|
+
`);return {title:"Cleanup Command",metadata:{sessionId:t.sessionId,success:o.length===0,cleaned:n.length,errors:o.length},output:s,success:o.length===0,parts:[{type:"text",text:s}]}},init:async()=>({})});var In;(f=>{let e=a.create({service:"knowledge.memory"}),t;async function n(a){let p=await he.get(),u=a?.embedding?.model||p.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:h,model:g}=parseModelId(u),I=h||"easbot-local",T=g||"bge-base-zh-v1.5",y=await xe.getEmbedding(I,T),x=a?.graph?.model||p.graph_model,b,w;if(x){let{provider:v,model:C}=parseModelId(x);b=v||"easbot-local",w=C||x;}else {let v=await xe.defaultModel();b=v.providerId,w=v.modelId;}let k;try{let v=await xe.getModel(b,w);k=await xe.getLanguage(v);}catch(v){e.error("memory loadModels graphLlm failed",{graphProvider:b,graphModel:w,error:String(v)});}return {embeddingLlm:y,graphLlm:k}}function o(){return t||(t=R.state(async()=>{let a$1=await sr();if(!a$1||a$1.enabled===false)return {system:null,config:null,rootDir:"",initialized:true};let{Global:p}=await import('./global-5WFCDQ45.mjs'),u=R.directory,h=Filesystem.normalize(a$1?.workspaceDir?Se__default.isAbsolute(a$1.workspaceDir)?a$1.workspaceDir:Se__default.resolve(u,a$1.workspaceDir):Se__default.join(u,".easbot","memory")),g=Filesystem.normalize(a$1?.database?Se__default.isAbsolute(a$1.database)?a$1.database:Se__default.resolve(u,a$1.database):Se__default.join(R.worktree,".easbot","db","memory.db")),{embeddingLlm:I,graphLlm:T}=await n(a$1);return await initLog({logDir:p.Path.log,logFile:"memory.log",level:a.getLevel(),print:false}),{system:await createMemorySystem({workspaceDir:h,database:{path:g,walMode:true},sessionsDir:a$1?.sessionsDir,archiveDays:a$1?.archiveDays,shortTermMaxRounds:a$1?.shortTermMaxRounds,search:{maxResults:a$1?.search?.maxResults??5,minScore:a$1?.search?.minScore??.1,hybrid:{enabled:a$1?.search?.hybrid?.enabled??true,vectorWeight:a$1?.search?.hybrid?.vectorWeight??.7,textWeight:a$1?.search?.hybrid?.textWeight??.3}},embeddingLlm:I,graphLlm:T}),config:a$1??null,rootDir:h,initialized:true}},async a=>{a.system&&await a?.system?.close().catch(()=>{});})),t}function s(){return o()()}f.state=s;async function r(){return (await s()).system}f.get=r;async function i(){return (await s()).rootDir}f.rootDir=i;async function c(){return (await s()).system!==null}f.isEnabled=c;async function l(){return (await s()).config}f.config=l;async function d(){return (await s()).initialized}f.isInitialized=d;async function m(){(await r())?.sync().catch(p=>e.warn("memory sync failed",{error:String(p)}));}f.sync=m;})(In||(In={}));var jo;(p=>{let e=a.create({service:"knowledge.codebase"}),t;async function n(u){let h=await he.get(),g=u?.embedding?.model||h.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:I,model:T}=parseModelId(g),y=I||"easbot-local",x=T||"bge-base-zh-v1.5";try{return await xe.getEmbedding(y,x)}catch(b){return e.warn("failed to load embedding model, using easbot-local/bge-base-zh-v1.5",{error:b}),xe.getEmbedding("easbot-local","bge-base-zh-v1.5")}}function o(){return t||(t=R.state(async()=>{let u=await or();if(!u||u.enabled===false)return {codebase:null,config:null,rootDir:"",initialized:true};let{Global:h}=await import('./global-5WFCDQ45.mjs'),g=Filesystem.normalize(R.worktree??R.directory),I=Filesystem.normalize(u.database?Se__default.isAbsolute(u.database)?u.database:Se__default.resolve(g,u.database):Se__default.join(R.worktree,".easbot","db","codebase.db")),T=await n(u);await initLog$1({logDir:h.Path.log,logFile:"codebase.log",level:a.getLevel(),print:false});let y=await createCodebase({workspaceDir:g,database:{path:I,walMode:true},search:u.search?{maxResults:u.search.maxResults??3,minScore:u.search.minScore??.1,hybrid:{enabled:u.search.hybrid?.enabled??true,vectorWeight:u.search.hybrid?.vectorWeight??.7,textWeight:u.search.hybrid?.textWeight??.3}}:void 0,parser:u.parser?{languages:u.parser.languages,lazyLoad:u.parser.lazyLoad}:void 0,indexer:{batchSize:u.indexer?.batchSize??50,ignorePatterns:[...Glob.DEFAULT_IGNORE_PATTERNS,...u.indexer?.ignorePatterns??[],...(await Glob.parseGitignore(Se__default.join(R.worktree,".gitignore"))).filter(x=>!x.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,embeddingLlm:T});return u.sync?.onBoot&&await y.sync().catch(x=>e.warn("codebase sync on boot failed",{error:String(x)})),{codebase:y,config:u,rootDir:g,initialized:true}},async u=>{u.codebase&&await u?.codebase?.close().catch(()=>{});})),t}function s(){return o()()}p.state=s;async function r(){return (await s()).codebase}p.get=r;async function i(){return (await s()).rootDir}p.rootDir=i;async function c(){return (await s()).codebase!==null}p.isEnabled=c;async function l(){return (await s()).config}p.config=l;async function d(){return (await s()).initialized}p.isInitialized=d;async function m(){let u=await r();u&&u.sync().catch(h=>e.warn("codebase sync failed",{error:String(h)}));}p.sync=m;async function f(){let u=await r();return u?u.getStatus():null}p.status=f;async function a$1(){let u=await r();if(!u)return {healthy:false,issues:["Codebase knowledge base is not enabled"]};let h=await u.healthCheck();return {healthy:h.healthy,issues:h.issues}}p.healthCheck=a$1;})(jo||(jo={}));async function yv(e){let t,n;switch(e){case "note":t=await Yt.isEnabled(),n=()=>Yt.sync();break;case "codebase":t=await jo.isEnabled(),n=()=>jo.sync();break;case "memory":t=await In.isEnabled(),n=()=>In.sync();break}return t?(n().catch(o=>{console.error(`${e} sync failed:`,o);}),{target:e,started:true,message:`${e} sync started`}):{target:e,started:false,message:`${e} not enabled`}}function bv(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>["note","codebase","memory"].includes(t))}var Zl=f("sync",{description:"Sync knowledge bases (note, codebase, memory)",source:"command",commandType:"local",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=bv(e),o=n.length>0?n:["note","codebase","memory"],s=await Promise.all(o.map(d=>yv(d))),r=s.filter(d=>d.started),i=s.filter(d=>!d.started),c=[];r.length>0&&c.push(`\u2713 Started: ${r.map(d=>d.target).join(", ")}`),i.length>0&&c.push(`\u2298 Skipped: ${i.map(d=>d.target).join(", ")}`);let l=c.join(`
|
|
273
|
+
`);return {title:"Knowledge Base Sync",metadata:{sessionId:t.sessionId,success:i.length===0,started:r.length,skipped:i.length},output:l,success:i.length===0,parts:[{type:"text",text:l}]}},init:async()=>({})});var Pv=["BOOT.md","IDENTITY.md","SOUL.md","USER.md","AGENTS.md","TOOLS.md","CONTEXT.md","CODER.md"];function rf(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return `${t}-${n}-${o}`}async function af(e){try{return await access(e,constants.F_OK),!0}catch{return false}}async function Tv(e,t,n){let o={backedUpFiles:[],cleanedOldBackups:0},s=rf(),r=join(t,s);await mkdir(r,{recursive:true});for(let i of Pv){let c=join(e,i),l=join(r,i);await af(c)&&(await copyFile(c,l),o.backedUpFiles.push(i));}if(n>0){let i=new Date;i.setDate(i.getDate()-n);try{let c=await readdir(t);for(let l of c){if(l===s)continue;let d=join(t,l),m=await stat(d);m.isDirectory()&&m.mtime<i&&(await rm$1(d,{recursive:!0,force:!0}),o.cleanedOldBackups++);}}catch{}}return o}var eu=f("backup",{description:"Backup agent configuration files to Global.Path.data/backup/yyyy-mm-dd/",source:"command",commandType:"local",subtask:false,hidden:true,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=[],o=[],s=".easbot",r=30;if(typeof e=="string"){let c=e.split(" ");for(let l of c)if(l.startsWith("config-path=")){let d=l.split("=")[1];d&&(s=d);}else if(l.startsWith("retention-days=")){let d=l.split("=")[1];d&&(r=parseInt(d,10)||30);}}else if(typeof e=="object"&&e!==null){let c=e;s=c.configPath||s,r=c.retentionDays||r;}try{await a$1.init();let c=join(a$1.Path.data,"backup");if(!await af(s))n.push(`Config directory not found: ${s}`);else {let d=await Tv(s,c,r);n.push(`Backup completed to: ${join(c,rf())}`),n.push(`Backed up files: ${d.backedUpFiles.length}`),d.backedUpFiles.length>0&&n.push(`Files: ${d.backedUpFiles.join(", ")}`),d.cleanedOldBackups>0&&n.push(`Cleaned old backups: ${d.cleanedOldBackups}`);}}catch(c){o.push(`Backup failed: ${c instanceof Error?c.message:String(c)}`);}let i=[...n,...o].join(`
|
|
274
|
+
`);return {title:"Backup Command",metadata:{sessionId:t.sessionId,success:o.length===0,backedUpFiles:n.filter(c=>c.includes("Backed up files:")).length,errors:o.length},output:i,success:o.length===0,parts:[{type:"text",text:i}]}},init:async()=>({})});var cf=a.create({service:"command-abort"});function tu(e,t,n,o={}){let s={title:"Abort",metadata:{sessionId:e,...o},output:n,parts:[{type:"text",text:n}],success:t};return t?s:{...s,error:n}}var nu=f("abort",{description:"Abort the currently running agent task",source:"command",commandType:"local",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{sessionId:n}=t;cf.debug("Abort command executed",{sessionId:n});try{return (await Mt.get(n))?.type!=="busy"?tu(n,!0,"\u2298 No active task to abort",{aborted:!1,reason:"no_active_task"}):(await tn.abortSession(n),tu(n,!0,`\u2713 Abort signal sent
|
|
275
|
+
|
|
276
|
+
The agent will stop after completing its current action.`,{aborted:!0}))}catch(o){let s=o instanceof Error?o.message:String(o);return cf.error("Failed to abort session",{sessionId:n,error:s}),tu(n,false,`\u2298 Failed to abort: ${s}`,{error:s})}},init:async()=>({})});var tn={};a$7(tn,{abort:()=>Uv,abortSession:()=>mf,create:()=>Fv,createSession:()=>uf,deleteSession:()=>Av,fork:()=>Nv,forkSession:()=>pf,formatSessionJSON:()=>Lv,formatSessionTable:()=>jv,get:()=>$v,getSession:()=>lf,getSessionChildren:()=>Rv,getSessionContextMode:()=>Mv,getSessionStatus:()=>qv,initSession:()=>_v,list:()=>Dv,listSessionStatuses:()=>Hv,listSessions:()=>df,setSessionContextMode:()=>Ov,summarize:()=>zv,summarizeSession:()=>Rc,updateSession:()=>Ev});async function df(e){let t=[];for await(let o of Y.list())!o.parentId&&(!e?.directory||o.directory===e.directory)&&t.push(o);t.sort((o,s)=>s.time.updated-o.time.updated);let n=e?.limit;return !n||n<=0?t:t.slice(0,n)}async function lf(e){return Y.get(e)}async function uf(e){return Y.create(e)}async function pf(e,t,n){return Y.fork({sessionId:e,messageId:t,directory:n})}async function Av(e){await Y.remove(e);}async function mf(e){let{SessionPrompt:t}=await import('./prompt-XYHKPB7Q.mjs');await t.cancel(e);}async function Rc(e){let[{SessionPrompt:t},{Compaction:n},{SessionRevert:o}]=await Promise.all([import('./prompt-XYHKPB7Q.mjs'),import('./compaction-R4RTVEDY.mjs'),import('./revert-7RBPZDWL.mjs')]),s=e.sessionId,r=await Y.get(s);if(!r)throw new Error("session not found");await o.cleanup(r);let i;return e.providerId&&e.modelId&&(i={providerId:e.providerId,modelId:e.modelId}),await n.create({sessionId:s,model:i,agent:e.agent??"compaction",auto:e.auto??false}),await t.loop({sessionId:s}),true}async function Ev(e,t){let n=await Y.get(e);if(!n)throw new Error("session not found");t.title&&(n.title=t.title),t.time?.archived&&(n.time.archived=t.time.archived);let{Storage:o}=await import('./storage-6F64537E.mjs'),{Instance:s}=await import('./instance-YVRWMB6M.mjs');return await o.write(["session",s.project.id,e],n),n}async function Rv(e){return Y.children(e)}async function _v(e){return true}async function Mv(e){return Y.getContextMode(e)}async function Ov(e,t){await Y.setContextMode(e,t);}function jv(e,t=20,n=25){let o=[],s=Math.max(t,...e.map(c=>c.id.length)),r=Math.max(n,...e.map(c=>c.title.length)),i=`Session ID${" ".repeat(s-10)} Title${" ".repeat(r-5)} Updated`;o.push(i),o.push("\u2500".repeat(i.length));for(let c of e){let l=c.title.length>r?c.title.slice(0,r-3)+"...":c.title,d=new Date(c.time.updated).toLocaleString(),m=`${c.id.padEnd(s)} ${l.padEnd(r)} ${d}`;o.push(m);}return o.join(`
|
|
277
|
+
`)}function Lv(e){let t=e.map(n=>({id:n.id,title:n.title,updated:n.time.updated,created:n.time.created,projectId:n.providerId,directory:n.directory}));return JSON.stringify(t,null,2)}var Dv=df,$v=lf,Fv=uf,Nv=pf,Uv=mf,zv=Rc;async function qv(e){return Mt.get(e)}async function Hv(){return Mt.list()}var ff=a.create({service:"command-compact"});function gf(e,t,n,o={}){let s={title:"Compact",metadata:{sessionId:e,...o},output:n,parts:[{type:"text",text:n}],success:t};return t?s:{...s,error:n}}var ou=f("compact",{description:"Compact context by summarizing old messages",source:"command",commandType:"local",agent:"compaction",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{sessionId:n}=t;ff.debug("Compact command executed",{sessionId:n});try{return await Rc({sessionId:n,agent:"compaction"}),gf(n,!0,`\u2713 Context compaction started
|
|
278
|
+
|
|
279
|
+
Summarization is running in the background.`)}catch(o){let s=o instanceof Error?o.message:String(o);return ff.error("Failed to start compact",{sessionId:n,error:s}),gf(n,false,`\u2298 Failed to start compaction: ${s}`,{error:s})}},init:async()=>({})});var hf=[zl,ql,Hl,Bl,Gl,Wl,Xl,Ql,Zl,eu,nu,ou];var wf=a.create({service:"command.registry"}),vn;(T=>{T.Info=N.object({name:N.string(),description:N.string().optional(),agent:N.string().optional(),model:N.string().optional(),source:N.enum(["command","mcp","skill"]).optional(),subtask:N.boolean().optional(),hints:N.array(N.string()).optional(),commandType:N.enum(["prompt","local"]).optional(),isHidden:N.boolean().optional(),isEnabled:N.any().optional(),execute:N.any()}).meta({ref:"Command"}),T.Default={INIT:"init",REVIEW:"review",BTW:"btw"},T.Event={Executed:a$5.define("command.executed",N.object({name:N.string(),sessionId:Identifier.schema("session"),arguments:N.union([N.string(),N.record(N.string(),N.unknown())]),messageId:Identifier.schema("message")}))},T.define=f;let s,r;async function i(y){let x={};return y.init&&await y.init(x),{name:y.name,description:y.description,agent:y.agent,model:y.model,source:y.source,subtask:y.subtask,hints:y.hints,commandType:y.commandType,isEnabled:y.isEnabled,scope:y.scope??"all",hidden:y.hidden,execute:y.execute}}async function c(y){let{glob:x}=await import('glob'),b={};if(!await Filesystem.isDir(y))return b;let w=await x("*.md",{cwd:y,absolute:true,nodir:true,follow:false,dot:false});for(let k of w)try{let{ConfigMarkdown:v}=await import('./markdown-Z6UXVBNP.mjs'),C=await v.parse(k),{CommandMetadataSchema:E}=await import('@easbot/plugin'),O=E.parse(C.data),U=c$3(O,C.content,"command");b[U.name]=U;}catch(v){wf.error("Failed to load command file",{file:k,error:v});}return b}function l(){return s||(s=R.state(async()=>{let y=await he.get(),x={};for(let b of hf){let w=await i(b);x[b.name]=w;}for(let[b,w]of Object.entries(y.command??{})){let k=typeof w.template=="string"?w.template:"";x[b]={name:b,agent:w.agent,model:w.model,scope:w.scope??"all",description:w.description,source:"command",subtask:w.subtask,hints:/\{\{ARGUMENTS\}\}/i.test(k)?["{{ARGUMENTS}}"]:[],commandType:"prompt",isEnabled:()=>true,execute:async(v,C)=>{let{replaceTemplateVars:E}=await import('./command-CJGBEATT.mjs'),O=E(k,v);return {title:b,metadata:{sessionId:C.sessionId},output:O,success:true,parts:[{type:"text",text:O}]}}};}for(let[b,w]of Object.entries(await ze.prompts()))x[b]={name:b,source:"mcp",scope:w.scope??"all",description:w.description,commandType:"prompt",hints:w.arguments?.map((k,v)=>`$${v+1}`)??[],isEnabled:()=>true,execute:async k=>{if(typeof k=="string"){let O=(k.match(/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi)??[]).map(X=>X.replace(/^["']|["']$/g,"")),U=w.arguments?Object.fromEntries(w.arguments.map((X,$)=>[X.name,O[$]??""])):{},K=(await ze.getPrompt(w.client,w.name,U))?.messages.map(X=>X.content.type==="text"?X.content.text:"").join(`
|
|
280
|
+
`)||"";return {title:b,metadata:{},output:K,success:true,parts:[{type:"text",text:K}]}}let C=(await ze.getPrompt(w.client,w.name,k))?.messages.map(E=>E.content.type==="text"?E.content.text:"").join(`
|
|
281
|
+
`)||"";return {title:b,metadata:{},output:C,success:true,parts:[{type:"text",text:C}]}}};for(let b of await Vt.all())x[b.name]={name:b.name,description:b.description,source:"skill",commandType:"prompt",hints:[],scope:b.scope??"all",isEnabled:()=>true,execute:async(w,k)=>({title:b.name,metadata:{sessionId:k.sessionId},output:b.content,success:true,parts:[{type:"text",text:b.content}]})};if(r)for(let[b,w]of Object.entries(r))x[b]=w;for await(let b of Filesystem.up({targets:[".easbot/commands"],start:R.directory,stop:R.worktree})){let w=await c(b);for(let[k,v]of Object.entries(w))x[k]||(x[k]=v);}return x})),s}async function d(){return l()()}T.state=d;async function m(){return d()}T.all=m;async function f$1(y){return d().then(x=>x[y])}T.get=f$1;async function a(y){let x=await d(),b=y??"general",w=[];for(let k of Object.values(x)){let v=k.scope??"all";v!=="all"&&v!==b||k.isEnabled&&!await k.isEnabled()||w.push(k);}return w}T.list=a;async function p(y,x){r||(r=await d()),r[y]=x,h();}T.register=p;async function u(y){return r?.[y]?(delete r[y],h(),true):false}T.unregister=u;function h(){s=void 0;}async function g(){r=void 0,h(),await d();}T.refresh=g;async function I(){await d(),wf.debug("command registry initialized");}T.init=I;})(vn||(vn={}));var su=vn;var Sf=a$5.define("command.executed",N.object({name:N.string(),sessionId:N.string(),arguments:N.union([N.string(),N.record(N.string(),N.unknown())]),messageId:N.string().optional()})),Cf=a.create({service:"command.executor"});N.object({sessionId:Identifier.schema("session"),agent:N.string(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),command:N.string()});N.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:N.string().optional(),model:N.string().optional(),arguments:N.union([N.string(),N.record(N.string(),N.unknown())]),command:N.string(),variant:N.string().optional(),parts:N.array(N.discriminatedUnion("type",[ve.TextPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"TextPartInput"}),ve.FilePart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"FilePartInput"})])).optional()});var Kv=/!`([^`]+)`/g;async function _c(e){let t=await Xo(e);return await xe.getModel(t.providerId,t.modelId)}async function Jv(e){let t=[{type:"text",text:e}],n=a$9.files(e),o=new Set;for(let s of n){let r=s[1];if(!r||o.has(r))continue;o.add(r);let i=R.directory,c=Se__default.isAbsolute(r)?r:Se__default.resolve(i,r),l=Filesystem.stat(c);l&&(l.isDirectory()?t.push({type:"file",url:pathToFileURL(c).href,filename:r,mime:"application/x-directory"}):t.push({type:"file",url:pathToFileURL(c).href,filename:r,mime:"text/plain"}));}return t}var Di;(n=>{async function e(o){let s=Je.start(o.sessionId);if(!s)throw new Y.BusyError(o.sessionId);let r=async()=>{(Je.state()[o.sessionId]?.callbacks??[]).length===0?await Je.cancel(o.sessionId):Je.loop({sessionId:o.sessionId,resume_existing:true}).catch(c=>{Cf.error("session loop failed to resume after shell command",{sessionId:o.sessionId,error:c});});};try{let i=await Y.get(o.sessionId);i.revert&&await io.cleanup(i);let c=await Ue.get(o.agent);if(!c)throw new Error(`Agent not found: ${o.agent}`);let l;o.model?l=await xe.getModel(o.model.providerId,o.model.modelId):c.model?l=await xe.getModel(c.model.providerId,c.model.modelId):l=await _c(o.sessionId);let d={id:Identifier.ascending("message"),sessionId:o.sessionId,time:{created:Date.now()},role:"user",agent:o.agent,model:{providerId:l.providerId,modelId:l.id}};await Y.updateMessage(d);let m={type:"text",id:Identifier.ascending("part"),messageId:d.id,sessionId:o.sessionId,text:"The following tool was executed by the user",synthetic:!0};await Y.updatePart(m);let f={id:Identifier.ascending("message"),sessionId:o.sessionId,parentId:d.id,mode:o.agent,agent:o.agent,cost:0,path:{cwd:R.directory,root:R.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:l.id,providerId:l.providerId};await Y.updateMessage(f);let a={type:"tool",id:Identifier.ascending("part"),messageId:f.id,sessionId:o.sessionId,tool:"bash",callId:ulid(),state:{status:"running",time:{start:Date.now()},input:{command:o.command}}};await Y.updatePart(a);let p=Shell.acceptable(),u=await Promise.resolve(p),h=(process.platform==="win32"?Se__default.win32.basename(u??"",".exe"):Se__default.basename(u??"")).toLowerCase(),g={nu:{args:["-c",o.command]},fish:{args:["-c",o.command]},zsh:{args:["-c","-l",`
|
|
282
|
+
[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
|
|
283
|
+
[[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
|
|
284
|
+
eval ${JSON.stringify(o.command)}
|
|
285
|
+
`]},bash:{args:["-c","-l",`
|
|
286
|
+
shopt -s expand_aliases
|
|
287
|
+
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
|
|
288
|
+
eval ${JSON.stringify(o.command)}
|
|
289
|
+
`]},cmd:{args:["/c",o.command]},powershell:{args:["-NoProfile","-Command",o.command]},pwsh:{args:["-NoProfile","-Command",o.command]},"":{args:["-c",`${o.command}`]}},T=(g[h]??g[""])?.args??[];process.platform==="win32"&&(h==="cmd"?T=["/c",`chcp 65001 >nul 2>&1 && ${o.command}`]:(h==="powershell"||h==="pwsh")&&(T=["-NoProfile","-Command",`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${o.command}`]));let y=R.directory,b=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:y},{cwd:y})).output?.env??{},w=spawn(u??"sh",T,{cwd:y,detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"],env:{...process.env,...b,TERM:"dumb",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"}}),k="";w.stdout?.on("data",U=>{k+=U.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:k,description:""},Y.updatePart(a));}),w.stderr?.on("data",U=>{k+=U.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:k,description:""},Y.updatePart(a));});let v=!1,C=!1,E=()=>Shell.killTree(w,{exited:()=>C});s.aborted&&(v=!0,await E());let O=()=>{v=!0,E();};return s.addEventListener("abort",O,{once:!0}),await new Promise(U=>{w.on("close",()=>{C=!0,s.removeEventListener("abort",O),U();});}),v&&(k+=`
|
|
290
|
+
|
|
291
|
+
`+["<metadata>","User aborted the command","</metadata>"].join(`
|
|
292
|
+
`)),f.time={...f.time,completed:Date.now()},await Y.updateMessage(f),a.state.status==="running"&&(a.state={status:"completed",time:{...a.state.time,end:Date.now()},input:a.state.input,title:"",metadata:{output:k,description:""},output:k},await Y.updatePart(a)),{info:f,parts:[a],title:"Shell Command",metadata:{command:o.command},output:k,success:!v}}finally{await r();}}n.shell=e;async function t(o){Cf.debug("command",o);let s=await vn.get(o.command);if(!s)throw new Error(`Command not found: ${o.command}`);if(await Le.triggerEvent(HookEvent.CommandBefore,{command:o.command,sessionId:o.sessionId,arguments:o.arguments},{sessionId:o.sessionId}),s.commandType==="local"){let w={sessionId:o.sessionId,directory:R.worktree,model:o.model,agent:s.agent??o.agent??await Ue.defaultAgent(),arguments:o.arguments},k=await s.execute(o.arguments,w);k.metadata.commandType="local";let v={...k,success:k.success,error:k.metadata?.error};return await pe.publish(Sf,{name:o.command,sessionId:o.sessionId,arguments:o.arguments}),await Le.triggerEvent(HookEvent.CommandAfter,{command:o.command,sessionId:o.sessionId,arguments:o.arguments,result:v},{sessionId:o.sessionId}),v}let r=s.agent??o.agent??await Ue.defaultAgent(),i={sessionId:o.sessionId,directory:R.worktree,model:o.model,agent:r,arguments:o.arguments},l=(await s.execute(o.arguments,i)).output,d=l,m=a$9.shell(d);if(m.length>0){let w=await Promise.all(m.map(async([,v])=>{try{return await $`${{raw:v}}`.quiet().nothrow().text()}catch(C){return `Error executing command: ${C instanceof Error?C.message:String(C)}`}})),k=0;d=d.replace(Kv,()=>w[k++]??"");}d=d.trim();let a=await(async()=>{if(s.model)return xe.parseModel(s.model);if(s.agent){let k=await Ue.get(s.agent);if(k?.model)return k.model}if(o.model)return xe.parseModel(o.model);let w=await _c(o.sessionId);return {providerId:w.providerId,modelId:w.id}})();try{await xe.getModel(a.providerId,a.modelId);}catch(w){if(xe.ModelNotFoundError.isInstance(w)){let{providerId:k,modelId:v,suggestions:C}=w.data,E=C&&C.length>0?` Did you mean: ${C.join(", ")}?`:"";await pe.publish(Y.Event.Error,{sessionId:o.sessionId,error:new NamedError.Unknown({message:`Model not found: ${k}/${v}.${E}`}).toObject()});}throw w}let p=await Ue.get(r);if(!p){let w=await Ue.list().then(C=>C.filter(E=>!E.hidden).map(E=>E.name)),k=w.length>0?` Available agents: ${w.join(", ")}`:"",v=new NamedError.Unknown({message:`Agent not found: "${r}".${k}`});throw await pe.publish(Y.Event.Error,{sessionId:o.sessionId,error:v.toObject()}),v}let u=await Jv(d),h=[],g=s.subtask===true,I=Identifier.ascending("task"),T=g?[{type:"subtask",taskId:I,agent:p.name,description:s.description??"",command:o.command,model:{providerId:a.providerId,modelId:a.modelId},prompt:[...u??[],...h].find(w=>w.type==="text")?.text??""}]:[...u??[],...h,...o.parts??[]],y=g?o.agent??await Ue.defaultAgent():r,x=g?o.model?xe.parseModel(o.model):{providerId:(await _c(o.sessionId)).providerId,modelId:(await _c(o.sessionId)).id}:a,b=await Je.prompt({sessionId:o.sessionId,messageId:o.messageId,model:x,agent:y,parts:T,variant:o.variant});return await pe.publish(Sf,{name:o.command,sessionId:o.sessionId,arguments:o.arguments,messageId:b.info.id}),await Le.triggerEvent(HookEvent.CommandAfter,{command:o.command,sessionId:o.sessionId,arguments:o.arguments,result:{info:b.info,parts:b.parts,success:true}},{sessionId:o.sessionId}),{info:b.info,parts:b.parts,title:o.command,metadata:{command:o.command,arguments:o.arguments,commandType:"prompt"},output:l,success:true}}n.execute=t;})(Di||(Di={}));var iu=new Set(["powershell","pwsh"]),au=new Set(["cmd"]);function Xv(e){return e==="pwsh"?"pwsh":e==="powershell"?"powershell":e==="cmd"?"cmd":e==="bash"?"bash":e==="zsh"?"zsh":e}function ru(e){return iu.has(e)?`Brief description of this command (5-10 words). Examples:
|
|
293
|
+
Input: Get-ChildItem -LiteralPath "."
|
|
294
|
+
Output: Lists current directory
|
|
295
|
+
|
|
296
|
+
Input: git status
|
|
297
|
+
Output: Shows working tree status
|
|
298
|
+
|
|
299
|
+
Input: npm install
|
|
300
|
+
Output: Installs package dependencies
|
|
301
|
+
|
|
302
|
+
Input: New-Item -ItemType Directory -Path "tmp"
|
|
303
|
+
Output: Creates directory tmp`:au.has(e)?`Brief description of this command (5-10 words). Examples:
|
|
304
|
+
Input: dir
|
|
305
|
+
Output: Lists current directory
|
|
306
|
+
|
|
307
|
+
Input: if exist "package.json" type "package.json"
|
|
308
|
+
Output: Prints package.json when it exists
|
|
309
|
+
|
|
310
|
+
Input: mkdir tmp
|
|
311
|
+
Output: Creates directory tmp`:`Brief description of this command (5-10 words). Examples:
|
|
312
|
+
Input: ls
|
|
313
|
+
Output: Lists files in current directory
|
|
314
|
+
|
|
315
|
+
Input: git status
|
|
316
|
+
Output: Shows working tree status
|
|
317
|
+
|
|
318
|
+
Input: npm install
|
|
319
|
+
Output: Installs package dependencies
|
|
320
|
+
|
|
321
|
+
Input: mkdir foo
|
|
322
|
+
Output: Creates directory 'foo'`}function Qv(e){return e==="pwsh"?'# PowerShell (7+) shell notes\n- This cross-platform shell supports pipeline chain operators (`&&` and `||`).\n- Use double quotes for interpolated strings (`"Hello $name"`), single quotes for verbatim strings.\n- Prefer full cmdlet names like `Get-ChildItem`, `Set-Content`, `Remove-Item`, and `New-Item` over aliases.\n- Use `$(...)` for subexpressions. Use `@(...)` for array expressions.\n- To call a native executable whose path contains spaces, use the call operator: `& "path/to/exe" args`.\n- Escape special characters with the PowerShell backtick character.':e==="powershell"?'# Windows PowerShell (5.1) shell notes\n- Use `cmd1; if ($?) { cmd2 }` to chain dependent commands.\n- Use double quotes for interpolated strings (`"Hello $name"`), single quotes for verbatim strings.\n- Prefer full cmdlet names like `Get-ChildItem`, `Set-Content`, `Remove-Item`, and `New-Item` over aliases.\n- Use `$(...)` for subexpressions. Use `@(...)` for array expressions.\n- To call a native executable whose path contains spaces, use the call operator: `& "path/to/exe" args`.\n- Escape special characters with the PowerShell backtick character.':""}function Zv(e){return e==="powershell"?"If the commands depend on each other and must run sequentially, avoid '&&' in this shell because Windows PowerShell (5.1) does not support it. Use PowerShell conditionals such as `cmd1; if ($?) { cmd2 }` when later commands must depend on earlier success.":iu.has(e)?"If the commands depend on each other and must run sequentially, use '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before bash for git operations, or git add before git commit), run these operations sequentially instead.":au.has(e)?"If the commands depend on each other and must run sequentially, use `&&` to chain them together (e.g., `mkdir out && dir out`). For instance, if one operation must complete before another starts, run these operations sequentially instead.":"If the commands depend on each other and must run sequentially, use '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before bash for git operations, or git add before git commit), run these operations sequentially instead."}function eS(e,t){return `Before executing the command, please follow these steps:
|
|
323
|
+
|
|
324
|
+
1. Directory Verification:
|
|
325
|
+
- If the command will create new directories or files, first use \`ls\` to verify the parent directory exists and is the correct location
|
|
326
|
+
- For example, before running "mkdir foo/bar", first use \`ls foo\` to check that "foo" exists and is the intended parent directory
|
|
327
|
+
|
|
328
|
+
2. Command Execution:
|
|
329
|
+
- Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
|
|
330
|
+
- Examples of proper quoting:
|
|
331
|
+
- mkdir "/Users/name/My Documents" (correct)
|
|
332
|
+
- mkdir /Users/name/My Documents (incorrect - will fail)
|
|
333
|
+
- python "/path/with spaces/script.py" (correct)
|
|
334
|
+
- python /path/with spaces/script.py (incorrect - will fail)
|
|
335
|
+
- After ensuring proper quoting, execute the command.
|
|
336
|
+
- Capture the output of the command.
|
|
337
|
+
|
|
338
|
+
Usage notes:
|
|
339
|
+
- The command argument is required.
|
|
340
|
+
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
|
|
341
|
+
- Provide a brief description of what this command does (5-10 words).
|
|
342
|
+
- If the output exceeds ${t.maxLines} lines or ${t.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`head\`, \`tail\`, or other truncation commands to limit output - just run the command directly.
|
|
343
|
+
|
|
344
|
+
- Avoid using Bash with the \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
|
|
345
|
+
- File search: Use Glob (NOT find or ls)
|
|
346
|
+
- Content search: Use Grep (NOT grep or rg)
|
|
347
|
+
- Read files: Use Read (NOT cat/head/tail)
|
|
348
|
+
- Edit files: Use Edit (NOT sed/awk)
|
|
349
|
+
- Write files: Use Write (NOT echo >/cat <<EOF)
|
|
350
|
+
- Communication: Output text directly (NOT echo/printf)
|
|
351
|
+
- When issuing multiple commands:
|
|
352
|
+
- If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel.
|
|
353
|
+
- ${e}
|
|
354
|
+
- Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
|
|
355
|
+
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
|
|
356
|
+
- AVOID using \`cd <directory> && <command>\`. Use the \`workdir\` parameter to change directories instead.
|
|
357
|
+
<good-example>
|
|
358
|
+
Use workdir="/foo/bar" with command: pytest tests
|
|
359
|
+
</good-example>
|
|
360
|
+
<bad-example>
|
|
361
|
+
cd /foo/bar && pytest tests
|
|
362
|
+
</bad-example>`}function tS(e,t,n){let o=process.platform==="win32"?"\\":"/";return `${Qv(e)}
|
|
363
|
+
|
|
364
|
+
Before executing the command, please follow these steps:
|
|
365
|
+
|
|
366
|
+
1. Directory Verification:
|
|
367
|
+
- If the command will create new directories or files, first use \`Test-Path -LiteralPath <parent>\` to verify the parent directory exists and is the correct location
|
|
368
|
+
- For example, before creating \`foo${o}bar\`, first use \`Test-Path -LiteralPath "foo"\` to check that \`foo\` exists and is the intended parent directory
|
|
369
|
+
|
|
370
|
+
2. Command Execution:
|
|
371
|
+
- Always quote file paths that contain spaces with double quotes (e.g., Remove-Item -LiteralPath "path with spaces${o}file.txt")
|
|
372
|
+
- Examples of proper quoting:
|
|
373
|
+
- New-Item -ItemType Directory -Path "My Documents" (correct)
|
|
374
|
+
- New-Item -ItemType Directory -Path My Documents (incorrect - path is split)
|
|
375
|
+
- & "path with spaces${o}script.ps1" (correct)
|
|
376
|
+
- path with spaces${o}script.ps1 (incorrect - path is split and not invoked)
|
|
377
|
+
- After ensuring proper quoting, execute the command.
|
|
378
|
+
- Capture the output of the command.
|
|
379
|
+
|
|
380
|
+
Usage notes:
|
|
381
|
+
- The command argument is required.
|
|
382
|
+
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
|
|
383
|
+
- Provide a brief description of what this command does (5-10 words).
|
|
384
|
+
- If the output exceeds ${n.maxLines} lines or ${n.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`Select-Object -First\`, \`Select-Object -Last\`, or other truncation commands to limit output - just run the command directly.
|
|
385
|
+
|
|
386
|
+
- Avoid using Shell with PowerShell file/content cmdlets unless explicitly instructed or when these cmdlets are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
|
|
387
|
+
- File search: Use Glob (NOT Get-ChildItem)
|
|
388
|
+
- Content search: Use Grep (NOT Select-String)
|
|
389
|
+
- Read files: Use Read (NOT Get-Content)
|
|
390
|
+
- Edit files: Use Edit (NOT Set-Content)
|
|
391
|
+
- Write files: Use Write (NOT Set-Content/Out-File or here-strings)
|
|
392
|
+
- Communication: Output text directly (NOT Write-Output/Write-Host)
|
|
393
|
+
- When issuing multiple commands:
|
|
394
|
+
- If the commands are independent and can run in parallel, make multiple Shell tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Shell tool calls in parallel.
|
|
395
|
+
- ${t}
|
|
396
|
+
- Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
|
|
397
|
+
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
|
|
398
|
+
- AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
|
|
399
|
+
<good-example>
|
|
400
|
+
Use workdir="project${o}subdir" with command: pytest tests
|
|
401
|
+
</good-example>
|
|
402
|
+
<bad-example>
|
|
403
|
+
${e==="powershell"?`Set-Location -LiteralPath "project${o}subdir"; if ($?) { pytest tests }`:`Set-Location -LiteralPath "project${o}subdir" && pytest tests`}
|
|
404
|
+
</bad-example>`}function nS(e,t){return `# cmd.exe shell notes
|
|
405
|
+
- Use double quotes for paths with spaces.
|
|
406
|
+
- Use %VAR% for environment variables.
|
|
407
|
+
- Use \`if exist\` for existence checks.
|
|
408
|
+
- Use \`call\` when invoking batch files from another batch-style command.
|
|
409
|
+
|
|
410
|
+
Before executing the command, please follow these steps:
|
|
411
|
+
|
|
412
|
+
1. Directory Verification:
|
|
413
|
+
- If the command will create new directories or files, first use \`if exist\` to verify the parent directory exists and is the correct location
|
|
414
|
+
- For example, before creating \`foo\\bar\`, first use \`if exist "foo\\" dir "foo"\` to check that \`foo\` exists and is the intended parent directory
|
|
415
|
+
|
|
416
|
+
2. Command Execution:
|
|
417
|
+
- Always quote file paths that contain spaces with double quotes (e.g., del "path with spaces\\file.txt")
|
|
418
|
+
- Examples of proper quoting:
|
|
419
|
+
- mkdir "My Documents" (correct)
|
|
420
|
+
- mkdir My Documents (incorrect - path is split)
|
|
421
|
+
- call "path with spaces\\script.bat" (correct)
|
|
422
|
+
- path with spaces\\script.bat (incorrect - path is split and not invoked correctly)
|
|
423
|
+
- After ensuring proper quoting, execute the command.
|
|
424
|
+
- Capture the output of the command.
|
|
425
|
+
|
|
426
|
+
Usage notes:
|
|
427
|
+
- The command argument is required.
|
|
428
|
+
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
|
|
429
|
+
- Provide a brief description of what this command does (5-10 words).
|
|
430
|
+
- If the output exceeds ${t.maxLines} lines or ${t.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`more\` or other pagination commands to limit output - just run the command directly.
|
|
431
|
+
|
|
432
|
+
- Avoid using Shell with cmd.exe file/content commands unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
|
|
433
|
+
- File search: Use Glob (NOT dir /s)
|
|
434
|
+
- Content search: Use Grep (NOT findstr)
|
|
435
|
+
- Read files: Use Read (NOT type)
|
|
436
|
+
- Edit files: Use Edit (NOT copy)
|
|
437
|
+
- Write files: Use Write (NOT echo > file)
|
|
438
|
+
- Communication: Output text directly (NOT echo)
|
|
439
|
+
- When issuing multiple commands:
|
|
440
|
+
- If the commands are independent and can run in parallel, make multiple Shell tool calls in a single message. For example, if you need to run "dir" and "where cmd", send a single message with two Shell tool calls in parallel.
|
|
441
|
+
- ${e}
|
|
442
|
+
- Use '&' only when you need to run commands sequentially but don't care if earlier commands fail
|
|
443
|
+
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
|
|
444
|
+
- AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
|
|
445
|
+
<good-example>
|
|
446
|
+
Use workdir="project\\subdir" with command: dir
|
|
447
|
+
</good-example>
|
|
448
|
+
<bad-example>
|
|
449
|
+
cd /d "project\\subdir" && dir
|
|
450
|
+
</bad-example>`}function oS(e,t){let n=iu.has(e),o=au.has(e),s=Xv(e),r=Zv(e);return o?{intro:`Executes a given ${s} command with optional timeout, ensuring proper handling and security measures.`,workdirSection:"All commands run in {{directory}} by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",commandSection:nS(r,t),gitSection:`# Committing changes with git
|
|
451
|
+
|
|
452
|
+
Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
|
|
453
|
+
|
|
454
|
+
Git Safety Protocol:
|
|
455
|
+
- NEVER update the git config
|
|
456
|
+
- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
|
|
457
|
+
- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
|
|
458
|
+
- NEVER run force push to main/master, warn the user if they request it
|
|
459
|
+
- Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
|
|
460
|
+
(1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
|
|
461
|
+
(2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
|
|
462
|
+
(3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
|
|
463
|
+
- CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
|
|
464
|
+
- CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
|
|
465
|
+
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
466
|
+
|
|
467
|
+
1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run the following bash commands in parallel:
|
|
468
|
+
- Run \`git status\` to see all untracked files
|
|
469
|
+
- Run \`git diff\` to see both staged and unstaged changes that will be committed
|
|
470
|
+
- Run \`git log --oneline -10\` to see recent commit messages
|
|
471
|
+
|
|
472
|
+
2. Analyze all staged changes and draft a commit message:
|
|
473
|
+
- Summarize the nature of the changes
|
|
474
|
+
- Draft a concise (1-2 sentences) commit message
|
|
475
|
+
- Do not commit files that likely contain secrets (.env, etc.)
|
|
476
|
+
|
|
477
|
+
3. Create the commit using a temporary body file so cmd.exe quoting stays simple:
|
|
478
|
+
\`(
|
|
479
|
+
echo ## Summary
|
|
480
|
+
echo ^<1-3 bullet points^>
|
|
481
|
+
) ^> pr-body.txt
|
|
482
|
+
gh pr create --title "the pr title" --body-file pr-body.txt\`
|
|
483
|
+
|
|
484
|
+
4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
|
|
485
|
+
|
|
486
|
+
# Creating pull requests
|
|
487
|
+
|
|
488
|
+
Use the gh command via the Shell tool for ALL GitHub-related tasks including PRs and issues. Create PR using a temporary body file so cmd.exe quoting stays simple.`,createPrSection:`IMPORTANT: When creating a PR with gh, use a temporary body file for correct cmd.exe quoting:
|
|
489
|
+
\`(
|
|
490
|
+
echo ## Summary
|
|
491
|
+
echo - ^<1-3 bullet points^>
|
|
492
|
+
) ^> pr-body.txt
|
|
493
|
+
gh pr create --title "the pr title" --body-file pr-body.txt\``,parameterDescription:ru(e)}:n?{intro:`Executes a given ${s} command with optional timeout, ensuring proper handling and security measures.`,workdirSection:"All commands run in {{directory}} by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",commandSection:tS(e,r,t),gitSection:`# Committing changes with git
|
|
494
|
+
|
|
495
|
+
Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
|
|
496
|
+
|
|
497
|
+
Git Safety Protocol:
|
|
498
|
+
- NEVER update the git config
|
|
499
|
+
- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
|
|
500
|
+
- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
|
|
501
|
+
- NEVER run force push to main/master, warn the user if they request it
|
|
502
|
+
- Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
|
|
503
|
+
(1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
|
|
504
|
+
(2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
|
|
505
|
+
(3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
|
|
506
|
+
- CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
|
|
507
|
+
- CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
|
|
508
|
+
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
509
|
+
|
|
510
|
+
1. Run these commands in parallel:
|
|
511
|
+
- Run \`git status\` to see all untracked files
|
|
512
|
+
- Run \`git diff\` to see both staged and unstaged changes
|
|
513
|
+
- Run \`git log --oneline -10\` to see recent commit messages
|
|
514
|
+
|
|
515
|
+
2. Analyze all staged changes and draft a commit message
|
|
516
|
+
|
|
517
|
+
3. Create the commit:
|
|
518
|
+
- Add relevant untracked files to the staging area
|
|
519
|
+
- Create the commit with a message
|
|
520
|
+
- Run git status after the commit completes
|
|
521
|
+
|
|
522
|
+
4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
|
|
523
|
+
|
|
524
|
+
# Creating pull requests
|
|
525
|
+
|
|
526
|
+
Use the gh command via the Shell tool for ALL GitHub-related tasks. Create PR using gh pr create with a PowerShell here-string to pass the body correctly:
|
|
527
|
+
\`\`\`powershell
|
|
528
|
+
gh pr create --title "the pr title" --body @'
|
|
529
|
+
## Summary
|
|
530
|
+
- <1-3 bullet points>
|
|
531
|
+
'@
|
|
532
|
+
\`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a PowerShell here-string for correct body formatting:
|
|
533
|
+
\`gh pr create --title "the pr title" --body @'
|
|
534
|
+
## Summary
|
|
535
|
+
- <1-3 bullet points>
|
|
536
|
+
'@`,parameterDescription:ru(e)}:{intro:`Executes a given ${s} command in a persistent shell session with optional timeout, ensuring proper handling and security measures.`,workdirSection:"All commands run in {{directory}} by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",commandSection:eS(r,t),gitSection:`# Committing changes with git
|
|
537
|
+
|
|
538
|
+
Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
|
|
539
|
+
|
|
540
|
+
Git Safety Protocol:
|
|
541
|
+
- NEVER update the git config
|
|
542
|
+
- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
|
|
543
|
+
- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
|
|
544
|
+
- NEVER run force push to main/master, warn the user if they request it
|
|
545
|
+
- Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
|
|
546
|
+
(1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
|
|
547
|
+
(2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
|
|
548
|
+
(3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
|
|
549
|
+
- CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
|
|
550
|
+
- CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
|
|
551
|
+
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
552
|
+
|
|
553
|
+
1. Run these commands in parallel:
|
|
554
|
+
- Run \`git status\` to see all untracked files
|
|
555
|
+
- Run \`git diff\` to see both staged and unstaged changes
|
|
556
|
+
- Run \`git log --oneline -10\` to see recent commit messages
|
|
557
|
+
|
|
558
|
+
2. Analyze all staged changes and draft a commit message
|
|
559
|
+
|
|
560
|
+
3. Create the commit:
|
|
561
|
+
- Add relevant untracked files to the staging area
|
|
562
|
+
- Create the commit with a message
|
|
563
|
+
- Run git status after the commit completes
|
|
564
|
+
|
|
565
|
+
4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
|
|
566
|
+
|
|
567
|
+
# Creating pull requests
|
|
568
|
+
|
|
569
|
+
Use the gh command via the Shell tool for ALL GitHub-related tasks including PRs and issues. Use gh pr create with the format below. Use a HEREDOC to pass the body:
|
|
570
|
+
\`\`\`bash
|
|
571
|
+
gh pr create --title "the pr title" --body "$(cat <<'EOF'
|
|
572
|
+
## Summary
|
|
573
|
+
<1-3 bullet points>
|
|
574
|
+
EOF
|
|
575
|
+
)"
|
|
576
|
+
\`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a HEREDOC to pass the body:
|
|
577
|
+
\`gh pr create --title "the pr title" --body "$(cat <<'EOF'
|
|
578
|
+
## Summary
|
|
579
|
+
<1-3 bullet points>
|
|
580
|
+
EOF
|
|
581
|
+
)"\``,parameterDescription:ru(e)}}function kf(e){let t={maxLines:Ve.MAX_LINES,maxBytes:Ve.MAX_BYTES},n=Shell.name(e),o=oS(n,t);return {description:`${o.intro}
|
|
582
|
+
|
|
583
|
+
${o.workdirSection}
|
|
584
|
+
|
|
585
|
+
${o.commandSection}
|
|
586
|
+
|
|
587
|
+
${o.gitSection}
|
|
588
|
+
|
|
589
|
+
${o.createPrSection}`,parameterDescription:o.parameterDescription}}var Oc=3e4,aS=a$2.EASBOT_BASH_DEFAULT_TIMEOUT_MS||120*1e3,jc=a.create({service:"tool.bash"});function cS(e){let t=[];function n(o){if(o){if(o.type==="Command"){let s=o.name?.text||"",r=[],i=o.text||"";if(o.suffix)for(let c of o.suffix)c.text&&r.push(c.text);s&&t.push({command:s,args:r,fullText:i});}if(o.commands)for(let s of o.commands)n(s);o.left&&n(o.left),o.right&&n(o.right),o.then&&n(o.then),o.else&&n(o.else);}}return n(e),t}var Tf=De.define("bash",async()=>{let e=Shell.acceptable()??"/bin/bash";jc.debug("bash tool using shell",{shell:e});let{description:t,parameterDescription:n}=kf(e);return {description:t.replaceAll("{{directory}}",R.directory).replaceAll("{{maxLines}}",String(Ve.MAX_LINES)).replaceAll("{{maxBytes}}",String(Ve.MAX_BYTES)),parameters:N.object({command:N.string().describe("The command to execute"),timeout:N.number().describe("Optional timeout in milliseconds").optional(),workdir:N.string().describe(`The working directory to run the command in. Defaults to ${R.directory}. Use this instead of 'cd' commands.`).optional(),description:N.string().describe(n)}),async execute(o,s){let r=o.workdir||R.directory;if(o.timeout!==void 0&&o.timeout<0)throw new Error(`Invalid timeout value: ${o.timeout}. Timeout must be a positive number.`);let i=o.timeout??aS,c;try{c=rS(o.command);}catch(g){jc.warn("Failed to parse command, requesting full bash permission",{command:o.command,error:g instanceof Error?g.message:String(g)}),await s.ask({permission:"bash",patterns:[o.command],always:[],metadata:{unparseable:true,reason:"Command syntax too complex to analyze"}}),c=null;}if(c){let g=new Set;R.containsPath(r)||g.add(r);let I=new Set,T=new Set,y=cS(c);for(let{command:x,args:b,fullText:w}of y){if(["cd","rm","cp","mv","mkdir","touch","chmod","chown","cat"].includes(x))for(let k of b){if(k.startsWith("-")||x==="chmod"&&k.startsWith("+"))continue;let v=await realpath(Se__default.resolve(r,k)).catch(()=>null);if(jc.debug("resolved path",{arg:k,resolved:v}),v){let C=process.platform==="win32"&&v.match(/^\/[a-z]\//)?v.replace(/^\/([a-z])\//,(E,O)=>`${O.toUpperCase()}:\\`).replace(/\//g,"\\"):v;if(!R.containsPath(C)){let E=await Filesystem.isDir(C)?C:Filesystem.dirname(C);g.add(E);}}}x&&x!=="cd"&&(I.add(w),T.add(`${x} *`));}if(g.size>0){let x=Array.from(g).map(b=>Filesystem.join(b,"*"));await s.ask({permission:"external_directory",patterns:x,always:x,metadata:{}});}I.size>0&&await s.ask({permission:"bash",patterns:Array.from(I),always:Array.from(T),metadata:{}});}jc.debug("Executing bash command",{command:o.command,cwd:r,shell:e});let d=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:r})).output?.env??{},m=Shell.spawn(e,o.command,{cwd:r,env:{...process.env,...d},stdin:"null",stdout:"pipe",stderr:"pipe",signal:s.abort}),f="";s.metadata({metadata:{output:"",description:o.description}});let a=g=>{f+=g.toString("utf-8"),s.metadata({metadata:{output:f.length>Oc?f.slice(0,Oc)+`
|
|
590
|
+
|
|
591
|
+
...`:f,description:o.description}});};m.stdout.on("data",a),m.stderr.on("data",a);let p=false,u=false,h=setTimeout(()=>{p=true,m.kill();},i+100);try{let g=await m.exited;clearTimeout(h),m.stdout.destroy(),m.stderr.destroy(),s.abort.aborted&&(u=!0);let I=[];return p&&I.push(`bash tool terminated command after exceeding timeout ${i} ms`),u&&I.push("User aborted the command"),I.length>0&&(f+=`
|
|
592
|
+
|
|
593
|
+
<bash_metadata>
|
|
594
|
+
`+I.join(`
|
|
595
|
+
`)+`
|
|
596
|
+
</bash_metadata>`),{title:o.description,metadata:{output:f.length>Oc?f.slice(0,Oc)+`
|
|
597
|
+
|
|
598
|
+
...`:f,exit:g,description:o.description},output:f}}catch(g){throw clearTimeout(h),g}}}});var Lc;(r=>{let e=new Set(["node_modules","bower_components",".pnpm-store","vendor",".npm","dist","build","out",".next","target","bin","obj",".git",".svn",".hg",".vscode",".idea",".turbo",".output","desktop",".sst",".cache",".webkit-cache","__pycache__",".pytest_cache","mypy_cache",".history",".gradle"]),t=["**/*.swp","**/*.swo","**/*.pyc","**/.DS_Store","**/Thumbs.db","**/logs/**","**/tmp/**","**/temp/**","**/*.log","**/coverage/**","**/.nyc_output/**"],n=t.map(i=>new PKG.Glob(i));r.PATTERNS=[...t,...e];function s(i,c){for(let m of c?.whitelist||[])if(m.match(i))return false;let l=i.split(sep);for(let m=0;m<l.length;m++){let f=l[m];if(f&&e.has(f))return true}let d=c?.extra||[];for(let m of [...n,...d])if(m.match(i))return true;return false}r.match=s;})(Lc||(Lc={}));createRequire(import.meta.url);var Rf=1e4,Fn;(f=>{let e=a.create({service:"file.watcher"});f.Event={Updated:a$5.define("file.watcher.updated",N.object({file:N.string(),event:N.union([N.literal("add"),N.literal("change"),N.literal("unlink")])}))};function n(){let a=process.platform==="linux"?`-${EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${a}`}async function o(a){try{let p=process.env.EASBOT_CACHE_PATH||Se__default.join(".easbot","cache");return !!await PKG.resolve(a,void 0,{extraPaths:[p]})}catch{return false}}async function s(a,p){e.info("Installing Parcel watcher binding",{binding:a,version:p});let u=process.env.EASBOT_CACHE_PATH||Se__default.join(".easbot","cache");return await Shell.install(a,p,u)}let r=lazyAsync(async()=>{try{let a=n(),p=await o(a),u;if(p){let T=process.env.EASBOT_CACHE_PATH||Se__default.join(".easbot","cache");u=Se__default.join(T,"node_modules",a);}else {let T="latest";e.info("Parcel watcher binding not found, attempting to install",{binding:a}),u=await s(a,T);}e.info("Loading Parcel watcher binding",{binding:a,modulePath:u});let{createWrapper:h}=await import('@parcel/watcher/wrapper.js'),I=createRequire(Se__default.join(u,"package.json"))(a);return h(I)}catch(a){e.error("failed to load watcher binding",{error:a});return}});async function i(){if(R.project.vcs!=="git")return {};e.info("init");let a=await he.get(),p=(()=>{if(process.platform==="win32")return "windows";if(process.platform==="darwin")return "fs-events";if(process.platform==="linux")return "inotify"})();if(!p)return e.error("watcher backend not supported",{platform:process.platform}),{};e.info("watcher backend",{platform:process.platform,backend:p});let u=await r();if(!u)return {};let h=R.directory,g=(b,w)=>{R.provide({directory:h,init:void 0,fn:()=>pe.publish(f.Event.Updated,{file:b,event:w})});},I=(b,w)=>{if(!b)for(let k of w){let v=k;v.type==="create"&&g(v.path,"add"),v.type==="update"&&g(v.path,"change"),v.type==="delete"&&g(v.path,"unlink");}},T=[],y=a.watcher?.ignore??[];if(a$2.EASBOT_FILEWATCHER){let b=u.subscribe(R.directory,I,{ignore:[...Lc.PATTERNS,...y],backend:p}),w=await withTimeout(b,Rf).catch(k=>{e.error("failed to subscribe to Instance.directory",{error:k}),b.then(v=>v.unsubscribe()).catch(()=>{});});w&&T.push(w);}let x=await $`git rev-parse --git-dir`.quiet().nothrow().cwd(R.worktree).text().then(b=>Filesystem.resolve(Filesystem.join(R.worktree,b.trim()))).catch(()=>{});if(x&&!y.includes(".git")&&!y.includes(x)){let w=(await readdir(x).catch(()=>[])).filter(C=>C!=="HEAD"),k=u.subscribe(x,I,{ignore:w,backend:p}),v=await withTimeout(k,Rf).catch(C=>{e.error("failed to subscribe to vcsDir",{error:C}),k.then(E=>E.unsubscribe()).catch(()=>{});});v&&T.push(v);}return {subs:T}}let c;function l(){return c||(c=R.state(i,async a=>{a.subs&&await Promise.all(a.subs.map(p=>p?.unsubscribe()));})),c}async function d(){return l()()}function m(){a$2.EASBOT_FILEWATCHER&&d();}f.init=m;})(Fn||(Fn={}));var Rr=class e extends Error{constructor(n,o,s){let r=o||`Operation '${n}' was aborted`;super(r);b$1(this,"name","AbortError");b$1(this,"operation");b$1(this,"cause");this.operation=n,this.cause=s,Object.setPrototypeOf(this,e.prototype);}static isAbortError(n){return n instanceof e}};var Rt;(o=>{function e(s,r){if(s?.aborted)throw new Rr(r,`Operation '${r}' was aborted`)}o.check=e;function t(s,r){let i=new AbortController,{signal:c}=i,l=setTimeout(()=>{i.abort(new Error(`Operation timed out after ${s}ms`));},s);if(r){let d=()=>{clearTimeout(l),i.abort(r.reason);};r.aborted?(clearTimeout(l),i.abort(r.reason)):(r.addEventListener("abort",d,{once:true}),c.addEventListener("abort",()=>{clearTimeout(l),r.removeEventListener("abort",d);},{once:true}));}else c.addEventListener("abort",()=>clearTimeout(l),{once:true});return {signal:c,controller:i}}o.withTimeout=t;async function n(s,r,i){if(e(r,s),!r)return await i(void 0);let c=new Promise((l,d)=>{if(r.aborted)d(new Rr(s,`Operation '${s}' was aborted`,r.reason));else {let m=()=>{d(new Rr(s,`Operation '${s}' was aborted`,r.reason));};r.addEventListener("abort",m,{once:true});}});return await Promise.race([i(r),c])}o.wrap=n;})(Rt||(Rt={}));var bS=loadTextFile("./edit.txt",import.meta.url),wS=bS(),uu=20;function Dc(e){return e.replaceAll(`\r
|
|
599
|
+
`,`
|
|
600
|
+
`)}var $c=De.define("edit",{description:wS,parameters:N.object({filePath:N.string().describe("The absolute path to the file to modify"),oldString:N.string().describe("The text to replace"),newString:N.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:N.boolean().optional().describe("Replace all occurrences of oldString (default false)")}),async execute(e,t){if(Rt.check(t.abort,"edit"),!e.filePath)throw new Error("filePath is required");if(e.oldString===e.newString)throw new Error("No changes to apply: oldString and newString are identical.");let n=Filesystem.normalize(Se.isAbsolute(e.filePath)?e.filePath:Filesystem.join(R.directory,e.filePath));await Jt(t,n,{tool:"edit"});let o="",s="",r="";await An.withLock(n,async()=>{if(e.oldString===""){let m=await PKG.file(n).exists();r=e.newString,o=Lo(createTwoFilesPatch(n,n,s,r)),await t.ask({permission:"edit",patterns:[Se.posix.relative(R.worktree,n)],always:["*"],metadata:{filepath:n,diff:o}}),Rt.check(t.abort,"edit"),await PKG.write(n,e.newString),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Fn.Event.Updated,{file:n,event:m?"change":"add"}),An.read(t.sessionId,n);return}let d=await Tt.stat(n).catch(()=>null);if(!d)throw new Error(`File ${n} not found`);if(d.isDirectory())throw new Error(`Path is a directory, not a file: ${n}`);await An.assert(t.sessionId,n),s=await Tt.readFile(n,"utf-8"),r=RS(s,e.oldString,e.newString,e.replaceAll),o=Lo(createTwoFilesPatch(n,n,Dc(s),Dc(r))),await t.ask({permission:"edit",patterns:[Se.posix.relative(R.worktree,n)],always:["*"],metadata:{filepath:n,diff:o}}),Rt.check(t.abort,"edit"),await Tt.writeFile(n,r),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Fn.Event.Updated,{file:n,event:"change"}),r=await Tt.readFile(n,"utf-8"),o=Lo(createTwoFilesPatch(n,n,Dc(s),Dc(r))),An.read(t.sessionId,n);});let i={file:n,before:s,after:r,additions:0,deletions:0};for(let d of diffLines(s,r))d.added&&(i.additions+=d.count||0),d.removed&&(i.deletions+=d.count||0);t.metadata({metadata:{diff:o,filediff:i,diagnostics:{}}});let c="Edit applied successfully.";Rt.check(t.abort,"edit");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(n,true);let d=await We.getFileDiagnostics(n);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,uu),a=m.length>uu?`
|
|
601
|
+
... and ${m.length-uu} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
|
|
602
|
+
|
|
603
|
+
LSP errors detected in this file, please fix:
|
|
604
|
+
<diagnostics file="${n}">
|
|
605
|
+
${p.join(`
|
|
606
|
+
`)}${a}
|
|
607
|
+
</diagnostics>`;}}return {metadata:{filepath:n,diagnostics:{[Filesystem.normalize(n)]:l},diff:o,filediff:i},title:`${Se.posix.relative(R.worktree,n)}`,output:c}}}),Of=0,xS=.3;function jf(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let n=Array.from({length:e.length+1},(o,s)=>Array.from({length:t.length+1},(r,i)=>s===0?i:i===0?s:0));for(let o=1;o<=e.length;o++)for(let s=1;s<=t.length;s++){let r=e[o-1]===t[s-1]?0:1,i=n[o],c=n[o-1];i[s]=Math.min((c[s]??0)+1,(i[s-1]??0)+1,(c[s-1]??0)+r);}return n[e.length]?.[t.length]??0}var IS=function*(e,t){yield t;},vS=function*(e,t){let n=e.split(`
|
|
608
|
+
`),o=t.split(`
|
|
609
|
+
`);o[o.length-1]===""&&o.pop();for(let s=0;s<=n.length-o.length;s++){let r=true;for(let i=0;i<o.length;i++){let c=n[s+i],l=o[i];if(c===void 0||l===void 0){r=false;break}let d=c.trim(),m=l.trim();if(d!==m){r=false;break}}if(r){let i=0;for(let l=0;l<s;l++){let d=n[l];d!==void 0&&(i+=d.length+1);}let c=i;for(let l=0;l<o.length;l++){let d=n[s+l];d!==void 0&&(c+=d.length,l<o.length-1&&(c+=1));}yield e.substring(i,c);}}},SS=function*(e,t){let n=e.split(`
|
|
610
|
+
`),o=t.split(`
|
|
611
|
+
`);if(o.length<3)return;o[o.length-1]===""&&o.pop();let s=o[0]?.trim()??"",r=o[o.length-1]?.trim()??"",i=o.length,c=[];for(let m=0;m<n.length;m++){let f=n[m];if(f!==void 0&&f.trim()===s)for(let a=m+2;a<n.length;a++){let p=n[a];if(p!==void 0&&p.trim()===r){c.push({startLine:m,endLine:a});break}}}if(c.length===0)return;if(c.length===1&&c[0]){let{startLine:m,endLine:f}=c[0],a=f-m+1,p=0,u=Math.min(i-2,a-2);if(u>0)for(let h=1;h<i-1&&h<a-1;h++){let g=n[m+h],I=o[h];if(!g||!I)continue;let T=g.trim(),y=I.trim(),x=Math.max(T.length,y.length);if(x===0)continue;let b=jf(T,y);if(p+=(1-b/x)/u,p>=Of)break}else p=1;if(p>=Of){let h=0;for(let I=0;I<m;I++){let T=n[I];T!==void 0&&(h+=T.length+1);}let g=h;for(let I=m;I<=f;I++){let T=n[I];T!==void 0&&(g+=T.length,I<f&&(g+=1));}yield e.substring(h,g);}return}let l=null,d=-1;for(let m of c){let{startLine:f,endLine:a}=m,p=a-f+1,u=0,h=Math.min(i-2,p-2);if(h>0){for(let g=1;g<i-1&&g<p-1;g++){let I=n[f+g],T=o[g];if(!I||!T)continue;let y=I.trim(),x=T.trim(),b=Math.max(y.length,x.length);if(b===0)continue;let w=jf(y,x);u+=1-w/b;}u/=h;}else u=1;u>d&&(d=u,l=m);}if(d>=xS&&l){let{startLine:m,endLine:f}=l,a=0;for(let u=0;u<m;u++){let h=n[u];h&&(a+=h.length+1);}let p=a;for(let u=m;u<=f;u++){let h=n[u];h&&(p+=h.length,u<f&&(p+=1));}yield e.substring(a,p);}},CS=function*(e,t){let n=i=>i.replace(/\s+/g," ").trim(),o=n(t),s=e.split(`
|
|
612
|
+
`);for(let i=0;i<s.length;i++){let c=s[i];if(n(c)===o)yield c;else if(n(c).includes(o)){let d=t.trim().split(/\s+/);if(d.length>0&&d[0]){let m=d.map(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let f=new RegExp(m),a=c.match(f);a?.[0]&&(yield a[0]);}catch{}}}}let r=t.split(`
|
|
613
|
+
`);if(r.length>1)for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length);n(c.join(`
|
|
614
|
+
`))===o&&(yield c.join(`
|
|
615
|
+
`));}},kS=function*(e,t){let n=i=>{let c=i.split(`
|
|
616
|
+
`),l=c.filter(m=>m.trim().length>0);if(l.length===0)return i;let d=Math.min(...l.map(m=>m.match(/^(\s*)/)?.[1]?.length??0));return c.map(m=>m.trim().length===0?m:m.slice(d)).join(`
|
|
617
|
+
`)},o=n(t),s=e.split(`
|
|
618
|
+
`),r=t.split(`
|
|
619
|
+
`);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
|
|
620
|
+
`);n(c)===o&&(yield c);}},PS=function*(e,t){let n=i=>i.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(c,l)=>{switch(l){case "n":return `
|
|
621
|
+
`;case "t":return " ";case "r":return "\r";case "'":return "'";case '"':return '"';case "`":return "`";case "\\":return "\\";case `
|
|
622
|
+
`:return `
|
|
623
|
+
`;case "$":return "$";default:return c}}),o=n(t);e.includes(o)&&(yield o);let s=e.split(`
|
|
624
|
+
`),r=o.split(`
|
|
625
|
+
`);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
|
|
626
|
+
`);n(c)===o&&(yield c);}},TS=function*(e,t){let n=0;for(;;){let o=e.indexOf(t,n);if(o===-1)break;yield t,n=o+t.length;}},AS=function*(e,t){let n=t.trim();if(n===t)return;e.includes(n)&&(yield n);let o=e.split(`
|
|
627
|
+
`),s=t.split(`
|
|
628
|
+
`);for(let r=0;r<=o.length-s.length;r++){let i=o.slice(r,r+s.length).join(`
|
|
629
|
+
`);i.trim()===n&&(yield i);}},ES=function*(e,t){let n=t.split(`
|
|
630
|
+
`);if(n.length<3)return;n[n.length-1]===""&&n.pop();let o=e.split(`
|
|
631
|
+
`),s=n[0]?.trim(),r=n[n.length-1]?.trim();if(!(!s||!r))for(let i=0;i<o.length;i++){let c=o[i];if(!(!c||c.trim()!==s))for(let l=i+2;l<o.length;l++){let d=o[l];if(!d||d.trim()!==r)continue;let m=o.slice(i,l+1),f=m.join(`
|
|
632
|
+
`);if(m.length===n.length){let a=0,p=0;for(let u=1;u<m.length-1;u++){let h=m[u],g=n[u];if(!h||!g)continue;let I=h.trim(),T=g.trim();(I.length>0||T.length>0)&&(p++,I===T&&a++);}if(p===0||a/p>=.5){yield f;break}}break}}};function Lo(e){let t=e.split(`
|
|
633
|
+
`),n=t.filter(r=>(r.startsWith("+")||r.startsWith("-")||r.startsWith(" "))&&!r.startsWith("---")&&!r.startsWith("+++"));if(n.length===0)return e;let o=1/0;for(let r of n){let i=r.slice(1);if(i.trim().length>0){let c=i.match(/^(\s*)/);c?.[1]&&(o=Math.min(o,c[1].length));}}return o===1/0||o===0?e:t.map(r=>{let i=r[0];if(!i)return r;if((r.startsWith("+")||r.startsWith("-")||r.startsWith(" "))&&!r.startsWith("---")&&!r.startsWith("+++")){let c=r.slice(1);return i+c.slice(o)}return r}).join(`
|
|
634
|
+
`)}function RS(e,t,n,o=false){if(t===n)throw new Error("No changes to apply: oldString and newString are identical.");let s=true;for(let r of [IS,vS,SS,CS,kS,PS,AS,ES,TS])for(let i of r(e,t)){let c=e.indexOf(i);if(c===-1)continue;if(s=false,o)return e.replaceAll(i,n);let l=e.lastIndexOf(i);if(c===l)return e.substring(0,c)+n+e.substring(c+i.length)}throw s?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}var OS=loadTextFile("./glob.txt",import.meta.url),jS=OS(),Df=De.define("glob",{description:jS,parameters:N.object({pattern:N.string().describe("The glob pattern to match files against"),path:N.string().optional().describe('The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.'),limit:N.number().optional().default(100).describe("Maximum number of results to return (default: 100)")}),async execute(e,t){await t.ask({permission:"glob",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path}});let n=e.path??R.directory;n=Filesystem.normalize(Se__default.isAbsolute(n)?n:Se__default.resolve(R.directory,n)),await Jt(t,n,{kind:"directory",tool:"glob"});let o=e.limit??100,s=[],r=false;for await(let c of a$8.files({cwd:n,glob:[e.pattern],signal:t.abort})){if(s.length>=o){r=true;break}let l=Filesystem.join(n,c),d=await PKG.file(l).stat().then(m=>m.mtime.getTime()).catch(()=>0);s.push({path:l,mtime:d});}s.sort((c,l)=>l.mtime-c.mtime);let i=[];return s.length===0&&i.push("No files found"),s.length>0&&(i.push(...s.map(c=>c.path)),r&&(i.push(""),i.push(`[${o} results limit reached. Use limit=${o*2} for more, or refine pattern]`))),{title:Se__default.posix.relative(R.worktree,n),metadata:{pattern:e.pattern,path:n,count:s.length,truncated:r,resultLimitReached:r?o:void 0},output:i.join(`
|
|
635
|
+
`)}}});var FS=loadTextFile("./grep.txt",import.meta.url),NS=FS(),Nf=2e3,zf=De.define("grep",{description:NS,parameters:N.object({pattern:N.string().describe("The regex pattern to search for in file contents"),path:N.string().optional().describe("The directory to search in. Defaults to the current working directory."),include:N.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")')}),async execute(e,t){if(!e.pattern)throw new Error("pattern is required");await t.ask({permission:"grep",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path,include:e.include}});let n=e.path??R.directory;n=Filesystem.normalize(Se__default.isAbsolute(n)?n:Se__default.resolve(R.directory,n)),await Jt(t,n,{kind:"directory",tool:"grep"});let o=await a$8.filepath(),s=100,r=["--json","--line-number","--color=never","--hidden","--no-messages","--regexp",e.pattern];e.include&&r.push("--glob",e.include),r.push(n);let i=PKG.spawn([o,...r],{stdin:"null",stdout:"pipe",stderr:"pipe"}),c=createInterface({input:i.stdout}),l="",d=0,m=false,f=[];i.stderr?.on("data",I=>{l+=I.toString("utf-8");}),c.on("line",I=>{if(!I.trim()||d>=s)return;let T;try{T=JSON.parse(I);}catch{return}if(T.type==="match"){let y=Filesystem.toUnixPath(T.data?.path?.text),x=T.data?.line_number,b=T.data?.lines?.text;y&&typeof x=="number"&&b&&Tt.stat(y).then(w=>{d++,f.push({path:y,lineNum:x,lineText:b.replace(/\r?\n$/,""),modTime:w.mtime.getTime()}),d>=s&&(m=true,i.kill()||i.kill("SIGTERM"));}).catch(()=>{});}});let a=await i.exited;if(f.length===0){if(a!==0&&a!==1&&a!==2){let I=l.trim()||`ripgrep exited with code ${a}`;throw new Error(I)}return {title:e.pattern,metadata:{matches:0,truncated:false},output:"No files found"}}f.sort((I,T)=>T.modTime-I.modTime);let p=m,u=[`Found ${f.length} matches`],h="";for(let I of f){h!==I.path&&(h!==""&&u.push(""),h=I.path,u.push(`${I.path}:`));let T=I.lineText.length>Nf?I.lineText.substring(0,Nf)+"...":I.lineText;u.push(` Line ${I.lineNum}: ${T}`);}return p&&(u.push(""),u.push("(Results are truncated. Consider using a more specific path or pattern.)")),a===2&&(u.push(""),u.push("(Some paths were inaccessible and skipped)")),{title:e.pattern,metadata:{pattern:e.pattern,path:n,matches:f.length,truncated:p},output:u.join(`
|
|
636
|
+
`)}}});var zS=loadTextFile("./batch.txt",import.meta.url),qS=zS(),mu=new Set(["batch"]),HS=new Set(["invalid","patch",...mu]),qf=De.define("batch",async()=>{let e=await he.get();return {isEnabled:async()=>e.experimental?.batch_tool===true,description:qS,parameters:N.object({tool_calls:N.array(N.object({tool:N.string().describe("The name of the tool to execute"),parameters:N.object({}).loose().describe("Parameters for the tool")})).min(1,"Provide at least one tool call").describe("Array of tool calls to execute in parallel")}),formatValidationError(t){return `Invalid parameters for tool 'batch':
|
|
637
|
+
${t.issues.map(o=>` - ${o.path.length>0?o.path.join("."):"root"}: ${o.message}`).join(`
|
|
638
|
+
`)}
|
|
639
|
+
|
|
640
|
+
Expected payload format:
|
|
641
|
+
[{"tool": "tool_name", "parameters": {...}}, {...}]`},async execute(t,n){let{Session:o}=await import('./session-5OU5P7UF.mjs'),{Identifier:s}=await import('@easbot/utils'),r=t.tool_calls.slice(0,25),i=t.tool_calls.slice(25),{ToolRegistry:c}=await import('./registry-GGSZXBFC.mjs'),l=await c.tools({modelId:"",providerId:""}),d=new Map(l.map(g=>[g.id,g])),m=async g=>{let I=Date.now(),T=s.ascending("part");try{if(mu.has(g.tool))throw new Error(`Tool '${g.tool}' is not allowed in batch. Disallowed tools: ${Array.from(mu).join(", ")}`);let y=d.get(g.tool);if(!y){let k=Array.from(d.keys()).filter(v=>!HS.has(v));throw new Error(`Tool '${g.tool}' not in registry. External tools (MCP, environment) cannot be batched - call them directly. Available tools: ${k.join(", ")}`)}let x=y.parameters.parse(g.parameters);await o.updatePart({id:T,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:g.tool,callId:T,state:{status:"running",input:g.parameters,time:{start:I}}});let b=await y.execute(x,{...n,callId:T}),w;return b.attachments&&b.attachments.length>0&&(w=b.attachments.map(k=>({...k,id:k.id??s.ascending("part"),sessionId:k.sessionId??n.sessionId,messageId:k.messageId??n.messageId}))),await o.updatePart({id:T,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:g.tool,callId:T,state:{status:"completed",input:g.parameters,output:b.output,title:b.title,metadata:b.metadata,attachments:w,time:{start:I,end:Date.now()}}}),{success:!0,tool:g.tool,result:b}}catch(y){return await o.updatePart({id:T,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:g.tool,callId:T,state:{status:"error",input:g.parameters,error:y instanceof Error?y.message:String(y),time:{start:I,end:Date.now()}}}),{success:false,tool:g.tool,error:y}}},f=await Promise.all(r.map(g=>m(g))),a=Date.now();for(let g of i){let I=s.ascending("part");await o.updatePart({id:I,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:g.tool,callId:I,state:{status:"error",input:g.parameters,error:"Maximum of 25 tools allowed in batch",time:{start:a,end:a}}}),f.push({success:false,tool:g.tool,error:new Error("Maximum of 25 tools allowed in batch")});}let p=f.filter(g=>g.success).length,u=f.length-p,h=u>0?`Executed ${p}/${f.length} tools successfully. ${u} failed.`:`All ${p} tools executed successfully.
|
|
642
|
+
|
|
643
|
+
Keep using the batch tool for optimal performance in your next response!`;return {title:`Batch execution (${p}/${f.length} successful)`,output:h,attachments:f.filter(g=>g.success).flatMap(g=>g.result.attachments??[]),metadata:{totalCalls:f.length,successful:p,failed:u,tools:t.tool_calls.map(g=>g.tool),details:f.map(g=>({tool:g.tool,success:g.success}))}}}}});var lo;(s=>{s.Info=N.object({content:N.string().describe("Brief description of the task"),status:N.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),priority:N.string().describe("Priority level of the task: high, medium, low"),id:N.string().describe("Unique identifier for the todo item")}).meta({ref:"Todo"}),s.Event={Updated:a$5.define("todo.updated",N.object({sessionId:N.string(),todos:N.array(s.Info)}))};async function n(r){await a$6.write(["todo",r.sessionId],r.todos),await pe.publish(s.Event.Updated,r);}s.update=n;async function o(r){return a$6.read(["todo",r]).then(i=>i||[]).catch(()=>[])}s.get=o;})(lo||(lo={}));var GS=loadTextFile("./todo.txt",import.meta.url),WS=GS(),Hf={write:N.object({operation:N.literal("write").describe("Write or update TODO list"),todos:N.union([N.array(lo.Info),N.string()]).describe("The updated todo list")}),read:N.object({operation:N.literal("read").describe("Read current TODO list")})},VS=N.discriminatedUnion("operation",[Hf.write,Hf.read]),Bf=De.define("todo",{description:WS,parameters:VS,formatValidationError(e){return `Todo tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(Rt.check(t.abort,"todo"),e.operation==="write")return KS(e,t);if(e.operation==="read")return JS(e,t);throw new Error(`Unknown operation: ${e.operation}`)}});async function KS(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let n=[];if(typeof e.todos=="string")try{n=JSON.parse(e.todos);}catch{throw new Error("Invalid todos format: expected JSON array or array")}else n=e.todos;await lo.update({sessionId:t.sessionId,todos:n});let o=n.filter(s=>s.status!=="completed").length;return {title:`${o} todos`,output:JSON.stringify(n,null,2),metadata:{operation:"write",total:n.length,active:o,todos:n}}}async function JS(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let n=await lo.get(t.sessionId),o=n.filter(s=>s.status!=="completed").length;return {title:`${o} todos`,metadata:{operation:"read",total:n.length,active:o,todos:n},output:JSON.stringify(n,null,2)}}var eC=loadTextFile("./webfetch.txt",import.meta.url),tC=eC(),Wf=5*1024*1024,Vf=2*1024*1024,nC=30*1e3,oC=120*1e3,Kf=De.define("webfetch",{description:tC,parameters:N.object({url:N.string().describe("The URL to fetch content from"),format:N.enum(["text","markdown","html"]).default("markdown").describe("The format to return the content in (text, markdown, or html). Defaults to markdown."),timeout:N.number().describe("Optional timeout in seconds (max 120)").optional()}),formatValidationError(e){return `WebFetch tool validation error:
|
|
644
|
+
${e.issues.map(n=>n.path.includes("format")?`Invalid format parameter: "${"received"in n?n.received:"unknown"}". Must be one of: "text", "markdown", or "html". Defaults to "markdown" if not specified.`:n.path.includes("url")?`Invalid URL: ${n.message}. URL must start with http:// or https://.`:n.path.includes("timeout")?`Invalid timeout: ${n.message}. Timeout must be a number (max 120 seconds).`:n.message).join(`
|
|
645
|
+
`)}`},async execute(e,t){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");await t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let n=Math.min((e.timeout??nC/1e3)*1e3,oC),{signal:o,clearTimeout:s}=abortAfterAny(n,t.abort),r="*/*";switch(e.format){case "markdown":r="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case "text":r="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case "html":r="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:r="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";}let i={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:r,"Accept-Language":"en-US,en;q=0.9"},c;try{let I=await Fetch.get(e.url,{signal:o,headers:i,responseType:"arrayBuffer"});c={ok:I.ok,status:I.status,statusText:I.statusText,headers:I.headers,arrayBuffer:async()=>Promise.resolve(I.data)};}catch(I){if(s(),I instanceof Error){if(I.name==="AbortError")throw new Error(`Request timed out after ${n/1e3} seconds. Try increasing the timeout parameter.`);if(I.message.includes("fetch failed"))throw new Error(`Failed to fetch URL: ${e.url}. The server may be unreachable or blocking requests. Original error: ${I.message}`)}throw I}let l=c.status===403&&c.headers.get("cf-mitigated")==="challenge"?await(async()=>{let I=await Fetch.get(e.url,{signal:o,headers:{...i,"User-Agent":"easbot"},responseType:"arrayBuffer"});return {ok:I.ok,status:I.status,statusText:I.statusText,headers:I.headers,arrayBuffer:async()=>Promise.resolve(I.data)}})():c;if(s(),!l.ok){let I=l.statusText||"Unknown error";throw new Error(`Request failed with status ${l.status} (${I}). The server may be blocking requests or the URL may be incorrect.`)}let d=l.headers.get("content-length");if(d&&parseInt(d,10)>Wf)throw new Error("Response too large (exceeds 5MB limit)");let m=await l.arrayBuffer();if(m.byteLength>Wf)throw new Error("Response too large (exceeds 5MB limit)");let f=l.headers.get("content-type")||"",a=f.split(";")[0]?.trim().toLowerCase()||"",p=`${e.url} (${f})`;if(a.startsWith("image/")&&a!=="image/svg+xml"&&a!=="image/vnd.fastbidsheet"){if(m.byteLength>Vf)return {title:p,output:`Image fetched successfully but too large to display (${(m.byteLength/1024/1024).toFixed(2)}MB, max ${Vf/1024/1024}MB). Image URL: ${e.url}`,metadata:{size:m.byteLength,mime:a,url:e.url}};try{let I=Buffer.from(m).toString("base64");return {title:p,output:`Image fetched successfully (${(m.byteLength/1024).toFixed(2)}KB)`,metadata:{size:m.byteLength,mime:a,url:e.url},attachments:[{type:"file",mime:a,url:`data:${a};base64,${I}`}]}}catch(I){return {title:p,output:`Image fetched but failed to convert to base64: ${I instanceof Error?I.message:"Unknown error"}. Image URL: ${e.url}`,metadata:{size:m.byteLength,mime:a,url:e.url}}}}let h=new TextDecoder().decode(m),g=m.byteLength;switch(e.format){case "markdown":return f.includes("text/html")?{output:rC(h),title:p,metadata:{size:g,mime:a,url:e.url}}:{output:h,title:p,metadata:{size:g,mime:a,url:e.url}};case "text":return f.includes("text/html")?{output:await sC(h),title:p,metadata:{size:g,mime:a,url:e.url}}:{output:h,title:p,metadata:{size:g,mime:a,url:e.url}};case "html":return {output:h,title:p,metadata:{size:g,mime:a,url:e.url}};default:return {output:h,title:p,metadata:{size:g,mime:a,url:e.url}}}}});async function sC(e){try{let t=parse(e),n=["script","style","noscript","iframe","object","embed","svg","head"];for(let r of n){let i=t.querySelectorAll(r);for(let c of i)c.remove();}let o=t.querySelector("body"),s=o?o.textContent||o.text||"":t.textContent||t.text||"";return s=s.replace(/<[^>]+>/g," "),s=s.replace(/\s+/g," ").trim(),s}catch{let n=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi,"").replace(/<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,"").replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi,"");return n=n.replace(/<[^>]+>/g," "),n=n.replace(/\s+/g," ").trim(),n}}function rC(e){let t=new QS({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}var cC=loadTextFile("./write.txt",import.meta.url),dC=cC(),hu=20;var Yf=De.define("write",{description:dC,parameters:N.object({content:N.string().describe("The content to write to the file"),filePath:N.string().describe("The absolute path to the file to write (must be absolute, not relative)")}),async execute(e,t){Rt.check(t.abort,"write");let n=Filesystem.normalize(Se.isAbsolute(e.filePath)?e.filePath:Filesystem.join(R.directory,e.filePath));await Jt(t,n,{tool:"write"});let o=PKG.file(n),s=await o.exists(),r=s?await o.text():"";s&&await An.assert(t.sessionId,n);let i=Lo(createTwoFilesPatch(n,n,r,e.content));await t.ask({permission:"edit",patterns:[Se.posix.relative(R.worktree,n)],always:["*"],metadata:{filepath:n,diff:i}}),Rt.check(t.abort,"write"),await PKG.write(n,e.content),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Fn.Event.Updated,{file:n,event:s?"change":"add"}),An.read(t.sessionId,n);let c="Wrote file successfully.";Rt.check(t.abort,"write");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(n,true);let d=await We.getFileDiagnostics(n);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,hu),a=m.length>hu?`
|
|
646
|
+
... and ${m.length-hu} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
|
|
647
|
+
|
|
648
|
+
LSP errors detected in this file, please fix:
|
|
649
|
+
<diagnostics file="${n}">
|
|
650
|
+
${p.join(`
|
|
651
|
+
`)}${a}
|
|
652
|
+
</diagnostics>`;}}return {title:Se.posix.relative(R.worktree,n),metadata:{diagnostics:{[Filesystem.normalize(n)]:l},filepath:n,exists:s},output:c}}});var Xf=De.define("invalid",{description:"Do not use",parameters:N.object({tool:N.string(),error:N.string()}),async execute(e){return {title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}}});var eg=De.define("skill",async()=>{let e=["Load a specialized skill that provides domain-specific instructions and workflows.","","When you recognize that a task matches one of the available skills, use this tool to load the full skill instructions.","","The skill will inject detailed instructions, workflows, and access to bundled resources (scripts, references, templates) into the conversation context.","",'Tool output includes a `<skill_content name="...">` block with the loaded content.'].join(`
|
|
653
|
+
`),t=N.object({name:N.string().describe("The name of the skill to load")});return {description:e,parameters:t,async execute(n,o){let s=await Y.getContextMode(o.sessionId),r=await Ue.get(o.agent),i=await Vt.available(r,s),c=await Vt.get(n.name);if(!c){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${n.name}" not found. Available skills: ${p}`)}if(!i.some(p=>p.name===n.name)){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${n.name}" is not available. Available skills: ${p}`)}await o.ask({permission:"skill",patterns:[n.name],always:[n.name],metadata:{}});let d=Se__default.posix.dirname(c.location),m=pathToFileURL(d).href,f=10,a=await iife(async()=>{let p=[];for await(let u of a$8.files({cwd:d,follow:false,hidden:true,signal:o.abort}))if(!u.includes("SKILL.md")&&(p.push(Se__default.posix.join(d,u)),p.length>=f))break;return p}).then(p=>p.map(u=>`<file>${u}</file>`).join(`
|
|
654
|
+
`));return {title:`Loaded skill: ${c.name}`,output:[`<skill_content name="${c.name}">`,`# Skill: ${c.name}`,"",c.content.trim(),"",`Base directory for this skill: ${m}`,"Relative paths in this skill (e.g., scripts/, references/) are relative to this base directory.","If you need to load references or scripts files, use the Read tool with paths relative to this base directory.","Note: file list is sampled.","","<skill_files>",a,"</skill_files>","</skill_content>"].join(`
|
|
655
|
+
`),metadata:{name:c.name,dir:d}}}}});var ot;(v=>{let e=a.create({service:"pty"}),t=1024*1024*2,n=64*1024,o=new TextEncoder,s=C=>{let E=JSON.stringify({cursor:C}),O=o.encode(E),U=new Uint8Array(O.length+1);return U[0]=0,U.set(O,1),U},r=lazy(async()=>pC);v.Info=N.object({id:Identifier.schema("pty"),title:N.string(),command:N.string(),args:N.array(N.string()),cwd:N.string(),status:N.enum(["running","exited"]),pid:N.number()}).meta({ref:"Pty"}),v.CreateInput=N.object({command:N.string().optional(),args:N.array(N.string()).optional(),cwd:N.string().optional(),title:N.string().optional(),env:N.record(N.string(),N.string()).optional(),persistent:N.boolean().optional().default(true)}),v.UpdateInput=N.object({title:N.string().optional(),size:N.object({rows:N.number(),cols:N.number()}).optional()}),v.Event={Created:a$5.define("pty.created",N.object({info:v.Info})),Updated:a$5.define("pty.updated",N.object({info:v.Info})),Exited:a$5.define("pty.exited",N.object({id:Identifier.schema("pty"),exitCode:N.number()})),Deleted:a$5.define("pty.deleted",N.object({id:Identifier.schema("pty")}))};let m;function f(){return m||(m=R.state(()=>new Map,async C=>{for(let E of C.values()){try{E.process.kill();}catch{}for(let O of E.subscribers)O.close();}C.clear();})),m}function a$1(){return f()()}let p=new Map;async function u(){let C=a$1();return Array.from(C.values()).map(E=>E.info)}v.list=u;async function h(C){return a$1().get(C)?.info}v.get=h;async function g(C){let E=Identifier.create("pty",false),O=C.persistent??true,U=process.platform==="win32"?"cmd":Shell.acceptable(),D=C.command||U,K=C.args||[],X=C.cwd||R.directory,M=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:X})).output?.env??{},A={...process.env,...C.env,...M,TERM:"xterm-256color",EASBOT_TERMINAL:"1"};process.platform==="win32"&&(A.LANG="en_US.UTF-8",A.LC_ALL="en_US.UTF-8",A.LC_CTYPE="en_US.UTF-8");let L=D;if(process.platform==="win32"){let{PKG:le}=await import('@easbot/utils'),ae=await le.which(L);if(ae)e.debug("resolved command path",{original:L,resolved:ae});else {e.warn("command not found in PATH, trying PKG.which() fallback",{command:L});let we=L?.toLowerCase(),re=null;if(we==="cmd.exe"||we==="cmd"?re="cmd":we==="powershell.exe"||we==="powershell"?re="powershell":we==="pwsh.exe"||we==="pwsh"?re="pwsh":we==="wsl.exe"||we==="wsl"?re="wsl":re=Shell.acceptable(we)??"",re){let Q=await le.which(re);Q?(e.debug("found command via PKG.which()",{original:L,resolved:Q})):(e.warn("command not found, using original",{command:L}),L);}else e.warn("unknown command type, using original",{command:L});}}let P=D??"",_=[...K];P.endsWith("sh")&&_.push("-l"),e.debug("creating PTY session",{id:E,cmd:P,args:_,cwd:X,platform:process.platform});let j=await r(),B;try{B=j.spawn(P,_,{name:"xterm-256color",cwd:X,env:A}),e.debug("PTY process spawned successfully",{id:E,pid:B.pid});}catch(le){let ae=le instanceof Error?le.message:String(le);e.error("Failed to spawn PTY process",{command:P,args:_,cwd:X,platform:process.platform,error:ae,stack:le instanceof Error?le.stack:void 0});let we="";throw ae.includes("ENOENT")||ae.includes("not found")?we=`
|
|
656
|
+
|
|
657
|
+
\u{1F4A1} Hint: The command "${P}" was not found. Please ensure:
|
|
658
|
+
- The command is installed and available in PATH
|
|
659
|
+
- On Windows, use full path like "cmd.exe" or "powershell.exe"
|
|
660
|
+
- On Unix, use full path like "/bin/bash" or "/usr/bin/ssh"`:ae.includes("permission")&&(we=`
|
|
661
|
+
|
|
662
|
+
\u{1F4A1} Hint: Permission denied. Please check file permissions.`),new Error(`Failed to create PTY session: ${ae}${we}`)}let Z={id:E,title:C.title||`Terminal ${E.slice(-4)}`,command:D,args:_,cwd:X,status:"running",pid:B.pid},ee={info:Z,process:B,buffer:"",bufferCursor:0,cursor:0,subscribers:new Set};return a$1().set(E,ee),B.onData(le=>{ee.cursor+=le.length;for(let we of ee.subscribers){if(we.readyState!==1){ee.subscribers.delete(we);continue}we.send(le);}if(ee.buffer+=le,ee.buffer.length<=t)return;let ae=ee.buffer.length-t;ee.buffer=ee.buffer.slice(ae),ee.bufferCursor+=ae;}),B.onExit(async({exitCode:le})=>{e.debug("session exited",{id:E,exitCode:le,persistent:O}),ee.info.status="exited";for(let ae of ee.subscribers)ae.close();ee.subscribers.clear(),await pe.publish(v.Event.Exited,{id:E,exitCode:le}),O?e.debug("persistent session, keeping for reconnection",{id:E,exitCode:le}):(e.debug("non-persistent session, deleting",{id:E,exitCode:le}),p.set(E,le),a$1().delete(E));}),await pe.publish(v.Event.Created,{info:Z}),Z}v.create=g;async function I(C,E){let U=a$1().get(C);if(!U)throw new Error(`Session ${C} not found`);if(E.title&&(U.info.title=E.title),(E?.size?.cols??0)>0&&(E?.size?.rows??0)>0){if(U.info.status==="exited")throw new Error(`Session ${C} has exited (PID: ${U.info.pid}). Cannot resize. Use 'remove' to delete and create a new session.`);U.process.resize(E?.size?.cols??0,E?.size?.rows??0);}return await pe.publish(v.Event.Updated,{info:U.info}),U.info}v.update=I;async function T(C){let E=a$1(),O=E.get(C);if(!O)throw new Error(`Session ${C} not found`);e.debug("removing session",{id:C,pid:O.info.pid,status:O.info.status});try{O.process.kill();}catch{}for(let U of O.subscribers)U.close();E.delete(C),p.delete(C),await pe.publish(v.Event.Deleted,{id:C});}v.remove=T;async function y(C,E,O){let D=a$1().get(C);if(!D)throw new Error(`Session ${C} not found`);if(D.info.status==="exited")throw e.warn("cannot resize exited session",{id:C}),new Error(`Session ${C} has exited (PID: ${D.info.pid}). Use 'remove' to delete it and create a new session.`);D.process.resize(E,O);}v.resize=y;async function x(C,E){let U=a$1().get(C);if(!U)throw new Error(`Session ${C} not found`);if(U.info.status==="exited")throw e.warn("cannot write to exited session",{id:C}),new Error(`Session ${C} has exited (PID: ${U.info.pid}). Use 'remove' to delete it and create a new session.`);U.process.write(E);}v.write=x;async function b(C,E,O){let D=a$1().get(C);if(!D)return e.warn("cannot connect to non-existent session",{id:C}),E.close(),{onMessage:()=>{},onClose:()=>{}};e.debug("client connected to session",{id:C,status:D.info.status});let K=D.bufferCursor,X=D.cursor,$=O===-1?X:typeof O=="number"&&Number.isSafeInteger(O)?Math.max(0,O):0,M=(()=>{if(!D.buffer||$>=X)return "";let A=Math.max(0,$-K);return A>=D.buffer.length?"":D.buffer.slice(A)})();if(M)try{for(let A=0;A<M.length;A+=n)E.send(M.slice(A,A+n));}catch{E.close();return}try{E.send(s(X));}catch{E.close();return}return D.subscribers.add(E),{onMessage:A=>{D.process.write(String(A));},onClose:()=>{e.debug("client disconnected from session",{id:C}),D.subscribers.delete(E);}}}v.connect=b;async function w(C){let O=a$1().get(C);if(O)return {buffer:O.buffer,cursor:O.cursor,bufferCursor:O.bufferCursor}}v.getBuffer=w;async function k(C,E){let U=a$1().get(C);if(!U){let X=p.get(C);if(X!==void 0)return e.debug("subscribing to exited session",{id:C,exitCode:X}),E.onExit&&E.onExit(X),()=>{};throw e.warn("session not found for subscription",{id:C}),new Error(`Session ${C} not found`)}let D={readyState:1,send:X=>{typeof X=="string"&&E.onData&&E.onData(X);},close:()=>{}};U.subscribers.add(D);let K;return E.onExit&&(K=pe.subscribe(v.Event.Exited,X=>{X.properties.id===C&&E.onExit&&E.onExit(X.properties.exitCode);})),()=>{U.subscribers.delete(D),K&&K();}}v.subscribe=k;})(ot||(ot={}));var fC=loadTextFile("./pty_session.txt",import.meta.url),gC=loadTextFile("./pty_manage.txt",import.meta.url),hC=fC(),yC=gC(),ng=a.create({service:"tool.pty"}),Mr={BUFFER_SIZE_LIMIT:8*1024,MAX_LINES:200,DEFAULT_COLS:120,DEFAULT_ROWS:30},bC=N.object({action:N.enum(["list","get","resize","write","close"]).describe("Management action to perform"),sessionId:N.string().optional().describe("Session ID for get/resize/write/close actions"),cols:N.number().optional().describe("New columns for resize action"),rows:N.number().optional().describe("New rows for resize action"),data:N.string().optional().describe("Data to write to session")}),sg=De.define("pty_manage",{description:yC,parameters:bC,async execute(e,t){if(await t.ask({permission:"pty_manage",patterns:[e.action],always:["*"],metadata:{action:e.action,sessionId:e.sessionId}}),t.abort.aborted)throw new Error("Operation aborted");switch(e.action){case "list":{let n=await ot.list(),o=n.length===0?"No active PTY sessions":`Active PTY Sessions (${n.length}):
|
|
663
|
+
${n.map(s=>`- ${s.id}: ${s.title} (PID: ${s.pid}, Status: ${s.status})`).join(`
|
|
664
|
+
`)}`;return {title:"PTY Sessions",metadata:{action:"list",sessionCount:n.length,sessions:n.map(s=>({id:s.id,title:s.title,command:s.command,pid:s.pid,status:s.status}))},output:o}}case "get":{if(!e.sessionId)throw new Error("sessionId is required for get action");let n=await ot.get(e.sessionId);if(!n)return {title:"Session Not Found",metadata:{action:"get",found:false,sessionCount:0,sessions:[]},output:`No session found with ID: ${e.sessionId}`};let o=await ot.getBuffer(e.sessionId),s=o?.buffer||"";return {title:`Session ${e.sessionId}`,metadata:{action:"get",found:true,sessionCount:1,sessions:[{id:n.id,title:n.title,command:n.command,pid:n.pid,status:n.status}],session:{id:n.id,title:n.title,command:n.command,cwd:n.cwd,pid:n.pid,status:n.status},bufferSize:s.length,cursor:o?.cursor,bufferCursor:o?.bufferCursor},output:`Session Details:
|
|
665
|
+
ID: ${n.id}
|
|
666
|
+
Title: ${n.title}
|
|
667
|
+
Command: ${n.command}
|
|
668
|
+
PID: ${n.pid}
|
|
669
|
+
Status: ${n.status}
|
|
670
|
+
CWD: ${n.cwd}
|
|
671
|
+
|
|
672
|
+
Output Buffer (${s.length} characters):
|
|
673
|
+
${s||"(no output yet)"}`}}case "resize":{if(!e.sessionId||e.cols===void 0||e.rows===void 0)throw new Error("sessionId, cols, and rows are required for resize action");return await ot.resize(e.sessionId,e.cols,e.rows),{title:"Session Resized",metadata:{action:"resize",sessionId:e.sessionId,cols:e.cols,rows:e.rows,sessionCount:1,sessions:[]},output:`Session ${e.sessionId} resized to ${e.cols}x${e.rows}`}}case "write":{if(!e.sessionId||e.data===void 0)throw new Error("sessionId and data are required for write action");let n=process.platform==="win32"?e.data.replace(/\n/g,`\r
|
|
674
|
+
`):e.data;return await ot.write(e.sessionId,n),{title:"Data Written",metadata:{action:"write",sessionId:e.sessionId,dataLength:n.length,sessionCount:1,sessions:[]},output:`Wrote ${n.length} characters to session ${e.sessionId}`}}case "close":{if(!e.sessionId)throw new Error("sessionId is required for close action");return await ot.remove(e.sessionId),{title:"Session Closed",metadata:{action:"close",sessionId:e.sessionId,sessionCount:0,sessions:[]},output:`Session ${e.sessionId} closed successfully`}}default:throw new Error(`Unsupported action: ${e.action}`)}}}),rg=De.define("pty_session",{description:hC,parameters:N.object({command:N.string().describe("Initial command to run in session"),args:N.array(N.string()).optional().describe("Command arguments"),cwd:N.string().optional().describe("Working directory (defaults to project directory)"),env:N.record(N.string(),N.string()).optional().describe("Environment variables"),sessionName:N.string().optional().describe("Session name for identification"),cols:N.number().min(10).max(500).optional().default(Mr.DEFAULT_COLS).describe("Terminal columns (default: 120)"),rows:N.number().min(5).max(200).optional().default(Mr.DEFAULT_ROWS).describe("Terminal rows (default: 30)"),truncateMode:N.enum(["head","tail"]).optional().default("tail").describe("Truncation mode: head (keep beginning) or tail (keep end, default for PTY sessions)"),persistent:N.boolean().optional().default(true).describe("Keep session running after initial command completes (default: true, for SSH/long-running connections)")}),async execute(e,t){let n=e.command,o=e.args||[];await t.ask({permission:"pty_session",patterns:[e.command],always:[`${e.command} *`],metadata:{command:e.command,args:e.args,cwd:e.cwd||R.directory,sessionName:e.sessionName}});let s=e.cwd||R.directory,r=e.cols??Mr.DEFAULT_COLS,i=e.rows??Mr.DEFAULT_ROWS;try{if(t.abort.aborted)throw new Error("Operation aborted");let c=await ot.create({command:n,args:o,cwd:s,env:e.env,title:e.sessionName||`Interactive Session: ${e.command}`,persistent:e.persistent??!0});return r&&i&&await ot.resize(c.id,r,i),ng.debug("PTY session created successfully",{sessionId:c.id,command:c.command,pid:c.pid,status:c.status}),{title:`PTY Session Created: ${e.sessionName||e.command}`,metadata:{sessionId:c.id,sessionName:e.sessionName||c.title,command:c.command,pid:c.pid,status:c.status,truncateMode:e.truncateMode,persistent:e.persistent,websocketSupport:!0},output:`PTY session created successfully.
|
|
675
|
+
|
|
676
|
+
Session ID: ${c.id}
|
|
677
|
+
Session Name: ${e.sessionName||c.title}
|
|
678
|
+
Command: ${c.command}
|
|
679
|
+
PID: ${c.pid}
|
|
680
|
+
Status: ${c.status}
|
|
681
|
+
Output Limit: ${Mr.BUFFER_SIZE_LIMIT/1024}KB / ${Mr.MAX_LINES} lines
|
|
682
|
+
Truncate Mode: ${e.truncateMode||"tail"} (${e.truncateMode==="head"?"keeps beginning of output":"keeps latest output for interactive use"})
|
|
683
|
+
|
|
684
|
+
\u26A0\uFE0F IMPORTANT: This session will run in the background until explicitly closed.
|
|
685
|
+
Use pty_manage tool to interact with this session:
|
|
686
|
+
- Send input: pty_manage { "action": "write", "sessionId": "${c.id}", "data": "your command\\n" }
|
|
687
|
+
- Check status: pty_manage { "action": "get", "sessionId": "${c.id}" }
|
|
688
|
+
- Close session: pty_manage { "action": "close", "sessionId": "${c.id}" }
|
|
689
|
+
|
|
690
|
+
\u26A0\uFE0F RESOURCE WARNING: Remember to close unused sessions to prevent resource exhaustion!`}}catch(c){let l=c instanceof Error?c.message:String(c),d=c instanceof Error?c.stack:void 0;throw ng.error("PTY session creation failed",{command:e.command,args:e.args,cwd:s,error:l,stack:d}),new Error(`Failed to create PTY session: ${l}`)}}});var vC=loadTextFile("./websearch.txt",import.meta.url),SC=vC(),bu={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{SEARCH:"/mcp"},DEFAULT_NUM_RESULTS:8},ig=De.define("websearch",async()=>({get description(){return SC.replace("{{year}}",new Date().getFullYear().toString())},parameters:N.object({query:N.string().describe("Websearch query"),numResults:N.number().optional().describe("Number of search results to return (default: 8)"),livecrawl:N.enum(["fallback","preferred"]).optional().describe("Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')"),type:N.enum(["auto","fast","deep"]).optional().describe("Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"),contextMaxCharacters:N.number().optional().describe("Maximum characters for context string optimized for LLMs (default: 10000)")}),async execute(e,t){await t.ask({permission:"websearch",patterns:[e.query],always:["*"],metadata:{query:e.query,numResults:e.numResults,livecrawl:e.livecrawl,type:e.type,contextMaxCharacters:e.contextMaxCharacters}});let n={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||bu.DEFAULT_NUM_RESULTS,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}},{signal:o,clearTimeout:s}=abortAfterAny(25e3,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${bu.BASE_URL}${bu.ENDPOINTS.SEARCH}`,n,{headers:r,responseType:"text",signal:o});if(s(),!i.ok)throw new Error(`Search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
|
|
691
|
+
`);for(let d of l)if(d.startsWith("data: ")){let m=JSON.parse(d.substring(6));if(m.result?.content&&m.result.content.length>0){let f=m.result.content[0]?.text;if(f)return {output:f,title:`Web search: ${e.query}`,metadata:{query:e.query}}}}return {output:"No search results found. Please try a different query.",title:`Web search: ${e.query}`,metadata:{query:e.query}}}catch(r){throw s(),r instanceof Error&&r.name==="AbortError"?new Error("Search request timed out"):r}}}));var TC=loadTextFile("./codesearch.txt",import.meta.url),AC=TC(),ag={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{CONTEXT:"/mcp"}},cg=De.define("codesearch",{scope:g.Coder,description:AC,parameters:N.object({query:N.string().describe("Search query to find relevant context for APIs, Libraries, and SDKs. For example, 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware', 'Next js partial prerendering configuration'"),tokensNum:N.number().min(1e3).max(5e4).default(5e3).describe("Number of tokens to return (1000-50000). Default is 5000 tokens. Adjust this value based on how much context you need - use lower values for focused queries and higher values for comprehensive documentation.")}),async execute(e,t){await t.ask({permission:"codesearch",patterns:[e.query],always:["*"],metadata:{query:e.query,tokensNum:e.tokensNum}});let n={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:e.query,tokensNum:e.tokensNum||5e3}}},{signal:o,clearTimeout:s}=abortAfterAny(3e4,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${ag.BASE_URL}${ag.ENDPOINTS.CONTEXT}`,n,{headers:r,responseType:"text",signal:o});if(s(),!i.ok)throw new Error(`Code search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
|
|
692
|
+
`);for(let d of l)if(d.startsWith("data: ")){let m=JSON.parse(d.substring(6));if(m.result?.content&&m.result.content.length>0){let f=m.result.content[0]?.text;if(f)return {output:f,title:`Code search: ${e.query}`,metadata:{}}}}return {output:"No code snippets or documentation found. Please try a different query, be more specific about the library or programming concept, or check the spelling of framework names.",title:`Code search: ${e.query}`,metadata:{}}}catch(r){throw s(),r instanceof Error&&r.name==="AbortError"?new Error("Code search request timed out"):r}}});var xu=a.create({service:"tool.note"}),RC=loadTextFile("./note.txt",import.meta.url),_C=RC(),MC=10,OC=800,dg=30,lg=1500,jC=10,LC=500,DC=N.discriminatedUnion("operation",[N.object({operation:N.literal("search"),query:N.string().optional().describe("Search query for note content"),maxResults:N.number().optional().default(10).describe("Maximum number of results to return"),minScore:N.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),N.object({operation:N.literal("queryEdges"),nodeId:N.number().describe("Node ID to query relations"),maxDepth:N.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function $C(e,t){if(e.length===0)return `<note_context>
|
|
693
|
+
No note context found.
|
|
694
|
+
</note_context>`;let n=[];n.push(`<note_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=await Ve.output(s.snippet,{maxLines:MC,maxBytes:OC,contentType:"list",toolName:"note_snippet"},t);if(n.push(`[${o+1}]`),n.push(` document: ${s.document.path}`),n.push(` lines: ${s.chunk.startLine}-${s.chunk.endLine}`),n.push(` score: ${s.score.toFixed(4)}`),n.push(` source: ${s.source}`),n.push(` snippet: ${r.content}`),r.truncated&&n.push(` (snippet: ${r.outputPath})`),s.nodes&&s.nodes.length>0){let i=s.nodes.map(l=>{let d=[` - node: id=${l.id} type=${l.type} name=${l.name}`];if(l.edges&&l.edges.length>0)for(let m of l.edges){let f=m.source===l.id?"out":"in";m.targetNode?d.push(` \u2192 [${f}] ${m.relation} \u2192 ${m.targetNode.type}:${m.targetNode.name} (id=${m.target})`):d.push(` \u2192 [${f}] ${m.relation} \u2192 id=${m.target} (node not found)`);}return d.join(`
|
|
695
|
+
`)}).join(`
|
|
696
|
+
`),c=await Ve.output(i,{maxLines:dg,maxBytes:lg,contentType:"list",toolName:"note_nodes"},t);n.push(` nodes (${s.nodes.length}):`),n.push(c.content),c.truncated&&n.push(` (nodes: ${c.outputPath})`);}n.push("");}return n.push("</note_context>"),n.join(`
|
|
697
|
+
`)}var ug=De.define("note",{description:_C,parameters:DC,async execute(e,t){if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");let n={directory:t.extra.directory},o=await Yt.config(),s=n.directory;xu.debug("note tool execute",{operation:e.operation,...e.operation==="search"&&{query:e.query},directory:s,noteConfigLoaded:!!o,noteConfig:o?{search:o.search,sync:o.sync}:null}),await t.ask({permission:"note",patterns:[e.operation],always:["*"],metadata:{operation:e.operation,...e.operation==="search"&&{query:e.query},...e.operation==="queryEdges"&&{nodeId:e.nodeId},workspaceDir:s,noteConfigLoaded:!!o}});let r=await Yt.get();if(!r)return xu.warn("note kb not available"),{output:`<note_context>
|
|
698
|
+
Note knowledge base is not enabled or not properly configured.
|
|
699
|
+
</note_context>`,title:`Note: ${e.operation}`,metadata:{available:false,count:0,enabled:false}};if(e.operation==="search"){let i=o?.search?.minScore??.3,c=e.minScore!==void 0&&e.minScore!==null?Number(e.minScore):i,l=o?.search?.maxResults??10;xu.debug("note search params",{query:e.query,minScore:c,defaultMinScore:i,maxResults:e.maxResults??l,noteMinScore:o?.search?.minScore}),o?.sync?.onSearch&&r.sync().catch(()=>{});let d=await r.search(e.query??"",{maxResults:e.maxResults??l,minScore:c,includeEdges:true,enableEmbedding:true,enableFts:true});return {output:await $C(d,t.extra?.agent),title:`Note search: ${e.query??""}`,metadata:{available:true,operation:"search",total:d.length,query:e.query,enabled:true}}}if(e.operation==="queryEdges"){let i=typeof e.nodeId=="string"?parseInt(e.nodeId,10):e.nodeId,c=await r.queryNodes({ids:[i]});if(!c||c.length===0)return {output:`<note_queryEdges>
|
|
700
|
+
Node with id ${e.nodeId} not found.
|
|
701
|
+
</note_queryEdges>`,title:`Note queryEdges: ${e.nodeId}`,metadata:{available:true,operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:0}};let l=c[0],d=typeof e.maxDepth=="string"?parseInt(e.maxDepth,10):e.maxDepth??2,m=Math.min(d||2,3),f=await r.queryNeighbors(i,{limit:20,maxDepth:m}),a=20,p=f.edges.slice(0,a),u=f.nodes.map(y=>`[id=${y.id}] type=${y.type} name=${y.name}`).join(`
|
|
702
|
+
`),h=await Ve.output(u,{maxLines:dg,maxBytes:lg,contentType:"list",toolName:"note_neighbors"},t.extra?.agent),g=p.map(y=>{let x=y.source===i?"out":"in";return y.targetNode?` \u2192 [${x}] ${y.relation} \u2192 ${y.targetNode.type}:${y.targetNode.name} (id=${y.target})`:` \u2192 [${x}] ${y.relation} \u2192 id=${y.target} (node not found)`}).join(`
|
|
703
|
+
`);if(f.edges.length>a){let y=f.edges.length-a,x=p.length>0?`
|
|
704
|
+
`:"";g=g+x+` ... and ${y} more relations`;}let I=await Ve.output(g,{maxLines:jC,maxBytes:LC,contentType:"list",toolName:"note_edges"},t.extra?.agent),T=[];return T.push(`<note_queryEdges node_id="${e.nodeId}" name="${l.name}" type="${l.type}">`),T.push(`neighbors (${f.nodes.length}):`),T.push(h.content),h.truncated&&T.push(` (neighbors: ${h.outputPath})`),T.push(""),T.push(`relations (${f.edges.length}):`),T.push(I.content),I.truncated&&T.push(` (relations: ${I.outputPath})`),T.push("</note_queryEdges>"),{output:T.join(`
|
|
705
|
+
`),title:`Note queryEdges: ${e.nodeId}`,metadata:{available:true,operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:f.nodes.length}}}throw new Error(`Unknown operation: ${e.operation}`)}});var UC=loadTextFile("./memory.txt",import.meta.url),zC=UC()||"Access and manage memory system for agent operations",qC=10,HC=800,BC=30,GC=1500;async function WC(e,t){if(e.length===0)return `<memory_context>
|
|
706
|
+
No memories found.
|
|
707
|
+
</memory_context>`;let n=[];n.push(`<memory_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=new Date(s.createdAt),i=formatLocalISOCompact(r),c=Intl.DateTimeFormat().resolvedOptions().timeZone,l=await Ve.output(s.snippet,{maxLines:qC,maxBytes:HC,contentType:"list",toolName:"memory_snippet"},t);if(n.push(`[${o+1}]`),n.push(` id: ${s.memoryId}`),n.push(` [${s.category}] importance=${s.importance}`),n.push(` score: ${s.score.toFixed(4)}`),n.push(` created: ${i} (${c})`),n.push(` agent: ${s.agentId}`),n.push(` source: ${s.source}`),n.push(` snippet: ${l.content}`),l.truncated&&n.push(` (snippet: ${l.outputPath})`),s.filePath){let d=Filesystem.normalize(s.filePath);n.push(` file: ${d}`);}if(s.nodes&&s.nodes.length>0){let d=s.nodes.map(f=>{let a=[` - node: id=${f.id} type=${f.type} name=${f.name}`];if(f.edges&&f.edges.length>0)for(let p of f.edges){let u=p.source===f.id?"out":"in";p.targetNode?a.push(` \u2192 [${u}] ${p.relation} \u2192 ${p.targetNode.type}:${p.targetNode.name} (id=${p.target})`):a.push(` \u2192 [${u}] ${p.relation} \u2192 id=${p.target} (node not found)`);}return a.join(`
|
|
708
|
+
`)}).join(`
|
|
709
|
+
`),m=await Ve.output(d,{maxLines:BC,maxBytes:GC,contentType:"list",toolName:"memory_nodes"},t);n.push(` nodes (${s.nodes.length}):`),n.push(m.content),m.truncated&&n.push(` (nodes: ${m.outputPath})`);}n.push("");}return n.push("</memory_context>"),n.join(`
|
|
710
|
+
`)}function pg(e){if(e?.trim())return e.split(",").map(t=>t.trim()).filter(Boolean)}function mg(e){if(e)try{let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}catch{return}}var Iu=N.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),VC=N.discriminatedUnion("operation",[N.object({operation:N.literal("remember"),content:N.string().describe("Memory content to store"),category:Iu.describe("Memory category"),importance:N.coerce.number().min(1).max(10).describe("Importance score 1-10"),tags:N.string().optional().describe('Optional tags, comma-separated (e.g. "typescript, testing, api")')}),N.object({operation:N.literal("recall"),query:N.string().describe("Search query"),maxResults:N.coerce.number().optional().default(10).describe("Maximum number of results to return (default 10)"),minScore:N.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)"),category:Iu.optional().describe("Filter by memory category"),fromTime:N.string().optional().describe('Start time filter in local time (e.g. "2024-01-01 00:00:00" without timezone suffix), will be converted to UTC internally'),toTime:N.string().optional().describe('End time filter in local time (e.g. "2024-12-31 23:59:59" without timezone suffix), will be converted to UTC internally')}),N.object({operation:N.literal("queryEdges"),nodeId:N.coerce.number().describe("Node ID to query relations"),maxDepth:N.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")}),N.object({operation:N.literal("forget"),memoryId:N.string().describe("Memory ID to delete")}),N.object({operation:N.literal("update"),memoryId:N.string().describe("Memory ID to update"),content:N.string().optional().describe("Updated memory content"),importance:N.coerce.number().min(1).max(10).optional().describe("Updated importance score 1-10"),tags:N.string().optional().describe('Updated tags, comma-separated (e.g. "typescript, testing, api")')}),N.object({operation:N.literal("list"),maxResults:N.coerce.number().min(1).max(100).optional().default(20).describe("Maximum number of memories to list (default 20, max 100)"),category:Iu.optional().describe("Filter by memory category"),fromTime:N.string().optional().describe('Start time filter in local time (e.g. "2024-01-01 00:00:00")'),toTime:N.string().optional().describe('End time filter in local time (e.g. "2024-12-31 23:59:59")')})]),gg=De.define("memory",{description:zC,parameters:VC,formatValidationError(e){return `Memory tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){let n=t.extra?.directory??"unknown";await t.ask({permission:"memory",patterns:e.operation==="recall"?[e.query]:["*"],always:["*"],metadata:{operation:e.operation,workspaceDir:n}});let o=await In.get();if(!o)return {output:`<memory_context>
|
|
711
|
+
Memory system is not enabled or not properly configured.
|
|
712
|
+
</memory_context>`,title:`Memory: ${e.operation}`,metadata:{enabled:false,operation:e.operation,truncated:false}};let s=t.protocolMetadata?.agentId??t.agent;if(e.operation==="remember"){if(!e.category||e.importance==null)throw new Error("remember requires category and importance");let r;if(t.messageId){let c=await ve.get({sessionId:t.sessionId,messageId:t.messageId});c?.info.role==="assistant"&&(r=c.info.parentId);}let i=await o.remember({agentId:s,content:e.content,category:e.category,importance:e.importance,source:"session_self_write",tags:pg(e.tags),sessionId:t.sessionId,msgId:t.messageId,parentMsgId:r});return {output:`<memory_result>
|
|
713
|
+
Memory saved successfully.
|
|
714
|
+
id: ${i.id}
|
|
715
|
+
category: ${i.category}
|
|
716
|
+
importance: ${i.importance}
|
|
717
|
+
</memory_result>`,title:"Memory saved",metadata:{operation:"remember",enabled:true,memoryId:i.id,category:i.category,importance:i.importance,truncated:false}}}if(e.operation==="recall"){let i=(await In.config())?.search?.minScore??.3,c=await o.query(e.query,{agentId:s,maxResults:e.maxResults??10,minScore:e.minScore??i,category:e.category,fromTime:mg(e.fromTime),toTime:mg(e.toTime)}),l=t.extra?.agent;return {output:await WC(c,l),title:`Memory recall: ${e.query}`,metadata:{operation:"recall",enabled:true,total:c.length,query:e.query}}}if(e.operation==="queryEdges"){if(e.nodeId===void 0)throw new Error("nodeId is required for queryEdges operation");let r=typeof e.nodeId=="string"?parseInt(e.nodeId,10):e.nodeId,i=typeof e.maxDepth=="string"?parseInt(e.maxDepth,10):e.maxDepth??2,c=Math.min(i||2,3),l=await o.queryEdgesByNodeId(r,{maxDepth:c});if(!l.node)return {output:`<memory_queryEdges node_id="${e.nodeId}">
|
|
718
|
+
Node ${e.nodeId} not found.
|
|
719
|
+
</memory_queryEdges>`,title:`Memory queryEdges: ${e.nodeId}`,metadata:{operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:0}};let d=[];d.push(`<memory_queryEdges node_id="${e.nodeId}" name="${l.node.name}" type="${l.node.type}">`),d.push(`neighbors (${l.nodes.length}):`);for(let a of l.nodes)d.push(` [id=${a.id}] type=${a.type} name=${a.name}`);let m=20,f=l.edges.slice(0,m);d.push(`relations (${l.edges.length}):`);for(let a of f){let p=a.source===r?"out":"in";a.targetNode?d.push(` \u2192 [${p}] ${a.relation} \u2192 ${a.targetNode.type}:${a.targetNode.name} (id=${a.target})`):d.push(` \u2192 [${p}] ${a.relation} \u2192 id=${a.target} (node not found)`);}return l.edges.length>m&&d.push(` ... and ${l.edges.length-m} more relations`),d.push("</memory_queryEdges>"),{output:d.join(`
|
|
720
|
+
`),title:`Memory queryEdges: ${e.nodeId}`,metadata:{operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:l.edges.length}}}if(e.operation==="forget")try{return await o.forget(s,e.memoryId),{output:`<memory_result>
|
|
721
|
+
Memory ${e.memoryId} deleted successfully.
|
|
722
|
+
</memory_result>`,title:"Memory deleted",metadata:{operation:"forget",enabled:!0,memoryId:e.memoryId,truncated:!1}}}catch(r){if(r?.message?.includes("not found")||r?.name==="MemoryNotFoundError")return {output:`<memory_result>
|
|
723
|
+
Memory ${e.memoryId} not found or already deleted.
|
|
724
|
+
</memory_result>`,title:"Memory forget",metadata:{operation:"forget",enabled:true,memoryId:e.memoryId,truncated:false}};throw r}if(e.operation==="update")try{let r=await o.update(s,e.memoryId,{content:e.content,importance:e.importance,tags:pg(e.tags)});return {output:`<memory_result>
|
|
725
|
+
Memory ${r.id} updated successfully.
|
|
726
|
+
category: ${r.category}
|
|
727
|
+
importance: ${r.importance}
|
|
728
|
+
</memory_result>`,title:"Memory updated",metadata:{operation:"update",enabled:!0,memoryId:r.id,category:r.category,truncated:!1}}}catch(r){if(r?.name==="MemoryNotFoundError")return {output:`<memory_result>
|
|
729
|
+
Memory ${e.memoryId} not found. Please use 'list' to see available memory IDs.
|
|
730
|
+
</memory_result>`,title:"Memory update failed",metadata:{operation:"update",enabled:true,memoryId:e.memoryId,truncated:false}};throw r}if(e.operation==="list"){let r=await o.queryForSummary(s,{limit:e.maxResults??20,category:e.category,fromTime:e.fromTime,toTime:e.toTime});if(r.length===0)return {output:`<memory_context>
|
|
731
|
+
No memories found${e.category||e.fromTime||e.toTime?" with given filters":""}.
|
|
732
|
+
</memory_context>`,title:"Memory list",metadata:{operation:"list",enabled:true,total:0,truncated:false}};let i=[];i.push(`<memory_context total="${r.length}">`);for(let c=0;c<r.length;c++){let l=r[c],d=new Date(l.createdAt),m=formatLocalISOCompact(d);i.push(`[${c+1}] id=${l.id} [${l.category}] importance=${l.importance} created=${m}`),i.push(` ${l.content.slice(0,100)}${l.content.length>100?"...":""}`),l.tags&&l.tags.length>0&&i.push(` tags: ${l.tags.join(", ")}`);}return i.push("</memory_context>"),{output:i.join(`
|
|
733
|
+
`),title:`Memory list (${r.length})`,metadata:{operation:"list",enabled:true,total:r.length,truncated:false}}}throw new Error(`Unknown operation: ${e.operation}`)}});var JC=loadTextFile("./codebase.txt",import.meta.url),YC=JC()||"Access and analyze codebase knowledge graph for agent operations",XC=10,QC=1e3,qc=20,Hc=2e3,ZC=N.discriminatedUnion("operation",[N.object({operation:N.literal("search"),query:N.string().optional().describe("Search query for codebase content"),maxResults:N.number().optional().default(10).describe("Maximum number of results to return"),astType:N.string().optional().describe("Filter by AST type (e.g., class_declaration, function_declaration)"),language:N.string().optional().describe("Filter by programming language"),minScore:N.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),N.object({operation:N.literal("queryEdges"),nodeId:N.string().describe("Node ID to query relations"),direction:N.enum(["in","out","both"]).optional().default("both").describe("Edge direction: in (incoming), out (outgoing), both"),maxDepth:N.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function ek(e,t){if(e.length===0)return `<codebase_context>
|
|
734
|
+
No codebase results found.
|
|
735
|
+
</codebase_context>`;let n=[];n.push(`<codebase_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=await Ve.output(s.text,{maxLines:XC,maxBytes:QC,contentType:"output",toolName:"codebase_code"},t),i=s.edges?.map(l=>` \u2192 ${l.relation} \u2192 node:${l.target}`).join(`
|
|
736
|
+
`)||"";s.edges&&s.edges.length>0?await Ve.output(i,{maxLines:qc,maxBytes:Hc,contentType:"list",toolName:"codebase_edges"},t):null;if(n.push(`[${o+1}]`),n.push(` node id=${s.id}`),n.push(` type: ${s.ast_type}`),n.push(` language: ${s.language}`),n.push(` name: ${s.name}`),n.push(` location: ${s.file_path}:${s.start_line}`),n.push(` code: ${r.content.replace(/\s+/g," ")}`),s.edges&&s.edges.length>0){let l=new Map(e.map(f=>[f.id,f])),d=s.edges.map(f=>{let a=f.source===s.id?"out":"in",p=l.get(f.target),u=p?.ast_type||"unknown",h=p?.name||String(f.target);return ` \u2192 [${a}] ${f.relation} \u2192 target=${u}:${h} (id=${f.target})`}).join(`
|
|
737
|
+
`),m=await Ve.output(d,{maxLines:qc,maxBytes:Hc,contentType:"list",toolName:"codebase_edges"},t);n.push(` edges (${s.edges.length}):`),n.push(m.content);}n.push("");}return n.push("</codebase_context>"),n.join(`
|
|
738
|
+
`)}var hg=De.define("codebase",{scope:g.Coder,description:YC,parameters:ZC,formatValidationError(e){return `Codebase tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");await t.ask({permission:"codebase",patterns:[e.operation==="search"?e.query??"*":"*"],always:["*"],metadata:{operation:e.operation,...e.operation==="search"&&{query:e.query},...e.operation==="queryEdges"&&{nodeId:e.nodeId},workspaceDir:t.extra.directory}});let n=await jo.get();if(!n)return {output:`<codebase_context>
|
|
739
|
+
Codebase knowledge base is not enabled or not properly configured.
|
|
740
|
+
</codebase_context>`,title:`Codebase ${e.operation}`,metadata:{count:0,enabled:false,operation:e.operation}};if(e.operation==="search"){let s=(await jo.config())?.search?.minScore??.3,r=await n.search(e.query??"",{maxResults:e.maxResults??10,enableEmbedding:true,enableFts:true,astType:e.astType,minScore:e.minScore??s,language:e.language,includeEdges:true}),i=await ek(r,t.extra?.agent);return r.length===0&&e.astType&&(i+=`
|
|
741
|
+
|
|
742
|
+
<i>Tip: astType filter was applied but returned no results. Try without astType or use different astType value.</i>`),{output:i,title:`Codebase search: ${e.query??""}`,metadata:{count:r.length,query:e.query,enabled:true,operation:"search",astType:e.astType,language:e.language}}}if(e.operation==="queryEdges"){let o={in:"incoming",out:"outgoing",both:"both"},s=String(e.nodeId),r=await n.getNode(s),i=Math.min(e.maxDepth??2,3),{nodes:c,edges:l}=await n.queryNeighbors(s,{limit:50,maxDepth:i,direction:o[e.direction??"both"]});if((!l||l.length===0)&&!r)return {output:`<codebase_queryEdges node_id="${e.nodeId}">
|
|
743
|
+
Node ${e.nodeId} not found or has no relations.
|
|
744
|
+
</codebase_queryEdges>`,title:`Codebase queryEdges: ${e.nodeId}`,metadata:{count:0,nodeId:e.nodeId,direction:e.direction,enabled:true,operation:"queryEdges"}};let d=[];if(d.push(`<codebase_queryEdges node_id="${s}" name="${r?.name}" type="${r?.ast_type}" language="${r?.language}" location="${r?.file_path}:${r?.start_line}" direction="${e.direction??"both"}">`),d.push(`neighbors (${c.length}):`),c.length>0){let a=c.map(u=>`[id=${u.id}] type=${u.ast_type} name=${u.name} location=${u.file_path}:${u.start_line}`).join(`
|
|
745
|
+
`),p=await Ve.output(a,{maxLines:qc,maxBytes:Hc,contentType:"list",toolName:"codebase_neighbors"},t.extra?.agent);d.push(p.content);}d.push(""),d.push(`relations (${l.length}):`);let m=20,f=l.slice(0,m);if(l.length>0){let a=new Map(c.map(g=>[g.id,g])),p=[];for(let g of f){let I=g.source===s?"out":"in",T=a.get(g.target),y=T?.ast_type||"unknown",x=T?.name||String(g.target);p.push(` \u2192 [${I}] ${g.relation} \u2192 target=${y}:${x} (id=${g.target})`);}l.length>m&&p.push(` ... and ${l.length-m} more relations`);let u=p.join(`
|
|
746
|
+
`),h=await Ve.output(u,{maxLines:qc,maxBytes:Hc,contentType:"list",toolName:"codebase_edges"},t.extra?.agent);d.push(h.content);}return d.push("</codebase_queryEdges>"),{output:d.join(`
|
|
747
|
+
`),title:`Codebase queryEdges: ${s}`,metadata:{count:l.length,nodeId:s,direction:e.direction,enabled:true,operation:"queryEdges"}}}throw new Error(`Unknown operation: ${e.operation}`)}});var sk=loadTextFile("./lsp.txt",import.meta.url),rk=sk(),ik=200,ak=5*1024,ck=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],yg=De.define("lsp",{scope:g.Coder,isEnabled:()=>a$2.EASBOT_LSP_TOOL,description:rk,parameters:N.object({operation:N.enum(ck).describe("The LSP operation to perform"),filePath:N.string().describe("The absolute or relative path to the file"),line:N.number().int().min(1).describe("The line number (1-based, as shown in editors)"),character:N.number().int().min(1).describe("The character offset (1-based, as shown in editors)"),query:N.string().optional().describe("Search query for workspaceSymbol. Empty string requests all symbols.")}),formatValidationError(e){return `LSP tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},execute:async(e,t)=>{Rt.check(t.abort,"lsp");let n=Filesystem.normalize(Se__default.isAbsolute(e.filePath)?e.filePath:Se__default.join(R.directory,e.filePath));await Jt(t,n,{tool:"lsp"});let o=e.operation==="workspaceSymbol"?{operation:e.operation}:e.operation==="documentSymbol"?{operation:e.operation,filePath:n}:{operation:e.operation,filePath:n,line:e.line,character:e.character};await t.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:o});let s={file:n,line:e.line-1,character:e.character-1},r=Se__default.posix.relative(R.worktree,n),i=e.operation==="workspaceSymbol"?"":e.operation==="documentSymbol"?r:`${r}:${e.line}:${e.character}`,c=i?`${e.operation} ${i}`:e.operation;if(!await Tt__default.access(n).then(()=>true).catch(()=>false))throw new Error(`File not found: ${n}`);if(!await We.hasClients(n))throw new Error("No LSP server available for this file type.");await We.touchFile(n,true);let m=await Rt.wrap("lsp",t.abort,async()=>{switch(e.operation){case "goToDefinition":return We.definition(s);case "findReferences":return We.references(s);case "hover":return We.hover(s);case "documentSymbol":return We.documentSymbol({file:n});case "workspaceSymbol":return We.workspaceSymbol(e.query??"");case "goToImplementation":return We.implementation(s);case "prepareCallHierarchy":return We.prepareCallHierarchy(s);case "incomingCalls":return We.incomingCalls(s);case "outgoingCalls":return We.outgoingCalls(s)}}),f=m.length===0?`No results found for ${e.operation}`:JSON.stringify(m,null,2),a=await Ve.output(f,{maxLines:ik,maxBytes:ak,contentType:"output",toolName:"lsp"});return {title:c,metadata:{filepath:n,truncated:a.truncated,...a.truncated&&{outputPath:a.outputPath}},output:a.content}}});var lk=loadTextFile("./plan.txt",import.meta.url),uk=lk();async function xg(e){for await(let t of ve.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return xe.defaultModel()}var bg={enter:N.object({operation:N.literal("enter").describe("Enter plan mode for research and planning")}),exit:N.object({operation:N.literal("exit").describe("Exit plan mode and switch to build mode")})},pk=N.discriminatedUnion("operation",[bg.enter,bg.exit]),Ig=De.define("plan",{description:uk,parameters:pk,formatValidationError(e){return `Plan tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(e.operation==="enter")return mk(t);if(e.operation==="exit")return fk(t);throw new Error(`Unknown operation: ${e.operation}`)}});async function mk(e){let t=await Y.get(e.sessionId),n=Se__default.posix.relative(R.worktree,Y.plan(t));if((await Ot.ask({sessionId:e.sessionId,questions:[{question:`Would you like to switch to the plan agent and create a plan saved to ${n}?`,header:"Plan Mode",custom:false,options:[{label:"Yes",description:"Switch to plan agent for research and planning"},{label:"No",description:"Stay with build agent to continue making changes"}]}],tool:e.callId?{messageId:e.messageId,callId:e.callId}:void 0}))[0]?.[0]==="No")throw new Ot.RejectedError;let r=await xg(e.sessionId),i={providerId:r.providerId||"unknown",modelId:r.modelId},c={id:Identifier.ascending("message"),sessionId:e.sessionId,role:"user",time:{created:Date.now()},agent:"plan",model:i};return await Y.updateMessage(c),await Y.updatePart({id:Identifier.ascending("part"),messageId:c.id,sessionId:e.sessionId,type:"text",text:"User has requested to enter plan mode. Switch to plan mode and begin planning.",synthetic:true}),{title:"Switching to plan agent",output:`User confirmed to switch to plan mode. A new message has been created to switch you to plan mode. The plan file will be at ${n}. Begin planning.`,metadata:{operation:"enter"}}}async function fk(e){let t=await Y.get(e.sessionId),n=Se__default.posix.relative(R.worktree,Y.plan(t));if((await Ot.ask({sessionId:e.sessionId,questions:[{question:`Plan at ${n} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:false,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:e.callId?{messageId:e.messageId,callId:e.callId}:void 0}))[0]?.[0]==="No")throw new Ot.RejectedError;let r=await xg(e.sessionId),i={providerId:r.providerId||"unknown",modelId:r.modelId},c={id:Identifier.ascending("message"),sessionId:e.sessionId,role:"user",time:{created:Date.now()},agent:"build",model:i};return await Y.updateMessage(c),await Y.updatePart({id:Identifier.ascending("part"),messageId:c.id,sessionId:e.sessionId,type:"text",text:`The plan at ${n} has been approved, you can now edit files. Execute the plan`,synthetic:true}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{operation:"exit"}}}var Hi;(b=>{let e=a.create({service:"patch"});b.PatchSchema=N.object({patchText:N.string().describe("The full patch text that describes all changes to be made")});(E=>(E.ParseError="ParseError",E.IoError="IoError",E.ComputeReplacements="ComputeReplacements",E.ImplicitInvocation="ImplicitInvocation"))(b.ApplyPatchError||(b.ApplyPatchError={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.PatchParseError="PatchParseError",E.NotApplyPatch="NotApplyPatch"))(b.MaybeApplyPatch||(b.MaybeApplyPatch={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.CorrectnessError="CorrectnessError",E.NotApplyPatch="NotApplyPatch"))(b.MaybeApplyPatchVerified||(b.MaybeApplyPatchVerified={}));function r(w,k){let v=w[k];if(!v)return null;let C=E=>{let O=E.indexOf(":");if(O!==-1)return E.substring(O+1).trim()||void 0};if(v.startsWith("*** Add File:")){let E=C(v);return E?{filePath:E,nextIdx:k+1}:null}if(v.startsWith("*** Delete File:")){let E=C(v);return E?{filePath:E,nextIdx:k+1}:null}if(v.startsWith("*** Update File:")){let E=C(v),O,U=k+1;if(U<w.length&&w[U]?.startsWith("*** Move to:")){let D=w[U];D&&(O=C(D)),U++;}return E?{filePath:E,movePath:O,nextIdx:U}:null}return null}function i(w,k){let v=[],C=k;for(;C<w.length&&!w[C]?.startsWith("***");){let E=w[C];if(!E){C++;continue}if(E.startsWith("@@")){let O=E.indexOf("@@",2),U=O!==-1?E.substring(O+2).trim():"";C++;let D=[],K=[],X=false;for(;C<w.length&&!w[C]?.startsWith("@@")&&!w[C]?.startsWith("***");){let $=w[C];if(!$){C++;continue}if($==="*** End of File"){X=true,C++;break}if($.startsWith(" ")){let M=$.substring(1);D.push(M),K.push(M);}else $.startsWith("-")?D.push($.substring(1)):$.startsWith("+")&&K.push($.substring(1));C++;}v.push({old_lines:D,new_lines:K,change_context:U||void 0,is_end_of_file:X||void 0});}else C++;}return {chunks:v,nextIdx:C}}function c(w,k){let v="",C=k;for(;C<w.length&&!w[C]?.startsWith("***");){let E=w[C];if(!E){C++;continue}E.startsWith("+")&&(v+=E.substring(1)+`
|
|
748
|
+
`),C++;}return v.endsWith(`
|
|
749
|
+
`)&&(v=v.slice(0,-1)),{content:v,nextIdx:C}}function l(w){let k=w.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return k?.[2]?k[2]:w}function d(w){let v=l(w.trim()).split(`
|
|
750
|
+
`),C=[],E=0,O="*** Begin Patch",U="*** End Patch",D=v.findIndex(X=>X.trim()===O),K=v.findIndex(X=>X.trim()===U);if(D===-1||K===-1||D>=K)throw new Error("Invalid patch format: missing Begin/End markers");for(E=D+1;E<K;){let X=r(v,E);if(!X){E++;continue}if(v[E]?.startsWith("*** Add File:")){let{content:$,nextIdx:M}=c(v,X.nextIdx);C.push({type:"add",path:X.filePath,contents:$}),E=M;}else if(v[E]?.startsWith("*** Delete File:"))C.push({type:"delete",path:X.filePath}),E=X.nextIdx;else if(v[E]?.startsWith("*** Update File:")){let{chunks:$,nextIdx:M}=i(v,X.nextIdx);C.push({type:"update",path:X.filePath,move_path:X.movePath,chunks:$}),E=M;}else E++;}return {hunks:C}}b.parsePatch=d;function m(w){let k=["apply_patch","applypatch"];if(w.length===2&&k.includes(w[0]))try{let v=w[1];if(!v)return {type:"PatchParseError",error:new Error("Missing patch argument")};let{hunks:C}=d(v);return {type:"Body",args:{patch:v,hunks:C}}}catch(v){return {type:"PatchParseError",error:v}}if(w.length===3&&w[0]==="bash"&&w[1]==="-lc"){let v=w[2];if(!v)return {type:"NotApplyPatch"};let C=v.match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(C?.[2]){let E=C[2];try{let{hunks:O}=d(E);return {type:"Body",args:{patch:E,hunks:O}}}catch(O){return {type:"PatchParseError",error:O}}}}return {type:"NotApplyPatch"}}b.maybeParseApplyPatch=m;function f(w,k){let v;try{v=readFileSync(w,"utf-8");}catch(K){throw new Error(`Failed to read file ${w}: ${K}`)}let C=v.split(`
|
|
751
|
+
`);C.length>0&&C[C.length-1]===""&&C.pop();let E=a$1(C,w,k),O=p(C,E);(O.length===0||O[O.length-1]!=="")&&O.push("");let U=O.join(`
|
|
752
|
+
`);return {unified_diff:I(v,U),content:U}}b.deriveNewContentsFromChunks=f;function a$1(w,k,v){let C=[],E=0;for(let O of v){if(O.change_context){let X=g(w,[O.change_context],E);if(X===-1)throw new Error(`Failed to find context '${O.change_context}' in ${k}`);E=X+1;}if(O.old_lines.length===0){let X=w.length>0&&w[w.length-1]===""?w.length-1:w.length;C.push([X,0,O.new_lines]);continue}let U=O.old_lines,D=O.new_lines,K=g(w,U,E,O.is_end_of_file);if(K===-1&&U.length>0&&U[U.length-1]===""&&(U=U.slice(0,-1),D.length>0&&D[D.length-1]===""&&(D=D.slice(0,-1)),K=g(w,U,E,O.is_end_of_file)),K!==-1){let X=[K,U.length,D];C.push(X),E=K+U.length;}else throw new Error(`Failed to find expected lines in ${k}:
|
|
753
|
+
${O.old_lines.join(`
|
|
754
|
+
`)}`)}return C.sort((O,U)=>O[0]-U[0]),C}function p(w,k){let v=[...w];for(let C=k.length-1;C>=0;C--){let E=k[C];if(!E)continue;let[O,U,D]=E;v.splice(O,U);for(let K=0;K<D.length;K++){let X=D[K];X!==void 0&&v.splice(O+K,0,X);}}return v}function u(w){return w.replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015]/g,"-").replace(/\u2026/g,"...").replace(/\u00A0/g," ")}function h(w,k,v,C,E){if(E){let O=w.length-k.length;if(O>=v){let U=true;for(let D=0;D<k.length;D++){let K=w[O+D],X=k[D];if(!K||!X||!C(K,X)){U=false;break}}if(U)return O}}for(let O=v;O<=w.length-k.length;O++){let U=true;for(let D=0;D<k.length;D++){let K=w[O+D],X=k[D];if(!K||!X||!C(K,X)){U=false;break}}if(U)return O}return -1}function g(w,k,v,C=false){if(k.length===0)return -1;let E=h(w,k,v,(K,X)=>K===X,C);if(E!==-1)return E;let O=h(w,k,v,(K,X)=>K.trimEnd()===X.trimEnd(),C);if(O!==-1)return O;let U=h(w,k,v,(K,X)=>K.trim()===X.trim(),C);return U!==-1?U:h(w,k,v,(K,X)=>u(K.trim())===u(X.trim()),C)}function I(w,k){let v=w.split(`
|
|
755
|
+
`),C=k.split(`
|
|
756
|
+
`),E=`@@ -1 +1 @@
|
|
757
|
+
`,O=Math.max(v.length,C.length),U=false;for(let D=0;D<O;D++){let K=v[D]||"",X=C[D]||"";K!==X?(K&&(E+=`-${K}
|
|
758
|
+
`),X&&(E+=`+${X}
|
|
759
|
+
`),U=true):K&&(E+=` ${K}
|
|
760
|
+
`);}return U?E:""}async function T(w){if(w.length===0)throw new Error("No files were modified.");let k=[],v=[],C=[];for(let E of w)switch(E.type){case "add":{let O=Se.dirname(E.path);O!=="."&&O!=="/"&&await Tt.mkdir(O,{recursive:true}),await Tt.writeFile(E.path,E.contents,"utf-8"),k.push(E.path),e.info(`Added file: ${E.path}`);break}case "delete":await Tt.unlink(E.path),C.push(E.path),e.info(`Deleted file: ${E.path}`);break;case "update":{let O=f(E.path,E.chunks);if(E.move_path){let U=Se.dirname(E.move_path);U!=="."&&U!=="/"&&await Tt.mkdir(U,{recursive:true}),await Tt.writeFile(E.move_path,O.content,"utf-8"),await Tt.unlink(E.path),v.push(E.move_path),e.info(`Moved file: ${E.path} -> ${E.move_path}`);}else await Tt.writeFile(E.path,O.content,"utf-8"),v.push(E.path),e.info(`Updated file: ${E.path}`);break}}return {added:k,modified:v,deleted:C}}b.applyHunksToFiles=T;async function y(w){let{hunks:k}=d(w);return T(k)}b.applyPatch=y;async function x(w,k){if(w.length===1){let C=w[0];if(!C)return {type:"NotApplyPatch"};try{return d(C),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}}let v=m(w);switch(v.type){case "Body":{let{args:C}=v,E=C.workdir?Se.resolve(k,C.workdir):k,O=new Map;for(let U of C.hunks){let D=Se.resolve(E,U.type==="update"&&U.move_path?U.move_path:U.path);switch(U.type){case "add":O.set(D,{type:"add",content:U.contents});break;case "delete":{let K=Se.resolve(E,U.path);try{let X=await Tt.readFile(K,"utf-8");O.set(D,{type:"delete",content:X});}catch{return {type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${K}`)}}break}case "update":{let K=Se.resolve(E,U.path);try{let X=f(K,U.chunks);O.set(D,{type:"update",unified_diff:X.unified_diff,move_path:U.move_path?Se.resolve(E,U.move_path):void 0,new_content:X.content});}catch(X){return {type:"CorrectnessError",error:X}}break}}}return {type:"Body",action:{changes:O,patch:C.patch,cwd:E}}}case "PatchParseError":return {type:"CorrectnessError",error:v.error};case "NotApplyPatch":return {type:"NotApplyPatch"}}}b.maybeParseApplyPatchVerified=x;})(Hi||(Hi={}));var yk=loadTextFile("./apply_patch.txt",import.meta.url),bk=yk(),wk=N.object({patchText:N.string().describe("The full patch text that describes all changes to be made")}),kg=De.define("apply_patch",{scope:g.Coder,description:bk,parameters:wk,async execute(e,t){if(Rt.check(t.abort,"apply_patch"),!e.patchText)throw new Error("patchText is required");let n;try{n=Hi.parsePatch(e.patchText).hunks;}catch(a){throw new Error(`apply_patch verification failed: ${a}`)}if(n.length===0)throw e.patchText.replace(/\r\n/g,`
|
|
761
|
+
`).replace(/\r/g,`
|
|
762
|
+
`).trim()===`*** Begin Patch
|
|
763
|
+
*** End Patch`?new Error("patch rejected: empty patch"):new Error("apply_patch verification failed: no hunks found");let o=[],s="";for(let a of n){let p=Filesystem.normalize(Se.resolve(R.directory,a.path));switch(await Jt(t,p,{tool:"patch"}),a.type){case "add":{let h=a.contents.length===0||a.contents.endsWith(`
|
|
764
|
+
`)?a.contents:`${a.contents}
|
|
765
|
+
`,g=Lo(createTwoFilesPatch(p,p,"",h)),I=0,T=0;for(let y of diffLines("",h))y.added&&(I+=y.count||0),y.removed&&(T+=y.count||0);o.push({filePath:p,oldContent:"",newContent:h,type:"add",diff:g,additions:I,deletions:T}),s+=g+`
|
|
766
|
+
`;break}case "update":{let u=await Tt.stat(p).catch(()=>null);if(!u||u.isDirectory())throw new Error(`apply_patch verification failed: Failed to read file to update: ${p}`);let h=await Tt.readFile(p,"utf-8"),g=h;try{g=Hi.deriveNewContentsFromChunks(p,a.chunks).content;}catch(b){throw new Error(`apply_patch verification failed: ${b}`)}let I=Lo(createTwoFilesPatch(p,p,h,g)),T=0,y=0;for(let b of diffLines(h,g))b.added&&(T+=b.count||0),b.removed&&(y+=b.count||0);let x=a.move_path?Filesystem.normalize(Se.resolve(R.directory,a.move_path)):void 0;await Jt(t,x,{tool:"patch"}),o.push({filePath:p,oldContent:h,newContent:g,type:a.move_path?"move":"update",movePath:x,diff:I,additions:T,deletions:y}),s+=I+`
|
|
767
|
+
`;break}case "delete":{let u=await Tt.stat(p).catch(()=>null);if(!u||u.isDirectory())throw new Error(`apply_patch verification failed: File not found: ${p}`);let h=await Tt.readFile(p,"utf-8"),g=Lo(createTwoFilesPatch(p,p,h,"")),I=h.split(`
|
|
768
|
+
`).length;o.push({filePath:p,oldContent:h,newContent:"",type:"delete",diff:g,additions:0,deletions:I}),s+=g+`
|
|
769
|
+
`;break}}}let r=o.map(a=>({filePath:a.filePath,relativePath:Se.posix.relative(R.worktree,a.movePath??a.filePath),type:a.type,diff:a.diff,before:a.oldContent,after:a.newContent,additions:a.additions,deletions:a.deletions,movePath:a.movePath})),i=o.map(a=>Se.posix.relative(R.worktree,a.filePath));await t.ask({permission:"edit",patterns:i,always:["*"],metadata:{filepath:i.join(", "),diff:s,files:r}}),Rt.check(t.abort,"apply_patch");let c=[];for(let a of o){let p=a.type==="delete"?void 0:a.movePath??a.filePath;switch(a.type){case "add":await Tt.mkdir(Se.posix.dirname(a.filePath),{recursive:true}),await Tt.writeFile(a.filePath,a.newContent,"utf-8"),c.push({file:a.filePath,event:"add"});break;case "update":await Tt.writeFile(a.filePath,a.newContent,"utf-8"),c.push({file:a.filePath,event:"change"});break;case "move":a.movePath&&(await Tt.mkdir(Se.posix.dirname(a.movePath),{recursive:true}),await Tt.writeFile(a.movePath,a.newContent,"utf-8"),await Tt.unlink(a.filePath),c.push({file:a.filePath,event:"unlink"}),c.push({file:a.movePath,event:"add"}));break;case "delete":await Tt.unlink(a.filePath),c.push({file:a.filePath,event:"unlink"});break}p&&await pe.publish(bt.Event.Edited,{file:p});}for(let a of c)await pe.publish(Fn.Event.Updated,a);Rt.check(t.abort,"apply_patch");for(let a of o){if(a.type==="delete")continue;let p=a.movePath??a.filePath;await We.touchFile(p,true);}let l=await We.diagnostics(),m=`Success. Updated the following files:
|
|
770
|
+
${o.map(a=>{if(a.type==="add")return `A ${Se.posix.relative(R.worktree,a.filePath)}`;if(a.type==="delete")return `D ${Se.posix.relative(R.worktree,a.filePath)}`;let p=a.movePath??a.filePath;return `M ${Se.posix.relative(R.worktree,p)}`}).join(`
|
|
771
|
+
`)}`,f=20;for(let a of o){if(a.type==="delete")continue;let p=a.movePath??a.filePath,u=Filesystem.normalize(p),g=(l[u]??[]).filter(I=>I.severity===1);if(g.length>0){let I=g.slice(0,f),T=g.length>f?`
|
|
772
|
+
... and ${g.length-f} more`:"";m+=`
|
|
773
|
+
|
|
774
|
+
LSP errors detected in ${Se.posix.relative(R.worktree,p)}, please fix:
|
|
775
|
+
<diagnostics file="${p}">
|
|
776
|
+
${I.map(We.Diagnostic.pretty).join(`
|
|
777
|
+
`)}${T}
|
|
778
|
+
</diagnostics>`;}}return {title:m,metadata:{diff:s,files:r,diagnostics:l},output:m}}});var Ik=loadTextFile("./multiedit.txt",import.meta.url),vk=Ik(),Ck=N.object({edits:N.array(N.object({filePath:N.string().describe("The absolute path to the file to modify"),oldString:N.string().describe("The text to replace"),newString:N.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:N.boolean().optional().describe("Replace all occurrences of oldString (default false)")})).min(1).describe("Array of edit operations to perform sequentially"),continueOnError:N.boolean().optional().default(false).describe("Continue processing remaining edits if one fails (default false)")});function kk(e){return "filePath"in e&&"edits"in e?(console.warn('[multiedit] Deprecated parameter format detected. The top-level "filePath" field is no longer needed. Please update to new format where each edit contains its own filePath.'),{edits:e.edits.map(n=>({filePath:n.filePath||e.filePath,oldString:n.oldString,newString:n.newString,replaceAll:n.replaceAll})),continueOnError:e.continueOnError??false}):e}var Pg=De.define("multiedit",{description:vk,parameters:Ck,async execute(e,t){let n=kk(e);Rt.check(t.abort,"multiedit");let o=await $c.init(),s=[],r=[],i=new Map;for(let a of n.edits)i.has(a.filePath)||i.set(a.filePath,[]),i.get(a.filePath).push(a);for(let[a,p]of i.entries()){Rt.check(t.abort,"multiedit");try{for(let u of p){let h=await o.execute({filePath:u.filePath,oldString:u.oldString,newString:u.newString,replaceAll:u.replaceAll},t);s.push({success:!0,filePath:u.filePath,result:h});}}catch(u){if(r.push({filePath:a,error:u}),s.push({success:false,filePath:a,error:u}),!n.continueOnError)throw u}}let c=s.filter(a=>a.success).length,l=s.filter(a=>!a.success).length,d=n.edits.length,m=s.filter(a=>a.success).at(-1),f="";if(l===0?f=`Successfully applied ${d} edit(s) across ${i.size} file(s)`:c===0?f=`Failed to apply all ${d} edit(s)`:f=`Applied ${c}/${d} edit(s) successfully, ${l} failed`,r.length>0){f+=`
|
|
779
|
+
|
|
780
|
+
Errors:
|
|
781
|
+
`;for(let{filePath:a,error:p}of r)f+=`- ${Se__default.posix.relative(R.worktree,a)}: ${p.message}
|
|
782
|
+
`;}return m?.result&&(f+=`
|
|
783
|
+
|
|
784
|
+
Last successful edit:
|
|
785
|
+
`,f+=m.result.output),{title:`Multiedit: ${c}/${d} successful`,metadata:{totalEdits:d,successCount:c,failureCount:l,filesModified:i.size,files:s.map(a=>({success:a.success,filePath:a.filePath,metadata:a.result?.metadata,error:a.error?.message}))},output:f}}});var Bi=a.create({service:"connection-registry"}),fn;(a=>{let e=null;async function t(){return e||(e=await Gc.create()),e}async function n(p){e=await Gc.create(p),Bi.info("AcpConnectionRegistry initialized");}a.init=n;async function o(p){return (await t()).connect(p.baseUrl,p.localAgentId,p.remoteAgentId,p.remoteSessionId,p.localSessionId)}a.connect=o;async function s(p){return (await t()).resolve(p)}a.resolve=s;function r(p){if(e)return e.resolve(p)}a.resolveSync=r;async function i(p){(await t()).closeConnection(p);}a.close=i;async function c(p,u){(await t()).markDegraded(p,u);}a.markDegraded=c;async function l(p){return (await t()).getConnectionsByAgent(p)}a.getConnectionsByLocalAgent=l;async function d(p){return (await t()).getConnectionsByService(p)}a.getConnectionsByService=d;async function m(){return (await t()).getAllActiveConnections()}a.getAllActiveConnections=m;async function f(p,u){(await t()).updateLastSeenMessageId(p,u);}a.updateLastSeenMessageId=f;})(fn||(fn={}));var Gc=class e{constructor(t){b$1(this,"defaultHistoryScope");b$1(this,"defaultHistoryWindowSize");b$1(this,"defaultDegradePolicy");b$1(this,"agentIndex",new Map);b$1(this,"serviceIndex",new Map);b$1(this,"connections",new Map);this.defaultHistoryScope=t?.defaultHistoryScope??"session",this.defaultHistoryWindowSize=t?.defaultHistoryWindowSize??10,this.defaultDegradePolicy=t?.defaultDegradePolicy??"streaming_first",Bi.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(t){return new e(t)}connect(t,n,o,s,r){let i=this.agentIndex.get(n);if(i)for(let m of i){let f=this.connections.get(m);if(f&&f.baseUrl===t&&f.status!=="closed")return s&&f.sessionId!==s&&(f.sessionId=s,f.sessionSequence=f.sessionSequence??[],f.sessionSequence.includes(s)||f.sessionSequence.push(s)),r&&(f.localSessionId=r),f.updatedAt=Date.now(),{connectionId:f.connectionId,sessionId:f.sessionId,localAgentId:f.localAgentId,remoteAgentId:f.remoteAgentId,baseUrl:f.baseUrl}}let c=this.generateConnectionId(),l=s??`session-${this.generateShortId()}`,d={localAgentId:n,remoteAgentId:o,connectionId:c,sessionId:l,...r?{localSessionId:r}:{},baseUrl:t,historyScope:this.defaultHistoryScope,historyWindowSize:this.defaultHistoryWindowSize,degradePolicy:this.defaultDegradePolicy,updatedAt:Date.now(),status:"active"};return this.connections.set(c,d),this.agentIndex.has(n)||this.agentIndex.set(n,new Set),this.agentIndex.get(n).add(c),this.serviceIndex.has(t)||this.serviceIndex.set(t,new Set),this.serviceIndex.get(t).add(c),{connectionId:c,sessionId:l,localAgentId:n,remoteAgentId:o,baseUrl:t}}resolve(t,n=false){let o=this.connections.get(t);if(o)return o;let s=this.agentIndex.get(t);if(s&&s.size>0)for(let r of s){let i=this.connections.get(r);if(i&&i.status!=="closed")return i}for(let r of this.connections.values())if(r.status!=="closed"&&(r.sessionId===t||r.localSessionId===t))return r;if(n){let c=this.connect("http://localhost","system-local","system-remote",t);return this.connections.get(c.connectionId)}}closeConnection(t){let n=this.connections.get(t);if(!n)return;this.connections.delete(t);let o=this.agentIndex.get(n.localAgentId);o&&(o.delete(t),o.size===0&&this.agentIndex.delete(n.localAgentId));let s=this.serviceIndex.get(n.baseUrl);s&&(s.delete(t),s.size===0&&this.serviceIndex.delete(n.baseUrl)),Bi.debug("connection closed and removed",{connectionId:t,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId});}markDegraded(t,n){let o=this.connections.get(t);o&&(o.status="degraded",o.updatedAt=Date.now(),Bi.debug("connection marked degraded",{connectionId:t,reason:n}));}getConnectionsByAgent(t){let n=this.agentIndex.get(t);return n?Array.from(n).map(o=>this.connections.get(o)).filter(o=>o!==void 0&&o.status!=="closed"):[]}getConnectionsByService(t){let n=this.serviceIndex.get(t);return n?Array.from(n).map(o=>this.connections.get(o)).filter(o=>o!==void 0&&o.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(t=>t.status!=="closed")}updateLastSeenMessageId(t,n){let o=this.connections.get(t);o&&(o.lastSeenMessageId=n,o.updatedAt=Date.now());}generateConnectionId(){return `conn-${this.generateShortId()}`}generateShortId(){return createHash("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,8)}async close(){this.connections.clear(),this.agentIndex.clear(),this.serviceIndex.clear(),Bi.info("connection registry closed");}};var $o=a.create({service:"session-router"});var Lr=class extends Error{constructor(n,o,s){super(o);b$1(this,"code",n);b$1(this,"context",s);this.name="RoutingError";}},ku=class e{static create(){return new e}constructor(){$o.info("session router created");}route(t){if(!this.isValidContext(t))return {success:false,error:"routing context is empty or invalid"};try{return t.connectionId?this.routeByConnectionId(t.connectionId):t.localAgentId&&t.baseUrl?this.routeByPeerAndBaseUrl(t.localAgentId,t.baseUrl):t.baseUrl&&t.sessionId?this.routeByBaseUrlAndSessionId(t.baseUrl,t.sessionId):{success:!1,error:"insufficient routing parameters: need connectionId, or localAgentId+baseUrl, or baseUrl+sessionId"}}catch(n){let o=n instanceof Error?n.message:String(n);return $o.error("routing failed",{context:t,error:o}),{success:false,error:o}}}routeOrThrow(t){let n=this.route(t);if(!n.success)throw new Lr(this.getErrorCode(n.error),n.error??"routing failed",t);if(!n.connectionId)throw new Lr("NOT_FOUND","connection not found",t);let o=this.getConnectionState(n.connectionId);if(!o)throw new Lr("NOT_FOUND","connection state not found",t);if(o.status==="closed")throw new Lr("CONNECTION_CLOSED","connection is closed",t);return o}registerConnection(t){return !t.connectionId||!t.localAgentId||!t.remoteAgentId||!t.baseUrl||!t.sessionId?{success:false,error:"invalid connection state: missing required fields"}:($o.debug("connection registered",{connectionId:t.connectionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),{success:true,connectionId:t.connectionId,sessionId:t.sessionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl})}unregisterConnection(t){let n=this.getConnectionState(t);return n?($o.debug("connection unregistered",{connectionId:t,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId,baseUrl:n.baseUrl}),true):($o.debug("connection not found for unregister",{connectionId:t}),false)}isValidContext(t){return !!(t.connectionId||t.remoteAgentId||t.baseUrl||t.sessionId)}routeByConnectionId(t){let n=this.getConnectionState(t);return n?n.status==="closed"?{success:false,error:`connection is closed: ${t}`}:{success:true,connectionId:n.connectionId,sessionId:n.sessionId,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId,baseUrl:n.baseUrl}:{success:false,error:`connection not found: ${t}`}}routeByPeerAndBaseUrl(t,n){let s=this.getConnectionsByPeer(t).filter(i=>i.baseUrl===n&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for localAgentId=${t}, baseUrl=${n}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${t}, baseUrl=${n}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}routeByBaseUrlAndSessionId(t,n){let s=this.getConnectionsByService(t).filter(i=>i.sessionId===n&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for baseUrl=${t}, sessionId=${n}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${t}, sessionId=${n}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}getConnectionState(t){$o.warn("getConnectionState not implemented, returning undefined",{connectionId:t});}getConnectionsByPeer(t){return $o.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:t}),[]}getConnectionsByService(t){return $o.warn("getConnectionsByService not implemented, returning empty array",{baseUrl:t}),[]}getErrorCode(t){return t?t.includes("empty")||t.includes("invalid")?"EMPTY_CONTEXT":t.includes("ambiguous")?"AMBIGUOUS_ROUTE":t.includes("not found")?"NOT_FOUND":t.includes("closed")?"CONNECTION_CLOSED":t.includes("insufficient")||t.includes("missing")?"MISSING_REQUIRED_PARAMS":"NOT_FOUND":"NOT_FOUND"}},Tg=class e extends ku{constructor(n){super();b$1(this,"registry");this.registry=n,$o.info("registry session router created");}static fromRegistry(n){return new e(n)}getConnectionState(n){return this.registry.resolve(n)}getConnectionsByPeer(n){return this.registry.getConnectionsByPeer(n)}getConnectionsByService(n){return this.registry.getConnectionsByService(n)}};var uo=a.create({service:"agent-client-api"});function Tk(e){return e==="stdio"||e==="http"||e==="websocket"?e:"http"}async function Ak(e){return (await Pe(()=>vo.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",e||{directory:R.directory}).catch(()=>{}))?.acp?.server?.agentId??""}var rn;(I=>{async function e(T,y){uo.debug("connect called",{args:T,context:y});let x=await Pe(()=>vo.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",y||{directory:R.directory}).catch(()=>{}),b=x?.acp?.server?.agentId,w=T.agentId;w||(w=(await Zo.getServiceByUrl(T.baseUrl))?.agentId);let k;if(T.baseUrl.startsWith("ws://")||T.baseUrl.startsWith("wss://")?k="websocket":T.baseUrl.startsWith("http://")||T.baseUrl.startsWith("https://")?k="http":k=Tk(x?.acp?.server?.channel),uo.debug("connect resolved",{baseUrl:T.baseUrl,resolvedChannel:k,localAgentId:b,remoteAgentId:w}),b){let X=(await fn.getConnectionsByLocalAgent(b)).find($=>$.baseUrl===T.baseUrl);if(X){if(uo.debug("connect: found existing connection by agent"),X.channel&&X.channel!==k)throw new Error(`Channel mismatch for agent ${b}: ${X.channel} != ${k}`);return {reused:true,...X,channel:X.channel??k}}}let v=await fn.getConnectionsByService(T.baseUrl);if(v.length>0){let K=v[0];if(uo.debug("connect: found existing connection by service",{existing:K}),K.channel&&K.channel!==k)throw new Error(`Channel mismatch for service ${T.baseUrl}: ${K.channel} != ${k}`);return {reused:true,connectionId:K.connectionId,sessionId:K.sessionId,remoteAgentId:K.remoteAgentId,baseUrl:K.baseUrl,channel:K.channel??k}}let C=b??"local-unknown",E=w??`remote-${Buffer.from(T.baseUrl).toString("base64").slice(0,16)}`;uo.debug("connect: using effective agent IDs",{effectiveLocalAgentId:C,effectiveRemoteAgentId:E}),uo.debug("connect: calling AgentClientService.connect",{baseUrl:T.baseUrl,channel:k});let O;try{O=await Xn.connect({config:{type:k,url:T.baseUrl,cwd:y.directory}}),uo.debug("connect: AgentClientService.connect succeeded",{remote:O});}catch(K){throw uo.error("connect: AgentClientService.connect failed",{error:K.message,stack:K.stack}),K}uo.debug("connect: creating connection in registry",{baseUrl:O.baseUrl,localAgentId:C,remoteAgentId:E,sessionId:O.sessionId});let U=await fn.connect({baseUrl:O.baseUrl,localAgentId:C,remoteAgentId:E,remoteSessionId:O.sessionId}),D=await fn.resolve(U.connectionId);return D&&(D.channel=O.channel??k,D.subscriber=O.subscriber),uo.debug("connect: completed",{result:U}),{created:true,connectionId:U.connectionId,sessionId:U.sessionId,remoteAgentId:U.remoteAgentId,baseUrl:U.baseUrl,channel:O.channel??k}}I.connect=e;async function t(T,y){let x=T.agentId??await Ak(y);return (await fn.getConnectionsByLocalAgent(x)).filter(w=>!T.baseUrl||w.baseUrl===T.baseUrl)}I.list=t;async function n(T,y,x){let b=await fn.resolve(T);if(!b)throw new Error("Connection not found");let w=b.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");await Xn.send(w,b.sessionId,y.parts),b.updatedAt=Date.now();}I.send=n;async function o(T,y){let x=await fn.resolve(T);if(!x)throw new Error("Connection not found");let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");return Xn.capabilities(b)}I.capabilities=o;async function s(T,y){await fn.close(T);}I.close=s;async function r(T,y){let x=await fn.resolve(T);return x?{connectionId:x.connectionId,remoteAgentId:x.remoteAgentId,baseUrl:x.baseUrl,sessionId:x.sessionId,status:x.status,updatedAt:x.updatedAt}:{connectionId:T,status:"unknown"}}I.status=r;async function i(T){let y=await Pe(()=>vo.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",T).catch(()=>{}),x=await fn.getAllActiveConnections();return {config:y?.acp,managedConnections:x.length}}I.config=i;async function c(T){return Zo.listServices(T)}I.listServices=c;async function l(T){return Zo.getService(T)}I.getService=l;async function d(T){return Zo.registerService(T)}I.registerService=d;async function m(T,y,x,b){let w=await fn.resolve(T);if(!w)throw new Error("Connection not found");let k={...En,...b},v=w.channel??"http";switch(v){case "websocket":return f(w,k,y);case "http":return a(w,k,y);case "stdio":return p(w,k,y);default:throw new Error(`Unsupported channel type: ${v}`)}}I.subscribe=m;async function f(T,y,x){let b=T.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");return b.subscribe(T.sessionId,x)}async function a(T,y,x,b){let w=T.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(T.sessionId,x,b)}async function p(T,y,x,b){let w=T.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(T.sessionId,x,b)}async function u(T,y){let x=await fn.resolve(T);if(!x)throw new Error("Connection not found");let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");await Xn.interrupt(b,x.sessionId);}I.interrupt=u;async function h(T,y,x,b,w){return await n(T,y),m(T,x,b,w)}I.exchangeSubscribe=h;async function g(T,y){let x=await fn.resolve(T);if(!x){uo.warn("Connection not found for releaseSubscription",{connectionId:T});return}let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");await Xn.releaseSubscription(b,x.sessionId);}I.releaseSubscription=g;})(rn||(rn={}));var Pu=a.create({service:"api"}),Wc=class extends Error{constructor(n,o,s){super(n);b$1(this,"code",o);b$1(this,"details",s);this.name="ApiError";}};async function Pe(e,t,n){try{n&&Pu.debug(`API call started: ${JSON.stringify(n)}`,{errorCode:t});let o=await R.provide({directory:n?.directory??R.directory,init:void 0,fn:e});return n&&Pu.debug(`API call completed: ${JSON.stringify(n)}`,{errorCode:t}),o}catch(o){let s=o instanceof Error?o.message:String(o),r=o instanceof Error?o.name:"Error",i=o instanceof Error?o.stack:void 0;throw Pu.error(`API call failed: ${n||t}`,{errorCode:t,errorName:r,error:s,stack:i}),o instanceof Wc?o:new Wc(s,t,o)}}var So=a.create({service:"tool.agent-client"}),Rk=loadTextFile("./agent-client.txt",import.meta.url),_k=10,Ts=new Map,Ag=De.define("agent_client",{description:Rk(),parameters:N.object({operation:N.enum(["connect","list","discover","capabilities","send","status","interrupt","close"]).default("connect").describe("Operation: connect | list | discover | capabilities | send | status | interrupt | close"),baseUrl:N.string().optional().describe("Target easbot service base URL (required for connect operation, e.g. http://127.0.0.1:3000)"),connectionId:N.string().optional().describe("Connection ID from a previous connect operation (auto-resolved if not provided)"),prompt:N.string().optional().describe("Message to send to remote agent (required for send operation)")}),formatValidationError(e){return `Agent client chat tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){let n=e.operation??"connect",o=new Set(["connect","capabilities","send","interrupt"]);if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");let s={directory:t.extra.directory};if(o.has(n)&&e.baseUrl&&await t.ask({permission:"agent_client",patterns:[e.baseUrl],always:["*"],metadata:{operation:n,baseUrl:e.baseUrl}}),n==="list"){let r=await rn.list({baseUrl:e.baseUrl},s);if(r.length===0)return {title:"Connection List",metadata:{count:0},output:`<connections>
|
|
786
|
+
No active connections
|
|
787
|
+
</connections>`};let i=[`<connections total="${r.length}">`];for(let c of r)i.push(`[connection_id="${c.connectionId}"]`),i.push(` baseUrl: ${c.baseUrl}`),i.push(` channel: ${c.channel}`),c.sessionId&&i.push(` sessionId: ${c.sessionId}`),i.push("");return i.push("</connections>"),{title:"Connection List",metadata:{count:r.length},output:i.join(`
|
|
788
|
+
`)}}if(n==="connect"){if(!e.baseUrl)throw new Error("baseUrl required for connect");let r=await rn.connect({baseUrl:e.baseUrl},s),i=["<connection>"];return i.push(` connectionId: ${r.connectionId}`),i.push(` baseUrl: ${r.baseUrl}`),i.push(` channel: ${r.channel}`),i.push(` sessionId: ${r.sessionId}`),i.push("</connection>"),{title:"Connection established",metadata:{count:0},output:i.join(`
|
|
789
|
+
`)}}if(n==="discover"){let r=await rn.listServices();if(r.length===0)return {title:"Discoverable Services",metadata:{count:0},output:`<services>
|
|
790
|
+
No services discovered
|
|
791
|
+
</services>`};let i=[`<services total="${r.length}">`];for(let c of r)i.push(`- ${c.name} (${c.status}): ${c.baseUrl}`);return i.push("</services>"),{title:"Discoverable Services",metadata:{count:r.length},output:i.join(`
|
|
792
|
+
`)}}if(!e.connectionId){let i=(await rn.list({baseUrl:e.baseUrl},s)).at(0);if(i)e.connectionId=i.connectionId;else throw new Error("No active connection found. Please connect first or provide connectionId.")}if(!e.connectionId)throw new Error("connectionId is required");if(n==="close"){await rn.interrupt(e.connectionId,s).catch(i=>{So.warn("interrupt during close failed (connection may already be closed)",{error:i});});let r=Ts.get(e.connectionId);return r&&(r.unsubscribe?.(),Ts.delete(e.connectionId)),await rn.close(e.connectionId,s),{title:"Connection closed",metadata:{count:0},output:`<connection>
|
|
793
|
+
connectionId: ${e.connectionId}
|
|
794
|
+
status: closed
|
|
795
|
+
</connection>`}}if(n==="interrupt"){await rn.interrupt(e.connectionId,s);let r=Ts.get(e.connectionId);return r&&(r.unsubscribe?.(),Ts.delete(e.connectionId)),{title:"Session Interrupted",metadata:{count:0},output:`<connection>
|
|
796
|
+
connectionId: ${e.connectionId}
|
|
797
|
+
status: interrupted
|
|
798
|
+
</connection>`}}if(n==="capabilities"){let r=await rn.capabilities(e.connectionId,s);return {title:"Remote Agent Capabilities",metadata:{count:1},output:JSON.stringify(r,null,2)}}if(n==="status"){let r=await rn.status(e.connectionId,s),i=["<connection>"];return i.push(` connectionId: ${e.connectionId}`),r.baseUrl&&i.push(` baseUrl: ${r.baseUrl}`),r.sessionId&&i.push(` sessionId: ${r.sessionId}`),i.push(` status: ${r.status}`),i.push("</connection>"),{title:"Connection Status",metadata:{count:0},output:i.join(`
|
|
799
|
+
`)}}if(n==="send"){if(!e.prompt)throw new Error("prompt required");let r=e.connectionId,i=Ts.get(r);if(i){if(i.currentRound>=i.maxRounds)return {title:"Round Limit Exceeded",metadata:{count:0},output:JSON.stringify({success:false,error:`Round limit reached (${i.maxRounds})`},null,2)};if(i.hasPendingResponse){let l=i.currentRound+1;return {title:"Waiting for Remote Response",metadata:{count:0,completedRounds:i.currentRound,pendingRound:l,maxRounds:i.maxRounds},output:JSON.stringify({success:false,status:"waiting",completedRounds:i.currentRound,pendingRound:l,maxRounds:i.maxRounds,note:`Round ${l} pending - waiting for remote agent response. Please do NOT send again, the remote response will be injected automatically.`},null,2)}}}else {let l=await rn.status(r,s);i={connectionId:r,sessionId:l.sessionId??"",localSessionId:t.sessionId,baseUrl:l.baseUrl??e.baseUrl??"",remoteAgentId:l.remoteAgentId,originalPrompt:e.prompt,currentRound:0,maxRounds:_k,hasPendingResponse:false,startedAt:Date.now()},So.debug("Establishing subscription for Agent-to-Agent interaction",{connectionId:r,sessionId:t.sessionId,remoteSessionId:l.sessionId});let d=await rn.subscribe(r,async m=>{if(So.debug("Subscription callback triggered",{connectionId:r,sessionId:t.sessionId,isComplete:!m.metadata,hasText:!!m.text,textLength:m.text?.length??0,hasThinking:!!m.thinking,toolsCount:m.tools?.length??0,hasSessionId:!!m.metadata?.sessionId,msgMetadata:m.metadata}),m.metadata?.sessionId){i.currentRound++,i.hasPendingResponse=false,So.debug("Remote response received, building prompt for local LLM",{connectionId:r,currentRound:i.currentRound,textPreview:m.text?.substring(0,100)??"",error:m.metadata.error});let f=(await Mt.get(t.sessionId)).type==="idle";if(await Je.prompt({sessionId:t.sessionId,parts:[{type:"subtask-result",taskId:i.connectionId,source:"agent-client",agent:"remote-agent",status:m.metadata.error?"error":"completed",result:m.text??"",error:m.metadata.error,rounds:{current:i.currentRound,max:i.maxRounds},thinking:m.thinking,tools:await Promise.all((m.tools??[]).map(async a=>{let p=typeof a.output=="string"?a.output:"",u=await Ve.output(p,{contentType:"output",toolName:a.name});return {name:a.name,status:a.status,output:u.content||void 0}})),metadata:{originalPrompt:i.originalPrompt,remoteAgentId:i.remoteAgentId,baseUrl:i.baseUrl,remoteSessionId:m.metadata.sessionId,connectionId:i.connectionId,tool:"agent_client"},time:{start:i.startedAt,end:Date.now()}}],noReply:!f}),So.debug("Round completed, keeping connection alive for next round",{connectionId:r,currentRound:i.currentRound,remainingRounds:i.maxRounds-i.currentRound}),i.currentRound>=i.maxRounds){So.debug("Max rounds reached, closing connection",{connectionId:r,currentRound:i.currentRound,maxRounds:i.maxRounds});try{await rn.releaseSubscription(r,s);}catch(a){So.warn("Failed to release server subscription",{connectionId:r,error:a instanceof Error?a.message:String(a)});}Ts.delete(r);}}},s,{includeThinking:false,includeToolDetails:false,includeToolOutput:false});i.unsubscribe=d,Ts.set(r,i);}So.debug("Sending message to remote agent",{connectionId:r,sessionId:t.sessionId,currentRound:i.currentRound,promptLength:e.prompt.length,promptPreview:e.prompt.substring(0,200)}),i.hasPendingResponse=true;try{await rn.send(r,{sessionId:i.sessionId,parts:[{type:"text",text:`${e.prompt}
|
|
800
|
+
|
|
801
|
+
[async] Agent Client message`}]},s);}catch(l){throw i.hasPendingResponse=false,l}So.debug("Message sent successfully, waiting for subscription callback",{connectionId:r,sessionId:t.sessionId,currentRound:i.currentRound,pendingRound:i.currentRound+1});let c=i.currentRound+1;return So.debug("Tool execute returning, subscription should trigger callback on remote response",{connectionId:r,pendingRound:c,maxRounds:i.maxRounds}),{title:"Message sent to remote agent",metadata:{count:0,connectionId:r,completedRounds:i.currentRound,pendingRound:c,maxRounds:i.maxRounds},output:`<agent_message>
|
|
802
|
+
connectionId: ${r}
|
|
803
|
+
round: ${i.currentRound}/${i.maxRounds}
|
|
804
|
+
status: Remote agent is processing, response will be injected automatically
|
|
805
|
+
</agent_message>`}}throw new Error(`Unknown operation: ${n}`)}});var po=a.create({service:"tool.gateway"}),jk=loadTextFile("./gateway.txt",import.meta.url),Lk=jk(),Wi=null;async function Dk(){if(Wi)return Wi;try{let e=await c$1(),t=e.path||"",n=t.endsWith("/")?t.slice(0,-1):t,o=`ws://${e.hostname}:${e.port}${n}`;Wi=new vr({url:o,type:"api"});let s=new Promise(i=>{Wi.onStateChange(c=>{c==="connected"?(po.debug("gateway client connected",{url:o}),i(c)):c==="disconnected"&&i(c);});}),r=await Promise.race([s,new Promise(i=>setTimeout(()=>i("timeout"),1e4))]);return r==="connected"?Wi:(po.error("failed to connect to gateway",{state:r}),null)}catch(e){return po.error("failed to connect to gateway",{error:String(e)}),null}}var $k=N.discriminatedUnion("operation",[N.object({operation:N.literal("status")}),N.object({operation:N.literal("channels")}),N.object({operation:N.literal("sessions"),limit:N.number().optional(),offset:N.number().optional(),type:N.enum(["private","group","all"]).optional().default("all").describe("Filter by chat type: private, group, or all")}),N.object({operation:N.literal("contacts"),platform:N.string().describe("Platform to list contacts (e.g., telegram, discord)"),limit:N.number().optional(),offset:N.number().optional()}),N.object({operation:N.literal("send"),contactUid:N.string().optional().describe('Full Contact UID like "telegram:123456789" (recommended)'),sessionId:N.string().optional().describe("Session ID to use"),content:N.string(),messageType:N.enum(["text","image","file"]).default("text")})]),_g=De.define("gateway",async()=>({description:Lk,parameters:$k,async execute(e,t){let n=await Dk();if(!n)return {title:"Gateway Not Available",metadata:{available:false},output:"**Error**: Cannot connect to Gateway server"};if(e.operation==="status"){let o=await n.getStatus(),s=o.agents?`
|
|
806
|
+
- **Registered Agents**: ${o.agents.total} (healthy: ${o.agents.healthy}, unhealthy: ${o.agents.unhealthy})`:"";return {title:"Gateway Status",metadata:{connections:o.connections,sessions:o.sessions,messageSubscriptions:o.messageSubscriptions,agentSubscriptions:o.agentSubscriptions,...o.agents?{agents:o.agents}:{}},output:`## Gateway Status
|
|
807
|
+
|
|
808
|
+
- **Status**: ${o.status}
|
|
809
|
+
- **Connections**: ${o.connections}
|
|
810
|
+
- **Sessions**: ${o.sessions}
|
|
811
|
+
- **Message Subscriptions**: ${o.messageSubscriptions}
|
|
812
|
+
- **Agent Subscriptions**: ${o.agentSubscriptions}${s}
|
|
813
|
+
- **Uptime**: ${Fk(o.uptime)}
|
|
814
|
+
- **Version**: ${o.version}`}}if(e.operation==="channels"){let o=await n.listChannels();if(o.channels.length===0)return {title:"Channels",metadata:{count:0},output:"**No channels connected**"};let s=["## Connected Channels"];for(let r of o.channels)s.push(`### ${r.name} (${r.platform})`),s.push(`- ID: ${r.id}`),r.version&&s.push(`- Version: ${r.version}`);return {title:"Channels",metadata:{count:o.channels.length},output:s.join(`
|
|
815
|
+
`)}}if(e.operation==="sessions"){let o=e.limit??50,s=e.offset??0,r=e.type??"all",i=await n.listSessions({limit:o,offset:s}),c=i.sessions.filter(d=>r==="all"?true:r==="private"?d.chatType==="private":r==="group"?d.chatType==="supergroup"||d.chatType==="group":true);if(c.length===0)return {title:"Sessions",metadata:{count:0},output:`**No ${r==="all"?"":r+" "}sessions**`};let l=[`## ${r==="all"?"Active":r.charAt(0).toUpperCase()+r.slice(1)} Sessions (${c.length})`];for(let d of c)l.push(`### ${d.id}`),l.push(`- **Type**: ${d.chatType||"unknown"}`),d.chatTitle&&l.push(`- **Title**: ${d.chatTitle}`),d.platform&&d.userId&&l.push(`- **UID**: ${d.platform}:${d.userId}`),d.channelId&&l.push(`- **Channel**: ${d.channelId}`),l.push(`- **State**: ${d.state}`),l.push(`- **Last Active**: ${Eg(d.lastActiveAt)}`);return i.hasMore&&l.push(`
|
|
816
|
+
*Showing ${c.length} of ${i.total}*`),{title:"Sessions",metadata:{count:i.sessions.length,total:i.total},output:l.join(`
|
|
817
|
+
`)}}if(e.operation==="contacts"){let o=e.platform,s=e.limit??50,r=e.offset??0,i=await n.listContacts(o,{limit:s,offset:r});if(i.contacts.length===0)return {title:"Contacts",metadata:{count:0},output:`**No contacts found on ${o}**`};let c=[`## Contacts on ${o} (${i.total})`];for(let l of i.contacts){let d=l.profile.displayName||l.profile.username||l.stableId;c.push(`### ${d}`),l.profile.username&&c.push(`- **@**: ${l.profile.username}`),c.push(`- **UID**: ${l.uid}`),c.push(`- **Last Seen**: ${Eg(l.lastSeenAt)}`);}return i.hasMore&&c.push(`
|
|
818
|
+
*Showing ${i.contacts.length} of ${i.total}*`),{title:"Contacts",metadata:{count:i.contacts.length,total:i.total,platform:o},output:c.join(`
|
|
819
|
+
`)}}if(e.operation==="send"){if(!e.content)return {title:"Send Message",metadata:{success:false},output:"**Error**: content is required"};if(e.messageType==="image"||e.messageType==="file"){let l=await Uk(t,e.content,e.messageType);if(!l.valid)return {title:"Send Failed",metadata:{success:false},output:`**Error**: ${l.error}`}}let o,s,r,i,c;if(e.contactUid){let[l,d]=e.contactUid.split(":");l&&d&&(r=l,o=d,s=d,i=`${r}-main`,c=`${r}_${i}_${s}_${o}`,po.debug("built session from contactUid",{contactUid:e.contactUid,sessionId:c}));}else if(e.sessionId){c=e.sessionId;let l=c.split("_");l.length>=3&&(r=l[0],i=l[1],s=l[2],o=l.length>=4?l[3]:s,po.debug("extracted params from sessionId",{sessionId:c,platform:r,channelId:i,chatId:s,userId:o}));}if(!c||!s)return {title:"Send Failed",metadata:{success:false},output:"**Error**: sessionId or contactUid is required"};if(!i)try{let l=await n.listChannels();l.channels.length>0&&(i=l.channels[0]?.id,r=l.channels[0]?.platform,po.debug("using first available channel",{channelId:i,platform:r}));}catch(l){po.warn("failed to get channels",{error:String(l)});}if(!i)return {title:"Send Failed",metadata:{success:false},output:"**Error**: no channel available"};try{let l=await n.getOrCreateSession({sessionId:c,platform:r,channel:i,userId:o,chatId:s});c=l.sessionId,po.debug("session ensured",{sessionId:c,created:l.created});}catch(l){return po.error("failed to ensure session",{error:String(l),targetSessionId:c}),{title:"Send Failed",metadata:{success:false},output:`**Error**: Failed to create session - ${l instanceof Error?l.message:String(l)}`}}try{let l=f=>{if(f.startsWith("http://")||f.startsWith("https://")||f.startsWith("file://"))return f;try{let a=Se__default.isAbsolute(f)?f:Se__default.resolve(R.directory,f);return pathToFileURL(a).href}catch{return f}},d=e.messageType==="text"?[{type:"text",text:e.content}]:e.messageType==="image"?[{type:"image",image:l(e.content)}]:[{type:"file",data:l(e.content)}],m=await n.sendMessage(c,{content:d,channel:i,userId:o,chatId:s,processorId:"gateway",agent:t?.agent??"gateway"});return po.debug("message sent via HTTP API",{messageId:m.messageId,sessionId:c}),{title:"Message Sent",metadata:{success:!0,messageId:m.messageId,sessionId:c},output:`## Message Sent
|
|
820
|
+
|
|
821
|
+
- **Message ID**: ${m.messageId}
|
|
822
|
+
- **Session ID**: ${c}
|
|
823
|
+
${r&&o?`- **Contact UID**: ${r}:${o}`:""}
|
|
824
|
+
- **Content**: ${l(e.content).length>100?l(e.content).slice(0,100)+"...":l(e.content)}`}}catch(l){return po.error("failed to send message via HTTP API",{error:String(l),sessionId:c}),{title:"Send Failed",metadata:{success:false},output:`**Error**: Failed to send message - ${l instanceof Error?l.message:String(l)}`}}}return {title:"Unknown Operation",metadata:{success:false},output:"**Error**: Unknown operation"}}}));function Fk(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=Math.floor(n/60),s=Math.floor(o/24);return s>0?`${s}d ${o%24}h ${n%60}m`:o>0?`${o}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function Eg(e){let t=new Date(e),o=new Date().getTime()-t.getTime();return o<6e4?"just now":o<36e5?`${Math.floor(o/6e4)}m ago`:o<864e5?`${Math.floor(o/36e5)}h ago`:t.toISOString().replace("T"," ").slice(0,19)}function Nk(e){let t=e.trim();if(t.startsWith("file://")&&(t=t.slice(7)),Filesystem.isAbsolute(t))return Filesystem.normalize(t);let n=Se__default.resolve(R.directory,t);return Filesystem.normalize(n)}async function Uk(e,t,n){let o=Nk(t),s=Filesystem.stat(o);if(!s){let i=Filesystem.dirname(o),c=Filesystem.basename(o),l=await Tt.readdir(i).then(d=>d.filter(m=>m.toLowerCase().includes(c.toLowerCase())||c.toLowerCase().includes(m.toLowerCase())).map(m=>Filesystem.join(i,m)).slice(0,3)).catch(()=>[]);return l.length>0?{valid:false,error:`File not found: ${o}
|
|
825
|
+
|
|
826
|
+
Did you mean one of these?
|
|
827
|
+
${l.join(`
|
|
828
|
+
`)}`}:{valid:false,error:`File not found: ${o}`}}if(s.isDirectory())return {valid:false,error:`Path is a directory, not a file: ${o}`};await Jt(e,o,{bypass:!!e.extra?.bypassCwdCheck,kind:"file",tool:"gateway"});let r=Se__default.posix.relative(R.worktree,o);return await e.ask({permission:"read",patterns:[r],always:["*"],metadata:{}}),{valid:true,filePath:o}}var qk=loadTextFile("./question.txt",import.meta.url),Hk=qk(),Og=De.define("question",{isEnabled:()=>["app","cli","desktop"].includes(a$2.EASBOT_CLIENT)||a$2.EASBOT_ENABLE_QUESTION_TOOL,description:Hk,parameters:N.object({questions:N.array(Ot.Info).describe("Questions to ask")}),async execute(e,t){let n=await Ot.ask({sessionId:t.sessionId,questions:e.questions,tool:t.callId?{messageId:t.messageId,callId:t.callId}:void 0});function o(r){return !r||r.length===0?"Unanswered":r.join(", ")}let s=e.questions.map((r,i)=>`"${r.question}"="${o(n[i])}"`).join(", ");return {title:`Asked ${e.questions.length} question${e.questions.length>1?"s":""}`,output:`User has answered your questions: ${s}. You can now continue with the user's answers in mind.`,metadata:{answers:n}}}});var jg=a.create({service:"tool.registry"}),Bk=[Xf,Og,Tf,rg,sg,mc,Df,fc,zf,$c,Yf,Pg,Oi,Kf,Bf,ig,cg,ug,gg,hg,Ag,_g,eg,kg,yg,qf,Ig],Un;(p=>{let e,t;async function n(){let u={},{Filesystem:h}=await import('@easbot/utils'),{glob:g}=await import('glob');for await(let I of h.up({targets:[".easbot/tools"],start:R.directory,stop:R.worktree})){if(!await h.isDir(I))continue;let T=await g("*.{ts,js}",{cwd:I,absolute:true,nodir:true,follow:false,dot:false});for(let y of T)try{let x=h.extname(y),b=h.basename(y,x),{pathToFileURL:w}=await import('url'),k=await import(w(y).href);for(let[v,C]of Object.entries(k)){let E=v==="default"?b:`${b}_${v}`;u[E]={...C,id:E,source:"custom"};}}catch(x){jg.error("Failed to load tool file",{file:y,error:x});}}return u}function o(){return e||(e=R.state(async()=>{let u={};for(let g of Bk)g.isEnabled&&!await g.isEnabled()||(u[g.id]={...g,source:"builtin"});let h=await n();for(let[g,I]of Object.entries(h))u[g]||(u[g]=I);if(t)for(let[g,I]of Object.entries(t))u[g]=I;return u})),e}async function s(){return o()()}p.state=s;async function r(){return s().then(u=>Object.values(u))}p.all=r;async function i(){return s().then(u=>Object.keys(u))}p.ids=i;async function c(u,h){let g=await r();return (await Promise.all(g.map(async T=>{let x=(await Le.triggerEvent(HookEvent.ToolDefinition,T)).output;if(x.isEnabled&&!await x.isEnabled())return null;let b=await x.init({agent:h});return {id:x.id,init:x.init,scope:x.scope,isEnabled:x.isEnabled,...b}}))).filter(T=>T!==null)}p.tools=c;async function l(u){t||(t={}),t[u.id]={...u,source:"plugin"},m();}p.register=l;async function d(u){return t?.[u]?(delete t[u],m(),true):false}p.unregister=d;function m(){e=void 0;}async function f(){t=void 0,m(),await s();}p.refresh=f;async function a(){await s(),jg.debug("tool registry initialized");}p.init=a;})(Un||(Un={}));var Kc=a.create({service:"tool.builder"}),Jc;(r=>{function e(i){return (c,l)=>({sessionId:i.sessionId,abort:l.abortSignal??new AbortController().signal,messageId:i.processor?.message.id??"",callId:l.toolCallId,extra:{model:i.model,bypassAgentCheck:i.bypassAgentCheck,directory:i.session.directory},agent:i.agentName,messages:i.messages??[],protocolMetadata:i.protocolMetadata,metadata:async d=>{if(!i.processor)return;let m=i.processor.partFromToolCall(l.toolCallId);m&&m.state.status==="running"&&await Y.updatePart({...m,state:{title:d.title,metadata:d.metadata,status:"running",input:c,time:{start:Date.now()}}});},ask:async d=>{await Me.ask({...d,sessionId:i.sessionId,tool:{messageId:i.processor?.message.id??"",callId:l.toolCallId??""},ruleset:Me.merge(i.agent.permission,i.session.permission??[])});}})}async function t(i$1){var C=[];try{let{agent:c$1,session:l,model:d,userTools:m,messages:f,userMessageId:a,processor:p,bypassAgentCheck:u,protocolMetadata:h,includeMCP:g=!0,includeBuiltIn:I=!0,toolFilter:T}=i$1;let y=c(C,Kc.time("buildTools"));let x=l.id;let b=l.contextMode??f$1;let w=e({sessionId:x,session:l,agent:c$1,model:d,agentName:c$1.name,messages:f??[],protocolMetadata:h,bypassAgentCheck:u,processor:p,userMessageId:a});let k={};if(I){let D=await Un.tools({providerId:d.providerId,modelId:d.api.id},c$1);for(let K of D){if(T&&!T(K.id))continue;let X=K.scope??i;if(X!=="all"&&X!==b)continue;let $=wt.schema(d,Vk.toJSONSchema(K.parameters));k[K.id]=tool({description:K.description,inputSchema:jsonSchema($),async execute(M,A){let L=w(M,A);await Le.triggerEvent(HookEvent.ToolBefore,{tool:K.id,sessionId:L.sessionId,userMessageId:a,callId:L.callId??""},{sessionId:L.sessionId});let S=await K.execute(M,L);return await Le.triggerEvent(HookEvent.ToolAfter,{tool:K.id,sessionId:L.sessionId,userMessageId:a,callId:L.callId??"",args:M},{sessionId:L.sessionId}),S}});}}if(g)try{let D=await ze.tools(),K=await ze.configInfo();for(let[X,$]of Object.entries(D)){if(T&&!T(X))continue;let M=X.split("_")[0];if(M){let S=K[M];if(S){let P=S.scope??i;if(P!=="all"&&P!==b)continue}}let A=$.execute;if(!A)continue;let L=wt.schema(d,await asSchema($.inputSchema).jsonSchema);$.inputSchema=jsonSchema(L),$.execute=async(S,P)=>{let _=w(S,P);await Le.triggerEvent(HookEvent.ToolBefore,{tool:X,sessionId:_.sessionId,userMessageId:a,callId:P.toolCallId},{sessionId:_.sessionId}),await _.ask({permission:X,metadata:{},patterns:["*"],always:["*"]});let j=await A(S,P);await Le.triggerEvent(HookEvent.ToolAfter,{tool:X,sessionId:_.sessionId,userMessageId:a,callId:P.toolCallId,args:S},{sessionId:_.sessionId});let B=[],Z=[];for(let le of j.content)if(le.type==="text")B.push(le.text);else if(le.type==="image")Z.push({id:Identifier.ascending("part"),sessionId:x,messageId:p?.message.id??"",type:"file",mime:le.mimeType,url:`data:${le.mimeType};base64,${le.data}`});else if(le.type==="resource"){let{resource:ae}=le;ae.text&&B.push(ae.text),ae.blob&&Z.push({id:Identifier.ascending("part"),sessionId:x,messageId:p?.message.id??"",type:"file",mime:ae.mimeType??"application/octet-stream",url:`data:${ae.mimeType??"application/octet-stream"};base64,${ae.blob}`,filename:ae.uri});}let ee=await Ve.output(B.join(`
|
|
829
|
+
|
|
830
|
+
`),{},c$1);return {title:"",metadata:{...j.metadata??{},truncated:ee.truncated,...ee.truncated&&{outputPath:ee.outputPath}},output:ee.content,attachments:Z,content:j.content}},k[X]=$;}}catch(D){Kc.error("Failed to load MCP tools",{error:D});}let v=n(k,c$1,m);Kc.debug("built tools",{count:Object.keys(v).length,includeBuiltIn:I,includeMCP:g,contextMode:b,userToolsDisabled:Object.entries(m??{}).filter(([,D])=>D===!1).map(([D])=>D)});return v}catch(E){var O=E,U=true;}finally{d(C,O,U);}}r.buildTools=t;function n(i,c,l){let d=Me.disabled(Object.keys(i),c.permission),m={...i};for(let f of Object.keys(m))(l?.[f]===false||d.has(f))&&delete m[f];return m}async function o(i={}){let{includeMCP:c=true,includeBuiltIn:l=true,toolFilter:d}=i,m=[];if(l){let f=await Un.ids();for(let a of f)d&&!d(a)||m.push(a);}if(c)try{let f=await ze.tools();for(let a of Object.keys(f))d&&!d(a)||m.includes(a)||m.push(a);}catch(f){Kc.error("Failed to load MCP tools",{error:f});}return m}r.listTools=o;async function s(i){let c=await Un.ids();if(Array.isArray(c)&&c.includes(i))return true;try{let l=await ze.tools();return i in l}catch{return false}}r.hasTool=s;})(Jc||(Jc={}));globalThis.AI_SDK_LOG_WARNINGS=false;var Je;(y=>{let e$1=a.create({service:"session.prompt"}),t;function n(){return t||(t=R.state(()=>({}),async x=>{for(let b of Object.values(x))b.abort.abort();})),t}function o(){return n()()}y.state=o;function s(x){if(o()[x])throw new Y.BusyError(x)}y.assertNotBusy=s,y.PromptInput=N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message").optional(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),agent:N.string().optional(),contextMode:N.enum(e).optional(),noReply:N.boolean().optional(),tools:N.record(N.string(),N.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),system:N.string().optional(),variant:N.string().optional(),parts:N.array(N.discriminatedUnion("type",[ve.TextPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"TextPartInput"}),ve.FilePart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"FilePartInput"}),ve.AgentPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"AgentPartInput"}),ve.SubtaskPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"SubtaskPartInput"}),ve.SubtaskResultPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"SubtaskResultPartInput"}),ve.MemoryPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"MemoryPartInput"})]))}),y.prompt=fn$1(y.PromptInput,async x=>{let b=await Y.get(x.sessionId);await io.cleanup(b),x.contextMode&&(await Y.update(b.id,v=>{v.contextMode=x.contextMode;}),b.contextMode=x.contextMode);let w=await p(x);await Y.touch(x.sessionId);let k=[];for(let[v,C]of Object.entries(x.tools??{}))k.push({permission:v,action:C?"allow":"deny",pattern:"*"});return k.length>0&&(b.permission=k,await Y.update(b.id,v=>{v.permission=k;})),x.noReply===true?w:(0, y.loop)({sessionId:x.sessionId})});async function c$1(x){let b=[{type:"text",text:x}],w=a$9.files(x),k=new Set;return await Promise.all(w.map(async v=>{let C=v[1];if(!C||k.has(C))return;k.add(C);let E=C.startsWith("~/")?Se__default.join(ec.homedir(),C.slice(2)):Se__default.resolve(R.worktree,C),O=await Tt__default.stat(E).catch(()=>{});if(O){if(O.isDirectory()){b.push({type:"file",url:pathToFileURL(E).href,filename:C,mime:"application/x-directory"});return}b.push({type:"file",url:pathToFileURL(E).href,filename:C,mime:"text/plain"});}})),b}y.resolvePromptParts=c$1;function l(x){let b=o();if(b[x])return;let w=new AbortController;return b[x]={abort:w,callbacks:[]},w.signal}y.start=l;function d$1(x){let b=o();if(b[x])return b[x].abort.signal}y.resume=d$1;async function m(x){e$1.debug("cancel",{sessionId:x});let b=o(),w=b[x];if(!w){await Mt.set(x,{type:"idle"});return}for(let k of w.callbacks)k.reject(new Error("Session aborted"));w.callbacks=[],w.abort.abort(),delete b[x],await Mt.set(x,{type:"idle"});}y.cancel=m,y.LoopInput=N.object({sessionId:Identifier.schema("session"),resume_existing:N.boolean().optional()}),y.loop=fn$1(y.LoopInput,async x=>{var $=[];try{let{sessionId:b,resume_existing:w}=x;let k=w?d$1(b):l(b);if(!k)return new Promise((P,_)=>{let j=o()[b]?.callbacks;if(!j){let B=o()[b]?.callbacks;B&&B.push({resolve:P,reject:_});return}j.push({resolve:P,reject:_});});let v=c($,defer(async()=>await m(b)),!0);let C=0;let E=await Y.get(b);for(;;){var O=[];try{await Mt.set(b,{type:"busy"});e$1.debug("loop",{step:C,sessionId:b});if(k.aborted)break;let P=await Le.triggerEvent(HookEvent.LoopStart,{sessionId:b,step:C,lastUserId:"",result:"start"},{sessionId:b});if(P.modified&&P.output?.result==="stop"){e$1.debug("exiting loop due to hook",{sessionId:b});break}let _=await ve.filterCompacted(ve.stream(b));let j;let B;let Z;let ee;let se=[];for(let ce=_.length-1;ce>=0;ce--){let ye=_[ce];if(!ye)continue;if(!j&&ye.info.role==="user"&&(j=ye.info,B=ye),!Z&&ye.info.role==="assistant"&&(Z=ye.info),!ee&&ye.info.role==="assistant"&&ye.info.finish&&(ee=ye),j&&ee)break;let je=ye.parts.filter(Ie=>Ie.type==="compaction"||Ie.type==="subtask");je.length>0&&!ee&&se.push(...je);}if(!j)throw new Error("No user message found in stream. This should never happen.");if(Z?.finish&&!["tool-calls","unknown"].includes(Z.finish)&&j.id<Z.id){e$1.debug("exiting loop",{sessionId:b});break}C++;C===1&&await T({session:E,modelId:j.model.modelId,providerId:j.model.providerId,history:_});let le=await xe.getModel(j.model.providerId,j.model.modelId).catch(async ce=>{if(xe.ModelNotFoundError.isInstance(ce)){let ye=ce.data.suggestions&&ce.data.suggestions.length>0?` Did you mean: ${ce.data.suggestions.join(", ")}?`:"";await pe.publish(Y.Event.Error,{sessionId:b,error:new NamedError.Unknown({message:`Model not found: ${ce.data.providerId}/${ce.data.modelId}.${ye}`}).toObject()});}throw ce});let ae=se.pop();if(ae?.type==="subtask"){let ce=await Oi.init(),ye=ae.model?await xe.getModel(ae.model.providerId,ae.model.modelId):le,je=await Y.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:j.id,sessionId:b,mode:ae.agent,agent:ae.agent,variant:j.variant,path:{cwd:R.directory,root:R.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:ye.id,providerId:ye.providerId,time:{created:Date.now()}}),Ie=await Y.updatePart({id:Identifier.ascending("part"),messageId:je.id,sessionId:je.sessionId,type:"tool",callId:ulid(),tool:Oi.id,state:{status:"running",input:{prompt:ae.prompt,description:ae.description,subagent_type:ae.agent,command:ae.command},time:{start:Date.now()}}}),Ce={operation:"create",prompt:ae.prompt,description:ae.description,subagent_type:ae.agent};await Le.triggerEvent(HookEvent.ToolBefore,{tool:"task",sessionId:b,userMessageId:je.parentId,callId:Ie.id},{sessionId:b});let ie,$e=await Ue.get(ae.agent);if(!$e)throw new Error(`Task agent not found: ${ae.agent}`);let Ae={agent:ae.agent,messageId:je.id,sessionId:b,abort:k,callId:Ie.callId,extra:{bypassAgentCheck:!0},messages:_,async metadata(Ct){await Y.updatePart({...Ie,type:"tool",state:{...Ie.state,...Ct}});},async ask(Ct){await Me.ask({...Ct,sessionId:b,ruleset:Me.merge($e.permission,E.permission??[])});}},pt=await ce.execute(Ce,Ae).catch(Ct=>{ie=Ct,e$1.error("subtask execution failed",{error:Ct,agent:ae.agent,description:ae.description});});if(await Le.triggerEvent(HookEvent.ToolAfter,{tool:"task",sessionId:b,userMessageId:je.parentId,callId:Ie.id,args:Ce},{sessionId:b}),je.finish="tool-calls",je.time.completed=Date.now(),await Y.updateMessage(je),pt&&Ie.state.status==="running"){let Ct;pt.attachments&&pt.attachments.length>0&&(Ct=pt.attachments.map(cn=>({...cn,id:cn.id??Identifier.ascending("part"),sessionId:cn.sessionId??Ie.sessionId,messageId:cn.messageId??Ie.messageId}))),await Y.updatePart({...Ie,state:{status:"completed",input:Ie.state.input,title:pt.title,metadata:pt.metadata,output:pt.output,attachments:Ct,time:{...Ie.state.time,end:Date.now()}}});}if(pt||await Y.updatePart({...Ie,state:{status:"error",error:ie?`Tool execution failed: ${ie.message}`:"Tool execution failed",time:{start:Ie.state.status==="running"?Ie.state.time.start:Date.now(),end:Date.now()},metadata:Ie.metadata,input:Ie.state.input}}),ae.command){let Ct={id:Identifier.ascending("message"),sessionId:b,role:"user",time:{created:Date.now()},agent:j.agent,model:j.model};await Y.updateMessage(Ct),await Y.updatePart({id:Identifier.ascending("part"),messageId:Ct.id,sessionId:b,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0});}continue}if(ae?.type==="compaction"){if(await on.compactConversation({messages:_,parentId:j.id,abort:k,sessionId:b,auto:ae.auto})==="stop")break;continue}let we=await Ue.get(j.agent);if(!we)throw new Error(`Agent not found: ${j.agent}`);let re=we.steps??1/0;let Q=C>=re;let H=wr.create({assistantMessage:await Y.updateMessage({id:Identifier.ascending("message"),parentId:j.id,role:"assistant",mode:we.name,agent:we.name,variant:j.variant,path:{cwd:R.directory,root:R.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:le.id,providerId:le.providerId,time:{created:Date.now()},sessionId:b}),sessionId:b,model:le,abort:k});let F=c(O,defer(()=>vs.clear(H.message.id)),!0);let te=_.findLast(ce=>ce.info.role==="user");let V=te?.parts.some(ce=>ce.type==="agent")??!1;let J=await mo.getProtocolMetadata(we);let oe=await Jc.buildTools({agent:we,session:E,model:le,userTools:j.tools,processor:{message:{id:H.message.id,parentId:H.message.parentId},partFromToolCall:ce=>H.partFromToolCall(ce)},bypassAgentCheck:V,messages:_,protocolMetadata:J,userMessageId:H.message.parentId});let de=await mo.build({sessionId:b,userMessage:B,user:j,messages:_,model:le,agent:we,session:E,tools:oe,isLastStep:Q,step:C,lastFinished:ee,maxMessages:100,mode:E.contextMode});if(de.metadata.needsCompaction){await on.create({sessionId:b,agent:"compaction",model:j.model,auto:!0});continue}let me=await H.process({user:j,agent:we,abort:k,sessionId:b,system:de.system,messages:de.messages,tools:oe,model:le,mode:de.metadata.mode});if(me==="stop"){let ce=await Le.triggerEvent(HookEvent.LoopEnd,{sessionId:b,step:C,lastUserId:j.id,result:"stop"},{sessionId:b});if(ce.modified&&ce.output.result==="continue")continue;break}me==="compact"&&await on.create({sessionId:b,agent:"compaction",model:j.model,auto:!0});}catch(U){var D=U,K=!0;}finally{var X=d(O,D,K);X&&await X;}}await on.prune({sessionId:b});for await(let P of ve.stream(b)){if(P.info.role==="user")continue;let _=o()[b]?.callbacks??[];for(let j of _)j.resolve(P);return P}throw new Error("Impossible")}catch(M){var A=M,L=true;}finally{var S=d($,A,L);S&&await S;}});async function p(x){var U=[];try{let b=await Ue.get(x.agent??await Ue.defaultAgent());if(!b)throw new Error(`Agent not found: ${x.agent}`);let w=x.model??b.model??await Xo(x.sessionId);let k=!x.variant&&b.variant&&w.providerId?await xe.getModel(w.providerId,w.modelId).catch(()=>{}):void 0;let v=x.variant??(b.variant&&k?.variants?.[b.variant]?b.variant:void 0);let C={id:x.messageId??Identifier.ascending("message"),role:"user",sessionId:x.sessionId,time:{created:Date.now()},tools:x.tools,agent:b.name,model:{providerId:w.providerId,modelId:w.modelId},system:x.system,variant:v};let E=c(U,defer(()=>vs.clear(C.id)),!0);let O=await Promise.all(x.parts.map(async M=>{if(M.type==="file"){if(M.source?.type==="resource"){let{clientName:L,uri:S}=M.source;e$1.debug("mcp resource",{clientName:L,uri:S,mime:M.mime});let P=[{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Reading MCP resource: ${M.filename} (${S})`}];try{let _=await ze.readResource(L,S);if(!_)throw new Error(`Resource not found: ${L}/${S}`);let j=Array.isArray(_.contents)?_.contents:[_.contents];for(let B of j)if("text"in B&&B.text)P.push({id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:B.text});else if("blob"in B&&B.blob){let Z="mimeType"in B?B.mimeType:M.mime;P.push({id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`[Binary content: ${Z}]`});}P.push({...M,id:M.id??Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId});}catch(_){e$1.error("failed to read MCP resource",{error:_,clientName:L,uri:S});let j=_ instanceof Error?_.message:String(_);P.push({id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Failed to read MCP resource ${M.filename}: ${j}`});}return P}let A=new URL(M.url);switch(A.protocol){case "data:":if(M.mime==="text/plain")return [{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:M.filename})}`},{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:Buffer.from(M.url,"base64url").toString()},{...M,id:M.id??Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId}];break;case "file:":{e$1.debug("file",{mime:M.mime});let L=fileURLToPath(M.url),S;try{S=await Tt__default.stat(L);}catch{S=void 0;}if(S?.isDirectory()&&(M.mime="application/x-directory"),M.mime==="text/plain"){let P,_,j={start:A.searchParams.get("start"),end:A.searchParams.get("end")};if(j.start!=null){let ee=M.url.split("?")[0]??"",se=parseInt(j.start,10),le=j.end?parseInt(j.end,10):void 0;if(se===le){let ae=fileURLToPath(ee),we=await We.documentSymbol({file:ae}).catch(()=>[]);for(let re of we){let Q;if("range"in re?Q=re.range:"location"in re&&(Q=re.location.range),Q?.start?.line&&Q?.start?.line===se){se=Q.start.line,le=Q?.end?.line??se;break}}}P=Math.max(se-1,0),le&&(_=le-P);}let B={filePath:L,offset:P,limit:_},Z=[{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(B)}`}];return await mc.init().then(async ee=>{let se=await xe.getModel(C.model.providerId,C.model.modelId),le={sessionId:x.sessionId,abort:new AbortController().signal,agent:x.agent,messageId:C.id,extra:{bypassCwdCheck:!0,model:se},messages:[],metadata:async()=>{},ask:async()=>{}},ae=await ee.execute(B,le);Z.push({id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:ae.output}),ae.attachments&&ae.attachments.length>0?Z.push(...ae.attachments.map(we=>({...we,id:we.id??Identifier.ascending("part"),synthetic:!0,filename:we.filename??M.filename,messageId:C.id,sessionId:x.sessionId}))):Z.push({...M,id:M.id??Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId});}).catch(async ee=>{e$1.error("failed to read file",{error:ee});let se=ee instanceof Error?ee.message:ee.toString();await pe.publish(Y.Event.Error,{sessionId:x.sessionId,error:new NamedError.Unknown({message:se}).toObject()}),Z.push({id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Read tool failed to read ${L} with the following error: ${se}`});}),Z}if(M.mime==="application/x-directory"){let P={path:L,limit:100},_={sessionId:x.sessionId,abort:new AbortController().signal,agent:x.agent,messageId:C.id,extra:{bypassCwdCheck:!0},messages:[],metadata:async()=>{},ask:async()=>{}},j=await fc.init().then(B=>B.execute(P,_));return [{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the list tool with the following input: ${JSON.stringify(P)}`},{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:j.output},{...M,id:M.id??Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId}]}else {let P=await Tt__default.readFile(L);return An.read(x.sessionId,L),[{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",text:`Called the Read tool with the following input: {"filePath":"${L}"}`,synthetic:!0},{id:M.id??Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"file",url:`data:${M.mime};base64,`+Buffer.from(P).toString("base64"),mime:M.mime,filename:M.filename,source:M.source}]}}}}if(M.type==="agent"){let L=Me.evaluate("task",M.name,b.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return [{id:Identifier.ascending("part"),...M,messageId:C.id,sessionId:x.sessionId},{id:Identifier.ascending("part"),messageId:C.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+M.name+L}]}return [{id:Identifier.ascending("part"),...M,messageId:C.id,sessionId:x.sessionId}]})).then(M=>M.flat());await Le.triggerEvent(HookEvent.MessageReceive,{sessionId:x.sessionId,agent:x.agent,model:x.model,userMessageId:C.id,messageId:x.messageId,variant:x.variant});await Y.updateMessage(C);for(let M of O)await Y.updatePart(M);return {info:C,parts:O}}catch(D){var K=D,X=true;}finally{var $=d(U,K,X);$&&await $;}}y.ShellInput=N.object({sessionId:Identifier.schema("session"),agent:N.string(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),command:N.string()});async function h(x){return Di.shell(x)}y.shell=h,y.CommandInput=N.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:N.string().optional(),model:N.string().optional(),contextMode:N.enum(e).optional(),arguments:N.union([N.string(),N.record(N.string(),N.unknown())]),command:N.string(),variant:N.string().optional(),parts:N.array(N.discriminatedUnion("type",[ve.TextPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"TextPartInput"}),ve.FilePart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"FilePartInput"})])).optional()});async function I(x){return x.contextMode&&await Y.update(x.sessionId,b=>{b.contextMode=x.contextMode;}),Di.execute(x)}y.command=I;async function T(x){if(x.session.parentId||!Y.isDefaultTitle(x.session.title))return;let b=x.history.findIndex(X=>X.info.role==="user"&&!X.parts.every($=>"synthetic"in $&&$.synthetic));if(b===-1||!(x.history.filter(X=>X.info.role==="user"&&!X.parts.every($=>"synthetic"in $&&$.synthetic)).length===1))return;let k=x.history.slice(0,b+1),v=k[b];if(!v)return;let C=v.parts.filter(X=>X.type==="subtask"),E=C.length>0&&v.parts.every(X=>X.type==="subtask"),O=await Ue.get("title");if(!O)return;let U=await iife(async()=>O.model?await xe.getModel(O.model.providerId,O.model.modelId):await xe.getSmallModel(x.providerId)??await xe.getModel(x.providerId,x.modelId)),D=await Jo.stream({agent:O,user:v.info,system:[O.prompt??""],small:true,tools:{},model:U,abort:new AbortController().signal,sessionId:x.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
|
|
831
|
+
`},...E?[{role:"user",content:C.map(X=>X.prompt).join(`
|
|
832
|
+
`)}]:await ve.toModelMessages(k,U)]}),K=await Promise.resolve(D.text).catch(X=>{e$1.error("failed to generate title",{error:X});});if(K)return Y.update(x.session.id,X=>{let $=K.replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
|
|
833
|
+
`).map(A=>A.trim()).find(A=>A.length>0);if(!$)return;let M=$.length>100?$.substring(0,97)+"...":$;X.title=M;},{touch:false})}})(Je||(Je={}));var Vi=a.create({service:"forked-agent"}),Sr;(n=>{async function e(o){let{source:s,title:r,agent:i,parts:c,model:l,system:d,tools:m,syncMessages:f,metadata:a}=o,p=await Y.fork({sessionId:s});try{let u=await Cm(s),h=i??u?.agent??await Ue.defaultAgent(),g;if(l?.providerId&&l.modelId?g={providerId:l.providerId,modelId:l.modelId}:g=(await Ue.get(h))?.model,!l){let{Provider:x}=await import('./provider-2RFHZVX4.mjs');g=u?.model??await x.defaultModel();}Vi.debug("forked started and session created",{sessionId:p.id,source:s,title:r,agent:h,model:g}),await Je.prompt({sessionId:p.id,system:d,tools:m,agent:h,model:g,parts:c??[]}),Vi.debug("forked agent prompt sent",{sessionId:p.id,agent:h});let I=await ve.getLastMessages(p.id,{filterByText:!0}),T="";I.lastAssistantWithText&&(T=I.lastAssistantWithText.parts.filter(x=>x.type==="text").map(x=>x.text).join(""));let y={title:r,output:T,metadata:{...a,sessionId:p.id,source:s,agent:h,userMessage:I.lastUser,assistantMessage:I.lastAssistant}};if(f&&I.lastUser&&I.lastFinished){let x=await t(p.id,s,I,h);y.metadata.userMessage=x.userMessage,y.metadata.assistantMessage=x.assistantMessage;}return Vi.debug("forked agent completed",{sessionId:p.id,source:s,title:r,agent:h,contentLength:T.length,hasText:T.length>0,lastUser:I.lastUser?.id,lastAssistant:I.lastAssistant?.id,lastFinished:I.lastFinished?.info?.id}),y}finally{await Y.remove(p.id),Vi.debug("forked session removed",{sessionId:p.id});}}n.run=e;async function t(o,s,r,i){if(!r.lastUser||!r.lastFinished)throw new Error("Messages not found in forked session");let c=i??r.lastUser.agent??await Ue.defaultAgent(),l=Identifier.ascending("message"),d={...r.lastUser,id:l,agent:c,sessionId:s};await Y.updateMessage(d);for(let a of r.lastUserMessage.parts)await Y.updatePart({...a,id:Identifier.ascending("part"),messageId:l,sessionId:s});let m=Identifier.ascending("message"),f={...r.lastFinished.info,id:m,parentId:l,agent:c,sessionId:s};await Y.updateMessage(f);for(let a of r.lastFinished.parts)await Y.updatePart({...a,id:Identifier.ascending("part"),messageId:m,sessionId:s});return Vi.debug("messages synced",{fromSessionID:o,toSessionID:s,userMessageId:l,assistantMessageId:m}),{userMessage:d,assistantMessage:f}}n.syncMessagesToParent=t;})(Sr||(Sr={}));var as=a.create({service:"hook.builtin.memory"}),Hg=2e3,Eu=new Map;function Bg(e,t){return `${e}:${t??"default"}`}async function eP(e,t,n){let o=[];if(t){let r=t.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&o.push({role:"user",content:r});}let s=await ve.get({sessionId:e,messageId:n});if(s){let r=s.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&o.push({role:"assistant",content:r});}return o}async function tP(e){if(e.length===0)return "";let t=`### Our Conversation
|
|
834
|
+
|
|
835
|
+
`;for(let n of e.slice(-4)){let o=Token.estimate(n.content),s=n.content,r=false;if(o>Hg){s=n.content.slice(-8e3),r=true;}r?t+=`**${n.role==="user"?"User":"Me"}**: ${s}
|
|
836
|
+
|
|
837
|
+
[Content truncated from ${o} tokens]
|
|
838
|
+
|
|
839
|
+
`:t+=`**${n.role==="user"?"User":"Me"}**: ${s||"(empty)"}
|
|
840
|
+
|
|
841
|
+
`;}return t}function nP(){return `### My Reflection
|
|
842
|
+
|
|
843
|
+
After reading this conversation, I ask myself:
|
|
844
|
+
|
|
845
|
+
**Mistakes & Corrections:**
|
|
846
|
+
- Did I make any mistakes the user corrected?
|
|
847
|
+
- What errors should I avoid next time?
|
|
848
|
+
- Is there a pattern I keep getting wrong?
|
|
849
|
+
|
|
850
|
+
**Better Approaches:**
|
|
851
|
+
- Was there a smarter way to solve this?
|
|
852
|
+
- What approach would be more efficient?
|
|
853
|
+
- Any workflow improvements I discovered?
|
|
854
|
+
|
|
855
|
+
**Knowledge & Context:**
|
|
856
|
+
- What new insights did I gain?
|
|
857
|
+
- What preferences did the user show?
|
|
858
|
+
- What context is important for future work?
|
|
859
|
+
|
|
860
|
+
**Evolution:**
|
|
861
|
+
- How can I do better next time?
|
|
862
|
+
- What should I remember to improve my effectiveness?
|
|
863
|
+
|
|
864
|
+
If nothing special happened, don't save anything.
|
|
865
|
+
|
|
866
|
+
Importance 1-10, skip 1-3`}var Ru=Kt("memory",{async init(){return await In.isEnabled()?{isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:(t,n)=>{let o=t;if(!o.userMessageId)return {modified:false,input:t};let s=Bg(o.sessionId,o.userMessageId);return Eu.set(s,{startTime:Date.now()}),as.debug("step start recorded",{key:s}),{modified:false,input:t}}},{name:HookEvent.StepFinish,handler:async(t,n)=>{let o=t;if(!o.userMessageId)return as.debug("step.finish: no userMessageId, skip"),{modified:false,input:t};let s=Bg(o.sessionId,o.userMessageId);as.debug("step.finish: memory extract started",{convKey:s,finishReason:o.finishReason,messageId:o.messageId});let r=await ve.get({sessionId:o.sessionId,messageId:o.userMessageId});if(r?.parts.some(u=>u.type==="memory"))return as.debug("step.finish: skip memory extract, already processing"),{modified:false,input:t};let i=Identifier.ascending("part"),c=Date.now(),l={id:i,sessionId:o.sessionId,messageId:o.userMessageId,type:"memory",status:"processing",time:{start:c}};await Y.updatePart(l);let d=Eu.get(s);Eu.delete(s);let m="";d&&(m=`Step Duration: ${((Date.now()-d.startTime)/1e3).toFixed(1)}s`);let f=await eP(o.sessionId,r,o.messageId);if(!f.some(u=>u.role==="assistant"&&u.content))return as.debug("step.finish: skip memory extract, no assistant text content",{convKey:s,finishReason:o.finishReason,messageId:o.messageId}),await Y.updatePart({...l,status:"skipped",time:{start:c,end:Date.now()},reason:`No assistant text content (finish: ${o.finishReason})`}),{modified:false,input:t};let p=`## Conversation Reflection
|
|
867
|
+
|
|
868
|
+
Local Time: ${formatLocalISOCompact(new Date)}
|
|
869
|
+
Finish Reason: ${o.finishReason}
|
|
870
|
+
${m?`${m}
|
|
871
|
+
`:""}${o.tokens?`Tokens Used: ${o.tokens.total??0}
|
|
872
|
+
`:""}}
|
|
873
|
+
|
|
874
|
+
${await tP(f)}
|
|
875
|
+
|
|
876
|
+
${nP()}`;return Sr.run({source:o.sessionId,title:"memory-extract",agent:"memory",syncMessages:false,parts:[{type:"memory",status:"processing",time:{start:c}},{type:"text",text:p}]}).then(async u=>{as.debug("memory extract completed",{outputLength:u.output.length}),await Y.updatePart({...l,status:"completed",time:{start:c,end:Date.now()},result:u.output});}).catch(async u=>{as.error("memory extract failed",{error:u.message}),await Y.updatePart({...l,status:"failed",time:{start:c,end:Date.now()},error:u.message});}),{modified:false,input:t}}}]}:(as.debug("memory hook disabled, skipping"),{isEnabled:()=>false,handlers:[]})}});var Wg=a.create({service:"hook.builtin.compaction"}),_u=Kt("compaction",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.SessionStart,handler:async(e,t)=>{let n=e;return Wg.debug("session.start hook triggered, resetting compaction failure counter",{sessionId:n.sessionId,agent:n.agent}),await on.resetSessionFailures(n.sessionId),{modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let n=e;return Wg.debug("step.finish hook triggered, resetting compaction failure counter",{sessionId:n.sessionId,agent:n.agent,finishReason:n.finishReason}),await on.resetSessionFailures(n.sessionId),{modified:false,input:e}}}]}}});var Es=a.create({service:"hook.builtin.coder"}),Mu=new Map,Ou=Kt("coder",{async init(){return {scope:g.Coder,isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:async(e,t)=>{let n=e;try{Es.debug("coder.step-start hook triggered",{sessionId:n.sessionId,messageId:n.messageId});let o=await yt.track();Mu.set(n.sessionId,o);let r=(await ve.parts(n.messageId)).find(i=>i.type==="step-start");r&&o&&await Y.updatePart({...r,snapshot:o}),Es.debug("coder.step-start hook completed",{sessionId:n.sessionId,hasSnapshot:!!o});}catch(o){Es.error("coder.step-start hook error",{sessionId:n.sessionId,error:String(o)});}return {modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let n=e;try{Es.debug("coder.step-finish hook triggered",{sessionId:n.sessionId,messageId:n.messageId,finishReason:n.finishReason});let o=Mu.get(n.sessionId);if(o){let r=(await ve.parts(n.messageId)).find(c=>c.type==="step-finish");r&&await Y.updatePart({...r,snapshot:o});let i=await yt.patch(o);i.files.length>0&&(await Y.updatePart({id:Identifier.ascending("part"),messageId:n.messageId,sessionId:n.sessionId,type:"patch",hash:i.hash,files:i.files}),Es.debug("coder.step-finish patch generated",{sessionId:n.sessionId,hash:i.hash,fileCount:i.files.length})),Mu.delete(n.sessionId);}Es.debug("coder.step-finish hook completed",{sessionId:n.sessionId});}catch(o){Es.error("coder.step-finish hook error",{sessionId:n.sessionId,error:String(o)});}return {modified:false,input:e}}}]}}});var Sn=a.create({service:"hook.builtin.gateway"}),ju=new Map,Lu=Kt("gateway",{async init(){return {handlers:[{name:HookEvent.GatewayMessageReceive,handler:async(e,t)=>{let n=e,o=t.messageStore;return o?n?.id?(await o.store(n),Sn.debug("gateway message stored",{id:n.id,sessionId:n.sessionId,type:n.type}),{modified:false,input:e}):(Sn.warn("gateway message receive: missing id",{input:e}),{modified:false,input:e}):(Sn.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageProcess,handler:async(e,t)=>{let n=e,o=n.id,s=t.messageStore;return s?o?(ju.set(o,n.timestamp??Date.now()),await s.updateStatus(o,"processing",{processorId:n.processorId,processType:n.processType,agent:n.agent}),Sn.debug("gateway message processing",{id:o}),{modified:false,input:e}):(Sn.warn("gateway message process: missing id",{input:e}),{modified:false,input:e}):(Sn.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageComplete,handler:async(e,t)=>{let n=e,o=n.id,s=t.messageStore;if(!s)return Sn.debug("messageStore not available in context"),{modified:false,input:e};if(!o)return Sn.warn("gateway message complete: missing id",{input:e}),{modified:false,input:e};let r=ju.get(o);return ju.delete(o),await s.updateStatus(o,n.status??"completed",{error:n.error,responseMessageId:n.responseMessageId,tokens:n.tokens,duration:n.duration??(r?Date.now()-r:void 0),processedBy:n.processorId??n.agent}),Sn.debug("gateway message completed",{id:o,status:n.status}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageSend,handler:async(e,t)=>{let n=e,o=t.messageStore;if(!n?.id)return Sn.warn("gateway message send: missing id",{input:e}),{modified:false,input:e};if(o){let s=n.processorId||n.agent||"gateway";await o.store({id:n.id,sessionId:n.sessionId,type:n.type,content:n.content||[],channel:n.channel,replyToMessageId:n.replyToMessageId,proactive:n.proactive??!n.replyToMessageId,timestamp:n.timestamp,processorId:n.processorId,agent:n.agent},"completed"),n.replyToMessageId&&await o.updateStatus(n.replyToMessageId,"completed",{processedBy:s});}return Sn.debug("gateway message sent",{id:n.id,proactive:n.proactive}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageDelivered,handler:async(e,t)=>{let n=e,o=t.messageStore;return n?.id?(o&&await o.updateStatus(n.id,"delivered",{deliveredAt:n.timestamp}),Sn.debug("gateway message delivered",{id:n.id}),{modified:false,input:e}):(Sn.warn("gateway message delivered: missing id",{input:e}),{modified:false,input:e})}},{name:HookEvent.GatewayMessageRead,handler:async(e,t)=>{let n=e,o=t.messageStore;return n?.id?(o&&await o.updateStatus(n.id,"read",{readAt:n.timestamp}),Sn.debug("gateway message read",{id:n.id}),{modified:false,input:e}):(Sn.warn("gateway message read: missing id",{input:e}),{modified:false,input:e})}}]}}});var Du=a.create({service:"hook.executor.prompt"}),Rs=class Rs{constructor(){b$1(this,"type","prompt");}static getInstance(){return Rs._instance||(Rs._instance=new Rs),Rs._instance}canExecute(t){return t?.type==="prompt"}async execute(t,n,o){let s=Date.now(),r=t.runMode??"session";try{return Du.debug("Execute Prompt Hook",{partsCount:t.parts?.length,model:t.model,runMode:r,context:o?.sessionId}),r==="fork"?await this.executeInFork(t,n,o,s):await this.executeInSession(t,n,o,s)}catch(i){return Du.error("Prompt Hook execution failed",{error:i?.message,stack:i?.stack}),{success:false,modified:false,error:i?.message??String(i),duration:Date.now()-s}}}async executeInSession(t,n,o,s){let r=s??Date.now(),i=o?.sessionId??"",c=Identifier.ascending("message"),d=(await Je.prompt({messageId:c,sessionId:i,model:t.model,system:t.system,parts:t.parts})).parts.findLast(m=>m.type==="text")?.text??"";return {success:true,modified:n.modified,input:n.input,output:d,duration:Date.now()-r}}async executeInFork(t,n,o,s){let r=s??Date.now(),i=o?.sessionId??"";if(!i)return {success:false,modified:false,error:"Fork mode requires sessionId in context",duration:Date.now()-r};Du.debug("Fork session for Prompt Hook",{sourceSessionID:i});let c=await Y.fork({sessionId:i});try{let l=Identifier.ascending("message"),m=(await Je.prompt({messageId:l,sessionId:c.id,model:t.model,system:t.system,agent:o?.agent,parts:t.parts})).parts.findLast(f=>f.type==="text")?.text??"";return {success:!0,modified:n.modified,input:n.input,output:m,duration:Date.now()-r}}finally{await Y.remove(c.id);}}};b$1(Rs,"_instance");var Ki=Rs;var Yg=a.create({service:"hook.builtin.heartbeat"});var $u=Kt("heartbeat.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.HeartbeatTrigger,handler:async(e,t)=>{let n=e;return Yg.debug("Heartbeat trigger event received",{timestamp:n.timestamp,name:n.name}),{modified:false,input:e}}},{name:HookEvent.HeartbeatComplete,handler:(e,t)=>{let n=e;return Yg.debug("Heartbeat complete event received",{timestamp:n.timestamp,duration:n.duration}),{modified:false,input:e}}}]}}});var _s=class _s{constructor(){b$1(this,"type","function");}static getInstance(){return _s._instance||(_s._instance=new _s),_s._instance}canExecute(t){return t?.type==="function"}async execute(t,n,o){try{let s=t.handler,r=await s(n.input,o??{});return {success:!0,modified:r.modified,input:r.input}}catch(s){return {success:false,modified:false,error:s instanceof Error?s.message:String(s)}}}};b$1(_s,"_instance");var Xc=_s;var Xg=a.create({service:"hook.executor.command"}),Ms=class Ms{constructor(){b$1(this,"type","command");}static getInstance(){return Ms._instance||(Ms._instance=new Ms),Ms._instance}canExecute(t){return t?.type==="command"}async execute(t,n,o){let s=Date.now();try{Xg.debug("Execute Command Hook",{command:t.command,context:o});let i=await createPkgShell({cwd:o?.cwd,env:{...process.env,...n.input}})`${t.command}`.nothrow();return i.exitCode===0?{success:!0,modified:n.modified,input:n.input,stdout:i.text(),stderr:i.stderr.toString(),duration:Date.now()-s}:{success:!1,modified:n.modified,input:n.input,stdout:i.text(),stderr:i.stderr.toString(),exitCode:i.exitCode,duration:Date.now()-s}}catch(r){return Xg.error("Command Hook execution failed",{error:r?.message}),{success:false,modified:false,error:r?.message??String(r),duration:Date.now()-s}}}};b$1(Ms,"_instance");var Qc=Ms;var Qg=a.create({service:"hook.executor.http"}),Os=class Os{constructor(){b$1(this,"type","http");}static getInstance(){return Os._instance||(Os._instance=new Os),Os._instance}canExecute(t){return t?.type==="http"}async execute(t,n,o){let s=Date.now(),r=t.timeout??3e4,i=t.method??"GET";try{Qg.debug("Execute HTTP Hook",{url:t.url,method:i,context:o});let c={"Content-Type":"application/json",...t.headers};if(t.allowedEnvVars&&t.allowedEnvVars.length>0)for(let p of t.allowedEnvVars)process.env[p]&&(c[p]=process.env[p]);let l=new AbortController,d=setTimeout(()=>l.abort(),r),m=await Fetch.request(t.url,{method:i,headers:c,body:i!=="GET"?JSON.stringify(n.input):void 0,responseType:"text",signal:l.signal});clearTimeout(d);let f=m.data,a;try{a=JSON.parse(f);}catch{a=f;}return {success:m.ok,modified:n.modified,input:n.input,output:a,stdout:f,exitCode:m.ok?0:m.status,duration:Date.now()-s}}catch(c){return Qg.error("HTTP Hook execution failed",{error:c?.message}),{success:false,modified:false,error:c?.message??String(c),duration:Date.now()-s}}}};b$1(Os,"_instance");var Zc=Os;var Zg=a.create({service:"hook.executor.agent"}),js=class js{constructor(){b$1(this,"type","agent");}static getInstance(){return js._instance||(js._instance=new js),js._instance}canExecute(t){return !t||typeof t!="object"?false:t.type==="agent"}async execute(t,n,o){let s=Date.now();try{Zg.debug("Execute Agent Hook",{type:t.type,timeout:t.timeout,context:o?.sessionId});let r=await ks.run({source:o?.sessionId??"",title:this.extractTitle(t.parts),agent:"default",system:t.system,parts:t.parts,model:t.model?{modelId:t.model,providerId:"default"}:void 0,syncMessages:!1});return {success:!0,modified:n.modified,input:n.input,output:r.output,duration:Date.now()-s}}catch(r){return Zg.error("Agent Hook execution failed",{error:r?.message,stack:r?.stack}),{success:false,modified:false,error:r?.message??String(r),duration:Date.now()-s}}}extractTitle(t){if(!t||t.length===0)return "Agent Task";let n=t.find(o=>typeof o=="object"&&o!==null&&o.type==="text");return n&&typeof n.text=="string"?n.text.slice(0,50):"Agent Task"}};b$1(js,"_instance");var Ji=js;var cs=class cs{constructor(){b$1(this,"executors",[]);}static getInstance(){return cs._instance||(cs._instance=new cs,cs._instance.registerDefaultExecutors()),cs._instance}registerDefaultExecutors(){this.register(Xc.getInstance()),this.register(Qc.getInstance()),this.register(Ki.getInstance()),this.register(Zc.getInstance()),this.register(Ji.getInstance());}register(t){this.executors.push(t);}getExecutor(t){return this.executors.find(n=>n.canExecute(t))}async execute(t,n,o){let s=this.getExecutor(t);return s?s.execute(t,n,o):{success:false,modified:false,error:`No executor found for hook type: ${t.type}`}}};b$1(cs,"_instance");var Yi=cs;var th=a.create({service:"hook.builtin.scheduler"});var Fu=Kt("scheduler.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ScheduledTaskTrigger,handler:async(e,t)=>{let n=e;return th.debug("Scheduled task trigger event received",{taskID:n.taskID,taskName:n.taskName,timestamp:n.timestamp}),{modified:false,input:e}}},{name:HookEvent.ScheduledTaskComplete,handler:(e,t)=>{let n=e;return th.debug("Scheduled task complete event received",{taskID:n.taskID,timestamp:n.timestamp,success:n.success}),{modified:false,input:e}}}]}}});var oh=a.create({service:"hook.builtin.context"}),Nu=Kt("context.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ContextBuildBefore,handler:(e,t)=>{let n=e;return oh.debug("context.build.before hook triggered",{sessionId:n.sessionId,mode:n.mode}),{modified:false,input:e}}},{name:HookEvent.ContextBuildAfter,handler:(e,t)=>{let n=e;return oh.debug("context.build.after hook triggered",{sessionId:n.context.metadata.sessionId}),{modified:false,input:e}}}]}}});var gn=a.create({service:"hook.builtin.task"});async function iP(e){try{return (await Mt.get(e)).type==="idle"}catch{return false}}async function aP(e){let{taskId:t,duration:n,error:o}=e;e.source==="scheduler"&&gn.debug("Scheduled task completed",{taskId:t,duration:n,success:!o});}async function cP(e){let{taskId:t,error:n}=e;e.source==="cli"&&(n?gn.error("CLI task error",{taskId:t,error:n}):gn.debug("CLI task completed",{taskId:t}));}async function dP(e){let{taskId:t,result:n,error:o}=e;e.source==="api"&&gn.debug("API task event",{taskId:t,hasError:!!o,hasResult:!!n});}var lP={tool:async()=>gn.debug("Tool task completed"),scheduler:aP,cli:cP,api:dP};async function uP(e){try{await jt.create({taskId:e.taskId,sessionId:e.sessionId,description:e.description||"",prompt:e.prompt||"",agentType:e.agentType||"unknown",source:e.source,metadata:{agentType:e.agentType}});}catch(t){gn.error("Failed to create task",{taskId:e.taskId,error:String(t)});return}gn.debug("Task created (pending)",{taskId:e.taskId,sessionId:e.sessionId,source:e.source,agentType:e.agentType});}async function pP(e){await jt.update(e.taskId,{status:"running"}),gn.debug("Task running",{taskId:e.taskId,sessionId:e.sessionId});}async function mP(e){if(!await jt.get(e.taskId)){gn.warn("Task progress for unknown task",{taskId:e.taskId});return}gn.debug("Task progress",{taskId:e.taskId,step:e.step,totalSteps:e.totalSteps});}async function fP(e){let t=await jt.get(e.taskId);if(!t){gn.warn("Task complete for unknown task",{taskId:e.taskId});return}await jt.update(e.taskId,{status:e.error?"error":"completed",result:e.result,error:e.error,duration:e.duration,metadata:e.metadata}),gn.debug("Task completed (persisted)",{taskId:e.taskId,sessionId:t.sessionId,source:e.source,duration:e.duration,hasError:!!e.error}),await lP[e.source](e),t.sessionId&&e.source==="tool"&&(e.result||e.error?await gP(t,e):gn.debug("Task completed without result, skip injection",{taskId:e.taskId,sessionId:t.sessionId}));}async function gP(e,t){if(e?.sessionId)try{let n=await iP(e.sessionId);await Je.prompt({sessionId:e.sessionId,parts:[{type:"subtask-result",taskId:e.taskId,source:e.source,agent:t.agentType??e.agentType,status:t.error?"error":"completed",result:t.result,error:t.error,duration:t.duration,time:{start:e.createdAt,end:Date.now()},metadata:t.metadata}],noReply:!n}),n?gn.debug("Injected result to parent session (agent idle, will trigger LLM)",{taskId:e.taskId,sessionId:e.sessionId}):gn.debug("Injected result to parent session (agent busy, queued for next turn)",{taskId:e.taskId,sessionId:e.sessionId});}catch(n){gn.error("Failed to inject result to parent session",{taskId:e.taskId,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)});}}var Uu=Kt("task.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.TaskStart,handler:async e=>(await uP(e),{modified:false,input:e})},{name:HookEvent.TaskRunning,handler:async e=>(await pP(e),{modified:false,input:e})},{name:HookEvent.TaskProgress,handler:async e=>(await mP(e),{modified:false,input:e})},{name:HookEvent.TaskComplete,handler:async e=>(await fP(e),{modified:false,input:e})}]}}});var td=a.create({service:"hook.builtin.loop"});async function hP(e,t){let n=await ve.getLastMessages(e);return !n.lastUser||n.lastUser.id===t?false:n.lastFinished?n.lastFinished.info.role==="assistant"&&n.lastFinished.info.parentId!==n.lastUser.id?(td.debug("Latest assistant message does not respond to latest user message, should continue loop",{lastUserId:n.lastUser.id,assistantParentId:n.lastFinished.info.parentId}),true):false:(td.debug("Found new user message without assistant response, should continue loop",{lastUserId:n.lastUser.id,expectedParentId:n.lastUser.id}),true)}var zu=Kt("loop.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.LoopStart,handler:async e=>{let t=e;return td.debug("Loop started",{sessionId:t.sessionId,step:t.step}),{modified:false,input:e}}},{name:HookEvent.LoopEnd,handler:async e=>{let t=e;return t.result==="stop"&&await hP(t.sessionId,t.lastUserId)?(td.debug("Loop should continue for pending messages"),{modified:true,input:{...t,result:"continue"}}):{modified:false,input:e}}}]}}});var rh=a.create({service:"hook.matcher"}),Ls=class Ls{static getInstance(){return Ls._instance||(Ls._instance=new Ls),Ls._instance}match(t,n,o){return t.event!==n?{matched:false}:t.matcher&&!this.evaluateCondition(t.matcher,o)?(rh.debug("Hook matcher condition not met",{matcher:t.matcher,context:o}),{matched:false}):{matched:true}}matchHook(t,n,o){return !("if"in t)||!t.if?true:this.evaluateCondition(t.if,o)}getHookName(t){switch(t.type){case "function":return "function";case "command":return t.command.split(" ")[0]||"command";case "prompt":return "prompt";case "http":try{return new URL(t.url).hostname}catch{return "http"}case "agent":return "agent";default:return "unknown"}}evaluateCondition(t,n){try{let o={...process.env,SESSION_ID:n?.sessionId,AGENT:n?.agent,MODEL:n?.model,CWD:n?.cwd};for(let[i,c]of Object.entries(n??{}))typeof c=="string"&&(o[i.toUpperCase()]=c);let s=t.replace(/\$\{(\w+)\}/g,(i,c)=>{let l=o[c];return typeof l=="string"?`"${l.replace(/"/g,'\\"')}"`:"undefined"});return !!new Function(`return ${s}`)()}catch(o){return rh.error("Failed to evaluate condition",{condition:t,error:o?.message}),false}}};b$1(Ls,"_instance");var Xi=Ls;var yP=a.create({service:"hook.registry"}),ih=[Ru,_u,Ou,$u,Fu,Nu,Uu,zu,Lu],Le;(m=>{let e;function t(){return e||(e=R.state(async()=>({matchers:[],executorRegistry:Yi.getInstance(),hookMatcher:Xi.getInstance()}))),e}function n(){return t()()}m.state=n;function o(){return [...ih]}m.all=o;async function s(){await n();let a=[];for(let p of ih){let u=await p.init();if(u.isEnabled){let h=u.isEnabled();if(h instanceof Promise){if(!await h)continue}else if(!h)continue}for(let h of u.handlers){let g=await r({event:h.name,scope:u.scope,hooks:[{type:"function",handler:h.handler}],hookName:p.name});a.push(g);}}return a}m.init=s;async function r(f){let a={...f,scope:f.scope,hookName:f.hookName};return (await n()).matchers.push(a),()=>{n().then(u=>{let h=u.matchers.indexOf(a);h>-1&&u.matchers.splice(h,1);});}}m.registerMatcher=r;async function i(f){try{let p=await Y.get(f);if(p.contextMode)return p.contextMode}catch{}return (await he.get()).context?.mode??g.General}async function c(f,a,p){let u=await n(),h=Date.now(),g$1={success:true,output:a,modified:false,aborted:false,details:[],errors:[],duration:0},I=p?.sessionId,T=I?await i(I):g.General,y=u.matchers.filter(w=>{if(!u.hookMatcher.match(w,f,p).matched)return false;let k=w.scope??g.All;return !(k!==g.All&&k!==T)}),x=[];for(let w of y)for(let k=0;k<w.hooks.length;k++){let v=w.hooks[k];v&&u.hookMatcher.matchHook(v,a,p)&&x.push({hook:v,hookIndex:k});}let b=a;for(let w=0;w<x.length;w++){if(p?.abort?.aborted){g$1.aborted=true,g$1.errors.push({index:w,hookName:"system",error:String(p.abort.reason??"Aborted")});break}let k=x[w];if(!k)continue;let{hook:v}=k,C={index:w,hookType:v.type,hookName:`${f}:${u.hookMatcher.getHookName(v)}`,matched:true,skipped:false,success:false,modified:false,duration:0},E=Date.now();try{let O={modified:!1,input:b},U=await u.executorRegistry.execute(v,O,p);if(p?.abort?.aborted){g$1.aborted=!0,g$1.errors.push({index:w,hookName:C.hookName,error:String(p.abort.reason??"Aborted by hook")});break}U.modified&&U.input!==void 0&&(b=U.input,C.modified=!0,g$1.modified=!0),C.success=U.success!==!1,C.output=U.output,C.duration=Date.now()-E,g$1.details.push(C);}catch(O){let U=O;if(U?.name==="AbortError"){g$1.aborted=true,g$1.errors.push({index:w,hookName:C.hookName,error:String(p?.abort?.reason??"Aborted")});break}g$1.errors.push({index:w,hookName:C.hookName,error:U?.message??String(O),stack:U?.stack}),yP.error("Hook execution error",{hook:C.hookName,error:U?.message,stack:U?.stack}),C.duration=Date.now()-E,g$1.details.push(C);}}return g$1.output=b,g$1.duration=Date.now()-h,g$1.success=g$1.errors.length===0&&!g$1.aborted,g$1}m.triggerEvent=c;async function l(){e=void 0;}m.clear=l;async function d(){return (await n()).matchers.length}m.matcherCount=d;})(Le||(Le={}));var xP=loadTextFile("./generate.txt",import.meta.url),IP=xP(),vP=loadTextFile("./prompt/compaction.txt",import.meta.url),SP=vP(),CP=loadTextFile("./prompt/explore.txt",import.meta.url),kP=CP(),PP=loadTextFile("./prompt/summary.txt",import.meta.url),TP=PP(),AP=loadTextFile("./prompt/title.txt",import.meta.url),EP=AP(),RP=loadTextFile("./prompt/btw.txt",import.meta.url),_P=RP(),MP=loadTextFile("./prompt/memory.txt",import.meta.url),OP=MP(),Ue;(d=>{d.Info=N.object({name:N.string(),description:N.string().optional(),mode:N.enum(["subagent","primary","all"]),native:N.boolean().optional(),hidden:N.boolean().optional(),topP:N.number().optional(),temperature:N.number().optional(),color:N.string().optional(),permission:N.lazy(()=>Me.Ruleset),scope:N.enum(h).optional(),model:N.object({modelId:N.string(),providerId:N.string()}).optional(),variant:N.string().optional(),prompt:N.string().optional(),options:N.record(N.string(),N.any()),steps:N.number().int().positive().optional()}).meta({ref:"Agent"});async function t(){let m=await he.get(),f=await Vt.dirs(),a=Me.fromConfig({"*":"allow",doom_loop:"ask",external_directory:{"*":"ask",[Ve.GLOB]:"allow",...Object.fromEntries(f.map(h=>[Se__default.join(h,"*"),"allow"]))},question:"deny",plan:"deny",read:{"*":"allow","*.env":"ask","*.env.*":"ask","*.env.example":"allow"}}),p=Me.fromConfig(m.permission??{}),u={build:{name:"build",description:"The default agent. Executes tools based on configured permissions.",options:{},permission:Me.merge(a,Me.fromConfig({question:"allow",plan:"allow"}),p),mode:"primary",native:true},plan:{name:"plan",description:"Plan mode. Disallows all edit tools.",options:{},permission:Me.merge(a,Me.fromConfig({question:"allow",plan_exit:"allow",external_directory:{[Se__default.join(a$1.Path.data,"plans","*")]:"allow"},edit:{"*":"deny",[Se__default.posix.join(".easbot","plans","*.md")]:"allow",[Se__default.posix.relative(R.worktree,Se__default.posix.join(a$1.Path.data,Se__default.posix.join("plans","*.md")))]:"allow"}}),p),mode:"primary",native:true},general:{name:"general",description:"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.",permission:Me.merge(a,Me.fromConfig({todo:"deny"}),p),options:{},mode:"subagent",native:true},explore:{name:"explore",permission:Me.merge(a,Me.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",codesearch:"allow",read:"allow",external_directory:{[Ve.GLOB]:"allow"}}),p),description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',prompt:kP,options:{},mode:"subagent",native:true},compaction:{name:"compaction",mode:"primary",native:true,hidden:true,prompt:SP,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),options:{}},title:{name:"title",mode:"primary",options:{},native:true,hidden:true,temperature:.5,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),prompt:EP},summary:{name:"summary",mode:"primary",options:{},native:true,hidden:true,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),prompt:TP},btw:{name:"btw",description:"Act like a professional in the relevant domain",mode:"primary",options:{},native:true,permission:Me.merge(a,Me.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",codesearch:"allow",read:"allow",question:"allow",plan:"allow",external_directory:{[Ve.GLOB]:"allow"}}),p),prompt:_P},memory:{name:"memory",mode:"primary",options:{},native:true,hidden:true,permission:Me.merge(a,Me.fromConfig({"*":"deny",memory:"allow",read:{"*":"allow","*.env":"deny","*.env.*":"deny","*.env.example":"allow"},list:"allow",glob:"allow",grep:"allow",webfetch:"allow",websearch:"allow",external_directory:{[Ve.GLOB]:"allow",...Object.fromEntries(f.map(h=>[Se__default.join(h,"*"),"allow"]))}}),p),prompt:OP}};for(let[h,g]of Object.entries(m.agent??{})){if(g.disable){delete u[h];continue}let I=u[h];if(I||(I=u[h]={name:h,mode:"all",permission:Me.merge(a,p),options:{},native:false}),g.model){let T=xe.parseModel(g.model);I.model={providerId:T.providerId,modelId:T.modelId};}I.variant=g.variant??I.variant,I.prompt=g.prompt??I.prompt,I.description=g.description??I.description,I.temperature=g.temperature??I.temperature,I.topP=g.top_p??I.topP,I.mode=g.mode??I.mode,I.color=g.color??I.color,I.hidden=g.hidden??I.hidden,I.name=g.name??I.name,I.steps=g.steps??I.steps,I.options=mergeDeep(I.options,g.options??{}),I.permission=Me.merge(I.permission,Me.fromConfig(g.permission??{}));}for(let h in u){if(!Object.hasOwn(u,h))continue;let g=u[h];!g||g.permission.some(T=>T.permission!=="external_directory"||T.action!=="deny"?false:T.pattern===Ve.GLOB)||!u[h]||(u[h].permission=Me.merge(u[h].permission,Me.fromConfig({external_directory:{[Ve.GLOB]:"allow"}})));}return u}let n;function o(){return n||(n=R.state(t)),n}function s(){return o()()}async function r(m){return (await s())[m]}d.get=r;async function i(m){let f=await he.get(),a=m??"general";return pipe(await s(),values(),sortBy([u=>f.default_agent?u.name===f.default_agent:u.name==="build","desc"])).filter(u=>{let h=u.scope??"all";return !(h!=="all"&&h!==a)})}d.list=i;async function c(){let m=await he.get(),f=await s();if(m.default_agent){let p=f[m.default_agent];if(!p)throw new Error(`default agent "${m.default_agent}" not found`);if(p.mode==="subagent")throw new Error(`default agent "${m.default_agent}" is a subagent`);if(p.hidden===true)throw new Error(`default agent "${m.default_agent}" is hidden`);return p.name}let a=Object.values(f).find(p=>p.mode!=="subagent"&&p.hidden!==true);if(!a)throw new Error("no primary visible agent found");return a.name}d.defaultAgent=c;async function l(m){let f=await he.get(),a=m.model??await xe.defaultModel(),p=await xe.getModel(a.providerId,a.modelId),u=await xe.getLanguage(p),h=[IP];await Le.triggerEvent(HookEvent.SystemTransform,{model:p});let g=await i(),I={experimental_telemetry:{isEnabled:f.experimental?.openTelemetry,metadata:{userId:f.username??"unknown"}},temperature:.3,messages:[...h.map(y=>({role:"system",content:y})),{role:"user",content:`Create an agent configuration based on this request: "${m.description}".
|
|
877
|
+
|
|
878
|
+
IMPORTANT: The following identifiers already exist and must NOT be used: ${g.map(y=>y.name).join(", ")}
|
|
879
|
+
Return ONLY the JSON object, no other text, do not wrap in backticks`}],model:u,schema:N.object({identifier:N.string(),whenToUse:N.string(),systemPrompt:N.string()})};if(a.providerId==="openai"&&(await Qe.get(a.providerId))?.type==="oauth"){let y=streamObject({...I,providerOptions:wt.providerOptions(p,{instructions:h.join(`
|
|
880
|
+
`),store:false}),onError:()=>{}});for await(let x of y.fullStream)if(x.type==="error")throw x.error;return y.object}return (await generateObject(I)).object}d.generate=l;})(Ue||(Ue={}));var zn=a.create({service:"agent-cli-api-agent"});async function ah(){try{zn.debug("Get agent list");let t=(await Ue.list()).map(n=>{let o=n.model,s;if(o&&typeof o=="string"){let{provider:r,model:i}=parseModelId(o);r&&i&&(s={providerId:r,modelId:i});}return {...n,model:s}});return zn.debug("Get agent list successful",{count:t.length}),t}catch(e){throw zn.error("Failed to get agent list",{error:e}),e}}async function nd(e){try{e=e?.trim()??await Ue.defaultAgent(),zn.debug("Get agent details",{agentName:e});let t=await Ue.get(e);return t?(zn.debug("Get agent details successful",{agentName:e}),t):(zn.warn("Agent does not exist",{agentName:e}),null)}catch(t){throw zn.error("Failed to get agent details",{agentName:e,error:t}),t}}async function NP(){try{zn.debug("Get default agent");let e=await Ue.defaultAgent(),t=await nd(e);if(!t)throw new Error(`Default agent "${e}" not found`);return zn.debug("Get default agent successful",{agentName:e}),t}catch(e){throw zn.error("Failed to get default agent",{error:e}),e}}var UP=ah;async function ch(e){try{if(zn.debug("Creating agent",{name:e.name,mode:e.mode}),!e.name||e.name.trim()==="")throw new Error("Agent name is required");let t=["subagent","primary","all"],n=e.mode||"primary";if(!t.includes(n))throw new Error(`Invalid agent mode: ${e.mode}. Valid modes are: ${t.join(", ")}`);if(await nd(e.name))throw new Error(`Agent "${e.name}" already exists`);let s={mode:n};e.description&&(s.description=e.description),e.prompt&&(s.prompt=e.prompt),e.model&&(s.model=`${e.model.providerId}/${e.model.modelId}`),e.temperature!==void 0&&(s.temperature=e.temperature),e.topP!==void 0&&(s.top_p=e.topP),e.color&&(s.color=e.color),e.hidden!==void 0&&(s.hidden=e.hidden),e.variant&&(s.variant=e.variant),e.steps!==void 0&&(s.steps=e.steps),e.permission&&(s.permission=e.permission),e.options&&(s.options=e.options);let{Config:r}=await import('./config-YSZNIWZT.mjs');await r.update({agent:{[e.name]:s}}),zn.debug("Agent created successfully",{name:e.name});let i=await nd(e.name);if(!i)throw new Error(`Failed to retrieve created agent "${e.name}"`);return i}catch(t){throw zn.error("Failed to create agent",{name:e.name,error:t}),t}}var zP=ch;var Qi={};a$7(Qi,{formatModels:()=>VP,getDefaultModel:()=>qP,listModels:()=>BP,listProviders:()=>HP,parseModel:()=>WP,refreshModels:()=>GP});async function qP(){try{let e=await xe.defaultModel();return e?`${e.providerId}/${e.modelId}`:void 0}catch{return}}async function HP(){return xe.list()}async function BP(e){let t=await xe.list();if(e){let n=t[e];if(!n)throw new Error(`Provider not found: ${e}`);return {[e]:n}}return t}async function GP(){await a$3.refresh();}function WP(e){let t=xe.parseModel(e);if(t?.providerId)return {providerId:t.providerId,modelId:t.modelId}}function VP(e,t=false){let n=[],o=Object.keys(e).sort((s,r)=>{let i=s.startsWith("opencode"),c=r.startsWith("opencode");return i&&!c?-1:!i&&c?1:s.localeCompare(r)});for(let s of o){let r=e[s];if(!r?.models)continue;let i=Object.entries(r.models).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of i)n.push(`${s}/${c}`),t&&l&&n.push(JSON.stringify(l,null,2));}return n.join(`
|
|
881
|
+
`)}var Fs={};a$7(Fs,{command:()=>tT,deleteMessage:()=>YP,deletePart:()=>QP,getMessage:()=>JP,list:()=>KP,listMessages:()=>lh,send:()=>eT,updateMessage:()=>XP,updatePart:()=>ZP});var $r=a.create({service:"agent-cli-api-message"});async function lh(e,t){$r.debug(i$1("message.history.start"),{sessionId:e});let n=await Y.messages({sessionId:e,limit:t});return $r.debug(i$1("message.history.success"),{sessionId:e,count:n.length}),n}var KP=lh;async function JP(e,t){return await ve.get({sessionId:e,messageId:t})}async function YP(e,t){return Y.removeMessage({sessionId:e,messageId:t})}async function XP(e){return Y.updateMessage(e)}async function QP(e,t,n){return Y.removePart({sessionId:e,messageId:t,partId:n})}async function ZP(e){return Y.updatePart(e)}async function eT(e){$r.debug(i$1("message.send.start"),{sessionId:e.sessionId});let t=[{type:"text",text:e.text}];if(e.files&&e.files.length>0)for(let o of e.files)t.push({type:"file",url:o.url,filename:o.filename,mime:o.mime});e.subAgent&&t.push({type:"agent",name:e.subAgent});let n=await Je.prompt({sessionId:e.sessionId,messageId:Identifier.ascending("message"),agent:e.agent,model:e.model,variant:e.variant,noReply:e.noReply,contextMode:e.contextMode,parts:t,system:e.system});return $r.debug(i$1("message.send.success"),{sessionId:e.sessionId,messageId:n.info.id}),n}async function tT(e){$r.debug(i$1("message.command.start"),{sessionId:e.sessionId,command:e.command});let t=await Je.command({sessionId:e.sessionId,messageId:e.messageId||Identifier.ascending("message"),command:e.command,arguments:e.arguments||"",agent:e.agent,model:e.model,variant:e.variant,contextMode:e.contextMode,parts:e.parts});return $r.debug(i$1("message.command.success"),{sessionId:e.sessionId,command:e.command,title:t.title}),t}a.create({service:"agent-cli-api-tool"});var vo={};a$7(vo,{getConfig:()=>oT,getConfigDirectories:()=>aT,getGlobalConfig:()=>sT,updateConfig:()=>rT,updateGlobalConfig:()=>iT,waitForConfigDependencies:()=>cT});async function oT(){return he.get()}async function sT(){return he.getGlobal()}async function rT(e){return await he.update(e),he.get()}async function iT(e){return await he.updateGlobal(e),he.getGlobal()}async function aT(){return he.directories()}async function cT(){await he.waitForDependencies();}var od={};a$7(od,{getProvider:()=>lT,listAllProviders:()=>dT,listProviders:()=>uh});var Co=a.create({service:"agent-cli-api-provider"});async function uh(){try{Co.debug("List providers");let e=await xe.list(),t=Object.values(e);return Co.debug("List providers success",{count:t.length}),t}catch(e){throw Co.error("List providers failed",{error:e}),e}}async function dT(){try{Co.debug("List all available providers");let e=await a$3.get(),t=Object.values(e).map(n=>xe.fromModelsDevProvider(n));return Co.debug("List all available providers success",{count:t.length}),t}catch(e){throw Co.error("List all available providers failed",{error:e}),e}}async function lT(e){try{Co.debug("Get provider details",{providerId:e});let n=(await uh()).find(o=>o.id===e);return n?(Co.debug("Get provider details success",{providerId:e}),n):(Co.warn("Provider not found",{providerId:e}),null)}catch(t){throw Co.error("Get provider details failed",{providerId:e,error:t}),t}}var sd={};a$7(sd,{list:()=>uT,listCommands:()=>ph});async function ph(e){return (await vn.list(e)).map(o=>({name:o.name,description:o.description,source:o.source,subtask:o.subtask,hints:o.hints??[],agent:o.agent,model:o.model,commandType:o.commandType,hidden:o.hidden??false}))}var uT=ph;var qn={};a$7(qn,{add:()=>fT,addMcpServer:()=>MT,authCallback:()=>ET,authenticate:()=>ST,clients:()=>RT,connect:()=>gT,disconnect:()=>hT,finishAuth:()=>CT,getAuthStatus:()=>AT,getMcpServerInfo:()=>jT,getPrompt:()=>xT,hasStoredTokens:()=>TT,list:()=>mT,listMcpServers:()=>_T,prompts:()=>bT,readResource:()=>IT,removeAuth:()=>kT,removeMcpServer:()=>OT,resources:()=>wT,startAuth:()=>vT,status:()=>pT,supportsOAuth:()=>PT,tools:()=>yT});async function pT(){return ze.status()}async function mT(){return ze.status()}async function fT(e,t){await ze.add(e,t);return ze.status()}async function gT(e){await ze.connect(e);return ze.status()}async function hT(e){await ze.disconnect(e);return ze.status()}async function yT(){return ze.tools()}async function bT(){return ze.prompts()}async function wT(){return ze.resources()}async function xT(e,t,n){return ze.getPrompt(e,t,n)}async function IT(e,t){return ze.readResource(e,t)}async function vT(e){return ze.startAuth(e)}async function ST(e){return ze.authenticate(e)}async function CT(e,t){return ze.finishAuth(e,t)}async function kT(e){return ze.removeAuth(e)}async function PT(e){return ze.supportsOAuth(e)}async function TT(e){return ze.hasStoredTokens(e)}async function AT(e){return ze.getAuthStatus(e)}async function ET(e,t){return ze.finishAuth(e,t)}async function RT(){return ze.clients()}async function _T(){let t=(await he.get()).mcp??{};return Object.entries(t).map(([n,o])=>({name:n,...o}))}async function MT(e){let{name:t,...n}=e;return await he.update({mcp:{[t]:n}}),{name:t,...n}}async function OT(e){await he.update({mcp:{[e]:void 0}});}async function jT(e){let n=(await he.get()).mcp?.[e];return n?{name:e,...n}:null}var rd={};a$7(rd,{getLspStatus:()=>mh,status:()=>LT});var qu=a.create({service:"agent-cli-api-lsp"});async function mh(){try{qu.debug("Get LSP status");let e=await We.status();return qu.debug("Get LSP status successful",{count:e.length}),e}catch(e){throw qu.error("Failed to get LSP status",{error:e}),e}}var LT=mh;var Fo={};a$7(Fo,{publish:()=>DT,subscribe:()=>UT,subscribeAll:()=>NT,subscribeMessage:()=>qT,subscribeSession:()=>zT});var Rn=a.create({service:"agent-cli-api-events"});async function DT(e){try{Rn.debug("Publish event",{eventType:e.type});let t=a$5.define(e.type,N.record(N.string(),N.any()));await pe.publish(t,e.properties??{});}catch(t){throw Rn.error("Publish event failed",{eventType:e.type,error:t}),t}}function fh(e){return typeof e!="object"||e===null?false:typeof e.sessionId=="string"}function $T(e){return fh(e)?typeof e.messageId=="string":false}function gh(e){if(fh(e))return e.sessionId}function FT(e){if($T(e))return e.messageId}async function NT(e){try{Rn.debug("Subscribe all events");let t=await pe.subscribeAll(e);return Rn.debug("Subscribe all events success"),t}catch(t){throw Rn.error("Subscribe all events failed",{error:t}),t}}async function UT(e,t){try{Rn.debug("Subscribe event",{eventType:e});let n=await pe.subscribeAll(o=>{o.type===e&&t(o);});return Rn.debug("Subscribe event success",{eventType:e}),n}catch(n){throw Rn.error("Subscribe event failed",{eventType:e,error:n}),n}}async function zT(e,t){try{Rn.debug("Subscribe session events",{sessionId:e});let n=await pe.subscribeAll(o=>{gh(o.properties)===e&&t(o);});return Rn.debug("Subscribe session events success",{sessionId:e}),n}catch(n){throw Rn.error("Subscribe session events failed",{sessionId:e,error:n}),n}}async function qT(e,t,n){try{Rn.debug("Subscribe message events",{sessionId:e,messageId:t});let o=await pe.subscribeAll(s=>{let r=gh(s.properties),i=FT(s.properties);r===e&&(t===void 0||i===t)&&n(s);});return Rn.debug("Subscribe message events success",{sessionId:e,messageId:t}),o}catch(o){throw Rn.error("Subscribe message events failed",{sessionId:e,messageId:t,error:o}),o}}var id={};a$7(id,{all:()=>HT});function HT(){return Vt.all()}var Zi={};a$7(Zi,{remove:()=>GT,set:()=>BT});async function BT(e,t){return Qe.set(e,t)}async function GT(e){return Qe.remove(e)}var Ns={};a$7(Ns,{current:()=>KT,initGit:()=>JT,list:()=>VT,update:()=>YT});async function VT(){return Ut.list()}async function KT(){return R.project}async function JT(e){let t=e.directory||R.directory,n=await git(["init"],{cwd:t});if(n.exitCode!==0)throw new Error(`Git init failed: ${await n.text()}`);return R.project}async function YT(e,t){return R.project}var No={};a$7(No,{connect:()=>oA,create:()=>ZT,get:()=>QT,list:()=>XT,remove:()=>tA,resize:()=>nA,update:()=>eA});async function XT(){return ot.list()}async function QT(e){return ot.get(e)}async function ZT(e){return ot.create(e)}async function eA(e,t){return ot.update(e,t)}async function tA(e){return ot.remove(e)}async function nA(e,t,n){return ot.resize(e,t,n)}async function oA(e){return ot.get(e)}var hh;(t=>{async function e(){return []}t.list=e;})(hh||(hh={}));var Fr={};a$7(Fr,{list:()=>rA,listQuestions:()=>yh,reject:()=>aA,rejectQuestion:()=>wh,reply:()=>iA,replyQuestion:()=>bh});async function yh(){return Ot.list()}async function bh(e){return await Ot.reply(e),true}async function wh(e){return await Ot.reject(e.requestId),true}var rA=yh,iA=bh,aA=wh;var Us={};a$7(Us,{list:()=>cA,read:()=>dA,search:()=>uA,status:()=>lA});async function cA(e){return bt.list(e.path)}async function dA(e){return bt.read(e.path)}async function lA(){return bt.status()}async function uA(e){return bt.search(e)}var ad={};a$7(ad,{dispose:()=>pA});async function pA(){return R.dispose()}var Nr={};a$7(Nr,{list:()=>mA,listPermissions:()=>xh,reply:()=>fA,replyPermission:()=>Ih,respond:()=>gA,respondPermission:()=>vh});async function xh(){return Me.list()}async function Ih(e){return await Me.reply(e),true}async function vh(e){return await Me.reply({requestId:e.permissionId,reply:e.response}),true}var mA=xh,fA=Ih,gA=vh;var cd={};a$7(cd,{getContext:()=>hA,getProtocolMetadata:()=>yA});async function hA(){return mo.getContext()}async function yA(){return mo.getProtocolMetadata()}function ea(){let e=null,t=false,n=[];return {stream:{[Symbol.asyncIterator](){return {next(){return t?Promise.resolve({value:void 0,done:true}):n.length>0?Promise.resolve({value:n.shift(),done:false}):new Promise(i=>{e=i;})}}}},push:i=>{t||(e?(e({value:i,done:false}),e=null):n.push(i));},close:()=>{t=true,e&&(e({value:void 0,done:true}),e=null);}}}function Sh(e){let t={directory:e.directory};return {config:{get:async(n,o)=>({data:await Pe(()=>vo.getConfig(),"CONFIG_GET_ERROR",t)}),providers:async(n,o)=>({data:{providers:await Pe(()=>od.listProviders(),"CONFIG_PROVIDERS_ERROR",t)}})},model:{default:async(n,o)=>{let s=await Pe(()=>Qi.getDefaultModel(),"MODEL_DEFAULT_ERROR",t);if(!s)return {data:void 0};let{provider:r,model:i}=parseModelId(s);return {data:{providerId:r,modelId:i}}},parse:async(n,o)=>({data:await Pe(()=>Promise.resolve(Qi.parseModel(n.model)),"MODEL_PARSE_ERROR",t)})},command:{list:async(n,o)=>({data:await Pe(()=>sd.listCommands(n.contextMode),"COMMAND_LIST_ERROR",t)})},permission:{list:async(n,o)=>({data:await Pe(()=>Nr.listPermissions(),"PERMISSION_LIST_ERROR",t)}),respond:async(n,o)=>(await Pe(()=>Nr.respondPermission({sessionId:n.sessionId,permissionId:n.permissionId,response:n.response}),"PERMISSION_RESPOND_ERROR",t),{data:true}),reply:async(n,o)=>(await Pe(()=>Nr.replyPermission({requestId:n.requestId,reply:n.reply,message:n.message}),"PERMISSION_REPLY_ERROR",t),{data:true})},question:{list:async(n,o)=>({data:await Pe(()=>Fr.listQuestions(),"QUESTION_LIST_ERROR",t)}),reply:async(n,o)=>(await Pe(()=>Fr.replyQuestion({requestId:n.requestId,answers:n.answers}),"QUESTION_REPLY_ERROR",t),{data:true}),reject:async(n,o)=>(await Pe(()=>Fr.rejectQuestion({requestId:n.requestId}),"QUESTION_REJECT_ERROR",t),{data:true})},session:{create:async(n,o)=>({data:await Pe(()=>tn.createSession({title:n?.title,directory:n?.directory??t.directory}),"SESSION_CREATE_ERROR",t)}),get:async(n,o)=>({data:await Pe(()=>tn.getSession(n.sessionId),"SESSION_GET_ERROR",t)}),list:async(n,o)=>({data:await Pe(()=>tn.listSessions({limit:n?.limit,directory:n?.directory??t.directory}),"SESSION_LIST_ERROR",t)}),fork:async(n,o)=>{let s=n?.directory??t.directory;return {data:await Pe(()=>tn.forkSession(n.sessionId,n.messageId,s),"SESSION_FORK_ERROR",t)}},delete:async(n,o)=>(await Pe(()=>tn.deleteSession(n.sessionId),"SESSION_DELETE_ERROR",t),{data:true}),abort:async(n,o)=>(await Pe(()=>tn.abortSession(n.sessionId),"SESSION_ABORT_ERROR",t),{data:true}),summarize:async(n,o)=>({data:await Pe(()=>tn.summarizeSession({sessionId:n.sessionId,providerId:n.providerId,modelId:n.modelId,auto:n.auto}),"SESSION_SUMMARIZE_ERROR",t)}),contextMode:{get:async(n,o)=>({data:await Pe(()=>tn.getSessionContextMode(n.sessionId),"SESSION_CONTEXT_MODE_ERROR",t)}),set:async(n,o)=>(await Pe(()=>tn.setSessionContextMode(n.sessionId,n.mode),"SESSION_CONTEXT_MODE_ERROR",t),{data:n.mode})},messages:async(n,o)=>({data:await Pe(()=>Fs.listMessages(n.sessionId,n.limit),"SESSION_MESSAGES_ERROR",t)}),message:async(n,o)=>({data:await Pe(()=>Fs.getMessage(n.sessionId,n.messageId),"SESSION_MESSAGE_ERROR",t)}),prompt:async(n,o)=>{let s=(n.parts??[]).filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
882
|
+
`),r=(n.parts??[]).filter(l=>l.type==="file").map(l=>({url:l.url,filename:l.filename,mime:l.mime})),i=(n.parts??[]).find(l=>l.type==="agent")?.name;return {data:await Pe(()=>Fs.send({sessionId:n.sessionId,text:s,agent:n.agent,subAgent:i,model:n.model,variant:n.variant,files:r.length>0?r:void 0,noReply:n.noReply,contextMode:n.contextMode,system:n.system}),"SESSION_PROMPT_ERROR",t)}},command:async(n,o)=>({data:await Pe(()=>Fs.command({sessionId:n.sessionId,command:n.command,arguments:n.arguments,agent:n.agent,model:n.model,variant:n.variant,messageId:n.messageId,contextMode:n.contextMode,parts:n.parts}),"SESSION_COMMAND_ERROR",t)}),event:async(n,o)=>{let{stream:s,push:r,close:i}=ea(),c;try{c=await Pe(()=>Fo.subscribeSession(n.sessionId,d=>{r({sessionId:n.sessionId,payload:d});}),"SESSION_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},update:async(n,o)=>({data:await Pe(()=>tn.updateSession(n.sessionId,n),"SESSION_UPDATE_ERROR",t)}),children:async(n,o)=>({data:await Pe(()=>tn.getSessionChildren(n.sessionId),"SESSION_CHILDREN_ERROR",t)}),init:async(n,o)=>({data:await Pe(()=>tn.initSession(n),"SESSION_INIT_ERROR",t)}),status:async(n,o)=>({data:await Pe(()=>tn.listSessionStatuses(),"SESSION_STATUS_ERROR",t)})},message:{event:async(n,o)=>{let{stream:s,push:r,close:i}=ea(),c;try{c=await Pe(()=>Fo.subscribeMessage(n.sessionId,n.messageId,d=>{r({sessionId:n.sessionId,messageId:n.messageId,payload:d});}),"MESSAGE_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},event:{subscribe:async(n,o)=>{let{stream:s,push:r,close:i}=ea(),c;try{c=await Pe(()=>Fo.subscribeAll(d=>{r({payload:d});}),"EVENT_SUBSCRIBE_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},publish:async(n,o)=>(await Pe(()=>Fo.publish(n),"EVENT_PUBLISH_ERROR",t),{data:true})},agent:{list:async(n,o)=>({data:await Pe(()=>ds.listAgents(),"AGENT_LIST_ERROR",t)}),get:async(n,o)=>({data:await Pe(()=>ds.getAgent(n.agentId),"AGENT_GET_ERROR",t)}),default:async(n,o)=>({data:await Pe(()=>ds.getDefaultAgent(),"AGENT_DEFAULT_ERROR",t)}),create:async(n,o)=>({data:await Pe(()=>ds.createAgent({name:n.name,mode:n.mode,permission:n.permission}),"AGENT_CREATE_ERROR",t)}),event:async(n,o)=>{let{stream:s,push:r,close:i}=ea(),c;try{c=await Pe(()=>Fo.subscribeAll(d=>{d.properties?.agentId===n.agentId&&r({agentId:n.agentId,payload:d});}),"AGENT_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},global:{event:async(n,o)=>{let{stream:s,push:r,close:i}=ea(),c;try{c=await Pe(()=>Fo.subscribeAll(d=>{r({payload:d});}),"GLOBAL_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},config:{get:async(n,o)=>({data:await Pe(()=>vo.getGlobalConfig(),"CONFIG_GET_ERROR",t)}),update:async(n,o)=>({data:await Pe(()=>vo.updateGlobalConfig(n),"CONFIG_UPDATE_ERROR",t)})},dispose:async(n,o)=>(await Pe(()=>ad.dispose(),"GLOBAL_DISPOSE_ERROR",t),{data:true})},app:{agents:async(n,o)=>({data:await Pe(()=>ds.listAgents(),"APP_AGENTS_ERROR",t)}),skills:async(n,o)=>({data:(await Pe(()=>id.all(),"APP_SKILLS_ERROR",t)).map(r=>({name:r.name,description:r.description??"",location:r.location}))}),log:async(n,o)=>({data:[]}),context:async(n,o)=>({data:await Pe(()=>cd.getContext(),"APP_CONTEXT_ERROR",t)})},auth:{set:async(n,o)=>(await Pe(()=>Zi.set(n.providerId,n.info),"AUTH_SET_ERROR",t),{data:true}),remove:async(n,o)=>(await Pe(()=>Zi.remove(n.providerId),"AUTH_REMOVE_ERROR",t),{data:true})},project:{list:async(n,o)=>({data:await Pe(()=>Ns.list(),"PROJECT_LIST_ERROR",t)}),current:async(n,o)=>({data:await Pe(()=>Ns.current(),"PROJECT_CURRENT_ERROR",t)}),initGit:async(n,o)=>({data:await Pe(()=>Ns.initGit(n),"PROJECT_INIT_GIT_ERROR",t)}),update:async(n,o)=>({data:await Pe(()=>Ns.update(n.providerId,n),"PROJECT_UPDATE_ERROR",t)})},pty:{list:async(n,o)=>({data:await Pe(()=>No.list(),"PTY_LIST_ERROR",t)}),get:async(n,o)=>({data:await Pe(()=>No.get(n.id),"PTY_GET_ERROR",t)}),create:async(n,o)=>({data:await Pe(()=>No.create(n),"PTY_CREATE_ERROR",t)}),update:async(n,o)=>({data:await Pe(()=>No.update(n.id,n),"PTY_UPDATE_ERROR",t)}),remove:async(n,o)=>(await Pe(()=>No.remove(n.id),"PTY_REMOVE_ERROR",t),{data:true}),connect:async(n,o)=>({data:await Pe(()=>No.connect(n.id),"PTY_CONNECT_ERROR",t)})},file:{list:async(n,o)=>({data:await Pe(()=>Us.list({directory:n?.directory,path:n?.path}),"FILE_LIST_ERROR",t)}),read:async(n,o)=>({data:await Pe(()=>Us.read({directory:n?.directory,path:n?.path}),"FILE_READ_ERROR",t)}),status:async(n,o)=>({data:await Pe(()=>Us.status(),"FILE_STATUS_ERROR",t)}),search:async(n,o)=>({data:await Pe(()=>Us.search(n),"FILE_SEARCH_ERROR",t)})},mcp:{status:async(n,o)=>({data:await Pe(()=>qn.status(),"MCP_STATUS_ERROR",t)}),add:async(n,o)=>{let{name:s,config:r}=n;return {data:await Pe(()=>qn.add(s,r),"MCP_ADD_ERROR",t)}},connect:async(n,o)=>{let{name:s}=n;return {data:await Pe(()=>qn.connect(s),"MCP_CONNECT_ERROR",t)}},disconnect:async(n,o)=>{let{name:s}=n;return {data:await Pe(()=>qn.disconnect(s),"MCP_DISCONNECT_ERROR",t)}},tools:async(n,o)=>{let s=await Pe(()=>qn.tools(),"MCP_TOOLS_ERROR",t),r={};for(let i of Object.keys(s)){let c=i.split("_"),l=c[0];if(!l)continue;let d=c.slice(1).join("_");r[l]||(r[l]=[]),r[l].push(d);}return {data:r}},auth:{start:async(n,o)=>{let{name:s}=n;return {data:await Pe(()=>qn.startAuth(s),"MCP_AUTH_START_ERROR",t)}},authenticate:async(n,o)=>{let{name:s}=n;return {data:await Pe(()=>qn.authenticate(s),"MCP_AUTH_AUTHENTICATE_ERROR",t)}},finish:async(n,o)=>{let{name:s,authorizationCode:r}=n;return {data:await Pe(()=>qn.finishAuth(s,r),"MCP_AUTH_FINISH_ERROR",t)}},callback:async(n,o)=>{let{name:s,callbackUrl:r}=n;return {data:await Pe(()=>qn.authCallback(s,r),"MCP_AUTH_CALLBACK_ERROR",t)}},remove:async(n,o)=>{let{name:s}=n;return await Pe(()=>qn.removeAuth(s),"MCP_AUTH_REMOVE_ERROR",t),{data:true}}}},lsp:{status:async(n,o)=>({data:await Pe(()=>rd.getLspStatus(),"LSP_STATUS_ERROR",t)})}}}async function bA(){let{Server:e}=await import('./server-ITUF2HX7.mjs');return e.openapi()}var Ne=a.create({service:"cli-tui-state"});async function vA(e,t,n){let o=t.options,s=m=>{if(!m)return SessionTitle.createDefault(false);let f=m.trim();return f.slice(0,50)+(f.length>50?"...":"")};if(o?.new){let m=s(o.prompt),{data:f}=await e.session.create({title:m,directory:R.directory,contextMode:n.contextMode});return Ne.debug("New session created via --new",{sessionId:f?.id,contextMode:n.contextMode}),f?.id??null}let{data:r}=await e.session.list({limit:1}),i=r?.find(m=>!m.parentId)?.id,c=t.sessionId||n.sessionId||i;if(c&&o?.fork){let{data:m}=await e.session.fork({sessionId:c,contextMode:n.contextMode});return Ne.debug("Session forked",{baseID:c,forkedID:m?.id,contextMode:n.contextMode}),m?.id??null}if(c)return Ne.debug("Using existing session",{sessionId:c}),c;let l=s(o?.prompt),{data:d}=await e.session.create({title:l,directory:R.directory,contextMode:n.contextMode});return Ne.debug("New session created (fallback)",{sessionId:d?.id,contextMode:n.contextMode}),d?.id??null}async function SA(e={}){Ne.debug("Creating TUI state",{options:e});let t={directory:R.directory,projectId:R.project.id},n={toolsExpanded:true,showThinking:true,thinkingLevel:"low",verboseLevel:"off",messageLimit:50,localShellPermission:"ask",contextMode:void 0,model:void 0,agent:void 0,sessionId:void 0},o=e.sessionId||e.options?.sessionId;if(o)try{n=await a$b(o),Ne.debug("Loaded TUI state from session",{sessionId:o,persistedState:n});}catch{Ne.debug("No persisted state found for session",{sessionId:o});}let s=Sh({directory:t.directory}),r=await vA(s,{...e,sessionId:o},n),i=r||"new";if(r)try{let m=(await s.session.get({sessionId:r})).data;m?.title&&(i=m.title);}catch(d){Ne.debug("Failed to load session title",{sessionId:r,error:d});}if(r&&r!==o)try{n=await a$b(r),Ne.debug("Loaded TUI state from resolved session",{sessionId:r,persistedState:n});}catch{Ne.debug("No persisted state found for resolved session",{sessionId:r});}let c=e.model||n.model;if(!c)try{let d=await s.model.default({});d.data&&(c=`${d.data.providerId}/${d.data.modelId}`,Ne.debug("Got default model from backend",{model:c}));}catch(d){Ne.warn("Failed to get default model",{error:d});}let l=e.agent||n.agent;if(!l)try{let f=((await s.app.agents({})).data||[]).filter(a=>a.mode!=="subagent");f.length>0?(l=f[0].name,Ne.debug("Got default agent from backend",{agent:l})):(l="",Ne.warn("No agents available"));}catch(d){l="",Ne.warn("Failed to get default agent",{error:d});}return r||Ne.warn("No session ID provided, TUI may not function correctly"),Ne.debug("TUI state resolved",{agent:{provided:e.agent,persisted:n.agent,final:l},model:{provided:e.model,persisted:n.model,final:c},sessionId:{provided:e.sessionId,persisted:n.sessionId,final:r},contextMode:n.contextMode}),{agent:l,currentSessionKey:i,currentSessionId:r,activeChatRunId:null,historyLoaded:false,toolsExpanded:n.toolsExpanded,showThinking:n.showThinking,thinkingLevel:n.thinkingLevel,verboseLevel:n.verboseLevel,messageLimit:n.messageLimit,localShellPermission:n.localShellPermission,contextMode:n.contextMode,pendingShellCommand:null,sessionInfo:{model:c,modelProvider:void 0,totalTokens:null,contextTokens:null},pendingPermission:null,pendingQuestion:null,questionDisplayTimer:null,instanceContext:t,sdk:s}}var Bu;function CA(){if(!Bu){let e=R.state(()=>new Map,async t=>{Ne.debug("Disposing TUI state",{count:t.size}),t.clear();});Bu=async t=>{let n=e(),o=JSON.stringify(t);if(!n.has(o)){let s=await SA(t);n.set(o,s);}return n.get(o)};}return Bu}async function Gu(e={}){return CA()(e)}async function TX(e,t,n,o){Ne.debug("Initializing TUI state with health check and event subscription");let s=await Gu(e);if(s.currentSessionId&&!s.contextMode)try{let c=await s.sdk.session.contextMode.get({sessionId:s.currentSessionId});c.data&&(s.contextMode=c.data,Ne.debug("Got contextMode from session API",{sessionId:s.currentSessionId,contextMode:s.contextMode}));}catch(c){Ne.debug("Failed to get contextMode from session API",{sessionId:s.currentSessionId,error:c});}s.currentSessionId?(Ne.debug("Saving initial TUI state to storage",{sessionId:s.currentSessionId}),await b$4(s)):Ne.warn("No session ID, skipping initial state save"),await kA(s,n),Ne.debug("Running TUI state health check");let r=await Th(s);if(r.healthy)Ne.debug("TUI state health check passed");else {Ne.warn("TUI state health check failed",{report:r}),Ne.debug("Attempting to auto-heal TUI state");let c=await TA(s);c.success?(Ne.debug("TUI state auto-heal successful",{report:c}),n.addSystem(i$1("tui.state.healed")),await b$4(s)):(Ne.error("TUI state auto-heal failed",{report:c}),n.addSystem(i$1("tui.state.heal_failed")));}Ne.debug("Subscribing to backend state events");let i=await PA(s,t,n,o);return Ne.debug("Backend state events subscribed"),{state:s,unsubscribe:i}}async function kA(e,t){Ne.debug("Validating local preferences",{localModel:e.sessionInfo.model,localAgent:e.agent,sessionId:e.currentSessionId});try{let n=[];if(e.sessionInfo.model)try{let o=await e.sdk.model.parse({model:e.sessionInfo.model});o.data&&(((await e.sdk.config.providers({})).data?.providers||[]).find(l=>l.id===o.data.providerId)?.models?.[o.data.modelId]?(n.push(`model: ${e.sessionInfo.model}`),Ne.debug("Model validated successfully",{model:e.sessionInfo.model})):(Ne.warn("Local model does not exist",{model:e.sessionInfo.model,providerId:o.data.providerId,modelId:o.data.modelId}),t.addSystem(i$1("tui.state.model_not_found",{vars:{model:e.sessionInfo.model}})),e.sessionInfo.model=void 0));}catch(o){Ne.error("Failed to validate model",{model:e.sessionInfo.model,error:o});}if(e.agent)try{((await e.sdk.app.agents({})).data||[]).find(i=>i.name===e.agent)?(n.push(`agent: ${e.agent}`),Ne.debug("Agent validated successfully",{agent:e.agent})):(Ne.warn("Local agent does not exist",{agent:e.agent}),t.addSystem(i$1("tui.state.agent_not_found",{vars:{agent:e.agent}})),e.agent="");}catch(o){Ne.error("Failed to validate agent",{agent:e.agent,error:o});}n.length>0&&(Ne.debug("Local preferences validated",{validationResults:n}),t.addSystem(i$1("tui.state.preferences_validated",{vars:{items:n.join(", ")}}))),Ne.debug("Local preferences validation completed");}catch(n){Ne.error("Failed to validate local preferences",{error:n});}}async function Ch(e,t){return R.provide({directory:e.instanceContext.directory,init:void 0,fn:t})}async function fo(e,t,n){await Ch(e,async()=>{await pe.publish(t,n);});}async function dd(e,t,n){let o=()=>{};return await Ch(e,async()=>{o=pe.subscribe(t,n),await pe.waitForSubscription();}),o}async function AX(e,t){await e.sdk.permission.reply({requestId:t.requestId,reply:t.reply});}async function EX(e,t){await e.sdk.question.reply({requestId:t.requestId,answers:t.answers});}var eo={async appendPrompt(e,t){await fo(e,c$2.PromptAppend,t);},async openHelp(e){await fo(e,c$2.CommandExecute,{command:"help.show"});},async openSessions(e){await fo(e,c$2.CommandExecute,{command:"session.list"});},async openThemes(e){await fo(e,c$2.CommandExecute,{command:"session.list"});},async openModels(e){await fo(e,c$2.CommandExecute,{command:"model.list"});},async submitPrompt(e){await fo(e,c$2.CommandExecute,{command:"prompt.submit"});},async clearPrompt(e){await fo(e,c$2.CommandExecute,{command:"prompt.clear"});},async executeCommand(e,t){let n={session_new:"session.new",session_share:"session.share",session_interrupt:"session.interrupt",session_compact:"session.compact",messages_page_up:"session.page.up",messages_page_down:"session.page.down",messages_line_up:"session.line.up",messages_line_down:"session.line.down",messages_half_page_up:"session.half.page.up",messages_half_page_down:"session.half.page.down",messages_first:"session.first",messages_last:"session.last",agent_cycle:"agent.cycle"};await fo(e,c$2.CommandExecute,{command:n[t.command]||t.command});},async showToast(e,t){await fo(e,c$2.ToastShow,t);},async selectSession(e,t){await fo(e,c$2.SessionSelect,t);},async publish(e,t){let n=Object.values(c$2).find(o=>o.type===t.type);n&&await fo(e,n,t.properties);}};async function kh(e){return (await e.sdk.app.agents({})).data||[]}async function RX(e){return (await e.sdk.session.list({limit:50})).data||[]}async function Ph(e){let n=(await e.sdk.config.providers({})).data?.providers||[];return Object.fromEntries(n.filter(o=>typeof o.id=="string"&&o.id.length>0).map(o=>[o.id,{name:o.name,models:o.models}]))}async function PA(e,t,n,o){let s=[];Ne.debug("Subscribing to backend events");let r=await dd(e,Y.Event.Created,async d=>{Ne.debug("Session created",{sessionId:d.properties.info.id}),n.addSystem(i$1("tui.state.session.created",{vars:{title:d.properties.info.title||d.properties.info.id}}));});s.push(r);let i=await dd(e,Y.Event.Updated,async d=>{Ne.debug("Session updated",{sessionId:d.properties.info.id}),e.currentSessionId===d.properties.info.id&&o();});s.push(i);let c=await dd(e,Y.Event.Deleted,async d=>{let m=d.properties.info.id,f=d.properties.info.title||m;Ne.debug("Session deleted",{sessionId:m,sessionTitle:f}),n.addSystem(i$1("tui.state.session.deleted",{vars:{title:f}})),e.currentSessionId===m&&(e.currentSessionId=null,e.currentSessionKey="new",o());});s.push(c);let l=await dd(e,ze.ToolsChanged,async d=>{Ne.debug("MCP tools changed",{server:d.properties.server});});return s.push(l),Ne.debug("Backend events subscribed",{count:s.length}),()=>{Ne.debug("Unsubscribing from backend events");for(let d of s)d();}}async function Th(e){let t={checks:[],healthy:true};Ne.debug("Running TUI state diagnostics");try{await(await import('fs/promises')).access(e.instanceContext.directory),t.checks.push({name:"Instance Context",status:"pass",message:`Directory exists: ${e.instanceContext.directory}`});}catch{t.healthy=false,t.checks.push({name:"Instance Context",status:"fail",message:`Directory not accessible: ${e.instanceContext.directory}`,suggestion:"Reinitialize Instance context"});}try{let n=await kh(e);Ne.debug("Agent list retrieved for health check",{agent:e.agent,availableAgents:n.map(s=>s.name),agentCount:n.length}),n.find(s=>s.name===e.agent)?t.checks.push({name:"Current Agent",status:"pass",message:`Agent exists: ${e.agent}`}):(t.healthy=!1,t.checks.push({name:"Current Agent",status:"fail",message:`Agent not found: ${e.agent}`,suggestion:"Switch to default agent or first available agent"}),Ne.warn("Current agent not found in available agents",{agent:e.agent,availableAgents:n.map(s=>s.name)}));}catch(n){t.healthy=false,t.checks.push({name:"Current Agent",status:"fail",message:`Failed to check agent: ${String(n)}`,suggestion:"Check Instance context and API layer"});}if(e.currentSessionId)try{(await e.sdk.session.get({sessionId:e.currentSessionId})).data?t.checks.push({name:"Current Session",status:"pass",message:`Session exists: ${e.currentSessionId}`}):(t.healthy=!1,t.checks.push({name:"Current Session",status:"fail",message:`Session not found: ${e.currentSessionId}`,suggestion:"Clear invalid session ID or create new session"}));}catch(n){t.healthy=false,t.checks.push({name:"Current Session",status:"fail",message:`Failed to check session: ${String(n)}`,suggestion:"Clear invalid session ID"});}if(e.sessionInfo.model)try{let n=await Ph(e),{provider:o,model:s}=parseModelId(e.sessionInfo.model);n[o]?.models?.[s]?t.checks.push({name:"Current Model",status:"pass",message:`Model exists: ${e.sessionInfo.model}`}):(t.healthy=!1,t.checks.push({name:"Current Model",status:"fail",message:`Model not found: ${e.sessionInfo.model}`,suggestion:"Switch to default model or first available model"}));}catch(n){t.healthy=false,t.checks.push({name:"Current Model",status:"fail",message:`Failed to check model: ${String(n)}`,suggestion:"Check Instance context and API layer"});}return Ne.debug("TUI state diagnostics completed",{healthy:t.healthy,checks:t.checks.length}),t}async function TA(e){let t={actions:[],success:true};Ne.debug("Running TUI state auto-heal");let n=await Th(e);for(let o of n.checks)if(o.status==="fail")try{switch(o.name){case "Current Agent":{let s=await kh(e);s.length>0?(e.agent=s[0].name,t.actions.push({name:"Fix Current Agent",status:"success",message:`Switched to agent: ${e.agent} (temporary, not saved)`})):(t.success=!1,t.actions.push({name:"Fix Current Agent",status:"fail",message:"No agents available"}));break}case "Current Session":{e.currentSessionId=null,e.currentSessionKey="new",t.actions.push({name:"Fix Current Session",status:"success",message:"Cleared invalid session ID"});break}case "Current Model":{let s=await Ph(e),r=Object.keys(s);if(r.length>0){let i=r[0],c=s[i];if(c?.models){let l=Object.keys(c.models);if(l.length>0){let d=l[0];e.sessionInfo.model=`${i}/${d}`,t.actions.push({name:"Fix Current Model",status:"success",message:`Switched to model: ${e.sessionInfo.model}`});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No models available in provider"});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No models available"});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No providers available"});break}}}catch(s){t.success=false,t.actions.push({name:`Fix ${o.name}`,status:"fail",message:`Failed to fix: ${String(s)}`});}return Ne.debug("TUI state auto-heal completed",{success:t.success,actions:t.actions.length}),t}var AA={400:{description:"Bad request",content:{"application/json":{schema:resolver(N.object({data:N.any(),errors:N.array(N.record(N.string(),N.any())),success:N.literal(false)}).meta({ref:"BadRequestError"}))}}},404:{description:"Not found",content:{"application/json":{schema:resolver(a$6.NotFoundError.Schema)}}}};function Te(...e){return Object.fromEntries(e.map(t=>[t,AA[t]]))}var go=()=>Gu(),RA=N.object({path:N.string(),body:N.any()}),_A=new AsyncQueue,MA=new AsyncQueue;var OA=new Hono().get("/next",describeRoute({summary:"Get next TUI request",description:"Retrieve the next TUI (Terminal User Interface) request from the queue for processing.",operationId:"tui.control.next",responses:{200:{description:"Next TUI request",content:{"application/json":{schema:resolver(RA)}}}}}),async e=>{let t=await _A.next();return e.json(t)}).post("/response",describeRoute({summary:"Submit TUI response",description:"Submit a response to the TUI request queue to complete a pending request.",operationId:"tui.control.response",responses:{200:{description:"Response submitted successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),validator("json",N.any()),async e=>{let t=e.req.valid("json");return MA.push(t),e.json(true)}),_h=lazy(()=>new Hono().post("/append-prompt",describeRoute({summary:"Append TUI prompt",description:"Append prompt to the TUI",operationId:"tui.appendPrompt",responses:{200:{description:"Prompt processed successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",b$2.PromptAppend.properties),async e=>{let t=await go();return await eo.appendPrompt(t,e.req.valid("json")),e.json(true)}).post("/open-help",describeRoute({summary:"Open help dialog",description:"Open the help dialog in the TUI to display user assistance information.",operationId:"tui.openHelp",responses:{200:{description:"Help dialog opened successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.openHelp(t),e.json(true)}).post("/open-sessions",describeRoute({summary:"Open sessions dialog",description:"Open the session dialog",operationId:"tui.openSessions",responses:{200:{description:"Session dialog opened successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.openSessions(t),e.json(true)}).post("/open-themes",describeRoute({summary:"Open themes dialog",description:"Open the theme dialog",operationId:"tui.openThemes",responses:{200:{description:"Theme dialog opened successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.openThemes(t),e.json(true)}).post("/open-models",describeRoute({summary:"Open models dialog",description:"Open the model dialog",operationId:"tui.openModels",responses:{200:{description:"Model dialog opened successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.openModels(t),e.json(true)}).post("/submit-prompt",describeRoute({summary:"Submit TUI prompt",description:"Submit the prompt",operationId:"tui.submitPrompt",responses:{200:{description:"Prompt submitted successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.submitPrompt(t),e.json(true)}).post("/clear-prompt",describeRoute({summary:"Clear TUI prompt",description:"Clear the prompt",operationId:"tui.clearPrompt",responses:{200:{description:"Prompt cleared successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>{let t=await go();return await eo.clearPrompt(t),e.json(true)}).post("/execute-command",describeRoute({summary:"Execute TUI command",description:"Execute a TUI command (e.g. agent_cycle)",operationId:"tui.executeCommand",responses:{200:{description:"Command executed successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",N.object({command:N.string()})),async e=>{let t=await go();return await eo.executeCommand(t,e.req.valid("json")),e.json(true)}).post("/show-toast",describeRoute({summary:"Show TUI toast",description:"Show a toast notification in the TUI",operationId:"tui.showToast",responses:{200:{description:"Toast notification shown successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),validator("json",b$2.ToastShow.properties),async e=>{let t=await go();return await eo.showToast(t,e.req.valid("json")),e.json(true)}).post("/publish",describeRoute({summary:"Publish TUI event",description:"Publish a TUI event",operationId:"tui.publish",responses:{200:{description:"Event published successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",N.union(Object.values(b$2).map(e=>N.object({type:N.literal(e.type),properties:e.properties}).meta({ref:"Event."+e.type})))),async e=>{let t=await go();return await eo.publish(t,e.req.valid("json")),e.json(true)}).post("/select-session",describeRoute({summary:"Select session",description:"Navigate the TUI to display the specified session.",operationId:"tui.selectSession",responses:{200:{description:"Session selected successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("json",b$2.SessionSelect.properties),async e=>{let t=await go();return await eo.selectSession(t,e.req.valid("json")),e.json(true)}).route("/control",OA));var Mh=a.create({service:"vcs"}),qs;(l=>{l.Event={BranchUpdated:a$5.define("vcs.branch.updated",N.object({branch:N.string().optional()}))},l.Info=N.object({branch:N.string()}).meta({ref:"VcsInfo"});async function n(){return $`git rev-parse --abbrev-ref HEAD`.quiet().nothrow().cwd(R.worktree).text().then(d=>d.trim()).catch(()=>{})}let o;function s(){return o||(o=R.state(async()=>{if(R.project.vcs!=="git")return {branch:async()=>{},unsubscribe:void 0};let d=await n();Mh.info("initialized",{branch:d});let m=pe.subscribe(Fn.Event.Updated,async f=>{if(f.properties.file.endsWith("HEAD"))return;let a=await n();a!==d&&(Mh.info("branch changed",{from:d,to:a}),d=a,await pe.publish(l.Event.BranchUpdated,{branch:a}));});return {branch:async()=>d,unsubscribe:m}},async d=>{d.unsubscribe?.();})),o}function r(){return s()()}async function i(){return r()}l.init=i;async function c(){return await r().then(d=>d.branch())}l.branch=c;})(qs||(qs={}));var Lh=lazy(()=>new Hono().get("/",describeRoute({summary:"List all projects",description:"Get a list of projects that have been opened with EasBot.",operationId:"project.list",responses:{200:{description:"List of projects",content:{"application/json":{schema:resolver(Ut.Info.array())}}}}}),async e=>{let t=await Ut.list();return e.json(t)}).get("/current",describeRoute({summary:"Get current project",description:"Retrieve the currently active project that EasBot is working with.",operationId:"project.current",responses:{200:{description:"Current project information",content:{"application/json":{schema:resolver(Ut.Info)}}}}}),async e=>e.json(R.project)).patch("/:providerId",describeRoute({summary:"Update project",description:"Update project properties such as name, icon, and commands.",operationId:"project.update",responses:{200:{description:"Updated project information",content:{"application/json":{schema:resolver(Ut.Info)}}},...Te(400,404)}}),validator("param",N.object({providerId:N.string()})),validator("json",Ut.update.schema.omit({providerId:true})),async e=>{let t=e.req.valid("param").providerId,n=e.req.valid("json"),o=await Ut.update({...n,providerId:t});return e.json(o)}));var zr=a.create({service:"server"}),Fh=lazy(()=>new Hono().get("/",describeRoute({summary:"List sessions",description:"Get a list of all EasBot sessions, sorted by most recently updated.",operationId:"session.list",responses:{200:{description:"List of sessions",content:{"application/json":{schema:resolver(Y.Info.array())}}}}}),validator("query",N.object({directory:N.string().optional().meta({description:"Filter sessions by project directory"}),roots:N.coerce.boolean().optional().meta({description:"Only return root sessions (no parentId)"}),start:N.coerce.number().optional().meta({description:"Filter sessions updated on or after this timestamp (milliseconds since epoch)"}),search:N.string().optional().meta({description:"Filter sessions by title (case-insensitive)"}),limit:N.coerce.number().optional().meta({description:"Maximum number of sessions to return"})})),async e=>{let t=e.req.valid("query"),n=t.search?.toLowerCase(),o=[];for await(let s of Y.list())if(!(t.directory!==void 0&&s.directory!==t.directory)&&!(t.roots&&s.parentId)&&!(t.start!==void 0&&s.time.updated<t.start)&&!(n!==void 0&&!s.title.toLowerCase().includes(n))&&(o.push(s),t.limit!==void 0&&o.length>=t.limit))break;return e.json(o)}).get("/status",describeRoute({summary:"Get session status",description:"Retrieve the current status of all sessions, including active, idle, and completed states.",operationId:"session.status",responses:{200:{description:"Get session status",content:{"application/json":{schema:resolver(N.record(N.string(),Mt.Info))}}},...Te(400)}}),async e=>{let t=Mt.list();return e.json(t)}).get("/:sessionId",describeRoute({summary:"Get session",description:"Retrieve detailed information about a specific EasBot session.",tags:["Session"],operationId:"session.get",responses:{200:{description:"Get session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:Y.get.schema})),async e=>{let t=e.req.valid("param").sessionId;zr.debug("SEARCH",{url:e.req.url});let n=await Y.get(t);return e.json(n)}).get("/:sessionId/children",describeRoute({summary:"Get session children",tags:["Session"],description:"Retrieve all child sessions that were forked from the specified parent session.",operationId:"session.children",responses:{200:{description:"List of children",content:{"application/json":{schema:resolver(Y.Info.array())}}},...Te(400,404)}}),validator("param",N.object({sessionId:Y.children.schema})),async e=>{let t=e.req.valid("param").sessionId,n=await Y.children(t);return e.json(n)}).get("/:sessionId/todo",describeRoute({summary:"Get session todos",description:"Retrieve the todo list associated with a specific session, showing tasks and action items.",operationId:"session.todo",responses:{200:{description:"Todo list",content:{"application/json":{schema:resolver(lo.Info.array())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,n=await lo.get(t);return e.json(n)}).post("/",describeRoute({summary:"Create session",description:"Create a new EasBot session for interacting with AI assistants and managing conversations.",operationId:"session.create",responses:{...Te(400),200:{description:"Successfully created session",content:{"application/json":{schema:resolver(Y.Info)}}}}}),validator("json",Y.create.schema.optional()),async e=>{let t=e.req.valid("json")??{},n=await Y.create(t);return e.json(n)}).delete("/:sessionId",describeRoute({summary:"Delete session",description:"Delete a session and permanently remove all associated data, including messages and history.",operationId:"session.delete",responses:{200:{description:"Successfully deleted session",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:Y.remove.schema})),async e=>{let t=e.req.valid("param").sessionId;return await Y.remove(t),e.json(true)}).patch("/:sessionId",describeRoute({summary:"Update session",description:"Update properties of an existing session, such as title or other metadata.",operationId:"session.update",responses:{200:{description:"Successfully updated session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string()})),validator("json",N.object({title:N.string().optional(),time:N.object({archived:N.number().optional()}).optional()})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Y.update(t,s=>{n.title!==void 0&&(s.title=n.title),n.time?.archived!==void 0&&(s.time.archived=n.time.archived);},{touch:false});return e.json(o)}).post("/:sessionId/init",describeRoute({summary:"Initialize session",description:"Analyze the current application and create an AGENTS.md file with project-specific agent configurations.",operationId:"session.init",responses:{200:{description:"200",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",Y.initialize.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");return await Y.initialize({...n,sessionId:t}),e.json(true)}).post("/:sessionId/fork",describeRoute({summary:"Fork session",description:"Create a new session by forking an existing session at a specific message point.",operationId:"session.fork",responses:{200:{description:"200",content:{"application/json":{schema:resolver(Y.Info)}}}}}),validator("param",N.object({sessionId:Y.fork.schema.shape.sessionId})),validator("json",Y.fork.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Y.fork({...n,sessionId:t});return e.json(o)}).post("/:sessionId/abort",describeRoute({summary:"Abort session",description:"Abort an active session and stop any ongoing AI processing or command execution.",operationId:"session.abort",responses:{200:{description:"Aborted session",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string()})),async e=>(await Je.cancel(e.req.valid("param").sessionId),e.json(true))).post("/:sessionId/share",describeRoute({summary:"Share session",description:"Create a shareable link for a session, allowing others to view the conversation.",operationId:"session.share",responses:{200:{description:"Successfully shared session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string()})),async e=>{let t=e.req.valid("param").sessionId;await Y.share(t);let n=await Y.get(t);return e.json(n)}).get("/:sessionId/diff",describeRoute({summary:"Get message diff",description:"Get the file changes (diff) that resulted from a specific user message in the session.",operationId:"session.diff",responses:{200:{description:"Successfully retrieved diff",content:{"application/json":{schema:resolver(yt.FileDiff.array())}}}}}),validator("param",N.object({sessionId:Yo.diff.schema.shape.sessionId})),validator("query",N.object({messageId:Yo.diff.schema.shape.messageId})),async e=>{let t=e.req.valid("query"),n=e.req.valid("param"),o=await Yo.diff({sessionId:n.sessionId,messageId:t.messageId});return e.json(o)}).delete("/:sessionId/share",describeRoute({summary:"Unshare session",description:"Remove the shareable link for a session, making it private again.",operationId:"session.unshare",responses:{200:{description:"Successfully unshared session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:Y.unshare.schema})),async e=>{let t=e.req.valid("param").sessionId;await Y.unshare(t);let n=await Y.get(t);return e.json(n)}).post("/:sessionId/summarize",describeRoute({summary:"Summarize session",description:"Generate a concise summary of the session using AI compaction to preserve key information.",operationId:"session.summarize",responses:{200:{description:"Summarized session",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",N.object({providerId:N.string(),modelId:N.string(),auto:N.boolean().optional().default(false)})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Y.get(t);return await io.cleanup(o),await on.create({sessionId:t,agent:"compaction",model:{providerId:n.providerId,modelId:n.modelId},auto:n.auto}),await Je.loop({sessionId:t}),e.json(true)}).get("/:sessionId/contextMode",describeRoute({summary:"Get session context mode",description:"Get the context mode of a session (general or coder).",tags:["Session"],operationId:"session.contextMode.get",responses:{200:{description:"Context mode",content:{"application/json":{schema:resolver(N.enum(["general","coder"]))}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,n=await Y.getContextMode(t);return e.json(n)}).put("/:sessionId/contextMode",describeRoute({summary:"Set session context mode",description:"Set the context mode of a session (general or coder).",tags:["Session"],operationId:"session.contextMode.set",responses:{200:{description:"Successfully updated context mode",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",N.object({mode:N.enum(["general","coder"]).meta({description:"Context mode to set"})})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");return await Y.setContextMode(t,n.mode),e.json(true)}).get("/:sessionId/message",describeRoute({summary:"Get session messages",description:"Retrieve all messages in a session, including user prompts and AI responses.",operationId:"session.messages",responses:{200:{description:"List of messages",content:{"application/json":{schema:resolver(ve.WithParts.array())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("query",N.object({limit:N.coerce.number().optional()})),async e=>{let t=e.req.valid("query"),n=await Y.messages({sessionId:e.req.valid("param").sessionId,limit:t.limit});return e.json(n)}).get("/:sessionId/message/:messageId",describeRoute({summary:"Get message",description:"Retrieve a specific message from a session by its message ID.",operationId:"session.message",responses:{200:{description:"Message",content:{"application/json":{schema:resolver(N.object({info:ve.Info,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"}),messageId:N.string().meta({description:"Message ID"})})),async e=>{let t=e.req.valid("param"),n=await ve.get({sessionId:t.sessionId,messageId:t.messageId});return e.json(n)}).delete("/:sessionId/message/:messageId/part/:partId",describeRoute({description:"Delete a part from a message",operationId:"part.delete",responses:{200:{description:"Successfully deleted part",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"}),messageId:N.string().meta({description:"Message ID"}),partId:N.string().meta({description:"Part ID"})})),async e=>{let t=e.req.valid("param");return await Y.removePart({sessionId:t.sessionId,messageId:t.messageId,partId:t.partId}),e.json(true)}).patch("/:sessionId/message/:messageId/part/:partId",describeRoute({description:"Update a part in a message",operationId:"part.update",responses:{200:{description:"Successfully updated part",content:{"application/json":{schema:resolver(ve.Part)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"}),messageId:N.string().meta({description:"Message ID"}),partId:N.string().meta({description:"Part ID"})})),validator("json",ve.Part),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");if(n.id!==t.partId||n.messageId!==t.messageId||n.sessionId!==t.sessionId)throw new Error(`Part mismatch: body.id='${n.id}' vs partId='${t.partId}', body.messageId='${n.messageId}' vs messageId='${t.messageId}', body.sessionId='${n.sessionId}' vs sessionId='${t.sessionId}'`);let o=await Y.updatePart(n);return e.json(o)}).post("/:sessionId/message",describeRoute({summary:"Send message",description:"Create and send a new message to a session, streaming the AI response.",operationId:"session.prompt",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(N.object({info:ve.Assistant,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",Je.PromptInput.omit({sessionId:true})),async e=>(e.status(200),e.header("Content-Type","application/json"),stream(e,async t=>{let n=e.req.valid("param").sessionId,o=e.req.valid("json"),s=await Je.prompt({...o,sessionId:n});t.write(JSON.stringify(s));}))).post("/:sessionId/prompt_async",describeRoute({summary:"Send async message",description:"Create and send a new message to a session asynchronously, starting the session if needed and returning immediately.",operationId:"session.prompt_async",responses:{204:{description:"Prompt accepted"},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",Je.PromptInput.omit({sessionId:true})),async e=>(e.status(204),e.header("Content-Type","application/json"),stream(e,async()=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");Je.prompt({...n,sessionId:t});}))).post("/:sessionId/command",describeRoute({summary:"Send command",description:"Send a new command to a session for execution by the AI assistant.",operationId:"session.command",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(N.object({info:ve.Assistant.optional(),parts:ve.Part.array().optional(),title:N.string(),metadata:N.record(N.string(),N.unknown()),output:N.string(),success:N.boolean(),error:N.string().optional()}))}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",Je.CommandInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Je.command({...n,sessionId:t});return e.json(o)}).post("/:sessionId/shell",describeRoute({summary:"Run shell command",description:"Execute a shell command within the session context and return the AI's response.",operationId:"session.shell",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(ve.Assistant)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string().meta({description:"Session ID"})})),validator("json",Je.ShellInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Je.shell({...n,sessionId:t});return e.json(o)}).post("/:sessionId/revert",describeRoute({summary:"Revert message",description:"Revert a specific message in a session, undoing its effects and restoring the previous state.",operationId:"session.revert",responses:{200:{description:"Updated session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string()})),validator("json",io.RevertInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId;zr.info("revert",e.req.valid("json"));let n=await io.revert({sessionId:t,...e.req.valid("json")});return e.json(n)}).post("/:sessionId/unrevert",describeRoute({summary:"Restore reverted messages",description:"Restore all previously reverted messages in a session.",operationId:"session.unrevert",responses:{200:{description:"Updated session",content:{"application/json":{schema:resolver(Y.Info)}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string()})),async e=>{let t=e.req.valid("param").sessionId,n=await io.unrevert({sessionId:t});return e.json(n)}).post("/:sessionId/permissions/:permissionId",describeRoute({summary:"Respond to permission",deprecated:true,description:"Approve or deny a permission request from the AI assistant.",operationId:"permission.respond",responses:{200:{description:"Permission processed successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({sessionId:N.string(),permissionId:N.string()})),validator("json",N.object({response:Me.Reply})),async e=>{let t=e.req.valid("param");return Me.reply({requestId:t.permissionId,reply:e.req.valid("json").response}),e.json(true)}).get("/:sessionId/event",describeRoute({summary:"Get session events",description:"Subscribe to events for a specific session using server-sent events.",operationId:"session.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(N.object({sessionId:N.string(),directory:N.string(),payload:a$5.payloads()}))}}}}}),validator("param",N.object({sessionId:N.string()})),async e=>{let{sessionId:t}=e.req.valid("param");return zr.info("session event connected",{sessionId:t}),streamSSE(e,async n=>{await n.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"session.connected",properties:{}}})});async function o(r){(r.properties?.sessionId??r.properties?.sessionId)===t&&await n.writeSSE({data:JSON.stringify({sessionId:t,payload:r})});}ft.on("event",o);let s=setInterval(()=>{n.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(r=>{n.onAbort(()=>{clearInterval(s),ft.off("event",o),zr.info("session event disconnected",{sessionId:t}),r();});});})}).get("/:sessionId/message/:messageId/event",describeRoute({summary:"Get message events",description:"Subscribe to events for a specific message using server-sent events.",operationId:"message.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(N.object({sessionId:N.string(),messageId:N.string(),directory:N.string(),payload:a$5.payloads()}))}}}}}),validator("param",N.object({sessionId:N.string(),messageId:N.string()})),async e=>{let{sessionId:t,messageId:n}=e.req.valid("param");return zr.debug("message event connected",{sessionId:t,messageId:n}),streamSSE(e,async o=>{await o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:{type:"message.connected",properties:{}}})});async function s(i){let c=i.properties?.sessionId??i.properties?.sessionId,l=i.properties?.messageId??i.properties?.messageId;c===t&&l===n&&await o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:i})});}ft.on("event",s);let r=setInterval(()=>{o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(i=>{o.onAbort(()=>{clearInterval(r),ft.off("event",s),zr.debug("message event disconnected",{sessionId:t,messageId:n}),i();});});})}));var Nh=lazy(()=>new Hono().get("/",describeRoute({summary:"List PTY sessions",description:"Get a list of all active pseudo-terminal (PTY) sessions managed by EasBot.",operationId:"pty.list",responses:{200:{description:"List of sessions",content:{"application/json":{schema:resolver(ot.Info.array())}}}}}),async e=>e.json(ot.list())).post("/",describeRoute({summary:"Create PTY session",description:"Create a new pseudo-terminal (PTY) session for running shell commands and processes.",operationId:"pty.create",responses:{200:{description:"Created session",content:{"application/json":{schema:resolver(ot.Info)}}},...Te(400)}}),validator("json",ot.CreateInput),async e=>{let t=await ot.create(e.req.valid("json"));return e.json(t)}).get("/:ptyId",describeRoute({summary:"Get PTY session",description:"Retrieve detailed information about a specific pseudo-terminal (PTY) session.",operationId:"pty.get",responses:{200:{description:"Session info",content:{"application/json":{schema:resolver(ot.Info)}}},...Te(404)}}),validator("param",N.object({ptyId:N.string()})),async e=>{let t=ot.get(e.req.valid("param").ptyId);if(!t)throw new a$6.NotFoundError({message:"Session not found"});return e.json(t)}).put("/:ptyId",describeRoute({summary:"Update PTY session",description:"Update properties of an existing pseudo-terminal (PTY) session.",operationId:"pty.update",responses:{200:{description:"Updated session",content:{"application/json":{schema:resolver(ot.Info)}}},...Te(400)}}),validator("param",N.object({ptyId:N.string()})),validator("json",ot.UpdateInput),async e=>{let t=await ot.update(e.req.valid("param").ptyId,e.req.valid("json"));return e.json(t)}).delete("/:ptyId",describeRoute({summary:"Remove PTY session",description:"Remove and terminate a specific pseudo-terminal (PTY) session.",operationId:"pty.remove",responses:{200:{description:"Session removed",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(404)}}),validator("param",N.object({ptyId:N.string()})),async e=>(await ot.remove(e.req.valid("param").ptyId),e.json(true))).get("/:ptyId/connect",describeRoute({summary:"Connect to PTY session",description:"Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time.",operationId:"pty.connect",responses:{200:{description:"Connected session",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(404)}}),validator("param",N.object({ptyId:N.string()})),async e=>e.json({error:"WebSocket not implemented in Node.js mode yet"},501)));var Uh=lazy(()=>new Hono().get("/",describeRoute({summary:"Get MCP status",description:"Get the status of all Model Context Protocol (MCP) servers.",operationId:"mcp.status",responses:{200:{description:"MCP server status",content:{"application/json":{schema:resolver(N.record(N.string(),Status))}}}}}),async e=>e.json(await ze.status())).post("/",describeRoute({summary:"Add MCP server",description:"Dynamically add a new Model Context Protocol (MCP) server to the system.",operationId:"mcp.add",responses:{200:{description:"MCP server added successfully",content:{"application/json":{schema:resolver(N.record(N.string(),Status))}}},...Te(400)}}),validator("json",N.object({name:N.string(),config:he.Mcp})),async e=>{let{name:t,config:n}=e.req.valid("json"),o=await ze.add(t,n);return e.json(o.status)}).post("/:name/auth",describeRoute({summary:"Start MCP OAuth",description:"Start OAuth authentication flow for a Model Context Protocol (MCP) server.",operationId:"mcp.auth.start",responses:{200:{description:"OAuth flow started",content:{"application/json":{schema:resolver(N.object({authorizationUrl:N.string().describe("URL to open in browser for authorization")}))}}},...Te(400,404)}}),async e=>{let t=e.req.param("name");if(!await ze.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let o=await ze.startAuth(t);return e.json(o)}).post("/:name/auth/callback",describeRoute({summary:"Complete MCP OAuth",description:"Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code.",operationId:"mcp.auth.callback",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:resolver(Status)}}},...Te(400,404)}}),validator("json",N.object({code:N.string().describe("Authorization code from OAuth callback")})),async e=>{let t=e.req.param("name"),{code:n}=e.req.valid("json"),o=await ze.finishAuth(t,n);return e.json(o)}).post("/:name/auth/authenticate",describeRoute({summary:"Authenticate MCP OAuth",description:"Start OAuth flow and wait for callback (opens browser)",operationId:"mcp.auth.authenticate",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:resolver(Status)}}},...Te(400,404)}}),async e=>{let t=e.req.param("name");if(!await ze.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let o=await ze.authenticate(t);return e.json(o)}).delete("/:name/auth",describeRoute({summary:"Remove MCP OAuth",description:"Remove OAuth credentials for an MCP server",operationId:"mcp.auth.remove",responses:{200:{description:"OAuth credentials removed",content:{"application/json":{schema:resolver(N.object({success:N.literal(true)}))}}},...Te(404)}}),async e=>{let t=e.req.param("name");return await ze.removeAuth(t),e.json({success:true})}).post("/:name/connect",describeRoute({description:"Connect an MCP server",operationId:"mcp.connect",responses:{200:{description:"MCP server connected successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),validator("param",N.object({name:N.string()})),async e=>{let{name:t}=e.req.valid("param");return await ze.connect(t),e.json(true)}).post("/:name/disconnect",describeRoute({description:"Disconnect an MCP server",operationId:"mcp.disconnect",responses:{200:{description:"MCP server disconnected successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),validator("param",N.object({name:N.string()})),async e=>{let{name:t}=e.req.valid("param");return await ze.disconnect(t),e.json(true)}).get("/tools",describeRoute({summary:"Get MCP tools",description:"Get the list of tools from all connected MCP servers.",operationId:"mcp.tools",responses:{200:{description:"MCP tools by server",content:{"application/json":{schema:resolver(N.record(N.string(),N.array(N.string())))}}}}}),async e=>{let t=await ze.tools(),n={};for(let o of Object.keys(t)){let s=o.split("_"),r=s[0];if(!r)continue;let i=s.slice(1).join("_");n[r]||(n[r]=[]),n[r].push(i);}return e.json(n)}));var zh=lazy(()=>new Hono().get("/find",describeRoute({summary:"Find text",description:"Search for text patterns across files in the project using ripgrep.",operationId:"find.text",responses:{200:{description:"Matches",content:{"application/json":{schema:resolver(a$8.Match.shape.data.array())}}}}}),validator("query",N.object({pattern:N.string()})),async e=>{let t=e.req.valid("query").pattern,n=await a$8.search({cwd:R.directory,pattern:t,limit:10});return e.json(n)}).get("/find/file",describeRoute({summary:"Find files",description:"Search for files or directories by name or pattern in the project directory.",operationId:"find.files",responses:{200:{description:"File paths",content:{"application/json":{schema:resolver(N.string().array())}}}}}),validator("query",N.object({query:N.string(),dirs:N.enum(["true","false"]).optional(),type:N.enum(["file","directory"]).optional(),limit:N.coerce.number().int().min(1).max(200).optional()})),async e=>{let t=e.req.valid("query").query,n=e.req.valid("query").dirs,o=e.req.valid("query").type,s=e.req.valid("query").limit,r=await bt.search({query:t,limit:s??10,dirs:n!=="false",type:o});return e.json(r)}).get("/find/symbol",describeRoute({summary:"Find symbols",description:"Search for workspace symbols like functions, classes, and variables using LSP.",operationId:"find.symbols",responses:{200:{description:"Symbols",content:{"application/json":{schema:resolver(We.LspSymbol.array())}}}}}),validator("query",N.object({query:N.string()})),async e=>e.json([])).get("/file",describeRoute({summary:"List files",description:"List files and directories in a specified path.",operationId:"file.list",responses:{200:{description:"Files and directories",content:{"application/json":{schema:resolver(bt.Node.array())}}}}}),validator("query",N.object({path:N.string()})),async e=>{let t=e.req.valid("query").path,n=await bt.list(t);return e.json(n)}).get("/file/content",describeRoute({summary:"Read file",description:"Read the content of a specified file.",operationId:"file.read",responses:{200:{description:"File content",content:{"application/json":{schema:resolver(bt.Content)}}}}}),validator("query",N.object({path:N.string()})),async e=>{let t=e.req.valid("query").path,n=await bt.read(t);return e.json(n)}).get("/file/status",describeRoute({summary:"Get file status",description:"Get the git status of all files in the project.",operationId:"file.status",responses:{200:{description:"File status",content:{"application/json":{schema:resolver(bt.Info.array())}}}}}),async e=>{let t=await bt.status();return e.json(t)}));var KA=a.create({service:"server"}),Hh=lazy(()=>new Hono().get("/",describeRoute({summary:"Get configuration",description:"Retrieve the current EasBot configuration settings and preferences.",operationId:"config.get",responses:{200:{description:"Get config info",content:{"application/json":{schema:resolver(he.Info)}}}}}),async e=>e.json(await he.get())).patch("/",describeRoute({summary:"Update configuration",description:"Update EasBot configuration settings and preferences.",operationId:"config.update",responses:{200:{description:"Successfully updated config",content:{"application/json":{schema:resolver(he.Info)}}},...Te(400)}}),validator("json",he.Info),async e=>{let t=e.req.valid("json");return await he.update(t),e.json(t)}).get("/providers",describeRoute({summary:"List config providers",description:"Get a list of all configured AI providers and their default models.",operationId:"config.providers",responses:{200:{description:"List of providers",content:{"application/json":{schema:resolver(N.object({providers:xe.Info.array(),default:N.record(N.string(),N.string())}))}}}}}),async e=>{var o=[];try{let t=c(o,KA.time("providers"));let n=await xe.list().then(c=>mapValues(c,l=>l));return e.json({providers:Object.values(n),default:mapValues(n,c=>xe.sort(Object.values(c.models))[0]?.id??"")})}catch(s){var r=s,i=true;}finally{d(o,r,i);}}));var fd;(m=>{let e=a.create({service:"share-next"});async function t(){return he.get().then(f=>f.enterprise?.url??"https://api.easbot.cn")}m.url=t;let n=process.env.EASBOT_DISABLE_SHARE==="true"||process.env.EASBOT_DISABLE_SHARE==="1";async function o(){n||(pe.subscribe(Y.Event.Updated,async f=>{await c(f.properties.info.id,[{type:"session",data:f.properties.info}]);}),pe.subscribe(ve.Event.Updated,async f=>{await c(f.properties.info.sessionId,[{type:"message",data:f.properties.info}]),f.properties.info.role==="user"&&await c(f.properties.info.sessionId,[{type:"model",data:[await xe.getModel(f.properties.info.model.providerId,f.properties.info.model.modelId).then(a=>a)]}]);}),pe.subscribe(ve.Event.PartUpdated,async f=>{await c(f.properties.part.sessionId,[{type:"part",data:f.properties.part}]);}),pe.subscribe(Y.Event.Diff,async f=>{await c(f.properties.sessionId,[{type:"session_diff",data:f.properties.diff}]);}));}m.init=o;async function s(f){if(n)return {id:"",url:"",secret:""};e.info("creating share",{sessionId:f});let p=(await Fetch.post(`${await t()}/api/share`,{sessionId:f})).data;return await a$6.write(["session_share",f],p),await d(f),p}m.create=s;function r(f){return a$6.read(["session_share",f])}let i=new Map;async function c(f,a){if(n)return;let p=i.get(f);if(p){for(let g of a)p.data.set("id"in g?g.id:ulid(),g);return}let u=new Map;for(let g of a)u.set("id"in g?g.id:ulid(),g);let h=setTimeout(async()=>{let g=i.get(f);if(!g)return;i.delete(f);let I=await r(f).catch(()=>{});I&&await Fetch.post(`${await t()}/api/share/${I.id}/sync`,{secret:I.secret,data:Array.from(g.data.values())});},1e3);i.set(f,{timeout:h,data:u});}async function l(f){if(n)return;e.debug("removing share",{sessionId:f});let a=await r(f);a&&(await Fetch.del(`${await t()}/api/share/${a.id}`,{secret:a.secret}),await a$6.remove(["session_share",f]));}m.remove=l;async function d(f){e.info("full sync",{sessionId:f});let a=await Y.get(f),p=await Y.diff(f),u=await Array.fromAsync(ve.stream(f)),h=await Promise.all(u.filter(g=>g.info.role==="user").map(g=>g.info.model).map(g=>xe.getModel(g.providerId,g.modelId).then(I=>I)));await c(f,[{type:"session",data:a},...u.map(g=>({type:"message",data:g.info})),...u.flatMap(g=>g.parts.map(I=>({type:"part",data:I}))),{type:"session_diff",data:p},{type:"model",data:h}]);}})(fd||(fd={}));var JA=a$5.define("command.executed",N.object({name:N.string(),sessionId:N.string(),arguments:N.union([N.string(),N.record(N.string(),N.unknown())]),messageId:N.string().optional()})),Gh=false;async function na(){if(Gh){a.Default.debug("InstanceBootstrap already executed, skipping");return}Gh=true,a.Default.info("bootstrapping",{directory:R.directory}),await ls.init(),await fd.init(),xs.init(),await We.init(),Fn.init(),bt.init(),await qs.init(),await yt.init(),await Ve.init(),pe.subscribe(JA,async e=>{e.properties.name===su.Default.INIT&&await Ut.setInitialized(R.project.id);});}var Po;(A=>{let e=a.create({service:"worktree"});A.Event={Ready:a$5.define("worktree.ready",N.object({name:N.string(),branch:N.string()})),Failed:a$5.define("worktree.failed",N.object({message:N.string()}))},A.Info=N.object({name:N.string(),branch:N.string(),directory:N.string()}).meta({ref:"Worktree"}),A.CreateInput=N.object({name:N.string().optional(),startCommand:N.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),A.RemoveInput=N.object({directory:N.string()}).meta({ref:"WorktreeRemoveInput"}),A.ResetInput=N.object({directory:N.string()}).meta({ref:"WorktreeResetInput"}),A.NotGitError=NamedError.create("WorktreeNotGitError",N.object({message:N.string()})),A.NameGenerationFailedError=NamedError.create("WorktreeNameGenerationFailedError",N.object({message:N.string()})),A.CreateFailedError=NamedError.create("WorktreeCreateFailedError",N.object({message:N.string()})),A.StartCommandFailedError=NamedError.create("WorktreeStartCommandFailedError",N.object({message:N.string()})),A.RemoveFailedError=NamedError.create("WorktreeRemoveFailedError",N.object({message:N.string()})),A.ResetFailedError=NamedError.create("WorktreeResetFailedError",N.object({message:N.string()}));let a$2=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],p=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function u(L){return L[Math.floor(Math.random()*L.length)]}function h(L){return L.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function g(){return `${u(a$2)}-${u(p)}`}async function I(L){return Tt__default.stat(L).then(()=>true).catch(()=>false)}function T(L){return L?.length===0?"":new TextDecoder().decode(L).trim()}function y(L){return [T(L.stderr),T(L.stdout)].filter(Boolean).join(`
|
|
883
|
+
`)}function x(L){return [T(L.stderr),T(L.stdout)].filter(Boolean).flatMap(S=>S.split(`
|
|
884
|
+
`).map(P=>P.trim()).flatMap(P=>{let _=P.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!_)return [];let j=_[1]?.trim().replace(/^['"]|['"]$/g,"");return j?[j]:[]}))}async function b(L,S){let P=await k(L);await Promise.all(S.map(async _=>{let j=await k(Se__default.resolve(L,_));j!==P&&j.startsWith(`${P}${Se__default.sep}`)&&await Tt__default.rm(j,{recursive:true,force:true}).catch(()=>{});}));}async function w(L){let S=await $`git clean -ffdx`.quiet().nothrow().cwd(L);if(S.exitCode===0)return S;let P=x(S);return P.length===0?S:(await b(L,P),$`git clean -ffdx`.quiet().nothrow().cwd(L))}async function k(L){let S=Se__default.resolve(L),P=await Tt__default.realpath(S).catch(()=>S),_=Se__default.normalize(P);return process.platform==="win32"?_.toLowerCase():_}async function v(L,S){for(let P of Array.from({length:26},(_,j)=>j)){let _=S?P===0?S:`${S}-${g()}`:g(),j=`easbot/${_}`,B=Se__default.join(L,_);if(await I(B))continue;let Z=`refs/heads/${j}`;if((await $`git show-ref --verify --quiet ${Z}`.quiet().nothrow().cwd(R.worktree)).exitCode!==0)return A.Info.parse({name:_,branch:j,directory:B})}throw new A.NameGenerationFailedError({message:"Failed to generate a unique worktree name"})}async function C(L,S){return process.platform==="win32"?$`cmd /c ${S}`.nothrow().cwd(L):$`bash -lc ${S}`.nothrow().cwd(L)}async function E(L,S,P){let _=S.trim();if(!_)return true;let j=await C(L,_);return j.exitCode===0?true:(e.error("worktree start command failed",{kind:P,directory:L,message:y(j)}),false)}async function O(L,S){let _=(await a$6.read(["project",S.providerId]).catch(()=>{}))?.commands?.start?.trim()??"";if(!await E(L,_,"project"))return false;let B=S.extra??"";return await E(L,B,"worktree"),true}function U(L,S){setTimeout(()=>{(async()=>{await O(L,S);})().catch(_=>{e.error("worktree start task failed",{directory:L,error:_});});},0);}async function D(L){if(R.project.vcs!=="git")throw new A.NotGitError({message:"Worktrees are only supported for git projects"});let S=Se__default.join(a$1.Path.data,"worktree",R.project.id);await Tt__default.mkdir(S,{recursive:true});let P=L?h(L):"";return v(S,P||void 0)}A.makeWorktreeInfo=D;async function K(L){if(R.project.vcs!=="git")throw new A.NotGitError({message:"Worktrees are only supported for git projects"});let S=await $`git worktree add --no-checkout -b ${L.branch} ${L.directory}`.quiet().nothrow().cwd(R.worktree);if(S.exitCode!==0)throw new A.CreateFailedError({message:y(S)||"Failed to create git worktree"});await Ut.addSandbox(R.project.id,L.directory).catch(()=>{});let P=R.project.id;setTimeout(()=>{(async()=>{let j=await $`git reset --hard`.quiet().nothrow().cwd(L.directory);if(j.exitCode!==0){let Z=y(j)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:L.directory,message:Z}),ft.emit("event",{directory:L.directory,payload:{type:A.Event.Failed.type,properties:{message:Z}}});return}await R.provide({directory:L.directory,init:na,fn:()=>{}}).then(()=>true).catch(Z=>{let ee=Z instanceof Error?Z.message:String(Z);return e.error("worktree bootstrap failed",{directory:L.directory,message:ee}),ft.emit("event",{directory:L.directory,payload:{type:A.Event.Failed.type,properties:{message:ee}}}),false})&&(ft.emit("event",{directory:L.directory,payload:{type:A.Event.Ready.type,properties:{name:L.name,branch:L.branch}}}),await O(L.directory,{providerId:P}));})().catch(j=>{e.error("worktree start task failed",{directory:L.directory,error:j});});},0);}A.createFromInfo=K,A.create=fn$1(A.CreateInput.optional(),async L=>{if(R.project.vcs!=="git")throw new A.NotGitError({message:"Worktrees are only supported for git projects"});let S=Se__default.join(a$1.Path.data,"worktree",R.project.id);await Tt__default.mkdir(S,{recursive:true});let P=L?.name?h(L.name):"",_=await v(S,P||void 0),j=await $`git worktree add --no-checkout -b ${_.branch} ${_.directory}`.quiet().nothrow().cwd(R.worktree);if(j.exitCode!==0)throw new A.CreateFailedError({message:y(j)||"Failed to create git worktree"});await Ut.addSandbox(R.project.id,_.directory).catch(()=>{});let B=R.project.id,Z=L?.startCommand?.trim();return setTimeout(()=>{(async()=>{let se=await $`git reset --hard`.quiet().nothrow().cwd(_.directory);if(se.exitCode!==0){let ae=y(se)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:_.directory,message:ae}),ft.emit("event",{directory:_.directory,payload:{type:A.Event.Failed.type,properties:{message:ae}}});return}await R.provide({directory:_.directory,init:na,fn:()=>{}}).then(()=>true).catch(ae=>{let we=ae instanceof Error?ae.message:String(ae);return e.error("worktree bootstrap failed",{directory:_.directory,message:we}),ft.emit("event",{directory:_.directory,payload:{type:A.Event.Failed.type,properties:{message:we}}}),false})&&(ft.emit("event",{directory:_.directory,payload:{type:A.Event.Ready.type,properties:{name:_.name,branch:_.branch}}}),await O(_.directory,{providerId:B,extra:Z}));})().catch(se=>{e.error("worktree start task failed",{directory:_.directory,error:se});});},0),_}),A.remove=fn$1(A.RemoveInput,async L=>{if(R.project.vcs!=="git")throw new A.NotGitError({message:"Worktrees are only supported for git projects"});let S=await k(L.directory),P=await $`git worktree list --porcelain`.quiet().nothrow().cwd(R.worktree);if(P.exitCode!==0)throw new A.RemoveFailedError({message:y(P)||"Failed to read git worktrees"});let j=T(P.stdout).split(`
|
|
885
|
+
`).map(se=>se.trim()).reduce((se,le)=>{if(!le)return se;if(le.startsWith("worktree "))return se.push({path:le.slice(9).trim()}),se;let ae=se[se.length-1];return ae&&le.startsWith("branch ")&&(ae.branch=le.slice(7).trim()),se},[]),B=await(async()=>{for(let se of j){if(!se.path)continue;if(await k(se.path)===S)return se}})();if(!B?.path)return await I(S)&&await Tt__default.rm(S,{recursive:true,force:true}),true;let Z=await $`git worktree remove --force ${B.path}`.quiet().nothrow().cwd(R.worktree);if(Z.exitCode!==0)throw new A.RemoveFailedError({message:y(Z)||"Failed to remove git worktree"});let ee=B.branch?.replace(/^refs\/heads\//,"");if(ee){let se=await $`git branch -D ${ee}`.quiet().nothrow().cwd(R.worktree);if(se.exitCode!==0)throw new A.RemoveFailedError({message:y(se)||"Failed to delete worktree branch"})}return true}),A.reset=fn$1(A.ResetInput,async L=>{if(R.project.vcs!=="git")throw new A.NotGitError({message:"Worktrees are only supported for git projects"});let S=await k(L.directory),P=await k(R.worktree);if(S===P)throw new A.ResetFailedError({message:"Cannot reset the primary workspace"});let _=await $`git worktree list --porcelain`.quiet().nothrow().cwd(R.worktree);if(_.exitCode!==0)throw new A.ResetFailedError({message:y(_)||"Failed to read git worktrees"});let B=T(_.stdout).split(`
|
|
886
|
+
`).map(ie=>ie.trim()).reduce((ie,$e)=>{if(!$e)return ie;if($e.startsWith("worktree "))return ie.push({path:$e.slice(9).trim()}),ie;let Ae=ie[ie.length-1];return Ae&&$e.startsWith("branch ")&&(Ae.branch=$e.slice(7).trim()),ie},[]),Z=await(async()=>{for(let ie of B){if(!ie.path)continue;if(await k(ie.path)===S)return ie}})();if(!Z?.path)throw new A.ResetFailedError({message:"Worktree not found"});let ee=await $`git remote`.quiet().nothrow().cwd(R.worktree);if(ee.exitCode!==0)throw new A.ResetFailedError({message:y(ee)||"Failed to list git remotes"});let se=T(ee.stdout).split(`
|
|
887
|
+
`).map(ie=>ie.trim()).filter(Boolean),le=se.includes("origin")?"origin":se.length===1?se[0]:se.includes("upstream")?"upstream":"",ae=le?await $`git symbolic-ref refs/remotes/${le}/HEAD`.quiet().nothrow().cwd(R.worktree):{exitCode:1,stdout:void 0},we=ae.exitCode===0?T(ae.stdout):"",re=we?we.replace(/^refs\/remotes\//,""):"",Q=le&&re.startsWith(`${le}/`)?re.slice(`${le}/`.length):"",H=await $`git show-ref --verify --quiet refs/heads/main`.quiet().nothrow().cwd(R.worktree),F=await $`git show-ref --verify --quiet refs/heads/master`.quiet().nothrow().cwd(R.worktree),te=H.exitCode===0?"main":F.exitCode===0?"master":"",V=Q?`${le}/${Q}`:te;if(!V)throw new A.ResetFailedError({message:"Default branch not found"});if(Q){let ie=await $`git fetch ${le} ${Q}`.quiet().nothrow().cwd(R.worktree);if(ie.exitCode!==0)throw new A.ResetFailedError({message:y(ie)||`Failed to fetch ${V}`})}if(!Z.path)throw new A.ResetFailedError({message:"Worktree path not found"});let J=Z.path,oe=await $`git reset --hard ${V}`.quiet().nothrow().cwd(J);if(oe.exitCode!==0)throw new A.ResetFailedError({message:y(oe)||"Failed to reset worktree to target"});let de=await w(J);if(de.exitCode!==0)throw new A.ResetFailedError({message:y(de)||"Failed to clean worktree"});let me=await $`git submodule update --init --recursive --force`.quiet().nothrow().cwd(J);if(me.exitCode!==0)throw new A.ResetFailedError({message:y(me)||"Failed to update submodules"});let ce=await $`git submodule foreach --recursive git reset --hard`.quiet().nothrow().cwd(J);if(ce.exitCode!==0)throw new A.ResetFailedError({message:y(ce)||"Failed to reset submodules"});let ye=await $`git submodule foreach --recursive git clean -fdx`.quiet().nothrow().cwd(J);if(ye.exitCode!==0)throw new A.ResetFailedError({message:y(ye)||"Failed to clean submodules"});let je=await $`git status --porcelain=v1`.quiet().nothrow().cwd(J);if(je.exitCode!==0)throw new A.ResetFailedError({message:y(je)||"Failed to read git status"});let Ie=T(je.stdout);if(Ie)throw new A.ResetFailedError({message:`Worktree reset left local changes:
|
|
888
|
+
${Ie}`});let Ce=R.project.id;return U(J,{providerId:Ce}),true});})(Po||(Po={}));var Wh=lazy(()=>new Hono().get("/tool/ids",describeRoute({summary:"List tool IDs",description:"Get a list of all available tool IDs, including both built-in tools and dynamically registered tools.",operationId:"tool.ids",responses:{200:{description:"Tool IDs",content:{"application/json":{schema:resolver(N.array(N.string()).meta({ref:"ToolIDs"}))}}},...Te(400)}}),async e=>e.json(await Un.ids())).get("/tool",describeRoute({summary:"List tools",description:"Get a list of available tools with their JSON schema parameters for a specific provider and model combination.",operationId:"tool.list",responses:{200:{description:"Tools",content:{"application/json":{schema:resolver(N.array(N.object({id:N.string(),description:N.string(),parameters:N.any()}).meta({ref:"ToolListItem"})).meta({ref:"ToolList"}))}}},...Te(400)}}),validator("query",N.object({provider:N.string(),model:N.string()})),async e=>{let{provider:t,model:n}=e.req.valid("query"),o=await Un.tools({providerId:t,modelId:n});return e.json(o.map(s=>({id:s.id,description:s.description,parameters:s.parameters?._def?zodToJsonSchema(s.parameters):s.parameters})))}).post("/worktree",describeRoute({summary:"Create worktree",description:"Create a new git worktree for the current project and run any configured startup scripts.",operationId:"worktree.create",responses:{200:{description:"Worktree created",content:{"application/json":{schema:resolver(Po.Info)}}},...Te(400)}}),validator("json",Po.create.schema),async e=>{let t=e.req.valid("json"),n=await Po.create(t);return e.json(n)}).get("/worktree",describeRoute({summary:"List worktrees",description:"List all sandbox worktrees for the current project.",operationId:"worktree.list",responses:{200:{description:"List of worktree directories",content:{"application/json":{schema:resolver(N.array(N.string()))}}}}}),async e=>{let t=await Ut.sandboxes(R.project.id);return e.json(t)}).delete("/worktree",describeRoute({summary:"Remove worktree",description:"Remove a git worktree and delete its branch.",operationId:"worktree.remove",responses:{200:{description:"Worktree removed",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",Po.remove.schema),async e=>{let t=e.req.valid("json");return await Po.remove(t),await Ut.removeSandbox(R.project.id,t.directory),e.json(true)}).post("/worktree/reset",describeRoute({summary:"Reset worktree",description:"Reset a worktree branch to the primary default branch.",operationId:"worktree.reset",responses:{200:{description:"Worktree reset",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",Po.reset.schema),async e=>{let t=e.req.valid("json");return await Po.reset(t),e.json(true)}).get("/resource",describeRoute({summary:"Get MCP resources",description:"Get all available MCP resources from connected servers. Optionally filter by name.",operationId:"experimental.resource.list",responses:{200:{description:"MCP resources",content:{"application/json":{schema:resolver(N.record(N.string(),N.unknown()))}}}}}),async e=>e.json(await ze.resources())));var us;(a=>{let e;function t(){return e||(e=R.state(async()=>({methods:pipe(await ls.list(),filter(u=>u.auth?.provider!==void 0),map(u=>[u.auth.provider,u.auth]),fromEntries()),pending:{}}))),e}function n(){return t()()}a.Method=N.object({type:N.union([N.literal("oauth"),N.literal("api")]),label:N.string()}).meta({ref:"ProviderAuthMethod"});async function s(){let p=await n().then(u=>u.methods);return mapValues(p,u=>u.methods.map(h=>({type:h.type,label:h.label})))}a.methods=s,a.Authorization=N.object({url:N.string(),method:N.union([N.literal("auto"),N.literal("code")]),instructions:N.string()}).meta({ref:"ProviderAuthAuthorization"}),a.authorize=fn$1(N.object({providerId:N.string(),method:N.number()}),async p=>{let u=await n().then(g=>g.methods[p.providerId]);if(!u)return;let h=u.methods[p.method];if(h&&h.type==="oauth"&&h.authorize){let g=await h.authorize();return g?(await n().then(I=>I.pending[p.providerId]=g),{url:g.url??"",method:g.method??"",instructions:g.instructions??""}):void 0}}),a.callback=fn$1(N.object({providerId:N.string(),method:N.number(),code:N.string().optional()}),async p=>{let u=await n().then(g=>g.pending[p.providerId]);if(!u)throw new a.OauthMissing({providerId:p.providerId});let h;if(u.method==="code"){if(!p.code)throw new a.OauthCodeMissing({providerId:p.providerId});h=await u.callback(p.code);}if(u.method==="auto"&&(h=await u.callback()),h?.type==="success"){if("key"in h&&h.key&&await Qe.set(p.providerId,{type:"api",key:h.key??""}),"refresh"in h&&h.refresh){let g={type:"oauth",access:h.access??"",refresh:h.refresh??"",expires:h.expires??0};h.accountId&&(g.accountId=h.accountId),await Qe.set(p.providerId,g);}return}throw new a.OauthCallbackFailed({})}),a.api=fn$1(N.object({providerId:N.string(),key:N.string()}),async p=>{await Qe.set(p.providerId,{type:"api",key:p.key});}),a.OauthMissing=NamedError.create("ProviderAuthOauthMissing",N.object({providerId:N.string()})),a.OauthCodeMissing=NamedError.create("ProviderAuthOauthCodeMissing",N.object({providerId:N.string()})),a.OauthCallbackFailed=NamedError.create("ProviderAuthOauthCallbackFailed",N.object({}));})(us||(us={}));var Kh=lazy(()=>new Hono().get("/",describeRoute({summary:"List providers",description:"Get a list of all available AI providers, including both available and connected ones.",operationId:"provider.list",responses:{200:{description:"List of providers",content:{"application/json":{schema:resolver(N.object({all:a$3.Provider.array(),default:N.record(N.string(),N.string()),connected:N.array(N.string())}))}}}}}),async e=>{let t=await he.get(),n=new Set(t.disabled_providers??[]),o=t.enabled_providers?new Set(t.enabled_providers):void 0,s=await a$3.get(),r={};for(let[l,d]of Object.entries(s))(!o||o.has(l))&&!n.has(l)&&(r[l]=d);let i=await xe.list(),c=Object.assign(mapValues(r,l=>xe.fromModelsDevProvider(l)),i);return e.json({all:Object.values(c),default:mapValues(c,l=>xe.sort(Object.values(l.models))[0]?.id??""),connected:Object.keys(i)})}).get("/auth",describeRoute({summary:"Get provider auth methods",description:"Retrieve available authentication methods for all AI providers.",operationId:"provider.auth",responses:{200:{description:"Provider auth methods",content:{"application/json":{schema:resolver(N.record(N.string(),N.array(us.Method)))}}}}}),async e=>e.json(await us.methods())).post("/:providerId/oauth/authorize",describeRoute({summary:"OAuth authorize",description:"Initiate OAuth authorization for a specific AI provider to get an authorization URL.",operationId:"provider.oauth.authorize",responses:{200:{description:"Authorization URL and method",content:{"application/json":{schema:resolver(us.Authorization.optional())}}},...Te(400)}}),validator("param",N.object({providerId:N.string().meta({description:"Provider ID"})})),validator("json",N.object({method:N.number().meta({description:"Auth method index"})})),async e=>{let t=e.req.valid("param").providerId,{method:n}=e.req.valid("json"),o=await us.authorize({providerId:t,method:n});return e.json(o)}).post("/:providerId/oauth/callback",describeRoute({summary:"OAuth callback",description:"Handle the OAuth callback from a provider after user authorization.",operationId:"provider.oauth.callback",responses:{200:{description:"OAuth callback processed successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("param",N.object({providerId:N.string().meta({description:"Provider ID"})})),validator("json",N.object({method:N.number().meta({description:"Auth method index"}),code:N.string().optional().meta({description:"OAuth authorization code"})})),async e=>{let t=e.req.valid("param").providerId,{method:n,code:o}=e.req.valid("json");return await us.callback({providerId:t,method:n,code:o}),e.json(true)}));var Xh=lazy(()=>new Hono().get("/default",describeRoute({summary:"Get default model",description:"Get the default model for the current project, based on configuration or first available provider.",operationId:"model.default",responses:{200:{description:"Default model",content:{"application/json":{schema:resolver(N.object({providerId:N.string(),modelId:N.string()}).optional())}}},...Te(400)}}),async e=>{let t=await xe.defaultModel();return t?e.json({providerId:t.providerId,modelId:t.modelId}):e.json(void 0)}).get("/parse",describeRoute({summary:"Parse model string",description:'Parse a model string in the format "providerId/modelId" and return its components.',operationId:"model.parse",responses:{200:{description:"Parsed model",content:{"application/json":{schema:resolver(N.object({providerId:N.string(),modelId:N.string()}).optional())}}},...Te(400)}}),async e=>{let t=e.req.query("model");if(!t)return e.json(void 0);let n=xe.parseModel(t);return n?.providerId?e.json({providerId:n.providerId,modelId:n.modelId}):e.json(void 0)}));var Qh=lazy(()=>new Hono().get("/",describeRoute({summary:"List pending questions",description:"Get all pending question requests across all sessions.",operationId:"question.list",responses:{200:{description:"List of pending questions",content:{"application/json":{schema:resolver(Ot.Request.array())}}}}}),async e=>{let t=await Ot.list();return e.json(t)}).post("/:requestId/reply",describeRoute({summary:"Reply to question request",description:"Provide answers to a question request from the AI assistant.",operationId:"question.reply",responses:{200:{description:"Question answered successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({requestId:N.string()})),validator("json",Ot.Reply),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");return await Ot.reply({requestId:t.requestId,answers:n.answers}),e.json(true)}).post("/:requestId/reject",describeRoute({summary:"Reject question request",description:"Reject a question request from the AI assistant.",operationId:"question.reject",responses:{200:{description:"Question rejected successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({requestId:N.string()})),async e=>{let t=e.req.valid("param");return await Ot.reject(t.requestId),e.json(true)}));var ny=lazy(()=>new Hono().post("/:requestId/reply",describeRoute({summary:"Respond to permission request",description:"Approve or deny a permission request from the AI assistant.",operationId:"permission.reply",responses:{200:{description:"Permission processed successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400,404)}}),validator("param",N.object({requestId:N.string()})),validator("json",N.object({reply:Me.Reply,message:N.string().optional()})),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");return await Me.reply({requestId:t.requestId,reply:n.reply,message:n.message}),e.json(true)}).get("/",describeRoute({summary:"List pending permissions",description:"Get all pending permission requests across all sessions.",operationId:"permission.list",responses:{200:{description:"List of pending permissions",content:{"application/json":{schema:resolver(Me.Request.array())}}}}}),async e=>{let t=await Me.list();return e.json(t)}));var oy=a.create({service:"server"}),hE=a$5.define("global.disposed",N.object({})),sy=lazy(()=>new Hono().get("/health",describeRoute({summary:"Get health",description:"Get health information about the EasBot server.",operationId:"global.health",responses:{200:{description:"Health information",content:{"application/json":{schema:resolver(N.object({healthy:N.literal(true),version:N.string()}))}}}}}),async e=>e.json({healthy:true,version:b$3.getVersion()})).get("/event",describeRoute({summary:"Get global events",description:"Subscribe to global events from the EasBot system using server-sent events.",operationId:"global.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(N.object({directory:N.string(),payload:a$5.payloads()}).meta({ref:"GlobalEvent"}))}}}}}),async e=>(oy.info("global event connected"),streamSSE(e,async t=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.connected",properties:{}}})});async function n(s){await t.writeSSE({data:JSON.stringify(s)});}ft.on("event",n);let o=setInterval(()=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(s=>{t.onAbort(()=>{clearInterval(o),ft.off("event",n),s(),oy.info("global event disconnected");});});}))).get("/config",describeRoute({summary:"Get global configuration",description:"Retrieve the current global EasBot configuration settings and preferences.",operationId:"global.config.get",responses:{200:{description:"Get global config info",content:{"application/json":{schema:resolver(he.Info)}}}}}),async e=>e.json(await he.getGlobal())).patch("/config",describeRoute({summary:"Update global configuration",description:"Update global EasBot configuration settings and preferences.",operationId:"global.config.update",responses:{200:{description:"Successfully updated global config",content:{"application/json":{schema:resolver(he.Info)}}},...Te(400)}}),validator("json",he.Info),async e=>{let t=e.req.valid("json"),n=await he.updateGlobal(t);return e.json(n)}).post("/dispose",describeRoute({summary:"Dispose instance",description:"Clean up and dispose all EasBot instances, releasing all resources.",operationId:"global.dispose",responses:{200:{description:"Global disposed",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async e=>(await R.disposeAll(),ft.emit("event",{directory:"global",payload:{type:hE.type,properties:{}}}),e.json(true))));var ry=lazy(()=>new Hono().get("/",describeRoute({summary:"List agents",description:"Get a list of all available AI agents in the EasBot system.",operationId:"app.agents",responses:{200:{description:"List of agents",content:{"application/json":{schema:resolver(N.array(Ue.Info))}}}}}),async e=>{let t=await Ue.list();return e.json(t)}).get("/:agentId",describeRoute({summary:"Get agent",description:"Get details of a specific AI agent by name or ID.",operationId:"agent.get",responses:{200:{description:"Agent details",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(404)}}),async e=>{let t=e.req.param("agentId"),n=await Ue.get(t);return n?e.json(n):e.json({error:`Agent not found: ${t}`},404)}).get("/:agentId/event",describeRoute({summary:"Get agent events",description:"Subscribe to events for a specific agent using server-sent events.",operationId:"agent.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:{type:"object"}}}}}}),async e=>{let t=e.req.param("agentId");return streamSSE(e,async n=>{await n.writeSSE({data:JSON.stringify({type:"agent.connected",properties:{agentId:t}})});let o=pe.subscribeAll(async s=>{s.properties?.agentId===t&&await n.writeSSE({data:JSON.stringify(s)});});await new Promise(s=>{n.onAbort(()=>{o(),s();});});})}).get("/default",describeRoute({summary:"Get default agent",description:"Get the default agent configuration.",operationId:"agent.default",responses:{200:{description:"Default agent details",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(404)}}),async e=>{let t=await Ue.defaultAgent(),n=await Ue.get(t);return n?e.json(n):e.json({error:`Default agent not found: ${t}`},404)}).post("/",describeRoute({summary:"Create agent",description:"Create a new AI agent with specified configuration.",operationId:"agent.create",responses:{201:{description:"Agent created successfully",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(400),...Te(404)}}),validator("json",N.object({name:N.string(),mode:N.enum(["subagent","primary","all"]).optional(),permission:N.record(N.string(),N.any()).optional(),description:N.string().optional(),prompt:N.string().optional(),model:N.object({providerId:N.string(),modelId:N.string()}).optional(),temperature:N.number().optional(),topP:N.number().optional(),color:N.string().optional(),hidden:N.boolean().optional(),variant:N.string().optional(),steps:N.number().int().positive().optional(),options:N.record(N.string(),N.any()).optional()})),async e=>{let t=e.req.valid("json");try{if(!t.name||t.name.trim()==="")return e.json({error:"Agent name is required"},400);if(await Ue.get(t.name))return e.json({error:`Agent "${t.name}" already exists`},400);let o={mode:t.mode||"primary"};t.description&&(o.description=t.description),t.prompt&&(o.prompt=t.prompt),t.model&&(o.model=`${t.model.providerId}/${t.model.modelId}`),t.temperature!==void 0&&(o.temperature=t.temperature),t.topP!==void 0&&(o.topP=t.topP),t.color&&(o.color=t.color),t.hidden!==void 0&&(o.hidden=t.hidden),t.variant&&(o.variant=t.variant),t.steps!==void 0&&(o.steps=t.steps),t.permission&&(o.permission=t.permission),t.options&&(o.options=t.options),await he.update({agent:{[t.name]:o}});let s=await Ue.get(t.name);return s?e.json(s,201):e.json({error:`Failed to retrieve created agent "${t.name}"`},500)}catch(n){let o=n instanceof Error?n.message:"Agent creation failed";return e.json({error:o},400)}}));var aa=a.create({service:"mdns"}),ca;(s=>{let e,t;function n(r,i){if(t!==r){e&&o();try{let c=i??"easbot.local",l=`easbot-${r}`;e=new IE;let d=e.publish({name:l,type:"http",host:c,port:r,txt:{path:"/"}});d.on("up",()=>{aa.info("mDNS service published",{name:l,port:r});}),d.on("error",m=>{aa.error("mDNS service error",{error:m});}),t=r;}catch(c){if(aa.error("mDNS publish failed",{error:c}),e)try{e.destroy();}catch{}e=void 0,t=void 0;}}}s.publish=n;function o(){if(e){try{e.unpublishAll(),e.destroy();}catch(r){aa.error("mDNS unpublish failed",{error:r});}e=void 0,t=void 0,aa.info("mDNS service unpublished");}}s.unpublish=o;})(ca||(ca={}));globalThis.AI_SDK_LOG_WARNINGS=false;var da;(f=>{let e=a.create({service:"server"}),t=compress(),n=(a,p)=>!!(a==="/event"||a==="/global/event"||a==="/global/sync-event"||p==="POST"&&/\/session\/[^/]+\/(message|prompt_async)$/.test(a)),o,s=[];function r(){return o??new URL("http://localhost:4096")}f.url=r;let i=new Hono;f.App=lazy(()=>i.onError((a,p)=>{if(e.error("failed",{error:a}),a instanceof NamedError){let h;return a instanceof a$6.NotFoundError?h=404:a instanceof xe.ModelNotFoundError||a.name==="ProviderAuthValidationFailed"||a.name.startsWith("Worktree")?h=400:h=500,p.json(a.toObject(),{status:h})}if(a instanceof HTTPException)return a.getResponse();let u=a instanceof Error&&a.stack?a.stack:a.toString();return p.json(new NamedError.Unknown({message:u}).toObject(),{status:500})}).use((a,p)=>{if(a.req.method==="OPTIONS")return p();let u=a$2.EASBOT_SERVER_PASSWORD;if(!u)return p();let h=a$2.EASBOT_SERVER_USERNAME??"easbot";return basicAuth({username:h,password:u})(a,p)}).use(async(a,p)=>{let u=a.req.path==="/log";u||e.info("request",{method:a.req.method,path:a.req.path});let h=e.time("request",{method:a.req.method,path:a.req.path});await p(),u||h.stop();}).use(cors({maxAge:86400,origin(a){if(a&&(a.startsWith("http://localhost:")||a.startsWith("http://127.0.0.1:")||a==="tauri://localhost"||a==="http://tauri.localhost"||a==="https://tauri.localhost"||/^https:\/\/([a-z0-9-]+\.)*easbot\.ai$/.test(a)||s.includes(a)))return a}})).use((a,p)=>n(a.req.path,a.req.method)?p():t(a,p)).route("/global",sy()).put("/auth/:providerId",describeRoute({summary:"Set auth credentials",description:"Set authentication credentials",operationId:"auth.set",responses:{200:{description:"Successfully set authentication credentials",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("param",N.object({providerId:N.string()})),validator("json",Qe.Info),async a=>{let p=a.req.valid("param").providerId,u=a.req.valid("json");return await Qe.set(p,u),a.json(true)}).delete("/auth/:providerId",describeRoute({summary:"Remove auth credentials",description:"Remove authentication credentials",operationId:"auth.remove",responses:{200:{description:"Successfully removed authentication credentials",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("param",N.object({providerId:N.string()})),async a=>{let p=a.req.valid("param").providerId;return await Qe.remove(p),a.json(true)}).use(async(a,p)=>{if(a.req.path==="/log")return p();let u=a.req.query("directory")||a.req.header("x-easbot-directory")||process.cwd(),h=Filesystem.resolve((()=>{try{return decodeURIComponent(u)}catch{return u}})());return R.provide({directory:h,init:na,async fn(){return p()}})}).get("/doc",openAPIRouteHandler(i,{documentation:{info:{title:"easbot",version:"0.0.3",description:"easbot api"},openapi:"3.1.1"}})).use(validator("query",N.object({directory:N.string().optional(),workspace:N.string().optional()}))).route("/project",Lh()).route("/pty",Nh()).route("/config",Hh()).route("/experimental",Wh()).route("/session",Fh()).route("/permission",ny()).route("/question",Qh()).route("/provider",Kh()).route("/model",Xh()).route("/",zh()).route("/mcp",Uh()).route("/agent",ry()).route("/tui",_h()).post("/instance/dispose",describeRoute({summary:"Dispose instance",description:"Clean up and dispose the current EasBot instance, releasing all resources.",operationId:"instance.dispose",responses:{200:{description:"Instance disposed",content:{"application/json":{schema:resolver(N.boolean())}}}}}),async a=>(await R.dispose(),a.json(true))).get("/path",describeRoute({summary:"Get paths",description:"Retrieve the current working directory and related path information for the EasBot instance.",operationId:"path.get",responses:{200:{description:"Path",content:{"application/json":{schema:resolver(N.object({home:N.string(),state:N.string(),config:N.string(),worktree:N.string(),directory:N.string()}).meta({ref:"Path"}))}}}}}),async a=>a.json({home:a$1.Path.home,state:a$1.Path.state,config:a$1.Path.config,worktree:R.worktree,directory:R.directory})).get("/vcs",describeRoute({summary:"Get VCS info",description:"Retrieve version control system (VCS) information for the current project, such as git branch.",operationId:"vcs.get",responses:{200:{description:"VCS info",content:{"application/json":{schema:resolver(qs.Info)}}}}}),async a=>{let p=await qs.branch();return a.json({branch:p})}).get("/command",describeRoute({summary:"List commands",description:"Get a list of all available commands in the EasBot system.",operationId:"command.list",responses:{200:{description:"List of commands",content:{"application/json":{schema:resolver(vn.Info.array())}}}}}),validator("query",N.object({contextMode:N.string().optional()})),async a=>{let{contextMode:p}=a.req.valid("query"),u=await vn.list(p);return a.json(u)}).post("/log",describeRoute({summary:"Write log",description:"Write a log entry to the server logs with specified level and metadata.",operationId:"app.log",responses:{200:{description:"Log entry written successfully",content:{"application/json":{schema:resolver(N.boolean())}}},...Te(400)}}),validator("json",N.object({service:N.string().meta({description:"Service name for the log entry"}),level:N.enum(["debug","info","error","warn"]).meta({description:"Log level"}),message:N.string().meta({description:"Log message"}),extra:N.record(N.string(),N.any()).optional().meta({description:"Additional metadata for the log entry"})})),async a$1=>{let{service:p,level:u,message:h,extra:g}=a$1.req.valid("json"),I=a.create({service:p});switch(u){case "debug":I.debug(h,g);break;case "info":I.info(h,g);break;case "error":I.error(h,g);break;case "warn":I.warn(h,g);break}return a$1.json(true)}).get("/agent",describeRoute({summary:"List agents",description:"Get a list of all available AI agents in the EasBot system.",operationId:"app.agents",responses:{200:{description:"List of agents",content:{"application/json":{schema:resolver(Ue.Info.array())}}}}}),async a=>{let p=await Ue.list();return a.json(p)}).get("/skill",describeRoute({summary:"List skills",description:"Get a list of all available skills in the EasBot system.",operationId:"app.skills",responses:{200:{description:"List of skills",content:{"application/json":{schema:resolver(Vt.Info.array())}}}}}),async a=>{let p=await Vt.all();return a.json(p)}).get("/lsp",describeRoute({summary:"Get LSP status",description:"Get LSP server status",operationId:"lsp.status",responses:{200:{description:"LSP server status",content:{"application/json":{schema:resolver(We.Status.array())}}}}}),async a=>a.json(await We.status())).get("/formatter",describeRoute({summary:"Get formatter status",description:"Get formatter status",operationId:"formatter.status",responses:{200:{description:"Formatter status",content:{"application/json":{schema:resolver(xs.Status.array())}}}}}),async a=>a.json(await xs.status())).get("/event",describeRoute({summary:"Subscribe to events",description:"Get events",operationId:"event.subscribe",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(a$5.payloads())}}}}}),async a=>(e.info("event connected"),streamSSE(a,async p=>{p.writeSSE({data:JSON.stringify({type:"server.connected",properties:{}})});let u=pe.subscribeAll(async g=>{await p.writeSSE({data:JSON.stringify(g)}),g.type===pe.InstanceDisposed.type&&p.close();}),h=setInterval(()=>{p.writeSSE({data:JSON.stringify({type:"server.heartbeat",properties:{}})});},3e4);await new Promise(g=>{p.onAbort(()=>{clearInterval(h),u(),g(),e.info("event disconnected");});});}))).post("/event",describeRoute({summary:"Publish event",description:"Publish an event to the event bus",operationId:"event.publish",responses:{200:{description:"Event published successfully",content:{"application/json":{schema:resolver(N.boolean())}}}}}),validator("json",N.object({type:N.string(),properties:N.record(N.string(),N.any()).optional()})),async a=>{let p=a.req.valid("json"),u=a$5.define(p.type,N.record(N.string(),N.any()));return await pe.publish(u,p.properties??{}),a.json(true)}).get("/context",describeRoute({summary:"Get context info",description:"Retrieve context information including protocol metadata, workspace path, and agent name.",operationId:"app.context",responses:{200:{description:"Context information",content:{"application/json":{schema:resolver(N.object({protocolMetadata:N.object({agentId:N.string().optional(),workspace:N.string(),name:N.string(),userName:N.string(),mission:N.string(),preferredName:N.string().optional(),coreRelationship:N.string().optional(),coreValues:N.array(N.string()).optional(),behaviorStyle:N.string().optional(),decisionPrinciples:N.array(N.string()).optional()}),protocolInitialized:N.boolean()}))}}}}}),async a=>{let p=await mo.getContext();return a.json(p)}).all("/*",async a=>{let p=a.req.path,u=await proxy(`https://app.easbot.cn${p}`,{...a.req,headers:{...a.req.raw.headers,host:"app.easbot.cn"}});return u.headers.set("Content-Security-Policy","default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:"),u}));async function l(){return await generateSpecs((0, f.App)(),{documentation:{info:{title:"easbot",version:"1.0.0",description:"easbot api"},openapi:"3.1.1"}})}f.openapi=l;function d(a){s=a.cors??[];let p=createServer((b,w)=>{(0, f.App)().fetch;let v=new URL(b.url??"/",`http://${b.headers.host}`),C=new Headers;for(let[D,K]of Object.entries(b.headers))K&&C.set(D,Array.isArray(K)?K.join(", "):K);let E=new AbortController;b.on("close",()=>E.abort());let O=new Request(v,{method:b.method,headers:C,body:b.method!=="GET"&&b.method!=="HEAD"?b:void 0,signal:E.signal,duplex:"half"}),U=(0, f.App)().fetch(O);Promise.resolve(U).then(D=>{w.statusCode=D.status,w.statusMessage=D.statusText;for(let[K,X]of D.headers.entries())w.setHeader(K,X);D.body?D.body.pipeTo(new WritableStream({write(K){w.write(K);},close(){w.end();}})):w.end();}).catch(D=>{e.error("Server error",{error:D.message}),w.statusCode=500,w.end("Internal Server Error");});}),u=b=>{try{return p.listen(b,a.hostname),!0}catch{return false}},h=a.port===0?u(4096)?4096:u(0)?p.address().port:null:u(a.port)?a.port:null;if(h===null)throw new Error(`Failed to start server on port ${a.port}`);let g=p.address(),I=typeof g=="object"&&g?g.port:h,T=a.hostname==="0.0.0.0"?"localhost":a.hostname;o=new URL(`http://${T}:${I}`);let y=a.mdns&&I&&a.hostname!=="127.0.0.1"&&a.hostname!=="localhost"&&a.hostname!=="::1";return y?ca.publish(I,a.mdnsDomain):a.mdns&&e.warn("mDNS enabled but hostname is loopback; skipping mDNS publish"),{url:o,port:I,stop:async b=>(y&&ca.unpublish(),new Promise(w=>{p.close(()=>{w();});})),raw:p}}f.listen=d,f.Default=f.App;})(da||(da={}));var ip=a.create({service:"plugin.codex"}),ua="app_EMoamEEZ73f0CkXaXp7hrann",ps="https://auth.openai.com",LE="https://chatgpt.com/backend-api/codex/responses",Ks=1455,DE=3e3;async function $E(){let e=FE(43),n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n),s=dy(o);return {verifier:e,challenge:s}}function FE(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=crypto.getRandomValues(new Uint8Array(e));return Array.from(n).map(o=>t[o%t.length]).join("")}function dy(e){let t=new Uint8Array(e),n=String.fromCharCode(...t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function NE(){return dy(crypto.getRandomValues(new Uint8Array(32)).buffer)}function ay(e){let t=e.split(".");if(t.length===3)try{let n=t[1];return n?JSON.parse(Buffer.from(n,"base64url").toString()):void 0}catch{return}}function cy(e){return e.chatgpt_account_id||e["https://api.openai.com/auth"]?.chatgpt_account_id||e.organizations?.[0]?.id}function sp(e){if(e.id_token){let t=ay(e.id_token),n=t&&cy(t);if(n)return n}if(e.access_token){let t=ay(e.access_token);return t?cy(t):void 0}}function UE(e,t,n){let o=new URLSearchParams({response_type:"code",client_id:ua,redirect_uri:e,scope:"openid profile email offline_access",code_challenge:t.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:n,originator:"easbot"});return `${ps}/oauth/authorize?${o.toString()}`}async function zE(e,t,n){let o=await fetch(`${ps}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:t,client_id:ua,code_verifier:n.verifier}).toString()});if(!o.ok)throw new Error(`Token exchange failed: ${o.status}`);return o.json()}async function qE(e){let t=await fetch(`${ps}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:ua}).toString()});if(!t.ok)throw new Error(`Token refresh failed: ${t.status}`);return t.json()}var HE=`<!doctype html>
|
|
889
|
+
<html>
|
|
890
|
+
<head>
|
|
891
|
+
<title>EasBot - Codex Authorization Successful</title>
|
|
892
|
+
<style>
|
|
893
|
+
body {
|
|
894
|
+
font-family:
|
|
895
|
+
system-ui,
|
|
896
|
+
-apple-system,
|
|
897
|
+
sans-serif;
|
|
898
|
+
display: flex;
|
|
899
|
+
justify-content: center;
|
|
900
|
+
align-items: center;
|
|
901
|
+
height: 100vh;
|
|
902
|
+
margin: 0;
|
|
903
|
+
background: #131010;
|
|
904
|
+
color: #f1ecec;
|
|
905
|
+
}
|
|
906
|
+
.container {
|
|
907
|
+
text-align: center;
|
|
908
|
+
padding: 2rem;
|
|
909
|
+
}
|
|
910
|
+
h1 {
|
|
911
|
+
color: #f1ecec;
|
|
912
|
+
margin-bottom: 1rem;
|
|
913
|
+
}
|
|
914
|
+
p {
|
|
915
|
+
color: #b7b1b1;
|
|
916
|
+
}
|
|
917
|
+
</style>
|
|
918
|
+
</head>
|
|
919
|
+
<body>
|
|
920
|
+
<div class="container">
|
|
921
|
+
<h1>Authorization Successful</h1>
|
|
922
|
+
<p>You can close this window and return to EasBot.</p>
|
|
923
|
+
</div>
|
|
924
|
+
<script>
|
|
925
|
+
setTimeout(() => window.close(), 2000)
|
|
926
|
+
</script>
|
|
927
|
+
</body>
|
|
928
|
+
</html>`,rp=e=>`<!doctype html>
|
|
929
|
+
<html>
|
|
930
|
+
<head>
|
|
931
|
+
<title>EasBot - Codex Authorization Failed</title>
|
|
932
|
+
<style>
|
|
933
|
+
body {
|
|
934
|
+
font-family:
|
|
935
|
+
system-ui,
|
|
936
|
+
-apple-system,
|
|
937
|
+
sans-serif;
|
|
938
|
+
display: flex;
|
|
939
|
+
justify-content: center;
|
|
940
|
+
align-items: center;
|
|
941
|
+
height: 100vh;
|
|
942
|
+
margin: 0;
|
|
943
|
+
background: #131010;
|
|
944
|
+
color: #f1ecec;
|
|
945
|
+
}
|
|
946
|
+
.container {
|
|
947
|
+
text-align: center;
|
|
948
|
+
padding: 2rem;
|
|
949
|
+
}
|
|
950
|
+
h1 {
|
|
951
|
+
color: #fc533a;
|
|
952
|
+
margin-bottom: 1rem;
|
|
953
|
+
}
|
|
954
|
+
p {
|
|
955
|
+
color: #b7b1b1;
|
|
956
|
+
}
|
|
957
|
+
.error {
|
|
958
|
+
color: #ff917b;
|
|
959
|
+
font-family: monospace;
|
|
960
|
+
margin-top: 1rem;
|
|
961
|
+
padding: 1rem;
|
|
962
|
+
background: #3c140d;
|
|
963
|
+
border-radius: 0.5rem;
|
|
964
|
+
}
|
|
965
|
+
</style>
|
|
966
|
+
</head>
|
|
967
|
+
<body>
|
|
968
|
+
<div class="container">
|
|
969
|
+
<h1>Authorization Failed</h1>
|
|
970
|
+
<p>An error occurred during authorization.</p>
|
|
971
|
+
<div class="error">${e}</div>
|
|
972
|
+
</div>
|
|
973
|
+
</body>
|
|
974
|
+
</html>`,la,Cn;async function BE(){return la?{port:Ks,redirectUri:`http://localhost:${Ks}/auth/callback`}:(la=serve({port:Ks,fetch(e){let t=new URL(e.url);if(t.pathname==="/auth/callback"){let n=t.searchParams.get("code"),o=t.searchParams.get("state"),s=t.searchParams.get("error"),r=t.searchParams.get("error_description");if(s){let c=r||s;return Cn?.reject(new Error(c)),Cn=void 0,new Response(rp(c),{headers:{"Content-Type":"text/html"}})}if(!n){let c="Missing authorization code";return Cn?.reject(new Error(c)),Cn=void 0,new Response(rp(c),{status:400,headers:{"Content-Type":"text/html"}})}if(!Cn||o!==Cn.state){let c="Invalid state - potential CSRF attack";return Cn?.reject(new Error(c)),Cn=void 0,new Response(rp(c),{status:400,headers:{"Content-Type":"text/html"}})}let i=Cn;return Cn=void 0,zE(n,`http://localhost:${Ks}/auth/callback`,i.pkce).then(c=>i.resolve(c)).catch(c=>i.reject(c)),new Response(HE,{headers:{"Content-Type":"text/html"}})}return t.pathname==="/cancel"?(Cn?.reject(new Error("Login cancelled")),Cn=void 0,new Response("Login cancelled",{status:200})):new Response("Not found",{status:404})}}),ip.info("codex oauth server started",{port:Ks}),{port:Ks,redirectUri:`http://localhost:${Ks}/auth/callback`})}function GE(){la&&(la.close(),la=void 0,ip.info("codex oauth server stopped"));}function WE(e,t){return new Promise((n,o)=>{let s=setTimeout(()=>{Cn&&(Cn=void 0,o(new Error("OAuth callback timeout - authorization took too long")));},3e5);Cn={pkce:e,state:t,resolve:r=>{clearTimeout(s),n(r);},reject:r=>{clearTimeout(s),o(r);}};})}async function ly(e){return {auth:{provider:"openai",loader:async(t,n)=>{if((await t()).type!=="oauth")return {};let s=new Set(["gpt-5.1-codex-max","gpt-5.1-codex-mini","gpt-5.2","gpt-5.2-codex","gpt-5.3-codex","gpt-5.1-codex"]);for(let r of Object.keys(n.models))s.has(r)||delete n.models[r];if(!n.models["gpt-5.3-codex"]){let r={id:"gpt-5.3-codex",providerId:"openai",api:{id:"gpt-5.3-codex",url:"https://chatgpt.com/backend-api/codex",npm:"@ai-sdk/openai"},name:"GPT-5.3 Codex",capabilities:{temperature:false,reasoning:true,attachment:true,toolcall:true,input:{text:true,audio:false,image:true,video:false,pdf:false},output:{text:true,audio:false,image:false,video:false,pdf:false},interleaved:false},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:4e5,input:272e3,output:128e3},status:"active",options:{},headers:{},release_date:"2026-02-05",variants:{},family:"gpt-codex"};r.variants=wt.variants(r),n.models["gpt-5.3-codex"]=r;}for(let r of Object.values(n.models))r.cost={input:0,output:0,cache:{read:0,write:0}};return {apiKey:Fp,async fetch(r,i){i?.headers&&(i.headers instanceof Headers?(i.headers.delete("authorization"),i.headers.delete("Authorization")):Array.isArray(i.headers)?i.headers=i.headers.filter(([a])=>a.toLowerCase()!=="authorization"):(delete i.headers.authorization,delete i.headers.Authorization));let c=await t();if(c.type!=="oauth")return fetch(r,i);let l=c;if(!c.access||c.expires<Date.now()){ip.info("refreshing codex access token");let a=await qE(c.refresh),p=sp(a)||l.accountId;await e.client.auth.set({providerId:"openai",auth:{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+(a.expires_in??3600)*1e3,...p&&{accountId:p}}}),c.access=a.access_token,l.accountId=p;}let d=new Headers;if(i?.headers)if(i.headers instanceof Headers)i.headers.forEach((a,p)=>{d.set(p,a);});else if(Array.isArray(i.headers))for(let[a,p]of i.headers)p!==void 0&&d.set(a,String(p));else for(let[a,p]of Object.entries(i.headers))p!==void 0&&d.set(a,String(p));d.set("authorization",`Bearer ${c.access}`),l.accountId&&d.set("ChatGPT-Account-Id",l.accountId);let m=r instanceof URL?r:new URL(typeof r=="string"?r:r.url),f=m.pathname.includes("/v1/responses")||m.pathname.includes("/chat/completions")?new URL(LE):m;return fetch(f,{...i,headers:d})}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:t}=await BE(),n=await $E(),o=NE(),s=UE(t,n,o),r=WE(n,o);return {url:s,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{let i=await r;GE();let c=sp(i);return {type:"success",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+(i.expires_in??3600)*1e3,accountId:c}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let t=await fetch(`${ps}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({client_id:ua})});if(!t.ok)throw new Error("Failed to initiate device authorization");let n=await t.json(),o=Math.max(parseInt(n.interval,10)||5,1)*1e3;return {url:`${ps}/codex/device`,instructions:`Enter code: ${n.user_code}`,method:"auto",async callback(){for(;;){let s=await fetch(`${ps}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({device_auth_id:n.device_auth_id,user_code:n.user_code})});if(s.ok){let r=await s.json(),i=await fetch(`${ps}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r.authorization_code,redirect_uri:`${ps}/deviceauth/callback`,client_id:ua,code_verifier:r.code_verifier}).toString()});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);let c=await i.json();return {type:"success",refresh:c.refresh_token,access:c.access_token,expires:Date.now()+(c.expires_in??3600)*1e3,accountId:sp(c)}}if(s.status!==403&&s.status!==404)return {type:"failed"};await new Promise(r=>setTimeout(r,o+DE));}}}}},{label:"Manually enter API Key",type:"api"}]},"llm.headers":async(t,n)=>{t.model&&t.model.providerId==="openai"&&(t.headers??(t.headers={}),t.headers.originator="easbot",t.headers["User-Agent"]=`easbot/${b$3.getVersion()} (${ec.platform()} ${ec.release()}; ${ec.arch()})`,t.headers.session_id=t.sessionId,n.modified=true,n.input=t);}}}var uy="Ov23li8tweQw6odWQebz",ap=3e3;function py(e){return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}function KE(e){return {DEVICE_CODE_URL:`https://${e}/login/device/code`,ACCESS_TOKEN_URL:`https://${e}/login/oauth/access_token`}}async function my(e){let t=e.client;return {auth:{provider:"github-copilot",async loader(n,o){let s=await n();if(!s||s.type!=="oauth")return {};let r=s.enterpriseUrl,i=r?`https://copilot-api.${py(r)}`:void 0;if(o?.models)for(let c of Object.values(o.models))c.cost={input:0,output:0,cache:{read:0,write:0}},c.api.npm="@ai-sdk/github-copilot";return {baseURL:i,apiKey:"",async fetch(c,l){let d=await n();if(d.type!=="oauth")return fetch(c,l);let m=c instanceof URL?c.href:c.toString(),{isVision:f,isAgent:a}=iife(()=>{try{let u=typeof l?.body=="string"?JSON.parse(l.body):l?.body;if(u?.messages&&m.includes("completions")){let h=u.messages[u.messages.length-1];return {isVision:u.messages.some(g=>Array.isArray(g.content)&&g.content.some(I=>I.type==="image_url")),isAgent:h?.role!=="user"}}if(u?.input){let h=u.input[u.input.length-1];return {isVision:u.input.some(g=>Array.isArray(g?.content)&&g.content.some(I=>I.type==="input_image")),isAgent:h?.role!=="user"}}if(u?.messages){let h=u.messages[u.messages.length-1],g=Array.isArray(h?.content)&&h.content.some(I=>I?.type!=="tool_result");return {isVision:u.messages.some(I=>Array.isArray(I?.content)&&I.content.some(T=>T?.type==="image"||T?.type==="tool_result"&&Array.isArray(T?.content)&&T.content.some(y=>y?.type==="image"))),isAgent:!(h?.role==="user"&&g)}}}catch{}return {isVision:false,isAgent:false}}),p={"x-initiator":a?"agent":"user",...l?.headers,"User-Agent":`easbot/${b$3.getVersion()}`,Authorization:`Bearer ${d.refresh}`,"Openai-Intent":"conversation-edits"};return f&&(p["Copilot-Vision-Request"]="true"),delete p["x-api-key"],delete p.authorization,fetch(c,{...l,headers:p})}}},methods:[{type:"oauth",label:"Login with GitHub Copilot",prompts:[{type:"select",key:"deploymentType",message:"Select GitHub deployment type",options:[{label:"GitHub.com",value:"github.com",hint:"Public"},{label:"GitHub Enterprise",value:"enterprise",hint:"Data residency or self-hosted"}]},{type:"text",key:"enterpriseUrl",message:"Enter your GitHub Enterprise URL or domain",placeholder:"company.ghe.com or https://company.ghe.com",condition:n=>n.deploymentType==="enterprise",validate:n=>{if(!n)return "URL or domain is required";try{return (n.includes("://")?new URL(n):new URL(`https://${n}`)).hostname?void 0:"Please enter a valid URL or domain"}catch{return "Please enter a valid URL (e.g., company.ghe.com or https://company.ghe.com)"}}}],async authorize(n={}){let o=n.deploymentType||"github.com",s="github.com",r="github-copilot";if(o==="enterprise"){let d=n.enterpriseUrl;s=py(d),r="github-copilot-enterprise";}let i=KE(s),c=await fetch(i.DEVICE_CODE_URL,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({client_id:uy,scope:"read:user"})});if(!c.ok)throw new Error("Failed to initiate device authorization");let l=await c.json();return {url:l.verification_uri,instructions:`Enter code: ${l.user_code}`,method:"auto",async callback(){for(;;){let d=await fetch(i.ACCESS_TOKEN_URL,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({client_id:uy,device_code:l.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!d.ok)return {type:"failed"};let m=await d.json();if(m.access_token){let f={type:"success",refresh:m.access_token,access:m.access_token,expires:0};return r==="github-copilot-enterprise"&&(f.provider="github-copilot-enterprise",f.enterpriseUrl=s),f}if(m.error==="authorization_pending"){await new Promise(f=>setTimeout(f,l.interval*1e3+ap));continue}if(m.error==="slow_down"){let f=(l.interval+5)*1e3,a=m.interval;a&&typeof a=="number"&&a>0&&(f=a*1e3),await new Promise(p=>setTimeout(p,f+ap));continue}if(m.error)return {type:"failed"};await new Promise(f=>setTimeout(f,l.interval*1e3+ap));}}}}}]},"llm.headers":async(n,o)=>{!n.model||typeof n.model=="string"||!n.model.providerId.includes("github-copilot")||(n.headers??(n.headers={}),"api"in n.model&&typeof n.model.api=="object"&&n.model.api?.npm==="@ai-sdk/anthropic"&&(n.headers["anthropic-beta"]="interleaved-thinking-2025-05-14"),!(await t.session.get({sessionId:n.sessionId}).catch(()=>{}))?.data?.parentId)||(n.headers["x-initiator"]="agent",o.modified=true,o.input=n);}}}var ls;(m=>{let e=a.create({service:"plugin"}),t=[],n=[ly,my],o;function s(f){if(f.hooks&&Array.isArray(f.hooks))for(let a of f.hooks)Le.registerMatcher(a),e.debug("registered plugin hook matcher to Hook system",{event:a.event,hookCount:a.hooks.length});}async function r(f){if(f.tool&&Object.keys(f.tool).length>0)for(let[a,p]of Object.entries(f.tool))await Un.register({id:a,init:async()=>({parameters:N.object(p.args),description:p.description,execute:async(u,h)=>{if(!p.execute)throw new Error(`Tool ${a} does not have an execute function`);let g={...h,directory:R.directory,worktree:R.worktree};return await p.execute(u,g)}})}),e.debug("registered plugin tool to Tool system",{toolId:a});}function i(){return o||(o=R.state(async()=>{let f=createEasbotClient({baseUrl:"http://localhost:4096",directory:R.directory,fetch:async(...g)=>da.App().fetch(...g)}),a=await he.get(),p=[],u={client:f,project:R.project,worktree:R.worktree,directory:R.directory,serverUrl:da.url(),$:shell};for(let g of n){e.info("loading internal plugin",{name:g.name});let I=await g(u).catch(T=>{e.error("failed to load internal plugin",{name:g.name,error:T});});I&&(p.push(I),s(I),await r(I));}let h=a.plugin??[];h.length>0&&await he.waitForDependencies(),a$2.EASBOT_DISABLE_DEFAULT_PLUGINS||(h=[...t,...h]);for(let g of h)if(!(g.includes("easbot-openai-codex-auth")||g.includes("easbot-copilot-auth"))){if(e.info("loading plugin",{path:g}),!g.startsWith("file://")){let I=g.lastIndexOf("@"),T=I>0?g.substring(0,I):g,y=I>0?g.substring(I+1):"latest",x=t.some(b=>b.startsWith(T+"@"));if(g=await Shell.install(T,y).catch(b=>{if(!x)throw b;let w=b instanceof Error?b.message:String(b);return e.error("failed to install builtin plugin",{pkg:T,version:y,error:w}),pe.publish(Y.Event.Error,{error:new NamedError.Unknown({message:`Failed to install built-in plugin ${T}@${y}: ${w}`}).toObject()}).catch(k=>{e.error("failed to publish error event",{error:k});}),""}),!g)continue}await import(g).then(async I=>{let T=new Set;for(let[y,x]of Object.entries(I)){if(T.has(x))continue;T.add(x);let b=await x(u);p.push(b),s(b),await r(b);}}).catch(I=>{let T=I instanceof Error?I.message:String(I);e.error("failed to load plugin",{path:g,error:T}),pe.publish(Y.Event.Error,{error:new NamedError.Unknown({message:`Failed to load plugin ${g}: ${T}`}).toObject()}).catch(y=>{e.error("failed to publish error event",{error:y});});});}return {plugins:p,input:u}})),o}function c(){return i()()}async function l(){return c().then(f=>f.plugins)}m.list=l;async function d(){await Le.init(),await vn.init(),await Un.init();let f=await c().then(p=>p.plugins),a=await he.get();for(let p of f)await p.config?.(a);pe.subscribeAll(async p=>{let u=await c().then(h=>h.plugins);for(let h of u)h.event?.({event:p});});}m.init=d;})(ls||(ls={}));var nR={"@ai-sdk/amazon-bedrock":()=>import('@ai-sdk/amazon-bedrock').then(e=>e.createAmazonBedrock),"@ai-sdk/anthropic":()=>import('@ai-sdk/anthropic').then(e=>e.createAnthropic),"@ai-sdk/azure":()=>import('@ai-sdk/azure').then(e=>e.createAzure),"@ai-sdk/google":()=>import('@ai-sdk/google').then(e=>e.createGoogleGenerativeAI),"@ai-sdk/google-vertex":()=>import('@ai-sdk/google-vertex').then(e=>e.createVertex),"@ai-sdk/google-vertex/anthropic":()=>import('@ai-sdk/google-vertex/anthropic').then(e=>e.createVertexAnthropic),"@ai-sdk/openai":()=>import('@ai-sdk/openai').then(e=>e.createOpenAI),"@ai-sdk/openai-compatible":()=>import('@ai-sdk/openai-compatible').then(e=>e.createOpenAICompatible),"@openrouter/ai-sdk-provider":()=>import('@openrouter/ai-sdk-provider').then(e=>e.createOpenRouter),"@ai-sdk/xai":()=>import('@ai-sdk/xai').then(e=>e.createXai),"@ai-sdk/mistral":()=>import('@ai-sdk/mistral').then(e=>e.createMistral),"@ai-sdk/groq":()=>import('@ai-sdk/groq').then(e=>e.createGroq),"@ai-sdk/deepinfra":()=>import('@ai-sdk/deepinfra').then(e=>e.createDeepInfra),"@ai-sdk/cerebras":()=>import('@ai-sdk/cerebras').then(e=>e.createCerebras),"@ai-sdk/cohere":()=>import('@ai-sdk/cohere').then(e=>e.createCohere),"@ai-sdk/gateway":()=>import('@ai-sdk/gateway').then(e=>e.createGateway),"@ai-sdk/togetherai":()=>import('@ai-sdk/togetherai').then(e=>e.createTogetherAI),"@ai-sdk/perplexity":()=>import('@ai-sdk/perplexity').then(e=>e.createPerplexity),"@ai-sdk/vercel":()=>import('@ai-sdk/vercel').then(e=>e.createVercel),"@ai-sdk/alibaba":()=>import('@ai-sdk/alibaba').then(e=>e.createAlibaba),"@ai-sdk/deepseek":()=>import('@ai-sdk/deepseek').then(e=>e.createDeepSeek),"gitlab-ai-provider":()=>import('gitlab-ai-provider').then(e=>e.createGitLab),"@ai-sdk/github-copilot":()=>import('./copilot-I52DJYYX.mjs').then(e=>e.createOpenaiCompatible),"@easbot/ollama-sdk":()=>import('@easbot/ollama-sdk').then(e=>e.createOllama),"@easbot/local-model-sdk":()=>import('@easbot/local-model-sdk').then(e=>e.createLocal)},xe;($=>{$.DEFAULT_CONTEXT_LIMIT=2e5,$.DEFAULT_INPUT_LIMIT_RATIO=.9,$.DEFAULT_OUTPUT_LIMIT=8192;function o(M=2e5){return Math.floor(M*.9)}$.getDefaultInputLimit=o;let s=a.create({service:"provider"});function r(M){let A=/^gpt-(\d+)/.exec(M);return A?Number(A[1])>=5:false}function i(M){return r(M)&&!M.startsWith("gpt-5-mini")}let c$1={async anthropic(){return {autoload:false,options:{headers:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"}}}},async opencode(M){let A=await(async()=>{let L=await tt.all();return !!(M.env.some(P=>L[P])||await Qe.get(M.id)||(await he.get()).provider?.opencode?.options?.apiKey)})();if(!A)for(let[L,S]of Object.entries(M.models))S.cost.input!==0&&delete M.models[L];return {autoload:Object.keys(M.models).length>0,options:A?{}:{apiKey:"public"}}},openai:async()=>{let M=await tt.get("OPENAI_BASE_URL");return {autoload:false,async getModel(A,L,S){return A.responses(L)},options:M?{baseURL:M}:{}}},"github-copilot":async()=>({autoload:false,async getModel(M,A,L){return M.responses===void 0&&M.chat===void 0?M.languageModel(A):i(A)?M.responses(A):M.chat(A)},options:{}}),"github-copilot-enterprise":async()=>({autoload:false,async getModel(M,A,L){return M.responses===void 0&&M.chat===void 0?M.languageModel(A):i(A)?M.responses(A):M.chat(A)},options:{}}),azure:async()=>({autoload:false,async getModel(M,A,L){return L?.useCompletionUrls?M.chat(A):M.responses(A)},options:{}}),"azure-cognitive-services":async()=>{let M=tt.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return {autoload:false,async getModel(A,L,S){return S?.useCompletionUrls?A.chat(L):A.responses(L)},options:{baseURL:M?`https://${M}.cognitiveservices.azure.com/openai`:void 0}}},"amazon-bedrock":async()=>{let A=(await he.get()).provider?.["amazon-bedrock"],L=await Qe.get("amazon-bedrock"),S=A?.options?.region,P=tt.get("AWS_REGION"),_=S??P??"us-east-1",j=A?.options?.profile,B=tt.get("AWS_PROFILE"),Z=j??B,ee=tt.get("AWS_ACCESS_KEY_ID"),se=iife(()=>{let Q=process.env.AWS_BEARER_TOKEN_BEDROCK;if(Q)return Q;if(L?.type==="api")return process.env.AWS_BEARER_TOKEN_BEDROCK=L.key,L.key}),le=tt.get("AWS_WEB_IDENTITY_TOKEN_FILE"),ae=!!(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!Z&&!ee&&!se&&!le&&!ae)return {autoload:false};let we={region:_};if(!se){let Q=await Shell.install("@aws-sdk/credential-providers"),{pathToFileURL:H}=await import('url'),F=Se__default.join(Q,"dist-cjs","index.js"),{fromNodeProviderChain:te}=await import(H(F).href),V=Z?{profile:Z}:{};we.credentialProvider=te(V);}let re=A?.options?.endpoint??A?.options?.baseURL;return re&&(we.baseURL=re),{autoload:true,options:we,async getModel(Q,H,F){if(["global.","us.","eu.","jp.","apac.","au."].some(oe=>H.startsWith(oe)))return Q.languageModel(H);let V=F?.region??_,J=V.split("-")[0];switch(J){case "us":{let oe=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some(me=>H.includes(me)),de=V.startsWith("us-gov");oe&&!de&&(H=`${J}.${H}`);break}case "eu":{let oe=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some(me=>V.includes(me)),de=["claude","nova-lite","nova-micro","llama3","pixtral"].some(me=>H.includes(me));oe&&de&&(H=`${J}.${H}`);break}case "ap":{let oe=["ap-southeast-2","ap-southeast-4"].includes(V),de=V==="ap-northeast-1";oe&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some(me=>H.includes(me))?(J="au",H=`${J}.${H}`):de?["claude","nova-lite","nova-micro","nova-pro"].some(ce=>H.includes(ce))&&(J="jp",H=`${J}.${H}`):["claude","nova-lite","nova-micro","nova-pro"].some(ce=>H.includes(ce))&&(J="apac",H=`${J}.${H}`);break}}return Q.languageModel(H)}}},nvidia:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.ai/","X-Title":"easbot"}}}),openrouter:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.cn/","X-Title":"easbot"}}}),vercel:async()=>({autoload:false,options:{headers:{"http-referer":"https://easbot.cn/","x-title":"easbot"}}}),"google-vertex":async()=>{let M=await tt.get("GOOGLE_CLOUD_PROJECT")??tt.get("GCP_PROJECT")??tt.get("GCLOUD_PROJECT"),A=await tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"us-east5";return !M?{autoload:false}:{autoload:true,vars(S){let P=A==="global"?"aiplatform.googleapis.com":`${A}-aiplatform.googleapis.com`;return {...M&&{GOOGLE_VERTEX_PROJECT:M},GOOGLE_VERTEX_LOCATION:A,GOOGLE_VERTEX_ENDPOINT:P}},options:{project:M,location:A,fetch:async(S,P)=>{let{GoogleAuth:_}=await import('google-auth-library'),Z=await(await new _().getApplicationDefault()).credential.getAccessToken(),ee=new Headers(P?.headers);return ee.set("Authorization",`Bearer ${Z.token}`),fetch(S,{...P,headers:ee})}},async getModel(S,P){let _=String(P).trim();return S.languageModel(_)}}},"google-vertex-anthropic":async()=>{let M=tt.get("GOOGLE_CLOUD_PROJECT")??tt.get("GCP_PROJECT")??tt.get("GCLOUD_PROJECT"),A=tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"global";return !M?{autoload:false}:{autoload:true,options:{project:M,location:A},async getModel(S,P){let _=String(P).trim();return S.languageModel(_)}}},"sap-ai-core":async()=>{let M=await Qe.get("sap-ai-core"),A=iife(()=>{let P=process.env.AICORE_SERVICE_KEY;if(P)return P;if(M?.type==="api")return process.env.AICORE_SERVICE_KEY=M.key,M.key}),L=process.env.AICORE_DEPLOYMENT_ID,S=process.env.AICORE_RESOURCE_GROUP;return {autoload:!!A,options:A?{deploymentId:L,resourceGroup:S}:{},async getModel(P,_){return P(_)}}},zenmux:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.cn/","X-Title":"easbot"}}}),gitlab:async M=>{let A=tt.get("GITLAB_INSTANCE_URL")||"https://gitlab.com",L=await Qe.get(M.id),S=await(async()=>L?.type==="oauth"?L.access:L?.type==="api"?L.key:tt.get("GITLAB_TOKEN"))(),_=(await he.get()).provider?.gitlab,{VERSION:j,createGitLab:B}=await import('gitlab-ai-provider'),Z={"User-Agent":`easbot/${b$3.getVersion()} gitlab-ai-provider/${j} (${ec.platform()} ${ec.release()}; ${ec.arch()})`,..._?.options?.aiGatewayHeaders||{}};return {autoload:!!S,options:{instanceUrl:A,apiKey:S,aiGatewayHeaders:Z,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,..._?.options?.featureFlags||{}}},async getModel(ee,se){return ee.agenticChat(se,{aiGatewayHeaders:Z,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,..._?.options?.featureFlags||{}}})}}},"cloudflare-workers-ai":async M=>{let A=tt.get("CLOUDFLARE_ACCOUNT_ID");if(!A)return {autoload:false};let L=await iife(async()=>{let S=tt.get("CLOUDFLARE_API_KEY");if(S)return S;let P=await Qe.get(M.id);if(P?.type==="api")return P.key});return {autoload:!!L,options:{apiKey:L,baseURL:`https://api.cloudflare.com/client/v4/accounts/${A}/ai/v1`},async getModel(S,P){return S.languageModel(P)}}},"cloudflare-ai-gateway":async M=>{let A=await tt.get("CLOUDFLARE_ACCOUNT_ID"),L=await tt.get("CLOUDFLARE_GATEWAY_ID");if(!A||!L)return {autoload:false};let S=await(async()=>{let Z=await tt.get("CLOUDFLARE_API_TOKEN")||await tt.get("CF_AIG_TOKEN");if(Z)return Z;let ee=await Qe.get(M.id);if(ee?.type==="api")return ee.key})();if(!S)throw new Error("CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. Set it via environment variable or run `easbot auth cloudflare-ai-gateway`.");let{createAiGateway:P}=await import('ai-gateway-provider'),{createUnified:_}=await import('ai-gateway-provider/providers/unified'),j=P({accountId:A,gateway:L,apiKey:S}),B=_();return {autoload:true,async getModel(Z,ee,se){return j(B(ee))},options:{}}},cerebras:async()=>({autoload:false,options:{headers:{"X-Cerebras-3rd-Party-Integration":"easbot"}}}),ollama:async()=>{let M=await tt.get("OLLAMA_BASE_URL")||"http://localhost:11434",A=a.file(),L=A?Se__default.dirname(A):"",S=a.getLevel();return {autoload:true,options:{baseURL:M,logDir:L,logLevel:S},async getModel(P,_,j){return P.languageModel?P.languageModel(_):P(_)}}},"easbot-local":async()=>{let{Global:M}=await import('./global-5WFCDQ45.mjs'),A=await tt.get("LOCAL_MODEL_PATH")||Se__default.join(M.Path.cache,"models"),L=a.file(),S=L?Se__default.dirname(L):"",P=a.getLevel(),{SUPPORTED_EMBEDDING_MODELS:_}=await import('@easbot/local-model-sdk');return {autoload:true,options:{cacheDir:A,logDir:S,logLevel:P,verbose:true},async getModel(j,B,Z){return B in _?j.embeddingModel(B,Z):B.startsWith("rerank-")?j.rerankingModel?j.rerankingModel(B.slice(6),Z):j(B):j.languageModel?j.languageModel(B,Z):j(B)}}}};$.Model=N.object({id:N.string(),providerId:N.string(),api:N.object({id:N.string(),url:N.string(),npm:N.string()}),name:N.string(),family:N.string().optional(),capabilities:N.object({temperature:N.boolean(),reasoning:N.boolean(),attachment:N.boolean(),toolcall:N.boolean(),input:N.object({text:N.boolean(),audio:N.boolean(),image:N.boolean(),video:N.boolean(),pdf:N.boolean()}),output:N.object({text:N.boolean(),audio:N.boolean(),image:N.boolean(),video:N.boolean(),pdf:N.boolean()}),interleaved:N.union([N.boolean(),N.object({field:N.enum(["reasoning_content","reasoning_details"])})])}),cost:N.object({input:N.number(),output:N.number(),cache:N.object({read:N.number(),write:N.number()}),experimentalOver200K:N.object({input:N.number(),output:N.number(),cache:N.object({read:N.number(),write:N.number()})}).optional()}),limit:N.object({context:N.number(),input:N.number().optional(),output:N.number()}),status:N.enum(["alpha","beta","deprecated","active"]),options:N.record(N.string(),N.any()),headers:N.record(N.string(),N.string()),release_date:N.string(),variants:N.record(N.string(),N.record(N.string(),N.any())).optional()}).meta({ref:"Model"}),$.Info=N.object({id:N.string(),name:N.string(),source:N.enum(["env","config","custom","api"]),env:N.string().array(),key:N.string().optional(),options:N.record(N.string(),N.any()),models:N.record(N.string(),$.Model)}).meta({ref:"Provider"});function m(M,A){let L={id:A.id,providerId:M.id,name:A.name,family:A.family,api:{id:A.id,url:M.api,npm:A.provider?.npm??M.npm??"@ai-sdk/openai-compatible"},status:A.status??"active",headers:A.headers??{},options:A.options??{},cost:{input:A.cost?.input??0,output:A.cost?.output??0,cache:{read:A.cost?.cache_read??0,write:A.cost?.cache_write??0},experimentalOver200K:A.cost?.context_over_200k?{cache:{read:A.cost.context_over_200k.cache_read??0,write:A.cost.context_over_200k.cache_write??0},input:A.cost.context_over_200k.input,output:A.cost.context_over_200k.output}:void 0},limit:{context:A.limit.context??2e5,input:A.limit.input??o(A.limit.context??2e5),output:A.limit.output??8192},capabilities:{temperature:A.temperature,reasoning:A.reasoning,attachment:A.attachment,toolcall:A.tool_call,input:{text:A.modalities?.input?.includes("text")??false,audio:A.modalities?.input?.includes("audio")??false,image:A.modalities?.input?.includes("image")??false,video:A.modalities?.input?.includes("video")??false,pdf:A.modalities?.input?.includes("pdf")??false},output:{text:A.modalities?.output?.includes("text")??false,audio:A.modalities?.output?.includes("audio")??false,image:A.modalities?.output?.includes("image")??false,video:A.modalities?.output?.includes("video")??false,pdf:A.modalities?.output?.includes("pdf")??false},interleaved:A.interleaved??false},release_date:A.release_date,variants:{}};return L.variants=mapValues(wt.variants(L),S=>S),L}function f(M){return {id:M.id,source:"custom",name:M.name,env:M.env??[],options:{},models:mapValues(M.models,A=>m(M,A))}}$.fromModelsDevProvider=f;async function a$1(){var Q=[];try{let M=c(Q,s.time("state"));let A=await he.get();let L=await a$3.get();let S=mapValues(L,f);let P=new Set(A.disabled_providers??[]);let _=A.enabled_providers?new Set(A.enabled_providers):null;function j(V){return !(_&&!_.has(V)||P.has(V))}let B={};let Z=new Map;let ee={};let se=new Map;let le=new Map;s.info("init");let ae=Object.entries(A.provider??{});if(S["github-copilot"]){let V=S["github-copilot"];S["github-copilot-enterprise"]={...V,id:"github-copilot-enterprise",name:"GitHub Copilot Enterprise",models:mapValues(V.models,J=>({...J,providerId:"github-copilot-enterprise"}))};}function we(V,J){let oe=B[V];if(oe){B[V]=mergeDeep(oe,J);return}let de=S[V];de&&(B[V]=mergeDeep(de,J));}for(let[V,J]of ae){let oe=S[V],de={id:V,name:J.name??oe?.name??V,env:J.env??oe?.env??[],options:mergeDeep(oe?.options??{},J.options??{}),source:"config",models:oe?.models??{}};for(let[me,ce]of Object.entries(J.models??{})){let ye=de.models[ce.id??me],je=iife(()=>ce.name?ce.name:ce.id&&ce.id!==me?me:ye?.name??me),Ie={id:me,api:{id:ce.id??ye?.api.id??me,npm:ce.provider?.npm??J.npm??ye?.api.npm??L[V]?.npm??"@ai-sdk/openai-compatible",url:J?.api??ye?.api.url??L[V]?.api??""},status:ce.status??ye?.status??"active",name:je,providerId:V,capabilities:{temperature:ce.temperature??ye?.capabilities.temperature??!1,reasoning:ce.reasoning??ye?.capabilities.reasoning??!1,attachment:ce.attachment??ye?.capabilities.attachment??!1,toolcall:ce.tool_call??ye?.capabilities.toolcall??!0,input:{text:ce.modalities?.input?.includes("text")??ye?.capabilities.input.text??!0,audio:ce.modalities?.input?.includes("audio")??ye?.capabilities.input.audio??!1,image:ce.modalities?.input?.includes("image")??ye?.capabilities.input.image??!1,video:ce.modalities?.input?.includes("video")??ye?.capabilities.input.video??!1,pdf:ce.modalities?.input?.includes("pdf")??ye?.capabilities.input.pdf??!1},output:{text:ce.modalities?.output?.includes("text")??ye?.capabilities.output.text??!0,audio:ce.modalities?.output?.includes("audio")??ye?.capabilities.output.audio??!1,image:ce.modalities?.output?.includes("image")??ye?.capabilities.output.image??!1,video:ce.modalities?.output?.includes("video")??ye?.capabilities.output.video??!1,pdf:ce.modalities?.output?.includes("pdf")??ye?.capabilities.output.pdf??!1},interleaved:ce.interleaved??!1},cost:{input:ce?.cost?.input??ye?.cost?.input??0,output:ce?.cost?.output??ye?.cost?.output??0,cache:{read:ce?.cost?.cache_read??ye?.cost?.cache.read??0,write:ce?.cost?.cache_write??ye?.cost?.cache.write??0}},options:mergeDeep(ye?.options??{},ce.options??{}),limit:{context:ce.limit?.context??ye?.limit?.context??2e5,input:ce.limit?.input??ye?.limit?.input??o(ce.limit?.context??2e5),output:ce.limit?.output??ye?.limit?.output??8192},headers:mergeDeep(ye?.headers??{},ce.headers??{}),family:ce.family??ye?.family??"",release_date:ce.release_date??ye?.release_date??"",variants:{}},Ce=mergeDeep(wt.variants(Ie),ce.variants??{});Ie.variants=mapValues(pickBy(Ce,ie=>!ie.disabled),ie=>omit(ie,["disabled"])),de.models[me]=Ie;}S[V]=de;}let re=await tt.all();for(let[V,J]of Object.entries(S)){if(P.has(V))continue;let oe=J.env.map(de=>re[de]).find(Boolean);oe&&we(V,{source:"env",key:J.env.length===1?oe:void 0});}for(let[V,J]of Object.entries(await Qe.all()))P.has(V)||J.type==="api"&&we(V,{source:"api",key:J.key});for(let V of await ls.list()){if(!V.auth)continue;let J=V.auth.provider;if(P.has(J))continue;let oe=!1,de=await Qe.get(J);if(de&&(oe=!0),J==="github-copilot"&&!oe&&await Qe.get("github-copilot-enterprise")&&(oe=!0),!!oe&&V.auth.loader){if(de){let me=S[V.auth.provider];if(!me){s.error(`Auth provider ${V.auth.provider} not found in database`);return}let ye=await V.auth.loader(()=>Qe.get(J),me)??{},je=B[J]?{options:ye}:{source:"custom",options:ye};we(J,je);}if(J==="github-copilot"){let me="github-copilot-enterprise";if(!P.has(me)&&await Qe.get(me)){let ye=S[me];if(!ye){s.error(`Enterprise provider ${me} not found in database`);return}let Ie=await V.auth.loader(()=>Qe.get(me),ye)??{},Ce=B[me]?{options:Ie}:{source:"custom",options:Ie};we(me,Ce);}}}}for(let[V,J]of Object.entries(c$1)){if(P.has(V))continue;let oe=S[V];if(!oe){s.error("Provider does not exist in model list "+V);continue}let de=await J(oe);if(de&&(de.autoload||B[V])){de.getModel&&(ee[V]=de.getModel);let me=de.options??{},ce=B[V]?{options:me}:{source:"custom",options:me};we(V,ce);}}for(let[V,J]of ae){let oe={source:"config"};J.env&&(oe.env=J.env),J.name&&(oe.name=J.name),J.options&&(oe.options=J.options),we(V,oe);}for(let[V,J]of Object.entries(B)){if(!j(V)){delete B[V];continue}let oe=A.provider?.[V];for(let[de,me]of Object.entries(J.models)){me.api.id=me.api.id??me.id??de,(de==="gpt-5-chat-latest"||V==="openrouter"&&de==="openai/gpt-5-chat")&&delete J.models[de],me.status==="alpha"&&!a$2.EASBOT_ENABLE_EXPERIMENTAL_MODELS&&delete J.models[de],me.status==="deprecated"&&delete J.models[de],(oe?.blacklist?.includes(de)||oe?.whitelist&&!oe.whitelist.includes(de))&&delete J.models[de],me.variants=mapValues(wt.variants(me),ye=>ye);let ce=oe?.models?.[de]?.variants;if(ce&&me.variants){let ye=mergeDeep(me.variants,ce);me.variants=mapValues(pickBy(ye,je=>!je.disabled),je=>omit(je,["disabled"]));}}if(Object.keys(J.models).length===0){delete B[V];continue}s.info("found",{providerId:V});}return {models:Z,providers:B,sdk:se,localProxy:le,modelLoaders:ee}}catch(H){var F=H,te=true;}finally{d(Q,F,te);}}let p;function u(){return p||(p=R.state(a$1)),p}async function h(){return u()()}async function g(){return (await h())?.providers??{}}$.list=g;async function I(){return (await h())?.localProxy??{}}$.getLocalProxy=I;async function T(M){try{var A=[];try{let _=c(A,s.time("getSDK",{providerId:M.providerId}));let j=await h();if(!j)throw new Error("Provider state not available");let B=j.providers[M.providerId];if(!B)throw new Error(`Provider ${M.providerId} not found`);let Z={...B.options};M.api.npm.includes("@ai-sdk/openai-compatible")&&Z.includeUsage!==!1&&(Z.includeUsage=!0);Z.baseURL||(Z.baseURL=M.api.url);Z.apiKey===void 0&&B.key&&(Z.apiKey=B.key);M.headers&&(Z.headers={...Z.headers,...M.headers});let ee=JSON.stringify({providerId:M.providerId,npm:M.api.npm,options:Z}).split("").reduce((ye,je)=>(ye=(ye<<5)-ye+je.charCodeAt(0),ye&ye),0);let se=j.sdk.get(ee);if(se)return se;let le=Z.fetch;Z.fetch=async(ye,je)=>{let Ie=le??fetch,Ce=je??{};if(Z.timeout!==void 0&&Z.timeout!==null){let ie=[];Ce.signal&&ie.push(Ce.signal),Z.timeout!==!1&&ie.push(AbortSignal.timeout(Z.timeout));let $e=ie.length>1?AbortSignal.any(ie):ie[0];Ce.signal=$e;}if(M.api.npm==="@ai-sdk/openai"&&Ce.body&&Ce.method==="POST"){let ie=JSON.parse(Ce.body);if(!(M.providerId.includes("azure")&&ie.store===!0)&&Array.isArray(ie.input)){for(let pt of ie.input)"id"in pt&&delete pt.id;Ce.body=JSON.stringify(ie);}}return Ie(ye,{...Ce,timeout:!1})};let ae=nR[M.api.npm];if(ae){s.info("using bundled provider",{providerId:M.providerId,pkg:M.api.npm});let je=(await ae())({name:M.providerId,...Z});return j.sdk.set(ee,je),je}let we;M.api.npm.startsWith("file://")?we=M.api.npm:we=await Shell.install(M.api.npm,"latest");let{pathToFileURL:re}=await import('url');let Q=await import('path');let H=await import('fs/promises');let F=Q.join(we,"package.json");let te=JSON.parse(await H.readFile(F,"utf-8"));let V;te.exports?.["."]?.import?V=te.exports["."].import:te.exports?.["."]?.require?V=te.exports["."].require:te.module?V=te.module:te.main?V=te.main:V="index.js";let J=Q.join(we,V);let oe=re(J).href;let de=await import(oe);let me=de[Object.keys(de).find(ye=>ye.startsWith("create"))];let ce=me({name:M.providerId,...Z});j.sdk.set(ee,ce);return ce}catch(L){var S=L,P=!0;}finally{d(A,S,P);}}catch(_){throw new $.InitError({providerId:M.providerId},{cause:_})}}async function y(M){return (await h())?.providers[M]}$.getProvider=y;async function x(M,A){let L=await h();if(!L)throw new Error("Provider state not available");let S=L.providers[M];if(!S){let _=Object.keys(L.providers),B=gy.go(M,_,{limit:3,threshold:-1e4}).map(Z=>Z.target);throw new $.ModelNotFoundError({providerId:M,modelId:A,suggestions:B})}let P=S.models[A];if(!P){let _=Object.keys(S.models),B=gy.go(A,_,{limit:3,threshold:-1e4}).map(Z=>Z.target);throw new $.ModelNotFoundError({providerId:M,modelId:A,suggestions:B})}return P}$.getModel=x;async function b(M){s.debug("getLanguage called",{providerId:M.providerId,modelId:M.id});let A=await h();if(!A)throw new Error("Provider state not available");let L=`${M.providerId}/${M.id}`;if(A.models.has(L))return A.models.get(L);let S=A.providers[M.providerId];if(!S)throw new Error(`Provider ${M.providerId} not found`);let P=await T(M);try{let _=A.modelLoaders[M.providerId],j=_?await _(P,M.api.id,S.options):P.languageModel(M.api.id);return A.models.set(L,j),j}catch(_){throw s.error("Failed to create language model",{providerId:M.providerId,modelId:M.id,error:_}),_ instanceof NoSuchModelError?new $.ModelNotFoundError({modelId:M.id,providerId:M.providerId},{cause:_}):_}}$.getLanguage=b;async function w(M,A){s.debug("getEmbedding called",{providerId:M,modelId:A});let L=await x(M,A),S=await T(L),P,_=S;if(typeof _.embeddingModel=="function")P=_.embeddingModel(L.api.id);else if(typeof _.textEmbeddingModel=="function")P=_.textEmbeddingModel(L.api.id);else throw new Error(`Provider ${M} does not support embedding model. SDK missing both 'embeddingModel' and 'textEmbeddingModel' methods.`);return P}$.getEmbedding=w;async function k(M,A){s.debug("getRerank called",{providerId:M,modelId:A});let L=await x(M,A),S=await T(L),P,_=S;if(typeof _.rerankingModel=="function")P=_.rerankingModel(L.api.id);else if(typeof _.languageModel=="function"){let j=await I(),B=`${M}/${A}`;if(B in j)return j[B];let Z=await b(L);if(Z){let ee=await x("easbot-local","rerank-proxy"),le=await T(ee);P=le.rerankingModel?le.rerankingModel(ee.api.id,{llm:Z,useEnhancedPrompt:true,promptLanguage:"cn",totalScore:1}):void 0,P&&j.set(B,P);}}if(!P)throw new Error(`Provider ${M} and model ${A} does not support rerank`);return P}$.getRerank=k;async function v(M,A){let L=await h();if(!L)return;let S=L.providers[M];if(S){for(let P of A)for(let _ of Object.keys(S.models))if(_.includes(P))return {providerId:M,modelId:_}}}$.closest=v;async function C(M){let A=await he.get();if(A.small_model){let _=D(A.small_model);if(!_.providerId||!_.modelId)throw new Error("Invalid small_model format");return x(_.providerId,_.modelId)}let L=await h(),S=L?.providers[M];if(S){let _=["claude-haiku-4-5","claude-haiku-4.5","3-5-haiku","3.5-haiku","gemini-3-flash","gemini-2.5-flash","gpt-5-nano"];M.startsWith("easbot")&&(_=["gpt-5-nano"]),M.startsWith("github-copilot")&&(_=["gpt-5-mini","claude-haiku-4.5",..._]);for(let j of _)if(M==="amazon-bedrock"){let B=["global.","us.","eu."],Z=Object.keys(S.models).filter(ae=>ae.includes(j)),ee=Z.find(ae=>ae.startsWith("global."));if(ee)return x(M,ee);let se=S.options?.region;if(se){let ae=se.split("-")[0];if(ae==="us"||ae==="eu"){let we=Z.find(re=>re.startsWith(`${ae}.`));if(we)return x(M,we)}}let le=Z.find(ae=>!B.some(we=>ae.startsWith(we)));if(le)return x(M,le)}else for(let B of Object.keys(S.models))if(B.includes(j))return x(M,B)}if(L?.providers.easbot?.models["gpt-5-nano"])return x("easbot","gpt-5-nano")}$.getSmallModel=C;let E=["gpt-5","claude-sonnet-4","big-pickle","gemini-3-pro"];function O(M){return sortBy(M,[A=>E.findIndex(L=>A.id.includes(L)),"desc"],[A=>A.id.includes("latest")?0:1,"asc"],[A=>A.id,"desc"])}$.sort=O;async function U(){let M=await he.get();if(M.model)return D(M.model);let A=await g().then(S=>Object.values(S)).then(S=>S.find(P=>!M.provider||Object.keys(M.provider).includes(P.id)));if(!A)throw new Error("no providers found");let[L]=O(Object.values(A.models));if(!L)throw new Error("no models found");return {providerId:A.id,modelId:L.id}}$.defaultModel=U;function D(M){let{provider:A,model:L}=parseModelId(M);if(!A)throw new Error("Invalid model format: "+M);return {providerId:A,modelId:L}}$.parseModel=D,$.ModelNotFoundError=NamedError.create("ProviderModelNotFoundError",N.object({providerId:N.string(),modelId:N.string(),suggestions:N.array(N.string()).optional()})),$.InitError=NamedError.create("ProviderInitError",N.object({providerId:N.string()}));})(xe||(xe={}));var Yt;(p=>{let e=a.create({service:"knowledge.note"}),t;async function n(u){let h=await he.get(),g=u?.embedding?.model||h.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:I,model:T}=parseModelId(g),y=I||"easbot-local",x=T||"bge-base-zh-v1.5",b=await xe.getEmbedding(y,x),w=u?.graph?.model??h.graph_model,k,v;if(w){let{provider:K,model:X}=parseModelId(w);k=K||"easbot-local",v=X||w;}else {let K=await xe.defaultModel();k=K.providerId,v=K.modelId;}let C;try{let K=await xe.getModel(k,v);C=await xe.getLanguage(K);}catch(K){e.error("note loadModels graphLlm failed",{graphProvider:k,graphModel:v,error:String(K)});}let E=u?.rerank?.model||h.rerank_model,O,U;if(E){let{provider:K,model:X}=parseModelId(E);O=K||"easbot-local",U=X||E;}else {let K=await xe.defaultModel();O="easbot-local",U=`rerank-${K.providerId}/${K.modelId}`;}let D;try{D=await xe.getRerank(O,U);}catch(K){e.error("note loadModels rerankLlm failed",{rerankProvider:O,rerankModel:U,error:String(K)});}return {embeddingLlm:b,graphLlm:C,rerankLlm:D}}function o(){return t||(t=R.state(async()=>{let u=await nr();if(!u||u.enabled===false)return {kb:null,config:null,rootDir:"",sources:[],initialized:true};let{Global:h}=await import('./global-5WFCDQ45.mjs'),g=R.worktree??R.directory,I=Filesystem.normalize(Se__default.join(g,".easbot","knowledge")),T=Filesystem.normalize(u.database?Se__default.isAbsolute(u.database)?u.database:Se__default.resolve(g,u.database):Se__default.join(R.worktree,".easbot","db","note.db")),{embeddingLlm:y,graphLlm:x,rerankLlm:b}=await n(u),w=(u?.sources?.length??0)>0?u.sources:["docs","tasks"];for(let C of w??[]){let E=Filesystem.normalize(Se__default.join(I,C));await Filesystem.exists(E)||await Filesystem.mkdir(E);}let k={workspaceDir:I,vectorDims:u.embedding?.dimensions??1,embeddingLlm:y,graphLlm:x,rerankLlm:b,search:{maxResults:u.search?.maxResults??3,minScore:u.search?.minScore??0,hybrid:{enabled:u.search?.hybrid?.enabled??true,vectorWeight:u.search?.hybrid?.vectorWeight??0,textWeight:u.search?.hybrid?.textWeight??1}},indexer:{batchSize:20,ignorePatterns:[...Glob.DEFAULT_IGNORE_PATTERNS,...u.indexer?.ignorePatterns??[],...(await Glob.parseGitignore(Se__default.join(R.worktree,".gitignore"))).filter(C=>!C.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,sources:w};T&&(k.database={path:T,walMode:true}),await initLog$2({logDir:h.Path.log,logFile:"note.log",level:a.getLevel(),print:false});let v=await createNoteKnowledge(k);return u.sync?.onBoot&&await v.sync().catch(C=>e.warn("note sync on boot failed",{error:String(C)})),{kb:v,config:u??null,rootDir:I,sources:w??[],initialized:true}},async u=>{u.kb&&await u?.kb?.close().catch(()=>{});})),t}function s(){return o()()}p.state=s;async function r(){return (await s()).kb}p.get=r;async function i(){return (await s()).rootDir}p.rootDir=i;async function c(){return (await s()).sources}p.sources=c;async function l(){return (await s()).kb!==null}p.isEnabled=l;async function d(){return (await s()).config}p.config=d;async function m(){return (await s()).initialized}p.isInitialized=m;async function f(){let u=await r();u&&u.sync().catch(h=>e.warn("note sync failed",{error:String(h)}));}p.sync=f;async function a$1(){let u=await r();if(!u)return null;let h=u.getStatus();return {dbPath:h.dbPath,documentsCount:h.documentsCount,chunksCount:h.chunksCount,nodesCount:h.nodesCount,edgesCount:h.edgesCount,vectorDims:0,vectorSearchAvailable:h.embeddingLlmAvailable,llmAvailable:h.graphLlmAvailable,healthy:h.healthy}}p.status=a$1;})(Yt||(Yt={}));var nn=a.create({service:"context-instructions"});async function iR(e){let t=[{name:"memory",description:"Use this tool to store, retrieve, update, and delete persistent memories across agent sessions. Memory enables learning from interactions, remembering user preferences, and building long-term knowledge",condition:async()=>In.isEnabled()},{name:"note",description:"Use this tool to search and retrieve information from the local note/document knowledge base. It returns document paths, line ranges, snippets, and related graph nodes",condition:async()=>Yt.isEnabled()}],n=["| Tool | Description |","|------|-------------|"];for(let o of t)await o.condition()&&n.push(`| \`${o.name}\` | ${o.description} |`);return n.join(`
|
|
975
|
+
`)}async function aR(e){let t=["| Directory | Description |","|-------------|-------------|"],n=[{path:async()=>Yt.rootDir(),description:"Knowledge base root directory",condition:async()=>Yt.isEnabled()},{path:async()=>`${await Yt.rootDir()}/tasks`,description:"Task files - each task in separate folder (task_plan.md, progress.md, findings.md)",condition:async()=>Yt.isEnabled()},{path:async()=>`${await Yt.rootDir()}/docs`,description:"Documentation - categorized by topic as needed",condition:async()=>Yt.isEnabled()}];for(let o of n)if(o.condition?await o.condition():true){let r=await o.path();t.push(`| \`${r}/\` | ${o.description} |`);}return t.join(`
|
|
976
|
+
`)}async function lp(e,t){let n=e;if(n.includes("{{tools}}"))try{n=n.replace("{{tools}}",await iR(t));}catch(s){nn.warn("failed to render {{tools}} placeholder",{error:String(s)}),n=n.replace("{{tools}}","");}if(n.includes("{{directories}}"))try{n=n.replace("{{directories}}",await aR(t));}catch(s){nn.warn("failed to render {{directories}} placeholder",{error:String(s)}),n=n.replace("{{directories}}","");}n=n.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(s,r,i)=>{let c=t[r];return c!=null&&c!==0&&c!==""?i:""}),n=n.replace(/\{\{#each\s+(\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(s,r,i)=>{let c=t[r];return !Array.isArray(c)||c.length===0?"":c.map(l=>{let d=i;return typeof l=="object"&&l!==null&&Object.entries(l).forEach(([m,f])=>{d=d.replace(new RegExp(`\\{\\{${m}\\}\\}`,"g"),String(f));}),d}).join("")});let o={};return t.metadata&&Object.entries(t.metadata).forEach(([s,r])=>{o[s]=r;}),Object.entries(t).forEach(([s,r])=>{s==="metadata"||s==="tools"||s==="directories"||s==="files"||(o[s]=r);}),Object.keys(o).length>0&&(n=a$9.replaceVariables(n,o)),n}function cR(e){let t=`| File | Priority | Description | Scope | Type | Permission | Location | Status |
|
|
977
|
+
|------|----------|-------------|-------|------|------------|----------|--------|`,n=e.map(o=>`| ${o.name} | ${o.priority} | ${o.description} | ${o.scope} | ${o.type} | ${o.permission} | ${o.location} | ${o.status} |`).join(`
|
|
978
|
+
`);return `${t}
|
|
979
|
+
${n}`}function ho(e){if(e)return typeof e=="string"?e:String(e)}function up(e){if(e!=null){if(typeof e=="number")return e;if(typeof e=="string"){let t=Number.parseInt(e,10);if(!Number.isNaN(t))return t}}}function vy(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true"}}function Sd(e){if(e){if(Array.isArray(e))return e.map(t=>String(t));if(typeof e=="string")try{let t=JSON.parse(e);if(Array.isArray(t))return t.map(n=>String(n))}catch{return e.split(",").map(t=>t.trim())}}}function Sy(e,t){return e.scope===i?true:e.scope===t}function dR(e,t){return !e.owner||e.owner.length===0?true:t?!!(e.owner.includes(t)||e.share?.includes(t)):false}async function lR(e,t,n){if(await Filesystem.isDir(e))try{let o=await Tt__default.readdir(e,{withFileTypes:!0});for(let s of o){if(!s.isFile()||!s.name.endsWith(".md"))continue;let r=s.name;if(!l.includes(r)||t.has(r))continue;let i=Se__default.join(e,r),c=await Cd(i,n);c&&t.set(r,c);}}catch(o){nn.warn("failed to scan builtin system files",{dir:e,error:String(o)});}}async function uR(e,t,n$1){for(let[o,s]of Object.entries(n))if(!n$1.has(o))for await(let r of Filesystem.up({targets:[s],start:e,stop:R.worktree})){let i=await Cd(r,t);if(i){n$1.set(o,i);break}}}async function pR(e,t,n){let o=Se__default.join(e,"rules"),s=new Map;if(!await Filesystem.isDir(o))return s;try{let r=await Tt__default.readdir(o,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(".md")||t.has(i.name))continue;let c=Se__default.join(o,i.name),l=await Cd(c,n);l&&s.set(i.name,l);}}catch(r){nn.warn("failed to scan rules directory",{dir:o,error:String(r)});}return s}async function mR(e,t,n,o){let s=new Map,r=await he.get(),i$1=r.context?.files,c=r.context?.contextFiles;if(!c)return s;let l=c[t]||c[i]||[];if(l.length===0||!await Filesystem.isDir(e))return s;try{let d=await Tt__default.readdir(e,{withFileTypes:!0});for(let m of l){if(s.has(m))continue;let f=d.find(h=>h.isFile()&&h.name===m);if(!f)continue;let a=Se__default.join(e,f.name),p=await Cd(a,o);if(!p)continue;let u=Cy(m,i$1,p.frontmatter);Sy(u,t)&&dR(u,n)&&s.set(m,{...p,config:u});}}catch(d){nn.warn("failed to load context files",{root:e,error:String(d)});}return s}function Cy(e,t,n){let o=p[e],s=t?.[e];return {name:e,type:ho(n?.type)??s?.type??o?.type??"system",scope:ho(n?.scope)??s?.scope??o?.scope??"all",priority:up(n?.priority)??s?.priority??o?.priority??q,owner:Sd(n?.owner)??s?.owner??o?.owner,share:Sd(n?.share)??s?.share??o?.share,permission:ho(n?.permission)??s?.permission??o?.permission??"read",description:ho(n?.description)??s?.description??o?.description,dynamic:vy(n?.dynamic)??s?.dynamic??o?.dynamic}}function vd(e,t,n,o,s,r=false){let i=n.permission==="write"?"writable":"readonly",c=`<file path="${o}" priority="${s}" mode="${i}">
|
|
980
|
+
${t}
|
|
981
|
+
</file>`;return {name:e,content:c,priority:s,dynamic:r,location:o,permission:n.permission,owner:n.owner,share:n.share}}async function fR(e,t){try{if(await Ya(e))return nn.debug("workspace already initialized, skipping builtin bootstrap"),null;let o=null,s="",r=await Vt.get("eas-agent-evolution");if(r){let l=Se__default.join(Se__default.dirname(r.location),"assets","BOOTSTRAP.md");try{o=await Tt__default.readFile(l,"utf-8"),s=l;}catch{}}if(!o){let l=m.replace(".md","");o=await loadTextFileAsync(`./template/${l}.txt`,import.meta.url)(),o&&(s=`context/template/${l}.txt`);}if(!o)return nn.debug("builtin bootstrap template not found"),null;let i=await lp(o,t).catch(l=>(nn.warn("renderTemplate failed for bootstrap, using raw content",{error:String(l)}),o)),c=p[m]??{name:m,type:"system",scope:"all",priority:20};return nn.debug("loaded builtin bootstrap template",{location:s}),vd(m,i,c,`<builtin:${s}>`,c.priority??20,!1)}catch(n){return nn.warn("failed to load builtin bootstrap",{error:String(n)}),null}}function gR(e,t,n$1=false){let o$1=[],s=(r,i$1)=>{let c=i$1?.frontmatter||{},l=p[r],d=ho(c.scope)||l?.scope||i;d!==i&&d!==t||n$1&&!o.includes(r)||o$1.push({name:r,priority:up(c.priority)||l?.priority||q,description:ho(c.description)||l?.description||"",scope:d,type:ho(c.type)||l?.type||"system",permission:ho(c.permission)||l?.permission||"read",location:i$1?.location||"",status:i$1?"\u2705":"\u274C"});};for(let r of l)s(r,e.get(r));for(let r of Object.keys(n))s(r,e.get(r));for(let[r,i]of e)p[r]||s(r,i);return o$1.sort((r,i)=>r.priority-i.priority),o$1}async function hR(e,t){let n={};try{let s=`${await Ci(e)}/protocol.json`,r=await pl(s);n.metadata=r.metadata;}catch(o){nn.debug("failed to read protocol for render context",{error:String(o)});}return n}async function Cd(e,t){let n=t??{};try{let o=await a$9.parse(e);return {content:await lp(o.content,n).catch(r=>(nn.warn("renderTemplate failed on parsed content, using raw",{filePath:e,error:String(r)}),o.content)),frontmatter:o.data,location:e}}catch(o){if(o.code==="ENOENT")return null;try{let s=await Tt__default.readFile(e,"utf-8");return nn.warn("failed to parse frontmatter, using raw content",{filePath:e,error:String(o)}),{content:await lp(s,n).catch(i=>(nn.warn("renderTemplate failed on raw content, using as-is",{filePath:e,error:String(i)}),s)),frontmatter:{},location:e}}catch(s){return nn.warn("failed to load template file",{filePath:e,error:String(s)}),null}}}async function yR(e){let t=e.mode??f$1,n=e.workspaceDir??R.directory,o$1=e.agent?.mode==="subagent",s=e.agent?.name,r$1=[],i=new Set,c=new Map,l=await hR(n),d=e.protocolInitialized??await Ya(n);if(nn.debug("loadTemplatesForMode: initialization status",{workspaceDir:n,isInitialized:d,protocolInitializedProvided:e.protocolInitialized!==void 0}),d){for await(let m of Filesystem.up({targets:[".easbot"],start:n,stop:R.worktree}))await lR(m,c,l);await uR(n,l,c);for(let[m,f]of c){if(i.has(m)||o$1&&!o.includes(m))continue;let a=Cy(m,void 0,f.frontmatter);if(!Sy(a,t))continue;let p=a.priority??q,u=m==="HEARTBEAT.md"||a.dynamic===true;r$1.push(vd(m,f.content,a,f.location,p,u)),i.add(m);}}else {let m$1=await fR(n,l);m$1&&(r$1.push(m$1),i.add(m));}for await(let m of Filesystem.up({targets:[".easbot"],start:n,stop:R.worktree})){let f=await pR(m,i,l);for(let[p,u]of f){if(i.has(p))continue;let h={scope:ho(u.frontmatter?.scope)??"all",priority:up(u.frontmatter?.priority)??r,permission:ho(u.frontmatter?.permission)??"read",dynamic:vy(u.frontmatter?.dynamic)??true,owner:Sd(u.frontmatter?.owner),share:Sd(u.frontmatter?.share),description:ho(u.frontmatter?.description)};r$1.push(vd(p,u.content,h,u.location,h.priority,h.dynamic)),i.add(p);}let a=await mR(m,t,s,l);for(let[p,u]of a)i.has(p)||(r$1.push(vd(p,u.content,u.config,u.location,u.config.priority??q)),i.add(p));}if(l.files=gR(c,t,o$1),l.files&&l.files.length>0)try{let m=cR(l.files);for(let f of r$1)f.content.includes("{{files}}")&&(f.content=f.content.replace("{{files}}",m));}catch(m){nn.warn("failed to render {{files}} placeholder",{error:String(m)});}return r$1.sort((m,f)=>m.priority-f.priority),nn.debug("templates loaded from filesystem",{mode:t,workspaceDir:n,agentMode:e.agent?.mode,isInitialized:d,sectionCount:r$1.length,sections:r$1.map(m=>({name:m.name,priority:m.priority,location:m.location,dynamic:m.dynamic}))}),r$1}var Iy=new Map;async function ky(e){let t=e.mode??f$1,n=e.workspaceDir??R.directory,s=e.agent?.mode==="subagent"?e.agent.name:"primary",r=n?`template:${t}:${s}:${n}`:`template:${t}:${s}`,i=Iy.get(r);if(i)return i;let l={sections:await yR(e),mode:t,loadedAt:Date.now()};return Iy.set(r,l),l}async function pp(e){return (await ky(e)).sections}var ms=a.create({service:"file-cache"}),Py=25*1024*1024,Ty=100,fp=class{constructor(t=Ty,n=Py){b$1(this,"cache");b$1(this,"maxEntries");b$1(this,"maxSizeBytes");b$1(this,"currentSizeBytes");this.cache=new Map,this.maxEntries=t,this.maxSizeBytes=n,this.currentSizeBytes=0;}get(t){let n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){for(this.cache.has(t)&&(this.cache.delete(t),this.currentSizeBytes-=this.estimateSize(n));this.cache.size>=this.maxEntries||this.currentSizeBytes>=this.maxSizeBytes;){let o=this.cache.keys().next().value;if(o!==void 0){let s=this.cache.get(o);s!==void 0&&(this.currentSizeBytes-=this.estimateSize(s)),this.cache.delete(o),ms.debug("cache entry evicted",{key:o});}else break}this.cache.set(t,n),this.currentSizeBytes+=this.estimateSize(n);}has(t){return this.cache.has(t)}delete(t){let n=this.cache.get(t);return n!==void 0&&(this.currentSizeBytes-=this.estimateSize(n)),this.cache.delete(t)}clear(){this.cache.clear(),this.currentSizeBytes=0;}get size(){return this.cache.size}get sizeBytes(){return this.currentSizeBytes}estimateSize(t){return typeof t=="string"?t.length*2:100}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}},kd=class{constructor(t=Ty,n=Py){b$1(this,"maxEntries",t);b$1(this,"maxSizeBytes",n);b$1(this,"cache");this.cache=new fp(this.maxEntries,this.maxSizeBytes),ms.debug("file state cache created",{maxEntries:this.maxEntries,maxSizeBytes:this.maxSizeBytes});}async readFile(t,n){try{let o=await Tt__default.stat(t),s=o.mtimeMs,r=this.cache.get(t);if(r&&r.timestamp===s&&r.offset===n?.offset&&r.limit===n?.limit)return ms.debug("cache hit",{filePath:t}),r.content;let i;if(n?.offset!==void 0||n?.limit!==void 0){let d=(await Tt__default.readFile(t,"utf-8")).split(`
|
|
982
|
+
`),m=n.offset??0,f=n.limit?m+n.limit:d.length;i=d.slice(m,f).join(`
|
|
983
|
+
`);}else i=await Tt__default.readFile(t,"utf-8");let c={content:i,timestamp:s,lineCount:i.split(`
|
|
984
|
+
`).length,size:o.size,offset:n?.offset,limit:n?.limit};return this.cache.set(t,c),ms.debug("cache miss, file read",{filePath:t,size:o.size}),i}catch(o){if(o.code==="ENOENT"){this.cache.delete(t);return}throw o}}getState(t){return this.cache.get(t)}async detectChanges(){let t=[];for(let[n,o]of this.cache.entries())try{let s=await Tt__default.stat(n);if(s.mtimeMs!==o.timestamp){let r=await Tt__default.readFile(n,"utf-8");t.push({path:n,oldContent:o.content,newContent:r,oldMtime:o.timestamp,newMtime:s.mtimeMs}),this.cache.set(n,{...o,content:r,timestamp:s.mtimeMs});}}catch(s){s.code==="ENOENT"&&(t.push({path:n,oldContent:o.content,newContent:"",oldMtime:o.timestamp,newMtime:0}),this.cache.delete(n));}return t.length>0&&ms.info("file changes detected",{count:t.length}),t}invalidate(t){this.cache.delete(t),ms.debug("cache invalidated",{filePath:t});}invalidateAll(){this.cache.clear(),ms.info("all cache invalidated");}has(t){return this.cache.has(t)}clear(){this.cache.clear(),ms.info("cache cleared");}get size(){return this.cache.size}get sizeBytes(){return this.cache.sizeBytes}getFilePaths(){return Array.from(this.cache.keys())}},mp=null;function ei(e,t){return mp||(mp=new kd(e,t)),mp}var ti=a.create({service:"static-prompt"}),Xs;(f=>{let e$1;function t(){return e$1||(e$1=R.state(()=>({promptCache:new Map,fileCache:ei()}))),e$1}function n(){return t()()}function o(a,p,u){return [a.agent.name,a.model.id,p,u??"primary"].join("|")}function s(a,p,u){return `${a.agent.name}/${a.model.id}/${p}/${u??"primary"}`}function r(a,p,u){let h=n(),g=u?.mode,I=s(a,p,g),T=h.promptCache.get(I);return T&&T.configHash===o(a,p,g)?(ti.debug("static prompt cache hit",{cacheKey:I}),T.sections):null}f.getCached=r;function i(a,p,u,h){let g=n(),I=h?.mode,T=s(a,p,I),y={sections:u,configHash:o(a,p,I),builtAt:Date.now()};g.promptCache.set(T,y),ti.debug("static prompt cached",{cacheKey:T,length:u.length});}f.setCache=i;async function c(a){let p=a.mode??f$1,u=r(a,p,a.agent);if(u)return u;ti.debug("buildStaticPrompt: building",{agentName:a.agent.name,modelId:a.model.api?.id??a.model.id,mode:p,agentMode:a.agent.mode,workspaceDir:a.workspaceDir,protocolInitialized:a.protocolInitialized});let h=await pp(a);return i(a,p,h,a.agent),ti.debug("static prompt built",{length:h.length}),h}f.buildStaticPrompt=c;function l(a,p){let u=n();if(a&&p){for(let h of e){let g=`${a}/${p}/${h}`;u.promptCache.delete(g);}ti.debug("static prompt cache entries invalidated",{agentName:a,modelId:p});}else u.promptCache.clear(),ti.debug("all static prompt cache invalidated");}f.invalidateCache=l;function d(){let a=n(),p=Date.now(),u=[];for(let[h,g]of a.promptCache.entries())u.push({key:h,age:p-g.builtAt});return {size:a.promptCache.size,entries:u}}f.getCacheStats=d;function m(){return n().fileCache}f.getFileCache=m;})(Xs||(Xs={}));var ga;(m=>{a.create({service:"summary"});let t=loadTextFile("./memory-summary.txt",import.meta.url),n=loadTextFile("./knowledge-summary.txt",import.meta.url);async function r(f,a,p,u,h){return streamText({model:f,system:a,prompt:p,maxOutputTokens:u,abortSignal:h}).text}async function i(f){let a=await xe.defaultModel(),p=f??await xe.getModel(a.providerId??"default",a.modelId??"default");return xe.getLanguage(p)}function c(f){return f.map(a=>{let p=[` - node: id=${a.id} type=${a.type} name=${a.name}`];if(a.edges&&a.edges.length>0)for(let u of a.edges){let h=u.targetId!==void 0?` (id=${u.targetId})`:"";p.push(` \u2192 [${u.direction}] ${u.relation} \u2192 target=${u.targetType}:${u.targetName}${h}`);}return p.join(`
|
|
985
|
+
`)}).join(`
|
|
986
|
+
`)}async function l(f,a){let{query:p,chunks:u,model:h,maxLength:g}=f;if(u.length===0)return "";let I=await i(h),T=n()??"Synthesize the following document chunks into a concise summary relevant to the query. Order by Priority descending.",y=u.map((w,k)=>{let v=w.startLine!=null?`#L${w.startLine}-L${w.endLine??w.startLine}`:"",C=w.score??0,E=`[Chunk ${k+1}] Priority: ${C.toFixed(3)}
|
|
987
|
+
Source: [${w.path}](./${w.path}${v})
|
|
988
|
+
${w.content}`;return !w.nodes||w.nodes.length===0?E:`${E}
|
|
989
|
+
Graph Nodes:
|
|
990
|
+
${c(w.nodes)}`}).join(`
|
|
991
|
+
|
|
992
|
+
`),x=`[Query]
|
|
993
|
+
${p}
|
|
994
|
+
|
|
995
|
+
[Knowledge Chunks]
|
|
996
|
+
${y}`;return (await r(I,T,x,g??1e3,a)).trim()}m.summarizeNote=l;async function d(f,a){let{query:p,facts:u,model:h,maxLength:g}=f;if(u.length===0)return "";let I=await i(h),T=t()??"Synthesize the following memory facts into a concise summary relevant to the query. Order by Priority descending.",y=u.map((w,k)=>{let v=w.score??0,C=`[Fact ${k+1}] Priority: ${v.toFixed(3)}
|
|
997
|
+
Category: ${w.category} | Importance: ${w.importance} | Source: ${w.source}
|
|
998
|
+
${w.content}`;if(!w.nodes||w.nodes.length===0)return C;let E=w.nodes.map(O=>{let U=[` - node: id=${O.id} type=${O.type} name=${O.name}`];if(O.edges&&O.edges.length>0)for(let D of O.edges){let K=D.direction??(D.source===O.id?"out":"in");U.push(` \u2192 [${K}] ${D.relation} \u2192 target=${D.targetNode?.type??"node"}:${D.targetNode?.name??`id=${D.target}`} (id=${D.target})`);}return U.join(`
|
|
999
|
+
`)}).join(`
|
|
1000
|
+
`);return `${C}
|
|
1001
|
+
Graph Nodes:
|
|
1002
|
+
${E}`}).join(`
|
|
1003
|
+
|
|
1004
|
+
`),x=`[Query]
|
|
1005
|
+
${p}
|
|
1006
|
+
|
|
1007
|
+
[Memory Facts]
|
|
1008
|
+
${y}`;return (await r(I,T,x,g??1e3,a)).trim()}m.summarizeMemoryFacts=d;})(ga||(ga={}));a.create({service:"context-token"});function fs(e){return e?Token.estimate(e):0}var gp=800,ha=a.create({service:"dynamic-prompt"}),ya;(l=>{async function e(d){let m=[],{mode:f}=d,a=d.useLLMSummary??true,p=d.maxTokens??gp;if(d.memoryResults&&d.memoryResults.length>0){let u=await t(d.query??"",d.memoryResults,a,p);u&&m.push(u);}if(d.knowledgeResults&&d.knowledgeResults.length>0){let u=await n(d.query??"",d.knowledgeResults,a,p);u&&m.push(u);}if(d.fileChanges&&d.fileChanges.length>0){let u=r(d.fileChanges);m.push(u);}if((d.includeTodos??true)&&d.sessionId)try{let u=await lo.get(d.sessionId),h=o(u);m.push(h);}catch(u){ha.warn("failed to load todos for dynamic prompt",{error:String(u)});}if((d.includeTaskAgents??true)&&d.sessionId)try{let u=await jt.list(d.sessionId),h=s(u);h&&m.push(h);}catch(u){ha.warn("failed to load task agents for dynamic prompt",{error:String(u)});}if(f==="coder"&&d.includeCoderContext){let u=i();m.push(...u);}return ha.debug("dynamic prompt built",{mode:f,parts:m.length,memoryCount:d.memoryResults?.length??0,knowledgeCount:d.knowledgeResults?.length??0,fileChangesCount:d.fileChanges?.length??0,useLLMSummary:a}),m}l.build=e;async function t(d,m,f,a=gp){if(m.length===0)return `<memory>
|
|
1009
|
+
## Memory Summary
|
|
1010
|
+
|
|
1011
|
+
No memory found.
|
|
1012
|
+
</memory>`;if(f)try{return `<memory>
|
|
1013
|
+
## Memory Summary
|
|
1014
|
+
|
|
1015
|
+
${await ga.summarizeMemoryFacts({query:d,facts:m.map(g=>({content:g.snippet,category:g.category,importance:g.importance,source:g.source,score:g.score,createdAt:g.createdAt,nodes:g.nodes?.map(I=>({id:I.id,name:I.name,type:I.type,edges:I.edges?.map(T=>({source:T.source,target:T.target,relation:T.relation,direction:T.source===I.id?"out":"in",targetNode:T.targetNode?{name:T.targetNode.name,type:T.targetNode.type}:void 0}))}))})),maxLength:a})}
|
|
1016
|
+
</memory>`}catch(h){ha.warn("memory LLM summary failed, falling back to basic format",{error:String(h)});}let p=["<memory>","## Memory Search Results","",`Query: ${d||"(no query)"}`,""],u=Math.floor(a/m.length);for(let h=0;h<m.length;h++){let g=m[h],I=new Date(g.createdAt).getTime(),T=(Date.now()-I)/864e5,y=Math.exp(-0.1*T),x=(g.importance-1)/9,b=.35*g.score+.35*y+.3*x;if(p.push(`[${h+1}] Priority: ${b.toFixed(3)}`),p.push(`Category: ${g.category} | Importance: ${g.importance} | Source: ${g.source}`),g.nodes&&g.nodes.length>0){let k=[];for(let O of g.nodes){let U=O.edges&&O.edges.length>0?O.edges.map(D=>` --[${D.source===O.id?"out":"in"}] ${D.relation}--> ${D.targetNode?.name??`node:${D.target}`} (${D.targetNode?.type??"node"})`).join(`
|
|
1017
|
+
`):" (no relations)";k.push(` Node: ${O.name} (${O.type})
|
|
1018
|
+
${U}`);}let v=k.join(`
|
|
1019
|
+
`),C=Math.floor(u*4*.5),E=c(v,C);p.push(`Graph Nodes:
|
|
1020
|
+
${E}`);}let w=Math.max(0,u-fs(p.join(`
|
|
1021
|
+
`)));if(w>30){let k=Math.floor(w*4),v=c(g.snippet,k);p.push(v);}p.push("");}return p.push("</memory>"),p.join(`
|
|
1022
|
+
`)}l.buildMemorySummary=t;async function n(d,m,f,a=gp){if(m.length===0)return `<note>
|
|
1023
|
+
## Knowledge Summary
|
|
1024
|
+
|
|
1025
|
+
No knowledge found.
|
|
1026
|
+
</note>`;if(f)try{return `<note>
|
|
1027
|
+
## Knowledge Summary
|
|
1028
|
+
|
|
1029
|
+
${await ga.summarizeNote({query:d,chunks:m.map(g=>({path:g.chunk.path,content:g.chunk.content,startLine:g.chunk.startLine,endLine:g.chunk.endLine,score:g.score,updatedAt:g.document.updatedAt,nodes:g.nodes?.map(I=>({id:I.id,name:I.name,type:I.type,properties:I.properties,edges:I.edges?.map(T=>{let y=T.source===I.id?"out":"in",x=g.nodes?.find(b=>b.id===T.target);return {direction:y,relation:T.relation,targetId:T.target,targetName:x?.name??String(T.target),targetType:x?.type??"node"}})}))})),maxLength:a})}
|
|
1030
|
+
</note>`}catch(h){ha.warn("knowledge LLM summary failed, falling back to basic format",{error:String(h)});}let p=["<note>","## Knowledge Search Results","",`Query: ${d||"(no query)"}`,""],u=Math.floor(a/m.length);for(let h=0;h<m.length;h++){let g=m[h],I=g.chunk.startLine!=null?`#L${g.chunk.startLine}-L${g.chunk.endLine??g.chunk.startLine}`:"",T=.7*(g.score??0);if(p.push(`[${h+1}] Priority: ${T.toFixed(3)}`),p.push(`Source: [${g.chunk.path}](./${g.chunk.path}${I})`),g.nodes&&g.nodes.length>0){let x=[];for(let v of g.nodes){let C=v.edges&&v.edges.length>0?v.edges.map(E=>` --[${E.source===v.id?"out":"in"}] ${E.relation}--> node:${E.target} (node)`).join(`
|
|
1031
|
+
`):" (no relations)";x.push(` Node: ${v.name} (${v.type})
|
|
1032
|
+
${C}`);}let b=x.join(`
|
|
1033
|
+
`),w=Math.floor(u*4*.5),k=c(b,w);p.push(`Graph Nodes:
|
|
1034
|
+
${k}`);}let y=Math.max(0,u-fs(p.join(`
|
|
1035
|
+
`)));if(y>20){let x=Math.floor(y*4),b=c(g.chunk.content,x);p.push(b);}p.push("");}return p.push("</note>"),p.join(`
|
|
1036
|
+
`)}l.buildKnowledgeSummary=n;function o(d){let m=["<todo>","## Todo List",""];if(!d||d.length===0)return m.push("No todo items. Use the todo tool to add tasks."),m.push("</todo>"),m.join(`
|
|
1037
|
+
`);m.push("The following tasks need to be tracked:","");let f=d.filter(p=>p.status==="pending"),a=d.filter(p=>p.status==="in_progress");if(a.length>0){m.push("### In Progress");for(let p of a){let u=p.priority?` [${p.priority.toUpperCase()}]`:"";m.push(`- [ ] ${p.content}${u}`);}m.push("");}if(f.length>0){m.push("### Pending");for(let p of f){let u=p.priority?` [${p.priority.toUpperCase()}]`:"";m.push(`- [ ] ${p.content}${u}`);}m.push("");}return m.push("</todo>"),m.join(`
|
|
1038
|
+
`)}l.buildTodosSummary=o;function s(d){let m=["<tasks>","## Agent Tasks",""];if(!d||d.length===0)return m.push("No running tasks."),m.push("</tasks>"),m.join(`
|
|
1039
|
+
`);let f=d.filter(u=>u.status==="running"),a=d.filter(u=>u.status==="pending"),p=d.filter(u=>u.status==="error");if(f.length===0&&a.length===0&&p.length===0)return m.push("No active tasks."),m.push("</tasks>"),m.join(`
|
|
1040
|
+
`);if(m.push("Active tasks (pending/running):",""),f.length>0){m.push("### Running");for(let u of f)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\``);m.push("");}if(a.length>0){m.push("### Pending");for(let u of a)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\``);m.push("");}if(p.length>0){m.push("### Failed");for(let u of p)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\` - ${u.error||"unknown error"}`);m.push("");}return m.push("</tasks>"),m.join(`
|
|
1041
|
+
`)}l.buildTaskAgentSummary=s;function r(d){if(d.length===0)return "";let m=["<changes>","## Recently Changed Files","The following files have been modified since your last check:",""];for(let f of d)m.push(`- ${f.path}`),f.newMtime===0?m.push(" Status: deleted"):m.push(` Modified: ${new Date(f.newMtime).toISOString()}`);return m.push(""),m.push("Consider reading these files if relevant to the current task."),m.push("</changes>"),m.join(`
|
|
1042
|
+
`)}l.buildFileChangesSummary=r;function i(d){return []}l.buildCoderContext=i;function c(d,m){if(d.length<=m)return d;let a=d.slice(0,m).lastIndexOf(`
|
|
1043
|
+
`),p=a>m*.8?a:m;return d.slice(0,p).trimEnd()+`
|
|
1044
|
+
[...truncated...]`}})(ya||(ya={}));var IR=loadTextFile("./prompt/anthropic.txt",import.meta.url)(),vR=loadTextFile("./prompt/default.txt",import.meta.url)(),SR=loadTextFile("./prompt/beast.txt",import.meta.url)(),CR=loadTextFile("./prompt/gemini.txt",import.meta.url)(),kR=loadTextFile("./prompt/codex.txt",import.meta.url)(),PR=loadTextFile("./prompt/gpt.txt",import.meta.url)(),TR=loadTextFile("./prompt/trinity.txt",import.meta.url)(),AR=loadTextFile("./prompt/kimi.txt",import.meta.url)(),ER=loadTextFile("./prompt/qwen.txt",import.meta.url)(),RR=loadTextFile("./prompt/glm.txt",import.meta.url)(),_R=loadTextFile("./prompt/minimax.txt",import.meta.url)();function hp(e){let t=e.model.id.toLowerCase(),n=e.protocolMetadata;return t.includes("gpt-4")||t.includes("o1")||t.includes("o3")?[a$9.replaceVariables(SR,n)]:t.includes("gpt")?t.includes("codex")?[a$9.replaceVariables(kR,n)]:[PR]:t.includes("gemini-")?[a$9.replaceVariables(CR,n)]:t.includes("claude")?[a$9.replaceVariables(IR,n)]:t.includes("trinity")?[a$9.replaceVariables(TR,n)]:t.includes("kimi")?[a$9.replaceVariables(AR,n)]:t.includes("qwen")?[a$9.replaceVariables(ER,n)]:t.includes("glm")?[a$9.replaceVariables(RR,n)]:t.includes("minimax")?[a$9.replaceVariables(_R,n)]:[a$9.replaceVariables(vR,n)]}function MR(e){return e==="coder"?["<guidelines>","## Mode: Coder","You are operating in coding assistant mode.","Focus on code-related tasks: reading, writing, editing, and explaining code.","Use tools efficiently to explore the codebase and complete coding tasks.","","## Working Guidelines","","**CRITICAL: Explore code first before implementing**","You MUST use these tools to explore the codebase:","- `Grep` - Search code patterns and function calls","- `Glob` - Find files matching patterns","- `Read` - Read full file contents","- `codebase` - Query code knowledge graph","","**Recommended workflow:**","1. Search existing implementations using Grep/codebase","2. Read related files using Read tool","3. Check existing tests to understand behavior","4. Query memory/note for relevant past experiences","5. Then implement based on what you found","","**Plan before implementing**","- `todo` - Create and update and read todo list before implementing","","**External knowledge:**","- `codesearch` - Search and get relevant context for any programming task using Exa Code API","- `websearch` - Search the web","- `webfetch` - Fetch web page content","","**Writing code:**","- Use `write` tool to create or overwrite files","- Use `edit` tool for incremental changes","- Always verify with tests after writing","","**Fallback:**","- `Bash` - When other tools are insufficient","","</guidelines>"]:["<guidelines>","## Mode: General","You are operating in general assistant mode.","You can help with a wide range of tasks including coding, analysis, writing, and more.","","## Working Guidelines","","**CRITICAL: Plan before executing**","- `todo` - Create and update and read todo list","","**Proactively gather context before responding:**","- `Grep` - Search code patterns and function calls","- `Glob` - Find files matching patterns","- `Read` - Read file contents","","**External knowledge:**","- `websearch` - Search the web","- `webfetch` - Fetch web page content","","**Writing file:**","- `write` - Create or overwrite files","- `edit` - Incremental changes","","**Always consider:**","- User intent and preferences","- Relevant historical context","- Available tools and their capabilities","","**Fallback:**","- `Bash` - When other tools are insufficient","","</guidelines>"]}async function OR(e,t){if(Me.disabled(["skill"],e.permission).has("skill"))return [];let n=await Vt.available(e,t);return ["<skills>",Vt.format(n,{verbose:false}),"</skills>"]}async function yp(e){let{Instance:t}=await import('./instance-YVRWMB6M.mjs'),n=t.project,o=new Date,s=Intl.DateTimeFormat().resolvedOptions().timeZone,r=[];return r.push("<env>"),r.push("Here is some useful information about the environment you are running in:"),r.push(` Current model: ${e.model.id}`),r.push(` Agent ID: ${e.protocolMetadata.agentId}`),r.push(` Workspace directory: ${t.directory}`),r.push(` Worktree root folder: ${t.worktree}`),r.push(` Is directory a git repo: ${n.vcs==="git"?"yes":"no"}`),r.push(` Platform: ${process.platform}`),r.push(` Local time: ${formatLocalISOCompact(o)} (${s})`),r.push(` UTC time: ${o.toISOString()}`),r.push("</env>"),r.push(...MR(e.mode)),r.push(...await OR(e.agent,e.mode)),[r.join(`
|
|
1045
|
+
`)]}var ba=a.create({service:"context-search"});async function bp(e,t,n){try{let o=await In.get();return !o||!t?[]:await o.query(t,{agentId:e.agent.name,maxResults:n,minScore:.2})}catch(o){return ba.warn("memory search error",{error:String(o)}),[]}}async function wp(e,t,n){try{let o=await Yt.get();if(!o||!t)return ba.debug("searchKnowledge: kb or query not available",{kb:!!o,query:!!t}),[];ba.debug("searchKnowledge: calling kb.search",{query:t,maxResults:n,minScore:.3});let s=await o.search(t,{maxResults:n,minScore:.3});return ba.debug("searchKnowledge: kb.search returned",{query:t,resultsCount:s.length,results:s.map(r=>({score:r.score,path:r.document.path}))}),s}catch(o){return ba.warn("knowledge search error",{error:String(o)}),[]}}var Qs=a.create({service:"context-engine"}),LR=loadTextFile("./prompt/max-steps.txt",import.meta.url),DR=LR(),$R=loadTextFile("./prompt/plan.txt",import.meta.url),FR=$R(),NR=loadTextFile("./prompt/coder-plan.txt",import.meta.url),UR=NR(),zR=loadTextFile("./prompt/build-switch.txt",import.meta.url),Ry=zR();function vp(e,t,n){let o=n?`A plan file already exists at ${t}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${t} using the write tool.`;return e.replace("{{planFileInfo}}",o)}var mo;(x=>{let e,t;async function n(){return t||(t=hi().then(b=>({mode:b.mode??f$1,fileCacheMaxEntries:b.fileCache?.maxEntries??100,fileCacheMaxBytes:b.fileCache?.maxBytes??25*1024*1024,maxTokens:b.maxTokens??2e3,searchMaxResults:b.searchMaxResults??3}))),t}function o(){return e||(e=R.state(async()=>{let b=await n(),w=R.directory,k={workspace:w,name:"EasBot",userName:"",mission:""},v=false;try{let C=Se__default.join(w,".easbot"),E=Se__default.join(C,"protocol.json"),O=await Tt__default.readFile(E,"utf-8"),U=JSON.parse(O);U.metadata&&(k={agentId:U.metadata.agentId,workspace:U.metadata.workspace||w,name:U.metadata.name||"EasBot",userName:U.metadata.userName||"",mission:U.metadata.mission||""}),v=typeof U.setupCompletedAt=="string"&&U.setupCompletedAt.trim().length>0;}catch{Qs.debug("protocol.json not found, using default metadata");}return {config:b,initialized:true,protocolInitialized:v,fileCache:ei(),protocolMetadata:k}})),e}async function s(){return o()()}function r(b){t=Promise.resolve({mode:b.mode??f$1,fileCacheMaxEntries:b.fileCacheMaxEntries??100,fileCacheMaxBytes:b.fileCacheMaxBytes??25*1024*1024,maxTokens:b.maxTokens??2e3,searchMaxResults:b.searchMaxResults??3}),Qs.info("context engine configured",{mode:b.mode,maxTokens:b.maxTokens,searchMaxResults:b.searchMaxResults});}x.configure=r;async function i(){return (await s()).config}x.getConfig=i;async function c(b){let w=await s();return !w.protocolInitialized&&!w.protocolMetadata.agentId&&b&&(w.protocolMetadata.agentId=b.name),w.protocolMetadata}x.getProtocolMetadata=c;async function l(){let b=await s();return {protocolMetadata:b.protocolMetadata,protocolInitialized:b.protocolInitialized}}x.getContext=l;function d(){return ei()}x.getFileCache=d;function m(b){let w=[];for(let k of b.parts)k.type==="text"&&k.text&&w.push(k.text);return w.join(" ").trim()}x.extractQuery=m;async function f(b){let w=await Le.triggerEvent(HookEvent.ContextBuildBefore,b,{sessionId:b.sessionId});w.modified&&w.output&&(b=w.output);let k=await s();k.protocolMetadata.agentId||(k.protocolMetadata.agentId=b.agent.name);let v=b.mode??k.config.mode??f$1,C=b.maxTokens??k.config.maxTokens??2e3,E=b.searchMaxResults??k.config.searchMaxResults??3,O=m(b.userMessage),[U,D]=[bp(b,O,E).catch(V=>(Qs.warn("memory search failed",{error:String(V)}),[])),wp(b,O,E).catch(V=>(Qs.warn("knowledge search failed",{error:String(V)}),[]))],K=Xs.buildStaticPrompt({mode:v,workspaceDir:b.session.directory,agent:b.agent,model:b.model,protocolMetadata:k.protocolMetadata,protocolInitialized:k.protocolInitialized}),[X,$,M]=await Promise.all([K,U,D]),A=k.protocolMetadata,L=X.map(V=>V.name),S=X.map(V=>V.content),P=await ya.build({query:O,mode:v,sessionId:b.sessionId,memoryResults:$,knowledgeResults:M,includeTodos:true,includeCoderContext:v==="coder",useLLMSummary:true,maxTokens:C}),_=await a({sessionId:b.sessionId,model:b.model,agent:b.agent,user:b.user,workspace:b.session.directory,staticPrompt:S,staticPromptSources:L,dynamicParts:P,maxChars:C*4,protocolMetadata:k.protocolMetadata,mode:v}),{messages:j,lastUserMessage:B,lastAssistantMessage:Z}=await p(b),ee=h(j,_),se=b.model.limit?.context??0,le=se>0?se:xe.DEFAULT_CONTEXT_LIMIT,we=Math.max(le-2e4,5e4)-ee,re=on.calculateTokenUsageState(ee,b.model),Q=re.isAboveAutoCompactThreshold||re.isAtBlockingLimit;re.isAboveWarningThreshold&&Qs.warn("context window running low",{remaining:we,tokenEstimate:ee,percentLeft:re.percentLeft,needsCompaction:Q});let H={sessionId:b.sessionId,isLastStep:b.isLastStep??false,mode:v,messageCount:j.length,tokenEstimate:ee,remaining:we,sources:g(v,$.length>0,M.length>0),memoryResults:$.length,knowledgeResults:M.length,lastUserMessage:B,lastAssistantMessage:Z,needsCompaction:Q,protocolMetadata:A};Qs.debug("context build completed",{...H,lastUserMessage:B?.info.id,lastAssistantMessage:Z?.info.id});let F={system:_,messages:j,tools:b.tools,model:b.model,agent:b.agent,session:b.session,metadata:H},te=await Le.triggerEvent(HookEvent.ContextBuildAfter,{context:F},{sessionId:b.sessionId});return te.modified&&te.output?te.output.context:F}x.build=f;async function a(b){let {sessionId:w,model:k,agent:v,user:C,staticPrompt:O,staticPromptSources:U,dynamicParts:D,maxChars:K,protocolMetadata:X,mode:$}=b;await xe.getProvider(k.providerId);await Qe.get(k.providerId);let L=[];v.prompt&&v.prompt.trim().length>0?L.push(a$9.replaceVariables(v.prompt,X)):L.push(...hp({model:k,protocolMetadata:X}));for(let S=0;S<O.length;S++){let P=U?.[S]??`template-${S}`,_=await TruncateContent.truncate(O[S],{label:"static prompt",sourcePath:P,maxChars:K});L.push(_.content);}if(L.push(...await yp({model:k,mode:$,agent:v,protocolMetadata:X})),L.push(...D),C.system){let S=await TruncateContent.truncate(C.system,{label:"user system prompt",maxChars:K});L.push(S.content);}return await Le.triggerEvent(HookEvent.SystemTransform,{sessionId:w,model:k}),L}async function p(b){let w=clone(b.messages),k=b.mode??f$1;for(let K=w.length-1;K>=0;K--){let X=w[K];if(X&&X.info.role==="assistant"&&X.info.finish){break}}(b.includeReminders??true)&&await u(w,{agent:b.agent,session:b.session,userMessageId:b.userMessage.info.id,lastFinished:b.lastFinished,step:b.step??1,isLastStep:b.isLastStep??false,mode:k});let E=w;b.maxMessages&&b.maxMessages>0&&(E=w.slice(-b.maxMessages));let O=await ve.toModelMessages(E,b.model);b.isLastStep&&O.push({role:"assistant",content:[{type:"text",text:DR}]});let U=w.findLast(K=>K.info.role==="user"),D=w.findLast(K=>K.info.role==="assistant");return {messages:O,lastUserMessage:U,lastAssistantMessage:D}}async function u(b,w){let{agent:k,session:v,lastFinished:C,step:E,isLastStep:O,mode:U}=w,D=b.findLast(A=>A.info.role==="user");if(!D)return;let K=U==="coder"?UR:FR,X=Y.plan(v),$=false;try{await Tt__default.access(X),$=!0;}catch{$=false;}let M=vp(K,X,$);if(!a$2.EASBOT_PLAN_MODE)k.name==="plan"&&D.parts.push({id:Identifier.ascending("part"),messageId:D.info.id,sessionId:D.info.sessionId,type:"text",text:M,synthetic:true}),b.some(L=>L.info.role==="assistant"&&L.info.agent==="plan")&&k.name==="build"&&D.parts.push({id:Identifier.ascending("part"),messageId:D.info.id,sessionId:D.info.sessionId,type:"text",text:vp(Ry,X,$),synthetic:true});else {let A=b.findLast(L=>L.info.role==="assistant");if(k.name!=="plan"&&A?.info.agent==="plan"){if($){let L=await Y.updatePart({id:Identifier.ascending("part"),messageId:D.info.id,sessionId:D.info.sessionId,type:"text",text:vp(Ry,X,$),synthetic:true});D.parts.push(L);}return}if(k.name==="plan"&&A?.info.agent!=="plan"){$||await Tt__default.mkdir(Se__default.dirname(X),{recursive:true});let L=await Y.updatePart({id:Identifier.ascending("part"),messageId:D.info.id,sessionId:D.info.sessionId,type:"text",text:M,synthetic:true});D.parts.push(L);return}}if(E>1&&C&&!O){for(let A of b)if(!(A.info.role!=="user"||A.info.id<=C.info.id))for(let L of A.parts)L.type!=="text"||L.ignored||L.synthetic||L.text?.trim()&&(L.text=`<system-reminder>
|
|
1046
|
+
The user sent the following message:
|
|
1047
|
+
`+L.text+`
|
|
1048
|
+
|
|
1049
|
+
Please address this message and continue with your tasks.
|
|
1050
|
+
</system-reminder>`);}await Le.triggerEvent(HookEvent.MessageTransform,{sessionId:w.session.id,userMessageId:w.userMessageId});}function h(b,w){let k=0;if(w)for(let v of w)k+=fs(v);for(let v of b)if(v.content){if(typeof v.content=="string")k+=fs(v.content);else if(Array.isArray(v.content)){for(let C of v.content)if(typeof C=="object"&&C!==null){let E=C;typeof E.text=="string"&&(k+=fs(E.text));}}}return k}x.tokenCountWithEstimation=h;function g(b,w,k){let v=["system","history","tools","templates"];return w&&v.push("memory"),k&&v.push("knowledge"),b==="coder"&&v.push("coder-context"),v}function I(b,w){Xs.invalidateCache(b,w);}x.invalidateCache=I;function T(){return Xs.getCacheStats()}x.getCacheStats=T;async function y(){(await s()).fileCache.clear(),Qs.debug("file cache reset");}x.resetFileCache=y;})(mo||(mo={}));var Y;(S=>{let e$1=a.create({service:"session"});function t(P=false){return SessionTitle.createDefault(P)}S.createDefaultTitle=t;function n(P){return SessionTitle.isDefault(P)}S.isDefaultTitle=n;function o(P){return SessionTitle.getForked(P)}S.Info=N.object({id:Identifier.schema("session"),slug:N.string(),providerId:N.string(),directory:N.string(),parentId:Identifier.schema("session").optional(),contextMode:N.enum(e).optional(),summary:N.object({additions:N.number(),deletions:N.number(),files:N.number(),diffs:yt.FileDiff.array().optional()}).optional(),share:N.object({url:N.string()}).optional(),title:N.string(),version:N.string(),time:N.object({created:N.number(),updated:N.number(),compacting:N.number().optional(),archived:N.number().optional()}),permission:Me.Ruleset.optional(),revert:N.object({messageId:N.string(),partId:N.string().optional(),snapshot:N.string().optional(),diff:N.string().optional()}).optional()}).meta({ref:"Session"}),S.ProjectInfo=N.object({id:N.string(),name:N.string().optional(),worktree:N.string()}).meta({ref:"ProjectSummary"}),S.GlobalInfo=S.Info.extend({project:S.ProjectInfo.nullable()}).meta({ref:"GlobalSession"}),S.ShareInfo=N.object({secret:N.string(),url:N.string()}).meta({ref:"SessionShare"}),S.Event={Created:a$5.define("session.created",N.object({info:S.Info})),Updated:a$5.define("session.updated",N.object({info:S.Info})),Deleted:a$5.define("session.deleted",N.object({info:S.Info})),Diff:a$5.define("session.diff",N.object({sessionId:N.string(),diff:yt.FileDiff.array()})),Error:a$5.define("session.error",N.object({sessionId:N.string().optional(),error:ve.Assistant.shape.error})),ContextModeChanged:a$5.define("session.context_mode_changed",N.object({sessionId:N.string(),contextMode:N.enum(e)}))},S.create=fn$1(N.object({parentId:Identifier.schema("session").optional(),title:N.string().optional(),directory:N.string().optional(),permission:S.Info.shape.permission,contextMode:S.Info.shape.contextMode}).optional(),async P=>a$3({parentId:P?.parentId,directory:P?.directory??R.directory,title:P?.title,permission:P?.permission,contextMode:P?.contextMode})),S.fork=fn$1(N.object({sessionId:Identifier.schema("session"),directory:N.string().optional(),messageId:Identifier.schema("message").optional(),contextMode:S.Info.shape.contextMode}),async P=>{let _=await(0, S.get)(P.sessionId);if(!_)throw new Error("session not found");let j=o(_.title),B=await a$3({directory:P?.directory??_.directory??R.directory,title:j,contextMode:P.contextMode}),Z=await(0, S.messages)({sessionId:P.sessionId}),ee=new Map;for(let se of Z){if(P.messageId&&se.info.id>=P.messageId)break;let le=Identifier.ascending("message");ee.set(se.info.id,le);let ae=se.info.role==="assistant"&&se.info.parentId?ee.get(se.info.parentId):void 0,we=await(0, S.updateMessage)({...se.info,sessionId:B.id,id:le,...ae&&{parentId:ae}});for(let re of se.parts)await(0, S.updatePart)({...re,id:Identifier.ascending("part"),messageId:we.id,sessionId:B.id});}return B}),S.touch=fn$1(Identifier.schema("session"),async P=>{await w(P,_=>{_.time.updated=Date.now();});});async function a$3(P){let _=await he.get(),j={id:Identifier.descending("session",P.id),slug:Slug.create(),version:b$3.getVersion(),providerId:R.project.id,directory:P.directory,parentId:P.parentId,contextMode:P.contextMode??_.context?.mode,title:P.title??t(!!P.parentId),permission:P.permission,time:{created:Date.now(),updated:Date.now()}};return e$1.debug("created",j),await a$6.write(["session",R.project.id,j.id],j),await pe.publish(S.Event.Created,{info:j}),!j.parentId&&(a$2.EASBOT_AUTO_SHARE||_.share==="auto")&&(0, S.share)(j.id).then(B=>{w(j.id,Z=>{Z.share=B;});}).catch(()=>{}),await pe.publish(S.Event.Updated,{info:j}),j}S.createNext=a$3;function p(P){let _=R.project.vcs?Se__default.join(R.worktree,".easbot","plans"):Se__default.join(a$1.Path.data,"plans");return Se__default.join(_,[P.time.created,P.slug].join("-")+".md")}S.plan=p,S.get=fn$1(Identifier.schema("session"),async P=>await a$6.read(["session",R.project.id,P])),S.getShare=fn$1(Identifier.schema("session"),async P=>a$6.read(["share",P])),S.getProjectInfo=fn$1(N.void(),async()=>({id:R.project.id,name:R.project.name,worktree:R.worktree})),S.getGlobalInfo=fn$1(Identifier.schema("session"),async P=>{let _=await(0, S.get)(P);if(_)return {..._,project:{id:R.project.id,name:R.project.name,worktree:R.worktree}}});async function T(P){let _=await(0, S.get)(P);if(_?.contextMode)return _.contextMode;let j=await he.get();return j.context?.mode?j.context.mode:"general"}S.getContextMode=T;async function y(P,_){if(!e.includes(_))throw new Error(`Invalid contextMode: ${_}. Must be one of: ${e.join(", ")}`);await w(P,j=>{j.contextMode=_;}),await pe.publish(S.Event.ContextModeChanged,{sessionId:P,contextMode:_});}S.setContextMode=y,S.share=fn$1(Identifier.schema("session"),async P=>{if((await he.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let{Share:j}=await import('./share-45SYUA47.mjs'),B=await j.create(P);return await w(P,Z=>{Z.share={url:B.url};},{touch:false}),B}),S.unshare=fn$1(Identifier.schema("session"),async P=>{let{Share:_}=await import('./share-45SYUA47.mjs');await _.remove(P),await w(P,j=>{j.share=void 0;},{touch:false});});async function w(P,_,j){let B=R.project,Z=await a$6.update(["session",B.id,P],ee=>{_(ee),j?.touch!==false&&(ee.time.updated=Date.now());});return await pe.publish(S.Event.Updated,{info:Z}),Z}S.update=w,S.diff=fn$1(Identifier.schema("session"),async P=>await a$6.read(["session_diff",P])??[]),S.messages=fn$1(N.object({sessionId:Identifier.schema("session"),limit:N.number().optional()}),async P=>{let _=[];for await(let j of ve.stream(P.sessionId)){if(P.limit&&_.length>=P.limit)break;_.push(j);}return _.reverse(),_});async function*C(){let P=R.project;for(let _ of await a$6.list(["session",P.id])){let j=await a$6.read(_).catch(()=>{});j&&(yield j);}}S.list=C,S.children=fn$1(Identifier.schema("session"),async P=>{let _=R.project,j=[];for(let B of await a$6.list(["session",_.id])){let Z=await a$6.read(B).catch(()=>{});Z&&Z.parentId===P&&j.push(Z);}return j}),S.remove=fn$1(Identifier.schema("session"),async P=>{let _=R.project;try{let j=await(0,S.get)(P);for(let B of await(0,S.children)(P))await(0,S.remove)(B.id);await(0,S.unshare)(P).catch(()=>{});for(let B of await a$6.list(["message",P])){let Z=B.at(-1);for(let le of await a$6.list(["part",Z]))await a$6.remove(le);let ee=await a$6.dir(["part",Z]);await a$6.rmdir(ee).catch(()=>{}),await a$6.remove(B);let se=await a$6.dir(["message",P]);await a$6.rmdir(se).catch(()=>{});}await a$6.remove(["session",_.id,P]),await a$6.remove(["tui",P]).catch(()=>{}),await pe.publish(S.Event.Deleted,{info:j});}catch(j){e$1.error(j);}}),S.updateMessage=fn$1(ve.Info,async P=>(await a$6.write(["message",P.sessionId,P.id],P),pe.publish(ve.Event.Updated,{info:P}),P)),S.removeMessage=fn$1(N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message")}),async P=>(await a$6.remove(["message",P.sessionId,P.messageId]),pe.publish(ve.Event.Removed,{sessionId:P.sessionId,messageId:P.messageId}),P.messageId)),S.removePart=fn$1(N.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part")}),async P=>(await a$6.remove(["part",P.messageId,P.partId]),pe.publish(ve.Event.PartRemoved,{sessionId:P.sessionId,messageId:P.messageId,partId:P.partId}),P.partId));let X=N.union([ve.Part,N.object({part:ve.TextPart,delta:N.string()}),N.object({part:ve.ReasoningPart,delta:N.string()})]);S.updatePart=fn$1(X,async P=>{let _="delta"in P?P.part:P,j="delta"in P?P.delta:void 0;return await a$6.write(["part",_.messageId,_.id],_),pe.publish(ve.Event.PartUpdated,{part:_,delta:j,time:Date.now()}),_}),S.getUsage=fn$1(N.object({model:N.custom(),usage:N.custom(),metadata:N.custom().optional()}),P=>{let _=H=>Number.isFinite(H)?H:0,j=_(P.usage.inputTokens??0),B=_(P.usage.outputTokens??0),Z=_(P.usage.reasoningTokens??0),ee=_(P.usage.cachedInputTokens??0),se=_(P.metadata?.anthropic?.cacheCreationInputTokens??P.metadata?.bedrock?.usage?.cacheWriteInputTokens??P.metadata?.venice?.usage?.cacheCreationInputTokens??0),le=!!(P.metadata?.anthropic||P.metadata?.bedrock),ae=_(le?j:j-ee-se),re={total:iife(()=>P.model.api.npm==="@ai-sdk/anthropic"||P.model.api.npm==="@ai-sdk/amazon-bedrock"||P.model.api.npm==="@ai-sdk/google-vertex/anthropic"?ae+B+ee+se:P.usage.totalTokens),input:ae,output:B,reasoning:Z,cache:{write:se,read:ee}},Q=P.model.cost?.experimentalOver200K&&re.input+re.cache.read>2e5?P.model.cost.experimentalOver200K:P.model.cost;return {cost:_(new Decimal(0).add(new Decimal(re.input).mul(Q?.input??0).div(1e6)).add(new Decimal(re.output).mul(Q?.output??0).div(1e6)).add(new Decimal(re.cache.read).mul(Q?.cache?.read??0).div(1e6)).add(new Decimal(re.cache.write).mul(Q?.cache?.write??0).div(1e6)).add(new Decimal(re.reasoning).mul(Q?.output??0).div(1e6)).toNumber()),tokens:re}});class A extends Error{constructor(j){super(`Session ${j} is busy`);b$1(this,"sessionId",j);}}S.BusyError=A,S.initialize=fn$1(N.object({sessionId:Identifier.schema("session"),modelId:N.string(),providerId:N.string(),messageId:Identifier.schema("message")}),async P=>{await Je.command({sessionId:P.sessionId,messageId:P.messageId,model:P.providerId+"/"+P.modelId,command:vn.Default.INIT,arguments:""});});})(Y||(Y={}));var Ut;(a$1=>{let e=a.create({service:"project"});a$1.Info=N.object({id:N.string(),worktree:N.string(),vcs:N.literal("git").optional(),name:N.string().optional(),icon:N.object({url:N.string().optional(),override:N.string().optional(),color:N.string().optional()}).optional(),commands:N.object({start:N.string().optional().describe("Startup script to run when creating a new workspace (worktree)")}).optional(),time:N.object({created:N.number(),updated:N.number(),initialized:N.number().optional()}),sandboxes:N.array(N.string())}).meta({ref:"Project"}),a$1.Event={Updated:a$5.define("project.updated",a$1.Info)};async function o(p){e.debug("fromDirectory",{directory:p});let{id:u,sandbox:h,worktree:g,vcs:I}=await iife(async()=>{let x=Filesystem.up({targets:[".git"],start:p}),b=await x.next().then(k=>k.value);if(await x.return(void 0),b){let k=Se__default.dirname(b),v=await PKG.which("git"),C=await Tt__default.readFile(Se__default.join(b,"easbot"),"utf-8").then(U=>U.trim()).catch(()=>{});if(!v)return {id:C??"global",worktree:k,sandbox:k,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};if(!C){let U=await $`git rev-list --max-parents=0 --all`.quiet().nothrow().cwd(k).text().then(D=>D.split(`
|
|
1051
|
+
`).filter(Boolean).map(K=>K.trim()).toSorted()).catch(()=>{});if(!U)return {id:"global",worktree:k,sandbox:k,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};C=U[0],C&&Tt__default.writeFile(Se__default.join(b,"easbot"),C).catch(()=>{});}if(!C)return {id:"global",worktree:k,sandbox:k,vcs:"git"};let E=await $`git rev-parse --show-toplevel`.quiet().nothrow().cwd(k).text().then(U=>Se__default.resolve(k,U.trim())).catch(()=>{});if(!E)return {id:C,sandbox:k,worktree:k,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};k=E;let O=await $`git rev-parse --git-common-dir`.quiet().nothrow().cwd(k).text().then(U=>{let D=Se__default.dirname(U.trim());return D==="."?k:D}).catch(()=>{});return O?{id:C,sandbox:k,worktree:O,vcs:"git"}:{id:C,sandbox:k,worktree:k,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)}}let w=p||process.cwd();return {id:"global",worktree:w,sandbox:w,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)}}),T=await a$6.read(["project",u]).catch(()=>{});T||(T={id:u,worktree:g,vcs:I,sandboxes:[],time:{created:Date.now(),updated:Date.now()}},u!=="global"&&await r(u,g)),T?.sandboxes||(T.sandboxes=[]),a$2.EASBOT_ICON_DISCOVERY&&await s(T);let y={...T,worktree:g,vcs:I,time:{...T?.time,updated:Date.now()}};return h!==y.worktree&&!y.sandboxes.includes(h)&&y.sandboxes.push(h),y.sandboxes=y.sandboxes.filter(x=>existsSync(x)),await a$6.write(["project",u],y),ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:y}}),{project:y,sandbox:h}}a$1.fromDirectory=o;async function s(p){if(p.vcs!=="git"||p.icon?.override||p.icon?.url)return;let h=(await glob("**/{favicon}.{ico,png,svg,jpg,jpeg,webp}",{cwd:p.worktree,absolute:true,nodir:true,follow:false,dot:false})).sort((w,k)=>w.length-k.length)[0];if(!h)return;let I=(await Tt__default.readFile(h)).toString("base64"),T=Se__default.extname(h).toLowerCase(),b=`data:${{".ico":"image/x-icon",".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"}[T]||"image/png"};base64,${I}`;await(0, a$1.update)({providerId:p.id,icon:{url:b}});}a$1.discover=s;async function r(p,u){if(!await a$6.read(["project","global"]).catch(()=>{}))return;let g=await a$6.list(["session","global"]).catch(()=>[]);g.length!==0&&(e.info("migrating sessions from global",{newProjectID:p,worktree:u,count:g.length}),await work(10,g,async I=>{let T=I[I.length-1]??"",y=await a$6.read(I).catch(()=>{});y&&(y.directory&&y.directory!==u||(y.providerId=p,e.debug("migrating session",{sessionId:T,from:"global",to:p}),await a$6.write(["session",p,T],y),await a$6.remove(I)));}).catch(I=>{e.error("failed to migrate sessions from global to project",{error:I,projectId:p});}));}async function i(p){await a$6.update(["project",p],u=>{u.time.initialized=Date.now();});}a$1.setInitialized=i;async function c(){let p=await a$6.list(["project"]);return (await Promise.all(p.map(h=>a$6.read(h)))).map(h=>({...h,sandboxes:h.sandboxes?.filter(g=>existsSync(g))}))}a$1.list=c,a$1.update=fn$1(N.object({providerId:N.string(),name:N.string().optional(),icon:a$1.Info.shape.icon.optional(),commands:a$1.Info.shape.commands.optional()}),async p=>{let u=await a$6.update(["project",p.providerId],h=>{if(p.name!==void 0&&(h.name=p.name),p.icon!==void 0&&(h.icon={...h.icon},p.icon.url!==void 0&&(h.icon.url=p.icon.url),p.icon.override!==void 0&&(h.icon.override=p.icon.override||void 0),p.icon.color!==void 0&&(h.icon.color=p.icon.color)),p.commands?.start!==void 0){let g=p.commands.start||void 0;h.commands={...h.commands??{}},h.commands.start=g,h.commands.start||(h.commands=void 0);}h.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:u}}),u});async function d(p){let u=await a$6.read(["project",p]).catch(()=>{});if(!u?.sandboxes)return [];let h=[];for(let g of u.sandboxes)(await Tt__default.stat(g).catch(()=>{}))?.isDirectory()&&h.push(g);return h}a$1.sandboxes=d;async function m(p,u){let h=await a$6.update(["project",p],g=>{let I=g.sandboxes??[];I.includes(u)||I.push(u),g.sandboxes=I,g.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:h}}),h}a$1.addSandbox=m;async function f(p,u){let h=await a$6.update(["project",p],g=>{let I=g.sandboxes??[];g.sandboxes=I.filter(T=>T!==u),g.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:h}}),h}a$1.removeSandbox=f;})(Ut||(Ut={}));var wa;(s=>{let e=a.create({service:"state"}),t=new Map;function n(r,i,c){return ()=>{let l=r(),d=t.get(l);d||(d=new Map,t.set(l,d));let m=d.get(i);if(m)return m.state;let f=i();return d.set(i,{state:f,dispose:c}),f}}s.create=n;async function o(r){let i=t.get(r);if(!i)return;e.info("waiting for state disposal to complete",{key:r});let c=false;setTimeout(()=>{c||e.warn("state disposal is taking an unusually long time - if it does not complete in a reasonable time, please report this as a bug",{key:r});},1e4).unref();let l=[];for(let[d,m]of i){if(!m.dispose)continue;let f=typeof d=="function"?d.name:String(d),a=Promise.resolve(m.state).then(p=>m.dispose(p)).catch(p=>{e.error("Error while disposing state:",{error:p,key:r,init:f});});l.push(a);}await Promise.all(l),i.clear(),t.delete(r),c=true,e.info("state disposal completed",{key:r});}s.dispose=o;})(wa||(wa={}));var si=Context.create("instance"),gs=new Map,xa={all:void 0},R={async provide(e){let t=gs.get(e.directory);t||(a.Default.info("creating instance",{directory:e.directory}),t=iife(async()=>{let{project:o,sandbox:s}=await Ut.fromDirectory(e.directory),r={directory:e.directory,worktree:s,project:o};return await si.provide(r,async()=>{await e.init?.();}),r}),gs.set(e.directory,t));let n=await t;return si.provide(n,async()=>e.fn())},get directory(){return si.use().directory},get worktree(){return si.use().worktree},get project(){return si.use().project},containsPath(e){return Filesystem.contains(R.directory,e)?true:R.worktree==="/"?false:Filesystem.contains(R.worktree,e)},state(e,t){return wa.create(()=>R.directory,e,t)},async dispose(){a.Default.info("disposing instance",{directory:R.directory}),await wa.dispose(R.directory),gs.delete(R.directory),ft.emit("event",{directory:R.directory,payload:{type:"server.instance.disposed",properties:{directory:R.directory}}});},async disposeAll(){return xa.all||(xa.all=iife(async()=>{a.Default.info("disposing all instances");let e=[...gs.entries()];for(let[t,n]of e){if(gs.get(t)!==n)continue;let o=await n.catch(s=>{a.Default.warn("instance dispose failed",{key:t,error:s});});if(!o){gs.get(t)===n&&gs.delete(t);continue}gs.get(t)===n&&await si.provide(o,async()=>{await R.dispose();});}}).finally(()=>{xa.all=void 0;})),xa.all}};var pe;(f=>{let e=a.create({service:"bus"});f.InstanceDisposed=a$5.define("server.instance.disposed",N.object({directory:N.string()}));let n;function o(){return n||(n=R.state(async()=>({subscriptions:new Map}),async a=>{let p=a.subscriptions.get("*");if(!p)return;let u={type:f.InstanceDisposed.type,properties:{directory:R.directory}};for(let h of [...p])h(u);})),n}function s(){return o()()}async function r(a,p){let u={type:a.type,properties:p};e.debug("publishing",{type:a.type});let h=[],g=await s();for(let I of [a.type,"*"]){let T=g.subscriptions.get(I);for(let y of T??[])h.push(y(u));}return ft.emit("event",{directory:R.directory,payload:u}),Promise.all(h)}f.publish=r;function i(a,p){return d(a.type,p)}f.subscribe=i;function c(a,p){let u=i(a,h=>{p(h)&&u();});}f.once=c;function l(a){return d("*",a)}f.subscribeAll=l;function d(a,p){e.debug("subscribing",{type:a});s().then(h=>{let g=h.subscriptions,I=g.get(a)??[];I.push(p),g.set(a,I);});return ()=>{e.debug("unsubscribing",{type:a}),s().then(h=>{let g=h.subscriptions.get(a);if(!g)return;let I=g.indexOf(p);I!==-1&&g.splice(I,1);});}}async function m(){await s();}f.waitForSubscription=m;})(pe||(pe={}));export{jt as $,ja as $a,di as A,Je as Aa,li as B,Le as Ba,_a as C,Qm as Ca,ui as D,Zm as Da,lr as E,Jl as Ea,Vd as F,Ac as Fa,Ro as G,ts as Ga,Kd as H,pn as Ha,fi as I,Jd as J,yt as Ja,Yd as K,ve as Ka,Ob as L,Qd as La,jb as M,Vb as Ma,Lb as N,Kb as Na,on as O,hi as Oa,ze as P,fd as Pa,vr as Q,Y as Qa,Ap as R,Ut as Ra,Dd as S,R as Sa,bi as T,Ma as Ta,Va as U,Zd as Ua,dw as V,el as Va,sl as W,tl as Wa,lw as X,Oa as Xa,uw as Y,ur as Ya,Zo as Z,Xb as Za,ks as _,ws as _a,pe as a,Pa as aa,La as ab,We as b,Ta as ba,Da as bb,Be as c,Aa as ca,$a as cb,Vl as d,nr as da,Kn as db,Cr as e,or as ea,Fa as eb,es as f,sr as fa,ht as fb,Cc as g,Ud as ga,yi as gb,JI as h,tn as ha,Na as hb,Gm as i,bt as ia,Ua as ib,xe as j,Gc as ja,ro as jb,Me as k,Tg as ka,za as kb,io as l,Pe as la,qa as lb,Ot as m,Un as ma,Ha as mb,Fx as n,TX as na,Ba as nb,dc as o,kA as oa,Ga as ob,Nx as p,fo as pa,cr as pb,zx as q,dd as qa,nl as qb,no as r,AX as ra,ol as rb,ii as s,EX as sa,fw as sb,ai as t,kh as ta,he as tb,Eo as u,RX as ua,na as ub,oo as v,Ph as va,so as w,da as wa,ir as x,Sh as xa,ar as y,bA as ya,ci as z,vn as za};
|